diff --git a/docs/specs/layerfs-postgresql-attach.md b/docs/specs/layerfs-postgresql-attach.md deleted file mode 100644 index 9475db8..0000000 --- a/docs/specs/layerfs-postgresql-attach.md +++ /dev/null @@ -1,264 +0,0 @@ -# LayerFS 2.0: attach PostgreSQL Stores to machines one by one - -Status: **implemented** (2026-11-12, owner approved) in the LayerFS worktree -`../layerfs-pg-attach`, uncommitted on top of `layerfs_v2_0_0`. §6 lists the -files as built; where they differ from the proposal below, §6 and the -"As built" notes win. - -As built: - -- `machine.remove` **refuses** (`InUse`, "Stores [..]") while a PostgreSQL - Store is attached to the machine, as it does for its sqlite Stores; it - does not drop attachments. `store detach` first. -- The privilege probe is one engine function, - `layerfs_persistence::postgresql_access` (server version, latency, role, - the privileges missing on the schema, its tables and sequences, and - `TEMP`); `layerfs-store`'s `postgresql/attach.rs` turns it into the check. -- `store connect` records `native`'s check only when it passes (a role that - may not write leaves native attached but unchecked). -- The store family has 12 calls (with `stats`), the table 68. - -**This reverses two owner decisions of #536 (2026-11-03):** - -| Decision | Today | Proposed | -| --- | --- | --- | -| C4 | "PostgreSQL Stores are usable from every machine automatically; there is no `store.attach`/`store.detach`." | A PostgreSQL Store is usable on the machines it is attached to. `store connect` attaches `native`; every other machine is attached by `store attach`. | -| H9 | "Per-machine PostgreSQL URL: deferred." | `store attach` takes an optional URL and password reference for that machine. | - -H1 stays: sqlite Stores keep `store push` / `store pull`. Attach is not a -placement: it copies nothing, a Store may be attached to many machines, and -it does not apply to sqlite Stores. - -## 1. Why - -- **Supported is not reached.** `supports.postgresql_sandbox` says a platform - can run a PostgreSQL Sandbox. It says nothing about whether this machine - reaches this server with these credentials. Today the first - `sandbox create` on a machine is the only check, and it needs a project, - so an empty Store cannot be checked anywhere but `native`. -- **One login for every machine.** Each machine's Sandbox daemons get the - host's URL and password. A VM can't get a role of its own with only the - rights it needs, and one machine can't be cut off without changing the - password for all of them. -- **One address for every machine.** The loopback rewrite (`reach`) covers a - server on this host. It does not cover a server that a VM or ssh host - sees at another address, or `sslmode=verify-full` with a certificate - name the rewrite would break (H9's case). -- **Clients can't show where a Store is usable.** `machine list` names only - sqlite Stores per machine, so a client has to assume every PostgreSQL - Store is on every capable machine. - -## 2. Model - -``` -store connect team --password the host's connection; makes the Store - └─ attaches native (checked by connect's own probe) -store attach team docker docker reuses the host's connection -store attach team dev --url --password dev has its own connection -store detach team dev -``` - -- `store connect` is unchanged in meaning: it records the Store's identity - (database, schema `layerfs`, binding) and the host's connection. Store - calls (project, branch, commit, fs, Init) keep running in the caller's - process with this connection. -- An **attachment** lets one machine run Sandboxes of the Store, with - either the Store's connection or its own. Either way it must reach the - database that holds the Store's binding; a machine's URL can never name - another Store. -- `attach` never creates a Store; the Store must be connected first. - -## 3. The record - -`store//record.json` of a PostgreSQL Store gains `machines`: - -```json -{ - "kind": "postgresql", - "url": "postgresql://lfs_host@db.lan:5432/team", - "password": "env:LAYERFS_PG_TEAM", - "schema": "layerfs", - "synchronous_commit": "off", - "binding": "…", - "machines": { - "native": { "checked": { "at": 1763000000000, "server_version": "17.2", "latency_ms": 3 } }, - "docker": { "checked": { "at": 1763000100000, "server_version": "17.2", "latency_ms": 5 } }, - "dev": { - "url": "postgresql://lfs_dev@10.0.0.5:5432/team?sslmode=verify-full", - "password": "file:/Users/me/.config/layerfs/dev.pw", - "checked": { "at": 1763000200000, "server_version": "17.2", "latency_ms": 9 } - } - } -} -``` - -- `url` and `password` per machine are optional; when absent the machine - uses the Store's. As for the Store, `url` holds no password and - `password` is a reference (`env:NAME` or `file:/path`). No secret is - written. -- `checked` is the last check that passed. A failed check writes nothing. -- **A record without `machines`** (written before this change) is read as - `{ "native": {} }`. 2.0 is unreleased, so there is no conversion; `native` - shows no `checked` until the next `attach native`. -- Every read and write goes through `StoreRecord` (`store/record.rs`), as - for every other field; `StoreRef::Postgres` gains the parsed attachments. - -## 4. Calls - -The `store` family goes from 9 calls to 11 (`api/crates/layerfs-api/src/store/mod.rs`). - -| Call | Arguments | Options | What it does | -| --- | --- | --- | --- | -| ★ `store.attach` | `name`, `machine` | `url`, `password` | attaches a PostgreSQL Store to a machine after checking it from that machine; again on an attached machine, re-checks and replaces its connection | -| ★ `store.detach` | `name`, `machine` | — | detaches it; its data and other machines are untouched | - -``` -layerfs store attach [--url ] [--password ] - let a machine run Sandboxes of a PostgreSQL Store, after checking it reaches the server -layerfs store detach - stop a machine running Sandboxes of a PostgreSQL Store -``` - -The result of both is the Store's `store.get` view, with `machines`. - -### 4.1 `store.attach` - -Every refusal of its input comes before any effect, as in `store.connect`. - -1. `name` must be a Store: else `NotFound`. A sqlite Store is - `InvalidInput`: "Store X is a sqlite Store; `store push X M` places it". -2. `machine` must exist (`NotFound`) and its platform must allow - PostgreSQL Sandboxes on this host (`layerfs_machine::sandbox_allowed`): - else `Unsupported` with the support table's reason, word for word. -3. `url`, when given, is refused as `store.connect` refuses one - (`refuse_password`, `target`): `InvalidInput`. -4. The password (the given reference, else the Store's) must resolve in - this process (`common::secrets::resolve`): else its refusal. -5. The URL the machine dials is built as `sandbox/route.rs` `reached()` - builds it today: the given URL else the Store's, with its password, - through `layerfs_machine::reach` (loopback rewritten, ssh loopback - refused, `verify-full` with a rewrite refused). -6. **The check**, on the side that runs the machine's calls - (`common::place::on_machine`): - - `Executor::Local`: in this process. - - `Executor::Worker`: a new worker op `store.reach` (§5). A machine with - no recorded worker is refused `Unavailable`, naming - `layerfs machine start M` (`Worker::ready`). Nothing is started. - - The check opens one connection and runs, read-only: - - `read_binding` (`store/postgres.rs`). It must equal the record's - `binding`: else `Unavailable` "the PostgreSQL server M reaches at - holds another Store than X" (today's `reach_check` wording). - - `has_schema_privilege(current_user, 'layerfs', 'USAGE')` and, for - every table in schema `layerfs`, `has_table_privilege` for `SELECT`, - `INSERT`, `UPDATE` and `DELETE` (a Sandbox commits, and a write - takes `store_lane` with `UPDATE`). Any missing: `Denied`, naming - the role and the first missing privilege. - - `server_version` and the connection's latency. - - A failure names the machine and the host it tried, never the URL; the - apple-container hint of `reach_check` is added as today. -7. Under the Store's entity lock (`store::record::lock`), re-read the - record. If the Store's binding changed or the Store is gone, - `Conflict`. Then write `machines.` = `{ url?, password?, - checked }`. - -Attaching `native` with no options is how a caller re-checks `native`. - -### 4.2 `store.detach` - -1. `name` must be a PostgreSQL Store (`NotFound`, `InvalidInput` as above). -2. `machine` must be attached: else `InvalidInput` "Store X is not - attached to machine M". -3. `InUse` while a Sandbox record of a project of this Store names the - machine, with `detail.related` naming each, as `store.disconnect` does. -4. Remove `machines.` under the Store's lock. Detaching `native` - is allowed: Store calls still run on the host with the Store's - connection; only Sandboxes on `native` are refused. - -LayerFS never creates or drops PostgreSQL roles; it has no admin -credentials. Revoking a machine's role is the operator's step. - -### 4.3 Changes to existing calls - -| Call | Change | -| --- | --- | -| `store.connect` | writes `machines: { native: { checked } }` from the probe it already makes. That probe runs in the caller's process, which is `native`'s network. | -| `sandbox.create` | for a PostgreSQL Store, after the machine is chosen (none named: `native`, unchanged) and under the home lock that claims the name: refused `Unsupported` unless the machine is attached, "PostgreSQL Store X is not attached to machine M; `layerfs store attach X M`". The reach check on create stays, as the last guard. | -| every Sandbox host op (`sandbox/route.rs` `reached()`) | uses the machine's attachment `url`/`password` when set, else the Store's; the rest unchanged | -| `store.get`, `store.list` | the record view shows `machines` (references only, as it shows `url` and `password` today) | -| `machine.list`, `machine.get` | each machine gains `postgresql`: the names of the PostgreSQL Stores attached to it, sorted. `stores` keeps its meaning (sqlite Stores on its disk), so no caller of `stores` changes. | -| `machine.remove` | drops the machine from every PostgreSQL Store's `machines`, each under its Store's lock, after its existing refusals (its Sandboxes) pass | -| `store.disconnect` | unchanged; the attachments go with the record | -| `store.status` | unchanged (the host's server check). Per-machine state is the record's `checked`. | - -`machine.list`'s new field is computed in `inventory.rs` beside `stores_on` -(a `postgresql_on(home, machine)` that reads each PostgreSQL record's -`machines`). - -## 5. The worker op `store.reach` - -`machine/worker/server.rs` `run()` gains: - -``` -"store.reach" => args { postgresql: , binding: } - -> { server_version, latency_ms } | refusal -``` - -The caller resolves the password and rewrites the URL; the selection -travels only in this request, as for every Sandbox call today. The worker -reads no home. A worker from a bundle without the op answers an unknown op; -`attach` maps that to `Unsupported` "machine M's worker predates -store.attach; `layerfs machine stop M` and `machine start M` update it". - -## 6. Files - -| File | Change | -| --- | --- | -| `api/crates/layerfs-api/src/store/attach.rs`, `detach.rs` | new table entries (`a("name", Name), a("machine", Name)`; `opt("url", Text), opt("password", Text)`) | -| `api/crates/layerfs-api/src/store/mod.rs` | 12 calls; help order puts `attach`, `detach` after `connect` | -| `engine/crates/layerfs-persistence/src/backend/postgresql/access.rs` | new: the read-only privilege probe (`postgresql_access`) | -| `control/crates/layerfs-store/src/postgresql/attach.rs` | new: `check`, `record` (under the home and Store locks, `Conflict` if the binding changed), `detach` | -| `control/crates/layerfs-store/src/record.rs` | `Attachment`, `attachments()` (absent `machines` = native), `with_attachment`, `without_attachment`, `url_on` | -| `control/crates/layerfs-store/src/postgresql/connect.rs` | attaches `native` on connect; `refuse_password`, `target` public | -| `control/crates/layerfs-sandbox/src/route.rs` | `reached(home, machine, record)` dials the attachment's connection | -| `control/crates/layerfs-sandbox/src/create.rs` | the attachment refusal | -| `control/crates/layerfs-control/src/store.rs` | `attach` (local or `worker.attempt("store.reach")`), `reach_in_worker`, `detach` | -| `control/crates/layerfs-control/src/worker_server.rs` | the `store.reach` op | -| `control/crates/layerfs-control/src/inventory.rs` | `postgresql_on`, `store_idle_on`; `can_remove_machine` counts attached Stores | -| `control/crates/layerfs-machine/src/{related,record,list}.rs` | `postgresql` per machine | -| `docs/versioned/2.0.0/calls.md`, `machines-and-stores.md`; `docs/architecture/api/sdk/store/{README,attach,detach,connect}.md`, `machine/{list,get,remove}.md`, call-table `table.md`, `coverage.md` | the calls | -| `core/docs/issues/536/DECISIONS.md`, `README.md`; `control/AGENTS.md` | C4 superseded, H9 taken up (owner, 2026-11-12); the G3 rule replaced | -| `api/node/src/index.d.ts`, `api/python/src/layerfs/_client.pyi`, `aio.pyi` | regenerated | - -The CLI, Node and Python faces have no per-call code for `store.connect` -(`layerfs-cli`, `layerfs-node`, `layerfs-python` don't name it), so they -follow from the call table. Regenerate whatever type files the build emits. - -## 7. Tests - -- `store.attach` refusals in order, each before any effect: no Store, - a sqlite Store, no machine, a platform the table refuses, a URL with a - password, an unresolved reference, a stopped worker machine. -- The check: another database (binding mismatch → `Unavailable`), a role - without `INSERT` on one table (`Denied`), a good role (`checked` - written), re-attach replacing the connection, a failed re-attach - keeping the old one. -- `sandbox.create` on an unattached machine refused before the name is - claimed; on an attached one with its own URL, the daemon dials that URL - (the receipt names the host). -- `store.detach` `InUse` with a Sandbox recorded, then allowed after - `sandbox close`. -- `machine.list` `postgresql`; `machine.remove` refused while attached. -- A record without `machines` reads as `native` only. -- Per platform, beside `tests/sandbox_machines.rs` - (`a_sandbox_runs_where_its_store_can_be_reached`): attach and a Sandbox - on `native`, `docker`, `lima`, with the Store's connection and with one - of the machine's own. - -## 8. Not in this change - -- Creating PostgreSQL roles or grants. -- Changing `store push` / `store pull` (H1). -- A per-machine `synchronous_commit` (it stays the Store's). -- Backups of PostgreSQL Stores (still `InvalidInput`). diff --git a/docs/specs/layerfs-postgresql-connection.md b/docs/specs/layerfs-postgresql-connection.md new file mode 100644 index 0000000..2e85629 --- /dev/null +++ b/docs/specs/layerfs-postgresql-connection.md @@ -0,0 +1,43 @@ +# PostgreSQL Stores: the LayerFS calls the plugin builds on + +Status: **current** (2026-11-17). Replaces `layerfs-postgresql-attach.md`: +`store.attach` and `store.detach` are gone. This page records the contract +the plugin is written against; LayerFS's own documentation is the source of +truth for the calls. + +## The model + +A PostgreSQL Store is a database on a server. It is on **no machine**. Its +record holds one connection: a URL (no password), a password reference and +`synchronous_commit`. Any machine whose platform runs PostgreSQL Sandboxes +(`machine.supports.postgresql_sandbox`) reaches the Store with that +connection; nothing is attached first. `sandbox.create` of a PostgreSQL +project works on any such machine. + +A machine can have a connection **of its own** (another address, another +password) when the Store's does not work from it. That is the exception, and +the only thing LayerFS records per machine. + +## Calls + +| Call | What the plugin uses | +| --- | --- | +| `store.connect --password [--synchronous-commit]` | Connects the database as a Store. The result has no `machines`. | +| `store.update [--url] [--password ] [--synchronous-commit]` | Edits the Store's own connection. Answers the Store as `store.get` does. | +| `store.update --machine [--url] [--password ]` | Sets that machine's own connection. LayerFS checks it from the machine before it saves anything. Refusals: `Unavailable`, `Denied`, `Unsupported`. A long call. | +| `store.update --machine --clear` | Removes that machine's own connection. | +| `store.status ` | `server`: the host's own reach of the server. | +| `store.status --machine ` | Adds `check`: `{ machine, host, ok: true, at, server_version, latency_ms }` or `{ machine, host, ok: false, error: { code, message } }`. A bad input (no such machine, a SQLite Store, a platform that runs none) is a refusal. | +| `store.get` / `store.list` | `machines` only names machines with their own connection: `{ "": { url?, password? } }`. No `checked`. | +| `store.disconnect ` | Forgets the Store. The database stays. | +| `machine.list` / `machine.get` | No `postgresql` field. `machine.remove` no longer refuses for PostgreSQL Stores. | +| `sandbox.create` | A machine that cannot reach the server refuses `Unavailable`: "machine cannot reach PostgreSQL Store 's server at : ...". | + +A password is always a reference (`env:NAME` or `file:/path`). LayerFS keeps +no password in a URL and refuses one. + +## What LayerFS does not record + +Which machine a Store's sessions run on. That is the plugin's own choice +(see [postgresql-stores-ui.md](postgresql-stores-ui.md) §2); LayerFS takes a +machine per `sandbox.create`. diff --git a/docs/specs/layerfs-workspaces.md b/docs/specs/layerfs-workspaces.md index 9851903..5770cca 100644 --- a/docs/specs/layerfs-workspaces.md +++ b/docs/specs/layerfs-workspaces.md @@ -15,12 +15,14 @@ no per-project page. on native; `store push` / `store pull` move it (both machines running; the whole Store moves, every project in it; refused while one of its projects has a Sandbox). -- A **PostgreSQL Store** is on no machine. `store connect` attaches native; - `store attach` / `detach` add or remove machines (detach is refused while a - Sandbox runs there). Attachments belong to the Store, not one project. +- A **PostgreSQL Store** is on no machine. `store connect` records one + connection, and any machine that runs PostgreSQL Sandboxes reaches it; + nothing is attached. The plugin keeps one machine per Store, where its + sessions run (postgresql-stores-ui.md §2). It belongs to the Store, not one + project. - A **project** is `/`. Its sessions run on its SQLite Store's - machine, or on one machine its PostgreSQL Store is attached to (the host - picks: native when attached, else the first checked, else the first). + machine, or on the machine its PostgreSQL Store runs on (the saved choice, + else docker, else native). - `project init` never creates a Store. The UI creates SQLite projects on native and then pushes the Store, the order the presets use. @@ -66,10 +68,10 @@ the pane. Opened from the picker, the head has a **‹ Projects** link back to i ` · N projects` or ` · N projects`); the kind icon is on the card only, not repeated on rows. - **Runs on**: machine tiles with the machine's mark (Docker whale, Apple for - native, Lima…), name, state and a badge (Default, Here now). SQLite picks one - (radio); PostgreSQL ticks any (checkbox). **Default: docker** when it can run - the kind, else native. Machines that can't run the kind are not offered. A - stopped one is offered with a line saying Create starts it. **New machine** + native, Lima…), name, state and a badge (Default, Here now). Both kinds pick one + (radio). **Default: docker** when it can run the kind, else native. Machines + that can't run the kind are not offered. A stopped one is offered with a + line saying Create starts it. **New machine** closes the dialog and opens Resources with Add machine open (`openStorage(api, 'machines:new')`). Moving an existing SQLite Store warns that its other projects move too. @@ -80,10 +82,10 @@ the pane. Opened from the picker, the head has a **‹ Projects** link back to i the storage job) when not native → open a session. - SQLite, existing Store: start its machine if stopped → Init → start the target and place when it differs → open. - - PostgreSQL, new connection: `POST /api/stores/postgresql` → Init → start - and attach each ticked machine other than native → detach native when - unticked → open. Existing connection: Init → attach ticked machines not yet - attached → open. + - PostgreSQL, new connection: `POST /api/stores/postgresql` (with the + machine picked, `runsOn`) → Init → start the machine if stopped → open. + Existing connection: Init → `POST /api/stores//runs-on` when another + machine is picked → start it if stopped → open. Nothing is attached. On success the dialog closes and the new session is on screen. @@ -96,9 +98,9 @@ the pane. Opened from the picker, the head has a **‹ Projects** link back to i - **SQLite Runs on**: the tiles, the current one marked Here now. Choosing another shows the move warning and **Move to ** in the footer, which starts both machines if needed and places the Store. -- **PostgreSQL Runs on**: a tile per machine, ticked when attached; ticking - attaches (starting a stopped machine first), unticking detaches. Applies to - every project in the Store. +- **PostgreSQL Runs on**: the tiles, the current one marked Here now. Choosing + another shows **Run on ** in the footer, which saves the choice + (`POST /api/stores//runs-on`). Applies to every project in the Store. - Footer: **Hide from sidebar** (per browser, until the project's next session) and Done. A project whose Store is gone says so and offers Open Resources. @@ -146,7 +148,7 @@ decides when a hidden project shows again. ## 8. Readiness A project's machine for readiness is its SQLite Store's machine, or for -PostgreSQL the machine the host would pick from its attachments (§1), read +PostgreSQL the machine its Store runs on (§1; the Store row's `runsOn`), read from `/api/storage`. Readiness shows as words, never a light. ## 9. Not in scope diff --git a/docs/specs/postgresql-stores-ui.md b/docs/specs/postgresql-stores-ui.md index f1f55e2..1adb435 100644 --- a/docs/specs/postgresql-stores-ui.md +++ b/docs/specs/postgresql-stores-ui.md @@ -1,282 +1,153 @@ # PostgreSQL Stores in dsh-layerfs -Status: **implemented** (2026-11-12) except where "As built" says -otherwise. Attach and Detach need `store.attach` / `store.detach` from -[layerfs-postgresql-attach.md](layerfs-postgresql-attach.md) in the pinned -CLI; the host detects them from the CLI's call table -(`StorageView.features.attach`). +Status: **implemented** (2026-11-17), built against the calls in +[layerfs-postgresql-connection.md](layerfs-postgresql-connection.md). Not +yet verified against a live runtime: the pinned CLI must be one with +`store.update` and `store.status --machine`. -As built: +## 1. The model the UI shows -- Password files are `/pg---.pw` (the Store's; `` - is config `secrets` / `DSH_LAYERFS_SECRETS`, default `/secrets`) - and `pg-----.pw` (a machine's own), a new file per - write so a refused call never breaks the file an earlier call recorded; - a passing attach removes that machine's older files, detach removes them - all, disconnect removes the Store's. -- The view's attachment carries the machine's own `url` and `password` - reference (never a secret) and `saved` when the reference names a file the - host wrote. Refused attaches to machines not attached are - `attachRefusals` on the Store row. -- Without `store.attach` in the CLI, the Store shows one unchecked - attachment, the LayerFS Home, and the Attach controls are hidden (sessions - run on native, as before). -- The Store page's Machines table has no Sandboxes column; LayerFS's - `InUse` on Detach names the Sandboxes. -- Not built yet: the New Session / `NewProjectForm` machine choice (§7); - sessions take the default machine (`pgMachineOf`: the session's own, - else native, else the first checked, else the first attached). -- `environment-reset.js` (copied from Connect) still leaves `pg-*.pw` files. - -## 1. What changes for the user - -Today a PostgreSQL Store can only be added from the Storage panel's -"+ New Store" dialog. It then appears as a pretend machine named -"PostgreSQL" under Machines, and the Machines page lists it on every -machine that supports PostgreSQL Sandboxes. Sessions of its projects -always run on `native`. - -After this change: - -- PostgreSQL gets its own group in the Storage sidebar, next to Backups, - with a "Connect a database" row. A database is an outside server, like - a bucket, not a machine. -- Each machine shows the PostgreSQL Stores **attached** to it, beside its - sqlite Stores. -- A Store's page lists its machines, each with its connection and its last - check, and attaches more. -- A project session in a PostgreSQL Store runs on a machine the Store is - attached to. - -## 2. Sidebar - -> **Superseded (2026-11-13):** the Storage page no longer has a resources -> sidebar. Pages open under a navigation bar (`storage/Nav.tsx`): Back and -> Forward, a breadcrumb from Resources down with a switcher of sibling pages, -> Jump to (⌘K / Ctrl+K) over every machine, Store, project, Sandbox and -> bucket, the running transfers, Refresh and Add (New project, New Store, -> Connect a database, New machine, Add bucket). Attaching a PostgreSQL Store -> to a machine goes through its Store page's Attach (§4, §5) instead of a -> drag. The rest of this section records the tree as it was. - -``` -Overview -MACHINES - LayerFS Home - demo-studio 18.9 MB - ⛁ team ↗ ● attached, checked - docker - ⛁ team ↗ ○ attached, not checked yet - demo-build - demo-build-cache 14.7 MB -POSTGRESQL + - ⛁ team db.lan:5432 - api - load -BACKUPS + - + Connect a bucket -``` - -With no PostgreSQL Stores the group shows one dim row, "+ Connect a -database", as Backups shows "+ Connect a bucket". +A PostgreSQL Store is a database on a server, connected once. It is on no +machine. Two things can be said about it and a machine: -| Row | Behaviour | -| --- | --- | -| `POSTGRESQL` group | always shown; its `+` opens the Connect dialog (§3); collapsed, it carries the worst signal of its Stores | -| a PostgreSQL Store | the PostgreSQL glyph; meta is the server (`user@host:port/db` without the user when narrow); expands to its projects; opens the Store page; dot: the host's `store.status` server check | -| an attachment, under a machine | the PostgreSQL glyph with a small link mark, never expandable (the projects are under the Store); opens the Store page at its Machines section; dot: `checked` and the latest refusal (§4) | -| drag a PostgreSQL Store onto a machine | opens the Attach dialog with that machine chosen (§5). It is not instant: the machine may need its own connection. Only machines that can take it accept the drop: platform supports PostgreSQL Sandboxes, not already attached, not stopped. Others show why on hover. | - -The pretend "PostgreSQL" machine row (`g:postgresql` under `g:machines` in -`Explorer.tsx`) goes; its key moves to the top level. - -Search matches a PostgreSQL Store by name, project and server, and shows -its attachments under the machines that matched. +- **Runs on**: the one machine its sessions start on. A choice, changed any + time, with no call to LayerFS. +- **Own connection**: an address or password one machine uses instead of the + Store's. Offered only when a check from that machine fails. -## 3. Connect a database - -Opened from the group's `+`, the "Connect a database" row, or "+ New Store" -with PostgreSQL chosen (the existing tile choice in `dialogs.tsx` stays). - -| Field | Rules | -| --- | --- | -| Name | as today (`NAME`, not taken) | -| Database URL | `postgresql://user@host:5432/db`; a password in it is refused in the dialog with "Give the password below" before LayerFS refuses it | -| Password | a segmented choice, as buckets' keys: **Enter password**, which the host writes to an owner-only file `/secrets/pg-.pw` and passes as `file:`, or **Reference** (`env:NAME` / `file:/path`) | -| `synchronous_commit` | under "Advanced", default `off` | +There is no Attach, no Detach, no "attached" mark and no per-machine check +state. A check is run when asked for and shown once; nothing keeps it. -Action: **Connect**. On success the dialog closes and opens the Store's -page with a notice: "Connected and attached to the LayerFS Home. Attach it -to other machines to run Sandboxes there." +## 2. Where a Store runs -Refusals in the dialog: `Exists` (name taken, or the same database under -another Store's name, which LayerFS names), `Denied` (login), `Unavailable` -(not reached; LayerFS names the host). +The plugin keeps the choice in `/store-machines.json` +(`src/host/store-machines.ts`), one machine name per Store, read on every +use. LayerFS records none. -An `env:` reference resolves in the 3080 server's environment, not the -browser's. The hint says so, and "Enter password" is the default. +`pgMachineOf(saved, machines, preferred)`: -## 4. The Store page (PostgreSQL) +1. `preferred`: the session's own machine, or one named in the request; +2. else the saved choice, while that machine exists and runs PostgreSQL + Sandboxes; +3. else `docker`, when it exists and runs them; +4. else `native`. -Sections, top to bottom: +A default (3, 4) is not written down. Connect saves the machine picked in +the dialog; `POST /api/stores/:s/runs-on` saves a change; Disconnect drops +the entry. A stopped machine can be chosen. Saving a choice starts nothing; +a session starts no machine either, so a stopped one must be started (Create +does it, §6). -1. **Pane bar**: name, server, state chip; actions: Doctor's "Test - connection" (exists), and a menu with Disconnect. -2. **Machines** (new): +Sessions (`sessions/service.ts machineFor`), `POST /api/projects/:p/sandboxes` +and the presets all use it. A preset names one machine per PostgreSQL Store +and hands it to the plugin (`PresetSpec.runsOn`); its script holds no +attach command. - | Machine | Connection | Check | Sandboxes | | - | --- | --- | --- | --- | --- | - | LayerFS Home | Same as the host | ● 17.2 · 3 ms · 2 min ago | 1 | Re-check · Edit · Detach | - | docker | Same as the host | ○ Not checked | 0 | Re-check · Edit · Detach | - | dev | Own: `lfs_dev@10.0.0.5:5432/team` | ✕ Unavailable: dev cannot reach 10.0.0.5 | 0 | … | +## 3. Host routes - - **Re-check** runs `store attach` with the same settings. - - **Edit** opens the Attach dialog filled in. - - **Detach** asks for confirmation. It is disabled with "Close its - Sandboxes first" while Sandboxes of the Store run there (LayerFS's - `InUse` names them). - - A failed check is shown only in the browser session that ran it, with - LayerFS's message: LayerFS writes only passing checks. It is kept in - the host's view state until the next check of that machine passes. - - The section's button **Attach to a machine…** opens §5. -3. **Projects**: unchanged. -4. **Facts**: server, version, reachable from the host, latency, - `synchronous_commit`. - -Backups stay hidden for PostgreSQL Stores (LayerFS refuses them). - -## 5. Attach dialog - -| Field | Rules | +| Route | Does | | --- | --- | -| Machine | a picker of every machine. Disabled with the reason: already attached, platform doesn't support PostgreSQL Sandboxes (`supports.reason`), stopped ("Start it on Machines first", with a link). | -| Connection | **Same as the host** (default) or **Own connection** | -| Same as the host | a note of what the machine dials: "localhost becomes host.docker.internal on docker", from LayerFS's per-platform table (`stores.md`, "Sandboxes and reach"). For ssh with a localhost server, "Use an own connection: an ssh machine cannot reach this host's localhost". | -| Own connection | Database URL and Password, as in §3. An entered password goes to `/secrets/pg--.pw`. | - -Action: **Attach and check**, then "Checking from docker…" while it runs. -On success the row appears with its check. On failure the dialog stays -open with LayerFS's refusal (`Unavailable` naming the host tried, `Denied` -naming the missing privilege, `Unsupported` naming a worker to restart), so -the user can change the connection and retry. - -## 6. Machines panel - -The machine page's Stores tab (`machines/Stores.tsx`) lists the PostgreSQL -Stores **attached** to the machine, from `machine.list`'s new `postgresql` -field, each with its check. It no longer lists every PostgreSQL Store on -every capable machine. A button **Attach a PostgreSQL Store…** opens §5 -with the machine fixed and a Store picker. - -## 7. Sessions and projects - -- `SessionService.machineFor` (`src/host/sessions/service.ts`) and the - other hard-coded `'native'` for PostgreSQL projects (`service.ts` at the - binding and placement sites, `projects/availability.ts`, - `routes/projects.ts` `createSandbox`): a PostgreSQL project's machine is - the session binding's `machine` when it is attached. Otherwise it is - `native` when attached, then the first attached machine whose check - passed. If none is attached, the session can't run and says "Attach team - to a machine". -- The New Session project control and `NewProjectForm`: for a PostgreSQL - project attached to more than one machine, a machine choice, defaulting - as above. A sqlite project keeps its Store's machine. -- `createSandbox` refuses an unattached machine itself (`Unsupported`, - LayerFS's wording) so the panel's error comes before a LayerFS call. -- A session's machine never changes after its first turn, as its project - doesn't (`project-sessions.md` §1). - -## 8. Host - -### Routes (`src/host/routes/router.ts`) - -| Route | Calls | -| --- | --- | -| `POST /api/stores/postgresql` `{ name, url, password? \| passwordValue?, synchronousCommit? }` | `store.connect`; `passwordValue` is written to `/secrets/pg-.pw` (0600) and passed as `file:` | -| `POST /api/stores/:name/attach` `{ machine, url?, password? \| passwordValue? }` | `store.attach`; `passwordValue` → `/secrets/pg--.pw` | -| `POST /api/stores/:name/detach` `{ machine }` | `store.detach`; removes that machine's password file, if the host wrote one | -| `POST /api/stores/:name/disconnect` | unchanged, and removes the Store's password files | - -A password value is never logged, never put in a job record or an event, -and never sent back. The host writes the file first, calls LayerFS, and -removes the file again if the call refuses. - -### View (`src/host/routes/storage.ts`, `machines.ts`) - -- `storeRow` gains `attachments: [{ machine, own: boolean, target - (user@host:port/db, from the attachment's url), checked: { at, version, - latencyMs } | null, lastError: { code, message, at } | null }]` from the - record's `machines`. `lastError` is the host's memory of the last failed - `attach` from this server. -- `machineOf` reads `postgresql`. `pgStoreOf` stays for the per-machine - lists. -- **Feature detection**: attach is on when the pinned CLI's call table has - `store.attach` (`discover()` identity / `layerfs help store`). Without - it (Phase 1), attachments are derived as today, "every machine whose - platform supports it", marked "not checked", and the Attach and Detach - controls are hidden. - -### Presets - -`environment-reset.js` still disconnects PostgreSQL Stores; it also removes -`/secrets/pg-*.pw`. - -## 9. Phases - -**Phase 1, now (no LayerFS change):** -- The POSTGRESQL group, the "Connect a database" row and dialog, entered - passwords written to owner-only files. -- The Store page's Machines section, read-only: every capable machine, "not - checked". -- Sessions keep running PostgreSQL projects on `native`. - -**Phase 2, after LayerFS ships attach and the pinned CLI is bumped -(`DSH_LAYERFS_CLI`/`DSH_LAYERFS_DAEMON`):** -- Attach and Detach, attachment rows under machines, drag to attach. -- The Machines tab from `machine.list` `postgresql`. -- Machine choice for PostgreSQL sessions. - -## 10. Copy (en; zh alongside in `storage/locale.ts` and `machines/locale.ts`) - -| Key | en | -| --- | --- | -| `groupPostgresql` | PostgreSQL | -| `connectDatabaseRow` | Connect a database | -| `connectDatabase` | Connect a database | -| `pgPasswordHow` | Password | -| `pgPasswordEntered` | Enter password | -| `pgPasswordReference` | Reference | -| `pgPasswordInUrl` | Give the password below, not in the URL. | -| `pgEnvHint` | An env: reference is read from the LayerFS server's environment. | -| `connectedAttached` | Connected and attached to the LayerFS Home. Attach it to other machines to run Sandboxes there. | -| `machinesSection` | Machines | -| `attachToMachine` | Attach to a machine… | -| `attachAndCheck` | Attach and check | -| `checkingFrom` | Checking from {machine}… | -| `sameAsHost` | Same as the host | -| `ownConnection` | Own connection | -| `notChecked` | Not checked | -| `recheck` | Re-check | -| `detach` | Detach | -| `detachTitle` | Detach {store} from {machine}? | -| `detachBody` | Sandboxes of its projects can no longer run on {machine}. Its data stays on the server. | -| `closeSandboxesFirst` | Close its Sandboxes on {machine} first. | -| `notAttachedAnywhere` | Attach {store} to a machine to run its projects. | -| `loopbackNote` | localhost becomes {alias} on {machine}. | - -## 11. Tests +| `POST /api/stores/postgresql` | `store.connect`. Body: `name`, `url`, `password` \| `passwordValue` \| `passwordFrom`, `synchronousCommit?`, `runsOn?`. | +| `POST /api/stores/:s/connection` | `store.update`. Body: `machine?`, `url?`, `password?` \| `passwordValue?`, `synchronousCommit?`, `clear?`. Without `machine` the Store's own connection; with one, that machine's; `clear` removes it. Nothing to change is refused 400. | +| `GET /api/stores/:s/check?machine=` | `store.status --machine`. Answers `{ machine, host, ok: true, at, version, latencyMs }` or `{ machine, host, ok: false, error }`. A failed check is an answer (200), not a refusal. | +| `POST /api/stores/:s/runs-on` | Body: `machine`. Saves the choice. Refused for a SQLite Store, an unknown machine, or one that runs no PostgreSQL Sandboxes. | +| `POST /api/stores/:s/disconnect` | `store.disconnect`; removes the Store's password files and its saved machine. | + +`GET /api/storage` gives each PostgreSQL Store row: + +- `postgresql`: `target`, `url`, `server`, `database`, `user`, the host's own + check (`reachable`, `version`, `latencyMs`, `error`), `password` (the + reference, or null with `saved: true` when it names a file the host + wrote) and `synchronousCommit`; +- `runsOn`: §2's answer; +- `ownConnections`: `[{ machine, url, target, password, saved }]`, only the + machines with a connection of their own. + +`GET /api/machines` gives each PostgreSQL Store its `runsOn`; a machine row +has no `postgresql` list. + +Password files: `/pg---.pw` (the Store's) and +`pg-----.pw` (a machine's own), mode 0600, a new file +per write so a refused call never breaks the file an earlier call recorded. +A passing update removes the older files of that connection, `clear` removes +that machine's, Disconnect removes them all. A typed password never reaches +a view, an event or a log. + +## 4. Stores tab (Home and a machine page) + +The PostgreSQL tile has one view. There is no Servers / Databases switch and +no server card. + +```text +localhost:5432 ● Reachable · 2 ms layerfs · PG 17 + Add database +┌───────────────────────┐ ┌───────────────────────┐ +│ demo-services ⋯ │ │ demo-experiments ⋯ │ +│ 48 MB demo_services │ │ 12 MB demo_exp… │ +│ Runs on [docker] Change│ │ Runs on [native] Change│ +│ api 31 MB ▆▆▆ │ │ trials 12 MB ▆▆▆ │ +│ worker 17 MB ▆▆ │ │ │ +└───────────────────────┘ └───────────────────────┘ +``` -- `test/routes.test.mjs`: connect with an entered password writes a 0600 - file and passes `file:`, and removes it on refusal; attach and detach - routes; disconnect removes the files; no password in any answer or - event; the Phase 1 fallback when the CLI has no `store.attach`. -- Storage model: tree grouping (POSTGRESQL group; attachments under - machines; search). -- `test/sessions.test.mjs`: a PostgreSQL project's machine from the - binding, the defaults of §7, and none attached. -- End to end on a side server with a disposable PostgreSQL - (`docker run postgres`, a role per machine): connect, attach `docker` - with the host's connection, attach with an own role, a role without - `INSERT` refused `Denied`, a Sandbox on the attached machine, detach - `InUse` then allowed. Clean up with `tools/cleanup-dev.mjs` and drop - the container. +- One thin header per server: address, the host's check (reachable and + latency, said once for all its databases), user, version, **Add + database** (Connect a database with that host and user filled in and its + password reused). +- One card per database: name, size, the database, **Runs on** with + **Change**, its projects. +- A card says its own status only when it is not its server's: this + database fails while the server answers. No "Home reaches it" footer. +- Card menu: **Edit connection**, **Check from a machine…**, **Disconnect**. +- **Connect a database** is the tile's button, top right. + +A machine page lists the Stores that run on it, and those with a Sandbox on +it now. Its **Connect a database** opens the same dialog with new databases +set to run there. + +## 5. Dialogs + +**Connect a database** (`storage/ConnectDatabase.tsx`) is the one connect +dialog; New Store's and Add Store's PostgreSQL tiles open it. + +1. *Pick*: connected Stores under their server, each with where it runs and + **Check** (on a machine page, **Run here** for one that runs elsewhere); + "New database on this server"; "New server". +2. *New*: database, Store name, host, user and password for a new server + (a pasted URL fills them), **Runs on**, synchronous_commit under More + options. Connect, then the check from that machine. +3. *Check*: the path the machine dials and three steps (reaches the server, + finds the Store, may write it), from `GET …/check`. "Check from" picks + another machine. Only after a failure at the server, and never for the + LayerFS Home, the machine can be given **its own address** + (`POST …/connection` with `machine`), then it is checked again. + +**Edit connection** (`pg-edit`): the Store's URL, password and +synchronous_commit; or one machine's own URL and password. Only what changed +is sent. + +**Where it runs** (`pg-runs-on`): one machine, picked from those that run +PostgreSQL Sandboxes. + +## 6. Other pages + +- **Store page**: the third tab is **Connection**: the connection (URL, + password reference, synchronous_commit, the host's check) with Edit and + Check from a machine; where it runs, with Change; then one row per machine + with its own connection (Check, Edit, Remove own connection). The + Overview's fourth tile is Runs on. +- **Project dialog**: both Store kinds pick one machine. Create connects a + new PostgreSQL Store with it (`connect`), or changes an existing Store's + (`runs-on:`), then starts that machine if it is stopped; nothing is + attached. Configure + changes where the Store runs. +- **Health**: per PostgreSQL Store, "server reachable" (the host's check) + and the doctor's connection check. No per-machine item. +- **Presets**: the Studio preset's PostgreSQL Stores name one machine each. + +## 7. Not built + +- A check runs only when asked for; the Overview does not show that a + machine cannot reach a Store until a session or a check finds out. +- synchronous_commit cannot be set back to "database default" from Edit + connection (`store.update` has no way to clear it). +- `environment-reset.js` (copied from Connect) still leaves `pg-*.pw` files. diff --git a/src/client/doctor/Health.tsx b/src/client/doctor/Health.tsx index d70189f..9737262 100644 --- a/src/client/doctor/Health.tsx +++ b/src/client/doctor/Health.tsx @@ -9,8 +9,8 @@ * host, machine, Sandbox its diagnosis * Store integrity; a PostgreSQL Store adds its doctor * connection check, whether the host reaches it - * now (`GET /api/storage`'s live probe) and each - * attached machine's last check; a backed-up Store + * now (`GET /api/storage`'s live probe); a + * backed-up Store * shows each bucket's connection * bucket its connection * @@ -33,7 +33,7 @@ import { useQuery, type Query } from '../files/use-query.ts' import { useMachinesContext } from '../machines/context.tsx' import type { StorageT } from '../storage/locale.ts' import { useHostEvents } from '../storage/hooks.ts' -import type { DoctorReport, PgAttachment, StorageView, StoreRow } from '../storage/types.ts' +import type { DoctorReport, StorageView, StoreRow } from '../storage/types.ts' import { MachinesGlyph, SandboxesGlyph, StoreGlyph } from '../machines/icons.tsx' import { BucketGlyph } from '../storage/parts.tsx' import { CopyLine } from '../ui/index.tsx' @@ -111,23 +111,6 @@ function liveItem(s: StoreRow, t: DoctorT): Item | null { return { key: `${s.name}:live`, label: t('healthItemReachable'), live, ...!pg.reachable ? { problem: { message: pg.error ?? t('healthLiveUnreachable'), fix: null } } : {} } } -/** One machine's last check of a PostgreSQL Store it is attached to. */ -function attachItem(s: StoreRow, a: PgAttachment, t: DoctorT, place: (m: string) => string): Item { - const checked = a.checked?.at ?? null - const failed = a.lastError && (checked === null || (a.lastError.at ?? 0) >= checked) - const live: Cell = failed - ? { state: 'error', words: t('healthAttachFailed'), job: null, at: a.lastError!.at, title: a.lastError!.message } - : a.checked - ? { state: 'done', words: a.checked.latencyMs != null ? msWords(a.checked.latencyMs, t) : t('healthCellOk'), job: null, at: checked, title: a.checked.version ?? undefined } - : { state: 'idle', words: t('healthCellNone'), job: null } - return { - key: `${s.name}:attach:${a.machine}`, - label: t('healthItemAttached', { machine: place(a.machine) }), - live, - ...failed ? { problem: { message: `${place(a.machine)}: ${a.lastError!.message}`, fix: t('healthAttachFix') } } : {}, - } -} - interface MachineRow { name: string, platform: string } function useMachineRows(): { machines: MachineRow[], sandboxes: { name: string, machine: string | null }[] } { @@ -169,7 +152,6 @@ function rowsOf(t: DoctorT, home: string, machines: ReturnType attachItem(s, a, t, place)), { key: `${s.name}:integrity`, label: t('healthItemIntegrity'), probe: { target: 'store.integrity', name: s.name } }, ...[...new Set(s.links.map((l) => l.bucket))].map((bucket) => ({ key: `${s.name}:backup:${bucket}`, label: t('healthItemBackup', { bucket }), probe: { target: 'backup.connection' as const, name: bucket }, mirror: true })), ] diff --git a/src/client/doctor/locale.ts b/src/client/doctor/locale.ts index 753e7fe..558adff 100644 --- a/src/client/doctor/locale.ts +++ b/src/client/doctor/locale.ts @@ -52,13 +52,10 @@ const en = { healthItemIntegrity: 'Integrity', healthItemBackup: 'Backup · {bucket}', healthItemReachable: 'Reachable now', - healthItemAttached: 'Attached · {machine}', healthLiveReachable: 'Reachable', healthLiveReachableMs: '{ms} ms', healthLiveFast: '<1 ms', healthLiveUnreachable: 'Unreachable', - healthAttachFailed: 'Failed', - healthAttachFix: 'Re-check the attachment from the Store page in Home.', healthSubHost: 'This host and its LayerFS home', healthSubMachine: '{platform} machine', healthSubSandbox: 'Sandbox on {machine}', @@ -251,13 +248,10 @@ const zh: typeof en = { healthItemIntegrity: '完整性', healthItemBackup: '备份 · {bucket}', healthItemReachable: '当前可达', - healthItemAttached: '已连接 · {machine}', healthLiveReachable: '可达', healthLiveReachableMs: '{ms} ms', healthLiveFast: '<1 ms', healthLiveUnreachable: '不可达', - healthAttachFailed: '失败', - healthAttachFix: '在“主页”中的 Store 页面重新检查该连接。', healthSubHost: '本主机及其 LayerFS 主目录', healthSubMachine: '{platform} 机器', healthSubSandbox: '{machine} 上的 Sandbox', diff --git a/src/client/hero/HeroProject.tsx b/src/client/hero/HeroProject.tsx index e86b208..1fab4b0 100644 --- a/src/client/hero/HeroProject.tsx +++ b/src/client/hero/HeroProject.tsx @@ -95,7 +95,7 @@ export function HeroProject({ sessionId, api, t, imports }: HeroProjectProps): R const loadProjects = () => { setLoadError(false) listProjects(api).then(({ rows: list, scratchKey: key }) => { setRows(list); setScratchKey(key) }, () => setLoadError(true)) - // Where each project runs (its SQLite Store's machine, or its PostgreSQL Store's attached machines). + // Where each project runs (its SQLite Store's machine, or the machine its PostgreSQL Store's sessions run on). api.call('GET', '/api/storage').then(setStorage, () => {}) } useEffect(loadProjects, [api]) diff --git a/src/client/machines/Board.tsx b/src/client/machines/Board.tsx index 9253042..ced222a 100644 --- a/src/client/machines/Board.tsx +++ b/src/client/machines/Board.tsx @@ -31,7 +31,7 @@ import css from './machines.module.css' /** * `onAddStore`: Storage's Add Store dialog for a machine (move a SQLite Store - * there, or attach a PostgreSQL one); `storeMenu`: a Store row's menu for a + * there, or connect a PostgreSQL one); `storeMenu`: a Store row's menu for a * machine (Storage's Store actions). Without them the Stores column has * neither. */ diff --git a/src/client/machines/Inventory.tsx b/src/client/machines/Inventory.tsx index 4f02a05..97a8c51 100644 --- a/src/client/machines/Inventory.tsx +++ b/src/client/machines/Inventory.tsx @@ -40,12 +40,12 @@ export function sandboxNeedsYou(b: MachineSandbox): boolean { return !!look.attention || look.tone === 'danger' } -/** One Store row: what the machine's Sandboxes can use, sqlite on its disk or PostgreSQL attached to it. */ +/** One Store row: what the machine's Sandboxes can use, sqlite on its disk, or PostgreSQL that runs its Sandboxes here. */ interface StoreLine { name: string, family: 'sqlite' | 'postgresql', projects: string[], count: number, size: number | null, state?: string | undefined, op?: MachineSandbox['op'] } export function storeLines(view: AvailableView, m: MachineInfo): StoreLine[] { const sqlite = storesOn(view, m).map((s): StoreLine => ({ name: s.name, family: 'sqlite', projects: s.names ?? [], count: s.projects, size: s.size, state: s.state, op: s.op ?? null })) - const pg = pgUsable(m, view.postgresql ?? []).map((s): StoreLine => ({ name: s.name, family: 'postgresql', projects: s.names ?? [], count: s.projects, size: null, state: s.state, op: s.op ?? null })) + const pg = pgUsable(view, m).map((s): StoreLine => ({ name: s.name, family: 'postgresql', projects: s.names ?? [], count: s.projects, size: null, state: s.state, op: s.op ?? null })) return [...sqlite, ...pg] } diff --git a/src/client/machines/locale.ts b/src/client/machines/locale.ts index 5546569..54c8a9f 100644 --- a/src/client/machines/locale.ts +++ b/src/client/machines/locale.ts @@ -497,9 +497,6 @@ const en = { pgNote: 'PostgreSQL Stores: {note}', storeSqliteOn: 'SQLite · on {machine}', storePgReached: 'PostgreSQL · reached by Sandboxes here', - storePgAttached: 'PostgreSQL · attached, checked from here', - storePgAttachedUnchecked: 'PostgreSQL · attached, not checked yet', - pgAttachOnStorage: 'attach more on Storage, from a Store’s Machines section', sandboxesOn: 'Sandboxes on {machine}', projectsUnnamedOne: '1 project; name not reported', projectsUnnamed: '{n} projects; names not reported', @@ -1580,9 +1577,6 @@ const zh: typeof en = { pgNote: 'PostgreSQL Store:{note}', storeSqliteOn: 'SQLite · 位于 {machine}', storePgReached: 'PostgreSQL · 可由这里的 Sandbox 访问', - storePgAttached: 'PostgreSQL · 已挂接,已从此处检查', - storePgAttachedUnchecked: 'PostgreSQL · 已挂接,尚未检查', - pgAttachOnStorage: '可在“存储”中 Store 的“机器”部分挂接更多', sandboxesOn: '{machine} 上的 Sandbox', projectsUnnamedOne: '1 个项目;未报告名称', projectsUnnamed: '{n} 个项目;未报告名称', diff --git a/src/client/machines/model.ts b/src/client/machines/model.ts index 3d10a45..5a514a8 100644 --- a/src/client/machines/model.ts +++ b/src/client/machines/model.ts @@ -88,8 +88,6 @@ export interface MachineInfo { memory: number | null disk: number | null stores: string[] - /** The PostgreSQL Stores attached to it (store.attach); absent from a CLI before attachments. */ - postgresql?: string[] sandboxes: string[] image?: string docker?: string @@ -110,8 +108,8 @@ export interface MachineStore { /** A PostgreSQL Store: on no machine; Sandboxes on a machine that supports it reach its database. */ export interface MachinePgStore { - /** The machines it is attached to, each checked or not; null from a CLI before attachments. */ - machines?: { machine: string, checked: boolean }[] | null + /** The machine its sessions run on by default (this DSH install's own choice); absent from an older host half. */ + runsOn?: string | null state?: string op?: SdkOperation | null name: string @@ -897,10 +895,14 @@ export function shortSandbox(name: string): string { return /^dsh-[0-9a-f]{12,}$/.test(name) ? name.slice(4, 11) : name } -/** The PostgreSQL Stores a machine's Sandboxes use: those attached to it, else (an older CLI) every one it can reach. */ -export function pgUsable(m: MachineInfo, postgresql: MachinePgStore[]): MachinePgStore[] { - if (m.postgresql) return postgresql.filter((s) => m.postgresql!.includes(s.name)) - return m.supports?.postgresql_sandbox ? postgresql : [] +/** + * The PostgreSQL Stores a machine shows: those whose sessions run on it by + * default, and those with a Sandbox on it now. A PostgreSQL Store is on no + * machine, so every other one is left to Storage. + */ +export function pgUsable(view: Pick, m: Pick): MachinePgStore[] { + const here = new Set(view.sandboxes.filter((b) => b.machine === m.name && b.project).map((b) => b.project!.split('/')[0])) + return (view.postgresql ?? []).filter((s) => s.runsOn === m.name || here.has(s.name)) } // ---------- the Sandbox page ---------- diff --git a/src/client/picker/location.ts b/src/client/picker/location.ts index 9cf2bdf..63e2168 100644 --- a/src/client/picker/location.ts +++ b/src/client/picker/location.ts @@ -19,14 +19,6 @@ export function slugify(text: string): string { return text.trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, '-').replace(/^[^a-z0-9]+/, '').slice(0, 63).replace(/[^a-z0-9]+$/, '') } -/** The machine a PostgreSQL Store's sessions use when none is asked for (host `pgMachineOf`). */ -export function defaultPgMachine(attachments: readonly { machine: string, checked?: unknown }[] | null | undefined): string { - if (!attachments) return 'native' - const names = attachments.map((a) => a.machine) - if (names.includes('native')) return 'native' - return attachments.find((a) => a.checked)?.machine ?? names[0] ?? 'native' -} - /** * The Stores of a `/api/storage` view a project can be made in from this host: * SQLite Stores on native, then PostgreSQL Stores; never the Scratch Store. @@ -37,7 +29,7 @@ export function locationsOf(view: any, scratchStore?: string | null): Location[] const sqlite = usable.filter((s) => (s.kind ?? 'sqlite') !== 'postgresql' && (s.machine ?? 'native') === 'native') .map((s): Location => ({ store: String(s.name), kind: 'sqlite', server: null, runsOn: null })) const pg = usable.filter((s) => s.kind === 'postgresql') - .map((s): Location => ({ store: String(s.name), kind: 'postgresql', server: s.postgresql?.target ?? null, runsOn: defaultPgMachine(s.attachments) })) + .map((s): Location => ({ store: String(s.name), kind: 'postgresql', server: s.postgresql?.target ?? null, runsOn: typeof s.runsOn === 'string' && s.runsOn ? s.runsOn : 'native' })) return [...sqlite, ...pg] } diff --git a/src/client/presets/Topology.tsx b/src/client/presets/Topology.tsx index 232ae7d..d9ffd56 100644 --- a/src/client/presets/Topology.tsx +++ b/src/client/presets/Topology.tsx @@ -122,10 +122,7 @@ export function PresetTopology({ preset, t, onCommands }: { preset: DemoPreset, {machineLabel(machine)} {machineSub(machine)} - {stores.map((g) => [ - t(g.kind === 'postgresql' ? 'pgStoreLabel' : 'storeLabel', { store: g.store }), - ...(g.attach?.length ? [t('pgAlsoAttached', { machines: g.attach.map(machineLabel).join(', ') })] : []), - ].join(' · ')).join(' · ')} + {stores.map((g) => t(g.kind === 'postgresql' ? 'pgStoreLabel' : 'storeLabel', { store: g.store })).join(' · ')}
    {stores.flatMap((g) => g.projects.map((p) => ( diff --git a/src/client/presets/locale.ts b/src/client/presets/locale.ts index b5922ad..fe8fbe3 100644 --- a/src/client/presets/locale.ts +++ b/src/client/presets/locale.ts @@ -183,7 +183,6 @@ const en = { projectLine: '{commits} commits · {branches} side branches', storeLabel: 'store {store}', pgStoreLabel: 'PostgreSQL store {store}', - pgAlsoAttached: 'also attached to {machines}', opBuilding: 'Building', opStopping: 'Stopping machines', opLastBuild: 'Last build', @@ -382,7 +381,6 @@ const zh: typeof en = { projectLine: '{commits} 个提交 · {branches} 个侧分支', storeLabel: 'Store {store}', pgStoreLabel: 'PostgreSQL Store {store}', - pgAlsoAttached: '也挂载到 {machines}', opBuilding: '正在构建', opStopping: '正在停止机器', opLastBuild: '上次构建', diff --git a/src/client/projects/setup/MachineTiles.tsx b/src/client/projects/setup/MachineTiles.tsx index 3fa3559..fa8b37f 100644 --- a/src/client/projects/setup/MachineTiles.tsx +++ b/src/client/projects/setup/MachineTiles.tsx @@ -1,7 +1,8 @@ /** * Machines as tiles, shared by the project dialog and Storage's New Store: * one tile per machine (its mark, name, state, a badge), and the Location - * picker a SQLite Store is placed with. `native` is shown as the LayerFS Home. + * picker: where a SQLite Store is placed, or where a PostgreSQL Store's + * sessions run. `native` is shown as the LayerFS Home. * A machine whose platform is not ready here (`blocks`, model.ts tileBlocks) * shows so and cannot be picked, except a docker machine whose Docker Engine * its Start launches (Create starts it). @@ -101,9 +102,9 @@ export function MachineTile({ m, label, selected, multi, note, badge, onSelect, } /** - * Where a SQLite Store lives: one machine, the LayerFS Home among them. - * `current` marks the Store's machine (Here now); without it `fallback` is - * marked Default. `children` follow the tiles (a New machine tile). + * One machine, the LayerFS Home among them: where a SQLite Store lives, or + * where a PostgreSQL Store's sessions run. `current` marks the Store's + * machine (Here now); without it `fallback` is marked Default. `children` follow the tiles (a New machine tile). */ export function LocationPicker({ machines, value, onChange, words, label, current, fallback, disabled, compact, blocks = NO_BLOCKS, children }: { machines: readonly Machine[], value: string, onChange: (machine: string) => void, words: LocationWords, label: string @@ -123,23 +124,3 @@ export function LocationPicker({ machines, value, onChange, words, label, curren {children} } - -/** - * The machines a PostgreSQL Store is attached to: any number, none included. - * `fallback` is marked Default; `notes` overrides a tile's note (Attached…). - */ -export function AttachPicker({ machines, value, onChange, words, label, fallback, disabled, notes, compact, blocks = NO_BLOCKS, children }: { - machines: readonly Machine[], value: readonly string[], onChange: (machines: string[]) => void, words: LocationWords, label: string - fallback?: string | undefined, disabled?: boolean | undefined, notes?: Record | undefined, compact?: boolean | undefined - /** Machines that cannot run here now (model.ts tileBlocks). */ - blocks?: ReadonlyMap | undefined - children?: ReactNode -}): ReactNode { - return
    - {machines.map((m) => onChange(value.includes(m.name) ? value.filter((x) => x !== m.name) : [...value, m.name])} />)} - {children} -
    -} diff --git a/src/client/projects/setup/ProjectDialog.tsx b/src/client/projects/setup/ProjectDialog.tsx index 96e30b2..ecd8c1a 100644 --- a/src/client/projects/setup/ProjectDialog.tsx +++ b/src/client/projects/setup/ProjectDialog.tsx @@ -2,8 +2,9 @@ * The project dialog (docs/specs/layerfs-workspaces.md §2-§4): one modal that * creates or imports a project in three steps (Project, Store, Runs on, on a * left rail), configures where one runs, and picks a project to start a - * session in. SQLite runs on one machine (place = push / pull / move); - * PostgreSQL on any number (attach / detach). Docker is the default. + * session in. Both kinds run on one machine: a SQLite Store's file is placed + * there (push / pull / move); a PostgreSQL Store is on no machine, so its + * machine is only where its sessions run. Docker is the default. */ import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react' import clsx from 'clsx' @@ -27,9 +28,9 @@ import { sidebarStatus } from '../readiness.ts' import { sidebarHidden } from '../recent.ts' import type { SetupT } from './locale.ts' import type { MachinePlatformInfo } from '../../machines/model.ts' -import { attachedMachines, createSteps, defaultMachine, freeStoreName, isRunning, machinesFor, pickable, tileBlocks, type CreatePlan, type Step, type StoreKind } from './model.ts' -import { LocationPicker, machineNote, MachineTile, placeName, stoppedPicked, Tick, type LocationWords } from './MachineTiles.tsx' -import { attachStore, detachStore, placeStore, runStep, startMachine } from './run.ts' +import { createSteps, defaultMachine, freeStoreName, isRunning, machinesFor, pgMachine, pickable, tileBlocks, type CreatePlan, type Step, type StoreKind } from './model.ts' +import { LocationPicker, placeName, stoppedPicked, Tick, type LocationWords } from './MachineTiles.tsx' +import { placeStore, runStep, setRunsOn, startMachine } from './run.ts' import css from './dialog.module.css' const PG_URL = /^postgres(?:ql)?:\/\//i @@ -152,11 +153,10 @@ function stepLabel(step: Step, plan: CreatePlan, t: SetupT): string { if (id === 'connect') return t('step_connect', { store }) if (id === 'init') return plan.source ? t('step_import', { source: shortPath(plan.source), name: plan.name }) : t('step_init', { name: plan.name }) if (id === 'open') return t('step_open') - if (id === 'detach:native') return t('step_detach', { store }) const machine = placeName(step.machine ?? '', wordsOf(t)) if (id === 'start-store' || id.startsWith('start:')) return t('step_start', { machine }) if (id.startsWith('place:')) return t('step_place', { store, machine }) - return t('step_attach', { store, machine }) + return t('step_runs_on', { store, machine }) } /** The running Init's phase and count: `hash · 8,412 / 12,930`. */ @@ -238,7 +238,7 @@ function Create({ api, t, startFromFolder, back, onBusy }: { api: LayerfsApi, t: const [url, setUrl] = useState('') const [password, setPassword] = useState('') const [sqliteMachine, setSqliteMachine] = useState(null) - const [pgMachines, setPgMachines] = useState(null) + const [pgChoice, setPgChoice] = useState(null) const [steps, setSteps] = useState(null) const [shown, setShown] = useState(null) const [error, setError] = useState(null) @@ -255,8 +255,9 @@ function Create({ api, t, startFromFolder, back, onBusy }: { api: LayerfsApi, t: const slug = slugify(name) const newStoreName = storeName ?? freeStoreName(slug || 'project', data) const chosenSqlite = sqliteMachine ?? (existing?.machine ?? fallback) - const chosenPg = pgMachines ?? (existing ? attachedMachines(existing).filter((m) => machines.some((x) => x.name === m)) : [fallback]) - const chosen = kind === 'sqlite' ? [chosenSqlite] : chosenPg + // PostgreSQL: one machine too, the Store's saved one when it has one + const chosenPg = pgChoice ?? (existing ? pgMachine(existing) : fallback) + const chosen = [kind === 'sqlite' ? chosenSqlite : chosenPg] const running = steps !== null && !error useEffect(() => { onBusy(running) }, [running]) const words = wordsOf(t, data?.computer?.os) @@ -325,9 +326,9 @@ function Create({ api, t, startFromFolder, back, onBusy }: { api: LayerfsApi, t: projectDialog.close() } - const chooseKind = (next: StoreKind) => { setKind(next); setMode('new'); setPicked(null); setQuery(''); setPgMachines(null); setSqliteMachine(null) } + const chooseKind = (next: StoreKind) => { setKind(next); setMode('new'); setPicked(null); setQuery(''); setPgChoice(null); setSqliteMachine(null) } const chooseMode = (next: StoreMode) => { - setMode(next); setPgMachines(null); setSqliteMachine(null) + setMode(next); setPgChoice(null); setSqliteMachine(null) if (next === 'existing' && !stores.some((s) => s.name === picked)) setPicked(stores[0]?.name ?? null) } const head = @@ -434,7 +435,7 @@ function Create({ api, t, startFromFolder, back, onBusy }: { api: LayerfsApi, t:
    {listed.map((s) =>
    +
    + {chosen !== current + ? <> + + + + : } +
    } diff --git a/src/client/projects/setup/locale.ts b/src/client/projects/setup/locale.ts index de9e96b..ee2ca3e 100644 --- a/src/client/projects/setup/locale.ts +++ b/src/client/projects/setup/locale.ts @@ -25,18 +25,18 @@ const en = { storeName: 'Store name', storeNameInvalid: 'Use lowercase letters, numbers, dots, underscores and hyphens.', storeTaken: 'A Store named {store} exists.', url: 'Database URL', urlHint: 'Without the password, for example postgres://app@db.lan:5432/app.', urlInvalid: 'Use a postgres:// URL without the password.', password: 'Password', passwordHint: 'Or a reference: env:NAME or file:/path.', - runsOn: 'Runs on', locationHint: 'Where the Store file lives. Its projects’ sessions run there.', layerfsHome: 'LayerFS Home', runsOnMany: 'Any machines: each connects to the database.', + runsOn: 'Runs on', locationHint: 'Where the Store file lives. Its projects’ sessions run there.', layerfsHome: 'LayerFS Home', runsOnPg: 'Where this Store’s sessions run. Any machine can reach the database.', newMachine: 'New machine', noMachines: 'No machine can run this kind of Store. Add one in Home.', default: 'Default', thisMac: 'This Mac, unisolated', thisLinux: 'This computer, sandboxed', thisPc: 'This PC', running: 'Running', stopped: 'Stopped', startsOnCreate: '{machine} is stopped. Create starts it.', startsOnMove: '{machine} is stopped. Moving starts it.', here: 'Here now', - attachedChecked: 'Attached', attachedUnchecked: 'Attached · not checked yet', notAttached: 'Not attached', working: 'Working…', + working: 'Working…', moveWarn: 'Moves the whole Store {store} to {machine}: its {n} other projects run there too. Refused while any of them has a Sandbox.', create: 'Create and open', import: 'Import and open', creating: 'Creating…', step_check: 'Check folder {source}', step_import: 'Copy {source} into {name}', step_store: 'Create Store {store}', step_connect: 'Connect {store}', step_init: 'Create project {name}', step_start: 'Start {machine}', - step_place: 'Move {store} to {machine}', step_attach: 'Attach {store} to {machine}', step_detach: 'Detach {store} from native', step_open: 'Open a session', + step_place: 'Move {store} to {machine}', step_runs_on: 'Run {store} on {machine}', step_open: 'Open a session', failed: 'Stopped at “{step}”: {message}', kindSqlite: 'SQLite Store', kindPg: 'PostgreSQL Store', shared: 'Shared with {n} other projects', sharedOne: 'Shared with 1 other project', alone: 'Only this project', moveTo: 'Move to {machine}', moving: 'Moving…', - attachNote: 'Tick to attach, untick to detach. Applies to every project in {store}.', + runsOnNote: 'Where sessions run. Applies to every project in {store}.', runsOnSave: 'Run on {machine}', saving: 'Saving…', hide: 'Hide from sidebar', hidden: 'Hidden until its next session', storeMissing: 'This project’s Store is not in this LayerFS home any more. Its conversations are kept.', openResources: 'Open Home', search: 'Search projects or Stores', noProjects: 'No projects yet.', noMatch: 'No project matches.', @@ -70,18 +70,18 @@ const zh: typeof en = { storeName: '存储名称', storeNameInvalid: '请使用小写字母、数字、点、下划线和连字符。', storeTaken: '已存在名为 {store} 的存储。', url: '数据库 URL', urlHint: '不含密码,例如 postgres://app@db.lan:5432/app。', urlInvalid: '请使用不含密码的 postgres:// URL。', password: '密码', passwordHint: '或引用:env:NAME 或 file:/path。', - runsOn: '运行于', locationHint: '存储文件所在的位置,其中项目的会话也在那里运行。', layerfsHome: 'LayerFS Home', runsOnMany: '任意机器:每台都连接到该数据库。', + runsOn: '运行于', locationHint: '存储文件所在的位置,其中项目的会话也在那里运行。', layerfsHome: 'LayerFS Home', runsOnPg: '该 Store 的会话运行的位置。任何机器都能访问该数据库。', newMachine: '新建机器', noMachines: '没有机器能运行这类存储。请在“主页”中添加。', default: '默认', thisMac: '本机,无隔离', thisLinux: '这台电脑,沙箱隔离', thisPc: '这台 PC', running: '运行中', stopped: '已停止', startsOnCreate: '{machine} 已停止,创建时会启动它。', startsOnMove: '{machine} 已停止,移动时会启动它。', here: '当前位置', - attachedChecked: '已连接', attachedUnchecked: '已连接 · 尚未检查', notAttached: '未连接', working: '处理中…', + working: '处理中…', moveWarn: '会把整个存储 {store} 移到 {machine}:其中另外 {n} 个项目也会在那里运行。任一项目有沙箱时会被拒绝。', create: '创建并打开', import: '导入并打开', creating: '正在创建…', step_check: '检查文件夹 {source}', step_import: '把 {source} 复制到 {name}', step_store: '创建存储 {store}', step_connect: '连接 {store}', step_init: '创建项目 {name}', step_start: '启动 {machine}', - step_place: '把 {store} 移到 {machine}', step_attach: '把 {store} 连接到 {machine}', step_detach: '断开 {store} 与 native 的连接', step_open: '打开会话', + step_place: '把 {store} 移到 {machine}', step_runs_on: '让 {store} 运行于 {machine}', step_open: '打开会话', failed: '停在“{step}”:{message}', kindSqlite: 'SQLite 存储', kindPg: 'PostgreSQL 存储', shared: '与另外 {n} 个项目共用', sharedOne: '与另外 1 个项目共用', alone: '仅此项目', moveTo: '移到 {machine}', moving: '正在移动…', - attachNote: '勾选即连接,取消勾选即断开。对 {store} 中的所有项目生效。', + runsOnNote: '会话运行的位置。对 {store} 中的所有项目生效。', runsOnSave: '运行于 {machine}', saving: '保存中…', hide: '从侧边栏隐藏', hidden: '已隐藏,直到它有新会话', storeMissing: '此项目的存储已不在这个 LayerFS 主目录中。它的对话仍然保留。', openResources: '打开主页', search: '搜索项目或存储', noProjects: '还没有项目。', noMatch: '没有匹配的项目。', diff --git a/src/client/projects/setup/model.ts b/src/client/projects/setup/model.ts index 865e625..50d6341 100644 --- a/src/client/projects/setup/model.ts +++ b/src/client/projects/setup/model.ts @@ -59,27 +59,22 @@ export function defaultMachine(machines: readonly Machine[], blocks: ReadonlyMap /** Whether `name` can be picked: not blocked here, or only waiting on the Docker Engine its Start launches. */ export const pickable = (name: string, blocks: ReadonlyMap): boolean => blocks.get(name)?.startable ?? true -/** A PostgreSQL Store's attached machines (native when the CLI predates attachments). */ -export function attachedMachines(store: Pick): string[] { - return store.attachments ? store.attachments.map((a) => a.machine) : ['native'] -} - -/** The machine the host runs a PostgreSQL project's sessions on (`pgMachineOf`). */ -export function pgMachine(store: Pick): string | null { - if (!store.attachments) return 'native' - const names = store.attachments.map((a) => a.machine) - if (names.includes('native')) return 'native' - return store.attachments.find((a) => a.checked)?.machine ?? names[0] ?? null +/** + * The machine a PostgreSQL Store's sessions run on by default: the host's + * answer (this install's saved choice, else docker when it can, else native). + */ +export function pgMachine(store: Pick): string { + return store.runsOn ?? 'native' } -/** Where a project runs: its SQLite Store's machine, or its PostgreSQL Store's attached machines. */ -export function runsOn(store: Pick | undefined): string[] { +/** Where a project runs: its SQLite Store's machine, or the machine its PostgreSQL Store runs on. */ +export function runsOn(store: Pick | undefined): string[] { if (!store) return [] - return store.kind === 'postgresql' ? attachedMachines(store) : [store.machine ?? 'native'] + return [store.kind === 'postgresql' ? pgMachine(store) : store.machine ?? 'native'] } /** The machine a project's readiness follows (§8). */ -export function primaryMachine(store: Pick | undefined): string | null { +export function primaryMachine(store: Pick | undefined): string | null { if (!store) return null return store.kind === 'postgresql' ? pgMachine(store) : store.machine ?? 'native' } @@ -105,18 +100,22 @@ export interface CreatePlan { /** An existing Store, or null for a new one. */ store: StoreRow | null newStore?: { name: string, url?: string, password?: string } - /** SQLite: one machine. PostgreSQL: every ticked machine. */ + /** One machine: where a SQLite Store's file goes, or where a PostgreSQL Store's sessions run. */ machines: string[] /** An absolute folder the project starts from; empty when absent. */ source?: string } -export type StepId = 'check' | 'store' | 'connect' | 'start-store' | 'init' | `start:${string}` | `place:${string}` | `attach:${string}` | 'detach:native' | 'open' +export type StepId = 'check' | 'store' | 'connect' | 'start-store' | 'init' | `start:${string}` | `place:${string}` | `runs-on:${string}` | 'open' export interface Step { id: StepId, machine?: string } /** * The steps a Create runs, in order (§3). `view` gives machine states, so a - * running machine is not started again. + * running machine is not started again. A PostgreSQL Store is on no machine: + * a new one is connected with the machine its sessions run on, an existing + * one only has that choice changed (`runs-on:`) when another is picked. + * Nothing is attached; the machine is started last, because a session starts + * none and the one Create opens runs there. */ export function createSteps(plan: CreatePlan, view: Pick | undefined): Step[] { const state = (name: string) => view?.machines.find((m) => m.name === name) @@ -131,14 +130,11 @@ export function createSteps(plan: CreatePlan, view: Pick api.call('POST', `/api/stores/${enc(store)}/attach`, { machine }) -export const detachStore = (api: LayerfsApi, store: string, machine: string) => api.call('POST', `/api/stores/${enc(store)}/detach`, { machine }) +/** The machine a PostgreSQL Store's sessions run on by default (the plugin's own choice; LayerFS records none). */ +export const setRunsOn = (api: LayerfsApi, store: string, machine: string) => api.call('POST', `/api/stores/${enc(store)}/runs-on`, { machine }) /** The Store a plan creates in or uses. */ export const storeOfPlan = (plan: CreatePlan): string => plan.store?.name ?? plan.newStore?.name ?? '' @@ -51,7 +51,7 @@ export async function runStep(api: LayerfsApi, plan: CreatePlan, step: Step, onJ await api.call('POST', '/api/stores', { name: store }) return case step.id === 'connect': - await api.call('POST', '/api/stores/postgresql', { name: store, url: plan.newStore?.url ?? '', ...passwordBody(plan.newStore?.password ?? '') }) + await api.call('POST', '/api/stores/postgresql', { name: store, url: plan.newStore?.url ?? '', ...passwordBody(plan.newStore?.password ?? ''), ...(step.machine ? { runsOn: step.machine } : {}) }) return case step.id === 'start-store': case step.id.startsWith('start:'): @@ -65,11 +65,8 @@ export async function runStep(api: LayerfsApi, plan: CreatePlan, step: Step, onJ case step.id.startsWith('place:'): await placeStore(api, store, step.machine!) return - case step.id.startsWith('attach:'): - await attachStore(api, store, step.machine!) - return - case step.id === 'detach:native': - await detachStore(api, store, 'native') + case step.id.startsWith('runs-on:'): + await setRunsOn(api, store, step.machine!) return default: } diff --git a/src/client/storage/ConnectDatabase.tsx b/src/client/storage/ConnectDatabase.tsx index 597e69a..6e22add 100644 --- a/src/client/storage/ConnectDatabase.tsx +++ b/src/client/storage/ConnectDatabase.tsx @@ -1,104 +1,137 @@ /** - * Connect a database to a machine (the Stores tab's PostgreSQL side). One - * dialog, three screens: + * Connect a database: the one dialog a PostgreSQL Store is connected and + * checked with. A PostgreSQL Store is on no machine; "Runs on" is only the + * machine its sessions start on (the plugin's own choice), and any machine + * that runs PostgreSQL Sandboxes reaches the Store with the Store's own + * connection. Three screens: * - * - pick: every connected PostgreSQL Store, grouped by server (host and - * user). One already on the machine says so; another has Attach, or why it - * cannot be attached here. Each server ends with "New database on this - * server" (its host and user filled in) and the list with "New server". - * - new: the database, its Store name (the database's by default), and for a - * new server its host, user and password; a pasted connection URL fills - * them. store.connect, then store.attach to this machine (store.connect - * attaches the LayerFS Home itself). + * - pick: every connected PostgreSQL Store under its server, each with where + * it runs and one button (Check; on a machine page, Run here for a Store + * that runs elsewhere). Each server ends with "New database on this + * server" (its host and user filled in, its password reused) and the list + * with "New server". + * - new: the database, its Store name (the database's by default), for a new + * server its host, user and password (a pasted connection URL fills them), + * and Runs on. store.connect, then the check from that machine. * - check: the path the machine dials (machine, server, Store) and the three - * things store.attach checks from there. The call answers once, so the path - * runs as one until it does; a refusal marks the step LayerFS names - * (machine-stores.ts `failedStep`), else shows as it came. A server not - * reached offers the machine its own address, a new attempt the person - * starts. A database connected whose attach failed says so: it stays - * connected on the LayerFS Home. + * things the check tries from there (store.status --machine). It answers + * once, so the path runs as one until it does; a failure marks the step + * LayerFS names (machine-stores.ts `failedStep`), else shows as it came. + * Only then, and only for a server not reached, the machine can be given + * an address of its own (store.update --machine, which LayerFS checks + * from the machine before it saves anything). */ -import { useState, type ReactNode } from 'react' -import { Button, Modal, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' +import { useEffect, useRef, useState, type ReactNode } from 'react' +import { Button, IconChevronRightOutlineRegular, Modal, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' import { enc, type LayerfsApi } from '../api.ts' import { MachineGlyph } from '../machines/icons.tsx' -import { Refusal, refusalOf } from '../ui/index.tsx' +import { LocationPicker } from '../projects/setup/MachineTiles.tsx' +import { defaultMachine, machinesFor } from '../projects/setup/model.ts' +import { Field, MenuSelect, Refusal } from '../ui/index.tsx' import type { StorageT } from './locale.ts' -import { CHECK_STEPS, failedStep, parsePgUrl, pgServers, pgUrl, routedServer, type CheckStep, type PgServerGroup } from './machine-stores.ts' -import { loopbackAlias } from './model.ts' -import { refusalLabels, StoreGlyph, TextField } from './parts.tsx' +import { CHECK_STEPS, failedStep, parsePgUrl, pgUrl, routedServer, serverGroups, serverKey, type CheckStep, type PgServerGroup } from './machine-stores.ts' +import { loopbackAlias, runsOnOf } from './model.ts' +import { locationWords, refusalLabels, StoreGlyph, TextField } from './parts.tsx' import { PG_URL_PASSWORD, PgPasswordFields, usePgPassword } from './pg-fields.tsx' -import type { StorageView } from './types.ts' +import type { PgCheck, StorageView, StoreRow } from './types.ts' import css from './MachineStores.module.css' import scss from './Storage.module.css' const NAME = /^[a-z0-9](?:[a-z0-9_.-]{0,61}[a-z0-9])?$/ +const SYNC = ['off', 'local', 'remote_write', 'on', 'remote_apply'] as const type Screen = { kind: 'pick' } | { kind: 'new', server: PgServerGroup | null } | { kind: 'check', check: Check } interface Check { store: string - /** The address the machine dials, as shown on the path. */ - server: string + machine: string state: 'running' | 'ok' | 'failed' + /** What the machine answered. */ + result?: PgCheck + /** A refusal of the call itself, or the check's own error. */ error?: unknown - /** A new database: connected, then its attach failed. */ + /** This dialog connected the Store just before. */ connected?: boolean } -export function ConnectDatabaseDialog({ api, t, view, machine, onClose, done }: { - api: LayerfsApi, t: StorageT, view: StorageView | undefined, machine: string, onClose: () => void, done: () => void +/** The address `machine` dials for `store`: its own connection's, else the Store's with a loopback host renamed for the machine. */ +export function dialedServer(s: StoreRow | undefined, machine: string, platform: string | undefined): string { + const own = s?.ownConnections?.find((c) => c.machine === machine) + const ownHost = own?.url ? parsePgUrl(own.url)?.host : null + if (ownHost) return ownHost + return s ? routedServer(serverKey(s), platform ? loopbackAlias(platform) : null) : '' +} + +export function ConnectDatabaseDialog({ api, t, view, machine: fixed, server, check: startCheck, onClose, done }: { + api: LayerfsApi, t: StorageT, view: StorageView | undefined + /** A machine page's dialog: new databases run on it, and a Store that runs elsewhere can be moved here. */ + machine?: string | undefined + /** Open on a new database on this server (`host:port`). */ + server?: string | undefined + /** Open on the check of a Store, from `machine` (else where it runs). */ + check?: { store: string, machine?: string | undefined } | undefined + onClose: () => void, done: () => void }): ReactNode { - const [screen, setScreen] = useState({ kind: 'pick' }) + const groups = serverGroups(view?.stores ?? []) + const [screen, setScreen] = useState(() => { + if (startCheck) { + const s = view?.stores.find((x) => x.name === startCheck.store) + return { kind: 'check', check: { store: startCheck.store, machine: startCheck.machine ?? fixed ?? (s ? runsOnOf(s) : 'native'), state: 'running' } } + } + if (server) return { kind: 'new', server: groups.find((g) => g.server === server) ?? null } + return groups.length ? { kind: 'pick' } : { kind: 'new', server: null } + }) const [own, setOwn] = useState(false) const [ownUrl, setOwnUrl] = useState('') const ownPw = usePgPassword() - if (!view) return null - const place = machine === 'native' ? t('layerfsHome') : machine - const platform = view.machines.find((m) => m.name === machine)?.platform - const alias = platform ? loopbackAlias(platform) : null - const groups = pgServers(view, machine, t) - const running = screen.kind === 'check' && screen.check.state === 'running' + // one call at a time: a newer check wins, an older answer is dropped + const turn = useRef(0) - /** store.attach from the machine, with its own connection when one is given. */ - const attach = async (store: string, server: string, extra: { connected?: boolean } = {}, ownBody: Record = {}) => { - setScreen({ kind: 'check', check: { store, server, state: 'running', ...extra } }) + /** The check from `machine` (GET …/check); `via` runs first (a new connection of the machine's own). */ + const check = async (store: string, machine: string, extra: { connected?: boolean } = {}, via?: () => Promise) => { + const mine = ++turn.current + setScreen({ kind: 'check', check: { store, machine, state: 'running', ...extra } }) try { - await api.call('POST', `/api/stores/${enc(store)}/attach`, { machine, ...ownBody }) - setScreen({ kind: 'check', check: { store, server, state: 'ok', ...extra } }) + if (via) { await via(); done() } + const result = await api.call('GET', `/api/stores/${enc(store)}/check?machine=${enc(machine)}`) + if (mine !== turn.current) return + setScreen({ kind: 'check', check: { store, machine, state: result.ok ? 'ok' : 'failed', result, ...(result.ok ? {} : { error: result.error }), ...extra } }) } catch (error) { - setScreen({ kind: 'check', check: { store, server, state: 'failed', error, ...extra } }) - } finally { - done() + if (mine === turn.current) setScreen({ kind: 'check', check: { store, machine, state: 'failed', error, ...extra } }) } } - - const title = t('cdTitle', { machine: place }) - const back = screen.kind === 'pick' || running ? null : () => { setOwn(false); setScreen({ kind: 'pick' }) } + // opened on a check: run it once + useEffect(() => { if (screen.kind === 'check' && screen.check.state === 'running') void check(screen.check.store, screen.check.machine) }, []) + if (!view) return null + const place = (m: string) => (m === 'native' ? t('layerfsHome') : m) + const running = screen.kind === 'check' && screen.check.state === 'running' + const runHere = async (store: string, machine: string) => { + await check(store, machine, {}, () => api.call('POST', `/api/stores/${enc(store)}/runs-on`, { machine })) + } + const title = screen.kind === 'check' ? t('cdCheckTitle', { store: screen.check.store }) : fixed ? t('cdTitle', { machine: place(fixed) }) : t('connectDatabase') + // a dialog opened on one screen has no list to go back to + const back = startCheck || running || screen.kind === 'pick' || (screen.kind === 'new' && (server || !groups.length)) ? null : () => { setOwn(false); setScreen({ kind: 'pick' }) } return ( { if (!running) onClose() }} title={title} closeLabel={t('close')} className={scss.modal} footer={