diff --git a/changelog.d/route-choice.md b/changelog.d/route-choice.md new file mode 100644 index 0000000000..f9917b06f1 --- /dev/null +++ b/changelog.d/route-choice.md @@ -0,0 +1,9 @@ +### `darkbloom route this-mac`, `my-macs` or `my-macs-first` + +- `darkbloom route this-mac`, `darkbloom route my-macs` and `darkbloom route my-macs-first` save where your requests go when this Mac's local API can't take them (`[local] route`), so the route no longer needs a hand edit of `provider.toml` or a whole `darkbloom start --route`. Each says what it means: `my-macs` sends them to your other Macs, free, and never to the network; `my-macs-first` sends them to your other Macs, then to the Darkbloom network, billed, and requests from other machines (your LAN or tailnet) never use the paid network. +- `my-macs` and `my-macs-first` need your account API key: without one they save nothing, exit 1 and name `darkbloom route key`. They only ask whether a key is saved; no line shows a key. +- A running local API uses a saved route from its next request, with no restart and no model reload: its router reads `[local] route` again when `provider.toml` changes (one `stat` by a request this Mac can't take or a model list; none for a request this Mac serves). The command says "Saved. Your local API uses it now.", or "It applies when your local API starts." with none running. A malformed edit keeps the last good route and is said once in the local API's log, with nothing from the file. So does a read that catches an editor saving the file in place (it empties the file before it writes it): only a whole file counts, so a saved `this-mac` never passes a request on while the file is saved. +- `darkbloom route key` says the same when it saves or removes the key, which a running local API already read again from its next request. A key removed while the route passes requests on says that the next request this Mac can't take gets this Mac's own answer. +- That answer now says why. A request this Mac can't take, with `my-macs` or `my-macs-first` saved and no account key, or after `darkbloom route key --remove` removed the key a running local API used, keeps this Mac's 404, 429 or 503. Its message says that this Mac doesn't serve the model (or can't take the request now), and that reaching your other Macs needs an account key (`darkbloom route key`), with code `account_key_needed`. The local API's log says it once, never with the key. Before, it was this Mac's plain "Requested model is unavailable." with nothing in the log. +- In a two-Mac cluster, both commands say plainly that the leading Mac's route and key apply: the pair's local API runs there, and requests from the other Mac reach it from another machine, so with `my-macs-first` they never use the paid network, which both Macs now say. Their words are now true for each Mac. On the leading Mac, a removed key says that the pair passes nothing on until a key is saved there again, `route this-mac` says that the pair's local API passes nothing on, and the summary and `--no-auth` lines name this pair, not this Mac. The other Mac says only that the leading Mac's route decides what the pair passes on, and names `darkbloom route key`, or `darkbloom route key --remove`, to run on the leading Mac; refused for want of a key, it names the leading Mac first. A pair's local API without a local key (`--no-auth`) never claims to pass requests on. +- `darkbloom route key`, with `[local] route = "this-mac"`, now names `darkbloom route my-macs` to use the key. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 985f503602..59d8a1ba5d 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -196,6 +196,7 @@ Subcommands declared by `Darkbloom.configuration.subcommands`: | `doctor` | Diagnostics (see [troubleshooting](./troubleshooting.md#doctor-checks)) | ✓ | `DoctorCommand.swift` (`Doctor`) | | `models` | `list`, `catalog`, `download`, `remove` | ✓ | `ModelsCommand.swift` (`Models`) | | `local` | Print the local API's address and key | | `LocalCommand.swift` (`Local`) | +| `route` | Where your requests go when this Mac's local API can't take them: `this-mac`, `my-macs` or `my-macs-first` saves `[local] route` ([below](#darkbloom-route-this-mac-my-macs-my-macs-first)); `key` saves the account API key | ✓ | `RouteCommand.swift` (`Route`), `RouteChoiceCommand.swift` (`RouteChoiceFlow`) | | `cluster` | Set up two Macs to serve one model together ([guided setup](./two-mac-cluster.md)); `cluster local` serves without a coordinator. In a terminal, the first setup asks how the pair serves (**Only me (this pair, local)**, **Darkbloom network**, or **Both, me first**, preselected: the leader's local API beside Darkbloom, which pauses while you use it), saves the answer in `[local] mode`, and asks nothing without a terminal ([Both, me first](./two-mac-cluster.md#both-me-first-the-pairs-own-api-beside-darkbloom)). Run again on a paired Mac it works like `darkbloom start` (which opens the same screen there): both Macs, the cable and the status, then the pair's models with the current one preselected (Enter keeps it or starts it again), each with the modes it runs there, the recommended one first and no speed, **Change how the pair serves** (the three choices below; `cluster local`'s list keeps its line to switch to Darkbloom), and **Start over**; another model asks once before the serving one stops, and every start ends with the outcome, the pair's card and `darkbloom stop` / `restart` / `status` ([after setup](./two-mac-cluster.md#the-steps-once)). It offers **Start over** after one question (also when the other Mac does not answer over the cable: the screen then names that Mac and what to run there), and **Pair again** without it only when the saved pairing was made with another Secure Enclave key; both take the steps of `cluster pair --forget` (`ClusterUnpairing`), then pair ([pairing again](./two-mac-cluster.md#pairing-again)) | ✓ | `ClusterCommand.swift` (`Cluster`) | | `waitlist` | List the waitlists the coordinator offers and where the account stands (bare), or put the account on one and show where it stands (`waitlist cluster`, `waitlist sandbox`); waitlists are per account | ✓ | `Waitlist/WaitlistCommand.swift` (`Waitlist`) | | `login` | Link the machine to an account (RFC 8628 device code) | ✓ | `LoginCommand.swift` (`Login`) | @@ -957,6 +958,52 @@ the start summary's words) and `requests:` (where your requests go) keyed server adds `tools: darkbloom --opencode · --hermes` (`Local.toolsLine`). `--json` is unchanged. +### `darkbloom route this-mac`, `my-macs`, `my-macs-first` + +| Command | Saves | A request this Mac can't take | +|---|---|---| +| `darkbloom route this-mac` | `[local] route = "this-mac"` | Gets this Mac's own answer; nothing is passed on. Needs no account key | +| `darkbloom route my-macs` | `[local] route = "my-macs"` | Goes on to your other Macs, free; never to the Darkbloom network | +| `darkbloom route my-macs-first` | `[local] route = "my-macs-first"` | Goes on to your other Macs (free), then to the Darkbloom network, billed to your balance | + +Each takes `-c`, `--config` (the `provider.toml` to save in) and writes only +`[local] route` (`setLocalSettings`), so it replaces a hand edit of the file +and `darkbloom start --route`. It then says what the route means; with +`my-macs-first`, that requests from other machines (your LAN or tailnet) never +use the paid network ([the local router](./direct-mode.md#when-this-mac-cant-take-a-request-the-local-router)). +The same choice again writes nothing (`✓ Already saved. …`). + +- **Without a saved account key,** `my-macs` and `my-macs-first` save nothing + and exit 1: ``✗ Not saved: `darkbloom route my-macs` passes your requests on + with your account API key, and this Mac has none saved.``, then the command + that saves one (`darkbloom route key`) and the one to run again. It only asks + whether a key is saved, and never prints one. +- **A local API running now uses it from its next request,** with no restart + and no model reload: `✓ Saved. Your local API uses it now.` With none + running: `✓ Saved. It applies when your local API starts.` Its router reads + `[local] route` again when `provider.toml` changes + ([the local router](./direct-mode.md#when-this-mac-cant-take-a-request-the-local-router)). + One without a local key (`--no-auth`) keeps every request on this Mac (on a + pair's leading Mac, on this pair), whatever the route, and the command says + so. +- **In a two-Mac cluster,** the leading Mac's route applies: the pair's local + API runs there and passes on what the pair can't take, including requests + from the other Mac. Those reach it from another machine, so with + `my-macs-first` they never use the paid network, and both Macs say so. On + the leading Mac the command says so, or, with `this-mac`, that the pair's + local API passes nothing on. A pair's API without a local key + (`cluster local --no-auth`) gets the `--no-auth` line instead. On the other + Mac it saves the route for when that Mac serves alone (``It applies when + this Mac serves alone (`darkbloom start --solo`).``), says that the leading + Mac's route decides what the pair passes on (that Mac's route and key aren't + known here), and names the command to run there. Refused for want of a key, + it first names the leading Mac's `darkbloom route key` and route for the + pair, then a key saved here for this Mac alone. +- A `provider.toml` that doesn't load is refused with its reason, and nothing + is written (exit 1). + +`RouteChoiceFlow` in `provider-swift/Sources/darkbloom/RouteChoiceCommand.swift`. + ### `darkbloom route key` | Flag | Type | Default | Effect | @@ -977,9 +1024,29 @@ never printed (`RouteKeyFlow`, `provider-swift/Sources/darkbloom/RouteCommand.sw `KeychainLocalRouterAccountKeyStore`). After it saves or removes the key, it posts the Darwin notification `.route-key-changed`: a running local API keeps the key in memory and reads it again on its next request that -needs it. When the local API running now has no local key (`--no-auth`), it -says that this API keeps every request on this Mac and never uses the key. ^C at the hidden prompt gives the terminal its echo -back before the command ends (`HiddenReadSignals`). See +needs it, so it says `Your local API uses it now.` (or, with none running, `It +applies when your local API starts.`). A key removed while the route passes +requests on says what the next request does: ``Your local API uses it now. +From its next request, one this Mac can't take gets this Mac's own answer +instead of going to your other Macs or the Darkbloom network.`` That answer +says an account key is needed (code `account_key_needed`, see +[the local router](./direct-mode.md#when-this-mac-cant-take-a-request-the-local-router)). + +In a two-Mac cluster it says whose key the pair's local API uses, and on the +leading Mac its summary names the pair (`Your requests: this pair first, then +your other Macs (free).`): + +| This Mac | Saved | Removed | +|---|---|---| +| Leads (the pair's local API runs here) | `In this pair, the pair's local API runs on this Mac and passes requests on with this key.` | ``From its next request, one the pair can't take gets the pair's own answer …``, then `In this pair, the pair's local API runs on this Mac, so the pair passes nothing on until a key is saved here again.` | +| Leads, with `[local] route = "this-mac"` | `In this pair, the pair's local API runs on this Mac and uses this Mac's key once its route passes requests on.` | `In this pair, the pair's local API runs on this Mac: once its route passes requests on, it needs a key saved here again.` | +| Follows | ``In this pair, the pair's local API uses the leading Mac's key (…), not this one: run `darkbloom route key` there.`` | ``… not this one: to stop the pair passing requests on, run `darkbloom route key --remove` there.`` | + +When the local API running now has no local key (`--no-auth`), it says that +this API keeps every request on this Mac (on the leading Mac, on this pair) and +never uses the key; on the leading Mac it then says nothing of the pair's key. ^C at the hidden prompt +gives the terminal its echo back before the command ends +(`HiddenReadSignals`). See [the local router](./direct-mode.md#when-this-mac-cant-take-a-request-the-local-router). ### Cluster placement request metadata @@ -3184,12 +3251,16 @@ only, your other Macs (free), or your Macs first and then the Darkbloom network (billed), from `[local] route` and a saved account API key. ```bash +darkbloom route this-mac # your requests stay on this Mac +darkbloom route my-macs # then your other Macs (free); needs the account key +darkbloom route my-macs-first # then your other Macs (free), then the Darkbloom network (billed); needs the key darkbloom route key # ask for the key with hidden input, check it, save it in the Keychain darkbloom route key --stdin # read it from standard input darkbloom route key --remove # remove it: requests stay on this Mac ``` -No output line contains the key. Flags: [`darkbloom route key`](#darkbloom-route-key). +No output line contains the key. Details: [the three routes](#darkbloom-route-this-mac-my-macs-my-macs-first) +and [`darkbloom route key`](#darkbloom-route-key). ## `darkbloom logs` diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md index 2f8d0eef53..f23ecb56c7 100644 --- a/docs/provider/direct-mode.md +++ b/docs/provider/direct-mode.md @@ -223,7 +223,26 @@ gets `my-macs-first` as `my-macs` (`self` only, never `prefer`), and its saved. A connection's peer is read once, when it opens, and nothing is added to this Mac's own path. -The route is read when the local API starts (a change needs a restart). The +`darkbloom route this-mac`, `darkbloom route my-macs` and +`darkbloom route my-macs-first` save the route; the last two need a saved +account key and refuse without one +([CLI reference](./cli-reference.md#darkbloom-route-this-mac-my-macs-my-macs-first)). +A running local API uses a saved route from its next request that needs it, +with no restart and no model reload: its router reads `[local] route` again +when the provider config file it started with changes (`LocalRouterRouteFile`, +`provider-swift/Sources/ProviderCore/Server/LocalRouter.swift`). Only a +request this Mac can't take and a model list look at the file, one `stat` each +(its device, inode, size and modification time); a request this Mac serves +never does. A change is logged (`local router: route is now my-macs-first +(provider.toml changed)`). A file that doesn't read as a provider config, a +malformed edit or a file that is gone, keeps the last good route and is said +once in the log until it reads again (`local router: provider.toml doesn't read +as a provider config now; requests keep the route my-macs until it does`); the +line holds nothing from the file. Only a whole file counts: an editor that +saves in place empties the file before it writes it, so a read that finds it +empty, or shorter than its `stat` said, keeps the last good route the same way, +and a saved `this-mac` never passes a request on while the file is saved. A +pair's local API reads the leading Mac's `provider.toml`. The key is read once, by the first request that needs it, and kept in memory: `darkbloom route key` tells a running local API when it saves or removes the key (a Darwin notification, `.route-key-changed`), and the @@ -250,6 +269,23 @@ next request reads it again, with no restart. serves this Mac only, never reads the account key and never dials the coordinator, whatever the route. The start banner, `darkbloom local` and `darkbloom route key` say so. +- **A route that needs the key, with none saved, says why.** That is a saved + `my-macs` or `my-macs-first` with no account key, or no route saved after + `darkbloom route key --remove` removed a key this local API had used. A + request this Mac can't take stays on this Mac. Its answer keeps this Mac's + status (`404`, `429` or `503`), `Retry-After` and + `X-Darkbloom-Served-By: this-mac`, with code `account_key_needed`: + ``This Mac doesn't serve , and reaching your other Macs needs an + account key: run `darkbloom route key`.`` A `429` or `503` starts `This Mac + can't take this request right now`. With `my-macs-first` it says `your other + Macs or the Darkbloom network`, except to a client on another machine. The + log says it once, until a key is read again, never with the key: + ``local router: a request this Mac can't take stays on this Mac: reaching + your other Macs needs an account key, and none is saved (`darkbloom route + key` saves one)``. With no route saved and no key read while the local API + ran, or with `this-mac`, the answer is this Mac's own, as before + (`LocalRouter.needsAccountKey`, + `provider-swift/Sources/ProviderCore/Server/LocalRouterResponder.swift`). - **What passes a request on:** only this Mac's own `404` (it doesn't serve the model), `429` (its queue is full) or `503` (draining, an add-on hold, a refused load, no capacity), before any byte reached the client. A client diff --git a/docs/provider/local-first.md b/docs/provider/local-first.md index b36957598a..ca136b9368 100644 --- a/docs/provider/local-first.md +++ b/docs/provider/local-first.md @@ -148,11 +148,21 @@ busy, they can go on, like the Darkbloom iPhone app: Requests from other machines never use the paid network; they can use this Mac and your other Macs. -This needs your account API key, from the Darkbloom console, saved with -`darkbloom route key`. It goes into this Mac's Keychain and is never printed. -With a key saved, the question asks this too; you can also start with -`--route this-mac`, `--route my-macs` or `--route my-macs-first`. The details -are in [the local router](./direct-mode.md#when-this-mac-cant-take-a-request-the-local-router). +Choose with one command; it saves your choice and says what it means: + +```bash +darkbloom route this-mac # Only this Mac +darkbloom route my-macs # Only my Macs (free) +darkbloom route my-macs-first # My Macs first, then the network (billed) +``` + +The last two need your account API key, from the Darkbloom console, saved +with `darkbloom route key`; without it they save nothing and say so. The key +goes into this Mac's Keychain and is never printed. With a key saved, the +start question asks this too. A running local API uses a new choice, and a key +saved or removed, from its next request: no restart, and no model reload. The +details are in +[the local router](./direct-mode.md#when-this-mac-cant-take-a-request-the-local-router). ## Your local API diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index ee1aad6189..e386d0673b 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -796,8 +796,13 @@ With **Both, me first**: - **Requests the pair can't take** (a model it doesn't serve, a full queue) go on as that Mac's `[local] route` says, with that Mac's account key ([the local router](./direct-mode.md#when-this-mac-cant-take-a-request-the-local-router)). + `darkbloom route this-mac`, `my-macs` or `my-macs-first` on that Mac sets it, + and the pair's API uses it from its next request, with no restart; on the + other Mac it says to run it on the leading Mac. Requests from other machines never use the paid network; they can use the - pair and your other Macs. + pair and your other Macs. That includes the pair's other Mac: its requests + reach the leading Mac from another machine, so with `my-macs-first` tools + there use the pair and your other Macs, never the paid network. - **Me first:** while one of your requests runs on it, or waits for a lane, the pair takes no new Darkbloom request, and Darkbloom's running requests finish. It takes Darkbloom requests again 2 minutes after your last request ends diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 8b673218aa..933d806199 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -363,7 +363,7 @@ Every key is optional, and an absent key keeps today's behaviour | `[local] mode` | `"local"` (**Only me**), `"network"` (**Darkbloom network**), `"both"` (**Both, me first**) | The launch flags decide, as today: plain `start` = `network`, `--local` = `local`, `--local-endpoint` = `both` (`launchMode`, `resolvedMode`). In a terminal, `darkbloom start` asks once and saves the answer; a mode flag saves it too, and so does the desktop app's "Local only" (`local`). The background service always serves it: `restart` and `update` rewrite a job serving another way to it first (`SavedChoiceService.align`) | | `[local] me_first` | `true` or `false` | On with `mode = "both"`, off otherwise; `false` keeps today's shared serving (`meFirstEnabled`). It applies only to Both, me first, never to Only me (`--local`, `meFirstIdle`) | | `[local] me_first_idle_minutes` | Whole minutes, `1`–`120` | `2` (`defaultMeFirstIdleMinutes`, `resolvedMeFirstIdleMinutes`): Darkbloom requests return this long after the owner's last local request ends | -| `[local] route` | `"this-mac"` (only this Mac), `"my-macs"` (only your Macs), `"my-macs-first"` (your Macs first, then the Darkbloom network) | `this-mac`; `my-macs` once an account key is saved with `darkbloom route key` (`resolvedRoute`). Without a saved key, or without a local key (`--no-auth`), nothing leaves this Mac, whatever the route (`LocalRouterConfig.effectiveRoute`). `my-macs` sends `X-Darkbloom-Route: self`; `my-macs-first` sends `prefer`, then `self` once on a `402`, and only `self` for a client on another machine (a TCP peer that isn't loopback, `LocalRouterPolicy.route`). Read when the local API starts | +| `[local] route` | `"this-mac"` (only this Mac), `"my-macs"` (only your Macs), `"my-macs-first"` (your Macs first, then the Darkbloom network) | `this-mac`; `my-macs` once an account key is saved with `darkbloom route key` (`resolvedRoute`). Without a saved key, or without a local key (`--no-auth`), nothing leaves this Mac, whatever the route (`LocalRouterConfig.effectiveRoute`); a saved `my-macs` or `my-macs-first` with no key then answers why, with code `account_key_needed` ([the local router](../provider/direct-mode.md#when-this-mac-cant-take-a-request-the-local-router)). `my-macs` sends `X-Darkbloom-Route: self`; `my-macs-first` sends `prefer`, then `self` once on a `402`, and only `self` for a client on another machine (a TCP peer that isn't loopback, `LocalRouterPolicy.route`). A running local API reads it again when the file changes, from its next request that needs it (`LocalRouterRouteFile`) | | `[local] port` | Whole number, `1`–`65535` | This Mac's one local API port, for every local API it serves (`LocalAPIPort`, `provider-swift/Sources/ProviderCore/Config/LocalAPIPort.swift`). When absent, the first start that serves a local API keeps the port this Mac's local API already uses: its running API's, else its installed LaunchAgent job's (`LaunchAgent.installedLocalAPIPort`), even `8000`, so a Mac updated from 0.10.10 keeps `8000`. Only a Mac with no local API at all chooses the first free port from the build's `defaultLocalPort` (production's `8000`, so `8001`), never `8000` or `47420`–`47423`. Either is saved (`LocalAPIPort.choose`); the desktop app's local mode saves it, with `mode = "local"`, once its service started (`Desktop.StartLocal.serve`). Once saved it is used as it is, never moved; only `--port ` replaces it | | `[local] bind` | `localhost` or a numeric IPv4 or IPv6 address (`ClusterServingScope.isValidBind`) | `127.0.0.1` (`defaultBind`, `resolvedBind`) | @@ -376,6 +376,7 @@ cancelled picker or a refused start writes nothing): | A mode flag: `--local`, `--network`, `--me-first`, `--local-endpoint` (`LocalFirstOptions.savesModeFlag`) | `mode`, so the background service, `restart` and `update` serve it from now on; never with `--local --here` (one terminal session) or for a service's child | | The desktop app's "Local only" (`desktop start-local`), once its service started (`Desktop.StartLocal.serve`) | `mode = "local"`, as `--local` writes it; the app's other choices pass `--local-endpoint`, a mode flag | | `--no-me-first`, `--me-first` (only to undo a saved `me_first = false`), `--me-first-idle `, `--route ` | `me_first`, `me_first_idle_minutes`, `route`, as `--idle-timeout` writes `idle_timeout_mins` | +| `darkbloom route this-mac`, `my-macs`, `my-macs-first` (`RouteChoiceFlow`) | `route` only, at once and without a start, and a running local API uses it from its next request; `my-macs` and `my-macs-first` write nothing while no account key is saved | | Any start that serves a local API (the question's Only me or Both, a saved `mode`, `--me-first`, `--local`, `--local-endpoint`, the desktop app's starts), except a service's child (`--foreground`, or `start --local` a service runs) | `port`, when none is saved (the one this Mac's local API already uses, else the first free one, as above) or `--port ` names another | | `--bind`, `--no-auth`, and every other start; the mode of `--local --here` | Nothing: a start with no saved `mode`, no mode flag and no terminal keeps today's behaviour exactly (no local API, so no port) | diff --git a/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedLocalServer+Router.swift b/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedLocalServer+Router.swift index 04cbde2656..46187c7a21 100644 --- a/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedLocalServer+Router.swift +++ b/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedLocalServer+Router.swift @@ -13,7 +13,8 @@ extension LocalRouterConfig { /// leader: one other Mac serving the model would read as this Mac alone (`this_mac_only`). The pair's API beside /// Darkbloom is the coordinator-paired member's (`start --cluster-member --local-endpoint`), whose router takes /// Darkbloom work. - public static func pairLeaderOutsideDarkbloom(local: LocalSettings?, coordinatorURL: String?) -> LocalRouterConfig { - .host(local: local, coordinatorURL: coordinatorURL, takesCoordinatorWork: false) + public static func pairLeaderOutsideDarkbloom(local: LocalSettings?, settingsFile: URL?, + coordinatorURL: String?) -> LocalRouterConfig { + .host(local: local, settingsFile: settingsFile, coordinatorURL: coordinatorURL, takesCoordinatorWork: false) } } diff --git a/provider-swift/Sources/ProviderCore/Server/LocalRouter.swift b/provider-swift/Sources/ProviderCore/Server/LocalRouter.swift index 81606d941c..cb7c579426 100644 --- a/provider-swift/Sources/ProviderCore/Server/LocalRouter.swift +++ b/provider-swift/Sources/ProviderCore/Server/LocalRouter.swift @@ -21,8 +21,12 @@ import notify /// A request this Mac serves never leaves the process: the router hands it to the engine and returns the engine's /// response as it is, adding one header. The upstream client exists only once a request needs it. public struct LocalRouterConfig: Sendable { - /// The saved `[local]` settings; `route` decides the hops. + /// The saved `[local]` settings at start; `route` decides the hops until `settingsFile` says another. public var settings: LocalSettings + /// The provider config file `settings` came from. A running router reads its `[local] route` again when the file + /// changes (`LocalRouterRouteFile`), so `darkbloom route ` or an edit counts from the next request that + /// needs the route, with no restart. nil: `settings.route` stays as given. + public var settingsFile: URL? /// The coordinator's HTTP base URL (`LocalRouterPolicy.upstreamBaseURL`). public var upstreamBaseURL: URL /// This Mac takes Darkbloom work from the coordinator, so a `self` request could come back to it (`--local` and @@ -31,7 +35,8 @@ public struct LocalRouterConfig: Sendable { public var accountKeys: any LocalRouterAccountKeyStore /// Makes the upstream client; called once, by the first request that needs the coordinator. public var makeTransport: @Sendable () -> any LocalRouterTransport - /// One line per decision to pass a request on; never a key, a body or a prompt. + /// Where the router's lines go: its decisions to pass requests on and the saved route's changes; never a key, a + /// body, a prompt or text from the config file. public var log: @Sendable (String) -> Void public var timing: LocalRouter.Timing /// Whether the local API requires its key. Without one (`--no-auth`) anything that reaches the port is a client, so @@ -43,13 +48,16 @@ public struct LocalRouterConfig: Sendable { var keyChangeNotification: String? /// The account key as last read, kept until it changes. let keyCache = LocalRouterKeyCache() + /// `[local] route` as `settingsFile` said it when it last changed. + let routeFile = LocalRouterRouteFile() - public init(settings: LocalSettings, upstreamBaseURL: URL, takesCoordinatorWork: Bool, + public init(settings: LocalSettings, settingsFile: URL? = nil, upstreamBaseURL: URL, takesCoordinatorWork: Bool, accountKeys: any LocalRouterAccountKeyStore, makeTransport: @escaping @Sendable () -> any LocalRouterTransport = { URLSessionLocalRouterTransport() }, log: @escaping @Sendable (String) -> Void = LocalRouter.standardErrorLog, timing: LocalRouter.Timing = .init()) { self.settings = settings + self.settingsFile = settingsFile self.upstreamBaseURL = upstreamBaseURL self.takesCoordinatorWork = takesCoordinatorWork self.accountKeys = accountKeys @@ -59,24 +67,44 @@ public struct LocalRouterConfig: Sendable { keyChangeNotification = (accountKeys as? KeychainLocalRouterAccountKeyStore)?.changeNotification } - /// The router of a host: `[local]` from the config (absent = today's defaults), the configured coordinator, and - /// the account key in the Keychain. - public static func host(local: LocalSettings?, coordinatorURL: String?, takesCoordinatorWork: Bool, + /// The router of a host: `[local]` from the config at `settingsFile` (absent = today's defaults), read again when + /// that file changes, the configured coordinator, and the account key in the Keychain. + public static func host(local: LocalSettings?, settingsFile: URL?, coordinatorURL: String?, takesCoordinatorWork: Bool, accountKeys: any LocalRouterAccountKeyStore = KeychainLocalRouterAccountKeyStore()) -> LocalRouterConfig { - LocalRouterConfig(settings: local ?? LocalSettings(), + LocalRouterConfig(settings: local ?? LocalSettings(), settingsFile: settingsFile, upstreamBaseURL: LocalRouterPolicy.upstreamBaseURL(coordinatorURL: coordinatorURL), takesCoordinatorWork: takesCoordinatorWork, accountKeys: accountKeys) } - /// The route in effect now, and the key it uses. Without a saved key, or without a local key (`--no-auth`), nothing - /// can go upstream, whatever the route. The key is read once, by the first call that needs it, and kept in memory - /// (`LocalRouterKeyCache`); `route key` announces a change, and the next call reads it again, so a change counts - /// from the next request without a restart. A saved `this-mac`, or no local key, never reads the Keychain. A key - /// that can't be read (the Keychain won't hand it over without asking) isn't kept: it is said once per run of - /// failures, in a line without the key, and keeps requests on this Mac. `[local] route` itself is read at start. - func effectiveRoute() -> (route: LocalSettings.Route, accountKey: String?) { - guard localKeyRequired, settings.route != .thisMac else { return (.thisMac, nil) } + /// `[local] route` now: as `settingsFile` says it (`LocalRouterRouteFile`), else as the router started with. + func savedRoute() -> LocalSettings.Route? { + guard let settingsFile else { return settings.route } + return routeFile.route(in: settingsFile, startingWith: settings.route, log: log) + } + + /// The route in effect now, and the key it uses; `.thisMacOnly` whenever nothing may leave this Mac. + /// + /// - Only a request this Mac can't take, and a model list, call this, once each. A request this Mac serves never + /// looks at the config file or the Keychain, and nothing here runs per token. A request passed on keeps, through + /// every hop, the route and key this call gave it, whatever an edit says meanwhile. + /// - Without a local key (`--no-auth`), anything that reaches the port is a client: nothing is passed on, and + /// neither the file nor the Keychain is looked at. + /// - The route is `[local] route` as the config file says it now (`savedRoute`); a saved `this-mac` never reads the + /// Keychain. + /// - The key is read once, by the first call that needs it, and kept in memory (`LocalRouterKeyCache`); `route key` + /// announces a change, and the next call reads it again, so a change counts from the next request without a + /// restart. Without a saved key, nothing is passed on, whatever the route; `routeNeedingKey` then names the route + /// that asked for one, so the answer can say why. A key that can't be read (the Keychain won't hand it over + /// without asking) isn't kept: it is said once per run of failures, in a line without the key, and keeps requests + /// on this Mac. + /// - Whatever route the file says, the caller then serves a client on another machine `my-macs-first` as `my-macs` + /// (`LocalRouterPolicy.route`): a client on the LAN never uses the paid network. + func effectiveRoute() -> LocalRouterEffectiveRoute { + // First: without a local key the route doesn't matter, so the file isn't even looked at. + guard localKeyRequired else { return .thisMacOnly } + let saved = savedRoute() + guard saved != .thisMac else { return .thisMacOnly } let key: String? do { key = try keyCache.key(from: accountKeys, changes: keyChangeNotification) @@ -87,11 +115,124 @@ public struct LocalRouterConfig: Sendable { log("\(reason); requests stay on this Mac until it can be read (after a new build, save it again with " + "`\(BuildEnvironment.current.cliName) route key`)") } - return (.thisMac, nil) + return .thisMacOnly + } + let route = LocalSettings(route: saved).resolvedRoute(accountKeySaved: true) + guard let key else { + // A saved `my-macs` or `my-macs-first` asks for a key. With no route saved, only a key read while this + // router ran did, and `route key --remove` removed it since. + let asked = saved != nil || keyCache.keySeenThisRun + return LocalRouterEffectiveRoute(route: .thisMac, routeNeedingKey: asked ? route : nil) + } + guard route != .thisMac else { return .thisMacOnly } + return LocalRouterEffectiveRoute(route: route, accountKey: key) + } +} + +/// Where a request this Mac can't take goes now (`LocalRouterConfig.effectiveRoute`). +struct LocalRouterEffectiveRoute: Sendable { + /// The route in effect; `.thisMac` whenever nothing may leave this Mac. + var route: LocalSettings.Route + /// The account key `route` passes requests on with; nil with `.thisMac`. + var accountKey: String? + /// The route that would pass the request on, but no account key is saved: a saved `my-macs` or `my-macs-first`, + /// or, with no route saved, `my-macs` once a key read while this router ran was removed. nil otherwise. + var routeNeedingKey: LocalSettings.Route? + + static let thisMacOnly = LocalRouterEffectiveRoute(route: .thisMac) +} + +/// `[local] route` as the provider config file says it now, for a running router: the one place that decides when the +/// file is read again. +/// +/// - Each call compares the file with the one it last saw: one `stat`, for its device, inode, size and modification +/// time. Only a change reads it again: `darkbloom route `'s atomic replace (a new inode each time), or an +/// edit in place (a new size or modification time). On a file system with coarser times than APFS's nanoseconds, an +/// edit in place that keeps the size within the same tick is seen only at the file's next change. +/// - The `stat` comes before the read, so an edit that lands between them is read again by the next call, never +/// missed. The lock is held across the read: one change is read once, and the calls that need the route meanwhile +/// wait for it. +/// - A file that doesn't read as a provider config (a malformed edit, or a file that is gone) keeps the last good +/// route, said once in the log until it reads again. A file missing at the first call isn't read: the route stays as +/// the router started with. +/// - Only a whole file counts (`route(inWhole:stamped:)`). An editor that saves in place empties the file, then writes +/// it, so a read can find it empty, or holding only its start, which can parse without `[local] route`: "no route", +/// which with a key is `my-macs`. Either keeps the last good route like a malformed edit, so a saved `this-mac` +/// never passes a request on while the file is saved. +/// - A line names the file and a route (one of its fixed names) only, never text from the file: the file can hold +/// credentials. +final class LocalRouterRouteFile: @unchecked Sendable { + private let lock = NSLock() + /// The file as the last call found it; nil before the first call and while the file is missing. + private var stamp: Stamp? + /// The route of the last good read; nil before one (the router's own route counts), `.some(nil)` for a good file + /// without `[local] route`. + private var lastGood: LocalSettings.Route?? + /// A bad read was said; the next good one clears it. + private var failing = false + private var checkCount = 0 + + /// How many times the file was compared (one `stat` each). + var checks: Int { lock.withLock { checkCount } } + + /// The route the file says now: `initial` (the router's own) until a good read, and the last good one after a bad + /// read. `read` hands back the file's bytes. + func route(in file: URL, startingWith initial: LocalSettings.Route?, log: (String) -> Void, + read: (URL) throws -> Data = { try Data(contentsOf: $0) }) -> LocalSettings.Route? { + lock.withLock { + checkCount += 1 + let now = Stamp(file) + let current = lastGood ?? initial + guard now != stamp else { return current } + stamp = now + let outcome = Result { try Self.route(inWhole: read(file), stamped: now) } + guard case .success(let route) = outcome else { + // The last good route stands. The error isn't said: it can quote the file. + if !failing { + failing = true + log("\(file.lastPathComponent) doesn't read as a provider config now; requests keep the route " + + "\(Self.name(current)) until it does") + } + return current + } + failing = false + lastGood = .some(route) + if route != current { log("route is now \(Self.name(route)) (\(file.lastPathComponent) changed)") } + return route + } + } + + static func name(_ route: LocalSettings.Route?) -> String { route?.rawValue ?? "not set" } + + /// `[local] route` in `bytes`, which must be the whole file as `stamp` saw it: not empty, the size the `stat` gave, + /// and a provider config. Anything less is a save in place caught half done (or a file that is gone or broken), + /// and throws. + static func route(inWhole bytes: Data, stamped stamp: Stamp?) throws -> LocalSettings.Route? { + guard !bytes.isEmpty, Int64(bytes.count) == stamp?.size, let text = String(data: bytes, encoding: .utf8) + else { throw NotWhole() } + return try ConfigManager.parseValidating(text).local?.route + } + + /// A read that isn't the whole file the `stat` saw. + struct NotWhole: Error {} + + /// What tells one version of the file from another without reading it. + struct Stamp: Equatable { + let device: Int64 + let inode: UInt64 + let size: Int64 + let modifiedSeconds: Int + let modifiedNanoseconds: Int + + init?(_ file: URL) { + var info = stat() + guard stat(file.path, &info) == 0 else { return nil } + device = Int64(info.st_dev) + inode = UInt64(info.st_ino) + size = Int64(info.st_size) + modifiedSeconds = info.st_mtimespec.tv_sec + modifiedNanoseconds = info.st_mtimespec.tv_nsec } - let route = settings.resolvedRoute(accountKeySaved: key != nil) - guard let key, route != .thisMac else { return (.thisMac, nil) } - return (route, key) } } @@ -99,7 +240,8 @@ public struct LocalRouterConfig: Sendable { /// /// The copy is kept only while the store's changes are watched: the store posts a Darwin notification when `route key` /// saves or removes the key, and this drops the copy on it (`notify_register_dispatch`), so the next request reads the -/// key again. A failed read isn't kept, so the next request tries again; a run of failures is said once. +/// key again. A failed read isn't kept, so the next request tries again; a run of failures is said once. A request kept +/// on this Mac because no key is saved is said once too, until a key is read again. final class LocalRouterKeyCache: @unchecked Sendable { private let lock = NSLock() /// nil: no copy; `.some(nil)`: read, and no key is saved. @@ -110,12 +252,28 @@ final class LocalRouterKeyCache: @unchecked Sendable { private var watchTried = false /// The registration for the change notification; nil when there is none to watch, or it couldn't be made. private var watch: Int32? + /// Whether a read found a saved key while this router ran. + private var sawAKey = false + /// Whether a request kept on this Mac for want of a key was said since this router started or a key was last read. + private var missingSaid = false deinit { if let watch { notify_cancel(watch) } } /// Whether a copy is kept now. var keepsACopy: Bool { lock.withLock { copy != nil } } + /// Whether a read found a saved key while this router ran: with no route saved, that key passed requests on. + var keySeenThisRun: Bool { lock.withLock { sawAKey } } + + /// Notes a request kept on this Mac for want of a key; true for the first since this router started or a key was + /// last read, so the log says it once for each time the key goes. + func missingKeyNoted() -> Bool { + lock.withLock { + defer { missingSaid = true } + return !missingSaid + } + } + /// The saved key, nil when none is saved: the kept copy, else a read of `store`, kept while `changes` (the store's /// change notification) is watched. func key(from store: any LocalRouterAccountKeyStore, changes notification: String?) throws -> String? { @@ -130,6 +288,10 @@ final class LocalRouterKeyCache: @unchecked Sendable { let key = try store.load().flatMap { $0.isEmpty ? nil : $0 } lock.withLock { failing = false + if key != nil { + sawAKey = true + missingSaid = false + } if keeps, changes == seen { copy = .some(key) } } return key diff --git a/provider-swift/Sources/ProviderCore/Server/LocalRouterResponder.swift b/provider-swift/Sources/ProviderCore/Server/LocalRouterResponder.swift index 887f6fd78e..4b2e62f6ec 100644 --- a/provider-swift/Sources/ProviderCore/Server/LocalRouterResponder.swift +++ b/provider-swift/Sources/ProviderCore/Server/LocalRouterResponder.swift @@ -98,9 +98,14 @@ public final class LocalRouter: Sendable { var local = try await inner.respond(to: request, context: context) local.headers[LocalRouterPolicy.servedByHeader] = LocalRouterPolicy.thisMac guard LocalRouterPolicy.passesOn(localStatus: local.status) else { return local } - // Only a request this Mac can't take reads the account key; without one, this Mac's answer stands. - let (saved, key) = config.effectiveRoute() - guard let key else { return local } + // Only a request this Mac can't take reads the saved route (one `stat` of the config file) and the account key; + // without a key, this Mac's answer stands, saying why when a route asked for your other Macs. + let effective = config.effectiveRoute() + guard let key = effective.accountKey else { + guard let wanted = effective.routeNeedingKey else { return local } + return needsAccountKey(local, model: Self.model(in: body), route: wanted) + } + let saved = effective.route if local.status == .notFound, let answer = try await answerAliasHere(request, body: body, context: context, inner: inner) { local = answer @@ -340,6 +345,31 @@ public final class LocalRouter: Sendable { return response } + /// This Mac's refusal, said plainly, when `wanted` would pass the request on but no account key is saved: the + /// saved `my-macs` or `my-macs-first`, or the route a key gave until `route key --remove`. It keeps this Mac's + /// status and `Retry-After`. The log says it once, until a key is read again; neither names the key. + private func needsAccountKey(_ local: Response, model: String?, route wanted: LocalSettings.Route) -> Response { + let cli = BuildEnvironment.current.cliName + if config.keyCache.missingKeyNoted() { + log("a request this Mac can't take stays on this Mac: reaching \(Self.reach(wanted)) needs an account key, " + + "and none is saved (`\(cli) route key` saves one)") + } + // A client on another machine never uses the paid network, so it is told of your other Macs only. + let route = LocalRouterPolicy.route(wanted, fromAnotherMachine: LocalHTTPClient.fromAnotherMachine) + let refusal = local.status == .notFound ? "This Mac doesn't serve \(model ?? "the requested model")" + : "This Mac can't take this request right now" + var response = Self.errorResponse(local.status, message: "\(refusal), and reaching \(Self.reach(route)) needs an " + + "account key: run `\(cli) route key`.", code: "account_key_needed") + if let retryAfter = local.headers[.retryAfter] { response.headers[.retryAfter] = retryAfter } + response.headers[LocalRouterPolicy.servedByHeader] = LocalRouterPolicy.thisMac + return response + } + + /// Where `route` passes a request on, in plain words. + private static func reach(_ route: LocalSettings.Route) -> String { + route == .myMacsFirst ? "your other Macs or the Darkbloom network" : "your other Macs" + } + // MARK: - Models func models(_ request: Request, context: Inner.Context, inner: Inner) async throws -> Response { @@ -351,10 +381,10 @@ public final class LocalRouter: Sendable { for entry in list.data { localLimits[entry.id] = await self.localLimits(entry.id) } var upstream: [(ownedBy: String, entries: [LocalRouterModelEntry])] = [] var catalog: LocalRouterCatalog? - let (saved, key) = config.effectiveRoute() + let effective = config.effectiveRoute() // Only what this client can reach: no network model for one on another machine. - let route = LocalRouterPolicy.route(saved, fromAnotherMachine: LocalHTTPClient.fromAnotherMachine) - if let key { + let route = LocalRouterPolicy.route(effective.route, fromAnotherMachine: LocalHTTPClient.fromAnotherMachine) + if let key = effective.accountKey { async let catalogRead = self.catalog() async let mine = upstreamModels(view: .mine, key: key) async let network = route == .myMacsFirst ? upstreamModels(view: .network, key: key) : [] diff --git a/provider-swift/Sources/darkbloom/RouteChoiceCommand.swift b/provider-swift/Sources/darkbloom/RouteChoiceCommand.swift new file mode 100644 index 0000000000..9fbc8b9803 --- /dev/null +++ b/provider-swift/Sources/darkbloom/RouteChoiceCommand.swift @@ -0,0 +1,219 @@ +import ArgumentParser +import Foundation +import ProviderCore + +// Each command's `route` is both its name and what it saves, so `route my-macs` can't save another route. + +/// `darkbloom route this-mac`: your requests stay on this Mac. +struct RouteThisMac: AsyncParsableCommand { + static let route = LocalSettings.Route.thisMac + static let configuration = CommandConfiguration( + commandName: route.rawValue, + abstract: "Keep your requests on this Mac.", + discussion: "Saves [local] route = \"this-mac\": a request this Mac can't take gets this Mac's own answer, and " + + "nothing is passed on. Needs no account key.") + + @OptionGroup var configOptions: ConfigOptions + + func run() async throws { + throw ExitCode(RouteChoiceFlow.live(configPath: configOptions.config).choose(Self.route)) + } +} + +/// `darkbloom route my-macs`: a request this Mac can't take goes on to your other Macs. +struct RouteMyMacs: AsyncParsableCommand { + static let route = LocalSettings.Route.myMacs + static let configuration = CommandConfiguration( + commandName: route.rawValue, + abstract: "Send a request this Mac can't take to your other Macs (free).", + discussion: "Saves [local] route = \"my-macs\": your other Macs answer, free; nothing goes to the Darkbloom " + + "network. Needs your account API key (`\(BuildEnvironment.current.cliName) route key`).") + + @OptionGroup var configOptions: ConfigOptions + + func run() async throws { + throw ExitCode(RouteChoiceFlow.live(configPath: configOptions.config).choose(Self.route)) + } +} + +/// `darkbloom route my-macs-first`: your other Macs first, then the Darkbloom network. +struct RouteMyMacsFirst: AsyncParsableCommand { + static let route = LocalSettings.Route.myMacsFirst + static let configuration = CommandConfiguration( + commandName: route.rawValue, + abstract: "Send it to your other Macs (free), then the Darkbloom network (billed).", + discussion: "Saves [local] route = \"my-macs-first\": your other Macs first, free, then the Darkbloom network, " + + "billed to your balance. Requests from other machines (your LAN or tailnet) never use the paid network. " + + "Needs your account API key (`\(BuildEnvironment.current.cliName) route key`).") + + @OptionGroup var configOptions: ConfigOptions + + func run() async throws { + throw ExitCode(RouteChoiceFlow.live(configPath: configOptions.config).choose(Self.route)) + } +} + +/// The steps of `route `, apart from the Keychain, the config file and the terminal: it saves `[local] route` +/// and says where your requests go. A route that passes requests on needs a saved account key: the flow gets only +/// whether one is saved, and no line names a key. No line names a speed. +struct RouteChoiceFlow { + /// Whether the local router's account key is saved; asked only for a route that passes requests on. + let accountKeySaved: () -> Bool + /// Saves `[local] route`; true when the file changed. + let save: (LocalSettings.Route) throws -> Bool + /// The local API running now: its router uses the saved route from its next request that needs it. Only whether it + /// runs and whether it has a local key are read; its key is never said. + var liveEndpoint: LocalEndpoint.Info? + /// This Mac's part in a two-Mac cluster: the pair's local API uses the leading Mac's route. + var pair: RouteSaved.PairPart? + let say: (String) -> Void + + func choose(_ route: LocalSettings.Route) -> Int32 { + let cli = BuildEnvironment.current.cliName + if route != .thisMac, !accountKeySaved() { + say("✗ Not saved: `\(cli) route \(route.rawValue)` passes your requests on with your account API key, and " + + "this Mac has none saved.") + // On the Mac that follows, the pair's route and key are the leading Mac's: said first, so a key meant for + // the pair isn't saved here, where it counts only when this Mac serves alone. + if case .follows(let leader) = pair { + say("In this pair, the leading Mac's route and key apply (\(leader)): for the pair, run `\(cli) route key` " + + "and `\(cli) route \(route.rawValue)` there.") + say("For this Mac alone (`\(cli) start --solo`), save one here from the Darkbloom console with " + + "`\(cli) route key` (a self-route-only key is safest), then run `\(cli) route \(route.rawValue)` again.") + } else { + say("Save one from the Darkbloom console with `\(cli) route key` (a self-route-only key is safest), then " + + "run `\(cli) route \(route.rawValue)` again.") + } + return 1 + } + let changed: Bool + do { + changed = try save(route) + } catch { + say("✗ Not saved: \(error)") + return 1 + } + // A local API without a local key (`--no-auth`) passes nothing on, whatever the route, the pair's on the leading + // Mac included. On the Mac that follows, the pair's API is the leading Mac's, whatever this Mac runs. + let keyless = pair?.follows != true && liveEndpoint?.apiKey.isEmpty == true + let head = changed ? "✓ Saved." : "✓ Already saved." + say(keyless ? head : head + " " + RouteSaved.when(running: liveEndpoint != nil, pair: pair)) + for line in Self.meaning(route) { say(line) } + if keyless { + say("The local API running now has no local key (--no-auth): it keeps every request on " + + "\(RouteSaved.thisMacOrPair(pair)), whatever the route.") + } else if let pair { + say(RouteSaved.pairRouteLine(pair, route: route)) + } + return 0 + } + + /// Where your requests go with `route`, in plain words. + static func meaning(_ route: LocalSettings.Route) -> [String] { + switch route { + case .thisMac: + return ["Your requests stay on this Mac: one it can't take gets this Mac's own answer, and nothing is passed on."] + case .myMacs: + return ["A request this Mac can't take goes on to your other Macs, free. It never goes to the Darkbloom network."] + case .myMacsFirst: + return ["A request this Mac can't take goes on to your other Macs (free), then to the Darkbloom network, billed " + + "to your balance. With a self-route-only key, only your Macs answer.", + "Requests from other machines (your LAN or tailnet) never use the paid network: they can use this Mac " + + "and your other Macs."] + } + } + + /// This Mac's Keychain, provider.toml (`configPath`, else the default), local API and pairing. + static func live(configPath: String?) -> RouteChoiceFlow { + RouteChoiceFlow( + accountKeySaved: { Start.accountKeySaved() }, + save: { route in try setLocalSettings(configPath: configPath) { $0.route = route }.changed }, + liveEndpoint: LocalEndpoint.readLiveInfo(), pair: .of(ClusterPairSummary.local()), say: { print($0) }) + } +} + +/// When a saved route or account key counts. A running local API uses both from its next request that needs them: +/// its router reads `[local] route` again once provider.toml changes (`LocalRouterRouteFile`), and the key's change +/// notification makes it read the key again, so nothing restarts and no model reloads. In a two-Mac cluster, the +/// pair's local API runs on the leading Mac and uses that Mac's route and key. Requests from the other Mac reach it +/// from another machine (a relay, or tools that dial its address), so it never sends them to the paid network. +enum RouteSaved { + /// This Mac's part in a two-Mac cluster. + enum PairPart: Equatable, Sendable { + /// This Mac leads: the pair's local API runs here. + case leads(other: String) + /// This Mac follows `leader`, whose local API is the pair's. + case follows(leader: String) + + /// Whether this Mac follows: the pair doesn't use what it saves. + var follows: Bool { + if case .follows = self { return true } + return false + } + + /// This Mac's part, when its pairing can be read; nil on a Mac in no pair. + static func of(_ pair: ClusterPairSummary) -> PairPart? { + guard pair.paired, !pair.pairingUnreadable, let role = pair.role else { return nil } + return role == .leader ? .leads(other: pair.otherMac) : .follows(leader: pair.otherMac) + } + } + + static let usesItNow = "Your local API uses it now." + static let appliesAtStart = "It applies when your local API starts." + static var appliesAlone: String { "It applies when this Mac serves alone (`\(BuildEnvironment.current.cliName) start --solo`)." } + + /// When what was saved counts on this Mac: now, when a local API (or the pair's, on the leading Mac) runs; else at + /// its start. On the Mac that follows, only when it serves alone: the pair uses the leading Mac's. + static func when(running: Bool, pair: PairPart?) -> String { + if pair?.follows == true { return appliesAlone } + return running ? usesItNow : appliesAtStart + } + + /// What serves your requests here: the pair on the leading Mac, whose local API is the pair's; else this Mac (alone, + /// or the Mac that follows, whose route counts when it serves alone). + static func thisMacOrPair(_ pair: PairPart?) -> String { + if case .leads = pair { return "this pair" } + return "this Mac" + } + + /// Whose route the pair's local API uses. The Mac that follows can't know the leading Mac's route or key, so it says + /// only whose route decides. Requests from the other Mac reach the leading Mac's API from another machine, so with + /// `my-macs-first` they never use the paid network, and both Macs say so. + static func pairRouteLine(_ pair: PairPart, route: LocalSettings.Route) -> String { + let neverPaid = route == .myMacsFirst + switch pair { + case .leads(let other): + let passes = route == .thisMac ? "passes nothing on" : "passes on what the pair can't take" + return "In this pair, this Mac's route applies: the pair's local API runs here and \(passes), including " + + "requests from \(other)" + + (neverPaid ? "; to this Mac those come from another machine, so they never use the paid network." : ".") + case .follows(let leader): + return "In this pair, the leading Mac's route applies (\(leader)): its route decides what the pair passes on, " + + "including requests from this Mac" + + (neverPaid ? "; to the leading Mac those come from another machine, so they never use the paid network." + : ".") + + " Run `\(BuildEnvironment.current.cliName) route \(route.rawValue)` there." + } + } + + /// Whose account key the pair's local API uses, once `route key` saved this Mac's key or `removed` it. + /// `routePassesOn`: this Mac's route passes requests on with a key. + static func pairKeyLine(_ pair: PairPart, removed: Bool, routePassesOn: Bool) -> String { + let cli = BuildEnvironment.current.cliName + switch pair { + case .leads: + let runsHere = "In this pair, the pair's local API runs on this Mac" + if !routePassesOn { + // A removed key can't be named: say what a route that passes requests on will need. + return removed ? runsHere + ": once its route passes requests on, it needs a key saved here again." + : runsHere + " and uses this Mac's key once its route passes requests on." + } + return removed ? runsHere + ", so the pair passes nothing on until a key is saved here again." + : runsHere + " and passes requests on with this key." + case .follows(let leader): + return "In this pair, the pair's local API uses the leading Mac's key (\(leader)), not this one: " + + (removed ? "to stop the pair passing requests on, run `\(cli) route key --remove` there." + : "run `\(cli) route key` there.") + } + } +} diff --git a/provider-swift/Sources/darkbloom/RouteCommand.swift b/provider-swift/Sources/darkbloom/RouteCommand.swift index cadadd8eaa..f95f71a8b1 100644 --- a/provider-swift/Sources/darkbloom/RouteCommand.swift +++ b/provider-swift/Sources/darkbloom/RouteCommand.swift @@ -12,11 +12,13 @@ struct Route: AsyncParsableCommand { commandName: "route", abstract: "Where your requests go when this Mac can't take them.", discussion: """ - This Mac's local API answers your requests first. With an account API key saved, a request this Mac can't \ - take goes on to your other Macs (free), and with `[local] route = "my-macs-first"` then to the Darkbloom \ - network (billed). Without a key, requests stay on this Mac. + This Mac's local API answers your requests first. A request it can't take stays on this Mac (`this-mac`), \ + goes on to your other Macs, free (`my-macs`), or to your other Macs and then the Darkbloom network, billed \ + (`my-macs-first`). Requests from other machines never use the paid network. `my-macs` and `my-macs-first` \ + need your account API key, saved with `route key`. The choice is saved in [local] route, and a running local \ + API uses it, and the key, from its next request: no restart. """, - subcommands: [RouteKey.self] + subcommands: [RouteThisMac.self, RouteMyMacs.self, RouteMyMacsFirst.self, RouteKey.self] ) } @@ -53,7 +55,8 @@ struct RouteKey: AsyncParsableCommand { savedRoute: loaded?.config.local?.route, check: { key in await RouteKeyFlow.checkWithDarkbloom(key: key, upstream: upstream) }, say: { print($0) }) - flow.liveEndpointHasNoLocalKey = LocalEndpoint.readLiveInfo().map { $0.apiKey.isEmpty } ?? false + flow.seesLocalAPI(LocalEndpoint.readLiveInfo()) + flow.pair = .of(ClusterPairSummary.local()) if remove { throw ExitCode(flow.remove()) } @@ -89,6 +92,17 @@ struct RouteKeyFlow { let say: (String) -> Void /// The local API running now has no local key (`--no-auth`), so its router never passes a request on. var liveEndpointHasNoLocalKey = false + /// A local API with a local key runs now: its router reads the key again before its next request that needs it. + var localAPIRunning = false + /// This Mac's part in a two-Mac cluster: the pair's local API uses the leading Mac's key. + var pair: RouteSaved.PairPart? + + /// The local API running now (`LocalEndpoint.readLiveInfo`), if any: with a local key it reads the account key again + /// before its next request that needs it; without one (`--no-auth`) it never uses it. + mutating func seesLocalAPI(_ live: LocalEndpoint.Info?) { + liveEndpointHasNoLocalKey = live.map { $0.apiKey.isEmpty } ?? false + localAPIRunning = live.map { !$0.apiKey.isEmpty } ?? false + } func save(_ rawKey: String) async -> Int32 { let key = rawKey.trimmingCharacters(in: .whitespacesAndNewlines) @@ -113,13 +127,16 @@ struct RouteKeyFlow { return 1 } say("✓ Account key saved in this Mac's Keychain. " + note) - for line in Self.routeLines(savedRoute: savedRoute, keySaved: true) { say(line) } + for line in Self.routeLines(savedRoute: savedRoute, keySaved: true, here: RouteSaved.thisMacOrPair(pair)) { + say(line) + } if liveEndpointHasNoLocalKey { - say("The running local API has no local key (--no-auth): it keeps every request on this Mac and never " - + "uses the account key.") + say("The running local API has no local key (--no-auth): it keeps every request on " + + "\(RouteSaved.thisMacOrPair(pair)) and never uses the account key.") } else { - say("A running local API uses it from its next request that needs it; no restart is needed.") + say(RouteSaved.when(running: localAPIRunning, pair: pair)) } + if let line = pairKeyLine(removed: false) { say(line) } return 0 } @@ -131,22 +148,48 @@ struct RouteKeyFlow { return 1 } say("✓ Account key removed from this Mac's Keychain.") - for line in Self.routeLines(savedRoute: savedRoute, keySaved: false) { say(line) } + for line in Self.routeLines(savedRoute: savedRoute, keySaved: false, here: RouteSaved.thisMacOrPair(pair)) { + say(line) + } + // A local API without a local key (`--no-auth`) never used the key, so nothing changes for it. Any other one + // whose route passed requests on with the key stops doing so from its next request: on the leading Mac of a + // pair, the pair's. + if localAPIRunning, pair?.follows != true, routeWithTheKey != .thisMac { + let here = pair == nil ? "this Mac" : "the pair" + say("\(RouteSaved.usesItNow) From its next request, one \(here) can't take gets \(here)'s own answer " + + "instead of going to your other Macs" + + (routeWithTheKey == .myMacsFirst ? " or the Darkbloom network." : ".")) + } else if !liveEndpointHasNoLocalKey { + say(RouteSaved.when(running: localAPIRunning, pair: pair)) + } + if let line = pairKeyLine(removed: true) { say(line) } return 0 } - /// Where requests go with this route and key, in the iPhone app's words. Never a speed. - static func routeLines(savedRoute: LocalSettings.Route?, keySaved: Bool) -> [String] { + /// Where a request this Mac can't take goes while a key is saved: what the key lets the route do. + var routeWithTheKey: LocalSettings.Route { LocalSettings(route: savedRoute).resolvedRoute(accountKeySaved: true) } + + /// Whose key the pair's local API uses, after this save or removal; nil outside a pair, and on a leading Mac whose + /// running API has no local key, which never uses one. + func pairKeyLine(removed: Bool) -> String? { + guard let pair, pair.follows || !liveEndpointHasNoLocalKey else { return nil } + return RouteSaved.pairKeyLine(pair, removed: removed, routePassesOn: routeWithTheKey != .thisMac) + } + + /// Where requests go with this route and key, in the iPhone app's words, from `here`: this Mac, or this pair on the + /// leading Mac (`RouteSaved.thisMacOrPair`). Never a speed. + static func routeLines(savedRoute: LocalSettings.Route?, keySaved: Bool, here: String = "this Mac") -> [String] { let route = LocalSettings(route: savedRoute).resolvedRoute(accountKeySaved: keySaved) switch (route, keySaved) { case (.thisMac, true): - return ["Your requests: this Mac only ([local] route = \"this-mac\"). The key is used once you choose your Macs."] + return ["Your requests: \(here) only ([local] route = \"this-mac\"). The key is used once you choose your " + + "Macs: `\(BuildEnvironment.current.cliName) route my-macs`."] case (_, false): - return ["Your requests: this Mac only, until an account key is saved again."] + return ["Your requests: \(here) only, until an account key is saved again."] case (.myMacs, true): - return ["Your requests: this Mac first, then your other Macs (free)."] + return ["Your requests: \(here) first, then your other Macs (free)."] case (.myMacsFirst, true): - return ["Your requests: this Mac first, then your other Macs (free), then the Darkbloom network (billed to " + return ["Your requests: \(here) first, then your other Macs (free), then the Darkbloom network (billed to " + "your balance; the network needs a positive balance).", "With a self-route-only key, Darkbloom answers only from your Macs, even with My Macs first."] } diff --git a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift index e462f914d0..53659942c9 100644 --- a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift +++ b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift @@ -96,9 +96,7 @@ extension Start { mtpAcceptance: config.backend.mtpAcceptance, mtpAcceptanceByModel: config.backend.mtpAcceptanceByModel, coordinatorURL: config.coordinator.url, - // `--local` never registers with the coordinator, so a `self` request can't come back to it. - router: .host(local: config.local, coordinatorURL: coordinatorURL ?? config.coordinator.url, - takesCoordinatorWork: false) + router: Self.onlyMeRouter(config: config, configFile: snapshot.configPath, coordinatorURL: coordinatorURL) ), models: advertised ) @@ -343,6 +341,7 @@ extension Start { } let localEndpointConfig = try Self.unifiedLocalEndpoint(serving: serving, config: config, + settingsFile: snapshot.configPath, coordinatorURL: coordinatorURL) let loopConfig = ProviderLoopConfig( @@ -383,11 +382,19 @@ extension Start { await TelemetryClient.shared.shutdown() } + /// Only me's local router: `[local]` from `config`, read again from `configFile` (the provider.toml the start loaded) + /// when it changes. `--local` never registers with the coordinator, so a `self` request can't come back to it. + static func onlyMeRouter(config: ProviderConfig, configFile: URL, coordinatorURL: String?) -> LocalRouterConfig { + .host(local: config.local, settingsFile: configFile, coordinatorURL: coordinatorURL ?? config.coordinator.url, + takesCoordinatorWork: false) + } + /// The unified local API of a provider that serves Darkbloom and its owner (Both); nil for the Darkbloom network /// only, which then binds nothing and creates no key. Reuses the same persistent bearer token and address as - /// `--local`; `--no-auth` opts out of the token (trusted/airgapped only). + /// `--local`; `--no-auth` opts out of the token (trusted/airgapped only). Its router reads `[local] route` again + /// from `settingsFile`, the provider.toml the start loaded, when it changes. static func unifiedLocalEndpoint( - serving: StartServing, config: ProviderConfig, coordinatorURL: String, + serving: StartServing, config: ProviderConfig, settingsFile: URL, coordinatorURL: String, loadToken: () throws -> String = { try LocalEndpoint.loadOrCreateToken() } ) throws -> LocalInferenceHTTPConfig? { guard serving.mode == .both else { return nil } @@ -409,7 +416,8 @@ extension Start { print("Local endpoint: \(serving.baseURL)\(token != nil ? " (API key from `\(BuildEnvironment.current.cliName) local`)" : " (auth disabled: requests stay on this Mac)")") return LocalInferenceHTTPConfig( host: serving.bind, port: serving.port, authToken: token, - router: .host(local: config.local, coordinatorURL: coordinatorURL, takesCoordinatorWork: true)) + router: .host(local: config.local, settingsFile: settingsFile, coordinatorURL: coordinatorURL, + takesCoordinatorWork: true)) } /// A provider that launchd runs relaunches through launchd, as the diff --git a/provider-swift/Sources/darkbloom/StartCommand+ClusterMember.swift b/provider-swift/Sources/darkbloom/StartCommand+ClusterMember.swift index 55c934bc66..d429cae7de 100644 --- a/provider-swift/Sources/darkbloom/StartCommand+ClusterMember.swift +++ b/provider-swift/Sources/darkbloom/StartCommand+ClusterMember.swift @@ -44,7 +44,8 @@ extension Start { let capabilities = DistributedServingEligibility.memberCapabilities(chipFamily: hardware.chipFamily) let coordinator = coordinatorURL ?? config.coordinator.url let endpoint = Self.clusterMemberLocalEndpoint(requested: localEndpoint, hostsPairSlot: prepared.hostsPairSlot, - bind: bind, port: port, local: config.local, coordinatorURL: coordinator) + bind: bind, port: port, local: config.local, settingsFile: path, + coordinatorURL: coordinator) // A setup saved for coordinator pairing yields this Mac's member // installation; every other setup yields none and registers no claim. let installation = try current.withCurrentReference { _ in @@ -86,9 +87,10 @@ extension Start { /// refuses an endpoint on a member without the slot (`admitsClusterPairLocalAPI`), which would end the part. /// Never without a key: always the pair's (`cluster local`'s); `validate` refuses `--no-auth`, the loop refuses a /// keyless endpoint, and a key that can't be read here leaves the pair serving Darkbloom without the API, never - /// with an open one. + /// with an open one. Its router reads `[local] route` again from `settingsFile`, this Mac's provider.toml, when it + /// changes. static func clusterMemberLocalEndpoint(requested: Bool, hostsPairSlot: Bool, bind: String, port: UInt16, - local: LocalSettings?, coordinatorURL: String?, + local: LocalSettings?, settingsFile: URL, coordinatorURL: String?, loadToken: () throws -> String = { try LocalEndpoint.loadOrCreateClusterToken() }, say: (String) -> Void = printError) -> LocalInferenceHTTPConfig? { guard requested else { return nil } @@ -101,7 +103,7 @@ extension Start { return nil } return LocalInferenceHTTPConfig(host: bind, port: port, authToken: token, - router: .host(local: local, coordinatorURL: coordinatorURL, takesCoordinatorWork: true)) + router: .host(local: local, settingsFile: settingsFile, coordinatorURL: coordinatorURL, takesCoordinatorWork: true)) } /// What a member's start that failed with `error` ends with. Refused because another Darkbloom app holds this Mac's diff --git a/provider-swift/Sources/darkbloom/StartCommand+Distributed.swift b/provider-swift/Sources/darkbloom/StartCommand+Distributed.swift index 378ebe2289..c1f4a2eb9d 100644 --- a/provider-swift/Sources/darkbloom/StartCommand+Distributed.swift +++ b/provider-swift/Sources/darkbloom/StartCommand+Distributed.swift @@ -46,10 +46,7 @@ extension Start { let batching = try DistributedAutomaticBatchFactory(providerConfiguration: configPath, stopNotice: announce) // The pair is this Mac's engine, and it takes no Darkbloom work here, whatever the registration wait below // decides: local only, or a control-only member that hosts no pair slot (`pairLeaderOutsideDarkbloom`). - let providerConfig = FileManager.default.fileExists(atPath: configPath.path) - ? try? ConfigManager.load(from: configPath) : nil - let router = LocalRouterConfig.pairLeaderOutsideDarkbloom( - local: providerConfig?.local, coordinatorURL: coordinatorURL ?? providerConfig?.coordinator.url) + let router = Self.clusterLocalRouter(configFile: configPath, coordinatorURL: coordinatorURL) let server = DistributedLocalServer( session: session, config: .init(host: bind, port: port, authToken: token, router: router), firstTokenBudgetPolicy: budget, batchReplacement: { try await batching.replacement(for: $0) }) @@ -152,6 +149,16 @@ extension Start { // A stop nobody asked for is never a clean exit: a supervisor restarts it. if let member, await member.memberStopReason != nil { throw DistributedStartRuntimeError.memberControlEnded } } + + /// The router of `cluster local`'s API (and a control-only member's that hosts no pair slot): `[local]` and the + /// coordinator from the provider.toml at `configFile` (today's defaults when there is none, or it doesn't load), + /// read again from that file when it changes. + static func clusterLocalRouter(configFile: URL, coordinatorURL: String?) -> LocalRouterConfig { + let providerConfig = FileManager.default.fileExists(atPath: configFile.path) + ? try? ConfigManager.load(from: configFile) : nil + return .pairLeaderOutsideDarkbloom(local: providerConfig?.local, settingsFile: configFile, + coordinatorURL: coordinatorURL ?? providerConfig?.coordinator.url) + } } /// How a distributed leader serves this run, decided once by its registration wait: publicly (registered with the diff --git a/provider-swift/Tests/DarkbloomCLITests/ClusterPairBothMeFirstCLITests.swift b/provider-swift/Tests/DarkbloomCLITests/ClusterPairBothMeFirstCLITests.swift index ead6d23b01..2e04b2c16d 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ClusterPairBothMeFirstCLITests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ClusterPairBothMeFirstCLITests.swift @@ -13,6 +13,9 @@ import TOMLKit struct ClusterPairBothMeFirstCLITests { typealias F = LocalFirstStatusFixtures + /// The provider.toml the pair's local API reads its route from again (never read here: no request is made). + static let configFile = URL(fileURLWithPath: "/tmp/pair-both-me-first/provider.toml") + // MARK: - The leading part @Test("the cluster service's part takes the local API's flags", arguments: [ @@ -39,7 +42,8 @@ struct ClusterPairBothMeFirstCLITests { @Test func onlyThePartThatHostsThePairsSlotStartsTheLocalAPI() { var said: [String] = [] let leader = Start.clusterMemberLocalEndpoint(requested: true, hostsPairSlot: true, bind: "0.0.0.0", port: 8001, - local: LocalSettings(route: .thisMac), coordinatorURL: "wss://example.invalid/ws/provider", + local: LocalSettings(route: .thisMac), settingsFile: Self.configFile, + coordinatorURL: "wss://example.invalid/ws/provider", loadToken: { "dk-cluster-fixture" }, say: { said.append($0) }) #expect(leader?.host == "0.0.0.0" && leader?.port == 8001) #expect(leader?.authToken == "dk-cluster-fixture", "always the pair's key, as `cluster local`") @@ -50,17 +54,20 @@ struct ClusterPairBothMeFirstCLITests { // Every other member: no API, no key read, one line. var loads = 0 let other = Start.clusterMemberLocalEndpoint(requested: true, hostsPairSlot: false, bind: "0.0.0.0", port: 8001, - local: nil, coordinatorURL: nil, loadToken: { loads += 1; return "dk" }, say: { said.append($0) }) + local: nil, settingsFile: Self.configFile, coordinatorURL: nil, + loadToken: { loads += 1; return "dk" }, say: { said.append($0) }) #expect(other == nil && loads == 0 && said.count == 1) // Today's member, without --local-endpoint: nothing at all. let today = Start.clusterMemberLocalEndpoint(requested: false, hostsPairSlot: true, bind: "127.0.0.1", port: 8000, - local: nil, coordinatorURL: nil, loadToken: { loads += 1; return "dk" }, say: { said.append($0) }) + local: nil, settingsFile: Self.configFile, coordinatorURL: nil, + loadToken: { loads += 1; return "dk" }, say: { said.append($0) }) #expect(today == nil && loads == 0 && said.count == 1) // A key that can't be read: Darkbloom keeps serving, and the API never opens without its key. let keyless = Start.clusterMemberLocalEndpoint(requested: true, hostsPairSlot: true, bind: "0.0.0.0", port: 8001, - local: nil, coordinatorURL: nil, loadToken: { throw CocoaError(.fileWriteNoPermission) }, say: { said.append($0) }) + local: nil, settingsFile: Self.configFile, coordinatorURL: nil, + loadToken: { throw CocoaError(.fileWriteNoPermission) }, say: { said.append($0) }) #expect(keyless == nil && said.count == 2) } diff --git a/provider-swift/Tests/DarkbloomCLITests/RouteChoiceCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/RouteChoiceCommandTests.swift new file mode 100644 index 0000000000..f9caeff8df --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/RouteChoiceCommandTests.swift @@ -0,0 +1,289 @@ +import ArgumentParser +import Foundation +import ProviderCore +import Testing + +@testable import darkbloom + +/// `darkbloom route this-mac|my-macs|my-macs-first`: saves `[local] route` without a hand-edited provider.toml, says in +/// plain words where your requests go, and refuses a route that passes requests on while no account key is saved. +/// Every test writes a temporary provider.toml and stands in for the Keychain; no key is ever read or printed. +@Suite("route ") +struct RouteChoiceCommandTests { + typealias Lines = RouteKeyCommandTests.Lines + + static var cli: String { BuildEnvironment.current.cliName } + + private func makeTempConfig(_ toml: String = "[provider]\nname = \"route-test\"\n") throws -> URL { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("route-choice-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = directory.appendingPathComponent("provider.toml") + try toml.write(to: url, atomically: true, encoding: .utf8) + return url + } + + private func flow(config url: URL, keySaved: Bool, live: LocalEndpoint.Info? = nil, + pair: RouteSaved.PairPart? = nil) -> (RouteChoiceFlow, Lines) { + let lines = Lines() + let flow = RouteChoiceFlow( + accountKeySaved: { keySaved }, + save: { route in try setLocalSettings(configPath: url.path) { $0.route = route }.changed }, + liveEndpoint: live, pair: pair, say: { lines.append($0) }) + return (flow, lines) + } + + @Test func eachChoiceParsesBesideRouteKey() throws { + #expect(try Darkbloom.parseAsRoot(["route", "this-mac"]) is RouteThisMac) + #expect(try Darkbloom.parseAsRoot(["route", "my-macs"]) is RouteMyMacs) + #expect(try Darkbloom.parseAsRoot(["route", "my-macs-first"]) is RouteMyMacsFirst) + #expect(try Darkbloom.parseAsRoot(["route", "my-macs", "--config", "/tmp/provider.toml"]) is RouteMyMacs) + #expect(try Darkbloom.parseAsRoot(["route", "key", "--stdin"]) is RouteKey) + #expect(throws: (any Error).self) { try Darkbloom.parseAsRoot(["route", "everywhere"]) } + // What each saves is the route it is named after: `route my-macs` never saves the paid route. + #expect(RouteThisMac.route == .thisMac && RouteMyMacs.route == .myMacs) + #expect(RouteMyMacsFirst.route == .myMacsFirst) + } + + @Test func aChoiceIsSavedAsTheLocalRouteAndKeepsTheRestOfTheFile() throws { + let url = try makeTempConfig("[provider]\nname = \"route-test\"\n\n[local]\nmode = \"both\"\nport = 8003\n") + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let (flow, lines) = flow(config: url, keySaved: true) + + #expect(flow.choose(.myMacsFirst) == 0) + let config = try ConfigManager.load(from: url) + #expect(config.local == LocalSettings(mode: .both, route: .myMacsFirst, port: 8003)) + #expect(config.provider.name == "route-test") + #expect(lines.all.first == "✓ Saved. It applies when your local API starts.") + + #expect(flow.choose(.thisMac) == 0) + #expect(try ConfigManager.load(from: url).local?.route == .thisMac) + } + + @Test func theSameChoiceAgainChangesNothing() throws { + let url = try makeTempConfig("[local]\nroute = \"my-macs\"\n") + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let before = try Data(contentsOf: url) + let (flow, lines) = flow(config: url, keySaved: true) + #expect(flow.choose(.myMacs) == 0) + #expect(try Data(contentsOf: url) == before) + #expect(lines.all.first == "✓ Already saved. It applies when your local API starts.") + } + + @Test(arguments: [LocalSettings.Route.myMacs, .myMacsFirst]) + func aRouteThatPassesRequestsOnNeedsASavedAccountKey(_ route: LocalSettings.Route) throws { + let url = try makeTempConfig() + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let before = try Data(contentsOf: url) + let (flow, lines) = flow(config: url, keySaved: false) + + #expect(flow.choose(route) == 1) + #expect(try Data(contentsOf: url) == before) + #expect(lines.all.first?.hasPrefix("✗ Not saved: ") == true) + #expect(lines.text.contains("`\(Self.cli) route key`")) + #expect(lines.text.contains("`\(Self.cli) route \(route.rawValue)` again")) + } + + @Test func thisMacNeedsNoAccountKey() throws { + let url = try makeTempConfig() + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let (flow, lines) = flow(config: url, keySaved: false) + #expect(flow.choose(.thisMac) == 0) + #expect(try ConfigManager.load(from: url).local?.route == .thisMac) + #expect(lines.text.contains("stay on this Mac")) + } + + @Test func eachChoiceSaysWhatItMeansInPlainWords() throws { + func said(_ route: LocalSettings.Route) throws -> String { + let url = try makeTempConfig() + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let (flow, lines) = flow(config: url, keySaved: true) + #expect(flow.choose(route) == 0) + return lines.text + } + let thisMac = try said(.thisMac), myMacs = try said(.myMacs), first = try said(.myMacsFirst) + #expect(thisMac.contains("Your requests stay on this Mac")) + #expect(myMacs.contains("your other Macs, free")) + #expect(myMacs.contains("never goes to the Darkbloom network")) + #expect(first.contains("then to the Darkbloom network, billed to your balance")) + #expect(first.contains("Requests from other machines (your LAN or tailnet) never use the paid network")) + for words in [thisMac, myMacs, first] { + #expect(!words.contains("tok/s") && !words.lowercased().contains("tokens per second")) + #expect(!words.contains("dk-local-") && !words.contains("sk-")) + } + } + + static let keyed = LocalEndpoint.Info(host: "127.0.0.1", port: 8001, apiKey: "dk-local-fixture", version: "test", + pid: 4242, updatedAt: "now") + + @Test func aRunningLocalAPIUsesTheSavedRouteNowWithNoRestart() throws { + let url = try makeTempConfig() + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let keyed = Self.keyed + let (flow, lines) = flow(config: url, keySaved: true, live: keyed) + #expect(flow.choose(.myMacs) == 0) + #expect(lines.all.first == "✓ Saved. Your local API uses it now.") + #expect(!lines.text.contains("restart")) + #expect(!lines.text.contains("dk-local-fixture")) + let (again, againLines) = self.flow(config: url, keySaved: true, live: keyed) + #expect(again.choose(.myMacs) == 0) + #expect(againLines.all.first == "✓ Already saved. Your local API uses it now.") + + var keyless = keyed + keyless.apiKey = "" + let (open, openLines) = self.flow(config: url, keySaved: true, live: keyless) + #expect(open.choose(.myMacsFirst) == 0) + #expect(openLines.all.first == "✓ Saved.") + #expect(openLines.text.contains("has no local key (--no-auth): it keeps every request on this Mac")) + } + + @Test func inAPairTheLeadingMacsRouteApplies() throws { + let url = try makeTempConfig() + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let other = "the other Mac (Apple M3 Ultra, 256 GB)" + // The Mac that follows: saved for when it serves alone; the pair uses the leading Mac's. + let (follower, followerLines) = flow(config: url, keySaved: true, live: Self.keyed, pair: .follows(leader: other)) + #expect(follower.choose(.myMacs) == 0) + #expect(try ConfigManager.load(from: url).local?.route == .myMacs) + #expect(followerLines.all.first == "✓ Saved. It applies when this Mac serves alone (`\(Self.cli) start --solo`).") + // It can't know the leading Mac's route or key, so it says only whose route decides. + #expect(followerLines.all.last == "In this pair, the leading Mac's route applies (\(other)): its route decides " + + "what the pair passes on, including requests from this Mac. Run `\(Self.cli) route my-macs` there.") + // The leading Mac runs the pair's API: it uses the route now. + let leaderURL = try makeTempConfig() + defer { try? FileManager.default.removeItem(at: leaderURL.deletingLastPathComponent()) } + let (leader, leaderLines) = flow(config: leaderURL, keySaved: true, live: Self.keyed, pair: .leads(other: other)) + #expect(leader.choose(.myMacs) == 0) + #expect(leaderLines.all.first == "✓ Saved. Your local API uses it now.") + #expect(leaderLines.all.last == "In this pair, this Mac's route applies: the pair's local API runs here and passes " + + "on what the pair can't take, including requests from \(other).") + // With `this-mac`, the pair's API passes nothing on. + let (pinned, pinnedLines) = flow(config: url, keySaved: true, live: Self.keyed, pair: .leads(other: other)) + #expect(pinned.choose(.thisMac) == 0) + #expect(pinnedLines.all.last == "In this pair, this Mac's route applies: the pair's local API runs here and passes " + + "nothing on, including requests from \(other).") + // No line says the other Mac forwards anything: a Both pair's other Mac runs no relay. + #expect(!(followerLines.text + leaderLines.text + pinnedLines.text).contains("forwards")) + } + + /// The pair's other Mac is another machine to the leading Mac's API: with `my-macs-first`, its requests go to your + /// other Macs, never to the paid network, and both Macs say so. + @Test func inAPairMyMacsFirstNeverPaysForTheOtherMacsRequests() throws { + let url = try makeTempConfig() + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let other = "the other Mac (Apple M3 Ultra, 256 GB)" + let (leader, leaderLines) = flow(config: url, keySaved: true, live: Self.keyed, pair: .leads(other: other)) + #expect(leader.choose(.myMacsFirst) == 0) + #expect(leaderLines.all.last == "In this pair, this Mac's route applies: the pair's local API runs here and passes " + + "on what the pair can't take, including requests from \(other); to this Mac those come from another " + + "machine, so they never use the paid network.") + let (follower, followerLines) = flow(config: url, keySaved: true, live: Self.keyed, pair: .follows(leader: other)) + #expect(follower.choose(.myMacsFirst) == 0) + #expect(followerLines.all.last == "In this pair, the leading Mac's route applies (\(other)): its route decides " + + "what the pair passes on, including requests from this Mac; to the leading Mac those come from another " + + "machine, so they never use the paid network. Run `\(Self.cli) route my-macs-first` there.") + } + + /// On the Mac that follows, a route refused for want of a key says first that the pair's route and key are the + /// leading Mac's, so no key is saved on the wrong Mac for the pair; a single Mac and the leading Mac say as before. + @Test func onTheMacThatFollowsTheNoKeyRefusalNamesTheLeadingMac() throws { + let url = try makeTempConfig() + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let before = try Data(contentsOf: url) + let leading = "the leading Mac (Apple M3 Ultra, 256 GB)" + let (follower, lines) = flow(config: url, keySaved: false, live: Self.keyed, pair: .follows(leader: leading)) + #expect(follower.choose(.myMacs) == 1) + #expect(try Data(contentsOf: url) == before) + #expect(lines.all == [ + "✗ Not saved: `\(Self.cli) route my-macs` passes your requests on with your account API key, and this Mac has " + + "none saved.", + "In this pair, the leading Mac's route and key apply (\(leading)): for the pair, run `\(Self.cli) route key` " + + "and `\(Self.cli) route my-macs` there.", + "For this Mac alone (`\(Self.cli) start --solo`), save one here from the Darkbloom console with " + + "`\(Self.cli) route key` (a self-route-only key is safest), then run `\(Self.cli) route my-macs` again.", + ]) + let saveHere = "Save one from the Darkbloom console with `\(Self.cli) route key` (a self-route-only key is safest), " + + "then run `\(Self.cli) route my-macs-first` again." + for pair in [RouteSaved.PairPart?.none, .leads(other: "the other Mac")] { + let (flow, lines) = flow(config: url, keySaved: false, live: Self.keyed, pair: pair) + #expect(flow.choose(.myMacsFirst) == 1) + #expect(lines.all.count == 2 && lines.all.last == saveHere, "\(String(describing: pair))") + } + } + + /// The pair's local API on the leading Mac without a local key (`cluster local --no-auth`) passes nothing on, so no + /// line says it does. + @Test func aLeadingMacWithoutALocalKeyNeverClaimsToPassRequestsOn() throws { + let url = try makeTempConfig() + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + var keyless = Self.keyed + keyless.apiKey = "" + let (leader, lines) = flow(config: url, keySaved: true, live: keyless, pair: .leads(other: "the other Mac")) + #expect(leader.choose(.myMacs) == 0) + #expect(try ConfigManager.load(from: url).local?.route == .myMacs) + #expect(lines.all.first == "✓ Saved.") + // That API is the pair's: it keeps every request on the pair, not on this Mac alone. + #expect(lines.all.last == "The local API running now has no local key (--no-auth): it keeps every request on " + + "this pair, whatever the route.") + #expect(!lines.text.contains("passes on")) + } + + @Test func aRefusedFileSaysWhyAndChangesNothing() throws { + let url = try makeTempConfig("[local]\nmode = \"elsewhere\"\n") + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let before = try Data(contentsOf: url) + let (flow, lines) = flow(config: url, keySaved: true) + #expect(flow.choose(.myMacs) == 1) + #expect(try Data(contentsOf: url) == before) + #expect(lines.all.first?.hasPrefix("✗ Not saved: ") == true) + #expect(lines.text.contains("[local] mode must be")) + } + + /// Every local API's router reads its route again from the provider.toml its start loaded: Only me's, Both's, the + /// pair's beside Darkbloom and `cluster local`'s. Each start passes that file to the function tested here, which + /// takes it as a `URL` (never optional), so a start that drops it doesn't build. + @Test func eachLocalAPIsRouterReadsTheConfigFileItCameFrom() throws { + let file = URL(fileURLWithPath: "/tmp/route-choice-wiring/provider.toml") + let config = ProviderConfig(provider: ProviderSettings(name: "wiring")) + let onlyMe = Start.onlyMeRouter(config: config, configFile: file, coordinatorURL: nil) + #expect(onlyMe.settingsFile == file) + #expect(!onlyMe.takesCoordinatorWork, "Only me never registers, so a `self` request can't come back to it") + let serving = StartServing(mode: .both, source: .saved, meFirst: true, meFirstIdleMinutes: 2, route: .myMacs, + accountKeySaved: true, port: 8001, bind: "127.0.0.1", noAuth: false) + let both = try #require(try Start.unifiedLocalEndpoint( + serving: serving, config: config, settingsFile: file, + coordinatorURL: "wss://coordinator.invalid/ws/provider", loadToken: { "dk-local-fixture" })) + #expect(both.router?.settingsFile == file) + let pair = Start.clusterMemberLocalEndpoint(requested: true, hostsPairSlot: true, bind: "0.0.0.0", port: 8001, + local: nil, settingsFile: file, coordinatorURL: nil, + loadToken: { "dk-local-fixture" }, say: { _ in }) + #expect(pair?.router?.settingsFile == file) + // `cluster local` loads `[local]` and the coordinator from that file itself, and has today's defaults without it. + let saved = try makeTempConfig( + "[local]\nroute = \"my-macs-first\"\n\n[coordinator]\nurl = \"wss://saved.invalid/ws/provider\"\n") + defer { try? FileManager.default.removeItem(at: saved.deletingLastPathComponent()) } + let clusterLocal = Start.clusterLocalRouter(configFile: saved, coordinatorURL: nil) + #expect(clusterLocal.settingsFile == saved && clusterLocal.settings.route == .myMacsFirst) + #expect(clusterLocal.upstreamBaseURL == URL(string: "https://saved.invalid")) + #expect(!clusterLocal.takesCoordinatorWork) + let fresh = Start.clusterLocalRouter(configFile: file, coordinatorURL: "wss://flag.invalid/ws/provider") + #expect(fresh.settingsFile == file && fresh.settings == LocalSettings()) + #expect(fresh.upstreamBaseURL == URL(string: "https://flag.invalid")) + } + + /// Each Mac's part comes from its pairing role: the leading Mac's lines name the other Mac, the other Mac's name the + /// leading one. A Mac in no pair, or whose pairing or role can't be read, has none. + @Test func eachMacsPartInAPairComesFromItsRole() { + let leading = ClusterPairSummary(paired: true, role: .leader, otherMacName: "Apple M3 Ultra, 256 GB") + #expect(RouteSaved.PairPart.of(leading) == .leads(other: leading.otherMac)) + let following = ClusterPairSummary(paired: true, role: .member, otherMacName: "Apple M5 Max, 128 GB") + #expect(RouteSaved.PairPart.of(following) == .follows(leader: following.otherMac)) + #expect(RouteSaved.PairPart.of(.notPaired) == nil) + #expect(RouteSaved.PairPart.of(ClusterPairSummary(paired: true, role: .leader, state: .pairingUnreadable)) == nil) + #expect(RouteSaved.PairPart.of(ClusterPairSummary(paired: true)) == nil) + } + + @Test func routeKeyNamesTheCommandThatChoosesYourMacs() { + let line = RouteKeyFlow.routeLines(savedRoute: .thisMac, keySaved: true).joined() + #expect(line.contains("`\(Self.cli) route my-macs`")) + } +} diff --git a/provider-swift/Tests/DarkbloomCLITests/RouteKeyCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/RouteKeyCommandTests.swift index 6668336490..6f500c6090 100644 --- a/provider-swift/Tests/DarkbloomCLITests/RouteKeyCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/RouteKeyCommandTests.swift @@ -13,10 +13,12 @@ import Testing struct RouteKeyCommandTests { static let key = "sk-synthetic-route-key-5e1d0c9b8a7f6e5d" + /// What a flow said, line by line; the other `route` suites use it too. final class Lines: @unchecked Sendable { private let lock = NSLock() private var stored: [String] = [] var all: [String] { lock.withLock { stored } } + var text: String { all.joined(separator: "\n") } func append(_ line: String) { lock.withLock { stored.append(line) } } } @@ -80,7 +82,8 @@ struct RouteKeyCommandTests { #expect(flow.remove() == 0) #expect(try store.load() == nil) #expect(lines.all == ["✓ Account key removed from this Mac's Keychain.", - "Your requests: this Mac only, until an account key is saved again."]) + "Your requests: this Mac only, until an account key is saved again.", + "It applies when your local API starts."]) } @Test func eachRouteIsSaidInPlainWordsWithoutSpeeds() { diff --git a/provider-swift/Tests/DarkbloomCLITests/RouteKeyLiveWordsTests.swift b/provider-swift/Tests/DarkbloomCLITests/RouteKeyLiveWordsTests.swift new file mode 100644 index 0000000000..8ba56eb880 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/RouteKeyLiveWordsTests.swift @@ -0,0 +1,156 @@ +import Foundation +import ProviderCore +import Testing + +@testable import darkbloom + +/// `darkbloom route key` (save and remove) counts on a running local API from its next request, with no restart, and +/// says so: "Your local API uses it now." or "It applies when your local API starts."; a key removed while the route +/// passes requests on says what the next request does. In a pair, it says whose key the pair's API uses. The key store +/// is in memory; no key is ever printed. +@Suite("route key: when the key counts") +struct RouteKeyLiveWordsTests { + typealias Lines = RouteKeyCommandTests.Lines + + static var cli: String { BuildEnvironment.current.cliName } + static let key = RouteKeyCommandTests.key + static let other = "the other Mac (Apple M3 Ultra, 256 GB)" + + private func flow(route: LocalSettings.Route?, running: Bool, pair: RouteSaved.PairPart? = nil, + saved: String? = nil, keyless: Bool = false) -> (RouteKeyFlow, Lines) { + let lines = Lines() + var flow = RouteKeyFlow(store: InMemoryLocalRouterAccountKeyStore(saved), savedRoute: route, + check: { _ in .accepted(models: 1) }, say: { lines.append($0) }) + flow.localAPIRunning = running && !keyless + flow.liveEndpointHasNoLocalKey = running && keyless + flow.pair = pair + return (flow, lines) + } + + @Test func aKeySavedWhileTheLocalAPIRunsIsUsedNow() async { + let (running, runningLines) = flow(route: .myMacs, running: true) + #expect(await running.save(Self.key) == 0) + #expect(runningLines.all.last == "Your local API uses it now.") + #expect(!runningLines.text.contains("restart") && !runningLines.text.contains(Self.key)) + + let (stopped, stoppedLines) = flow(route: .myMacs, running: false) + #expect(await stopped.save(Self.key) == 0) + #expect(stoppedLines.all.last == "It applies when your local API starts.") + } + + @Test func aKeyRemovedWhileTheRouteGoesOnKeepsTheNextRequestOnThisMac() { + let next = "Your local API uses it now. From its next request, one this Mac can't take gets this Mac's own " + + "answer instead of going to your other Macs" + for (route, tail) in [(LocalSettings.Route?.none, "."), (.myMacs, "."), (.myMacsFirst, " or the Darkbloom network.")] { + let (flow, lines) = flow(route: route, running: true, saved: Self.key) + #expect(flow.remove() == 0) + #expect(lines.all == ["✓ Account key removed from this Mac's Keychain.", + "Your requests: this Mac only, until an account key is saved again.", + next + tail], "\(String(describing: route))") + } + // `this-mac` never used the key: nothing changes for the next request. + let (pinned, pinnedLines) = flow(route: .thisMac, running: true, saved: Self.key) + #expect(pinned.remove() == 0) + #expect(pinnedLines.all.last == "Your local API uses it now.") + // No local API running: it applies at its start. + let (stopped, stoppedLines) = flow(route: .myMacsFirst, running: false, saved: Self.key) + #expect(stopped.remove() == 0) + #expect(stoppedLines.all.last == "It applies when your local API starts.") + } + + @Test func inAPairThePairsAPIUsesTheLeadingMacsKey() async { + let (follower, followerLines) = flow(route: .myMacs, running: true, pair: .follows(leader: Self.other)) + #expect(await follower.save(Self.key) == 0) + #expect(followerLines.all.suffix(2) == [ + "It applies when this Mac serves alone (`\(Self.cli) start --solo`).", + "In this pair, the pair's local API uses the leading Mac's key (\(Self.other)), not this one: run " + + "`\(Self.cli) route key` there.", + ]) + let (leader, leaderLines) = flow(route: .myMacs, running: true, pair: .leads(other: Self.other)) + #expect(await leader.save(Self.key) == 0) + #expect(leaderLines.all.suffix(2) == [ + "Your local API uses it now.", + "In this pair, the pair's local API runs on this Mac and passes requests on with this key.", + ]) + #expect(!(followerLines.text + leaderLines.text).contains(Self.key)) + // On the leading Mac your requests are the pair's; on the other Mac, this Mac's when it serves alone. + #expect(leaderLines.all.contains("Your requests: this pair first, then your other Macs (free).")) + #expect(followerLines.all.contains("Your requests: this Mac first, then your other Macs (free).")) + } + + /// `route key --remove`, in each role's true words: a single Mac's next request stays on it; the pair's local API on + /// the leading Mac passes nothing on until a key is saved there again; on the other Mac, the pair keeps using the + /// leading Mac's key. + @Test func aKeyRemovedSaysWhatChangesForEachRole() { + let (single, singleLines) = flow(route: .myMacs, running: true, saved: Self.key) + #expect(single.remove() == 0) + #expect(singleLines.all.last == "Your local API uses it now. From its next request, one this Mac can't take gets " + + "this Mac's own answer instead of going to your other Macs.") + + let (leader, leaderLines) = flow(route: .myMacsFirst, running: true, pair: .leads(other: Self.other), saved: Self.key) + #expect(leader.remove() == 0) + #expect(leaderLines.all.suffix(3) == [ + "Your requests: this pair only, until an account key is saved again.", + "Your local API uses it now. From its next request, one the pair can't take gets the pair's own answer " + + "instead of going to your other Macs or the Darkbloom network.", + "In this pair, the pair's local API runs on this Mac, so the pair passes nothing on until a key is saved " + + "here again.", + ]) + #expect(!leaderLines.text.contains("passes requests on with this key")) + + let (follower, followerLines) = flow(route: .myMacs, running: true, pair: .follows(leader: Self.other), + saved: Self.key) + #expect(follower.remove() == 0) + #expect(followerLines.all.suffix(2) == [ + "It applies when this Mac serves alone (`\(Self.cli) start --solo`).", + "In this pair, the pair's local API uses the leading Mac's key (\(Self.other)), not this one: to stop the " + + "pair passing requests on, run `\(Self.cli) route key --remove` there.", + ]) + } + + /// The leading Mac's key with a route that passes nothing on, or a pair API without a local key: no line says it + /// passes requests on. + @Test func theLeadingMacNeverClaimsToPassRequestsOnWhenItDoesnt() async { + let pinnedLine = "In this pair, the pair's local API runs on this Mac and uses this Mac's key once its route " + + "passes requests on." + let (pinned, pinnedLines) = flow(route: .thisMac, running: true, pair: .leads(other: Self.other)) + #expect(await pinned.save(Self.key) == 0) + #expect(pinnedLines.all.last == pinnedLine) + // Removed, there is no key to name: a route that passes requests on needs one saved again. + let (pinnedRemove, pinnedRemoveLines) = flow(route: .thisMac, running: true, pair: .leads(other: Self.other), + saved: Self.key) + #expect(pinnedRemove.remove() == 0) + #expect(pinnedRemoveLines.all.suffix(2) == [ + "Your local API uses it now.", + "In this pair, the pair's local API runs on this Mac: once its route passes requests on, it needs a key " + + "saved here again.", + ]) + let (keyless, keylessLines) = flow(route: .myMacs, running: true, pair: .leads(other: Self.other), keyless: true) + #expect(await keyless.save(Self.key) == 0) + #expect(keylessLines.all.last == "The running local API has no local key (--no-auth): it keeps every request on " + + "this pair and never uses the account key.") + #expect(!keylessLines.text.contains("passes requests on with this key")) + let (keylessRemove, keylessRemoveLines) = flow(route: .myMacs, running: true, pair: .leads(other: Self.other), + saved: Self.key, keyless: true) + #expect(keylessRemove.remove() == 0) + #expect(!keylessRemoveLines.text.contains("In this pair")) + } + + /// What `route key` reads of the local API running now: one with a local key uses the account key from its next + /// request; one without (`--no-auth`) never uses it; with none running, it counts at the next start. + @Test func theLocalAPIRunningNowIsReadAsKeyedOrKeyless() { + let keyed = LocalEndpoint.Info(host: "127.0.0.1", port: 8001, apiKey: "dk-local-fixture", version: "test", + pid: 4242, updatedAt: "now") + var keyless = keyed + keyless.apiKey = "" + let cases: [(name: String, live: LocalEndpoint.Info?, running: Bool, keyless: Bool)] = [ + ("keyed", keyed, true, false), ("--no-auth", keyless, false, true), ("none", nil, false, false), + ] + for (name, live, running, noKey) in cases { + var flow = RouteKeyFlow(store: InMemoryLocalRouterAccountKeyStore(), savedRoute: .myMacs, + check: { _ in .accepted(models: 1) }, say: { _ in }) + flow.seesLocalAPI(live) + #expect(flow.localAPIRunning == running && flow.liveEndpointHasNoLocalKey == noKey, "\(name)") + } + } +} diff --git a/provider-swift/Tests/DarkbloomCLITests/StartLocalFirstTests.swift b/provider-swift/Tests/DarkbloomCLITests/StartLocalFirstTests.swift index a0dd822b2c..01a1cfe791 100644 --- a/provider-swift/Tests/DarkbloomCLITests/StartLocalFirstTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/StartLocalFirstTests.swift @@ -246,6 +246,7 @@ struct StartLocalFirstTests { var tokenAsked = false let endpoint = try Start.unifiedLocalEndpoint( serving: serving, config: ProviderConfig(provider: ProviderSettings(name: "l4")), + settingsFile: URL(fileURLWithPath: "/tmp/start-local-first/provider.toml"), coordinatorURL: "wss://coordinator.invalid/ws/provider", loadToken: { tokenAsked = true; return "dk-local-fixture" }) #expect(endpoint == nil && !tokenAsked) @@ -422,7 +423,8 @@ struct StartLocalFirstTests { var served = ProviderConfig(provider: ProviderSettings(name: "l4")) served.local = config.local let endpoint = try #require(try Start.unifiedLocalEndpoint( - serving: serving, config: served, coordinatorURL: "wss://coordinator.invalid/ws/provider", + serving: serving, config: served, settingsFile: URL(fileURLWithPath: "/tmp/start-local-first/provider.toml"), + coordinatorURL: "wss://coordinator.invalid/ws/provider", loadToken: { Issue.record("--no-auth reads no token"); return "dk-local-fixture" })) #expect(endpoint.authToken == nil && endpoint.router?.settings.route == .myMacsFirst) #expect(serving.summaryLines.suffix(2) == [ diff --git a/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterLiveSettingsTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterLiveSettingsTests.swift new file mode 100644 index 0000000000..1c9aaec8db --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterLiveSettingsTests.swift @@ -0,0 +1,439 @@ +import Foundation +import HTTPTypes +import Hummingbird +import HummingbirdTesting +import NIOCore +import Testing +import notify +@testable import ProviderCore + +/// A running local API uses a saved route and account key from its next request: `darkbloom route ` and +/// `darkbloom route key` need no restart, so no model reloads for a routing change. The route is read again from the +/// provider config file when it changes; a file that doesn't read keeps the last good route and says so once. A +/// request this Mac serves never looks at the file. The races are pinned too: an edit while a request is passed on or +/// while the file is read, two quick edits, and an edit in place. Every test uses a temporary provider.toml, and the +/// router runs over a stub engine and coordinator; nothing leaves the process. +@Suite("Local router: saved route and key, live") +struct LocalRouterLiveSettingsTests { + /// A provider.toml in its own temporary folder, replaced as `setLocalSettings` replaces it (a new file each time). + final class ConfigFile: Sendable { + let folder: URL + let url: URL + + init(_ text: String) throws { + folder = FileManager.default.temporaryDirectory.appendingPathComponent("router-live-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + url = folder.appendingPathComponent("provider.toml") + try write(text) + } + + convenience init(route: LocalSettings.Route) throws { try self.init(Self.text(route)) } + + static func text(_ route: LocalSettings.Route) -> String { + "[provider]\nname = \"router-live\"\n\n[local]\nmode = \"both\"\nroute = \"\(route.rawValue)\"\n" + } + + func write(_ text: String) throws { try text.write(to: url, atomically: true, encoding: .utf8) } + func save(_ route: LocalSettings.Route) throws { try write(Self.text(route)) } + + /// Rewrites the file where it is, as an editor that saves in place does: the same inode. + func writeInPlace(_ text: String) throws { + let handle = try FileHandle(forWritingTo: url) + defer { try? handle.close() } + try handle.truncate(atOffset: 0) + try handle.write(contentsOf: Data(text.utf8)) + } + + /// What `stat` says of the file now. + var info: stat { + var info = stat() + _ = stat(url.path, &info) + return info + } + + /// Sets the file's modification time, to the nanosecond. + func setModified(_ time: timespec) throws { + var times = [time, time] + guard utimensat(AT_FDCWD, url.path, ×, 0) == 0 else { throw POSIXError(.EIO) } + } + + deinit { try? FileManager.default.removeItem(at: folder) } + } + + /// One chat for `model`; returns its status and the route the coordinator was asked with (nil: not passed on). + static func chat(_ client: some TestClientProtocol, _ model: String = "absent", upstream: RouterStubUpstream) + async throws -> (HTTPResponse.Status, String?) { + let before = upstream.posts.count + var status = HTTPResponse.Status.ok + try await client.execute(uri: "/v1/chat/completions", method: .post, headers: RouterFixture.authorized, + body: ByteBuffer(string: RouterFixture.chat(model))) { response in + status = response.status + } + return (status, upstream.posts.count > before ? upstream.posts.last?.route : nil) + } + + @Test func aSavedRouteIsUsedOnTheNextRequestWithNoRestart() async throws { + let file = try ConfigFile(route: .thisMac) + let fixture = RouterFixture(route: .thisMac, settingsFile: file.url) + try await fixture.app.test(.router) { client in + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.notFound, nil)) + try file.save(.myMacs) + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.ok, "self")) + try file.save(.myMacsFirst) + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.ok, "prefer")) + try file.save(.thisMac) + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.notFound, nil)) + } + #expect(fixture.log.lines.contains("route is now my-macs (provider.toml changed)")) + #expect(fixture.log.lines.contains("route is now my-macs-first (provider.toml changed)")) + #expect(fixture.log.lines.contains("route is now this-mac (provider.toml changed)")) + // One line per change: the first read finds the route the router started with, and says nothing. + #expect(fixture.log.lines.filter { $0.hasPrefix("route is now") }.count == 3, "\(fixture.log.lines)") + } + + @Test func theModelListFollowsTheSavedRouteToo() async throws { + let file = try ConfigFile(route: .myMacs) + let fixture = RouterFixture(route: .myMacs, settingsFile: file.url) { request in + request.method == "GET" && request.url.path == "/v1/models" && request.route == nil + ? .json(200, #"{"object":"list","data":[{"id":"big","owned_by":"darkbloom"}]}"#) + : .json(200, #"{"object":"list","data":[]}"#) + } + try await fixture.app.test(.router) { client in + #expect(try await !Self.networkListed(client)) + try file.save(.myMacsFirst) + #expect(try await Self.networkListed(client)) + } + } + + /// Whether the local `/v1/models` lists a network model. + static func networkListed(_ client: some TestClientProtocol) async throws -> Bool { + var listed = false + try await client.execute(uri: "/v1/models", method: .get, headers: RouterFixture.authorized) { response in + let list = try JSONDecoder().decode(LocalRouterModelList.self, from: Data(buffer: response.body)) + listed = list.data.contains { $0.ownedBy == "darkbloom" } + } + return listed + } + + /// The key was already read again after `route key`'s notification; with the route read from the file, a key saved + /// while the route is `my-macs` passes the next request on, and a key removed keeps the next one on this Mac. + @Test func aKeySavedOrRemovedWhileRunningCountsFromTheNextRequest() async throws { + let file = try ConfigFile(route: .myMacs) + let fixture = RouterFixture(route: .myMacs, settingsFile: file.url, key: nil) + let router = try #require(fixture.routerConfig) + let notification = try #require(router.keyChangeNotification) + try await fixture.app.test(.router) { client in + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.notFound, nil)) + try fixture.keys.save(RouterFixture.accountKey) + notify_post(notification) + #expect(await holdsWithinTwoSeconds { !router.keyCache.keepsACopy }) + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.ok, "self")) + try fixture.keys.remove() + notify_post(notification) + #expect(await holdsWithinTwoSeconds { !router.keyCache.keepsACopy }) + // This Mac's 404, served by this Mac, saying that your other Macs need a key (`LocalRouterMissingKeyTests`). + try await client.execute(uri: "/v1/chat/completions", method: .post, headers: RouterFixture.authorized, + body: ByteBuffer(string: RouterFixture.chat("absent"))) { response in + #expect(response.status == .notFound) + #expect(response.headers[LocalRouterPolicy.servedByHeader] == "this-mac") + #expect(String(buffer: response.body).contains("account_key_needed")) + } + } + #expect(fixture.upstream.posts.map(\.route) == ["self"]) + #expect(!fixture.log.lines.joined(separator: "\n").contains(RouterFixture.accountKey)) + } + + @Test func aMalformedEditKeepsTheLastGoodRouteAndSaysSoOnce() async throws { + let file = try ConfigFile(route: .myMacs) + let fixture = RouterFixture(route: .myMacs, settingsFile: file.url) + let kept = "provider.toml doesn't read as a provider config now; requests keep the route my-macs until it does" + try await fixture.app.test(.router) { client in + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.ok, "self")) + try file.write("[local]\nmode = \"both\"\nroute = \"everywhere\"\n") + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.ok, "self")) + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.ok, "self")) + try file.write("[local\nroute = ") + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.ok, "self")) + #expect(fixture.log.lines.filter { $0 == kept }.count == 1, "\(fixture.log.lines)") + try file.save(.myMacsFirst) + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.ok, "prefer")) + } + #expect(fixture.log.lines.contains("route is now my-macs-first (provider.toml changed)")) + #expect(!fixture.log.lines.joined(separator: "\n").contains("everywhere")) + } + + @Test func aRequestThisMacServesNeverLooksAtTheFile() async throws { + let file = try ConfigFile(route: .myMacs) + let fixture = RouterFixture(route: .myMacs, settingsFile: file.url) + let router = try #require(fixture.routerConfig) + try await fixture.app.test(.router) { client in + for _ in 0..<5 { #expect(try await Self.chat(client, "here", upstream: fixture.upstream) == (.ok, nil)) } + #expect(router.routeFile.checks == 0) + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.ok, "self")) + #expect(router.routeFile.checks == 1) + try await client.execute(uri: "/v1/models", method: .get, headers: RouterFixture.authorized) { response in + #expect(response.status == .ok) + } + #expect(router.routeFile.checks == 2) + } + } + + /// `--no-auth`: nothing is passed on, so neither a request nor a model list looks at the file. + @Test func withoutALocalKeyTheFileIsNeverLookedAt() async throws { + let file = try ConfigFile(route: .myMacsFirst) + let fixture = RouterFixture(route: .myMacsFirst, settingsFile: file.url, localKey: nil) + let router = try #require(fixture.routerConfig) + try await fixture.app.test(.router) { client in + #expect(try await Self.chat(client, upstream: fixture.upstream) == (.notFound, nil)) + try await client.execute(uri: "/v1/models", method: .get) { response in + #expect(response.status == .ok) + } + } + #expect(router.routeFile.checks == 0) + #expect(fixture.upstream.requests.isEmpty) + } + + /// An edit while a request is passed on counts from the next request: the one in flight keeps its route through + /// every hop (`prefer`, then `self` after the network's 402). + @Test func anEditWhileARequestIsPassedOnCountsFromTheNextOne() async throws { + let file = try ConfigFile(route: .myMacsFirst) + let fixture = RouterFixture(route: .myMacsFirst, settingsFile: file.url) { request in + guard request.method == "POST" else { return .json(200, #"{"object":"list","data":[]}"#) } + guard request.route == "prefer" else { + return .json(200, #"{"id":"chatcmpl-up","object":"chat.completion","choices":[]}"#) + } + try file.save(.thisMac) + return .json(402, #"{"error":{"type":"insufficient_funds","message":"no balance"}}"#) + } + try await fixture.app.test(.router) { client in + let passedOn = try await Self.chat(client, upstream: fixture.upstream) + #expect(passedOn == (.ok, "self")) + let next = try await Self.chat(client, upstream: fixture.upstream) + #expect(next == (.notFound, nil)) + } + #expect(fixture.upstream.posts.map(\.route) == ["prefer", "self"]) + #expect(fixture.log.lines.contains("route is now this-mac (provider.toml changed)")) + } + + /// A client on another machine never takes the paid network, whichever route the file comes to say. + @Test func aClientOnAnotherMachineStaysOffThePaidNetworkAfterAnEdit() async throws { + let file = try ConfigFile(route: .myMacs) + let fixture = RouterFixture(route: .myMacs, settingsFile: file.url) { request in + request.method == "GET" ? .json(200, #"{"object":"list","data":[]}"#) + : .json(200, #"{"id":"chatcmpl-up","object":"chat.completion","choices":[]}"#) + } + try file.save(.myMacsFirst) + for (peer, routeUsed) in [("192.168.1.20", "self"), ("2001:db8::20", "self"), ("127.0.0.1", "prefer")] { + let answer = try await LocalRouterRemoteClientTests.respond( + fixture, peer: peer, method: .post, path: "/v1/chat/completions", body: RouterFixture.chat("elsewhere")) + #expect(answer.status == .ok, "\(peer)") + #expect(answer.routeUsed == routeUsed, "\(peer)") + } + #expect(fixture.upstream.posts.map(\.route) == ["self", "self", "prefer"]) + } + + /// The file is read again only when it changed (one `stat` a call otherwise); a file that is gone keeps the last + /// good route and is said once; one that comes back is read again. + @Test func theFileIsReadAgainOnlyWhenItChanges() throws { + let file = try ConfigFile(route: .myMacs) + let routes = LocalRouterRouteFile() + let reads = RouterLogLines(), log = RouterLogLines() + func route() -> LocalSettings.Route? { + routes.route(in: file.url, startingWith: .thisMac, log: { log.append($0) }, read: { url in + reads.append(url.lastPathComponent) + return try Data(contentsOf: url) + }) + } + #expect(route() == .myMacs) + #expect(route() == .myMacs) + #expect(reads.lines.count == 1) + try file.save(.myMacsFirst) + #expect(route() == .myMacsFirst) + #expect(reads.lines.count == 2) + try FileManager.default.removeItem(at: file.url) + #expect(route() == .myMacsFirst) + #expect(route() == .myMacsFirst) + #expect(log.lines.filter { $0.hasPrefix("provider.toml doesn't read") }.count == 1) + try file.save(.thisMac) + #expect(route() == .thisMac) + #expect(routes.checks == 6) + #expect(reads.lines.count == 4) + } + + /// The `stat` comes before the read: an edit that lands while the file is read is read again by the next call. + @Test func anEditDuringTheReadIsReadByTheNextCall() throws { + let file = try ConfigFile(route: .myMacs) + let routes = LocalRouterRouteFile() + var editsDuringTheRead = 1 + func route() -> LocalSettings.Route? { + routes.route(in: file.url, startingWith: .thisMac, log: { _ in }, read: { url in + let bytes = try Data(contentsOf: url) + if editsDuringTheRead > 0 { + editsDuringTheRead -= 1 + try file.save(.myMacsFirst) + } + return bytes + }) + } + #expect(route() == .myMacs) + #expect(route() == .myMacsFirst) + #expect(route() == .myMacsFirst) + } + + /// Two edits between requests: the next one reads the file once, as the second left it. + @Test func twoQuickEditsAreReadOnceAsTheLastLeftIt() throws { + let file = try ConfigFile(route: .myMacs) + let routes = LocalRouterRouteFile() + let reads = RouterLogLines(), log = RouterLogLines() + func route() -> LocalSettings.Route? { + routes.route(in: file.url, startingWith: .myMacs, log: { log.append($0) }, read: { url in + reads.append(url.lastPathComponent) + return try Data(contentsOf: url) + }) + } + #expect(route() == .myMacs) + try file.save(.myMacsFirst) + try file.save(.thisMac) + #expect(route() == .thisMac) + #expect(reads.lines.count == 2) + #expect(log.lines == ["route is now this-mac (provider.toml changed)"]) + } + + /// An edit in place keeps the inode: its new size tells it apart, and at the same size its modification time does, + /// to the nanosecond. + @Test func anEditInPlaceIsReadToo() throws { + let file = try ConfigFile(route: .myMacs) + let routes = LocalRouterRouteFile() + func route() -> LocalSettings.Route? { routes.route(in: file.url, startingWith: .thisMac, log: { _ in }) } + let first = file.info + #expect(route() == .myMacs) + // Another size, with the first modification time put back: only the size differs. + try file.writeInPlace(ConfigFile.text(.myMacsFirst)) + try file.setModified(first.st_mtimespec) + #expect(file.info.st_size != first.st_size) + #expect(route() == .myMacsFirst) + // "my-macs" padded to the length of "my-macs-first", one nanosecond later: only the modification time differs. + let sameSize = ConfigFile.text(.myMacs).replacingOccurrences(of: "\"my-macs\"", with: "\"my-macs\" ") + try file.writeInPlace(sameSize) + var later = first.st_mtimespec + later.tv_nsec = (later.tv_nsec + 1) % 1_000_000_000 + try file.setModified(later) + #expect(file.info.st_size == ConfigFile.text(.myMacsFirst).utf8.count) + #expect(file.info.st_mtimespec.tv_sec == first.st_mtimespec.tv_sec) + #expect(route() == .myMacs) + #expect(file.info.st_ino == first.st_ino) + } + + /// Each run of bad reads is said once: after a good read, the next bad one is said again. + @Test func eachRunOfBadReadsIsSaidOnce() throws { + let file = try ConfigFile(route: .myMacs) + let routes = LocalRouterRouteFile() + let log = RouterLogLines() + func route() -> LocalSettings.Route? { + routes.route(in: file.url, startingWith: .myMacs, log: { log.append($0) }) + } + #expect(route() == .myMacs) + try file.write("[local\nroute = ") + #expect(route() == .myMacs) + try file.write("[local]\nroute = \"everywhere\"\n") + #expect(route() == .myMacs) + try file.save(.myMacsFirst) + #expect(route() == .myMacsFirst) + try file.write("[local\n") + #expect(route() == .myMacsFirst) + #expect(log.lines == [ + "provider.toml doesn't read as a provider config now; requests keep the route my-macs until it does", + "route is now my-macs-first (provider.toml changed)", + "provider.toml doesn't read as a provider config now; requests keep the route my-macs-first until it does", + ]) + } + + // MARK: - A save in place + + /// An editor that saves in place empties the file, then writes it. A request that finds it empty keeps the last good + /// route: with `this-mac` saved and a key, nothing is passed on (an empty file read as "no route" would mean + /// `my-macs`). Said once, and the whole file then reads as before, with no "route is now" line. + @Test func aFileFoundEmptyWhileItIsSavedInPlaceKeepsTheLastGoodRoute() async throws { + let file = try ConfigFile(route: .thisMac) + let fixture = RouterFixture(route: .thisMac, settingsFile: file.url) + try await fixture.app.test(.router) { client in + let before = try await Self.chat(client, upstream: fixture.upstream) + #expect(before == (.notFound, nil)) + try file.writeInPlace("") + let midSave = try await Self.chat(client, upstream: fixture.upstream) + #expect(midSave == (.notFound, nil)) + try file.writeInPlace(ConfigFile.text(.thisMac)) + let after = try await Self.chat(client, upstream: fixture.upstream) + #expect(after == (.notFound, nil)) + } + #expect(fixture.upstream.posts.count == 0) + #expect(fixture.log.lines == [ + "provider.toml doesn't read as a provider config now; requests keep the route this-mac until it does", + ]) + } + + /// A read that catches a save in place half done keeps the last good route: the `stat` saw the whole file, and the + /// read finds it emptied, or holding only its start (which parses, without `[local] route`). The next call reads + /// the file whole. + @Test func aReadThatCatchesASaveInPlaceHalfDoneKeepsTheLastGoodRoute() throws { + let whole = ConfigFile.text(.thisMac) + let start = try #require(whole.components(separatedBy: "route = ").first) + for midSave in ["", start] { + let file = try ConfigFile(whole) + let routes = LocalRouterRouteFile() + var pending: String? = midSave + func route() -> LocalSettings.Route? { + routes.route(in: file.url, startingWith: .thisMac, log: { _ in }, read: { url in + if let text = pending { + pending = nil + try file.writeInPlace(text) + } + return try Data(contentsOf: url) + }) + } + #expect(route() == .thisMac, "\(midSave.debugDescription)") + try file.writeInPlace(whole) + #expect(route() == .thisMac, "\(midSave.debugDescription)") + } + } + + /// `this-mac` saved in place over and over while requests this Mac can't take keep coming: not one is passed on. + @Test func aThisMacFileSavedInPlaceOverAndOverPassesNothingOn() async throws { + let file = try ConfigFile(route: .thisMac) + let fixture = RouterFixture(route: .thisMac, settingsFile: file.url) + let saving = SavingInPlace(file, text: ConfigFile.text(.thisMac)) + try await fixture.app.test(.router) { client in + for _ in 0..<2_000 { _ = try await Self.chat(client, upstream: fixture.upstream) } + } + let saves = await saving.stop() + let passedOn = fixture.upstream.posts.count + #expect(saves > 100, "the file was saved only \(saves) times") + #expect(passedOn == 0, "\(passedOn) of 2,000 requests were passed on") + #expect(!fixture.log.lines.contains { $0.hasPrefix("route is now") }, "\(Set(fixture.log.lines))") + } + + /// Saves `text` into `file` in place, over and over, from its own task until `stop()`, which returns how many times. + final class SavingInPlace: @unchecked Sendable { + private let lock = NSLock() + private var stopped = false + private var task: Task? + + init(_ file: ConfigFile, text: String) { + task = Task.detached { [self] in + var saves = 0 + while !isStopped { + try? file.writeInPlace(text) + saves += 1 + } + return saves + } + } + + private var isStopped: Bool { lock.withLock { stopped } } + + func stop() async -> Int { + lock.withLock { stopped = true } + return await task?.value ?? 0 + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterMissingKeyTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterMissingKeyTests.swift new file mode 100644 index 0000000000..23f6340883 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterMissingKeyTests.swift @@ -0,0 +1,134 @@ +import Foundation +import HTTPTypes +import Hummingbird +import HummingbirdTesting +import NIOCore +import Testing +import notify +@testable import ProviderCore + +/// A request this Mac can't take, with a route that would pass it on but no account key: the saved `my-macs` or +/// `my-macs-first` with none saved, or the route a key gave until `darkbloom route key --remove` removed it while the +/// local API ran. The answer keeps this Mac's status and says why, and the log says it once per run; neither holds a +/// key. Without a chosen route and without a key ever seen, the answer is this Mac's own, as before. The router runs +/// over the stub engine and coordinator; nothing leaves the process. +@Suite("Local router: a route that needs a key without one") +struct LocalRouterMissingKeyTests { + static var cli: String { BuildEnvironment.current.cliName } + + /// The error a client gets, as status, message and code. + struct Refusal: Equatable { + var status: HTTPResponse.Status + var message: String? + var code: String? + var servedBy: String? + } + + static func chat(_ client: some TestClientProtocol, _ model: String = "absent") async throws -> Refusal { + var refusal = Refusal(status: .ok) + try await client.execute(uri: "/v1/chat/completions", method: .post, headers: RouterFixture.authorized, + body: ByteBuffer(string: RouterFixture.chat(model))) { response in + let object = try? JSONSerialization.jsonObject(with: Data(buffer: response.body)) as? [String: Any] + let error = object?["error"] as? [String: Any] + refusal = Refusal(status: response.status, message: error?["message"] as? String, + code: error?["code"] as? String, + servedBy: response.headers[LocalRouterPolicy.servedByHeader]) + } + return refusal + } + + static func needsKey(_ status: HTTPResponse.Status, _ what: String, reach: String = "your other Macs") -> Refusal { + Refusal(status: status, message: "\(what), and reaching \(reach) needs an account key: run `\(cli) route key`.", + code: "account_key_needed", servedBy: "this-mac") + } + + static func loggedNeedsKey(_ fixture: RouterFixture) -> [String] { + fixture.log.lines.filter { $0.contains("needs an account key") } + } + + @Test func aSavedRouteWithoutAKeySaysSoOnTheAnswerAndOnceInTheLog() async throws { + let fixture = RouterFixture(route: .myMacs, key: nil) + try await fixture.app.test(.router) { client in + for _ in 0..<2 { + let absent = try await Self.chat(client) + #expect(absent == Self.needsKey(.notFound, "This Mac doesn't serve absent")) + } + let busy = try await Self.chat(client, "busy") + #expect(busy == Self.needsKey(.tooManyRequests, "This Mac can't take this request right now")) + let draining = try await Self.chat(client, "draining") + #expect(draining == Self.needsKey(.serviceUnavailable, "This Mac can't take this request right now")) + } + #expect(fixture.upstream.requests.isEmpty) + #expect(Self.loggedNeedsKey(fixture) == ["a request this Mac can't take stays on this Mac: reaching your other " + + "Macs needs an account key, and none is saved (`\(Self.cli) route key` saves one)"]) + } + + @Test func myMacsFirstNamesTheNetworkToo() async throws { + let fixture = RouterFixture(route: .myMacsFirst, key: nil) + try await fixture.app.test(.router) { client in + let absent = try await Self.chat(client) + #expect(absent == Self.needsKey(.notFound, "This Mac doesn't serve absent", + reach: "your other Macs or the Darkbloom network")) + } + #expect(Self.loggedNeedsKey(fixture).count == 1) + } + + /// A client on another machine never uses the paid network, so its answer names your other Macs only. + @Test func aClientOnAnotherMachineIsToldOfYourOtherMacsOnly() async throws { + let fixture = RouterFixture(route: .myMacsFirst, key: nil) + let answer = try await LocalRouterRemoteClientTests.respond( + fixture, peer: "192.168.1.20", method: .post, path: "/v1/chat/completions", body: RouterFixture.chat("absent")) + #expect(answer.status == .notFound) + #expect(answer.body.contains("This Mac doesn't serve absent, and reaching your other Macs needs an account key"), + "\(answer.body)") + #expect(!answer.body.contains("Darkbloom network")) + #expect(fixture.upstream.requests.isEmpty) + } + + /// The route was unset, so the key alone made requests go on to your other Macs; `route key --remove` while the API + /// runs keeps the next one here, and says why. A key saved again passes requests on, and a second removal is said + /// again. + @Test func aKeyRemovedWhileTheAPIRunsSaysWhyFromTheNextRequest() async throws { + let fixture = RouterFixture(route: nil, key: RouterFixture.accountKey) + let config = try #require(fixture.routerConfig) + let stays = Self.needsKey(.notFound, "This Mac doesn't serve absent") + try await fixture.app.test(.router) { client in + let before = try await Self.chat(client) + #expect(before.status == .ok) + try await Self.changeKey(to: nil, fixture: fixture, config: config) + let removed = try await Self.chat(client) + #expect(removed == stays) + try await Self.changeKey(to: RouterFixture.accountKey, fixture: fixture, config: config) + let savedAgain = try await Self.chat(client) + #expect(savedAgain.status == .ok) + try await Self.changeKey(to: nil, fixture: fixture, config: config) + let removedAgain = try await Self.chat(client) + #expect(removedAgain == stays) + } + #expect(fixture.upstream.posts.map(\.route) == ["self", "self"]) + #expect(Self.loggedNeedsKey(fixture).count == 2, "\(fixture.log.lines)") + #expect(!fixture.log.lines.joined(separator: "\n").contains(RouterFixture.accountKey)) + } + + /// Saves or removes the key as `route key` does, with its change notification, and waits until the router drops + /// its copy. + static func changeKey(to key: String?, fixture: RouterFixture, config: LocalRouterConfig) async throws { + if let key { try fixture.keys.save(key) } else { try fixture.keys.remove() } + notify_post(try #require(config.keyChangeNotification)) + #expect(await holdsWithinTwoSeconds { !config.keyCache.keepsACopy }) + } + + /// Nothing asked for your other Macs: no route chosen and no key seen while the API ran, or `this-mac`. The answer + /// is this Mac's own, and nothing is logged. + @Test func withoutARouteThatPassesRequestsOnTheAnswerIsThisMacsOwn() async throws { + for route in [LocalSettings.Route?.none, .thisMac] { + let fixture = RouterFixture(route: route, key: nil) + try await fixture.app.test(.router) { client in + let refusal = try await Self.chat(client) + #expect(refusal.status == .notFound) + #expect(refusal.code != "account_key_needed" && refusal.servedBy == "this-mac") + } + #expect(Self.loggedNeedsKey(fixture).isEmpty) + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterPairLeaderTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterPairLeaderTests.swift index 25d6d1b7b5..b208bf5fc9 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterPairLeaderTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterPairLeaderTests.swift @@ -20,7 +20,7 @@ struct LocalRouterPairLeaderTests { : .json(200, #"{"id":"chatcmpl-up","object":"chat.completion","choices":[]}"#) } let factory = RouterTransportFactory(upstream) - var router = LocalRouterConfig.pairLeaderOutsideDarkbloom(local: LocalSettings(route: .myMacs), + var router = LocalRouterConfig.pairLeaderOutsideDarkbloom(local: LocalSettings(route: .myMacs), settingsFile: nil, coordinatorURL: "ws://127.0.0.1:1/ws/provider") #expect(!router.takesCoordinatorWork) router.accountKeys = InMemoryLocalRouterAccountKeyStore(RouterFixture.accountKey) @@ -43,8 +43,12 @@ struct LocalRouterPairLeaderTests { /// The router's coordinator and `[local]` are the ones any host's has. @Test func itReadsLocalAndTheCoordinatorAsAnyHostsRouter() { let local = LocalSettings(route: .myMacsFirst) - let router = LocalRouterConfig.pairLeaderOutsideDarkbloom(local: local, coordinatorURL: "wss://coordinator.example/ws/provider") - let host = LocalRouterConfig.host(local: local, coordinatorURL: "wss://coordinator.example/ws/provider", takesCoordinatorWork: false) + let file = URL(fileURLWithPath: "/tmp/leader/provider.toml") + let router = LocalRouterConfig.pairLeaderOutsideDarkbloom(local: local, settingsFile: file, + coordinatorURL: "wss://coordinator.example/ws/provider") + let host = LocalRouterConfig.host(local: local, settingsFile: file, coordinatorURL: "wss://coordinator.example/ws/provider", + takesCoordinatorWork: false) #expect(router.settings == host.settings && router.upstreamBaseURL == host.upstreamBaseURL) + #expect(router.settingsFile == file && host.settingsFile == file) } } diff --git a/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterRemoteClientTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterRemoteClientTests.swift index e3850c376f..5be8d55987 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterRemoteClientTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterRemoteClientTests.swift @@ -72,7 +72,7 @@ struct LocalRouterRemoteClientTests { /// The local API's responder stack answering one request on a connection whose TCP peer is `peer`. static func respond(_ fixture: RouterFixture, peer: String, method: HTTPRequest.Method, path: String, - body: String?) async throws -> (status: HTTPResponse.Status, routeUsed: String?) { + body: String?) async throws -> (status: HTTPResponse.Status, routeUsed: String?, body: String) { let channel = NIOAsyncTestingChannel() channel.remoteAddress = try SocketAddress(ipAddress: peer, port: 50_123) let context = LocalDisconnectContext(source: ApplicationRequestContextSource( @@ -84,8 +84,9 @@ struct LocalRouterRemoteClientTests { headerFields: headers), body: .init(buffer: buffer)) let response = try await fixture.app.responder.respond(to: request, context: context) - try await response.body.write(RouterRecordingWriter()) + let writer = RouterRecordingWriter() + try await response.body.write(writer) try await channel.close() - return (response.status, response.headers[LocalRouterPolicy.routeUsedHeader]) + return (response.status, response.headers[LocalRouterPolicy.routeUsedHeader], writer.text) } } diff --git a/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterTestSupport.swift b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterTestSupport.swift index 1c977b1376..9babccf31f 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterTestSupport.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/LocalRouterTestSupport.swift @@ -198,10 +198,11 @@ struct RouterFixture { /// - Parameters: /// - route: `[local] route`; nil = absent. + /// - settingsFile: the provider.toml the router reads `[local] route` from again when it changes; nil = none. /// - key: the saved account key; nil = none. /// - router: false builds the endpoint without a router (today's endpoint). - init(route: LocalSettings.Route? = .myMacs, key: String? = RouterFixture.accountKey, router: Bool = true, - takesCoordinatorWork: Bool = false, localModels: [String] = RouterStubEngine.servedModels, + init(route: LocalSettings.Route? = .myMacs, settingsFile: URL? = nil, key: String? = RouterFixture.accountKey, + router: Bool = true, takesCoordinatorWork: Bool = false, localModels: [String] = RouterStubEngine.servedModels, localLimits: [String: LocalModelLimits] = [:], timing: LocalRouter.Timing = .init(), engineServes: Set = [], engineBusy: Set = [], localKey: String? = RouterFixture.localKey, upstream script: @escaping @Sendable (LocalRouterUpstreamRequest) throws -> RouterStubUpstream.Answer = { _ in @@ -216,7 +217,7 @@ struct RouterFixture { self.localLimits = localLimits let factory = factory, log = log var config = LocalRouterConfig( - settings: LocalSettings(route: route), upstreamBaseURL: Self.upstreamBase, + settings: LocalSettings(route: route), settingsFile: settingsFile, upstreamBaseURL: Self.upstreamBase, takesCoordinatorWork: takesCoordinatorWork, accountKeys: keys, makeTransport: { factory.make() }, log: { log.append($0) }, timing: timing) // A change notification of this fixture's own, never an install's `route key` one.