forked from leg100/otf
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathchunk.go
More file actions
88 lines (72 loc) · 2.21 KB
/
chunk.go
File metadata and controls
88 lines (72 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package internal
import (
"context"
"html/template"
term2html "github.com/buildkite/terminal-to-html"
)
const (
STX = 0x02 // marks the beginning of logs for a phase
ETX = 0x03 // marks the end of logs for a phase
)
type (
// Chunk is a section of logs for a phase.
Chunk struct {
ID string `json:"id"` // Uniquely identifies the chunk.
RunID string `json:"run_id"` // ID of run that generated the chunk
Phase PhaseType `json:"phase"` // Phase that generated the chunk
Offset int `json:"offset"` // Position within logs.
Data []byte `json:"data"` // The log data
}
PutChunkOptions struct {
RunID string `schema:"run_id,required"`
Phase PhaseType `schema:"phase,required"`
Offset int `schema:"offset,required"`
Data []byte
}
GetChunkOptions struct {
RunID string `schema:"run_id"`
Phase PhaseType `schema:"phase"`
Limit int `schema:"limit"` // size of the chunk to retrieve
Offset int `schema:"offset"` // position in overall data to seek from.
}
PutChunkService interface {
PutChunk(ctx context.Context, opts PutChunkOptions) error
}
)
// Cut returns a new, smaller chunk.
func (c Chunk) Cut(opts GetChunkOptions) Chunk {
if opts.Offset > c.NextOffset() {
// offset is out of bounds - return an empty chunk with offset set to
// the end of the chunk
return Chunk{Offset: c.NextOffset()}
}
// ensure limit is not greater than the chunk itself.
if (opts.Offset+opts.Limit) > c.NextOffset() || opts.Limit == 0 {
opts.Limit = c.NextOffset() - opts.Offset
}
c.Data = c.Data[(opts.Offset - c.Offset):((opts.Offset - c.Offset) + opts.Limit)]
c.Offset = opts.Offset
return c
}
// NextOffset returns the offset for the next chunk
func (c Chunk) NextOffset() int {
return c.Offset + len(c.Data)
}
func (c Chunk) IsStart() bool {
return len(c.Data) > 0 && c.Data[0] == STX
}
func (c Chunk) IsEnd() bool {
return len(c.Data) > 0 && c.Data[len(c.Data)-1] == ETX
}
func (c Chunk) ToHTML() template.HTML {
// remove ASCII markers
if c.IsStart() {
c.Data = c.Data[1:]
}
if c.IsEnd() {
c.Data = c.Data[:len(c.Data)-1]
}
// convert ANSI escape sequences to HTML
html := term2html.Render(c.Data)
return template.HTML(string(html))
}