From 7fd8cf552bcca533fc961599cf2bfa3b7e80ce1f Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Tue, 6 Oct 2026 10:12:19 -0400 Subject: [PATCH] api: zstd responses, streams and request bodies; images served as raw bytes; drop redundant re-encodes --- cli/go.mod | 1 + cli/go.sum | 2 + cli/internal/daemon/agents.go | 4 +- cli/internal/daemon/coding.go | 71 ++++++ cli/internal/daemon/events.go | 11 - cli/internal/daemon/history.go | 13 +- cli/internal/daemon/history_content_test.go | 13 +- cli/internal/daemon/http.go | 15 +- cli/internal/daemon/protocol/api.gen.go | 102 ++++++-- cli/internal/daemon/session_stream.go | 2 +- cli/test/e2e/acknowledgement_proxy_test.go | 2 + cli/test/e2e/content_coding_test.go | 214 +++++++++++++++++ docs/http-api-design.md | 25 +- docs/openapi.yaml | 91 +++++-- robot-docs/sessions.md | 6 +- src/albedo/daemon/active_output.gleam | 4 +- src/albedo/daemon/albedo_bus.erl | 32 +-- src/albedo/daemon/albedo_http_api.erl | 69 +++++- src/albedo/daemon/bus.gleam | 4 +- src/albedo/daemon/events.gleam | 11 +- src/albedo/daemon/http_active_output.gleam | 4 +- src/albedo/daemon/http_api.gleam | 58 ++--- src/albedo/daemon/http_coding.gleam | 124 ++++++++++ src/albedo/daemon/http_history.gleam | 31 ++- .../daemon/http_session_collection.gleam | 53 ++--- src/albedo/daemon/http_session_stream.gleam | 20 +- src/albedo/daemon/http_sessions.gleam | 11 +- src/albedo/daemon/http_stream.gleam | 60 ++++- src/albedo/daemon/http_transcript.gleam | 223 ++++++++++-------- src/albedo/daemon/images.gleam | 28 +++ src/albedo/daemon/server.gleam | 70 ++++-- test/daemon/http_budget_test.gleam | 12 - test/e2e/albedo_stream_pressure_probe.erl | 2 +- 33 files changed, 1043 insertions(+), 345 deletions(-) create mode 100644 cli/internal/daemon/coding.go create mode 100644 cli/test/e2e/content_coding_test.go create mode 100644 src/albedo/daemon/http_coding.gleam diff --git a/cli/go.mod b/cli/go.mod index febfd2e3c..c68d4b389 100644 --- a/cli/go.mod +++ b/cli/go.mod @@ -12,6 +12,7 @@ require ( github.com/charmbracelet/x/ansi v0.11.8 github.com/charmbracelet/x/term v0.2.2 github.com/google/jsonschema-go v0.4.3 + github.com/klauspost/compress v1.20.1 github.com/lucasb-eyer/go-colorful v1.4.1 github.com/mattn/go-isatty v0.0.24 github.com/oapi-codegen/runtime v1.7.0 diff --git a/cli/go.sum b/cli/go.sum index 667661c88..cef551c76 100644 --- a/cli/go.sum +++ b/cli/go.sum @@ -63,6 +63,8 @@ github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSo github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= diff --git a/cli/internal/daemon/agents.go b/cli/internal/daemon/agents.go index b8fa00c77..8b3c5be2b 100644 --- a/cli/internal/daemon/agents.go +++ b/cli/internal/daemon/agents.go @@ -172,7 +172,7 @@ func decodeAgentEvent(raw json.RawMessage) (*AgentEvent, error) { return nil, fieldError("duplicate collection progress") } seen[p.CallID] = true - progress, err := typedToolProgress(p) + progress, err := validateToolProgress(p) if err != nil || progress == nil { return nil, fieldError("collection progress") } @@ -229,7 +229,7 @@ func GetAgents(ctx context.Context, conn *Connection, id string) (AgentsSnapshot session.FamilyRevision = result.FamilyRevision node := AgentNode{Parent: row.ParentID, Address: row.Address, Session: session, Name: session.Title, Depth: session.Depth, Running: session.Status.Running, Closed: session.Closed, Cursor: row.Cursor, Activity: row.Activity, CurrentProgress: []ToolProgress{}} for _, p := range row.CurrentProgress { - progress, progressErr := typedToolProgress(p) + progress, progressErr := validateToolProgress(p) if progressErr != nil || progress == nil { return fieldError("family progress") } diff --git a/cli/internal/daemon/coding.go b/cli/internal/daemon/coding.go new file mode 100644 index 000000000..564d83fab --- /dev/null +++ b/cli/internal/daemon/coding.go @@ -0,0 +1,71 @@ +package daemon + +import ( + "io" + "net/http" + "strings" + + "github.com/klauspost/compress/zstd" +) + +// Request bodies at least this large are compressed when the daemon +// advertises zstd_requests; smaller ones are not worth a frame. +const compressedRequestBytes = 16 * 1024 + +// The daemon compresses with a small window; anything larger is refused. +const zstdWindowBytes = 8 << 20 + +var zstdEncoder, _ = zstd.NewWriter(nil, zstd.WithEncoderLevel(zstd.SpeedFastest), zstd.WithEncoderConcurrency(1)) + +// requestBody returns the payload to send and its Content-Encoding, empty +// for identity. +func requestBody(conn *Connection, payload []byte) ([]byte, string) { + if len(payload) < compressedRequestBytes || conn.capability("zstd_requests") < 1 { + return payload, "" + } + return zstdEncoder.EncodeAll(payload, nil), "zstd" +} + +// codingTransport asks for zstd responses and decodes them, the way +// net/http does for gzip when no Accept-Encoding is set. +type codingTransport struct{ base http.RoundTripper } + +func (transport codingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if req.Header.Get("Accept-Encoding") == "" { + req = req.Clone(req.Context()) + req.Header.Set("Accept-Encoding", "zstd") + } + res, err := transport.base.RoundTrip(req) + if err != nil || !strings.EqualFold(res.Header.Get("Content-Encoding"), "zstd") { + return res, err + } + decoder, err := zstd.NewReader(res.Body, zstd.WithDecoderConcurrency(1), zstd.WithDecoderMaxWindow(zstdWindowBytes)) + if err != nil { + _ = res.Body.Close() + return nil, err + } + res.Body = zstdBody{decoder: decoder, body: res.Body} + res.Header.Del("Content-Encoding") + res.Header.Del("Content-Length") + res.ContentLength = -1 + res.Uncompressed = true + return res, nil +} + +func (transport codingTransport) CloseIdleConnections() { + if closer, ok := transport.base.(interface{ CloseIdleConnections() }); ok { + closer.CloseIdleConnections() + } +} + +type zstdBody struct { + decoder *zstd.Decoder + body io.ReadCloser +} + +func (body zstdBody) Read(target []byte) (int, error) { return body.decoder.Read(target) } + +func (body zstdBody) Close() error { + body.decoder.Close() + return body.body.Close() +} diff --git a/cli/internal/daemon/events.go b/cli/internal/daemon/events.go index 42fb507d6..924080b10 100644 --- a/cli/internal/daemon/events.go +++ b/cli/internal/daemon/events.go @@ -206,17 +206,6 @@ func decodeToolProgress(raw json.RawMessage) (*ToolProgress, error) { return validateToolProgress(wire) } -func typedToolProgress(wire protocol.ToolProgress) (*ToolProgress, error) { - encoded, err := json.Marshal(wire) - if err != nil { - return nil, err - } - if len(encoded) > 8192 { - return nil, errors.New("tool progress exceeds 8 KiB") - } - return validateToolProgress(wire) -} - func validateToolProgress(wire protocol.ToolProgress) (*ToolProgress, error) { if wire.CallID == "" || wire.Name == "" || len(wire.Name) > 100 || (wire.Phase != "generating" && wire.Phase != "running") { return nil, fieldError("tool progress") diff --git a/cli/internal/daemon/history.go b/cli/internal/daemon/history.go index e4f77fd4f..4606309ff 100644 --- a/cli/internal/daemon/history.go +++ b/cli/internal/daemon/history.go @@ -2,7 +2,6 @@ package daemon import ( "context" - "encoding/base64" "encoding/json" "errors" "io" @@ -218,17 +217,11 @@ func ReadEntryContent(ctx context.Context, conn *Connection, session, entry stri if part.Field == "" || complete[part.Field] || part.OffsetBytes != int64(len(fields[part.Field])) { return fieldError("content byte offset") } - data := []byte(part.Text) - if part.Encoding == "base64" { - var err error - data, err = base64.StdEncoding.DecodeString(part.Text) - if err != nil { - return err - } - } else if part.Encoding != "utf8" { + if part.Encoding != "utf8" { return fieldError("content encoding") } - if part.Encoding == "utf8" && !utf8.Valid(data) { + data := []byte(part.Text) + if !utf8.Valid(data) { return fieldError("content UTF-8") } total += len(data) diff --git a/cli/internal/daemon/history_content_test.go b/cli/internal/daemon/history_content_test.go index df40eba0e..741a61822 100644 --- a/cli/internal/daemon/history_content_test.go +++ b/cli/internal/daemon/history_content_test.go @@ -13,7 +13,7 @@ func TestPagedContentValidatesOffsetsAndReconstructsUTF8(t *testing.T) { for _, failure := range []string{"", "offset", "false completeness"} { t.Run(failure, func(t *testing.T) { imageReads := 0 - image := map[string]any{"mime_type": "image/png", "width": 1, "height": 1, "original_bytes": 3, "reference": map[string]any{"url": "/sessions/s/history/u", "field": "image-0", "bytes": 3}} + image := map[string]any{"mime_type": "image/png", "width": 1, "height": 1, "original_bytes": 3, "reference": map[string]any{"url": "/sessions/s/history/u/image-0", "field": "image-0", "bytes": 3}} conn := controlledConnection(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/sessions/s/history" { entry := func(id, kind string, position int, content ...any) map[string]any { @@ -29,9 +29,8 @@ func TestPagedContentValidatesOffsetsAndReconstructsUTF8(t *testing.T) { }, "older": nil, "newer": nil, "high_water": 3}) return } - if r.URL.Path == "/sessions/s/history/u" { + if strings.HasPrefix(r.URL.Path, "/sessions/s/history/u") { imageReads++ - _ = json.NewEncoder(w).Encode(map[string]any{"entry_id": "u", "parts": []any{map[string]any{"field": "image-0", "offset_bytes": 0, "encoding": "base64", "text": "AAEC", "complete": true}}, "next": nil, "image": image}) return } if r.URL.Path != "/sessions/s/history/e" { @@ -50,7 +49,7 @@ func TestPagedContentValidatesOffsetsAndReconstructsUTF8(t *testing.T) { offset = 1 } } - _ = json.NewEncoder(w).Encode(map[string]any{"entry_id": "e", "parts": []any{map[string]any{"field": "text", "offset_bytes": offset, "encoding": "utf8", "text": text, "complete": complete}}, "next": next, "image": nil}) + _ = json.NewEncoder(w).Encode(map[string]any{"entry_id": "e", "parts": []any{map[string]any{"field": "text", "offset_bytes": offset, "encoding": "utf8", "text": text, "complete": complete}}, "next": next}) }) page, err := NewChatClient(conn, "s").History(t.Context(), 0, 10) if failure != "" { @@ -63,11 +62,7 @@ func TestPagedContentValidatesOffsetsAndReconstructsUTF8(t *testing.T) { t.Fatalf("history lost full text or image metadata: %+v, %v", page, err) } if imageReads != 0 { - t.Fatal("displaying image metadata fetched raw image bytes") - } - fields, err := ReadEntryContent(t.Context(), conn, "s", "u") - if err != nil || string(fields["image-0"]) != string([]byte{0, 1, 2}) || imageReads != 1 { - t.Fatalf("explicit full image retrieval changed: %v, %v", fields, err) + t.Fatal("displaying image metadata fetched the image") } }) } diff --git a/cli/internal/daemon/http.go b/cli/internal/daemon/http.go index 5a46a03d9..1ee675fe8 100644 --- a/cli/internal/daemon/http.go +++ b/cli/internal/daemon/http.go @@ -61,9 +61,16 @@ func (c *Connection) operationEndpoint(op operation) (ConnectionSnapshot, error) return state.endpoint, nil } +func (c *Connection) capability(name string) int64 { + if state := c.state.Load(); state != nil { + return state.capabilities[name] + } + return 0 +} + func newHTTPClient() *http.Client { return &http.Client{ - Transport: &http.Transport{Proxy: http.ProxyFromEnvironment}, + Transport: codingTransport{base: &http.Transport{Proxy: http.ProxyFromEnvironment}}, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, } } @@ -187,10 +194,14 @@ func requestBytes(ctx context.Context, conn *Connection, operation operation, li if err != nil { return nil, err } - req, err := operationRequest(ctx, snapshot, operation, payload) + sent, encoding := requestBody(conn, payload) + req, err := operationRequest(ctx, snapshot, operation, sent) if err != nil { return nil, err } + if encoding != "" { + req.Header.Set("Content-Encoding", encoding) + } if canceled := ctx.Err(); canceled != nil { return nil, canceled } diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 195c6693f..44717423b 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -424,7 +424,7 @@ type Composition struct { Quarantine []QuarantineDiagnostic `json:"quarantine"` } -// ContentPart UTF-8 offsets count exact stored bytes. Base64 offsets count decoded image bytes. +// ContentPart Offsets count exact stored UTF-8 bytes. type ContentPart struct { Complete bool `json:"complete"` Encoding string `json:"encoding"` @@ -603,15 +603,9 @@ type EmptyRequest = map[string]interface{} // EntryContentPage defines model for EntryContentPage. type EntryContentPage struct { // EntryID Opaque identity. Never infer a resource type or route from its contents. - EntryID ID `json:"entry_id"` - Image *struct { - Height int64 `json:"height"` - MimeType string `json:"mime_type"` - OriginalBytes Counter `json:"original_bytes"` - Width int64 `json:"width"` - } `json:"image" nullable:"true"` - Next *PageToken `json:"next" nullable:"true"` - Parts []ContentPart `json:"parts"` + EntryID ID `json:"entry_id"` + Next *PageToken `json:"next" nullable:"true"` + Parts []ContentPart `json:"parts"` } // ExtensionDeletion defines model for ExtensionDeletion. @@ -978,11 +972,13 @@ type ImageContent struct { // ImageMetadata defines model for ImageMetadata. type ImageMetadata struct { - Height int64 `json:"height"` - MimeType string `json:"mime_type"` - OriginalBytes Counter `json:"original_bytes"` - Reference ContentReference `json:"reference"` - Width int64 `json:"width"` + Height int64 `json:"height"` + MimeType string `json:"mime_type"` + OriginalBytes Counter `json:"original_bytes"` + + // Reference Its url is the image resource, which serves the decoded bytes. + Reference ContentReference `json:"reference"` + Width int64 `json:"width"` } // ImageUpload Strict base64; decoded dimensions and provider constraints are validated before admission. @@ -4173,11 +4169,18 @@ type ClientInterface interface { // GetHistoryContent Read full content in bounded pieces // - // Follow next until null. UTF-8 pieces end at character boundaries. Base64 image offsets count decoded bytes. Reconstruct stored content, not shortened previews. + // Follow next until null. UTF-8 pieces end at character boundaries. Reconstruct stored content, not shortened previews. Image fields are not paged here; their references name the image resource. // // Corresponds with GET /sessions/{session_id}/history/{entry_id} (the `GetHistoryContent` operationId). GetHistoryContent(ctx context.Context, sessionID ID, entryID ID, params *GetHistoryContentParams, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetHistoryImage Read one image field as its own bytes + // + // Image references in history point here. The body is the stored image itself, not base64, and is never content-coded. + // + // Corresponds with GET /sessions/{session_id}/history/{entry_id}/{field} (the `GetHistoryImage` operationId). + GetHistoryImage(ctx context.Context, sessionID ID, entryID ID, field string, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetInput Read a durable input outcome // // Available after session deletion. Accepted is not consumed or answered. Retain pending and unfinished-turn identities; terminal decisions last seven days. Unknown old UUIDv7 returns 410, never a fresh admission. @@ -5716,7 +5719,7 @@ func (c *Client) GetHistory(ctx context.Context, sessionID ID, params *GetHistor // GetHistoryContent Read full content in bounded pieces // -// Follow next until null. UTF-8 pieces end at character boundaries. Base64 image offsets count decoded bytes. Reconstruct stored content, not shortened previews. +// Follow next until null. UTF-8 pieces end at character boundaries. Reconstruct stored content, not shortened previews. Image fields are not paged here; their references name the image resource. // // Corresponds with GET /sessions/{session_id}/history/{entry_id} (the `GetHistoryContent` operationId). func (c *Client) GetHistoryContent(ctx context.Context, sessionID ID, entryID ID, params *GetHistoryContentParams, reqEditors ...RequestEditorFn) (*http.Response, error) { @@ -5731,6 +5734,23 @@ func (c *Client) GetHistoryContent(ctx context.Context, sessionID ID, entryID ID return c.Client.Do(req) } +// GetHistoryImage Read one image field as its own bytes +// +// Image references in history point here. The body is the stored image itself, not base64, and is never content-coded. +// +// Corresponds with GET /sessions/{session_id}/history/{entry_id}/{field} (the `GetHistoryImage` operationId). +func (c *Client) GetHistoryImage(ctx context.Context, sessionID ID, entryID ID, field string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetHistoryImageRequest(c.Server, sessionID, entryID, field) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + // GetInput Read a durable input outcome // // Available after session deletion. Accepted is not consumed or answered. Retain pending and unfinished-turn identities; terminal decisions last seven days. Unknown old UUIDv7 returns 410, never a fresh admission. @@ -9703,6 +9723,54 @@ func NewGetHistoryContentRequest(server string, sessionID ID, entryID ID, params return req, nil } +// NewGetHistoryImageRequest constructs an http.Request for the GetHistoryImage method +func NewGetHistoryImageRequest(server string, sessionID ID, entryID ID, field string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "session_id", sessionID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entry_id", entryID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam2 string + + pathParam2, err = runtime.StyleParamWithOptions("simple", false, "field", field, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/sessions/%s/history/%s/%s", pathParam0, pathParam1, pathParam2) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + // NewGetInputRequest constructs an http.Request for the GetInput method func NewGetInputRequest(server string, sessionID ID, inputID ID) (*http.Request, error) { var err error diff --git a/cli/internal/daemon/session_stream.go b/cli/internal/daemon/session_stream.go index e9805e64c..d80abccc0 100644 --- a/cli/internal/daemon/session_stream.go +++ b/cli/internal/daemon/session_stream.go @@ -179,7 +179,7 @@ func (c *ChatClient) readStream(ctx context.Context, scanner *bufio.Scanner, onB } events = append(events, wireChatEvent{StreamEvent: StreamEvent{Type: EventUsage, Usage: usageValue(snapshot.wire.Usage), Replayed: true}}) for _, progress := range snapshot.wire.CurrentProgress { - parsed, err := typedToolProgress(progress) + parsed, err := validateToolProgress(progress) if err != nil || parsed == nil { return streamFailure(StreamProtocol, fieldError("current progress")) } diff --git a/cli/test/e2e/acknowledgement_proxy_test.go b/cli/test/e2e/acknowledgement_proxy_test.go index 82a9999ee..547f40c2d 100644 --- a/cli/test/e2e/acknowledgement_proxy_test.go +++ b/cli/test/e2e/acknowledgement_proxy_test.go @@ -111,6 +111,8 @@ func mutateAcknowledgement(t *testing.T, path string, fault acknowledgementFault forwarded.URL.Scheme, forwarded.URL.Host = destination.Scheme, destination.Host forwarded.RequestURI = "" forwarded.Host = destination.Host + // Faults rewrite the JSON acknowledgement, so it must cross uncoded. + forwarded.Header.Del("Accept-Encoding") response, forwardErr := transport.RoundTrip(forwarded) if forwardErr != nil { proxy.mu.Lock() diff --git a/cli/test/e2e/content_coding_test.go b/cli/test/e2e/content_coding_test.go new file mode 100644 index 000000000..67eee128a --- /dev/null +++ b/cli/test/e2e/content_coding_test.go @@ -0,0 +1,214 @@ +//go:build unix + +package e2e + +import ( + "bufio" + "bytes" + "context" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "strings" + "sync" + "testing" + "time" + + "albedo/cli/internal/daemon" + "github.com/klauspost/compress/zstd" +) + +// uploadRecorder keeps the Content-Encoding of each input upload. +type uploadRecorder struct { + upstream http.RoundTripper + mu sync.Mutex + encodings []string +} + +func (recorder *uploadRecorder) RoundTrip(req *http.Request) (*http.Response, error) { + if req.Method == http.MethodPut && strings.Contains(req.URL.Path, "/inputs/") { + recorder.mu.Lock() + recorder.encodings = append(recorder.encodings, req.Header.Get("Content-Encoding")) + recorder.mu.Unlock() + } + return recorder.upstream.RoundTrip(req) +} + +// rawGet reads a daemon resource without the CLI's transport, so the test +// sees the coding the daemon chose. +func rawGet(t *testing.T, path string, headers map[string]string) *http.Response { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, conn(t).BaseURL()+path, nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+conn(t).Snapshot().Token) + for name, value := range headers { + req.Header.Set(name, value) + } + res, err := (&http.Client{Transport: &http.Transport{DisableCompression: true}}).Do(req) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = res.Body.Close() }) + return res +} + +func decoded(t *testing.T, res *http.Response) []byte { + t.Helper() + var body io.Reader = res.Body + if res.Header.Get("Content-Encoding") == "zstd" { + decoder, err := zstd.NewReader(res.Body) + if err != nil { + t.Fatal(err) + } + defer decoder.Close() + body = decoder + } + data, err := io.ReadAll(body) + if err != nil { + t.Fatal(err) + } + return data +} + +// A large upload crosses zstd-coded once the daemon advertises it, the reply +// and its history come back coded and identical to identity, the session +// stream decodes frame by frame, and the attached image is served as itself. +func TestZstdCodingAndRawImages(t *testing.T) { + profile := providerRoute(t, echoReply) + t.Parallel() + attached, err := daemon.Attach(t.Context(), conn(t).Snapshot(), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(attached.HTTPClient().CloseIdleConnections) + server, err := daemon.ProbeServer(t.Context(), attached) + if err != nil { + t.Fatal(err) + } + if server.Capabilities["zstd_requests"] < 1 { + t.Skip("this daemon's runtime has no zstd") + } + recorder := &uploadRecorder{upstream: attached.HTTPClient().Transport} + attached.HTTPClient().Transport = recorder + + id := newSession(t, t.TempDir()) + png := "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + prompt := strings.Repeat("a long prompt that compresses well. ", 600) + image := daemon.ImageAttachment{Data: png, ImageMetadata: daemon.ImageMetadata{MimeType: daemon.ImagePNG, Width: 1, Height: 1, Bytes: 69}} + if _, err := daemon.NewChatClient(attached, id).Send(context.Background(), prompt, []daemon.ImageAttachment{image}); err != nil { + t.Fatalf("compressed upload: %v", err) + } + waitIdle(t, id, profile, 1) + if recorder.encodings[0] != "zstd" { + t.Fatalf("a %d byte upload went out as %q", len(prompt), recorder.encodings[0]) + } + if forwarded := lastUserText(suite.provider.requests(profile)[0]["body"].(map[string]any)); !strings.Contains(forwarded, prompt) { + t.Fatal("the decoded upload lost the prompt") + } + + path := "/sessions/" + id + "/history?limit=200" + coded := rawGet(t, path, map[string]string{"Accept-Encoding": "gzip, zstd"}) + plain := rawGet(t, path, nil) + if coded.Header.Get("Content-Encoding") != "zstd" || !strings.Contains(coded.Header.Get("Vary"), "Accept-Encoding") || plain.Header.Get("Content-Encoding") != "" { + t.Fatalf("history coding: %q vary %q, identity %q", coded.Header.Get("Content-Encoding"), coded.Header.Get("Vary"), plain.Header.Get("Content-Encoding")) + } + history := decoded(t, coded) + if !bytes.Equal(history, decoded(t, plain)) { + t.Fatal("the zstd history differs from identity") + } + refused := rawGet(t, path, map[string]string{"Accept-Encoding": "zstd;q=0"}) + if refused.Header.Get("Content-Encoding") != "" { + t.Fatal("zstd;q=0 still got zstd") + } + + var page struct { + Items []struct { + Content []struct { + Image *struct { + Reference struct{ URL string } `json:"reference"` + } `json:"image"` + } `json:"content"` + } `json:"items"` + } + if err := json.Unmarshal(history, &page); err != nil { + t.Fatal(err) + } + var url string + for _, item := range page.Items { + for _, part := range item.Content { + if part.Image != nil { + url = part.Image.Reference.URL + } + } + } + served := rawGet(t, url, map[string]string{"Accept-Encoding": "zstd"}) + want, _ := base64.StdEncoding.DecodeString(png) + if got, _ := io.ReadAll(served.Body); served.StatusCode != http.StatusOK || served.Header.Get("Content-Type") != "image/png" || served.Header.Get("Content-Encoding") != "" || !bytes.Equal(got, want) { + t.Fatalf("image %s: %d %q %q, %d bytes", url, served.StatusCode, served.Header.Get("Content-Type"), served.Header.Get("Content-Encoding"), len(got)) + } + + stream := rawGet(t, "/sessions/"+id, map[string]string{"Accept": "text/event-stream", "Accept-Encoding": "zstd"}) + var frames io.Reader = stream.Body + if stream.Header.Get("Content-Encoding") == "zstd" { + decoder, err := zstd.NewReader(stream.Body, zstd.WithDecoderConcurrency(1)) + if err != nil { + t.Fatal(err) + } + defer decoder.Close() + frames = decoder + } + first := make(chan string, 1) + go func() { + line, _ := bufio.NewReaderSize(frames, 1<<20).ReadString('\n') + first <- line + }() + select { + case line := <-first: + if !strings.HasPrefix(line, "data: {") { + t.Fatalf("first stream frame: %q", line) + } + case <-time.After(10 * time.Second): + t.Fatal("the coded stream withheld its first frame") + } +} + +// A coded body must be one frame that declares a size within the route's +// limit; anything else is refused before the operation runs. +func TestZstdRequestBodiesAreBounded(t *testing.T) { + t.Parallel() + server, err := daemon.ProbeServer(t.Context(), conn(t)) + if err != nil { + t.Fatal(err) + } + if server.Capabilities["zstd_requests"] < 1 { + t.Skip("this daemon's runtime has no zstd") + } + unsized, _ := zstd.NewWriter(nil) + var streamed bytes.Buffer + unsized.Reset(&streamed) + _, _ = unsized.Write([]byte(`{"name":"x"}`)) + _ = unsized.Close() + bomb, _ := zstd.NewWriter(nil) + for name, body := range map[string][]byte{ + "garbage": []byte("not zstd"), + "unsized": streamed.Bytes(), + "oversized": bomb.EncodeAll(bytes.Repeat([]byte{' '}, 1<<20), nil), + } { + req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, conn(t).BaseURL()+"/hosts/coded/probe", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+conn(t).Snapshot().Token) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Content-Encoding", "zstd") + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + problem, _ := io.ReadAll(res.Body) + _ = res.Body.Close() + if res.StatusCode != http.StatusBadRequest || !strings.Contains(string(problem), "does not decode") { + t.Errorf("%s body: %d %s", name, res.StatusCode, problem) + } + } +} diff --git a/docs/http-api-design.md b/docs/http-api-design.md index d9e4ca5df..bdc1c157d 100644 --- a/docs/http-api-design.md +++ b/docs/http-api-design.md @@ -191,6 +191,17 @@ HTTP body framing accepts valid fixed-length and chunked requests, enforcing the same byte limit while reading. Ambiguous framing, unsupported content encoding, and incomplete bodies fail without executing the operation. +zstd is the one content coding. A JSON or text response of at least 1 KiB is +compressed when `Accept-Encoding` admits `zstd`, and so is a session or +collection event stream, flushed after every frame. Limits and `ETag` values +describe the decoded representation, and these responses add +`Vary: Accept-Encoding`. Image resources are never coded. A daemon whose +runtime lacks zstd answers in identity; stream compression needs OTP 29. +When `GET /server` lists the `zstd_requests` capability, a request body may use +`Content-Encoding: zstd`. It must be one frame that declares its decoded size, +which must fit the route's limit; anything else is `400`. The CLI compresses +bodies of 16 KiB or more. + Lists return `{ "items": [], "next": null }`. `next` is an opaque continuation token tied to the query and representation, including `limit`. Follow-up requests retain the original query and add `next`. Default `limit` is 50; maximum is @@ -835,11 +846,13 @@ It provides the TUI tree and fork picker without a separate tree route. as pages of `parts`, each with `field`, `offset_bytes`, `text`, and `complete`. Text and JSON fields use their exact stored UTF-8 encoding; offsets are bytes, and pieces end on UTF-8 boundaries. Opaque `next` identifies the next piece. -Binary image parts use base64 with decoded-byte offsets. The decoded content -budget is 256 KiB per page. The daemon shortens a page further when JSON escaping -or base64 would reach the common encoded response bound. -Metadata identifies MIME type, dimensions, and original byte count. Clients -can reconstruct full arguments, results, and images without filesystem access. +The decoded content budget is 256 KiB per page. The daemon shortens a page +further when JSON escaping would reach the common encoded response bound. +Image fields are not paged. An image's metadata gives its MIME type, +dimensions, byte count, and a reference to +`GET /sessions/{session_id}/history/{entry_id}/{field}`, which returns the +stored bytes with the image's own `Content-Type`. Clients can reconstruct full +arguments, results, and images without filesystem access. ### Prepared context and request records @@ -1289,7 +1302,7 @@ Both stream kinds send keepalives at least every five seconds when quiet. Sockets have bounded write waits. Publication never awaits subscriber socket writes. A stalled reader cannot retain an unbounded mailbox or force another subscriber's writes to wait behind its own. Reverse proxies must pass streaming -responses without buffering. Compression is disabled by default. History, images, and +responses without buffering. History, images, and large extension results remain bounded HTTP reads, not unsolicited stream data. ## Extension contracts diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 6ae931054..85b57e51f 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -11,7 +11,10 @@ info: and SSE frames are at most 1 MiB unless an extension explicitly overrides that limit. Ordinary request bodies are at most 64 KiB, input bodies 72,200,000 bytes and proxy bodies 32,000,000 bytes. UTF-8 and encoded-byte limits are described with x-max-utf8-bytes/x-max-encoded-bytes; standard schema validation - alone does not assert them. Examples use synthetic secrets only. + alone does not assert them. Examples use synthetic secrets only. JSON and text responses of at least + 1 KiB, and session event streams, use Content-Encoding zstd when Accept-Encoding admits it; limits + and ETags apply to the decoded representation. When capabilities include zstd_requests, a request + body may use Content-Encoding zstd as one frame that declares its decoded size. jsonSchemaDialect: https://json-schema.org/draft/2020-12/schema externalDocs: description: Behavior, ownership, feature coverage and verification. @@ -1406,8 +1409,9 @@ paths: $ref: '#/components/responses/Problem503' '404': $ref: '#/components/responses/Problem404' - description: Follow next until null. UTF-8 pieces end at character boundaries. Base64 image offsets - count decoded bytes. Reconstruct stored content, not shortened previews. + description: Follow next until null. UTF-8 pieces end at character boundaries. Reconstruct stored + content, not shortened previews. Image fields are not paged here; their references name the + image resource. parameters: - name: entry_id in: path @@ -1420,6 +1424,60 @@ paths: schema: $ref: '#/components/schemas/ID' - $ref: '#/components/parameters/Next' + /sessions/{session_id}/history/{entry_id}/{field}: + get: + operationId: getHistoryImage + summary: Read one image field as its own bytes + tags: + - sessions + responses: + '200': + description: The decoded image, typed by its MIME type. + content: + image/png: + schema: + type: string + contentMediaType: image/png + image/jpeg: + schema: + type: string + contentMediaType: image/jpeg + image/webp: + schema: + type: string + contentMediaType: image/webp + '400': + $ref: '#/components/responses/Problem400' + '401': + $ref: '#/components/responses/Problem401' + '403': + $ref: '#/components/responses/Problem403' + '405': + $ref: '#/components/responses/Problem405' + '503': + $ref: '#/components/responses/Problem503' + '404': + $ref: '#/components/responses/Problem404' + description: Image references in history point here. The body is the stored image itself, + not base64, and is never content-coded. + parameters: + - name: session_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + - name: entry_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + - name: field + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 256 /sessions/{session_id}/context: get: operationId: getContext @@ -6896,6 +6954,7 @@ components: $ref: '#/components/schemas/Counter' reference: $ref: '#/components/schemas/ContentReference' + description: Its url is the image resource, which serves the decoded bytes. required: [mime_type, width, height, original_bytes, reference] additionalProperties: false TextContent: @@ -7110,13 +7169,13 @@ components: $ref: '#/components/schemas/Counter' encoding: type: string - enum: [utf8, base64] + enum: [utf8] text: type: string maxLength: 1048576 complete: type: boolean - description: UTF-8 offsets count exact stored bytes. Base64 offsets count decoded image bytes. + description: Offsets count exact stored UTF-8 bytes. required: [field, offset_bytes, encoding, text, complete] additionalProperties: false EntryContentPage: @@ -7133,28 +7192,8 @@ components: anyOf: - $ref: '#/components/schemas/PageToken' - type: 'null' - image: - anyOf: - - type: object - properties: - mime_type: - type: string - maxLength: 100 - width: - type: integer - minimum: 1 - maximum: 9007199254740991 - height: - type: integer - minimum: 1 - maximum: 9007199254740991 - original_bytes: - $ref: '#/components/schemas/Counter' - required: [mime_type, width, height, original_bytes] - additionalProperties: false - - type: 'null' x-max-decoded-content-bytes: 262144 - required: [entry_id, parts, next, image] + required: [entry_id, parts, next] additionalProperties: false ContextSection: type: object diff --git a/robot-docs/sessions.md b/robot-docs/sessions.md index 0d2ce273b..cfc902180 100644 --- a/robot-docs/sessions.md +++ b/robot-docs/sessions.md @@ -19,7 +19,11 @@ it. starting a new turn does not require `/compact` to change the old phase. Internal checkpoint and provider-started signals are suppressed before stream encoding and do not allocate SSE sequence numbers. -Session streams require the `text/event-stream` content type. Each batch carries +Session streams require the `text/event-stream` content type, zstd-coded when +the request accepts it ([encoding](../docs/http-api-design.md)): `http_stream` +flushes the coder after every frame and ends the frame before a deliberate +stop. A zstd context works only in the process that created it, so the stream +process creates its own writer. Each batch carries a nonempty `generation`, a nonnegative integer `cursor`, and an `events` array. The generation identifies one lifetime of the session actor. Reconnect requests send both `after_generation` and `after_seq`; an initial request omits both. diff --git a/src/albedo/daemon/active_output.gleam b/src/albedo/daemon/active_output.gleam index 07b23fd4e..981a63a56 100644 --- a/src/albedo/daemon/active_output.gleam +++ b/src/albedo/daemon/active_output.gleam @@ -6,6 +6,7 @@ import gleam/list import gleam/option.{type Option, None, Some} import gleam/result import gleam/string +import gleam/string_tree pub opaque type Projection { Projection( @@ -199,7 +200,8 @@ fn append_segment( Segment(..next, pending: segment.pending <> text), )) None -> { - let encoded = string.byte_size(json.to_string(json.string(text))) - 2 + let encoded = + string_tree.byte_size(json.to_string_tree(json.string(text))) - 2 let raw = projection.raw + bytes let size = projection.encoded + encoded case raw <= 65_536 && size <= 65_536 { diff --git a/src/albedo/daemon/albedo_bus.erl b/src/albedo/daemon/albedo_bus.erl index 9321f7dad..84c1e29aa 100644 --- a/src/albedo/daemon/albedo_bus.erl +++ b/src/albedo/daemon/albedo_bus.erl @@ -14,7 +14,7 @@ subscribe_filtered(Owner, Notify, Sessions) -> Filter = maps:from_keys(Sessions, true), Ref = make_ref(), Control = atomics:new(2, [{signed, false}]), - albedo_registry:register(?QUEUES, Ref, {queue:new(), 0, 0}), + albedo_registry:register(?QUEUES, Ref, {queue:new(), 0, 0, false}), albedo_registry:register(?TABLE, Ref, {Owner, Notify, Control, Filter}), spawn(fun() -> Monitor = erlang:monitor(process, Owner), @@ -37,7 +37,7 @@ publish(Event) -> _ -> lists:foreach( fun({Ref, {_Owner, Notify, Control, _Filter}}) -> - admit(Ref, Event, byte_size(Event), Notify, Control, ?CAS_ATTEMPTS) + admit(Ref, Event, byte_size(Event), true, Notify, Control, ?CAS_ATTEMPTS) end, ets:tab2list(?TABLE)), nil @@ -63,7 +63,7 @@ publish_activity(Session, Event) -> _ -> lists:foreach(fun({Ref, {_Owner, Notify, Control, Filter}}) -> case maps:is_key(Session, Filter) of - true -> admit(Ref, Event, byte_size(Event), Notify, Control, ?CAS_ATTEMPTS); + true -> admit(Ref, Event, byte_size(Event), false, Notify, Control, ?CAS_ATTEMPTS); false -> ok end end, ets:tab2list(?TABLE)), @@ -80,32 +80,34 @@ publish_mail(Sender, Recipient, Event) -> Interested = maps:is_key(Recipient, Filter) orelse case Sender of {some, Id} -> maps:is_key(Id, Filter); _ -> false end, case Interested of - true -> admit(Ref, Event, byte_size(Event), Notify, Control, ?CAS_ATTEMPTS); + true -> admit(Ref, Event, byte_size(Event), false, Notify, Control, ?CAS_ATTEMPTS); false -> ok end end, ets:tab2list(?TABLE)), nil end. -admit(Ref, Event, Size, Notify, Control, Attempts) -> +%% Invalidates marks a batch that requires a collection refresh, so a drain +%% reports it without decoding the encoded events. +admit(Ref, Event, Size, Invalidates, Notify, Control, Attempts) -> case atomics:get(Control, 1) of 1 -> ok; 0 when Attempts == 0 -> overflow(Ref, Notify, Control); 0 -> case ets:lookup(?QUEUES, Ref) of [] -> ok; - [{Ref, {Queue, Count, Bytes} = Previous}] -> + [{Ref, {Queue, Count, Bytes, Invalidated} = Previous}] -> case Count + 1 > ?EVENT_LIMIT orelse Bytes + Size > ?BYTE_LIMIT of true -> case replace_queue(Ref, Previous, Previous) of true -> overflow(Ref, Notify, Control); - false -> admit(Ref, Event, Size, Notify, Control, Attempts - 1) + false -> admit(Ref, Event, Size, Invalidates, Notify, Control, Attempts - 1) end; false -> - Next = {queue:in(Event, Queue), Count + 1, Bytes + Size}, + Next = {queue:in(Event, Queue), Count + 1, Bytes + Size, Invalidated orelse Invalidates}, case replace_queue(Ref, Previous, Next) of true -> wake(Notify, Control); - false -> admit(Ref, Event, Size, Notify, Control, Attempts - 1) + false -> admit(Ref, Event, Size, Invalidates, Notify, Control, Attempts - 1) end end end @@ -134,7 +136,7 @@ replace_queue(Ref, Previous, Next) -> drain(Ref) -> case ets:lookup(?TABLE, Ref) of [{Ref, {_Owner, Notify, Control, _Filter}}] -> drain(Ref, Notify, Control, ?CAS_ATTEMPTS); - [] -> {batch, []} + [] -> {batch, [], false} end. drain(Ref, Notify, Control, Attempts) -> @@ -143,14 +145,14 @@ drain(Ref, Notify, Control, Attempts) -> 0 when Attempts == 0 -> overflow(Ref, Notify, Control), overflow; 0 -> case ets:lookup(?QUEUES, Ref) of - [] -> {batch, []}; - [{Ref, {Queue, _Count, _Bytes} = Previous}] -> - case replace_queue(Ref, Previous, {queue:new(), 0, 0}) of + [] -> {batch, [], false}; + [{Ref, {Queue, _Count, _Bytes, Invalidated} = Previous}] -> + case replace_queue(Ref, Previous, {queue:new(), 0, 0, false}) of false -> drain(Ref, Notify, Control, Attempts - 1); true -> case atomics:get(Control, 1) of 1 -> ets:delete(?QUEUES, Ref), overflow; - 0 -> {batch, queue:to_list(Queue)} + 0 -> {batch, queue:to_list(Queue), Invalidated} end end end @@ -167,7 +169,7 @@ rearm(Ref, WakeConsumed) -> end, case {atomics:get(Control, 1), ets:lookup(?QUEUES, Ref)} of {1, _} -> wake(Notify, Control); - {0, [{Ref, {_Queue, Count, _Bytes}}]} when Count > 0 -> wake(Notify, Control); + {0, [{Ref, {_Queue, Count, _Bytes, _Invalidated}}]} when Count > 0 -> wake(Notify, Control); _ -> ok end; [] -> ok diff --git a/src/albedo/daemon/albedo_http_api.erl b/src/albedo/daemon/albedo_http_api.erl index e16f69df6..a925b51c2 100644 --- a/src/albedo/daemon/albedo_http_api.erl +++ b/src/albedo/daemon/albedo_http_api.erl @@ -1,5 +1,6 @@ -module(albedo_http_api). --export([stream_socket/1, scalar_prefix/2, content_slice/3, image_slice/3, page_token/3, page_state/3, parse/1, accept/2, encode/1, timestamp/1, etag/1, instance_id/0, read_chunked/2]). +-export([zstd_available/0, zstd_streams/0, accepts_zstd/1, zstd_compress/1, zstd_stream/0, zstd_flush/2, zstd_end/1, zstd_decompress/2, + stream_socket/1, scalar_prefix/2, content_slice/3, page_token/3, page_state/3, parse/1, accept/2, encode/1, timestamp/1, etag/1, instance_id/0, read_chunked/2]). parse(Bytes) -> try @@ -151,14 +152,68 @@ utf8_end(Text, End, Size) -> _ -> End end. -image_slice(Base64, Offset, Limit) -> +%% zstd ships with OTP 28; flushing a stream mid-frame needs OTP 29. +zstd_available() -> code:ensure_loaded(zstd) =:= {module, zstd}. + +zstd_streams() -> zstd_available() andalso erlang:function_exported(zstd, flush, 1). + +%% Whether an Accept-Encoding header admits zstd, by name or wildcard. +accepts_zstd(Header) -> try - Bytes = base64:decode(Base64), Size = byte_size(Bytes), - true = Offset >= 0 andalso Offset =< Size, - End = min(Size, Offset + Limit), - {ok, {base64:encode(binary:part(Bytes, Offset, End - Offset)), End, End =:= Size}} - catch _:_ -> {error, <<"image content is unavailable">>} end. + true = byte_size(Header) =< 8192, + Codings = [media_range(Part) || Part0 <- binary:split(Header, <<",">>, [global]), + Part <- [string:trim(Part0)], Part =/= <<>>], + Named = [Quality || {<<"zstd">>, Quality} <- Codings], + Any = [Quality || {<<"*">>, Quality} <- Codings], + Quality = case {Named, Any} of + {[_|_], _} -> lists:max(Named); + {[], [_|_]} -> lists:max(Any); + {[], []} -> 0 + end, + Quality > 0 andalso zstd_available() + catch _:_ -> false end. + +zstd_compress(Data) -> zstd:compress(Data, #{compressionLevel => 1}). + +zstd_stream() -> + {ok, Context} = zstd:context(compress, #{compressionLevel => 1}), + Context. +%% Everything written so far, decodable by a reader without waiting for more. +zstd_flush(Context, Data) -> + Buffered = zstd_feed(Context, Data), + {continue, Flushed} = zstd:flush(Context), + [Buffered, Flushed]. + +zstd_feed(Context, Data) -> + case zstd:stream(Context, Data) of + {continue, Rest, Out} -> [Out | zstd_feed(Context, Rest)]; + {continue, Out} -> [Out] + end. + +zstd_end(Context) -> + {done, Tail} = zstd:finish(Context, <<>>), + Tail. + +%% One frame that declares its decoded size, at most Limit bytes. Output is +%% produced in bounded steps, so a frame that lies about its size cannot +%% allocate past Limit, and a truncated frame fails the size check. +zstd_decompress(Data, Limit) -> + try + {ok, #{frameContentSize := Size}} = zstd:get_frame_header(Data), + true = is_integer(Size) andalso Size =< Limit, + {ok, Context} = zstd:context(decompress), + try inflate(Context, Data, Size, [], 0) after zstd:close(Context) end + catch _:_ -> {error, nil} end. + +inflate(_, _, Size, _, Total) when Total > Size -> {error, nil}; +inflate(Context, Data, Size, Acc, Total) -> + case zstd:stream(Context, Data) of + {continue, Rest, Out} -> inflate(Context, Rest, Size, [Out|Acc], Total + byte_size(Out)); + {continue, Out} when Total + byte_size(Out) =:= Size -> + {ok, iolist_to_binary(lists:reverse(Acc, [Out]))}; + {continue, _} -> {error, nil} + end. %% Rank supported representations while respecting a specific q=0 exclusion %% over a less-specific wildcard. JSON wins a tie so */* never starts a stream. diff --git a/src/albedo/daemon/bus.gleam b/src/albedo/daemon/bus.gleam index bcc4498cc..9f9d360c7 100644 --- a/src/albedo/daemon/bus.gleam +++ b/src/albedo/daemon/bus.gleam @@ -135,8 +135,10 @@ fn scalar_prefix(value: String, count: Int) -> String { /// One subscriber's bounded queue, removed when its stream process dies. pub type Subscription +/// Events stay encoded on the bus; `invalidated` says whether any of them +/// came from `invalidate`. pub type Batch { - Batch(events: List(String)) + Batch(events: List(String), invalidated: Bool) Overflow } diff --git a/src/albedo/daemon/events.gleam b/src/albedo/daemon/events.gleam index 036244e68..cbb227ed6 100644 --- a/src/albedo/daemon/events.gleam +++ b/src/albedo/daemon/events.gleam @@ -230,14 +230,11 @@ fn tool( False -> json.null() } let result = json.string(output) - let result_bytes = string.byte_size(json.to_string(result)) + let result_bytes = http_api.encoded_size(result) let size = - string.byte_size(json.to_string(arguments)) + http_api.encoded_size(arguments) + result_bytes - + { - option.map(trace, fn(value) { string.byte_size(json.to_string(value)) }) - |> option.unwrap(0) - } + + { option.map(trace, http_api.encoded_size) |> option.unwrap(0) } let complete = string.byte_size(call.arguments) <= 65_536 && size <= 65_536 json.object([ #("tool_call_id", json.string(call.id)), @@ -287,7 +284,7 @@ pub fn status(value: session_activity.Status) -> json.Json { pub fn activity(value: session_activity.Projection) -> json.Json { let encoded = activity_value(value) - case string.byte_size(json.to_string(encoded)) <= 16_384 { + case http_api.encoded_size(encoded) <= 16_384 { True -> encoded False -> case value.lines { diff --git a/src/albedo/daemon/http_active_output.gleam b/src/albedo/daemon/http_active_output.gleam index 423cc7021..8ac561e50 100644 --- a/src/albedo/daemon/http_active_output.gleam +++ b/src/albedo/daemon/http_active_output.gleam @@ -12,7 +12,6 @@ import gleam/json import gleam/list import gleam/option.{None, Some} import gleam/result -import gleam/string import gleam/uri import mist @@ -218,7 +217,6 @@ pub fn content( ), ), #("next", next), - #("image", json.null()), ]), )) } @@ -239,7 +237,7 @@ fn encoded_page( )) }) let value = json.string(read.0) - case string.byte_size(json.to_string(value)) <= content_page_bytes { + case http_api.encoded_size(value) <= content_page_bytes { True -> Ok(#(value, read.1, read.2)) False -> { // One scalar escapes to at most six ASCII bytes. This fallback bounds diff --git a/src/albedo/daemon/http_api.gleam b/src/albedo/daemon/http_api.gleam index 1b84ba03d..cad010f5b 100644 --- a/src/albedo/daemon/http_api.gleam +++ b/src/albedo/daemon/http_api.gleam @@ -17,6 +17,7 @@ import gleam/list import gleam/option.{type Option, None, Some} import gleam/result import gleam/string +import gleam/string_tree import gleam/uri import mist @@ -137,13 +138,18 @@ pub type Interrupt { } pub fn problem(failure: Failure) -> json.Json { - json.object([ + json.object(problem_fields(failure)) +} + +/// The problem members, for a decision body that extends them. +pub fn problem_fields(failure: Failure) -> List(#(String, json.Json)) { + [ #("type", json.string("about:blank")), #("title", json.string(failure.code)), #("status", json.int(failure.status)), #("detail", json.string(failure.detail)), #("code", json.string(failure.code)), - ]) + ] } pub fn fail(failure: Failure) -> response.Response(mist.ResponseData) { @@ -155,14 +161,27 @@ pub fn reply( status: Int, value: json.Json, ) -> response.Response(mist.ResponseData) { - raw(status, json.to_string(value)) + let encoded = json.to_string_tree(value) + bounded( + status, + string_tree.byte_size(encoded), + bytes_tree.from_string_tree(encoded), + ) } pub fn raw( status: Int, encoded: String, ) -> response.Response(mist.ResponseData) { - case string.byte_size(encoded) > response_limit { + bounded(status, string.byte_size(encoded), bytes_tree.from_string(encoded)) +} + +fn bounded( + status: Int, + size: Int, + body: bytes_tree.BytesTree, +) -> response.Response(mist.ResponseData) { + case size > response_limit { True -> fail(Failure( 503, @@ -173,10 +192,15 @@ pub fn raw( response.new(status) |> response.set_header("content-type", "application/json") |> response.set_header("cache-control", "no-store") - |> response.set_body(mist.Bytes(bytes_tree.from_string(encoded))) + |> response.set_body(mist.Bytes(body)) } } +/// The encoded byte length of `value`, counted without flattening it. +pub fn encoded_size(value: json.Json) -> Int { + string_tree.byte_size(json.to_string_tree(value)) +} + pub fn invalid(detail: String) -> Failure { Failure(400, "invalid_request", detail) } @@ -241,7 +265,7 @@ pub fn bounded_items( budget, fn(item) { let value = encode(item) - Ok(#(value, string.byte_size(json.to_string(value)) + overhead)) + Ok(#(value, encoded_size(value) + overhead)) }, [], ) @@ -257,7 +281,7 @@ pub fn bounded_catalog( values, budget, fn(value) { - let bytes = string.byte_size(json.to_string(value)) + let bytes = encoded_size(value) case bytes > 65_536 { True -> Error(Failure( @@ -307,13 +331,6 @@ pub fn next_page( } } -@external(erlang, "albedo_http_api", "image_slice") -pub fn image_slice( - base64: String, - offset: Int, - limit: Int, -) -> Result(#(String, Int, Bool), String) - @external(erlang, "albedo_http_api", "read_chunked") pub fn read_chunked( connection: mist.Connection, @@ -328,19 +345,6 @@ pub fn json_value(encoded: String) -> Result(json.Json, Failure) { Ok(dynamic_json(value)) } -/// Decode a bus event once for forwarding and its structural type decision. -pub fn event_value( - encoded: String, -) -> Result(#(json.Json, Option(String)), Failure) { - use value <- result.try( - strict_json(bit_array.from_string(encoded)) |> result.map_error(invalid), - ) - let kind = - decode.run(value, decode.field("type", decode.string, decode.success)) - |> option.from_result - Ok(#(dynamic_json(value), kind)) -} - pub fn fields(encoded: String) -> Result(List(#(String, json.Json)), Failure) { use value <- result.try( strict_json(bit_array.from_string(encoded)) |> result.map_error(invalid), diff --git a/src/albedo/daemon/http_coding.gleam b/src/albedo/daemon/http_coding.gleam new file mode 100644 index 000000000..fe64798d3 --- /dev/null +++ b/src/albedo/daemon/http_coding.gleam @@ -0,0 +1,124 @@ +//// zstd content coding for daemon HTTP bodies. A response is compressed when +//// its request's Accept-Encoding admits zstd; a request body may arrive +//// compressed once the client has seen the `zstd_requests` capability. + +import gleam/bytes_tree.{type BytesTree} +import gleam/http/request.{type Request} +import gleam/http/response.{type Response} +import gleam/result +import gleam/string +import mist + +/// Smaller bodies would not shrink by more than a frame header costs. +const minimum_bytes = 1024 + +@external(erlang, "albedo_http_api", "zstd_available") +pub fn available() -> Bool + +@external(erlang, "albedo_http_api", "accepts_zstd") +fn accepts_zstd(header: String) -> Bool + +@external(erlang, "albedo_http_api", "zstd_streams") +fn streams() -> Bool + +@external(erlang, "albedo_http_api", "zstd_compress") +fn compress(data: BytesTree) -> BytesTree + +/// A zstd request body, or Error unless it is one frame that declares a +/// decoded size of at most `limit` and decodes to exactly that. +@external(erlang, "albedo_http_api", "zstd_decompress") +pub fn decompress(data: BitArray, limit: Int) -> Result(BitArray, Nil) + +fn accepted(req: Request(a)) -> Bool { + request.get_header(req, "accept-encoding") + |> result.map(accepts_zstd) + |> result.unwrap(False) +} + +/// Compresses a JSON or text body of at least `minimum_bytes` when the request +/// accepts zstd. Validators describe the decoded representation either way. +pub fn encode( + req: Request(a), + reply: Response(mist.ResponseData), +) -> Response(mist.ResponseData) { + let textual = + response.get_header(reply, "content-type") + |> result.map(fn(kind) { + string.starts_with(kind, "application/json") + || string.starts_with(kind, "application/problem+json") + || string.starts_with(kind, "text/") + }) + |> result.unwrap(False) + case reply.body, textual { + mist.Bytes(body), True -> { + let reply = vary(reply) + case + bytes_tree.byte_size(body) >= minimum_bytes + && response.get_header(reply, "content-encoding") == Error(Nil) + && accepted(req) + { + True -> + reply + |> response.set_header("content-encoding", "zstd") + |> response.set_body(mist.Bytes(compress(body))) + False -> reply + } + } + _, _ -> reply + } +} + +fn vary(reply: Response(a)) -> Response(a) { + let value = case response.get_header(reply, "vary") { + Ok(existing) -> existing <> ", Accept-Encoding" + Error(_) -> "Accept-Encoding" + } + response.set_header(reply, "vary", value) +} + +/// The coding of one event stream, owned by the process that writes it. +pub opaque type Stream { + Identity + Zstd(context: Context) +} + +type Context + +@external(erlang, "albedo_http_api", "zstd_stream") +fn context() -> Context + +@external(erlang, "albedo_http_api", "zstd_flush") +fn flush(context: Context, data: BitArray) -> BytesTree + +@external(erlang, "albedo_http_api", "zstd_end") +fn finish(context: Context) -> BytesTree + +/// Whether an event stream for this request is zstd-coded. +pub fn stream_coded(req: Request(a)) -> Bool { + streams() && accepted(req) +} + +/// Starts a stream's coding. A zstd context works only in the process that +/// created it, so the stream process itself must call this. +pub fn start(coded: Bool) -> Stream { + case coded { + True -> Zstd(context()) + False -> Identity + } +} + +/// One chunk, flushed so the client can decode it without waiting. +pub fn chunk(coding: Stream, data: BitArray) -> BitArray { + case coding { + Identity -> data + Zstd(context) -> bytes_tree.to_bit_array(flush(context, data)) + } +} + +/// The bytes that close the stream's frame; identity has none. +pub fn close(coding: Stream) -> Result(BitArray, Nil) { + case coding { + Identity -> Error(Nil) + Zstd(context) -> Ok(bytes_tree.to_bit_array(finish(context))) + } +} diff --git a/src/albedo/daemon/http_history.gleam b/src/albedo/daemon/http_history.gleam index b655eb3f1..33c59e36e 100644 --- a/src/albedo/daemon/http_history.gleam +++ b/src/albedo/daemon/http_history.gleam @@ -358,7 +358,7 @@ fn encode_part( True -> None False -> { let value = json.string(text) - case string.byte_size(json.to_string(value)) <= budget { + case http_api.encoded_size(value) <= budget { True -> Some(value) False -> None } @@ -382,7 +382,7 @@ fn encode_part( } } Value(field, value) -> { - let bytes = string.byte_size(json.to_string(value)) + let bytes = http_api.encoded_size(value) case bytes <= budget { True -> #( json.object([ @@ -402,7 +402,7 @@ fn encode_part( } } Trace(field, value) -> { - let bytes = string.byte_size(json.to_string(value)) + let bytes = http_api.encoded_size(value) case bytes <= budget { True -> #( json.object([#("kind", json.string("trace")), #("trace", value)]), @@ -429,7 +429,24 @@ fn encode_part( #("width", json.int(width)), #("height", json.int(height)), #("original_bytes", json.int(bytes)), - #("reference", reference(session, id, field, image_bytes(image))), + #( + "reference", + json.object([ + #( + "url", + json.string( + "/sessions/" + <> session + <> "/history/" + <> id + <> "/" + <> field, + ), + ), + #("field", json.string(field)), + #("bytes", json.int(bytes)), + ]), + ), ]), ), ]), @@ -439,12 +456,6 @@ fn encode_part( } } -fn image_bytes(image: types.Image) -> Int { - // Encoded length is available without loading a stored blob. Exact decoded - // bytes are resolved only by an explicit content request. - types.image_meta(image).3 -} - pub fn checkpoint(entry: Entry) -> Option(json.Json) { use _ <- option.then(case entry.kind { "user" -> Some(Nil) diff --git a/src/albedo/daemon/http_session_collection.gleam b/src/albedo/daemon/http_session_collection.gleam index 91f3399ab..ed99e995d 100644 --- a/src/albedo/daemon/http_session_collection.gleam +++ b/src/albedo/daemon/http_session_collection.gleam @@ -20,6 +20,7 @@ import gleam/list import gleam/option.{type Option, None, Some} import gleam/otp/actor import gleam/result +import gleam/string import mist fn collection_filter( @@ -151,9 +152,10 @@ pub fn read( |> result.map_error(http_api.failure), ) use _ <- result.try(http_stream.configure(live.body)) + let coded = http_stream.coded(live) Ok(mist.chunked( live, - http_stream.response(live), + http_stream.response(live, coded), fn(subject) { let subscription = bus.subscribe_filtered( @@ -170,6 +172,7 @@ pub fn read( filter, subscription, subject, + http_stream.writer(live, coded), True, ) }, @@ -284,6 +287,7 @@ type CollectionStream { filter: session_collection.Filter, subscription: bus.Subscription, subject: Subject(StreamMessage), + writer: http_stream.Writer, initial: Bool, ) } @@ -305,10 +309,10 @@ fn collection_ids( } } -fn collection_overflow(connection: mist.Connection) -> mist.ChunkNext(a) { +fn collection_overflow(writer: http_stream.Writer) -> mist.ChunkNext(a) { let _ = http_stream.send( - connection, + writer, json.object([ #( "events", @@ -325,6 +329,7 @@ fn collection_overflow(connection: mist.Connection) -> mist.ChunkNext(a) { ]) |> json.to_string, ) + http_stream.close(writer) mist.ChunkStop } @@ -346,16 +351,16 @@ fn collection_refresh( fn collection_stream_loop( state: CollectionStream, message: StreamMessage, - connection: mist.Connection, + _connection: mist.Connection, ) -> mist.ChunkNext(CollectionStream) { case state.initial { True -> case collection_refresh(state) { - Error(_) -> collection_overflow(connection) + Error(_) -> collection_overflow(state.writer) Ok(state) -> { let sent = http_stream.send( - connection, + state.writer, json.object([ #( "events", @@ -390,33 +395,23 @@ fn collection_stream_loop( } False -> case bus.drain(state.subscription) { - bus.Overflow -> collection_overflow(connection) - bus.Batch(encoded) -> { - let outcome = { - use events <- result.try(list.try_map(encoded, http_api.event_value)) - use state <- result.try( - case - list.any(events, fn(event) { event.1 == Some("invalidate") }) - { - True -> collection_refresh(state) - False -> Ok(state) - }, - ) - Ok(#(state, list.map(events, fn(event) { event.0 }))) + bus.Overflow -> collection_overflow(state.writer) + bus.Batch(encoded, invalidated) -> { + let refreshed = case invalidated { + True -> collection_refresh(state) + False -> Ok(state) } - case outcome { - Error(_) -> collection_overflow(connection) - Ok(#(state, events)) -> { - let sent = case events, message { + case refreshed { + Error(_) -> collection_overflow(state.writer) + Ok(state) -> { + // Bus events are already encoded; the batch only joins them. + let sent = case encoded, message { [], StreamWake -> Ok(Nil) - [], StreamTick -> http_stream.keepalive(connection) + [], StreamTick -> http_stream.keepalive(state.writer) _, _ -> http_stream.send( - connection, - json.object([ - #("events", json.array(events, fn(value) { value })), - ]) - |> json.to_string, + state.writer, + "{\"events\":[" <> string.join(encoded, ",") <> "]}", ) } case sent { diff --git a/src/albedo/daemon/http_session_stream.gleam b/src/albedo/daemon/http_session_stream.gleam index d0a708da9..5c3e1c0af 100644 --- a/src/albedo/daemon/http_session_stream.gleam +++ b/src/albedo/daemon/http_session_stream.gleam @@ -31,6 +31,7 @@ type State { cursor: session.Cursor, initial: Option(String), tail: Int, + writer: http_stream.Writer, ) } @@ -109,9 +110,10 @@ pub fn attach( )) }, ) + let coded = http_stream.coded(req) Ok(mist.chunked( req, - http_stream.response(req), + http_stream.response(req, coded), fn(subject) { let owner = process.self() session.watch(worker, owner, fn() { process.send(subject, StreamWake) }) @@ -126,6 +128,7 @@ pub fn attach( first.cursor, Some(initial), tail, + http_stream.writer(req, coded), ) }, session_stream_loop, @@ -133,13 +136,13 @@ pub fn attach( } fn stream_failure( - connection: mist.Connection, + writer: http_stream.Writer, cursor: session.Cursor, failure: http_api.Failure, ) -> mist.ChunkNext(a) { let _ = http_stream.send( - connection, + writer, json.object([ #("generation", json.string(cursor.generation)), #("cursor", json.int(cursor.sequence)), @@ -158,17 +161,18 @@ fn stream_failure( ]) |> json.to_string, ) + http_stream.close(writer) mist.ChunkStop } fn session_stream_loop( state: State, message: StreamMessage, - connection: mist.Connection, + _connection: mist.Connection, ) -> mist.ChunkNext(State) { case state.initial { Some(batch) -> - case http_stream.send(connection, batch) { + case http_stream.send(state.writer, batch) { Error(_) -> mist.ChunkStop Ok(_) -> { session.consumed( @@ -199,15 +203,15 @@ fn session_stream_loop( Ok(#(page, batch)) } case outcome { - Error(failure) -> stream_failure(connection, state.cursor, failure) + Error(failure) -> stream_failure(state.writer, state.cursor, failure) Ok(#(page, batch)) -> { let sent = case page.snapshot == None && list.is_empty(page.events) && message == StreamTick { - True -> http_stream.keepalive(connection) - False -> http_stream.send(connection, batch) + True -> http_stream.keepalive(state.writer) + False -> http_stream.send(state.writer, batch) } case sent { Error(_) -> mist.ChunkStop diff --git a/src/albedo/daemon/http_sessions.gleam b/src/albedo/daemon/http_sessions.gleam index 795e11d15..e670889f9 100644 --- a/src/albedo/daemon/http_sessions.gleam +++ b/src/albedo/daemon/http_sessions.gleam @@ -86,13 +86,10 @@ fn creation_failure( ), ), ]) - use fields <- result.try(http_api.fields( - http_api.problem(failure) |> json.to_string, - )) Ok( http_api.reply( failure.status, - json.object([#("decision", decision), ..fields]), + json.object([#("decision", decision), ..http_api.problem_fields(failure)]), ) |> response.set_header("content-type", "application/problem+json"), ) @@ -727,11 +724,7 @@ fn input_decision_response( "accepted" -> http_api.reply(outcome.receipt.http_status, http_wire.input(outcome)) _ -> { - let fields = - http_api.problem(rejection_failure(outcome.receipt)) - |> json.to_string - |> http_api.fields - |> result.unwrap([]) + let fields = http_api.problem_fields(rejection_failure(outcome.receipt)) http_api.reply( outcome.receipt.http_status, json.object([ diff --git a/src/albedo/daemon/http_stream.gleam b/src/albedo/daemon/http_stream.gleam index d78059d01..fcce591be 100644 --- a/src/albedo/daemon/http_stream.gleam +++ b/src/albedo/daemon/http_stream.gleam @@ -2,6 +2,7 @@ //// this module reports that its entire batch reached the socket. import albedo/daemon/http_api +import albedo/daemon/http_coding import gleam/bit_array import gleam/http/request import gleam/http/response @@ -9,14 +10,37 @@ import gleam/result import gleam/string import mist -pub fn response(req: request.Request(a)) -> response.Response(Nil) { +/// One stream's socket and content coding. +pub opaque type Writer { + Writer(connection: mist.Connection, coding: http_coding.Stream) +} + +/// Whether the stream for this request is zstd-coded. The handler decides, +/// since it sends the headers. +pub fn coded(req: request.Request(a)) -> Bool { + http_coding.stream_coded(req) +} + +/// The stream process's writer; it must create its own coding. +pub fn writer(req: request.Request(mist.Connection), coded: Bool) -> Writer { + Writer(req.body, http_coding.start(coded)) +} + +pub fn response( + req: request.Request(a), + coded: Bool, +) -> response.Response(Nil) { let response = response.new(200) |> response.set_header("content-type", "text/event-stream") |> response.set_header("cache-control", "no-store") |> response.set_header("x-accel-buffering", "no") - |> response.set_header("vary", "Accept") + |> response.set_header("vary", "Accept, Accept-Encoding") |> response.set_body(Nil) + let response = case coded { + True -> response.set_header(response, "content-encoding", "zstd") + False -> response + } // Streaming sends its headers before ordinary outer response decorators. // Ingress has already verified any Origin carried by this request. case request.get_header(req, "origin") { @@ -28,7 +52,7 @@ pub fn response(req: request.Request(a)) -> response.Response(Nil) { "access-control-expose-headers", "ETag, Location, Retry-After", ) - |> response.set_header("vary", "Origin, Accept") + |> response.set_header("vary", "Origin, Accept, Accept-Encoding") } } @@ -46,17 +70,31 @@ pub fn configure(connection: mist.Connection) -> Result(Nil, http_api.Failure) { }) } -pub fn send(connection: mist.Connection, encoded: String) -> Result(Nil, Nil) { +pub fn send(writer: Writer, encoded: String) -> Result(Nil, Nil) { case string.byte_size(encoded) <= http_api.response_limit { False -> Error(Nil) - True -> - mist.send_chunk( - connection, - bit_array.from_string("data: " <> encoded <> "\n\n"), - ) + True -> write(writer, "data: " <> encoded <> "\n\n") + } +} + +pub fn keepalive(writer: Writer) -> Result(Nil, Nil) { + write(writer, ": keepalive\n\n") +} + +/// Ends the coded frame before a stream stops on its own terms. +pub fn close(writer: Writer) -> Nil { + case http_coding.close(writer.coding) { + Ok(tail) -> { + let _ = mist.send_chunk(writer.connection, tail) + Nil + } + Error(_) -> Nil } } -pub fn keepalive(connection: mist.Connection) -> Result(Nil, Nil) { - mist.send_chunk(connection, bit_array.from_string(": keepalive\n\n")) +fn write(writer: Writer, frame: String) -> Result(Nil, Nil) { + mist.send_chunk( + writer.connection, + http_coding.chunk(writer.coding, bit_array.from_string(frame)), + ) } diff --git a/src/albedo/daemon/http_transcript.gleam b/src/albedo/daemon/http_transcript.gleam index 7e6bd8a65..562b2723a 100644 --- a/src/albedo/daemon/http_transcript.gleam +++ b/src/albedo/daemon/http_transcript.gleam @@ -3,8 +3,10 @@ import albedo/daemon/conversation import albedo/daemon/http_api import albedo/daemon/http_history +import albedo/daemon/images import albedo/daemon/store import albedo/openai_api/types +import gleam/bytes_tree import gleam/dynamic/decode import gleam/http/request import gleam/http/response @@ -381,90 +383,53 @@ pub fn content( }) } }) - use part <- result.try( - list.drop(entry.parts, cursor.0) - |> list.first - |> result.map_error(fn(_) { - http_api.Failure(404, "content_unknown", "entry content was not found") - }), - ) - use part <- result.try(case part { - http_history.Reference(field, source_id, _) -> { - use source <- result.try(history_entry(ledger, id, source_id)) - list.find(source.parts, fn(part) { - case part { - http_history.Text(key, _) - | http_history.Value(key, _) - | http_history.Trace(key, _) - | http_history.Image(key, _) - | http_history.Reference(key, _, _) -> key == field - } - }) - |> result.map_error(fn(_) { - http_api.Failure( + // Image fields are served whole by `image`, never as pages here. + let parts = + list.filter(entry.parts, fn(part) { + case part { + http_history.Image(..) -> False + _ -> True + } + }) + use page <- result.try(case list.drop(parts, cursor.0), cursor { + [], #(0, 0) -> Ok(None) + [], _ -> + Error(http_api.Failure( + 404, + "content_unknown", + "entry content was not found", + )) + [part, ..], _ -> { + use #(field, text) <- result.try(stored_text(ledger, id, part)) + use sliced <- result.try( + text + |> result.try(http_api.content_slice(_, cursor.1, 262_144)) + |> result.replace_error(http_api.Failure( 503, "content_unavailable", - "associated tool content is unavailable", - ) - }) - } - _ -> Ok(part) - }) - let #(field, encoding, content, image) = case part { - http_history.Reference(field, _, _) -> #( - field, - "utf8", - Error("associated tool content is unavailable"), - None, - ) - http_history.Text(field, text) -> #(field, "utf8", Ok(text), None) - http_history.Value(field, value) | http_history.Trace(field, value) -> #( - field, - "utf8", - Ok(json.to_string(value)), - None, - ) - http_history.Image(field, image) -> { - let bytes = case types.image_data(image) { - types.InlineData(data) -> Ok(data) - types.StoredData(read: read, ..) -> read() - } - #( - field, - "base64", - bytes |> result.map_error(fn(_) { "image unavailable" }), - Some(image), + "entry content is unavailable", + )), ) + Ok(Some(#(field, sliced))) } + }) + let parts_json = case page { + None -> [] + Some(#(field, sliced)) -> [ + json.object([ + #("field", json.string(field)), + #("offset_bytes", json.int(cursor.1)), + #("encoding", json.string("utf8")), + #("text", json.string(sliced.0)), + #("complete", json.bool(sliced.2)), + ]), + ] } - use content <- result.try( - content - |> result.map_error(fn(_) { - http_api.Failure( - 503, - "content_unavailable", - "entry content is unavailable", - ) - }), - ) - use sliced <- result.try( - case encoding { - "base64" -> http_api.image_slice(content, cursor.1, 262_144) - _ -> http_api.content_slice(content, cursor.1, 262_144) - } - |> result.map_error(fn(_) { - http_api.Failure( - 503, - "content_unavailable", - "entry content is unavailable", - ) - }), - ) - let next_state = case sliced.2 { - True -> #(cursor.0 + 1, 0) - False -> #(cursor.0, sliced.1) + let next_state = case page { + Some(#(_, #(_, offset, False))) -> #(cursor.0, offset) + _ -> #(cursor.0 + 1, 0) } - let next = case next_state.0 < list.length(entry.parts) { + let next = case next_state.0 < list.length(parts) { False -> json.null() True -> json.string(http_api.page_token( @@ -477,43 +442,93 @@ pub fn content( |> json.to_string, )) } - let image = - json.nullable(image, fn(image) { - let #(mime, width, height, bytes) = types.image_meta(image) - json.object([ - #("mime_type", json.string(mime)), - #("width", json.int(width)), - #("height", json.int(height)), - #("original_bytes", json.int(bytes)), - ]) - }) Ok(http_api.reply( 200, json.object([ #("entry_id", json.string(entry_id)), - #( - "parts", - json.array( - [ - json.object([ - #("field", json.string(field)), - #("offset_bytes", json.int(cursor.1)), - #("encoding", json.string(encoding)), - #("text", json.string(sliced.0)), - #("complete", json.bool(sliced.2)), - ]), - ], - fn(value) { value }, - ), - ), + #("parts", json.array(parts_json, fn(value) { value })), #("next", next), - #("image", image), ]), )) } http_api.answer(outcome) } +/// A part's field name and stored UTF-8, read from the entry a reference +/// names. Images and unresolved references have no text. +fn stored_text( + ledger: store.Store, + id: String, + part: http_history.Part, +) -> Result(#(String, Result(String, String)), http_api.Failure) { + case part { + http_history.Reference(field, source_id, _) -> { + use source <- result.try(history_entry(ledger, id, source_id)) + list.find(source.parts, fn(part) { part.field == field }) + |> result.map(fn(part) { #(field, part_text(part)) }) + |> result.replace_error(http_api.Failure( + 503, + "content_unavailable", + "associated tool content is unavailable", + )) + } + _ -> Ok(#(part.field, part_text(part))) + } +} + +fn part_text(part: http_history.Part) -> Result(String, String) { + case part { + http_history.Text(_, text) -> Ok(text) + http_history.Value(_, value) | http_history.Trace(_, value) -> + Ok(json.to_string(value)) + http_history.Image(..) | http_history.Reference(..) -> + Error("part has no stored text") + } +} + +/// One image field's decoded bytes with its own MIME type. +pub fn image( + storage: Result(store.Store, String), + id: String, + entry_id: String, + field: String, + req: request.Request(BitArray), +) -> response.Response(mist.ResponseData) { + let outcome = { + use _ <- result.try(http_api.parameters(req, [])) + use ledger <- result.try(storage |> result.map_error(http_api.failure)) + use entry <- result.try(history_entry(ledger, id, entry_id)) + use image <- result.try( + list.find_map(entry.parts, fn(part) { + case part { + http_history.Image(key, image) if key == field -> Ok(image) + _ -> Error(Nil) + } + }) + |> result.replace_error(http_api.Failure( + 404, + "content_unknown", + "entry image was not found", + )), + ) + use bytes <- result.try( + images.bytes(ledger, image) + |> result.replace_error(http_api.Failure( + 503, + "content_unavailable", + "entry image is unavailable", + )), + ) + Ok( + response.new(200) + |> response.set_header("content-type", types.image_meta(image).0) + |> response.set_header("cache-control", "no-store") + |> response.set_body(mist.Bytes(bytes_tree.from_bit_array(bytes))), + ) + } + http_api.answer(outcome) +} + fn history_entry( ledger: store.Store, id: String, diff --git a/src/albedo/daemon/images.gleam b/src/albedo/daemon/images.gleam index 98517d5b3..bf27be7d8 100644 --- a/src/albedo/daemon/images.gleam +++ b/src/albedo/daemon/images.gleam @@ -49,6 +49,31 @@ fn read(db: sqlight.Connection, hash: String) -> Result(String, Nil) { } } +/// An image's decoded bytes, for serving the image itself. Same caveat as +/// `reader`: never call this from inside `store.query`. +pub fn bytes(ledger: store.Store, image: types.Image) -> Result(BitArray, Nil) { + case types.image_data(image) { + types.InlineData(data) -> decode_legacy_base64(data) + types.StoredData(hash: hash, ..) -> stored_bytes(ledger, hash) + } +} + +fn stored_bytes(ledger: store.Store, hash: String) -> Result(BitArray, Nil) { + store.query(ledger, fn(db) { + case + store.rows( + db, + "SELECT data FROM images WHERE hash=? AND typeof(data)='blob'", + [sqlight.text(hash)], + decode.field(0, decode.bit_array, decode.success), + ) + { + Ok([data]) -> Ok(data) + _ -> read(db, hash) |> result.try(decode_legacy_base64) + } + }) +} + /// The input with its inline images replaced by stored references, after /// writing their payloads. Runs inside the caller's transaction. pub fn externalize( @@ -272,3 +297,6 @@ fn hashes(payload: BitArray) -> List(String) @external(erlang, "albedo_images", "encode_base64") fn encode_base64(data: BitArray) -> String + +@external(erlang, "albedo_images", "decode_legacy_base64") +fn decode_legacy_base64(data: String) -> Result(BitArray, Nil) diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index 0995895b0..36c852ded 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -3,6 +3,7 @@ import albedo/daemon/configuration import albedo/daemon/http_active_output import albedo/daemon/http_api import albedo/daemon/http_auth +import albedo/daemon/http_coding import albedo/daemon/http_resources import albedo/daemon/http_session_collection import albedo/daemon/http_sessions @@ -108,7 +109,7 @@ fn route( req: request.Request(mist.Connection), ) -> response.Response(mist.ResponseData) { case http_request(fn() { handle_request(config, registry, boundary, req) }) { - Ok(response) -> response + Ok(response) -> http_coding.encode(req, response) Error(_) -> http_api.fail(http_api.Failure( 503, @@ -313,21 +314,29 @@ fn admitted( list.filter(req.headers, fn(header) { string.lowercase(header.0) == "content-encoding" }) - let supported = case admission, encodings { - extension.RelayAdmission(..), _ -> True - _, [] -> True + // Ok(True) when the body arrives zstd-compressed. + let compressed = case admission, encodings { + extension.RelayAdmission(..), _ | _, [] -> Ok(False) _, [#(_, encoding)] -> - string.lowercase(string.trim(encoding)) == "identity" - _, _ -> False + case string.lowercase(string.trim(encoding)) { + "identity" -> Ok(False) + "zstd" -> + case http_coding.available() { + True -> Ok(True) + False -> Error(Nil) + } + _ -> Error(Nil) + } + _, _ -> Error(Nil) } - case supported { - False -> + case compressed { + Error(_) -> failure( 415, "unsupported_encoding", "content encoding is unsupported", ) - True -> + Ok(compressed) -> case body_length(req, admission.body_limit, failure) { Error(refusal) -> refusal Ok(length) -> { @@ -343,10 +352,20 @@ fn admitted( case read { Ok(body) -> { let size = bit_array.byte_size(body) - case length { - Some(length) if size != length -> + case length, compressed { + Some(length), _ if size != length -> failure(400, "invalid_request", "invalid request body") - _ -> next(request.set_body(req, body)) + _, False -> next(request.set_body(req, body)) + _, True -> + case http_coding.decompress(body, admission.body_limit) { + Ok(body) -> next(request.set_body(req, body)) + Error(_) -> + failure( + 400, + "invalid_request", + "request body does not decode within its limit", + ) + } } } Error(mist.MalformedBody) -> @@ -528,6 +547,14 @@ fn daemon_route( id, req, ) + Get, ["sessions", id, "history", entry_id, field] -> + http_transcript.image( + registry.host(registry) |> result.map(runtime.ledger), + id, + entry_id, + field, + req, + ) Get, ["sessions", id, "history", entry_id] -> http_transcript.content( config.token, @@ -659,6 +686,7 @@ fn protocol_method(path: List(String)) -> response.Response(mist.ResponseData) { ["sessions", _, "visits", _] -> Some("PUT") ["sessions", _, "history"] | ["sessions", _, "history", _] + | ["sessions", _, "history", _, _] | ["sessions", _, "active-output", _] | ["sessions", _, "context"] | ["sessions", _, "catalog"] -> Some("GET") @@ -753,9 +781,21 @@ fn protocol_server( json.object( list.map( [ - "durable_inputs", "session_replay", "collection_invalidation", - "tool_progress", "storage_report", "context", "catalog", - "settings", "workspace_browsing", "host_probes", "provider_auth", + "durable_inputs", + "session_replay", + "collection_invalidation", + "tool_progress", + "storage_report", + "context", + "catalog", + "settings", + "workspace_browsing", + "host_probes", + "provider_auth", + ..case http_coding.available() { + True -> ["zstd_requests"] + False -> [] + } ], fn(name) { #( diff --git a/test/daemon/http_budget_test.gleam b/test/daemon/http_budget_test.gleam index 6b9a7e9b1..af3a997ad 100644 --- a/test/daemon/http_budget_test.gleam +++ b/test/daemon/http_budget_test.gleam @@ -3,7 +3,6 @@ import albedo/daemon/http_api as api import gleam/json -import gleam/option.{None, Some} import gleam/string pub fn bounded_items_retain_the_measured_prefix_test() -> Nil { @@ -30,14 +29,3 @@ pub fn catalog_limits_include_separator_bytes_test() -> Nil { let assert Ok([]) = api.bounded_catalog([], 0) Nil } - -pub fn invalidation_type_is_independent_of_json_field_order_test() -> Nil { - let assert Ok(#(_, Some("invalidate"))) = - api.event_value("{\"data\":{},\"type\":\"invalidate\"}") - let assert Ok(#(_, Some("invalidate"))) = - api.event_value("{ \"type\" : \"invalidate\", \"data\" : {} }") - let assert Ok(#(_, Some("status"))) = api.event_value("{\"type\":\"status\"}") - let assert Ok(#(_, None)) = api.event_value("{\"other\":\"invalidate\"}") - let assert Error(_) = api.event_value("{\"type\":") - Nil -} diff --git a/test/e2e/albedo_stream_pressure_probe.erl b/test/e2e/albedo_stream_pressure_probe.erl index 079171276..87820f5c8 100644 --- a/test/e2e/albedo_stream_pressure_probe.erl +++ b/test/e2e/albedo_stream_pressure_probe.erl @@ -27,7 +27,7 @@ blocked(Owner) -> sample({Ref, {Owner, _, Control, _}}) -> {Count, Bytes} = case ets:lookup(albedo_bus_queues, Ref) of - [{_, {_, C, B}}] -> {C, B}; + [{_, {_, C, B, _}}] -> {C, B}; [] -> {0, 0} end, case process_info(Owner, [messages, message_queue_len]) of -- knotmirror 0.0.1