Merge main into port/edge-02 (CTRL-01, BUS-01, row 72, parity flake fix)
This commit is contained in:
commit
d5b576a2c1
72 changed files with 6366 additions and 599 deletions
|
|
@ -6,6 +6,12 @@ nothing outside the container can reach it, and the bridge is the only intended
|
|||
There is deliberately **no endpoint that presses buttons, edits game memory, or changes the
|
||||
reward catalog**. That is a structural guarantee, not a configuration.
|
||||
|
||||
Who serves it (2026-10-01): flysim itself (`FLY_CONTROL_VIA=direct`, the default), or
|
||||
`fly-control-edge` from flysim's control services on the bus (`FLY_CONTROL_VIA=bus`,
|
||||
`docs/design/flybus.md`, "Control over the bus"). Both are the same HTTP code over the same
|
||||
request handling, so nothing in this document depends on the switch. On the bus, the
|
||||
guarantee above is also a grant table.
|
||||
|
||||
| Method and path | Body | Effect |
|
||||
|---|---|---|
|
||||
| `GET /status` | | Same fields as the feed header minus events and attachments, plus `version` strings (kernel, plasticity, adapter, binjgb, dataset fingerprint) and `checkpoint: { latestWallMs, generation }`. Includes the macro buttons' `game.scene`, `game.macroMode`, `game.palette`, `game.macro` and `game.macroOutcome` (2026-09-16), because the body is the header reshaped rather than a parallel struct. `game.macroMode` is `"raw"` or `"macros"`, and each `game.palette` entry carries its `slot` (0..5), its `name`, its `gloss` and its `channel` tag (`docs/design/macros.md` section 12). |
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
# flybus: the communications bus
|
||||
|
||||
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus`, off by default; EDGE-02
|
||||
(2026-10-01) made it switchable in production with one command, `fly-feed bus|direct`**.
|
||||
Written 2026-09-22, amended 2026-09-23 (EDGE-01) and 2026-10-01 (EDGE-02, below). Index only; the
|
||||
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus` and the control API behind
|
||||
`FLY_CONTROL_VIA=bus`, both off by default; EDGE-02 (2026-10-01) made the feed switchable in
|
||||
production with one command, `fly-feed bus|direct`**. Written 2026-09-22, amended 2026-09-23
|
||||
(EDGE-01) and 2026-10-01 (EDGE-02 and CTRL-01, below). Index only; the
|
||||
authority for the API and the wire format is the crate's own
|
||||
[README](../../services/flysim/crates/flybus/README.md), and the audit of the crate against
|
||||
the draft is the [conformance report](session-framework/bus-conformance.md).
|
||||
|
|
@ -62,13 +63,13 @@ allocate/seal/read with quotas and router restarts, plus the conformance suites
|
|||
## Wiring still pending
|
||||
|
||||
- ~~**flysim publisher.**~~ Done 2026-09-23 behind `FLY_FEED_VIA=bus`: see "Feed over the bus".
|
||||
- **flysim control services.** The control endpoints as RPC services with grants, so the
|
||||
"no button endpoint" structural guarantee is expressed as a grant table.
|
||||
- ~~**flysim control services.**~~ Done 2026-10-01 behind `FLY_CONTROL_VIA=bus`: see "Control
|
||||
over the bus". The "no button endpoint" guarantee is a grant table there.
|
||||
- **Stage and bridge clients.** Both are TypeScript/Node; the crate is Rust only, so either
|
||||
a binding or a thin translating edge process is required before they leave the WebSocket
|
||||
and HTTP surfaces. The operator chose the edge process (port decisions, 2026-09-23); for
|
||||
the feed it exists (`fly-edge`), and they keep the WebSocket contract unchanged. The
|
||||
control API (:7401) is the next slice and stays in flysim until then.
|
||||
the feed it is `fly-edge` and for the control API `fly-control-edge`, and both keep their
|
||||
contracts byte for byte.
|
||||
- ~~**Sizing.**~~ Decided 2026-09-23: amendment "Feed sizing" below.
|
||||
- ~~**Lifecycle.**~~ Decided 2026-09-23: amendment "Feed store lifecycle" below.
|
||||
- **Migration order.** The feed is the cheaper first move; control should follow only once
|
||||
|
|
@ -231,3 +232,207 @@ Accepted for now and written down rather than fixed:
|
|||
stays on loopback). *Rollback while in bus mode*: refused by the deploy and one command by
|
||||
`fly-feed direct`. *Store quota per router* and *old fixtures*: unchanged, accepted as written.
|
||||
|
||||
## Control over the bus (2026-10-01, CTRL-01)
|
||||
|
||||
`control.via` (`FLY_CONTROL_VIA`) picks who serves `http://127.0.0.1:7401`. `direct` is the
|
||||
default and the behaviour that predates the bus. With `bus`:
|
||||
|
||||
```text
|
||||
api router (flysim::api) BusBackend flybus (Unix socket) control host (in flysim)
|
||||
:7401 in fly-control-edge --> encode_request --> <bus_dir>/control-edge.sock --> fly.control.s.main.* services
|
||||
same routes, extractors, (controlbus) bound to "fly-control-edge" -> flysim::control::handle
|
||||
404s, headers, bodies -> the same Command queue
|
||||
```
|
||||
|
||||
- `docs/control-api.md` is unchanged and still binding: every endpoint, status code and body.
|
||||
flysim's control code is split in two. `flysim::control` holds the semantics: one
|
||||
`ControlRequest` per endpoint, and `handle`, the only code that validates a request, talks to
|
||||
the loop and picks a status. `flysim::api` is the HTTP layer over any `ControlBackend`. Direct
|
||||
mode is `api` over `control` in one process. Bus mode is the same `api` in `fly-control-edge`
|
||||
over a `BusBackend`, which carries the request to the `control` services in flysim. Neither
|
||||
process has an HTTP table or a validation rule of its own, so the bytes on `:7401` are the
|
||||
same in both modes. `crates/fly-control-edge/tests/parity.rs` sends every endpoint, each
|
||||
validation case and each refusal to both paths and requires equal status, headers and
|
||||
body. Over real sockets, it also requires the whole HTTP/1.1 response to be equal apart from
|
||||
`date`. `fly-legacy-session/tests/service_parity.rs` runs the session runtime once more with
|
||||
its control on the bus and compares it with the legacy loop. The comparison covers 120
|
||||
frames, 19 control responses, the event log, the journal and the final checkpoint.
|
||||
- Both runtimes get it: `flysim` and `flysim-session` both run `flysim::serve`, which in bus mode
|
||||
does not bind `control.bind`. Instead it registers the services on the embedded router. That
|
||||
is the feed's router when the feed is on the bus too: one router, one store, one closed policy
|
||||
(`flysim::bus`). The read-only `control.metrics_bind` listener (`:9101`) stays in flysim in
|
||||
both modes.
|
||||
- Nothing about the fly changes. The command queue, its bound and its timeouts are the same.
|
||||
The compatibility string is byte-identical in both modes.
|
||||
|
||||
### Services and methods
|
||||
|
||||
flybus grants name services, not methods. The surface is therefore split into six service
|
||||
*families*, and a grant names families. Every family is scoped either to a session or to one
|
||||
agent (fly) of it. Each method's payload and outcome:
|
||||
|
||||
| Service (live names) | Method | Endpoint | Payload |
|
||||
| --- | --- | --- | --- |
|
||||
| `fly.control.s.main.read` | `Control.Status` | `GET /status`, `/status.json` | `{}` |
|
||||
| | `Control.Healthz` | `GET /healthz` | `{}` |
|
||||
| | `Control.Metrics` | `GET /metrics` | `{}` |
|
||||
| | `Control.Events` | `GET /events` | `{since?: string, limit?: string}`, the raw query values |
|
||||
| `fly.control.s.main.a.fly.status` | `Control.Status` | (none: the fly's own status, for native clients) | `{}` |
|
||||
| `fly.control.s.main.a.fly.sugar` | `Control.Stimulate` | `POST /stimulate` | `{request?: <body JSON>}` |
|
||||
| `fly.control.s.main.a.fly.reward` | `Control.Reward` | `POST /reward` | `{request?: <body JSON>}` |
|
||||
| `fly.control.s.main.chat` | `Control.Chat` | `POST /chat` | `{request?: <body JSON>}` |
|
||||
| `fly.control.s.main.ops` | `Control.Checkpoint`, `Control.Pause`, `Control.Resume` | `POST /checkpoint`, `/pause`, `/resume` | `{}` |
|
||||
|
||||
- **Outcome.** `{"status": <the control-api.md code>, "body": <the JSON body>}`, or `{"status",
|
||||
"text"}` for `/metrics`. Above 48 KiB (a full `/events` page can be 4,096 events) the body
|
||||
travels as a sealed `body` artifact instead, with `bodyArtifact` naming its type. The status
|
||||
code is the outcome's vocabulary, not transport. A bus caller reads `429 {retryAfterMs}` as an
|
||||
HTTP caller does, so the edge needs no table of its own.
|
||||
- **Requests** carry the body as the caller sent it (`request` is absent when it was empty or
|
||||
not JSON), so validation stays in `control::handle`. A `request` over 48 KiB of JSON travels as
|
||||
a sealed `request` artifact with `requestArtifact: true` in the payload, so a large body gets
|
||||
the answer direct mode gives it, not an envelope error (`tests/parity.rs`). An unknown payload field is a 400. A
|
||||
method the service does not have is a 404. Neither reaches the loop.
|
||||
- **Concurrency.** Each service has 16 queued and 16 in flight (`controlbus::SERVICE_CONFIG`).
|
||||
The router dispatches FIFO per service. The host answers each request in a task of its own, so
|
||||
a pause waiting on a durable write does not hold up a resume. Families are separate services,
|
||||
so a stuck `ops` never delays `/status`.
|
||||
- **Backpressure.** The bound is on the queue at the moment of admission. A burst can
|
||||
therefore be refused before the router has dispatched its first calls into the in-flight
|
||||
slots. That is measured, not assumed (`tests/backpressure.rs`). A full service refuses at
|
||||
once with `BACKPRESSURE`, and the edge answers it
|
||||
with direct mode's `503 {"error": "the simulation command queue is full"}`. Bus failures use
|
||||
direct mode's words for the same failure (`control::unavailable`). `NO_SERVICE` before
|
||||
dispatch is "has stopped"; `NO_SERVICE` after dispatch, `CALL_GONE` and `ROUTER_LOST` are
|
||||
"dropped the request". `NOT_AUTHORIZED` is a 403.
|
||||
- **Deadlines and cancel.** The host keeps direct mode's own timeouts: 2 s for a command,
|
||||
none for `/checkpoint` and `/pause`, which wait for a durable write. The edge adds a guard of
|
||||
that plus 2 s for timed requests only. At the guard it cancels the call and answers direct
|
||||
mode's timeout 503. A call cancelled before dispatch never reaches the loop. A dispatched call
|
||||
may still act, as a direct request whose caller timed out may. An HTTP client that goes away
|
||||
drops its handler, and with it the pending call. The router discards the late result, and
|
||||
the call record goes once the host answers (`tests/backpressure.rs`).
|
||||
|
||||
### Grants: the structural guarantee as a table
|
||||
|
||||
| Participant (socket) | read | status | sugar | reward | chat | ops | register |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `flysim-control`, the host (in-process, no socket) | | | | | | | every control service, exact names |
|
||||
| `fly-stage` (`control/stage.sock`) | yes | yes | | | | | |
|
||||
| `fly-bridge` (`control/bridge.sock`) | yes | yes | yes | | yes | | |
|
||||
| `fly-watchdog` (`control/watchdog.sock`): watchdog, loop-recover ladder, `fly-runtime`, probation, shadow guard, stream check | yes | yes | | | | | |
|
||||
| `fly-operator` (`control/operator.sock`) | yes | yes | yes | yes | yes | yes | |
|
||||
| `fly-control-edge` (`control-edge.sock`): everything on `:7401` | yes | yes | yes | yes | yes | yes | |
|
||||
| a player backing one fly (`player_grants`, not wired yet) | yes | that fly | that fly | | | | |
|
||||
|
||||
The status, sugar and reward columns are per agent: a role gets them for every fly of the
|
||||
session (`grants`), or for one fly by id or by controller port (`grants_for`, `player_grants`
|
||||
with `Agents::Id` or `Agents::Port`). The table is `controlbus::Role` and `controlbus::grants`. It reflects what each client calls
|
||||
today: the stage only waits on `/healthz`; the bridge calls `/status`, `/stimulate`, `/chat`,
|
||||
`/events` and `/healthz`; the infra scripts only read; the operator uses `curl`. Each socket is
|
||||
launcher-bound to its participant. The watchdog and the ladder restart through systemd, never
|
||||
through a control call.
|
||||
|
||||
"Nothing can press buttons" is structurally true because of four properties. Each is tested:
|
||||
|
||||
1. **No method takes input.** `ControlRequest` and the loop's `Command` have no variant that
|
||||
presses a button, edits game memory or changes the reward catalog, so no method can be added
|
||||
without a contract change. Service and method names are scanned for the same words `api.rs`
|
||||
scans routes for (`controlbus` unit tests).
|
||||
2. **Grants are exact calls and nothing else.** No role is granted `Any`, a prefix, `register`,
|
||||
`publish`, `subscribe` or topic management (`every_grant_is_an_exact_call_...`). On a router
|
||||
that also carries an environment's input service, no control participant can call that
|
||||
service, the operator and the edge included. The router refuses before dispatch
|
||||
(`tests/grants.rs`, `on_a_shared_router_no_control_participant_can_reach_an_input_service`).
|
||||
3. **Only the host registers.** The one register grant belongs to an in-process participant
|
||||
with no socket, so nothing outside flysim can stand in for a control service. A socket admits
|
||||
only its own participant; claiming another id at hello is refused.
|
||||
4. **The policy is closed.** An id that is not in the table cannot connect.
|
||||
|
||||
What this does not change: loopback HTTP has no caller identity, so `fly-control-edge` carries
|
||||
the whole surface. That is exactly the trust `:7401` has today. A client is narrowed by moving
|
||||
it off HTTP onto its own role socket. That needs a native client for the TypeScript processes
|
||||
(a later slice; the operator chose edges over a Node binding for now). The bus's own limit still
|
||||
applies: processes running as the same OS user are inside the trust boundary (crate README,
|
||||
"Limitations").
|
||||
|
||||
### N flies, M environments, controller ports, players
|
||||
|
||||
Operator direction (2026-10-01): first the existing Game Boy fly goes fully onto the framework
|
||||
and the bus. A later project puts several flies on multi-controller consoles, one fly per
|
||||
controller port. This slice does not build that, but the services and grants are scoped per
|
||||
session, per agent and per port from the start, so multi-fly is configuration, not a redesign.
|
||||
A single-fly deployment is the same design with one agent.
|
||||
|
||||
- **Scope** (`controlbus::Scope`): a session id and its agents, each an id and, where the
|
||||
environment has controller ports, the port it plays on (`AgentScope { id, port }`). The live
|
||||
fly is session `main`, agent `fly` on port 0, the Game Boy's one pad (`Scope::live`). A scope
|
||||
refuses two agents with one id or on one port.
|
||||
- **Session-scoped** families (read, chat, ops) are `fly.control.s.<session>.<family>`. Pause and
|
||||
checkpoint act on a whole session: one coordinator steps every agent, and one save is one
|
||||
generation. The chat ring is the session's stage. `read` holds the session's status, health,
|
||||
metrics and event log.
|
||||
- **Agent-scoped** families (status, sugar, reward) are
|
||||
`fly.control.s.<session>.a.<agent>.<family>`, one service per fly. A sugar or reward pulse goes
|
||||
into one brain. Each fly's own view is its `status` service. Adding a fly adds its three
|
||||
services, and nothing else changes.
|
||||
- **Ports.** A port is a property of an agent's binding, not part of a name, because a pulse
|
||||
goes into a brain, not into a controller. A grant limited to a port
|
||||
(`Agents::Port(n)`) is resolved to the agent bound to that port when the policy is built. The
|
||||
policy is fixed for a router's lifetime, so rebinding ports is a session restart. A port nobody
|
||||
plays on grants no agent service.
|
||||
- **M sessions** on one router (several games, or one multiplayer game) have disjoint names, so
|
||||
a grant on one session never names another's. `:7401` addresses the live scope only. A second
|
||||
session gets native bus clients, or an edge of its own on another port with its own scope.
|
||||
- **Environments.** Environment-scoped status is reserved as
|
||||
`fly.control.s.<session>.e.<env>.read`. Environment *input* services (`Environment.Step` and
|
||||
the like) are never in a control scope. An agent's decision reaches its environment through
|
||||
the coordinator, never through control, and on a multi-controller console each fly's decoder
|
||||
writes only its own port. Property 2 holds however many environments and ports share the
|
||||
router.
|
||||
- **Players.** A viewer who backs one fly gets `player_grants(scope, Agents::Port(n))` or
|
||||
`Agents::Id(..)`: read the session, see and sugar that fly, nothing else
|
||||
(`a_player_sugars_their_own_fly_and_no_other`). In a multiplayer game the players on the pads
|
||||
are flies, and their presses come from their decoders. A human input path would be a new
|
||||
contract, never a control grant.
|
||||
|
||||
### What in `docs/control-api.md` is single-fly
|
||||
|
||||
The contract is unchanged by this slice. These parts of it assume one fly per session. Each
|
||||
would need a contract amendment before a second fly could be served over HTTP. The bus services
|
||||
above are already addressed per agent, so the amendments are to the HTTP shapes, not the bus.
|
||||
|
||||
| Endpoint or rule | Why it is single-fly | Multi-fly direction |
|
||||
| --- | --- | --- |
|
||||
| `GET /status` | The feed header reshaped: one `buttons`, `rates`, `decoder`, `learning`, `game`, `milestone`, `sugar`, `version` | Per agent: each fly's `status` service. The session's `Control.Status` becomes a session shape listing its agents and ports |
|
||||
| `POST /stimulate` | No agent field; addresses "the fly" | The agent's `sugar` service; over HTTP an `agent` (or `port`) field, absent meaning the only fly |
|
||||
| sugar limits ("6 per minute globally, no overlap with an active pulse") | The overlap rule is per brain; the budget is per deployment | Overlap per agent; whether the budget is per fly or per session is a policy decision |
|
||||
| `POST /reward` | No agent field | The agent's `reward` service; same field as `/stimulate` |
|
||||
| `GET /events`, `events.jsonl` | `FeedEvent` has no agent: reward, sugar and macro events cannot say whose they are | An `agent` field on agent events, absent for session events |
|
||||
| `POST /checkpoint` | One generation of one FLYSIM01 envelope, which is single-fly by format | A session checkpoint holding every agent. FLYSIM01 stays the format of record until RETIRE-01 |
|
||||
| `GET /metrics` | Series carry no agent label (`fly_reward_*`, the rates) | An `agent` label on per-fly series |
|
||||
| `[macros]`, `loop.game` | One mode and one game per deployment | Per environment |
|
||||
| `POST /chat`, `/pause`, `/resume`, `/healthz` | Session-level already | None |
|
||||
|
||||
### Lifecycle and operations
|
||||
|
||||
- `bus_dir` (`FLY_BUS_DIR`, `/run/fly/bus`) as for the feed. Sockets are `control-edge.sock` and
|
||||
`control/{stage,bridge,watchdog,operator}.sock`. Stale sockets are removed at start. With
|
||||
control on the bus, the router's `max_clients` and `max_services` are the feed's plus 8.
|
||||
- `flycontrol-edge.service` has no `[Install]` section: `flysim.service` `Wants=` it, and its
|
||||
`ExecCondition=` on `FLY_CONTROL_VIA` skips it in direct mode (EDGE-02's pattern for
|
||||
`flyedge`), so every start of flysim, `fly-loop-reset`'s stop and start included, brings
|
||||
`:7401` back. It is `After=` and `Requires=flysim.service`, gets the page's CPUs from the cpuset plan, and exports its own
|
||||
counters on loopback `:9103` (`fly_control_edge_bus_connected`, `_calls_total`,
|
||||
`_call_failures_total`, `_cancelled_total`, `_bus_lost_total`, `_bind_failures_total`).
|
||||
- The edge binds `:7401` only once the services answer. When the bus goes away it unbinds and
|
||||
reconnects every 500 ms. To a client that looks exactly like flysim restarting
|
||||
(`tests/backpressure.rs`, `tests/serve.rs`).
|
||||
- Watchdog. Check 1 reads flysim's own `/healthz` on `:9101` when `FLY_CONTROL_VIA=bus`, so an
|
||||
edge outage never restarts the fly. Check 1b restarts the edge alone when `:7401` fails while
|
||||
flysim is healthy. Every other `:7401` reader (`fly-runtime`, probation, shadow guard,
|
||||
loop-recover, the stream check) goes through the edge unchanged.
|
||||
- Switch and rollback: `infra/docs/runbook.md`, "Control over the bus".
|
||||
- **Migration order.** This document's rule stands: the control API moves after the feed has
|
||||
been on the bus in production for a full session. The switch exists independently of the
|
||||
feed's, and when to throw it is the coordinator's call.
|
||||
|
|
|
|||
|
|
@ -2184,9 +2184,10 @@ Knowledge inside macros, never in the choice; the pad still lists buttons and th
|
|||
- **Ladder.** Unchanged; no reward for shopping or healing (rewards are the adapter's,
|
||||
untouched).
|
||||
- **Screen.** Two new channel tags; the cells and the MACROS rate row take them as they come.
|
||||
- **Proof.** ROM-gated from the Viridian checkpoint: `GO SHOP` enters the Viridian mart and
|
||||
`BUY POTION` buys one; `GO HEAL` enters the center and `HEAL` restores the party; the errand is
|
||||
not offered again in Viridian; trap hunt before/after.
|
||||
- **Proof.** ROM-gated: from the Viridian checkpoint `GO HEAL` enters the center and `HEAL`
|
||||
restores the party; from the rung-11 Pewter checkpoint (a state where `GO SHOP` is dealt, since
|
||||
rows 62/66: money, no ball, no parcel) `GO SHOP` enters the mart and walks to its counter, and
|
||||
is not dealt back from the street for the reached window; trap hunt before/after.
|
||||
|
||||
## 14. The full pad and four move buttons (the operator, 2026-09-17: "scoot fly over. make it 2
|
||||
## columns" … "four, one per move slot" … "2 cols.")
|
||||
|
|
|
|||
|
|
@ -105,7 +105,7 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
|
|||
| Method strings are 1..128 printable ASCII | conforms | `wire.rs::is_method` | `wire.rs::tests::scalars` |
|
||||
| The call target is a service name; `expectedIncarnation` is the registration id | conforms | `router/state.rs::op_call` (`f.name`, `f.nullable_id`) | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) |
|
||||
| Location grants are `{storeId, relativePath}` resolved under the configured root; absolute paths, parent traversal and symlink escapes are rejected | conforms | `store.rs::resolve`, opened `O_NOFOLLOW` | `store.rs::tests::resolve_refuses_escapes`, `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
|
||||
| Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies | `wire.rs::Location`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
|
||||
| Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies and, since the 2026-10-01 amendment (BUS-01), in a delivery's attachments, never in a body | `wire.rs::Location`, `wire.rs::Attachment`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained`, `::deliveries_carry_the_read_location_their_ownership_grants` (both) |
|
||||
| Deliveries carry exactly the listed bodies (`rpc.request`, `rpc.result`, `topic.message`) | conforms | `router/state.rs::{Call::request_body, Call::result_body, TopicMsg::body}` | `tests/conformance_wire.rs` + `client/reactor.rs::on_delivery` strict parse |
|
||||
| `caller`/`responder` include clientId and clientIncarnation | conforms | `wire.rs::Identity` | `tests/rpc.rs::request_reply_roundtrip` (both) |
|
||||
| Delivery attachment ownerIds are replaced by the recipient's deliveryId; source tokens are never delegated | conforms, and the client refuses a delivery whose attachment owner is not its delivery | `router/state.rs::attachments_with_owner`, `client/reactor.rs::attachments` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) |
|
||||
|
|
@ -189,7 +189,7 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
|
|||
| Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) |
|
||||
| A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) |
|
||||
| No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) |
|
||||
| Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
|
||||
| Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms; amended 2026-10-01 (bus-v1 section 12, BUS-01): a delivered handle uses the location its delivery carries, every other handle still asks | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
|
||||
| Locations are private grants, not placed in application bodies or public feeds | conforms | `router/state.rs::op_open` reply only | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
|
||||
| All filesystem access stays behind the client Artifact API; no second bulk-transfer server | conforms in the API. The store is only as private as the OS user, which the crate's Limitations section states | `client/handles.rs`, `store.rs` | `store.rs::tests::resolve_refuses_escapes` |
|
||||
|
||||
|
|
|
|||
|
|
@ -534,3 +534,30 @@ before anything is sent (`INVALID_ENVELOPE`, not dispatched). They exist for par
|
|||
process that hand each other buffers directly ([session RPCs](ipc-v1.md) section 1, amendment of
|
||||
the same date); section 8's ownership rules apply to every artifact a router stores, which these
|
||||
never are.
|
||||
|
||||
**2026-10-01, BUS-01 (wire change; `contractDigest` changes).** A delivery's attachments carry the
|
||||
read location their delivery ownership grants. Section 8.1 makes a consumer resolve a
|
||||
store-issued `readLocation` through `artifact.open` before it reads, which is one router round
|
||||
trip per artifact read. The legacy composition on the bus reads four artifacts a frame on its
|
||||
critical path (the frame in `Agent.Prepare`, the memory image and the audio chunk after
|
||||
`Environment.Advance`, the spike bitset after `Agent.Commit`), so that rule cost four round trips
|
||||
a frame for an answer the router already knows when it delivers.
|
||||
|
||||
- In an `rpc.request`, `rpc.result` or `topic.message` delivery, every attachment is
|
||||
`{name, ref, ownerId, readLocation}`, where `readLocation` is the `{storeId, relativePath}`
|
||||
`artifact.open` would return for that artifact under that delivery's ownership. It is still
|
||||
store-issued, private to the SDK, resolved beneath the store root with the same traversal and
|
||||
symlink checks, and never placed in an application body.
|
||||
- A client never sends one: an attachment in a command that carries `readLocation` is an unknown
|
||||
field, and the connection closes as for any malformed envelope.
|
||||
- The SDK's handle on a delivered artifact reads through it with no round trip. Section 8.1's
|
||||
guarantee is unchanged: the delivery's root holds the bytes while the handle (or a file opened
|
||||
from it) lives, exactly as after an `artifact.open`. `artifact.open` stays for every handle that
|
||||
did not come from a delivery (a sealed writer's hold, an explicit `retain` of one) and for any
|
||||
client that prefers to ask.
|
||||
|
||||
Two SDK-only changes of the same slice, no wire change: small store operations (creating or sealing
|
||||
a staging file, reading a sealed one, up to 256 KiB) run in place rather than on the blocking pool
|
||||
-- on the store's tmpfs a hop to the pool and back costs more than the copy -- and
|
||||
`Artifact::is_hold` tells a sealed writer's or a retained hold from a delivery's handle, so a holder
|
||||
that needs the bytes kept alive can keep a clone instead of taking a second hold.
|
||||
|
|
|
|||
|
|
@ -495,6 +495,52 @@ line also prints the measurement spans (and the brain's phase split) when
|
|||
`FLY_SESSION_PROFILE` is set at start; the service reads the same variable as its profile name, so
|
||||
a measured service sets it to `production`. The report `claude-perf-02` has the measurements.
|
||||
|
||||
### BUS-01 (port slice) — The live session's participants on the router
|
||||
|
||||
Not the framework guide's BUS-01 above (the router itself); the port plan reuses the name.
|
||||
**2026-10-01: built** on `port/bus-01` off `main` (v0.7.5), awaiting review. Operator direction:
|
||||
run the live session over the flybus router on Unix sockets, one emulator and one fly, because
|
||||
multiplayer and more flies follow. The topology, its rules and the shadow procedure are
|
||||
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 12 (amendment 2026-10-01) and section 18
|
||||
(amendment of the same date); the wire change is [bus-v1](bus-v1.md) section 12 (2026-10-01).
|
||||
|
||||
- **Selecting it.** `FLY_SESSION_TRANSPORT=bus` / `flysim-session --transport bus` (process mode
|
||||
by default; `FLY_SESSION_MODE=thread` and `in-process` too), `fly-runtime session --bus`
|
||||
(`session-bus`) on the container, `fly-shadow --mode bus/process` and
|
||||
`fly-shadow-run start --bus` / `check --bus` for its shadow. The local lane stays the default.
|
||||
`SessionArm` names the four arms; `FLY_PARITY_ARMS` picks them for the parity suites (default
|
||||
`local,bus/thread,bus/process`).
|
||||
- **What it took.** Per-process CPU placement (`Launcher::place_process`,
|
||||
`--host-cpus`/`--sweep-cpus`, `flybrain_core::pool::apply_placement`), the launcher's own clients
|
||||
in memory in thread and process modes, `block_in_place` for a bus request's handler (without it a
|
||||
slow `Agent.Initialize` could not be resolved and a process-mode session failed to boot on a
|
||||
loaded box: "never resolved"), delivered read locations (bus-v1 amendment), writers allocated
|
||||
ahead (`WriterPool`), no second hold on a worker's own seals, small store I/O in place, the
|
||||
envelope encoded without copying its body, and the agent's feed status attached to a bus Commit
|
||||
(the host's 30 Hz `Legacy.FeedStatus` call was a round trip of its own).
|
||||
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
|
||||
`7b940584`, as v0.7.5) are the same in every arm: the toy and FAFB parity suites
|
||||
(`session_trace`, `service_parity`, `rollback_sequence`, `save_handoff`) ran `local`,
|
||||
`bus/thread` and `bus/process`.
|
||||
- **Measured, and not fast enough to go live.** The report `claude-bus-01` has the tables. On a
|
||||
build box with the release CPU model and the release cpuset's shape (four CPUs, four sweep
|
||||
threads), same frames, interleaved, unpaced: legacy 16.1 ms a frame, the lane 17.4,
|
||||
`bus/thread` 25.1, `bus/process` 25.7 (`main`'s process mode: 30.4, so this slice took about a
|
||||
third off the bus's cost). Paced at real time the lane holds 1.00 and the bus 0.69 to 0.71, with a
|
||||
neighbour CPU busy or not. Every round trip through the router is 0.5 to 1 ms there (the
|
||||
synthetic `fly-session measure` puts a bare `Worker.Status` at 0.5 ms whether the processes
|
||||
share one CPU or four), and a transition needs at least five in sequence: Prepare; Advance and
|
||||
its seals; Commit and its seals. That is a realtime factor of roughly 0.7 on the release
|
||||
container, so the lane stays live and nothing is switched. Moving the router, the coordinator
|
||||
and the world to a fifth CPU (`FLY_SESSION_AUX_CPUS`) made it 1.5 to 2 ms slower. What would close
|
||||
it is a cheaper round trip, not more CPUs: the router's own per-message work (strict JSON parsed
|
||||
and re-encoded per hop, the state lock, about three task hops a direction), and sealing a reply's
|
||||
media in the reply itself (one round trip fewer for Advance and for Commit).
|
||||
- **`fly_frame_work_*`** on `/metrics` (both runtimes): the loop's compute time per frame without
|
||||
its pacing sleep, mean, p99 and max over the last 3,600 frames. It agrees with the unpaced
|
||||
ms/frame within 1% on every arm measured, and it is the headroom a paced realtime factor of 1.0
|
||||
hides.
|
||||
|
||||
### SHADOW-01 — The session runtime beside the live fly (port slice)
|
||||
|
||||
**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no
|
||||
|
|
|
|||
|
|
@ -456,6 +456,79 @@ the CPU a thread runs on, never what an index of a parallel phase computes.
|
|||
legacy loop's, which is what failed CUT-01's speed probation (0.959 < 0.97); placed, they cost
|
||||
what the legacy loop's do.
|
||||
|
||||
**Amendment, 2026-10-01 (BUS-01): the composition on the router.** The operator's direction of
|
||||
2026-10-01: run the live session's participants over the flybus router on Unix sockets, one
|
||||
emulator and one fly today, because multiplayer and more flies follow. Nothing in the declaration,
|
||||
the digest or the compatibility string changes, and no result can: the bus carries the same
|
||||
domain calls, in the same order, to the same endpoints as the local lane. Traces, checkpoints and
|
||||
the FAFB parity runs are identical in every arm (`local`, `bus/thread`, `bus/process`;
|
||||
`fly_legacy_session::composition::SessionArm`).
|
||||
|
||||
*Selecting it.* `FLY_SESSION_TRANSPORT=bus` (or `flysim-session --transport bus`) puts every
|
||||
participant on the router's sockets; `FLY_SESSION_MODE` then defaults to `process`, and `thread` and
|
||||
`in-process` are also allowed (`in-process` on the bus is every participant a socket client from
|
||||
the coordinator's own runtime). `local`, the default, is the PERF-01 lane and stays the release
|
||||
configuration until a cutover onto the bus. `local` with a thread or a process is refused: those
|
||||
have no lane. On the container, `fly-runtime session --bus` (`session-bus`) writes
|
||||
`Environment=FLY_SESSION_TRANSPORT=bus` into the runtime drop-in, and `session --local` takes it out.
|
||||
|
||||
*The topology (process mode, the bus default).*
|
||||
|
||||
| Process | Runs | Bus client | Reached by |
|
||||
| --- | --- | --- | --- |
|
||||
| `flysim-session` (the unit's main process) | the router (one per session), the launcher's supervisor, the coordinator with the `pokered-macros-v1` task and executor, the service host (feed, control API, metrics, checkpoint writer, sugar journal) | `coordinator`, `launcher` | in memory: they live with the router |
|
||||
| `fly-session legacy-agent` (child) | AGENT-01: the brain, its readout and its sweep pool | `legacy-fly`, registers `agent.fly` | `<session dir>/attempt-N/sockets/legacy-fly-<n>.sock`, launcher-bound |
|
||||
| `fly-session legacy-environment` (child) | ENV-01: binjgb, the slot, the memory image | `legacy-world`, then `legacy-world-r2` for the restore's replacement world; registers `env.world` | `.../sockets/legacy-world[-r2]-<n>.sock`, launcher-bound |
|
||||
|
||||
- *Policy* (closed, `composition.rs`): the coordinator may call `agent.*` and `env.*` and owns
|
||||
`session.*` (publish, topics, its query service); the supervisor may call `agent.*` and `env.*`
|
||||
and register nothing; each participant may register exactly its own service and call nothing.
|
||||
An identity is bound by the launcher before Hello, so a process cannot answer as another.
|
||||
- *Media* stay artifacts in the router's store (`<session dir>/attempt-N/store`, tmpfs, `fly`
|
||||
0700): the 92,160-byte frame, the 65,536-byte memory image, the audio chunk (about 6.4 KB a frame
|
||||
of `f32le`) and the 17,407-byte spike bitset every transition, and the captures (MBs, every hot
|
||||
save). Inline is not an option: bus-v1 section 8.1 forbids binary in a body, and the image alone
|
||||
would not fit the 64 KiB envelope once encoded. A delivery names each attachment's read location
|
||||
(bus-v1 section 12, 2026-10-01), so a read is a local file read; a worker seals into writers it
|
||||
allocated after the previous step (`worker::WriterPool`). Over the bus the agent's Commit also
|
||||
attaches its feed status (`legacy.feed-status`, the `Legacy.FeedStatus` result's bytes as of the
|
||||
committed boundary), which the service host reads instead of making that call at every publish;
|
||||
a rollback after the Commit makes it ask again.
|
||||
- *One unit, restarted as a whole.* The session cannot survive the loss of a participant: its
|
||||
state is split across them and is recovered only as a group (STATE-01), and the store's last save
|
||||
is that group. So the children belong to `flysim.service` (the launcher spawns them; systemd's
|
||||
default `KillMode=control-group` reaps them with the unit), a dead participant fails the step
|
||||
within `ipc-v1` section 6's ten seconds, `flysim-session` exits, and `Restart=always` starts the
|
||||
whole session again from the store -- what a crash of the in-process session does today. A
|
||||
child also exits when its router connection closes. The router lives in the coordinator's
|
||||
process for the same reason: its loss is the session's. One unit keeps `fly-runtime`'s one
|
||||
drop-in switch, the `OnFailure=` fallback to legacy (three starts in ten minutes), the speed
|
||||
probation, the watchdog and the unstick rule's restart unchanged; separate units would need
|
||||
`BindsTo=` chains and three start limits for no recovery a group restore does not already give.
|
||||
- *CPUs.* The unit's cpuset is unchanged (on the release container `flysim.slice`'s four CPUs).
|
||||
The service splits it as PERF-02 does and hands the split out: the agent process pins its spawned
|
||||
sweep workers one per CPU and keeps its other threads (its dispatcher is sweep worker 0) on the
|
||||
remaining CPU (`fly-session ... --sweep-cpus 3,5,7 --host-cpus 1`); the service process and the
|
||||
world process run on that same host CPU. The transaction is serial -- nothing overlaps Prepare
|
||||
(PERF-01) -- so they take turns on it rather than contend. `FLY_SESSION_AUX_CPUS` moves the
|
||||
service and the world elsewhere in the unit's cpuset; it was measured and does not pay
|
||||
(implementation guide, BUS-01). `FLY_SESSION_PIN=0` floats everything, as before.
|
||||
- *Each participant process has one async worker, and a long handler gives it up*
|
||||
(`tokio::task::block_in_place` for `*.Initialize`, `State.*`, `Agent.Rollback`): the agent's
|
||||
warm-up runs for seconds, and a Tokio worker blocked that long stranded the shell's own bus loop,
|
||||
so `ipc-v1` section 6's resolution of a slow `Agent.Initialize` failed ("never resolved") and a
|
||||
session could not boot on a loaded box. A step's handlers (milliseconds) run in place, so a bus
|
||||
request crosses no thread inside a participant. The local lane is unchanged.
|
||||
|
||||
*N agents and M environments are configuration.* Nothing above assumes one of each: the
|
||||
launcher starts any number of `LegacyAgentLaunch` and environment launches, each with its own
|
||||
client id, service name and socket; the policy grants are per client; placements are per worker
|
||||
id (`Launcher::place_process`), so each agent process pins its own sweep to its own CPUs; the
|
||||
coordinator calls agents concurrently and assembles one batch over every declared port; the router
|
||||
has no notion of a fly. What is one-of-each today is this composition (`LegacyConfig`, one
|
||||
`PokeredTask`, `FLYSIM01`'s one agent and one world) and the service's CPU split (one agent's
|
||||
plan), which a multi-agent composition replaces rather than extends.
|
||||
|
||||
## 13. Machine-readable parts
|
||||
|
||||
| Where | What |
|
||||
|
|
@ -944,3 +1017,24 @@ verdict comes back (`shadow::remote`, `shadow::relay`, `shadow::ingest`).
|
|||
unchanged. `fly-shadow-run start` runs the shadow on the container only with `--local`.
|
||||
- *The guard* stays on the container and guards the live fly as before; it now watches the relay's
|
||||
cost, which is a few file reads and one ssh stream.
|
||||
|
||||
**Amendment, 2026-10-01 (BUS-01): a shadow of the bus topology.** A cutover onto the bus is a
|
||||
cutover into another topology, so it needs a shadow that ran it. `fly-shadow --mode` (and
|
||||
`FLY_SHADOW_MODE`) names the topology as `SessionArm` does: `local` (the default, the in-process
|
||||
lane; `in-process` is the same), `bus/thread`, `bus/process` (`bus`, `process`), `bus/in-process`.
|
||||
`fly-shadow-run start --bus` sets `FLY_SHADOW_MODE=bus/process` in a drop-in of
|
||||
`flyshadow.service` (`mode.conf`); in remote mode the relay forwards it with the rest of the live
|
||||
composition's settings (it is in `FORWARDED_ENV`), so the box's shadow -- the same release, which
|
||||
ships `fly-session` beside `fly-shadow` -- starts its agent and its world as child processes on its
|
||||
own router's sockets. Its placement is the box's: the shadow places no thread. The verdict records
|
||||
the topology (`candidate.executionMode`, and `candidate.transport`, new), and
|
||||
`fly-shadow check --require-arm bus/process` (`fly-shadow-run check --bus`) refuses a verdict that
|
||||
did not run it; a verdict from before this amendment, with no `transport`, counts as `local` when
|
||||
it ran in process. The comparison, the window and every other rule of this section are unchanged.
|
||||
|
||||
The shadow follows the trace only the legacy loop writes (`FLY_TRACE_DIR`); the session runtime
|
||||
ignores it. So the live fly runs the legacy runtime for the shadow's window, as it did for CUT-01:
|
||||
`fly-shadow-run start` refuses while `flysim.service` runs the session runtime. The procedure for a
|
||||
switch onto the bus is: `fly-runtime legacy`; `fly-shadow-run start --bus`; three hours of zero
|
||||
divergence; `fly-shadow-run check --bus && fly-runtime session --bus` (the probation then judges
|
||||
the bus topology). Shadowing the session runtime from its own trace is not built.
|
||||
|
|
|
|||
|
|
@ -123,6 +123,9 @@ need pct
|
|||
# /opt/fly/current, rather than half way through the deploy or at flysim's boot.
|
||||
FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")" \
|
||||
|| die "05-deploy: FLY_FEED_VIA must be 'direct' or 'bus', got '${FLY_FEED_VIA}'"
|
||||
# Who serves the control API (docs/design/flybus.md, "Control over the bus"): the same.
|
||||
FLY_CONTROL_VIA_EFFECTIVE="$(control_via_normalize "${FLY_CONTROL_VIA:-}")" \
|
||||
|| die "05-deploy: FLY_CONTROL_VIA must be 'direct' or 'bus', got '${FLY_CONTROL_VIA}'"
|
||||
|
||||
# The container's own value, read before anything changes. A `fly-feed bus` (or `direct`) on the
|
||||
# container is not in the env file unless the operator put it there, and this deploy writes the env
|
||||
|
|
@ -421,6 +424,11 @@ The 'current' symlink has NOT been moved; the running release is untouched."
|
|||
if ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then
|
||||
ct_exec "$CTID" -- test -x "${release_path}/flysim-session" \
|
||||
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime (fly-runtime session) and this release has no flysim-session. Run \`fly-runtime legacy\` in the container first, or deploy a release that ships it. The 'current' symlink has NOT been moved."
|
||||
# BUS-01: on the bus transport flysim-session starts its participants from fly-session.
|
||||
if ct_exec "$CTID" -- grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' /etc/systemd/system/flysim.service.d/10-runtime.conf; then
|
||||
ct_exec "$CTID" -- test -x "${release_path}/fly-session" \
|
||||
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime on the bus (fly-runtime session --bus) and this release has no fly-session worker. Run \`fly-runtime session --local\` in the container first. The 'current' symlink has NOT been moved."
|
||||
fi
|
||||
session_compat="$(ct_exec "$CTID" -- env \
|
||||
"FLY_GAME=${GAME}" \
|
||||
"FLY_DATASET=${release_path}/data/fafb-v783" \
|
||||
|
|
@ -609,6 +617,14 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
|
|||
# feed counters (flysim's :9101, or flyedge's loopback :9102).
|
||||
# Validated and lowercased above (feed_via_normalize).
|
||||
echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"
|
||||
# Who serves the control API on :7401 (docs/design/flybus.md, "Control over
|
||||
# the bus"). "direct" is the default: flysim binds it. "bus" makes flysim
|
||||
# register the control services on its embedded router and leave :7401 to
|
||||
# flycontrol-edge.service, which this script never enables (runbook,
|
||||
# "Control over the bus"). Written unconditionally; the watchdog reads it
|
||||
# to know whose /healthz is flysim's own (check 1) and whether to watch
|
||||
# the edge (check 1b). Validated and lowercased above.
|
||||
echo "FLY_CONTROL_VIA=${FLY_CONTROL_VIA_EFFECTIVE}"
|
||||
# How long a macro leaves a target alone after a walk to it aborted
|
||||
# (macros.md section 12.1, the Viridian stall). Only written when it is set,
|
||||
# because the default lives in the crate and a box that has not tuned it
|
||||
|
|
@ -746,7 +762,8 @@ if [ -n "${CPUSET:-}" ]; then
|
|||
log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')"
|
||||
tmp_dropin="$(mktemp)"
|
||||
# flyedge is off by default, but its drop-in is written with the rest so that the day
|
||||
# it is enabled it serves the page from the page's CPUs, never from flysim's.
|
||||
# it is enabled it serves the page from the page's CPUs, never from flysim's; likewise
|
||||
# flycontrol-edge (CTRL-01).
|
||||
# flysim-session (SERVE-01) is the session runtime's standalone unit: flysim's cores.
|
||||
# (`fly-runtime session` runs it AS flysim.service, which already has them.)
|
||||
# flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not
|
||||
|
|
|
|||
|
|
@ -3,8 +3,10 @@
|
|||
# session runtime (`flysim-session`, SERVE-01).
|
||||
#
|
||||
# Usage (INSIDE the container, as root):
|
||||
# fly-runtime status print `legacy` or `session`, and what flysim.service runs
|
||||
# fly-runtime session [--no-restart] [--no-fallback] [--no-probation]
|
||||
# fly-runtime status print `legacy` or `session` (and the session's transport), and
|
||||
# what flysim.service runs
|
||||
# fly-runtime session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation]
|
||||
# fly-runtime session-bus [...] the same as `session --bus`
|
||||
# fly-runtime legacy [--no-restart]
|
||||
# fly-runtime fallback [reason] (run by fly-runtime-fallback.service, see below; idempotent)
|
||||
#
|
||||
|
|
@ -12,6 +14,19 @@
|
|||
# the one-command rollback (port decisions, 2026-09-23). Neither migrates any data: both
|
||||
# binaries read and write the same FLYSIM01 stores, event log, sugar journal and chat sidecar.
|
||||
#
|
||||
# The session's transport (BUS-01). `--local` (the default for a first switch) runs the session's
|
||||
# participants in flysim-session's own process over the local lane. `--bus` runs them on the flybus
|
||||
# router over Unix sockets: flysim-session (the router, the coordinator, the listeners) starts the
|
||||
# agent and the world as child processes of the same unit (`fly-session legacy-agent`,
|
||||
# `fly-session legacy-environment`, from the same release), in flysim.slice, on flysim's cpuset.
|
||||
# The drop-in then carries `Environment=FLY_SESSION_TRANSPORT=bus`. Without either flag `session`
|
||||
# keeps the transport the drop-in already has, so 05-deploy's `session --no-restart` refresh never
|
||||
# changes it; `session --local` is the way back from the bus. Results, traces, checkpoints and the
|
||||
# compatibility string are the same in both: only where the participants run changes. A switch onto
|
||||
# the bus needs a shadow that ran the bus (`fly-shadow-run check --bus`), which the coordinator runs
|
||||
# before this command, as for the first cutover. Everything below applies to both transports: one
|
||||
# unit, OnFailure= falls back to LEGACY, the probation judges the session runtime either way.
|
||||
#
|
||||
# How the switch works. flysim.service stays the fly's one unit name, and the runtime it runs
|
||||
# is chosen by one drop-in, ${DROPIN}:
|
||||
#
|
||||
|
|
@ -91,6 +106,7 @@ RUNTIME_LOG="$FLY_RUNTIME_LOG"
|
|||
FELLBACK_FILE="$FLY_RUNTIME_FELLBACK"
|
||||
FALLBACK_UNIT=fly-runtime-fallback.service
|
||||
SESSION_BIN="${FLY_RELEASE_DIR}/flysim-session"
|
||||
WORKER_BIN="${FLY_RELEASE_DIR}/fly-session"
|
||||
LEGACY_BIN="${FLY_RELEASE_DIR}/flysim"
|
||||
SESSION_DIR=/run/fly/session
|
||||
SHADOW_RUN_BIN="${FLY_SHADOW_RUN_BIN:-$(dirname "$(readlink -f "$0")")/fly-shadow-run}"
|
||||
|
|
@ -120,7 +136,7 @@ stop_shadow() {
|
|||
}
|
||||
|
||||
usage() {
|
||||
echo "usage: fly-runtime status | session [--no-restart] [--no-fallback] [--no-probation] | legacy [--no-restart] | fallback [reason]" >&2
|
||||
echo "usage: fly-runtime status | session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation] | session-bus [...] | legacy [--no-restart] | fallback [reason]" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
|
|
@ -128,6 +144,20 @@ current() {
|
|||
if [ -f "$DROPIN" ]; then echo session; else echo legacy; fi
|
||||
}
|
||||
|
||||
# The session's transport the drop-in selects: `bus` or `local` (also with no drop-in).
|
||||
current_transport() {
|
||||
if [ -f "$DROPIN" ] && grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' "$DROPIN"; then
|
||||
echo bus
|
||||
else
|
||||
echo local
|
||||
fi
|
||||
}
|
||||
|
||||
# `legacy`, `session` or `session-bus`, for the runtime log.
|
||||
current_label() {
|
||||
if [ "$(current)" = session ] && [ "$(current_transport)" = bus ]; then echo session-bus; else current; fi
|
||||
}
|
||||
|
||||
record() {
|
||||
local line
|
||||
line="$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*"
|
||||
|
|
@ -176,6 +206,12 @@ ExecStart=${SESSION_BIN}
|
|||
Environment=FLY_SESSION_DIR=${SESSION_DIR}
|
||||
Environment=MALLOC_ARENA_MAX=2
|
||||
EOF
|
||||
if [ "$transport" = bus ]; then
|
||||
cat >>"$tmp" <<EOF
|
||||
# BUS-01: the participants are child processes on the session router's Unix sockets.
|
||||
Environment=FLY_SESSION_TRANSPORT=bus
|
||||
EOF
|
||||
fi
|
||||
chmod 0644 "$tmp"
|
||||
mv -f "$tmp" "$DROPIN"
|
||||
}
|
||||
|
|
@ -339,26 +375,33 @@ command="$1"; shift
|
|||
restart=1
|
||||
fallback=1
|
||||
probe=1
|
||||
transport=""
|
||||
fallback_reason=""
|
||||
if [ "$command" = fallback ]; then fallback_reason="$*"; set --; fi
|
||||
if [ "$command" = session-bus ]; then command=session; transport=bus; fi
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--no-restart) restart=0 ;;
|
||||
--no-fallback) fallback=0 ;;
|
||||
--no-probation) probe=0 ;;
|
||||
--bus) [ "$command" = session ] || usage; transport=bus ;;
|
||||
--local) [ "$command" = session ] || usage; transport=local ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
done
|
||||
# No flag: keep the drop-in's transport (05-deploy's refresh); local for a first switch.
|
||||
[ -n "$transport" ] || transport="$(current_transport)"
|
||||
|
||||
case "$command" in
|
||||
status)
|
||||
current
|
||||
if [ "$(current)" = session ]; then echo " transport: $(current_transport)"; fi
|
||||
if [ -f "$FELLBACK_FILE" ]; then echo " fell back to legacy: $(cat "$FELLBACK_FILE")"; fi
|
||||
if [ -x "$PROBATION_BIN" ]; then "$PROBATION_BIN" status 2>/dev/null | sed 's/^/ /' || true; fi
|
||||
systemctl show -p ExecStart --value "$FLY_SERVICE" 2>/dev/null | sed -n 's/.*path=\([^ ;]*\).*/ flysim.service runs \1/p' || true
|
||||
exit 0
|
||||
;;
|
||||
session|legacy) ;;
|
||||
session|session-bus|legacy) ;;
|
||||
fallback)
|
||||
[ "$(id -u)" -eq 0 ] || die "run as root"
|
||||
do_fallback "${fallback_reason:-flysim.service failed on the session runtime (OnFailure=)}"
|
||||
|
|
@ -372,6 +415,9 @@ esac
|
|||
if [ "$command" = session ]; then
|
||||
[ -x "$SESSION_BIN" ] || die "this release has no ${SESSION_BIN}; the session runtime ships from SERVE-01 on"
|
||||
[ -x "$LEGACY_BIN" ] || die "no ${LEGACY_BIN}"
|
||||
if [ "$transport" = bus ] && [ ! -x "$WORKER_BIN" ]; then
|
||||
die "this release has no ${WORKER_BIN}: the bus transport starts its participants from it"
|
||||
fi
|
||||
legacy_compat="$(compat_of "$LEGACY_BIN")"
|
||||
session_compat="$(compat_of "$SESSION_BIN")"
|
||||
[ -n "$session_compat" ] || die "${SESSION_BIN} --print-compatibility printed nothing (see its stderr); not switching"
|
||||
|
|
@ -381,7 +427,7 @@ if [ "$command" = session ]; then
|
|||
flysim-session: ${session_compat}"
|
||||
fi
|
||||
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
|
||||
before="$(current)"
|
||||
before="$(current_label)"
|
||||
if [ -f "$DROPIN" ]; then
|
||||
prev_dropin="$(mktemp "${DROPIN}.prev.XXXXXX")"
|
||||
cp -f "$DROPIN" "$prev_dropin"
|
||||
|
|
@ -390,7 +436,7 @@ if [ "$command" = session ]; then
|
|||
switching=1
|
||||
rm -f "$FELLBACK_FILE"
|
||||
write_dropin
|
||||
record "session (was ${before}); compatibility ${session_compat}"
|
||||
record "$(current_label) (was ${before}); compatibility ${session_compat}"
|
||||
if [ "$restart" -ne 1 ]; then
|
||||
systemctl daemon-reload
|
||||
switching=0
|
||||
|
|
@ -438,7 +484,7 @@ fi
|
|||
|
||||
# legacy
|
||||
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
|
||||
before="$(current)"
|
||||
before="$(current_label)"
|
||||
switch_target=legacy
|
||||
switching=1
|
||||
rm -f "$DROPIN"
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@
|
|||
# restart; --restart-flysim restarts it now), remove trace and spool
|
||||
# fly-shadow-run status the verdict in one screen
|
||||
# fly-shadow-run check CUT-01's hook: exit 0 only if the verdict allows the automatic cutover
|
||||
# into the release /opt/fly/current points to, onto flysim-session
|
||||
# into the release /opt/fly/current points to, onto flysim-session.
|
||||
# --bus also requires that the shadow ran the bus topology (BUS-01)
|
||||
# fly-shadow-run guard (flyshadow-guard.timer, every 60 s) stop everything and restart flysim
|
||||
# without the trace if the live fly pays for the shadow
|
||||
# fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl the guard's rule over recorded samples
|
||||
|
|
@ -53,6 +54,17 @@
|
|||
# ActiveState inactive or failed (systemctl show), never activating: the shadow's 10-s crash-restart
|
||||
# delay must not switch the guard off. `check` also requires the guard timer active and baseline.json.
|
||||
#
|
||||
# THE BUS TOPOLOGY (BUS-01). `start --bus` runs the shadow's session the way `fly-runtime
|
||||
# session --bus` runs the live one: the router, the coordinator and the task in the shadow's own
|
||||
# process, the agent and the world as child processes (`fly-session legacy-agent`,
|
||||
# `fly-session legacy-environment`, from the same release) on the router's Unix sockets. It sets
|
||||
# FLY_SHADOW_MODE=bus/process in flyshadow.service's drop-in (mode.conf); a remote relay forwards it
|
||||
# to the box (live.env), whose shadow reads it. The verdict records the topology
|
||||
# (candidate.executionMode "process", candidate.transport "bus"), and `check --bus` refuses any
|
||||
# verdict that did not run it. The live fly must run the LEGACY runtime while a shadow runs: only
|
||||
# the legacy loop writes the trace (FLY_TRACE_DIR) the shadow follows, so `start` refuses while
|
||||
# flysim.service runs the session runtime (fly-runtime status: session).
|
||||
#
|
||||
# REMOTE (SHADOW-02). With /etc/fly/shadow-remote.env present (the operator's private file:
|
||||
# FLY_SHADOW_REMOTE=<user>@<box>, FLY_SHADOW_REMOTE_KEY, FLY_SHADOW_REMOTE_KNOWN_HOSTS, optional
|
||||
# FLY_SHADOW_REMOTE_PORT), `start` gives flyshadow.service a drop-in (remote.conf) that runs
|
||||
|
|
@ -85,6 +97,8 @@ DROPIN="$DROPIN_DIR/shadow-trace.conf"
|
|||
REMOTE_ENV="${FLY_SHADOW_REMOTE_ENV:-/etc/fly/shadow-remote.env}"
|
||||
REMOTE_DROPIN_DIR="${FLY_SHADOW_REMOTE_DROPIN_DIR:-/etc/systemd/system/flyshadow.service.d}"
|
||||
REMOTE_DROPIN="$REMOTE_DROPIN_DIR/remote.conf"
|
||||
MODE_DROPIN="$REMOTE_DROPIN_DIR/mode.conf"
|
||||
RUNTIME_DROPIN="${FLY_RUNTIME_DROPIN:-$DROPIN_DIR/10-runtime.conf}"
|
||||
# How long start waits for the first heartbeat (remote: at least 300 s, because the box's shadow
|
||||
# restarts for the new run and the ingest hashes the release first).
|
||||
HEARTBEAT_WAIT="${FLY_SHADOW_HEARTBEAT_WAIT_SECONDS:-60}"
|
||||
|
|
@ -275,14 +289,21 @@ check_remote() {
|
|||
|
||||
start() {
|
||||
need_root
|
||||
local mode=remote
|
||||
local mode=remote arm=""
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--local) mode=local ;;
|
||||
--bus) arm=bus/process ;;
|
||||
*) die "start: unknown option $arg" ;;
|
||||
esac
|
||||
done
|
||||
[ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
|
||||
# Only the legacy loop writes the trace the shadow follows (FLY_TRACE_DIR); the session runtime
|
||||
# ignores it, and every process it ran would be a coverage divergence.
|
||||
[ ! -f "$RUNTIME_DROPIN" ] || die "flysim.service runs the session runtime, which writes no trace for a shadow to follow. Switch the live fly to legacy for the shadow window first (fly-runtime legacy), then start the shadow"
|
||||
if [ -n "$arm" ]; then
|
||||
[ -x "$(dirname "$(readlink -f "$BIN")")/fly-session" ] || die "the bus topology needs fly-session beside $BIN"
|
||||
fi
|
||||
systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running"
|
||||
if [ "$mode" = remote ]; then
|
||||
[ -f "$REMOTE_ENV" ] || die "no $REMOTE_ENV: the shadow runs on a build box (SHADOW-02; runbook). Pass --local to run it on this container instead, at the live fly's expense"
|
||||
|
|
@ -311,6 +332,17 @@ start() {
|
|||
chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json"
|
||||
log "baseline: $base"
|
||||
mkdir -p "$DROPIN_DIR" "$REMOTE_DROPIN_DIR"
|
||||
if [ -n "$arm" ]; then
|
||||
cat > "$MODE_DROPIN" <<EOF
|
||||
# written by fly-shadow-run start --bus (BUS-01); removed by fly-shadow-run stop and by its guard.
|
||||
# The shadow's session runs the bus topology; a remote relay forwards this to the box.
|
||||
[Service]
|
||||
Environment=FLY_SHADOW_MODE=$arm
|
||||
EOF
|
||||
log "the shadow runs the bus topology ($arm)"
|
||||
else
|
||||
rm -f "$MODE_DROPIN"
|
||||
fi
|
||||
if [ "$mode" = remote ]; then
|
||||
local run_id
|
||||
run_id="$(date +%s%3N)"
|
||||
|
|
@ -360,7 +392,7 @@ EOF
|
|||
stop_all() {
|
||||
systemctl stop flyshadow-guard.timer 2>/dev/null || true
|
||||
systemctl stop flyshadow.service 2>/dev/null || true
|
||||
rm -f "$DROPIN" "$REMOTE_DROPIN"
|
||||
rm -f "$DROPIN" "$REMOTE_DROPIN" "$MODE_DROPIN"
|
||||
systemctl daemon-reload
|
||||
log "stopped the shadow: $1"
|
||||
}
|
||||
|
|
@ -476,6 +508,16 @@ PY
|
|||
}
|
||||
|
||||
check() {
|
||||
# `--bus` (BUS-01): the cutover goes onto the bus topology, so the shadow must have run it.
|
||||
local -a pass=()
|
||||
local arg
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--bus) pass+=(--require-arm bus/process) ;;
|
||||
*) pass+=("$arg") ;;
|
||||
esac
|
||||
done
|
||||
set -- "${pass[@]}"
|
||||
# A tripped guard, a shadow that is not running, or a run that no guard watched never allows a
|
||||
# cutover, whatever the verdict file says: the guard timer must be active and its baseline
|
||||
# present (G1-a).
|
||||
|
|
|
|||
|
|
@ -327,9 +327,30 @@ is_enabled() {
|
|||
# ============================================================================
|
||||
# Check 1: flysim — /healthz 200 and hot-state mtime age < 30s.
|
||||
# ============================================================================
|
||||
# FLY_CONTROL_VIA from fly.env, lowercased ("direct" when absent).
|
||||
control_via() {
|
||||
local via=""
|
||||
if [ -f "$FLY_ENV_FILE" ]; then
|
||||
via="$(awk -F= '/^FLY_CONTROL_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
|
||||
fi
|
||||
echo "${via:-direct}"
|
||||
}
|
||||
|
||||
# flysim's own /healthz: :7401 when flysim serves it, and with FLY_CONTROL_VIA=bus
|
||||
# (docs/design/flybus.md, "Control over the bus") flysim's read-only listener,
|
||||
# which flysim serves itself in both modes -- so an edge that is down is check
|
||||
# 1b's business and never restarts the fly.
|
||||
flysim_health_url() {
|
||||
if [ "$(control_via)" = "bus" ]; then
|
||||
echo "${FLY_METRICS_URL}/healthz"
|
||||
else
|
||||
echo "${FLY_CONTROL_URL}/healthz"
|
||||
fi
|
||||
}
|
||||
|
||||
check_flysim() {
|
||||
local ok=1
|
||||
if ! curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then
|
||||
if ! curl -fsS -o /dev/null "$(flysim_health_url)"; then
|
||||
ok=0
|
||||
fi
|
||||
if [ -e "$FLY_STATE_HOT" ]; then
|
||||
|
|
@ -347,6 +368,24 @@ check_flysim() {
|
|||
fi
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# Check 1b: flycontrol-edge -- only with FLY_CONTROL_VIA=bus. :7401/healthz
|
||||
# answered by the edge while flysim's own /healthz is fine; when the edge does
|
||||
# not answer, restart the edge (never flysim, never a reboot: the fly is fine
|
||||
# and the edge holds no state). With flysim itself down, check 1 owns it.
|
||||
# ============================================================================
|
||||
check_control_edge() {
|
||||
[ "$(control_via)" = "bus" ] || return 0
|
||||
curl -fsS -o /dev/null "${FLY_METRICS_URL}/healthz" || return 0
|
||||
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then
|
||||
record_ok flycontrol-edge
|
||||
else
|
||||
record_fail flycontrol-edge
|
||||
log_err "flycontrol-edge: :7401 does not answer while flysim is healthy; restarting the edge"
|
||||
restart_unit flycontrol-edge
|
||||
fi
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# Check 2: flystage — flysim's frames_sent_total / feed_clients from the
|
||||
# read-only metrics listener (infra.md section 5; not superseded by the
|
||||
|
|
@ -1285,6 +1324,7 @@ check_loop() {
|
|||
main() {
|
||||
check_flysim
|
||||
check_flyedge
|
||||
check_control_edge
|
||||
check_flystage
|
||||
check_flycast
|
||||
check_encoder
|
||||
|
|
|
|||
|
|
@ -85,6 +85,9 @@ log "building in $crate_dir for target-cpu=haswell (the host is E5-2660 v3, Hasw
|
|||
# without a rebuild. It lands next to OUT_PATH, where package-release.sh
|
||||
# looks for it.
|
||||
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge
|
||||
# fly-control-edge (FLY_CONTROL_VIA=bus, CTRL-01): the control API served from
|
||||
# flysim's control services on the bus. Same reasons, same place.
|
||||
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-control-edge
|
||||
# flysim-session (SERVE-01): the live fly on the session runtime, a drop-in for flysim
|
||||
# that `fly-runtime session` points flysim.service at; fly-shadow (SHADOW-01,
|
||||
# infra/units/flyshadow.service): the session runtime shadowing the live fly; and
|
||||
|
|
@ -125,6 +128,12 @@ edge_out="$(dirname "$OUT_PATH")/fly-edge"
|
|||
cp "$edge_built" "$edge_out"
|
||||
chmod 0755 "$edge_out"
|
||||
log "built $edge_out ($(du -h "$edge_out" | cut -f1))"
|
||||
control_edge_built="${crate_dir}/target/${CARGO_TARGET}/release/fly-control-edge"
|
||||
[ -x "$control_edge_built" ] || die "expected binary not found after build: $control_edge_built"
|
||||
control_edge_out="$(dirname "$OUT_PATH")/fly-control-edge"
|
||||
cp "$control_edge_built" "$control_edge_out"
|
||||
chmod 0755 "$control_edge_out"
|
||||
log "built $control_edge_out ($(du -h "$control_edge_out" | cut -f1))"
|
||||
for extra in flysim-session fly-shadow fly-session; do
|
||||
extra_built="${crate_dir}/target/${CARGO_TARGET}/release/${extra}"
|
||||
[ -x "$extra_built" ] || die "expected binary not found after build: $extra_built"
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@
|
|||
# fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh
|
||||
# left one beside FLYSIM_BIN; flyedge.service stays
|
||||
# inactive on a release without it)
|
||||
# fly-control-edge (the control-bus edge, CTRL-01, likewise;
|
||||
# flycontrol-edge.service stays inactive without it)
|
||||
# flysim-session (the session runtime, SERVE-01, and fly-session, its
|
||||
# fly-shadow worker program; mode 0755, when build-flysim.sh left
|
||||
# fly-session them beside FLYSIM_BIN. `fly-runtime session` refuses
|
||||
|
|
@ -88,6 +90,13 @@ if [ -x "$EDGE_BIN" ]; then
|
|||
else
|
||||
log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)"
|
||||
fi
|
||||
CONTROL_EDGE_BIN="$(dirname "$FLYSIM_BIN")/fly-control-edge"
|
||||
if [ -x "$CONTROL_EDGE_BIN" ]; then
|
||||
cp "$CONTROL_EDGE_BIN" "${release_dir}/fly-control-edge"
|
||||
chmod 0755 "${release_dir}/fly-control-edge"
|
||||
else
|
||||
log "no fly-control-edge beside $FLYSIM_BIN; packaging without it (FLY_CONTROL_VIA=bus unavailable in this release)"
|
||||
fi
|
||||
for extra in flysim-session fly-shadow fly-session; do
|
||||
EXTRA_BIN="$(dirname "$FLYSIM_BIN")/${extra}"
|
||||
if [ -x "$EXTRA_BIN" ]; then
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
# <unit>` and, on the 5-consecutive-failure escalation, a container
|
||||
# reboot. This is the minimum NOPASSWD surface for exactly what
|
||||
# bin/fly-watchdog's checks actually restart (flysim, flystage, flycast,
|
||||
# mediamtx, flypush, flyedge in bus mode), plus reboot. No `systemctl stop`, no
|
||||
# mediamtx, flypush, flyedge in bus mode, flycontrol-edge when FLY_CONTROL_VIA=bus), plus reboot. No `systemctl stop`, no
|
||||
# `enable`/`disable`, no arbitrary unit name, and no units this script
|
||||
# does not itself restart (xvfb, pulse, flystage-web are never touched by
|
||||
# fly-watchdog's checks, so they are not granted here).
|
||||
|
|
@ -16,6 +16,7 @@ fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flyedge.service
|
|||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service
|
||||
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycontrol-edge.service
|
||||
fly ALL=(root) NOPASSWD: /usr/sbin/reboot
|
||||
# fly-loop-recover.service (also User=fly): its ladder restarts flysim (granted above) and
|
||||
# resets to a milestone archive through this one root wrapper, which validates the rung,
|
||||
|
|
|
|||
|
|
@ -518,6 +518,26 @@ pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback
|
|||
(flysim's limits, cpuset and environment; `Conflicts=flysim.service`; no `[Install]`, so it
|
||||
cannot be enabled). It is for a rehearsal or a soak on a container whose `flysim.service` is
|
||||
stopped, not for switching the stream.
|
||||
- **The session on the bus (BUS-01).** `fly-runtime session --bus` (or `session-bus`) runs the
|
||||
session's participants on the flybus router over Unix sockets: `flysim-session` (the router, the
|
||||
coordinator, the listeners) starts `fly-session legacy-agent` and `fly-session legacy-environment`
|
||||
as children of the same unit, in `flysim.slice`, on flysim's CPUs. The drop-in gains
|
||||
`Environment=FLY_SESSION_TRANSPORT=bus`; `fly-runtime status` prints `session` and then
|
||||
` transport: bus`. `fly-runtime session` without a flag (05-deploy's refresh) keeps the transport
|
||||
the drop-in has; `fly-runtime session --local` goes back to the in-process lane, and
|
||||
`fly-runtime legacy` to legacy. The fallback, the probation, the watchdog and the unstick rule's
|
||||
restart are the same on either transport: one unit, restarted as a whole, children included
|
||||
(`ps -o pid,args --ppid $(systemctl show -p MainPID --value flysim)` lists them). A deploy
|
||||
refuses a release without `fly-session` while the drop-in says `bus`. **Before switching onto the
|
||||
bus, run a shadow of it** (Shadow run below): with the live fly on legacy (`fly-runtime legacy`),
|
||||
`fly-shadow-run start --bus`, three hours, then `fly-shadow-run check --bus && fly-runtime
|
||||
session --bus`. Watch `fly_frame_work_mean_ms` and `fly_frame_work_p99_ms` on `/metrics` (the
|
||||
loop's compute time per frame, without its pacing sleep, over the last 3,600 frames; the budget
|
||||
at real time is 16.74 ms): they show the headroom that a realtime factor of 1.0 hides.
|
||||
- **Per-frame compute time, both runtimes.** `/metrics` exports `fly_frame_work_mean_ms`,
|
||||
`fly_frame_work_p99_ms`, `fly_frame_work_max_ms` and `fly_frame_work_frames` for the legacy loop
|
||||
and the session runtime alike: everything one running iteration does except the pacing sleep.
|
||||
Headroom is `1 - mean / 16.74` at real time.
|
||||
|
||||
## Feed over the bus (EDGE-02)
|
||||
|
||||
|
|
@ -677,6 +697,12 @@ pct exec <ctid> -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0
|
|||
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off
|
||||
```
|
||||
|
||||
- **A shadow of the bus topology (BUS-01).** `start --bus` runs the box's shadow session with its
|
||||
agent and world as child processes on its router's sockets (`FLY_SHADOW_MODE=bus/process`, which
|
||||
the relay forwards); `check --bus` also requires that the verdict ran that topology
|
||||
(`candidate.transport` `bus`, `executionMode` `process`). The live fly must be on the legacy
|
||||
runtime for any shadow: only the legacy loop writes the trace, and `start` refuses otherwise.
|
||||
|
||||
- **Where it runs (SHADOW-02).** On a build box, not on the release container: there it cost the
|
||||
live fly real time (2026-09-30: the realtime factor fell from 0.9998 to 0.93-0.98 and came back
|
||||
to 0.999-1.0 the moment the shadow stopped), and at about 27 ms a frame on shared CPUs it fell
|
||||
|
|
@ -945,6 +971,76 @@ pct exec $CTID -- /opt/fly/bin/fly-runtime legacy
|
|||
growth, a restore, a restart, legacy cancel), and the unit wiring has been run under a real
|
||||
systemd 257 user manager (state, timer enable/disable, `OnFailure`-style fallback, resume).
|
||||
|
||||
## Control over the bus (CTRL-01)
|
||||
|
||||
`FLY_CONTROL_VIA` picks who serves `http://127.0.0.1:7401`: `direct` (the default; flysim binds
|
||||
it) or `bus`. In bus mode flysim registers the control API as RPC services on its embedded flybus
|
||||
router, and `flycontrol-edge.service` serves the same HTTP bytes on `:7401` by calling them
|
||||
(`docs/design/flybus.md`, "Control over the bus"). Clients do not change: the bridge, the stage's
|
||||
health wait, the watchdog, `fly-runtime`, the probation and shadow guards, `fly-loop-recover`,
|
||||
the stream check and `curl` still talk to `:7401`. It works under either runtime, independently
|
||||
of `FLY_FEED_VIA`. Claim the container in the host log first, as for any host work.
|
||||
|
||||
**Prerequisites.** The release ships `fly-control-edge` (`ls /opt/fly/current/fly-control-edge`).
|
||||
The env file has `FLY_CONTROL_VIA=bus`, deployed with `05-deploy.sh`. The deploy only rewrites
|
||||
`/etc/fly/fly.env` and pushes the unit; it neither enables the edge nor restarts flysim, so the
|
||||
box keeps serving `:7401` directly until step 2.
|
||||
|
||||
```
|
||||
# 1. Before: what the switch must preserve.
|
||||
pct exec $CTID -- grep -E '^FLY_(CONTROL|FEED)_VIA=' /etc/fly/fly.env # FLY_CONTROL_VIA=bus
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status, .checkpoint'
|
||||
pct exec $CTID -- curl -s -X POST 127.0.0.1:7401/checkpoint # a fresh generation to restart from
|
||||
# 2. The switch: flysim stops binding :7401 and registers the services; the edge (Wants= of
|
||||
# flysim.service, started with it because fly.env says bus) binds :7401 once they answer.
|
||||
# Between the two, :7401 refuses connections, exactly as during any flysim restart.
|
||||
# There is nothing to enable: the unit has no [Install] section.
|
||||
pct exec $CTID -- systemctl restart flysim.service
|
||||
# 3. Verify.
|
||||
pct exec $CTID -- ss -ltnp | grep ':7401' # users:(("fly-control-edg"...
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz # {"status":"ok"}
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status' # the frame moves
|
||||
pct exec $CTID -- curl -s 127.0.0.1:9103/metrics | grep -E '^fly_control_edge_(bus_connected|calls_total|call_failures_total)'
|
||||
pct exec $CTID -- journalctl -u flysim -b --since -5min | grep -E 'control services registered|bus listening'
|
||||
pct exec $CTID -- ls /run/fly/bus/control-edge.sock /run/fly/bus/control/
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7410/health | jq . # the bridge: sim reachable
|
||||
```
|
||||
|
||||
- **Healthy looks like:** `fly_control_edge_bus_connected 1`, `calls_total` rising (the bridge and
|
||||
the watchdog poll it), `call_failures_total` flat, no `fly-watchdog:` restart lines, and the next
|
||||
real channel-points sugar fulfilled as before. Do not fire a test sugar or chat line on the live
|
||||
stream to prove it; both are visible on screen.
|
||||
- **Watchdog.** With `FLY_CONTROL_VIA=bus`, check 1 reads flysim's own `/healthz` on `:9101`, so a
|
||||
dead edge never restarts the fly. Check 1b restarts `flycontrol-edge` alone when `:7401` fails
|
||||
while flysim is healthy (the sudoers file grants exactly that restart).
|
||||
- **Restarts.** `flysim.service` has `Wants=flycontrol-edge.service` and the edge has `Requires=`
|
||||
on flysim plus an `ExecCondition=` on `FLY_CONTROL_VIA`, so the edge follows flysim in bus mode
|
||||
and stays off ("skipped", not failed) in direct mode. A `restart`, and a `stop` then `start`
|
||||
(`fly-loop-reset`, `fly-reset-to-milestone`, the milestone-reset rung of the unstick rule) all
|
||||
bring `:7401` back with flysim; nothing needs a separate `start` of the edge. A crash-restart of flysim needs nothing: the edge
|
||||
unbinds `:7401`, reconnects every 500 ms and binds again once the new services answer.
|
||||
|
||||
**Rollback** (any time, no release change):
|
||||
|
||||
```
|
||||
pct exec $CTID -- sed -i 's/^FLY_CONTROL_VIA=.*/FLY_CONTROL_VIA=direct/' /etc/fly/fly.env
|
||||
pct exec $CTID -- systemctl restart flysim.service # binds :7401 itself; the edge is skipped
|
||||
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz
|
||||
# then set FLY_CONTROL_VIA=direct in the env file too, or the next 05-deploy.sh writes bus back.
|
||||
```
|
||||
|
||||
- **Rolling back to a release from before CTRL-01 while in bus mode** is safe. The older flysim
|
||||
does not know `FLY_CONTROL_VIA`, so it binds `:7401` itself. The edge unit's
|
||||
`ConditionPathExists=` keeps it inactive on a release without the binary, and the older
|
||||
watchdog reads `:7401` as before. Switch to direct first anyway, so the env file says what
|
||||
runs.
|
||||
- **If the edge cannot bind** (`fly_control_edge_bind_failures_total` rising, "the control port
|
||||
cannot be bound" in its journal), flysim is still in direct mode. `fly.env` says bus but flysim
|
||||
was not restarted after the deploy. Restart flysim (step 2).
|
||||
- **Upgrading a container that had the edge enabled** (before this wiring): an
|
||||
old `fly.target.wants/flycontrol-edge.service` symlink is harmless (the condition decides), but
|
||||
run `systemctl disable flycontrol-edge.service` once so `systemctl is-enabled` says what is true.
|
||||
|
||||
## CPU partition (cpuset)
|
||||
|
||||
`05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit
|
||||
|
|
|
|||
7
infra/env/example.env
vendored
7
infra/env/example.env
vendored
|
|
@ -329,6 +329,13 @@ FLY_MACRO_MODE=raw
|
|||
# Watchdog check 2 follows the running mode to the edge's counters by itself.
|
||||
# Runbook: "Feed over the bus".
|
||||
FLY_FEED_VIA=direct
|
||||
# --- control path -------------------------------------------------------------
|
||||
# Who serves http://127.0.0.1:7401 (docs/control-api.md; docs/design/flybus.md,
|
||||
# "Control over the bus"). direct: flysim binds it, as always. bus: flysim
|
||||
# registers the control services on its embedded bus (/run/fly/bus) and
|
||||
# flycontrol-edge.service serves the same bytes; enable that unit by hand
|
||||
# (infra/docs/runbook.md, "Control over the bus"). Independent of FLY_FEED_VIA.
|
||||
FLY_CONTROL_VIA=direct
|
||||
# How long a macro leaves a target alone after a walk to it aborted "blocked" or
|
||||
# "timeout" (macros.md section 12.1). Session state, so a restart offers every
|
||||
# target once more. Unset means the default, 10.
|
||||
|
|
|
|||
|
|
@ -168,6 +168,19 @@ feed_via_normalize() {
|
|||
esac
|
||||
}
|
||||
|
||||
# control_via_normalize VALUE — FLY_CONTROL_VIA as feed_via_normalize does FLY_FEED_VIA:
|
||||
# lowercased (empty means "direct"), or return 1 for anything but direct|bus. flysim refuses
|
||||
# anything else at boot; 05-deploy.sh refuses it at deploy and writes the lowercased word, which
|
||||
# the watchdog reads to know who serves :7401 (docs/design/flybus.md, "Control over the bus").
|
||||
control_via_normalize() {
|
||||
local via
|
||||
via="$(printf '%s' "${1:-direct}" | tr '[:upper:]' '[:lower:]')"
|
||||
case "$via" in
|
||||
direct|bus) printf '%s\n' "$via" ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
cpuset_partition() {
|
||||
local cpuset="$1" rayon_threads="$2" encoder_cores="${3:-2}"
|
||||
local sim_cpus remainder remainder_count page_count page_cpus encoder_cpus
|
||||
|
|
@ -196,7 +209,7 @@ cpuset_partition() {
|
|||
# flysim.slice the sim's CPUs (flysim.service and flysim-session.service run in it);
|
||||
# flysim.service, flysim-session.service the same set (belt and braces: a unit outside the
|
||||
# slice is still bounded);
|
||||
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge the page CPUs;
|
||||
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge, flycontrol-edge the page CPUs;
|
||||
# flycast the encoder CPUs;
|
||||
# flyshadow page + encoder (never the sim's);
|
||||
# FLY_SIM_CPUS / FLY_OTHER_CPUS "=": the lists /etc/fly/cpuset.env carries; OTHER is every CPU
|
||||
|
|
@ -209,7 +222,7 @@ cpuset_dropin_plan() {
|
|||
read -r sim page enc <<< "$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1
|
||||
echo "flysim.slice $sim"
|
||||
for u in flysim flysim-session; do echo "${u}.service $sim"; done
|
||||
for u in xvfb flystage flystage-web pulse mediamtx flyedge; do echo "${u}.service $page"; done
|
||||
for u in xvfb flystage flystage-web pulse mediamtx flyedge flycontrol-edge; do echo "${u}.service $page"; done
|
||||
echo "flycast.service $enc"
|
||||
echo "flyshadow.service ${page},${enc}"
|
||||
echo "FLY_SIM_CPUS= $sim"
|
||||
|
|
|
|||
|
|
@ -507,6 +507,89 @@ if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR
|
|||
else
|
||||
pass "07-enable.sh and verify.sh leave flyedge.service alone"
|
||||
fi
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3b2b. The control bus edge (CTRL-01, docs/design/flybus.md, "Control over the
|
||||
# bus"). flycontrol-edge.service is off unless the operator switches a
|
||||
# container to FLY_CONTROL_VIA=bus, follows flysim when on, and the deploy
|
||||
# writes the default. The watchdog's use of FLY_CONTROL_VIA is driven for real
|
||||
# further down, next to check 2's.
|
||||
# ---------------------------------------------------------------------------
|
||||
echo "--- flycontrol-edge.service: follows flysim in bus mode, skipped in direct mode ---"
|
||||
CEDGE_UNIT="$INFRA_DIR/units/flycontrol-edge.service"
|
||||
if [ ! -f "$CEDGE_UNIT" ]; then
|
||||
fail "units/flycontrol-edge.service is missing"
|
||||
else
|
||||
grep -qE '^After=.*\bflysim\.service\b' "$CEDGE_UNIT" \
|
||||
&& pass "flycontrol-edge.service orders itself After=flysim.service" \
|
||||
|| fail "flycontrol-edge.service must be After=flysim.service: flysim owns the router"
|
||||
grep -qE '^Requires=.*\bflysim\.service\b' "$CEDGE_UNIT" \
|
||||
&& pass "flycontrol-edge.service Requires=flysim.service" \
|
||||
|| fail "flycontrol-edge.service must Require flysim.service"
|
||||
grep -qE '^ExecStart=/opt/fly/current/fly-control-edge$' "$CEDGE_UNIT" \
|
||||
&& pass "flycontrol-edge.service runs the release's fly-control-edge" \
|
||||
|| fail "flycontrol-edge.service ExecStart must be /opt/fly/current/fly-control-edge"
|
||||
grep -qE '^ConditionPathExists=/opt/fly/current/fly-control-edge$' "$CEDGE_UNIT" \
|
||||
&& pass "flycontrol-edge.service stays inactive on a release without fly-control-edge" \
|
||||
|| fail "flycontrol-edge.service needs ConditionPathExists=/opt/fly/current/fly-control-edge"
|
||||
grep -qE '^Environment=FLY_CONTROL_BIND=127\.0\.0\.1:7401$' "$CEDGE_UNIT" \
|
||||
&& pass "flycontrol-edge.service binds the contract's loopback :7401" \
|
||||
|| fail "flycontrol-edge.service FLY_CONTROL_BIND must be 127.0.0.1:7401 (docs/control-api.md)"
|
||||
# N1 (review of CTRL-01): Requires= alone stops the edge with flysim but never starts it
|
||||
# again, so fly-loop-reset's stop and start left :7401 dead. flysim Wants= it, and the
|
||||
# unit's own ExecCondition= decides by FLY_CONTROL_VIA (EDGE-02's pattern for flyedge).
|
||||
grep -qE '^Wants=.*\bflycontrol-edge\.service\b' "$INFRA_DIR/units/flysim.service" \
|
||||
&& pass "flysim.service Wants=flycontrol-edge.service (every flysim start brings the edge up in bus mode)" \
|
||||
|| fail "flysim.service must Want flycontrol-edge.service: a stop and start of flysim (fly-loop-reset) would leave :7401 dead"
|
||||
if grep -qE '^\[Install\]' "$CEDGE_UNIT"; then
|
||||
fail "flycontrol-edge.service has an [Install] section; flysim's Wants= is what starts it"
|
||||
else
|
||||
pass "flycontrol-edge.service has no [Install] section"
|
||||
fi
|
||||
cond="$(sed -nE "s/^ExecCondition=\/bin\/sh -c '(.*)'\$/\1/p" "$CEDGE_UNIT")"
|
||||
if [ -z "$cond" ]; then
|
||||
fail "flycontrol-edge.service needs an ExecCondition= on FLY_CONTROL_VIA"
|
||||
else
|
||||
# Run the condition as systemd would ($$ is systemd's escape for a literal $).
|
||||
cond="${cond//\$\$/\$}"
|
||||
cond_bad=""
|
||||
for v in "" direct Direct junk; do
|
||||
FLY_CONTROL_VIA="$v" sh -c "$cond" && cond_bad="$cond_bad [$v->runs]"
|
||||
done
|
||||
env -u FLY_CONTROL_VIA sh -c "$cond" && cond_bad="$cond_bad [unset->runs]"
|
||||
for v in bus Bus BUS; do
|
||||
FLY_CONTROL_VIA="$v" sh -c "$cond" || cond_bad="$cond_bad [$v->skipped]"
|
||||
done
|
||||
[ -z "$cond_bad" ] \
|
||||
&& pass "flycontrol-edge.service ExecCondition= runs only for FLY_CONTROL_VIA=bus (any case); direct, unset and junk skip" \
|
||||
|| fail "flycontrol-edge.service ExecCondition= wrong for:$cond_bad"
|
||||
fi
|
||||
grep -qE '^Environment=FLY_CONTROL_EDGE_METRICS_ADDR=127\.0\.0\.1:' "$CEDGE_UNIT" \
|
||||
&& pass "flycontrol-edge.service keeps its metrics on loopback" \
|
||||
|| fail "flycontrol-edge.service FLY_CONTROL_EDGE_METRICS_ADDR must be a 127.0.0.1 address"
|
||||
fi
|
||||
if target_pulls "$INFRA_DIR/units/fly.target" | grep -qx 'flycontrol-edge.service'; then
|
||||
fail "fly.target pulls flycontrol-edge.service in; flysim.service Wants= it, the condition decides"
|
||||
else
|
||||
pass "fly.target does not pull flycontrol-edge.service in"
|
||||
fi
|
||||
if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR/verify.sh" | grep -q 'flycontrol-edge'; then
|
||||
fail "07-enable.sh or verify.sh lists flycontrol-edge.service as always-on"
|
||||
else
|
||||
pass "07-enable.sh and verify.sh leave flycontrol-edge.service alone"
|
||||
fi
|
||||
grep -qE '^ echo "FLY_CONTROL_VIA=\$\{FLY_CONTROL_VIA_EFFECTIVE\}"$' "$INFRA_DIR/05-deploy.sh" \
|
||||
&& pass "05-deploy.sh writes FLY_CONTROL_VIA into fly.env" \
|
||||
|| fail "05-deploy.sh must write FLY_CONTROL_VIA (validated) into fly.env"
|
||||
grep -qE '^fly ALL=\(root\) NOPASSWD: /usr/bin/systemctl restart flycontrol-edge\.service$' "$INFRA_DIR/config/fly-sudoers" \
|
||||
&& pass "the watchdog may restart flycontrol-edge.service" \
|
||||
|| fail "config/fly-sudoers must let the watchdog restart flycontrol-edge.service (check 1b)"
|
||||
cv_out="$(bash -c "source '$INFRA_DIR/lib/common.sh' >/dev/null 2>&1; for v in '' direct Bus BUS http; do control_via_normalize \"\$v\" || echo refused; done" 2>&1)"
|
||||
if [ "$(echo $cv_out)" = "direct direct bus bus refused" ]; then
|
||||
pass "control_via_normalize: empty/direct -> direct, Bus/BUS -> bus, anything else refused"
|
||||
else
|
||||
fail "control_via_normalize: got '$(echo $cv_out)'"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3b3. The shadow run (SHADOW-01, infra/units/flyshadow.service).
|
||||
#
|
||||
|
|
@ -732,7 +815,60 @@ rs_start "no remote file (the shadow runs on a build box; --local to override)"
|
|||
rs_start "a remote file without its key" "FLY_SHADOW_REMOTE=user@box
|
||||
FLY_SHADOW_REMOTE_KEY=$cs_tmp/missing-key
|
||||
FLY_SHADOW_REMOTE_KNOWN_HOSTS=$cs_tmp/missing-known"
|
||||
# BUS-01: only the legacy loop writes the trace, so `start` refuses while flysim.service runs the
|
||||
# session runtime; `--bus` needs the release's fly-session worker beside fly-shadow.
|
||||
bs_start() { # name, expect (refuse|proceed), runtime drop-in (yes|no), worker (yes|no), args...
|
||||
local name="$1" expect="$2" rt="$3" worker="$4" rc=0 out
|
||||
shift 4
|
||||
: > "$cs_tmp/systemctl.log"
|
||||
rm -f "$cs_tmp/10-runtime.conf" "$cs_tmp/fly-session"
|
||||
[ "$rt" = yes ] && printf '[Service]\nExecStart=/opt/fly/current/flysim-session\n' > "$cs_tmp/10-runtime.conf"
|
||||
[ "$worker" = yes ] && { printf '#!/bin/sh\nexit 0\n' > "$cs_tmp/fly-session"; chmod +x "$cs_tmp/fly-session"; }
|
||||
out="$(PATH="$cs_tmp/bin:$PATH" CS_DIR="$cs_tmp" CS_SHADOW_CPUS="0 2" CS_SIM_CPUS="1 3" \
|
||||
FLY_SHADOW_DIR="$cs_tmp/shadow" FLY_SHADOW_BIN="$cs_tmp/fly-shadow" \
|
||||
FLY_SHADOW_CPUSET_DROPIN="$cs_tmp/dropin.conf" FLY_SHADOW_REMOTE_ENV="$cs_tmp/no-remote.env" \
|
||||
FLY_SHADOW_REMOTE_DROPIN_DIR="$cs_tmp/flyshadow.d" FLY_RUNTIME_DROPIN="$cs_tmp/10-runtime.conf" \
|
||||
FLY_SHADOW_BASELINE_SECONDS=30 FLY_METRICS_URL=http://127.0.0.1:1 \
|
||||
"$INFRA_DIR/bin/fly-shadow-run" start "$@" 2>&1)" || rc=$?
|
||||
case "$expect" in
|
||||
refuse)
|
||||
if [ "$rc" -ne 0 ] && ! grep -qE '^(start|restart|daemon-reload)' "$cs_tmp/systemctl.log" \
|
||||
&& [ ! -e "$cs_tmp/flyshadow.d/mode.conf" ]; then
|
||||
pass "fly-shadow-run start refuses, $name: ${out#fly-shadow-run: }"
|
||||
else
|
||||
fail "fly-shadow-run start must refuse and start nothing, $name (rc=$rc): $out"
|
||||
fi ;;
|
||||
proceed)
|
||||
if echo "$out" | grep -q 'stub install reached'; then
|
||||
pass "fly-shadow-run start proceeds, $name"
|
||||
else
|
||||
fail "fly-shadow-run start must proceed, $name (rc=$rc): $out"
|
||||
fi ;;
|
||||
esac
|
||||
}
|
||||
bs_start "the live fly on the session runtime (no trace to follow)" refuse yes yes --local
|
||||
bs_start "--bus without fly-session in the release" refuse no no --local --bus
|
||||
bs_start "--bus with fly-session, live on legacy" proceed no yes --local --bus
|
||||
rm -rf "$cs_tmp"
|
||||
# BUS-01: `check --bus` asks fly-shadow for a verdict that ran the bus topology.
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
cb_tmp="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-checkbus.XXXXXX")"
|
||||
mkdir -p "$cb_tmp/bin" "$cb_tmp/shadow"
|
||||
printf '#!/bin/sh\ncase "$1" in is-active) exit 0 ;; esac\nexit 0\n' > "$cb_tmp/bin/systemctl"
|
||||
printf '#!/bin/sh\necho "$*" > "%s/args"\n' "$cb_tmp" > "$cb_tmp/fly-shadow"
|
||||
chmod +x "$cb_tmp/bin/systemctl" "$cb_tmp/fly-shadow"
|
||||
printf '{"rtfMean":1,"rtfSd":0,"lagRate":0,"samples":60,"margin":0.05}\n' > "$cb_tmp/shadow/baseline.json"
|
||||
printf '{"status":"pass"}\n' > "$cb_tmp/shadow/verdict.json"
|
||||
PATH="$cb_tmp/bin:$PATH" FLY_SHADOW_DIR="$cb_tmp/shadow" FLY_SHADOW_BIN="$cb_tmp/fly-shadow" \
|
||||
FLY_SHADOW_REMOTE_DROPIN_DIR="$cb_tmp/none.d" FLY_ENV_FILE="$cb_tmp/none.env" \
|
||||
"$INFRA_DIR/bin/fly-shadow-run" check --bus >/dev/null 2>&1 || true
|
||||
if grep -q -- '--binary flysim-session --require-arm bus/process$' "$cb_tmp/args" 2>/dev/null; then
|
||||
pass "fly-shadow-run check --bus requires a verdict that ran bus/process (fly-shadow check --require-arm)"
|
||||
else
|
||||
fail "fly-shadow-run check --bus must pass --require-arm bus/process to fly-shadow check ($(cat "$cb_tmp/args" 2>/dev/null))"
|
||||
fi
|
||||
rm -rf "$cb_tmp"
|
||||
fi
|
||||
# SHADOW-02: `check` in remote mode also needs the relay healthy now (relay.json under a minute
|
||||
# old), of this run (the drop-in's id, the verdict's too), without coverageLost (review B1: flysim
|
||||
# stopped its trace for want of a consumer) and with a live trace written in the last 90 s.
|
||||
|
|
@ -1002,6 +1138,50 @@ if fly_runtime && [ ! -f "$rt_dropin" ]; then
|
|||
else
|
||||
fail "fly-runtime legacy must remove the drop-in and succeed"
|
||||
fi
|
||||
# BUS-01: the bus transport. `session-bus` (= `session --bus`) adds FLY_SESSION_TRANSPORT=bus to
|
||||
# the drop-in and needs the release's fly-session worker; a flag-less `session` (05-deploy's
|
||||
# refresh) keeps the transport; `session --local` is the way back; status says which.
|
||||
rt_status() { env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_SYSTEMD_DIR="$rt_dir/systemd" bash "$INFRA_DIR/bin/fly-runtime" status 2>/dev/null; }
|
||||
RT_ARGS=(session-bus)
|
||||
if ! fly_runtime && [ ! -f "$rt_dropin" ]; then
|
||||
pass "fly-runtime session-bus refuses a release without the fly-session worker"
|
||||
else
|
||||
fail "fly-runtime session-bus must refuse without \$FLY_RELEASE_DIR/fly-session and write nothing"
|
||||
fi
|
||||
printf '#!/usr/bin/env bash\nexit 0\n' > "$rt_dir/release/fly-session"
|
||||
chmod +x "$rt_dir/release/fly-session"
|
||||
if fly_runtime && grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' "$rt_dropin" \
|
||||
&& grep -qx "ExecStart=$rt_dir/release/flysim-session" "$rt_dropin" \
|
||||
&& grep -qx 'OnFailure=fly-runtime-fallback.service' "$rt_dropin" \
|
||||
&& [ "$(rt_status | head -n1)" = session ] \
|
||||
&& rt_status | grep -qx ' transport: bus' \
|
||||
&& tail -n1 "$rt_dir/runtime.log" | grep -q 'session-bus (was legacy)'; then
|
||||
pass "fly-runtime session-bus: the drop-in adds FLY_SESSION_TRANSPORT=bus (fallback and probation unchanged); status: session, transport bus"
|
||||
else
|
||||
fail "fly-runtime session-bus: drop-in/status/log wrong ($(tr '\n' ' ' < "$rt_dropin" 2>/dev/null); $(tail -n1 "$rt_dir/runtime.log"))"
|
||||
fi
|
||||
RT_ARGS=(session --no-restart)
|
||||
if fly_runtime && grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' "$rt_dropin"; then
|
||||
pass "fly-runtime session --no-restart (05-deploy's refresh) keeps the bus transport"
|
||||
else
|
||||
fail "fly-runtime session --no-restart must keep the drop-in's transport"
|
||||
fi
|
||||
RT_ARGS=(session --local)
|
||||
if fly_runtime && [ -f "$rt_dropin" ] && ! grep -q 'FLY_SESSION_TRANSPORT' "$rt_dropin" \
|
||||
&& rt_status | grep -qx ' transport: local' \
|
||||
&& tail -n1 "$rt_dir/runtime.log" | grep -q 'session (was session-bus)'; then
|
||||
pass "fly-runtime session --local takes the session off the bus (status: transport local)"
|
||||
else
|
||||
fail "fly-runtime session --local must drop FLY_SESSION_TRANSPORT from the drop-in"
|
||||
fi
|
||||
RT_ARGS=(legacy --bus)
|
||||
if ! fly_runtime && [ -f "$rt_dropin" ]; then
|
||||
pass "fly-runtime legacy --bus is refused (usage)"
|
||||
else
|
||||
fail "fly-runtime legacy --bus must be refused"
|
||||
fi
|
||||
rm -f "$rt_dir/release/fly-session"
|
||||
RT_ARGS=(legacy); fly_runtime || fail "fly-runtime legacy after the bus tests failed"
|
||||
RT_ARGS=(session)
|
||||
if ! fly_runtime RT_COMPAT_FLYSIM_SESSION=other && [ ! -f "$rt_dropin" ]; then
|
||||
pass "fly-runtime session refuses when the two compatibility strings differ"
|
||||
|
|
@ -1394,6 +1574,27 @@ else
|
|||
feed_url_case "BUS" "FLY_FEED_VIA=BUS" "" "http://edge"
|
||||
feed_url_case "quoted bus" 'FLY_FEED_VIA="bus"' "" "http://edge"
|
||||
feed_url_case "explicit override wins" "FLY_FEED_VIA=bus" "http://other" "http://other"
|
||||
# Check 1 reads flysim's own /healthz: :7401 when flysim serves it, flysim's read-only
|
||||
# listener when the control edge does (FLY_CONTROL_VIA=bus), so an edge outage never
|
||||
# restarts the fly (CTRL-01).
|
||||
health_url_case() {
|
||||
local label="$1" env_line="$2" want="$3" got
|
||||
printf '%s\n' "$env_line" > "$fe_fixture/fly.env"
|
||||
got="$(FLY_ENV_FILE="$fe_fixture/fly.env" FLY_CONTROL_URL=http://control \
|
||||
FLY_METRICS_URL=http://sim \
|
||||
WD_RUN_DIR="$fe_fixture/run" WD_STATE_DIR="$fe_fixture/state" \
|
||||
TEXTFILE_DIR="$fe_fixture/textfile" \
|
||||
bash -c "source '$fe_fixture/wd.sh'; flysim_health_url" 2>&1 || true)"
|
||||
if [ "$got" = "$want" ]; then
|
||||
pass "check 1 flysim health: $label -> $got"
|
||||
else
|
||||
fail "check 1 flysim health: $label: got '$got', want '$want'"
|
||||
fi
|
||||
}
|
||||
health_url_case "direct" "FLY_CONTROL_VIA=direct" "http://control/healthz"
|
||||
health_url_case "no FLY_CONTROL_VIA line" "FLY_FEED_VIA=bus" "http://control/healthz"
|
||||
health_url_case "bus" "FLY_CONTROL_VIA=bus" "http://sim/healthz"
|
||||
health_url_case "Bus" 'FLY_CONTROL_VIA="Bus"' "http://sim/healthz"
|
||||
rm -rf "$fe_fixture"
|
||||
fi
|
||||
|
||||
|
|
|
|||
56
infra/units/flycontrol-edge.service
Normal file
56
infra/units/flycontrol-edge.service
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
# infra/units/flycontrol-edge.service — pushed to /etc/systemd/system/flycontrol-edge.service.
|
||||
#
|
||||
# The control API (http://127.0.0.1:7401, docs/control-api.md) served from
|
||||
# flysim's control services on the bus (docs/design/flybus.md, "Control over
|
||||
# the bus"; services/flysim/crates/fly-control-edge). Whether it runs is decided
|
||||
# by one line, FLY_CONTROL_VIA in /etc/fly/fly.env (05-deploy.sh writes it from
|
||||
# the env file's FLY_CONTROL_VIA, default `direct`):
|
||||
#
|
||||
# direct flysim binds 127.0.0.1:7401 itself. ExecCondition= below fails, so
|
||||
# this unit starts as "skipped" (inactive, no failure, no restart).
|
||||
# bus flysim registers the control services on its router and leaves
|
||||
# :7401 to this unit.
|
||||
#
|
||||
# flysim.service has Wants= on this unit, so EVERY start of flysim (the unstick
|
||||
# rule's restart, fly-loop-reset's stop and start, fly-reset-to-milestone, a
|
||||
# crash-restart, a reboot through fly.target) starts the edge in bus mode and
|
||||
# skips it in direct mode; fly.env alone decides, and flysim and the edge can
|
||||
# never disagree. This unit is in no target and has no [Install] section:
|
||||
# `systemctl enable` has nothing to do. The switch and the way back are
|
||||
# infra/docs/runbook.md, "Control over the bus": edit FLY_CONTROL_VIA, run
|
||||
# 05-deploy.sh, restart flysim.
|
||||
#
|
||||
# Ordering: flysim owns the router (/run/fly/bus, shared with the feed when
|
||||
# that rides the bus too), so it starts first and the edge follows it.
|
||||
# Requires= makes an explicit stop or restart of flysim stop or restart the
|
||||
# edge with it (and Wants= on the other side brings it back after a plain
|
||||
# start). A crash-restart of flysim is covered by the edge itself: it unbinds
|
||||
# :7401 and reconnects every 500 ms, so to every client it looks exactly like
|
||||
# flysim restarting. The edge holds no state.
|
||||
[Unit]
|
||||
Description=flycontrol-edge: the control API served from flysim's control services on the bus
|
||||
After=flysim.service
|
||||
Requires=flysim.service
|
||||
# A release that predates fly-control-edge has no binary; stay cleanly
|
||||
# inactive rather than restart-looping.
|
||||
ConditionPathExists=/opt/fly/current/fly-control-edge
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=fly
|
||||
# FLY_CONTROL_VIA, FLY_BUS_DIR and the rest of flysim's configuration: the
|
||||
# edge reads the same file, so the two cannot disagree about the port or the bus.
|
||||
EnvironmentFile=/etc/fly/fly.env
|
||||
Environment=FLY_CONTROL_BIND=127.0.0.1:7401
|
||||
Environment=FLY_BUS_DIR=/run/fly/bus
|
||||
# Its own /metrics and /healthz. Loopback only.
|
||||
Environment=FLY_CONTROL_EDGE_METRICS_ADDR=127.0.0.1:9103
|
||||
# Only in bus mode. EnvironmentFile= is the same fly.env flysim reads, so this is the value
|
||||
# flysim started with (flysim reads it case-insensitively, so does this). Exit 1 means
|
||||
# "skip": the unit goes inactive without failing and without being restarted.
|
||||
ExecCondition=/bin/sh -c 'case "$$FLY_CONTROL_VIA" in [Bb][Uu][Ss]) ;; *) exit 1;; esac'
|
||||
ExecStart=/opt/fly/current/fly-control-edge
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
# Small JSON requests; an /events page is the largest thing it ever holds.
|
||||
MemoryMax=128M
|
||||
|
|
@ -18,7 +18,11 @@ After=network.target
|
|||
# direct mode (units/flyedge.service decides): a stop and start of flysim (fly-loop-reset,
|
||||
# fly-reset-to-milestone) would otherwise leave the stage with nothing on :7400, because
|
||||
# flyedge.service's Requires= stops the edge with flysim but does not bring it back.
|
||||
Wants=flyedge.service
|
||||
# Every start of flysim starts the control edge when fly.env says FLY_CONTROL_VIA=bus, and skips
|
||||
# it in direct mode (units/flycontrol-edge.service decides): a stop and start of flysim
|
||||
# (fly-loop-reset, fly-reset-to-milestone) would otherwise leave :7401 dead, because the edge's
|
||||
# Requires= stops it with flysim but does not bring it back.
|
||||
Wants=flyedge.service flycontrol-edge.service
|
||||
StartLimitIntervalSec=300
|
||||
StartLimitBurst=5
|
||||
|
||||
|
|
|
|||
18
services/flysim/Cargo.lock
generated
18
services/flysim/Cargo.lock
generated
|
|
@ -416,6 +416,23 @@ dependencies = [
|
|||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fly-control-edge"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
"clap",
|
||||
"flybus",
|
||||
"flysim",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fly-edge"
|
||||
version = "0.1.1"
|
||||
|
|
@ -442,6 +459,7 @@ dependencies = [
|
|||
"anyhow",
|
||||
"axum",
|
||||
"clap",
|
||||
"fly-control-edge",
|
||||
"fly-session",
|
||||
"flybrain-core",
|
||||
"flybrain-gb",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
[workspace]
|
||||
resolver = "3"
|
||||
members = [
|
||||
"crates/fly-control-edge",
|
||||
"crates/fly-edge",
|
||||
"crates/fly-legacy-session",
|
||||
"crates/fly-session",
|
||||
|
|
|
|||
35
services/flysim/crates/fly-control-edge/Cargo.toml
Normal file
35
services/flysim/crates/fly-control-edge/Cargo.toml
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
[package]
|
||||
name = "fly-control-edge"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "The control API (:7401) served from flysim's control services on the bus (FLY_CONTROL_VIA=bus)."
|
||||
|
||||
[lib]
|
||||
name = "fly_control_edge"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "fly-control-edge"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
# The HTTP layer, the request/reply types and the bus encoding are flysim's own modules (`api`,
|
||||
# `control`, `controlbus`), so the edge writes the :7401 bytes with the code flysim uses in direct
|
||||
# mode and cannot disagree with the services about the encoding.
|
||||
flysim = { path = "../flysim" }
|
||||
flybus = { path = "../flybus" }
|
||||
|
||||
anyhow = "1.0"
|
||||
axum = "0.8"
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "net", "sync", "time", "signal", "macros"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
462
services/flysim/crates/fly-control-edge/src/lib.rs
Normal file
462
services/flysim/crates/fly-control-edge/src/lib.rs
Normal file
|
|
@ -0,0 +1,462 @@
|
|||
//! `fly-control-edge`: the control API on `:7401`, answered by flysim's control services on the
|
||||
//! bus (CTRL-01, `docs/design/flybus.md`, "Control over the bus").
|
||||
//!
|
||||
//! With `FLY_CONTROL_VIA=bus` flysim (either runtime) does not bind `control.bind`. It registers
|
||||
//! the control services on its embedded router (`flysim::controlbus`), and this process serves the
|
||||
//! HTTP surface of `docs/control-api.md` to the bridge, the stage, the infra scripts and the
|
||||
//! operator's `curl` by calling them. The HTTP layer is flysim's own `api::router_with`, so the
|
||||
//! routes, the 404s, the extractors, the headers and the body encoding are the code direct mode
|
||||
//! runs; this crate only adds a [`BusBackend`] that carries each request across the bus.
|
||||
//!
|
||||
//! Lifecycle (as `fly-edge` for the feed):
|
||||
//!
|
||||
//! - the control port is bound only once the control services answer, so before that a client
|
||||
//! is refused exactly as it is by a flysim that has not started;
|
||||
//! - when the bus goes away (flysim stopped or restarted) the edge unbinds the port, again what a
|
||||
//! stopped flysim looks like, and reconnects every `retry` until a router answers.
|
||||
//!
|
||||
//! Failures on the bus side map onto the 503s direct mode answers for the same failure (the
|
||||
//! words are `flysim::control::unavailable`), so a client cannot tell which side was in trouble.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::get;
|
||||
use flybus::{BusError, Client, ClientConfig, Dispatch, ErrorCode};
|
||||
use flysim::api::ControlBackend;
|
||||
use flysim::control::{COMMAND_TIMEOUT, ControlReply, ControlRequest, unavailable};
|
||||
use flysim::controlbus::{self, Role, Scope};
|
||||
use flysim::feedbus;
|
||||
use flysim::metrics::metric;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// How much longer than the services' own [`COMMAND_TIMEOUT`] the edge waits before it gives up
|
||||
/// on a timed request and cancels it. The services answer a wedged loop with their own 503 at
|
||||
/// [`COMMAND_TIMEOUT`]; this guard only covers a bus or a host that stopped answering at all.
|
||||
pub const DEADLINE_MARGIN: Duration = Duration::from_secs(2);
|
||||
|
||||
/// What the edge needs to know, from flysim's own configuration.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EdgeConfig {
|
||||
/// `feed.bus_dir`: the router's sockets and store root.
|
||||
pub bus_dir: PathBuf,
|
||||
/// `control.bind`, the port flysim leaves alone in bus mode.
|
||||
pub control_bind: SocketAddr,
|
||||
/// `FLY_CONTROL_EDGE_METRICS_ADDR`: the edge's own `/metrics` and `/healthz`, when set.
|
||||
pub metrics_bind: Option<SocketAddr>,
|
||||
/// Delay between attempts to reach the bus.
|
||||
pub retry: Duration,
|
||||
/// The session and agents whose services `:7401` addresses.
|
||||
pub scope: Scope,
|
||||
}
|
||||
|
||||
impl EdgeConfig {
|
||||
pub fn from_flysim(config: &flysim::config::Config, metrics_bind: Option<SocketAddr>) -> Self {
|
||||
Self {
|
||||
bus_dir: config.feed.bus_dir.clone(),
|
||||
control_bind: config.control.bind,
|
||||
metrics_bind,
|
||||
retry: Duration::from_millis(500),
|
||||
scope: Scope::live(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The edge's counters.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct EdgeMetrics {
|
||||
/// 1 while connected and serving.
|
||||
pub connected: AtomicU64,
|
||||
/// Requests carried across the bus.
|
||||
pub calls: AtomicU64,
|
||||
/// Requests that ended in a bus failure rather than a reply (each a 503 or 403 to the
|
||||
/// client).
|
||||
pub call_failures: AtomicU64,
|
||||
/// Requests the edge cancelled at its own deadline.
|
||||
pub cancelled: AtomicU64,
|
||||
/// Serving sessions ended by the bus going away.
|
||||
pub bus_lost: AtomicU64,
|
||||
/// Sessions that reached the bus but could not bind the control port.
|
||||
pub bind_failures: AtomicU64,
|
||||
}
|
||||
|
||||
impl EdgeMetrics {
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = String::with_capacity(1_024);
|
||||
for (name, kind, help, value) in [
|
||||
(
|
||||
"fly_control_edge_bus_connected",
|
||||
"gauge",
|
||||
"1 while the edge is connected to the control bus and serving.",
|
||||
&self.connected,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_calls_total",
|
||||
"counter",
|
||||
"Control requests carried across the bus.",
|
||||
&self.calls,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_call_failures_total",
|
||||
"counter",
|
||||
"Control requests that ended in a bus failure instead of a reply.",
|
||||
&self.call_failures,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_cancelled_total",
|
||||
"counter",
|
||||
"Control requests the edge cancelled at its own deadline.",
|
||||
&self.cancelled,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_bus_lost_total",
|
||||
"counter",
|
||||
"Serving sessions ended by the control bus going away.",
|
||||
&self.bus_lost,
|
||||
),
|
||||
(
|
||||
"fly_control_edge_bind_failures_total",
|
||||
"counter",
|
||||
"Times the bus was reachable but the control port could not be bound.",
|
||||
&self.bind_failures,
|
||||
),
|
||||
] {
|
||||
metric(&mut out, name, kind, help, value.load(Ordering::Relaxed));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`ControlBackend`] that answers each request by calling the control services on the bus.
|
||||
#[derive(Clone)]
|
||||
pub struct BusBackend {
|
||||
client: Client,
|
||||
scope: Scope,
|
||||
metrics: Arc<EdgeMetrics>,
|
||||
}
|
||||
|
||||
impl BusBackend {
|
||||
pub fn new(client: Client, scope: Scope, metrics: Arc<EdgeMetrics>) -> BusBackend {
|
||||
BusBackend {
|
||||
client,
|
||||
scope,
|
||||
metrics,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bus connection.
|
||||
pub fn client(&self) -> &Client {
|
||||
&self.client
|
||||
}
|
||||
|
||||
/// The service a request goes to: the session's, or the first agent's for the agent-scoped
|
||||
/// families (`:7401` addresses the one live fly; a second fly has no HTTP surface).
|
||||
fn service(&self, family: controlbus::Family) -> String {
|
||||
let agent = self.scope.agent_ids().next().unwrap_or("");
|
||||
self.scope.service(family, agent)
|
||||
}
|
||||
|
||||
/// Carry one request across the bus and wait for its reply, under the edge's deadline.
|
||||
pub async fn call(&self, request: ControlRequest) -> ControlReply {
|
||||
self.metrics.calls.fetch_add(1, Ordering::Relaxed);
|
||||
let deadline = if request.waits_for_a_write() {
|
||||
None
|
||||
} else {
|
||||
Some(COMMAND_TIMEOUT + DEADLINE_MARGIN)
|
||||
};
|
||||
let (family, method, mut payload) = controlbus::encode_request(&request);
|
||||
let service = self.service(family);
|
||||
// A body over the envelope travels as an artifact, so a large request gets the answer
|
||||
// direct mode gives it.
|
||||
let sealed = match controlbus::take_out_of_line_request(&mut payload) {
|
||||
None => None,
|
||||
Some(bytes) => match seal(&self.client, &bytes, "application/json").await {
|
||||
Ok(artifact) => Some(artifact),
|
||||
Err(error) => return self.failed(&error),
|
||||
},
|
||||
};
|
||||
let attachments: Vec<(&str, &flybus::Artifact)> = sealed
|
||||
.iter()
|
||||
.map(|artifact| (controlbus::REQUEST_ARTIFACT, artifact))
|
||||
.collect();
|
||||
let mut pending = match self
|
||||
.client
|
||||
.call(&service, None, method, payload, &attachments)
|
||||
.await
|
||||
{
|
||||
Ok(pending) => pending,
|
||||
Err(error) => return self.failed(&error),
|
||||
};
|
||||
let result = match deadline {
|
||||
None => pending.result().await,
|
||||
Some(deadline) => match tokio::time::timeout(deadline, pending.result()).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
// Cancelled before dispatch, the loop never sees it; dispatched, it may still
|
||||
// act, exactly as a direct request whose caller timed out.
|
||||
let state = pending.cancel().await;
|
||||
self.metrics.cancelled.fetch_add(1, Ordering::Relaxed);
|
||||
tracing::warn!(method, ?state, "a control call passed the edge's deadline");
|
||||
return ControlReply::error(503, unavailable::TIMED_OUT);
|
||||
}
|
||||
},
|
||||
};
|
||||
let result = match result {
|
||||
Ok(result) => result,
|
||||
Err(error) => return self.failed(&error),
|
||||
};
|
||||
let artifact = if controlbus::has_body_artifact(result.outcome()) {
|
||||
match result.artifact(controlbus::BODY_ARTIFACT) {
|
||||
Ok(artifact) => match artifact.read_all().await {
|
||||
Ok(bytes) => Some(bytes),
|
||||
Err(error) => return self.failed(&error),
|
||||
},
|
||||
Err(error) => return self.failed(&error),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match controlbus::decode_reply(result.outcome(), artifact) {
|
||||
Ok(reply) => reply,
|
||||
Err(error) => {
|
||||
self.metrics.call_failures.fetch_add(1, Ordering::Relaxed);
|
||||
tracing::warn!(%error, method, "an undecodable control reply");
|
||||
ControlReply::error(502, format!("the control service answered badly: {error}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(&self, error: &BusError) -> ControlReply {
|
||||
self.metrics.call_failures.fetch_add(1, Ordering::Relaxed);
|
||||
tracing::debug!(%error, "a control call failed on the bus");
|
||||
bus_failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl ControlBackend for BusBackend {
|
||||
fn handle(
|
||||
&self,
|
||||
request: ControlRequest,
|
||||
) -> impl std::future::Future<Output = ControlReply> + Send {
|
||||
let backend = self.clone();
|
||||
async move { backend.call(request).await }
|
||||
}
|
||||
}
|
||||
|
||||
async fn seal(
|
||||
client: &Client,
|
||||
bytes: &[u8],
|
||||
content_type: &str,
|
||||
) -> Result<flybus::Artifact, BusError> {
|
||||
let mut writer = client
|
||||
.artifacts()
|
||||
.allocate(bytes.len() as u64, content_type)
|
||||
.await?;
|
||||
writer
|
||||
.write_all(bytes)
|
||||
.map_err(|error| BusError::new(ErrorCode::StoreFailure, error.to_string()))?;
|
||||
writer.seal().await
|
||||
}
|
||||
|
||||
/// The reply a client gets for a request the bus did not deliver, in the words direct mode uses
|
||||
/// for the same failure.
|
||||
pub fn bus_failure(error: &BusError) -> ControlReply {
|
||||
match error.code {
|
||||
// The service's queue and in-flight slots are full: the direct API's full command queue.
|
||||
ErrorCode::Backpressure => ControlReply::error(503, unavailable::QUEUE_FULL),
|
||||
// Nobody is serving it: before dispatch the loop never saw it, as a closed command queue.
|
||||
ErrorCode::NoService if error.dispatch == Dispatch::NotDispatched => {
|
||||
ControlReply::error(503, unavailable::STOPPED)
|
||||
}
|
||||
ErrorCode::NoService | ErrorCode::CallGone | ErrorCode::RouterLost => {
|
||||
ControlReply::error(503, unavailable::DROPPED)
|
||||
}
|
||||
ErrorCode::NotAuthorized => ControlReply::error(
|
||||
403,
|
||||
format!("not authorized on the control bus: {}", error.message),
|
||||
),
|
||||
code => ControlReply::error(
|
||||
503,
|
||||
format!("the control bus refused the request: {}", code.as_str()),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve until the process is stopped. Only a metrics listener that cannot bind is fatal;
|
||||
/// everything about the bus is retried.
|
||||
pub async fn run(config: EdgeConfig, metrics: Arc<EdgeMetrics>) -> Result<()> {
|
||||
config.scope.validate()?;
|
||||
if let Some(addr) = config.metrics_bind {
|
||||
let listener = tokio::net::TcpListener::bind(addr)
|
||||
.await
|
||||
.with_context(|| format!("binding the edge metrics listener on {addr}"))?;
|
||||
let app = axum::Router::new()
|
||||
.route("/metrics", get(prometheus))
|
||||
.route("/healthz", get(healthz))
|
||||
.with_state(Arc::clone(&metrics));
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = axum::serve(listener, app).await {
|
||||
tracing::error!(%error, "the edge metrics listener stopped");
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut last: Option<&'static str> = None;
|
||||
loop {
|
||||
let end = session(&config, &metrics).await;
|
||||
match &end {
|
||||
SessionEnd::BusLost => {
|
||||
tracing::warn!("the control bus went away; :7401 unbound, reconnecting");
|
||||
}
|
||||
SessionEnd::Unreachable(error) if last != Some(end.kind()) => {
|
||||
tracing::info!(error = format!("{error:#}"), "waiting for the control bus");
|
||||
}
|
||||
SessionEnd::BindFailed(error) if last != Some(end.kind()) => {
|
||||
// The bus is fine; the port is not ours. Most likely flysim is still in direct
|
||||
// mode and holds it (FLY_CONTROL_VIA is not bus), or another process does.
|
||||
tracing::warn!(
|
||||
error = format!("{error:#}"),
|
||||
"the bus is up but the control port cannot be bound; retrying"
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
last = match end {
|
||||
SessionEnd::BusLost => None,
|
||||
other => Some(other.kind()),
|
||||
};
|
||||
tokio::time::sleep(config.retry).await;
|
||||
}
|
||||
}
|
||||
|
||||
enum SessionEnd {
|
||||
Unreachable(anyhow::Error),
|
||||
BindFailed(anyhow::Error),
|
||||
BusLost,
|
||||
}
|
||||
|
||||
impl SessionEnd {
|
||||
fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unreachable(_) => "unreachable",
|
||||
Self::BindFailed(_) => "bind",
|
||||
Self::BusLost => "lost",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn prometheus(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoResponse {
|
||||
(
|
||||
[(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
"text/plain; version=0.0.4",
|
||||
)],
|
||||
metrics.render(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn healthz(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoResponse {
|
||||
if metrics.connected.load(Ordering::Relaxed) == 1 {
|
||||
(StatusCode::OK, "ok")
|
||||
} else {
|
||||
(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"waiting for the control bus",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect as [`controlbus::EDGE`] and wait until the control services answer.
|
||||
pub async fn connect(config: &EdgeConfig, metrics: &Arc<EdgeMetrics>) -> Result<BusBackend> {
|
||||
let client = Client::connect_unix(
|
||||
controlbus::socket_path(&config.bus_dir, Role::Edge),
|
||||
ClientConfig::new(controlbus::EDGE, feedbus::store_root(&config.bus_dir)),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| anyhow!("connecting to the control bus: {error}"))?;
|
||||
let backend = BusBackend::new(client, config.scope.clone(), Arc::clone(metrics));
|
||||
// The host registers its services right after the router starts; until it has, a call is
|
||||
// NO_SERVICE. Bind :7401 only once one is answered, whatever it answers.
|
||||
let (family, method, payload) = controlbus::encode_request(&ControlRequest::Healthz);
|
||||
let service = backend.service(family);
|
||||
for _ in 0..20 {
|
||||
match backend
|
||||
.client
|
||||
.call(&service, None, method, payload.clone(), &[])
|
||||
.await
|
||||
{
|
||||
Ok(mut pending) => match pending.result().await {
|
||||
Ok(_) => return Ok(backend),
|
||||
Err(error) if error.code == ErrorCode::NoService => {}
|
||||
Err(error) => return Err(anyhow!("the control services did not answer: {error}")),
|
||||
},
|
||||
Err(error) if error.code == ErrorCode::NoService => {}
|
||||
Err(error) => return Err(anyhow!("calling the control services: {error}")),
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(anyhow!(
|
||||
"the control services are not registered on the bus"
|
||||
))
|
||||
}
|
||||
|
||||
async fn session(config: &EdgeConfig, metrics: &Arc<EdgeMetrics>) -> SessionEnd {
|
||||
let backend = match connect(config, metrics).await {
|
||||
Ok(backend) => backend,
|
||||
Err(error) => return SessionEnd::Unreachable(error),
|
||||
};
|
||||
let listener = match tokio::net::TcpListener::bind(config.control_bind).await {
|
||||
Ok(listener) => listener,
|
||||
Err(error) => {
|
||||
metrics.bind_failures.fetch_add(1, Ordering::Relaxed);
|
||||
return SessionEnd::BindFailed(anyhow::Error::new(error).context(format!(
|
||||
"binding the control listener on {}",
|
||||
config.control_bind
|
||||
)));
|
||||
}
|
||||
};
|
||||
serve(config, metrics, backend, listener).await;
|
||||
SessionEnd::BusLost
|
||||
}
|
||||
|
||||
/// Serve `listener` until the bus connection closes.
|
||||
async fn serve(
|
||||
config: &EdgeConfig,
|
||||
metrics: &EdgeMetrics,
|
||||
backend: BusBackend,
|
||||
listener: tokio::net::TcpListener,
|
||||
) {
|
||||
tracing::info!(control = %config.control_bind, bus = %config.bus_dir.display(), "serving the control API from the bus");
|
||||
metrics.connected.store(1, Ordering::Relaxed);
|
||||
let client = backend.client.clone();
|
||||
let (stop, stopped) = oneshot::channel::<()>();
|
||||
let server = tokio::spawn(async move {
|
||||
let result = axum::serve(listener, flysim::api::router_with(backend))
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = stopped.await;
|
||||
})
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
tracing::error!(%error, "the control listener stopped");
|
||||
}
|
||||
});
|
||||
while client.closed().is_none() {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
metrics.connected.store(0, Ordering::Relaxed);
|
||||
metrics.bus_lost.fetch_add(1, Ordering::Relaxed);
|
||||
let _ = stop.send(());
|
||||
if tokio::time::timeout(Duration::from_secs(5), server)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("the control listener took more than 5 s to stop");
|
||||
}
|
||||
}
|
||||
81
services/flysim/crates/fly-control-edge/src/main.rs
Normal file
81
services/flysim/crates/fly-control-edge/src/main.rs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
//! `fly-control-edge`: serve the control API (`:7401`) from flysim's control services on the bus.
|
||||
//!
|
||||
//! ```sh
|
||||
//! FLY_CONTROL_VIA=bus flysim-session &
|
||||
//! fly-control-edge
|
||||
//! ```
|
||||
//!
|
||||
//! Configured through the same environment as flysim (`FLY_CONTROL_BIND`, `FLY_BUS_DIR`, or
|
||||
//! `--config flysim.toml`), plus `FLY_CONTROL_EDGE_METRICS_ADDR` for its own `/metrics` and
|
||||
//! `/healthz`. `infra/units/flycontrol-edge.service` runs it with no arguments.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use fly_control_edge::{EdgeConfig, EdgeMetrics};
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
name = "fly-control-edge",
|
||||
about = "The control API, served from flysim's control services on the bus.",
|
||||
version
|
||||
)]
|
||||
struct Args {
|
||||
/// Path to `flysim.toml`, read for `[control]` and `[feed] bus_dir`. Environment overrides
|
||||
/// apply as they do for flysim.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
config: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
init_tracing();
|
||||
let config = flysim::config::Config::load(args.config.as_deref())?;
|
||||
let metrics_bind = match std::env::var("FLY_CONTROL_EDGE_METRICS_ADDR") {
|
||||
Ok(value) if !value.is_empty() => Some(value.parse().with_context(|| {
|
||||
format!("FLY_CONTROL_EDGE_METRICS_ADDR: {value:?} is not a host:port address")
|
||||
})?),
|
||||
_ => None,
|
||||
};
|
||||
let edge = EdgeConfig::from_flysim(&config, metrics_bind);
|
||||
if config.control.via != flysim::config::ControlVia::Bus {
|
||||
tracing::warn!(
|
||||
"FLY_CONTROL_VIA is not \"bus\": flysim serves the control API itself and binds {}; \
|
||||
this edge will wait for control services that are not there",
|
||||
edge.control_bind
|
||||
);
|
||||
}
|
||||
tracing::info!(config = ?edge, "fly-control-edge starting");
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.thread_name("fly-control-edge")
|
||||
.enable_all()
|
||||
.build()
|
||||
.context("building the tokio runtime")?;
|
||||
runtime.block_on(async move {
|
||||
let metrics = Arc::new(EdgeMetrics::default());
|
||||
let mut terminate =
|
||||
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
.context("installing the SIGTERM handler")?;
|
||||
tokio::select! {
|
||||
result = fly_control_edge::run(edge, metrics) => result,
|
||||
_ = tokio::signal::ctrl_c() => { tracing::info!("SIGINT: shutting down"); Ok(()) }
|
||||
_ = terminate.recv() => { tracing::info!("SIGTERM: shutting down"); Ok(()) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Logs to stderr, like flysim, under `FLY_CONTROL_EDGE_LOG` (or `RUST_LOG`).
|
||||
fn init_tracing() {
|
||||
use tracing_subscriber::EnvFilter;
|
||||
let filter = EnvFilter::try_from_env("FLY_CONTROL_EDGE_LOG")
|
||||
.or_else(|_| EnvFilter::try_from_default_env())
|
||||
.unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(filter)
|
||||
.with_writer(std::io::stderr)
|
||||
.with_target(false)
|
||||
.init();
|
||||
}
|
||||
313
services/flysim/crates/fly-control-edge/tests/backpressure.rs
Normal file
313
services/flysim/crates/fly-control-edge/tests/backpressure.rs
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
//! Backpressure, cancellation and the edge's lifecycle.
|
||||
//!
|
||||
//! - a family whose service is full refuses with the direct API's "queue is full" 503, and the
|
||||
//! other families keep answering;
|
||||
//! - a call cancelled before dispatch never reaches the loop; a caller that goes away, or a call
|
||||
//! past the edge's deadline, leaves no call on the router;
|
||||
//! - the edge unbinds `:7401` when the bus goes away and binds it again when a router is back.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use axum::http::{Method, StatusCode};
|
||||
use common::{exchange, rig};
|
||||
use flybus::{CancelState, Client, ClientConfig, Policy, Router, RouterConfig};
|
||||
use flysim::control::{ControlRequest, unavailable};
|
||||
use flysim::controlbus::{self, Family, Role, Scope};
|
||||
use serde_json::json;
|
||||
|
||||
async fn until(what: &str, mut check: impl FnMut() -> bool) {
|
||||
let started = Instant::now();
|
||||
while !check() {
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(30),
|
||||
"timed out waiting for {what}"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_full_service_is_a_503_and_the_other_families_still_answer() {
|
||||
let rig = rig(|_| {}).await;
|
||||
rig.sim.hold.store(true, Ordering::SeqCst);
|
||||
let slots =
|
||||
(controlbus::SERVICE_CONFIG.max_in_flight + controlbus::SERVICE_CONFIG.max_queued) as usize;
|
||||
// The first 16 fill the service's in-flight slots and reach the (wedged) loop; only then
|
||||
// the next 16 fill its queue. (Sent as one burst, the queue bound can be met before the
|
||||
// router has dispatched the first ones: a bounded queue refuses what it cannot hold at that
|
||||
// instant, which is the point, but not what this test counts.)
|
||||
let in_flight = controlbus::SERVICE_CONFIG.max_in_flight as usize;
|
||||
let mut pauses = Vec::new();
|
||||
for batch in [in_flight, slots - in_flight] {
|
||||
for _ in 0..batch {
|
||||
let edge = rig.edge.clone();
|
||||
pauses.push(tokio::spawn(async move {
|
||||
edge.call(ControlRequest::Pause).await
|
||||
}));
|
||||
}
|
||||
until("the in-flight pauses", || rig.sim.received("pause") == in_flight).await;
|
||||
}
|
||||
let started = Instant::now();
|
||||
while (rig.bus.router.stats().calls as usize) < slots {
|
||||
if started.elapsed() > Duration::from_secs(30) {
|
||||
let mut finished = Vec::new();
|
||||
for pause in pauses.iter_mut().filter(|p| p.is_finished()) {
|
||||
finished.push(format!("{:?}", pause.await.unwrap()));
|
||||
}
|
||||
panic!(
|
||||
"not every pause admitted: {:?}, received {}, finished {finished:?}",
|
||||
rig.bus.router.stats(),
|
||||
rig.sim.received("pause")
|
||||
);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
|
||||
// One more is refused at once, in the direct API's words.
|
||||
let started = Instant::now();
|
||||
let refused = exchange(rig.via_edge(), &Method::POST, "/pause", None, &[]).await;
|
||||
assert_eq!(refused.status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(refused.json(), json!({"error": unavailable::QUEUE_FULL}));
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(1),
|
||||
"a full service made the caller wait"
|
||||
);
|
||||
|
||||
// Reads, sugar and chat are other services: they answer while ops is saturated.
|
||||
let status = exchange(rig.via_edge(), &Method::GET, "/status", None, &[]).await;
|
||||
assert_eq!(status.status, StatusCode::OK);
|
||||
let healthz = exchange(rig.via_edge(), &Method::GET, "/healthz", None, &[]).await;
|
||||
assert_eq!(healthz.status, StatusCode::OK);
|
||||
|
||||
// A queued pause cancelled before dispatch never reaches the loop.
|
||||
let operator = Client::connect_unix(
|
||||
controlbus::socket_path(&rig.config.bus_dir, Role::Operator),
|
||||
ClientConfig::new(
|
||||
Role::Operator.participant(),
|
||||
flysim::feedbus::store_root(&rig.config.bus_dir),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// Let the loop go: the held pauses are dropped (503 "dropped"), the queued ones answered.
|
||||
rig.sim.hold.store(false, Ordering::SeqCst);
|
||||
rig.sim.release_held();
|
||||
for pause in pauses {
|
||||
let reply = pause.await.unwrap();
|
||||
// The 16 the wedged loop dropped answer "dropped"; the 16 queued ones were answered.
|
||||
assert!(
|
||||
reply.status == 200 || reply.json_error() == Some(unavailable::DROPPED),
|
||||
"{reply:?}"
|
||||
);
|
||||
}
|
||||
let answered = rig.sim.received("pause");
|
||||
assert_eq!(answered, slots);
|
||||
|
||||
// Wedge it again with 16 of the operator's own in flight; the 17th waits in the queue and
|
||||
// is cancelled there.
|
||||
rig.sim.hold.store(true, Ordering::SeqCst);
|
||||
let (family, method, payload) = controlbus::encode_request(&ControlRequest::Pause);
|
||||
let service = Scope::live().service(family, "");
|
||||
let mut holders = Vec::new();
|
||||
for _ in 0..controlbus::SERVICE_CONFIG.max_in_flight {
|
||||
holders.push(
|
||||
operator
|
||||
.call(&service, None, method, payload.clone(), &[])
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
until("the in-flight pauses", || {
|
||||
rig.sim.received("pause") == slots + controlbus::SERVICE_CONFIG.max_in_flight as usize
|
||||
})
|
||||
.await;
|
||||
let queued = operator
|
||||
.call(&service, None, method, payload.clone(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
queued.cancel().await.unwrap(),
|
||||
CancelState::CancelledBeforeDispatch
|
||||
);
|
||||
rig.sim.hold.store(false, Ordering::SeqCst);
|
||||
rig.sim.release_held();
|
||||
for mut holder in holders {
|
||||
let _ = holder.result().await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(
|
||||
rig.sim.received("pause"),
|
||||
slots + controlbus::SERVICE_CONFIG.max_in_flight as usize,
|
||||
"the cancelled pause reached the loop"
|
||||
);
|
||||
until("no calls left on the router", || {
|
||||
rig.bus.router.stats().calls == 0
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
trait ErrorText {
|
||||
fn json_error(&self) -> Option<&str>;
|
||||
}
|
||||
|
||||
impl ErrorText for flysim::control::ControlReply {
|
||||
fn json_error(&self) -> Option<&str> {
|
||||
match &self.body {
|
||||
flysim::control::ReplyBody::Json(value) => value["error"].as_str(),
|
||||
flysim::control::ReplyBody::Text(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_client_that_goes_away_leaves_no_call_behind() {
|
||||
let rig = rig(|_| {}).await;
|
||||
rig.sim.hold.store(true, Ordering::SeqCst);
|
||||
// An HTTP client that gives up on a pause (which waits for a durable write, so has no
|
||||
// deadline of its own): axum drops the handler, the edge drops the pending call.
|
||||
let gave_up = tokio::time::timeout(
|
||||
Duration::from_millis(300),
|
||||
exchange(rig.via_edge(), &Method::POST, "/pause", None, &[]),
|
||||
)
|
||||
.await;
|
||||
assert!(gave_up.is_err());
|
||||
until("the dropped call to be dispatched", || {
|
||||
rig.sim.received("pause") == 1
|
||||
})
|
||||
.await;
|
||||
// The host still holds it (the loop has it), so the router keeps the correlation until the
|
||||
// host answers; then the detached result is discarded and nothing is left.
|
||||
rig.sim.hold.store(false, Ordering::SeqCst);
|
||||
rig.sim.release_held();
|
||||
until("no calls left on the router", || {
|
||||
rig.bus.router.stats().calls == 0
|
||||
})
|
||||
.await;
|
||||
// And the edge is fine afterwards.
|
||||
let ok = exchange(rig.via_edge(), &Method::POST, "/resume", None, &[]).await;
|
||||
assert_eq!(ok.status, StatusCode::OK);
|
||||
}
|
||||
|
||||
/// A host that registered the services but never answers: the edge gives up at its own deadline,
|
||||
/// cancels, and answers the direct API's timeout 503.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_edge_cancels_at_its_deadline_when_the_host_never_answers() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let scope = Scope::live();
|
||||
let mut config = RouterConfig::new(dir.path());
|
||||
config.policy = controlbus::policy(Policy::closed(), &scope);
|
||||
let router = Router::new(config).unwrap();
|
||||
let silent = Client::connect(
|
||||
router.connect_in_memory_as(controlbus::HOST),
|
||||
ClientConfig::new(controlbus::HOST, router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let name = scope.service(Family::Sugar, controlbus::LIVE_AGENT);
|
||||
let mut service = silent
|
||||
.register(&name, controlbus::SERVICE_CONFIG)
|
||||
.await
|
||||
.unwrap();
|
||||
let held = tokio::spawn(async move {
|
||||
let mut kept = Vec::new();
|
||||
while let Some(request) = service.next().await {
|
||||
kept.push(request);
|
||||
}
|
||||
});
|
||||
let edge_client = Client::connect(
|
||||
router.connect_in_memory_as(controlbus::EDGE),
|
||||
ClientConfig::new(controlbus::EDGE, router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
|
||||
let backend = fly_control_edge::BusBackend::new(edge_client, scope, Arc::clone(&metrics));
|
||||
let started = Instant::now();
|
||||
let reply = exchange(
|
||||
flysim::api::router_with(backend),
|
||||
&Method::POST,
|
||||
"/stimulate",
|
||||
Some("application/json"),
|
||||
&serde_json::to_vec(&json!({"by": "v", "source": "chat"})).unwrap(),
|
||||
)
|
||||
.await;
|
||||
let waited = started.elapsed();
|
||||
assert_eq!(reply.status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(reply.json(), json!({"error": unavailable::TIMED_OUT}));
|
||||
let deadline = flysim::control::COMMAND_TIMEOUT + fly_control_edge::DEADLINE_MARGIN;
|
||||
assert!(
|
||||
waited >= deadline && waited < deadline + Duration::from_secs(2),
|
||||
"{waited:?}"
|
||||
);
|
||||
assert_eq!(metrics.cancelled.load(Ordering::Relaxed), 1);
|
||||
held.abort();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_edge_unbinds_when_the_bus_goes_and_binds_again_when_it_is_back() {
|
||||
let mut rig = rig(|_| {}).await;
|
||||
// The edge process connects as the edge participant, which the router admits once.
|
||||
rig.close_edge().await;
|
||||
let addr = common::free_port();
|
||||
let config = fly_control_edge::EdgeConfig {
|
||||
control_bind: addr,
|
||||
..rig.config.clone()
|
||||
};
|
||||
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
|
||||
let edge = tokio::spawn(fly_control_edge::run(config, Arc::clone(&metrics)));
|
||||
until("the edge to bind", || {
|
||||
metrics.connected.load(Ordering::Relaxed) == 1
|
||||
})
|
||||
.await;
|
||||
let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
|
||||
let served = common::raw_http(addr, request).await.unwrap();
|
||||
assert!(
|
||||
served.starts_with(b"HTTP/1.1 200"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&served)
|
||||
);
|
||||
|
||||
// flysim stops: its router goes, and the port with it.
|
||||
rig.host.take();
|
||||
rig.bus.router.shutdown();
|
||||
until("the edge to notice", || {
|
||||
metrics.bus_lost.load(Ordering::Relaxed) == 1
|
||||
})
|
||||
.await;
|
||||
let started = Instant::now();
|
||||
while common::raw_http(addr, request).await.is_some() {
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
":7401 stayed bound"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
|
||||
// flysim is back: a new router on the same directory, the services registered again.
|
||||
let scope = Scope::live();
|
||||
let uses = flysim::bus::Uses {
|
||||
feed: false,
|
||||
control: true,
|
||||
};
|
||||
let bus = flysim::bus::start(&rig.config.bus_dir, uses, &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
let _host = controlbus::serve(&bus.router, rig.state.clone(), &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
until("the edge to bind again", || {
|
||||
metrics.connected.load(Ordering::Relaxed) == 1
|
||||
})
|
||||
.await;
|
||||
let served = common::raw_http(addr, request).await.unwrap();
|
||||
assert!(
|
||||
served.starts_with(b"HTTP/1.1 200"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&served)
|
||||
);
|
||||
edge.abort();
|
||||
}
|
||||
320
services/flysim/crates/fly-control-edge/tests/common/mod.rs
Normal file
320
services/flysim/crates/fly-control-edge/tests/common/mod.rs
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
#![allow(dead_code)]
|
||||
|
||||
//! A control rig: flysim's control state with a scripted stand-in for the loop behind it, the
|
||||
//! embedded router with the control services registered, and the edge connected over its socket.
|
||||
//! Every request can be sent to both sides — `direct` (flysim's own `:7401` router) and `edge`
|
||||
//! (the same router over the bus) — and the answers compared byte for byte.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{HeaderMap, Method, Request, StatusCode};
|
||||
use fly_control_edge::{BusBackend, EdgeConfig, EdgeMetrics};
|
||||
use flysim::AppState;
|
||||
use flysim::bus::{EmbeddedBus, Uses};
|
||||
use flysim::chat::{ChatRefusal, RejectReason};
|
||||
use flysim::controlbus::{ControlHost, Scope};
|
||||
use flysim::eventlog::{EventLog, EventRing, NewEvent};
|
||||
use flysim::ratelimit::Refusal;
|
||||
use flysim::simloop::{Command, Shared, booting_snapshot};
|
||||
use flysim::snapshot::{FeedEventKind, FeedStatus, MacroMode, Snapshot};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tower::ServiceExt;
|
||||
|
||||
/// The stand-in loop: answers every command deterministically from what the request says, so
|
||||
/// the same request gets the same answer however often (and from whichever side) it is sent.
|
||||
#[derive(Default)]
|
||||
pub struct FakeSim {
|
||||
/// Commands received, by kind.
|
||||
pub received: Mutex<Vec<&'static str>>,
|
||||
/// Hold every command without answering (a wedged loop).
|
||||
pub hold: AtomicBool,
|
||||
/// Answer `/checkpoint` with a failure.
|
||||
pub fail_checkpoint: AtomicBool,
|
||||
/// Held commands: kept so their reply channels stay open.
|
||||
pub held: Mutex<Vec<Command>>,
|
||||
pub answered: AtomicU64,
|
||||
}
|
||||
|
||||
impl FakeSim {
|
||||
pub fn received(&self, kind: &str) -> usize {
|
||||
self.received
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|k| **k == kind)
|
||||
.count()
|
||||
}
|
||||
|
||||
pub fn release_held(&self) {
|
||||
self.held.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
fn answer(&self, command: Command) {
|
||||
let kind = match &command {
|
||||
Command::Stimulate { .. } => "stimulate",
|
||||
Command::Reward { .. } => "reward",
|
||||
Command::Chat { .. } => "chat",
|
||||
Command::Checkpoint { .. } => "checkpoint",
|
||||
Command::Pause { .. } => "pause",
|
||||
Command::Resume { .. } => "resume",
|
||||
Command::Shutdown { .. } => "shutdown",
|
||||
};
|
||||
self.received.lock().unwrap().push(kind);
|
||||
if self.hold.load(Ordering::SeqCst) {
|
||||
self.held.lock().unwrap().push(command);
|
||||
return;
|
||||
}
|
||||
self.answered.fetch_add(1, Ordering::SeqCst);
|
||||
match command {
|
||||
Command::Stimulate { by, reply, .. } => {
|
||||
let answer = match by.as_str() {
|
||||
"pulse" => Err(Refusal::PulseActive {
|
||||
retry_after_ms: 250,
|
||||
}),
|
||||
"spent" => Err(Refusal::RateLimited {
|
||||
retry_after_ms: 41_500,
|
||||
}),
|
||||
"drop" => return,
|
||||
"hang" => {
|
||||
self.held.lock().unwrap().push(Command::Stimulate {
|
||||
duration_ms: None,
|
||||
by,
|
||||
source: String::new(),
|
||||
reply,
|
||||
});
|
||||
return;
|
||||
}
|
||||
_ => Ok(41),
|
||||
};
|
||||
let _ = reply.send(answer);
|
||||
}
|
||||
Command::Reward { reply, .. } => {
|
||||
let _ = reply.send(42);
|
||||
}
|
||||
Command::Chat {
|
||||
by, text, reply, ..
|
||||
} => {
|
||||
let answer = if text.contains("http") {
|
||||
Err(ChatRefusal::Rejected(RejectReason::Url))
|
||||
} else if by == "fast" {
|
||||
Err(ChatRefusal::RateLimited {
|
||||
retry_after_ms: 1_999,
|
||||
})
|
||||
} else {
|
||||
Ok(43)
|
||||
};
|
||||
let _ = reply.send(answer);
|
||||
}
|
||||
Command::Checkpoint { reply } => {
|
||||
let answer = if self.fail_checkpoint.load(Ordering::SeqCst) {
|
||||
Err("disk full".to_owned())
|
||||
} else {
|
||||
Ok(12)
|
||||
};
|
||||
let _ = reply.send(answer);
|
||||
}
|
||||
Command::Pause { reply } => {
|
||||
let _ = reply.send(FeedStatus::Paused);
|
||||
}
|
||||
Command::Resume { reply } => {
|
||||
let _ = reply.send(FeedStatus::Running);
|
||||
}
|
||||
Command::Shutdown { reply } => {
|
||||
let _ = reply.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Rig {
|
||||
pub state: AppState,
|
||||
pub sim: Arc<FakeSim>,
|
||||
pub snapshots: watch::Sender<Arc<Snapshot>>,
|
||||
pub bus: EmbeddedBus,
|
||||
pub host: Option<ControlHost>,
|
||||
pub edge: BusBackend,
|
||||
pub metrics: Arc<EdgeMetrics>,
|
||||
pub config: EdgeConfig,
|
||||
pub dir: tempfile::TempDir,
|
||||
_log: EventLog,
|
||||
}
|
||||
|
||||
/// A snapshot with a few fields that are not the boot defaults, so `/status` has content.
|
||||
fn snapshot() -> Snapshot {
|
||||
let mut snapshot = booting_snapshot(4_242, 1_757_000_000_000, MacroMode::Raw);
|
||||
let header = &mut snapshot.header;
|
||||
header.status = FeedStatus::Running;
|
||||
header.realtime_factor = 1.0312;
|
||||
header.uptime_seconds = 612.5;
|
||||
header.brain_ms = 3_600_250.0;
|
||||
header.frame = 215_089;
|
||||
header.population_rate = 12.375;
|
||||
header.learning.signal = -0.125;
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// The rig, with `configure` applied to flysim's configuration.
|
||||
pub async fn rig(configure: impl FnOnce(&mut flysim::config::Config)) -> Rig {
|
||||
rig_with(
|
||||
configure,
|
||||
Uses {
|
||||
feed: false,
|
||||
control: true,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn rig_with(configure: impl FnOnce(&mut flysim::config::Config), uses: Uses) -> Rig {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut config = flysim::config::Config::default();
|
||||
config.feed.bus_dir = dir.path().join("bus");
|
||||
config.control.via = flysim::config::ControlVia::Bus;
|
||||
configure(&mut config);
|
||||
let shared = Arc::new(Shared::new(config.clone(), EventRing::new()));
|
||||
let (commands, mut command_rx) = mpsc::channel::<Command>(flysim::simloop::COMMAND_QUEUE);
|
||||
let (snapshots, receiver) = watch::channel(Arc::new(snapshot()));
|
||||
let state = AppState {
|
||||
shared: Arc::clone(&shared),
|
||||
commands,
|
||||
snapshots: receiver,
|
||||
};
|
||||
// A short event log, so `/events` has pages to turn.
|
||||
let mut log = EventLog::open(&dir.path().join("events"), state.shared.events.clone()).unwrap();
|
||||
for index in 0..7u64 {
|
||||
log.append(
|
||||
1_000 + index,
|
||||
index as f64 * 0.5,
|
||||
NewEvent::new(FeedEventKind::System, format!("event {index}")).value(index as f64),
|
||||
);
|
||||
}
|
||||
state.shared.beat();
|
||||
|
||||
let sim = Arc::new(FakeSim::default());
|
||||
{
|
||||
let sim = Arc::clone(&sim);
|
||||
tokio::spawn(async move {
|
||||
while let Some(command) = command_rx.recv().await {
|
||||
sim.answer(command);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let scope = Scope::live();
|
||||
let bus = flysim::bus::start(&config.feed.bus_dir, uses, &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
let host = flysim::controlbus::serve(&bus.router, state.clone(), &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
let edge_config = EdgeConfig {
|
||||
retry: Duration::from_millis(50),
|
||||
..EdgeConfig::from_flysim(&config, None)
|
||||
};
|
||||
let metrics = Arc::new(EdgeMetrics::default());
|
||||
let edge = fly_control_edge::connect(&edge_config, &metrics)
|
||||
.await
|
||||
.unwrap();
|
||||
Rig {
|
||||
state,
|
||||
sim,
|
||||
snapshots,
|
||||
bus,
|
||||
host: Some(host),
|
||||
edge,
|
||||
metrics,
|
||||
config: edge_config,
|
||||
dir,
|
||||
_log: log,
|
||||
}
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
pub fn direct(&self) -> axum::Router {
|
||||
flysim::api::router(self.state.clone())
|
||||
}
|
||||
|
||||
/// Close the rig's own edge connection, so an edge process can connect as the edge (the
|
||||
/// router admits one live connection per participant).
|
||||
pub async fn close_edge(&self) {
|
||||
self.edge.client().clone().close().await;
|
||||
}
|
||||
|
||||
pub fn via_edge(&self) -> axum::Router {
|
||||
flysim::api::router_with(self.edge.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// One HTTP exchange as the bytes a client sees: status, every header, body.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Exchange {
|
||||
pub status: StatusCode,
|
||||
pub headers: Vec<(String, Vec<u8>)>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn json(&self) -> serde_json::Value {
|
||||
serde_json::from_slice(&self.body).unwrap_or(serde_json::Value::Null)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn exchange(
|
||||
router: axum::Router,
|
||||
method: &Method,
|
||||
uri: &str,
|
||||
content_type: Option<&str>,
|
||||
body: &[u8],
|
||||
) -> Exchange {
|
||||
let mut request = Request::builder().method(method.clone()).uri(uri);
|
||||
if let Some(content_type) = content_type {
|
||||
request = request.header("content-type", content_type);
|
||||
}
|
||||
let request = request.body(Body::from(body.to_vec())).unwrap();
|
||||
let response = router.oneshot(request).await.unwrap();
|
||||
let status = response.status();
|
||||
let headers = sorted(response.headers());
|
||||
let body = axum::body::to_bytes(response.into_body(), 64 << 20)
|
||||
.await
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
Exchange {
|
||||
status,
|
||||
headers,
|
||||
body,
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted(headers: &HeaderMap) -> Vec<(String, Vec<u8>)> {
|
||||
let mut out: Vec<(String, Vec<u8>)> = headers
|
||||
.iter()
|
||||
.map(|(name, value)| (name.as_str().to_owned(), value.as_bytes().to_vec()))
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// A free loopback port (bound, read, released).
|
||||
pub fn free_port() -> std::net::SocketAddr {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.local_addr().unwrap()
|
||||
}
|
||||
|
||||
/// A raw HTTP/1.1 exchange over TCP: the whole response, with the `date` header line removed
|
||||
/// (the one header that differs from second to second). `None` when nothing listens.
|
||||
pub async fn raw_http(addr: std::net::SocketAddr, request: &str) -> Option<Vec<u8>> {
|
||||
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
|
||||
let mut stream = tokio::net::TcpStream::connect(addr).await.ok()?;
|
||||
stream.write_all(request.as_bytes()).await.ok()?;
|
||||
let mut out = Vec::new();
|
||||
stream.read_to_end(&mut out).await.ok()?;
|
||||
let text = String::from_utf8_lossy(&out).into_owned();
|
||||
let kept: Vec<&str> = text
|
||||
.split("\r\n")
|
||||
.filter(|line| !line.to_ascii_lowercase().starts_with("date:"))
|
||||
.collect();
|
||||
Some(kept.join("\r\n").into_bytes())
|
||||
}
|
||||
388
services/flysim/crates/fly-control-edge/tests/grants.rs
Normal file
388
services/flysim/crates/fly-control-edge/tests/grants.rs
Normal file
|
|
@ -0,0 +1,388 @@
|
|||
//! The grant table refuses what it should, over the router's real sockets.
|
||||
//!
|
||||
//! - each native role calls exactly its families, and a refused call never reaches the loop;
|
||||
//! - no role can register a service (so none can stand in for the control host), publish,
|
||||
//! subscribe or manage a topic;
|
||||
//! - a socket is bound to its role: claiming another identity on it is refused at hello;
|
||||
//! - on a router shared with a service that does take input (an environment's, say), no control
|
||||
//! participant can call it: "nothing can press buttons" holds for the grant table, not only for
|
||||
//! the list of control methods;
|
||||
//! - per-agent scoping: a player may sugar their own fly and not another.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use axum::http::{Method, StatusCode};
|
||||
use common::{exchange, rig, rig_with};
|
||||
use flybus::{
|
||||
BusError, Client, ClientConfig, Dispatch, ErrorCode, Grants, Pattern, Policy, Retained, Router,
|
||||
RouterConfig, ServiceConfig,
|
||||
};
|
||||
use flysim::bus::Uses;
|
||||
use flysim::control::ControlRequest;
|
||||
use flysim::controlbus::{self, Family, Role, Scope};
|
||||
use serde_json::{Map, json};
|
||||
|
||||
fn request_of(family: Family) -> ControlRequest {
|
||||
match family {
|
||||
Family::Read | Family::Status => ControlRequest::Status,
|
||||
Family::Sugar => ControlRequest::Stimulate {
|
||||
body: Some(json!({"by": "viewer", "source": "points"})),
|
||||
},
|
||||
Family::Reward => ControlRequest::Reward {
|
||||
body: Some(json!({"value": 1.0, "by": "op", "source": "operator"})),
|
||||
},
|
||||
Family::Chat => ControlRequest::Chat {
|
||||
body: Some(json!({"by": "viewer", "text": "hi"})),
|
||||
},
|
||||
Family::Ops => ControlRequest::Resume,
|
||||
}
|
||||
}
|
||||
|
||||
async fn call(
|
||||
client: &Client,
|
||||
scope: &Scope,
|
||||
family: Family,
|
||||
agent: &str,
|
||||
) -> Result<Map<String, serde_json::Value>, BusError> {
|
||||
let (encoded_family, method, payload) = controlbus::encode_request(&request_of(family));
|
||||
// An agent's status service answers the same method the session's read does.
|
||||
if family != Family::Status {
|
||||
assert_eq!(encoded_family, family);
|
||||
}
|
||||
let service = scope.service(family, agent);
|
||||
let result = client
|
||||
.call_and_wait(&service, None, method, payload, &[])
|
||||
.await?;
|
||||
Ok(result.outcome().clone())
|
||||
}
|
||||
|
||||
fn assert_refused(result: Result<impl std::fmt::Debug, BusError>, what: &str) {
|
||||
let error = result.expect_err(what);
|
||||
assert_eq!(error.code, ErrorCode::NotAuthorized, "{what}: {error}");
|
||||
assert_eq!(error.dispatch, Dispatch::NotDispatched, "{what}");
|
||||
}
|
||||
|
||||
async fn connect_role(
|
||||
bus_dir: &std::path::Path,
|
||||
role: Role,
|
||||
claimed: &str,
|
||||
) -> Result<Client, BusError> {
|
||||
Client::connect_unix(
|
||||
controlbus::socket_path(bus_dir, role),
|
||||
ClientConfig::new(claimed, flysim::feedbus::store_root(bus_dir)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn each_role_calls_exactly_its_families_and_nothing_else() {
|
||||
let rig = rig_with(
|
||||
|_| {},
|
||||
Uses {
|
||||
feed: true,
|
||||
control: true,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
rig.close_edge().await;
|
||||
let bus_dir = rig.config.bus_dir.clone();
|
||||
let scope = Scope::live();
|
||||
for role in Role::ALL {
|
||||
let client = connect_role(&bus_dir, role, role.participant())
|
||||
.await
|
||||
.unwrap();
|
||||
for family in Family::ALL {
|
||||
let before = rig.sim.received.lock().unwrap().len();
|
||||
let result = call(&client, &scope, family, controlbus::LIVE_AGENT).await;
|
||||
if role.families().contains(&family) {
|
||||
let outcome = result.unwrap_or_else(|e| panic!("{role:?} {family:?}: {e}"));
|
||||
assert!(outcome["status"].as_u64().is_some(), "{role:?} {family:?}");
|
||||
} else {
|
||||
assert_refused(result, &format!("{role:?} {family:?}"));
|
||||
assert_eq!(
|
||||
rig.sim.received.lock().unwrap().len(),
|
||||
before,
|
||||
"{role:?} {family:?}: a refused call reached the loop"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Nobody but the in-process host may register anything, a control name least of all.
|
||||
for name in [
|
||||
scope.service(Family::Ops, ""),
|
||||
scope.service(Family::Sugar, controlbus::LIVE_AGENT),
|
||||
"fly.control.s.main.buttons".to_owned(),
|
||||
"anything".to_owned(),
|
||||
] {
|
||||
assert_refused(
|
||||
client
|
||||
.register(&name, ServiceConfig::default())
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} registering {name}"),
|
||||
);
|
||||
}
|
||||
// No topics: not the feed, not a new one.
|
||||
assert_refused(
|
||||
client
|
||||
.subscribe(flysim::feedbus::TOPIC, flybus::SubscriptionConfig::latest())
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} subscribing to the feed"),
|
||||
);
|
||||
assert_refused(
|
||||
client
|
||||
.declare_topic("fly.control.events", Retained::None)
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} declaring a topic"),
|
||||
);
|
||||
assert_refused(
|
||||
client
|
||||
.publish(flysim::feedbus::TOPIC, Map::new(), &[])
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} publishing on the feed"),
|
||||
);
|
||||
client.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_socket_admits_only_its_own_role() {
|
||||
let rig = rig(|_| {}).await;
|
||||
let bus_dir = rig.config.bus_dir.clone();
|
||||
for (socket, claimed) in [
|
||||
(Role::Stage, Role::Operator.participant()),
|
||||
(Role::Bridge, controlbus::HOST),
|
||||
(Role::Watchdog, controlbus::EDGE),
|
||||
(Role::Edge, Role::Operator.participant()),
|
||||
] {
|
||||
let result = connect_role(&bus_dir, socket, claimed).await;
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"{claimed} was admitted on {socket:?}'s socket"
|
||||
);
|
||||
}
|
||||
// No socket is bound to the host.
|
||||
assert!(
|
||||
!bus_dir.join("control").join("flysim-control.sock").exists()
|
||||
&& std::fs::read_dir(bus_dir.join("control")).unwrap().count() == Role::NATIVE.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn on_a_shared_router_no_control_participant_can_reach_an_input_service() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let scope = Scope::live();
|
||||
// An environment that takes input lives on the same router as the control services.
|
||||
let input = "fly.env.s.main.input";
|
||||
let policy = controlbus::policy(
|
||||
Policy::closed().client(
|
||||
"env",
|
||||
Grants {
|
||||
register: vec![Pattern::exact(input)],
|
||||
..Grants::default()
|
||||
},
|
||||
),
|
||||
&scope,
|
||||
);
|
||||
let mut config = RouterConfig::new(dir.path());
|
||||
config.policy = policy;
|
||||
let router = Router::new(config).unwrap();
|
||||
let env = Client::connect(
|
||||
router.connect_in_memory_as("env"),
|
||||
ClientConfig::new("env", router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut service = env.register(input, ServiceConfig::default()).await.unwrap();
|
||||
let pressed = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
{
|
||||
let pressed = Arc::clone(&pressed);
|
||||
tokio::spawn(async move {
|
||||
while let Some(request) = service.next().await {
|
||||
pressed.fetch_add(1, Ordering::SeqCst);
|
||||
let _ = request.reply(Map::new(), &[]).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
for role in Role::ALL {
|
||||
let client = Client::connect(
|
||||
router.connect_in_memory_as(role.participant()),
|
||||
ClientConfig::new(role.participant(), router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for method in ["Environment.Step", "Control.Stimulate", "Press"] {
|
||||
let mut payload = Map::new();
|
||||
payload.insert("buttons".into(), json!(1));
|
||||
assert_refused(
|
||||
client
|
||||
.call(input, None, method, payload, &[])
|
||||
.await
|
||||
.map(|_| ()),
|
||||
&format!("{role:?} calling {input} {method}"),
|
||||
);
|
||||
}
|
||||
client.close().await;
|
||||
}
|
||||
assert_eq!(pressed.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_player_sugars_their_own_fly_and_no_other() {
|
||||
// Two flies on two controller ports; one player backs the fly on port 1 and another is
|
||||
// granted by id. Single-fly is the same table with one agent.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let scope = Scope {
|
||||
session: "arena".to_owned(),
|
||||
agents: vec![
|
||||
controlbus::AgentScope::new("fly-a", Some(1)),
|
||||
controlbus::AgentScope::new("fly-b", Some(2)),
|
||||
],
|
||||
};
|
||||
let policy = controlbus::policy(Policy::closed(), &scope)
|
||||
.client(
|
||||
"player-a",
|
||||
controlbus::player_grants(&scope, controlbus::Agents::Port(1)),
|
||||
)
|
||||
.client(
|
||||
"player-b",
|
||||
controlbus::player_grants(&scope, controlbus::Agents::Id("fly-b")),
|
||||
);
|
||||
let mut config = RouterConfig::new(dir.path());
|
||||
config.policy = policy;
|
||||
let router = Router::new(config).unwrap();
|
||||
let rig = rig(|_| {}).await;
|
||||
let _host = controlbus::serve(&router, rig.state.clone(), &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
let player = Client::connect(
|
||||
router.connect_in_memory_as("player-a"),
|
||||
ClientConfig::new("player-a", router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let other = Client::connect(
|
||||
router.connect_in_memory_as("player-b"),
|
||||
ClientConfig::new("player-b", router.store_root()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
call(&other, &scope, Family::Sugar, "fly-b").await.unwrap()["status"],
|
||||
json!(202)
|
||||
);
|
||||
assert_refused(
|
||||
call(&other, &scope, Family::Sugar, "fly-a").await,
|
||||
"player-b sugar on fly-a",
|
||||
);
|
||||
assert_eq!(
|
||||
call(&player, &scope, Family::Status, "fly-a").await.unwrap()["status"],
|
||||
json!(200)
|
||||
);
|
||||
assert_refused(
|
||||
call(&player, &scope, Family::Status, "fly-b").await,
|
||||
"status of fly-b",
|
||||
);
|
||||
let outcome = call(&player, &scope, Family::Sugar, "fly-a").await.unwrap();
|
||||
assert_eq!(outcome["status"], json!(202));
|
||||
assert_eq!(outcome["body"], json!({"eventId": 41}));
|
||||
assert_eq!(
|
||||
call(&player, &scope, Family::Read, "").await.unwrap()["status"],
|
||||
json!(200)
|
||||
);
|
||||
assert_refused(
|
||||
call(&player, &scope, Family::Sugar, "fly-b").await,
|
||||
"sugar on fly-b",
|
||||
);
|
||||
assert_refused(
|
||||
call(&player, &scope, Family::Reward, "fly-a").await,
|
||||
"reward on fly-a",
|
||||
);
|
||||
assert_refused(call(&player, &scope, Family::Chat, "").await, "chat");
|
||||
assert_refused(call(&player, &scope, Family::Ops, "").await, "ops");
|
||||
// The live session's names are not the arena's.
|
||||
assert_refused(
|
||||
call(&player, &Scope::live(), Family::Read, "").await,
|
||||
"another session's read",
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_method_the_service_does_not_have_is_a_404_and_reaches_nothing() {
|
||||
let rig = rig(|_| {}).await;
|
||||
let operator = connect_role(
|
||||
&rig.config.bus_dir,
|
||||
Role::Operator,
|
||||
Role::Operator.participant(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let scope = Scope::live();
|
||||
for (family, method) in [
|
||||
(Family::Read, "Control.Pause"),
|
||||
(Family::Sugar, "Control.Press"),
|
||||
(Family::Ops, "Control.Buttons"),
|
||||
(Family::Chat, "Control.Stimulate"),
|
||||
] {
|
||||
let result = operator
|
||||
.call_and_wait(
|
||||
&scope.service(family, controlbus::LIVE_AGENT),
|
||||
None,
|
||||
method,
|
||||
Map::new(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
result.outcome()["status"],
|
||||
json!(404),
|
||||
"{family:?} {method}"
|
||||
);
|
||||
}
|
||||
assert!(rig.sim.received.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// An HTTP edge holding a narrower role answers what the role may not do with a 403, and the
|
||||
/// loop never sees it.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn an_edge_on_a_narrow_role_refuses_over_http() {
|
||||
let rig = rig(|_| {}).await;
|
||||
let stage = connect_role(&rig.config.bus_dir, Role::Stage, Role::Stage.participant())
|
||||
.await
|
||||
.unwrap();
|
||||
let backend = fly_control_edge::BusBackend::new(stage, Scope::live(), Arc::clone(&rig.metrics));
|
||||
let router = || flysim::api::router_with(backend.clone());
|
||||
let ok = exchange(router(), &Method::GET, "/healthz", None, &[]).await;
|
||||
assert_eq!(ok.status, StatusCode::OK);
|
||||
for (uri, body) in [
|
||||
("/stimulate", json!({"by": "v", "source": "chat"})),
|
||||
("/chat", json!({"by": "v", "text": "hi"})),
|
||||
("/pause", json!({})),
|
||||
("/checkpoint", json!({})),
|
||||
] {
|
||||
let refused = exchange(
|
||||
router(),
|
||||
&Method::POST,
|
||||
uri,
|
||||
Some("application/json"),
|
||||
&serde_json::to_vec(&body).unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(refused.status, StatusCode::FORBIDDEN, "{uri}");
|
||||
assert!(
|
||||
refused.json()["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("not authorized on the control bus"),
|
||||
"{uri}"
|
||||
);
|
||||
}
|
||||
assert!(rig.sim.received.lock().unwrap().is_empty());
|
||||
}
|
||||
402
services/flysim/crates/fly-control-edge/tests/parity.rs
Normal file
402
services/flysim/crates/fly-control-edge/tests/parity.rs
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
//! Every `docs/control-api.md` endpoint through the edge equals direct, byte for byte.
|
||||
//!
|
||||
//! Each case is sent twice, to flysim's own `:7401` router (`control.via = direct`) and to the
|
||||
//! same router over the bus (`fly-control-edge`'s [`BusBackend`]), and the status, every header
|
||||
//! and the body bytes must be equal. The stand-in loop answers each command from what the request
|
||||
//! says, so both sends get the same answer. The last test does it over real TCP sockets against
|
||||
//! the running edge, where the whole HTTP response must be equal but for its `date` line.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::http::{Method, StatusCode};
|
||||
use common::{exchange, rig};
|
||||
use serde_json::json;
|
||||
|
||||
/// `(method, uri, content type, body)`.
|
||||
type Case = (Method, &'static str, Option<&'static str>, Vec<u8>);
|
||||
|
||||
fn json_case(method: Method, uri: &'static str, body: serde_json::Value) -> Case {
|
||||
(
|
||||
method,
|
||||
uri,
|
||||
Some("application/json"),
|
||||
serde_json::to_vec(&body).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn bare(method: Method, uri: &'static str) -> Case {
|
||||
(method, uri, None, Vec::new())
|
||||
}
|
||||
|
||||
fn raw(method: Method, uri: &'static str, body: &str) -> Case {
|
||||
(
|
||||
method,
|
||||
uri,
|
||||
Some("application/json"),
|
||||
body.as_bytes().to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The cases every configuration runs: each endpoint, its validation and its refusals.
|
||||
fn cases() -> Vec<Case> {
|
||||
use Method as M;
|
||||
vec![
|
||||
bare(M::GET, "/status"),
|
||||
bare(M::GET, "/status.json"),
|
||||
bare(M::GET, "/healthz"),
|
||||
bare(M::GET, "/metrics"),
|
||||
// /events: the page, its parameters and the lenient defaults.
|
||||
bare(M::GET, "/events"),
|
||||
bare(M::GET, "/events?since=3"),
|
||||
bare(M::GET, "/events?since=0&limit=2"),
|
||||
bare(M::GET, "/events?since=99"),
|
||||
bare(M::GET, "/events?since=abc&limit=abc"),
|
||||
bare(M::GET, "/events?since=&limit="),
|
||||
bare(M::GET, "/events?limit=0"),
|
||||
bare(M::GET, "/events?since=-1&limit=100000"),
|
||||
bare(M::GET, "/events?since=1&since=2"),
|
||||
bare(M::GET, "/events?unknown=1"),
|
||||
// /stimulate: accepted, both refusals, every malformed shape.
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "points"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "chat", "durationMs": 300}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "op", "source": "operator", "durationMs": null}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "pulse", "source": "points"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "spent", "source": "chat"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "bridge"}),
|
||||
),
|
||||
json_case(M::POST, "/stimulate", json!({"by": "viewer"})),
|
||||
json_case(M::POST, "/stimulate", json!({"source": "points"})),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "points", "durationMs": -5}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "viewer", "source": "points", "durationMs": "400"}),
|
||||
),
|
||||
json_case(M::POST, "/stimulate", json!([1, 2, 3])),
|
||||
raw(M::POST, "/stimulate", "{not json"),
|
||||
raw(M::POST, "/stimulate", "\"a string\""),
|
||||
bare(M::POST, "/stimulate"),
|
||||
(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
Some("text/plain"),
|
||||
b"{\"by\":\"v\",\"source\":\"chat\"}".to_vec(),
|
||||
),
|
||||
(M::POST, "/stimulate", None, vec![0xff, 0xfe, 0x00]),
|
||||
// The loop dropped the request: the 503 both sides answer.
|
||||
json_case(
|
||||
M::POST,
|
||||
"/stimulate",
|
||||
json!({"by": "drop", "source": "chat"}),
|
||||
),
|
||||
// /reward: 403 unless enabled; its validation once it is.
|
||||
json_case(
|
||||
M::POST,
|
||||
"/reward",
|
||||
json!({"value": 0.5, "by": "op", "source": "operator"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/reward",
|
||||
json!({"value": "x", "by": "op", "source": "operator"}),
|
||||
),
|
||||
bare(M::POST, "/reward"),
|
||||
// /chat: accepted, both refusals, the body rules.
|
||||
json_case(
|
||||
M::POST,
|
||||
"/chat",
|
||||
json!({"by": "viewer_two", "text": "go fly go"}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/chat",
|
||||
json!({"by": "bot", "text": "hello", "bot": true}),
|
||||
),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/chat",
|
||||
json!({"by": "viewer", "text": "see http://x.example"}),
|
||||
),
|
||||
json_case(M::POST, "/chat", json!({"by": "fast", "text": "again"})),
|
||||
json_case(
|
||||
M::POST,
|
||||
"/chat",
|
||||
json!({"by": "viewer", "text": "hi", "bot": "yes"}),
|
||||
),
|
||||
json_case(M::POST, "/chat", json!({"by": "viewer"})),
|
||||
json_case(M::POST, "/chat", json!({"text": 5})),
|
||||
raw(M::POST, "/chat", "]"),
|
||||
bare(M::POST, "/chat"),
|
||||
// /checkpoint, /pause, /resume.
|
||||
bare(M::POST, "/checkpoint"),
|
||||
bare(M::POST, "/pause"),
|
||||
bare(M::POST, "/resume"),
|
||||
json_case(M::POST, "/pause", json!({"ignored": true})),
|
||||
// Everything that is not a route is the same 404, the wrong method on a route included.
|
||||
bare(M::GET, "/stimulate"),
|
||||
bare(M::POST, "/status"),
|
||||
bare(M::PUT, "/pause"),
|
||||
bare(M::DELETE, "/checkpoint"),
|
||||
json_case(M::POST, "/button", json!({"button": "a"})),
|
||||
bare(M::GET, "/joypad"),
|
||||
bare(M::POST, "/memory"),
|
||||
bare(M::GET, "/"),
|
||||
bare(M::GET, "/status/"),
|
||||
]
|
||||
}
|
||||
|
||||
async fn compare_all(
|
||||
configure: impl FnOnce(&mut flysim::config::Config),
|
||||
cases: &[Case],
|
||||
) -> Vec<(String, StatusCode)> {
|
||||
let rig = rig(configure).await;
|
||||
let mut seen = Vec::new();
|
||||
for (method, uri, content_type, body) in cases {
|
||||
let direct = exchange(rig.direct(), method, uri, *content_type, body).await;
|
||||
let edge = exchange(rig.via_edge(), method, uri, *content_type, body).await;
|
||||
assert_eq!(
|
||||
direct,
|
||||
edge,
|
||||
"{method} {uri}: direct {} {:?} vs edge {} {:?}",
|
||||
direct.status,
|
||||
String::from_utf8_lossy(&direct.body),
|
||||
edge.status,
|
||||
String::from_utf8_lossy(&edge.body)
|
||||
);
|
||||
seen.push((format!("{method} {uri}"), direct.status));
|
||||
}
|
||||
assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0);
|
||||
seen
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn every_endpoint_through_the_edge_equals_direct() {
|
||||
let seen = compare_all(|_| {}, &cases()).await;
|
||||
// The cases reach every status code control-api.md names, so the comparison is not of
|
||||
// twenty identical 200s.
|
||||
let codes: std::collections::BTreeSet<u16> = seen.iter().map(|(_, s)| s.as_u16()).collect();
|
||||
for code in [200, 202, 400, 403, 404, 422, 429, 503] {
|
||||
assert!(codes.contains(&code), "no case answered {code}: {seen:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn with_reward_enabled_and_chat_disabled_too() {
|
||||
let seen = compare_all(
|
||||
|config| {
|
||||
config.control.allow_reward = true;
|
||||
config.chat.enabled = false;
|
||||
},
|
||||
&cases(),
|
||||
)
|
||||
.await;
|
||||
let status = |what: &str| seen.iter().find(|(w, _)| w == what).unwrap().1;
|
||||
assert_eq!(status("POST /chat"), StatusCode::FORBIDDEN);
|
||||
assert_eq!(status("POST /reward"), StatusCode::ACCEPTED);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_failed_checkpoint_an_unhealthy_loop_and_a_timeout_match_too() {
|
||||
let rig = rig(|_| {}).await;
|
||||
rig.sim.fail_checkpoint.store(true, Ordering::SeqCst);
|
||||
for (method, uri, body) in [
|
||||
(Method::POST, "/checkpoint", Vec::new()),
|
||||
// The loop takes the command but never answers: both sides wait COMMAND_TIMEOUT and 503.
|
||||
(
|
||||
Method::POST,
|
||||
"/stimulate",
|
||||
serde_json::to_vec(&json!({"by": "hang", "source": "chat"})).unwrap(),
|
||||
),
|
||||
] {
|
||||
let direct = exchange(rig.direct(), &method, uri, Some("application/json"), &body).await;
|
||||
let edge = exchange(
|
||||
rig.via_edge(),
|
||||
&method,
|
||||
uri,
|
||||
Some("application/json"),
|
||||
&body,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(direct, edge, "{method} {uri}");
|
||||
assert!(
|
||||
direct.status.is_server_error(),
|
||||
"{method} {uri}: {}",
|
||||
direct.status
|
||||
);
|
||||
}
|
||||
// A loop that has not advanced for 2 s.
|
||||
tokio::time::sleep(Duration::from_millis(2_100)).await;
|
||||
let direct = exchange(rig.direct(), &Method::GET, "/healthz", None, &[]).await;
|
||||
let edge = exchange(rig.via_edge(), &Method::GET, "/healthz", None, &[]).await;
|
||||
assert_eq!(direct, edge);
|
||||
assert_eq!(direct.status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_large_events_page_rides_as_an_artifact_and_still_matches() {
|
||||
let rig = rig(|_| {}).await;
|
||||
// Enough events that the page is far over one envelope.
|
||||
let mut log = flysim::eventlog::EventLog::open(
|
||||
&rig.dir.path().join("more-events"),
|
||||
rig.state.shared.events.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
for index in 0..2_000u64 {
|
||||
log.append(
|
||||
2_000 + index,
|
||||
index as f64,
|
||||
flysim::eventlog::NewEvent::new(
|
||||
flysim::snapshot::FeedEventKind::Reward,
|
||||
format!("a reasonably long reward label number {index}"),
|
||||
)
|
||||
.value(0.25),
|
||||
);
|
||||
}
|
||||
let uri = "/events?since=0&limit=4096";
|
||||
let direct = exchange(rig.direct(), &Method::GET, uri, None, &[]).await;
|
||||
let edge = exchange(rig.via_edge(), &Method::GET, uri, None, &[]).await;
|
||||
assert!(
|
||||
direct.body.len() > flysim::controlbus::INLINE_MAX,
|
||||
"{} bytes",
|
||||
direct.body.len()
|
||||
);
|
||||
assert_eq!(direct, edge);
|
||||
// The artifact is released once read.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(rig.bus.router.stats().artifacts, 0);
|
||||
}
|
||||
|
||||
/// A request body over flybus's 65,536-byte envelope (N2): the edge carries it as an artifact and
|
||||
/// the answer is the one direct mode gives, whatever it is, for every body endpoint.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_request_body_over_the_envelope_gets_directs_answer() {
|
||||
let rig = rig(|_| {}).await;
|
||||
let mut cases = Vec::new();
|
||||
for size in [49_000usize, 70_000, 300_000] {
|
||||
let text = "x".repeat(size);
|
||||
for uri in ["/chat", "/stimulate", "/reward"] {
|
||||
cases.push(json_case(
|
||||
Method::POST,
|
||||
uri,
|
||||
json!({"by": "viewer", "source": "points", "text": text, "message": text, "reason": text}),
|
||||
));
|
||||
}
|
||||
}
|
||||
// Over the limit and not JSON at all: direct's 400 either way.
|
||||
cases.push(raw(Method::POST, "/chat", &"{".repeat(100_000)));
|
||||
let mut codes = Vec::new();
|
||||
for (method, uri, content_type, body) in &cases {
|
||||
let direct = exchange(rig.direct(), method, uri, *content_type, body).await;
|
||||
let edge = exchange(rig.via_edge(), method, uri, *content_type, body).await;
|
||||
assert_eq!(
|
||||
direct,
|
||||
edge,
|
||||
"{method} {uri} ({} bytes): direct {} {:?} vs edge {} {:?}",
|
||||
body.len(),
|
||||
direct.status,
|
||||
String::from_utf8_lossy(&direct.body),
|
||||
edge.status,
|
||||
String::from_utf8_lossy(&edge.body)
|
||||
);
|
||||
assert!(
|
||||
!String::from_utf8_lossy(&edge.body).contains("INVALID_ENVELOPE"),
|
||||
"{uri}: {:?}",
|
||||
String::from_utf8_lossy(&edge.body)
|
||||
);
|
||||
codes.push(direct.status.as_u16());
|
||||
}
|
||||
eprintln!("large-body statuses: {codes:?}");
|
||||
assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0);
|
||||
// Every request artifact was released once read.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(rig.bus.router.stats().artifacts, 0);
|
||||
}
|
||||
|
||||
/// The running edge over real sockets: the whole HTTP/1.1 response equals flysim's own listener's,
|
||||
/// `date` aside, for a request of every kind.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn over_tcp_the_edge_answers_the_same_bytes_as_flysim() {
|
||||
let rig = rig(|_| {}).await;
|
||||
rig.close_edge().await;
|
||||
// flysim's own listener, as direct mode binds it.
|
||||
let direct_addr = common::free_port();
|
||||
let listener = tokio::net::TcpListener::bind(direct_addr).await.unwrap();
|
||||
let router = rig.direct();
|
||||
tokio::spawn(async move { axum::serve(listener, router).await });
|
||||
// The edge process's loop, on another port.
|
||||
let edge_addr = common::free_port();
|
||||
let config = fly_control_edge::EdgeConfig {
|
||||
control_bind: edge_addr,
|
||||
..rig.config.clone()
|
||||
};
|
||||
let metrics = std::sync::Arc::new(fly_control_edge::EdgeMetrics::default());
|
||||
let edge = tokio::spawn(fly_control_edge::run(
|
||||
config,
|
||||
std::sync::Arc::clone(&metrics),
|
||||
));
|
||||
let mut waited = 0;
|
||||
while metrics.connected.load(Ordering::Relaxed) == 0 {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
waited += 1;
|
||||
assert!(waited < 250, "the edge never bound");
|
||||
}
|
||||
let body = r#"{"by":"viewer","source":"points","durationMs":300}"#;
|
||||
let chat = r#"{"by":"viewer","text":"see http://x.example"}"#;
|
||||
for request in [
|
||||
"GET /status HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"GET /metrics HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"GET /events?since=2&limit=3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
format!(
|
||||
"POST /stimulate HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
),
|
||||
format!(
|
||||
"POST /chat HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{chat}",
|
||||
chat.len()
|
||||
),
|
||||
"POST /pause HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"POST /reward HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
"GET /buttons HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
] {
|
||||
let direct = common::raw_http(direct_addr, &request).await.unwrap();
|
||||
let via_edge = common::raw_http(edge_addr, &request).await.unwrap();
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&direct),
|
||||
String::from_utf8_lossy(&via_edge),
|
||||
"{request}"
|
||||
);
|
||||
assert!(direct.starts_with(b"HTTP/1.1 "), "{}", String::from_utf8_lossy(&direct));
|
||||
}
|
||||
edge.abort();
|
||||
}
|
||||
90
services/flysim/crates/fly-control-edge/tests/serve.rs
Normal file
90
services/flysim/crates/fly-control-edge/tests/serve.rs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
//! `flysim::serve` with `control.via = bus`: flysim leaves the control port alone, registers the
|
||||
//! control services on its embedded router, and the edge process serves the port from them.
|
||||
//! This is the wiring both runtimes share (`flysim` and `flysim-session` both run `serve`).
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use flysim::config::{Config, ControlVia};
|
||||
use flysim::simloop::Command;
|
||||
use flysim::snapshot::FeedStatus;
|
||||
|
||||
#[test]
|
||||
fn serve_in_control_bus_mode_leaves_the_port_to_the_edge() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut config = Config::default();
|
||||
config.feed.bind = common::free_port();
|
||||
config.control.bind = common::free_port();
|
||||
config.control.via = ControlVia::Bus;
|
||||
config.feed.bus_dir = dir.path().join("bus");
|
||||
let control_bind = config.control.bind;
|
||||
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let serving = {
|
||||
let config = config.clone();
|
||||
let stop = Arc::clone(&stop);
|
||||
std::thread::spawn(move || {
|
||||
flysim::serve(
|
||||
config,
|
||||
move |shared, _snapshots, mut commands, _notifier| {
|
||||
// A stand-in loop: beats, answers pauses, stops when told.
|
||||
while !stop.load(Ordering::SeqCst) {
|
||||
shared.beat();
|
||||
while let Ok(command) = commands.try_recv() {
|
||||
if let Command::Pause { reply } = command {
|
||||
let _ = reply.send(FeedStatus::Paused);
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
runtime.block_on(async {
|
||||
let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
|
||||
// The router's sockets appear; flysim never binds the control port.
|
||||
let started = Instant::now();
|
||||
while !dir.path().join("bus/control-edge.sock").exists() {
|
||||
assert!(started.elapsed() < Duration::from_secs(20), "no control socket");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(common::raw_http(control_bind, request).await.is_none(), "flysim bound :7401");
|
||||
for role in ["stage", "bridge", "watchdog", "operator"] {
|
||||
assert!(dir.path().join(format!("bus/control/{role}.sock")).exists(), "{role}");
|
||||
}
|
||||
// The feed is still direct: no feed socket.
|
||||
assert!(!dir.path().join("bus/edge.sock").exists());
|
||||
|
||||
let edge_config = fly_control_edge::EdgeConfig::from_flysim(&config, None);
|
||||
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
|
||||
let edge = tokio::spawn(fly_control_edge::run(edge_config, Arc::clone(&metrics)));
|
||||
let started = Instant::now();
|
||||
while metrics.connected.load(Ordering::Relaxed) == 0 {
|
||||
assert!(started.elapsed() < Duration::from_secs(20), "the edge never bound");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
let health = common::raw_http(control_bind, request).await.unwrap();
|
||||
assert!(health.starts_with(b"HTTP/1.1 200"), "{}", String::from_utf8_lossy(&health));
|
||||
let pause = "POST /pause HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
|
||||
let paused = String::from_utf8(common::raw_http(control_bind, pause).await.unwrap()).unwrap();
|
||||
assert!(paused.starts_with("HTTP/1.1 200"), "{paused}");
|
||||
assert!(paused.ends_with("{\"status\":\"paused\"}"), "{paused}");
|
||||
|
||||
// flysim stops: the edge lets go of the port.
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
let started = Instant::now();
|
||||
while common::raw_http(control_bind, request).await.is_some() {
|
||||
assert!(started.elapsed() < Duration::from_secs(20), ":7401 stayed bound");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
edge.abort();
|
||||
});
|
||||
serving.join().unwrap().unwrap();
|
||||
}
|
||||
|
|
@ -42,6 +42,8 @@ tracing = "0.1"
|
|||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# CTRL-01: the service contracts with the control API on the bus (`tests/service_parity.rs`).
|
||||
fly-control-edge = { path = "../fly-control-edge" }
|
||||
tempfile = "3"
|
||||
axum = "0.8"
|
||||
futures-util = "0.3"
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@
|
|||
//! | `--out DIR` | `$FLY_SHADOW_DIR`: `verdict.json`, `divergence.json` |
|
||||
//! | `--spool DIR` | `<out>/spool` |
|
||||
//! | `--work DIR` | `$FLY_SHADOW_WORK`, else `<out>/work`: sockets and artifact stores |
|
||||
//! | `--mode in-process\|thread\|process` | `in-process` |
|
||||
//! | `--mode local\|bus/in-process\|bus/thread\|bus/process` | `$FLY_SHADOW_MODE`, else `local` (in-process over the local lane); `in-process`, `thread`, `process` and `bus` are accepted (BUS-01) |
|
||||
//! | `--threads N` | `$FLY_SHADOW_THREADS`, else 2: the shadow agent's sweep threads |
|
||||
//! | `--required-brain-seconds S` | 10800 |
|
||||
//! | `--lag-guard-margin S` | 0.05 s/s; the shadow pauses 60 s while the live `fly_lag_seconds` grows faster than `fly-shadow-run`'s baseline rate (`<out>/baseline.json`) plus this margin (the baseline's own margin wins), and stops pausing for 10 minutes when a pause did not help (0 disables) |
|
||||
|
|
@ -46,7 +46,9 @@
|
|||
//! and writes nothing outside DIR; N bounds the mirrored saves (3072).
|
||||
//!
|
||||
//! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING]
|
||||
//! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current`
|
||||
//! [--max-age-seconds N] [--require-arm ARM]`: the cutover rule of
|
||||
//! `fly_legacy_session::shadow::verdict`, and with `--require-arm` (BUS-01: `bus/process`, ...) also
|
||||
//! that the shadow ran that topology. `--current`
|
||||
//! is the release link CUT-01 switches into (default `/opt/fly/current`): the verdict must be for
|
||||
//! the directory it resolves to, with every shadowed binary unchanged there. `--binary` is the
|
||||
//! file name of the session-runtime binary CUT-01 switches to (default `flysim-session`,
|
||||
|
|
@ -160,6 +162,8 @@ fn main() {
|
|||
.unwrap_or_else(|| "flysim-session".to_owned());
|
||||
let compatibility = args.value("--compatibility");
|
||||
let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300);
|
||||
// BUS-01: the topology the cutover goes into, which the shadow must have run.
|
||||
let require_arm = args.value("--require-arm");
|
||||
args.done();
|
||||
let compatibility = compatibility.unwrap_or_else(|| {
|
||||
let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(e));
|
||||
|
|
@ -179,7 +183,12 @@ fn main() {
|
|||
dir: &dir_text,
|
||||
binaries: &binaries,
|
||||
};
|
||||
match verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age) {
|
||||
let allowed = verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age)
|
||||
.and_then(|()| match &require_arm {
|
||||
Some(arm) => verdict::ran_arm(&value, arm),
|
||||
None => Ok(()),
|
||||
});
|
||||
match allowed {
|
||||
Ok(()) => println!("cutover allowed: {}", value["reason"]),
|
||||
Err(reason) => {
|
||||
println!("cutover refused: {reason}");
|
||||
|
|
@ -212,12 +221,18 @@ fn run(mut args: Args) {
|
|||
.map(PathBuf::from)
|
||||
.or_else(|| env_path("FLY_SHADOW_WORK"))
|
||||
.unwrap_or_else(|| out_dir.join("work"));
|
||||
let mode = match args.value("--mode").as_deref() {
|
||||
None | Some("in-process") => ExecutionMode::InProcess,
|
||||
Some("thread") => ExecutionMode::Thread,
|
||||
Some("process") => ExecutionMode::Process,
|
||||
Some(other) => die(format!("--mode {other:?}")),
|
||||
};
|
||||
// BUS-01: `--mode` (else `FLY_SHADOW_MODE`, which the remote relay forwards to the box) names
|
||||
// the topology: `local` (= `in-process`, the default), `bus/in-process`, `bus/thread`,
|
||||
// `bus/process` (= `bus`, = `process`), `thread`.
|
||||
let arm = args
|
||||
.value("--mode")
|
||||
.or_else(|| std::env::var("FLY_SHADOW_MODE").ok().filter(|v| !v.is_empty()))
|
||||
.map(|value| {
|
||||
fly_legacy_session::composition::SessionArm::parse(&value)
|
||||
.unwrap_or_else(|e| die(format!("--mode / FLY_SHADOW_MODE: {e}")))
|
||||
})
|
||||
.unwrap_or(fly_legacy_session::composition::SessionArm::LOCAL);
|
||||
let mode: ExecutionMode = arm.mode;
|
||||
let agent_threads: usize = args.parsed("--threads").unwrap_or_else(|| {
|
||||
std::env::var("FLY_SHADOW_THREADS")
|
||||
.ok()
|
||||
|
|
@ -292,6 +307,7 @@ fn run(mut args: Args) {
|
|||
macro_mode: config.macros.mode,
|
||||
speed: config.loop_.speed,
|
||||
mode,
|
||||
transport: arm.transport,
|
||||
agent_threads,
|
||||
required_brain_seconds: required,
|
||||
all_files,
|
||||
|
|
@ -309,7 +325,8 @@ fn run(mut args: Args) {
|
|||
run_id_file,
|
||||
};
|
||||
eprintln!(
|
||||
"fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)",
|
||||
"fly-shadow: {} ({} mode), {} threads, following {} (stores {} and {}, read only)",
|
||||
arm.label(),
|
||||
mode.label(),
|
||||
agent_threads,
|
||||
shadow_config.trace_dir.display(),
|
||||
|
|
|
|||
|
|
@ -7,10 +7,11 @@
|
|||
//!
|
||||
//! It reads exactly `flysim`'s configuration (`/etc/fly/fly.env` through the unit, or
|
||||
//! `--config flysim.toml`), writes the same checkpoint stores, event log, sugar journal and chat
|
||||
//! sidecar, and serves the same feed, control API and metrics. Three variables are its own:
|
||||
//! sidecar, and serves the same feed, control API and metrics. These variables are its own:
|
||||
//! `FLY_SESSION_DIR` (the session's router store and sockets, default `/run/fly/session`),
|
||||
//! `FLY_SESSION_MODE` (`in-process`, `thread` or `process`) and `FLY_SESSION_PROFILE`
|
||||
//! (`production`, or `toy` for tests).
|
||||
//! `FLY_SESSION_TRANSPORT` (`local`, the default, or `bus`; `--transport`), `FLY_SESSION_MODE`
|
||||
//! (`in-process`, `thread` or `process`; `process` by default on the bus), `FLY_SESSION_PIN`,
|
||||
//! `FLY_SESSION_AUX_CPUS` and `FLY_SESSION_PROFILE` (`production`, or `toy` for tests).
|
||||
//!
|
||||
//! The one-shot flags are `flysim`'s: `--check-config`, `--print-compatibility` (the session's
|
||||
//! own string, which must equal `flysim`'s), `--print-state-compatibility` and
|
||||
|
|
@ -48,6 +49,12 @@ struct Args {
|
|||
/// service stopped; `flysim --reset-to-milestone`, the same store).
|
||||
#[arg(long, value_name = "RANK")]
|
||||
reset_to_milestone: Option<u32>,
|
||||
|
||||
/// `local` (in-process over the local lane) or `bus` (every participant a socket client of
|
||||
/// the session's router, one process each unless `FLY_SESSION_MODE` says otherwise).
|
||||
/// Overrides `FLY_SESSION_TRANSPORT`.
|
||||
#[arg(long, value_name = "local|bus")]
|
||||
transport: Option<String>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
|
|
@ -55,7 +62,8 @@ fn main() -> Result<()> {
|
|||
init_tracing();
|
||||
|
||||
let config = Config::load(args.config.as_deref())?;
|
||||
let options = fly_legacy_session::service::ServiceOptions::from_env()?;
|
||||
let options =
|
||||
fly_legacy_session::service::ServiceOptions::from_env_with(args.transport.as_deref())?;
|
||||
tracing::info!(config = ?config, options = ?options, "resolved configuration");
|
||||
if args.check_config {
|
||||
println!("{}", toml::to_string_pretty(&config)?);
|
||||
|
|
|
|||
|
|
@ -14,8 +14,8 @@ use fly_session::coordinator::{AgentSlot, Coordinator, StepDetails, StepReport};
|
|||
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
|
||||
use fly_session::fly_session_types::gameboy;
|
||||
use fly_session::launcher::{
|
||||
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT,
|
||||
ThreadBudget, Via,
|
||||
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, ProcessCpus,
|
||||
SUPERVISOR_CLIENT, ThreadBudget, Via,
|
||||
};
|
||||
use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT};
|
||||
use fly_session::legacy_env::BackendConfig;
|
||||
|
|
@ -54,12 +54,152 @@ const COORDINATOR_CLIENT: &str = "coordinator";
|
|||
const ENV_CLIENT: &str = "legacy-world";
|
||||
const ENV_SERVICE: &str = "env.world";
|
||||
const ENV_WORKER: &str = "world";
|
||||
/// The environment's worker id, which [`LegacyConfig::placements`] names it by.
|
||||
pub const WORLD_WORKER: &str = ENV_WORKER;
|
||||
const AGENT_CLIENT: &str = "legacy-fly";
|
||||
|
||||
/// How the session's participants reach each other (BUS-01).
|
||||
///
|
||||
/// - `Local`: in-process participants are called over the local lane (PERF-01): no bus message
|
||||
/// and no store file per call. Only [`ExecutionMode::InProcess`] has a lane.
|
||||
/// - `Bus`: every participant is a client of the session's router over a Unix-domain socket,
|
||||
/// launcher-bound to its identity, with its artifacts in the router's store: the topology that
|
||||
/// takes more flies and more worlds by configuration. In-process, thread and process modes all
|
||||
/// run it; thread and process modes have no other transport.
|
||||
///
|
||||
/// Neither changes a result, a trace or a checkpoint: the transport carries the same domain calls
|
||||
/// to the same endpoints (`legacy-gameboy-v1` section 12, amendment 2026-10-01 BUS-01).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Transport {
|
||||
#[default]
|
||||
Local,
|
||||
Bus,
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Transport::Local => "local",
|
||||
Transport::Bus => "bus",
|
||||
}
|
||||
}
|
||||
|
||||
/// `local` or `bus`.
|
||||
pub fn parse(value: &str) -> Result<Transport, String> {
|
||||
match value {
|
||||
"local" => Ok(Transport::Local),
|
||||
"bus" => Ok(Transport::Bus),
|
||||
other => Err(format!("transport {other:?}: local or bus")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The launcher transport for a mode: the lane only in process and only when asked for (and
|
||||
/// not turned off by `FLY_SESSION_LOCAL_LANE=0`, which keeps an in-memory bus); Unix sockets
|
||||
/// for the bus, and always for a thread or a process.
|
||||
pub fn via(&self, mode: ExecutionMode) -> Via {
|
||||
match (self, mode) {
|
||||
(Transport::Local, ExecutionMode::InProcess) if local_lane_enabled() => Via::Local,
|
||||
(Transport::Local, ExecutionMode::InProcess) => Via::Memory,
|
||||
_ => Via::Unix,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One way to run the composition: where the participants run and how they are reached.
|
||||
/// `local` (in-process over the lane, the release default until the bus cutover), `bus/in-process`,
|
||||
/// `bus/thread` and `bus/process`. Parity runs and measurements name them this way
|
||||
/// (`FLY_PARITY_ARMS`, `FLY_PERF_ARMS`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct SessionArm {
|
||||
pub mode: ExecutionMode,
|
||||
pub transport: Transport,
|
||||
}
|
||||
|
||||
impl SessionArm {
|
||||
pub const LOCAL: SessionArm = SessionArm {
|
||||
mode: ExecutionMode::InProcess,
|
||||
transport: Transport::Local,
|
||||
};
|
||||
pub const BUS_IN_PROCESS: SessionArm = SessionArm {
|
||||
mode: ExecutionMode::InProcess,
|
||||
transport: Transport::Bus,
|
||||
};
|
||||
pub const BUS_THREAD: SessionArm = SessionArm {
|
||||
mode: ExecutionMode::Thread,
|
||||
transport: Transport::Bus,
|
||||
};
|
||||
pub const BUS_PROCESS: SessionArm = SessionArm {
|
||||
mode: ExecutionMode::Process,
|
||||
transport: Transport::Bus,
|
||||
};
|
||||
|
||||
pub fn label(&self) -> String {
|
||||
match self.transport {
|
||||
Transport::Local => "local".to_owned(),
|
||||
Transport::Bus => format!("bus/{}", self.mode.label()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `local`, `bus` (= `bus/process`), `bus/in-process`, `bus/thread`, `bus/process`; also the
|
||||
/// bare mode names `in-process` (= local), `thread` and `process` (= the bus).
|
||||
pub fn parse(value: &str) -> Result<SessionArm, String> {
|
||||
Ok(match value.trim() {
|
||||
"local" | "in-process" => SessionArm::LOCAL,
|
||||
"bus/in-process" => SessionArm::BUS_IN_PROCESS,
|
||||
"bus/thread" | "thread" => SessionArm::BUS_THREAD,
|
||||
"bus" | "bus/process" | "process" => SessionArm::BUS_PROCESS,
|
||||
other => {
|
||||
return Err(format!(
|
||||
"{other:?}: local, bus/in-process, bus/thread or bus/process"
|
||||
));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The arms a parity run compares with the legacy loop: `FLY_PARITY_ARMS` (a list of
|
||||
/// [`SessionArm::parse`] names), else `local`, `bus/thread` and `bus/process`. Process mode
|
||||
/// needs the workspace's `fly-session` binary; a build without it skips that arm and says so.
|
||||
pub fn parity_arms() -> Vec<SessionArm> {
|
||||
let arms = match std::env::var("FLY_PARITY_ARMS") {
|
||||
Ok(list) if !list.trim().is_empty() => SessionArm::parse_list(&list)
|
||||
.unwrap_or_else(|e| panic!("FLY_PARITY_ARMS: {e}")),
|
||||
_ => vec![SessionArm::LOCAL, SessionArm::BUS_THREAD, SessionArm::BUS_PROCESS],
|
||||
};
|
||||
let program = fly_session::launcher::default_worker_program();
|
||||
arms.into_iter()
|
||||
.filter(|arm| {
|
||||
let runnable = arm.mode != ExecutionMode::Process || program.is_file();
|
||||
if !runnable {
|
||||
eprintln!(
|
||||
"{} skipped: no worker program at {}",
|
||||
arm.label(),
|
||||
program.display()
|
||||
);
|
||||
}
|
||||
runnable
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A comma-separated list of [`SessionArm::parse`] names.
|
||||
pub fn parse_list(value: &str) -> Result<Vec<SessionArm>, String> {
|
||||
value
|
||||
.split(',')
|
||||
.filter(|part| !part.trim().is_empty())
|
||||
.map(SessionArm::parse)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// How one legacy session is composed.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LegacyConfig {
|
||||
pub mode: ExecutionMode,
|
||||
/// The transport in-process participants use; thread and process modes always use the bus.
|
||||
pub transport: Transport,
|
||||
/// Process mode: where each participant process's threads run, by worker id (the agent's
|
||||
/// id, [`WORLD_WORKER`]). Empty: they float (BUS-01).
|
||||
pub placements: BTreeMap<Id, ProcessCpus>,
|
||||
pub rom_path: PathBuf,
|
||||
pub dataset_dir: PathBuf,
|
||||
pub profile: LegacyProfileKind,
|
||||
|
|
@ -337,11 +477,11 @@ impl LegacySession {
|
|||
let mut launcher = Launcher::start(
|
||||
router,
|
||||
config.mode,
|
||||
// In-process participants reach the router in memory: no socket between two tasks
|
||||
// of one process (a separate process always uses the socket). They are called over
|
||||
// the local lane: the same worker shell, no bus message and no store file per
|
||||
// artifact (PERF-01, `workers-v1` amendment).
|
||||
if local_lane_enabled() { Via::Local } else { Via::Memory },
|
||||
// `Transport::Local`: in-process participants are called over the local lane: the same
|
||||
// worker shell, no bus message and no store file per artifact (PERF-01, `workers-v1`
|
||||
// amendment). `Transport::Bus`: every participant is a socket client of the router,
|
||||
// whatever its mode (BUS-01); a thread or a separate process always is.
|
||||
config.transport.via(config.mode),
|
||||
&store_root,
|
||||
&sockets,
|
||||
budget,
|
||||
|
|
@ -349,6 +489,9 @@ impl LegacySession {
|
|||
.await
|
||||
.map_err(|e| format!("launcher: {}", e.message))?;
|
||||
|
||||
for (worker, cpus) in &config.placements {
|
||||
launcher.place_process(worker, cpus.clone());
|
||||
}
|
||||
let mut backend = BackendConfig::legacy(&rom_digest);
|
||||
backend.slots = vec![id(crate::task::SLOT)];
|
||||
launcher
|
||||
|
|
|
|||
|
|
@ -35,8 +35,10 @@ use serde_json::Value;
|
|||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
|
||||
use fly_session::fly_session_types::gameboy;
|
||||
use fly_session::launcher::ExecutionMode;
|
||||
use fly_session::legacy_agent::{LegacyProfileKind, METHOD_FEED_STATUS, SPIKES_ATTACHMENT};
|
||||
use fly_session::launcher::{ExecutionMode, ProcessCpus};
|
||||
use fly_session::legacy_agent::{
|
||||
FEED_STATUS_ATTACHMENT, LegacyProfileKind, METHOD_FEED_STATUS, SPIKES_ATTACHMENT,
|
||||
};
|
||||
use fly_session::legacy_checkpoint::{RankChange, SaveKind, SaveReport, SaveTicket};
|
||||
use fly_session::types::*;
|
||||
use flybrain_gb::adapter::GameAdapter;
|
||||
|
|
@ -56,9 +58,14 @@ use flysim::snapshot::{
|
|||
PROTOCOL, RewardKind, Snapshot, f32_bytes, finite,
|
||||
};
|
||||
|
||||
use crate::composition::{Boot, LegacyConfig, LegacySession, StoreConfig, boot_unsaved};
|
||||
use crate::composition::{
|
||||
Boot, LegacyConfig, LegacySession, StoreConfig, Transport, boot_unsaved,
|
||||
};
|
||||
use crate::task::GAME;
|
||||
|
||||
/// The service's one agent.
|
||||
const AGENT_ID: &str = "fly";
|
||||
|
||||
/// The runtime name the sugar journal's boot header records.
|
||||
pub const RUNTIME: &str = "fly-session";
|
||||
|
||||
|
|
@ -67,30 +74,83 @@ pub const SESSION_DIR_ENV: &str = "FLY_SESSION_DIR";
|
|||
pub const DEFAULT_SESSION_DIR: &str = "/run/fly/session";
|
||||
/// `in-process` (the default), `thread` or `process` (`fly-session`'s launcher modes).
|
||||
pub const SESSION_MODE_ENV: &str = "FLY_SESSION_MODE";
|
||||
/// `local` (the default: in-process over the local lane) or `bus` (every participant a socket
|
||||
/// client of the session's router; the mode defaults to `process`). BUS-01.
|
||||
pub const SESSION_TRANSPORT_ENV: &str = "FLY_SESSION_TRANSPORT";
|
||||
/// `production` (the default, `gameboy-legacy-fafb-v783-v1`) or `toy` (tests only).
|
||||
pub const SESSION_PROFILE_ENV: &str = "FLY_SESSION_PROFILE";
|
||||
|
||||
/// `0` keeps every thread floating over the cpuset; anything else, or unset, places them
|
||||
/// ([`place_threads`]).
|
||||
pub const SESSION_PIN_ENV: &str = "FLY_SESSION_PIN";
|
||||
/// Process mode: a CPU list for the service process (router, coordinator, listeners, checkpoint
|
||||
/// writer) and the environment process, instead of the sweep's host CPU (BUS-01). It must lie in
|
||||
/// the unit's cpuset (on the containers, `flysim.slice`'s AllowedCPUs).
|
||||
pub const SESSION_AUX_CPUS_ENV: &str = "FLY_SESSION_AUX_CPUS";
|
||||
|
||||
/// How the service composes its session, beyond flysim's own [`Config`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ServiceOptions {
|
||||
pub mode: ExecutionMode,
|
||||
pub transport: Transport,
|
||||
pub profile: LegacyProfileKind,
|
||||
pub session_dir: PathBuf,
|
||||
/// Process mode: each participant process's CPUs, by worker id ([`place_threads`]).
|
||||
pub placements: std::collections::BTreeMap<Id, ProcessCpus>,
|
||||
}
|
||||
|
||||
/// The mode and transport from their two settings: `FLY_SESSION_TRANSPORT` (or `--transport`)
|
||||
/// and `FLY_SESSION_MODE`. Unset, the transport follows the mode (thread and process modes have
|
||||
/// only the bus) and the mode follows the transport (`bus` runs one process per participant).
|
||||
/// `local` with a thread or a process is refused: those have no local lane.
|
||||
pub fn mode_and_transport(
|
||||
mode: Option<&str>,
|
||||
transport: Option<&str>,
|
||||
) -> Result<(ExecutionMode, Transport)> {
|
||||
let mode = match mode.filter(|v| !v.is_empty()) {
|
||||
None => None,
|
||||
Some("in-process") => Some(ExecutionMode::InProcess),
|
||||
Some("thread") => Some(ExecutionMode::Thread),
|
||||
Some("process") => Some(ExecutionMode::Process),
|
||||
Some(other) => bail!("{SESSION_MODE_ENV}={other}: in-process, thread or process"),
|
||||
};
|
||||
let transport = match transport.filter(|v| !v.is_empty()) {
|
||||
None => None,
|
||||
Some(value) => {
|
||||
Some(Transport::parse(value).map_err(|e| anyhow!("{SESSION_TRANSPORT_ENV}: {e}"))?)
|
||||
}
|
||||
};
|
||||
Ok(match (mode, transport) {
|
||||
(None, None) | (None, Some(Transport::Local)) => {
|
||||
(ExecutionMode::InProcess, Transport::Local)
|
||||
}
|
||||
(None, Some(Transport::Bus)) => (ExecutionMode::Process, Transport::Bus),
|
||||
(Some(ExecutionMode::InProcess), transport) => {
|
||||
(ExecutionMode::InProcess, transport.unwrap_or(Transport::Local))
|
||||
}
|
||||
(Some(mode), None | Some(Transport::Bus)) => (mode, Transport::Bus),
|
||||
(Some(mode), Some(Transport::Local)) => bail!(
|
||||
"{SESSION_MODE_ENV}={} has no local lane: its participants reach the router over \
|
||||
sockets ({SESSION_TRANSPORT_ENV}=bus, or unset)",
|
||||
mode.label()
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
impl ServiceOptions {
|
||||
/// From `FLY_SESSION_MODE`, `FLY_SESSION_PROFILE` and `FLY_SESSION_DIR`.
|
||||
/// From `FLY_SESSION_MODE`, `FLY_SESSION_TRANSPORT`, `FLY_SESSION_PROFILE` and
|
||||
/// `FLY_SESSION_DIR`.
|
||||
pub fn from_env() -> Result<ServiceOptions> {
|
||||
let mode = match std::env::var(SESSION_MODE_ENV).ok().as_deref() {
|
||||
None | Some("") | Some("in-process") => ExecutionMode::InProcess,
|
||||
Some("thread") => ExecutionMode::Thread,
|
||||
Some("process") => ExecutionMode::Process,
|
||||
Some(other) => bail!("{SESSION_MODE_ENV}={other}: in-process, thread or process"),
|
||||
};
|
||||
Self::from_env_with(None)
|
||||
}
|
||||
|
||||
/// [`ServiceOptions::from_env`], with `--transport` in place of `FLY_SESSION_TRANSPORT`.
|
||||
pub fn from_env_with(transport: Option<&str>) -> Result<ServiceOptions> {
|
||||
let env_transport = std::env::var(SESSION_TRANSPORT_ENV).ok();
|
||||
let (mode, transport) = mode_and_transport(
|
||||
std::env::var(SESSION_MODE_ENV).ok().as_deref(),
|
||||
transport.or(env_transport.as_deref()),
|
||||
)?;
|
||||
let profile = match std::env::var(SESSION_PROFILE_ENV).ok().as_deref() {
|
||||
None | Some("") | Some("production") => LegacyProfileKind::Production,
|
||||
Some("toy") => LegacyProfileKind::Toy,
|
||||
|
|
@ -101,8 +161,10 @@ impl ServiceOptions {
|
|||
.unwrap_or_else(|| PathBuf::from(DEFAULT_SESSION_DIR));
|
||||
Ok(ServiceOptions {
|
||||
mode,
|
||||
transport,
|
||||
profile,
|
||||
session_dir,
|
||||
placements: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -134,11 +196,13 @@ pub fn legacy_config(config: &Config, options: &ServiceOptions) -> Result<Legacy
|
|||
}
|
||||
Ok(LegacyConfig {
|
||||
mode: options.mode,
|
||||
transport: options.transport,
|
||||
placements: options.placements.clone(),
|
||||
rom_path: config.paths.rom.clone(),
|
||||
dataset_dir: config.paths.dataset.clone(),
|
||||
profile: options.profile,
|
||||
macro_mode: config.macros.mode,
|
||||
agent_id: id("fly"),
|
||||
agent_id: id(AGENT_ID),
|
||||
agent_threads: config.loop_.threads.max(1),
|
||||
record: false,
|
||||
})
|
||||
|
|
@ -179,7 +243,7 @@ pub fn service_config(mut config: Config) -> Config {
|
|||
}
|
||||
|
||||
/// Run the service until a signal or a fatal error: [`flysim::serve`] around a [`SessionHost`].
|
||||
pub fn run(config: Config, options: ServiceOptions) -> Result<()> {
|
||||
pub fn run(config: Config, mut options: ServiceOptions) -> Result<()> {
|
||||
let config = service_config(config);
|
||||
// Refuse a configuration the session cannot run before any listener is bound.
|
||||
legacy_config(&config, &options)?;
|
||||
|
|
@ -191,7 +255,19 @@ pub fn run(config: Config, options: ServiceOptions) -> Result<()> {
|
|||
tracing::warn!("{variable} is set, but {what} is a legacy-loop tool; ignored");
|
||||
}
|
||||
}
|
||||
place_threads(&config, &options);
|
||||
place_threads(&config, &mut options);
|
||||
tracing::info!(
|
||||
transport = options.transport.label(),
|
||||
mode = options.mode.label(),
|
||||
"session participants: {}",
|
||||
match (options.transport, options.mode) {
|
||||
(Transport::Local, _) => "in process, over the local lane",
|
||||
(Transport::Bus, ExecutionMode::InProcess) => "in process, socket clients of the router",
|
||||
(Transport::Bus, ExecutionMode::Thread) => "on threads, socket clients of the router",
|
||||
(Transport::Bus, ExecutionMode::Process) =>
|
||||
"one process each, socket clients of the router",
|
||||
}
|
||||
);
|
||||
flysim::serve(config, move |shared, snapshots, commands, notifier| {
|
||||
run_host(shared, snapshots, commands, notifier, &options)
|
||||
})
|
||||
|
|
@ -202,20 +278,79 @@ pub fn run(config: Config, options: ServiceOptions) -> Result<()> {
|
|||
/// writer), before any of them is spawned. The legacy loop's four busy threads keep their CPUs by
|
||||
/// themselves; the session's host threads sleep and wake around every transition, and without
|
||||
/// this the sweep workers' wake-ups often land two on one CPU (`flybrain_core::pool::
|
||||
/// place_workers`). In-process and thread modes only: a worker process would inherit the host's
|
||||
/// mask without the plan. Placement changes no result, trace or checkpoint.
|
||||
fn place_threads(config: &Config, options: &ServiceOptions) {
|
||||
/// place_workers`). Placement changes no result, trace or checkpoint.
|
||||
///
|
||||
/// In-process and thread modes place this process's own threads. Process mode (BUS-01) makes the
|
||||
/// same split of this process's cpuset and hands it out: the agent process gets the sweep CPUs
|
||||
/// and the host CPU (`--sweep-cpus`, `--host-cpus`), and this process -- the router, the
|
||||
/// coordinator, the listeners -- and the environment process run on the host CPU too, or on
|
||||
/// `FLY_SESSION_AUX_CPUS` when it is set. The transaction is serial (nothing overlaps Prepare,
|
||||
/// PERF-01), so they share that CPU with the agent's dispatcher without contending.
|
||||
fn place_threads(config: &Config, options: &mut ServiceOptions) {
|
||||
if std::env::var(SESSION_PIN_ENV).ok().as_deref() == Some("0") {
|
||||
tracing::info!("{SESSION_PIN_ENV}=0: the threads float over the cpuset");
|
||||
return;
|
||||
}
|
||||
if !matches!(
|
||||
options.mode,
|
||||
ExecutionMode::InProcess | ExecutionMode::Thread
|
||||
) {
|
||||
let workers = config.loop_.threads;
|
||||
if options.mode == ExecutionMode::Process {
|
||||
let plan = flybrain_core::pool::allowed_cpus()
|
||||
.and_then(|allowed| flybrain_core::pool::split_cpus(&allowed, workers));
|
||||
let Some(plan) = plan else {
|
||||
tracing::info!(
|
||||
workers,
|
||||
"threads not placed (fewer cpus than sweep threads): every process floats"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let aux = match std::env::var(SESSION_AUX_CPUS_ENV).ok().filter(|v| !v.is_empty()) {
|
||||
None => plan.host.clone(),
|
||||
Some(value) => match flybrain_core::pool::parse_cpu_list(&value) {
|
||||
Some(cpus) => cpus,
|
||||
None => {
|
||||
tracing::warn!("{SESSION_AUX_CPUS_ENV}={value:?} is not a cpu list; ignored");
|
||||
plan.host.clone()
|
||||
}
|
||||
},
|
||||
};
|
||||
let aux = if flybrain_core::pool::confine_current(&aux) {
|
||||
aux
|
||||
} else {
|
||||
tracing::warn!(?aux, "could not confine the service to these cpus; using the host cpus");
|
||||
if !flybrain_core::pool::confine_current(&plan.host) {
|
||||
tracing::warn!("could not confine the service at all: every process floats");
|
||||
return;
|
||||
}
|
||||
let workers = config.loop_.threads;
|
||||
plan.host.clone()
|
||||
};
|
||||
// The agent's own host threads (its dispatcher is sweep worker 0) keep the plan's host
|
||||
// cpus, less any the service and the world were moved onto.
|
||||
let agent_host: Vec<usize> = plan.host.iter().copied().filter(|c| !aux.contains(c)).collect();
|
||||
options.placements.insert(
|
||||
id(AGENT_ID),
|
||||
ProcessCpus {
|
||||
host: if agent_host.is_empty() { plan.host.clone() } else { agent_host },
|
||||
sweep: plan.workers.clone(),
|
||||
},
|
||||
);
|
||||
options.placements.insert(
|
||||
id(crate::composition::WORLD_WORKER),
|
||||
ProcessCpus {
|
||||
host: aux.clone(),
|
||||
sweep: Vec::new(),
|
||||
},
|
||||
);
|
||||
tracing::info!(
|
||||
sweep_workers = ?plan.workers,
|
||||
agent_host = ?plan.host,
|
||||
service_and_world = ?aux,
|
||||
"process mode: the agent's sweep workers pinned one per cpu; the service, the router \
|
||||
and the world on the rest"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if std::env::var_os(SESSION_AUX_CPUS_ENV).is_some() {
|
||||
tracing::warn!("{SESSION_AUX_CPUS_ENV} is for process mode; ignored");
|
||||
}
|
||||
match flybrain_core::pool::place_workers(workers) {
|
||||
Some(placement) => tracing::info!(
|
||||
sweep_workers = ?placement.workers,
|
||||
|
|
@ -402,6 +537,12 @@ pub struct SessionHost {
|
|||
spikes: Vec<u8>,
|
||||
/// The agent's feed status as last read, for a publish whose read failed.
|
||||
last_feed: AgentFeed,
|
||||
/// Over the bus (BUS-01): the feed status the last Commit attached, as of the committed
|
||||
/// boundary; the next publish uses it instead of calling `Legacy.FeedStatus`. Cleared by a
|
||||
/// rollback, which changes the agent after its Commit.
|
||||
committed_feed: Option<Value>,
|
||||
/// Whether the agent attaches its feed status to every Commit (the bus transport).
|
||||
feed_on_commit: bool,
|
||||
|
||||
semantic_rewards: bool,
|
||||
next_profile: Instant,
|
||||
|
|
@ -522,6 +663,8 @@ impl SessionHost {
|
|||
dc_blocker: DcBlocker::default(),
|
||||
spikes: Vec::new(),
|
||||
last_feed: AgentFeed::default(),
|
||||
committed_feed: None,
|
||||
feed_on_commit: options.transport == Transport::Bus,
|
||||
semantic_rewards,
|
||||
next_profile: now + PROFILE_PERIOD,
|
||||
shared,
|
||||
|
|
@ -532,9 +675,15 @@ impl SessionHost {
|
|||
// The service reads every transition's commit (the spike bitset) and paces itself by
|
||||
// flysim's `Pacer`, as the legacy loop does.
|
||||
host.session.coordinator.disable_pacing();
|
||||
if host.feed_on_commit {
|
||||
host.session
|
||||
.coordinator
|
||||
.request_commit_attachments(&[SPIKES_ATTACHMENT, FEED_STATUS_ATTACHMENT]);
|
||||
} else {
|
||||
host.session
|
||||
.coordinator
|
||||
.request_commit_attachments(&[SPIKES_ATTACHMENT]);
|
||||
}
|
||||
host.session.coordinator.digest_views(false);
|
||||
|
||||
let origin = match &boot {
|
||||
|
|
@ -659,6 +808,7 @@ impl SessionHost {
|
|||
let mut next_watchdog = Instant::now();
|
||||
|
||||
loop {
|
||||
let iteration = Instant::now();
|
||||
self.shared.beat();
|
||||
if let Some(period) = watchdog_period {
|
||||
let now = Instant::now();
|
||||
|
|
@ -739,6 +889,9 @@ impl SessionHost {
|
|||
"the simulation is behind real time; no frames are being skipped"
|
||||
);
|
||||
}
|
||||
// The frame's compute time, before the pacing sleep (`fly_frame_work_*`), as the
|
||||
// legacy loop records it.
|
||||
self.shared.metrics.frame_work.record(iteration.elapsed());
|
||||
let sleep = pacer.next_sleep(Instant::now());
|
||||
if !sleep.is_zero() {
|
||||
tokio::time::sleep(sleep).await;
|
||||
|
|
@ -787,6 +940,9 @@ impl SessionHost {
|
|||
self.remaining_ms = remaining;
|
||||
}
|
||||
for (agent, name, bytes) in &details.commit_attachments {
|
||||
if *agent == self.agent_id && name == FEED_STATUS_ATTACHMENT {
|
||||
self.committed_feed = serde_json::from_slice(bytes).ok();
|
||||
}
|
||||
if *agent == self.agent_id && name == SPIKES_ATTACHMENT {
|
||||
if self.spikes.len() < bytes.len() {
|
||||
self.spikes.resize(bytes.len(), 0);
|
||||
|
|
@ -860,6 +1016,8 @@ impl SessionHost {
|
|||
.await
|
||||
.map_err(|e| anyhow!("rollback ({} at {}): {}", e.detail, e.phase, e.error.message))?;
|
||||
if rolled_back {
|
||||
// The rollback changed the agent after its Commit: the next publish asks again.
|
||||
self.committed_feed = None;
|
||||
let feed = self.session.task.take_feed();
|
||||
let (game_over, events) = feed.rollback.unwrap_or_default();
|
||||
self.recovered(game_over, &events).await;
|
||||
|
|
@ -1277,7 +1435,11 @@ impl SessionHost {
|
|||
/// `Sim::publish`: one snapshot of the committed boundary. `with_attachments` is false while
|
||||
/// not running, which is the protocol's header-only idle cadence.
|
||||
async fn publish(&mut self, with_attachments: bool) {
|
||||
match self.read_feed().await {
|
||||
let feed = match self.committed_feed.take() {
|
||||
Some(value) => AgentFeed::parse(&value),
|
||||
None => self.read_feed().await,
|
||||
};
|
||||
match feed {
|
||||
Ok(feed) => self.last_feed = feed,
|
||||
Err(error) => tracing::warn!(%error, "the agent's feed status: publishing the last one"),
|
||||
}
|
||||
|
|
@ -1383,6 +1545,53 @@ impl SessionHost {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// BUS-01: the transport and the mode, from their two settings.
|
||||
#[test]
|
||||
fn the_transport_and_the_mode_follow_each_other() {
|
||||
use crate::composition::SessionArm;
|
||||
let pick = |mode, transport| mode_and_transport(mode, transport).ok();
|
||||
let local = (ExecutionMode::InProcess, Transport::Local);
|
||||
assert_eq!(pick(None, None), Some(local));
|
||||
assert_eq!(pick(Some(""), Some("")), Some(local));
|
||||
assert_eq!(pick(None, Some("local")), Some(local));
|
||||
assert_eq!(pick(Some("in-process"), None), Some(local));
|
||||
assert_eq!(pick(None, Some("bus")), Some((ExecutionMode::Process, Transport::Bus)));
|
||||
assert_eq!(
|
||||
pick(Some("in-process"), Some("bus")),
|
||||
Some((ExecutionMode::InProcess, Transport::Bus))
|
||||
);
|
||||
// A thread or a process has only the bus, whether or not the transport says so.
|
||||
assert_eq!(pick(Some("thread"), None), Some((ExecutionMode::Thread, Transport::Bus)));
|
||||
assert_eq!(pick(Some("process"), Some("bus")), Some((ExecutionMode::Process, Transport::Bus)));
|
||||
assert_eq!(pick(Some("process"), Some("local")), None);
|
||||
assert_eq!(pick(Some("thread"), Some("local")), None);
|
||||
assert_eq!(pick(Some("fork"), None), None);
|
||||
assert_eq!(pick(None, Some("udp")), None);
|
||||
// The arms the parity runs and the shadow name parse to the same pairs.
|
||||
for (name, arm) in [
|
||||
("local", SessionArm::LOCAL),
|
||||
("in-process", SessionArm::LOCAL),
|
||||
("bus", SessionArm::BUS_PROCESS),
|
||||
("process", SessionArm::BUS_PROCESS),
|
||||
("bus/process", SessionArm::BUS_PROCESS),
|
||||
("bus/thread", SessionArm::BUS_THREAD),
|
||||
("thread", SessionArm::BUS_THREAD),
|
||||
("bus/in-process", SessionArm::BUS_IN_PROCESS),
|
||||
] {
|
||||
assert_eq!(SessionArm::parse(name), Ok(arm), "{name}");
|
||||
}
|
||||
assert_eq!(SessionArm::BUS_PROCESS.label(), "bus/process");
|
||||
assert_eq!(SessionArm::LOCAL.label(), "local");
|
||||
assert!(SessionArm::parse("bus/fork").is_err());
|
||||
assert_eq!(
|
||||
SessionArm::parse_list("local, bus/thread,,bus").unwrap(),
|
||||
vec![SessionArm::LOCAL, SessionArm::BUS_THREAD, SessionArm::BUS_PROCESS]
|
||||
);
|
||||
// The launcher transport each arm runs on.
|
||||
assert_eq!(Transport::Bus.via(ExecutionMode::InProcess), fly_session::Via::Unix);
|
||||
assert_eq!(Transport::Local.via(ExecutionMode::Process), fly_session::Via::Unix);
|
||||
}
|
||||
|
||||
/// The environment's native audio through the f32 DC blocker is the legacy loop's u8 audio
|
||||
/// through its own, bit for bit, across chunk boundaries.
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ use fly_session::types::{id, parse_id};
|
|||
use flysim::snapshot::MacroMode;
|
||||
|
||||
use crate::admission::LegacyAdmission;
|
||||
use crate::composition::{LegacyConfig, LegacySession};
|
||||
use crate::composition::{LegacyConfig, LegacySession, Transport};
|
||||
use crate::trace::{self, Agreement, Difference};
|
||||
use checkpoint::ShadowCapture;
|
||||
use follow::Follower;
|
||||
|
|
@ -87,6 +87,9 @@ pub struct ShadowConfig {
|
|||
pub macro_mode: MacroMode,
|
||||
pub speed: f64,
|
||||
pub mode: ExecutionMode,
|
||||
/// How the shadow session's participants reach each other (BUS-01): the local lane, or the
|
||||
/// router's sockets.
|
||||
pub transport: Transport,
|
||||
pub agent_threads: usize,
|
||||
pub required_brain_seconds: f64,
|
||||
/// Follow every trace file present at start, oldest first (a rehearsal), rather than only the
|
||||
|
|
@ -457,6 +460,9 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
|
|||
}
|
||||
let session_config = LegacyConfig {
|
||||
mode: config.mode,
|
||||
transport: config.transport,
|
||||
// The shadow places nothing: its box gives it cores of its own.
|
||||
placements: Default::default(),
|
||||
rom_path: config.rom_path.clone(),
|
||||
dataset_dir: config.dataset_dir.clone(),
|
||||
profile: config.profile,
|
||||
|
|
@ -517,6 +523,7 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
|
|||
release: config.release.clone(),
|
||||
compatibility: compatibility.clone(),
|
||||
execution_mode: config.mode.label().to_owned(),
|
||||
transport: config.transport.label().to_owned(),
|
||||
agent_threads: config.agent_threads,
|
||||
required_brain_seconds: config.required_brain_seconds,
|
||||
agreement: Agreement::default(),
|
||||
|
|
|
|||
|
|
@ -57,7 +57,9 @@ pub const TRACE_CHUNK: u64 = 4 << 20;
|
|||
/// The live configuration the relay forwards to the box, so the remote shadow runs the live
|
||||
/// service's composition (game, macro mode, accepted adapters, pins): exactly these names, and
|
||||
/// nothing that is a path or a secret. The box's own env file supplies the paths.
|
||||
pub const FORWARDED_ENV: [&str; 14] = [
|
||||
pub const FORWARDED_ENV: [&str; 15] = [
|
||||
// BUS-01: the topology the box's shadow runs (`fly-shadow-run start --bus`).
|
||||
"FLY_SHADOW_MODE",
|
||||
"FLY_GAME",
|
||||
"FLYSIM_LOOP_GAME",
|
||||
"FLY_MACRO_MODE",
|
||||
|
|
|
|||
|
|
@ -229,6 +229,8 @@ pub struct Verdict {
|
|||
pub release: String,
|
||||
pub compatibility: String,
|
||||
pub execution_mode: String,
|
||||
/// `local` or `bus` (BUS-01): with `execution_mode`, the topology the shadow ran.
|
||||
pub transport: String,
|
||||
pub agent_threads: usize,
|
||||
pub required_brain_seconds: f64,
|
||||
pub agreement: Agreement,
|
||||
|
|
@ -324,6 +326,7 @@ impl Verdict {
|
|||
"compatibility": self.compatibility,
|
||||
"compatibilitySha256": crate::shadow::sha256_hex(self.compatibility.as_bytes()),
|
||||
"executionMode": self.execution_mode,
|
||||
"transport": self.transport,
|
||||
"agentThreads": self.agent_threads,
|
||||
},
|
||||
"required": {"brainSeconds": self.required_brain_seconds},
|
||||
|
|
@ -424,6 +427,36 @@ pub struct Release<'a> {
|
|||
pub binaries: &'a std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// The topology a verdict's shadow ran, named as [`crate::composition::SessionArm::label`] names
|
||||
/// it: `local`, `bus/in-process`, `bus/thread` or `bus/process`. A verdict from before BUS-01 has
|
||||
/// no `transport`: its in-process shadow ran the local lane, a thread or a process the bus.
|
||||
pub fn shadowed_arm(verdict: &Value) -> String {
|
||||
let candidate = &verdict["candidate"];
|
||||
let mode = candidate["executionMode"].as_str().unwrap_or("in-process");
|
||||
let transport = match candidate["transport"].as_str() {
|
||||
Some(transport) => transport,
|
||||
None if mode == "in-process" => "local",
|
||||
None => "bus",
|
||||
};
|
||||
if transport == "local" {
|
||||
"local".to_owned()
|
||||
} else {
|
||||
format!("{transport}/{mode}")
|
||||
}
|
||||
}
|
||||
|
||||
/// `fly-shadow check --require-arm`: the cutover is into a topology, so the shadow must have run
|
||||
/// that one (BUS-01). `required` is a [`crate::composition::SessionArm`] name.
|
||||
pub fn ran_arm(verdict: &Value, required: &str) -> Result<(), String> {
|
||||
let required = crate::composition::SessionArm::parse(required)?.label();
|
||||
let ran = shadowed_arm(verdict);
|
||||
if ran == required {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("the shadow ran {ran}, not {required}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// How far ahead of the clock a verdict's `updatedAt` may be before it is refused.
|
||||
const MAX_CLOCK_SKEW_S: i64 = 60;
|
||||
|
||||
|
|
@ -571,6 +604,7 @@ mod tests {
|
|||
release: "/opt/fly/releases/test".to_owned(),
|
||||
compatibility: "c".to_owned(),
|
||||
execution_mode: "in-process".to_owned(),
|
||||
transport: "local".to_owned(),
|
||||
agent_threads: 2,
|
||||
required_brain_seconds: 10_800.0,
|
||||
agreement: Agreement::default(),
|
||||
|
|
@ -607,6 +641,7 @@ mod tests {
|
|||
release: String::new(),
|
||||
compatibility: String::new(),
|
||||
execution_mode: String::new(),
|
||||
transport: String::new(),
|
||||
agent_threads: 1,
|
||||
required_brain_seconds: 10_800.0,
|
||||
agreement: Agreement::default(),
|
||||
|
|
@ -633,6 +668,27 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_arm_a_verdict_ran_is_checked_by_name() {
|
||||
// BUS-01: a cutover onto the bus needs a shadow that ran the bus.
|
||||
let mut v = verdict(Status::Pass, 10_800_000.0);
|
||||
assert_eq!(shadowed_arm(&v), "local");
|
||||
assert!(ran_arm(&v, "local").is_ok());
|
||||
assert!(ran_arm(&v, "bus/process").is_err());
|
||||
v["candidate"]["executionMode"] = json!("process");
|
||||
v["candidate"]["transport"] = json!("bus");
|
||||
assert_eq!(shadowed_arm(&v), "bus/process");
|
||||
assert!(ran_arm(&v, "bus").is_ok());
|
||||
assert!(ran_arm(&v, "process").is_ok());
|
||||
assert!(ran_arm(&v, "bus/thread").is_err());
|
||||
assert!(ran_arm(&v, "nonsense").is_err());
|
||||
// A verdict from before BUS-01: no transport.
|
||||
v["candidate"].as_object_mut().expect("an object").remove("transport");
|
||||
assert_eq!(shadowed_arm(&v), "bus/process");
|
||||
v["candidate"]["executionMode"] = json!("in-process");
|
||||
assert_eq!(shadowed_arm(&v), "local");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stop_ends_the_window() {
|
||||
// B2: brain time compared before a coverage gap never counts toward a pass.
|
||||
|
|
|
|||
|
|
@ -25,6 +25,8 @@ async fn session(root: &std::path::Path) -> Option<(LegacySession, StoreConfig)>
|
|||
};
|
||||
let config = LegacyConfig {
|
||||
mode: ExecutionMode::InProcess,
|
||||
transport: Default::default(),
|
||||
placements: Default::default(),
|
||||
rom_path,
|
||||
dataset_dir: legacy_parity::toy::dir(),
|
||||
profile: LegacyProfileKind::Toy,
|
||||
|
|
|
|||
|
|
@ -11,7 +11,8 @@
|
|||
//! - **feed**: every running snapshot, header field by field and attachments byte for byte,
|
||||
//! except the fields that are wall clock by definition (`wallMs`, `uptimeSeconds`,
|
||||
//! `realtimeFactor`, `sugar.cooldownMs`, an event's or chat line's `wallMs`) and `seq`, which
|
||||
//! counts the idle headers a pause publishes at 2 Hz of wall clock;
|
||||
//! counts the idle headers a pause publishes at 2 Hz of wall clock (the script holds the
|
||||
//! resume until the recorder has seen the first one, so each runtime must publish one);
|
||||
//! - **control**: status code and body of every request (`/stimulate` 202 and 429 with the same
|
||||
//! `retryAfterMs`, `/reward` 403, `/chat` 202/422, `/checkpoint` the same generation,
|
||||
//! `/pause`, `/resume`, `/events`, `/healthz`), `/status` minus its wall-clock fields, and the
|
||||
|
|
@ -19,6 +20,10 @@
|
|||
//! - **store**: the event log file, the journal lines (minus `wallMs`, the boot header's runtime
|
||||
//! and wall clock), and the final durable checkpoint decoded (minus `wallMs`).
|
||||
//!
|
||||
//! The in-process session runs a second time with its control API on the bus (CTRL-01): the
|
||||
//! same script through `fly-control-edge`'s router and the control services on an embedded
|
||||
//! router, compared against the legacy run the same way.
|
||||
//!
|
||||
//! Gated on `FLY_ROM` (source `bin/rom-env.sh`). `toy_raw_*` uses the committed toy connectome and
|
||||
//! a store seeded by a legacy fresh start; `fafb_*` (also `FLY_SERVE01_FAFB`) the real connectome
|
||||
//! from the ENV-01 service trace's `rollback` checkpoint, which rolls back on its first boundary.
|
||||
|
|
@ -29,8 +34,8 @@ use std::time::{Duration, Instant};
|
|||
|
||||
use axum::body::Body;
|
||||
use axum::http::{Method, Request};
|
||||
use fly_legacy_session::composition::SessionArm;
|
||||
use fly_legacy_session::service::{ServiceOptions, run_host};
|
||||
use fly_session::launcher::ExecutionMode;
|
||||
use fly_session::legacy_agent::LegacyProfileKind;
|
||||
use flysim::AppState;
|
||||
use flysim::config::Config;
|
||||
|
|
@ -69,14 +74,21 @@ fn sha(bytes: &[u8]) -> String {
|
|||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Runtime {
|
||||
Legacy,
|
||||
Session(ExecutionMode),
|
||||
Session(SessionArm),
|
||||
/// The session runtime with its control API on the bus (`FLY_CONTROL_VIA=bus`, CTRL-01): the
|
||||
/// script goes through `fly-control-edge`'s router, over the edge's Unix socket, to the
|
||||
/// control services on the embedded router.
|
||||
SessionOverBus(SessionArm),
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
fn label(&self) -> String {
|
||||
match self {
|
||||
Runtime::Legacy => "legacy".to_owned(),
|
||||
Runtime::Session(mode) => format!("session ({})", mode.label()),
|
||||
Runtime::Session(arm) => format!("session ({})", arm.label()),
|
||||
Runtime::SessionOverBus(arm) => {
|
||||
format!("session ({}) over the control bus", arm.label())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -245,11 +257,13 @@ fn record(
|
|||
let mut sim = Sim::boot(loop_shared, snapshots_tx, command_rx)?;
|
||||
sim.run(¬ifier)
|
||||
}
|
||||
Runtime::Session(mode) => {
|
||||
Runtime::Session(arm) | Runtime::SessionOverBus(arm) => {
|
||||
let options = ServiceOptions {
|
||||
mode,
|
||||
mode: arm.mode,
|
||||
transport: arm.transport,
|
||||
profile,
|
||||
session_dir,
|
||||
placements: Default::default(),
|
||||
};
|
||||
run_host(loop_shared, snapshots_tx, command_rx, ¬ifier, &options)
|
||||
}
|
||||
|
|
@ -261,7 +275,23 @@ fn record(
|
|||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let router = flysim::api::router(state.clone());
|
||||
let bus_dir = config.paths.save_dir.parent().unwrap().join("bus");
|
||||
let (router, _control_bus) = match runtime {
|
||||
Runtime::SessionOverBus(_) => driver.block_on(async {
|
||||
let scope = flysim::controlbus::Scope::live();
|
||||
let uses = flysim::bus::Uses { feed: false, control: true };
|
||||
let bus = flysim::bus::start(&bus_dir, uses, &scope).await.unwrap();
|
||||
let host = flysim::controlbus::serve(&bus.router, state.clone(), &scope)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut edge_config = fly_control_edge::EdgeConfig::from_flysim(&config, None);
|
||||
edge_config.bus_dir = bus_dir.clone();
|
||||
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
|
||||
let backend = fly_control_edge::connect(&edge_config, &metrics).await.unwrap();
|
||||
(flysim::api::router_with(backend), Some((bus, host)))
|
||||
}),
|
||||
_ => (flysim::api::router(state.clone()), None),
|
||||
};
|
||||
let metrics_router = flysim::api::metrics_router(state.clone());
|
||||
let recording = driver.block_on(async {
|
||||
let mut snapshots = snapshots;
|
||||
|
|
@ -315,6 +345,29 @@ fn record(
|
|||
));
|
||||
// Sent now, in order, each drained before the next frame.
|
||||
for action in actions.iter().filter(|a| a.at == index) {
|
||||
if action.path == "/resume" {
|
||||
// The pause is only observable as idle headers if the loop stays
|
||||
// paused until it has published one (a header-only publish is due
|
||||
// within the 2 Hz idle period). Resuming 2 ms after the pause let a
|
||||
// loaded box skip it in one runtime and not the other, so wait, bounded,
|
||||
// for the condition instead of racing it.
|
||||
let before = idle.len();
|
||||
let waited = Instant::now();
|
||||
while idle.len() == before {
|
||||
match tokio::time::timeout(Duration::from_secs(30), snapshots.changed()).await {
|
||||
Ok(Ok(())) => {}
|
||||
other => panic!(
|
||||
"{}: no idle header within 30 s of the pause ({other:?})",
|
||||
runtime.label()
|
||||
),
|
||||
}
|
||||
let snap = Arc::clone(&snapshots.borrow_and_update());
|
||||
if snap.header.status == FeedStatus::Paused {
|
||||
idle.push(comparable(&snap));
|
||||
}
|
||||
}
|
||||
eprintln!(" {}: idle header after {:.1?} paused", runtime.label(), waited.elapsed());
|
||||
}
|
||||
let router = router.clone();
|
||||
let label = format!("{} {}", action_label(action), index);
|
||||
let action = action.clone();
|
||||
|
|
@ -323,6 +376,18 @@ fn record(
|
|||
tokio::time::sleep(Duration::from_millis(2)).await;
|
||||
pending.push((label, handle));
|
||||
}
|
||||
// Requests sent at one frame must all be drained together (two sugars before
|
||||
// one commit): if the loop published another snapshot while they were being
|
||||
// sent, a loaded box split them across frames and the run cannot be compared.
|
||||
let group = actions.iter().filter(|a| a.at == index).count();
|
||||
let pauses = actions.iter().any(|a| a.at == index && a.path.starts_with("/pause"));
|
||||
if group > 1 && !pauses && snapshots.has_changed().unwrap_or(false) {
|
||||
eprintln!(
|
||||
" {}: the loop moved on while {group} requests were sent at frame {index}; the run will be repeated",
|
||||
runtime.label()
|
||||
);
|
||||
complete = false;
|
||||
}
|
||||
}
|
||||
FeedStatus::Paused => idle.push(comparable(&snapshot)),
|
||||
FeedStatus::Booting | FeedStatus::Error => {}
|
||||
|
|
@ -491,9 +556,20 @@ fn compare(legacy: &Recording, session: &Recording, label: &str) {
|
|||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(legacy.idle.is_empty(), session.idle.is_empty(), "{label}: idle headers");
|
||||
assert!(!legacy.idle.is_empty(), "{label}: the legacy pause published no idle header");
|
||||
assert!(!session.idle.is_empty(), "{label}: the session pause published no idle header");
|
||||
if let (Some(a), Some(b)) = (legacy.idle.first(), session.idle.first()) {
|
||||
same(&format!("{label}: the first idle header"), a, b);
|
||||
// An idle header carries the events not yet published, and which publish that is (the
|
||||
// pause's own or a later one, whichever the recorder saw first) is wall clock; the events
|
||||
// themselves are compared in the running snapshots and the event log.
|
||||
let strip = |v: &Value| {
|
||||
let mut v = v.clone();
|
||||
if let Some(map) = v.as_object_mut() {
|
||||
map.remove("events");
|
||||
}
|
||||
v
|
||||
};
|
||||
same(&format!("{label}: the first idle header"), &strip(a), &strip(b));
|
||||
}
|
||||
assert_eq!(legacy.responses.len(), session.responses.len());
|
||||
for ((la, sa, ba), (lb, sb, bb)) in legacy.responses.iter().zip(&session.responses) {
|
||||
|
|
@ -580,15 +656,8 @@ fn seed(from: &Path, to: &Path) {
|
|||
}
|
||||
}
|
||||
|
||||
fn modes() -> Vec<ExecutionMode> {
|
||||
let mut modes = vec![ExecutionMode::InProcess];
|
||||
let program = fly_session::launcher::default_worker_program();
|
||||
if program.is_file() {
|
||||
modes.push(ExecutionMode::Process);
|
||||
} else {
|
||||
eprintln!("process mode skipped: no worker program at {}", program.display());
|
||||
}
|
||||
modes
|
||||
fn modes() -> Vec<SessionArm> {
|
||||
SessionArm::parity_arms()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
|
|
@ -627,10 +696,22 @@ fn run_pair(
|
|||
let started = Instant::now();
|
||||
let legacy = run(Runtime::Legacy, "legacy");
|
||||
eprintln!("{label}: legacy {} running snapshots in {:.1?}", legacy.running.len(), started.elapsed());
|
||||
for exec in modes() {
|
||||
let runtimes = modes()
|
||||
.into_iter()
|
||||
.map(Runtime::Session)
|
||||
.chain([Runtime::SessionOverBus(SessionArm::LOCAL)]);
|
||||
for runtime in runtimes {
|
||||
let started = Instant::now();
|
||||
let session = run(Runtime::Session(exec), &format!("session-{}", exec.label()));
|
||||
let label = format!("{label}, {}", exec.label());
|
||||
let exec = match runtime {
|
||||
Runtime::Session(exec) | Runtime::SessionOverBus(exec) => exec,
|
||||
Runtime::Legacy => unreachable!(),
|
||||
};
|
||||
let name = match runtime {
|
||||
Runtime::SessionOverBus(_) => format!("session-bus-{}", exec.label()),
|
||||
_ => format!("session-{}", exec.label()),
|
||||
};
|
||||
let session = run(runtime, &name);
|
||||
let label = format!("{label}, {}", runtime.label());
|
||||
compare(&legacy, &session, &label);
|
||||
let rewards = legacy
|
||||
.events
|
||||
|
|
|
|||
|
|
@ -31,11 +31,12 @@ use std::sync::Arc;
|
|||
use serde_json::Value;
|
||||
|
||||
use fly_legacy_session::admission::LegacyAdmission;
|
||||
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
|
||||
use fly_legacy_session::composition::{
|
||||
LegacyConfig, LegacySession, SessionArm, channels_and_hold,
|
||||
};
|
||||
use fly_legacy_session::driver::{DecisionDriver, RotationDriver};
|
||||
use fly_legacy_session::task::ledgers_of;
|
||||
use fly_legacy_session::trace::{self, Agreement};
|
||||
use fly_session::ExecutionMode;
|
||||
use fly_session::legacy_agent::LegacyProfileKind;
|
||||
use fly_session::legacy_parity;
|
||||
use fly_session::types::id;
|
||||
|
|
@ -81,18 +82,8 @@ fn env_usize(name: &str, default: usize) -> usize {
|
|||
.unwrap_or(default)
|
||||
}
|
||||
|
||||
fn modes() -> Vec<ExecutionMode> {
|
||||
let mut modes = vec![ExecutionMode::InProcess];
|
||||
let program = fly_session::launcher::default_worker_program();
|
||||
if program.is_file() {
|
||||
modes.push(ExecutionMode::Process);
|
||||
} else {
|
||||
eprintln!(
|
||||
"process mode skipped: no worker program at {}",
|
||||
program.display()
|
||||
);
|
||||
}
|
||||
modes
|
||||
fn modes() -> Vec<SessionArm> {
|
||||
SessionArm::parity_arms()
|
||||
}
|
||||
|
||||
/// What each frame admits at its top, in admission order, and whether the rotation driver hands
|
||||
|
|
@ -230,7 +221,7 @@ fn run_legacy(
|
|||
/// The same run on the session framework.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn run_session(
|
||||
mode: ExecutionMode,
|
||||
mode: SessionArm,
|
||||
rom_path: &Path,
|
||||
dataset_dir: &Path,
|
||||
profile: LegacyProfileKind,
|
||||
|
|
@ -241,7 +232,9 @@ async fn run_session(
|
|||
) -> Run {
|
||||
let root = tempfile::tempdir().expect("tmp");
|
||||
let config = LegacyConfig {
|
||||
mode,
|
||||
mode: mode.mode,
|
||||
transport: mode.transport,
|
||||
placements: Default::default(),
|
||||
rom_path: rom_path.to_owned(),
|
||||
dataset_dir: dataset_dir.to_owned(),
|
||||
profile,
|
||||
|
|
@ -599,8 +592,10 @@ async fn fafb_boot_run_save_restore() {
|
|||
flysim::store::Store::new(&store.durable_dir, store.keep_generations)
|
||||
.commit(generation, &original, None)
|
||||
.expect("the seeded store");
|
||||
let config = |mode| LegacyConfig {
|
||||
mode,
|
||||
let config = |mode: SessionArm| LegacyConfig {
|
||||
mode: mode.mode,
|
||||
transport: mode.transport,
|
||||
placements: Default::default(),
|
||||
rom_path: rom_path.clone(),
|
||||
dataset_dir: dataset.clone(),
|
||||
profile: LegacyProfileKind::Production,
|
||||
|
|
|
|||
|
|
@ -203,6 +203,7 @@ fn config(
|
|||
macro_mode: MacroMode::Raw,
|
||||
speed: 0.0,
|
||||
mode: ExecutionMode::InProcess,
|
||||
transport: Default::default(),
|
||||
agent_threads: 1,
|
||||
required_brain_seconds: 30.0,
|
||||
all_files: true,
|
||||
|
|
|
|||
|
|
@ -182,6 +182,7 @@ fn box_shadow(rom: &Path, root: &Path) -> ShadowConfig {
|
|||
// The live service's loop.speed (real time), which its saves record.
|
||||
speed: 1.0,
|
||||
mode: ExecutionMode::InProcess,
|
||||
transport: Default::default(),
|
||||
agent_threads: 1,
|
||||
required_brain_seconds: 20.0,
|
||||
all_files: false,
|
||||
|
|
|
|||
|
|
@ -12,8 +12,9 @@
|
|||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
|
||||
use fly_session::ExecutionMode;
|
||||
use fly_legacy_session::composition::{
|
||||
LegacyConfig, LegacySession, SessionArm, channels_and_hold,
|
||||
};
|
||||
use fly_session::legacy_agent::LegacyProfileKind;
|
||||
use fly_session::legacy_parity;
|
||||
use fly_session::types::id;
|
||||
|
|
@ -175,13 +176,16 @@ async fn session_against_legacy_per_frame() {
|
|||
);
|
||||
|
||||
// ---- The session, unpaced then paced, in each mode.
|
||||
for mode in [ExecutionMode::InProcess, ExecutionMode::Process] {
|
||||
for arm in [SessionArm::LOCAL, SessionArm::BUS_PROCESS] {
|
||||
let mode = arm.mode;
|
||||
for paced in [false, true] {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let mut session = LegacySession::start(
|
||||
root.path(),
|
||||
LegacyConfig {
|
||||
mode,
|
||||
transport: arm.transport,
|
||||
placements: Default::default(),
|
||||
rom_path: rom_path.clone(),
|
||||
dataset_dir: dataset.clone(),
|
||||
profile: LegacyProfileKind::Production,
|
||||
|
|
|
|||
|
|
@ -12,8 +12,9 @@
|
|||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
|
||||
use fly_session::ExecutionMode;
|
||||
use fly_legacy_session::composition::{
|
||||
LegacyConfig, LegacySession, SessionArm, channels_and_hold,
|
||||
};
|
||||
use fly_session::legacy_agent::LegacyProfileKind;
|
||||
use fly_session::legacy_parity;
|
||||
use fly_session::types::id;
|
||||
|
|
@ -151,23 +152,24 @@ async fn run(workers: usize) {
|
|||
let bytes = std::fs::read(&checkpoint_path).unwrap();
|
||||
let checkpoint = flysim::store::decode(&bytes).unwrap();
|
||||
// PERF-01: `FLY_PERF_ARMS` picks the session arms, comma-separated: `local` (in-process
|
||||
// over the local lane, the default in-process path), `bus` (in-process over the bus,
|
||||
// `FLY_SESSION_LOCAL_LANE=0`, the TASK-01 path) and `process`. Default: all three.
|
||||
let arms = std::env::var("FLY_PERF_ARMS").unwrap_or_else(|_| "local,bus,process".to_owned());
|
||||
// over the local lane, the default in-process path), `memory` (in-process over the bus in
|
||||
// memory, `FLY_SESSION_LOCAL_LANE=0`, the TASK-01 path), and the BUS-01 socket arms
|
||||
// `bus/in-process`, `bus/thread`, `bus/process` (`process`). Default: local, memory, process.
|
||||
let arms = std::env::var("FLY_PERF_ARMS").unwrap_or_else(|_| "local,memory,process".to_owned());
|
||||
// `FLY_PERF_SERVICE=1` adds the service host's per-frame reads (SERVE-01's
|
||||
// `flysim-session`): the spike bitset of every commit and the audio chunk of every boundary.
|
||||
let service = std::env::var_os("FLY_PERF_SERVICE").is_some();
|
||||
for arm in arms.split(',') {
|
||||
let mode = match arm {
|
||||
"local" | "bus" => ExecutionMode::InProcess,
|
||||
"process" => ExecutionMode::Process,
|
||||
other => panic!("unknown arm {other}"),
|
||||
let parsed = match arm {
|
||||
"memory" => SessionArm::LOCAL,
|
||||
other => SessionArm::parse(other).unwrap_or_else(|e| panic!("FLY_PERF_ARMS: {e}")),
|
||||
};
|
||||
let mode = parsed.mode;
|
||||
// SAFETY: set before the session's runtime reads it; nothing else reads the variable.
|
||||
unsafe {
|
||||
std::env::set_var(
|
||||
fly_legacy_session::composition::LOCAL_LANE_ENV,
|
||||
if arm == "bus" { "0" } else { "1" },
|
||||
if arm == "memory" { "0" } else { "1" },
|
||||
);
|
||||
}
|
||||
let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads);
|
||||
|
|
@ -176,6 +178,8 @@ async fn run(workers: usize) {
|
|||
root.path(),
|
||||
LegacyConfig {
|
||||
mode,
|
||||
transport: parsed.transport,
|
||||
placements: Default::default(),
|
||||
rom_path: rom_path.clone(),
|
||||
dataset_dir: dataset.clone(),
|
||||
profile: LegacyProfileKind::Production,
|
||||
|
|
|
|||
|
|
@ -95,6 +95,26 @@ fly-session legacy-environment ... --worker ID --port p1 --rom PATH --rom-digest
|
|||
fly-session measure --steps 300 --agents 1,2,4
|
||||
```
|
||||
|
||||
BUS-01 (the live composition on the router) added four things here:
|
||||
|
||||
- **Placement per process.** `Launcher::place_process(worker_id, ProcessCpus { host, sweep })`
|
||||
hands a separate process its CPUs as `--host-cpus` and `--sweep-cpus`; the worker applies them
|
||||
(`flybrain_core::pool::apply_placement`) before it starts a thread, so an agent process pins its
|
||||
own sweep and every agent can have its own CPUs.
|
||||
- **The launcher's own clients in memory.** In thread and process modes the supervisor's and the
|
||||
coordinator's connections are in memory (they live with the router); the participants' are the
|
||||
sockets.
|
||||
- **One async worker per participant, and long handlers give it up.** A thread or process
|
||||
participant runs on a multi-thread runtime with one worker, so a bus request crosses no thread
|
||||
inside it; a handler that can run for seconds (`*.Initialize`, `State.*`, `Agent.Rollback`) runs
|
||||
under `tokio::task::block_in_place`, so the shell keeps reading -- and answers `Worker.Status`
|
||||
and an exact duplicate's `IN_PROGRESS` -- while the legacy agent warms up. The local lane is
|
||||
unchanged.
|
||||
- **Writers allocated ahead** (`worker::WriterPool`): after each bus reply the shell allocates a
|
||||
staging writer for each of the last few reply-artifact shapes it sealed, so the next step's seal
|
||||
is one round trip instead of two. Reply artifacts the worker holds itself (its own seals) are
|
||||
cached by clone, not by a second `retain`.
|
||||
|
||||
## What it implements
|
||||
|
||||
- **The transaction, in order.** Prepare all agents concurrently; run each task-local executor
|
||||
|
|
|
|||
|
|
@ -42,6 +42,8 @@ fly-session <command> [options]
|
|||
|
||||
Worker options (agent and environment):
|
||||
--socket PATH the launcher's endpoint for this participant
|
||||
--host-cpus LIST the CPUs every thread of this process runs on (optional)
|
||||
--sweep-cpus LIST an agent's sweep workers, one CPU each (optional, with --host-cpus)
|
||||
--store-root PATH the router's artifact store root
|
||||
--client-id ID the configured bus client identity
|
||||
--service NAME the one service name this worker registers
|
||||
|
|
@ -212,6 +214,7 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
|
|||
}
|
||||
let session_id = options.id(flags::SESSION)?;
|
||||
let incarnation_id = options.id(flags::INCARNATION)?;
|
||||
place(options)?;
|
||||
let what = match role {
|
||||
"agent" => Started::Agent(AgentLaunch {
|
||||
session_id,
|
||||
|
|
@ -291,8 +294,28 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
|
|||
service: service.clone(),
|
||||
}),
|
||||
};
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(threads)
|
||||
if crate::profile::enabled() {
|
||||
// A worker process keeps its own span table (`FLY_SESSION_PROFILE`): printed once a
|
||||
// minute on stderr, the service's journal, beside the coordinator's profile line.
|
||||
let who = client_id.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(std::time::Duration::from_secs(60));
|
||||
let line: Vec<String> = crate::profile::report_with_max()
|
||||
.into_iter()
|
||||
.map(|(name, count, mean, max)| {
|
||||
format!(
|
||||
"{name}={count}x{:.3}/{:.1}",
|
||||
mean.as_secs_f64() * 1e3,
|
||||
max.as_secs_f64() * 1e3
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
eprintln!("worker profile {who} (count x mean/max ms): {}", line.join(" "));
|
||||
}
|
||||
});
|
||||
}
|
||||
let runtime = crate::launcher::participant_runtime(threads)
|
||||
.enable_all()
|
||||
.build()
|
||||
.map_err(|e| format!("runtime: {e}"))?;
|
||||
|
|
@ -305,6 +328,42 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
|
|||
})
|
||||
}
|
||||
|
||||
/// `--host-cpus` and `--sweep-cpus` (BUS-01): the placement the launcher made for this process,
|
||||
/// applied before any thread starts, so every thread inherits the host set and every sweep pool
|
||||
/// pins its workers. Without `--host-cpus` the process floats over what it inherited.
|
||||
fn place(options: &Options) -> Result<(), String> {
|
||||
let list = |flag: &str| -> Result<Option<Vec<usize>>, String> {
|
||||
options
|
||||
.optional(flag)
|
||||
.map(|value| {
|
||||
flybrain_core::pool::parse_cpu_list(value)
|
||||
.ok_or_else(|| format!("--{flag}: {value:?} is not a cpu list"))
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let (host, sweep) = (list(flags::HOST_CPUS)?, list(flags::SWEEP_CPUS)?);
|
||||
let Some(host) = host else {
|
||||
if sweep.is_some() {
|
||||
return Err(format!("--{} needs --{}", flags::SWEEP_CPUS, flags::HOST_CPUS));
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
let placement = flybrain_core::pool::Placement {
|
||||
workers: sweep.unwrap_or_default(),
|
||||
host,
|
||||
};
|
||||
// Best effort, as in the service: a refused placement leaves the process floating.
|
||||
if flybrain_core::pool::apply_placement(&placement) {
|
||||
eprintln!(
|
||||
"placed: sweep workers {:?}, every other thread on {:?}",
|
||||
placement.workers, placement.host
|
||||
);
|
||||
} else {
|
||||
eprintln!("placement {placement:?} refused; the threads float");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_channels(value: &str) -> Result<Vec<String>, String> {
|
||||
value
|
||||
.split(',')
|
||||
|
|
|
|||
|
|
@ -411,6 +411,10 @@ pub enum ReapOutcome {
|
|||
struct Endpoints {
|
||||
router: Router,
|
||||
via: Via,
|
||||
/// How this process's own clients -- the supervisor and the coordinator, which live with the
|
||||
/// router -- reach it: in memory when the participants are a thread or a process away (their
|
||||
/// sockets are the ones that cross a boundary; BUS-01), else the participants' transport.
|
||||
own: Via,
|
||||
store_root: PathBuf,
|
||||
sockets: PathBuf,
|
||||
next_socket: AtomicU64,
|
||||
|
|
@ -423,9 +427,18 @@ impl Endpoints {
|
|||
self.sockets.join(format!("{client_id}-{n}.sock"))
|
||||
}
|
||||
|
||||
/// A connection this process owns, over the configured transport.
|
||||
/// A connection this process owns: the supervisor's and the coordinator's.
|
||||
async fn connect(&self, client_id: &str) -> Result<Client, flybus::BusError> {
|
||||
let transport = match self.via {
|
||||
self.connect_via(self.own, client_id).await
|
||||
}
|
||||
|
||||
/// A connection for an in-process participant, over the participants' transport.
|
||||
async fn connect_participant(&self, client_id: &str) -> Result<Client, flybus::BusError> {
|
||||
self.connect_via(self.via, client_id).await
|
||||
}
|
||||
|
||||
async fn connect_via(&self, via: Via, client_id: &str) -> Result<Client, flybus::BusError> {
|
||||
let transport = match via {
|
||||
Via::Memory | Via::Local => self.router.connect_in_memory_as(client_id),
|
||||
Via::Unix => {
|
||||
let path = self.socket_path(client_id);
|
||||
|
|
@ -480,6 +493,30 @@ pub struct Launcher {
|
|||
serial: u64,
|
||||
/// Whether an in-process participant's reference carries its local lane (PERF-01).
|
||||
local_lane: bool,
|
||||
/// Where each separate-process participant's threads run, by worker id (BUS-01).
|
||||
placements: BTreeMap<Id, ProcessCpus>,
|
||||
}
|
||||
|
||||
/// Where a separate-process participant's threads run (BUS-01): `host` for every thread of the
|
||||
/// process, and for an agent `sweep`, one CPU per spawned sweep worker (`flybrain_core::pool::
|
||||
/// Placement`). Given to the worker as `--host-cpus` and `--sweep-cpus`; the worker applies it
|
||||
/// before it starts a thread. Placement chooses a CPU, never a result.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ProcessCpus {
|
||||
pub host: Vec<usize>,
|
||||
pub sweep: Vec<usize>,
|
||||
}
|
||||
|
||||
/// The runtime a thread or process participant serves on (BUS-01): one async worker, so a bus
|
||||
/// request crosses no thread inside the participant -- each crossing was a wake-up on the
|
||||
/// participant's shared CPU, about a millisecond a transition in all -- and multi-thread rather
|
||||
/// than current-thread, so a handler that runs for seconds (a warm-up, a restore, a capture) can
|
||||
/// hand that worker over (`tokio::task::block_in_place`) and the shell keeps answering status and
|
||||
/// duplicates meanwhile. The thread allocation (`threads`) is the agent's sweep, not this runtime's.
|
||||
pub fn participant_runtime(_threads: usize) -> tokio::runtime::Builder {
|
||||
let mut builder = tokio::runtime::Builder::new_multi_thread();
|
||||
builder.worker_threads(1);
|
||||
builder
|
||||
}
|
||||
|
||||
/// The bus client id the supervisor connects under.
|
||||
|
|
@ -528,6 +565,10 @@ impl Launcher {
|
|||
let endpoints = Endpoints {
|
||||
router,
|
||||
via: mode.transport(via),
|
||||
own: match mode {
|
||||
ExecutionMode::InProcess => via,
|
||||
ExecutionMode::Thread | ExecutionMode::Process => Via::Memory,
|
||||
},
|
||||
store_root: store_root.into(),
|
||||
sockets,
|
||||
next_socket: AtomicU64::new(0),
|
||||
|
|
@ -544,9 +585,16 @@ impl Launcher {
|
|||
workers: BTreeMap::new(),
|
||||
serial: 0,
|
||||
local_lane: mode == ExecutionMode::InProcess && via == Via::Local,
|
||||
placements: BTreeMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Places the separate process of `worker_id` (launched from now on) on `cpus`. Process mode
|
||||
/// only; the other modes share this process's placement.
|
||||
pub fn place_process(&mut self, worker_id: &Id, cpus: ProcessCpus) {
|
||||
self.placements.insert(worker_id.clone(), cpus);
|
||||
}
|
||||
|
||||
/// Offers every in-process participant launched from now on over the local lane
|
||||
/// ([`crate::worker::LocalLane`]): its [`LaunchedWorker::worker_ref`] carries the lane, so a
|
||||
/// coordinator in this process calls its endpoint methods without the bus. A thread or a
|
||||
|
|
@ -807,7 +855,7 @@ impl Launcher {
|
|||
) -> Result<(WorkerHandle, StatusCell), DomainError> {
|
||||
let client = self
|
||||
.endpoints
|
||||
.connect(&identity.client_id)
|
||||
.connect_participant(&identity.client_id)
|
||||
.await
|
||||
.map_err(|e| launch_error(&identity.worker_id, &e))?;
|
||||
let service = register_with_retry(&client, &identity.service, self.health.boot)
|
||||
|
|
@ -862,10 +910,7 @@ impl Launcher {
|
|||
let join = std::thread::Builder::new()
|
||||
.name(format!("fly-session-{}", identity.worker_id))
|
||||
.spawn(move || {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(threads)
|
||||
.enable_all()
|
||||
.build();
|
||||
let runtime = participant_runtime(threads).enable_all().build();
|
||||
let runtime = match runtime {
|
||||
Ok(runtime) => runtime,
|
||||
Err(e) => {
|
||||
|
|
@ -953,6 +998,18 @@ impl Launcher {
|
|||
for (flag, value) in what.arguments() {
|
||||
command.arg(flag).arg(value);
|
||||
}
|
||||
if let Some(cpus) = self.placements.get(&identity.worker_id) {
|
||||
if !cpus.host.is_empty() {
|
||||
command
|
||||
.arg(format!("--{}", flags::HOST_CPUS))
|
||||
.arg(flybrain_core::pool::format_cpu_list(&cpus.host));
|
||||
}
|
||||
if !cpus.sweep.is_empty() {
|
||||
command
|
||||
.arg(format!("--{}", flags::SWEEP_CPUS))
|
||||
.arg(flybrain_core::pool::format_cpu_list(&cpus.sweep));
|
||||
}
|
||||
}
|
||||
command.stdin(std::process::Stdio::null());
|
||||
let child = command.spawn().map_err(|e| {
|
||||
DomainError::new(
|
||||
|
|
@ -1411,6 +1468,10 @@ pub(crate) mod flags {
|
|||
pub const WORKER_THREADS: &str = "worker-threads";
|
||||
pub const MODES: &str = "modes";
|
||||
|
||||
/// BUS-01: the CPUs of the worker's threads, and an agent's sweep workers.
|
||||
pub const HOST_CPUS: &str = "host-cpus";
|
||||
pub const SWEEP_CPUS: &str = "sweep-cpus";
|
||||
|
||||
/// What every launched worker is given.
|
||||
pub const COMMON: &[&str] = &[
|
||||
SOCKET,
|
||||
|
|
@ -1420,6 +1481,8 @@ pub(crate) mod flags {
|
|||
THREADS,
|
||||
SESSION,
|
||||
INCARNATION,
|
||||
HOST_CPUS,
|
||||
SWEEP_CPUS,
|
||||
];
|
||||
/// What only an agent is given.
|
||||
pub const AGENT_ONLY: &[&str] = &[
|
||||
|
|
|
|||
|
|
@ -95,6 +95,14 @@ pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset";
|
|||
/// declared extension of this one worker, not a `workers-v1` method: it changes nothing, is
|
||||
/// answered in any phase once initialized, and is not in any trace.
|
||||
pub const METHOD_FEED_STATUS: &str = "Legacy.FeedStatus";
|
||||
/// BUS-01: the same feed status, as of the boundary the Commit commits, attached to a Commit reply
|
||||
/// that reaches the agent over the bus (`application/json`, the [`METHOD_FEED_STATUS`] result's
|
||||
/// bytes). The service host reads it instead of calling [`METHOD_FEED_STATUS`] after the step, which
|
||||
/// over the bus is a round trip of its own; the bytes are the ones that call would return, since
|
||||
/// nothing changes the agent between its Commit and the host's publish. Over the local lane, where
|
||||
/// the call costs nothing, the reply does not carry it.
|
||||
pub const FEED_STATUS_ATTACHMENT: &str = "legacy.feed-status";
|
||||
pub const FEED_STATUS_CONTENT_TYPE: &str = "application/json";
|
||||
pub const FEED_STATUS_CAPABILITY: &str = "legacy-feed-status-v1";
|
||||
|
||||
/// The one stimulus kind the profile supports.
|
||||
|
|
@ -1358,16 +1366,32 @@ impl LegacyAgentWorker {
|
|||
telemetry: self.telemetry(),
|
||||
};
|
||||
let _seal_span = crate::profile::span("agent.seal_spikes");
|
||||
let artifact = ctx
|
||||
.seal(SPIKES_CONTENT_TYPE, spikes)
|
||||
.await
|
||||
.map_err(|e| applied(e.code, e.message))?;
|
||||
// Over the bus the feed status rides along, sealed beside the spikes (one round trip for
|
||||
// both): the service host's publish then needs no call of its own.
|
||||
let feed = match (ctx.is_local(), self.agent.as_ref()) {
|
||||
(false, Some(agent)) => Some(
|
||||
serde_json::to_vec(&feed_status_of(agent)).expect("a JSON value serializes"),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let (artifact, feed) = tokio::join!(ctx.seal(SPIKES_CONTENT_TYPE, spikes), async {
|
||||
match feed {
|
||||
Some(bytes) => ctx.seal(FEED_STATUS_CONTENT_TYPE, bytes).await.map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
});
|
||||
let artifact = artifact.map_err(|e| applied(e.code, e.message))?;
|
||||
let feed = feed.map_err(|e| applied(e.code, e.message))?;
|
||||
self.status.set_state(WorkerState::Ready);
|
||||
self.status
|
||||
.set_scope(Some(scope_at(&scope.session_id, &scope.epoch, k + 1)));
|
||||
let mut attachments = vec![(SPIKES_ATTACHMENT.to_owned(), artifact)];
|
||||
if let Some(feed) = feed {
|
||||
attachments.push((FEED_STATUS_ATTACHMENT.to_owned(), feed));
|
||||
}
|
||||
Ok(HandlerReply::with_artifacts(
|
||||
object(result.to_json()),
|
||||
vec![(SPIKES_ATTACHMENT.to_owned(), artifact)],
|
||||
attachments,
|
||||
))
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ pub fn audio_attachment(stream_id: &str) -> String {
|
|||
format!("audio.{stream_id}")
|
||||
}
|
||||
|
||||
fn store_error(what: &str, message: &str) -> DomainError {
|
||||
pub(crate) fn store_error(what: &str, message: &str) -> DomainError {
|
||||
DomainError::new(
|
||||
ErrorCode::BackendFailure,
|
||||
format!("{what}: {message}"),
|
||||
|
|
|
|||
|
|
@ -160,6 +160,78 @@ pub struct HandlerCtx<'a> {
|
|||
pub request: &'a SessionRpcRequest,
|
||||
pub client: &'a flybus::Client,
|
||||
pub incoming: &'a Incoming,
|
||||
/// Staging writers allocated ahead for the reply artifacts this worker seals every step.
|
||||
pub(crate) writers: &'a WriterPool,
|
||||
}
|
||||
|
||||
/// Staging writers allocated ahead of need (BUS-01). A bus worker seals the same shapes of reply
|
||||
/// artifact every step -- the environment a 92,160-byte frame, a 65,536-byte memory image and an
|
||||
/// audio chunk of one of two lengths, the agent a 17,407-byte spike bitset -- and allocating one
|
||||
/// is a router round trip on the step's critical path. The pool remembers the last few
|
||||
/// `(content type, length)` shapes [`HandlerCtx::seal`] asked for and, after each reply, allocates
|
||||
/// a writer for every remembered shape that has none, off the critical path. A seal that finds a
|
||||
/// ready writer of its exact shape writes and seals it; one that does not allocates as before. A
|
||||
/// writer is an artifact like any other: unsealed, it is released when dropped, and the bytes it
|
||||
/// seals are the bytes written, so nothing a caller sees depends on the pool.
|
||||
#[derive(Default)]
|
||||
pub struct WriterPool {
|
||||
state: Mutex<PoolState>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PoolState {
|
||||
/// The most recent distinct shapes, newest last.
|
||||
recent: Vec<(String, u64)>,
|
||||
ready: Vec<((String, u64), flybus::ArtifactWriter)>,
|
||||
allocating: Vec<(String, u64)>,
|
||||
}
|
||||
|
||||
/// Shapes the pool keeps writers for: an environment's three reply artifacts, with the audio
|
||||
/// chunk's two lengths, and an agent's one.
|
||||
const POOL_SHAPES: usize = 4;
|
||||
|
||||
impl WriterPool {
|
||||
fn take(&self, content_type: &str, len: u64) -> Option<flybus::ArtifactWriter> {
|
||||
let mut st = self.state.lock().expect("never poisoned");
|
||||
let shape = (content_type.to_owned(), len);
|
||||
if let Some(at) = st.recent.iter().position(|s| *s == shape) {
|
||||
st.recent.remove(at);
|
||||
} else if st.recent.len() >= POOL_SHAPES {
|
||||
let gone = st.recent.remove(0);
|
||||
st.ready.retain(|(s, _)| *s != gone);
|
||||
}
|
||||
st.recent.push(shape.clone());
|
||||
let at = st.ready.iter().position(|(s, _)| *s == shape)?;
|
||||
Some(st.ready.swap_remove(at).1)
|
||||
}
|
||||
|
||||
/// Allocates, in the background, a writer for every remembered shape that has none.
|
||||
fn refill(self: &Arc<Self>, client: &flybus::Client) {
|
||||
let wanted: Vec<(String, u64)> = {
|
||||
let mut st = self.state.lock().expect("never poisoned");
|
||||
let wanted: Vec<_> = st
|
||||
.recent
|
||||
.iter()
|
||||
.filter(|s| !st.ready.iter().any(|(r, _)| r == *s) && !st.allocating.contains(s))
|
||||
.cloned()
|
||||
.collect();
|
||||
st.allocating.extend(wanted.iter().cloned());
|
||||
wanted
|
||||
};
|
||||
for shape in wanted {
|
||||
let (pool, client) = (self.clone(), client.clone());
|
||||
tokio::spawn(async move {
|
||||
let writer = client.artifacts().allocate(shape.1, &shape.0).await;
|
||||
let mut st = pool.state.lock().expect("never poisoned");
|
||||
st.allocating.retain(|s| *s != shape);
|
||||
if let Ok(writer) = writer
|
||||
&& st.recent.contains(&shape)
|
||||
{
|
||||
st.ready.push((shape, writer));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a domain request reached the shell, and so where its attachments are.
|
||||
|
|
@ -224,7 +296,20 @@ impl HandlerCtx<'_> {
|
|||
if self.is_local() {
|
||||
return Ok(flybus::Artifact::in_memory(content_type, bytes));
|
||||
}
|
||||
crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await
|
||||
// A writer allocated ahead for this shape saves the allocation's round trip ([`WriterPool`]).
|
||||
let Some(mut writer) = self.writers.take(content_type, bytes.len() as u64) else {
|
||||
let _span = crate::profile::span("shell.seal.allocated");
|
||||
return crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await;
|
||||
};
|
||||
let _span = crate::profile::span("shell.seal.pooled");
|
||||
use std::io::Write as _;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| crate::media::store_error("write", &e.to_string()))?;
|
||||
writer
|
||||
.seal()
|
||||
.await
|
||||
.map_err(|e| crate::media::store_error("seal", &e.message))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -422,6 +507,8 @@ struct Shell<E> {
|
|||
closed: std::sync::atomic::AtomicBool,
|
||||
/// The admitted mutations' tasks, awaited when the shell stops.
|
||||
running: Mutex<Vec<tokio::task::JoinHandle<()>>>,
|
||||
/// Reply writers allocated ahead (BUS-01).
|
||||
writers: Arc<WriterPool>,
|
||||
}
|
||||
|
||||
/// The local lane's hold on a shell.
|
||||
|
|
@ -492,6 +579,7 @@ pub fn serve<E: WorkerEndpoint>(
|
|||
admission: tokio::sync::Mutex::new(()),
|
||||
closed: std::sync::atomic::AtomicBool::new(false),
|
||||
running: Mutex::new(Vec::new()),
|
||||
writers: Arc::default(),
|
||||
});
|
||||
let local = LocalLane(Arc::new(ShellRef(shell.clone())));
|
||||
let task = tokio::spawn(run(shell, service, common));
|
||||
|
|
@ -829,8 +917,24 @@ async fn execute<E: WorkerEndpoint>(
|
|||
request: &request,
|
||||
client: &shell.client,
|
||||
incoming: &incoming,
|
||||
writers: &shell.writers,
|
||||
};
|
||||
if matches!(incoming, Incoming::Bus(_)) && long_method(&method) && blocking_allowed() {
|
||||
// A long bus request's handler runs with this worker thread handed over to blocking
|
||||
// work (BUS-01): the legacy agent's warm-up is seconds of synchronous computation, and
|
||||
// a Tokio worker blocked that long strands the tasks queued on it -- the shell's own
|
||||
// bus loop and its connection's reader among them -- so a duplicate arriving
|
||||
// mid-execution could not be answered IN_PROGRESS and `ipc-v1` section 6's resolution
|
||||
// of a slow Initialize ran out ("never resolved"). `block_in_place` moves those tasks
|
||||
// to another thread first. A step's handlers (milliseconds) run in place: the hand-over
|
||||
// is a thread wake-up of its own. The local lane's caller awaits the handler on its own
|
||||
// task and is unchanged.
|
||||
tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current().block_on(e.handle(ctx))
|
||||
})
|
||||
} else {
|
||||
e.handle(ctx).await
|
||||
}
|
||||
};
|
||||
// A deferred reply finishes here, with the endpoint's lock released.
|
||||
let outcome = match outcome {
|
||||
|
|
@ -851,7 +955,12 @@ async fn execute<E: WorkerEndpoint>(
|
|||
.map(|(name, artifact)| {
|
||||
let (name, artifact) = (name.clone(), artifact.clone());
|
||||
async move {
|
||||
if artifact.is_in_memory() {
|
||||
// An in-memory artifact is its own hold, and so is a sealed one this
|
||||
// worker holds explicitly (its own seal): a clone keeps it as long as the
|
||||
// cache needs it, without another router round trip (BUS-01). Only a
|
||||
// delivery's handle -- a forwarded request attachment -- needs a hold of
|
||||
// its own, so the delivery can be consumed.
|
||||
if artifact.is_in_memory() || artifact.is_hold() {
|
||||
return (name, artifact);
|
||||
}
|
||||
let task = tokio::spawn(async move {
|
||||
|
|
@ -868,6 +977,7 @@ async fn execute<E: WorkerEndpoint>(
|
|||
for retain in retains {
|
||||
holds.push(retain.await);
|
||||
}
|
||||
let cache_span = crate::profile::span("shell.record.cache");
|
||||
let cached = CachedReply::with_artifacts(outcome.clone(), holds);
|
||||
{
|
||||
let mut c = cache.lock().await;
|
||||
|
|
@ -878,7 +988,15 @@ async fn execute<E: WorkerEndpoint>(
|
|||
}
|
||||
}
|
||||
status.set_completed(request.request_id.clone());
|
||||
drop(cache_span);
|
||||
let reply_span = crate::profile::span("shell.reply");
|
||||
answer.send(outcome, &reply.artifacts).await;
|
||||
drop(reply_span);
|
||||
// The next step's writers, allocated while the caller goes on (bus requests only:
|
||||
// the lane seals nothing into the store).
|
||||
if matches!(incoming, Incoming::Bus(_)) {
|
||||
shell.writers.refill(&shell.client);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if e.mutation == MutationCertainty::None {
|
||||
|
|
@ -914,6 +1032,20 @@ async fn execute<E: WorkerEndpoint>(
|
|||
}
|
||||
}
|
||||
|
||||
/// The methods whose handlers can run for seconds: the warm-ups, the restores and the captures.
|
||||
/// A step's methods (Prepare, Advance, Commit: milliseconds) are not among them; neither are the
|
||||
/// read-only extensions.
|
||||
fn long_method(method: &str) -> bool {
|
||||
method.ends_with(".Initialize") || method.starts_with("State.") || method == "Agent.Rollback"
|
||||
}
|
||||
|
||||
/// Whether this thread is a worker of a multi-thread Tokio runtime, where
|
||||
/// [`tokio::task::block_in_place`] is allowed.
|
||||
fn blocking_allowed() -> bool {
|
||||
tokio::runtime::Handle::try_current()
|
||||
.is_ok_and(|h| h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread)
|
||||
}
|
||||
|
||||
/// The retention class of every method name the contracts define.
|
||||
fn classify_default(method: &str) -> Option<OpClass> {
|
||||
match method {
|
||||
|
|
|
|||
|
|
@ -296,6 +296,61 @@ pub fn place_workers(workers: usize) -> Option<Placement> {
|
|||
Some(placement)
|
||||
}
|
||||
|
||||
/// [`place_workers`] with a plan made elsewhere (BUS-01): a separate agent process is handed its
|
||||
/// placement by the launcher, which split the service's cpuset, instead of splitting its own mask.
|
||||
/// Confines the calling thread (and every thread it spawns afterwards) to `placement.host` and
|
||||
/// pins worker `i` of every pool created afterwards to `placement.workers[i - 1]`. False, and
|
||||
/// nothing changed, when the kernel refuses the host set, when a placement is already recorded,
|
||||
/// or off Linux. Placement decides only the CPU: no result depends on it.
|
||||
pub fn apply_placement(placement: &Placement) -> bool {
|
||||
if WORKER_CPUS.get().is_some() || placement.host.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if !affinity::set_current(&placement.host) {
|
||||
return false;
|
||||
}
|
||||
WORKER_CPUS.set(placement.workers.clone()).is_ok()
|
||||
}
|
||||
|
||||
/// The CPUs the calling thread may run on (`sched_getaffinity`); `None` off Linux.
|
||||
pub fn allowed_cpus() -> Option<Vec<usize>> {
|
||||
affinity::allowed()
|
||||
}
|
||||
|
||||
/// Confines the calling thread, and every thread it spawns afterwards, to `cpus`; false (and
|
||||
/// unchanged) if the kernel refuses or off Linux.
|
||||
pub fn confine_current(cpus: &[usize]) -> bool {
|
||||
affinity::set_current(cpus)
|
||||
}
|
||||
|
||||
/// A CPU list as `taskset` and cpusets write it: `1,3,5-7`.
|
||||
pub fn parse_cpu_list(value: &str) -> Option<Vec<usize>> {
|
||||
let mut cpus = Vec::new();
|
||||
for part in value.split(',').map(str::trim).filter(|p| !p.is_empty()) {
|
||||
match part.split_once('-') {
|
||||
Some((a, b)) => {
|
||||
let (a, b): (usize, usize) = (a.trim().parse().ok()?, b.trim().parse().ok()?);
|
||||
if a > b {
|
||||
return None;
|
||||
}
|
||||
cpus.extend(a..=b);
|
||||
}
|
||||
None => cpus.push(part.parse().ok()?),
|
||||
}
|
||||
}
|
||||
cpus.sort_unstable();
|
||||
cpus.dedup();
|
||||
(!cpus.is_empty()).then_some(cpus)
|
||||
}
|
||||
|
||||
/// The inverse of [`parse_cpu_list`], without ranges: `1,3,5`.
|
||||
pub fn format_cpu_list(cpus: &[usize]) -> String {
|
||||
cpus.iter()
|
||||
.map(usize::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod affinity {
|
||||
/// The CPUs the calling thread may run on.
|
||||
|
|
@ -467,6 +522,16 @@ mod tests {
|
|||
assert_eq!(ran.load(Ordering::Relaxed), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_lists_parse_as_taskset_writes_them() {
|
||||
assert_eq!(parse_cpu_list("1,3,5,7"), Some(vec![1, 3, 5, 7]));
|
||||
assert_eq!(parse_cpu_list("9-11, 1 ,10"), Some(vec![1, 9, 10, 11]));
|
||||
assert_eq!(parse_cpu_list(""), None);
|
||||
assert_eq!(parse_cpu_list("3-1"), None);
|
||||
assert_eq!(parse_cpu_list("x"), None);
|
||||
assert_eq!(format_cpu_list(&[1, 3, 5]), "1,3,5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_split_gives_each_worker_a_cpu_and_the_host_the_rest() {
|
||||
// The release's flysim cpuset, four whole cores, four sweep threads.
|
||||
|
|
|
|||
|
|
@ -174,7 +174,13 @@ let kept = frame.retain().await?; // an independent explicit hold
|
|||
```
|
||||
|
||||
- `Artifact` is a read-only, cloneable handle on one owner: a delivery or an explicit hold.
|
||||
Its last clone (including any `ArtifactFile`) releases that owner.
|
||||
Its last clone (including any `ArtifactFile`) releases that owner. `is_hold()` is true for an
|
||||
explicit hold (a sealed writer, a `retain`): keeping a clone of one keeps the bytes, and costs
|
||||
no delivery credit.
|
||||
- A handle that came in a delivery opens and reads without a router round trip: the delivery
|
||||
names each attachment's read location (bus-v1 section 12, amendment 2026-10-01). Any other
|
||||
handle asks the router (`artifact.open`) first. Up to 256 KiB, `read_all()` reads in place
|
||||
rather than on the blocking pool.
|
||||
- `ArtifactWriter` is unique. Dropping it unsealed releases the staging storage. Writes past
|
||||
the allocated length fail. Unwritten bytes read as zeros.
|
||||
- Sealing copies staging into a fresh read-only (0444) file and unlinks staging. A descriptor
|
||||
|
|
@ -272,7 +278,8 @@ before admission are `not-dispatched`. A command in flight when the connection i
|
|||
call returns `routed:false` and creates no roots. Unregistering a service fails its queued
|
||||
calls; dispatched calls can still be answered while a `Request` or `Responder` retains reply
|
||||
capability. Both cancel/consume orderings retire cleanly.
|
||||
- **Seals** copy (and hash, when a digest was given) on Tokio's blocking pool, alongside the
|
||||
- **Seals** copy (and hash, when a digest was given) on Tokio's blocking pool (up to 256 KiB in
|
||||
place on the reader, which on the store's tmpfs is cheaper than the hop), alongside the
|
||||
connection's reader, so a large copy does not hold up that client's releases. If the writer is released or disconnects
|
||||
mid-seal, the copy is discarded and the artifact is never published.
|
||||
|
||||
|
|
@ -321,6 +328,10 @@ before admission are `not-dispatched`. A command in flight when the connection i
|
|||
final release atomically retires the correlation and caller slot and emits `call.failed`
|
||||
with dispatch `dispatched`: `CALL_GONE` while the route remains live, or `NO_SERVICE` after
|
||||
route loss.
|
||||
11. **Read locations in deliveries** (amendment 2026-10-01, BUS-01). Every attachment of an
|
||||
`rpc.request`, `rpc.result` or `topic.message` delivery carries `readLocation`, the location
|
||||
`artifact.open` would return under that delivery's ownership; a client attachment that carries
|
||||
one is refused as an unknown field. `wire::CONTRACT` (and so `contractDigest`) says so.
|
||||
|
||||
## Limitations
|
||||
|
||||
|
|
|
|||
|
|
@ -52,22 +52,29 @@ pub(crate) fn attachment_list(
|
|||
name: (*name).to_owned(),
|
||||
reference: a.reference.as_ref().clone(),
|
||||
owner_id: owner.id.clone(),
|
||||
read_location: None,
|
||||
});
|
||||
keep.push(owner.clone());
|
||||
}
|
||||
Ok((atts, keep))
|
||||
}
|
||||
|
||||
fn find(
|
||||
list: &[(String, ArtifactRef)],
|
||||
guard: &Arc<OwnerGuard>,
|
||||
name: &str,
|
||||
) -> Result<Artifact, BusError> {
|
||||
/// One attachment of a delivery, with the read location the router issued for it (bus-v1
|
||||
/// section 12 amendment 2026-10-01; `None` from a router that issues none).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Delivered {
|
||||
pub name: String,
|
||||
pub reference: ArtifactRef,
|
||||
pub location: Option<Arc<Location>>,
|
||||
}
|
||||
|
||||
fn find(list: &[Delivered], guard: &Arc<OwnerGuard>, name: &str) -> Result<Artifact, BusError> {
|
||||
list.iter()
|
||||
.find(|(n, _)| n == name)
|
||||
.map(|(_, r)| Artifact {
|
||||
reference: Arc::new(r.clone()),
|
||||
.find(|d| d.name == name)
|
||||
.map(|d| Artifact {
|
||||
reference: Arc::new(d.reference.clone()),
|
||||
holder: Holder::Bus(guard.clone()),
|
||||
location: d.location.clone(),
|
||||
})
|
||||
.ok_or_else(|| BusError::invalid(format!("no attachment named {name:?}")))
|
||||
}
|
||||
|
|
@ -88,6 +95,9 @@ fn find(
|
|||
pub struct Artifact {
|
||||
pub(crate) reference: Arc<ArtifactRef>,
|
||||
pub(crate) holder: Holder,
|
||||
/// Where the bytes are, when the router said so in the delivery that granted this handle:
|
||||
/// [`Artifact::open`] then needs no `artifact.open` round trip (BUS-01).
|
||||
pub(crate) location: Option<Arc<Location>>,
|
||||
}
|
||||
|
||||
/// What keeps an artifact's bytes alive.
|
||||
|
|
@ -129,6 +139,7 @@ impl Artifact {
|
|||
digest: None,
|
||||
}),
|
||||
holder: Holder::Memory(bytes),
|
||||
location: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -154,6 +165,7 @@ impl Artifact {
|
|||
Ok(Artifact {
|
||||
reference: self.reference.clone(),
|
||||
holder: Holder::Memory(bytes.into()),
|
||||
location: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -162,6 +174,14 @@ impl Artifact {
|
|||
matches!(self.holder, Holder::Memory(_))
|
||||
}
|
||||
|
||||
/// True when this handle's owner is an explicit hold of its own connection -- a sealed
|
||||
/// writer or a [`Artifact::retain`] -- rather than a delivery. Keeping a clone of such a handle
|
||||
/// keeps the bytes as long as a [`Artifact::retain`] would, and consumes no delivery credit,
|
||||
/// so a holder that only needs the bytes to stay alive need not take another hold (BUS-01).
|
||||
pub fn is_hold(&self) -> bool {
|
||||
matches!(&self.holder, Holder::Bus(owner) if !owner.delivery)
|
||||
}
|
||||
|
||||
/// The bytes of an in-memory artifact, without a copy; `None` for a sealed one.
|
||||
pub fn memory(&self) -> Option<&Arc<[u8]>> {
|
||||
match &self.holder {
|
||||
|
|
@ -190,10 +210,16 @@ impl Artifact {
|
|||
});
|
||||
}
|
||||
};
|
||||
let shared = &owner.conn.shared;
|
||||
// The delivery that granted this handle said where the bytes are (BUS-01); otherwise the
|
||||
// router is asked. Either way the location is store-issued and resolved below the store
|
||||
// root, and the owner this handle keeps holds the bytes while the file is open.
|
||||
let loc = match &self.location {
|
||||
Some(loc) => loc.as_ref().clone(),
|
||||
None => {
|
||||
let mut body = Map::new();
|
||||
body.insert("ref".into(), self.reference.to_json());
|
||||
body.insert("ownerId".into(), owner.id.clone().into());
|
||||
let shared = &owner.conn.shared;
|
||||
let reply = shared
|
||||
.command(
|
||||
"artifact.open",
|
||||
|
|
@ -203,7 +229,9 @@ impl Artifact {
|
|||
Hook::None,
|
||||
)
|
||||
.await?;
|
||||
let loc = Location::from_json(Fields::of(&reply.value, "reply").value("readLocation")?)?;
|
||||
Location::from_json(Fields::of(&reply.value, "reply").value("readLocation")?)?
|
||||
}
|
||||
};
|
||||
if loc.store_id != self.reference.store_id {
|
||||
return Err(BusError::new(
|
||||
ErrorCode::ArtifactGone,
|
||||
|
|
@ -229,12 +257,21 @@ impl Artifact {
|
|||
})
|
||||
}
|
||||
|
||||
/// Reads the whole artifact (on the blocking pool; an in-memory one is copied in place).
|
||||
/// Reads the whole artifact: on the blocking pool, or in place up to
|
||||
/// [`crate::store::INLINE_IO_BYTES`] (a tmpfs read of that size is cheaper than the pool hop);
|
||||
/// an in-memory one is copied in place.
|
||||
pub async fn read_all(&self) -> Result<Vec<u8>, BusError> {
|
||||
if let Holder::Memory(bytes) = &self.holder {
|
||||
return Ok(bytes.to_vec());
|
||||
}
|
||||
let mut file = self.open().await?;
|
||||
if file.len() <= crate::store::INLINE_IO_BYTES {
|
||||
let mut out = Vec::with_capacity(file.len() as usize);
|
||||
return file
|
||||
.read_to_end(&mut out)
|
||||
.map(|_| out)
|
||||
.map_err(|e| BusError::new(ErrorCode::StoreFailure, e.to_string()));
|
||||
}
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut out = Vec::with_capacity(file.len() as usize);
|
||||
file.read_to_end(&mut out).map(|_| out)
|
||||
|
|
@ -268,6 +305,7 @@ impl Artifact {
|
|||
Extra::Owner(owner) => Ok(Artifact {
|
||||
reference: self.reference.clone(),
|
||||
holder: Holder::Bus(owner),
|
||||
location: self.location.clone(),
|
||||
}),
|
||||
_ => Err(BusError::lost("retain reply without an owner")),
|
||||
}
|
||||
|
|
@ -365,6 +403,7 @@ impl ArtifactWriter {
|
|||
Ok(Artifact {
|
||||
reference: Arc::new(reference),
|
||||
holder: Holder::Bus(self.owner.clone()),
|
||||
location: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -405,7 +444,7 @@ pub struct Message {
|
|||
pub(crate) topic_sequence: u64,
|
||||
pub(crate) replaced: u64,
|
||||
pub(crate) payload: Map<String, Value>,
|
||||
pub(crate) attachments: Vec<(String, ArtifactRef)>,
|
||||
pub(crate) attachments: Vec<Delivered>,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
|
|
@ -432,7 +471,7 @@ impl Message {
|
|||
&self.payload
|
||||
}
|
||||
pub fn attachment_names(&self) -> impl Iterator<Item = &str> {
|
||||
self.attachments.iter().map(|(n, _)| n.as_str())
|
||||
self.attachments.iter().map(|d| d.name.as_str())
|
||||
}
|
||||
/// An artifact handle sharing this delivery's guard.
|
||||
pub fn artifact(&self, name: &str) -> Result<Artifact, BusError> {
|
||||
|
|
@ -451,7 +490,7 @@ pub struct Request {
|
|||
pub(crate) service_incarnation: String,
|
||||
pub(crate) method: String,
|
||||
pub(crate) payload: Map<String, Value>,
|
||||
pub(crate) attachments: Vec<(String, ArtifactRef)>,
|
||||
pub(crate) attachments: Vec<Delivered>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
|
|
@ -554,7 +593,7 @@ pub struct RpcResult {
|
|||
pub(crate) responder: Identity,
|
||||
pub(crate) service_incarnation: String,
|
||||
pub(crate) outcome: Map<String, Value>,
|
||||
pub(crate) attachments: Vec<(String, ArtifactRef)>,
|
||||
pub(crate) attachments: Vec<Delivered>,
|
||||
}
|
||||
|
||||
impl RpcResult {
|
||||
|
|
|
|||
|
|
@ -20,7 +20,8 @@ use tokio::sync::{Notify, mpsc, oneshot, watch};
|
|||
|
||||
use super::SessionInfo;
|
||||
use super::handles::{
|
||||
CallGuard, Message, OwnerGuard, ReplyGuard, Request, RpcResult, ServiceGuard, SubscriptionGuard,
|
||||
CallGuard, Delivered, Message, OwnerGuard, ReplyGuard, Request, RpcResult, ServiceGuard,
|
||||
SubscriptionGuard,
|
||||
};
|
||||
use crate::error::{BusError, Dispatch, ErrorCode};
|
||||
use crate::transport::Transport;
|
||||
|
|
@ -388,9 +389,16 @@ fn next_outgoing(shared: &Shared) -> Next {
|
|||
};
|
||||
st.next_msg += 1;
|
||||
let n = st.next_msg;
|
||||
let mut env = Envelope::new(serial_id("msg", n), Kind::Command, cmd.op, cmd.body.clone());
|
||||
env.attachments = cmd.attachments.clone();
|
||||
match env.encode() {
|
||||
let id = serial_id("msg", n);
|
||||
let head = crate::wire::EnvelopeHead {
|
||||
major: crate::wire::MAJOR,
|
||||
minor: crate::wire::MINOR,
|
||||
id: &id,
|
||||
reply_to: None,
|
||||
kind: Kind::Command,
|
||||
op: cmd.op,
|
||||
};
|
||||
match crate::wire::encode_parts(&head, &cmd.body, &cmd.attachments) {
|
||||
Ok(bytes) => {
|
||||
st.pending.insert(
|
||||
n,
|
||||
|
|
@ -786,7 +794,7 @@ fn complete(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn attachments(env: &Envelope, delivery_id: &str) -> Result<Vec<(String, ArtifactRef)>, WireError> {
|
||||
fn attachments(env: &Envelope, delivery_id: &str) -> Result<Vec<Delivered>, WireError> {
|
||||
env.attachments
|
||||
.iter()
|
||||
.map(|a| {
|
||||
|
|
@ -795,7 +803,20 @@ fn attachments(env: &Envelope, delivery_id: &str) -> Result<Vec<(String, Artifac
|
|||
"delivery attachment owner is not the delivery".into(),
|
||||
));
|
||||
}
|
||||
Ok((a.name.clone(), a.reference.clone()))
|
||||
if a
|
||||
.read_location
|
||||
.as_ref()
|
||||
.is_some_and(|loc| loc.store_id != a.reference.store_id)
|
||||
{
|
||||
return Err(WireError(
|
||||
"delivery attachment read location names another store".into(),
|
||||
));
|
||||
}
|
||||
Ok(Delivered {
|
||||
name: a.name.clone(),
|
||||
reference: a.reference.clone(),
|
||||
location: a.read_location.clone().map(Arc::new),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -304,18 +304,41 @@ async fn read_loop<R: AsyncRead + Unpin>(
|
|||
return;
|
||||
}
|
||||
};
|
||||
// A read location is the router's to issue, in a delivery (BUS-01 amendment): a client
|
||||
// attachment that carries one is malformed.
|
||||
if env.attachments.iter().any(|a| a.read_location.is_some()) {
|
||||
inner.with_state(|s| {
|
||||
s.reject_frame(c, "attachment: unknown field \"readLocation\"".into())
|
||||
});
|
||||
return;
|
||||
}
|
||||
let was_hello = !negotiated && env.op == "bus.hello";
|
||||
match inner.with_state(|s| s.handle(c, env)) {
|
||||
Outcome::Done => {}
|
||||
Outcome::Close => return,
|
||||
Outcome::Allocate(job) => {
|
||||
let (i, serial, len) = (inner.clone(), job.serial, job.len);
|
||||
let created =
|
||||
// A small staging file (a frame, a memory image) is created in place: on the
|
||||
// store's tmpfs that is a few microseconds, less than the hop to the blocking pool
|
||||
// and back, which an artifact-per-call protocol pays on its critical path
|
||||
// (BUS-01). A large one still goes to the blocking pool.
|
||||
let created = if len <= crate::store::INLINE_IO_BYTES {
|
||||
i.store.create_staging(serial, len)
|
||||
} else {
|
||||
tokio::task::spawn_blocking(move || i.store.create_staging(serial, len))
|
||||
.await
|
||||
.unwrap_or_else(|e| Err(io::Error::other(e)));
|
||||
.unwrap_or_else(|e| Err(io::Error::other(e)))
|
||||
};
|
||||
inner.with_state(|s| s.finish_allocate(job, created));
|
||||
}
|
||||
Outcome::Seal(job) if job.len <= crate::store::INLINE_IO_BYTES => {
|
||||
// A small seal copies in place, for the same reason; the connection's reader
|
||||
// waits for it as it waits for any command (BUS-01). The outcome is the
|
||||
// spawned path's, step for step.
|
||||
let result = inner.store.seal(job.serial, job.len, job.digest.as_deref());
|
||||
inner.store.remove(&crate::store::staging_rel(job.serial));
|
||||
inner.with_state(|s| s.finish_seal(job, result));
|
||||
}
|
||||
Outcome::Seal(job) => {
|
||||
let inner = inner.clone();
|
||||
tokio::spawn(async move {
|
||||
|
|
|
|||
|
|
@ -442,12 +442,21 @@ fn dedup(serials: Vec<u64>) -> Vec<u64> {
|
|||
serials.into_iter().filter(|s| seen.insert(*s)).collect()
|
||||
}
|
||||
|
||||
/// A delivery's attachments, each with the read location its delivery ownership grants
|
||||
/// (bus-v1 section 12 amendment 2026-10-01): every attachment the router admitted is a sealed
|
||||
/// artifact of this store, read at its sealed path.
|
||||
fn attachments_with_owner(list: &[(String, ArtifactRef)], owner: &str) -> Vec<Attachment> {
|
||||
list.iter()
|
||||
.map(|(name, r)| Attachment {
|
||||
name: name.clone(),
|
||||
reference: r.clone(),
|
||||
owner_id: owner.to_owned(),
|
||||
read_location: crate::wire::parse_serial_id("a", &r.artifact_id).map(|serial| {
|
||||
crate::wire::Location {
|
||||
store_id: r.store_id.clone(),
|
||||
relative_path: sealed_rel(serial),
|
||||
}
|
||||
}),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
|
@ -458,10 +467,18 @@ fn frame_len(
|
|||
body: Map<String, Value>,
|
||||
attachments: Vec<Attachment>,
|
||||
) -> usize {
|
||||
let mut env = Envelope::new(serial_id("bus", MAX_SERIAL), kind, op, body);
|
||||
env.attachments = attachments;
|
||||
serde_json::to_vec(&env.to_value())
|
||||
let id = serial_id("bus", MAX_SERIAL);
|
||||
let head = crate::wire::EnvelopeHead {
|
||||
major: crate::wire::MAJOR,
|
||||
minor: crate::wire::MINOR,
|
||||
id: &id,
|
||||
reply_to: None,
|
||||
kind,
|
||||
op,
|
||||
};
|
||||
crate::wire::encode_parts(&head, &body, &attachments)
|
||||
.map(|b| b.len())
|
||||
// Over the limit or unencodable: the caller refuses it either way.
|
||||
.unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -32,6 +32,11 @@ pub(crate) fn staging_rel(serial: u64) -> String {
|
|||
format!("staging/a-{serial}")
|
||||
}
|
||||
|
||||
/// Store file operations up to this size run in place on the async thread rather than on the
|
||||
/// blocking pool: creating or sealing a staging file, and reading a sealed one whole. The store is
|
||||
/// meant to be tmpfs, where such a copy takes microseconds and the pool hop costs more (BUS-01).
|
||||
pub const INLINE_IO_BYTES: u64 = 256 * 1024;
|
||||
|
||||
pub(crate) fn sealed_rel(serial: u64) -> String {
|
||||
format!("sealed/a-{serial}")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ pub const GENERATION: u64 = 1;
|
|||
pub const CONTRACT: &str = "flybus 1.0
|
||||
frame: u32le length, 1..=65536 bytes of strict UTF-8 JSON
|
||||
envelope: protocol major minor id replyTo kind op body attachments
|
||||
attachment: name ref ownerId
|
||||
attachment: name ref ownerId [readLocation(storeId relativePath): in a router delivery only]
|
||||
ref: storeId artifactId generation byteLength contentType digest
|
||||
reply: ok value | ok error{code message dispatch}
|
||||
bus.hello: clientId clientIncarnation supportedMajors -> routerId connectionId selectedMajor selectedMinor contractDigest limits
|
||||
|
|
@ -293,6 +293,12 @@ impl<'a> Fields<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
/// A field that may be absent; read (so [`Fields::finish`] accepts it) when present.
|
||||
pub fn optional(&mut self, key: &'static str) -> Option<&'a Value> {
|
||||
self.seen.insert(key);
|
||||
self.map.get(key)
|
||||
}
|
||||
|
||||
pub fn value(&mut self, key: &'static str) -> Result<&'a Value, WireError> {
|
||||
self.seen.insert(key);
|
||||
match self.map.get(key) {
|
||||
|
|
@ -472,6 +478,10 @@ pub struct Attachment {
|
|||
pub name: String,
|
||||
pub reference: ArtifactRef,
|
||||
pub owner_id: String,
|
||||
/// In a router delivery only (amendment 2026-10-01, BUS-01): the read location the
|
||||
/// delivery's ownership grants, so the recipient reads the bytes without an `artifact.open`
|
||||
/// round trip. A client never sends one; the router refuses an attachment that carries it.
|
||||
pub read_location: Option<Location>,
|
||||
}
|
||||
|
||||
impl Attachment {
|
||||
|
|
@ -480,6 +490,9 @@ impl Attachment {
|
|||
m.insert("name".into(), self.name.clone().into());
|
||||
m.insert("ref".into(), self.reference.to_json());
|
||||
m.insert("ownerId".into(), self.owner_id.clone().into());
|
||||
if let Some(location) = &self.read_location {
|
||||
m.insert("readLocation".into(), location.to_json());
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
|
|
@ -488,11 +501,13 @@ impl Attachment {
|
|||
let name = f.id("name")?;
|
||||
let reference = ArtifactRef::from_json(f.value("ref")?)?;
|
||||
let owner_id = f.id("ownerId")?;
|
||||
let read_location = f.optional("readLocation").map(Location::from_json).transpose()?;
|
||||
f.finish()?;
|
||||
Ok(Attachment {
|
||||
name,
|
||||
reference,
|
||||
owner_id,
|
||||
read_location,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -640,7 +655,7 @@ impl Envelope {
|
|||
return err("envelope: op must be 1..=64 of [a-z.]");
|
||||
}
|
||||
let op = op.to_owned();
|
||||
let body = f.object("body")?.clone();
|
||||
f.object("body")?;
|
||||
let raw = f.array("attachments", 0, MAX_ATTACHMENTS)?;
|
||||
let mut attachments = Vec::with_capacity(raw.len());
|
||||
let mut names = HashSet::new();
|
||||
|
|
@ -652,6 +667,14 @@ impl Envelope {
|
|||
attachments.push(a);
|
||||
}
|
||||
f.finish()?;
|
||||
// The body moves out of the parsed tree rather than being copied (BUS-01).
|
||||
let body = match v {
|
||||
Value::Object(mut m) => match m.remove("body") {
|
||||
Some(Value::Object(body)) => body,
|
||||
_ => return err("envelope: body must be an object"),
|
||||
},
|
||||
_ => return err("envelope must be an object"),
|
||||
};
|
||||
Ok(Envelope {
|
||||
major,
|
||||
minor,
|
||||
|
|
@ -686,7 +709,65 @@ impl Envelope {
|
|||
|
||||
/// Serializes, refusing anything over [`MAX_ENVELOPE_BYTES`].
|
||||
pub fn encode(&self) -> Result<Vec<u8>, WireError> {
|
||||
let bytes = serde_json::to_vec(&self.to_value()).map_err(|e| WireError(e.to_string()))?;
|
||||
encode_parts(
|
||||
&EnvelopeHead {
|
||||
major: self.major,
|
||||
minor: self.minor,
|
||||
id: &self.id,
|
||||
reply_to: self.reply_to.as_deref(),
|
||||
kind: self.kind,
|
||||
op: &self.op,
|
||||
},
|
||||
&self.body,
|
||||
&self.attachments,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// An envelope's scalar fields, borrowed, for [`encode_parts`].
|
||||
pub struct EnvelopeHead<'a> {
|
||||
pub major: u64,
|
||||
pub minor: u64,
|
||||
pub id: &'a str,
|
||||
pub reply_to: Option<&'a str>,
|
||||
pub kind: Kind,
|
||||
pub op: &'a str,
|
||||
}
|
||||
|
||||
/// Serializes an envelope from borrowed parts -- the same bytes as [`Envelope::to_value`] in its
|
||||
/// field order -- without copying the body into a value tree first (BUS-01: the body is the one
|
||||
/// large part of a message, and it used to be copied twice on the way out). Refuses anything over
|
||||
/// [`MAX_ENVELOPE_BYTES`].
|
||||
pub fn encode_parts(
|
||||
head: &EnvelopeHead<'_>,
|
||||
body: &Map<String, Value>,
|
||||
attachments: &[Attachment],
|
||||
) -> Result<Vec<u8>, WireError> {
|
||||
#[derive(serde::Serialize)]
|
||||
struct Out<'a> {
|
||||
protocol: &'static str,
|
||||
major: u64,
|
||||
minor: u64,
|
||||
id: &'a str,
|
||||
#[serde(rename = "replyTo")]
|
||||
reply_to: Option<&'a str>,
|
||||
kind: &'static str,
|
||||
op: &'a str,
|
||||
body: &'a Map<String, Value>,
|
||||
attachments: Vec<Value>,
|
||||
}
|
||||
let out = Out {
|
||||
protocol: PROTOCOL,
|
||||
major: head.major,
|
||||
minor: head.minor,
|
||||
id: head.id,
|
||||
reply_to: head.reply_to,
|
||||
kind: head.kind.as_str(),
|
||||
op: head.op,
|
||||
body,
|
||||
attachments: attachments.iter().map(Attachment::to_json).collect(),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&out).map_err(|e| WireError(e.to_string()))?;
|
||||
if bytes.len() > MAX_ENVELOPE_BYTES {
|
||||
return err(format!(
|
||||
"envelope of {} bytes exceeds {MAX_ENVELOPE_BYTES}",
|
||||
|
|
@ -694,9 +775,9 @@ impl Envelope {
|
|||
));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Framing
|
||||
|
||||
|
|
|
|||
|
|
@ -768,7 +768,71 @@ async fn issued_locations_are_relative_and_contained(via: Via) {
|
|||
);
|
||||
}
|
||||
|
||||
/// Amendment 2026-10-01 (BUS-01): every attachment of a delivery names the read location its
|
||||
/// delivery ownership grants -- the store's sealed path of that artifact -- so the recipient reads
|
||||
/// it without an `artifact.open` round trip; the SDK's handle uses it.
|
||||
async fn deliveries_carry_the_read_location_their_ownership_grants(via: Via) {
|
||||
let e = env(via).await;
|
||||
let caller = e.client("caller").await;
|
||||
let mut server = e.raw_hello("server").await;
|
||||
assert_eq!(
|
||||
code(
|
||||
&server
|
||||
.call(
|
||||
"service.register",
|
||||
json!({"name": "agent.located", "maxQueued": 4, "maxInFlight": 4})
|
||||
)
|
||||
.await
|
||||
),
|
||||
"OK"
|
||||
);
|
||||
let art = sealed(&caller, b"located bytes", "application/octet-stream").await;
|
||||
let _pending = caller
|
||||
.call("agent.located", None, "Look", obj(json!({})), &[("in", &art)])
|
||||
.await
|
||||
.unwrap();
|
||||
let request = within("the request", server.event()).await;
|
||||
let attachment = &request.attachments[0];
|
||||
let location = attachment
|
||||
.read_location
|
||||
.as_ref()
|
||||
.expect("a delivery's attachment names where its bytes are");
|
||||
assert_eq!(location.store_id, e.router.store_id());
|
||||
assert_eq!(
|
||||
location.relative_path,
|
||||
format!("sealed/{}", attachment.reference.artifact_id)
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(e.router.store_dir().join(&location.relative_path)).unwrap(),
|
||||
b"located bytes"
|
||||
);
|
||||
// The SDK's handle on a delivered artifact reads through the same location.
|
||||
let other = e.client("other").await;
|
||||
other
|
||||
.declare_topic("t.located", Retained::None)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut sub = caller
|
||||
.subscribe("t.located", SubscriptionConfig::bounded())
|
||||
.await
|
||||
.unwrap();
|
||||
other
|
||||
.publish("t.located", obj(json!({})), &[("frame", &art_of(&other).await)])
|
||||
.await
|
||||
.unwrap();
|
||||
let message = within("the message", sub.next()).await.unwrap();
|
||||
assert_eq!(
|
||||
message.artifact("frame").unwrap().read_all().await.unwrap(),
|
||||
b"other bytes"
|
||||
);
|
||||
}
|
||||
|
||||
async fn art_of(client: &flybus::Client) -> flybus::Artifact {
|
||||
sealed(client, b"other bytes", "application/octet-stream").await
|
||||
}
|
||||
|
||||
both_transports!(
|
||||
deliveries_carry_the_read_location_their_ownership_grants,
|
||||
allocate_write_seal_open_roundtrip_and_mismatches,
|
||||
seal_is_immutable_despite_a_stale_writable_handle,
|
||||
extracted_artifact_outlives_the_message_it_came_from,
|
||||
|
|
|
|||
|
|
@ -413,6 +413,7 @@ async fn client_strictly_validates_hello_envelope() {
|
|||
digest: None,
|
||||
},
|
||||
owner_id: "own-1".into(),
|
||||
read_location: None,
|
||||
}),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,6 +117,11 @@ async fn malformed_frames_close_the_connection(via: Via) {
|
|||
major["major"] = json!(2);
|
||||
let mut not_flybus = publish("msg-2");
|
||||
not_flybus["protocol"] = json!("flybusx");
|
||||
// A read location is the router's to issue, in a delivery (BUS-01): never from a client.
|
||||
let mut located = publish("msg-2");
|
||||
let mut located_att = att("a");
|
||||
located_att["readLocation"] = json!({"storeId": "s", "relativePath": "sealed/a-1"});
|
||||
located["attachments"] = json!([located_att]);
|
||||
|
||||
let cases: Vec<(&str, Vec<u8>)> = vec![
|
||||
("nested duplicate key", br#"{"protocol":"flybus","major":1,"minor":0,"id":"msg-2","replyTo":null,"kind":"command","op":"publish","body":{"topic":"t.x","payload":{"a":{"b":1,"b":2}}},"attachments":[]}"#.to_vec()),
|
||||
|
|
@ -133,6 +138,7 @@ async fn malformed_frames_close_the_connection(via: Via) {
|
|||
("non-null replyTo", text(reply_to).into_bytes()),
|
||||
("wrong major after hello", text(major).into_bytes()),
|
||||
("wrong protocol", text(not_flybus).into_bytes()),
|
||||
("a client attachment with a readLocation", text(located).into_bytes()),
|
||||
];
|
||||
for (i, (what, bytes)) in cases.into_iter().enumerate() {
|
||||
let mut raw = e.raw_hello(&format!("bad-{i}")).await;
|
||||
|
|
|
|||
|
|
@ -96,7 +96,10 @@ snapshot is consistent; the write and the fsyncs happen on the store thread.
|
|||
| `pacing` | absolute frame deadlines, `loop.speed`, the lag accounting, the realtime window |
|
||||
| `snapshot` | the feed protocol types, the exact framing, the spike bitset, the audio conversion |
|
||||
| `feed` | the WebSocket listener and the client hello |
|
||||
| `api` | the control routes, built from one route table |
|
||||
| `api` | the control routes, built from one route table, over a `ControlBackend` |
|
||||
| `control` | what each control request does: validation, the command, the status code (both transports) |
|
||||
| `controlbus` | the control API as flybus services, the grant table, the encoding (`FLY_CONTROL_VIA=bus`) |
|
||||
| `bus` | the embedded router shared by the feed and control when either rides the bus |
|
||||
| `ratelimit` | the per-minute sugar budget and the no-overlap rule |
|
||||
| `store` | the `FLYSIM01` envelope, atomic commits, generations, milestone archives, restore order |
|
||||
| `eventlog` | append-only JSONL plus the in-memory tail the feed and `/events` read |
|
||||
|
|
@ -202,6 +205,11 @@ router is built from it, and `tests/api.rs` asserts both over the table and agai
|
|||
router for thirteen spellings of such a route. The prototype's `manualButtons` field and its
|
||||
`learn: false` suppression are dropped, not disabled.
|
||||
|
||||
On the bus (`FLY_CONTROL_VIA=bus`) the same guarantee is a grant table: no control service has
|
||||
an input method, every grant is an exact call on a control service, only the in-process host
|
||||
registers, and the policy is closed (`controlbus`, `crates/fly-control-edge/tests/grants.rs`,
|
||||
`docs/design/flybus.md` "Control over the bus").
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! The control API, `http://127.0.0.1:7401`.
|
||||
//! The control API, `http://127.0.0.1:7401`: the HTTP layer.
|
||||
//!
|
||||
//! Binding contract: `docs/control-api.md`. Behavioural reference:
|
||||
//! `packages/feed/src/fake/server.ts`, which this must be a drop-in replacement for — same
|
||||
|
|
@ -9,8 +9,15 @@
|
|||
//!
|
||||
//! [`ROUTES`] is the entire surface; the router is built from it, so a route cannot be added
|
||||
//! without appearing in that table, and `tests/api.rs` asserts on the table itself.
|
||||
//!
|
||||
//! This module only turns HTTP into a [`ControlRequest`] and a [`ControlReply`] back into HTTP.
|
||||
//! What a request does is [`crate::control::handle`]'s, reached through a [`ControlBackend`]:
|
||||
//! [`AppState`] calls it in this process (`control.via = direct`), and `fly-control-edge` calls
|
||||
//! it across the bus (`control.via = bus`, [`crate::controlbus`]). The extractors, the 404s, the
|
||||
//! headers and the body encoding are this one copy in both cases, so the bytes on `:7401` do not
|
||||
//! depend on which side of the bus answered.
|
||||
|
||||
use std::time::Duration;
|
||||
use std::future::Future;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Bytes;
|
||||
|
|
@ -20,17 +27,24 @@ use axum::response::{IntoResponse, Response};
|
|||
use axum::routing::{get, post};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::chat::ChatRefusal;
|
||||
use crate::eventlog::now_wall_ms;
|
||||
use crate::simloop::Command;
|
||||
use crate::{AppState, metrics};
|
||||
pub use crate::control::COMMAND_TIMEOUT;
|
||||
use crate::AppState;
|
||||
use crate::control::{ControlReply, ControlRequest, METRICS_CONTENT_TYPE, ReplyBody};
|
||||
|
||||
/// Whatever answers a [`ControlRequest`]: the sim in this process, or the control services on
|
||||
/// the bus.
|
||||
pub trait ControlBackend: Clone + Send + Sync + 'static {
|
||||
fn handle(&self, request: ControlRequest) -> impl Future<Output = ControlReply> + Send;
|
||||
}
|
||||
|
||||
impl ControlBackend for AppState {
|
||||
fn handle(&self, request: ControlRequest) -> impl Future<Output = ControlReply> + Send {
|
||||
let state = self.clone();
|
||||
async move { crate::control::handle(&state, request).await }
|
||||
}
|
||||
}
|
||||
|
||||
/// Every route the control API serves, in the order `docs/control-api.md` lists them.
|
||||
///
|
||||
/// `/status.json` is an alias of `/status` (the read-only metrics listener that
|
||||
/// `infra/bin/fly-watchdog` scrapes asks for that name); `/metrics` is Prometheus text.
|
||||
pub const ROUTES: &[(&str, &str)] = &[
|
||||
("GET", "/status"),
|
||||
("GET", "/status.json"),
|
||||
|
|
@ -54,39 +68,40 @@ pub const READ_ONLY_ROUTES: &[(&str, &str)] = &[
|
|||
("GET", "/metrics"),
|
||||
];
|
||||
|
||||
/// How long a caller waits for the sim thread to pick a command up. One frame is 16.7 ms, so
|
||||
/// this is generous; exceeding it means the loop is wedged, which is a 503, not a hang.
|
||||
pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
pub fn router(state: AppState) -> Router {
|
||||
router_with(state)
|
||||
}
|
||||
|
||||
/// The full control router over any backend: [`ROUTES`] and a 404 for everything else.
|
||||
pub fn router_with<B: ControlBackend>(backend: B) -> Router {
|
||||
Router::new()
|
||||
.route("/status", get(status))
|
||||
.route("/status.json", get(status))
|
||||
.route("/stimulate", post(stimulate))
|
||||
.route("/reward", post(reward))
|
||||
.route("/chat", post(chat))
|
||||
.route("/checkpoint", post(checkpoint))
|
||||
.route("/pause", post(pause))
|
||||
.route("/resume", post(resume))
|
||||
.route("/events", get(events))
|
||||
.route("/healthz", get(healthz))
|
||||
.route("/metrics", get(prometheus))
|
||||
.route("/status", get(status::<B>))
|
||||
.route("/status.json", get(status::<B>))
|
||||
.route("/stimulate", post(stimulate::<B>))
|
||||
.route("/reward", post(reward::<B>))
|
||||
.route("/chat", post(chat::<B>))
|
||||
.route("/checkpoint", post(checkpoint::<B>))
|
||||
.route("/pause", post(pause::<B>))
|
||||
.route("/resume", post(resume::<B>))
|
||||
.route("/events", get(events::<B>))
|
||||
.route("/healthz", get(healthz::<B>))
|
||||
.route("/metrics", get(prometheus::<B>))
|
||||
.fallback(not_found)
|
||||
// The reference server answers every unmatched method-and-path pair with the same 404,
|
||||
// so `GET /stimulate` is "no such route" rather than a 405. Being a drop-in replacement
|
||||
// for it matters more here than the distinction does.
|
||||
.method_not_allowed_fallback(not_found)
|
||||
.layer(axum::middleware::map_response(no_store))
|
||||
.with_state(state)
|
||||
.with_state(backend)
|
||||
}
|
||||
|
||||
/// The read-only listener: [`READ_ONLY_ROUTES`] and nothing else.
|
||||
pub fn metrics_router(state: AppState) -> Router {
|
||||
Router::new()
|
||||
.route("/status", get(status))
|
||||
.route("/status.json", get(status))
|
||||
.route("/healthz", get(healthz))
|
||||
.route("/metrics", get(prometheus))
|
||||
.route("/status", get(status::<AppState>))
|
||||
.route("/status.json", get(status::<AppState>))
|
||||
.route("/healthz", get(healthz::<AppState>))
|
||||
.route("/metrics", get(prometheus::<AppState>))
|
||||
.fallback(not_found)
|
||||
.method_not_allowed_fallback(not_found)
|
||||
.layer(axum::middleware::map_response(no_store))
|
||||
|
|
@ -100,107 +115,25 @@ async fn no_store(mut response: Response) -> Response {
|
|||
response
|
||||
}
|
||||
|
||||
fn body(status: StatusCode, value: Value) -> Response {
|
||||
(status, axum::Json(value)).into_response()
|
||||
}
|
||||
|
||||
fn error(status: StatusCode, message: impl std::fmt::Display) -> Response {
|
||||
body(status, json!({ "error": message.to_string() }))
|
||||
}
|
||||
|
||||
// -- GET /status ------------------------------------------------------------------------------
|
||||
|
||||
/// The feed header minus `events` and `attachments`, plus `version` and `checkpoint`.
|
||||
///
|
||||
/// Built by reshaping the header itself rather than by a parallel struct, so "same fields as the
|
||||
/// feed header" cannot drift.
|
||||
async fn status(State(state): State<AppState>) -> Response {
|
||||
let snapshot = state.snapshot();
|
||||
let mut value = match serde_json::to_value(&snapshot.header) {
|
||||
Ok(Value::Object(map)) => map,
|
||||
_ => return error(StatusCode::INTERNAL_SERVER_ERROR, "could not render the status"),
|
||||
};
|
||||
value.remove("events");
|
||||
value.remove("attachments");
|
||||
let versions = state.shared.versions.get().cloned().unwrap_or_default();
|
||||
value.insert("version".to_string(), serde_json::to_value(versions).unwrap_or(Value::Null));
|
||||
let checkpoint = state
|
||||
.shared
|
||||
.checkpoint
|
||||
.lock()
|
||||
.map(|status| *status)
|
||||
.unwrap_or_default();
|
||||
value.insert("checkpoint".to_string(), serde_json::to_value(checkpoint).unwrap_or(Value::Null));
|
||||
// The readout's own numbers, additive: one row per channel with the role it reads, the resting
|
||||
// rate it is normalized against and the score the last decode computed, plus the roles a
|
||||
// restore has left for the next decode to calibrate (`docs/readout.md`).
|
||||
let decoder = state
|
||||
.shared
|
||||
.decoder
|
||||
.lock()
|
||||
.map(|status| status.clone())
|
||||
.unwrap_or_default();
|
||||
value.insert("decoder".to_string(), serde_json::to_value(decoder).unwrap_or(Value::Null));
|
||||
body(StatusCode::OK, Value::Object(value))
|
||||
}
|
||||
|
||||
// -- GET /healthz -----------------------------------------------------------------------------
|
||||
|
||||
/// 200 while the loop advanced in the last 2 seconds, else 503. This is what systemd's
|
||||
/// `wait-for-health` helper and `infra/bin/fly-watchdog` check first.
|
||||
async fn healthz(State(state): State<AppState>) -> Response {
|
||||
if state.shared.healthy(now_wall_ms()) {
|
||||
body(StatusCode::OK, json!({ "status": "ok" }))
|
||||
} else {
|
||||
error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"loop has not advanced in the last 2 seconds",
|
||||
)
|
||||
/// A [`ControlReply`] as HTTP: JSON bodies as `axum::Json` writes them, `/metrics` as
|
||||
/// Prometheus text.
|
||||
pub fn into_response(reply: ControlReply) -> Response {
|
||||
let status =
|
||||
StatusCode::from_u16(reply.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
match reply.body {
|
||||
ReplyBody::Json(value) => (status, axum::Json(value)).into_response(),
|
||||
ReplyBody::Text(text) => {
|
||||
(status, [(header::CONTENT_TYPE, METRICS_CONTENT_TYPE)], text).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -- GET /metrics -----------------------------------------------------------------------------
|
||||
|
||||
async fn prometheus(State(state): State<AppState>) -> Response {
|
||||
let snapshot = state.snapshot();
|
||||
let text = metrics::render(&state.shared.metrics, &snapshot, now_wall_ms());
|
||||
(
|
||||
StatusCode::OK,
|
||||
[(header::CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8")],
|
||||
text,
|
||||
)
|
||||
.into_response()
|
||||
async fn answer<B: ControlBackend>(backend: &B, request: ControlRequest) -> Response {
|
||||
into_response(backend.handle(request).await)
|
||||
}
|
||||
|
||||
// -- GET /events ------------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct EventsQuery {
|
||||
since: Option<String>,
|
||||
limit: Option<String>,
|
||||
}
|
||||
|
||||
/// `?since=<id>&limit=<n>`, parsed as leniently as the reference server's
|
||||
/// `Number.parseInt(...) || 0`: anything unreadable falls back to the default.
|
||||
async fn events(State(state): State<AppState>, Query(query): Query<EventsQuery>) -> Response {
|
||||
let since = query
|
||||
.since
|
||||
.as_deref()
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.unwrap_or(0);
|
||||
let limit = query
|
||||
.limit
|
||||
.as_deref()
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|limit| *limit > 0)
|
||||
.unwrap_or(100)
|
||||
.min(crate::eventlog::RING_CAPACITY);
|
||||
let events = state.shared.events.page(since, limit);
|
||||
body(StatusCode::OK, json!({ "events": events }))
|
||||
}
|
||||
|
||||
// -- POST /stimulate --------------------------------------------------------------------------
|
||||
|
||||
/// The request body as JSON, or `None` when it is empty or not JSON (the reference server's
|
||||
/// "malformed body").
|
||||
fn parse_json(bytes: &Bytes) -> Option<Value> {
|
||||
if bytes.is_empty() {
|
||||
return None;
|
||||
|
|
@ -208,217 +141,64 @@ fn parse_json(bytes: &Bytes) -> Option<Value> {
|
|||
serde_json::from_slice(bytes).ok()
|
||||
}
|
||||
|
||||
/// `chat`, `points` or `operator`, as `isActionSource` in the reference server.
|
||||
fn action_source(value: Option<&Value>) -> Option<&str> {
|
||||
match value.and_then(Value::as_str) {
|
||||
Some(source @ ("chat" | "points" | "operator")) => Some(source),
|
||||
_ => None,
|
||||
}
|
||||
async fn status<B: ControlBackend>(State(backend): State<B>) -> Response {
|
||||
answer(&backend, ControlRequest::Status).await
|
||||
}
|
||||
|
||||
async fn stimulate(State(state): State<AppState>, bytes: Bytes) -> Response {
|
||||
let Some(request) = parse_json(&bytes) else {
|
||||
return error(StatusCode::BAD_REQUEST, "expected { durationMs?, by, source }");
|
||||
};
|
||||
let (Some(by), Some(source)) = (
|
||||
request.get("by").and_then(Value::as_str),
|
||||
action_source(request.get("source")),
|
||||
) else {
|
||||
return error(StatusCode::BAD_REQUEST, "expected { durationMs?, by, source }");
|
||||
};
|
||||
let duration_ms = match request.get("durationMs") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(value) => match value.as_f64().filter(|value| value.is_finite() && *value > 0.0) {
|
||||
Some(value) => Some(value),
|
||||
None => {
|
||||
return error(StatusCode::BAD_REQUEST, "durationMs must be a positive number");
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let (reply, response) = oneshot::channel();
|
||||
let command = Command::Stimulate {
|
||||
duration_ms,
|
||||
by: by.to_string(),
|
||||
source: source.to_string(),
|
||||
reply,
|
||||
};
|
||||
match dispatch(&state, command, response).await {
|
||||
Ok(Ok(event_id)) => body(StatusCode::ACCEPTED, json!({ "eventId": event_id })),
|
||||
Ok(Err(refusal)) => body(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
json!({ "retryAfterMs": refusal.retry_after_ms() }),
|
||||
),
|
||||
Err(response) => response,
|
||||
}
|
||||
async fn healthz<B: ControlBackend>(State(backend): State<B>) -> Response {
|
||||
answer(&backend, ControlRequest::Healthz).await
|
||||
}
|
||||
|
||||
// -- POST /reward -----------------------------------------------------------------------------
|
||||
|
||||
async fn reward(State(state): State<AppState>, bytes: Bytes) -> Response {
|
||||
if !state.shared.config.control.allow_reward {
|
||||
// Present so that the later "who trains the fly" work does not change the API.
|
||||
return error(
|
||||
StatusCode::FORBIDDEN,
|
||||
"reward is disabled (control.allow_reward = false)",
|
||||
);
|
||||
}
|
||||
let Some(request) = parse_json(&bytes) else {
|
||||
return error(StatusCode::BAD_REQUEST, "expected { value, by, source }");
|
||||
};
|
||||
let (Some(value), Some(by), Some(source)) = (
|
||||
request.get("value").and_then(Value::as_f64).filter(|value| value.is_finite()),
|
||||
request.get("by").and_then(Value::as_str),
|
||||
action_source(request.get("source")),
|
||||
) else {
|
||||
return error(StatusCode::BAD_REQUEST, "expected { value, by, source }");
|
||||
};
|
||||
|
||||
let (reply, response) = oneshot::channel();
|
||||
let command = Command::Reward {
|
||||
value,
|
||||
by: by.to_string(),
|
||||
source: source.to_string(),
|
||||
reply,
|
||||
};
|
||||
match dispatch(&state, command, response).await {
|
||||
Ok(event_id) => body(StatusCode::ACCEPTED, json!({ "eventId": event_id })),
|
||||
Err(response) => response,
|
||||
}
|
||||
async fn prometheus<B: ControlBackend>(State(backend): State<B>) -> Response {
|
||||
answer(&backend, ControlRequest::Metrics).await
|
||||
}
|
||||
|
||||
// -- POST /chat -------------------------------------------------------------------------------
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct EventsQuery {
|
||||
since: Option<String>,
|
||||
limit: Option<String>,
|
||||
}
|
||||
|
||||
/// `{ by, text, bot? }`: one line for the feed header's chat ring.
|
||||
///
|
||||
/// The kill switch is answered here, because it is pure configuration and a 403 should not need
|
||||
/// the sim thread. Everything else — the name rule, the sanitizer, the deny list and the two rate
|
||||
/// limits — is decided on the sim thread, which owns the ring, the limiter and the event log.
|
||||
///
|
||||
/// Status codes, per `docs/control-api.md`: 202 with the event id, 403 while chat is disabled,
|
||||
/// 422 when a rule refused the line, 429 when a rate limit did, 400 for a malformed body.
|
||||
async fn chat(State(state): State<AppState>, bytes: Bytes) -> Response {
|
||||
if !state.shared.config.chat.enabled {
|
||||
return error(StatusCode::FORBIDDEN, "chat is disabled (chat.enabled = false)");
|
||||
}
|
||||
let Some(request) = parse_json(&bytes) else {
|
||||
return error(StatusCode::BAD_REQUEST, "expected { by, text, bot? }");
|
||||
async fn events<B: ControlBackend>(
|
||||
State(backend): State<B>,
|
||||
Query(query): Query<EventsQuery>,
|
||||
) -> Response {
|
||||
let request = ControlRequest::Events {
|
||||
since: query.since,
|
||||
limit: query.limit,
|
||||
};
|
||||
let (Some(by), Some(text)) = (
|
||||
request.get("by").and_then(Value::as_str),
|
||||
request.get("text").and_then(Value::as_str),
|
||||
) else {
|
||||
state
|
||||
.shared
|
||||
.metrics
|
||||
.chat_rejected(crate::chat::RejectReason::Malformed);
|
||||
return error(StatusCode::BAD_REQUEST, "expected { by, text, bot? }");
|
||||
};
|
||||
let bot = match request.get("bot") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(value)) => *value,
|
||||
Some(_) => return error(StatusCode::BAD_REQUEST, "bot must be a boolean"),
|
||||
};
|
||||
|
||||
let (reply, response) = oneshot::channel();
|
||||
let command = Command::Chat { by: by.to_string(), text: text.to_string(), bot, reply };
|
||||
match dispatch(&state, command, response).await {
|
||||
Ok(Ok(event_id)) => body(StatusCode::ACCEPTED, json!({ "eventId": event_id })),
|
||||
Ok(Err(ChatRefusal::Rejected(reason))) => body(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
json!({ "error": format!("chat line refused: {}", reason.as_str()) }),
|
||||
),
|
||||
Ok(Err(ChatRefusal::RateLimited { retry_after_ms })) => body(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
json!({ "retryAfterMs": retry_after_ms }),
|
||||
),
|
||||
Err(response) => response,
|
||||
}
|
||||
answer(&backend, request).await
|
||||
}
|
||||
|
||||
// -- POST /checkpoint, /pause, /resume --------------------------------------------------------
|
||||
|
||||
async fn checkpoint(State(state): State<AppState>) -> Response {
|
||||
let (reply, response) = oneshot::channel();
|
||||
// A forced checkpoint answers only once the bytes are on disk, so a caller that is about to
|
||||
// restart the service can rely on it.
|
||||
match dispatch_with_timeout(&state, Command::Checkpoint { reply }, response, None).await {
|
||||
Ok(Ok(generation)) => body(StatusCode::OK, json!({ "generation": generation })),
|
||||
Ok(Err(message)) => error(StatusCode::INTERNAL_SERVER_ERROR, message),
|
||||
Err(response) => response,
|
||||
}
|
||||
async fn stimulate<B: ControlBackend>(State(backend): State<B>, bytes: Bytes) -> Response {
|
||||
answer(&backend, ControlRequest::Stimulate { body: parse_json(&bytes) }).await
|
||||
}
|
||||
|
||||
async fn pause(State(state): State<AppState>) -> Response {
|
||||
let (reply, response) = oneshot::channel();
|
||||
// A pause takes an implicit durable checkpoint, so it can take as long as one write.
|
||||
match dispatch_with_timeout(&state, Command::Pause { reply }, response, None).await {
|
||||
Ok(status) => body(StatusCode::OK, json!({ "status": status })),
|
||||
Err(response) => response,
|
||||
}
|
||||
async fn reward<B: ControlBackend>(State(backend): State<B>, bytes: Bytes) -> Response {
|
||||
answer(&backend, ControlRequest::Reward { body: parse_json(&bytes) }).await
|
||||
}
|
||||
|
||||
async fn resume(State(state): State<AppState>) -> Response {
|
||||
let (reply, response) = oneshot::channel();
|
||||
match dispatch(&state, Command::Resume { reply }, response).await {
|
||||
Ok(status) => body(StatusCode::OK, json!({ "status": status })),
|
||||
Err(response) => response,
|
||||
}
|
||||
async fn chat<B: ControlBackend>(State(backend): State<B>, bytes: Bytes) -> Response {
|
||||
answer(&backend, ControlRequest::Chat { body: parse_json(&bytes) }).await
|
||||
}
|
||||
|
||||
// -- plumbing ---------------------------------------------------------------------------------
|
||||
async fn checkpoint<B: ControlBackend>(State(backend): State<B>) -> Response {
|
||||
answer(&backend, ControlRequest::Checkpoint).await
|
||||
}
|
||||
|
||||
async fn pause<B: ControlBackend>(State(backend): State<B>) -> Response {
|
||||
answer(&backend, ControlRequest::Pause).await
|
||||
}
|
||||
|
||||
async fn resume<B: ControlBackend>(State(backend): State<B>) -> Response {
|
||||
answer(&backend, ControlRequest::Resume).await
|
||||
}
|
||||
|
||||
async fn not_found(method: axum::http::Method, uri: axum::http::Uri) -> Response {
|
||||
error(
|
||||
StatusCode::NOT_FOUND,
|
||||
format!("no such route: {method} {}", uri.path()),
|
||||
)
|
||||
}
|
||||
|
||||
async fn dispatch<T>(
|
||||
state: &AppState,
|
||||
command: Command,
|
||||
response: oneshot::Receiver<T>,
|
||||
) -> Result<T, Response> {
|
||||
dispatch_with_timeout(state, command, response, Some(COMMAND_TIMEOUT)).await
|
||||
}
|
||||
|
||||
/// Queue a command and wait for its reply.
|
||||
///
|
||||
/// The queue is bounded: a full queue is a 503 rather than a wait, because the only way to fill
|
||||
/// it is a wedged loop or a flood, and neither is improved by blocking the caller.
|
||||
async fn dispatch_with_timeout<T>(
|
||||
state: &AppState,
|
||||
command: Command,
|
||||
response: oneshot::Receiver<T>,
|
||||
timeout: Option<Duration>,
|
||||
) -> Result<T, Response> {
|
||||
if let Err(error) = state.commands.try_send(command) {
|
||||
return Err(match error {
|
||||
tokio::sync::mpsc::error::TrySendError::Full(_) => self::error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"the simulation command queue is full",
|
||||
),
|
||||
tokio::sync::mpsc::error::TrySendError::Closed(_) => {
|
||||
self::error(StatusCode::SERVICE_UNAVAILABLE, "the simulation has stopped")
|
||||
}
|
||||
});
|
||||
}
|
||||
let awaited = match timeout {
|
||||
Some(timeout) => match tokio::time::timeout(timeout, response).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
return Err(self::error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"the simulation did not answer in time",
|
||||
));
|
||||
}
|
||||
},
|
||||
None => response.await,
|
||||
};
|
||||
awaited.map_err(|_| {
|
||||
self::error(StatusCode::SERVICE_UNAVAILABLE, "the simulation dropped the request")
|
||||
})
|
||||
into_response(ControlReply::json(
|
||||
404,
|
||||
json!({ "error": format!("no such route: {method} {}", uri.path()) }),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -447,15 +227,4 @@ mod tests {
|
|||
assert!(ROUTES.contains(&(method, path)), "{path} is not a control route");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn action_sources_are_the_three_the_contract_names() {
|
||||
for source in ["chat", "points", "operator"] {
|
||||
assert_eq!(action_source(Some(&json!(source))), Some(source));
|
||||
}
|
||||
for rejected in [json!("bridge"), json!(1), json!(null), Value::Null] {
|
||||
assert_eq!(action_source(Some(&rejected)), None);
|
||||
}
|
||||
assert_eq!(action_source(None), None);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
127
services/flysim/crates/flysim/src/bus.rs
Normal file
127
services/flysim/crates/flysim/src/bus.rs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
//! The embedded flybus router: one router under `feed.bus_dir` for whatever rides the bus
|
||||
//! (`FLY_FEED_VIA=bus`, `FLY_CONTROL_VIA=bus`, or both).
|
||||
//!
|
||||
//! The feed's half is `crate::feedbus` (its topic, its policy, its limits and `edge.sock`), the
|
||||
//! control's half is `crate::controlbus` (its services, its grant table and its sockets); this
|
||||
//! module only composes them on one router, so a box with both on the bus runs one router, one
|
||||
//! store and one closed policy.
|
||||
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use flybus::{Limits, Policy, Router, RouterConfig, UnixListenerHandle};
|
||||
|
||||
use crate::controlbus::{self, Role, Scope};
|
||||
use crate::feedbus;
|
||||
|
||||
/// What rides the bus.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Uses {
|
||||
pub feed: bool,
|
||||
pub control: bool,
|
||||
}
|
||||
|
||||
/// A running router and its sockets. Dropping it stops listening; the router stops with the
|
||||
/// runtime it was started on.
|
||||
pub struct EmbeddedBus {
|
||||
pub router: Router,
|
||||
_listeners: Vec<UnixListenerHandle>,
|
||||
}
|
||||
|
||||
/// The router limits: the feed's (`docs/design/flybus.md`, amendment "Feed sizing"), with room
|
||||
/// for the control participants when control rides the bus too: the in-process host, the edge
|
||||
/// and one connection per native role, pending handshakes included, and the control services.
|
||||
pub fn limits(uses: Uses) -> Limits {
|
||||
let feed = feedbus::limits();
|
||||
if !uses.control {
|
||||
return feed;
|
||||
}
|
||||
Limits {
|
||||
max_clients: feed.max_clients + 8,
|
||||
max_services: feed.max_services + 8,
|
||||
..feed
|
||||
}
|
||||
}
|
||||
|
||||
/// The closed policy for `uses`.
|
||||
pub fn policy(uses: Uses, scope: &Scope) -> Policy {
|
||||
let base = if uses.feed {
|
||||
feedbus::policy()
|
||||
} else {
|
||||
Policy::closed()
|
||||
};
|
||||
if uses.control {
|
||||
controlbus::policy(base, scope)
|
||||
} else {
|
||||
base
|
||||
}
|
||||
}
|
||||
|
||||
fn private_dir(path: &Path) -> Result<()> {
|
||||
std::fs::DirBuilder::new()
|
||||
.recursive(true)
|
||||
.mode(0o700)
|
||||
.create(path)
|
||||
.with_context(|| format!("creating {}", path.display()))
|
||||
}
|
||||
|
||||
fn remove_stale(socket: &Path) -> Result<()> {
|
||||
match std::fs::remove_file(socket) {
|
||||
Ok(()) => {
|
||||
tracing::info!(socket = %socket.display(), "removed a stale bus socket");
|
||||
Ok(())
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(error).with_context(|| format!("removing {}", socket.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the router under `bus_dir` and listen on every socket `uses` needs: `edge.sock` for the
|
||||
/// feed edge, `control-edge.sock` for the control edge and `control/<role>.sock` for each native
|
||||
/// control role, each launcher-bound to its participant.
|
||||
///
|
||||
/// Must run inside a Tokio runtime. `Router::new` removes store directories a previous flysim
|
||||
/// left behind; stale socket files are removed here, because a socket outlives its listener.
|
||||
pub async fn start(bus_dir: &Path, uses: Uses, scope: &Scope) -> Result<EmbeddedBus> {
|
||||
private_dir(bus_dir)?;
|
||||
let root = feedbus::store_root(bus_dir);
|
||||
private_dir(&root)?;
|
||||
let mut config = RouterConfig::new(root);
|
||||
config.limits = limits(uses);
|
||||
config.policy = policy(uses, scope);
|
||||
let router = Router::new(config).context("starting the flybus router")?;
|
||||
|
||||
let mut sockets = Vec::new();
|
||||
if uses.feed {
|
||||
sockets.push((feedbus::socket_path(bus_dir), feedbus::EDGE));
|
||||
}
|
||||
if uses.control {
|
||||
private_dir(&bus_dir.join(controlbus::ROLE_SOCKET_DIR))?;
|
||||
for role in Role::ALL {
|
||||
sockets.push((controlbus::socket_path(bus_dir, role), role.participant()));
|
||||
}
|
||||
}
|
||||
let mut listeners = Vec::new();
|
||||
for (socket, participant) in sockets {
|
||||
remove_stale(&socket)?;
|
||||
listeners.push(
|
||||
router
|
||||
.listen_unix_as(&socket, participant)
|
||||
.await
|
||||
.with_context(|| format!("listening on {}", socket.display()))?,
|
||||
);
|
||||
}
|
||||
tracing::info!(
|
||||
bus = %bus_dir.display(),
|
||||
feed = uses.feed,
|
||||
control = uses.control,
|
||||
store = %router.store_dir().display(),
|
||||
router = router.router_id(),
|
||||
"bus listening"
|
||||
);
|
||||
Ok(EmbeddedBus {
|
||||
router,
|
||||
_listeners: listeners,
|
||||
})
|
||||
}
|
||||
|
|
@ -9,7 +9,7 @@
|
|||
//! - the `FLY_*` names the systemd units already set (`FLY_GAME`, `FLY_ROM`, `FLY_DATASET`,
|
||||
//! `FLY_STATE`, `FLY_STATE_HOT`, `FLY_FEED_BIND`, `FLY_CONTROL_BIND`, `FLY_METRICS_ADDR`,
|
||||
//! `FLY_ROM_SHA256`, `FLY_ROM_PLATFORMER_SHA256`, `FLY_CHAT_ENABLED`, `FLY_CHAT_DENY_LIST`,
|
||||
//! `FLY_MACRO_MODE`, `FLY_FEED_VIA`, `FLY_BUS_DIR`, `RAYON_NUM_THREADS`);
|
||||
//! `FLY_MACRO_MODE`, `FLY_FEED_VIA`, `FLY_CONTROL_VIA`, `FLY_BUS_DIR`, `RAYON_NUM_THREADS`);
|
||||
//! - `FLYSIM_<SECTION>_<KEY>` for everything, e.g. `FLYSIM_LOOP_SPEED=0`.
|
||||
//!
|
||||
//! Nothing here is secret (`docs/control-api.md`: "No secrets live in this service or its
|
||||
|
|
@ -139,6 +139,8 @@ impl FeedVia {
|
|||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Control {
|
||||
pub bind: SocketAddr,
|
||||
/// Who serves `control.bind` (`docs/design/flybus.md`, "Control over the bus").
|
||||
pub via: ControlVia,
|
||||
/// Optional extra read-only listener carrying `/metrics`, `/status`, `/status.json` and
|
||||
/// `/healthz` only (`infra/units/flysim.service` sets `FLY_METRICS_ADDR=0.0.0.0:9101`).
|
||||
pub metrics_bind: Option<SocketAddr>,
|
||||
|
|
@ -152,6 +154,31 @@ pub struct Control {
|
|||
pub expect_rom_sha256: Option<String>,
|
||||
}
|
||||
|
||||
/// Where the control API is served from (CTRL-01).
|
||||
///
|
||||
/// `direct` is the default and the behaviour that predates the bus: flysim binds
|
||||
/// `control.bind` itself. `bus` registers the control services on the embedded flybus router
|
||||
/// (under `feed.bus_dir`, shared with the feed when that is on the bus too) and leaves
|
||||
/// `control.bind` to the `fly-control-edge` process, which serves the same HTTP bytes by calling
|
||||
/// them. The read-only `control.metrics_bind` listener stays in flysim in both modes. Outside the
|
||||
/// simulation loop and outside the compatibility string.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ControlVia {
|
||||
#[default]
|
||||
Direct,
|
||||
Bus,
|
||||
}
|
||||
|
||||
impl ControlVia {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Direct => "direct",
|
||||
Self::Bus => "bus",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `[macros]` (`docs/design/macros.md` sections 1 and 4): what the fly's channels mean.
|
||||
///
|
||||
/// One knob, and deliberately only one. `raw` is the default and stays the default until the
|
||||
|
|
@ -236,6 +263,7 @@ impl Default for Control {
|
|||
fn default() -> Self {
|
||||
Self {
|
||||
bind: "127.0.0.1:7401".parse().expect("literal address"),
|
||||
via: ControlVia::Direct,
|
||||
metrics_bind: None,
|
||||
allow_reward: false,
|
||||
sugar_default_ms: 400.0,
|
||||
|
|
@ -295,6 +323,9 @@ impl Config {
|
|||
if let Some(value) = get("FLY_CONTROL_BIND") {
|
||||
self.control.bind = parse_addr("FLY_CONTROL_BIND", value)?;
|
||||
}
|
||||
if let Some(value) = get("FLY_CONTROL_VIA") {
|
||||
self.control.via = parse_control_via("FLY_CONTROL_VIA", value)?;
|
||||
}
|
||||
if let Some(value) = get("FLY_METRICS_ADDR") {
|
||||
self.control.metrics_bind = Some(parse_addr("FLY_METRICS_ADDR", value)?);
|
||||
}
|
||||
|
|
@ -376,6 +407,9 @@ impl Config {
|
|||
if let Some(value) = get("FLYSIM_CONTROL_BIND") {
|
||||
self.control.bind = parse_addr("FLYSIM_CONTROL_BIND", value)?;
|
||||
}
|
||||
if let Some(value) = get("FLYSIM_CONTROL_VIA") {
|
||||
self.control.via = parse_control_via("FLYSIM_CONTROL_VIA", value)?;
|
||||
}
|
||||
if let Some(value) = get("FLYSIM_CONTROL_METRICS_BIND") {
|
||||
self.control.metrics_bind = Some(parse_addr("FLYSIM_CONTROL_METRICS_BIND", value)?);
|
||||
}
|
||||
|
|
@ -525,6 +559,14 @@ fn parse_feed_via(name: &str, value: &str) -> Result<FeedVia> {
|
|||
}
|
||||
}
|
||||
|
||||
fn parse_control_via(name: &str, value: &str) -> Result<ControlVia> {
|
||||
match value.to_ascii_lowercase().as_str() {
|
||||
"direct" => Ok(ControlVia::Direct),
|
||||
"bus" => Ok(ControlVia::Bus),
|
||||
_ => bail!("{name}: {value:?} is not a control path; expected \"direct\" or \"bus\""),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_addr(name: &str, value: &str) -> Result<SocketAddr> {
|
||||
value
|
||||
.parse()
|
||||
|
|
@ -771,6 +813,28 @@ mod tests {
|
|||
assert_eq!(toml::from_str::<Config>("[feed]\nvia = \"bus\"\n").unwrap().feed.via, FeedVia::Bus);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_path_is_direct_unless_the_environment_says_bus() {
|
||||
assert_eq!(Config::default().control.via, ControlVia::Direct);
|
||||
|
||||
let mut config = Config::default();
|
||||
config.apply_env(&env(&[("FLY_CONTROL_VIA", "Bus")])).unwrap();
|
||||
assert_eq!(config.control.via, ControlVia::Bus);
|
||||
// Independent of the feed's switch.
|
||||
assert_eq!(config.feed.via, FeedVia::Direct);
|
||||
|
||||
let mut config = Config::default();
|
||||
config.apply_env(&env(&[("FLYSIM_CONTROL_VIA", "direct")])).unwrap();
|
||||
assert_eq!(config.control.via, ControlVia::Direct);
|
||||
|
||||
let error = Config::default().apply_env(&env(&[("FLY_CONTROL_VIA", "http")])).unwrap_err();
|
||||
assert!(error.to_string().contains("FLY_CONTROL_VIA"), "{error}");
|
||||
assert_eq!(
|
||||
toml::from_str::<Config>("[control]\nvia = \"bus\"\n").unwrap().control.via,
|
||||
ControlVia::Bus
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bus_dir_must_be_absolute_and_not_empty() {
|
||||
Config::default().validate().unwrap();
|
||||
|
|
|
|||
451
services/flysim/crates/flysim/src/control.rs
Normal file
451
services/flysim/crates/flysim/src/control.rs
Normal file
|
|
@ -0,0 +1,451 @@
|
|||
//! The control API's semantics, independent of how a request arrives (CTRL-01).
|
||||
//!
|
||||
//! Binding contract: `docs/control-api.md`. Every endpoint there is one [`ControlRequest`]
|
||||
//! variant, and [`handle`] is the only code that decides what it does: the HTTP listener on
|
||||
//! `:7401` ([`crate::api`]) and the control services on the bus ([`crate::controlbus`]) both call
|
||||
//! it, so the status codes, the bodies and the commands the loop receives are one copy whichever
|
||||
//! way the caller came in.
|
||||
//!
|
||||
//! [`ControlRequest`] is the whole surface. It has no variant that presses a button, edits game
|
||||
//! memory or changes the reward catalog, and [`crate::simloop::Command`] has none either: the
|
||||
//! structural guarantee of `docs/control-api.md` is a property of these two types.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::chat::ChatRefusal;
|
||||
use crate::eventlog::now_wall_ms;
|
||||
use crate::simloop::Command;
|
||||
use crate::{AppState, metrics};
|
||||
|
||||
/// How long a caller waits for the sim thread to pick a command up. One frame is 16.7 ms, so
|
||||
/// this is generous; exceeding it means the loop is wedged, which is a 503, not a hang.
|
||||
pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// The Prometheus text exposition's content type (`GET /metrics`).
|
||||
pub const METRICS_CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8";
|
||||
|
||||
/// One control request, as `docs/control-api.md` lists them.
|
||||
///
|
||||
/// Bodies are carried as the caller sent them, parsed (`None` when the body was empty or not
|
||||
/// JSON), and the `/events` query as its raw strings, so validation, its lenient defaults and
|
||||
/// its error messages live in [`handle`] alone.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ControlRequest {
|
||||
/// `GET /status` (and its alias `/status.json`).
|
||||
Status,
|
||||
/// `GET /healthz`.
|
||||
Healthz,
|
||||
/// `GET /metrics`.
|
||||
Metrics,
|
||||
/// `GET /events?since=<id>&limit=<n>`.
|
||||
Events {
|
||||
since: Option<String>,
|
||||
limit: Option<String>,
|
||||
},
|
||||
/// `POST /stimulate`: a sugar (PAM) pulse.
|
||||
Stimulate { body: Option<Value> },
|
||||
/// `POST /reward`: disabled unless `control.allow_reward`.
|
||||
Reward { body: Option<Value> },
|
||||
/// `POST /chat`: one line for the chat ring; never reaches the simulation.
|
||||
Chat { body: Option<Value> },
|
||||
/// `POST /checkpoint`.
|
||||
Checkpoint,
|
||||
/// `POST /pause`.
|
||||
Pause,
|
||||
/// `POST /resume`.
|
||||
Resume,
|
||||
}
|
||||
|
||||
impl ControlRequest {
|
||||
/// The `docs/control-api.md` path this request is (for logs and tables).
|
||||
pub fn path(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Status => "/status",
|
||||
Self::Healthz => "/healthz",
|
||||
Self::Metrics => "/metrics",
|
||||
Self::Events { .. } => "/events",
|
||||
Self::Stimulate { .. } => "/stimulate",
|
||||
Self::Reward { .. } => "/reward",
|
||||
Self::Chat { .. } => "/chat",
|
||||
Self::Checkpoint => "/checkpoint",
|
||||
Self::Pause => "/pause",
|
||||
Self::Resume => "/resume",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the loop is waited on without a deadline: a forced checkpoint answers once the
|
||||
/// bytes are on disk, and a pause takes an implicit durable checkpoint.
|
||||
pub fn waits_for_a_write(&self) -> bool {
|
||||
matches!(self, Self::Checkpoint | Self::Pause)
|
||||
}
|
||||
}
|
||||
|
||||
/// A reply body: JSON for every endpoint but `/metrics`, which is Prometheus text.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ReplyBody {
|
||||
Json(Value),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
/// What [`handle`] answers: the `docs/control-api.md` status code and body.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ControlReply {
|
||||
pub status: u16,
|
||||
pub body: ReplyBody,
|
||||
}
|
||||
|
||||
impl ControlReply {
|
||||
pub fn json(status: u16, value: Value) -> ControlReply {
|
||||
ControlReply {
|
||||
status,
|
||||
body: ReplyBody::Json(value),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn error(status: u16, message: impl std::fmt::Display) -> ControlReply {
|
||||
ControlReply::json(status, json!({ "error": message.to_string() }))
|
||||
}
|
||||
|
||||
pub fn text(status: u16, text: String) -> ControlReply {
|
||||
ControlReply {
|
||||
status,
|
||||
body: ReplyBody::Text(text),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The messages a failed hand-off to the loop answers with (503). The bus edge uses the same
|
||||
/// words for the same failures on its side of the bus, so a client cannot tell them apart.
|
||||
pub mod unavailable {
|
||||
pub const QUEUE_FULL: &str = "the simulation command queue is full";
|
||||
pub const STOPPED: &str = "the simulation has stopped";
|
||||
pub const TIMED_OUT: &str = "the simulation did not answer in time";
|
||||
pub const DROPPED: &str = "the simulation dropped the request";
|
||||
}
|
||||
|
||||
/// Answer one control request.
|
||||
pub async fn handle(state: &AppState, request: ControlRequest) -> ControlReply {
|
||||
match request {
|
||||
ControlRequest::Status => status(state),
|
||||
ControlRequest::Healthz => healthz(state),
|
||||
ControlRequest::Metrics => prometheus(state),
|
||||
ControlRequest::Events { since, limit } => events(state, since, limit),
|
||||
ControlRequest::Stimulate { body } => stimulate(state, body).await,
|
||||
ControlRequest::Reward { body } => reward(state, body).await,
|
||||
ControlRequest::Chat { body } => chat(state, body).await,
|
||||
ControlRequest::Checkpoint => checkpoint(state).await,
|
||||
ControlRequest::Pause => pause(state).await,
|
||||
ControlRequest::Resume => resume(state).await,
|
||||
}
|
||||
}
|
||||
|
||||
// -- GET /status ------------------------------------------------------------------------------
|
||||
|
||||
/// The feed header minus `events` and `attachments`, plus `version` and `checkpoint`.
|
||||
///
|
||||
/// Built by reshaping the header itself rather than by a parallel struct, so "same fields as the
|
||||
/// feed header" cannot drift.
|
||||
fn status(state: &AppState) -> ControlReply {
|
||||
let snapshot = state.snapshot();
|
||||
let mut value = match serde_json::to_value(&snapshot.header) {
|
||||
Ok(Value::Object(map)) => map,
|
||||
_ => return ControlReply::error(500, "could not render the status"),
|
||||
};
|
||||
value.remove("events");
|
||||
value.remove("attachments");
|
||||
let versions = state.shared.versions.get().cloned().unwrap_or_default();
|
||||
value.insert(
|
||||
"version".to_string(),
|
||||
serde_json::to_value(versions).unwrap_or(Value::Null),
|
||||
);
|
||||
let checkpoint = state
|
||||
.shared
|
||||
.checkpoint
|
||||
.lock()
|
||||
.map(|status| *status)
|
||||
.unwrap_or_default();
|
||||
value.insert(
|
||||
"checkpoint".to_string(),
|
||||
serde_json::to_value(checkpoint).unwrap_or(Value::Null),
|
||||
);
|
||||
// The readout's own numbers, additive: one row per channel with the role it reads, the resting
|
||||
// rate it is normalized against and the score the last decode computed, plus the roles a
|
||||
// restore has left for the next decode to calibrate (`docs/readout.md`).
|
||||
let decoder = state
|
||||
.shared
|
||||
.decoder
|
||||
.lock()
|
||||
.map(|status| status.clone())
|
||||
.unwrap_or_default();
|
||||
value.insert(
|
||||
"decoder".to_string(),
|
||||
serde_json::to_value(decoder).unwrap_or(Value::Null),
|
||||
);
|
||||
ControlReply::json(200, Value::Object(value))
|
||||
}
|
||||
|
||||
// -- GET /healthz -----------------------------------------------------------------------------
|
||||
|
||||
/// 200 while the loop advanced in the last 2 seconds, else 503. This is what systemd's
|
||||
/// `wait-for-health` helper and `infra/bin/fly-watchdog` check first.
|
||||
fn healthz(state: &AppState) -> ControlReply {
|
||||
if state.shared.healthy(now_wall_ms()) {
|
||||
ControlReply::json(200, json!({ "status": "ok" }))
|
||||
} else {
|
||||
ControlReply::error(503, "loop has not advanced in the last 2 seconds")
|
||||
}
|
||||
}
|
||||
|
||||
// -- GET /metrics -----------------------------------------------------------------------------
|
||||
|
||||
fn prometheus(state: &AppState) -> ControlReply {
|
||||
let snapshot = state.snapshot();
|
||||
ControlReply::text(
|
||||
200,
|
||||
metrics::render(&state.shared.metrics, &snapshot, now_wall_ms()),
|
||||
)
|
||||
}
|
||||
|
||||
// -- GET /events ------------------------------------------------------------------------------
|
||||
|
||||
/// `?since=<id>&limit=<n>`, parsed as leniently as the reference server's
|
||||
/// `Number.parseInt(...) || 0`: anything unreadable falls back to the default.
|
||||
fn events(state: &AppState, since: Option<String>, limit: Option<String>) -> ControlReply {
|
||||
let since = since
|
||||
.as_deref()
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.unwrap_or(0);
|
||||
let limit = limit
|
||||
.as_deref()
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|limit| *limit > 0)
|
||||
.unwrap_or(100)
|
||||
.min(crate::eventlog::RING_CAPACITY);
|
||||
let events = state.shared.events.page(since, limit);
|
||||
ControlReply::json(200, json!({ "events": events }))
|
||||
}
|
||||
|
||||
// -- POST /stimulate --------------------------------------------------------------------------
|
||||
|
||||
/// `chat`, `points` or `operator`, as `isActionSource` in the reference server.
|
||||
pub fn action_source(value: Option<&Value>) -> Option<&str> {
|
||||
match value.and_then(Value::as_str) {
|
||||
Some(source @ ("chat" | "points" | "operator")) => Some(source),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn stimulate(state: &AppState, request: Option<Value>) -> ControlReply {
|
||||
let Some(request) = request else {
|
||||
return ControlReply::error(400, "expected { durationMs?, by, source }");
|
||||
};
|
||||
let (Some(by), Some(source)) = (
|
||||
request.get("by").and_then(Value::as_str),
|
||||
action_source(request.get("source")),
|
||||
) else {
|
||||
return ControlReply::error(400, "expected { durationMs?, by, source }");
|
||||
};
|
||||
let duration_ms = match request.get("durationMs") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(value) => match value
|
||||
.as_f64()
|
||||
.filter(|value| value.is_finite() && *value > 0.0)
|
||||
{
|
||||
Some(value) => Some(value),
|
||||
None => {
|
||||
return ControlReply::error(400, "durationMs must be a positive number");
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let (reply, response) = oneshot::channel();
|
||||
let command = Command::Stimulate {
|
||||
duration_ms,
|
||||
by: by.to_string(),
|
||||
source: source.to_string(),
|
||||
reply,
|
||||
};
|
||||
match dispatch(state, command, response).await {
|
||||
Ok(Ok(event_id)) => ControlReply::json(202, json!({ "eventId": event_id })),
|
||||
Ok(Err(refusal)) => {
|
||||
ControlReply::json(429, json!({ "retryAfterMs": refusal.retry_after_ms() }))
|
||||
}
|
||||
Err(reply) => reply,
|
||||
}
|
||||
}
|
||||
|
||||
// -- POST /reward -----------------------------------------------------------------------------
|
||||
|
||||
async fn reward(state: &AppState, request: Option<Value>) -> ControlReply {
|
||||
if !state.shared.config.control.allow_reward {
|
||||
// Present so that the later "who trains the fly" work does not change the API.
|
||||
return ControlReply::error(403, "reward is disabled (control.allow_reward = false)");
|
||||
}
|
||||
let Some(request) = request else {
|
||||
return ControlReply::error(400, "expected { value, by, source }");
|
||||
};
|
||||
let (Some(value), Some(by), Some(source)) = (
|
||||
request
|
||||
.get("value")
|
||||
.and_then(Value::as_f64)
|
||||
.filter(|value| value.is_finite()),
|
||||
request.get("by").and_then(Value::as_str),
|
||||
action_source(request.get("source")),
|
||||
) else {
|
||||
return ControlReply::error(400, "expected { value, by, source }");
|
||||
};
|
||||
|
||||
let (reply, response) = oneshot::channel();
|
||||
let command = Command::Reward {
|
||||
value,
|
||||
by: by.to_string(),
|
||||
source: source.to_string(),
|
||||
reply,
|
||||
};
|
||||
match dispatch(state, command, response).await {
|
||||
Ok(event_id) => ControlReply::json(202, json!({ "eventId": event_id })),
|
||||
Err(reply) => reply,
|
||||
}
|
||||
}
|
||||
|
||||
// -- POST /chat -------------------------------------------------------------------------------
|
||||
|
||||
/// `{ by, text, bot? }`: one line for the feed header's chat ring.
|
||||
///
|
||||
/// The kill switch is answered here, because it is pure configuration and a 403 should not need
|
||||
/// the sim thread. Everything else — the name rule, the sanitizer, the deny list and the two rate
|
||||
/// limits — is decided on the sim thread, which owns the ring, the limiter and the event log.
|
||||
///
|
||||
/// Status codes, per `docs/control-api.md`: 202 with the event id, 403 while chat is disabled,
|
||||
/// 422 when a rule refused the line, 429 when a rate limit did, 400 for a malformed body.
|
||||
async fn chat(state: &AppState, request: Option<Value>) -> ControlReply {
|
||||
if !state.shared.config.chat.enabled {
|
||||
return ControlReply::error(403, "chat is disabled (chat.enabled = false)");
|
||||
}
|
||||
let Some(request) = request else {
|
||||
return ControlReply::error(400, "expected { by, text, bot? }");
|
||||
};
|
||||
let (Some(by), Some(text)) = (
|
||||
request.get("by").and_then(Value::as_str),
|
||||
request.get("text").and_then(Value::as_str),
|
||||
) else {
|
||||
state
|
||||
.shared
|
||||
.metrics
|
||||
.chat_rejected(crate::chat::RejectReason::Malformed);
|
||||
return ControlReply::error(400, "expected { by, text, bot? }");
|
||||
};
|
||||
let bot = match request.get("bot") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(value)) => *value,
|
||||
Some(_) => return ControlReply::error(400, "bot must be a boolean"),
|
||||
};
|
||||
|
||||
let (reply, response) = oneshot::channel();
|
||||
let command = Command::Chat {
|
||||
by: by.to_string(),
|
||||
text: text.to_string(),
|
||||
bot,
|
||||
reply,
|
||||
};
|
||||
match dispatch(state, command, response).await {
|
||||
Ok(Ok(event_id)) => ControlReply::json(202, json!({ "eventId": event_id })),
|
||||
Ok(Err(ChatRefusal::Rejected(reason))) => ControlReply::json(
|
||||
422,
|
||||
json!({ "error": format!("chat line refused: {}", reason.as_str()) }),
|
||||
),
|
||||
Ok(Err(ChatRefusal::RateLimited { retry_after_ms })) => {
|
||||
ControlReply::json(429, json!({ "retryAfterMs": retry_after_ms }))
|
||||
}
|
||||
Err(reply) => reply,
|
||||
}
|
||||
}
|
||||
|
||||
// -- POST /checkpoint, /pause, /resume --------------------------------------------------------
|
||||
|
||||
async fn checkpoint(state: &AppState) -> ControlReply {
|
||||
let (reply, response) = oneshot::channel();
|
||||
// A forced checkpoint answers only once the bytes are on disk, so a caller that is about to
|
||||
// restart the service can rely on it.
|
||||
match dispatch_with_timeout(state, Command::Checkpoint { reply }, response, None).await {
|
||||
Ok(Ok(generation)) => ControlReply::json(200, json!({ "generation": generation })),
|
||||
Ok(Err(message)) => ControlReply::error(500, message),
|
||||
Err(reply) => reply,
|
||||
}
|
||||
}
|
||||
|
||||
async fn pause(state: &AppState) -> ControlReply {
|
||||
let (reply, response) = oneshot::channel();
|
||||
// A pause takes an implicit durable checkpoint, so it can take as long as one write.
|
||||
match dispatch_with_timeout(state, Command::Pause { reply }, response, None).await {
|
||||
Ok(status) => ControlReply::json(200, json!({ "status": status })),
|
||||
Err(reply) => reply,
|
||||
}
|
||||
}
|
||||
|
||||
async fn resume(state: &AppState) -> ControlReply {
|
||||
let (reply, response) = oneshot::channel();
|
||||
match dispatch(state, Command::Resume { reply }, response).await {
|
||||
Ok(status) => ControlReply::json(200, json!({ "status": status })),
|
||||
Err(reply) => reply,
|
||||
}
|
||||
}
|
||||
|
||||
// -- plumbing ---------------------------------------------------------------------------------
|
||||
|
||||
async fn dispatch<T>(
|
||||
state: &AppState,
|
||||
command: Command,
|
||||
response: oneshot::Receiver<T>,
|
||||
) -> Result<T, ControlReply> {
|
||||
dispatch_with_timeout(state, command, response, Some(COMMAND_TIMEOUT)).await
|
||||
}
|
||||
|
||||
/// Queue a command and wait for its reply.
|
||||
///
|
||||
/// The queue is bounded: a full queue is a 503 rather than a wait, because the only way to fill
|
||||
/// it is a wedged loop or a flood, and neither is improved by blocking the caller.
|
||||
async fn dispatch_with_timeout<T>(
|
||||
state: &AppState,
|
||||
command: Command,
|
||||
response: oneshot::Receiver<T>,
|
||||
timeout: Option<Duration>,
|
||||
) -> Result<T, ControlReply> {
|
||||
if let Err(error) = state.commands.try_send(command) {
|
||||
return Err(match error {
|
||||
tokio::sync::mpsc::error::TrySendError::Full(_) => {
|
||||
ControlReply::error(503, unavailable::QUEUE_FULL)
|
||||
}
|
||||
tokio::sync::mpsc::error::TrySendError::Closed(_) => {
|
||||
ControlReply::error(503, unavailable::STOPPED)
|
||||
}
|
||||
});
|
||||
}
|
||||
let awaited = match timeout {
|
||||
Some(timeout) => match tokio::time::timeout(timeout, response).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => return Err(ControlReply::error(503, unavailable::TIMED_OUT)),
|
||||
},
|
||||
None => response.await,
|
||||
};
|
||||
awaited.map_err(|_| ControlReply::error(503, unavailable::DROPPED))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn action_sources_are_the_three_the_contract_names() {
|
||||
for source in ["chat", "points", "operator"] {
|
||||
assert_eq!(action_source(Some(&json!(source))), Some(source));
|
||||
}
|
||||
for rejected in [json!("bridge"), json!(1), json!(null), Value::Null] {
|
||||
assert_eq!(action_source(Some(&rejected)), None);
|
||||
}
|
||||
assert_eq!(action_source(None), None);
|
||||
}
|
||||
}
|
||||
993
services/flysim/crates/flysim/src/controlbus.rs
Normal file
993
services/flysim/crates/flysim/src/controlbus.rs
Normal file
|
|
@ -0,0 +1,993 @@
|
|||
//! The control API as flybus RPC services with per-client grants (CTRL-01,
|
||||
//! `docs/design/flybus.md`, "Control over the bus").
|
||||
//!
|
||||
//! Both halves of the encoding live here, so the services flysim registers and the edge that
|
||||
//! calls them (`fly-control-edge`) cannot drift apart:
|
||||
//!
|
||||
//! - [`encode_request`] / [`decode_request`]: a [`ControlRequest`] as `(service, method,
|
||||
//! payload)`. The service is a [`Family`] in a [`Scope`]; the method is `Control.<Name>`.
|
||||
//! - [`encode_reply`] / [`decode_reply`]: a [`ControlReply`] as an RPC outcome
|
||||
//! `{"status": <u16>, "body": <JSON>}` or `{"status": <u16>, "text": "..."}`, with a body too
|
||||
//! large for an envelope carried as a `body` artifact instead.
|
||||
//!
|
||||
//! The `status` is the `docs/control-api.md` status code of the same request, used as the
|
||||
//! outcome's vocabulary rather than as transport: a bus caller reads `429 {retryAfterMs}`
|
||||
//! exactly as an HTTP caller does, and the edge turns it back into HTTP with no table of its own.
|
||||
//!
|
||||
//! **Grants.** Bus grants are per service name, so the surface is split into five service
|
||||
//! families and every participant is granted the families its role needs, by exact name, and
|
||||
//! nothing else ([`Role`], [`grants`]). [`host_grants`] is the only grant that may register a
|
||||
//! control service, and it belongs to an in-process participant no socket is bound to. No family
|
||||
//! has a method that presses a button, edits game memory or changes the reward catalog, and no
|
||||
//! role is granted `Any`, a prefix, `register`, `publish`, `subscribe` or topic management, so on
|
||||
//! a router shared with environment or agent services a control client still cannot name them:
|
||||
//! the "no button endpoint" guarantee is the grant table.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use flybus::{
|
||||
Artifact, BusError, Client, ClientConfig, Grants, Pattern, Policy, Request, Router,
|
||||
ServiceConfig,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::AppState;
|
||||
use crate::control::{ControlReply, ControlRequest, ReplyBody};
|
||||
|
||||
/// The in-process participant that registers the control services. Never bound to a socket.
|
||||
pub const HOST: &str = "flysim-control";
|
||||
/// The participant `fly-control-edge` connects as, on [`EDGE_SOCKET`].
|
||||
pub const EDGE: &str = "fly-control-edge";
|
||||
/// `<bus_dir>/control-edge.sock`, launcher-bound to [`EDGE`].
|
||||
pub const EDGE_SOCKET: &str = "control-edge.sock";
|
||||
/// `<bus_dir>/control/<role>.sock`, one per native [`Role`], each launcher-bound to that role.
|
||||
pub const ROLE_SOCKET_DIR: &str = "control";
|
||||
/// The one session today: the live fly.
|
||||
pub const LIVE_SESSION: &str = "main";
|
||||
/// The one agent today (the session runtime's agent id).
|
||||
pub const LIVE_AGENT: &str = "fly";
|
||||
/// Every service name starts with this.
|
||||
pub const PREFIX: &str = "fly.control.";
|
||||
/// Replies up to this many JSON bytes ride in the envelope; anything larger becomes a `body`
|
||||
/// artifact. Well under flybus's 65,536-byte envelope, leaving room for the router's ids. An
|
||||
/// `/events` page can be far larger (4,096 events), `/status` is a few KB.
|
||||
pub const INLINE_MAX: usize = 48 * 1024;
|
||||
/// The attachment name of an out-of-line body.
|
||||
pub const BODY_ARTIFACT: &str = "body";
|
||||
/// The attachment name of an out-of-line request body: a `request` JSON value larger than
|
||||
/// [`INLINE_MAX`] travels as this artifact, and the payload says so with `requestArtifact: true`.
|
||||
/// The direct API takes bodies up to the HTTP layer's own limit, so the bus must too.
|
||||
pub const REQUEST_ARTIFACT: &str = "request";
|
||||
/// Per-service bounds. A full service refuses with `BACKPRESSURE` (the edge's 503 "queue is
|
||||
/// full") instead of queueing without limit; each family has its own, so a stuck checkpoint
|
||||
/// cannot hold up `/status`.
|
||||
pub const SERVICE_CONFIG: ServiceConfig = ServiceConfig {
|
||||
max_queued: 16,
|
||||
max_in_flight: 16,
|
||||
};
|
||||
|
||||
/// A group of control methods behind one service name, the unit a grant names.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum Family {
|
||||
/// `Control.Status`, `Control.Healthz`, `Control.Metrics`, `Control.Events`. Session-scoped:
|
||||
/// the session's status (the one fly's, while a session has one), its health, its metrics
|
||||
/// and its event log.
|
||||
Read,
|
||||
/// `Control.Status` for one agent. Agent-scoped. With one fly per session it answers what
|
||||
/// the session's `Control.Status` does; with N flies it is where each fly's own view lives.
|
||||
Status,
|
||||
/// `Control.Stimulate`: a sugar pulse into one agent's brain. Agent-scoped.
|
||||
Sugar,
|
||||
/// `Control.Reward`: a reinforcement pulse into one agent's plasticity. Agent-scoped.
|
||||
Reward,
|
||||
/// `Control.Chat`: a line for the session's on-screen ring. Session-scoped.
|
||||
Chat,
|
||||
/// `Control.Checkpoint`, `Control.Pause`, `Control.Resume`. Session-scoped.
|
||||
Ops,
|
||||
}
|
||||
|
||||
impl Family {
|
||||
pub const ALL: [Family; 6] = [
|
||||
Family::Read,
|
||||
Family::Status,
|
||||
Family::Sugar,
|
||||
Family::Reward,
|
||||
Family::Chat,
|
||||
Family::Ops,
|
||||
];
|
||||
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Family::Read => "read",
|
||||
Family::Status => "status",
|
||||
Family::Sugar => "sugar",
|
||||
Family::Reward => "reward",
|
||||
Family::Chat => "chat",
|
||||
Family::Ops => "ops",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the family acts on one agent (and so has one service per agent).
|
||||
pub const fn agent_scoped(self) -> bool {
|
||||
matches!(self, Family::Status | Family::Sugar | Family::Reward)
|
||||
}
|
||||
|
||||
/// Every method the family's service answers.
|
||||
pub const fn methods(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Family::Read => &[
|
||||
"Control.Status",
|
||||
"Control.Healthz",
|
||||
"Control.Metrics",
|
||||
"Control.Events",
|
||||
],
|
||||
Family::Status => &["Control.Status"],
|
||||
Family::Sugar => &["Control.Stimulate"],
|
||||
Family::Reward => &["Control.Reward"],
|
||||
Family::Chat => &["Control.Chat"],
|
||||
Family::Ops => &["Control.Checkpoint", "Control.Pause", "Control.Resume"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One agent (fly) of a session, and the controller port it plays on, if the environment has
|
||||
/// ports. A Game Boy has one pad, so the live fly is port 0; a console with four controller ports
|
||||
/// can carry four flies, one per port.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AgentScope {
|
||||
pub id: String,
|
||||
pub port: Option<u32>,
|
||||
}
|
||||
|
||||
impl AgentScope {
|
||||
pub fn new(id: &str, port: Option<u32>) -> AgentScope {
|
||||
AgentScope {
|
||||
id: id.to_owned(),
|
||||
port,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which agents of a scope a grant covers.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Agents<'a> {
|
||||
/// Every agent of the session.
|
||||
All,
|
||||
/// One agent, by id.
|
||||
Id(&'a str),
|
||||
/// The agent bound to one controller port.
|
||||
Port(u32),
|
||||
}
|
||||
|
||||
/// Which session, and which agents in it, a set of services addresses.
|
||||
///
|
||||
/// Session-scoped families are `fly.control.s.<session>.<family>`; agent-scoped ones are
|
||||
/// `fly.control.s.<session>.a.<agent>.<family>`, one per agent. With N flies in a session each
|
||||
/// fly has its own status, sugar and reward services, so a grant can name one fly (or the fly on
|
||||
/// one port); with M sessions on a router each has its own names, so a grant can name one
|
||||
/// session. A single-fly deployment is the same design with one agent: multi-fly is
|
||||
/// configuration, not a new surface.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Scope {
|
||||
pub session: String,
|
||||
pub agents: Vec<AgentScope>,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
/// The live fly: session [`LIVE_SESSION`], agent [`LIVE_AGENT`] on port 0 (the Game Boy's
|
||||
/// one pad).
|
||||
pub fn live() -> Scope {
|
||||
Scope {
|
||||
session: LIVE_SESSION.to_owned(),
|
||||
agents: vec![AgentScope::new(LIVE_AGENT, Some(0))],
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse ids that would not make a valid, unambiguous service name segment, and two agents
|
||||
/// with one id or on one port.
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
let segment = |s: &str| {
|
||||
!s.is_empty()
|
||||
&& s.len() <= 48
|
||||
&& s.bytes().all(|c| {
|
||||
c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, b'_' | b'-')
|
||||
})
|
||||
};
|
||||
if !segment(&self.session) {
|
||||
bail!(
|
||||
"control scope: session id {:?} is not [a-z0-9_-]{{1,48}}",
|
||||
self.session
|
||||
);
|
||||
}
|
||||
if self.agents.is_empty() {
|
||||
bail!("control scope: no agents");
|
||||
}
|
||||
for (index, agent) in self.agents.iter().enumerate() {
|
||||
if !segment(&agent.id) {
|
||||
bail!("control scope: agent id {:?} is not [a-z0-9_-]{{1,48}}", agent.id);
|
||||
}
|
||||
for other in &self.agents[..index] {
|
||||
if other.id == agent.id {
|
||||
bail!("control scope: agent {:?} twice", agent.id);
|
||||
}
|
||||
if agent.port.is_some() && other.port == agent.port {
|
||||
bail!(
|
||||
"control scope: agents {:?} and {:?} on one port",
|
||||
other.id,
|
||||
agent.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The agent ids, in order.
|
||||
pub fn agent_ids(&self) -> impl Iterator<Item = &str> {
|
||||
self.agents.iter().map(|agent| agent.id.as_str())
|
||||
}
|
||||
|
||||
/// The agent bound to `port`.
|
||||
pub fn agent_on_port(&self, port: u32) -> Option<&str> {
|
||||
self.agents
|
||||
.iter()
|
||||
.find(|agent| agent.port == Some(port))
|
||||
.map(|agent| agent.id.as_str())
|
||||
}
|
||||
|
||||
/// The service name of a session-scoped `family`, or of an agent-scoped one for `agent`.
|
||||
pub fn service(&self, family: Family, agent: &str) -> String {
|
||||
if family.agent_scoped() {
|
||||
format!("{PREFIX}s.{}.a.{agent}.{}", self.session, family.as_str())
|
||||
} else {
|
||||
format!("{PREFIX}s.{}.{}", self.session, family.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Every service in this scope, with its family and its agent (`None` for a session-scoped
|
||||
/// one): what the host registers.
|
||||
pub fn services(&self) -> Vec<(Family, Option<&str>, String)> {
|
||||
let mut out = Vec::new();
|
||||
for family in Family::ALL {
|
||||
if family.agent_scoped() {
|
||||
for agent in self.agent_ids() {
|
||||
out.push((family, Some(agent), self.service(family, agent)));
|
||||
}
|
||||
} else {
|
||||
out.push((family, None, self.service(family, "")));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The services of `families` in this scope: session-scoped ones, and agent-scoped ones for
|
||||
/// the `agents` selected. A port no agent is bound to selects no agent.
|
||||
pub fn services_of(&self, families: &[Family], agents: Agents<'_>) -> Vec<String> {
|
||||
let selected = match agents {
|
||||
Agents::All => None,
|
||||
Agents::Id(id) => Some(Some(id)),
|
||||
Agents::Port(port) => Some(self.agent_on_port(port)),
|
||||
};
|
||||
self.services()
|
||||
.into_iter()
|
||||
.filter(|(family, agent, _)| {
|
||||
families.contains(family)
|
||||
&& match (agent, selected) {
|
||||
(Some(agent), Some(selected)) => selected == Some(*agent),
|
||||
_ => true,
|
||||
}
|
||||
})
|
||||
.map(|(_, _, name)| name)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The clients of the control API today, by what they need (`docs/design/flybus.md`, "Control
|
||||
/// over the bus", grant table).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Role {
|
||||
/// The broadcast page: it waits for `/healthz` and may read `/status`.
|
||||
Stage,
|
||||
/// The Twitch bridge: reads, sugar from points and chat commands, on-screen chat lines.
|
||||
Bridge,
|
||||
/// The watchdog, the probation and shadow guards, the loop-recover ladder and the stream
|
||||
/// check: reads only. A restart is systemd's, never a control call.
|
||||
Watchdog,
|
||||
/// The operator's own hand: everything the control API has.
|
||||
Operator,
|
||||
/// `fly-control-edge`, which serves the unchanged HTTP surface on `:7401`. Loopback HTTP has
|
||||
/// no caller identity, so the edge carries exactly the authority `:7401` has today: every
|
||||
/// family. Narrowing a client is moving it off HTTP onto its own role.
|
||||
Edge,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
pub const ALL: [Role; 5] = [
|
||||
Role::Stage,
|
||||
Role::Bridge,
|
||||
Role::Watchdog,
|
||||
Role::Operator,
|
||||
Role::Edge,
|
||||
];
|
||||
/// The roles with a socket of their own under [`ROLE_SOCKET_DIR`].
|
||||
pub const NATIVE: [Role; 4] = [Role::Stage, Role::Bridge, Role::Watchdog, Role::Operator];
|
||||
|
||||
/// The participant id the router binds to this role's socket.
|
||||
pub const fn participant(self) -> &'static str {
|
||||
match self {
|
||||
Role::Stage => "fly-stage",
|
||||
Role::Bridge => "fly-bridge",
|
||||
Role::Watchdog => "fly-watchdog",
|
||||
Role::Operator => "fly-operator",
|
||||
Role::Edge => EDGE,
|
||||
}
|
||||
}
|
||||
|
||||
/// The socket file name (under [`ROLE_SOCKET_DIR`] for native roles).
|
||||
pub const fn socket_name(self) -> &'static str {
|
||||
match self {
|
||||
Role::Stage => "stage.sock",
|
||||
Role::Bridge => "bridge.sock",
|
||||
Role::Watchdog => "watchdog.sock",
|
||||
Role::Operator => "operator.sock",
|
||||
Role::Edge => EDGE_SOCKET,
|
||||
}
|
||||
}
|
||||
|
||||
/// The families this role may call.
|
||||
pub const fn families(self) -> &'static [Family] {
|
||||
match self {
|
||||
Role::Stage | Role::Watchdog => &[Family::Read, Family::Status],
|
||||
Role::Bridge => &[Family::Read, Family::Status, Family::Sugar, Family::Chat],
|
||||
Role::Operator | Role::Edge => &Family::ALL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `<bus_dir>/control-edge.sock` or `<bus_dir>/control/<role>.sock`.
|
||||
pub fn socket_path(bus_dir: &Path, role: Role) -> PathBuf {
|
||||
match role {
|
||||
Role::Edge => bus_dir.join(EDGE_SOCKET),
|
||||
native => bus_dir.join(ROLE_SOCKET_DIR).join(native.socket_name()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact `call` grants on `families` in `scope`, for the `agents` selected, nothing else.
|
||||
pub fn call_grants(scope: &Scope, families: &[Family], agents: Agents<'_>) -> Grants {
|
||||
Grants {
|
||||
call: scope
|
||||
.services_of(families, agents)
|
||||
.iter()
|
||||
.map(|name| Pattern::exact(name))
|
||||
.collect(),
|
||||
..Grants::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// What `role` may do: call its families' services in `scope`, for every agent, by exact name.
|
||||
pub fn grants(role: Role, scope: &Scope) -> Grants {
|
||||
call_grants(scope, role.families(), Agents::All)
|
||||
}
|
||||
|
||||
/// What `role` may do, limited to the `agents` selected: the same families, but the agent-scoped
|
||||
/// ones only for that fly (or the fly on that port). A bridge for one fly of several, say.
|
||||
pub fn grants_for(role: Role, scope: &Scope, agents: Agents<'_>) -> Grants {
|
||||
call_grants(scope, role.families(), agents)
|
||||
}
|
||||
|
||||
/// A player backing one fly (by id or by port) in a multi-fly session: read the session, see
|
||||
/// and sugar that fly, nothing else. Not wired to a socket yet; it is how per-agent scoping is
|
||||
/// granted when players arrive.
|
||||
pub fn player_grants(scope: &Scope, agents: Agents<'_>) -> Grants {
|
||||
call_grants(scope, &[Family::Read, Family::Status, Family::Sugar], agents)
|
||||
}
|
||||
|
||||
/// The host's grant: register every control service of `scope`, by exact name, and nothing else.
|
||||
pub fn host_grants(scope: &Scope) -> Grants {
|
||||
Grants {
|
||||
register: scope
|
||||
.services()
|
||||
.iter()
|
||||
.map(|(_, _, name)| Pattern::exact(name))
|
||||
.collect(),
|
||||
..Grants::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// `base` plus the control participants: the host and every [`Role`].
|
||||
pub fn policy(base: Policy, scope: &Scope) -> Policy {
|
||||
let mut policy = base.client(HOST, host_grants(scope));
|
||||
for role in Role::ALL {
|
||||
policy = policy.client(role.participant(), grants(role, scope));
|
||||
}
|
||||
policy
|
||||
}
|
||||
|
||||
// -- encoding ---------------------------------------------------------------------------------
|
||||
|
||||
/// A request as `(family, method, payload)`.
|
||||
pub fn encode_request(request: &ControlRequest) -> (Family, &'static str, Map<String, Value>) {
|
||||
let mut payload = Map::new();
|
||||
let mut body = |value: &Option<Value>| {
|
||||
if let Some(value) = value {
|
||||
payload.insert("request".to_owned(), value.clone());
|
||||
}
|
||||
};
|
||||
let (family, method) = match request {
|
||||
ControlRequest::Status => (Family::Read, "Control.Status"),
|
||||
ControlRequest::Healthz => (Family::Read, "Control.Healthz"),
|
||||
ControlRequest::Metrics => (Family::Read, "Control.Metrics"),
|
||||
ControlRequest::Events { .. } => (Family::Read, "Control.Events"),
|
||||
ControlRequest::Stimulate { body: value } => {
|
||||
body(value);
|
||||
(Family::Sugar, "Control.Stimulate")
|
||||
}
|
||||
ControlRequest::Reward { body: value } => {
|
||||
body(value);
|
||||
(Family::Reward, "Control.Reward")
|
||||
}
|
||||
ControlRequest::Chat { body: value } => {
|
||||
body(value);
|
||||
(Family::Chat, "Control.Chat")
|
||||
}
|
||||
ControlRequest::Checkpoint => (Family::Ops, "Control.Checkpoint"),
|
||||
ControlRequest::Pause => (Family::Ops, "Control.Pause"),
|
||||
ControlRequest::Resume => (Family::Ops, "Control.Resume"),
|
||||
};
|
||||
if let ControlRequest::Events { since, limit } = request {
|
||||
if let Some(since) = since {
|
||||
payload.insert("since".to_owned(), Value::String(since.clone()));
|
||||
}
|
||||
if let Some(limit) = limit {
|
||||
payload.insert("limit".to_owned(), Value::String(limit.clone()));
|
||||
}
|
||||
}
|
||||
(family, method, payload)
|
||||
}
|
||||
|
||||
/// Move a `request` body larger than [`INLINE_MAX`] out of `payload` and return its JSON bytes,
|
||||
/// leaving `requestArtifact: true` behind. `None` (payload untouched) when it fits.
|
||||
pub fn take_out_of_line_request(payload: &mut Map<String, Value>) -> Option<Vec<u8>> {
|
||||
let bytes = serde_json::to_vec(payload.get("request")?).ok()?;
|
||||
if bytes.len() <= INLINE_MAX {
|
||||
return None;
|
||||
}
|
||||
payload.remove("request");
|
||||
payload.insert("requestArtifact".to_owned(), Value::Bool(true));
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
/// Why a bus request could not be read: answered as a control-API reply.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Undecodable(pub ControlReply);
|
||||
|
||||
/// The request a `(family, method, payload)` names. A method the family does not have is a 404,
|
||||
/// as an unknown route is over HTTP; an unknown or mistyped payload field is a 400.
|
||||
pub fn decode_request(
|
||||
family: Family,
|
||||
method: &str,
|
||||
payload: &Map<String, Value>,
|
||||
) -> Result<ControlRequest, Undecodable> {
|
||||
if !family.methods().contains(&method) {
|
||||
return Err(Undecodable(ControlReply::error(
|
||||
404,
|
||||
format!(
|
||||
"no such method: {method} on the {} service",
|
||||
family.as_str()
|
||||
),
|
||||
)));
|
||||
}
|
||||
let allowed: &[&str] = match method {
|
||||
"Control.Events" => &["since", "limit"],
|
||||
"Control.Stimulate" | "Control.Reward" | "Control.Chat" => &["request"],
|
||||
_ => &[],
|
||||
};
|
||||
if let Some(field) = payload.keys().find(|key| !allowed.contains(&key.as_str())) {
|
||||
return Err(Undecodable(ControlReply::error(
|
||||
400,
|
||||
format!("{method}: unknown field {field:?}"),
|
||||
)));
|
||||
}
|
||||
let string = |key: &str| -> Result<Option<String>, Undecodable> {
|
||||
match payload.get(key) {
|
||||
None => Ok(None),
|
||||
Some(Value::String(value)) => Ok(Some(value.clone())),
|
||||
Some(_) => Err(Undecodable(ControlReply::error(
|
||||
400,
|
||||
format!("{method}: {key} must be a string"),
|
||||
))),
|
||||
}
|
||||
};
|
||||
let body = || payload.get("request").cloned();
|
||||
Ok(match method {
|
||||
"Control.Status" => ControlRequest::Status,
|
||||
"Control.Healthz" => ControlRequest::Healthz,
|
||||
"Control.Metrics" => ControlRequest::Metrics,
|
||||
"Control.Events" => ControlRequest::Events {
|
||||
since: string("since")?,
|
||||
limit: string("limit")?,
|
||||
},
|
||||
"Control.Stimulate" => ControlRequest::Stimulate { body: body() },
|
||||
"Control.Reward" => ControlRequest::Reward { body: body() },
|
||||
"Control.Chat" => ControlRequest::Chat { body: body() },
|
||||
"Control.Checkpoint" => ControlRequest::Checkpoint,
|
||||
"Control.Pause" => ControlRequest::Pause,
|
||||
"Control.Resume" => ControlRequest::Resume,
|
||||
_ => unreachable!("every method of every family is listed above"),
|
||||
})
|
||||
}
|
||||
|
||||
/// A body too large for an envelope: its bytes and content type.
|
||||
pub type OutOfLine = (Vec<u8>, &'static str);
|
||||
|
||||
/// A reply as an outcome, plus the bytes of an out-of-line body (and their content type) when
|
||||
/// the body is larger than [`INLINE_MAX`].
|
||||
pub fn encode_reply(reply: &ControlReply) -> (Map<String, Value>, Option<OutOfLine>) {
|
||||
let mut outcome = Map::new();
|
||||
outcome.insert("status".to_owned(), json!(reply.status));
|
||||
match &reply.body {
|
||||
ReplyBody::Json(value) => {
|
||||
let bytes = serde_json::to_vec(value).unwrap_or_default();
|
||||
if bytes.len() <= INLINE_MAX {
|
||||
outcome.insert("body".to_owned(), value.clone());
|
||||
(outcome, None)
|
||||
} else {
|
||||
outcome.insert("bodyArtifact".to_owned(), json!("application/json"));
|
||||
(outcome, Some((bytes, "application/json")))
|
||||
}
|
||||
}
|
||||
ReplyBody::Text(text) => {
|
||||
if text.len() <= INLINE_MAX {
|
||||
outcome.insert("text".to_owned(), Value::String(text.clone()));
|
||||
(outcome, None)
|
||||
} else {
|
||||
outcome.insert("bodyArtifact".to_owned(), json!("text/plain"));
|
||||
(outcome, Some((text.clone().into_bytes(), "text/plain")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reply an outcome carries; `artifact` is the `body` attachment's bytes, read by the caller
|
||||
/// only when the outcome names one.
|
||||
pub fn decode_reply(
|
||||
outcome: &Map<String, Value>,
|
||||
artifact: Option<Vec<u8>>,
|
||||
) -> Result<ControlReply, String> {
|
||||
let status = outcome
|
||||
.get("status")
|
||||
.and_then(Value::as_u64)
|
||||
.filter(|status| (100..=599).contains(status))
|
||||
.ok_or("a control outcome without a status")? as u16;
|
||||
if let Some(value) = outcome.get("body") {
|
||||
return Ok(ControlReply::json(status, value.clone()));
|
||||
}
|
||||
if let Some(Value::String(text)) = outcome.get("text") {
|
||||
return Ok(ControlReply::text(status, text.clone()));
|
||||
}
|
||||
match outcome.get("bodyArtifact").and_then(Value::as_str) {
|
||||
Some(kind) => {
|
||||
let bytes = artifact.ok_or("a control outcome whose body artifact is missing")?;
|
||||
match kind {
|
||||
"application/json" => serde_json::from_slice(&bytes)
|
||||
.map(|value| ControlReply::json(status, value))
|
||||
.map_err(|error| format!("a control body artifact is not JSON: {error}")),
|
||||
"text/plain" => String::from_utf8(bytes)
|
||||
.map(|text| ControlReply::text(status, text))
|
||||
.map_err(|_| "a control text artifact is not UTF-8".to_owned()),
|
||||
other => Err(format!("a control body artifact of kind {other:?}")),
|
||||
}
|
||||
}
|
||||
None => Err("a control outcome without a body".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an outcome's body travels as an artifact.
|
||||
pub fn has_body_artifact(outcome: &Map<String, Value>) -> bool {
|
||||
outcome.contains_key("bodyArtifact")
|
||||
}
|
||||
|
||||
// -- the host ---------------------------------------------------------------------------------
|
||||
|
||||
/// The registered control services. Dropping it unregisters them and stops answering.
|
||||
pub struct ControlHost {
|
||||
tasks: Vec<tokio::task::JoinHandle<()>>,
|
||||
_client: Client,
|
||||
}
|
||||
|
||||
impl Drop for ControlHost {
|
||||
fn drop(&mut self) {
|
||||
for task in &self.tasks {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect to `router` in process as [`HOST`] and register every service of `scope`, each
|
||||
/// answered by [`crate::control::handle`] over `state`.
|
||||
///
|
||||
/// One flysim process runs one fly, so its scope is [`Scope::live`] and every agent-scoped
|
||||
/// service answers for that fly. A multi-fly host would hand each agent's services that agent's
|
||||
/// state; the names, the grants and the encoding stay as they are.
|
||||
///
|
||||
/// Requests are taken in the order the router dispatches them (FIFO per service) and answered
|
||||
/// concurrently, each in a task of its own, up to [`SERVICE_CONFIG`]'s in-flight bound: a pause
|
||||
/// waiting on a durable write does not hold up a resume, as two HTTP requests do not wait on each
|
||||
/// other. A caller that cancels or goes away has its result discarded by the router.
|
||||
pub async fn serve(router: &Router, state: AppState, scope: &Scope) -> Result<ControlHost> {
|
||||
scope.validate()?;
|
||||
let transport = router.connect_in_memory_as(HOST);
|
||||
let client = Client::connect(transport, ClientConfig::new(HOST, router.store_root()))
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!("the control host could not connect: {error}"))?;
|
||||
let mut tasks = Vec::new();
|
||||
for (family, _agent, name) in scope.services() {
|
||||
let mut service = client
|
||||
.register(&name, SERVICE_CONFIG)
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!("registering {name}: {error}"))
|
||||
.context("starting the control services")?;
|
||||
let state = state.clone();
|
||||
let client = client.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
while let Some(request) = service.next().await {
|
||||
let state = state.clone();
|
||||
let client = client.clone();
|
||||
tokio::spawn(async move { answer(&client, &state, family, request).await });
|
||||
}
|
||||
}));
|
||||
}
|
||||
tracing::info!(
|
||||
session = %scope.session,
|
||||
agents = ?scope.agents,
|
||||
services = scope.services().len(),
|
||||
"control services registered on the bus"
|
||||
);
|
||||
Ok(ControlHost {
|
||||
tasks,
|
||||
_client: client,
|
||||
})
|
||||
}
|
||||
|
||||
/// The request's payload with an out-of-line `request` body put back in place.
|
||||
async fn request_payload(request: &Request) -> Result<Map<String, Value>, ControlReply> {
|
||||
let mut payload = request.payload().clone();
|
||||
if payload.remove("requestArtifact").is_none() {
|
||||
return Ok(payload);
|
||||
}
|
||||
let bytes = match request.artifact(REQUEST_ARTIFACT) {
|
||||
Ok(artifact) => artifact.read_all().await,
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
.map_err(|error| {
|
||||
ControlReply::error(400, format!("the request body could not be read: {error}"))
|
||||
})?;
|
||||
let value = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| ControlReply::error(400, format!("the request body is not JSON: {error}")))?;
|
||||
payload.insert("request".to_owned(), value);
|
||||
Ok(payload)
|
||||
}
|
||||
|
||||
async fn answer(client: &Client, state: &AppState, family: Family, request: Request) {
|
||||
let reply = match request_payload(&request).await {
|
||||
Err(reply) => reply,
|
||||
Ok(payload) => match decode_request(family, request.method(), &payload) {
|
||||
Ok(decoded) => crate::control::handle(state, decoded).await,
|
||||
Err(Undecodable(reply)) => reply,
|
||||
},
|
||||
};
|
||||
let (outcome, out_of_line) = encode_reply(&reply);
|
||||
let result = match out_of_line {
|
||||
None => request.reply(outcome, &[]).await,
|
||||
Some((bytes, content_type)) => match seal(client, &bytes, content_type).await {
|
||||
Ok(artifact) => request.reply(outcome, &[(BODY_ARTIFACT, &artifact)]).await,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "a control reply body could not be sealed");
|
||||
let (outcome, _) = encode_reply(&ControlReply::error(
|
||||
503,
|
||||
"the reply could not be stored on the bus",
|
||||
));
|
||||
request.reply(outcome, &[]).await
|
||||
}
|
||||
},
|
||||
};
|
||||
if let Err(error) = result {
|
||||
// The caller is gone or the bus is closing; there is no one left to tell.
|
||||
tracing::debug!(%error, method = request.method(), "a control reply was not delivered");
|
||||
}
|
||||
}
|
||||
|
||||
async fn seal(client: &Client, bytes: &[u8], content_type: &str) -> Result<Artifact, BusError> {
|
||||
let mut writer = client
|
||||
.artifacts()
|
||||
.allocate(bytes.len() as u64, content_type)
|
||||
.await?;
|
||||
writer
|
||||
.write_all(bytes)
|
||||
.map_err(|error| BusError::new(flybus::ErrorCode::StoreFailure, error.to_string()))?;
|
||||
writer.seal().await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Words no control service or method may contain (`docs/control-api.md`, the structural
|
||||
/// guarantee; the same list `api.rs` checks its routes against).
|
||||
const FORBIDDEN: [&str; 10] = [
|
||||
"button", "buttons", "input", "press", "joypad", "key", "poke", "write", "memory",
|
||||
"catalog",
|
||||
];
|
||||
|
||||
fn two_flies() -> Scope {
|
||||
Scope {
|
||||
session: "arena".to_owned(),
|
||||
agents: vec![
|
||||
AgentScope::new("fly-a", Some(1)),
|
||||
AgentScope::new("fly-b", Some(2)),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn names(scope: &Scope) -> Vec<String> {
|
||||
scope.services().into_iter().map(|(_, _, n)| n).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_service_or_method_names_an_input() {
|
||||
for scope in [Scope::live(), two_flies()] {
|
||||
for (family, _, name) in scope.services() {
|
||||
assert!(flybus::wire::is_name(&name), "{name} is not a bus name");
|
||||
assert!(name.starts_with(PREFIX), "{name}");
|
||||
for method in family.methods() {
|
||||
let lowered = format!("{name} {method}").to_ascii_lowercase();
|
||||
for forbidden in FORBIDDEN {
|
||||
assert!(
|
||||
!lowered.contains(forbidden),
|
||||
"{lowered} contains {forbidden}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// One method per control-api.md endpoint (the `/status.json` alias is HTTP-only), plus
|
||||
// the per-agent status.
|
||||
let mut methods: Vec<&str> = Family::ALL
|
||||
.iter()
|
||||
.flat_map(|f| f.methods())
|
||||
.copied()
|
||||
.collect();
|
||||
assert_eq!(methods.len(), 11, "{methods:?}");
|
||||
methods.sort();
|
||||
methods.dedup();
|
||||
assert_eq!(methods.len(), 10, "{methods:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_live_names_are_these() {
|
||||
assert_eq!(
|
||||
names(&Scope::live()),
|
||||
[
|
||||
"fly.control.s.main.read",
|
||||
"fly.control.s.main.a.fly.status",
|
||||
"fly.control.s.main.a.fly.sugar",
|
||||
"fly.control.s.main.a.fly.reward",
|
||||
"fly.control.s.main.chat",
|
||||
"fly.control.s.main.ops",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_grant_is_an_exact_call_on_a_control_service_and_nothing_else() {
|
||||
for scope in [Scope::live(), two_flies()] {
|
||||
let services = names(&scope);
|
||||
let mut all: Vec<Grants> = Role::ALL.iter().map(|r| grants(*r, &scope)).collect();
|
||||
for role in Role::ALL {
|
||||
all.push(grants_for(role, &scope, Agents::Port(1)));
|
||||
all.push(grants_for(role, &scope, Agents::Id("fly")));
|
||||
}
|
||||
all.push(player_grants(&scope, Agents::Id(&scope.agents[0].id)));
|
||||
all.push(player_grants(&scope, Agents::Port(7)));
|
||||
for grant in &all {
|
||||
assert!(grant.register.is_empty() && grant.publish.is_empty());
|
||||
assert!(grant.subscribe.is_empty() && grant.manage_topics.is_empty());
|
||||
for pattern in &grant.call {
|
||||
match pattern {
|
||||
Pattern::Exact(name) => assert!(services.contains(name), "{name}"),
|
||||
other => panic!("a non-exact grant: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
let host = host_grants(&scope);
|
||||
assert!(host.call.is_empty() && host.publish.is_empty() && host.subscribe.is_empty());
|
||||
assert!(host.manage_topics.is_empty());
|
||||
assert_eq!(host.register.len(), services.len());
|
||||
for pattern in &host.register {
|
||||
assert!(matches!(pattern, Pattern::Exact(name) if services.contains(name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_grant_table() {
|
||||
let scope = Scope::live();
|
||||
let can = |role: Role, family: Family| {
|
||||
let name = scope.service(family, LIVE_AGENT);
|
||||
grants(role, &scope).call.iter().any(|p| p.matches(&name))
|
||||
};
|
||||
use Family::*;
|
||||
let table = [
|
||||
(Role::Stage, [true, true, false, false, false, false]),
|
||||
(Role::Bridge, [true, true, true, false, true, false]),
|
||||
(Role::Watchdog, [true, true, false, false, false, false]),
|
||||
(Role::Operator, [true, true, true, true, true, true]),
|
||||
(Role::Edge, [true, true, true, true, true, true]),
|
||||
];
|
||||
for (role, row) in table {
|
||||
for (family, expected) in [Read, Status, Sugar, Reward, Chat, Ops].into_iter().zip(row)
|
||||
{
|
||||
assert_eq!(can(role, family), expected, "{role:?} {family:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_player_sugars_only_their_own_fly_by_id_or_by_port() {
|
||||
let scope = two_flies();
|
||||
for grant in [
|
||||
player_grants(&scope, Agents::Id("fly-a")),
|
||||
player_grants(&scope, Agents::Port(1)),
|
||||
] {
|
||||
let allowed = |name: &str| grant.call.iter().any(|p| p.matches(name));
|
||||
assert!(allowed(&scope.service(Family::Sugar, "fly-a")));
|
||||
assert!(allowed(&scope.service(Family::Status, "fly-a")));
|
||||
assert!(!allowed(&scope.service(Family::Sugar, "fly-b")));
|
||||
assert!(!allowed(&scope.service(Family::Status, "fly-b")));
|
||||
assert!(allowed(&scope.service(Family::Read, "")));
|
||||
assert!(!allowed(&scope.service(Family::Chat, "")));
|
||||
assert!(!allowed(&scope.service(Family::Ops, "")));
|
||||
assert!(!allowed(&scope.service(Family::Reward, "fly-a")));
|
||||
}
|
||||
// A port nobody plays on reaches no fly, only the session's read.
|
||||
let empty = player_grants(&scope, Agents::Port(4));
|
||||
assert_eq!(empty.call, vec![Pattern::exact(&scope.service(Family::Read, ""))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_role_limited_to_one_fly_keeps_its_families_for_that_fly_only() {
|
||||
let scope = two_flies();
|
||||
let bridge_b = grants_for(Role::Bridge, &scope, Agents::Port(2));
|
||||
let allowed = |name: &str| bridge_b.call.iter().any(|p| p.matches(name));
|
||||
assert!(allowed(&scope.service(Family::Sugar, "fly-b")));
|
||||
assert!(!allowed(&scope.service(Family::Sugar, "fly-a")));
|
||||
assert!(allowed(&scope.service(Family::Chat, "")));
|
||||
assert!(!allowed(&scope.service(Family::Reward, "fly-b")));
|
||||
// The live, single-fly table is the same table with one agent.
|
||||
let live = Scope::live();
|
||||
assert_eq!(
|
||||
grants_for(Role::Bridge, &live, Agents::Port(0)),
|
||||
grants(Role::Bridge, &live)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scopes_refuse_ids_that_would_break_a_name() {
|
||||
for (session, agent) in [
|
||||
("", "fly"),
|
||||
("a.b", "fly"),
|
||||
("main", "Fly"),
|
||||
("main", "a.b"),
|
||||
] {
|
||||
let scope = Scope {
|
||||
session: session.to_owned(),
|
||||
agents: vec![AgentScope::new(agent, None)],
|
||||
};
|
||||
assert!(scope.validate().is_err(), "{session:?} {agent:?}");
|
||||
}
|
||||
assert!(Scope::live().validate().is_ok());
|
||||
assert!(two_flies().validate().is_ok());
|
||||
let mut same_port = two_flies();
|
||||
same_port.agents[1].port = Some(1);
|
||||
assert!(same_port.validate().is_err());
|
||||
let mut same_id = two_flies();
|
||||
same_id.agents[1].id = "fly-a".to_owned();
|
||||
assert!(same_id.validate().is_err());
|
||||
let mut no_ports = two_flies();
|
||||
no_ports.agents.iter_mut().for_each(|a| a.port = None);
|
||||
assert!(no_ports.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_round_trip_through_the_encoding() {
|
||||
let requests = [
|
||||
ControlRequest::Status,
|
||||
ControlRequest::Healthz,
|
||||
ControlRequest::Metrics,
|
||||
ControlRequest::Events {
|
||||
since: None,
|
||||
limit: None,
|
||||
},
|
||||
ControlRequest::Events {
|
||||
since: Some("12".into()),
|
||||
limit: Some("x".into()),
|
||||
},
|
||||
ControlRequest::Stimulate { body: None },
|
||||
ControlRequest::Stimulate {
|
||||
body: Some(json!({"by": "a", "source": "chat"})),
|
||||
},
|
||||
ControlRequest::Reward {
|
||||
body: Some(json!([1, 2])),
|
||||
},
|
||||
ControlRequest::Chat {
|
||||
body: Some(json!("text")),
|
||||
},
|
||||
ControlRequest::Checkpoint,
|
||||
ControlRequest::Pause,
|
||||
ControlRequest::Resume,
|
||||
];
|
||||
for request in requests {
|
||||
let (family, method, payload) = encode_request(&request);
|
||||
assert_eq!(
|
||||
decode_request(family, method, &payload),
|
||||
Ok(request.clone())
|
||||
);
|
||||
}
|
||||
// An agent's status service answers the status method.
|
||||
assert_eq!(
|
||||
decode_request(Family::Status, "Control.Status", &Map::new()),
|
||||
Ok(ControlRequest::Status)
|
||||
);
|
||||
assert!(decode_request(Family::Status, "Control.Healthz", &Map::new()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_method_on_the_wrong_service_is_a_404_and_a_stray_field_a_400() {
|
||||
let Err(Undecodable(reply)) = decode_request(Family::Read, "Control.Pause", &Map::new())
|
||||
else {
|
||||
panic!("decoded");
|
||||
};
|
||||
assert_eq!(reply.status, 404);
|
||||
let Err(Undecodable(reply)) = decode_request(Family::Read, "Control.Press", &Map::new())
|
||||
else {
|
||||
panic!("decoded");
|
||||
};
|
||||
assert_eq!(reply.status, 404);
|
||||
let mut payload = Map::new();
|
||||
payload.insert("buttons".into(), json!(1));
|
||||
let Err(Undecodable(reply)) = decode_request(Family::Sugar, "Control.Stimulate", &payload)
|
||||
else {
|
||||
panic!("decoded");
|
||||
};
|
||||
assert_eq!(reply.status, 400);
|
||||
let mut payload = Map::new();
|
||||
payload.insert("since".into(), json!(3));
|
||||
assert!(decode_request(Family::Read, "Control.Events", &payload).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replies_round_trip_inline_and_out_of_line() {
|
||||
let big = "x".repeat(INLINE_MAX + 1);
|
||||
for reply in [
|
||||
ControlReply::json(202, json!({"eventId": 7})),
|
||||
ControlReply::json(429, json!({"retryAfterMs": 1250.5})),
|
||||
ControlReply::text(200, "# HELP x\nx 1\n".into()),
|
||||
ControlReply::json(200, json!({ "events": [big.clone()] })),
|
||||
ControlReply::text(200, big.clone()),
|
||||
] {
|
||||
let (outcome, artifact) = encode_reply(&reply);
|
||||
assert_eq!(has_body_artifact(&outcome), artifact.is_some());
|
||||
let encoded = serde_json::to_vec(&outcome).unwrap();
|
||||
assert!(
|
||||
encoded.len() <= INLINE_MAX + 64,
|
||||
"{} bytes inline",
|
||||
encoded.len()
|
||||
);
|
||||
let decoded = decode_reply(&outcome, artifact.map(|(bytes, _)| bytes)).unwrap();
|
||||
assert_eq!(decoded, reply);
|
||||
}
|
||||
assert!(decode_reply(&Map::new(), None).is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -20,10 +20,17 @@
|
|||
//!
|
||||
//! There is deliberately **no endpoint that presses buttons**. The decoder is the only writer of
|
||||
//! joypad state; `api::ROUTES` is the whole surface and `tests/api.rs` asserts on it.
|
||||
//!
|
||||
//! With `FLY_CONTROL_VIA=bus` the control API is not bound here: `control` answers the same
|
||||
//! requests as RPC services on the embedded router (`controlbus`, `bus`), and `fly-control-edge`
|
||||
//! serves `:7401` with this crate's own `api` router calling them.
|
||||
|
||||
pub mod api;
|
||||
pub mod bus;
|
||||
pub mod chat;
|
||||
pub mod config;
|
||||
pub mod control;
|
||||
pub mod controlbus;
|
||||
pub mod eventlog;
|
||||
pub mod feed;
|
||||
pub mod feedbus;
|
||||
|
|
@ -46,7 +53,7 @@ use std::sync::Arc;
|
|||
use anyhow::{Context, Result};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
use crate::config::{Config, FeedVia};
|
||||
use crate::config::{Config, ControlVia, FeedVia};
|
||||
use crate::eventlog::{EventRing, now_wall_ms};
|
||||
use crate::simloop::{COMMAND_QUEUE, Command, Shared, Sim, booting_snapshot};
|
||||
use crate::snapshot::Snapshot;
|
||||
|
|
@ -129,6 +136,7 @@ where
|
|||
let control_addr = config.control.bind;
|
||||
let metrics_addr = config.control.metrics_bind;
|
||||
let via = config.feed.via;
|
||||
let control_via = config.control.via;
|
||||
let listeners = runtime.block_on(async {
|
||||
// In bus mode the feed port belongs to `fly-edge`; binding it here would take it away.
|
||||
let feed = match via {
|
||||
|
|
@ -139,9 +147,15 @@ where
|
|||
),
|
||||
FeedVia::Bus => None,
|
||||
};
|
||||
let control = tokio::net::TcpListener::bind(control_addr)
|
||||
// Likewise the control port belongs to `fly-control-edge` when control rides the bus.
|
||||
let control = match control_via {
|
||||
ControlVia::Direct => Some(
|
||||
tokio::net::TcpListener::bind(control_addr)
|
||||
.await
|
||||
.with_context(|| format!("binding the control listener on {control_addr}"))?;
|
||||
.with_context(|| format!("binding the control listener on {control_addr}"))?,
|
||||
),
|
||||
ControlVia::Bus => None,
|
||||
};
|
||||
let metrics = match metrics_addr {
|
||||
Some(addr) => Some(
|
||||
tokio::net::TcpListener::bind(addr)
|
||||
|
|
@ -157,6 +171,7 @@ where
|
|||
feed = %feed_addr,
|
||||
feed_via = via.as_str(),
|
||||
control = %control_addr,
|
||||
control_via = control_via.as_str(),
|
||||
metrics = ?metrics_addr,
|
||||
"listening"
|
||||
);
|
||||
|
|
@ -171,25 +186,38 @@ where
|
|||
}
|
||||
// The bus gets a runtime of its own, so neither its router nor the artifact copies can take
|
||||
// a worker from the control API; and it is fed from the watch slot, never from the sim thread.
|
||||
let bus_runtime = match via {
|
||||
FeedVia::Direct => None,
|
||||
FeedVia::Bus => {
|
||||
// One router for whatever rides the bus (`bus`): the feed publisher and the control
|
||||
// services are two participants on it.
|
||||
let uses = bus::Uses {
|
||||
feed: via == FeedVia::Bus,
|
||||
control: control_via == ControlVia::Bus,
|
||||
};
|
||||
let bus_runtime = if uses.feed || uses.control {
|
||||
let bus_runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.thread_name("flysim-bus")
|
||||
.enable_all()
|
||||
.build()
|
||||
.context("building the bus runtime")?;
|
||||
let bus = bus_runtime.block_on(feedbus::start_router(&config.feed.bus_dir))?;
|
||||
let scope = controlbus::Scope::live();
|
||||
let bus = bus_runtime.block_on(bus::start(&config.feed.bus_dir, uses, &scope))?;
|
||||
if uses.feed {
|
||||
bus_runtime.spawn(feedbus::run_publisher(
|
||||
bus.router.clone(),
|
||||
state.snapshots.clone(),
|
||||
Arc::clone(&state.shared.metrics),
|
||||
));
|
||||
Some((bus_runtime, bus))
|
||||
}
|
||||
let control_host = if uses.control {
|
||||
Some(bus_runtime.block_on(controlbus::serve(&bus.router, state.clone(), &scope))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
{
|
||||
Some((bus_runtime, bus, control_host))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(control_listener) = control_listener {
|
||||
let state = state.clone();
|
||||
runtime.spawn(async move {
|
||||
if let Err(error) = axum::serve(control_listener, api::router(state)).await {
|
||||
|
|
@ -210,10 +238,11 @@ where
|
|||
|
||||
let notifier = sdnotify::Notifier::from_env();
|
||||
let result = sim(shared, snapshots_tx, command_rx, ¬ifier);
|
||||
if let Some((bus_runtime, bus)) = bus_runtime {
|
||||
if let Some((bus_runtime, bus, control_host)) = bus_runtime {
|
||||
// The publisher ends by itself once the watch sender is gone; stopping the runtime under
|
||||
// it, rather than the router first, keeps a last in-flight publish from being logged as
|
||||
// a refusal. The edge sees the socket close either way.
|
||||
// a refusal. The edges see their sockets close either way.
|
||||
drop(control_host);
|
||||
drop(bus);
|
||||
bus_runtime.shutdown_timeout(std::time::Duration::from_secs(1));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@
|
|||
//! is dead or frozen even though Chromium is alive (watchdog check 2);
|
||||
//! - `/healthz` plus the hot-checkpoint mtime cover flysim itself (watchdog check 1).
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::snapshot::{FeedStatus, Snapshot};
|
||||
|
||||
|
|
@ -47,6 +49,83 @@ pub struct Metrics {
|
|||
pub bus_published: AtomicU64,
|
||||
/// Snapshots the feed bus refused or could not take; each one is skipped, never retried.
|
||||
pub bus_publish_failures: AtomicU64,
|
||||
/// The loop's compute time per frame, its pacing sleep excluded (BUS-01).
|
||||
pub frame_work: FrameWork,
|
||||
}
|
||||
|
||||
/// Frames in [`FrameWork`]'s window: a minute at real time.
|
||||
pub const FRAME_WORK_WINDOW: usize = 3_600;
|
||||
|
||||
/// The loop's compute time per frame over the last [`FRAME_WORK_WINDOW`] frames: everything one
|
||||
/// iteration of a running loop does -- commands, the transition, the publish, the checkpoint
|
||||
/// hand-off, the event log -- and not the pacing sleep after it, so the headroom against the
|
||||
/// 16.74 ms real-time budget is visible while the loop is paced (the realtime factor then reads
|
||||
/// 1.0 whatever the margin). A paused loop records nothing. Both runtimes record it the same way.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FrameWork {
|
||||
ring: Mutex<FrameWorkRing>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct FrameWorkRing {
|
||||
/// Milliseconds, oldest overwritten first once the window is full.
|
||||
samples: Vec<f32>,
|
||||
next: usize,
|
||||
total: u64,
|
||||
}
|
||||
|
||||
/// [`FrameWork`] summarised for `/metrics`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct FrameWorkSummary {
|
||||
/// Frames in the window (at most [`FRAME_WORK_WINDOW`]).
|
||||
pub frames: usize,
|
||||
/// Frames ever recorded by this process.
|
||||
pub total: u64,
|
||||
pub mean_ms: f64,
|
||||
pub p99_ms: f64,
|
||||
pub max_ms: f64,
|
||||
}
|
||||
|
||||
impl FrameWork {
|
||||
/// One frame's work. A lock the loop takes once a frame and a scrape takes once in a while.
|
||||
pub fn record(&self, work: Duration) {
|
||||
let ms = work.as_secs_f64() * 1000.0;
|
||||
let mut ring = self.ring.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if ring.samples.len() < FRAME_WORK_WINDOW {
|
||||
if ring.samples.capacity() == 0 {
|
||||
ring.samples.reserve_exact(FRAME_WORK_WINDOW);
|
||||
}
|
||||
ring.samples.push(ms as f32);
|
||||
} else {
|
||||
let next = ring.next;
|
||||
ring.samples[next] = ms as f32;
|
||||
}
|
||||
ring.next = (ring.next + 1) % FRAME_WORK_WINDOW;
|
||||
ring.total += 1;
|
||||
}
|
||||
|
||||
/// Mean, 99th percentile (nearest rank) and maximum over the window; zeros when empty.
|
||||
pub fn summary(&self) -> FrameWorkSummary {
|
||||
let (mut samples, total) = {
|
||||
let ring = self.ring.lock().unwrap_or_else(|e| e.into_inner());
|
||||
(ring.samples.clone(), ring.total)
|
||||
};
|
||||
let frames = samples.len();
|
||||
if frames == 0 {
|
||||
return FrameWorkSummary::default();
|
||||
}
|
||||
let mean_ms = samples.iter().map(|&v| f64::from(v)).sum::<f64>() / frames as f64;
|
||||
let max_ms = samples.iter().fold(0.0f32, |a, &b| a.max(b));
|
||||
let rank = (frames * 99).div_ceil(100).max(1) - 1;
|
||||
let (_, p99, _) = samples.select_nth_unstable_by(rank, f32::total_cmp);
|
||||
FrameWorkSummary {
|
||||
frames,
|
||||
total,
|
||||
mean_ms,
|
||||
p99_ms: f64::from(*p99),
|
||||
max_ms: f64::from(max_ms),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
|
|
@ -167,6 +246,35 @@ pub fn render(metrics: &Metrics, snapshot: &Snapshot, now_wall_ms: u64) -> Strin
|
|||
"Simulated milliseconds per wall millisecond over the last second.",
|
||||
header.realtime_factor,
|
||||
);
|
||||
let work = metrics.frame_work.summary();
|
||||
metric(
|
||||
&mut out,
|
||||
"fly_frame_work_mean_ms",
|
||||
"gauge",
|
||||
"Mean compute time per frame over the last 3600 frames, pacing sleep excluded; 0 before the first.",
|
||||
work.mean_ms,
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"fly_frame_work_p99_ms",
|
||||
"gauge",
|
||||
"99th percentile compute time per frame over the same window.",
|
||||
work.p99_ms,
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"fly_frame_work_max_ms",
|
||||
"gauge",
|
||||
"Longest compute time of one frame over the same window.",
|
||||
work.max_ms,
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"fly_frame_work_frames",
|
||||
"gauge",
|
||||
"Frames in the compute-time window (at most 3600).",
|
||||
work.frames,
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"fly_uptime_seconds",
|
||||
|
|
@ -418,6 +526,34 @@ mod tests {
|
|||
assert!(text.contains("fly_chat_ring_lines 0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_work_is_the_mean_p99_and_max_of_the_last_window() {
|
||||
let work = FrameWork::default();
|
||||
assert_eq!(work.summary(), FrameWorkSummary::default());
|
||||
// 100 frames of 1..=100 ms: nearest-rank p99 is 99, the mean 50.5.
|
||||
for ms in 1..=100u64 {
|
||||
work.record(Duration::from_millis(ms));
|
||||
}
|
||||
let s = work.summary();
|
||||
assert_eq!((s.frames, s.total), (100, 100));
|
||||
assert!((s.mean_ms - 50.5).abs() < 1e-9, "{s:?}");
|
||||
assert_eq!((s.p99_ms, s.max_ms), (99.0, 100.0));
|
||||
// The window keeps the newest FRAME_WORK_WINDOW frames: 3600 frames of 2 ms push every
|
||||
// older one out.
|
||||
for _ in 0..FRAME_WORK_WINDOW {
|
||||
work.record(Duration::from_millis(2));
|
||||
}
|
||||
let s = work.summary();
|
||||
assert_eq!((s.frames, s.total), (FRAME_WORK_WINDOW, 100 + FRAME_WORK_WINDOW as u64));
|
||||
assert_eq!((s.mean_ms, s.p99_ms, s.max_ms), (2.0, 2.0, 2.0));
|
||||
let metrics = Metrics::default();
|
||||
metrics.frame_work.record(Duration::from_micros(12_500));
|
||||
let text = render(&metrics, &crate::simloop::booting_snapshot(0, 0, crate::snapshot::MacroMode::Raw), 0);
|
||||
assert!(text.contains("fly_frame_work_mean_ms 12.5\n"), "{text}");
|
||||
assert!(text.contains("fly_frame_work_p99_ms 12.5\n"));
|
||||
assert!(text.contains("fly_frame_work_frames 1\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_series_has_a_help_and_type_header_and_a_finite_value() {
|
||||
let text = render(&Metrics::default(), &crate::simloop::booting_snapshot(0, 0, crate::snapshot::MacroMode::Raw), 0);
|
||||
|
|
|
|||
|
|
@ -876,6 +876,8 @@ impl Sim {
|
|||
"the simulation is behind real time; no frames are being skipped"
|
||||
);
|
||||
}
|
||||
// The frame's compute time, before the pacing sleep (`fly_frame_work_*`).
|
||||
self.shared.metrics.frame_work.record(iteration.elapsed());
|
||||
let sleep = pacer.next_sleep(Instant::now());
|
||||
if !sleep.is_zero() {
|
||||
std::thread::sleep(sleep);
|
||||
|
|
|
|||
|
|
@ -2068,60 +2068,54 @@ fn nopp_checkpoint() -> Option<flysim::store::Checkpoint> {
|
|||
// Section 13: the errands, a purchase and a heal, from the release box's own checkpoint
|
||||
// -------------------------------------------------------------------------------------------
|
||||
|
||||
/// `GO SHOP` walks the fly into the Viridian mart, once, and then to its counter.
|
||||
/// `GO SHOP` walks the fly into the town's mart, once, and then to its counter.
|
||||
///
|
||||
/// **What is proven here, and what is not.** The errand works: from the release container's own
|
||||
/// Viridian checkpoint the fly is inside the mart in 1.4 brain minutes, the errand is discharged
|
||||
/// on arrival and `GO SHOP` is never on the city's pad again. Inside, `GO SHOP` walks it to a tile
|
||||
/// it can talk to the clerk from — which needs the counter reach, because every tile beside a
|
||||
/// clerk behind a desk is a wall.
|
||||
/// **From a state where `GO SHOP` is dealt.** Since rows 62 and 66 `GO SHOP` is on the pad while
|
||||
/// `service_needed` holds -- no ball in the bag, the wallet covers one, no Oak's parcel -- and the
|
||||
/// parcel errand is `GO OBJECTIVE`'s (`the_objective_is_the_errand_and_macros_mode_walks_to_it`).
|
||||
/// The Viridian stall checkpoint carries the parcel, so `GO SHOP` is rightly not dealt there; this
|
||||
/// test starts from the rung-11 Pewter checkpoint (money, no ball, party hurt), where it is. The
|
||||
/// ledger half of the old claim ("paid once, never offered again") is row 66's counter window now:
|
||||
/// once the counter has been faced, the service walk is off the street's pad for the window.
|
||||
///
|
||||
/// **The purchase is not ROM-proven from this checkpoint**, and the mechanism is named rather than
|
||||
/// papered over (`infra/docs/macros-traps.md` rows 33b and 34b). Two things are in the way, both
|
||||
/// measured on the cartridge on 2026-09-17:
|
||||
///
|
||||
/// - the screen-buffer tile read disagrees with itself on a map smaller than the screen. In the
|
||||
/// Viridian mart the same tile reads walkable-and-counter from one of the fly's tiles and
|
||||
/// wall-and-not-counter from another two tiles away, because an 8x8 map cannot centre under a
|
||||
/// ten-by-nine view. `facing_target`'s reach is taken from the *map id* for exactly that reason,
|
||||
/// but the walk's own goals are still priced off the tile read;
|
||||
/// - a counter *faced* is lost to the next hold. `GO SHOP` ends standing at the counter looking at
|
||||
/// the clerk, and `TALK` is on the pad there — but a hold is 800 ms and whichever macro wins the
|
||||
/// next one turns the fly away before the A press happens. The `reached` window brings `GO SHOP`
|
||||
/// back in ten brain minutes, so it is bounded rather than a loop; it is not a proof.
|
||||
///
|
||||
/// The purchase scripts themselves are covered by the fake-game tests
|
||||
/// (`a_purchase_navigates_by_the_items_place_in_the_stock_list`), and the *stock* read is proven
|
||||
/// against the cartridge below: Viridian's counter sells no Potion.
|
||||
/// **What is proven here, and what is not.** The errand works: the fly is inside the mart, `GO
|
||||
/// SHOP` walks it to a tile it can talk to the clerk from, and the way out is withheld while the
|
||||
/// counter is unfaced. **The purchase is not ROM-proven from this checkpoint**
|
||||
/// (`infra/docs/macros-traps.md` rows 33b and 34b): a counter *faced* is lost to the next hold,
|
||||
/// since a hold is 800 ms and whichever macro wins the next one turns the fly away before the A
|
||||
/// press. The purchase scripts themselves are covered by the fake-game tests
|
||||
/// (`a_purchase_navigates_by_the_items_place_in_the_stock_list`).
|
||||
#[test]
|
||||
fn go_shop_enters_the_mart_once_and_walks_to_its_counter() {
|
||||
let rom = skip_without_rom!();
|
||||
let Some(checkpoint) = checkpoint() else {
|
||||
eprintln!("skipped: no FLY_TRAP_CHECKPOINT / FLY_MACRO_CHECKPOINT");
|
||||
let Some(checkpoint) = rank_eleven_checkpoint() else {
|
||||
eprintln!("skipped: no FLY_RANK11_CHECKPOINT");
|
||||
return;
|
||||
};
|
||||
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
|
||||
assert_eq!(run.map(), VIRIDIAN_CITY, "the checkpoint is the one the stream stalled on");
|
||||
assert_eq!(run.map(), PEWTER_CITY, "the checkpoint is the town the badge was won in");
|
||||
|
||||
// The errand is outstanding at the checkpoint: the ledger is session state and a restore
|
||||
// starts empty (`docs/design/macros.md` section 13).
|
||||
// The service is needed at the checkpoint, read from the cartridge: money, no ball, no parcel.
|
||||
// Forced hot before the first frame so that the first hold is `GO SHOP`'s, not the rotation's,
|
||||
// and the burst held open: the party is hurt here too, so `GO HEAL` is on the same pads and a
|
||||
// hold that fell between bursts would be the rotation's pick of the two, which walks the fly
|
||||
// out of the mart to the centre.
|
||||
run.force_hot = Some("macro_go_shop");
|
||||
run.next_burst = 1e15;
|
||||
run.frame();
|
||||
assert!(
|
||||
run.layer.bound_channels().iter().any(|channel| channel == "macro_go_shop"),
|
||||
"`GO SHOP` is on the pad with the errand outstanding: {:?}",
|
||||
"`GO SHOP` is on the pad with the service needed: {:?}",
|
||||
run.layer.bound_channels()
|
||||
);
|
||||
|
||||
// Into the mart, on `GO SHOP`'s own channel. Viridian is a wide city and the mart is on the
|
||||
// far side of it, so this is several budgets' worth of walking and several holds.
|
||||
run.force_hot = Some("macro_go_shop");
|
||||
let mart = u32::from(flybrain_gb::pokemon_red::maps::VIRIDIAN_MART);
|
||||
// Into the mart, on `GO SHOP`'s own channel.
|
||||
let mart = PEWTER_MART;
|
||||
run.drive_until("inside the mart", 240_000, |run| run.map() == mart);
|
||||
|
||||
// Inside, `GO SHOP` is still the walk to the clerk -- the half of section 13 the ledger does
|
||||
// not gate, because the errand's remaining job is to put the fly where the purchases can be
|
||||
// pressed. Every tile beside the clerk is a wall, so reaching one at all is the counter reach
|
||||
// doing the work (`docs/design/macros-wram.md` section 7).
|
||||
// Inside, `GO SHOP` is still the walk to the clerk. Every tile beside the clerk is a wall, so
|
||||
// reaching one at all is the counter reach doing the work (`docs/design/macros-wram.md`
|
||||
// section 7).
|
||||
let mut shop_seen = false;
|
||||
let mut faced_the_counter = false;
|
||||
let mut pad_in_the_mart: Vec<String> = Vec::new();
|
||||
|
|
@ -2131,10 +2125,9 @@ fn go_shop_enters_the_mart_once_and_walks_to_its_counter() {
|
|||
}
|
||||
let bound = run.layer.bound_channels();
|
||||
let shop = bound.iter().any(|channel| channel == "macro_go_shop");
|
||||
// The frames straight after a warp report the new map with the *old* coordinates -- the
|
||||
// header changes before the position does -- so the pad on those is dealt against a tile
|
||||
// of the city. Waiting for `GO SHOP` to appear is waiting for the fly to actually be in
|
||||
// the building.
|
||||
// The frames straight after a warp report the new map with the *old* coordinates, so the
|
||||
// pad on those is dealt against a tile of the city. Waiting for `GO SHOP` to appear is
|
||||
// waiting for the fly to actually be in the building.
|
||||
if !shop_seen {
|
||||
shop_seen = shop;
|
||||
if shop_seen {
|
||||
|
|
@ -2142,8 +2135,7 @@ fn go_shop_enters_the_mart_once_and_walks_to_its_counter() {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
// `GO SHOP` leaving the pad inside the building *is* the counter having been faced: the
|
||||
// reached ledger is what retires it (`palette::counter_aims`).
|
||||
// `GO SHOP` leaving the pad inside the building *is* the counter having been faced.
|
||||
faced_the_counter |= !shop;
|
||||
faced_the_counter
|
||||
});
|
||||
|
|
@ -2153,25 +2145,25 @@ fn go_shop_enters_the_mart_once_and_walks_to_its_counter() {
|
|||
run.money()
|
||||
);
|
||||
assert!(faced_the_counter, "`GO SHOP` walked to the clerk and retired it");
|
||||
// And while the counter was unfaced, nothing on the pad could leave the building: that is what
|
||||
// stops the one visit this area gets being spent on the doormat (`palette::counter_pending`).
|
||||
// While the counter was unfaced, nothing on the pad could leave the building
|
||||
// (`palette::counter_pending`).
|
||||
assert!(
|
||||
!pad_in_the_mart.iter().any(|channel| channel == "macro_go_out"),
|
||||
"no way out while the errand's counter is unfaced: {pad_in_the_mart:?}"
|
||||
"no way out while the counter is unfaced: {pad_in_the_mart:?}"
|
||||
);
|
||||
|
||||
// Out again -- the suppression is released now -- and the errand is paid: `GO SHOP` is not on
|
||||
// the city's pad a second time. That is "once per area per run", and it is what makes the
|
||||
// errand impossible to loop on.
|
||||
// Out again -- the suppression is released now -- and the counter was faced, so for the
|
||||
// reached window the service walk is not dealt from the street (row 66): that is what makes
|
||||
// the service impossible to ring on, though the bag still holds no ball.
|
||||
run.force_hot = Some("macro_go_out");
|
||||
run.drive_until("back out onto the city", 120_000, |run| run.map() == VIRIDIAN_CITY);
|
||||
run.drive_until("back out onto the town", 120_000, |run| run.map() == PEWTER_CITY);
|
||||
run.force_hot = None;
|
||||
for _ in 0..600 {
|
||||
for _ in 0..60 {
|
||||
run.frame();
|
||||
}
|
||||
assert!(
|
||||
!run.layer.bound_channels().iter().any(|channel| channel == "macro_go_shop"),
|
||||
"the errand is paid and never offered again: {:?}",
|
||||
"a counter just faced is not walked back to at once: {:?}",
|
||||
run.layer.bound_channels()
|
||||
);
|
||||
}
|
||||
|
|
@ -2195,6 +2187,10 @@ fn go_heal_enters_the_centre_and_heal_restores_the_party() {
|
|||
};
|
||||
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
|
||||
assert_eq!(run.map(), VIRIDIAN_CITY);
|
||||
// Forced hot *before* the first frame: the rotation's first hold is `GO OBJECTIVE`, which at
|
||||
// this checkpoint (the parcel in the bag) walks to Pallet Town and Oak's lab, and the fly is
|
||||
// then in another area for the rest of the budget, healing at Pewter's centre, never this one.
|
||||
run.force_hot = Some("macro_go_heal");
|
||||
run.frame();
|
||||
assert!(
|
||||
run.layer.bound_channels().iter().any(|channel| channel == "macro_go_heal"),
|
||||
|
|
@ -2210,7 +2206,6 @@ fn go_heal_enters_the_centre_and_heal_restores_the_party() {
|
|||
let mut heal_seen = false;
|
||||
let mut hurt_in_centre = false;
|
||||
let mut rested_in_centre = false;
|
||||
run.force_hot = Some("macro_go_heal");
|
||||
run.drive_until("the centre's own pad", 240_000, |run| {
|
||||
if run.map() != centre {
|
||||
return false;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue