An open-source, faster Devin alternative
TypeScript
computer: oc-modelproxy in the open, upstreams as profiles (#1028)
opencomputer-app[bot]93345a75a210
diff --git a/.github/workflows/computer.yml b/.github/workflows/computer.ymlindex c99ea1a2..3a32bc3e 100644--- a/.github/workflows/computer.yml+++ b/.github/workflows/computer.yml@@ -2,9 +2,10 @@ name: Computer# CI for computer: `npm run check` (typecheck, lint, unit tests, file-size# ratchet, boundaries, schemas, the runner bundle), the Slack-path timing-# check, the telemetry collector and Grafana JSON, and a secret scan. The-# integration checks in computer/src/dev/ (real processes, some need Claude-# credentials) are run by hand. Nothing here deploys, and no job has a secret.+# check, the telemetry collector and Grafana JSON, the model proxy (Go), and a+# secret scan. The integration checks in computer/src/dev/ (real processes,+# some need Claude credentials) are run by hand. Nothing here deploys, and no+# job has a secret.on:pull_request:@@ -80,6 +81,30 @@ jobs:node-version: 24- run: node telemetry/grafana/render.mjs --check+ modelproxy:+ name: Model proxy+ runs-on: ubuntu-latest+ timeout-minutes: 10+ defaults:+ run:+ working-directory: computer/modelproxy+ steps:+ - uses: actions/checkout@v4+ with:+ persist-credentials: false+ - uses: actions/setup-go@v5+ with:+ go-version-file: computer/modelproxy/go.mod+ cache: false # standard library only: nothing to cache+ - run: test -z "$(gofmt -l .)" || { gofmt -l .; exit 1; }+ - run: go vet ./...+ - run: go test -race -count=1 ./...+ # Did the proxy get slower: its median overhead and allocations per request, against a local upstream.+ - run: go test -run '^$' -bench ProxyOverhead -benchtime 5000x ./...+ env:+ MODELPROXY_OVERHEAD_GATE: 1+ - run: CGO_ENABLED=0 go build -trimpath -o "$RUNNER_TEMP/oc-modelproxy" .+secrets:name: Secret scanruns-on: ubuntu-latestdiff --git a/computer/.gitleaks.toml b/computer/.gitleaks.tomlindex 7599c578..a23aa204 100644--- a/computer/.gitleaks.toml+++ b/computer/.gitleaks.toml@@ -22,4 +22,5 @@ regexes = ['''^\s+'sk_live_abcdefghijkl',$''','''^\s+'AKIAABCDEFGHIJKLMNOP',$''','''find\(api, 'do_busy_ms_per_min_p95'\)''',+ '''-H 'x-api-key: ssh-placeholder' ''',]diff --git a/computer/modelproxy/.gitignore b/computer/modelproxy/.gitignorenew file mode 100644index 00000000..f441439b--- /dev/null+++ b/computer/modelproxy/.gitignore@@ -0,0 +1 @@+/oc-modelproxydiff --git a/computer/modelproxy/README.md b/computer/modelproxy/README.mdnew file mode 100644index 00000000..f6549181--- /dev/null+++ b/computer/modelproxy/README.md@@ -0,0 +1,206 @@+# oc-modelproxy++A small reverse proxy between the model clients in a computer's sessions (Claude Code, Codex, anything that takes a base URL) and the model APIs. A session's client is configured with a placeholder instead of a credential; the proxy knows which session a request comes from, puts the real credential on it and forwards it. The credential is never in the session's environment, files or logs.++Everything the proxy knows about an upstream is configuration: a **profile** names the upstream, the routes a session may call, the headers that carry the credential, and what to report back. The proxy has no built-in providers.++Go, standard library only. One static binary.++```+session's client ──HTTP──▶ api socket ─────────┐+ ├─ oc-modelproxy ──HTTPS──▶ the profile's upstream+binder ──JSON lines──▶ control socket ─────────┘+```++- **API socket**: model clients. An `Authorization` or `X-Api-Key` other than the placeholder is refused.+- **Control socket**: the binder (on a computer, the host). It binds a caller to a profile and the values of its variables, and hears what upstreams answer.++## Profiles++JSON files in `-profiles` (default `/etc/oc-modelproxy/profiles.d/*.json`), each an object of name → profile, read once at start. A file with an unknown field, a profile that fails a check, or a name defined twice stops the proxy at start. `oc-modelproxy -check -profiles <dir>` runs the same load and nothing else: exit 0, or the first error and exit 1.++`profiles/default.json` ships four:++| Profile | Upstream | Routes | Credential |+|---|---|---|---|+| `anthropic-key` | `api.anthropic.com` | `POST /v1/messages`, `/v1/messages/count_tokens` | `X-Api-Key: {token}` |+| `claude-oauth` | `api.anthropic.com` | the same, for Claude Code's requests, and its two account endpoints | `Authorization: Bearer {token}` |+| `openrouter` | `openrouter.ai/api` | `POST /v1/messages`, `/v1/messages/count_tokens` | `Authorization: Bearer {token}` |+| `openai-key` | `api.openai.com` | `POST` and `WS /v1/responses`, `GET /v1/models` | `Authorization: Bearer {token}` |++Each drops the caller's `Cookie` and reports the upstream's rate-limit headers and `retry-after`.++Any Anthropic-compatible or Responses-compatible API is one more entry:++```json+{+ "my-gateway": {+ "upstream": "https://llm.example.com/anthropic",+ "routes": {+ "POST /v1/messages": {},+ "POST /v1/messages/count_tokens": {}+ },+ "set": { "Authorization": "Bearer {token}" },+ "harness": { "claude": { "tokenEnv": "ANTHROPIC_AUTH_TOKEN" } }+ }+}+```++### Reference++| Field | Meaning |+|---|---|+| `upstream` | An `https` base URL. Its path, if any, prefixes every request's. |+| `routes` | The allowlist: `METHOD /path` (GET, POST, PUT, PATCH, DELETE) or `WS /path` for a WebSocket. The path matches exactly; the query passes through. Anything else is a 404. |+| `set` | Request headers to set. Values may use `{variables}`; every variable a profile uses must be in a bind to it. |+| `remove` | Globs of request header names to drop. |+| `report` | Globs of response header names sent to the binder with each `observed`. |+| `concurrency` | `{ "key": "{variable}", "limit": n }`: a cap on requests in flight across every caller whose binding expands `key` alike. Over it: 429, `Retry-After: 1`. |+| `websocket` | `false` refuses the profile's WS routes with 426, so clients go on over HTTP. |+| `harness` | Per harness name, an object passed to the binder in `hello`; the proxy does not read it. It is where a profile says how each model client is configured for it. |+| `errors` | Texts replacing the proxy's own: `require`, `notReady`, `refused`, `refusedPrefix`, `unreachable`, `concurrency`. |++Per route:++| Field | Meaning |+|---|---|+| `to` | The upstream path, when it differs from the route's. |+| `require` | Header globs the request must match (a whole value, or one item of a comma-separated list, parameters ignored), else 403. A header the request's `Connection` lists does not count: it would not reach the upstream. |+| `set`, `default` | Headers for this route; `default` only where the request has none. |+| `name` | Its name in telemetry; by default the path's last element (`messages`, `count_tokens`), `_ws` added for a WS route. |+| `format` | `responses`: the route streams Responses events, which telemetry reads for the first output and the service tier. A WS route always does. |++Globs match case-insensitively; `*` is any run of characters.++### What the proxy does to a request++1. Removes `Authorization` and `X-Api-Key` (the placeholder), then the profile's `remove`.+2. Applies the profile's `set`, the route's `set`, then the route's `default`.+3. Sends it to the profile's upstream, at `to` or the route's path (never the caller's own encoding of it).++Every other header, the query and the body pass untouched: for an upstream that also takes a credential in another header, a cookie or the query, name the headers in `remove` and do not use the proxy for one that authenticates by query. The body is streamed, never read; the response is flushed as it arrives. Hop-by-hop headers and `X-Forwarded-For/-Host/-Proto` are dropped as by any reverse proxy.++A profile's requests only ever go to its own upstream, over its own connections. A session only reaches its binding's profile.++## Refusals++Written by the proxy itself, never the upstream. One body on every route: `{"type":"error","error":{"type","message"}}`. `reason` is what the `model.denied` event says.++| Status | `reason` | When |+|---|---|---|+| 401 | `credentials` | The request carries a credential other than the placeholder. |+| 401 | `unknown_caller` | The connection is not a caller's (`-identity`). |+| 429 | `caller_cap` | The caller is at `-max-inflight-per-caller`. `Retry-After: 1`. |+| 503 | none (`model.held`) | The caller's bind has not arrived within `-hold-timeout`, and the binder named the caller or has not yet said `synced`. `Retry-After: 1`. |+| 401 | `unbound` | No bind within `-hold-timeout` for a caller the binder did not name by `synced`. |+| 401 | `refused` | The binder bound the caller with `mode: "refuse"`; its reason is the text. |+| 404 | `route` | Not a route of the caller's profile. |+| 426 | `websocket` | An upgrade that is not a WS route, or `websocket: false`. |+| 426 | none (`model.request`) | The upstream refused the WebSocket handshake; the event and `observed` carry its status. |+| 403 | `require` | The route's `require` does not match. |+| 429 | `concurrency_cap` | The profile's `concurrency`. `Retry-After: 1`. |+| 503 | `upstream_busy` | Still queued for one of the upstream's connections (`-max-conns-per-host`) after `-hold-timeout`. `Retry-After: 1`. |+| 502 | none (`model.request`) | The upstream could not be reached (10 s to connect, 10 s for TLS); `observed` carries the error. |++On a request to upgrade, every refusal is a 426 with `Use HTTP: ` before the text, so a client goes on over HTTP. A refusal is reported, as a `model.denied` event and a journal line, at most once per caller and reason every 10 s; `suppressed` counts those since the last report.++Before a request is admitted: its headers may be 32 KB (431 past it), and a caller may have `-max-conns-per-caller` connections open (more are closed as accepted).++## Control protocol++JSON lines on the control socket; `hello.protocol` is 1. Unknown `t` values and fields are ignored. One example of every frame: `testdata/control/`; the types: `frames.go`.++| Direction | `t` | |+|---|---|---|+| proxy → binder | `hello` | First line: `{version, protocol, placeholder, profiles, bindings}`. Each profile is `{name, vars, harness}`, sorted by name; `vars` are the names a bind to it must give. `bindings` are the ones the proxy holds, without variables, so the binder re-sends their binds. |+| binder → proxy | `bind` | `{id?, caller, sessionKey, profile, vars, key}`: the caller's requests go to `profile` with `vars`. `key` is the binder's own name for the credential, never the secret. `{caller, sessionKey, mode: "refuse", reason}` makes the caller's requests 401. |+| proxy → binder | `bound` | `{id?, caller, sessionKey, key?}`: in effect for the caller's next request. |+| proxy → binder | `refused` | `{id?, caller, code, message}`: not applied. `code` is `bad_frame`, `unknown_profile`, `missing_var`, `bad_key` or `caller_in_use`. |+| binder → proxy | `release` | `{caller}`: delete the binding. |+| binder → proxy | `synced` | The binder has sent every bind it has. From then on a caller without one is unknown (401), not early (503). |+| proxy → binder | `observed` | What an upstream answered a binding: `{sessionKey, caller, key, profile, status, headers, body}` or `{…, error}`. Headers are the profile's `report`; the body is the start of an error's. What it means is the binder's to decide. Deduplicated: never one per request in the steady state. |+| binder → proxy | `request` | `{id, profile, vars, method, path, query?, headers?, body?}`: one request on a profile's route with these variables, which are not stored. For checking a credential before binding it. |+| proxy → binder | `response` | `{id, status, headers, body}` or `{id, error}`, on the connection that asked. `error` is `unknown_profile`, `unknown_route`, `missing_var`, `bad_request`, `busy` (16 are in flight), `timeout` or `unreachable`. |+| proxy → binder | `event` | A telemetry event to relay (below). |++Rules that hold:++- Every binder → proxy frame is idempotent: the same `bind` twice is answered `bound` twice and changes nothing.+- A caller serves one `sessionKey` from its bind to its release; a bind naming another is `refused` (`caller_in_use`).+- A bind applies to the caller's next request. Streams in flight finish on the credential they started with; a WebSocket is closed after the response in flight, or at once if the client starts another on it first.+- Variables live only in memory. `-bindings-file` keeps caller, session, mode, profile and key, so a restarted proxy holds its callers' requests until the binder re-binds instead of refusing them.+- Only `release` removes a binding. A closed control connection changes nothing; a binder that connects again gets every binding in its `hello`.++### Events++`{t: "event", name, at, outcome, duration_ms?, error_type?, session_key?, profile?, data}`. `data` values are scalars: never a variable, a body or upstream text. One example of each: `testdata/control/event-*.json`.++| `name` | When | `data` |+|---|---|---|+| `model.request` | A request that reached the upstream, once it ends. | `route`, `stream`, `swapped`, `status`, `key`, `conn_wait_ms`, `conn_reused`, `overhead_us`, `ttfb_ms`; on a `responses` route `first_output_ms`, `service_tier`; over a WebSocket `transport`, `responses`, `closed`, `prewarm` |+| `model.held` | A request that waited for its caller's bind. | `held_ms`, `released` (`bound`, `timeout`) |+| `model.denied` | A refusal, at most one per caller and reason every 10 s. | `reason` (the table above), `route`, `suppressed` |+| `model.binding` | A bind, a change of credential, a release, a refused bind. | `action` (`bind`, `swap`, `release`, `refused`), `caller`, `mode`, `key`; `code` when refused |+| `model.pool` | Every minute, per profile with traffic. | `open_conns`, `idle_conns`, `active_streams`, `idle_pool_miss`, `dials`; on the first profile also `bindings`, `dropped_messages` |+| `model.proxy_started` | At start. | `version`, `bindings` |++`outcome` is `completed`, `failed`, `cancelled` or `timed_out`; `error_type` is `provider_error`, `provider_rate_limited`, `timeout`, `socket`, `websocket` or `concurrency`.++## Who is calling++`-identity=cgroup` (default): the caller is `<id>` of the `sp-runner-<id>.service` unit the connection's peer process runs in, read once from its cgroup when the connection is accepted. The outermost such unit in the path wins, so a process cannot rename itself by creating cgroups below its own. This is routing, not isolation: sessions that share a uid can move between each other's units, so do not put mutually untrusted tenants on one computer.++`-identity=single`: every connection is the caller `single`. For a computer that runs one session outside systemd.++## Flags++| Flag | Default | |+|---|---|---|+| `-api-socket` | `/run/oc-modelproxy/api.sock` | the model clients' socket, when not socket-activated |+| `-control-socket` | `/run/oc-modelproxy/control.sock` | the binder's socket, when not socket-activated |+| `-profiles` | `/etc/oc-modelproxy/profiles.d` | directory of profile files |+| `-check` | | load `-profiles`, print the first error, exit 0 or 1 |+| `-placeholder` | `ssh-placeholder` | the only credential a caller may send |+| `-identity` | `cgroup` | `cgroup` or `single` |+| `-bindings-file` | `/run/oc-modelproxy/profile-bindings.json` | persisted bindings, without variables (empty: off) |+| `-hold-timeout` | `10s` | how long a request waits for its caller's bind, and then for a free upstream connection |+| `-drain-timeout` | `630s` | on SIGTERM, how long streams in flight may finish |+| `-max-inflight-per-caller` | `32` | concurrent requests per caller, held ones included (0: no limit) |+| `-max-conns-per-caller` | `128` | connections a caller may have open on the API socket (0: no limit) |+| `-ws-idle-timeout` | `5m` | close a WebSocket idle this long between responses (0: never) |+| `-max-idle-conns-per-host`, `-max-conns-per-host`, `-idle-conn-timeout` | `96`, `256`, `50s` | upstream connection pool, per profile |+| `-debug`, `-version` | | |++Profiles are read at start; to change them, restart the proxy. Bindings survive the restart and streams in flight finish first. The garbage collector runs at `GOGC=400` unless the environment sets `GOGC`.++## Build and test++```sh+cd computer/modelproxy+gofmt -l . && go vet ./...+go test -race -count=1 ./...+MODELPROXY_OVERHEAD_GATE=1 go test -run '^$' -bench ProxyOverhead -benchtime 5000x ./...+CGO_ENABLED=0 go build -trimpath -ldflags "-X main.version=$(git rev-parse HEAD)" -o oc-modelproxy .+```++The tests run on the shipped profiles and a neutral fixture profile, against fake upstreams; none contacts a real API. The benchmark fails when the proxy's median overhead per request passes 0.1 ms or its allocations per request pass 250.++## Try it++```sh+mkdir -p /tmp/mp && ./oc-modelproxy -identity=single -profiles ./profiles \+ -api-socket /tmp/mp/api.sock -control-socket /tmp/mp/control.sock -bindings-file ""++# the binder's side: bind the single caller to a key+printf '%s\n' '{"t":"bind","caller":"single","sessionKey":"s1","profile":"anthropic-key","vars":{"token":"'"$ANTHROPIC_API_KEY"'"},"key":"mine"}' \+ | nc -U /tmp/mp/control.sock++# a client's side: the placeholder, not the key+curl --unix-socket /tmp/mp/api.sock http://localhost/v1/messages \+ -H 'x-api-key: ssh-placeholder' -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' \+ -d '{"model":"claude-haiku-4-5","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}'+```++## Files++One concept per file, each with a header comment that says what it is and what must stay true: `profile.go` and `template.go` (profiles), `bindings.go` and `lease.go` (the table, and a request's hold on it), `proxy.go` (a request's stages), `refuse.go` (refusals), `outbound.go` (the rewrite), `observed.go` and `request.go` (what the binder hears and asks), `control.go` and `frames.go` (the control protocol), `websocket.go`, `wsframe.go`, `wsmessages.go` (WebSocket tunnels), `responses.go` and `telemetry.go` (events), `upstream.go` (connections), `identity.go` and `connlimit.go` (who is calling), `inflight.go`, `persist.go`, `activation.go`.diff --git a/computer/modelproxy/activation.go b/computer/modelproxy/activation.gonew file mode 100644index 00000000..4c567055--- /dev/null+++ b/computer/modelproxy/activation.go@@ -0,0 +1,85 @@+// systemd integration without libsystemd: socket activation (LISTEN_PID,+// LISTEN_FDS, LISTEN_FDNAMES; fds from 3) and sd_notify (one datagram to+// NOTIFY_SOCKET). Not activated (local runs, tests): the proxy creates the+// sockets itself.+package main++import (+ "errors"+ "fmt"+ "net"+ "os"+ "strconv"+ "strings"+)++const listenFdsStart = 3++// activatedListeners returns systemd-passed listeners by name; nil when the+// process was not socket-activated.+func activatedListeners() (map[string]net.Listener, error) {+ defer func() {+ os.Unsetenv("LISTEN_PID")+ os.Unsetenv("LISTEN_FDS")+ os.Unsetenv("LISTEN_FDNAMES")+ }()+ pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))+ if err != nil || pid != os.Getpid() {+ return nil, nil+ }+ n, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))+ if err != nil || n <= 0 {+ return nil, nil+ }+ names := strings.Split(os.Getenv("LISTEN_FDNAMES"), ":")+ out := map[string]net.Listener{}+ for i := range n {+ fd := listenFdsStart + i+ name := ""+ if i < len(names) {+ name = names[i]+ }+ f := os.NewFile(uintptr(fd), name)+ l, err := net.FileListener(f) // dups the fd+ f.Close()+ if err != nil {+ return nil, fmt.Errorf("activated fd %d (%q): %w", fd, name, err)+ }+ out[name] = l+ }+ return out, nil+}++// listenUnix creates a Unix socket at path (replacing a stale one), mode 0660.+func listenUnix(path string) (net.Listener, error) {+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {+ return nil, err+ }+ l, err := net.Listen("unix", path)+ if err != nil {+ return nil, err+ }+ if err := os.Chmod(path, 0o660); err != nil {+ l.Close()+ return nil, err+ }+ return l, nil+}++// sdNotify sends state to the service manager; a no-op when not under systemd.+func sdNotify(state string) error {+ addr := os.Getenv("NOTIFY_SOCKET")+ if addr == "" {+ return nil+ }+ if addr[0] == '@' {+ addr = "\x00" + addr[1:]+ }+ c, err := net.DialUnix("unixgram", nil, &net.UnixAddr{Name: addr, Net: "unixgram"})+ if err != nil {+ return err+ }+ defer c.Close()+ _, err = c.Write([]byte(state))+ return err+}diff --git a/computer/modelproxy/activation_test.go b/computer/modelproxy/activation_test.gonew file mode 100644index 00000000..435e2ff1--- /dev/null+++ b/computer/modelproxy/activation_test.go@@ -0,0 +1,106 @@+package main++import (+ "net"+ "os"+ "os/exec"+ "path/filepath"+ "strconv"+ "testing"+ "time"+)++// TestSocketActivation runs this test binary as a child with two listening+// sockets on fds 3 and 4, as systemd passes them, and checks both are found+// by name and accept connections.+func TestSocketActivation(t *testing.T) {+ if os.Getenv("MP_ACTIVATION_CHILD") == "1" {+ os.Setenv("LISTEN_PID", strconv.Itoa(os.Getpid())) // systemd sets it after fork+ ls, err := activatedListeners()+ if err != nil || ls["api"] == nil || ls["control"] == nil {+ t.Fatalf("listeners %v err %v", ls, err)+ }+ if os.Getenv("LISTEN_FDS") != "" {+ t.Fatal("LISTEN_FDS not unset for children")+ }+ for _, name := range []string{"api", "control"} {+ go func() {+ c, err := ls[name].Accept()+ if err == nil {+ c.Write([]byte(name))+ c.Close()+ }+ }()+ }+ for _, name := range []string{"api", "control"} {+ c, err := net.Dial("unix", os.Getenv("MP_DIR")+"/"+name+".sock")+ if err != nil {+ t.Fatal(err)+ }+ b := make([]byte, 16)+ n, _ := c.Read(b)+ if string(b[:n]) != name {+ t.Fatalf("%s socket answered %q", name, b[:n])+ }+ c.Close()+ }+ return+ }+ dir, _ := os.MkdirTemp("", "mp")+ defer os.RemoveAll(dir)+ var files []*os.File+ for _, name := range []string{"api", "control"} {+ l, err := listenUnix(filepath.Join(dir, name+".sock"))+ if err != nil {+ t.Fatal(err)+ }+ l.(*net.UnixListener).SetUnlinkOnClose(false)+ f, err := l.(*net.UnixListener).File()+ if err != nil {+ t.Fatal(err)+ }+ l.Close()+ files = append(files, f)+ }+ cmd := exec.Command(os.Args[0], "-test.run=^TestSocketActivation$", "-test.count=1")+ cmd.ExtraFiles = files+ cmd.Env = append(os.Environ(), "MP_ACTIVATION_CHILD=1", "MP_DIR="+dir, "LISTEN_FDS=2", "LISTEN_FDNAMES=api:control")+ out, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("child: %v\n%s", err, out)+ }+}++func TestSdNotify(t *testing.T) {+ dir, _ := os.MkdirTemp("", "mp")+ defer os.RemoveAll(dir)+ path := filepath.Join(dir, "n.sock")+ c, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: path, Net: "unixgram"})+ if err != nil {+ t.Fatal(err)+ }+ defer c.Close()+ t.Setenv("NOTIFY_SOCKET", path)+ if err := sdNotify("READY=1"); err != nil {+ t.Fatal(err)+ }+ b := make([]byte, 64)+ c.SetReadDeadline(time.Now().Add(time.Second))+ n, _ := c.Read(b)+ if string(b[:n]) != "READY=1" {+ t.Fatalf("got %q", b[:n])+ }+ t.Setenv("NOTIFY_SOCKET", "")+ if err := sdNotify("READY=1"); err != nil {+ t.Fatal(err)+ }+}++func TestNotActivated(t *testing.T) {+ t.Setenv("LISTEN_PID", "1")+ t.Setenv("LISTEN_FDS", "2")+ ls, err := activatedListeners()+ if err != nil || ls != nil {+ t.Fatalf("another pid's fds taken: %v %v", ls, err)+ }+}diff --git a/computer/modelproxy/bench_test.go b/computer/modelproxy/bench_test.gonew file mode 100644index 00000000..035736e2--- /dev/null+++ b/computer/modelproxy/bench_test.go@@ -0,0 +1,262 @@+package main++import (+ "bufio"+ "cmp"+ "context"+ "crypto/x509"+ "encoding/json"+ "encoding/pem"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "runtime/debug"+ "slices"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++const (+ benchConcurrency = 64+ overheadMedianMs = 0.1+ allocsPerRequest = 250+)++// BenchmarkProxyOverhead streams SSE through the proxy at 64 concurrent+// streams from a local TLS fake upstream, and reports the proxy's own time+// per request: overhead_pre + overhead_first_byte (telemetry.go), which+// leaves out the upstream's time and the client's. The upstream and the+// clients run in a child process, as they do on a real host, so their+// allocations and goroutines do not land in the proxy's heap and scheduler.+// The proxy runs at the binary's GC setting (defaultGCPercent).+//+// With MODELPROXY_OVERHEAD_GATE=1 (CI) it fails when, in each of three+// rounds, the median overhead exceeds overheadMedianMs or the proxy+// allocates more than allocsPerRequest per request. p99 is reported, not+// gated: on a shared runner it measures the neighbours.+//+// MODELPROXY_OVERHEAD_GATE=1 go test -run '^$' -bench ProxyOverhead -benchtime 5000x+func BenchmarkProxyOverhead(b *testing.B) {+ setGCPercent()+ b.Cleanup(func() { debug.SetGCPercent(100) })+ cmd := exec.Command(os.Args[0], "-test.run=^TestLoadGenChild$", "-test.count=1", "-test.v=false")+ cmd.Env = append(os.Environ(), "MP_LOADGEN_CHILD=1")+ cmd.Stderr = os.Stderr+ stdin, _ := cmd.StdinPipe()+ stdout, _ := cmd.StdoutPipe()+ if err := cmd.Start(); err != nil {+ b.Fatal(err)+ }+ defer func() { stdin.Close(); cmd.Wait() }()+ out := bufio.NewScanner(stdout)+ out.Buffer(make([]byte, 1<<16), 1<<20)+ var hello struct{ URL, CertPEM string }+ if !out.Scan() || json.Unmarshal(out.Bytes(), &hello) != nil {+ b.Fatalf("load generator did not start: %q", out.Text())+ }+ blk, _ := pem.Decode([]byte(hello.CertPEM))+ cert, err := x509.ParseCertificate(blk.Bytes)+ if err != nil {+ b.Fatal(err)+ }+ roots := x509.NewCertPool()+ roots.AddCert(cert)+ ps, err := compileProfiles(map[string]profileJSON{mainProfile: {+ Upstream: hello.URL,+ Routes: map[string]routeJSON{"POST /v1/messages": {Require: map[string]string{"User-Agent": "claude-cli/*", "X-App": "cli", "Anthropic-Beta": "oauth-2025-04-20"}}},+ Set: map[string]string{"Authorization": "Bearer {token}"},+ Report: []string{"x-quota-*"},+ }})+ if err != nil {+ b.Fatal(err)+ }++ dir, err := os.MkdirTemp("", "mp")+ if err != nil {+ b.Fatal(err)+ }+ b.Cleanup(func() { os.RemoveAll(dir) })+ cfg := config{hold: 2 * time.Second, bindingsFile: filepath.Join(dir, "bindings.json"), placeholder: testPlaceholder, rootCAs: roots,+ maxIdlePerHost: 96, maxConnsPerHost: 256, idleConnTimeout: time.Minute}+ srv, err := newServer(cfg, ps, func(net.Conn) string { return testCaller })+ if err != nil {+ b.Fatal(err)+ }+ h := &harness{t: b, srv: srv, dir: dir, ctlPath: filepath.Join(dir, "c.sock")}+ apiL, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ b.Fatal(err)+ }+ ctlL, err := listenUnix(h.ctlPath)+ if err != nil {+ b.Fatal(err)+ }+ srv.start(apiL, ctlL)+ b.Cleanup(func() {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ srv.shutdown(ctx)+ })+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ go func() { // keep the control queue empty+ for range k.msgs {+ }+ }()++ var mu sync.Mutex+ var totals, pres, fbs []time.Duration+ srv.proxy.statsHook = func(st *reqState) {+ pre, ok1 := st.overheadPre()+ fb, ok2 := st.overheadFirstByte()+ if !ok1 || !ok2 {+ return+ }+ mu.Lock()+ totals, pres, fbs = append(totals, pre+fb), append(pres, pre), append(fbs, fb)+ mu.Unlock()+ }+ load := func(n int) {+ fmt.Fprintf(stdin, "http://%s %d\n", apiL.Addr(), n)+ if !out.Scan() || out.Text() != "ok" {+ b.Fatalf("load generator: %q", out.Text())+ }+ }+ load(benchConcurrency * 4) // warm both connection pools+ mu.Lock()+ totals, pres, fbs = nil, nil, nil+ mu.Unlock()++ // Three rounds of b.N requests each; the gate takes the best round, so a+ // burst from another process on a shared runner fails one round, not+ // the build. A real regression fails all three.+ const rounds = 3+ type result struct{ p50, p99, pre99, fb99, allocs float64 }+ p := func(xs []time.Duration, q float64) float64 {+ s := slices.Clone(xs)+ slices.Sort(s)+ return float64(s[min(int(q*float64(len(s))), len(s)-1)].Microseconds()) / 1000+ }+ var results []result+ b.ResetTimer()+ var mem runtime.MemStats+ for range rounds {+ runtime.ReadMemStats(&mem)+ mallocs := mem.Mallocs+ load(b.N)+ runtime.ReadMemStats(&mem)+ allocs := float64(mem.Mallocs-mallocs) / float64(b.N)+ mu.Lock()+ if len(totals) < b.N {+ mu.Unlock()+ b.Fatalf("%d measurements for %d requests", len(totals), b.N)+ }+ results = append(results, result{p(totals, 0.50), p(totals, 0.99), p(pres, 0.99), p(fbs, 0.99), allocs})+ totals, pres, fbs = nil, nil, nil+ mu.Unlock()+ }+ b.StopTimer()+ best := slices.MinFunc(results, func(x, y result) int { return cmp.Compare(x.p99, y.p99) })+ worst := slices.MaxFunc(results, func(x, y result) int { return cmp.Compare(x.p99, y.p99) })+ p50 := slices.MinFunc(results, func(x, y result) int { return cmp.Compare(x.p50, y.p50) }).p50+ allocs := slices.MinFunc(results, func(x, y result) int { return cmp.Compare(x.allocs, y.allocs) }).allocs+ b.ReportMetric(p50, "p50-overhead-ms")+ b.ReportMetric(allocs, "proxy-allocs/req")+ b.ReportMetric(best.p99, "p99-overhead-ms")+ b.ReportMetric(worst.p99, "worst-round-p99-ms")+ b.ReportMetric(best.pre99, "p99-pre-ms")+ b.ReportMetric(best.fb99, "p99-first-byte-ms")+ if os.Getenv("MODELPROXY_OVERHEAD_GATE") != "" && b.N >= 100 {+ if p50 > overheadMedianMs {+ b.Fatalf("proxy overhead median %.3f ms > %.3f ms in every round (%+v)", p50, overheadMedianMs, results)+ }+ if allocs > allocsPerRequest {+ b.Fatalf("%.0f allocations per request > %d in every round (%+v)", allocs, allocsPerRequest, results)+ }+ }+}++// TestLoadGenChild is BenchmarkProxyOverhead's other process: a TLS fake+// SSE upstream plus 64 concurrent streaming clients. It prints the upstream's+// URL and certificate, then for each "<proxy url> <n>" line on stdin runs n+// requests and answers "ok" (or the first error).+func TestLoadGenChild(t *testing.T) {+ if os.Getenv("MP_LOADGEN_CHILD") != "1" {+ t.Skip("run by BenchmarkProxyOverhead")+ }+ const events = 8+ payload := make([]byte, 0, 4096)+ for i := range events {+ payload = fmt.Appendf(payload, "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"chunk %d lorem ipsum dolor sit amet\"}}\n\n", i)+ }+ up := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ w.Header().Set("Content-Type", "text/event-stream")+ w.Header().Set("X-Quota-Used", "12")+ w.WriteHeader(200)+ f := w.(http.Flusher)+ f.Flush()+ chunk := len(payload) / events+ for i := 0; i < len(payload); i += chunk {+ w.Write(payload[i:min(i+chunk, len(payload))])+ f.Flush()+ }+ }))+ up.EnableHTTP2 = false+ up.StartTLS()+ defer up.Close()+ certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: up.Certificate().Raw})+ line, _ := json.Marshal(map[string]string{"URL": up.URL, "CertPEM": string(certPEM)})+ os.Stdout.Write(append(line, '\n'))++ clients := make([]*http.Client, benchConcurrency)+ for i := range clients {+ clients[i] = &http.Client{Transport: &http.Transport{DisableCompression: true, MaxIdleConnsPerHost: 4}}+ }+ in := bufio.NewScanner(os.Stdin)+ for in.Scan() {+ var target string+ var n int64+ if _, err := fmt.Sscanf(in.Text(), "%s %d", &target, &n); err != nil {+ t.Fatal(err)+ }+ h := &harness{apiURL: target}+ var next atomic.Int64+ var firstErr atomic.Value+ var wg sync.WaitGroup+ for i := range benchConcurrency {+ wg.Add(1)+ go func() {+ defer wg.Done()+ for next.Add(1) <= n {+ res, err := clients[i].Do(h.messagesReq(context.Background()))+ if err == nil {+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ if res.StatusCode != 200 {+ err = fmt.Errorf("status %d", res.StatusCode)+ }+ }+ if err != nil {+ firstErr.CompareAndSwap(nil, err.Error())+ return+ }+ }+ }()+ }+ wg.Wait()+ if e := firstErr.Load(); e != nil {+ fmt.Println(e)+ } else {+ fmt.Println("ok")+ }+ }+}diff --git a/computer/modelproxy/bindings.go b/computer/modelproxy/bindings.gonew file mode 100644index 00000000..8017b03b--- /dev/null+++ b/computer/modelproxy/bindings.go@@ -0,0 +1,270 @@+// Bindings: which caller serves which session with which credential. The+// binder is the source of truth; this table is the proxy's copy of it, fed+// over the control socket (frames.go).+//+// A credential is a profile (profile.go) and the values of its variables.+// `bind` names them as {profile, vars, key}: the key is the binder's own name+// for the credential (never the secret), echoed on `bound`, `observed` and+// telemetry. A bind with mode "refuse" makes the proxy answer the caller's+// requests with 401 and the bind's reason.+//+// Invariants:+// - A caller serves one sessionKey from its bind to its release; a bind+// naming another sessionKey is refused, never applied.+// - A bind applies to the caller's next request. Streams in flight finish+// on the credential they started with (lease.go).+// - The same bind twice changes nothing and is answered `bound` again.+// - Variables live only in memory; the persisted table (persist.go) has none.+// - Entries restored from disk are "known, not credentialed": requests for+// them are held until their bind arrives or the hold cap (then 503).+// - Only `release` removes a binding. A closed control connection keeps+// every binding and its variables; serving continues.+// - A binding always has every variable its profile uses.+// - Nothing is sent or logged while mu is held.+package main++import (+ "maps"+ "sync"+ "sync/atomic"+ "time"+)++const (+ modeProfile = "profile"+ modeRefuse = "refuse"+)++type credential struct {+ refuse bool+ prof *profile // nil for a refuse+ vars map[string]string+ key string+ reason string+}++func (c *credential) equal(o *credential) bool {+ return c.refuse == o.refuse && c.prof == o.prof && c.key == o.key && c.reason == o.reason && maps.Equal(c.vars, o.vars)+}++func (c *credential) profileName() string {+ if c.prof == nil {+ return ""+ }+ return c.prof.name+}++func (c *credential) mode() string {+ if c.refuse {+ return modeRefuse+ }+ return modeProfile+}++type binding struct {+ caller string+ sessionKey string+ cred credential+ credentialed bool+ swapped bool // credential changed; not yet used by a request+}++func (b *binding) info() bindingInfo {+ return bindingInfo{Caller: b.caller, SessionKey: b.sessionKey, Mode: b.cred.mode(), Profile: b.cred.profileName(), Key: b.cred.key}+}++// sender delivers proxy → binder frames without blocking (control.go).+type sender interface{ send(v any) }++type Bindings struct {+ profiles *profiles+ out sender+ dirty func() // the table's persisted shape changed+ now func() time.Time+ // synced: the binder has re-sent every bind since this start. Until then+ // a caller without a binding may only be one whose bind is on its way.+ synced atomic.Bool++ mu sync.Mutex+ m map[string]*binding+ changed chan struct{} // closed and replaced on every change: wakes held requests+}++func NewBindings(ps *profiles, out sender, dirty func()) *Bindings {+ if dirty == nil {+ dirty = func() {}+ }+ return &Bindings{profiles: ps, m: map[string]*binding{}, changed: make(chan struct{}), out: out, dirty: dirty, now: time.Now}+}++// broadcastLocked wakes every held request; callers hold mu.+func (s *Bindings) broadcastLocked() {+ close(s.changed)+ s.changed = make(chan struct{})+}++// Restore loads the persisted table at start: every entry known, none credentialed.+func (s *Bindings) Restore(entries []bindingInfo) {+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, e := range entries {+ refuse := e.Mode == modeRefuse+ prof := s.profiles.get(e.Profile)+ if !isID(e.Caller) || e.SessionKey == "" || (prof == nil) != refuse {+ continue // a profile that is gone: the binder binds the caller again, or not+ }+ s.m[e.Caller] = &binding{caller: e.Caller, sessionKey: e.SessionKey, cred: credential{refuse: refuse, prof: prof, key: e.Key}}+ }+}++// Snapshot is the table without variables, in no particular order.+func (s *Bindings) Snapshot() []bindingInfo {+ s.mu.Lock()+ defer s.mu.Unlock()+ out := make([]bindingInfo, 0, len(s.m))+ for _, b := range s.m {+ out = append(out, b.info())+ }+ return out+}++func (s *Bindings) Len() int {+ s.mu.Lock()+ defer s.mu.Unlock()+ return len(s.m)+}++// Bind applies a `bind` and answers it: `bound`, or `refused` with why.+func (s *Bindings) Bind(m bindMsg) bool {+ c, code, msg := s.credentialOf(m)+ if code != "" {+ s.refuse(m, code, msg)+ return false+ }+ s.mu.Lock()+ b := s.m[m.Caller]+ if b != nil && b.sessionKey != m.SessionKey {+ s.mu.Unlock()+ s.refuse(m, refuseCallerInUse, "the caller is bound to another session")+ return false+ }+ action := "bind"+ switch {+ case b == nil:+ b = &binding{caller: m.Caller, sessionKey: m.SessionKey}+ s.m[m.Caller] = b+ case b.credentialed && b.cred.equal(&c):+ action = "" // the same bind again+ case b.credentialed:+ action = "swap"+ b.swapped = true // the next request is the first on the new credential+ }+ if action != "" {+ reshaped := !b.credentialed || b.cred.refuse != c.refuse || b.cred.key != c.key || b.cred.prof != c.prof+ b.cred, b.credentialed = c, true+ s.broadcastLocked()+ if reshaped {+ s.dirty()+ }+ }+ s.mu.Unlock()++ s.out.send(boundMsg{T: "bound", ID: m.ID, Caller: m.Caller, SessionKey: m.SessionKey, Key: c.key})+ if action != "" {+ s.out.send(s.bindingEvent(action, m.Caller, m.SessionKey, &c))+ logInfo("bound", "caller", m.Caller, "session_key", m.SessionKey, "mode", c.mode(), "profile", c.profileName(), "key", c.key, "action", action)+ }+ return true+}++// credentialOf checks a bind and reads its credential. A refusal's message+// may name a variable, never its value.+func (s *Bindings) credentialOf(m bindMsg) (c credential, code, msg string) {+ switch {+ case !isID(m.Caller):+ return c, refuseBadFrame, "caller must be 1 to 64 of A-Z a-z 0-9 . _ : -"+ case m.SessionKey == "":+ return c, refuseBadFrame, "missing sessionKey"+ case m.Mode == modeRefuse:+ return credential{refuse: true, reason: m.Reason}, "", ""+ case m.Mode != "":+ return c, refuseBadFrame, "unknown mode"+ }+ c = credential{prof: s.profiles.get(m.Profile), key: m.Key}+ switch {+ case c.prof == nil:+ return c, refuseUnknownProfile, "no such profile"+ case !isID(m.Key):+ return c, refuseBadKey, "key must be 1 to 64 of A-Z a-z 0-9 . _ : -"+ }+ c.vars = make(map[string]string, len(c.prof.vars))+ for _, v := range c.prof.vars { // only what the profile uses is kept+ val := m.Vars[v]+ switch {+ case val == "":+ return c, refuseMissingVar, "missing " + v+ case !validHeaderValue(val):+ return c, refuseMissingVar, v + " is not a header value"+ }+ c.vars[v] = val+ }+ return c, "", ""+}++func (s *Bindings) refuse(m bindMsg, code, msg string) {+ caller := truncate(m.Caller, 64)+ logWarn("bind refused", "caller", caller, "session_key", m.SessionKey, "code", code, "message", msg)+ s.out.send(refusedMsg{T: "refused", ID: m.ID, Caller: caller, Code: code, Message: msg})+ e := newEvent(s.now(), "model.binding")+ e.SessionKey, e.Outcome = m.SessionKey, "failed"+ e.Data = map[string]any{"action": "refused", "caller": caller, "code": code}+ s.out.send(e)+}++// bindingEvent is the model.binding telemetry event for a bind, swap or release.+func (s *Bindings) bindingEvent(action, caller, sessionKey string, c *credential) eventMsg {+ e := newEvent(s.now(), "model.binding")+ e.SessionKey, e.Profile, e.Outcome = sessionKey, c.profileName(), "completed"+ e.Data = map[string]any{"action": action, "caller": caller, "mode": c.mode()}+ if c.key != "" {+ e.Data["key"] = c.key+ }+ return e+}++// Release drops a caller's binding. Streams already in flight finish on the+// credential they started with.+func (s *Bindings) Release(caller string) {+ s.mu.Lock()+ b := s.m[caller]+ if b == nil {+ s.mu.Unlock()+ return+ }+ delete(s.m, caller)+ s.broadcastLocked()+ s.mu.Unlock()+ s.dirty()+ s.out.send(s.bindingEvent("release", caller, b.sessionKey, &b.cred))+ logInfo("released", "caller", caller, "session_key", b.sessionKey)+}++// Synced notes the binder's `synced`: every bind it has is here. Nothing is+// dropped (only `release` removes a binding) and nothing stops holding (a+// bind may still come a moment later); from now on a caller that stays+// without a binding is unknown (401), not early (503). Returns how many+// known callers still have no credential.+func (s *Bindings) Synced() (waiting int) {+ s.synced.Store(true)+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, b := range s.m {+ if !b.credentialed {+ waiting+++ }+ }+ return waiting+}++// isID: a caller or a key, 1 to 64 of A-Z a-z 0-9 . _ : -+func isID(s string) bool { return isName(s, "._:-") }diff --git a/computer/modelproxy/connlimit.go b/computer/modelproxy/connlimit.gonew file mode 100644index 00000000..d452c36b--- /dev/null+++ b/computer/modelproxy/connlimit.go@@ -0,0 +1,53 @@+// The API socket's listener: it names each connection's caller as it is+// accepted (identity.go) and caps how many connections one caller may have+// open (-max-conns-per-caller), so one session cannot hold enough of them to+// exhaust the proxy's memory or descriptors. Connections without a caller+// share one cap. Over it, a connection is closed at once.+//+// Invariant: a connection's caller is resolved once, here, never per+// request.+package main++import (+ "context"+ "net"+ "sync"+)++type callerListener struct {+ net.Listener+ resolve Resolver+ conns *inflight // open connections per caller+}++func (l *callerListener) Accept() (net.Conn, error) {+ for {+ c, err := l.Listener.Accept()+ if err != nil {+ return nil, err+ }+ caller := l.resolve(c)+ if l.conns.enter(caller) {+ return &callerConn{Conn: c, caller: caller, l: l}, nil+ }+ c.Close()+ }+}++type callerConn struct {+ net.Conn+ caller string+ l *callerListener+ once sync.Once+}++func (c *callerConn) Close() error {+ c.once.Do(func() { c.l.conns.leave(c.caller) })+ return c.Conn.Close()+}++// connCaller is http.Server.ConnContext: every request on a connection is+// its caller's, whatever its process does afterwards.+func connCaller(ctx context.Context, c net.Conn) context.Context {+ return context.WithValue(ctx, callerKey, c.(*callerConn).caller)+}diff --git a/computer/modelproxy/connlimit_test.go b/computer/modelproxy/connlimit_test.gonew file mode 100644index 00000000..97406ea2--- /dev/null+++ b/computer/modelproxy/connlimit_test.go@@ -0,0 +1,77 @@+package main++import (+ "net"+ "net/http"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// dialAs opens a raw API connection the proxy sees as caller.+func (h *harness) dialAs(caller string) net.Conn {+ h.t.Helper()+ c, err := net.Dial("tcp", strings.TrimPrefix(h.apiURL, "http://"))+ if err != nil {+ h.t.Fatal(err)+ }+ h.callers.Store(c.LocalAddr().String(), caller)+ h.t.Cleanup(func() { c.Close() })+ return c+}++// closedByProxy: the proxy closes c without answering.+func closedByProxy(t *testing.T, c net.Conn) {+ t.Helper()+ c.SetReadDeadline(time.Now().Add(3 * time.Second))+ if n, err := c.Read(make([]byte, 1)); n != 0 || err == nil || strings.Contains(err.Error(), "timeout") {+ t.Fatalf("connection past the cap: read %d %v", n, err)+ }+}++// A caller's connections past -max-conns-per-caller are closed as accepted;+// another caller's are not, and a closed one frees its place.+func TestConnsPerCaller(t *testing.T) {+ up, hits := okUpstream()+ h := newHarness(t, up, harnessOpts{conns: 2})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ a, _ := h.dialAs("hog"), h.dialAs("hog")+ closedByProxy(t, h.dialAs("hog"))+ if res := do(t, h, testCaller); res.StatusCode != 200 || hits.Load() != 1 {+ t.Fatalf("another caller: %d", res.StatusCode)+ }+ a.Close()+ for deadline := time.Now().Add(3 * time.Second); ; { // the proxy sees the close in its own time+ c := h.dialAs("hog")+ c.Write([]byte("GET / HTTP/1.1\r\nHost: x\r\n\r\n"))+ c.SetReadDeadline(time.Now().Add(3 * time.Second))+ if n, _ := c.Read(make([]byte, 12)); n == 12 {+ return+ }+ c.Close()+ if time.Now().After(deadline) {+ t.Fatal("a closed connection did not free its place")+ }+ time.Sleep(10 * time.Millisecond)+ }+}++// Headers past maxHeaderBytes are refused before the request is admitted.+func TestHeaderLimit(t *testing.T) {+ var hits atomic.Int64+ h := newHarness(t, recordingUpstream(&hits, nil), harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ req := h.messagesReq(t.Context())+ req.Header.Set("X-Pad", strings.Repeat("a", 2*maxHeaderBytes))+ res, err := h.client(testCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ res.Body.Close()+ if res.StatusCode != http.StatusRequestHeaderFieldsTooLarge || hits.Load() != 0 {+ t.Fatalf("%d, upstream hits %d", res.StatusCode, hits.Load())+ }+}diff --git a/computer/modelproxy/control.go b/computer/modelproxy/control.gonew file mode 100644index 00000000..a5d4c184--- /dev/null+++ b/computer/modelproxy/control.go@@ -0,0 +1,283 @@+// The control socket: the binder's one connection to the proxy. JSON lines+// both ways (frames.go). The proxy speaks first (`hello` with its profiles+// and the bindings it holds), the binder re-sends every live bind and then+// `synced`.+//+// Invariants:+// - At most one control connection is live; a new one replaces the old.+// - Sending never blocks: messages go through a bounded queue and are+// dropped (counted, reported in model.pool) when it is full or no binder+// is connected.+// Lifecycle events from before the first connection are kept (a few) and+// sent after `hello`.+// - A failed accept is retried with a backoff; only closing the listener+// ends Serve.+// - A line that carries variables (`bind`, `request`) is never logged.+package main++import (+ "bufio"+ "context"+ "encoding/json"+ "errors"+ "net"+ "sync"+ "sync/atomic"+ "time"+)++const (+ controlQueue = 8192+ maxPending = 32+ maxControlLine = 1 << 20+ writeTimeout = 5 * time.Second+ requestTimeout = 15 * time.Second // a binder's `request` (request.go)+ maxRequests = 16 // such requests in flight; past it: error "busy"+ acceptBackoff = time.Second // the longest wait between failed accepts+)++type Control struct {+ version string+ placeholder string+ bindings *Bindings+ profiles *profiles++ mu sync.Mutex+ cur *ctrlConn+ pending [][]byte+ closed bool+ dropped atomic.Int64+ wg sync.WaitGroup+ reqs chan struct{} // maxRequests slots+ now func() time.Time+}++type ctrlConn struct {+ c net.Conn+ out chan []byte+ done chan struct{}+ once sync.Once+ helloAt time.Time+}++func (cc *ctrlConn) close() {+ cc.once.Do(func() {+ close(cc.done)+ cc.c.Close()+ })+}++func NewControl(version, placeholder string, ps *profiles) *Control {+ return &Control{version: version, placeholder: placeholder, profiles: ps, now: time.Now, reqs: make(chan struct{}, maxRequests)}+}++// hello is the first line of a connection (frames.go).+func (c *Control) hello(bindings []bindingInfo) helloMsg {+ h := helloMsg{T: "hello", Version: c.version, Protocol: controlProtocol, Placeholder: c.placeholder,+ Profiles: make([]helloProfile, 0, len(c.profiles.sorted)), Bindings: bindings}+ for _, p := range c.profiles.sorted {+ h.Profiles = append(h.Profiles, helloProfile{Name: p.name, Vars: p.vars, Harness: p.harness})+ }+ return h+}++// send queues v for the binder; dropped when there is none or the queue is full.+func (c *Control) send(v any) {+ b, err := json.Marshal(v)+ if err != nil {+ return+ }+ b = append(b, '\n')+ c.mu.Lock()+ cur := c.cur+ c.mu.Unlock()+ if cur == nil {+ c.dropped.Add(1)+ return+ }+ select {+ case cur.out <- b:+ default:+ c.dropped.Add(1)+ }+}++// reply answers a `request` on the connection that asked: a binder that has+// reconnected since never gets an answer to an id it did not send.+func (c *Control) reply(cc *ctrlConn, v any) {+ b, err := json.Marshal(v)+ if err != nil {+ return+ }+ select {+ case cc.out <- append(b, '\n'):+ default:+ c.dropped.Add(1)+ }+}++// sendKept is send, but kept for the first binder when none is connected yet.+func (c *Control) sendKept(v any) {+ c.mu.Lock()+ if c.cur == nil && !c.closed {+ if len(c.pending) < maxPending {+ b, err := json.Marshal(v)+ if err == nil {+ c.pending = append(c.pending, append(b, '\n'))+ }+ }+ c.mu.Unlock()+ return+ }+ c.mu.Unlock()+ c.send(v)+}++// Dropped is how many messages never reached a binder.+func (c *Control) Dropped() int64 { return c.dropped.Load() }++// Serve accepts control connections until l is closed.+func (c *Control) Serve(l net.Listener) {+ var wait time.Duration+ for {+ conn, err := l.Accept()+ if errors.Is(err, net.ErrClosed) {+ return+ }+ if err != nil {+ wait = min(max(2*wait, 5*time.Millisecond), acceptBackoff)+ logWarn("control accept failed; retrying", "error", err.Error(), "wait_ms", ms(wait))+ time.Sleep(wait)+ continue+ }+ wait = 0+ c.wg.Add(1)+ go func() {+ defer c.wg.Done()+ c.handle(conn)+ }()+ }+}++func (c *Control) handle(conn net.Conn) {+ cc := &ctrlConn{c: conn, out: make(chan []byte, controlQueue), done: make(chan struct{}), helloAt: c.now()}+ snap := c.bindings.Snapshot()+ hb, _ := json.Marshal(c.hello(snap))+ cc.out <- append(hb, '\n')++ c.mu.Lock()+ if c.closed {+ c.mu.Unlock()+ conn.Close()+ return+ }+ for _, p := range c.pending {+ cc.out <- p+ }+ c.pending = nil+ old := c.cur+ c.cur = cc+ c.mu.Unlock()+ if old != nil {+ logInfo("control connection replaced")+ old.close()+ }+ logInfo("control connected", "bindings", len(snap))++ go c.writer(cc)+ c.reader(cc)++ cc.close()+ c.mu.Lock()+ if c.cur == cc {+ c.cur = nil+ }+ c.mu.Unlock()+ logInfo("control disconnected")+}++func (c *Control) writer(cc *ctrlConn) {+ w := bufio.NewWriterSize(cc.c, 64<<10)+ for {+ select {+ case b := <-cc.out:+ cc.c.SetWriteDeadline(c.now().Add(writeTimeout))+ if _, err := w.Write(b); err != nil {+ cc.close()+ return+ }+ if len(cc.out) == 0 {+ if err := w.Flush(); err != nil {+ cc.close()+ return+ }+ }+ case <-cc.done:+ return+ }+ }+}++func (c *Control) reader(cc *ctrlConn) {+ sc := bufio.NewScanner(cc.c)+ sc.Buffer(make([]byte, 64<<10), maxControlLine)+ for sc.Scan() {+ line := sc.Bytes()+ var head inHead+ if err := json.Unmarshal(line, &head); err != nil {+ logWarn("control: unparsable line")+ continue+ }+ switch head.T {+ case "bind":+ var m bindMsg+ if json.Unmarshal(line, &m) != nil {+ c.reply(cc, refusedMsg{T: "refused", Code: refuseBadFrame, Message: "bind is not a JSON object of the documented shape"})+ continue+ }+ c.bindings.Bind(m)+ case "release":+ var m releaseMsg+ if json.Unmarshal(line, &m) == nil {+ c.bindings.Release(m.Caller)+ }+ case "synced":+ waiting := c.bindings.Synced()+ logInfo("synced", "bindings", c.bindings.Len(), "waiting", waiting, "since_hello_ms", ms(c.now().Sub(cc.helloAt)))+ case "request":+ var m requestMsg+ if json.Unmarshal(line, &m) != nil {+ continue+ }+ select {+ case c.reqs <- struct{}{}:+ default:+ c.reply(cc, responseMsg{T: "response", ID: m.ID, Error: responseBusy})+ continue+ }+ c.wg.Add(1)+ go func() {+ defer c.wg.Done()+ defer func() { <-c.reqs }()+ ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)+ defer cancel()+ r := c.profiles.request(ctx, m)+ r.T, r.ID = "response", m.ID+ c.reply(cc, r)+ }()+ }+ }+}++// Close drops the binder's connection (so it reconnects to the next instance at+// once) and refuses new ones.+func (c *Control) Close() {+ c.mu.Lock()+ c.closed = true+ cur := c.cur+ c.cur = nil+ c.mu.Unlock()+ if cur != nil {+ cur.close()+ }+}diff --git a/computer/modelproxy/control_test.go b/computer/modelproxy/control_test.gonew file mode 100644index 00000000..ad4c64b1--- /dev/null+++ b/computer/modelproxy/control_test.go@@ -0,0 +1,394 @@+package main++import (+ "bufio"+ "context"+ "errors"+ "io"+ "net"+ "net/http"+ "os"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++func do(t *testing.T, h *harness, caller string) *http.Response {+ t.Helper()+ res, err := h.client(caller).Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { res.Body.Close() })+ return res+}++func okUpstream() (http.Handler, *atomic.Int64) {+ var hits atomic.Int64+ return recordingUpstream(&hits, make(chan seen, 1)), &hits+}++func TestHelloFirst(t *testing.T) {+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{restore: []bindingInfo{{Caller: testCaller, SessionKey: "s1", Mode: modeProfile, Profile: mainProfile, Key: "fp1"}}})+ k := h.dialControl()+ m := <-k.msgs+ if m["t"] != "hello" || m["version"] == nil {+ t.Fatalf("first line %v", m)+ }+ if m["protocol"] != float64(controlProtocol) || m["placeholder"] != testPlaceholder {+ t.Fatalf("hello %v", m)+ }+ if toJSON(m["bindings"]) != `[{"caller":"abc123","key":"fp1","mode":"profile","profile":"claude-oauth","sessionKey":"s1"}]` {+ t.Fatalf("hello bindings %v", m["bindings"])+ }+ // The profiles by name, each with the variables a bind must give and+ // its `harness` as written.+ ps := m["profiles"].([]any)+ var names []string+ for _, p := range ps {+ names = append(names, p.(map[string]any)["name"].(string))+ }+ if toJSON(names) != `["alt","anthropic-key","claude-oauth","openai-key","openrouter"]` {+ t.Fatalf("hello profiles %v", names)+ }+ if toJSON(ps[0]) != `{"harness":{"codex":{"cache":"1h"}},"name":"alt","vars":["accountId","token"]}` ||+ toJSON(ps[2]) != `{"harness":{"claude":{"tokenEnv":"CLAUDE_CODE_OAUTH_TOKEN"}},"name":"claude-oauth","vars":["token"]}` {+ t.Fatalf("hello profiles %v", ps)+ }+ // model.proxy_started, sent before any binder connected, is kept for the first.+ ev := k.waitFor(isEvent("model.proxy_started"))+ if ev["data"].(map[string]any)["bindings"] != float64(1) {+ t.Fatalf("event %v", ev)+ }+}++func TestBindStateMachine(t *testing.T) {+ up, hits := okUpstream()+ h := newHarness(t, up, harnessOpts{hold: 300 * time.Millisecond})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ if res := do(t, h, testCaller); res.StatusCode != 200 {+ t.Fatalf("bound: %d", res.StatusCode)+ }+ bindingEvent := func(action string) map[string]any {+ t.Helper()+ ev := k.waitFor(func(m map[string]any) bool {+ return m["name"] == "model.binding" && m["data"].(map[string]any)["action"] == action+ })+ d := ev["data"].(map[string]any)+ if d["caller"] != testCaller || d["token"] != nil || ev["session_key"] == nil {+ t.Fatalf("binding event %v", ev)+ }+ return d+ }+ if d := bindingEvent("bind"); d["key"] != "fp1" || d["mode"] != "profile" {+ t.Fatalf("bind event %v", d)+ }++ // The same bind again changes nothing: `bound`, no event.+ k.send(map[string]any{"t": "bind", "id": "again", "caller": testCaller, "sessionKey": "s1", "profile": mainProfile, "vars": map[string]string{"token": "tok"}, "key": "fp1"})+ if m := k.waitFor(func(m map[string]any) bool { return m["t"] == "bound" || m["name"] == "model.binding" }); m["t"] != "bound" || m["id"] != "again" {+ t.Fatalf("the same bind again: %v", m)+ }++ // Another session for the same caller: refused, the binding stays.+ k.send(map[string]any{"t": "bind", "id": "b2", "caller": testCaller, "sessionKey": "s2", "profile": mainProfile, "vars": map[string]string{"token": "tok2"}, "key": "fp2"})+ m := k.waitFor(isT("refused"))+ if m["caller"] != testCaller || m["id"] != "b2" || m["code"] != refuseCallerInUse || m["message"] == "" {+ t.Fatalf("refused %v", m)+ }+ bindingEvent("refused")+ if res := do(t, h, testCaller); res.StatusCode != 200 {+ t.Fatalf("after refused bind: %d", res.StatusCode)+ }+ // Malformed binds are refused too, each with its code.+ tok := map[string]string{"token": "x"}+ for _, c := range []struct {+ code string+ bad map[string]any+ }{+ {refuseBadFrame, map[string]any{"caller": "sp-runner-x.service/y", "sessionKey": "s3", "profile": mainProfile, "vars": tok, "key": "k"}},+ {refuseBadFrame, map[string]any{"caller": "x", "profile": mainProfile, "vars": tok, "key": "k"}},+ {refuseBadFrame, map[string]any{"caller": "x", "sessionKey": "s3", "profile": mainProfile, "mode": "other", "vars": tok, "key": "k"}},+ {refuseBadFrame, map[string]any{"caller": "x", "sessionKey": "s3", "profile": mainProfile, "vars": "token", "key": "k"}},+ {refuseMissingVar, map[string]any{"caller": "x", "sessionKey": "s3", "profile": mainProfile, "key": "k"}},+ {refuseMissingVar, map[string]any{"caller": "x", "sessionKey": "s3", "profile": mainProfile, "vars": map[string]string{"token": "x\r\ny: z"}, "key": "k"}},+ {refuseUnknownProfile, map[string]any{"caller": "x", "sessionKey": "s3", "profile": "nope", "vars": tok, "key": "k"}},+ {refuseUnknownProfile, map[string]any{"caller": "x", "sessionKey": "s3", "vars": tok, "key": "k"}},+ {refuseBadKey, map[string]any{"caller": "x", "sessionKey": "s3", "profile": mainProfile, "vars": tok}},+ {refuseBadKey, map[string]any{"caller": "x", "sessionKey": "s3", "profile": mainProfile, "vars": tok, "key": "a key"}},+ } {+ c.bad["t"] = "bind"+ k.send(c.bad)+ if m := k.waitFor(isT("refused")); m["code"] != c.code || m["message"] == "" || strings.Contains(toJSON(m), "y: z") {+ t.Fatalf("refused %v, want %q for %v", m, c.code, c.bad)+ }+ }++ // Unknown t values and fields are ignored.+ k.send(map[string]any{"t": "future", "x": 1})++ // Mode refuse: 401 with the reason, upstream untouched.+ before := hits.Load()+ k.send(map[string]any{"t": "bind", "caller": testCaller, "sessionKey": "s1", "mode": "refuse", "reason": "paused by its owner"})+ k.waitFor(func(m map[string]any) bool { return m["t"] == "bound" && m["key"] == nil })+ res := do(t, h, testCaller)+ if res.StatusCode != 401 {+ t.Fatalf("refuse: %d", res.StatusCode)+ }+ if e := decodeAPIError(t, res); e.Error.Type != "authentication_error" || !strings.Contains(e.Error.Message, "paused by its owner") {+ t.Fatalf("refuse error %+v", e)+ }+ if ev := k.waitFor(isEvent("model.denied")); ev["data"].(map[string]any)["reason"] != "refused" {+ t.Fatalf("event %v", ev)+ }+ if hits.Load() != before {+ t.Fatal("refuse reached upstream")+ }++ // Release: the caller is unknown again; held, then 401, since the+ // binder has said it sent every bind.+ k.send(map[string]any{"t": "synced"})+ k.send(map[string]any{"t": "release", "caller": testCaller})+ if d := bindingEvent("release"); d["mode"] != "refuse" {+ t.Fatalf("release event %v", d)+ }+ start := time.Now()+ res = do(t, h, testCaller)+ if res.StatusCode != 401 || time.Since(start) < 250*time.Millisecond {+ t.Fatalf("released: %d after %v", res.StatusCode, time.Since(start))+ }+ ev := k.waitFor(isEvent("model.held"))+ if ev["outcome"] != "timed_out" || ev["data"].(map[string]any)["released"] != "timeout" {+ t.Fatalf("held event %v", ev)+ }+ // After release the caller may serve a new session.+ h.bindReady(k, testCaller, "s9", "tok9", "fp9")+}++func TestHoldThenServeWhenBindArrivesLate(t *testing.T) {+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{hold: 3 * time.Second})+ k := h.dialControl()+ go func() {+ time.Sleep(200 * time.Millisecond)+ k.bind(testCaller, "s1", "tok", "fp1")+ }()+ start := time.Now()+ res := do(t, h, testCaller)+ if res.StatusCode != 200 || time.Since(start) < 150*time.Millisecond {+ t.Fatalf("status %d after %v", res.StatusCode, time.Since(start))+ }+ ev := k.waitFor(isEvent("model.held"))+ d := ev["data"].(map[string]any)+ if d["released"] != "bound" || d["held_ms"].(float64) < 150 || ev["session_key"] != "s1" {+ t.Fatalf("held event %v", ev)+ }+}++func TestHoldTimeout503ForKnownCaller(t *testing.T) {+ up, hits := okUpstream()+ h := newHarness(t, up, harnessOpts{hold: 300 * time.Millisecond,+ restore: []bindingInfo{{Caller: testCaller, SessionKey: "s1", Mode: modeProfile, Profile: mainProfile, Key: "fp1"}}})+ res := do(t, h, testCaller)+ if res.StatusCode != 503 || res.Header.Get("Retry-After") != "1" {+ t.Fatalf("status %d retry-after %q", res.StatusCode, res.Header.Get("Retry-After"))+ }+ if e := decodeAPIError(t, res); e.Error.Type != "api_error" {+ t.Fatalf("error %+v", e)+ }+ if hits.Load() != 0 {+ t.Fatal("upstream contacted")+ }+}++// After a restart: persisted callers are held; `synced` does not end the hold+// or drop them; a bind after `synced` still serves the held request; a caller+// never re-bound gets 503 at the cap.+func TestPersistedBindingsAndSynced(t *testing.T) {+ const other = "other"+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{hold: 1500 * time.Millisecond, restore: []bindingInfo{+ {Caller: testCaller, SessionKey: "s1", Mode: modeProfile, Profile: mainProfile, Key: "fp1"},+ {Caller: other, SessionKey: "s2", Mode: modeProfile, Profile: mainProfile, Key: "fp2"},+ }})+ k := h.dialControl()+ k.waitFor(isT("hello"))++ type result struct {+ status int+ took time.Duration+ }+ run := func(caller string) chan result {+ ch := make(chan result, 1)+ go func() {+ start := time.Now()+ res, err := h.client(caller).Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Error(err)+ ch <- result{}+ return+ }+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ ch <- result{res.StatusCode, time.Since(start)}+ }()+ return ch+ }+ a, b := run(testCaller), run(other)+ time.Sleep(100 * time.Millisecond)+ k.send(map[string]any{"t": "synced"})+ time.Sleep(200 * time.Millisecond)+ k.bind(testCaller, "s1", "tok", "fp1")+ ra, rb := <-a, <-b+ if ra.status != 200 || ra.took < 250*time.Millisecond {+ t.Fatalf("re-bound caller: %+v", ra)+ }+ if rb.status != 503 || rb.took < 1400*time.Millisecond {+ t.Fatalf("never re-bound caller: %+v", rb)+ }+ // Still known: only `release` removes it.+ if h.srv.bindings.Len() != 2 {+ t.Fatalf("bindings %d", h.srv.bindings.Len())+ }++ // The file has the bindings and never a variable.+ h.srv.persist.flush()+ raw, err := os.ReadFile(h.srv.cfg.bindingsFile)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(raw), "tok") || !strings.Contains(string(raw), testCaller) {+ t.Fatalf("bindings file %s", raw)+ }+ st, _ := os.Stat(h.srv.cfg.bindingsFile)+ if st.Mode().Perm() != 0o600 {+ t.Fatalf("mode %v", st.Mode())+ }+}++// The binder restarting (control connection closed) keeps every binding and+// variable; serving continues; the next `hello` lists them.+func TestControlDisconnectKeepsBindings(t *testing.T) {+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{hold: 300 * time.Millisecond})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ k.c.Close()+ time.Sleep(50 * time.Millisecond)+ if res := do(t, h, testCaller); res.StatusCode != 200 {+ t.Fatalf("after the binder disconnected: %d", res.StatusCode)+ }+ k2 := h.dialControl()+ m := k2.waitFor(isT("hello"))+ bs := m["bindings"].([]any)+ if len(bs) != 1 || bs[0].(map[string]any)["key"] != "fp1" {+ t.Fatalf("hello %v", m)+ }+}++// A new control connection replaces the old one.+func TestControlReplaced(t *testing.T) {+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{})+ k1 := h.dialControl()+ k1.waitFor(isT("hello"))+ k2 := h.dialControl()+ k2.waitFor(isT("hello"))+ select {+ case _, ok := <-k1.msgs:+ for ok {+ _, ok = <-k1.msgs+ }+ case <-time.After(2 * time.Second):+ t.Fatal("old connection not closed")+ }+ h.bindReady(k2, testCaller, "s1", "tok", "fp1")+}++// Until the binder says `synced`, a caller without a binding may be one whose+// bind is on its way: 503, retryable. After it, such a caller is unknown: 401.+func TestUnboundBeforeAndAfterSynced(t *testing.T) {+ up, hits := okUpstream()+ h := newHarness(t, up, harnessOpts{hold: 50 * time.Millisecond})+ k := h.dialControl()+ k.waitFor(isT("hello"))+ res := do(t, h, testCaller)+ if e := decodeAPIError(t, res); res.StatusCode != 503 || res.Header.Get("Retry-After") != "1" || e.Error.Type != "api_error" {+ t.Fatalf("before synced: %d %+v", res.StatusCode, e)+ }+ k.send(map[string]any{"t": "synced"})+ k.send(map[string]any{"t": "release", "caller": "nobody"}) // processed after synced+ h.bindReady(k, altCaller, "s2", "tok", "fp2")+ res = do(t, h, testCaller)+ if e := decodeAPIError(t, res); res.StatusCode != 401 || e.Error.Type != "authentication_error" {+ t.Fatalf("after synced: %d %+v", res.StatusCode, e)+ }+ if ev := k.waitFor(isEvent("model.denied")); evData(ev)["reason"] != "unbound" {+ t.Fatalf("event %v", ev)+ }+ if hits.Load() != 0 {+ t.Fatal("upstream contacted")+ }+}++// A binder that connects again gets every binding in its `hello`, and the+// callers kept serving meanwhile.+func TestReconnectingBinderGetsBindings(t *testing.T) {+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ k.c.Close()+ if res := do(t, h, testCaller); res.StatusCode != 200 {+ t.Fatalf("without a binder: %d", res.StatusCode)+ }+ m := h.dialControl().waitFor(isT("hello"))+ if toJSON(m["bindings"]) != `[{"caller":"abc123","key":"fp1","mode":"profile","profile":"claude-oauth","sessionKey":"s1"}]` {+ t.Fatalf("hello bindings %v", m["bindings"])+ }+}++// flakyListener fails its first accepts.+type flakyListener struct {+ net.Listener+ fails atomic.Int64+}++func (l *flakyListener) Accept() (net.Conn, error) {+ if l.fails.Add(-1) >= 0 {+ return nil, errors.New("accept: too many open files")+ }+ return l.Listener.Accept()+}++// A failed accept does not end the control socket.+func TestControlAcceptRetried(t *testing.T) {+ ps, err := loadProfiles("profiles")+ if err != nil {+ t.Fatal(err)+ }+ l, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ fl := &flakyListener{Listener: l}+ fl.fails.Store(3)+ c := NewControl("test", testPlaceholder, ps)+ c.bindings = NewBindings(ps, c, nil)+ go c.Serve(fl)+ defer c.Close()+ defer l.Close()+ conn, err := net.Dial("tcp", l.Addr().String())+ if err != nil {+ t.Fatal(err)+ }+ defer conn.Close()+ conn.SetReadDeadline(time.Now().Add(5 * time.Second))+ line, err := bufio.NewReader(conn).ReadString('\n')+ if err != nil || !strings.Contains(line, `"t":"hello"`) {+ t.Fatalf("after failed accepts: %q %v", line, err)+ }+}diff --git a/computer/modelproxy/frames.go b/computer/modelproxy/frames.gonew file mode 100644index 00000000..48f28d50--- /dev/null+++ b/computer/modelproxy/frames.go@@ -0,0 +1,170 @@+// The binder ↔ proxy wire contract: JSON lines on the control socket, every+// frame type in the order of its golden example in testdata/control/. The+// binder is whoever holds the control socket: on a computer, the host.+//+// binder → proxy bind, release, synced, request+// proxy → binder hello, bound, refused, observed, response, event+//+// Invariants: unknown `t` values and unknown fields are ignored; nothing+// here carries a binding's variables proxy → binder; every binder → proxy+// frame is an idempotent operation on a named thing (put a binding, delete a+// binding, make a request).+package main++import "time"++// controlProtocol is `hello.protocol`: it changes when a frame's meaning does.+const controlProtocol = 1++// inHead: `t` is read first, then the line is decoded into the frame's own+// struct; `synced` has no fields.+type inHead struct {+ T string `json:"t"`+}++// helloMsg is the proxy's first line on a control connection: what it+// serves, and the bindings it holds, so the binder re-sends their binds.+type helloMsg struct {+ T string `json:"t"`+ Version string `json:"version"`+ Protocol int `json:"protocol"`+ Placeholder string `json:"placeholder"`+ Profiles []helloProfile `json:"profiles"`+ Bindings []bindingInfo `json:"bindings"`+}++// helloProfile: Vars are the names a bind to it must give; Harness is the+// profile's `harness` object as written (the proxy does not read it).+type helloProfile struct {+ Name string `json:"name"`+ Vars []string `json:"vars"`+ Harness map[string]any `json:"harness"`+}++// bindingInfo is a binding without its variables: as listed in `hello` and+// as written to the bindings file (persist.go).+type bindingInfo struct {+ Caller string `json:"caller"`+ SessionKey string `json:"sessionKey"`+ Mode string `json:"mode"` // profile | refuse+ Profile string `json:"profile,omitempty"`+ Key string `json:"key,omitempty"`+}++// bindMsg puts a binding: the caller's requests go to Profile with Vars, or+// (Mode "refuse") are answered 401 with Reason. ID, if set, is echoed on the+// answer.+type bindMsg struct {+ ID string `json:"id,omitempty"`+ Caller string `json:"caller"`+ SessionKey string `json:"sessionKey"`+ Profile string `json:"profile,omitempty"`+ Vars map[string]string `json:"vars,omitempty"`+ Key string `json:"key,omitempty"`+ Mode string `json:"mode,omitempty"` // "refuse", or absent+ Reason string `json:"reason,omitempty"`+}++// boundMsg: the bind is in effect for the caller's next request.+type boundMsg struct {+ T string `json:"t"`+ ID string `json:"id,omitempty"`+ Caller string `json:"caller"`+ SessionKey string `json:"sessionKey"`+ Key string `json:"key,omitempty"`+}++// refusedMsg: the bind was not applied. Code is one of the refuse* constants.+type refusedMsg struct {+ T string `json:"t"`+ ID string `json:"id,omitempty"`+ Caller string `json:"caller"`+ Code string `json:"code"`+ Message string `json:"message"`+}++const (+ refuseUnknownProfile = "unknown_profile"+ refuseMissingVar = "missing_var"+ refuseBadKey = "bad_key"+ refuseCallerInUse = "caller_in_use"+ refuseBadFrame = "bad_frame"+)++// releaseMsg deletes a binding; an unknown caller is not an error.+type releaseMsg struct {+ Caller string `json:"caller"`+}++// requestMsg asks the proxy to make one request on a profile with the given+// variables, which are not stored (request.go); responseMsg is its answer.+type requestMsg struct {+ ID string `json:"id"`+ Profile string `json:"profile"`+ Vars map[string]string `json:"vars,omitempty"`+ Method string `json:"method"`+ Path string `json:"path"`+ Query string `json:"query,omitempty"`+ Headers map[string]string `json:"headers,omitempty"`+ Body string `json:"body,omitempty"`+}++// responseMsg: Error, when set, is one of the response* constants.+type responseMsg struct {+ T string `json:"t"`+ ID string `json:"id"`+ Status int `json:"status,omitempty"`+ Headers map[string]string `json:"headers,omitempty"`+ Body string `json:"body,omitempty"`+ Error string `json:"error,omitempty"`+}++const (+ responseUnknownProfile = "unknown_profile"+ responseUnknownRoute = "unknown_route"+ responseMissingVar = "missing_var"+ responseBadRequest = "bad_request"+ responseBusy = "busy"+ responseTimeout = "timeout"+ responseUnreachable = "unreachable"+)++// observedMsg is what an upstream answered a credential (observed.go): the+// status, the response headers the profile's `report` names (names in lower+// case, repeated values joined with ", "), the start of an error's body, or+// the class of a transport error. What it means is the binder's to decide.+type observedMsg struct {+ T string `json:"t"`+ SessionKey string `json:"sessionKey"`+ Caller string `json:"caller"`+ Key string `json:"key"`+ Profile string `json:"profile"`+ Status int `json:"status,omitempty"`+ Headers map[string]string `json:"headers,omitempty"`+ Body string `json:"body,omitempty"`+ Error string `json:"error,omitempty"`+}++// eventMsg is a telemetry event for the binder to relay (README.md lists+// every one with its `data`; testdata/control/event-*.json has an example of+// each). `data` values are scalars; never variables, placeholders, bodies or+// upstream text. Profile is the request's or binding's, once it is known.+type eventMsg struct {+ T string `json:"t"`+ Name string `json:"name"`+ At int64 `json:"at"`+ Outcome string `json:"outcome,omitempty"`+ DurationMs *float64 `json:"duration_ms,omitempty"`+ ErrorType string `json:"error_type,omitempty"`+ SessionKey string `json:"session_key,omitempty"`+ Profile string `json:"profile,omitempty"`+ Data map[string]any `json:"data,omitempty"`+}++func newEvent(at time.Time, name string) eventMsg {+ return eventMsg{T: "event", Name: name, At: at.UnixMilli()}+}++func ms(d time.Duration) float64 { return float64(d.Microseconds()) / 1000 }++func msPtr(d time.Duration) *float64 { v := ms(d); return &v }diff --git a/computer/modelproxy/frames_test.go b/computer/modelproxy/frames_test.gonew file mode 100644index 00000000..d7f10b4f--- /dev/null+++ b/computer/modelproxy/frames_test.go@@ -0,0 +1,191 @@+package main++import (+ "context"+ "encoding/json"+ "io"+ "os"+ "path/filepath"+ "reflect"+ "slices"+ "testing"+ "time"+)++// The golden files in testdata/control are one JSON object per message type,+// exactly as it goes over the control socket (minus the newline), so a+// binder's test can read the same files. Binder → proxy files must decode+// into the frame's struct and encode back to the same object; proxy → binder+// files must equal what the proxy's structs encode to.++func golden(t *testing.T, name string) []byte {+ t.Helper()+ b, err := os.ReadFile(filepath.Join("testdata", "control", name+".json"))+ if err != nil {+ t.Fatal(err)+ }+ return b+}++func canon(t *testing.T, b []byte) any {+ t.Helper()+ var v any+ if err := json.Unmarshal(b, &v); err != nil {+ t.Fatalf("%s: %v", b, err)+ }+ return v+}++func sameJSON(t *testing.T, name string, got any) {+ t.Helper()+ b, err := json.Marshal(got)+ if err != nil {+ t.Fatal(err)+ }+ if want := golden(t, name); !reflect.DeepEqual(canon(t, b), canon(t, want)) {+ t.Fatalf("%s.json:\n got %s\nwant %s", name, b, want)+ }+}++func f64(v float64) *float64 { return &v }+func decode(t *testing.T, name string, into any) {+ t.Helper()+ if err := json.Unmarshal(golden(t, name), into); err != nil {+ t.Fatalf("%s: %v", name, err)+ }+}++func TestGoldenBinderToProxy(t *testing.T) {+ const caller, session = "abc123", "T0/C0/1700000000.000100"+ for name, want := range map[string]string{"bind": "bind", "bind-refuse": "bind", "release": "release", "request": "request", "synced": "synced"} {+ var head inHead+ decode(t, name, &head)+ if head.T != want {+ t.Fatalf("%s: t = %q", name, head.T)+ }+ }+ var b bindMsg+ decode(t, "bind", &b)+ if want := (bindMsg{ID: "b1", Caller: caller, SessionKey: session, Profile: "openai-key", Vars: map[string]string{"token": "sk-example"}, Key: "k1"}); !reflect.DeepEqual(b, want) {+ t.Fatalf("bind %+v", b)+ }+ sameJSON(t, "bind", struct {+ T string `json:"t"`+ bindMsg+ }{"bind", b})++ var br bindMsg+ decode(t, "bind-refuse", &br)+ if want := (bindMsg{Caller: caller, SessionKey: session, Mode: "refuse", Reason: "paused by its owner"}); !reflect.DeepEqual(br, want) {+ t.Fatalf("bind refuse %+v", br)+ }+ sameJSON(t, "bind-refuse", struct {+ T string `json:"t"`+ bindMsg+ }{"bind", br})++ var r releaseMsg+ decode(t, "release", &r)+ if r != (releaseMsg{Caller: caller}) {+ t.Fatalf("release %+v", r)+ }+ sameJSON(t, "release", struct {+ T string `json:"t"`+ releaseMsg+ }{"release", r})++ var q requestMsg+ decode(t, "request", &q)+ if want := (requestMsg{ID: "3f0e2a1c-5b7d-4e8f-9a0b-1c2d3e4f5a6b", Profile: "openai-key", Vars: map[string]string{"token": "sk-example"},+ Method: "GET", Path: "/v1/models", Query: "limit=1", Headers: map[string]string{"Accept": "application/json"}}); !reflect.DeepEqual(q, want) {+ t.Fatalf("request %+v", q)+ }+ sameJSON(t, "request", struct {+ T string `json:"t"`+ requestMsg+ }{"request", q})+}++func TestGoldenProxyToBinder(t *testing.T) {+ const caller, session, id = "abc123", "T0/C0/1700000000.000100", "3f0e2a1c-5b7d-4e8f-9a0b-1c2d3e4f5a6b"+ ps, err := compileProfiles(map[string]profileJSON{+ "openai-key": {Upstream: "https://api.example.com", Routes: map[string]routeJSON{"GET /v1/models": {}},+ Set: map[string]string{"Authorization": "Bearer {token}"}, Harness: map[string]any{"codex": map[string]any{}}},+ "plain": {Upstream: "https://api.example.com", Routes: map[string]routeJSON{"GET /v1/models": {}}},+ })+ if err != nil {+ t.Fatal(err)+ }+ c := NewControl("3b8618e", testPlaceholder, ps)+ sameJSON(t, "hello", c.hello([]bindingInfo{+ {Caller: caller, SessionKey: session, Mode: modeProfile, Profile: "openai-key", Key: "k1"},+ {Caller: "def456", SessionKey: "T0/C0/1700000000.000200", Mode: modeRefuse},+ }))+ sameJSON(t, "bound", boundMsg{T: "bound", ID: "b1", Caller: caller, SessionKey: session, Key: "k1"})+ sameJSON(t, "refused", refusedMsg{T: "refused", ID: "b1", Caller: caller, Code: refuseCallerInUse, Message: "the caller is bound to another session"})+ sameJSON(t, "observed", observedMsg{T: "observed", SessionKey: session, Caller: caller, Key: "k1", Profile: "openai-key", Status: 429,+ Headers: map[string]string{"retry-after": "30"}, Body: `{"error":{"type":"rate_limit_exceeded"}}`})+ sameJSON(t, "observed-error", observedMsg{T: "observed", SessionKey: session, Caller: caller, Key: "k1", Profile: "openai-key", Error: "connect"})+ sameJSON(t, "response", responseMsg{T: "response", ID: id, Status: 200, Headers: map[string]string{"retry-after": "30"}, Body: `{"data":[]}`})+ sameJSON(t, "response-error", responseMsg{T: "response", ID: id, Error: responseUnreachable})+}++// keysOf is a frame's field names, with its `data` object's.+func keysOf(m map[string]any) []string {+ var ks []string+ for k := range m {+ ks = append(ks, k)+ }+ if d, ok := m["data"].(map[string]any); ok {+ for k := range d {+ ks = append(ks, "data."+k)+ }+ }+ slices.Sort(ks)+ return ks+}++// Every event the proxy sends has a golden example with the same fields:+// each is taken here from a running proxy, not built by hand.+func TestGoldenEvents(t *testing.T) {+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{hold: 2 * time.Second})+ k := h.dialControl()+ go func() {+ time.Sleep(100 * time.Millisecond)+ k.bind(testCaller, "s1", "tok", "fp1")+ }()+ for range 2 { // held then served; then one on the connection it left+ res := do(t, h, testCaller)+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ }+ req := h.messagesReq(context.Background())+ req.URL.Path = "/v1/nope"+ res, err := h.client(testCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ res.Body.Close()+ h.srv.control.send(mainPool(h))++ got := map[string]map[string]any{}+ for len(got) < 6 {+ m := k.waitFor(isT("event"))+ name := m["name"].(string)+ if name == "model.request" && evData(m)["conn_reused"] != true {+ continue // the golden one found its connection in the pool+ }+ got[name] = m+ }+ for name, file := range map[string]string{"model.request": "event-request", "model.held": "event-held", "model.denied": "event-denied",+ "model.binding": "event-binding", "model.pool": "event-pool", "model.proxy_started": "event-proxy-started"} {+ want := canon(t, golden(t, file)).(map[string]any)+ if want["name"] != name {+ t.Fatalf("%s.json is a %v", file, want["name"])+ }+ if g, w := keysOf(got[name]), keysOf(want); !slices.Equal(g, w) {+ t.Errorf("%s:\n got %v\nwant %v", name, g, w)+ }+ }+}diff --git a/computer/modelproxy/go.mod b/computer/modelproxy/go.modnew file mode 100644index 00000000..b209af3b--- /dev/null+++ b/computer/modelproxy/go.mod@@ -0,0 +1,3 @@+module github.com/diggerhq/opencomputer/computer/modelproxy++go 1.27diff --git a/computer/modelproxy/helpers_test.go b/computer/modelproxy/helpers_test.gonew file mode 100644index 00000000..f5d25722--- /dev/null+++ b/computer/modelproxy/helpers_test.go@@ -0,0 +1,353 @@+package main++import (+ "bufio"+ "context"+ "crypto/x509"+ "encoding/json"+ "net"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "sync"+ "testing"+ "time"+)++const (+ testCaller = "abc123"+ testPlaceholder = "ssh-placeholder"+ placeholderAuth = "Bearer " + testPlaceholder+ wsNonce = "dGhlIHNhbXBsZSBub25jZQ==" // RFC 6455's sample nonce+)++// The profiles tests run on: the shipped defaults (profiles/default.json),+// their upstreams replaced by the fake one, plus `alt`, on a second fake+// upstream, which uses what the defaults do not: a base path, `to`,+// variables beyond the token, `remove`, `report`, `concurrency`, `errors`.+const (+ mainProfile = "claude-oauth"+ altProfile = "alt"+ altCaller = "alt001"+ altAccount = "acct-123"+ altShape = "alt: not this client's request"+ altNotReady = "alt: not ready"+)++func altProfileJSON(upstream string, limit int, ws bool) profileJSON {+ return profileJSON{+ Upstream: upstream + "/base",+ Routes: map[string]routeJSON{+ "POST /v1/responses": {To: "/x/responses", Format: "responses", Require: map[string]string{"Accept": "text/event-stream", "Content-Type": "application/json"}},+ "WS /v1/responses": {To: "/x/responses", Require: map[string]string{"X-Proto": "ws=*"}},+ "GET /v1/models": {To: "/x/models", Default: map[string]string{"Accept": "application/json"}},+ },+ Set: map[string]string{"Authorization": "Bearer {token}", "X-Account": "{accountId}", "Originator": "fixed"},+ Remove: []string{"X-Forwarded-*", "X-Real-Ip", "Cookie", "X-Private-*"},+ Report: []string{"x-quota-*", "retry-after"},+ Concurrency: &concurrencyJSON{Key: "{accountId}", Limit: limit},+ WebSocket: &ws,+ Harness: map[string]any{"codex": map[string]any{"cache": "1h"}},+ Errors: map[string]string{"require": altShape, "notReady": altNotReady},+ }+}++// harness: a proxy on a TCP listener (callers named by their dial, see+// client), a control socket, and two fake TLS upstreams.+type harness struct {+ t testing.TB+ srv *server+ upstream *httptest.Server // the default profiles'+ alt *httptest.Server // the alt profile's+ apiURL string+ ctlPath string+ dir string+ callers sync.Map // client local addr → caller+}++type harnessOpts struct {+ hold time.Duration+ restore []bindingInfo+ perCaller int // -max-inflight-per-caller; 0 = the default of 32+ conns int // -max-conns-per-caller; 0 = no limit+ alt http.Handler // the alt profile's upstream; nil = one that answers 500+ perKey int // alt's concurrency limit; 0 = 8+ noWS bool // alt's `websocket: false`+ wsIdle time.Duration // -ws-idle-timeout; 0 = never+ maxConns int // -max-conns-per-host; 0 = 256+}++func fakeUpstream(t testing.TB, h http.Handler, roots *x509.CertPool) *httptest.Server {+ up := httptest.NewUnstartedServer(h)+ up.EnableHTTP2 = false+ up.StartTLS()+ t.Cleanup(up.Close)+ roots.AddCert(up.Certificate())+ return up+}++func newHarness(t testing.TB, h http.Handler, o harnessOpts) *harness {+ t.Helper()+ roots := x509.NewCertPool()+ up := fakeUpstream(t, h, roots)+ if o.alt == nil {+ o.alt = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(500) })+ }+ alt := fakeUpstream(t, o.alt, roots)+ dir, err := os.MkdirTemp("", "mp") // short: sun_path is 108 bytes+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { os.RemoveAll(dir) })+ if o.hold == 0 {+ o.hold = 2 * time.Second+ }+ if o.perCaller == 0 {+ o.perCaller = 32+ }+ if o.maxConns == 0 {+ o.maxConns = 256+ }+ if o.perKey == 0 {+ o.perKey = 8+ }+ b, err := os.ReadFile(filepath.Join("profiles", "default.json"))+ if err != nil {+ t.Fatal(err)+ }+ raw, err := parseProfiles(b)+ if err != nil {+ t.Fatal(err)+ }+ for name, p := range raw {+ u, _ := url.Parse(p.Upstream)+ p.Upstream = up.URL + u.Path+ raw[name] = p+ }+ raw[altProfile] = altProfileJSON(alt.URL, o.perKey, !o.noWS)+ ps, err := compileProfiles(raw)+ if err != nil {+ t.Fatal(err)+ }+ cfg := config{hold: o.hold, bindingsFile: filepath.Join(dir, "bindings.json"), maxInflightPerCaller: o.perCaller, maxConnsPerCaller: o.conns, wsIdle: o.wsIdle,+ placeholder: testPlaceholder, rootCAs: roots,+ maxIdlePerHost: 128, maxConnsPerHost: o.maxConns, idleConnTimeout: time.Minute}+ if o.restore != nil {+ if err := writeBindings(cfg.bindingsFile, o.restore); err != nil {+ t.Fatal(err)+ }+ }+ hs := &harness{t: t, upstream: up, alt: alt, dir: dir, ctlPath: filepath.Join(dir, "c.sock")}+ // The proxy names a connection as it accepts it, which may be before the+ // client's dial has returned and stored its name: wait for it.+ resolve := func(c net.Conn) string {+ for range 2000 {+ if v, ok := hs.callers.Load(c.RemoteAddr().String()); ok {+ return v.(string)+ }+ time.Sleep(time.Millisecond)+ }+ return ""+ }+ srv, err := newServer(cfg, ps, resolve)+ if err != nil {+ t.Fatal(err)+ }+ hs.srv = srv+ srv.proxy.refusals.every = 0 // every refusal is an event+ apiL, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ ctlL, err := listenUnix(hs.ctlPath)+ if err != nil {+ t.Fatal(err)+ }+ hs.apiURL = "http://" + apiL.Addr().String()+ srv.start(apiL, ctlL)+ t.Cleanup(func() {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ srv.shutdown(ctx)+ })+ return hs+}++// client returns an HTTP client whose connections the proxy sees as caller.+func (h *harness) client(caller string) *http.Client {+ tr := &http.Transport{+ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {+ c, err := (&net.Dialer{}).DialContext(ctx, network, addr)+ if err == nil {+ h.callers.Store(c.LocalAddr().String(), caller)+ }+ return c, err+ },+ DisableCompression: true,+ MaxIdleConnsPerHost: 128,+ }+ h.t.Cleanup(tr.CloseIdleConnections)+ return &http.Client{Transport: tr}+}++// messagesReq is a /v1/messages request that passes claude-oauth's `require`.+func (h *harness) messagesReq(ctx context.Context) *http.Request {+ req, _ := http.NewRequestWithContext(ctx, http.MethodPost, h.apiURL+"/v1/messages?beta=true", stringsReader(`{"model":"x"}`))+ req.Host = "api.anthropic.com"+ req.Header.Set("User-Agent", "claude-cli/2.1.301 (external, sdk-cli)")+ req.Header.Set("X-App", "cli")+ req.Header.Set("Anthropic-Beta", "claude-code-20250219,interleaved-thinking-2025-05-14,oauth-2025-04-20")+ req.Header.Set("Anthropic-Version", "2023-06-01")+ req.Header.Set("Authorization", placeholderAuth)+ req.Header.Set("Content-Type", "application/json")+ return req+}++// ctl is a fake binder on the control socket.+type ctl struct {+ t testing.TB+ c net.Conn+ msgs chan map[string]any+}++func (h *harness) dialControl() *ctl {+ h.t.Helper()+ c, err := net.Dial("unix", h.ctlPath)+ if err != nil {+ h.t.Fatal(err)+ }+ h.t.Cleanup(func() { c.Close() })+ k := &ctl{t: h.t, c: c, msgs: make(chan map[string]any, 10000)}+ go func() {+ sc := bufio.NewScanner(c)+ sc.Buffer(make([]byte, 1<<16), 1<<20)+ for sc.Scan() {+ var m map[string]any+ if json.Unmarshal(sc.Bytes(), &m) == nil {+ k.msgs <- m+ }+ }+ close(k.msgs)+ }()+ return k+}++func (k *ctl) send(v any) {+ k.t.Helper()+ b, _ := json.Marshal(v)+ if _, err := k.c.Write(append(b, '\n')); err != nil {+ k.t.Fatal(err)+ }+}++// bind binds caller to the main profile.+func (k *ctl) bind(caller, session, token, key string) {+ k.send(map[string]any{"t": "bind", "caller": caller, "sessionKey": session, "profile": mainProfile, "vars": map[string]string{"token": token}, "key": key})+}++func (k *ctl) bindAlt(caller, session, token, key, account string) {+ k.send(map[string]any{"t": "bind", "caller": caller, "sessionKey": session, "profile": altProfile,+ "vars": map[string]string{"token": token, "accountId": account}, "key": key})+}++// waitFor returns the first message matching pred, failing after 3 s.+func (k *ctl) waitFor(pred func(map[string]any) bool) map[string]any {+ k.t.Helper()+ deadline := time.After(3 * time.Second)+ for {+ select {+ case m, ok := <-k.msgs:+ if !ok {+ k.t.Fatal("control connection closed")+ }+ if pred(m) {+ return m+ }+ case <-deadline:+ k.t.Fatal("timed out waiting for a control message")+ }+ }+}++func isT(t string) func(map[string]any) bool {+ return func(m map[string]any) bool { return m["t"] == t }+}++func isEvent(name string) func(map[string]any) bool {+ return func(m map[string]any) bool { return m["t"] == "event" && m["name"] == name }+}++// noMessage asserts no matching message arrives within d.+func (k *ctl) noMessage(pred func(map[string]any) bool, d time.Duration) {+ k.t.Helper()+ deadline := time.After(d)+ for {+ select {+ case m, ok := <-k.msgs:+ if !ok {+ return+ }+ if pred(m) {+ k.t.Fatalf("unexpected message %v", m)+ }+ case <-deadline:+ return+ }+ }+}++func isBound(caller, key string) func(map[string]any) bool {+ return func(m map[string]any) bool { return m["t"] == "bound" && m["caller"] == caller && m["key"] == key }+}++// bindReady binds caller and waits for `bound`.+func (h *harness) bindReady(k *ctl, caller, session, token, key string) {+ h.t.Helper()+ k.bind(caller, session, token, key)+ k.waitFor(isBound(caller, key))+}++func (h *harness) bindAltReady(k *ctl, caller, session, token, key, account string) map[string]any {+ h.t.Helper()+ k.bindAlt(caller, session, token, key, account)+ return k.waitFor(isBound(caller, key))+}++// responsesReq is a /v1/responses request that passes alt's `require`.+func (h *harness) responsesReq(ctx context.Context) *http.Request {+ req, _ := http.NewRequestWithContext(ctx, http.MethodPost, h.apiURL+"/v1/responses", stringsReader(`{"model":"m","stream":true,"input":[]}`))+ req.Header.Set("Authorization", placeholderAuth)+ req.Header.Set("User-Agent", "test-client/1.0")+ req.Header.Set("Accept", "text/event-stream")+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Session-Id", "sess-1")+ return req+}++func toJSON(v any) string {+ b, _ := json.Marshal(v)+ return string(b)+}++func evData(e map[string]any) map[string]any { return e["data"].(map[string]any) }++func isRoute(route string) func(map[string]any) bool {+ return func(m map[string]any) bool {+ d, _ := m["data"].(map[string]any)+ return isEvent("model.request")(m) && d["route"] == route+ }+}++func decodeAPIError(t *testing.T, res *http.Response) apiError {+ t.Helper()+ var e apiError+ if err := json.NewDecoder(res.Body).Decode(&e); err != nil {+ t.Fatalf("error body: %v", err)+ }+ if e.Type != "error" || e.Error.Type == "" || e.Error.Message == "" {+ t.Fatalf("not the API error shape: %+v", e)+ }+ return e+}diff --git a/computer/modelproxy/identity.go b/computer/modelproxy/identity.gonew file mode 100644index 00000000..f2893681--- /dev/null+++ b/computer/modelproxy/identity.go@@ -0,0 +1,107 @@+// Caller identity: which caller a connection on the API socket comes from.+// SO_PEERCRED gives the peer's pid; /proc/<pid>/cgroup gives its cgroup+// path, whose first `sp-runner-<id>.service` element names the caller <id>.+// The first, not the last: a process can create cgroups below its own unit+// and name them as it likes, but not above it.+//+// This is routing, not isolation: the computer is the trust boundary.+// Sessions that share a uid share a systemd user manager, and a process can+// move itself into a sibling unit's cgroup. Do not co-host mutually+// untrusted tenants on one computer.+//+// -identity=single is for a computer that runs one session outside systemd:+// every connection is the caller singleCaller, which the binder binds.+//+// Invariant: resolved once per connection, when it is accepted+// (connlimit.go), never per request; an empty caller means "not a+// session" and is refused at once.+package main++import (+ "bufio"+ "io"+ "net"+ "os"+ "path/filepath"+ "strconv"+ "strings"+)++// Resolver maps an accepted API connection to its caller ("" if none).+// Tests inject their own; a deployment uses peerResolver or singleResolver.+type Resolver func(c net.Conn) string++// callerFromCgroup reads /proc/<pid>/cgroup content. The cgroup v2 line+// ("0::/...") wins; on a hybrid host any line is accepted.+func callerFromCgroup(r io.Reader) string {+ var v2, other string+ sc := bufio.NewScanner(r)+ for sc.Scan() {+ line := sc.Text()+ parts := strings.SplitN(line, ":", 3)+ if len(parts) != 3 {+ continue+ }+ u := firstRunner(parts[2])+ if u == "" {+ continue+ }+ if parts[0] == "0" && parts[1] == "" {+ v2 = u+ } else if other == "" {+ other = u+ }+ }+ if v2 != "" {+ return v2+ }+ return other+}++// firstRunner is the caller named by the first runner unit in a cgroup path.+func firstRunner(path string) string {+ for elem := range strings.SplitSeq(path, "/") {+ if c := callerOfUnit(elem); c != "" {+ return c+ }+ }+ return ""+}++// callerOfUnit: sp-runner-<id>.service → <id>, when <id> is a caller id.+func callerOfUnit(unit string) string {+ id, ok := strings.CutPrefix(unit, "sp-runner-")+ if !ok {+ return ""+ }+ if id, ok = strings.CutSuffix(id, ".service"); !ok || !isID(id) {+ return ""+ }+ return id+}++// callerOfPid reads <procRoot>/<pid>/cgroup.+func callerOfPid(procRoot string, pid int) string {+ f, err := os.Open(filepath.Join(procRoot, strconv.Itoa(pid), "cgroup"))+ if err != nil {+ return ""+ }+ defer f.Close()+ return callerFromCgroup(f)+}++// singleCaller is every connection's caller under -identity=single.+const singleCaller = "single"++func singleResolver(net.Conn) string { return singleCaller }++// peerResolver is the cgroup Resolver: SO_PEERCRED pid → cgroup → caller.+func peerResolver(procRoot string) Resolver {+ return func(c net.Conn) string {+ pid, ok := peerPid(c)+ if !ok {+ return ""+ }+ return callerOfPid(procRoot, pid)+ }+}diff --git a/computer/modelproxy/identity_test.go b/computer/modelproxy/identity_test.gonew file mode 100644index 00000000..d625e24a--- /dev/null+++ b/computer/modelproxy/identity_test.go@@ -0,0 +1,86 @@+package main++import (+ "net"+ "os"+ "path/filepath"+ "runtime"+ "strconv"+ "strings"+ "testing"+)++func TestCallerFromCgroup(t *testing.T) {+ cases := map[string]string{+ "0::/user.slice/user-1500.slice/[email protected]/app.slice/sp-runner-abc123.service\n": "abc123",+ // a child cgroup below the unit+ "0::/user.slice/user-1500.slice/[email protected]/app.slice/sp-runner-abc123.service/tasks\n": "abc123",+ // the first matching element wins: a process can create a cgroup+ // below its own unit and name it like another, not one above it+ "0::/user.slice/[email protected]/app.slice/sp-runner-outer.service/sp-runner-inner.service\n": "outer",+ // hybrid hierarchy: the v2 line wins over v1 lines+ "12:pids:/user.slice/sp-runner-v1.service\n0::/user.slice/[email protected]/app.slice/sp-runner-v2.service\n": "v2",+ "12:pids:/user.slice/sp-runner-v1.service\n0::/user.slice\n": "v1",+ "0::/user.slice/user-1500.slice/session-3.scope\n": "",+ "0::/user.slice/[email protected]/app.slice/sp-runner-.service\n": "",+ "0::/user.slice/[email protected]/app.slice/sp-runner-a b.service\n": "",+ "0::/user.slice/[email protected]/app.slice/sp-runner-x.scope\n": "",+ "0::/user.slice/[email protected]/app.slice/oc-sp-runner-x.service\n": "",+ "garbage": "",+ "": "",+ }+ for in, want := range cases {+ if got := callerFromCgroup(strings.NewReader(in)); got != want {+ t.Errorf("%q → %q, want %q", in, got, want)+ }+ }+}++func TestCallerOfPidFromProcRoot(t *testing.T) {+ root := t.TempDir()+ os.MkdirAll(filepath.Join(root, "4242"), 0o755)+ os.WriteFile(filepath.Join(root, "4242", "cgroup"), []byte("0::/user.slice/user-1500.slice/[email protected]/app.slice/sp-runner-abc123.service\n"), 0o644)+ if u := callerOfPid(root, 4242); u != "abc123" {+ t.Fatalf("got %q", u)+ }+ if u := callerOfPid(root, 1); u != "" {+ t.Fatalf("missing pid: %q", u)+ }+}++// SO_PEERCRED on a real Unix socket names this process; the resolver then+// reads our cgroup from a fake proc root.+func TestPeerResolver(t *testing.T) {+ if runtime.GOOS != "linux" {+ t.Skip("SO_PEERCRED is Linux-only")+ }+ dir, _ := os.MkdirTemp("", "mp")+ defer os.RemoveAll(dir)+ l, err := listenUnix(filepath.Join(dir, "a.sock"))+ if err != nil {+ t.Fatal(err)+ }+ defer l.Close()+ root := t.TempDir()+ pid := os.Getpid()+ os.MkdirAll(filepath.Join(root, strconv.Itoa(pid)), 0o755)+ os.WriteFile(filepath.Join(root, strconv.Itoa(pid), "cgroup"), []byte("0::/app.slice/sp-runner-me.service\n"), 0o644)+ go func() {+ c, err := net.Dial("unix", filepath.Join(dir, "a.sock"))+ if err == nil {+ defer c.Close()+ c.Read(make([]byte, 1))+ }+ }()+ c, err := l.Accept()+ if err != nil {+ t.Fatal(err)+ }+ defer c.Close()+ if u := peerResolver(root)(c); u != "me" {+ t.Fatalf("got %q", u)+ }+ if u := peerResolver(root)(&net.TCPConn{}); u != "" {+ t.Fatalf("non-unix conn: %q", u)+ }+}diff --git a/computer/modelproxy/inflight.go b/computer/modelproxy/inflight.gonew file mode 100644index 00000000..44ba6011--- /dev/null+++ b/computer/modelproxy/inflight.go@@ -0,0 +1,66 @@+// Concurrency caps, counted between admission and the request's end (and,+// with the same counter, a caller's open connections, connlimit.go):+// - per caller (-max-inflight-per-caller, held requests included): one+// session cannot queue enough hanging requests to starve the others;+// - per profile `concurrency` key (profile.go): every caller whose binding+// expands the key alike shares it, so one upstream credential is never+// driven harder than its limit however many sessions use it. A+// WebSocket counts each response it carries, not the connection+// (websocket.go): its handshake is refused at the cap, but an idle+// tunnel holds no slot.+//+// Over either → 429 with Retry-After: 1 (proxy.go). A zero cap, or a nil+// counter (a profile without `concurrency`), is no limit.+package main++import "sync"++// inflight counts requests per key under a cap.+type inflight struct {+ limit int // 0 = none++ mu sync.Mutex+ n map[string]int+}++func newInflight(limit int) *inflight {+ return &inflight{limit: limit, n: map[string]int{}}+}++// enter counts a request against key's cap; false when key is at it.+func (c *inflight) enter(key string) bool {+ if c == nil || c.limit <= 0 {+ return true+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.n[key] >= c.limit {+ return false+ }+ c.n[key]+++ return true+}++// add counts a request against key whatever its cap: a response on a+// WebSocket already open cannot be refused (websocket.go).+func (c *inflight) add(key string) {+ if c == nil || c.limit <= 0 {+ return+ }+ c.mu.Lock()+ c.n[key]+++ c.mu.Unlock()+}++func (c *inflight) leave(key string) {+ if c == nil || c.limit <= 0 {+ return+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.n[key] <= 1 {+ delete(c.n, key)+ } else {+ c.n[key]--+ }+}diff --git a/computer/modelproxy/inflight_test.go b/computer/modelproxy/inflight_test.gonew file mode 100644index 00000000..a9ec575b--- /dev/null+++ b/computer/modelproxy/inflight_test.go@@ -0,0 +1,114 @@+package main++import (+ "context"+ "io"+ "net/http"+ "sync"+ "testing"+ "time"+)++// One caller at its in-flight cap gets 429 with Retry-After: 1 (never+// touching upstream or the hold); when a stream ends the slot is free again,+// and another caller is unaffected.+func TestInflightCapPerCaller(t *testing.T) {+ const other = "other"+ g := &gatedUpstream{started: make(chan string, 8), release: make(chan struct{})}+ h := newHarness(t, g, harnessOpts{perCaller: 2})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tokA", "fpA")+ h.bindReady(k, other, "s2", "tokB", "fpB")+ c := h.client(testCaller)++ var wg sync.WaitGroup+ stream := func(c *http.Client) {+ defer wg.Done()+ res, err := c.Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Error(err)+ return+ }+ b, _ := io.ReadAll(res.Body)+ res.Body.Close()+ if res.StatusCode != 200 {+ t.Errorf("stream: %d %s", res.StatusCode, b)+ }+ }+ wg.Add(2)+ go stream(c)+ go stream(c)+ <-g.started+ <-g.started++ res := do(t, h, testCaller)+ if res.StatusCode != 429 || res.Header.Get("Retry-After") != "1" || res.Header.Get("X-Should-Retry") != "true" {+ t.Fatalf("status %d retry-after %q", res.StatusCode, res.Header.Get("Retry-After"))+ }+ if e := decodeAPIError(t, res); e.Error.Type != "rate_limit_error" {+ t.Fatalf("error %+v", e)+ }+ if ev := k.waitFor(isEvent("model.denied")); ev["data"].(map[string]any)["reason"] != "caller_cap" {+ t.Fatalf("event %v", ev)+ }+ // Another caller has its own cap.+ wg.Add(1)+ go stream(h.client(other))+ if b := <-g.started; b != "Bearer tokB" {+ t.Fatalf("other caller %q", b)+ }++ close(g.release)+ wg.Wait()+ g.release = make(chan struct{})+ close(g.release)+ if res := do(t, h, testCaller); res.StatusCode != 200 {+ t.Fatalf("after the streams ended: %d", res.StatusCode)+ }+}++// Held requests count toward the cap: a caller with no credential yet cannot+// queue more than the cap waiting for its bind; the extra one gets 429 at+// once, not after the hold.+func TestInflightCapCountsHeld(t *testing.T) {+ up, hits := okUpstream()+ h := newHarness(t, up, harnessOpts{perCaller: 2, hold: time.Second,+ restore: []bindingInfo{{Caller: testCaller, SessionKey: "s1", Mode: modeProfile, Profile: mainProfile, Key: "fp1"}}})+ k := h.dialControl()+ k.waitFor(isT("hello"))+ c := h.client(testCaller)++ results := make(chan int, 2)+ for range 2 {+ go func() {+ res, err := c.Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Error(err)+ results <- 0+ return+ }+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ results <- res.StatusCode+ }()+ }+ time.Sleep(100 * time.Millisecond) // both held+ start := time.Now()+ res := do(t, h, testCaller)+ if res.StatusCode != 429 || time.Since(start) > 500*time.Millisecond {+ t.Fatalf("third: %d after %v", res.StatusCode, time.Since(start))+ }+ if hits.Load() != 0 {+ t.Fatal("upstream contacted")+ }+ // The bind arrives: the two held ones are served.+ k.bind(testCaller, "s1", "tok", "fp1")+ for range 2 {+ if s := <-results; s != 200 {+ t.Fatalf("held request: %d", s)+ }+ }+ if res := do(t, h, testCaller); res.StatusCode != 200 {+ t.Fatalf("after the hold: %d", res.StatusCode)+ }+}diff --git a/computer/modelproxy/lease.go b/computer/modelproxy/lease.gonew file mode 100644index 00000000..5978e9cd--- /dev/null+++ b/computer/modelproxy/lease.go@@ -0,0 +1,97 @@+// A lease is one request's copy of its caller's credential, taken when the+// request is admitted (proxy.go). A request whose caller has no credential+// yet is held until its bind arrives, up to the hold cap.+//+// Invariants: a lease never changes, so a stream finishes on the credential+// it started with whatever is bound meanwhile; a binding's variables leave+// the table only inside a lease.+package main++import (+ "context"+ "time"+)++// holdResult says why Acquire returned without a lease.+type holdResult int++const (+ holdOK holdResult = iota+ holdNotReady // the caller's credential may still come → 503+ holdUnknown // the binder knows no such caller → 401+ holdCanceled // the client went away+)++type lease struct {+ s *Bindings+ b *binding+ sessionKey string+ cred credential+ swapped bool // first request on a credential that replaced another+ waited bool // the request was held at least once+}++// Acquire waits (up to hold) until caller has a credential, then leases it.+func (s *Bindings) Acquire(ctx context.Context, caller string, hold time.Duration) (*lease, holdResult) {+ var timer *time.Timer+ for {+ s.mu.Lock()+ b := s.m[caller]+ if b != nil && b.credentialed {+ l := &lease{s: s, b: b, sessionKey: b.sessionKey, cred: b.cred, swapped: b.swapped, waited: timer != nil}+ b.swapped = false+ s.mu.Unlock()+ if timer != nil {+ timer.Stop()+ }+ return l, holdOK+ }+ ch := s.changed+ s.mu.Unlock()+ if timer == nil {+ timer = time.NewTimer(hold)+ }+ select {+ case <-ch:+ case <-ctx.Done():+ timer.Stop()+ return nil, holdCanceled+ case <-timer.C:+ s.mu.Lock()+ known := s.m[caller] != nil+ s.mu.Unlock()+ if known || !s.synced.Load() {+ return nil, holdNotReady+ }+ return nil, holdUnknown+ }+ }+}++// knownProfile is a known caller's profile (bound, or restored from disk;+// nil if it has none): the not-ready text is its own. Cold path: only after+// a hold timed out.+func (s *Bindings) knownProfile(caller string) *profile {+ s.mu.Lock()+ defer s.mu.Unlock()+ if b := s.m[caller]; b != nil {+ return b.cred.prof+ }+ return nil+}++// changes is closed at the table's next change.+func (s *Bindings) changes() <-chan struct{} {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.changed+}++// current: the caller is still bound to the lease's credential. A WebSocket+// closes between responses once it is not (websocket.go).+func (l *lease) current() bool {+ s := l.s+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.m[l.b.caller] == l.b && l.b.cred.equal(&l.cred)+}diff --git a/computer/modelproxy/log.go b/computer/modelproxy/log.gonew file mode 100644index 00000000..0d5a08fd--- /dev/null+++ b/computer/modelproxy/log.go@@ -0,0 +1,28 @@+// Logging: log/slog JSON to stderr (journald under systemd), with a fixed+// service envelope. Never logged: a binding's variables, placeholders,+// bodies, prompts.+package main++import (+ "io"+ "log"+ "log/slog"+ "os"+)++var logger = slog.New(slog.NewJSONHandler(io.Discard, nil))++// discardLog silences ReverseProxy's own logging (its messages can carry+// upstream error text); failures are logged by our ErrorHandler instead.+var discardLog = log.New(io.Discard, "", 0)++func initLogger(version string, level slog.Level) {+ h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})+ host, _ := os.Hostname()+ logger = slog.New(h).With("service", "modelproxy", "hostname", host, "version", version)+ slog.SetDefault(logger)+}++func logInfo(msg string, args ...any) { logger.Info(msg, args...) }+func logWarn(msg string, args ...any) { logger.Warn(msg, args...) }+func logError(msg string, args ...any) { logger.Error(msg, args...) }diff --git a/computer/modelproxy/main.go b/computer/modelproxy/main.gonew file mode 100644index 00000000..3f780e45--- /dev/null+++ b/computer/modelproxy/main.go@@ -0,0 +1,339 @@+// oc-modelproxy: the model proxy on a computer. A model client in a session+// (Claude Code, Codex, anything that takes a base URL) reaches it on a Unix+// socket in plaintext with a placeholder credential; the proxy names the+// caller from its cgroup (identity.go), applies the profile that caller is+// bound to (profile.go: the upstream, the routes allowed, the headers that+// carry the binding's variables) and streams to that upstream. A binder (the+// host) binds callers over a second socket (control.go). The real credential+// is never in the session's process, files or environment.+//+// Profiles are JSON files (-profiles), read at start: a change takes a+// restart, which keeps bindings (persist.go); -check validates them without+// starting. Everything else is flags. Standard library only.+package main++import (+ "cmp"+ "context"+ "crypto/x509"+ "errors"+ "flag"+ "fmt"+ "log/slog"+ "net"+ "net/http"+ "net/http/httputil"+ "os"+ "os/signal"+ "runtime/debug"+ "syscall"+ "time"+)++// version is set at build time: -ldflags "-X main.version=...".+var version = "dev"++type config struct {+ apiSocket, controlSocket string+ profilesDir string+ placeholder string+ identity string // cgroup | single+ bindingsFile string+ hold, drain time.Duration+ maxInflightPerCaller int+ maxConnsPerCaller int+ wsIdle time.Duration+ maxIdlePerHost int+ maxConnsPerHost int+ idleConnTimeout time.Duration+ procRoot string // tests only; "" = /proc+ debug bool+ rootCAs *x509.CertPool // tests only; nil = system roots+}++// defaultGCPercent: the live heap is a few MiB, so at Go's default of 100+// the collector runs every few hundred requests and its assists land in+// stream latency (p99 overhead about 1.5 ms at 64 streams, versus 0.15 ms+// at 400; see BenchmarkProxyOverhead). 400 costs a few tens of MiB.+const defaultGCPercent = 400++// maxHeaderBytes bounds a request's headers; with -max-conns-per-caller it+// bounds what a caller can make the proxy hold before a request is admitted.+const maxHeaderBytes = 32 << 10++// setGCPercent applies defaultGCPercent unless GOGC is set in the environment.+func setGCPercent() {+ if os.Getenv("GOGC") == "" {+ debug.SetGCPercent(defaultGCPercent)+ }+}++func main() {+ cfg, mode, err := parseFlags(os.Args[1:])+ if err != nil {+ os.Exit(2) // the FlagSet has printed it+ }+ switch mode {+ case modeVersion:+ fmt.Println(version)+ return+ case modeCheck:+ if err := checkProfiles(cfg); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ return+ }+ level := slog.LevelInfo+ if cfg.debug {+ level = slog.LevelDebug+ }+ initLogger(version, level)+ setGCPercent()+ if err := run(cfg); err != nil {+ logError("exit", "error", err.Error())+ os.Exit(1)+ }+}++// checkProfiles is -check: the load a start does, and nothing else.+func checkProfiles(cfg config) error {+ _, err := loadProfiles(cfg.profilesDir)+ return err+}++// runMode is what the command line asks for instead of serving.+type runMode int++const (+ modeServe runMode = iota+ modeVersion+ modeCheck+)++func parseFlags(args []string) (config, runMode, error) {+ var cfg config+ fs := flag.NewFlagSet("oc-modelproxy", flag.ContinueOnError)+ showVersion := fs.Bool("version", false, "print the version and exit")+ check := fs.Bool("check", false, "load -profiles as a start would, print the first error and exit 0 or 1; opens no socket")+ fs.StringVar(&cfg.apiSocket, "api-socket", "/run/oc-modelproxy/api.sock", "the model clients' socket; used when not socket-activated")+ fs.StringVar(&cfg.controlSocket, "control-socket", "/run/oc-modelproxy/control.sock", "the binder's control socket; used when not socket-activated")+ fs.StringVar(&cfg.profilesDir, "profiles", "/etc/oc-modelproxy/profiles.d", "directory of profile files (*.json)")+ fs.StringVar(&cfg.placeholder, "placeholder", "ssh-placeholder", "the only credential a caller may send: `Authorization: Bearer <it>` or `x-api-key: <it>`")+ fs.StringVar(&cfg.identity, "identity", "cgroup", "how a caller is named: cgroup (<id> of its sp-runner-<id>.service unit) or single (every caller is "+singleCaller+")")+ fs.StringVar(&cfg.bindingsFile, "bindings-file", "/run/oc-modelproxy/profile-bindings.json", "persisted bindings, without their variables (empty: do not persist)")+ fs.DurationVar(&cfg.hold, "hold-timeout", 10*time.Second, "how long a request waits for its caller's credential, and then for a free upstream connection")+ fs.DurationVar(&cfg.drain, "drain-timeout", 630*time.Second, "on SIGTERM, how long in-flight streams may finish")+ fs.IntVar(&cfg.maxInflightPerCaller, "max-inflight-per-caller", 32, "concurrent requests (held ones included) one caller may have; more get 429 (0: no limit)")+ fs.IntVar(&cfg.maxConnsPerCaller, "max-conns-per-caller", 128, "connections one caller may have open on the API socket; more are closed as accepted (0: no limit)")+ fs.DurationVar(&cfg.wsIdle, "ws-idle-timeout", 5*time.Minute, "close a WebSocket idle this long between responses; it holds a caller's in-flight slot while open (0: never)")+ fs.IntVar(&cfg.maxIdlePerHost, "max-idle-conns-per-host", 96, "idle upstream connections kept")+ fs.IntVar(&cfg.maxConnsPerHost, "max-conns-per-host", 256, "upstream connection ceiling; requests beyond it queue")+ fs.DurationVar(&cfg.idleConnTimeout, "idle-conn-timeout", 50*time.Second, "close idle upstream connections after this")+ fs.BoolVar(&cfg.debug, "debug", false, "debug logging")+ if err := fs.Parse(args); err != nil {+ return cfg, modeServe, err+ }+ switch {+ case *showVersion:+ return cfg, modeVersion, nil+ case *check:+ return cfg, modeCheck, nil+ }+ return cfg, modeServe, nil+}++func run(cfg config) error {+ started := time.Now()+ ps, err := loadProfiles(cfg.profilesDir)+ if err != nil {+ return err+ }+ var resolve Resolver+ switch cfg.identity {+ case "cgroup":+ resolve = peerResolver(cmp.Or(cfg.procRoot, "/proc"))+ case "single":+ resolve = singleResolver+ default:+ return fmt.Errorf("-identity must be cgroup or single")+ }+ srv, err := newServer(cfg, ps, resolve)+ if err != nil {+ return err+ }++ ls, err := activatedListeners()+ if err != nil {+ return err+ }+ apiL, ctlL := ls["api"], ls["control"]+ if apiL == nil {+ if apiL, err = listenUnix(cfg.apiSocket); err != nil {+ return err+ }+ }+ if ctlL == nil {+ if ctlL, err = listenUnix(cfg.controlSocket); err != nil {+ return err+ }+ }+ srv.start(apiL, ctlL)+ sdNotify("READY=1")+ logInfo("ready", "activated", len(ls) > 0, "profiles", len(ps.sorted), "bindings", srv.bindings.Len(), "startup_ms", ms(time.Since(started)))++ sig := make(chan os.Signal, 1)+ signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)+ <-sig+ sdNotify("STOPPING=1")+ logInfo("draining", "streams", srv.proxy.activeStreams())+ ctx, cancel := context.WithTimeout(context.Background(), cfg.drain)+ defer cancel()+ err = srv.shutdown(ctx)+ logInfo("exit", "uptime_s", int(time.Since(started).Seconds()), "dropped_messages", srv.control.Dropped())+ return err+}++// server wires the parts; tests build it with their own resolver and roots.+type server struct {+ cfg config+ profiles *profiles+ bindings *Bindings+ control *Control+ proxy *Proxy+ persist *persister+ http *http.Server+ resolve Resolver+ ctlL net.Listener+ stop chan struct{}+ done chan struct{}+}++func (cfg config) newUpstream(p *profile) *upstream {+ return newUpstream(upstreamConfig{url: p.url, maxIdlePerHost: cfg.maxIdlePerHost, maxConnsPerHost: cfg.maxConnsPerHost,+ idleConnTimeout: cfg.idleConnTimeout, rootCAs: cfg.rootCAs})+}++// newServer builds a server on ps, one upstream per profile.+func newServer(cfg config, ps *profiles, resolve Resolver) (*server, error) {+ if cfg.placeholder == "" || !validHeaderValue(cfg.placeholder) {+ return nil, fmt.Errorf("-placeholder must be a header value")+ }+ if cfg.hold <= 0 {+ return nil, fmt.Errorf("-hold-timeout must be positive")+ }+ s := &server{cfg: cfg, profiles: ps, resolve: resolve, stop: make(chan struct{}), done: make(chan struct{})}+ s.control = NewControl(version, cfg.placeholder, ps)+ s.bindings = NewBindings(ps, s.control, nil)+ s.persist = newPersister(cfg.bindingsFile, s.bindings.Snapshot)+ s.bindings.dirty = s.persist.markDirty+ s.control.bindings = s.bindings+ entries, err := loadBindings(cfg.bindingsFile)+ if err != nil {+ logWarn("bindings file unreadable; starting empty", "error", err.Error())+ }+ s.bindings.Restore(entries)+ s.proxy = NewProxy(s.bindings, NewObserver(s.control), s.control, ps, cfg.placeholder, cfg.hold, cfg.maxInflightPerCaller)+ s.proxy.wsIdle = cfg.wsIdle+ var pool httputil.BufferPool = newBufferPool(32 << 10)+ for _, p := range ps.sorted {+ newOutbound(s.proxy, p, cfg.newUpstream(p), pool)+ }+ s.http = &http.Server{+ Handler: s.proxy,+ ConnContext: connCaller,+ ReadHeaderTimeout: 30 * time.Second,+ MaxHeaderBytes: maxHeaderBytes,+ IdleTimeout: 5 * time.Minute,+ ErrorLog: discardLog,+ }+ s.http.SetKeepAlivesEnabled(true)+ return s, nil+}++func (s *server) start(apiL, ctlL net.Listener) {+ s.ctlL = ctlL+ go s.persist.run()+ go func() {+ l := &callerListener{Listener: apiL, resolve: s.resolve, conns: newInflight(s.cfg.maxConnsPerCaller)}+ if err := s.http.Serve(l); err != nil && !errors.Is(err, http.ErrServerClosed) {+ logError("api socket", "error", err.Error())+ }+ }()+ go s.control.Serve(ctlL)+ go s.poolLoop()+ e := newEvent(time.Now(), "model.proxy_started")+ e.Outcome = "completed"+ e.Data = map[string]any{"version": version, "bindings": s.bindings.Len()}+ s.control.sendKept(e)+}++// poolLoop reports each profile's upstream pool every minute, as a log line+// and a model.pool event.+func (s *server) poolLoop() {+ defer close(s.done)+ t := time.NewTicker(time.Minute)+ defer t.Stop()+ for {+ select {+ case <-t.C:+ for i, p := range s.profiles.sorted {+ e, ok := s.poolEvent(p, i == 0)+ if !ok {+ continue+ }+ args := make([]any, 0, 2*len(e.Data)+2)+ args = append(args, "profile", e.Profile)+ for k, v := range e.Data {+ args = append(args, k, v)+ }+ logInfo("pool", args...)+ s.control.send(e)+ }+ case <-s.stop:+ return+ }+ }+}++// poolEvent is one profile's model.pool telemetry event: gauges of its+// upstream pool, and the counters since the last one (which it resets). The+// first profile's is always sent and carries the proxy-wide gauges, so a+// sum over profiles counts them once; ok is false for another's idle pool+// with nothing to report.+func (s *server) poolEvent(p *profile, first bool) (eventMsg, bool) {+ up := p.up+ open, streams := up.open.Load(), up.streams.Load()+ if !first && open == 0 && streams == 0 && up.dials.Load() == 0 && up.poolMiss.Load() == 0 {+ return eventMsg{}, false+ }+ e := newEvent(time.Now(), "model.pool")+ e.Profile = p.name+ e.Outcome = "completed"+ e.Data = map[string]any{+ "open_conns": open, "idle_conns": max(open-streams, 0), "active_streams": streams,+ "idle_pool_miss": up.poolMiss.Swap(0), "dials": up.dials.Swap(0),+ }+ if first {+ e.Data["bindings"], e.Data["dropped_messages"] = s.bindings.Len(), s.control.Dropped()+ }+ return e, true+}++// shutdown: drop the binder's connection first (it reconnects to the next+// instance at once), stop accepting, let in-flight streams and WebSocket+// responses finish.+func (s *server) shutdown(ctx context.Context) error {+ s.control.Close()+ s.ctlL.Close()+ s.proxy.drainWS(ctx, false) // tunnels close between responses while HTTP streams finish+ err := s.http.Shutdown(ctx)+ s.proxy.drainWS(ctx, true)+ close(s.stop)+ <-s.done+ s.persist.close()+ for _, p := range s.profiles.sorted {+ p.up.close()+ }+ return err+}diff --git a/computer/modelproxy/main_test.go b/computer/modelproxy/main_test.gonew file mode 100644index 00000000..e815fd1c--- /dev/null+++ b/computer/modelproxy/main_test.go@@ -0,0 +1,32 @@+package main++import (+ "os"+ "path/filepath"+ "testing"+)++func TestParseFlags(t *testing.T) {+ cfg, mode, err := parseFlags(nil)+ if err != nil || mode != modeServe || cfg.identity != "cgroup" || cfg.maxInflightPerCaller != 32 {+ t.Fatalf("defaults: %+v %v %v", cfg, mode, err)+ }+ if _, mode, err := parseFlags([]string{"-version"}); err != nil || mode != modeVersion {+ t.Fatalf("-version: %v %v", mode, err)+ }+ cfg, mode, err = parseFlags([]string{"-check", "-profiles", "profiles"})+ if err != nil || mode != modeCheck {+ t.Fatalf("-check: %v %v", mode, err)+ }+ if err := checkProfiles(cfg); err != nil {+ t.Fatalf("the shipped profiles: %v", err)+ }+ dir := t.TempDir()+ if err := os.WriteFile(filepath.Join(dir, "a.json"), []byte(`{"p":{"upstream":"http://a.example"}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ cfg.profilesDir = dir+ if err := checkProfiles(cfg); err == nil {+ t.Fatal("a bad profile passed -check")+ }+}diff --git a/computer/modelproxy/observed.go b/computer/modelproxy/observed.gonew file mode 100644index 00000000..e1fcee61--- /dev/null+++ b/computer/modelproxy/observed.go@@ -0,0 +1,234 @@+// What upstreams answer, reported to the binder as `observed`: the proxy says+// what it saw and the binder decides what it means (a spent quota, a revoked+// credential, an outage). For a binding with a key, each upstream answer is+// a candidate:+//+// status the response's (a WebSocket: 101 for the handshake, 200 for+// each response completed on it, an `error` event's own status)+// headers the response headers the profile's `report` globs name+// body the start of a 4xx/5xx body that is not an event stream+// error instead of a status: the transport error's class (upstream.go)+//+// Per profile and key, sent:+// - every 401;+// - an answer below 400: the first, the first after a failure, and+// otherwise at most once a minute (its headers carry the figures);+// - any other: when the status or error class changes; with the same one,+// when the reported headers differ (at most once a second), and at least+// once a minute;+// - but not a change back to the status or class before the last, within+// a second of that one's report: answers that alternate (some requests+// limited, some not) are not one message each.+//+// So never one per request in the steady state.+//+// A body's start is copied as the client reads it, never ahead of it; the+// report waits for it at most errorBodyWait (headBody).+package main++import (+ "io"+ "net/http"+ "sort"+ "strconv"+ "strings"+ "sync"+ "time"+)++const (+ observedEvery = time.Minute+ observedBurst = time.Second+ observedBody = 2 << 10+ observedKeep = 10 * time.Minute // a key not seen this long is forgotten+ observedPruneAt = 1024+ statusFirstError = 400+)++// errorBodyWait bounds how long a report waits for the body (a var for tests).+var errorBodyWait = 2 * time.Second++type Observer struct {+ mu sync.Mutex+ m map[string]*observedSeen+ out sender+ now func() time.Time+}++type observedSeen struct {+ class string // "ok", else the status or error class+ hdrSig string+ sentAt time.Time+ // The class before this one and when it was last sent.+ prevClass string+ prevAt time.Time+}++func NewObserver(out sender) *Observer {+ return &Observer{m: map[string]*observedSeen{}, out: out, now: time.Now}+}++// subject is whose answer it is.+type subject struct {+ prof *profile+ sessionKey, caller, key string+}++func (st *reqState) subject() subject {+ return subject{prof: st.prof, sessionKey: st.sessionKey, caller: st.caller, key: st.key}+}++// response reports an upstream response; body is the start of its body, if kept.+func (o *Observer) response(s subject, status int, hdr http.Header, body []byte) {+ if s.key == "" {+ return+ }+ msg := observedMsg{T: "observed", SessionKey: s.sessionKey, Caller: s.caller, Key: s.key, Profile: s.prof.name,+ Status: status, Headers: reported(s.prof.report, hdr), Body: string(body[:min(len(body), observedBody)])}+ class := "ok"+ if status >= statusFirstError {+ class = strconv.Itoa(status)+ }+ o.report(msg, class, status == http.StatusUnauthorized)+}++// transport reports a request that got no response: class is errorClass's.+func (o *Observer) transport(s subject, class string) {+ if s.key == "" || class == "canceled" {+ return+ }+ o.report(observedMsg{T: "observed", SessionKey: s.sessionKey, Caller: s.caller, Key: s.key, Profile: s.prof.name, Error: class}, class, false)+}++func (o *Observer) report(msg observedMsg, class string, always bool) {+ now := o.now()+ sig := headerSig(msg.Headers)+ id := msg.Profile + "\x00" + msg.Key+ o.mu.Lock()+ seen := o.m[id]+ send := always || seen == nil || seen.class != class+ if !send {+ age := now.Sub(seen.sentAt)+ send = age >= observedEvery || (class != "ok" && seen.hdrSig != sig && age >= observedBurst)+ }+ if send && !always && seen != nil && seen.class != class && seen.prevClass == class && now.Sub(seen.prevAt) < observedBurst {+ send = false // flapping+ }+ if send {+ next := &observedSeen{class: class, hdrSig: sig, sentAt: now}+ if seen != nil {+ next.prevClass, next.prevAt = seen.prevClass, seen.prevAt+ if seen.class != class {+ next.prevClass, next.prevAt = seen.class, seen.sentAt+ }+ }+ if seen == nil && len(o.m) >= observedPruneAt {+ for k, v := range o.m {+ if now.Sub(v.sentAt) > observedKeep {+ delete(o.m, k)+ }+ }+ }+ o.m[id] = next+ }+ o.mu.Unlock()+ if send {+ o.out.send(msg)+ }+}++// reported is the headers matching the profile's `report` globs, names in+// lower case; nil when there are none.+func reported(globs []string, hdr http.Header) map[string]string {+ if len(globs) == 0 {+ return nil+ }+ var out map[string]string+ for name, vals := range hdr {+ lower := strings.ToLower(name)+ if len(vals) == 0 || !matchesAny(globs, lower) {+ continue+ }+ if out == nil {+ out = map[string]string{}+ }+ out[lower] = strings.Join(vals, ", ")+ }+ return out+}++func headerSig(h map[string]string) string {+ if len(h) == 0 {+ return ""+ }+ keys := make([]string, 0, len(h))+ for k := range h {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ var b strings.Builder+ for _, k := range keys {+ b.WriteString(k)+ b.WriteByte('=')+ b.WriteString(h[k])+ b.WriteByte('\n')+ }+ return b.String()+}++// headBody copies the first limit bytes of a body as the client reads them,+// and reports once: at that many bytes, the end of the body, its close, or+// errorBodyWait after the headers (a stalled body still reports, with what+// has arrived).+type headBody struct {+ io.ReadCloser+ limit int+ report func(head []byte)+ timer *time.Timer++ mu sync.Mutex+ buf []byte+ done bool+}++func newHeadBody(rc io.ReadCloser, limit int, report func([]byte)) *headBody {+ b := &headBody{ReadCloser: rc, limit: limit, report: report}+ b.mu.Lock() // fire may run before AfterFunc returns: it reads timer under mu+ b.timer = time.AfterFunc(errorBodyWait, b.fire)+ b.mu.Unlock()+ return b+}++func (b *headBody) Read(p []byte) (int, error) {+ n, err := b.ReadCloser.Read(p)+ b.mu.Lock()+ full := false+ if !b.done {+ b.buf = append(b.buf, p[:min(n, b.limit-len(b.buf))]...)+ full = len(b.buf) >= b.limit+ }+ b.mu.Unlock()+ if full || err != nil {+ b.fire()+ }+ return n, err+}++func (b *headBody) Close() error {+ b.fire()+ return b.ReadCloser.Close()+}++// fire reports once, with the head kept so far.+func (b *headBody) fire() {+ b.mu.Lock()+ if b.done {+ b.mu.Unlock()+ return+ }+ b.done = true+ head, timer := b.buf, b.timer+ b.mu.Unlock()+ timer.Stop()+ b.report(head)+}diff --git a/computer/modelproxy/observed_test.go b/computer/modelproxy/observed_test.gonew file mode 100644index 00000000..57075a8f--- /dev/null+++ b/computer/modelproxy/observed_test.go@@ -0,0 +1,238 @@+package main++import (+ "context"+ "io"+ "net/http"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++// scripted answers each request with the next status (the last one again),+// alt's quota headers, one header no profile reports, and a JSON body.+func scripted(statuses ...int) http.Handler {+ var n atomic.Int64+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ i := min(int(n.Add(1))-1, len(statuses)-1)+ w.Header().Set("Content-Type", "application/json")+ w.Header().Set("X-Quota-Used", "97")+ w.Header().Set("Retry-After", "30")+ w.Header().Set("X-Other", "no")+ w.WriteHeader(statuses[i])+ io.WriteString(w, `{"error":{"type":"quota","message":"spent"}}`)+ })+}++func doReq(t *testing.T, h *harness, caller string, req *http.Request) int {+ t.Helper()+ res, err := h.client(caller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ return res.StatusCode+}++// The binder hears what the upstream answered: the status, only the headers+// the profile's `report` names, and the start of an error's body; the client+// gets the response unchanged.+func TestObserved(t *testing.T) {+ h := newHarness(t, scripted(429), harnessOpts{alt: scripted(200, 429, 401, 401, 200)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ h.bindReady(k, testCaller, "s2", "tok", "fpA")++ for i, want := range []struct {+ status int+ body string+ }{{200, ""}, {429, `{"error":{"type":"quota","message":"spent"}}`}, {401, `{"error":{"type":"quota","message":"spent"}}`}, {401, `{"error":{"type":"quota","message":"spent"}}`}, {200, ""}} {+ if st := doReq(t, h, altCaller, h.responsesReq(context.Background())); st != want.status {+ t.Fatalf("%d: status %d", i, st)+ }+ m := k.waitFor(isT("observed"))+ hd, _ := m["headers"].(map[string]any)+ if m["status"] != float64(want.status) || m["profile"] != altProfile || m["key"] != "fpC" || m["caller"] != altCaller || m["sessionKey"] != "s1" ||+ len(hd) != 2 || hd["x-quota-used"] != "97" || hd["retry-after"] != "30" || m["error"] != nil {+ t.Fatalf("%d: observed %v", i, m)+ }+ if body, _ := m["body"].(string); body != want.body {+ t.Fatalf("%d: body %q", i, body)+ }+ if strings.Contains(toJSON(m), "tok") || strings.Contains(toJSON(m), altAccount) {+ t.Fatalf("a variable in observed: %v", m)+ }+ }++ // The shipped profile reports the headers its `report` names, no other.+ if st := doReq(t, h, testCaller, h.messagesReq(context.Background())); st != 429 {+ t.Fatalf("status %d", st)+ }+ if m := k.waitFor(isT("observed")); m["status"] != float64(429) || m["profile"] != mainProfile || toJSON(m["headers"]) != `{"retry-after":"30"}` || m["body"] == nil {+ t.Fatalf("observed %v", m)+ }+}++type sink struct {+ mu sync.Mutex+ msgs []observedMsg+}++func (s *sink) send(v any) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if m, ok := v.(observedMsg); ok {+ s.msgs = append(s.msgs, m)+ }+}++func (s *sink) take() []observedMsg {+ s.mu.Lock()+ defer s.mu.Unlock()+ out := s.msgs+ s.msgs = nil+ return out+}++// What is sent of a steady state: never one message per request.+func TestObserverDedupe(t *testing.T) {+ out := &sink{}+ o := NewObserver(out)+ now := time.Unix(1_800_000_000, 0)+ o.now = func() time.Time { return now }+ prof := &profile{name: "p", report: []string{"x-quota-*"}}+ a, b := subject{prof: prof, sessionKey: "s1", caller: testCaller, key: "A"}, subject{prof: prof, sessionKey: "s2", caller: altCaller, key: "B"}+ hdr := func(v string) http.Header { return http.Header{"X-Quota-Used": {v}, "X-Other": {v + "!"}} }+ step := func(what string, want int, f func()) {+ t.Helper()+ f()+ if got := out.take(); len(got) != want {+ t.Fatalf("%s: %d messages, want %d: %+v", what, len(got), want, got)+ }+ }+ step("first ok", 1, func() { o.response(a, 200, hdr("1"), nil) })+ step("ok again, other figures", 0, func() { o.response(a, 200, hdr("2"), nil) })+ step("another key", 1, func() { o.response(b, 200, hdr("1"), nil) })+ now = now.Add(observedEvery)+ step("ok a minute on", 1, func() { o.response(a, 200, hdr("3"), nil) })+ step("a failure", 1, func() { o.response(a, 429, hdr("100"), []byte("x")) })+ step("the same failure", 0, func() { o.response(a, 429, hdr("100"), nil) })+ step("other headers within the burst", 0, func() { o.response(a, 429, hdr("101"), nil) })+ now = now.Add(observedBurst)+ step("other headers after it", 1, func() { o.response(a, 429, hdr("101"), nil) })+ step("an unreported header differs", 0, func() { o.response(a, 429, http.Header{"X-Quota-Used": {"101"}, "X-Other": {"z"}}, nil) })+ now = now.Add(observedEvery)+ step("the same failure a minute on", 1, func() { o.response(a, 429, hdr("101"), nil) })+ step("another status", 1, func() { o.response(a, 500, nil, nil) })+ step("a transport error", 1, func() { o.transport(a, "connect") })+ step("the same error", 0, func() { o.transport(a, "connect") })+ step("a cancelled request", 0, func() { o.transport(a, "canceled") })+ step("ok after a failure", 1, func() { o.response(a, 200, nil, nil) })+ step("alternating answers", 1, func() {+ for range 20 {+ o.response(a, 429, nil, nil)+ o.response(a, 200, nil, nil)+ }+ })+ now = now.Add(observedBurst)+ step("the change back, a second on", 1, func() { o.response(a, 200, nil, nil) })+ step("every 401", 3, func() {+ for range 3 {+ o.response(a, 401, nil, nil)+ }+ })+ step("no key", 0, func() { o.response(subject{prof: prof}, 500, nil, nil); o.transport(subject{prof: prof}, "connect") })++ o.response(a, 400, hdr("1"), []byte(strings.Repeat("b", observedBody+100)))+ if got := out.take(); len(got) != 1 || len(got[0].Body) != observedBody || len(got[0].Headers) != 1 || got[0].Headers["x-quota-used"] != "1" {+ t.Fatalf("message %+v", got)+ }+}++type slowBody struct {+ chunks chan []byte+ closed chan struct{}+ once sync.Once+}++func (b *slowBody) Read(p []byte) (int, error) {+ select {+ case c, ok := <-b.chunks:+ if !ok {+ return 0, io.EOF+ }+ return copy(p, c), nil+ case <-b.closed:+ return 0, io.ErrClosedPipe+ }+}++func (b *slowBody) Close() error { b.once.Do(func() { close(b.closed) }); return nil }++// headBody reports once, with at most its limit: at the limit, at the end,+// at close, or after errorBodyWait when the body stalls. It reads nothing+// itself and passes every byte on.+func TestHeadBody(t *testing.T) {+ old := errorBodyWait+ errorBodyWait = 50 * time.Millisecond+ defer func() { errorBodyWait = old }()+ newBody := func() (*slowBody, *headBody, chan string) {+ got := make(chan string, 4)+ src := &slowBody{chunks: make(chan []byte, 4), closed: make(chan struct{})}+ return src, newHeadBody(src, 8, func(b []byte) { got <- string(b) }), got+ }+ one := func(got chan string) string {+ t.Helper()+ select {+ case s := <-got:+ return s+ case <-time.After(2 * time.Second):+ t.Fatal("no report")+ return ""+ }+ }+ buf := make([]byte, 64)++ src, hb, got := newBody() // larger than the limit+ src.chunks <- []byte("0123456789abcdef")+ if n, _ := hb.Read(buf); string(buf[:n]) != "0123456789abcdef" {+ t.Fatalf("read %q", buf[:n])+ }+ if s := one(got); s != "01234567" {+ t.Fatalf("head %q", s)+ }+ hb.Close()++ src, hb, got = newBody() // shorter: reported at its end+ src.chunks <- []byte("abc")+ close(src.chunks)+ hb.Read(buf)+ hb.Read(buf)+ if s := one(got); s != "abc" {+ t.Fatalf("head %q", s)+ }+ hb.Close()++ src, hb, got = newBody() // stalled after a start: reported with what arrived+ src.chunks <- []byte("ab")+ hb.Read(buf)+ if s := one(got); s != "ab" {+ t.Fatalf("head %q", s)+ }+ hb.Close()++ _, hb, got = newBody() // closed unread+ hb.Close()+ if s := one(got); s != "" {+ t.Fatalf("head %q", s)+ }+ select {+ case s := <-got:+ t.Fatalf("reported twice: %q", s)+ case <-time.After(100 * time.Millisecond):+ }+}diff --git a/computer/modelproxy/outbound.go b/computer/modelproxy/outbound.gonew file mode 100644index 00000000..e50feac8--- /dev/null+++ b/computer/modelproxy/outbound.go@@ -0,0 +1,192 @@+// The outbound half of a proxied request, one per profile (profile.go): its+// upstream, its own httputil.ReverseProxy, and the rewrite that applies the+// profile's header policy, in this order:+//+// URL the profile's scheme and host; its base path, then the route's+// `to` (else the path the route matched, re-encoded: never the+// caller's own encoding of it); the query kept as sent+// removed Authorization and X-Api-Key (the caller's placeholder), then+// the profile's `remove` globs+// set the profile's `set`, then the route's, with the binding's+// variables; then the route's `default`, where the header is absent+// WS Sec-WebSocket-Extensions dropped, so no compression is+// negotiated and frames stay readable (websocket.go)+//+// Every other header passes untouched. Hop-by-hop headers and+// X-Forwarded-For/-Host/-Proto/Forwarded are stripped by ReverseProxy; the+// request body is streamed and never read; the response is flushed+// immediately and never read ahead of the client.+//+// Invariant: a profile's ReverseProxy only ever dials its own upstream, and+// is only handed requests whose lease is on that profile (proxy.go), so a+// binding's variables never reach another profile's host.+package main++import (+ "bytes"+ "context"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptrace"+ "net/http/httputil"+ "time"+)++type outbound struct {+ prof *profile+ p *Proxy+}++// newOutbound gives prof its upstream and ReverseProxy.+func newOutbound(p *Proxy, prof *profile, up *upstream, pool httputil.BufferPool) {+ o := &outbound{prof: prof, p: p}+ prof.up = up+ prof.rp = &httputil.ReverseProxy{+ Rewrite: o.rewrite,+ Transport: up.transport,+ FlushInterval: -1,+ BufferPool: pool,+ ModifyResponse: o.modifyResponse,+ ErrorHandler: o.errorHandler,+ ErrorLog: discardLog,+ }+}++func (o *outbound) rewrite(pr *httputil.ProxyRequest) {+ st := pr.In.Context().Value(stateKey).(*reqState)+ out := pr.Out+ o.prof.target(out, st.rs)+ o.prof.headers(out.Header, st.rs, st.vars)+ if out.Body != nil {+ out.Body = &countingBody{ReadCloser: out.Body, n: &st.bytesIn}+ }+ pr.Out = out.WithContext(httptrace.WithClientTrace(out.Context(), st.trace(o.prof.up)))+}++// target points out at the profile's upstream; its query is left as it is.+func (p *profile) target(out *http.Request, rs *routeSpec) {+ out.URL.Scheme = p.url.Scheme+ out.URL.Host = p.url.Host+ out.Host = p.url.Host+ path := out.URL.Path+ if rs.to != "" {+ path = rs.to+ }+ // The route was matched on the decoded path: that is the one sent, not+ // the caller's own encoding of it.+ out.URL.Path, out.URL.RawPath = p.url.Path+path, ""+}++// headers applies the profile's and the route's header policy to h.+func (p *profile) headers(h http.Header, rs *routeSpec, vars map[string]string) {+ delete(h, "Authorization")+ delete(h, "X-Api-Key")+ if len(p.remove) > 0 {+ for k := range h {+ if matchesAny(p.remove, k) {+ delete(h, k)+ }+ }+ }+ for _, s := range p.set {+ h[s.name] = []string{s.value.expand(vars)}+ }+ for _, s := range rs.set {+ h[s.name] = []string{s.value.expand(vars)}+ }+ for _, s := range rs.def {+ if len(h[s.name]) == 0 {+ h[s.name] = []string{s.value.expand(vars)}+ }+ }+ if rs.ws {+ delete(h, "Sec-Websocket-Extensions")+ }+}++func (o *outbound) modifyResponse(res *http.Response) error {+ st := res.Request.Context().Value(stateKey).(*reqState)+ if st.rs.ws {+ return o.switchWS(st, res)+ }+ st.status = res.StatusCode+ st.stream = isEventStream(res.Header.Get("Content-Type"))+ o.observe(st, res)+ res.Body = &upstreamBody{ReadCloser: res.Body, st: st}+ if st.rs.responses && res.StatusCode == http.StatusOK && res.Header.Get("Content-Encoding") == "" {+ res.Body = watchResponses(st, res.Body)+ }+ return nil+}++// observe reports the response to the binder (observed.go). An error's body+// may say what its headers do not: that report waits for the body's start+// as the client reads it, bounded in time, so nothing is read ahead of the+// client. Not for an event stream or a compressed body.+func (o *outbound) observe(st *reqState, res *http.Response) {+ if st.key == "" {+ return+ }+ obs, sub, status := o.p.observer, st.subject(), res.StatusCode+ if status >= statusFirstError && !st.stream && res.Header.Get("Content-Encoding") == "" {+ hdr := res.Header.Clone()+ res.Body = newHeadBody(res.Body, observedBody, func(head []byte) { obs.response(sub, status, hdr, head) })+ return+ }+ obs.response(sub, status, res.Header, nil)+}++// switchWS takes the WebSocket handshake's response: a 101 becomes a+// tunnel (websocket.go); any other status is reported to the binder with its+// body's start and reaches the client as a 426, so it goes on over HTTP. The+// refused handshake's body is read here, bounded in size and time: it never+// reaches the client.+func (o *outbound) switchWS(st *reqState, res *http.Response) error {+ st.status = res.StatusCode+ if res.StatusCode != http.StatusSwitchingProtocols {+ stop := time.AfterFunc(errorBodyWait, func() { res.Body.Close() })+ head, _ := io.ReadAll(io.LimitReader(res.Body, wsErrorHead))+ stop.Stop()+ res.Body.Close()+ o.p.observer.response(st.subject(), res.StatusCode, res.Header, head)+ h := http.Header{}+ b := apiErrorHeaders(h, http.StatusUpgradeRequired, "invalid_request_error", wsUseHTTP+fmt.Sprintf(textWSRefused, res.StatusCode))+ res.StatusCode, res.Status, res.Header = http.StatusUpgradeRequired, "426 Upgrade Required", h+ res.Body, res.ContentLength = io.NopCloser(bytes.NewReader(b)), int64(len(b))+ return nil+ }+ up, ok := res.Body.(io.ReadWriteCloser)+ if !ok {+ return errors.New("101 with a body that is not writable") // errorHandler: 426+ }+ o.p.observer.response(st.subject(), http.StatusSwitchingProtocols, res.Header, nil)+ st.ws = newWSTunnel(o.p, st, up)+ res.Body = st.ws+ return nil+}++func (o *outbound) errorHandler(w http.ResponseWriter, r *http.Request, err error) {+ st := r.Context().Value(stateKey).(*reqState)+ if context.Cause(r.Context()) == errConnWait {+ // It never reached the upstream: a refusal, not a failed request.+ st.proxied = false+ st.denyAs(w, "upstream_busy", "timeout", http.StatusServiceUnavailable, "api_error", textBusy)+ return+ }+ if r.Context().Err() != nil {+ st.cancelled.Store(true)+ return+ }+ class := errorClass(err)+ st.transportErr = class+ logWarn("upstream request failed", "profile", o.prof.name, "route", st.route, "session_key", st.sessionKey, "error_type", class)+ o.p.observer.transport(st.subject(), class)+ if st.rs.ws {+ // The client goes on over HTTP, where an unreachable upstream is reported as usual.+ writeAPIError(w, http.StatusUpgradeRequired, "invalid_request_error", wsUseHTTP+o.prof.text.unreachable)+ return+ }+ writeAPIError(w, http.StatusBadGateway, "api_error", o.prof.text.unreachable)+}diff --git a/computer/modelproxy/peer_linux.go b/computer/modelproxy/peer_linux.gonew file mode 100644index 00000000..750066ae--- /dev/null+++ b/computer/modelproxy/peer_linux.go@@ -0,0 +1,29 @@+//go:build linux++package main++import (+ "net"+ "syscall"+)++// peerPid returns the pid of the process on the other end of a Unix socket+// connection, from SO_PEERCRED (taken by the kernel at connect time).+func peerPid(c net.Conn) (int, bool) {+ uc, ok := c.(*net.UnixConn)+ if !ok {+ return 0, false+ }+ raw, err := uc.SyscallConn()+ if err != nil {+ return 0, false+ }+ var cred *syscall.Ucred+ var serr error+ if err := raw.Control(func(fd uintptr) {+ cred, serr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)+ }); err != nil || serr != nil || cred == nil {+ return 0, false+ }+ return int(cred.Pid), true+}diff --git a/computer/modelproxy/peer_other.go b/computer/modelproxy/peer_other.gonew file mode 100644index 00000000..52e8dd93--- /dev/null+++ b/computer/modelproxy/peer_other.go@@ -0,0 +1,8 @@+//go:build !linux++package main++import "net"++// peerPid is Linux-only (SO_PEERCRED); elsewhere no caller is a runner.+func peerPid(net.Conn) (int, bool) { return 0, false }diff --git a/computer/modelproxy/persist.go b/computer/modelproxy/persist.gonew file mode 100644index 00000000..1dc9eae1--- /dev/null+++ b/computer/modelproxy/persist.go@@ -0,0 +1,131 @@+// The bindings table on disk (-bindings-file; its directory is a tmpfiles.d+// one, not RuntimeDirectory=, which would go when the service stops and take+// the activated sockets with it): caller → sessionKey, mode, profile, key.+// Never a binding's variables. Read once at start so a restarted proxy holds+// known callers' requests until the binder re-binds them; written atomically+// (temp file, fsync, rename) by one goroutine that coalesces bursts of+// changes.+//+// The file is a cache of what the binder knows: one of another version, or+// unreadable, is ignored and the proxy starts empty.+package main++import (+ "encoding/json"+ "errors"+ "io/fs"+ "os"+ "path/filepath"+ "sync"+)++// persistVersion is what writeBindings writes and the only one loadBindings reads.+const persistVersion = 1++type persistFile struct {+ Version int `json:"version"`+ Bindings []bindingInfo `json:"bindings"`+}++func loadBindings(path string) ([]bindingInfo, error) {+ if path == "" {+ return nil, nil+ }+ b, err := os.ReadFile(path)+ if errors.Is(err, fs.ErrNotExist) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }+ var f persistFile+ if err := json.Unmarshal(b, &f); err != nil {+ return nil, err+ }+ if f.Version != persistVersion {+ logWarn("bindings file is of another version; starting empty", "version", f.Version)+ return nil, nil+ }+ return f.Bindings, nil+}++func writeBindings(path string, entries []bindingInfo) error {+ b, err := json.Marshal(persistFile{Version: persistVersion, Bindings: entries})+ if err != nil {+ return err+ }+ tmp, err := os.CreateTemp(filepath.Dir(path), ".bindings-*.json")+ if err != nil {+ return err+ }+ defer os.Remove(tmp.Name()) // no-op after a successful rename+ if _, err := tmp.Write(b); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Chmod(0o600); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Sync(); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Close(); err != nil {+ return err+ }+ return os.Rename(tmp.Name(), path)+}++// persister writes the table whenever it is marked dirty, off the request path.+type persister struct {+ path string+ snapshot func() []bindingInfo+ kick chan struct{}+ stop chan struct{}+ done chan struct{}+ once sync.Once+}++func newPersister(path string, snapshot func() []bindingInfo) *persister {+ return &persister{path: path, snapshot: snapshot, kick: make(chan struct{}, 1), stop: make(chan struct{}), done: make(chan struct{})}+}++func (p *persister) markDirty() {+ select {+ case p.kick <- struct{}{}:+ default:+ }+}++func (p *persister) run() {+ defer close(p.done)+ for {+ select {+ case <-p.kick:+ p.flush()+ case <-p.stop:+ select {+ case <-p.kick:+ p.flush()+ default:+ }+ return+ }+ }+}++func (p *persister) flush() {+ if p.path == "" {+ return+ }+ if err := writeBindings(p.path, p.snapshot()); err != nil {+ logWarn("bindings write failed", "error", err.Error())+ }+}++// close writes any pending change and stops the goroutine.+func (p *persister) close() {+ p.once.Do(func() { close(p.stop) })+ <-p.done+}diff --git a/computer/modelproxy/profile.go b/computer/modelproxy/profile.gonew file mode 100644index 00000000..b5803e78--- /dev/null+++ b/computer/modelproxy/profile.go@@ -0,0 +1,341 @@+// Profiles: everything the proxy knows about an upstream is configuration.+// A profile names an upstream, the routes a bound runner may call on it, the+// headers that carry the binding's variables, and what to report back to the+// binder. The files are JSON objects of name → profile in -profiles+// (/etc/oc-modelproxy/profiles.d/*.json), read once at start.+//+// {+// "example": {+// "upstream": "https://api.example.com/base",+// "routes": {+// "POST /v1/messages": { "require": { "User-Agent": "my-cli/*" } },+// "GET /v1/models": { "to": "/models", "default": { "Accept": "application/json" } },+// "WS /v1/responses": {}+// },+// "set": { "Authorization": "Bearer {token}" },+// "remove": [ "X-Forwarded-*", "Cookie" ],+// "report": [ "x-ratelimit-*", "retry-after" ],+// "concurrency": { "key": "{account}", "limit": 8 },+// "harness": { "claude": { "tokenEnv": "ANTHROPIC_AUTH_TOKEN" } }+// }+// }+//+// Fields (README.md has the full reference):+// - upstream: an https base URL; its path, if any, prefixes every route's.+// - routes: the allowlist, `METHOD path` or `WS path` (a WebSocket). Each+// may set `to` (the upstream path), `name` (its telemetry name), `format`+// (`responses`: its stream is read for telemetry, responses.go),+// `require` (header globs that must match, else 403), and `set` /+// `default` headers for that route.+// - set / remove: request headers. Values may use {var} from the binding.+// - report: response header globs sent to the binder with each `observed`.+// - concurrency: a cap across callers whose bindings expand `key` alike.+// - websocket: false refuses WS routes with 426.+// - harness: per harness name, an object passed to the binder in `hello`+// and not read here.+// - errors: texts replacing the proxy's own (refuse.go).+//+// Invariants:+// - A profile's requests only ever go to its own upstream, through its own+// transport and ReverseProxy.+// - Every variable a profile uses must be in a binding to it (bindings.go).+// - A file with an unknown field, or a profile that fails a check, stops+// the proxy at start: nothing is half-loaded. `-check` runs the same+// load and nothing else.+package main++import (+ "bytes"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httputil"+ "net/textproto"+ "net/url"+ "os"+ "path/filepath"+ "slices"+ "sort"+ "strings"+)++type profileJSON struct {+ Upstream string `json:"upstream"`+ Routes map[string]routeJSON `json:"routes"`+ Set map[string]string `json:"set"`+ Remove []string `json:"remove"`+ Report []string `json:"report"`+ Concurrency *concurrencyJSON `json:"concurrency"`+ WebSocket *bool `json:"websocket"`+ Harness map[string]any `json:"harness"`+ Errors map[string]string `json:"errors"`+}++type routeJSON struct {+ To string `json:"to"`+ Name string `json:"name"`+ Format string `json:"format"`+ Require map[string]string `json:"require"`+ Set map[string]string `json:"set"`+ Default map[string]string `json:"default"`+}++type concurrencyJSON struct {+ Key string `json:"key"`+ Limit int `json:"limit"`+}++// profile is a loaded profile and its runtime: the upstream's transport, its+// ReverseProxy and its concurrency counter (outbound.go).+type profile struct {+ name string+ url *url.URL+ routes map[string]*routeSpec // "POST /v1/messages", "WS /v1/responses"+ set []headerValue+ remove []string // lower-case globs of header names+ report []string+ concKey *template+ ws bool+ vars []string // every variable the profile uses, sorted+ harness map[string]any // as written; never read here+ text texts++ up *upstream+ rp *httputil.ReverseProxy+ perKey *inflight+}++// routeSpec is one allowlisted endpoint of a profile.+type routeSpec struct {+ name string // telemetry name+ ws bool+ to string // the upstream path; "" = the request's+ responses bool // format responses: its stream is read for telemetry (responses.go)+ respName string // WS: the name its responses are reported under+ require []headerValue+ set []headerValue+ def []headerValue+}++// headerValue is a canonical header name with a template (set, default) or+// a lower-case glob as its literal (require).+type headerValue struct {+ name string+ value *template+}++// profiles is the loaded set, fixed for the process's life.+type profiles struct {+ byName map[string]*profile+ sorted []*profile // by name+}++func (ps *profiles) get(name string) *profile { return ps.byName[name] }++// loadProfiles reads every *.json in dir. A name defined twice is an error.+func loadProfiles(dir string) (*profiles, error) {+ files, err := filepath.Glob(filepath.Join(dir, "*.json"))+ if err != nil {+ return nil, err+ }+ sort.Strings(files)+ raw := map[string]profileJSON{}+ for _, f := range files {+ b, err := os.ReadFile(f)+ if err != nil {+ return nil, err+ }+ one, err := parseProfiles(b)+ if err != nil {+ return nil, fmt.Errorf("%s: %w", f, err)+ }+ for name, p := range one {+ if _, dup := raw[name]; dup {+ return nil, fmt.Errorf("%s: profile %q is already defined", f, name)+ }+ raw[name] = p+ }+ }+ if len(raw) == 0 {+ return nil, fmt.Errorf("no profiles in %s", dir)+ }+ return compileProfiles(raw)+}++func parseProfiles(b []byte) (map[string]profileJSON, error) {+ dec := json.NewDecoder(bytes.NewReader(b))+ dec.DisallowUnknownFields()+ var out map[string]profileJSON+ if err := dec.Decode(&out); err != nil {+ return nil, err+ }+ return out, nil+}++func compileProfiles(raw map[string]profileJSON) (*profiles, error) {+ ps := &profiles{byName: map[string]*profile{}}+ for name, j := range raw {+ p, err := compileProfile(name, j)+ if err != nil {+ return nil, fmt.Errorf("profile %q: %w", name, err)+ }+ ps.byName[name] = p+ ps.sorted = append(ps.sorted, p)+ }+ slices.SortFunc(ps.sorted, func(a, b *profile) int { return strings.Compare(a.name, b.name) })+ return ps, nil+}++func compileProfile(name string, j profileJSON) (*profile, error) {+ if !isName(name, "-_") {+ return nil, fmt.Errorf("the name must be letters, digits, - or _")+ }+ u, err := url.Parse(j.Upstream)+ if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {+ return nil, fmt.Errorf("upstream must be an https URL without a query")+ }+ u.Path = strings.TrimSuffix(u.Path, "/")+ p := &profile{name: name, url: u, routes: map[string]*routeSpec{}, ws: j.WebSocket == nil || *j.WebSocket,+ harness: j.Harness, text: defaultTexts}+ if p.harness == nil {+ p.harness = map[string]any{}+ }+ for h, v := range p.harness {+ if _, ok := v.(map[string]any); !ok || !isName(h, "-_") {+ return nil, fmt.Errorf("harness: %q must be a name with an object", h)+ }+ }+ used := map[string]bool{}+ if p.set, err = headerTemplates(j.Set, used); err != nil {+ return nil, fmt.Errorf("set: %w", err)+ }+ if p.remove, err = headerGlobs(j.Remove); err != nil {+ return nil, fmt.Errorf("remove: %w", err)+ }+ if p.report, err = headerGlobs(j.Report); err != nil {+ return nil, fmt.Errorf("report: %w", err)+ }+ if c := j.Concurrency; c != nil {+ if c.Limit <= 0 {+ return nil, fmt.Errorf("concurrency: limit must be positive")+ }+ if p.concKey, err = parseTemplate(c.Key, used); err != nil || len(p.concKey.vars) == 0 {+ return nil, fmt.Errorf("concurrency: key must name a {variable}")+ }+ p.perKey = newInflight(c.Limit)+ }+ if len(j.Routes) == 0 {+ return nil, fmt.Errorf("no routes")+ }+ for key, rj := range j.Routes {+ rs, err := compileRoute(key, rj, used)+ if err != nil {+ return nil, fmt.Errorf("route %q: %w", key, err)+ }+ p.routes[key] = rs+ }+ for key, rs := range p.routes {+ if !rs.ws {+ continue+ }+ rs.respName = strings.TrimSuffix(rs.name, "_ws")+ if post := p.routes["POST"+strings.TrimPrefix(key, "WS")]; post != nil {+ rs.respName = post.name+ }+ }+ if err := p.text.override(j.Errors); err != nil {+ return nil, err+ }+ p.vars = make([]string, 0, len(used))+ for v := range used {+ p.vars = append(p.vars, v)+ }+ sort.Strings(p.vars)+ return p, nil+}++func compileRoute(key string, j routeJSON, used map[string]bool) (*routeSpec, error) {+ method, path, ok := strings.Cut(key, " ")+ if !ok || !strings.HasPrefix(path, "/") || strings.ContainsAny(path, " ?#") {+ return nil, fmt.Errorf("write it as `METHOD /path`")+ }+ switch method {+ case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, "WS":+ default:+ return nil, fmt.Errorf("unknown method %q", method)+ }+ rs := &routeSpec{ws: method == "WS", to: j.To, name: j.Name}+ if rs.to != "" && (!strings.HasPrefix(rs.to, "/") || strings.ContainsAny(rs.to, " ?#")) {+ return nil, fmt.Errorf("`to` must be a path")+ }+ if rs.name == "" {+ rs.name = routeName(path)+ if rs.ws {+ rs.name += "_ws"+ }+ }+ if !isName(rs.name, "_") {+ return nil, fmt.Errorf("name must be letters, digits or _")+ }+ switch {+ case j.Format == "responses", j.Format == "" && rs.ws: // a tunnel reads Responses events (websocket.go)+ rs.responses = true+ case j.Format != "":+ return nil, fmt.Errorf("format: the only one is responses")+ }+ for name, glob := range j.Require {+ if !validHeaderName(name) || glob == "" {+ return nil, fmt.Errorf("require: bad header %q", name)+ }+ rs.require = append(rs.require, headerValue{name: textproto.CanonicalMIMEHeaderKey(name), value: &template{parts: []string{strings.ToLower(glob)}}})+ }+ sortHeaders(rs.require)+ var err error+ if rs.set, err = headerTemplates(j.Set, used); err != nil {+ return nil, fmt.Errorf("set: %w", err)+ }+ if rs.def, err = headerTemplates(j.Default, used); err != nil {+ return nil, fmt.Errorf("default: %w", err)+ }+ return rs, nil+}++// routeName is a path's last element, as a telemetry name.+func routeName(path string) string {+ last := path[strings.LastIndexByte(path, '/')+1:]+ b := []byte(strings.ToLower(last))+ for i, c := range b {+ if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9') {+ b[i] = '_'+ }+ }+ if len(b) == 0 {+ return "root"+ }+ return string(b)+}++// route is the profile's route for r (nil = not allowed). The path must+// match exactly; the query is not looked at. A request to upgrade can only+// match a WS route.+func (p *profile) route(r *http.Request, upgrade bool) *routeSpec {+ if upgrade {+ if r.Method != http.MethodGet {+ return nil+ }+ return p.routes["WS "+r.URL.Path]+ }+ return p.routes[r.Method+" "+r.URL.Path]+}++// requireOK: every required header has a value, or a comma-separated item of+// one (parameters after `;` ignored), matching its glob, and reaches the+// upstream: not one the caller's Connection header has stripped on the way.+func (rs *routeSpec) requireOK(h http.Header) bool {+ for _, req := range rs.require {+ if !headerMatches(h[req.name], req.value.parts[0]) || connectionLists(h, req.name) {+ return false+ }+ }+ return true+}diff --git a/computer/modelproxy/profile_policy_test.go b/computer/modelproxy/profile_policy_test.gonew file mode 100644index 00000000..9df3ef2c--- /dev/null+++ b/computer/modelproxy/profile_policy_test.go@@ -0,0 +1,385 @@+package main++import (+ "context"+ "io"+ "net/http"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// A profile with a base path, `to`, a second variable, `remove` and fixed+// headers: the request reaches its own upstream so shaped, the body and+// every other header untouched, and no other profile's upstream is contacted.+func TestAltRewrite(t *testing.T) {+ var mHits, aHits atomic.Int64+ got := make(chan seen, 1)+ h := newHarness(t, recordingUpstream(&mHits, make(chan seen, 1)), harnessOpts{alt: recordingUpstream(&aHits, got)})+ k := h.dialControl()+ b := h.bindAltReady(k, altCaller, "s1", "secret-token", "fpC", altAccount)+ if b["caller"] != altCaller || b["sessionKey"] != "s1" || b["key"] != "fpC" || b["profile"] != nil || b["vars"] != nil {+ t.Fatalf("bound %v", b)+ }++ req := h.responsesReq(context.Background())+ for _, kv := range [][2]string{+ {"X-Forwarded-For", "10.0.0.9"}, {"X-Forwarded-Host", "evil"}, {"X-Forwarded-Port", "8080"},+ {"X-Forwarded-Client-Cert", "x"}, {"Forwarded", "for=10.0.0.9"}, {"X-Real-Ip", "10.0.0.9"}, {"Cookie", "a=b"},+ {"X-Private-Session", "s1"}, {"X-Api-Key", testPlaceholder}, {"X-Account", "someone-else"}, {"Originator", "its-own"},+ {"X-Turn-Metadata", `{"turn":1}`},+ } {+ req.Header.Set(kv[0], kv[1])+ }+ res, err := h.client(altCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ io.ReadAll(res.Body)+ res.Body.Close()+ if res.StatusCode != 200 {+ t.Fatalf("status %d", res.StatusCode)+ }+ s := <-got+ if s.uri != "/base/x/responses" || !s.tls || s.host != h.alt.Listener.Addr().String() {+ t.Fatalf("upstream saw uri=%q host=%q tls=%v", s.uri, s.host, s.tls)+ }+ want := map[string]string{+ "Authorization": "Bearer secret-token", "X-Account": altAccount, "Originator": "fixed",+ "User-Agent": "test-client/1.0", "Accept": "text/event-stream", "Session-Id": "sess-1", "X-Turn-Metadata": `{"turn":1}`,+ }+ for k, v := range want {+ if got := s.header.Values(k); len(got) != 1 || got[0] != v {+ t.Errorf("%s = %q, want %q", k, got, v)+ }+ }+ for name := range s.header {+ if strings.HasPrefix(name, "X-Forwarded-") || strings.HasPrefix(name, "X-Private-") {+ t.Errorf("%s leaked upstream", name)+ }+ }+ for _, name := range []string{"Forwarded", "X-Real-Ip", "Cookie", "X-Api-Key"} {+ if v := s.header.Values(name); len(v) != 0 {+ t.Errorf("%s leaked upstream: %q", name, v)+ }+ }+ if s.body != `{"model":"m","stream":true,"input":[]}` {+ t.Fatalf("body %q", s.body)+ }+ if mHits.Load() != 0 {+ t.Fatalf("another profile's upstream contacted %d times", mHits.Load())+ }+ e := k.waitFor(isEvent("model.request"))+ d := evData(e)+ if e["profile"] != altProfile || d["route"] != "responses" || d["status"] != float64(200) || d["key"] != "fpC" {+ t.Fatalf("event %v", e)+ }+ if strings.Contains(toJSON(e), "secret-token") || strings.Contains(toJSON(e), altAccount) {+ t.Fatalf("a variable in an event: %v", e)+ }+}++// `to` keeps the query; a route's `default` applies only when the header is absent.+func TestAltQueryAndDefault(t *testing.T) {+ var hits atomic.Int64+ got := make(chan seen, 1)+ h := newHarness(t, recordingUpstream(&hits, nil), harnessOpts{alt: recordingUpstream(&hits, got)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ for _, accept := range []string{"", "text/plain"} {+ req, _ := http.NewRequest(http.MethodGet, h.apiURL+"/v1/models?client_version=1.2.3", nil)+ req.Header.Set("Authorization", placeholderAuth)+ want := "application/json"+ if accept != "" {+ req.Header.Set("Accept", accept)+ want = accept+ }+ res, err := h.client(altCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ res.Body.Close()+ if s := <-got; res.StatusCode != 200 || s.uri != "/base/x/models?client_version=1.2.3" || s.header.Get("Accept") != want {+ t.Fatalf("status %d uri %q accept %q", res.StatusCode, s.uri, s.header.Get("Accept"))+ }+ }+}++// A binding only reaches its own profile's routes: another profile's is a+// 404 like any path off the allowlist, and no upstream is contacted.+func TestOtherProfilesRoute(t *testing.T) {+ var mHits, aHits atomic.Int64+ h := newHarness(t, recordingUpstream(&mHits, nil), harnessOpts{alt: recordingUpstream(&aHits, nil)})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fpA")+ h.bindAltReady(k, altCaller, "s2", "tok", "fpC", altAccount)+ for _, c := range []struct {+ caller, prof string+ req *http.Request+ }{+ {testCaller, mainProfile, h.responsesReq(context.Background())},+ {altCaller, altProfile, h.messagesReq(context.Background())},+ } {+ res, err := h.client(c.caller).Do(c.req)+ if err != nil {+ t.Fatal(err)+ }+ e := decodeAPIError(t, res)+ res.Body.Close()+ if res.StatusCode != 404 || e.Error.Type != "not_found_error" {+ t.Fatalf("%s: %d %+v", c.caller, res.StatusCode, e)+ }+ ev := k.waitFor(isEvent("model.denied"))+ if d := evData(ev); ev["profile"] != c.prof || d["reason"] != "route" || d["route"] != "other" || ev["session_key"] == nil || ev["error_type"] != nil {+ t.Fatalf("%s: event %v", c.caller, ev)+ }+ }+ if mHits.Load() != 0 || aHits.Load() != 0 {+ t.Fatalf("upstream contacted: %d, %d", mHits.Load(), aHits.Load())+ }+}++// `require`: every header must match, as a whole value or as one item of a+// list, parameters ignored; else 403 with the profile's own text.+func TestAltRequire(t *testing.T) {+ var hits atomic.Int64+ h := newHarness(t, recordingUpstream(&hits, nil), harnessOpts{alt: recordingUpstream(&hits, nil)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ for _, mut := range []func(*http.Request){+ func(r *http.Request) { r.Header.Del("Accept") },+ func(r *http.Request) { r.Header.Set("Accept", "application/json") },+ func(r *http.Request) { r.Header.Set("Content-Type", "text/plain") },+ } {+ req := h.responsesReq(context.Background())+ mut(req)+ res, err := h.client(altCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ e := decodeAPIError(t, res)+ res.Body.Close()+ if res.StatusCode != 403 || e.Error.Message != altShape {+ t.Fatalf("%d %+v", res.StatusCode, e)+ }+ if ev := k.waitFor(isEvent("model.denied")); ev["profile"] != altProfile || evData(ev)["reason"] != "require" {+ t.Fatalf("event %v", ev)+ }+ }+ if hits.Load() != 0 {+ t.Fatalf("upstream contacted %d times", hits.Load())+ }+ req := h.responsesReq(context.Background())+ req.Header.Set("Accept", "application/json, Text/Event-Stream;q=0.9")+ req.Header.Set("Content-Type", "application/json; charset=utf-8")+ res, err := h.client(altCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ res.Body.Close()+ if res.StatusCode != 200 {+ t.Fatalf("list item with parameters: %d", res.StatusCode)+ }+}++// A protocol upgrade is 426 anywhere but a profile's WS route, whatever the+// method, with model.denied error_type websocket; it never reaches upstream.+// A handshake on the WS route that fails its `require` is a 426 too (reason+// shape): the client goes on over HTTP.+func TestUpgradeRefused(t *testing.T) {+ var hits atomic.Int64+ h := newHarness(t, recordingUpstream(&hits, nil), harnessOpts{alt: recordingUpstream(&hits, nil)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ h.bindReady(k, testCaller, "s2", "tokA", "fpA")+ upgrade := func(r *http.Request, conn string) *http.Request {+ r.Header.Set("Connection", conn)+ r.Header.Set("Upgrade", "websocket")+ return r+ }+ get, _ := http.NewRequest(http.MethodGet, h.apiURL+"/v1/responses", nil)+ get.Header.Set("Sec-Websocket-Version", "13")+ get.Header.Set("Sec-Websocket-Key", wsNonce)+ for _, c := range []struct {+ caller string+ req *http.Request+ prof string+ status int+ reason string+ errType any+ }{+ {altCaller, upgrade(h.responsesReq(context.Background()), "keep-alive, Upgrade"), altProfile, 426, "websocket", "websocket"},+ {altCaller, upgrade(get, "Upgrade"), altProfile, 426, "require", nil},+ {testCaller, upgrade(h.messagesReq(context.Background()), "Upgrade"), mainProfile, 426, "websocket", "websocket"},+ } {+ res, err := h.client(c.caller).Do(c.req)+ if err != nil {+ t.Fatal(err)+ }+ e := decodeAPIError(t, res)+ res.Body.Close()+ if res.StatusCode != c.status || res.Header.Get("X-Should-Retry") != "false" || !strings.HasPrefix(e.Error.Message, wsUseHTTP) {+ t.Fatalf("%s %s: %d %v %+v", c.req.Method, c.req.URL.Path, res.StatusCode, res.Header, e)+ }+ ev := k.waitFor(isEvent("model.denied"))+ if ev["error_type"] != c.errType || ev["profile"] != c.prof || evData(ev)["reason"] != c.reason {+ t.Fatalf("%s: event %v", c.req.URL.Path, ev)+ }+ }+ if hits.Load() != 0 {+ t.Fatalf("upstream contacted %d times", hits.Load())+ }+}++// A bare Upgrade header, without Connection: upgrade, asks for no switch+// (RFC 9110 §7.8): the request is served and the header never reaches upstream.+func TestBareUpgradeHeader(t *testing.T) {+ got := make(chan seen, 1)+ h := newHarness(t, recordingUpstream(new(atomic.Int64), got), harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tokA", "fpA")+ req := h.messagesReq(context.Background())+ req.Header.Set("Upgrade", "websocket")+ res, err := h.client(testCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ if s := <-got; res.StatusCode != 200 || s.header.Get("Upgrade") != "" {+ t.Fatalf("%d, upstream saw Upgrade %q", res.StatusCode, s.header.Get("Upgrade"))+ }+}++// `concurrency` is shared by every caller whose binding expands the key+// alike; another value, and other profiles, are not counted against it.+func TestConcurrencyCap(t *testing.T) {+ const caller2, caller3 = "alt002", "alt003"+ g := &gatedUpstream{started: make(chan string, 8), release: make(chan struct{})}+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{alt: g, perKey: 1})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tokA", "fpA", altAccount)+ h.bindAltReady(k, caller2, "s2", "tokA", "fpA", altAccount)+ h.bindAltReady(k, caller3, "s3", "tokB", "fpB", "acct-other")++ done := make(chan int, 2)+ stream := func(caller string) {+ res, err := h.client(caller).Do(h.responsesReq(context.Background()))+ if err != nil {+ t.Error(err)+ done <- 0+ return+ }+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ done <- res.StatusCode+ }+ go stream(altCaller)+ <-g.started+ res, err := h.client(caller2).Do(h.responsesReq(context.Background()))+ if err != nil {+ t.Fatal(err)+ }+ e := decodeAPIError(t, res)+ res.Body.Close()+ if res.StatusCode != 429 || res.Header.Get("Retry-After") != "1" || e.Error.Type != "rate_limit_error" {+ t.Fatalf("second stream on the key: %d %+v", res.StatusCode, e)+ }+ ev := k.waitFor(isEvent("model.denied"))+ if ev["error_type"] != "concurrency" || ev["profile"] != altProfile || evData(ev)["reason"] != "concurrency_cap" {+ t.Fatalf("event %v", ev)+ }+ if strings.Contains(toJSON(ev), altAccount) {+ t.Fatalf("a variable in an event: %v", ev)+ }+ go stream(caller3) // another value of the key: not counted+ <-g.started+ close(g.release)+ for range 2 {+ if st := <-done; st != 200 {+ t.Fatalf("status %d", st)+ }+ }+ // The slot is free again once the stream ended.+ go stream(caller2)+ if st := <-done; st != 200 {+ t.Fatalf("after release: %d", st)+ }+}++// A bind must carry every variable its profile uses.+func TestBindNeedsEveryVariable(t *testing.T) {+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{})+ k := h.dialControl()+ k.bindAlt(altCaller, "s1", "tok", "fp", "")+ if m := k.waitFor(isT("refused")); m["code"] != refuseMissingVar || m["message"] != "missing accountId" {+ t.Fatalf("refused %v", m)+ }+ if ev := k.waitFor(isEvent("model.binding")); ev["outcome"] != "failed" || evData(ev)["code"] != refuseMissingVar || ev["profile"] != nil {+ t.Fatalf("event %v", ev)+ }+ k.send(map[string]any{"t": "bind", "caller": altCaller, "sessionKey": "s1", "profile": "nope", "vars": map[string]string{"token": "t"}, "key": "f"})+ if m := k.waitFor(isT("refused")); m["code"] != refuseUnknownProfile {+ t.Fatalf("refused %v", m)+ }+ if ev := k.waitFor(isEvent("model.binding")); ev["profile"] != nil || evData(ev)["code"] != refuseUnknownProfile {+ t.Fatalf("event %v", ev)+ }+}++// A rebind to another profile applies at once: the stream in flight ends+// on the upstream and credential it started with, and the caller's next+// request reaches the new profile's upstream.+func TestRebindToAnotherProfile(t *testing.T) {+ g := &gatedUpstream{started: make(chan string, 4), release: make(chan struct{})}+ var aHits atomic.Int64+ h := newHarness(t, g, harnessOpts{alt: recordingUpstream(&aHits, nil)})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fpA")++ done := make(chan int, 1)+ go func() {+ res, err := h.client(testCaller).Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Error(err)+ done <- 0+ return+ }+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ done <- res.StatusCode+ }()+ <-g.started+ h.bindAltReady(k, testCaller, "s1", "tokC", "fpC", altAccount) // `bound` under the live stream++ res, err := h.client(testCaller).Do(h.responsesReq(context.Background()))+ if err != nil {+ t.Fatal(err)+ }+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ if res.StatusCode != 200 || aHits.Load() != 1 {+ t.Fatalf("after the rebind: %d, alt hits %d", res.StatusCode, aHits.Load())+ }+ close(g.release)+ if code := <-done; code != 200 || len(g.bearers) != 1 {+ t.Fatalf("the stream in flight: %d, main hits %d", code, len(g.bearers))+ }+}++// A known caller whose bind has not arrived gets the not-ready text of the+// profile it waits for (the restored one).+func TestNotReadyNamesBoundProfile(t *testing.T) {+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{hold: 50 * time.Millisecond,+ restore: []bindingInfo{{Caller: altCaller, SessionKey: "s1", Mode: modeProfile, Profile: altProfile, Key: "fpC"}}})+ res, err := h.client(altCaller).Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Fatal(err)+ }+ e := decodeAPIError(t, res)+ res.Body.Close()+ if res.StatusCode != http.StatusServiceUnavailable || e.Error.Message != altNotReady {+ t.Fatalf("%d %+v", res.StatusCode, e)+ }+}diff --git a/computer/modelproxy/profile_test.go b/computer/modelproxy/profile_test.gonew file mode 100644index 00000000..47576494--- /dev/null+++ b/computer/modelproxy/profile_test.go@@ -0,0 +1,179 @@+package main++import (+ "net/http"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++// The shipped profiles load from a directory as the proxy loads them.+func TestShippedProfiles(t *testing.T) {+ ps, err := loadProfiles("profiles")+ if err != nil {+ t.Fatal(err)+ }+ var names []string+ for _, p := range ps.sorted {+ names = append(names, p.name)+ if len(p.vars) != 1 || p.vars[0] != "token" || p.perKey != nil || len(p.harness) != 1 {+ t.Errorf("%s: vars %v harness %v", p.name, p.vars, p.harness)+ }+ }+ if got := strings.Join(names, " "); got != "anthropic-key claude-oauth openai-key openrouter" {+ t.Fatalf("profiles %q", got)+ }+ or := ps.get("openrouter")+ if or.url.Host != "openrouter.ai" || or.url.Path != "/api" {+ t.Fatalf("openrouter upstream %v", or.url)+ }+ oa := ps.get("openai-key")+ if ws := oa.routes["WS /v1/responses"]; ws == nil || !ws.ws || ws.name != "responses_ws" || ws.respName != "responses" || !ws.responses {+ t.Fatalf("WS route %+v", ws)+ }+ if r := oa.routes["POST /v1/responses"]; !r.responses || r.name != "responses" || oa.routes["GET /v1/models"].responses {+ t.Fatalf("formats %+v", r)+ }+ if r := ps.get("claude-oauth").routes["POST /v1/messages/count_tokens"]; r.name != "count_tokens" || len(r.require) != 3 || r.responses {+ t.Fatalf("route %+v", r)+ }+}++func TestLoadProfilesErrors(t *testing.T) {+ const ok = `{"upstream":"https://a.example","routes":{"POST /v1/messages":{}}}`+ write := func(files map[string]string) string {+ dir := t.TempDir()+ for name, body := range files {+ if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o600); err != nil {+ t.Fatal(err)+ }+ }+ return dir+ }+ for _, c := range []struct {+ name, want string+ files map[string]string+ }{+ {"empty directory", "no profiles", nil},+ {"only other files", "no profiles", map[string]string{"a.txt": "{}"}},+ {"a name twice", "already defined", map[string]string{"a.json": `{"p":` + ok + `}`, "b.json": `{"p":` + ok + `}`}},+ {"an unknown field", "unknown field", map[string]string{"a.json": `{"p":{"upstream":"https://a.example","routes":{"POST /x":{}},"sets":{}}}`}},+ {"an unknown route field", "unknown field", map[string]string{"a.json": `{"p":{"upstream":"https://a.example","routes":{"POST /x":{"too":"/y"}}}}`}},+ {"not JSON", "a.json", map[string]string{"a.json": `{`}},+ {"a bad profile", `profile "p"`, map[string]string{"a.json": `{"p":{"upstream":"http://a.example","routes":{"POST /x":{}}}}`}},+ } {+ if _, err := loadProfiles(write(c.files)); err == nil || !strings.Contains(err.Error(), c.want) {+ t.Errorf("%s: %v, want %q", c.name, err, c.want)+ }+ }+ ps, err := loadProfiles(write(map[string]string{"a.json": `{"p":` + ok + `}`, "b.json": `{"q":` + ok + `}`}))+ if err != nil || len(ps.sorted) != 2 {+ t.Fatalf("two files: %v", err)+ }+}++func TestCompileProfileErrors(t *testing.T) {+ routes := map[string]routeJSON{"POST /v1/messages": {}}+ base := func(mut func(*profileJSON)) profileJSON {+ p := profileJSON{Upstream: "https://a.example/base/", Routes: routes}+ mut(&p)+ return p+ }+ route := func(key string, r routeJSON) profileJSON {+ return profileJSON{Upstream: "https://a.example", Routes: map[string]routeJSON{key: r}}+ }+ for _, c := range []struct {+ name, want string+ p profileJSON+ }{+ {"plain http", "https URL", base(func(p *profileJSON) { p.Upstream = "http://a.example" })},+ {"a query", "https URL", base(func(p *profileJSON) { p.Upstream = "https://a.example/?k=v" })},+ {"credentials in the URL", "https URL", base(func(p *profileJSON) { p.Upstream = "https://u:[email protected]" })},+ {"no host", "https URL", base(func(p *profileJSON) { p.Upstream = "https://" })},+ {"no routes", "no routes", base(func(p *profileJSON) { p.Routes = nil })},+ {"a bad set header", "set: bad header", base(func(p *profileJSON) { p.Set = map[string]string{"Bad Name": "v"} })},+ {"a set value with a newline", "not a header value", base(func(p *profileJSON) { p.Set = map[string]string{"X-A": "v\r\nX-B: w"} })},+ {"an open variable", "write variables as {name}", base(func(p *profileJSON) { p.Set = map[string]string{"X-A": "{token"} })},+ {"an empty variable", "write variables as {name}", base(func(p *profileJSON) { p.Set = map[string]string{"X-A": "{}"} })},+ {"a stray brace", "unmatched }", base(func(p *profileJSON) { p.Set = map[string]string{"X-A": "a}"} })},+ {"a bad remove glob", "remove: bad header glob", base(func(p *profileJSON) { p.Remove = []string{"X Forwarded"} })},+ {"a bad report glob", "report: bad header glob", base(func(p *profileJSON) { p.Report = []string{""} })},+ {"concurrency without a limit", "limit must be positive", base(func(p *profileJSON) { p.Concurrency = &concurrencyJSON{Key: "{a}"} })},+ {"concurrency on a constant", "key must name a {variable}", base(func(p *profileJSON) { p.Concurrency = &concurrencyJSON{Key: "all", Limit: 2} })},+ {"an unknown error text", `errors: unknown key "nope"`, base(func(p *profileJSON) { p.Errors = map[string]string{"nope": "x"} })},+ {"a harness that is no object", "harness:", base(func(p *profileJSON) { p.Harness = map[string]any{"claude": "x"} })},+ {"a route without a method", "METHOD /path", route("/v1/messages", routeJSON{})},+ {"a relative route", "METHOD /path", route("POST v1/messages", routeJSON{})},+ {"a route with a query", "METHOD /path", route("POST /v1/messages?x=1", routeJSON{})},+ {"an unknown method", `unknown method "post"`, route("post /v1/messages", routeJSON{})},+ {"a relative to", "`to` must be a path", route("POST /a", routeJSON{To: "b"})},+ {"a to with a query", "`to` must be a path", route("POST /a", routeJSON{To: "/b?x=1"})},+ {"a bad name", "name must be", route("POST /a", routeJSON{Name: "a-b"})},+ {"a bad format", "format: the only one is responses", route("POST /a", routeJSON{Format: "chat"})},+ {"an empty require", "require: bad header", route("POST /a", routeJSON{Require: map[string]string{"X-A": ""}})},+ {"a bad default", "default: bad header", route("POST /a", routeJSON{Default: map[string]string{"": "v"}})},+ } {+ if _, err := compileProfile("p", c.p); err == nil || !strings.Contains(err.Error(), c.want) {+ t.Errorf("%s: %v, want %q", c.name, err, c.want)+ }+ }+ if _, err := compileProfile("bad name", base(func(*profileJSON) {})); err == nil {+ t.Error("a name with a space compiled")+ }+ p, err := compileProfile("p", base(func(p *profileJSON) {+ p.Set = map[string]string{"x-a": "{b} and {a}"}+ p.Routes = map[string]routeJSON{"POST /v1/chat.completions": {Set: map[string]string{"X-C": "{c}"}}, "GET /": {Name: "home", Format: "responses"}}+ p.Errors = map[string]string{"notReady": "wait"}+ }))+ if err != nil {+ t.Fatal(err)+ }+ if p.url.Path != "/base" || strings.Join(p.vars, ",") != "a,b,c" || p.set[0].name != "X-A" || !p.ws ||+ p.routes["POST /v1/chat.completions"].name != "chat_completions" || !p.routes["GET /"].responses ||+ p.text.notReady != "wait" || p.text.refused != defaultTexts.refused {+ t.Fatalf("profile %+v", p)+ }+ if got := p.set[0].value.expand(map[string]string{"a": "1", "b": "2"}); got != "2 and 1" {+ t.Fatalf("expand %q", got)+ }+}++func TestGlobMatch(t *testing.T) {+ for _, c := range []struct {+ glob, s string+ want bool+ }{+ {"cli", "CLI", true}, {"cli", "cli2", false}, {"claude-cli/*", "Claude-CLI/2.1 (x)", true}, {"claude-cli/*", "claude-cli", false},+ {"*", "", true}, {"*-id", "session-id", true}, {"*-id", "id", false}, {"x-*-id", "x-request-id", true}, {"x-*-id", "x-id", false},+ {"a*b*c", "a1b2c", true}, {"a*b*c", "a1c2b", false}, {"a*a", "a", false}, {"x-forwarded-*", "X-Forwarded-For", true},+ } {+ if got := globMatch(c.glob, c.s); got != c.want {+ t.Errorf("globMatch(%q, %q) = %v", c.glob, c.s, got)+ }+ }+}++func TestRequireOK(t *testing.T) {+ p, err := compileProfile("p", profileJSON{Upstream: "https://a.example", Routes: map[string]routeJSON{+ "POST /a": {Require: map[string]string{"user-agent": "My-CLI/*", "Accept": "text/event-stream"}}}})+ if err != nil {+ t.Fatal(err)+ }+ rs := p.routes["POST /a"]+ for _, c := range []struct {+ h http.Header+ want bool+ }{+ {http.Header{"User-Agent": {"my-cli/1.0"}, "Accept": {"text/event-stream"}}, true},+ {http.Header{"User-Agent": {"my-cli/1.0 (a, b)"}, "Accept": {"application/json, text/event-stream;q=0.5"}}, true},+ {http.Header{"User-Agent": {"other", "my-cli/2"}, "Accept": {"TEXT/EVENT-STREAM"}}, true},+ {http.Header{"User-Agent": {"my-cli/1.0"}}, false},+ {http.Header{"User-Agent": {"not-my-cli/1.0"}, "Accept": {"text/event-stream"}}, false},+ {http.Header{"User-Agent": {"my-cli/1.0"}, "Accept": {"text/event-stream-x"}}, false},+ } {+ if got := rs.requireOK(c.h); got != c.want {+ t.Errorf("%v: %v", c.h, got)+ }+ }+}diff --git a/computer/modelproxy/profiles/default.json b/computer/modelproxy/profiles/default.jsonnew file mode 100644index 00000000..842e3d31--- /dev/null+++ b/computer/modelproxy/profiles/default.json@@ -0,0 +1,53 @@+{+ "anthropic-key": {+ "upstream": "https://api.anthropic.com",+ "routes": {+ "POST /v1/messages": {},+ "POST /v1/messages/count_tokens": {}+ },+ "set": { "X-Api-Key": "{token}" },+ "remove": ["Cookie"],+ "report": ["retry-after", "request-id", "anthropic-ratelimit-*"],+ "harness": { "claude": { "tokenEnv": "ANTHROPIC_API_KEY" } }+ },+ "claude-oauth": {+ "upstream": "https://api.anthropic.com",+ "routes": {+ "POST /v1/messages": {+ "require": { "User-Agent": "claude-cli/*", "X-App": "cli", "Anthropic-Beta": "oauth-2025-04-20" }+ },+ "POST /v1/messages/count_tokens": {+ "require": { "User-Agent": "claude-cli/*", "X-App": "cli", "Anthropic-Beta": "oauth-2025-04-20" }+ },+ "GET /api/oauth/usage": { "default": { "Anthropic-Beta": "oauth-2025-04-20" } },+ "GET /api/claude_code/policy_limits": { "default": { "Anthropic-Beta": "oauth-2025-04-20" } }+ },+ "set": { "Authorization": "Bearer {token}" },+ "remove": ["Cookie"],+ "report": ["retry-after", "request-id", "anthropic-ratelimit-*"],+ "harness": { "claude": { "tokenEnv": "CLAUDE_CODE_OAUTH_TOKEN" } }+ },+ "openrouter": {+ "upstream": "https://openrouter.ai/api",+ "routes": {+ "POST /v1/messages": {},+ "POST /v1/messages/count_tokens": {}+ },+ "set": { "Authorization": "Bearer {token}" },+ "remove": ["Cookie"],+ "report": ["retry-after", "x-ratelimit-*"],+ "harness": { "claude": { "tokenEnv": "ANTHROPIC_AUTH_TOKEN" } }+ },+ "openai-key": {+ "upstream": "https://api.openai.com",+ "routes": {+ "POST /v1/responses": { "format": "responses" },+ "WS /v1/responses": {},+ "GET /v1/models": {}+ },+ "set": { "Authorization": "Bearer {token}" },+ "remove": ["Cookie"],+ "report": ["retry-after", "x-request-id", "x-ratelimit-*"],+ "harness": { "codex": {} }+ }+}diff --git a/computer/modelproxy/proxy.go b/computer/modelproxy/proxy.gonew file mode 100644index 00000000..58e4c0a4--- /dev/null+++ b/computer/modelproxy/proxy.go@@ -0,0 +1,331 @@+// The API socket's handler: one request from a model client (Claude Code,+// Codex, anything that speaks to a local base URL), in stages. Each stage+// either refuses the request (refuse.go) or passes it on:+//+// identify the caller carries no credential of its own, only the+// placeholder (401); the connection has a caller+// (connlimit.go; none → 401); the caller is under its+// in-flight cap (-max-inflight-per-caller, held requests+// count; over → 429), so one session cannot queue enough+// hanging requests to starve the others+// awaitBinding the caller's credential, held up to -hold-timeout until+// its bind arrives (lease.go). At the timeout: 503 for a+// caller the binder has named or may yet name (no `synced`+// since the start), 401 for one it has not. A refuse bind →+// 401 with its reason+// matchRoute the profile's route for the method and path (404; a+// protocol upgrade anywhere but a WS route → 426, since+// ReverseProxy would otherwise tunnel it unobserved)+// check the route's `require` (403) and the profile's+// `concurrency` cap (429): header compares only, never+// contacting the upstream+// forward the profile's own ReverseProxy (outbound.go), the response+// streamed with an immediate flush. A request still queued+// for one of the upstream's connections (-max-conns-per-host)+// after -hold-timeout → 503; an upstream that cannot be+// reached is a 502, on the dial's own limits (upstream.go)+//+// When the request ends, whatever stage it reached, finish sends its+// telemetry (telemetry.go). On a request to upgrade, every refusal is a 426+// (websocket.go).+//+// Invariant: a binding's variables are only ever in the lease and the+// outbound headers; never logged, never in an event.+package main++import (+ "context"+ "errors"+ "io"+ "mime"+ "net/http"+ "strings"+ "sync"+ "sync/atomic"+ "time"+)++type ctxKey int++const (+ callerKey ctxKey = iota+ stateKey+)++type Proxy struct {+ bindings *Bindings+ observer *Observer+ out sender+ profiles *profiles+ placeholder string // -placeholder+ hold time.Duration // -hold-timeout+ perCaller *inflight // -max-inflight-per-caller+ wsIdle time.Duration // -ws-idle-timeout+ wsDrain chan struct{} // closed at shutdown (websocket.go)+ wsDrainOnce sync.Once+ wsOpen sync.WaitGroup // open tunnels+ refusals refusalLog+ statsHook func(*reqState)+ now func() time.Time+}++// NewProxy serves ps; every profile's upstream must be set (newOutbound).+func NewProxy(b *Bindings, o *Observer, out sender, ps *profiles, placeholder string, hold time.Duration, perCaller int) *Proxy {+ return &Proxy{bindings: b, observer: o, out: out, profiles: ps, placeholder: placeholder, hold: hold, now: time.Now,+ wsIdle: 5 * time.Minute, wsDrain: make(chan struct{}), perCaller: newInflight(perCaller), refusals: refusalLog{every: refusalEvery}}+}++// activeStreams is every profile's requests in flight upstream.+func (p *Proxy) activeStreams() int64 {+ var n int64+ for _, prof := range p.profiles.sorted {+ n += prof.up.streams.Load()+ }+ return n+}++func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ st := &reqState{start: p.now(), path: r.URL.Path, upgrade: isUpgrade(r.Header)}+ defer p.finish(st, r)++ if !p.identify(w, r, st) {+ return+ }+ defer p.perCaller.leave(st.caller)+ l := p.awaitBinding(w, r, st)+ if l == nil {+ return+ }+ if !p.matchRoute(w, r, st) {+ return+ }+ release, ok := p.check(w, r, st, l)+ if !ok {+ return+ }+ defer release()+ p.forward(w, r, st, l)+}++// identify names the caller and takes its in-flight slot, which the caller+// of identify gives back.+func (p *Proxy) identify(w http.ResponseWriter, r *http.Request, st *reqState) bool {+ if !placeholderOK(r.Header, p.placeholder) {+ st.deny(w, "credentials", http.StatusUnauthorized, "authentication_error", textCredentials)+ return false+ }+ st.caller, _ = r.Context().Value(callerKey).(string)+ if st.caller == "" {+ st.deny(w, "unknown_caller", http.StatusUnauthorized, "authentication_error", textUnknownCaller)+ return false+ }+ if !p.perCaller.enter(st.caller) {+ st.deny(w, "caller_cap", http.StatusTooManyRequests, "rate_limit_error", textCallerCap)+ return false+ }+ return true+}++// awaitBinding leases the caller's credential, holding the request for it.+func (p *Proxy) awaitBinding(w http.ResponseWriter, r *http.Request, st *reqState) *lease {+ l, res := p.bindings.Acquire(r.Context(), st.caller, p.hold)+ st.held = p.now().Sub(st.start)+ switch res {+ case holdNotReady:+ st.holdEnd = "timeout"+ st.prof = p.bindings.knownProfile(st.caller) // the one the caller waits for+ st.deny(w, "", http.StatusServiceUnavailable, "api_error", st.text().notReady)+ return nil+ case holdUnknown:+ st.holdEnd = "timeout"+ st.deny(w, "unbound", http.StatusUnauthorized, "authentication_error", textUnbound)+ return nil+ case holdCanceled:+ st.holdEnd = "cancelled"+ st.cancelled.Store(true)+ return nil+ }+ if l.waited {+ st.holdEnd = "bound"+ }+ st.sessionKey, st.prof, st.key, st.swapped = l.sessionKey, l.cred.prof, l.cred.key, l.swapped+ if l.cred.refuse {+ msg := st.text().refused+ if l.cred.reason != "" {+ msg = st.text().refusedPrefix + l.cred.reason+ }+ st.deny(w, "refused", http.StatusUnauthorized, "authentication_error", msg)+ return nil+ }+ return l+}++// matchRoute finds the request's route on the binding's profile.+func (p *Proxy) matchRoute(w http.ResponseWriter, r *http.Request, st *reqState) bool {+ rs := st.prof.route(r, st.upgrade)+ switch {+ case rs == nil && st.upgrade, rs != nil && rs.ws && !st.prof.ws:+ st.denyAs(w, "websocket", "websocket", http.StatusUpgradeRequired, "invalid_request_error", textNoWebSocket)+ return false+ case rs == nil:+ st.deny(w, "route", http.StatusNotFound, "not_found_error", textNotFound)+ return false+ }+ st.rs, st.route = rs, rs.name+ return true+}++// check applies the route's `require` and the profile's concurrency cap;+// release gives the cap's slot back.+func (p *Proxy) check(w http.ResponseWriter, r *http.Request, st *reqState, l *lease) (release func(), ok bool) {+ prof, rs := st.prof, st.rs+ if (rs.ws && !wsHandshakeOK(r.Header)) || !rs.requireOK(r.Header) {+ st.deny(w, "require", http.StatusForbidden, "permission_error", st.text().require)+ return nil, false+ }+ if prof.perKey == nil {+ return func() {}, true+ }+ st.concKey = prof.concKey.expand(l.cred.vars)+ if !prof.perKey.enter(st.concKey) {+ st.denyAs(w, "concurrency_cap", "concurrency", http.StatusTooManyRequests, "rate_limit_error", st.text().concurrency)+ return nil, false+ }+ if rs.ws {+ prof.perKey.leave(st.concKey) // a tunnel counts its responses instead (websocket.go)+ return func() {}, true+ }+ return func() { prof.perKey.leave(st.concKey) }, true+}++// errConnWait cancels a request that got no upstream connection in time.+var errConnWait = errors.New("no free upstream connection within the hold timeout")++// forward hands the request to the profile's ReverseProxy.+func (p *Proxy) forward(w http.ResponseWriter, r *http.Request, st *reqState, l *lease) {+ prof := st.prof+ st.vars, st.lease = l.cred.vars, l+ st.leased = st.since()+ st.proxied = true++ prof.up.streams.Add(1)+ defer prof.up.streams.Add(-1)+ ctx, cancel := context.WithCancelCause(context.WithValue(r.Context(), stateKey, st))+ defer cancel(nil)+ // Stopped when the transport hands over a connection or starts dialling+ // one for this request (reqState.trace).+ st.connWait = time.AfterFunc(p.hold, func() { cancel(errConnWait) })+ defer st.connWait.Stop()+ defer func() { // also when ReverseProxy aborts the handler+ if st.ws != nil {+ st.ws.end()+ }+ }()+ prof.rp.ServeHTTP(&respWriter{ResponseWriter: w, st: st}, r.WithContext(ctx))+}++// placeholderOK: the caller sends no credential, or only the placeholder its+// client needs to be configured with (-placeholder). The proxy injects the+// real one; anything else is a caller trying its own.+func placeholderOK(h http.Header, placeholder string) bool {+ if v := h.Values("Authorization"); len(v) > 1 || (len(v) == 1 && v[0] != "Bearer "+placeholder) {+ return false+ }+ v := h.Values("X-Api-Key")+ return len(v) == 0 || (len(v) == 1 && v[0] == placeholder)+}++// isUpgrade: the request asks to switch protocols (a WebSocket): its+// Connection lists `upgrade` (RFC 9110 §7.8). Only a profile's WS route+// serves one; anywhere else it is refused with 426 rather than let+// ReverseProxy tunnel a connection the proxy cannot observe. A bare Upgrade+// header is no request to switch: it is a hop-by-hop header ReverseProxy+// strips.+func isUpgrade(h http.Header) bool { return connectionLists(h, "upgrade") }++// connectionLists: the request's Connection header names token, which makes+// a header of that name hop-by-hop: ReverseProxy strips it.+func connectionLists(h http.Header, token string) bool {+ for _, v := range h["Connection"] {+ for t := range strings.SplitSeq(v, ",") {+ if strings.EqualFold(strings.TrimSpace(t), token) {+ return true+ }+ }+ }+ return false+}++// wsHandshakeOK: a WebSocket upgrade, version 13, with a key.+func wsHandshakeOK(h http.Header) bool {+ return strings.EqualFold(h.Get("Upgrade"), "websocket") && h.Get("Sec-Websocket-Version") == "13" && h.Get("Sec-Websocket-Key") != ""+}++// respWriter counts bytes, notes the first flush to the client and client+// write failures. ReverseProxy flushes through http.ResponseController.+type respWriter struct {+ http.ResponseWriter+ st *reqState+}++func (w *respWriter) Write(b []byte) (int, error) {+ n, err := w.ResponseWriter.Write(b)+ w.st.bytesOut.Add(int64(n))+ if err != nil {+ w.st.clientErr.Store(true)+ }+ return n, err+}++func (w *respWriter) FlushError() error {+ err := http.NewResponseController(w.ResponseWriter).Flush()+ w.st.firstOut.CompareAndSwap(0, w.st.since())+ if err != nil {+ w.st.clientErr.Store(true)+ }+ return err+}++func (w *respWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }++type countingBody struct {+ io.ReadCloser+ n *atomic.Int64+}++func (b *countingBody) Read(p []byte) (int, error) {+ n, err := b.ReadCloser.Read(p)+ b.n.Add(int64(n))+ return n, err+}++// upstreamBody notes a failed upstream read (a stream cut by the upstream).+type upstreamBody struct {+ io.ReadCloser+ st *reqState+}++func (b *upstreamBody) Read(p []byte) (int, error) {+ n, err := b.ReadCloser.Read(p)+ if err != nil && err != io.EOF {+ b.st.upstreamReadErr.Store(true)+ }+ return n, err+}++func isEventStream(ct string) bool {+ mt, _, err := mime.ParseMediaType(ct)+ return err == nil && mt == "text/event-stream"+}++type bufferPool struct {+ size int+ p sync.Pool+}++func newBufferPool(size int) *bufferPool {+ return &bufferPool{size: size, p: sync.Pool{New: func() any { b := make([]byte, size); return &b }}}+}++func (b *bufferPool) Get() []byte { return *(b.p.Get().(*[]byte)) }+func (b *bufferPool) Put(x []byte) { b.p.Put(&x) }diff --git a/computer/modelproxy/proxy_test.go b/computer/modelproxy/proxy_test.gonew file mode 100644index 00000000..c2b68f34--- /dev/null+++ b/computer/modelproxy/proxy_test.go@@ -0,0 +1,363 @@+package main++import (+ "context"+ "io"+ "net"+ "net/http"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++type seen struct {+ header http.Header+ host string+ uri string+ tls bool+ body string+}++func recordingUpstream(hits *atomic.Int64, got chan<- seen) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hits.Add(1)+ b, _ := io.ReadAll(r.Body)+ select {+ case got <- seen{header: r.Header.Clone(), host: r.Host, uri: r.RequestURI, tls: r.TLS != nil, body: string(b)}:+ default:+ }+ w.Header().Set("Content-Type", "application/json")+ w.Header().Set("Request-Id", "req_1")+ w.Write([]byte(`{"ok":true}`))+ })+}++func TestRewrite(t *testing.T) {+ var hits atomic.Int64+ got := make(chan seen, 1)+ h := newHarness(t, recordingUpstream(&hits, got), harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "secret-token", "fp1")++ req := h.messagesReq(context.Background())+ req.Header.Set("X-Forwarded-For", "10.0.0.9")+ req.Header.Set("X-Forwarded-Host", "evil")+ req.Header.Set("X-Forwarded-Proto", "http")+ req.Header.Set("Forwarded", "for=10.0.0.9")+ req.Header.Set("Connection", "X-Hop")+ req.Header.Set("X-Hop", "1")+ req.Header.Set("Keep-Alive", "timeout=5")+ req.Header.Set("Proxy-Authorization", "x")+ req.Header.Set("X-Api-Key", testPlaceholder)+ req.Header.Set("Accept-Encoding", "gzip, br")+ req.Header.Set("Anthropic-Dangerous-Direct-Browser-Access", "true")+ req.Header.Set("X-Stainless-Retry-Count", "0")+ res, err := h.client(testCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ io.ReadAll(res.Body)+ res.Body.Close()+ if res.StatusCode != 200 || res.Header.Get("Request-Id") != "req_1" {+ t.Fatalf("status %d", res.StatusCode)+ }+ s := <-got+ if !s.tls {+ t.Fatal("upstream request was not https")+ }+ if a := s.header.Values("Authorization"); len(a) != 1 || a[0] != "Bearer secret-token" {+ t.Fatalf("authorization %q", a)+ }+ if s.host != strings.TrimPrefix(h.upstream.URL, "https://") {+ t.Fatalf("host %q", s.host)+ }+ if s.uri != "/v1/messages?beta=true" {+ t.Fatalf("uri %q", s.uri)+ }+ for _, k := range []string{"X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto", "Forwarded", "X-Hop", "Keep-Alive", "Proxy-Authorization", "X-Api-Key"} {+ if v := s.header.Values(k); len(v) != 0 {+ t.Errorf("%s forwarded: %q", k, v)+ }+ }+ want := map[string]string{+ "Anthropic-Beta": "claude-code-20250219,interleaved-thinking-2025-05-14,oauth-2025-04-20",+ "Anthropic-Version": "2023-06-01",+ "Anthropic-Dangerous-Direct-Browser-Access": "true",+ "Accept-Encoding": "gzip, br",+ "User-Agent": "claude-cli/2.1.301 (external, sdk-cli)",+ "X-App": "cli",+ "X-Stainless-Retry-Count": "0",+ "Content-Type": "application/json",+ }+ for k, v := range want {+ if got := s.header.Values(k); len(got) != 1 || got[0] != v {+ t.Errorf("%s = %q, want %q", k, got, v)+ }+ }+ if s.body != `{"model":"x"}` {+ t.Fatalf("body %q", s.body)+ }+ ev := k.waitFor(isEvent("model.request"))+ if ev["outcome"] != "completed" || ev["session_key"] != "s1" {+ t.Fatalf("event %v", ev)+ }+ d := ev["data"].(map[string]any)+ if ev["profile"] != mainProfile || d["route"] != "messages" || d["status"] != float64(200) || d["key"] != "fp1" || d["swapped"] != false {+ t.Fatalf("event data %v", d)+ }+ if _, ok := d["overhead_us"]; !ok {+ t.Fatalf("no overhead_us in %v", d)+ }+ for _, v := range d {+ if s, ok := v.(string); ok && (strings.Contains(s, "secret-token") || strings.Contains(s, "placeholder")) {+ t.Fatalf("secret in event: %v", d)+ }+ }+}++func TestPolicyLimitsForwardedWithToken(t *testing.T) {+ var hits atomic.Int64+ got := make(chan seen, 1)+ h := newHarness(t, recordingUpstream(&hits, got), harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ req, _ := http.NewRequest(http.MethodGet, h.apiURL+"/api/claude_code/policy_limits", nil)+ req.Host = "localhost"+ req.Header.Set("User-Agent", "claude-code/2.1.301")+ res, err := h.client(testCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ res.Body.Close()+ if res.StatusCode != 200 {+ t.Fatalf("status %d", res.StatusCode)+ }+ s := <-got+ if s.header.Get("Authorization") != "Bearer tok" || s.header.Get("Anthropic-Beta") != "oauth-2025-04-20" || s.header.Get("User-Agent") != "claude-code/2.1.301" {+ t.Fatalf("headers %v", s.header)+ }+}++func TestDenials(t *testing.T) {+ var hits atomic.Int64+ h := newHarness(t, recordingUpstream(&hits, make(chan seen, 1)), harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ c := h.client(testCaller)++ cases := []struct {+ name string+ mutate func(*http.Request)+ status int+ errType string+ reason string+ }{+ {"models not allowlisted", func(r *http.Request) {+ r.Method = http.MethodGet+ r.URL.Path = "/v1/models"+ r.Body = nil+ r.ContentLength = 0+ }, 404, "not_found_error", "route"},+ {"bootstrap not allowlisted", func(r *http.Request) {+ r.Method = http.MethodGet+ r.URL.Path = "/api/claude_cli/bootstrap"+ r.ContentLength = 0+ r.Body = nil+ }, 404, "not_found_error", "route"},+ {"GET messages", func(r *http.Request) { r.Method = http.MethodGet; r.Body = nil; r.ContentLength = 0 }, 404, "not_found_error", "route"},+ {"path trick", func(r *http.Request) { r.URL.Path = "/v1/messages/../models" }, 404, "not_found_error", "route"},+ {"curl user-agent", func(r *http.Request) { r.Header.Set("User-Agent", "curl/8") }, 403, "permission_error", "require"},+ {"no x-app", func(r *http.Request) { r.Header.Del("X-App") }, 403, "permission_error", "require"},+ {"no oauth beta", func(r *http.Request) { r.Header.Set("Anthropic-Beta", "claude-code-20250219") }, 403, "permission_error", "require"},+ {"count_tokens shape", func(r *http.Request) { r.URL.Path = "/v1/messages/count_tokens"; r.Header.Del("X-App") }, 403, "permission_error", "require"},+ {"other bearer", func(r *http.Request) { r.Header.Set("Authorization", "Bearer its-own") }, 401, "authentication_error", "credentials"},+ {"other x-api-key", func(r *http.Request) { r.Header.Set("X-Api-Key", "its-own") }, 401, "authentication_error", "credentials"},+ {"two bearers", func(r *http.Request) { r.Header.Add("Authorization", placeholderAuth) }, 401, "authentication_error", "credentials"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ req := h.messagesReq(context.Background())+ tc.mutate(req)+ res, err := c.Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer res.Body.Close()+ if res.StatusCode != tc.status {+ t.Fatalf("status %d, want %d", res.StatusCode, tc.status)+ }+ if e := decodeAPIError(t, res); e.Error.Type != tc.errType {+ t.Fatalf("error type %q", e.Error.Type)+ }+ ev := k.waitFor(isEvent("model.denied"))+ if ev["data"].(map[string]any)["reason"] != tc.reason || ev["outcome"] != "failed" {+ t.Fatalf("event %v", ev)+ }+ })+ }+ if n := hits.Load(); n != 0 {+ t.Fatalf("upstream contacted %d times", n)+ }++ // A caller that is no runner: 401 at once, upstream untouched.+ res, err := h.client("").Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Fatal(err)+ }+ if res.StatusCode != 401 || decodeAPIError(t, res).Error.Type != "authentication_error" || hits.Load() != 0 {+ t.Fatalf("no-caller status %d", res.StatusCode)+ }+ res.Body.Close()+}++func TestUpstreamUnreachable502(t *testing.T) {+ var hits atomic.Int64+ h := newHarness(t, recordingUpstream(&hits, make(chan seen, 1)), harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ h.upstream.Close()+ res, err := h.client(testCaller).Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Fatal(err)+ }+ defer res.Body.Close()+ if res.StatusCode != 502 || decodeAPIError(t, res).Error.Type != "api_error" {+ t.Fatalf("status %d", res.StatusCode)+ }+ // The binder hears of it (before the request event).+ om := k.waitFor(isT("observed"))+ if om["error"] != "connect" || om["key"] != "fp1" || om["profile"] != mainProfile || om["caller"] != testCaller || om["sessionKey"] != "s1" || om["status"] != nil {+ t.Fatalf("observed %v", om)+ }+ ev := k.waitFor(isEvent("model.request"))+ if ev["outcome"] != "failed" || ev["error_type"] != "socket" {+ t.Fatalf("event %v", ev)+ }+}++func TestIsEventStream(t *testing.T) {+ for ct, want := range map[string]bool{+ "text/event-stream": true,+ "text/event-stream; charset=utf-8": true,+ "Text/Event-Stream": true,+ "text/event-streams": false,+ "application/json": false,+ "": false,+ } {+ if got := isEventStream(ct); got != want {+ t.Errorf("%q: %v", ct, got)+ }+ }+}++// A request that gets no upstream connection within the hold timeout is+// refused, retryable; it never reached the upstream.+func TestUpstreamBusy(t *testing.T) {+ g := &gatedUpstream{started: make(chan string, 4), release: make(chan struct{})}+ h := newHarness(t, g, harnessOpts{hold: 100 * time.Millisecond, maxConns: 1})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ done := make(chan int, 1)+ go func() {+ res, err := h.client(testCaller).Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Error(err)+ done <- 0+ return+ }+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ done <- res.StatusCode+ }()+ <-g.started // holds the upstream's only connection++ res := do(t, h, testCaller)+ e := decodeAPIError(t, res)+ if res.StatusCode != 503 || res.Header.Get("Retry-After") != "1" || res.Header.Get("X-Should-Retry") != "true" || e.Error.Message != textBusy {+ t.Fatalf("busy: %d %v %+v", res.StatusCode, res.Header, e)+ }+ ev := k.waitFor(isEvent("model.denied"))+ if evData(ev)["reason"] != "upstream_busy" || ev["error_type"] != "timeout" || ev["profile"] != mainProfile {+ t.Fatalf("event %v", ev)+ }+ close(g.release)+ if st := <-done; st != 200 || len(g.bearers) != 1 {+ t.Fatalf("the stream: %d, upstream hits %d", st, len(g.bearers))+ }+}++// An upstream that accepts and never answers the TLS handshake is a 502 and+// an `observed` error, on the handshake's own limit, even when that is as+// long as the hold: only a request queued for a connection is "busy".+func TestUnreachableIsNotBusy(t *testing.T) {+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{hold: 300 * time.Millisecond})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ l, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer l.Close()+ go func() {+ for {+ c, err := l.Accept()+ if err != nil {+ return+ }+ defer c.Close()+ }+ }()+ prof := h.srv.profiles.get(mainProfile)+ prof.url.Host = l.Addr().String()+ prof.up.handshakeTimeout = 300 * time.Millisecond++ res := do(t, h, testCaller)+ if e := decodeAPIError(t, res); res.StatusCode != 502 || e.Error.Message != defaultTexts.unreachable {+ t.Fatalf("%d %+v", res.StatusCode, e)+ }+ if m := k.waitFor(isT("observed")); m["error"] != "timeout" || m["key"] != "fp1" {+ t.Fatalf("observed %v", m)+ }+}++// A required header the caller's Connection header would strip on the way+// does not pass `require`.+func TestRequireNotHopByHop(t *testing.T) {+ var hits atomic.Int64+ h := newHarness(t, recordingUpstream(&hits, nil), harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ req := h.messagesReq(context.Background())+ req.Header.Set("Connection", "keep-alive, x-app")+ if st := doReq(t, h, testCaller, req); st != 403 || hits.Load() != 0 {+ t.Fatalf("%d, upstream hits %d", st, hits.Load())+ }+}++// One caller's refusals for one reason are one model.denied in refusalEvery,+// however many there are: they cannot fill the control queue.+func TestDeniedEventsBounded(t *testing.T) {+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{})+ h.srv.proxy.refusals.every = refusalEvery+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ for range 20 {+ req, _ := http.NewRequest(http.MethodGet, h.apiURL+"/nope", nil)+ if st := doReq(t, h, testCaller, req); st != 404 {+ t.Fatalf("status %d", st)+ }+ }+ if ev := k.waitFor(isEvent("model.denied")); evData(ev)["reason"] != "route" || evData(ev)["suppressed"] != float64(0) {+ t.Fatalf("event %v", ev)+ }+ k.noMessage(isEvent("model.denied"), 200*time.Millisecond)+}++func TestHoldTimeoutMustBePositive(t *testing.T) {+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{})+ if _, err := newServer(config{placeholder: testPlaceholder}, h.srv.profiles, singleResolver); err == nil {+ t.Fatal("-hold-timeout=0 accepted")+ }+}diff --git a/computer/modelproxy/rawpath_test.go b/computer/modelproxy/rawpath_test.gonew file mode 100644index 00000000..b16223ad--- /dev/null+++ b/computer/modelproxy/rawpath_test.go@@ -0,0 +1,37 @@+package main++import (+ "net/http"+ "testing"+)++// The upstream gets the path the route matched, not the caller's encoding of+// it; and never the caller's cookies (the shipped profiles' `remove`).+func TestPathAsMatched(t *testing.T) {+ paths := make(chan string, 1)+ cookies := make(chan string, 1)+ h := newHarness(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ paths <- r.RequestURI+ cookies <- r.Header.Get("Cookie")+ }), harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ req, _ := http.NewRequest(http.MethodGet, h.apiURL+"/api/claude_code/policy_limits", nil)+ req.Host = "localhost"+ req.URL.RawPath = "/api/claude_code/policy%5Flimits"+ req.Header.Set("Cookie", "a=b")+ res, err := h.client(testCaller).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ res.Body.Close()+ if res.StatusCode != 200 {+ t.Fatalf("status %d", res.StatusCode)+ }+ if p := <-paths; p != "/api/claude_code/policy_limits" {+ t.Fatalf("path %q", p)+ }+ if c := <-cookies; c != "" {+ t.Fatalf("cookie %q", c)+ }+}diff --git a/computer/modelproxy/refuse.go b/computer/modelproxy/refuse.gonew file mode 100644index 00000000..dfd30e75--- /dev/null+++ b/computer/modelproxy/refuse.go@@ -0,0 +1,169 @@+// Refusals: the responses the proxy writes itself, their texts, and the log+// line each leaves.+//+// The body is `{"type":"error","error":{"type","message"}}` on every route:+// Anthropic's error shape, which also has the `error.type` and+// `error.message` an OpenAI client reads, so one body serves both families+// and a refusal made before the route is known needs no other.+//+// Texts are neutral by default; a profile may replace those in `texts` with+// its `errors` map (profile.go).+//+// Invariants: a request to upgrade gets every refusal as a 426 (a client+// that tried a WebSocket then goes on over HTTP at once, where the same+// refusal is served with its own status, websocket.go); a refusal is+// reported (a log line and a model.denied event, telemetry.go) at most once+// per caller and reason in refusalEvery, with how many like it went+// unreported since, so one session can flood neither the journal nor the+// control socket's queue, which every session's messages share.+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+ "sync"+ "time"+)++// Texts of refusals made before, or without, a profile.+const (+ textNotFound = "Not found: this endpoint is not served by the model proxy."+ textCredentials = "Unexpected credentials: the model proxy injects them."+ textUnknownCaller = "This process is not a session bound to a model credential."+ textUnbound = "This session is not bound to a model credential."+ textCallerCap = "Too many concurrent requests from this session; retry."+ textBusy = "The upstream has no free connection for this request; retry."+ textNoWebSocket = "WebSocket upgrades are not served on this endpoint."+ textWSRefused = "The upstream refused the WebSocket (%d)."+)++// texts are the refusals a profile may word itself; the JSON keys of its+// `errors` map are the field names.+type texts struct {+ require, notReady, refused, refusedPrefix, unreachable, concurrency string+}++var defaultTexts = texts{+ require: "This request is not allowed for this session's model credential.",+ notReady: "The model credential for this session is not ready yet; retry.",+ refused: "Model access is unavailable for this session.",+ refusedPrefix: "Model access unavailable: ",+ unreachable: "The model proxy could not reach the upstream.",+ concurrency: "Too many concurrent requests on this credential; retry.",+}++func (t *texts) override(m map[string]string) error {+ for k, v := range m {+ switch k {+ case "require":+ t.require = v+ case "notReady":+ t.notReady = v+ case "refused":+ t.refused = v+ case "refusedPrefix":+ t.refusedPrefix = v+ case "unreachable":+ t.unreachable = v+ case "concurrency":+ t.concurrency = v+ default:+ return fmt.Errorf("errors: unknown key %q", k)+ }+ }+ return nil+}++// deny refuses the request.+func (s *reqState) deny(w http.ResponseWriter, reason string, status int, typ, msg string) {+ s.denyReason, s.status, s.ownErrType = reason, status, typ+ if s.upgrade {+ status, typ, msg = http.StatusUpgradeRequired, "invalid_request_error", wsUseHTTP+msg+ }+ writeAPIError(w, status, typ, msg)+}++// denyAs is deny with an envelope error_type (telemetry.go has the closed set).+func (s *reqState) denyAs(w http.ResponseWriter, reason, errType string, status int, typ, msg string) {+ s.denyErr = errType+ s.deny(w, reason, status, typ, msg)+}++// text is the profile's refusal texts, the defaults without one.+func (s *reqState) text() *texts {+ if s.prof == nil {+ return &defaultTexts+ }+ return &s.prof.text+}++type apiError struct {+ Type string `json:"type"`+ Error struct {+ Type string `json:"type"`+ Message string `json:"message"`+ } `json:"error"`+}++func writeAPIError(w http.ResponseWriter, status int, typ, msg string) {+ b := apiErrorHeaders(w.Header(), status, typ, msg)+ w.WriteHeader(status)+ w.Write(b)+}++// apiErrorHeaders sets an API error's headers on h and returns its body.+func apiErrorHeaders(h http.Header, status int, typ, msg string) []byte {+ var e apiError+ e.Type = "error"+ e.Error.Type, e.Error.Message = typ, msg+ b, _ := json.Marshal(e)+ h.Set("Content-Type", "application/json")+ switch status {+ case http.StatusServiceUnavailable, http.StatusTooManyRequests:+ h.Set("Retry-After", "1")+ h.Set("X-Should-Retry", "true")+ case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusUpgradeRequired:+ h.Set("X-Should-Retry", "false") // retrying cannot help; fail the turn now+ }+ return b+}++const (+ refusalEvery = 10 * time.Second+ refusalLogKeys = 1024 // past it the table starts over+)++// refusalLog decides which refusals are reported.+type refusalLog struct {+ every time.Duration // refusalEvery; tests report each+ mu sync.Mutex+ seen map[string]*refusalSeen+}++type refusalSeen struct {+ at time.Time+ skipped int+}++// allow: whether to report this refusal, and how many like it went+// unreported since the last one that was.+func (l *refusalLog) allow(now time.Time, caller, reason string) (ok bool, skipped int) {+ key := caller + "\x00" + reason+ l.mu.Lock()+ defer l.mu.Unlock()+ e := l.seen[key]+ switch {+ case e == nil:+ if l.seen == nil || len(l.seen) >= refusalLogKeys {+ l.seen = map[string]*refusalSeen{}+ }+ l.seen[key] = &refusalSeen{at: now}+ return true, 0+ case now.Sub(e.at) < l.every:+ e.skipped+++ return false, 0+ }+ skipped, e.at, e.skipped = e.skipped, now, 0+ return true, skipped+}diff --git a/computer/modelproxy/refuse_test.go b/computer/modelproxy/refuse_test.gonew file mode 100644index 00000000..650e4150--- /dev/null+++ b/computer/modelproxy/refuse_test.go@@ -0,0 +1,37 @@+package main++import (+ "testing"+ "time"+)++// One log line per caller and reason in refusalEvery; the next one says+// how many went unlogged.+func TestRefusalLog(t *testing.T) {+ l := refusalLog{every: refusalEvery}+ now := time.Unix(1_800_000_000, 0)+ if ok, skipped := l.allow(now, "a", "route"); !ok || skipped != 0 {+ t.Fatalf("first: %v %d", ok, skipped)+ }+ for range 5 {+ if ok, _ := l.allow(now.Add(time.Second), "a", "route"); ok {+ t.Fatal("logged again within the interval")+ }+ }+ if ok, _ := l.allow(now, "a", "require"); !ok {+ t.Fatal("another reason not logged")+ }+ if ok, _ := l.allow(now, "b", "route"); !ok {+ t.Fatal("another caller not logged")+ }+ if ok, skipped := l.allow(now.Add(refusalEvery), "a", "route"); !ok || skipped != 5 {+ t.Fatalf("after the interval: %v %d", ok, skipped)+ }+ // The table is bounded.+ for i := range 3 * refusalLogKeys {+ l.allow(now, string(rune('A'+i%26))+time.Duration(i).String(), "route")+ }+ if len(l.seen) > refusalLogKeys {+ t.Fatalf("table %d", len(l.seen))+ }+}diff --git a/computer/modelproxy/request.go b/computer/modelproxy/request.gonew file mode 100644index 00000000..08633051--- /dev/null+++ b/computer/modelproxy/request.go@@ -0,0 +1,69 @@+// A binder's `request`: one request on a profile, made by the proxy with+// variables the binder supplies for it. It is how a binder checks a credential+// before binding anything to it, or reads an upstream's own account+// endpoints, without the credential ever being in a session.+//+// The path must be a route of the profile (not a WS one). The route's `to`,+// the profile's and the route's `set` and the route's `default` apply as for+// a session's request; `require` does not: it is a check on sessions, and+// the binder is trusted. The variables are used once and not stored.+//+// The answer is the status, the response headers the profile's `report`+// names and the start of the body; or an error: unknown_profile,+// unknown_route, missing_var (absent, or not a header value), bad_request,+// busy (maxRequests are in flight, control.go), timeout, or unreachable. It+// goes to the connection that asked.+package main++import (+ "context"+ "io"+ "net/http"+ "strings"+)++// maxResponseBody caps how much of the body a `response` carries.+const maxResponseBody = 16 << 10++func (ps *profiles) request(ctx context.Context, m requestMsg) responseMsg {+ prof := ps.get(m.Profile)+ if prof == nil {+ return responseMsg{Error: responseUnknownProfile}+ }+ rs := prof.routes[m.Method+" "+m.Path]+ if rs == nil || rs.ws {+ return responseMsg{Error: responseUnknownRoute}+ }+ for _, v := range prof.vars {+ if val := m.Vars[v]; val == "" || !validHeaderValue(val) {+ return responseMsg{Error: responseMissingVar}+ }+ }+ var body io.Reader+ if m.Body != "" {+ body = strings.NewReader(m.Body)+ }+ req, err := http.NewRequestWithContext(ctx, m.Method, "https://"+prof.url.Host+m.Path, body)+ if err != nil {+ return responseMsg{Error: responseBadRequest}+ }+ req.URL.RawQuery = m.Query+ for k, v := range m.Headers {+ if !validHeaderName(k) || !validHeaderValue(v) {+ return responseMsg{Error: responseBadRequest}+ }+ req.Header.Set(k, v)+ }+ prof.target(req, rs)+ prof.headers(req.Header, rs, m.Vars)+ res, err := prof.up.transport.RoundTrip(req)+ if err != nil {+ if errorClass(err) == "timeout" {+ return responseMsg{Error: responseTimeout}+ }+ return responseMsg{Error: responseUnreachable}+ }+ defer res.Body.Close()+ b, _ := io.ReadAll(io.LimitReader(res.Body, maxResponseBody))+ return responseMsg{Status: res.StatusCode, Headers: reported(prof.report, res.Header), Body: string(b)}+}diff --git a/computer/modelproxy/request_test.go b/computer/modelproxy/request_test.gonew file mode 100644index 00000000..c1b457b5--- /dev/null+++ b/computer/modelproxy/request_test.go@@ -0,0 +1,85 @@+package main++import (+ "net/http"+ "strings"+ "sync/atomic"+ "testing"+)++func (k *ctl) request(m map[string]any) map[string]any {+ k.t.Helper()+ m["t"] = "request"+ k.send(m)+ return k.waitFor(func(r map[string]any) bool { return r["t"] == "response" && r["id"] == m["id"] })+}++// A binder `request` is made on the profile with the variables it carries:+// the route's `to`, `set` and `default` apply, `require` does not, and the+// answer has the status, the reported headers and the body. Nothing is bound.+func TestRequest(t *testing.T) {+ got := make(chan seen, 1)+ alt := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got <- seen{header: r.Header.Clone(), host: r.Host, uri: r.RequestURI}+ w.Header().Set("X-Quota-Used", "40")+ w.Header().Set("X-Other", "no")+ w.WriteHeader(http.StatusAccepted)+ w.Write([]byte(strings.Repeat("m", maxResponseBody+100)))+ })+ var hits atomic.Int64+ h := newHarness(t, recordingUpstream(&hits, nil), harnessOpts{alt: alt})+ k := h.dialControl()+ r := k.request(map[string]any{"id": "r1", "profile": altProfile, "method": "GET", "path": "/v1/models", "query": "v=1",+ "vars": map[string]string{"token": "tok", "accountId": altAccount}, "headers": map[string]string{"X-Extra": "1", "Authorization": "Bearer mine"}})+ s := <-got+ if s.uri != "/base/x/models?v=1" || s.host != h.alt.Listener.Addr().String() || s.header.Get("Authorization") != "Bearer tok" ||+ s.header.Get("X-Account") != altAccount || s.header.Get("Accept") != "application/json" || s.header.Get("X-Extra") != "1" {+ t.Fatalf("upstream saw %s %v", s.uri, s.header)+ }+ hd, _ := r["headers"].(map[string]any)+ if r["status"] != float64(202) || len(hd) != 1 || hd["x-quota-used"] != "40" || len(r["body"].(string)) != maxResponseBody || r["error"] != nil {+ t.Fatalf("response status %v headers %v body %d error %v", r["status"], hd, len(r["body"].(string)), r["error"])+ }+ if h.srv.bindings.Len() != 0 || hits.Load() != 0 {+ t.Fatalf("bindings %d, other upstream hits %d", h.srv.bindings.Len(), hits.Load())+ }++ // `require` is a check on sessions: the binder's request passes without it.+ r = k.request(map[string]any{"id": "r2", "profile": altProfile, "method": "POST", "path": "/v1/responses", "body": "{}",+ "vars": map[string]string{"token": "tok", "accountId": altAccount}})+ if s := <-got; r["status"] != float64(202) || s.uri != "/base/x/responses" {+ t.Fatalf("response %v, uri %s", r["status"], s.uri)+ }+}++func TestRequestErrors(t *testing.T) {+ var hits atomic.Int64+ h := newHarness(t, recordingUpstream(&hits, nil), harnessOpts{alt: recordingUpstream(&hits, nil)})+ k := h.dialControl()+ vars := map[string]string{"token": "tok", "accountId": altAccount}+ for i, c := range []struct {+ want string+ m map[string]any+ }{+ {responseUnknownProfile, map[string]any{"profile": "nope", "method": "GET", "path": "/v1/models", "vars": vars}},+ {responseUnknownRoute, map[string]any{"profile": altProfile, "method": "GET", "path": "/v1/other", "vars": vars}},+ {responseUnknownRoute, map[string]any{"profile": altProfile, "method": "DELETE", "path": "/v1/models", "vars": vars}},+ {responseUnknownRoute, map[string]any{"profile": altProfile, "method": "WS", "path": "/v1/responses", "vars": vars}},+ {responseMissingVar, map[string]any{"profile": altProfile, "method": "GET", "path": "/v1/models", "vars": map[string]string{"token": "tok"}}},+ {responseMissingVar, map[string]any{"profile": altProfile, "method": "GET", "path": "/v1/models", "vars": map[string]string{"token": "a\r\nX: y", "accountId": "a"}}},+ {responseBadRequest, map[string]any{"profile": altProfile, "method": "GET", "path": "/v1/models", "vars": vars, "headers": map[string]string{"Bad Name": "v"}}},+ {responseBadRequest, map[string]any{"profile": altProfile, "method": "GET", "path": "/v1/models", "vars": vars, "headers": map[string]string{"X-A": "v\nw"}}},+ } {+ c.m["id"] = string(rune('a' + i))+ if r := k.request(c.m); r["error"] != c.want || r["status"] != nil {+ t.Errorf("%v: response %v, want error %s", c.m, r, c.want)+ }+ }+ if hits.Load() != 0 {+ t.Fatalf("upstream contacted %d times", hits.Load())+ }+ h.alt.Close()+ if r := k.request(map[string]any{"id": "z", "profile": altProfile, "method": "GET", "path": "/v1/models", "vars": vars}); r["error"] != responseUnreachable {+ t.Fatalf("response %v", r)+ }+}diff --git a/computer/modelproxy/responses.go b/computer/modelproxy/responses.gonew file mode 100644index 00000000..88af137d--- /dev/null+++ b/computer/modelproxy/responses.go@@ -0,0 +1,112 @@+// What a Responses stream (a route with format `responses`) says about its+// own request, read as the client reads it: when its first output item came+// (the model's own first token, as opposed to `ttfb_ms`, which+// `response.created` ends), the service tier it was served on, and whether+// it reached `response.completed`. A client such as Codex closes its+// connection once it has read `response.completed`, before the upstream's+// end; without the last fact every such finished request would be reported+// as cancelled.+//+// Invariants: nothing is read ahead of the client, nothing is buffered beyond+// a short tail kept to match markers split across reads, and nothing from the+// stream but these three facts is kept; a compressed body is not watched.+package main++import (+ "bytes"+ "io"+ "sync/atomic"+)++var (+ // Quoted JSON: model output inside the stream escapes its quotes, so it cannot match.+ markOutput = []byte(`"type":"response.output_item.added"`)+ markCompleted = []byte(`"type":"response.completed"`)+ markTier = []byte(`"service_tier":"`)+)++// sniffTail: a marker, or the tier marker and its value, fits in it.+const sniffTail = 64++// responsesFacts are set from the client's reads; read once the request ended.+type responsesFacts struct {+ firstOutput atomic.Int64 // offset from the request's start in ns (+1 so 0 means unset)+ completed atomic.Bool+ tier atomic.Value // string+}++func (f *responsesFacts) serviceTier() string {+ s, _ := f.tier.Load().(string)+ return s+}++type responsesBody struct {+ io.ReadCloser+ st *reqState+ scan tailScan+}++func watchResponses(st *reqState, body io.ReadCloser) io.ReadCloser {+ return &responsesBody{ReadCloser: body, st: st}+}++func (b *responsesBody) Read(p []byte) (int, error) {+ n, err := b.ReadCloser.Read(p)+ if n > 0 {+ b.see(p[:n])+ }+ return n, err+}++func (b *responsesBody) see(chunk []byte) {+ b.match(b.scan.seam(chunk))+ b.match(chunk)+ b.scan.keep(chunk)+}++// match notes the facts in buf; the tier is the last one named (response.completed's is the one served).+func (b *responsesBody) match(buf []byte) {+ f := &b.st.resp+ if f.firstOutput.Load() == 0 && bytes.Contains(buf, markOutput) {+ f.firstOutput.CompareAndSwap(0, b.st.since())+ }+ if !f.completed.Load() && bytes.Contains(buf, markCompleted) {+ f.completed.Store(true)+ }+ if t, ok := tierIn(buf); ok {+ f.tier.Store(t)+ }+}++// tailScan finds markers of up to sniffTail bytes split across two pieces+// of a stream: match each piece and its seam with the one before.+type tailScan struct {+ tail []byte // the last sniffTail bytes seen+ edge []byte // tail + the next piece's first sniffTail bytes+}++// seam is the bytes either side of the seam before chunk; keep(chunk) follows.+func (s *tailScan) seam(chunk []byte) []byte {+ s.edge = append(append(s.edge[:0], s.tail...), chunk[:min(len(chunk), sniffTail)]...)+ return s.edge+}++func (s *tailScan) keep(chunk []byte) {+ s.tail = append(s.tail, chunk[max(0, len(chunk)-sniffTail):]...)+ s.tail = s.tail[:copy(s.tail, s.tail[max(0, len(s.tail)-sniffTail):])]+}++func (s *tailScan) reset() { s.tail = s.tail[:0] }++// tierIn is the last service tier buf names.+func tierIn(buf []byte) (string, bool) {+ i := bytes.LastIndex(buf, markTier)+ if i < 0 {+ return "", false+ }+ v := buf[i+len(markTier):]+ if j := bytes.IndexByte(v, '"'); j > 0 && j <= 32 {+ return string(v[:j]), true+ }+ return "", false+}diff --git a/computer/modelproxy/responses_test.go b/computer/modelproxy/responses_test.gonew file mode 100644index 00000000..3652b416--- /dev/null+++ b/computer/modelproxy/responses_test.go@@ -0,0 +1,83 @@+package main++import (+ "bufio"+ "context"+ "io"+ "net/http"+ "strings"+ "testing"+ "time"+)++const responsesStream = "event: response.created\n" ++ `data: {"type":"response.created","response":{"id":"r1","service_tier":"auto"}}` + "\n\n" ++ "event: response.output_item.added\n" ++ `data: {"type":"response.output_item.added","item":{"type":"reasoning"}}` + "\n\n" ++ "event: response.output_text.delta\n" ++ `data: {"type":"response.output_text.delta","delta":"say \"type\":\"response.completed\" and \"service_tier\":\"flex\""}` + "\n\n" ++ "event: response.completed\n" ++ `data: {"type":"response.completed","response":{"id":"r1","service_tier":"priority"}}` + "\n\n"++// Every split of the stream into two reads finds the same facts; model text that names them does not count.+func TestResponsesFactsAcrossReads(t *testing.T) {+ for cut := 0; cut <= len(responsesStream); cut++ {+ st := &reqState{start: time.Now()}+ b := watchResponses(st, io.NopCloser(strings.NewReader(""))).(*responsesBody)+ b.see([]byte(responsesStream[:cut]))+ b.see([]byte(responsesStream[cut:]))+ if st.resp.firstOutput.Load() == 0 || !st.resp.completed.Load() || st.resp.serviceTier() != "priority" {+ t.Fatalf("cut %d: output %d completed %v tier %q", cut, st.resp.firstOutput.Load(), st.resp.completed.Load(), st.resp.serviceTier())+ }+ }+ st := &reqState{start: time.Now()}+ b := watchResponses(st, io.NopCloser(strings.NewReader(""))).(*responsesBody)+ b.see([]byte(responsesStream[:strings.Index(responsesStream, "event: response.output_item.added")]))+ if st.resp.firstOutput.Load() != 0 || st.resp.completed.Load() || st.resp.serviceTier() != "auto" {+ t.Fatalf("before output: output %d completed %v tier %q", st.resp.firstOutput.Load(), st.resp.completed.Load(), st.resp.serviceTier())+ }+ b.see([]byte(`data: {"type":"response.output_text.delta","delta":"\"type\":\"response.completed\""}`))+ if st.resp.completed.Load() {+ t.Fatal("model text counted as response.completed")+ }+}++// A client that reads up to response.completed and hangs up while the upstream is still open: a completed request+// with its first output and served tier, not a cancelled one.+func TestResponsesCompletedThenHangUp(t *testing.T) {+ release := make(chan struct{})+ defer close(release)+ up := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ w.Header().Set("Content-Type", "text/event-stream")+ w.WriteHeader(200)+ io.WriteString(w, responsesStream)+ w.(http.Flusher).Flush()+ select {+ case <-release:+ case <-r.Context().Done():+ }+ })+ h := newHarness(t, http.NotFoundHandler(), harnessOpts{alt: up})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ res, err := h.client(altCaller).Do(h.responsesReq(ctx))+ if err != nil {+ t.Fatal(err)+ }+ sc := bufio.NewScanner(res.Body)+ for sc.Scan() && !strings.Contains(sc.Text(), `"type":"response.completed"`) {+ }+ cancel()+ res.Body.Close()+ e := k.waitFor(isEvent("model.request"))+ d := e["data"].(map[string]any)+ if e["outcome"] != "completed" || d["service_tier"] != "priority" {+ t.Fatalf("event %v", e)+ }+ if _, ok := d["first_output_ms"].(float64); !ok {+ t.Fatalf("no first_output_ms in %v", d)+ }+}diff --git a/computer/modelproxy/stream_test.go b/computer/modelproxy/stream_test.gonew file mode 100644index 00000000..99f3ed65--- /dev/null+++ b/computer/modelproxy/stream_test.go@@ -0,0 +1,176 @@+package main++import (+ "bufio"+ "context"+ "fmt"+ "io"+ "net/http"+ "strings"+ "sync"+ "testing"+ "time"+)++// TestStreamingChunkByChunk: the upstream sends chunk i only after the client+// has read chunk i-1, so any buffering in the proxy deadlocks the test.+func TestStreamingChunkByChunk(t *testing.T) {+ const chunks = 5+ ack := make(chan int)+ up := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "text/event-stream")+ w.WriteHeader(200)+ w.(http.Flusher).Flush()+ for i := range chunks {+ fmt.Fprintf(w, "event: content_block_delta\ndata: {\"i\":%d}\n\n", i)+ w.(http.Flusher).Flush()+ select {+ case got := <-ack:+ if got != i {+ t.Errorf("ack %d for chunk %d", got, i)+ }+ case <-time.After(2 * time.Second):+ t.Errorf("chunk %d never reached the client", i)+ return+ }+ }+ })+ h := newHarness(t, up, harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ res, err := h.client(testCaller).Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Fatal(err)+ }+ defer res.Body.Close()+ if res.Header.Get("Content-Type") != "text/event-stream" {+ t.Fatalf("content-type %q", res.Header.Get("Content-Type"))+ }+ br := bufio.NewReader(res.Body)+ for i := range chunks {+ for {+ line, err := br.ReadString('\n')+ if err != nil {+ t.Fatalf("chunk %d: %v", i, err)+ }+ if strings.HasPrefix(line, "data: ") {+ if want := fmt.Sprintf("data: {\"i\":%d}\n", i); line != want {+ t.Fatalf("got %q want %q", line, want)+ }+ break+ }+ }+ ack <- i+ }+ io.Copy(io.Discard, br)+ ev := k.waitFor(isEvent("model.request"))+ if d := ev["data"].(map[string]any); d["stream"] != true || ev["outcome"] != "completed" {+ t.Fatalf("event %v", ev)+ }+}++// gatedUpstream records each request's bearer and holds its response open+// until released.+type gatedUpstream struct {+ mu sync.Mutex+ bearers []string+ started chan string+ release chan struct{}+}++func (g *gatedUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ b := r.Header.Get("Authorization")+ g.mu.Lock()+ g.bearers = append(g.bearers, b)+ g.mu.Unlock()+ w.Header().Set("Content-Type", "text/event-stream")+ w.WriteHeader(200)+ w.(http.Flusher).Flush()+ g.started <- b+ <-g.release+ io.WriteString(w, "event: message_stop\ndata: {}\n\n")+}++// TestRebindUnderStream: a new token for a caller with a stream in flight+// applies at once. The stream ends on the token it started with; the next+// request uses the new one and is marked swapped. A refuse bind does the+// same: the stream ends, the next request is refused.+func TestRebindUnderStream(t *testing.T) {+ g := &gatedUpstream{started: make(chan string, 4), release: make(chan struct{})}+ h := newHarness(t, g, harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tokA", "fpA")+ c := h.client(testCaller)++ var wg sync.WaitGroup+ stream := func() {+ defer wg.Done()+ res, err := c.Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Error(err)+ return+ }+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ if res.StatusCode != 200 {+ t.Errorf("stream: %d", res.StatusCode)+ }+ }+ wg.Add(1)+ go stream()+ if b := <-g.started; b != "Bearer tokA" {+ t.Fatalf("first stream %q", b)+ }+ k.bind(testCaller, "s1", "tokB", "fpB")+ if m := k.waitFor(isT("bound")); m["key"] != "fpB" || m["sessionKey"] != "s1" {+ t.Fatalf("bound %v", m)+ }+ if ev := k.waitFor(isEvent("model.binding")); evData(ev)["action"] != "swap" || evData(ev)["key"] != "fpB" {+ t.Fatalf("binding event %v", ev)+ }++ wg.Add(1)+ go stream() // starts while the first is in flight: tokB already+ if b := <-g.started; b != "Bearer tokB" {+ t.Fatalf("concurrent stream %q, want the new token", b)+ }+ k.send(map[string]any{"t": "bind", "caller": testCaller, "sessionKey": "s1", "mode": "refuse", "reason": "paused"})+ k.waitFor(func(m map[string]any) bool { return m["t"] == "bound" && m["key"] == nil })+ res, err := c.Do(h.messagesReq(context.Background()))+ if err != nil {+ t.Fatal(err)+ }+ res.Body.Close()+ if res.StatusCode != http.StatusUnauthorized {+ t.Fatalf("after a refuse bind under live streams: %d", res.StatusCode)+ }+ close(g.release)+ wg.Wait() // both streams end 200+ ev := k.waitFor(func(m map[string]any) bool { return m["name"] == "model.request" && evData(m)["key"] == "fpB" })+ if evData(ev)["swapped"] != true {+ t.Fatalf("event %v", ev)+ }+}++// TestClientAbortMidStream: the client goes away; the event says cancelled+// and the caller's in-flight count returns to zero.+func TestClientAbortMidStream(t *testing.T) {+ g := &gatedUpstream{started: make(chan string, 4), release: make(chan struct{})}+ defer close(g.release)+ h := newHarness(t, g, harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tokA", "fpA")+ ctx, cancel := context.WithCancel(context.Background())+ res, err := h.client(testCaller).Do(h.messagesReq(ctx))+ if err != nil {+ t.Fatal(err)+ }+ <-g.started+ cancel()+ res.Body.Close()+ ev := k.waitFor(isEvent("model.request"))+ if ev["outcome"] != "cancelled" {+ t.Fatalf("event %v", ev)+ }+ h.bindReady(k, testCaller, "s1", "tokB", "fpB")+}diff --git a/computer/modelproxy/telemetry.go b/computer/modelproxy/telemetry.gonew file mode 100644index 00000000..4b3a47ec--- /dev/null+++ b/computer/modelproxy/telemetry.go@@ -0,0 +1,250 @@+// Per-request measurements and the events they become. README.md lists every+// event with its fields; testdata/control/event-*.json has one of each:+// - model.request: once per request that reached the upstream, after it ends;+// - model.held: a request that waited for its caller's bind (served, or+// 503/401 at the cap);+// - model.denied: a request the proxy refused (refuse.go), with its reason:+// credentials | unknown_caller | caller_cap | unbound | refused | route |+// websocket | require | concurrency_cap | upstream_busy. At most one per+// caller and reason in refusalEvery, with how many it stands for.+//+// Every one carries `profile`: the name of the binding's profile, or none+// before the binding is known.+//+// Envelope enums: outcome completed | failed | cancelled | timed_out;+// error_type provider_error | provider_rate_limited | timeout | socket |+// websocket | concurrency.+//+// Proxy overhead is time inside the proxy only: lease → upstream request+// headers written, minus waiting for an upstream connection (reported apart+// as `conn_wait_ms`, with `conn_reused`); plus upstream first response byte+// → first flush to the client.+//+// A request on a `responses` route also reports `first_output_ms` (headers+// written → its first output item) and the `service_tier` it was served on,+// from its stream (responses.go); `ttfb_ms` ends at `response.created`,+// before the model produced anything.+//+// Over a WebSocket (websocket.go) the handshake's model.request (status 101)+// spans the connection and adds `transport`, `responses` (how many it+// carried) and `closed` (idle | rebind | drain, when the proxy closed it);+// each response on it has its own model.request (the route of the same path+// over HTTP, transport websocket, ttfb_ms from its response.create, and+// `prewarm` for a generate:false warm-up).+package main++import (+ "errors"+ "net/http"+ "net/http/httptrace"+ "sync/atomic"+ "time"+)++type reqState struct {+ start time.Time+ path string+ upgrade bool // the request asks to switch protocols+ caller string+ prof *profile // the binding's; nil before it is known+ rs *routeSpec // nil: not (yet) on the profile's allowlist+ route string // rs.name+ concKey string // the profile's concurrency key, expanded+ held time.Duration+ holdEnd string // "" (never waited) | bound | timeout | cancelled+ sessionKey string+ key string+ vars map[string]string // never logged, never in an event+ lease *lease+ connWait *time.Timer // cancels the request while it queues for an upstream connection (proxy.go)+ ws *wsTunnel // a WS route, once switched+ swapped bool+ proxied bool+ leased int64++ denyReason string+ denyErr string // the denial's envelope error_type, if it has one+ ownErrType string+ resp responsesFacts // a responses route: what its stream said (responses.go)+ status int+ stream bool++ // offsets from start in ns (+1 so 0 means unset); set from transport goroutines+ getConn, gotConn, wroteHeaders, firstByte, firstOut atomic.Int64+ reused atomic.Bool+ bytesIn, bytesOut atomic.Int64+ clientErr, upstreamReadErr, cancelled atomic.Bool+ transportErr string+}++func (s *reqState) since() int64 { return int64(time.Since(s.start)) + 1 }++// profileName is the event's profile: "" before the binding is known.+func (s *reqState) profileName() string {+ if s.prof == nil {+ return ""+ }+ return s.prof.name+}++func (s *reqState) trace(up *upstream) *httptrace.ClientTrace {+ return &httptrace.ClientTrace{+ GetConn: func(string) { s.getConn.CompareAndSwap(0, s.since()) },+ GotConn: func(i httptrace.GotConnInfo) {+ s.stopConnWait()+ s.gotConn.CompareAndSwap(0, s.since())+ s.reused.Store(i.Reused)+ if !i.Reused {+ up.poolMiss.Add(1)+ }+ },+ // A dial for this request has its own limits (upstream.go).+ ConnectStart: func(string, string) { s.stopConnWait() },+ WroteHeaders: func() { s.wroteHeaders.CompareAndSwap(0, s.since()) },+ GotFirstResponseByte: func() { s.firstByte.CompareAndSwap(0, s.since()) },+ }+}++func (s *reqState) stopConnWait() {+ if s.connWait != nil {+ s.connWait.Stop()+ }+}++// overheadPre: lease → upstream headers written, minus the connection wait.+func (s *reqState) overheadPre() (time.Duration, bool) {+ wh := s.wroteHeaders.Load()+ if wh == 0 || s.leased == 0 {+ return 0, false+ }+ d := wh - s.leased+ if gc, gt := s.getConn.Load(), s.gotConn.Load(); gc != 0 && gt >= gc {+ d -= gt - gc+ }+ return time.Duration(max(d, 0)), true+}++// overheadFirstByte: upstream first byte → first flush to the client.+func (s *reqState) overheadFirstByte() (time.Duration, bool) {+ fb, fo := s.firstByte.Load(), s.firstOut.Load()+ if fb == 0 || fo == 0 || fo < fb {+ return 0, false+ }+ return time.Duration(fo - fb), true+}++func (p *Proxy) finish(st *reqState, r *http.Request) {+ rec := recover()+ if rec != nil && !errors.Is(asError(rec), http.ErrAbortHandler) {+ panic(rec)+ }+ now := p.now()+ if st.holdEnd == "bound" || st.holdEnd == "timeout" {+ e := newEvent(now, "model.held")+ e.SessionKey = st.sessionKey+ e.Profile = st.profileName()+ e.DurationMs = msPtr(st.held)+ e.Outcome = "completed"+ if st.holdEnd == "timeout" {+ e.Outcome, e.ErrorType = "timed_out", "timeout"+ }+ e.Data = map[string]any{"held_ms": ms(st.held), "released": st.holdEnd}+ p.out.send(e)+ }+ if st.denyReason != "" {+ if ok, suppressed := p.refusals.allow(now, st.caller, st.denyReason); ok {+ e := newEvent(now, "model.denied")+ e.SessionKey = st.sessionKey+ e.Profile = st.profileName()+ e.Outcome = "failed"+ e.ErrorType = st.denyErr+ route := st.route+ if route == "" {+ route = "other"+ }+ e.Data = map[string]any{"reason": st.denyReason, "route": route, "suppressed": suppressed}+ p.out.send(e)+ logWarn("denied", "reason", st.denyReason, "error_type", st.denyErr, "profile", e.Profile, "route", route,+ "path", truncate(st.path, 120), "caller", st.caller, "session_key", st.sessionKey, "suppressed", suppressed)+ }+ }+ if st.proxied {+ p.out.send(p.requestEvent(st, r, now, rec != nil))+ }+ if p.statsHook != nil {+ p.statsHook(st)+ }+ if rec != nil {+ panic(rec)+ }+}++func (p *Proxy) requestEvent(st *reqState, r *http.Request, now time.Time, aborted bool) eventMsg {+ e := newEvent(now, "model.request")+ e.SessionKey = st.sessionKey+ e.Profile = st.profileName()+ e.DurationMs = msPtr(now.Sub(st.start))+ switch {+ case st.resp.completed.Load():+ // A client may hang up once it has read response.completed: the request is done, not cancelled.+ e.Outcome = "completed"+ case st.cancelled.Load() || st.clientErr.Load() || r.Context().Err() != nil:+ e.Outcome = "cancelled"+ case st.transportErr != "":+ e.Outcome, e.ErrorType = "failed", "socket"+ if st.transportErr == "timeout" {+ e.ErrorType = "timeout"+ }+ case st.upstreamReadErr.Load() || aborted:+ e.Outcome, e.ErrorType = "failed", "socket"+ case st.status == http.StatusTooManyRequests:+ e.Outcome, e.ErrorType = "failed", "provider_rate_limited"+ case st.status >= 400:+ e.Outcome, e.ErrorType = "failed", "provider_error"+ default:+ e.Outcome = "completed"+ }+ data := map[string]any{"route": st.route, "stream": st.stream, "swapped": st.swapped}+ if st.status != 0 {+ data["status"] = st.status+ }+ if st.key != "" {+ data["key"] = st.key+ }+ if gc, gt := st.getConn.Load(), st.gotConn.Load(); gc != 0 && gt >= gc {+ data["conn_wait_ms"], data["conn_reused"] = ms(time.Duration(gt-gc)), st.reused.Load()+ }+ pre, ok1 := st.overheadPre()+ fb, ok2 := st.overheadFirstByte()+ if ok1 || ok2 {+ data["overhead_us"] = (pre + fb).Microseconds()+ }+ if wh, fbt := st.wroteHeaders.Load(), st.firstByte.Load(); wh != 0 && fbt >= wh {+ data["ttfb_ms"] = ms(time.Duration(fbt - wh))+ }+ if wh, fo := st.wroteHeaders.Load(), st.resp.firstOutput.Load(); wh != 0 && fo >= wh {+ data["first_output_ms"] = ms(time.Duration(fo - wh))+ }+ if t := st.resp.serviceTier(); t != "" {+ data["service_tier"] = t+ }+ if st.ws != nil {+ st.ws.summary(data)+ }+ e.Data = data+ return e+}++func asError(v any) error {+ if err, ok := v.(error); ok {+ return err+ }+ return nil+}++func truncate(s string, n int) string {+ if len(s) > n {+ return s[:n]+ }+ return s+}diff --git a/computer/modelproxy/template.go b/computer/modelproxy/template.gonew file mode 100644index 00000000..1307a11f--- /dev/null+++ b/computer/modelproxy/template.go@@ -0,0 +1,177 @@+// Header templates and globs, the two small languages of a profile+// (profile.go): a header value with {variables} from the binding, and a+// header glob where `*` matches any run of bytes.+//+// Invariants: matching is ASCII case-insensitive; a template or a variable's+// value can neither end a header nor start one (validHeaderValue).+package main++import (+ "fmt"+ "net/textproto"+ "slices"+ "strings"+)++func headerMatches(values []string, glob string) bool {+ for _, v := range values {+ if globMatch(glob, strings.TrimSpace(v)) {+ return true+ }+ for item := range strings.SplitSeq(v, ",") {+ item, _, _ = strings.Cut(item, ";")+ if globMatch(glob, strings.TrimSpace(item)) {+ return true+ }+ }+ }+ return false+}++// globMatch: pattern (lower case, `*` matches any run) against s, ASCII+// case-insensitive.+func globMatch(pattern, s string) bool {+ for {+ star := strings.IndexByte(pattern, '*')+ if star < 0 {+ return strings.EqualFold(pattern, s)+ }+ if len(s) < star || !strings.EqualFold(pattern[:star], s[:star]) {+ return false+ }+ pattern, s = pattern[star+1:], s[star:]+ if pattern == "" {+ return true+ }+ next := strings.IndexByte(pattern, '*')+ if next < 0 {+ return len(s) >= len(pattern) && strings.EqualFold(pattern, s[len(s)-len(pattern):])+ }+ i := indexFold(s, pattern[:next])+ if i < 0 {+ return false+ }+ s = s[i:]+ }+}++func indexFold(s, sub string) int {+ for i := 0; i+len(sub) <= len(s); i++ {+ if strings.EqualFold(s[i:i+len(sub)], sub) {+ return i+ }+ }+ return -1+}++// matchesAny: one of the lower-case header-name globs matches name.+func matchesAny(globs []string, name string) bool {+ for _, g := range globs {+ if globMatch(g, name) {+ return true+ }+ }+ return false+}++func headerGlobs(in []string) ([]string, error) {+ out := make([]string, 0, len(in))+ for _, g := range in {+ if !validHeaderName(strings.ReplaceAll(g, "*", "x")) {+ return nil, fmt.Errorf("bad header glob %q", g)+ }+ out = append(out, strings.ToLower(g))+ }+ return out, nil+}++func headerTemplates(in map[string]string, used map[string]bool) ([]headerValue, error) {+ out := make([]headerValue, 0, len(in))+ for name, v := range in {+ if !validHeaderName(name) {+ return nil, fmt.Errorf("bad header %q", name)+ }+ t, err := parseTemplate(v, used)+ if err != nil {+ return nil, fmt.Errorf("%s: %w", name, err)+ }+ out = append(out, headerValue{name: textproto.CanonicalMIMEHeaderKey(name), value: t})+ }+ sortHeaders(out)+ return out, nil+}++func sortHeaders(h []headerValue) {+ slices.SortFunc(h, func(a, b headerValue) int { return strings.Compare(a.name, b.name) })+}++// template is a header value with {variables}: literal parts alternate with+// variable names, starting with a literal.+type template struct {+ parts []string // parts[0], vars[0], parts[1], vars[1], ..., parts[n]+ vars []string+}++func parseTemplate(s string, used map[string]bool) (*template, error) {+ if !validHeaderValue(s) {+ return nil, fmt.Errorf("not a header value")+ }+ t := &template{}+ for {+ open := strings.IndexByte(s, '{')+ if open < 0 {+ if strings.IndexByte(s, '}') >= 0 {+ return nil, fmt.Errorf("unmatched }")+ }+ t.parts = append(t.parts, s)+ return t, nil+ }+ end := strings.IndexByte(s, '}')+ if end < open || !isName(s[open+1:end], "_") {+ return nil, fmt.Errorf("write variables as {name}")+ }+ t.parts = append(t.parts, s[:open])+ t.vars = append(t.vars, s[open+1:end])+ used[s[open+1:end]] = true+ s = s[end+1:]+ }+}++func (t *template) expand(vars map[string]string) string {+ if len(t.vars) == 0 {+ return t.parts[0]+ }+ var b strings.Builder+ for i, v := range t.vars {+ b.WriteString(t.parts[i])+ b.WriteString(vars[v])+ }+ b.WriteString(t.parts[len(t.vars)])+ return b.String()+}++// isName: non-empty, ASCII letters and digits plus the bytes in extra.+func isName(s, extra string) bool {+ if s == "" || len(s) > 64 {+ return false+ }+ for i := 0; i < len(s); i++ {+ c := s[i]+ if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.IndexByte(extra, c) >= 0) {+ return false+ }+ }+ return true+}++func validHeaderName(s string) bool { return isName(s, "-_") }++// validHeaderValue: printable, so it can neither end a header nor start one.+func validHeaderValue(s string) bool {+ for i := 0; i < len(s); i++ {+ if c := s[i]; c < 0x20 && c != '\t' || c == 0x7f {+ return false+ }+ }+ return true+}diff --git a/computer/modelproxy/testdata/control/bind-refuse.json b/computer/modelproxy/testdata/control/bind-refuse.jsonnew file mode 100644index 00000000..260b1921--- /dev/null+++ b/computer/modelproxy/testdata/control/bind-refuse.json@@ -0,0 +1 @@+{"t":"bind","caller":"abc123","sessionKey":"T0/C0/1700000000.000100","mode":"refuse","reason":"paused by its owner"}diff --git a/computer/modelproxy/testdata/control/bind.json b/computer/modelproxy/testdata/control/bind.jsonnew file mode 100644index 00000000..d3da39a0--- /dev/null+++ b/computer/modelproxy/testdata/control/bind.json@@ -0,0 +1 @@+{"t":"bind","id":"b1","caller":"abc123","sessionKey":"T0/C0/1700000000.000100","profile":"openai-key","vars":{"token":"sk-example"},"key":"k1"}diff --git a/computer/modelproxy/testdata/control/bound.json b/computer/modelproxy/testdata/control/bound.jsonnew file mode 100644index 00000000..8c58b437--- /dev/null+++ b/computer/modelproxy/testdata/control/bound.json@@ -0,0 +1 @@+{"t":"bound","id":"b1","caller":"abc123","sessionKey":"T0/C0/1700000000.000100","key":"k1"}diff --git a/computer/modelproxy/testdata/control/event-binding.json b/computer/modelproxy/testdata/control/event-binding.jsonnew file mode 100644index 00000000..0041a1ec--- /dev/null+++ b/computer/modelproxy/testdata/control/event-binding.json@@ -0,0 +1 @@+{"t":"event","name":"model.binding","at":1792520091000,"outcome":"completed","session_key":"T0/C0/1700000000.000100","profile":"openai-key","data":{"action":"bind","caller":"abc123","mode":"profile","key":"k1"}}diff --git a/computer/modelproxy/testdata/control/event-denied.json b/computer/modelproxy/testdata/control/event-denied.jsonnew file mode 100644index 00000000..949b73b8--- /dev/null+++ b/computer/modelproxy/testdata/control/event-denied.json@@ -0,0 +1 @@+{"t":"event","name":"model.denied","at":1792520091000,"outcome":"failed","session_key":"T0/C0/1700000000.000100","profile":"openai-key","data":{"reason":"route","route":"other","suppressed":0}}diff --git a/computer/modelproxy/testdata/control/event-held.json b/computer/modelproxy/testdata/control/event-held.jsonnew file mode 100644index 00000000..c6d9d80d--- /dev/null+++ b/computer/modelproxy/testdata/control/event-held.json@@ -0,0 +1 @@+{"t":"event","name":"model.held","at":1792520091000,"outcome":"completed","duration_ms":412.0,"session_key":"T0/C0/1700000000.000100","profile":"openai-key","data":{"held_ms":412.0,"released":"bound"}}diff --git a/computer/modelproxy/testdata/control/event-pool.json b/computer/modelproxy/testdata/control/event-pool.jsonnew file mode 100644index 00000000..92ef5edb--- /dev/null+++ b/computer/modelproxy/testdata/control/event-pool.json@@ -0,0 +1 @@+{"t":"event","name":"model.pool","at":1792520091000,"outcome":"completed","profile":"openai-key","data":{"open_conns":3,"idle_conns":2,"active_streams":1,"idle_pool_miss":1,"dials":1,"bindings":4,"dropped_messages":0}}diff --git a/computer/modelproxy/testdata/control/event-proxy-started.json b/computer/modelproxy/testdata/control/event-proxy-started.jsonnew file mode 100644index 00000000..c1de2c37--- /dev/null+++ b/computer/modelproxy/testdata/control/event-proxy-started.json@@ -0,0 +1 @@+{"t":"event","name":"model.proxy_started","at":1792520091000,"outcome":"completed","data":{"version":"3b8618e","bindings":0}}diff --git a/computer/modelproxy/testdata/control/event-request.json b/computer/modelproxy/testdata/control/event-request.jsonnew file mode 100644index 00000000..e3f4d73c--- /dev/null+++ b/computer/modelproxy/testdata/control/event-request.json@@ -0,0 +1 @@+{"t":"event","name":"model.request","at":1792520091000,"outcome":"completed","duration_ms":1234.5,"session_key":"T0/C0/1700000000.000100","profile":"openai-key","data":{"route":"responses","stream":true,"swapped":false,"status":200,"key":"k1","conn_wait_ms":0.01,"conn_reused":true,"overhead_us":180,"ttfb_ms":812.4}}diff --git a/computer/modelproxy/testdata/control/hello.json b/computer/modelproxy/testdata/control/hello.jsonnew file mode 100644index 00000000..a2bcc391--- /dev/null+++ b/computer/modelproxy/testdata/control/hello.json@@ -0,0 +1 @@+{"t":"hello","version":"3b8618e","protocol":1,"placeholder":"ssh-placeholder","profiles":[{"name":"openai-key","vars":["token"],"harness":{"codex":{}}},{"name":"plain","vars":[],"harness":{}}],"bindings":[{"caller":"abc123","sessionKey":"T0/C0/1700000000.000100","mode":"profile","profile":"openai-key","key":"k1"},{"caller":"def456","sessionKey":"T0/C0/1700000000.000200","mode":"refuse"}]}diff --git a/computer/modelproxy/testdata/control/observed-error.json b/computer/modelproxy/testdata/control/observed-error.jsonnew file mode 100644index 00000000..86caec48--- /dev/null+++ b/computer/modelproxy/testdata/control/observed-error.json@@ -0,0 +1 @@+{"t":"observed","sessionKey":"T0/C0/1700000000.000100","caller":"abc123","key":"k1","profile":"openai-key","error":"connect"}diff --git a/computer/modelproxy/testdata/control/observed.json b/computer/modelproxy/testdata/control/observed.jsonnew file mode 100644index 00000000..dada3262--- /dev/null+++ b/computer/modelproxy/testdata/control/observed.json@@ -0,0 +1 @@+{"t":"observed","sessionKey":"T0/C0/1700000000.000100","caller":"abc123","key":"k1","profile":"openai-key","status":429,"headers":{"retry-after":"30"},"body":"{\"error\":{\"type\":\"rate_limit_exceeded\"}}"}diff --git a/computer/modelproxy/testdata/control/refused.json b/computer/modelproxy/testdata/control/refused.jsonnew file mode 100644index 00000000..3e2a5807--- /dev/null+++ b/computer/modelproxy/testdata/control/refused.json@@ -0,0 +1 @@+{"t":"refused","id":"b1","caller":"abc123","code":"caller_in_use","message":"the caller is bound to another session"}diff --git a/computer/modelproxy/testdata/control/release.json b/computer/modelproxy/testdata/control/release.jsonnew file mode 100644index 00000000..3fcbbcee--- /dev/null+++ b/computer/modelproxy/testdata/control/release.json@@ -0,0 +1 @@+{"t":"release","caller":"abc123"}diff --git a/computer/modelproxy/testdata/control/request.json b/computer/modelproxy/testdata/control/request.jsonnew file mode 100644index 00000000..bd8c4e9b--- /dev/null+++ b/computer/modelproxy/testdata/control/request.json@@ -0,0 +1 @@+{"t":"request","id":"3f0e2a1c-5b7d-4e8f-9a0b-1c2d3e4f5a6b","profile":"openai-key","vars":{"token":"sk-example"},"method":"GET","path":"/v1/models","query":"limit=1","headers":{"Accept":"application/json"}}diff --git a/computer/modelproxy/testdata/control/response-error.json b/computer/modelproxy/testdata/control/response-error.jsonnew file mode 100644index 00000000..84b4444d--- /dev/null+++ b/computer/modelproxy/testdata/control/response-error.json@@ -0,0 +1 @@+{"t":"response","id":"3f0e2a1c-5b7d-4e8f-9a0b-1c2d3e4f5a6b","error":"unreachable"}diff --git a/computer/modelproxy/testdata/control/response.json b/computer/modelproxy/testdata/control/response.jsonnew file mode 100644index 00000000..fc8e00d5--- /dev/null+++ b/computer/modelproxy/testdata/control/response.json@@ -0,0 +1 @@+{"t":"response","id":"3f0e2a1c-5b7d-4e8f-9a0b-1c2d3e4f5a6b","status":200,"headers":{"retry-after":"30"},"body":"{\"data\":[]}"}diff --git a/computer/modelproxy/testdata/control/synced.json b/computer/modelproxy/testdata/control/synced.jsonnew file mode 100644index 00000000..d794531d--- /dev/null+++ b/computer/modelproxy/testdata/control/synced.json@@ -0,0 +1 @@+{"t":"synced"}diff --git a/computer/modelproxy/upstream.go b/computer/modelproxy/upstream.gonew file mode 100644index 00000000..6039d8d6--- /dev/null+++ b/computer/modelproxy/upstream.go@@ -0,0 +1,127 @@+// One profile's upstream transport (one each, never shared, see+// profile.go): HTTP/1.1 only (one TCP connection per concurrent stream, so+// one lost packet stalls one stream), no transparent compression (the+// client's accept-encoding passes through), a TLS session cache, and the+// standard library's connection pool.+//+// Limits: 10 s to connect, 10 s more for the TLS handshake, 600 s for the+// response headers (a request that does not stream answers only when the+// model is done); none on a body once its headers are in. How long a request+// may queue for one of MaxConnsPerHost connections is the proxy's (proxy.go).+package main++import (+ "context"+ "crypto/tls"+ "crypto/x509"+ "errors"+ "net"+ "net/http"+ "net/url"+ "sync"+ "sync/atomic"+ "time"+)++const (+ dialTimeout = 10 * time.Second+ tlsHandshakeTimeout = 10 * time.Second+ responseHeaderTimeout = 600 * time.Second+)++type upstreamConfig struct {+ url *url.URL+ maxIdlePerHost int+ maxConnsPerHost int+ idleConnTimeout time.Duration+ rootCAs *x509.CertPool // tests only; nil = system roots+}++type upstream struct {+ cfg upstreamConfig+ tlsConf *tls.Config+ dialer net.Dialer+ transport *http.Transport+ handshakeTimeout time.Duration++ open atomic.Int64 // upstream TCP connections open+ dials atomic.Int64+ streams atomic.Int64 // requests in flight to this upstream (proxy.go)+ poolMiss atomic.Int64 // requests that found no idle connection+}++func newUpstream(cfg upstreamConfig) *upstream {+ u := &upstream{cfg: cfg, handshakeTimeout: tlsHandshakeTimeout, dialer: net.Dialer{Timeout: dialTimeout, KeepAlive: 30 * time.Second}}+ u.tlsConf = &tls.Config{+ ServerName: cfg.url.Hostname(),+ NextProtos: []string{"http/1.1"},+ ClientSessionCache: tls.NewLRUClientSessionCache(256),+ MinVersion: tls.VersionTLS12,+ RootCAs: cfg.rootCAs,+ }+ u.transport = &http.Transport{+ Proxy: nil, // never an environment proxy+ DialTLSContext: u.dialTLS,+ TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{}, // HTTP/1.1 only+ ForceAttemptHTTP2: false,+ DisableCompression: true,+ MaxIdleConnsPerHost: cfg.maxIdlePerHost,+ MaxConnsPerHost: cfg.maxConnsPerHost,+ IdleConnTimeout: cfg.idleConnTimeout,+ ResponseHeaderTimeout: responseHeaderTimeout,+ }+ return u+}++// countedConn decrements the open-connection gauge once on Close.+type countedConn struct {+ net.Conn+ u *upstream+ once sync.Once+}++func (c *countedConn) Close() error {+ c.once.Do(func() { c.u.open.Add(-1) })+ return c.Conn.Close()+}++func (u *upstream) dialTLS(ctx context.Context, network, addr string) (net.Conn, error) {+ raw, err := u.dialer.DialContext(ctx, network, addr)+ if err != nil {+ return nil, err+ }+ u.open.Add(1)+ u.dials.Add(1)+ tc := tls.Client(&countedConn{Conn: raw, u: u}, u.tlsConf)+ ctx, cancel := context.WithTimeout(ctx, u.handshakeTimeout)+ defer cancel()+ if err := tc.HandshakeContext(ctx); err != nil {+ tc.Close()+ return nil, err+ }+ return tc, nil+}++func (u *upstream) close() { u.transport.CloseIdleConnections() }++// errorClass is a closed class for an upstream transport error: never the+// error text, which may carry addresses.+func errorClass(err error) string {+ var ne net.Error+ var tlsErr *tls.CertificateVerificationError+ switch {+ case errors.Is(err, context.Canceled):+ return "canceled"+ case errors.Is(err, context.DeadlineExceeded):+ return "timeout"+ case errors.As(err, &tlsErr):+ return "tls_verify"+ case errors.As(err, &ne) && ne.Timeout():+ return "timeout"+ }+ var oe *net.OpError+ if errors.As(err, &oe) && oe.Op == "dial" {+ return "connect"+ }+ return "transport"+}diff --git a/computer/modelproxy/upstream_test.go b/computer/modelproxy/upstream_test.gonew file mode 100644index 00000000..81f016e9--- /dev/null+++ b/computer/modelproxy/upstream_test.go@@ -0,0 +1,87 @@+package main++import (+ "context"+ "io"+ "net"+ "net/url"+ "testing"+ "time"+)++// The pool event carries the gauges and the counters since the last one.+func TestPoolEvent(t *testing.T) {+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ for range 2 { // the second reuses the first's connection+ res := do(t, h, testCaller)+ io.Copy(io.Discard, res.Body)+ res.Body.Close()+ }+ e := mainPool(h)+ if e.Name != "model.pool" || e.Profile != mainProfile || e.Data["dials"] != int64(1) || e.Data["idle_pool_miss"] != int64(1) ||+ e.Data["bindings"] != 1 || e.Data["open_conns"] != int64(1) || e.Data["dropped_messages"] == nil {+ t.Fatalf("pool event %+v", e)+ }+ if e := mainPool(h); e.Data["dials"] != int64(0) {+ t.Fatalf("counters not reset: %+v", e.Data)+ }+}++// A TLS handshake the upstream never answers ends at the handshake timeout.+func TestStalledHandshake(t *testing.T) {+ l, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer l.Close()+ go func() {+ for {+ c, err := l.Accept()+ if err != nil {+ return+ }+ defer c.Close() // accepted, never answered+ }+ }()+ u := newUpstream(upstreamConfig{url: &url.URL{Scheme: "https", Host: l.Addr().String()}})+ u.handshakeTimeout = 100 * time.Millisecond+ start := time.Now()+ _, err = u.dialTLS(context.Background(), "tcp", l.Addr().String())+ if took := time.Since(start); err == nil || errorClass(err) != "timeout" || took > 2*time.Second {+ t.Fatalf("err %v after %v", err, took)+ }+ if u.open.Load() != 0 {+ t.Fatalf("open %d", u.open.Load())+ }+}++// mainPool is the main profile's pool event, as the first profile's.+func mainPool(h *harness) eventMsg {+ e, _ := h.srv.poolEvent(h.srv.profiles.get(mainProfile), true)+ return e+}++// Each profile reports its own pool; an idle one that is not the first has+// nothing to say, and only the first carries the proxy-wide gauges.+func TestPoolEventPerProfile(t *testing.T) {+ up, _ := okUpstream()+ h := newHarness(t, up, harnessOpts{})+ k := h.dialControl()+ h.bindReady(k, testCaller, "s1", "tok", "fp1")+ if res := do(t, h, testCaller); res.StatusCode != 200 {+ t.Fatalf("status %d", res.StatusCode)+ }+ if _, ok := h.srv.poolEvent(h.srv.profiles.get(altProfile), false); ok {+ t.Fatal("an idle profile reported its pool")+ }+ e, ok := h.srv.poolEvent(h.srv.profiles.get(mainProfile), false)+ if !ok || e.Profile != mainProfile || e.Data["dials"] != int64(1) || e.Data["bindings"] != nil {+ t.Fatalf("pool event %+v", e)+ }+ if e, ok := h.srv.poolEvent(h.srv.profiles.get(altProfile), true); !ok || e.Data["bindings"] != 1 {+ t.Fatalf("first profile's event %+v", e)+ }+}diff --git a/computer/modelproxy/util_test.go b/computer/modelproxy/util_test.gonew file mode 100644index 00000000..ebc86b7d--- /dev/null+++ b/computer/modelproxy/util_test.go@@ -0,0 +1,8 @@+package main++import (+ "io"+ "strings"+)++func stringsReader(s string) io.Reader { return strings.NewReader(s) }diff --git a/computer/modelproxy/websocket.go b/computer/modelproxy/websocket.gonew file mode 100644index 00000000..039fa24a--- /dev/null+++ b/computer/modelproxy/websocket.go@@ -0,0 +1,365 @@+// A profile's WS route: a Responses WebSocket (`WS /v1/responses`), tunnelled+// to the upstream. Over it a client such as Codex keeps one connection per+// session, warms it when the thread starts (a `generate:false` request) and+// sends each request as only its new input on top of the previous response+// (`previous_response_id`); over HTTP every request carries the whole+// context again.+//+// The handshake is admitted like any request (proxy.go: placeholder, caller,+// caps, hold, lease, the route's `require`) and rewritten like one+// (outbound.go), minus Sec-WebSocket-Extensions, so no compression is+// negotiated and frames stay readable. Every refusal of an upgrade, the+// proxy's own or the upstream's (any status but 101), reaches the client as+// a 426: on a 426 Codex goes on over HTTP at once, where the same refusal is+// served in its usual terms; on a 401/403/404/503 it would first reconnect+// for several seconds, and on a 429 it fails the turn.+//+// Once switched, ReverseProxy copies bytes both ways through wsTunnel, which+// reads the frames as they pass (wsframe.go) for:+// - one model.request per response (transport websocket): ttfb from its+// response.create to its first event, first output, the tier served,+// the outcome;+// - `observed` (observed.go): the handshake's headers, then each+// response.completed as an HTTP 200 and each `error` event's status and+// headers as an HTTP error's;+// - when to close: with no response in flight, once the tunnel is stale+// (the lease is no longer current: a rebind, refuse or release applies+// to new requests at once, and the handshake carried the old variables;+// or the proxy is draining: http.Server.Shutdown does not wait for a+// hijacked connection, so shutdown waits for tunnels itself, up to+// -drain-timeout), or after -ws-idle-timeout. And at once when a+// response.create arrives on a stale tunnel, before it is sent. The+// client reconnects on its next request and sends it whole.+//+// Invariants: a tunnel is one request for the caller's cap and the lease,+// held for its whole life, and each response on it one for the profile's+// concurrency cap (the handshake is refused at the cap; a response.create on+// an open tunnel cannot be, so it counts past it); frames are never altered,+// held back or read ahead of either side; the proxy never cuts a response in+// flight (unless it has run wsStuck without an end this reader knows, or the+// client sends another on a stale tunnel while it runs);+// nothing from a frame is kept but the facts above.+package main++import (+ "context"+ "io"+ "net/http"+ "sync"+ "sync/atomic"+ "time"+)++const (+ // wsTypeHead: an event's `type` is among its first bytes.+ wsTypeHead = 256+ // wsErrorHead: an `error` event is short; this much is read of one.+ wsErrorHead = 4 << 10+ // wsUseHTTP starts every refusal of an upgrade: the client shows it only+ // if HTTP fails too.+ wsUseHTTP = "Use HTTP: "+ // wsStuck: a response in flight this long no longer keeps the tunnel+ // open past a rebind, idle or drain (an end this reader missed).+ wsStuck = time.Hour+)++// markNoGenerate is a warm-up request's flag (a client's startup prewarm).+var markNoGenerate = []byte(`"generate":false`)++// wsResponse is one response.create on a tunnel, until its last event.+type wsResponse struct {+ start, firstEvent, firstOutput time.Time+ tier string+ prewarm bool+}++type wsTunnel struct {+ io.ReadWriteCloser // the upstream connection, after its 101+ p *Proxy+ st *reqState // the handshake's+ toUp, toClient *wsFrames+ client wsClientMsg+ server wsServerMsg++ mu sync.Mutex+ queue []*wsResponse // in flight, oldest first+ responses int+ closed string // why the proxy closed it: idle | rebind | drain+ ended bool+ upErr bool+ lastByte atomic.Int64 // unix ns of the last bytes either way; idle counts from it++ kick chan struct{} // a response ended+ done chan struct{}+ closeOnce sync.Once+}++func newWSTunnel(p *Proxy, st *reqState, up io.ReadWriteCloser) *wsTunnel {+ p.wsOpen.Add(1)+ t := &wsTunnel{ReadWriteCloser: up, p: p, st: st, kick: make(chan struct{}, 1), done: make(chan struct{})}+ t.lastByte.Store(p.now().UnixNano())+ t.client.t, t.server.t = t, t+ t.toUp, t.toClient = newWSFrames(&t.client), newWSFrames(&t.server)+ go t.watch()+ return t+}++// Write carries the client's bytes upstream.+func (t *wsTunnel) Write(p []byte) (int, error) {+ t.toUp.feed(p)+ t.lastByte.Store(t.p.now().UnixNano())+ return t.ReadWriteCloser.Write(p)+}++// Read carries the upstream's bytes to the client.+func (t *wsTunnel) Read(p []byte) (int, error) {+ n, err := t.ReadWriteCloser.Read(p)+ if n > 0 {+ t.toClient.feed(p[:n])+ t.lastByte.Store(t.p.now().UnixNano())+ }+ if err != nil && err != io.EOF {+ select {+ case <-t.done: // closed by the proxy or the client+ default:+ t.mu.Lock()+ t.upErr = true+ t.mu.Unlock()+ }+ }+ return n, err+}++func (t *wsTunnel) Close() error {+ err := error(nil)+ t.closeOnce.Do(func() {+ close(t.done)+ err = t.ReadWriteCloser.Close()+ })+ return err+}++// watch closes the tunnel between responses once its lease is stale or it+// has been idle too long.+func (t *wsTunnel) watch() {+ timer := time.NewTimer(time.Hour)+ defer timer.Stop()+ drain := t.p.wsDrain+ for {+ changed := t.p.bindings.changes()+ why, wait := t.closeReason()+ if why != "" {+ t.Close()+ return+ }+ timer.Reset(wait)+ select {+ case <-t.done:+ return+ case <-changed:+ case <-drain:+ drain = nil // closed for good: wake for it once+ case <-t.kick:+ case <-timer.C:+ }+ }+}++// closeReason: why to close now, else how long until the idle limit.+func (t *wsTunnel) closeReason() (string, time.Duration) {+ now := t.p.now()+ t.mu.Lock()+ defer t.mu.Unlock()+ if len(t.queue) > 0 {+ // A response's end kicks. One never seen to end (an event this+ // reader does not know) stops holding the tunnel open after wsStuck.+ if age := now.Sub(t.queue[0].start); age < wsStuck {+ return "", wsStuck - age+ }+ }+ if t.ended {+ return "", time.Hour+ }+ if t.closed = t.stale(); t.closed != "" {+ return t.closed, 0+ }+ if t.p.wsIdle <= 0 {+ return "", time.Hour+ }+ if left := t.p.wsIdle - now.Sub(time.Unix(0, t.lastByte.Load())); left > 0 {+ return "", left+ }+ t.closed = "idle"+ return t.closed, 0+}++// stale: why the tunnel may start no further response: the proxy is+// draining, or the lease is no longer current.+func (t *wsTunnel) stale() string {+ switch {+ case t.p.draining():+ return "drain"+ case !t.st.lease.current():+ return "rebind"+ }+ return ""+}++// created counts a response.create, read before its last bytes go upstream+// (Write). On a stale tunnel it closes the tunnel instead, so that write+// fails and no response starts on a credential the caller no longer has.+func (t *wsTunnel) created(prewarm bool) {+ now := t.p.now()+ why := t.stale()+ t.mu.Lock()+ switch {+ case t.ended:+ case why != "":+ t.closed = why+ default:+ t.queue = append(t.queue, &wsResponse{start: now, prewarm: prewarm})+ t.responses+++ t.st.prof.perKey.add(t.st.concKey) // under mu: end gives back exactly what is queued+ }+ t.mu.Unlock()+ if why != "" {+ t.Close()+ }+}++// event is one upstream event: typ is its `type`, tier the service tier it+// names, head its first bytes (all of a short one).+func (t *wsTunnel) event(typ, tier string, head []byte) {+ now := t.p.now()+ status, hdr := 0, http.Header(nil)+ if typ == "error" {+ status, hdr = wsError(head)+ }+ outcome, errType := "", ""+ switch typ {+ case "response.completed", "response.incomplete":+ outcome = "completed"+ case "response.failed", "error":+ outcome, errType = "failed", "provider_error"+ if status == http.StatusTooManyRequests {+ errType = "provider_rate_limited"+ }+ }+ t.mu.Lock()+ var r *wsResponse+ if len(t.queue) > 0 {+ r = t.queue[0]+ if r.firstEvent.IsZero() {+ r.firstEvent = now+ }+ if typ == "response.output_item.added" && r.firstOutput.IsZero() {+ r.firstOutput = now+ }+ if tier != "" {+ r.tier = tier+ }+ if outcome != "" {+ t.queue = t.queue[1:]+ }+ }+ t.mu.Unlock()+ if r != nil && outcome != "" {+ t.st.prof.perKey.leave(t.st.concKey)+ t.p.out.send(t.responseEvent(r, now, outcome, errType, status))+ select {+ case t.kick <- struct{}{}:+ default:+ }+ }+ switch {+ case typ == "response.completed":+ t.p.observer.response(t.st.subject(), http.StatusOK, nil, nil)+ case typ == "error" && status != 0:+ t.p.observer.response(t.st.subject(), status, hdr, head)+ }+}++// end follows ReverseProxy's copy: responses still in flight end cancelled,+// or failed (socket) when the upstream cut the connection.+func (t *wsTunnel) end() {+ defer t.p.wsOpen.Done()+ t.Close()+ now := t.p.now()+ t.mu.Lock()+ q, upErr := t.queue, t.upErr+ t.queue, t.ended = nil, true+ t.mu.Unlock()+ for _, r := range q {+ t.st.prof.perKey.leave(t.st.concKey)+ if upErr {+ t.p.out.send(t.responseEvent(r, now, "failed", "socket", 0))+ } else {+ t.p.out.send(t.responseEvent(r, now, "cancelled", "", 0))+ }+ }+}++// draining: shutdown has begun.+func (p *Proxy) draining() bool {+ select {+ case <-p.wsDrain:+ return true+ default:+ return false+ }+}++// drainWS has every tunnel close at its next response boundary, then waits+// for them up to ctx. Called once, at shutdown.+func (p *Proxy) drainWS(ctx context.Context, wait bool) {+ p.wsDrainOnce.Do(func() { close(p.wsDrain) })+ if !wait {+ return+ }+ done := make(chan struct{})+ go func() { p.wsOpen.Wait(); close(done) }()+ select {+ case <-done:+ case <-ctx.Done():+ }+}++// summary is what the handshake's own model.request adds.+func (t *wsTunnel) summary(data map[string]any) {+ t.mu.Lock()+ defer t.mu.Unlock()+ data["transport"] = "websocket"+ data["responses"] = t.responses+ if t.closed != "" {+ data["closed"] = t.closed+ }+}++func (t *wsTunnel) responseEvent(r *wsResponse, now time.Time, outcome, errType string, status int) eventMsg {+ e := newEvent(now, "model.request")+ e.SessionKey = t.st.sessionKey+ e.Profile = t.st.prof.name+ e.DurationMs = msPtr(now.Sub(r.start))+ e.Outcome, e.ErrorType = outcome, errType+ data := map[string]any{"route": t.st.rs.respName, "transport": "websocket", "stream": true}+ if status != 0 {+ data["status"] = status+ }+ if t.st.key != "" {+ data["key"] = t.st.key+ }+ if !r.firstEvent.IsZero() {+ data["ttfb_ms"] = ms(r.firstEvent.Sub(r.start))+ }+ if !r.firstOutput.IsZero() {+ data["first_output_ms"] = ms(r.firstOutput.Sub(r.start))+ }+ if r.tier != "" {+ data["service_tier"] = r.tier+ }+ if r.prewarm {+ data["prewarm"] = true+ }+ e.Data = data+ return e+}diff --git a/computer/modelproxy/websocket_test.go b/computer/modelproxy/websocket_test.gonew file mode 100644index 00000000..5b4f9a5a--- /dev/null+++ b/computer/modelproxy/websocket_test.go@@ -0,0 +1,422 @@+package main++import (+ "bufio"+ "context"+ "io"+ "net/http"+ "strings"+ "sync/atomic"+ "syscall"+ "testing"+ "time"+)++// wsPeer is one end of a WebSocket in a test: the client's frames are+// masked, the upstream's are not.+type wsPeer struct {+ t testing.TB+ r *bufio.Reader+ w io.Writer+ c io.Closer+ mask []byte+}++func (p *wsPeer) send(msg string) {+ p.t.Helper()+ if _, err := p.w.Write(wsFrame(1, true, []byte(msg), p.mask)); err != nil {+ p.t.Fatal(err)+ }+}++// recv is the next data message, its fragments joined, control frames skipped.+func (p *wsPeer) recv() string {+ p.t.Helper()+ var msg []byte+ for {+ op, fin, b, err := readWSFrame(p.r)+ if err != nil {+ p.t.Fatalf("recv: %v", err)+ }+ if op >= 8 {+ continue+ }+ msg = append(msg, b...)+ if fin {+ return string(msg)+ }+ }+}++// closed: the peer's connection ends within 3 s.+func (p *wsPeer) closed() {+ p.t.Helper()+ done := make(chan error, 1)+ go func() {+ for {+ if _, _, _, err := readWSFrame(p.r); err != nil {+ done <- err+ return+ }+ }+ }()+ select {+ case <-done:+ case <-time.After(3 * time.Second):+ p.t.Fatal("connection not closed")+ }+}++// wsUpstream is a fake upstream: a handshake gets status (101: switched,+// the connection handed to the test on conns), its headers on reqs.+func wsUpstream(t testing.TB, status int, hdr http.Header, body string, reqs chan<- *http.Request, conns chan<- *wsPeer) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if reqs != nil {+ reqs <- r.Clone(context.Background())+ }+ if status != http.StatusSwitchingProtocols {+ for k, v := range hdr {+ w.Header()[k] = v+ }+ w.WriteHeader(status)+ io.WriteString(w, body)+ return+ }+ c, brw, err := http.NewResponseController(w).Hijack()+ if err != nil {+ t.Error(err)+ return+ }+ brw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n" ++ "X-Quota-Used: 12\r\n\r\n")+ brw.Flush()+ conns <- &wsPeer{t: t, r: brw.Reader, w: c, c: c}+ })+}++// wsHandshake is a client's handshake on the alt profile's WS route.+func (h *harness) wsHandshake() *http.Request {+ req, _ := http.NewRequest(http.MethodGet, h.apiURL+"/v1/responses", nil)+ for k, v := range map[string]string{+ "Connection": "Upgrade", "Upgrade": "websocket", "Sec-Websocket-Version": "13",+ "Sec-Websocket-Key": wsNonce, "Sec-Websocket-Extensions": "permessage-deflate; client_max_window_bits",+ "Authorization": placeholderAuth, "X-Proto": "ws=1", "Originator": "its-own",+ "User-Agent": "test-client/1.0", "X-Turn-Metadata": `{"turn":1}`,+ } {+ req.Header.Set(k, v)+ }+ return req+}++// openWS opens the client's end, failing unless it switched.+func (h *harness) openWS(caller string) *wsPeer {+ h.t.Helper()+ res, err := h.client(caller).Do(h.wsHandshake())+ if err != nil {+ h.t.Fatal(err)+ }+ if res.StatusCode != http.StatusSwitchingProtocols {+ b, _ := io.ReadAll(res.Body)+ h.t.Fatalf("handshake: %d %s", res.StatusCode, b)+ }+ rwc := res.Body.(io.ReadWriteCloser)+ h.t.Cleanup(func() { rwc.Close() })+ return &wsPeer{t: h.t, r: bufio.NewReader(rwc), w: rwc, c: rwc, mask: []byte{7, 1, 9, 3}}+}++// The tunnel: the handshake reaches the upstream with the binding's+// variables and no compression offer; frames pass both ways unchanged (fragments and+// pings included); each response is its own model.request (ttfb, first+// output, tier, prewarm), the connection one more when it ends.+func TestWSTunnel(t *testing.T) {+ reqs, conns := make(chan *http.Request, 1), make(chan *wsPeer, 1)+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{alt: wsUpstream(t, 101, nil, "", reqs, conns)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ c := h.openWS(altCaller)+ up, r := <-conns, <-reqs+ if r.URL.Path != "/base/x/responses" || r.Header.Get("Authorization") != "Bearer tok" || r.Header.Get("X-Account") != altAccount ||+ r.Header.Get("Sec-Websocket-Extensions") != "" || r.Header.Get("X-Proto") != "ws=1" || r.Header.Get("Upgrade") != "websocket" ||+ r.Header.Get("Originator") != "fixed" || r.Header.Get("X-Turn-Metadata") == "" {+ t.Fatalf("handshake upstream: %s %v", r.URL.Path, r.Header)+ }++ warm := `{"type":"response.create","model":"m","generate":false,"input":[]}`+ c.send(warm)+ if got := up.recv(); got != warm {+ t.Fatalf("upstream got %q", got)+ }+ for _, m := range []string{`{"type":"response.created","response":{"id":"r1"}}`, `{"type":"response.completed","response":{"id":"r1","service_tier":"default"}}`} {+ up.send(m)+ if got := c.recv(); got != m {+ t.Fatalf("client got %q", got)+ }+ }+ e := k.waitFor(isRoute("responses"))+ if d := evData(e); e["outcome"] != "completed" || d["transport"] != "websocket" || d["prewarm"] != true || d["service_tier"] != "default" ||+ d["ttfb_ms"] == nil || d["key"] != "fpC" || e["session_key"] != "s1" || e["profile"] != altProfile {+ t.Fatalf("prewarm event %v", e)+ }++ // The next request in fragments, a ping between them.+ c.w.Write(wsFrame(1, false, []byte(`{"type":"response.cre`), c.mask))+ c.w.Write(wsFrame(9, true, []byte("p"), c.mask))+ c.w.Write(wsFrame(0, true, []byte(`ate","previous_response_id":"r1","input":[{"type":"message"}]}`), c.mask))+ if got := up.recv(); !strings.HasPrefix(got, `{"type":"response.create","previous_response_id":"r1"`) {+ t.Fatalf("upstream got %q", got)+ }+ big := strings.Repeat("z", 10000)+ for _, m := range []string{+ `{"type":"response.created","response":{"id":"r2","service_tier":"auto"}}`,+ `{"type":"response.output_item.added","item":{"type":"message"}}`,+ `{"type":"response.output_text.delta","delta":"` + big + `"}`,+ `{"type":"response.completed","response":{"id":"r2","output":[{"text":"` + big + `"}],"service_tier":"priority"}}`,+ } {+ up.send(m)+ if got := c.recv(); got != m {+ t.Fatalf("client got %.60q", got)+ }+ }+ e = k.waitFor(isRoute("responses"))+ if d := evData(e); e["outcome"] != "completed" || d["prewarm"] != nil || d["service_tier"] != "priority" || d["first_output_ms"] == nil {+ t.Fatalf("event %v", e)+ }++ c.c.Close()+ e = k.waitFor(isRoute("responses_ws"))+ if d := evData(e); e["outcome"] != "completed" || d["status"] != float64(101) || d["responses"] != float64(2) || d["transport"] != "websocket" || d["closed"] != nil {+ t.Fatalf("connection event %v", e)+ }+ up.closed()+}++// A rebind applies at once; the response in flight on a tunnel ends, then+// the proxy closes the tunnel (it carried the old variables).+func TestWSRebindClosesBetweenResponses(t *testing.T) {+ conns := make(chan *wsPeer, 1)+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{alt: wsUpstream(t, 101, nil, "", nil, conns)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ c := h.openWS(altCaller)+ up := <-conns+ c.send(`{"type":"response.create","input":[]}`)+ up.recv()+ up.send(`{"type":"response.created"}`)+ c.recv()++ h.bindAltReady(k, altCaller, "s1", "tok2", "fp2", altAccount)+ up.send(`{"type":"response.completed","response":{}}`)+ c.recv()+ c.closed()+ if e := k.waitFor(isRoute("responses_ws")); evData(e)["closed"] != "rebind" {+ t.Fatalf("connection event %v", e)+ }+}++// An idle tunnel closes after -ws-idle-timeout, and at shutdown.+func TestWSIdleAndDrain(t *testing.T) {+ conns := make(chan *wsPeer, 2)+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{alt: wsUpstream(t, 101, nil, "", nil, conns), wsIdle: 150 * time.Millisecond})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ c := h.openWS(altCaller)+ c.closed()+ if e := k.waitFor(isRoute("responses_ws")); evData(e)["closed"] != "idle" {+ t.Fatalf("connection event %v", e)+ }++ h.srv.proxy.wsIdle = 0+ c = h.openWS(altCaller)+ <-conns+ <-conns+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ h.srv.proxy.drainWS(ctx, true)+ c.closed()+ if e := k.waitFor(isRoute("responses_ws")); evData(e)["closed"] != "drain" {+ t.Fatalf("connection event %v", e)+ }+}++// Every refusal on the route is a 426, so the client goes on over HTTP at+// once: a profile without a WS route, the proxy's own (the concurrency cap+// here), the upstream's (its 429 is still reported to the binder).+func TestWSRefusals(t *testing.T) {+ expect426 := func(h *harness, k *ctl) {+ t.Helper()+ res, err := h.client(altCaller).Do(h.wsHandshake())+ if err != nil {+ t.Fatal(err)+ }+ e := decodeAPIError(t, res)+ res.Body.Close()+ if res.StatusCode != http.StatusUpgradeRequired || !strings.HasPrefix(e.Error.Message, wsUseHTTP) {+ t.Fatalf("%d %+v", res.StatusCode, e)+ }+ }++ var hits atomic.Int64+ h := newHarness(t, recordingUpstream(&hits, nil), harnessOpts{alt: recordingUpstream(&hits, nil), noWS: true})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ expect426(h, k)+ if e := k.waitFor(isEvent("model.denied")); evData(e)["reason"] != "websocket" || hits.Load() != 0 {+ t.Fatalf("no WS route: %v, %d hits", e, hits.Load())+ }++ // The cap counts a tunnel's responses, not the tunnel: an idle+ // one blocks nothing, one with a response in flight is the whole cap of 1.+ conns := make(chan *wsPeer, 3)+ h = newHarness(t, recordingUpstream(&hits, nil), harnessOpts{alt: wsUpstream(t, 101, nil, "", nil, conns), perKey: 1})+ k = h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ c := h.openWS(altCaller)+ up := <-conns+ h.openWS(altCaller).c.Close()+ <-conns+ c.send(`{"type":"response.create","input":[]}`)+ up.recv()+ expect426(h, k)+ if e := k.waitFor(isEvent("model.denied")); evData(e)["reason"] != "concurrency_cap" {+ t.Fatalf("cap: %v", e)+ }+ up.send(`{"type":"response.completed","response":{"id":"r1"}}`)+ c.recv()+ k.waitFor(isRoute("responses"))+ h.openWS(altCaller).c.Close()+ <-conns++ limit := http.Header{"Content-Type": {"application/json"}, "X-Quota-Kind": {"primary"}, "X-Other": {"no"}}+ h = newHarness(t, recordingUpstream(&hits, nil), harnessOpts{alt: wsUpstream(t, 429, limit, `{"error":{"type":"quota","resets_at":1792513800}}`, nil, nil)})+ k = h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ expect426(h, k)+ m := k.waitFor(isT("observed"))+ if hd, _ := m["headers"].(map[string]any); m["status"] != float64(429) || m["profile"] != altProfile || m["key"] != "fpC" ||+ len(hd) != 1 || hd["x-quota-kind"] != "primary" || m["body"] != `{"error":{"type":"quota","resets_at":1792513800}}` {+ t.Fatalf("observed %v", m)+ }+ if e := k.waitFor(isRoute("responses_ws")); e["error_type"] != "provider_rate_limited" || evData(e)["status"] != float64(429) {+ t.Fatalf("event %v", e)+ }+}++// An `error` event is an HTTP error's WebSocket form: its status and+// headers are reported to the binder, and it ends the response in flight.+func TestWSErrorEvent(t *testing.T) {+ conns := make(chan *wsPeer, 1)+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{alt: wsUpstream(t, 101, nil, "", nil, conns)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ c := h.openWS(altCaller)+ up := <-conns+ if m := k.waitFor(isT("observed")); m["status"] != float64(101) || m["headers"].(map[string]any)["x-quota-used"] != "12" {+ t.Fatalf("observed %v", m)+ }+ c.send(`{"type":"response.create","input":[]}`)+ up.recv()+ up.send(`{"type":"error","status":429,"error":{"type":"quota","message":"limit","resets_at":1792513800},"headers":{"x-quota-used":100,"x-other":"no"}}`)+ c.recv()+ if e := k.waitFor(isRoute("responses")); e["outcome"] != "failed" || e["error_type"] != "provider_rate_limited" || evData(e)["status"] != float64(429) {+ t.Fatalf("event %v", e)+ }+ m := k.waitFor(isT("observed"))+ if hd, _ := m["headers"].(map[string]any); m["status"] != float64(429) || len(hd) != 1 || hd["x-quota-used"] != "100" ||+ !strings.Contains(m["body"].(string), `"resets_at":1792513800`) {+ t.Fatalf("observed %v", m)+ }+}++func keySlots(h *harness) int {+ c := h.srv.profiles.get(altProfile).perKey+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.n[altAccount]+}++func callerSlots(h *harness, caller string) int {+ c := h.srv.proxy.perCaller+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.n[caller]+}++// A response.create on a tunnel whose lease is no longer current is never+// sent: the tunnel closes instead, whatever is still in flight on it.+func TestWSNoCreateOnStaleTunnel(t *testing.T) {+ conns := make(chan *wsPeer, 1)+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{alt: wsUpstream(t, 101, nil, "", nil, conns)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ c := h.openWS(altCaller)+ up := <-conns+ c.send(`{"type":"response.create","model":"m","input":[]}`)+ up.recv()+ h.bindAltReady(k, altCaller, "s1", "tok2", "fpD", altAccount)++ c.w.Write(wsFrame(1, true, []byte(`{"type":"response.create","model":"m","input":["second"]}`), c.mask))+ c.closed()+ if _, _, b, err := readWSFrame(up.r); err == nil {+ t.Fatalf("the upstream got %q on the old credential", b)+ }+ e := k.waitFor(isRoute("responses_ws"))+ if d := evData(e); d["closed"] != "rebind" || d["responses"] != float64(1) || keySlots(h) != 0 {+ t.Fatalf("event %v, key slots %d", e, keySlots(h))+ }+}++// A response.create read as the tunnel ends (the copy to the upstream may+// outlive the handler by a write) leaves no concurrency slot counted.+func TestWSCreateAtEndLeavesNoSlot(t *testing.T) {+ conns := make(chan *wsPeer, 1)+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{alt: wsUpstream(t, 101, nil, "", nil, conns)})+ ended := make(chan *wsTunnel, 1)+ h.srv.proxy.statsHook = func(st *reqState) { ended <- st.ws }+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ h.openWS(altCaller).c.Close()+ (<-ended).created(false)+ if n := keySlots(h); n != 0 {+ t.Fatalf("key slots %d", n)+ }+}++// A tunnel the upstream closed ends, and frees its caller's slot, without+// waiting for the client to close its side.+func TestWSUpstreamCloseEndsTunnel(t *testing.T) {+ conns := make(chan *wsPeer, 1)+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{alt: wsUpstream(t, 101, nil, "", nil, conns)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ h.openWS(altCaller)+ (<-conns).c.Close()+ k.waitFor(isRoute("responses_ws"))+ if n := callerSlots(h, altCaller); n != 0 {+ t.Fatalf("caller slots %d", n)+ }+}++// A draining proxy waits for a tunnel's response without spinning.+func TestWSDrainDoesNotSpin(t *testing.T) {+ conns := make(chan *wsPeer, 1)+ h := newHarness(t, recordingUpstream(new(atomic.Int64), nil), harnessOpts{alt: wsUpstream(t, 101, nil, "", nil, conns)})+ k := h.dialControl()+ h.bindAltReady(k, altCaller, "s1", "tok", "fpC", altAccount)+ c := h.openWS(altCaller)+ up := <-conns+ c.send(`{"type":"response.create","model":"m","input":[]}`)+ up.recv()+ cpu := func() time.Duration {+ var ru syscall.Rusage+ syscall.Getrusage(syscall.RUSAGE_SELF, &ru)+ return time.Duration(ru.Utime.Nano() + ru.Stime.Nano())+ }+ h.srv.proxy.drainWS(context.Background(), false)+ before := cpu()+ time.Sleep(400 * time.Millisecond)+ if used := cpu() - before; used > 200*time.Millisecond {+ t.Fatalf("%v of CPU in 400 ms of draining", used)+ }+ up.send(`{"type":"response.completed","response":{"id":"r1"}}`)+ c.closed()+}diff --git a/computer/modelproxy/wsframe.go b/computer/modelproxy/wsframe.gonew file mode 100644index 00000000..19d02ea5--- /dev/null+++ b/computer/modelproxy/wsframe.go@@ -0,0 +1,126 @@+// WebSocket frames (RFC 6455 §5.2) read as they pass through a tunnel+// (websocket.go): an incremental parser that hands each data message's+// payload, unmasked, to a sink piece by piece as the bytes go by.+//+// Invariants: it only reads; the bytes it is fed pass on unchanged whatever+// it makes of them. Nothing is buffered beyond one frame header. Control+// frames (ping, pong, close) are skipped, also between a message's+// fragments. A frame it cannot follow (an RSV bit set, so an extension such+// as compression it was not told of; a continuation out of place; a length+// over 2^63) stops it for good: it then reports nothing more.+package main++import "encoding/binary"++// wsSink receives the data messages a wsFrames sees, in order.+type wsSink interface {+ begin() // a text or binary message starts+ data([]byte) // a piece of its payload, unmasked; valid only during the call+ end() // its last byte has gone by+}++type wsFrames struct {+ sink wsSink+ broken bool+ hdr [14]byte+ hn int // header bytes read+ left int64 // payload bytes left in the current frame; -1: reading a header+ mask [4]byte+ masked bool+ mpos int // payload offset within the frame, for the mask+ control bool+ fin bool+ inMsg bool+ scratch []byte // unmasked payload+}++func newWSFrames(sink wsSink) *wsFrames { return &wsFrames{sink: sink, left: -1} }++// headerLen is the current frame header's length, as far as its bytes so far tell.+func (f *wsFrames) headerLen() int {+ if f.hn < 2 {+ return 2+ }+ n := 2+ switch f.hdr[1] & 0x7f {+ case 126:+ n += 2+ case 127:+ n += 8+ }+ if f.hdr[1]&0x80 != 0 {+ n += 4+ }+ return n+}++func (f *wsFrames) feed(p []byte) {+ for len(p) > 0 && !f.broken {+ if f.left < 0 {+ n := copy(f.hdr[f.hn:f.headerLen()], p)+ f.hn += n+ p = p[n:]+ if f.hn == f.headerLen() {+ f.startFrame()+ }+ continue+ }+ n := int(min(int64(len(p)), f.left))+ f.payload(p[:n])+ p = p[n:]+ if f.left -= int64(n); f.left == 0 {+ f.endFrame()+ }+ }+}++func (f *wsFrames) startFrame() {+ b0, b1 := f.hdr[0], f.hdr[1]+ op := b0 & 0x0f+ f.fin, f.masked, f.control = b0&0x80 != 0, b1&0x80 != 0, op >= 8+ n, i := int64(b1&0x7f), 2+ switch n {+ case 126:+ n, i = int64(binary.BigEndian.Uint16(f.hdr[2:])), 4+ case 127:+ n, i = int64(binary.BigEndian.Uint64(f.hdr[2:])), 10+ }+ if b0&0x70 != 0 || n < 0 || (!f.control && (op == 0) != f.inMsg) {+ f.broken = true+ return+ }+ if f.masked {+ copy(f.mask[:], f.hdr[i:i+4])+ }+ f.hn, f.mpos, f.left = 0, 0, n+ if !f.control && op != 0 {+ f.inMsg = true+ f.sink.begin()+ }+ if n == 0 {+ f.endFrame()+ }+}++func (f *wsFrames) payload(p []byte) {+ if f.control {+ return+ }+ if f.masked {+ f.scratch = append(f.scratch[:0], p...)+ for i := range f.scratch {+ f.scratch[i] ^= f.mask[(f.mpos+i)&3]+ }+ f.mpos += len(p)+ p = f.scratch+ }+ f.sink.data(p)+}++func (f *wsFrames) endFrame() {+ f.left = -1+ if !f.control && f.fin {+ f.inMsg = false+ f.sink.end()+ }+}diff --git a/computer/modelproxy/wsframe_test.go b/computer/modelproxy/wsframe_test.gonew file mode 100644index 00000000..d1d4fc5b--- /dev/null+++ b/computer/modelproxy/wsframe_test.go@@ -0,0 +1,143 @@+package main++import (+ "bufio"+ "encoding/binary"+ "io"+ "strings"+ "testing"+)++// wsFrame encodes one frame, masked when mask is set (a client's).+func wsFrame(op byte, fin bool, payload []byte, mask []byte) []byte {+ b0 := op+ if fin {+ b0 |= 0x80+ }+ out := []byte{b0}+ var mb byte+ if mask != nil {+ mb = 0x80+ }+ switch n := len(payload); {+ case n < 126:+ out = append(out, mb|byte(n))+ case n < 1<<16:+ out = append(out, mb|126, 0, 0)+ binary.BigEndian.PutUint16(out[2:], uint16(n))+ default:+ out = append(out, mb|127, 0, 0, 0, 0, 0, 0, 0, 0)+ binary.BigEndian.PutUint64(out[2:], uint64(n))+ }+ if mask == nil {+ return append(out, payload...)+ }+ out = append(out, mask...)+ for i, c := range payload {+ out = append(out, c^mask[i&3])+ }+ return out+}++// readWSFrame reads one frame, unmasked.+func readWSFrame(r *bufio.Reader) (op byte, fin bool, payload []byte, err error) {+ var h [2]byte+ if _, err = io.ReadFull(r, h[:]); err != nil {+ return+ }+ op, fin = h[0]&0x0f, h[0]&0x80 != 0+ n := uint64(h[1] & 0x7f)+ switch n {+ case 126:+ var x [2]byte+ if _, err = io.ReadFull(r, x[:]); err != nil {+ return+ }+ n = uint64(binary.BigEndian.Uint16(x[:]))+ case 127:+ var x [8]byte+ if _, err = io.ReadFull(r, x[:]); err != nil {+ return+ }+ n = binary.BigEndian.Uint64(x[:])+ }+ var mask [4]byte+ if h[1]&0x80 != 0 {+ if _, err = io.ReadFull(r, mask[:]); err != nil {+ return+ }+ }+ payload = make([]byte, n)+ if _, err = io.ReadFull(r, payload); err != nil {+ return+ }+ if h[1]&0x80 != 0 {+ for i := range payload {+ payload[i] ^= mask[i&3]+ }+ }+ return+}++type msgSink struct {+ msgs []string+ cur strings.Builder+ open bool+}++func (s *msgSink) begin() { s.cur.Reset(); s.open = true }+func (s *msgSink) data(p []byte) { s.cur.Write(p) }+func (s *msgSink) end() { s.msgs = append(s.msgs, s.cur.String()); s.open = false }++// Messages come out whole and unmasked however the bytes are split:+// masked or not, every length encoding, fragmented with control frames+// between the fragments, empty frames.+func TestWSFramesSplits(t *testing.T) {+ mask := []byte{1, 2, 3, 4}+ long := strings.Repeat("x", 300)+ huge := strings.Repeat("y", 70000)+ var stream []byte+ stream = append(stream, wsFrame(1, true, []byte(`{"type":"a"}`), mask)...)+ stream = append(stream, wsFrame(1, false, []byte(`{"type":`), nil)...)+ stream = append(stream, wsFrame(9, true, []byte("ping"), mask)...)+ stream = append(stream, wsFrame(0, false, nil, nil)...)+ stream = append(stream, wsFrame(0, true, []byte(`"b"}`), mask)...)+ stream = append(stream, wsFrame(1, true, []byte(long), mask)...)+ stream = append(stream, wsFrame(2, true, []byte(huge), nil)...)+ stream = append(stream, wsFrame(1, true, nil, nil)...)+ stream = append(stream, wsFrame(8, true, []byte{3, 232}, nil)...)+ want := []string{`{"type":"a"}`, `{"type":"b"}`, long, huge, ""}+ for _, step := range []int{1, 2, 3, 7, 13, 64, 1 << 20} {+ s := &msgSink{}+ f := newWSFrames(s)+ for i := 0; i < len(stream); i += step {+ f.feed(stream[i:min(i+step, len(stream))])+ }+ if f.broken || len(s.msgs) != len(want) || s.open {+ t.Fatalf("step %d: broken %v, %d messages, open %v", step, f.broken, len(s.msgs), s.open)+ }+ for i := range want {+ if s.msgs[i] != want[i] {+ t.Fatalf("step %d: message %d is %.40q", step, i, s.msgs[i])+ }+ }+ }+}++// A frame it cannot follow stops it for good: compressed (RSV1), or a+// continuation with no message open.+func TestWSFramesBroken(t *testing.T) {+ for name, b := range map[string][]byte{+ "rsv1": append([]byte{0xc1, 2}, 'h', 'i'),+ "continuation": wsFrame(0, true, []byte("x"), nil),+ "new mid-msg": append(wsFrame(1, false, []byte("x"), nil), wsFrame(1, true, []byte("y"), nil)...),+ } {+ s := &msgSink{}+ f := newWSFrames(s)+ f.feed(b)+ f.feed(wsFrame(1, true, []byte("after"), nil))+ if !f.broken || len(s.msgs) != 0 {+ t.Fatalf("%s: broken %v, messages %q", name, f.broken, s.msgs)+ }+ }+}diff --git a/computer/modelproxy/wsmessages.go b/computer/modelproxy/wsmessages.gonew file mode 100644index 00000000..fdde4ffa--- /dev/null+++ b/computer/modelproxy/wsmessages.go@@ -0,0 +1,106 @@+// What a WebSocket tunnel (websocket.go) reads from the messages passing+// through it, as wsframe.go hands them over piece by piece: from the client,+// a response.create and whether it is a warm-up (`"generate":false`); from+// the upstream, each event's `type`, the service tier it names and, for an+// `error` event, its status and headers.+//+// Invariants: of a message only its first bytes (wsTypeHead from the client,+// wsErrorHead from the upstream) and a tail for matches across pieces are+// kept, and only until the next one starts; an event's type is the first+// `type` in its head, which is the event's own as the upstream writes it+// first.+package main++import (+ "bytes"+ "encoding/json"+ "net/http"+ "strconv"+)++// wsClientMsg reads the client's messages: a response.create starts a response.+type wsClientMsg struct {+ t *wsTunnel+ head []byte+ scan tailScan+ prewarm bool+}++func (m *wsClientMsg) begin() { m.head, m.prewarm = m.head[:0], false; m.scan.reset() }++func (m *wsClientMsg) data(p []byte) {+ m.head = appendHead(m.head, p, wsTypeHead)+ if !m.prewarm && (bytes.Contains(m.scan.seam(p), markNoGenerate) || bytes.Contains(p, markNoGenerate)) {+ m.prewarm = true+ }+ m.scan.keep(p)+}++func (m *wsClientMsg) end() {+ if eventType(m.head) == "response.create" {+ m.t.created(m.prewarm)+ }+}++// wsServerMsg reads the upstream's events.+type wsServerMsg struct {+ t *wsTunnel+ head []byte+ scan tailScan+ tier string+}++func (m *wsServerMsg) begin() { m.head, m.tier = m.head[:0], ""; m.scan.reset() }++func (m *wsServerMsg) data(p []byte) {+ m.head = appendHead(m.head, p, wsErrorHead)+ if t, ok := tierIn(m.scan.seam(p)); ok {+ m.tier = t+ }+ if t, ok := tierIn(p); ok {+ m.tier = t+ }+ m.scan.keep(p)+}++func (m *wsServerMsg) end() { m.t.event(eventType(m.head), m.tier, m.head) }++func appendHead(head, p []byte, limit int) []byte {+ return append(head, p[:min(len(p), max(0, limit-len(head)))]...)+}++// eventType is the first `type` a message's head names: the event's own.+func eventType(head []byte) string {+ i := bytes.Index(head[:min(len(head), wsTypeHead)], []byte(`"type":"`))+ if i < 0 {+ return ""+ }+ v := head[i+len(`"type":"`):]+ if j := bytes.IndexByte(v, '"'); j > 0 && j <= 64 {+ return string(v[:j])+ }+ return ""+}++// wsError reads an `error` event's status and headers, the WebSocket form+// of an HTTP error: {"type":"error","status":429,"error":{…},"headers":{…}}.+func wsError(b []byte) (int, http.Header) {+ var e struct {+ Status int `json:"status"`+ StatusCode int `json:"status_code"`+ Headers map[string]any `json:"headers"`+ }+ if json.Unmarshal(b, &e) != nil {+ return 0, nil+ }+ h := http.Header{}+ for k, v := range e.Headers {+ switch v := v.(type) {+ case string:+ h.Set(k, v)+ case float64:+ h.Set(k, strconv.FormatFloat(v, 'f', -1, 64))+ }+ }+ return max(e.Status, e.StatusCode), h+}