Skip to content

Commit 0b89b33

Browse files
feat(service-automation, metadata-protocol, driver-mongodb, cli): a connector connection is unique per organization and instance (package, name) (#33199)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6Jao3aDjoEUznHeGMZJaoMEKa5)_ Part of #31699 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:按 Tesla 的裁定(连接唯一键「按 包+名字 唯一」),`sys_connector_connection` 的唯一键从 `(organization_id, connector_name)` 加宽为 `(organization_id, connector_package, connector_name)`。没有包的连接(环境自建或代码注册的连接器实例)靠一条运行时守卫索引 `uniq_sys_connector_connection_packageless` 继续保持每个组织一条。守卫立住之后,旧键在下一次安全同步时被替换(先建后删,`safe`),中间任何时刻都有唯一规则。 - 为什么改:ADR-0150 D4 / D8 R11,#31699 PR 3 的存储一半。下一步(3a-ii)让连接存储、连接门和 OAuth 回调带上包。 - 不变:用户可见的连接行为不变。存储仍按组织+名字读写;一持有者兜底仍然保证每个连接器名只有一个包。 - 风险与回滚:MySQL 8 升级库保留旧键(与 #32164 的授权守卫同一限制,driver-sql 识别修复另开卡);driver-memory 不建守卫。回滚即 revert;守卫索引是额外索引,回滚后旧键由声明重建。 - 先看:`packages/metadata-protocol/src/migrations/connector-connection-packageless-index.ts`(从 #32164 的授权守卫复制,只换常量和措辞)、`packages/services/service-automation/src/connector-connections.ts`(首次连接与回填竞态的回收)、`stored-reference-package-backfill.ts`(`duplicated`)。 ## What changes - **Key.** `sys_connector_connection` declares `{ fields: ['organization_id', 'connector_package', 'connector_name'], unique: 'global' }`. Spelled `'global'` with `organization_id` listed, as #32164 spelled the grant's, because `driver-sql`'s widening arm (`widenedUniqueReplacements`) does not fire for `'organization'` (measured: that spelling plans a destructive orphan drop). The arm keeps the old key until a partial guard on exactly `(organization_id, connector_name)` stands, then plans one `replace_unique_index`, `safe`, create-before-drop. - **Guard.** `uniq_sys_connector_connection_packageless`, built at `objectql:schema-synced` on every kernel that runs the table's DDL (`metadata-protocol` `plugin.ts`): partial index on SQLite and PostgreSQL, functional digest on MySQL 8.0.13+, INVISIBLE generated column on MariaDB 10.3+, `RUNTIME_OWNED_UNIQUES` on MongoDB (keyed `(connector_name)`, the key Mongo materialized for the old declaration). Listed in `runtime-index-preflight.ts` (so `os migrate duplicates`) and in the CLI's `schema-sync-indexes.ts` (so `os migrate plan` / `apply`). The module is a copy of `user-permission-set-packageless-index.ts` with the table's constants and wording. - **Store.** A first connect that counts a second row of its instance after its insert (the boot backfill stamped another connect's row between this one's read and insert, which the old key refused) deletes its own row and is refused. Everything else in the store is unchanged; carrying the package is the next PR. - **Backfill (R11) and bind.** A bind whose update is a unique violation, confirmed by a read of the row of that key already naming the holder, is left and reported (`duplicated`), and the walk goes on; the dry run agrees. `os migrate stored-references bind` refuses it as `duplicate`. - **Docs.** `content/docs/deployment/cli.mdx` (runtime-owned indexes, old-key retirement, MySQL limit, the bind refusal); `content/docs/automation/connectors.mdx` (one connection per organization and instance). ## Why ADR-0150 D4: a connector instance is identified by `(package, name)`, and D8 row R11 gives the connection its package column. The maintainer ruled on #31699 that a connection is unique by package and name, so one organization can connect both packages' instances of one name once the backstop narrows (the last PR of #31699). ## Verification - Booted kernel (`service-automation` `connector-connection-guard-at-schema-sync.test.ts`, real `ObjectQLPlugin`, SQLite, the shipped object): a second package-less connection written from a `start()` before `kernel:ready` is refused, two packages' connections of one name are admitted, a second of one package's is refused; with `bootPhaseHooks: false` too; a dropped guard is rebuilt by the next pass. Ablation (guard call removed from the hook): 3 of 5 red. - `driver-sql` `sql-driver-widened-connection-key.test.ts`: SQLite (no guard → old key kept; guard → one safe replace; re-plan empty) and live PostgreSQL 16 locally; the MySQL cell pins the declared limit (old key kept) and runs on `main`. - Guard module: 33 unit tests; live PostgreSQL test green locally; live MySQL suite runs on `main`. `driver-mongodb` 4 tests (live mongod not reachable here); `driver-memory` 3 (declared limit). - Store race: pin + control in `connector-connections.test.ts` (ablation red). Backfill: 3 new pins in `stored-reference-package-column.test.ts` (dry run agrees, unconfirmed violation and an R8 violation end the pass; each red under ablation). - Full suites: `@objectstack/service-automation` 3843 passed (before the review round; affected files re-run, 409 passed), `@objectstack/metadata-protocol` 339 files passed. CLI: `schema-sync-indexes`, `duplicates.contract`, `stored-references`, `apply.schema-sync-indexes`, `schema-migrate.grant-guard` green. Build with declarations, `tsc --noEmit` and `check:test-typecheck` green for every touched package. ## Red-line read Run in this thread by a separate review pass (maintainer's instruction: 「你自己有fable,自己审就可以了吧?」). Design round: PASS-WITH-CHANGES (M1–M7, S1–S9, taken). Code round 1: PASS-WITH-CHANGES, no must-fix, 7 should-fix (a racing first connect could leave two rows; dry run vs real run; backfill catch confirmation; docs and changeset wording), all taken. Round 2 (delta): PASS, one should-fix (foreign messages on the new count and delete) and two changeset notes, taken. Carried to the next PR: the store reads and counts by package. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibzKCovWpJoMZD6U3NT --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 633d8c4 commit 0b89b33

32 files changed

Lines changed: 2868 additions & 80 deletions
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/service-automation': patch
4+
'@objectstack/driver-mongodb': patch
5+
'@objectstack/cli': patch
6+
---
7+
8+
feat(service-automation, metadata-protocol, driver-mongodb, cli): a connector connection is unique per organization and instance, the instance being its package and name, and the connections that name no package keep one per organization through a runtime guard (ADR-0150 D4, D8 row R11, #31699)
9+
10+
Clause-②: yes (widening) — additive CLI and in-process surfaces: `os migrate plan` lists a second runtime-owned index (and `--json` `schemaSyncIndexes` an entry for it), `os migrate duplicates` probes it, `os migrate stored-references bind` answers the refusal `duplicate` where it threw, and the exports and types listed under In-process APIs grow. The connector doors (the connect door, the OAuth callback, revoke, the connection list) and every automation request answer as before: the store still reads and writes by organization and name, and the one-holder backstop keeps every connector name to one package until #31699's last PR, so no second package's connection is written yet.
11+
Metadata-protocol: none
12+
Skills-docs: `content/docs/automation/connectors.mdx` says a connection is one per organization and instance; `content/docs/deployment/cli.mdx` lists the guard among the runtime-owned indexes and the bind's `duplicate` refusal. `skills/**` teaches "connect once per organization", which still holds per instance.
13+
14+
<!-- adr-0087: not-required (no-migration-prescription) No key of any authorable schema is added, removed, renamed or re-shaped. `sys_connector_connection` is a platform object and its `indexes[]` is not authored metadata; the key change is a schema face the drift plan applies, the guard is a runtime-managed physical index, and no stored row is rewritten, so there is nothing for `objectstack migrate meta` to rewrite. -->
15+
16+
Part of #31699 (ADR-0150 child B, PR 3a: the storage half). The maintainer's ruling on #31699: a connection is unique by package and name. The store, the connect door and the OAuth callback carry the package in the next PR; this one widens the key, stands the guard that keeps the package-less rows to one, and teaches the two writers of the package column what the wider key can refuse.
17+
18+
**The key: `sys_connector_connection`.**
19+
20+
- FROM one connection per `(organization_id, connector_name)` (`uniq_sys_connector_connection_organization_id_connector_name`) TO one per `(organization_id, connector_package, connector_name)`. On SQL the drift plan replaces the old key with one `replace_unique_index`, categorized `safe`, create-before-drop, and only once the guard below stands; until then `driver-sql`'s widening arm keeps the old key, so the table is never without a unique rule over its rows. The guard is built at schema sync after the table's drift is read, so on an upgraded database the old key retires on the NEXT sync that runs safe drift (a dev `autoMigrate: 'safe'` boot, or `os migrate apply`, which lists it). Measured on SQLite and PostgreSQL 16: with the guard, the plan is that one safe op and a re-plan is empty; two packages' connections of one name in one organization are admitted, a second connection of one package's instance is refused, and a second package-less connection is refused. On MariaDB the retirement is read from `driver-sql`'s source, not measured: its carrier column is read as a partial unique on the two columns, and on an upgraded MySQL-family database `connector_package` is a TEXT column, so the wide key is built over the driver's hash shadow.
21+
22+
**The guard: `uniq_sys_connector_connection_packageless`.**
23+
24+
- `connector_package` is NULL on every connection of an instance the environment authored or a plugin registers in code, and of a name the boot backfill could not bind. A SQL UNIQUE treats NULLs as distinct, so for exactly those connections the wider key constrains nothing. The guard keeps them to one per `(organization_id, connector_name)`, as the old key did: two of them would keep two refresh tokens for one instance, and a revoke would leave the other stored.
25+
- Built as the permission-set grant's guard is (#32164), at `objectql:schema-synced`, on every kernel that runs the table's DDL; a pass that holds its DDL back builds nothing, a standing guard costs one catalog read, a refusal is reported once per boot. SQLite and PostgreSQL: a partial unique index `WHERE connector_package IS NULL`. MySQL 8.0.13+: a functional key part over the hash-shadow digest. MariaDB 10.3+: a UNIQUE key over an INVISIBLE generated column `uniq_sys_connector_connection_packageless__hash`. MongoDB: `driver-mongodb` builds it at collection sync (`RUNTIME_OWNED_UNIQUES`, `connector_package: null`), keyed `(connector_name)`, because Mongo materialized the earlier declaration's one column, so the widening arm there retires the old index once the guard stands.
26+
- Refuse, never keep-one: a database already holding two package-less connections of one key keeps both; the build fails and logs, at `error`, the keys, the consequence and the query that lists them. `os migrate duplicates` lists this index too. It admits nothing the old key refused.
27+
28+
**The writers of the table.**
29+
30+
- The connection store's first connect (`ConnectorConnectionStore#connect`): the old key refused a second row of one instance in one organization; the wide key admits one when the boot backfill stamped the first connect's row with its package between a second connect's read and its insert. A connect that counts a second row after its insert now deletes its own row and is refused ("its connection changed while this connect was completing … begin the connect again"), nothing kept, as the old key refused it; when both racing connects count two rows, both can be refused and no row stands. Where the engine answers no id for the inserted row, or the delete fails, the connect is refused saying the instance was connected twice and to revoke until it reads as not connected. A first connect with no race is unchanged.
31+
- The boot backfill (`stored-reference-package-backfill.ts`, row R11) binds a package-less connection to the one package that holds its name. Under the wider key that row can be a second row of one key, when a connection bound to that package already stands for the same organization and name (a database where a guard build was refused, `driver-memory`, a server with no form, or a pair a racing first connect left when its process died before taking its row back). The wider key makes that unique violation possible, and it would end R11's pass; it is now reported per row: the row is left as it is and listed in the report's new `duplicated` list, once a read confirms the row of that key that already names the holder, named in one `warn` line per pass. A dry run lists the same rows, counting the keys it has already bound in the pass. Any other failed write, a violation no such row confirms, and any violation on R8 or R9 (whose keys do not carry the package) still end the pass.
32+
- `os migrate stored-references bind`: FROM a unique violation thrown as an error TO the refusal `duplicate`, naming the row, the package and the key, nothing written.
33+
34+
**Declared limits.**
35+
36+
- MySQL 8, upgraded databases: `driver-sql` reads the guard's functional key part as an expression, not as a partial guard, so the widening arm keeps the old key there. The old key keeps refusing what it refused, so an organization cannot connect a second package's instance of one name on such a database until `driver-sql` recognises the form. A database created fresh on MySQL 8 has the wide key and the guard and no old key. The permission-set grant's guard (#32164) shares this limit. MySQL before 8.0.13 and MariaDB before 10.3 build no form, keep the old key (or build it under the driver's generated name where it is missing) and say so at `error` each boot.
37+
- `driver-memory` builds no guard (no raw-SQL seam), as for the grant: a pin measures that its unique check treats a NULL package as distinct, so two package-less connections of one instance are admitted there.
38+
- The MySQL, MariaDB and real-mongod pins run in suites that run on `main` only, so they first run after this lands.
39+
40+
**In-process APIs.** `@objectstack/metadata-protocol` exports `ensureConnectorConnectionPackagelessIndex`, `createConnectorConnectionGuardAtSchemaSync`, `buildConnectorConnectionPackagelessIndexSql`, `buildConnectorConnectionPackagelessIndexPresenceSql`, `buildConnectorConnectionPackagelessDuplicateProbeSql`, `buildConnectorConnectionOldKeySql`, `resolveConnectorConnectionIndexSeam`, `CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME`, `CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS`, `CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME` and the result, status and pass-outcome types. `@objectstack/service-automation`'s `StoredReferenceBackfillReport` gains `duplicated`. `@objectstack/cli`'s `BindRefusal` gains `'duplicate'`. All additive.

‎content/docs/automation/connectors.mdx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -754,7 +754,9 @@ a rotating refresh token is never spent twice.
754754
(`OS_BASE_URL` or `OS_AUTH_URL` plus `/api/v1/automation/connectors/oauth/callback`,
755755
or the automation plugin's `connectorOAuthRedirectUri`), never the
756756
request's; register that URI with the vendor. The refresh token is kept
757-
encrypted in `sys_connector_connection`, one row per organization; it is
757+
encrypted in `sys_connector_connection`, one row per organization and
758+
instance, an instance being its package and name (one per organization for
759+
an instance the environment authored or a plugin registers); it is
758760
not a sign-in account, and signing in never touches it. A run dispatches
759761
with its own organization's connection; a run with no organization uses the
760762
instance's only connection, and is refused when there are several. When the

‎content/docs/deployment/cli.mdx‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1189,23 +1189,37 @@ idempotent — but only the second takes time proportional to your data.
11891189
11901190
#### Runtime-owned indexes apply builds
11911191
1192-
`os migrate apply` also builds one index of its own once that DDL is done: the
1193-
permission-set grant's package-less guard, which keeps one grant per user,
1194-
permission set and organization among the grants that name no package.
1195-
`os migrate plan` lists it in a section after the held-back work and before the
1196-
drift, the order `apply` performs them in:
1192+
`os migrate apply` also builds two indexes of its own once that DDL is done:
1193+
the permission-set grant's package-less guard, which keeps one grant per user,
1194+
permission set and organization among the grants that name no package, and the
1195+
connector connection's, which keeps one connection per organization and
1196+
connector instance among the connections that name no package.
1197+
`os migrate plan` lists them in a section after the held-back work and before
1198+
the drift, the order `apply` performs them in:
11971199
11981200
```text
11991201
Runtime-owned indexes (built when you apply, after the work above)
12001202
+ sys_user_permission_set.uniq_sys_user_permission_set_packageless [unique (user_id, permission_set, organization_id) WHERE permission_set_package IS NULL]
1203+
+ sys_connector_connection.uniq_sys_connector_connection_packageless [unique (organization_id, connector_name) WHERE connector_package IS NULL]
12011204
```
12021205
1203-
The plan lists it only where `apply` would build it. An index that already
1206+
The plan lists each only where `apply` would build it. An index that already
12041207
stands is not listed, because `apply` sends it no DDL. Nor is it listed when the
12051208
plan has nothing else to apply, because `apply` then changes nothing at all; a
1206-
serving boot that runs schema sync builds it instead. Grants that would collide
1207-
under the index make the line read as refused, with how many: `apply` leaves
1209+
serving boot that runs schema sync builds it instead. Rows that would collide
1210+
under an index make its line read as refused, with how many: `apply` leaves
12081211
those rows as they are, applies the rest, and `os migrate duplicates` lists them.
1212+
1213+
Once a guard stands, the next safe sync (or `os migrate apply`) retires the key
1214+
it stands beside — the grant's `(user_id, permission_set, organization_id)`, the
1215+
connection's `(organization_id, connector_name)` — as one `replace_unique_index`
1216+
categorized safe, created before it is dropped. Until then that key stays and
1217+
keeps refusing a second package's grant or connection of one name. On an
1218+
upgraded MySQL database both old keys stay, because `driver-sql` does not read a
1219+
guard's functional key part as a guard there, so a second package's grant or
1220+
connection of one name stays refused on MySQL. A database created fresh on
1221+
MySQL never has the old keys.
1222+
12091223
Under `--json` the section is the `schemaSyncIndexes` array, whose entries carry
12101224
`table`, `index`, `keyParts`, `rowScope` and a `status` of `build`, `blocked` or
12111225
`unreadable`.
@@ -1466,7 +1480,7 @@ where the data lives.
14661480
| `os migrate meta --stored` | Replay the metadata conversion chain over this deployment's `sys_metadata` rows and rewrite the ones still carrying a pre-protocol shape. Hygiene, not a gate — nothing depends on it having run |
14671481
| `os migrate security-catalog-overlays` | List the environment-wide permission-set and position rows (the legacy plurals `permissions` / `positions` included) stored over a name a configured package holds — the rows a v18 cold boot refuses — each with the package that holds its name; `--apply` deletes them, one history tombstone per row. Run it before the first v18 boot, with the flags and environment the deployment boots with: the platform security plugin's sets are held only where `os serve` composes it (an auth secret set, and the `auth` tier on), and the step takes `serve`'s `--preset` and `--dev` with `serve`'s meaning. Adopts nothing; exits 1 while it lists a row |
14681482
| `os migrate packageless-overlays` | List the package-less view, dashboard, report, translation and email-template rows stored over a name exactly one installed package ships — the customizations Setup saved before ADR-0146 D11 closed that write — and with `--apply` move each into that package's paired `<base>.custom` (created when absent) as a declared override, `basedOn` the base's installed version; the package-less row is deleted only after the moved one reads back as served. A name no package ships is environment metadata and is not touched; a name several packages ship, or one the pair already holds a row of, is listed and left with the reason. So is a view container (`list`, `listViews`, `form`, `formViews`): only a single view declares an override, so it is listed `cannot_declare` and never attempted, with the way out — save each of its views into the pair as a single view, then delete the container row. Takes `serve`'s `--preset` and `--dev`. Idempotent: a second run moves nothing. Run it once after upgrading |
1469-
| `os migrate stored-references` | List the stored references the upgrade left naming no package because the one resolution rule (ADR-0150 D3) refuses them: a user's permission-set assignment, an audience-binding suggestion, a managed sharing rule, a queue membership, an open approval request, a paused flow run, a flow credential, a flow dispatch key, a connector connection, an assignment cursor or a legacy email template whose name more than one package holds, each with its row id and every candidate by its qualified address (`namespace/name`). A suggestion a package wrote naming an environment-authored permission set, or one held only outside the package's declared dependencies, is listed with the fix and is never bindable. Also lists the packaged fields whose picklist the rule refuses (served with no options) the names two packages held before the one-holder rule, and each installed package whose namespace spells a literal segment of the address grammar (`actions`, `connectors`, `global`, `hooks`, `oauth`, `runs`, `trigger`): the boot keeps it with one warning, its items are read with `?package=ID`, and only a rename of its namespace gives them qualified addresses at the door that reads the literal (for `runs` that door is the inbound hook alone, reached at its bare address until then). Read-only, and `--json` prints the same bytes on every run. Run before the release's first boot, it reads a table that has no package column yet as nothing bound yet, lists the rows that boot's backfill will leave unbound, and says so once; it adds no column. A table this composition does not carry (automation, approvals) is named, not skipped: compose as `os serve` does, with `--preset`/`--dev`. Then `os migrate stored-references bind --table T --id ID --package P` writes the package you chose into that one row: it asks the rule again first and refuses, writing nothing, when the row is already bound, now resolves on its own, or the package is no longer a candidate (a stale report). Each bind leaves a `sys_audit_log` row; a second run writes nothing. Confirm with `--yes` |
1483+
| `os migrate stored-references` | List the stored references the upgrade left naming no package because the one resolution rule (ADR-0150 D3) refuses them: a user's permission-set assignment, an audience-binding suggestion, a managed sharing rule, a queue membership, an open approval request, a paused flow run, a flow credential, a flow dispatch key, a connector connection, an assignment cursor or a legacy email template whose name more than one package holds, each with its row id and every candidate by its qualified address (`namespace/name`). A suggestion a package wrote naming an environment-authored permission set, or one held only outside the package's declared dependencies, is listed with the fix and is never bindable. Also lists the packaged fields whose picklist the rule refuses (served with no options) the names two packages held before the one-holder rule, and each installed package whose namespace spells a literal segment of the address grammar (`actions`, `connectors`, `global`, `hooks`, `oauth`, `runs`, `trigger`): the boot keeps it with one warning, its items are read with `?package=ID`, and only a rename of its namespace gives them qualified addresses at the door that reads the literal (for `runs` that door is the inbound hook alone, reached at its bare address until then). Read-only, and `--json` prints the same bytes on every run. Run before the release's first boot, it reads a table that has no package column yet as nothing bound yet, lists the rows that boot's backfill will leave unbound, and says so once; it adds no column. A table this composition does not carry (automation, approvals) is named, not skipped: compose as `os serve` does, with `--preset`/`--dev`. Then `os migrate stored-references bind --table T --id ID --package P` writes the package you chose into that one row: it asks the rule again first and refuses, writing nothing, when the row is already bound, now resolves on its own, or the package is no longer a candidate (a stale report), and refuses (`duplicate`) a bind the table's unique key refuses because a row bound to that package already holds the key, such as a connector connection the instance already has in that organization. Each bind leaves a `sys_audit_log` row; a second run writes nothing. Confirm with `--yes` |
14701484
| `os migrate duplicates` | Report business identifiers already minted twice across the organization partitions, and the rows blocking the boot-time NULL-safe index tightenings — a read-only inventory as JSON on stdout. Renumbers nothing and writes no row and no schema; run it before the boot-time tenancy repair, which overwrites part of the evidence |
14711485
14721486
**The boot itself writes no row and no schema you did not ask for.** Each of these commands boots

0 commit comments

Comments
 (0)