package hostedwire import ( "bytes" "encoding/json" "errors" "fmt" "io" "math" "time" "amadan.net/oficina/equipo/internal/isolatedjob" ) // Wire types for the controller's routes. Every body is one JSON object with // lower-case snake_case keys, read with DecodeStrict. Durations are whole // milliseconds in fields ending _ms; controller time is whole nanoseconds // since the controller's epoch in fields ending _ns. No field holds wall // time. // // POST /v1/jobs LaunchRequest -> JobView // GET /v1/jobs/{attempt} (empty body) -> JobView // POST /v1/jobs/{attempt}/stop StopRequest -> StopProof // POST /v1/jobs/{attempt}/drain DrainRequest -> DrainResponse // POST /v1/jobs/{attempt}/quiescent QuiescentRequest -> QuiescentResponse // POST /v1/jobs/{attempt}/suspend SuspendRequest -> SuspendResponse // POST /v1/jobs/{attempt}/reopen ReopenRequest -> ReopenResponse // POST /v1/jobs/{attempt}/resume ResumeRequest -> ResumeResponse // GET /v1/vms (empty body) -> VMListResponse // // A refused request gets an ErrorResponse. Every response, refusals included, // is signed with SignResponse. // ErrBadJSON is a body DecodeStrict refuses for any reason but its size. var ErrBadJSON = errors.New("hostedwire: body is not one strict JSON object") // LaunchRequest asks for one VM for one task attempt. type LaunchRequest struct { AttemptID string `json:"attempt_id"` TaskID string `json:"task_id"` Account string `json:"account"` Replaces string `json:"replaces"` // attempt this one replaces, or "" Image isolatedjob.ImageDigest `json:"image"` Size isolatedjob.Size `json:"size"` MaxLifetimeMS int64 `json:"max_lifetime_ms"` InstanceCode string `json:"instance_code"` } // MaxLifetime is MaxLifetimeMS as a duration. A negative value, or one too // large for a time.Duration, is ErrDuration: multiplied unchecked it would // wrap round to a plausible lifetime. func (q LaunchRequest) MaxLifetime() (time.Duration, error) { return millis(q.MaxLifetimeMS) } // ErrDuration is a wire duration that is negative or does not fit a // time.Duration. var ErrDuration = errors.New("hostedwire: duration out of range") // millis converts whole milliseconds from the wire, checking the integer // before it is multiplied. Every _ms field read as a duration goes through it. func millis(ms int64) (time.Duration, error) { if ms < 0 || ms > math.MaxInt64/int64(time.Millisecond) { return 0, ErrDuration } return time.Duration(ms) * time.Millisecond, nil } // JobView is the controller's view of one attempt. The *_in_ms fields count // down from the moment the controller answered, in controller time. type JobView struct { AttemptID string `json:"attempt_id"` LaunchID string `json:"launch_id"` State string `json:"state"` VMRef isolatedjob.Ref `json:"vm_ref"` Epoch int64 `json:"epoch"` DeadlineInMS int64 `json:"deadline_in_ms"` DrainInMS int64 `json:"drain_in_ms"` StopInMS int64 `json:"stop_in_ms"` } // StopRequest stops an attempt's VM. type StopRequest struct { Reason string `json:"reason"` } // StopProof says the provider reported the VM terminal, or gone after the // stop request. ObservedAt is controller time (Task 9), never wall time. type StopProof struct { AttemptID string `json:"attempt_id"` VMRef isolatedjob.Ref `json:"vm_ref"` State isolatedjob.State `json:"state"` ObservedAt time.Duration `json:"observed_at_ns"` // controller time: nanoseconds since the controller's epoch } // DrainRequest opens a new pause generation. It has no fields; its body is {}. type DrainRequest struct{} type DrainResponse struct { Generation int64 `json:"generation"` } type QuiescentRequest struct { Generation int64 `json:"generation"` } type QuiescentResponse struct { Generation int64 `json:"generation"` } type SuspendRequest struct { Generation int64 `json:"generation"` } type SuspendResponse struct { Generation int64 `json:"generation"` } type ReopenRequest struct { Generation int64 `json:"generation"` } type ReopenResponse struct { Generation int64 `json:"generation"` } // ResumeRequest resumes a suspended VM. OperationID makes a retry of the same // resume return the same epoch. type ResumeRequest struct { OperationID string `json:"operation_id"` } type ResumeResponse struct { Epoch int64 `json:"epoch"` } // VMView is one VM the provider lists, for operators. AttemptID is "" for a // VM no job or intent owns. type VMView struct { VMRef isolatedjob.Ref `json:"vm_ref"` State isolatedjob.State `json:"state"` AttemptID string `json:"attempt_id"` AgeKnown bool `json:"age_known"` AgeMS int64 `json:"age_ms"` } type VMListResponse struct { VMs []VMView `json:"vms"` } // ErrorResponse is the body of every refusal. Code is a short fixed word the // client can branch on; Message is for people and never holds key material // or request bodies. type ErrorResponse struct { Code string `json:"code"` Message string `json:"message"` } // BootstrapVersion is the Bootstrap layout this package writes. const BootstrapVersion = 1 // Bootstrap is the one-time payload the VM's /run hook receives. Slice 1b // adds ProxyCode. type Bootstrap struct { Version int `json:"version"` LaunchID string `json:"launch_id"` InstanceCode string `json:"instance_code"` } // DecodeStrict reads at most MaxBody bytes from r and decodes them into v. // The body must be exactly one JSON object, with nothing after it but white // space. It refuses fields v does not have, keys that are not lower case // (encoding/json would otherwise match "Reason" to "reason"), and a key that // appears twice in one object (encoding/json would keep the last). Error // texts name the rule broken, never the body. func DecodeStrict(r io.Reader, v any) error { data, err := io.ReadAll(io.LimitReader(r, MaxBody+1)) if err != nil { return fmt.Errorf("hostedwire: reading body: %w", err) } if len(data) > MaxBody { return ErrTooLarge } // checkKeys also refuses anything after the one object. if err := checkKeys(data); err != nil { return err } dec := json.NewDecoder(bytes.NewReader(data)) dec.DisallowUnknownFields() if err := dec.Decode(v); err != nil { return fmt.Errorf("%w: does not fit the request type", ErrBadJSON) } return nil } // checkKeys walks the tokens of data: one top-level object, every key lower // case snake_case, no key twice in one object. func checkKeys(data []byte) error { type frame struct { object bool wantKey bool keys map[string]bool } var stack []*frame values := 0 valueDone := func() { if n := len(stack); n > 0 && stack[n-1].object { stack[n-1].wantKey = true } else if n == 0 { values++ } } dec := json.NewDecoder(bytes.NewReader(data)) dec.UseNumber() for first := true; ; first = false { tok, err := dec.Token() if err == io.EOF { break } if err != nil { return fmt.Errorf("%w: syntax", ErrBadJSON) } if first && tok != json.Delim('{') { return fmt.Errorf("%w: not an object", ErrBadJSON) } if n := len(stack); n > 0 && stack[n-1].object && stack[n-1].wantKey { if tok == json.Delim('}') { stack = stack[:n-1] valueDone() continue } key, _ := tok.(string) if !validWireKey(key) { return fmt.Errorf("%w: key not lower-case snake_case", ErrBadJSON) } if stack[n-1].keys[key] { return fmt.Errorf("%w: key repeated", ErrBadJSON) } stack[n-1].keys[key] = true stack[n-1].wantKey = false continue } switch tok { case json.Delim('{'): stack = append(stack, &frame{object: true, wantKey: true, keys: map[string]bool{}}) case json.Delim('['): stack = append(stack, &frame{}) case json.Delim(']'): stack = stack[:len(stack)-1] valueDone() default: valueDone() } } if values != 1 || len(stack) != 0 { return fmt.Errorf("%w: not one complete object", ErrBadJSON) } return nil } func validWireKey(s string) bool { if s == "" { return false } for i := 0; i < len(s); i++ { c := s[i] if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_') { return false } } return true }