gunk-dev/the-valley

protocol.go

source40b311d8f0demain's published tip history
9.9 KiB
1package telemetry
2
3// The telemetry command, as a session sends it over ssh, and the request
4// the git user's shell passes to the collector for it.
5//
6// The command is a closed grammar: the word valley-telemetry, an
7// operation, and the flags that operation takes, each written --flag=value
8// and separated by single spaces. There is no quoting, no path, no unit
9// name and no pattern in it. Anything else is refused whole, and the
10// shell never hands a refused command to git-shell or to anything else.
11//
12// valley-telemetry sources
13// valley-telemetry snapshot
14// valley-telemetry read [--source=NAME] [--since=CURSOR] [--limit=N] [--logs]
15// valley-telemetry follow [--source=NAME] [--since=CURSOR] [--seconds=N] [--logs]
16// valley-telemetry report
17//
18// report is the one operation that sends records: they follow on standard
19// input, one JSON line each. Every other operation only reads.
20
21import (
22 "encoding/json"
23 "errors"
24 "fmt"
25 "regexp"
26 "sort"
27 "strconv"
28 "strings"
29)
30
31// CommandName is the first word of every telemetry command.
32const CommandName = "valley-telemetry"
33
34// The operations, and the grant each needs.
35const (
36 OpSources = "sources"
37 OpSnapshot = "snapshot"
38 OpRead = "read"
39 OpFollow = "follow"
40 OpReport = "report"
41
42 // GrantObserve reads every source on the host: shared logs span every
43 // project, so reading them is a host-wide grant, apart from any
44 // project's read consent. GrantReport sends records about the
45 // sender's own runs.
46 GrantObserve = "observe"
47 GrantReport = "report"
48)
49
50// Limits the collector holds every request to, whatever it asks for.
51const (
52 DefaultReadLimit = 200
53 MaxReadLimit = 1000
54 DefaultFollowSeconds = 60
55 MaxFollowSeconds = 300
56 MaxResponseBytes = 4 << 20
57 MaxReportBytes = 1 << 20
58 MaxReportRecords = 1000
59 LogTailBytes = 64 << 10
60 MaxCommandBytes = 4096
61)
62
63// The slots a collector gives each principal: how many requests of each
64// kind it may have open at once. Follows and bounded requests (sources,
65// snapshot, read) draw from pools of their own, so a principal's follows
66// never refuse its reads. BoundedSlots holds the reads one valley pending
67// runs at once: its history asks for four older pages together
68// (status/checkcost.go).
69const (
70 FollowSlots = 4
71 BoundedSlots = 4
72 ReportSlots = 1
73)
74
75// Request is what the shell passes to the collector: the operation and
76// its flags as the command gave them, and the principal the shell derived
77// from the key sshd authenticated. Nothing in the command names it.
78type Request struct {
79 V int `json:"v"`
80 Principal string `json:"principal"`
81 Op string `json:"op"`
82 Source string `json:"source,omitempty"`
83 Cursor string `json:"cursor,omitempty"`
84 Limit int `json:"limit,omitempty"`
85 Seconds int `json:"seconds,omitempty"`
86 Logs bool `json:"logs,omitempty"`
87}
88
89// Grant is the grant the request's operation needs.
90func (r Request) Grant() string {
91 if r.Op == OpReport {
92 return GrantReport
93 }
94 return GrantObserve
95}
96
97var (
98 sourceRE = regexp.MustCompile(`^[a-z0-9][a-z0-9._@-]{0,95}$`)
99 cursorRE = regexp.MustCompile(`^[a-z0-9._@-]{1,96}=[0-9a-f]{16}:[0-9]{1,18}$`)
100 principalRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$`)
101)
102
103// ValidPrincipal reports whether s is a principal name, as the push
104// policy reads one.
105func ValidPrincipal(s string) bool { return principalRE.MatchString(s) }
106
107// ValidSource reports whether s is a source or stream name.
108func ValidSource(s string) bool { return sourceRE.MatchString(s) }
109
110// IsCommand reports whether a session's command is meant as a telemetry
111// command: anything that starts with the command's name. Such a command
112// is the telemetry interface's to accept or refuse, and nothing else's.
113func IsCommand(cmd string) bool { return strings.HasPrefix(cmd, CommandName) }
114
115var opFlags = map[string]map[string]bool{
116 OpSources: {},
117 OpSnapshot: {},
118 OpRead: {"source": true, "since": true, "limit": true, "logs": true},
119 OpFollow: {"source": true, "since": true, "seconds": true, "logs": true},
120 OpReport: {},
121}
122
123// ParseCommand reads a telemetry command. principal is not part of it.
124func ParseCommand(cmd string) (Request, error) {
125 r := Request{V: 1}
126 if len(cmd) > MaxCommandBytes {
127 return r, errors.New("the command is too long")
128 }
129 for i := 0; i < len(cmd); i++ {
130 if cmd[i] < 0x21 && cmd[i] != ' ' || cmd[i] > 0x7e {
131 return r, errors.New("the command holds a character it may not")
132 }
133 }
134 words := strings.Split(cmd, " ")
135 if len(words) < 2 || words[0] != CommandName {
136 return r, fmt.Errorf("usage: %s sources|snapshot|read|follow|report [--flag=value]...", CommandName)
137 }
138 r.Op = words[1]
139 allowed, ok := opFlags[r.Op]
140 if !ok {
141 return r, fmt.Errorf("%q is not a telemetry operation", clip(r.Op))
142 }
143 seen := map[string]bool{}
144 for _, w := range words[2:] {
145 if !strings.HasPrefix(w, "--") {
146 return r, fmt.Errorf("%q is not a flag", clip(w))
147 }
148 name, value, hasValue := strings.Cut(w[2:], "=")
149 if !allowed[name] {
150 return r, fmt.Errorf("%s takes no --%s", r.Op, clip(name))
151 }
152 if seen[name] {
153 return r, fmt.Errorf("--%s is given twice", name)
154 }
155 seen[name] = true
156 if name == "logs" {
157 if hasValue {
158 return r, errors.New("--logs takes no value")
159 }
160 r.Logs = true
161 continue
162 }
163 if !hasValue || value == "" {
164 return r, fmt.Errorf("--%s needs a value", name)
165 }
166 switch name {
167 case "source":
168 if !ValidSource(value) {
169 return r, fmt.Errorf("%q is not a source name", clip(value))
170 }
171 r.Source = value
172 case "since":
173 if _, err := ParseCursor(value); err != nil {
174 return r, err
175 }
176 r.Cursor = value
177 case "limit", "seconds":
178 n, err := strconv.Atoi(value)
179 if err != nil || n < 1 || n > 1_000_000 || strconv.Itoa(n) != value {
180 return r, fmt.Errorf("--%s=%s is not a positive number", name, clip(value))
181 }
182 if name == "limit" {
183 r.Limit = n
184 } else {
185 r.Seconds = n
186 }
187 }
188 }
189 return r, nil
190}
191
192// Command is the command that asks for r: the inverse of ParseCommand.
193func (r Request) Command() string {
194 words := []string{CommandName, r.Op}
195 if r.Source != "" {
196 words = append(words, "--source="+r.Source)
197 }
198 if r.Cursor != "" {
199 words = append(words, "--since="+r.Cursor)
200 }
201 if r.Limit > 0 {
202 words = append(words, "--limit="+strconv.Itoa(r.Limit))
203 }
204 if r.Seconds > 0 {
205 words = append(words, "--seconds="+strconv.Itoa(r.Seconds))
206 }
207 if r.Logs {
208 words = append(words, "--logs")
209 }
210 return strings.Join(words, " ")
211}
212
213// Check holds a request the collector received to what ParseCommand
214// could have produced, and clamps its limits. The collector checks every
215// request again, whatever passed it on.
216func (r *Request) Check() error {
217 if r.V != 1 {
218 return fmt.Errorf("request version %d is not 1", r.V)
219 }
220 if !ValidPrincipal(r.Principal) {
221 return errors.New("the request names no principal")
222 }
223 parsed, err := ParseCommand(r.Command())
224 if err != nil {
225 return err
226 }
227 parsed.Principal = r.Principal
228 if parsed != *r {
229 return errors.New("the request is not one a command asks for")
230 }
231 if r.Limit <= 0 {
232 r.Limit = DefaultReadLimit
233 }
234 r.Limit = min(r.Limit, MaxReadLimit)
235 if r.Seconds <= 0 {
236 r.Seconds = DefaultFollowSeconds
237 }
238 r.Seconds = min(r.Seconds, MaxFollowSeconds)
239 return nil
240}
241
242// SlotRefusal is the error a collector answers with when principal
243// already has n requests of kind open, every slot of its pool, so a
244// reader knows which to end. It names no fault, and a request made once
245// one of them ends is admitted.
246func SlotRefusal(principal string, n int, kind string) string {
247 return fmt.Sprintf("%s already has %d %s requests open; try again when one ends", principal, n, kind)
248}
249
250// slotRefusalRE is a SlotRefusal of an observe request, whole: a
251// principal, a count, and the kind of a pool observe requests draw from,
252// follow, bounded, or observe (one pool for every observe request).
253var slotRefusalRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127} already has [1-9][0-9]{0,2} (follow|bounded|observe) requests open; try again when one ends$`)
254
255// IsSlotRefusal reports whether a collector's error refuses an observe
256// request for lack of a slot. The error line has no field that says so,
257// so it reads the text, and only text of that whole shape.
258func IsSlotRefusal(err string) bool { return slotRefusalRE.MatchString(err) }
259
260// DecodeRequest reads the one line the shell sends.
261func DecodeRequest(line []byte) (Request, error) {
262 var r Request
263 d := json.NewDecoder(strings.NewReader(string(line)))
264 d.DisallowUnknownFields()
265 if err := d.Decode(&r); err != nil {
266 return r, fmt.Errorf("the request does not read: %w", err)
267 }
268 return r, nil
269}
270
271// A cursor says how far a reader has read: for each stream, its epoch and
272// the number of the last record read, as stream=epoch:seq separated by
273// commas. A stream made again has another epoch, and a cursor naming the
274// old one reads it from its start, with the reset said.
275type Cursor map[string]Position
276
277// Position is how far one stream has been read.
278type Position struct {
279 Epoch string
280 Seq int64
281}
282
283// ParseCursor reads a cursor.
284func ParseCursor(s string) (Cursor, error) {
285 c := Cursor{}
286 if s == "" {
287 return c, nil
288 }
289 parts := strings.Split(s, ",")
290 if len(parts) > 64 {
291 return nil, errors.New("the cursor names too many streams")
292 }
293 for _, p := range parts {
294 if !cursorRE.MatchString(p) {
295 return nil, fmt.Errorf("%q is not a cursor", clip(p))
296 }
297 name, rest, _ := strings.Cut(p, "=")
298 epoch, seq, _ := strings.Cut(rest, ":")
299 n, err := strconv.ParseInt(seq, 10, 64)
300 if err != nil {
301 return nil, fmt.Errorf("%q is not a cursor", clip(p))
302 }
303 if _, dup := c[name]; dup {
304 return nil, fmt.Errorf("the cursor names %s twice", name)
305 }
306 c[name] = Position{epoch, n}
307 }
308 return c, nil
309}
310
311func (c Cursor) String() string {
312 names := make([]string, 0, len(c))
313 for n := range c {
314 names = append(names, n)
315 }
316 sort.Strings(names)
317 parts := make([]string, len(names))
318 for i, n := range names {
319 parts[i] = fmt.Sprintf("%s=%s:%d", n, c[n].Epoch, c[n].Seq)
320 }
321 return strings.Join(parts, ",")
322}