Skip to content

Commit 41106b5

Browse files
feat(runtime)!: refuse runtime package changes when replicas are declared on the Redis driver (#31751)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi968N7B64dDN7Noq8Fj3QSME)_ Fixes #31599 Maintainer ruling D1 on cloud#3814: 「多副本时拒绝」. Claim 6727421428 (`domain:server#4`, card-thread session_01ADHkmPnqZD15YnBkNbm1jJ), as amended by 6728532665; seat rulings A on the three open questions (one code, R6-style recipe wording, runtime's own ledger row). Clause-②: yes (narrowing) — narrowed: the seven runtime package doors (`POST /api/v1/packages`, `PATCH …/:id/enable`, `PATCH …/:id/disable`, `POST …/:id/duplicate`, `POST …/:id/ensure-customization`, `PATCH …/:id`, `DELETE …/:id`) answer `409 MULTI_REPLICA_PACKAGE_CHANGE_REFUSED` before anything is written when the deployment declares several replicas (`OS_CLUSTER_REPLICAS` greater than 1, or `OS_EXPECT_MULTI_NODE=true`) and the composed cluster service runs the `redis` driver; `POST /api/v1/automation/:name/clone` and `POST /api/v1/security/permission-sets/:name/clone` answer the same only when their default landing would create the source's paired customization package on this replica. Measured by the ablation that removes the condition (the base behaviour): every refused door answered `2xx` and ran its writer on base. Every other topology is unchanged. Widened: `ERROR_CODE_LEDGER` (`@objectstack/spec`) registers the already-registered code under `@objectstack/runtime` too (one row per emitting package); nothing is removed or renamed. A registered ledger row is a published schema, so this PR takes a `CONTRACT_REVIEW_TIER` review. Metadata-protocol: none ## 维护者速读 - 改了什么:部署声明了多副本(`OS_CLUSTER_REPLICAS` 大于 1 或 `OS_EXPECT_MULTI_NODE=true`)且集群驱动是 Redis 时,运行时的 7 个包门(安装、启用、停用、复制、确保定制包、改清单、删除)直接返回 409 `MULTI_REPLICA_PACKAGE_CHANGE_REFUSED`,提示在维护窗口里单副本或用 CLI 操作、再重启所有副本;流程和权限集的"新建相似"只在需要新建配对定制包时才拒绝。 - 为什么改:包注册表只在启动时读,启用/停用状态按副本各自保存,所以运行时改包只改到处理请求的那一个副本,其他副本看不到,重启后还会各自不同。维护者 D1 裁决「多副本时拒绝」。 - 风险与回滚:只在"声明多副本 + Redis 驱动"时生效;单节点、内存驱动、没有集群服务时字节不变;发布/草稿/回滚等元数据写门写共享库,不拒绝。回滚即 revert 本 PR。 - 先看:`packages/runtime/src/multi-replica-package-refusal.ts`(新文件,复用 #31602 落地的 `declaresMultiReplicaOnRedis`);`domains/packages.ts` 7 处调用点;`automation.ts` 与 `permission-set-clone.ts` 的两处克隆门;账本新增的一行。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/domains/packages-capability-gate.test.ts src/domains/automation-flow-clone-custom-package.test.ts src/domains/permission-set-clone.test.ts` —— 预期 209 passed,其中本卡新增 64 个。 - 需要你做的:无,席位落地(账本新增一行走 CONTRACT_REVIEW_TIER 复核)。 ## What changes Step 0, the doors that change the package registry or the per-replica package state, read on `cae8d8fe`: | Door | Handler | What it writes today | |---|---|---| | `POST /packages` | `handlePackagesRequest` install branch | `protocol` install or `registry.installPackage`: a package in this replica's registry | | `PATCH /:id/enable`, `/:id/disable` | same, enable/disable | `writePackageState`: the host store, or `OS_HOME/package-state/<env>.<project>.json` on this replica's volume; then the registry switch | | `POST /:id/duplicate` | same | `protocol.duplicatePackage`: a new package | | `POST /:id/ensure-customization` | same | `protocol.ensureCustomizationPackage`: the pair package | | `PATCH /:id` | same, manifest edit | `protocol.updatePackage` (`sys_packages` + registry) or `registry.updatePackageManifest` | | `DELETE /:id` | same | `registry.uninstallPackage` + `sys_metadata` removal | | `POST /automation/:name/clone` | `resolveCloneTarget` → `land` | ensures `<base>.custom` when the default landing needs it | | `POST /security/permission-sets/:name/clone` | `resolveDefaultCloneLanding` | same | - **`packages/runtime/src/multi-replica-package-refusal.ts`** (new) — `packageChangeReachesOneReplica` reads the composed `cluster` service's driver per request and asks `declaresMultiReplicaOnRedis(process.env, driver)` from `@objectstack/service-cluster` (landed by #31602). `refuseMultiReplicaPackageChange` answers `409` with the code and the recipe ("make the change in a maintenance window: run it on a single replica or through the CLI, then restart every replica"). `multiReplicaPairCreationRefusal` refuses a clone only when this replica's registry does not hold the pair yet. - **`packages/runtime/src/domains/packages.ts`** — the refusal at each of the seven doors right after `requireManageMetadata` and the walled-catalog refusal, before the body is judged or anything is read or written. - **`packages/runtime/src/domains/automation.ts`**, **`permission-set-clone.ts`** — the pair-creation refusal right before the ensure. The flow door asks it inside `land`, after the engine has accepted the copy, so a refusal withdraws the registration as a refused landing already does; the permission-set door asks it through a `beforeEnsure` hook and throws a `409` the door's existing envelope renders. - **`packages/spec/src/api/error-code-ledger.zod.ts`** — `MULTI_REPLICA_PACKAGE_CHANGE_REFUSED` under `@objectstack/runtime` (seat ruling: one row per emitting package, no second waiver). The code was already in the union, so no reference doc changes (`check:docs` green). - **Tests** — in the existing harnesses (shared-harness rule), each a new top-level `describe`: `packages-capability-gate.test.ts` (the `make()` fake kernel gains an optional `cluster` service), `automation-flow-clone-custom-package.test.ts` and `permission-set-clone.test.ts` (each `boot` gains `clusterDriver`). No existing case changed. - **`.changeset/31599-runtime-package-doors-multi-replica-refusal.md`** — `patch` for `@objectstack/runtime` and `@objectstack/spec`; both declaration lines; `adr-0087: not-required (no-migration-prescription)`; Before / Now / Unchanged / Who sees it. ## Tests - Package doors, for each declaration (`OS_CLUSTER_REPLICAS=3`, `OS_EXPECT_MULTI_NODE=true`) on `redis`, each of the seven doors: `409` with the code, the message names the maintenance window and "restart every replica", none of the registry or protocol writers ran, and `OS_HOME` stays empty (no package-state file). An `isSystem` caller is refused too; a caller without `manage_metadata` still gets the `403` first. - CONTROLs, each of the seven doors runs its writer as before: a single node on `redis`, `OS_CLUSTER_REPLICAS=1` on `redis`, declared replicas on the in-process driver (escape hatch), declared replicas with no cluster service. On a single node, disable writes `OS_HOME/package-state`, so the "nothing written" check would see a write. - Unchanged: the five metadata write doors of the same table (publish-drafts, discard-drafts, commit revert, rollback, adopt-orphans) are not refused under declared replicas on `redis`. - Flow clone (real `ObjectQL` + `ObjectStackProtocolImplementation` rig): `409` when the pair is absent (no pair installed, nothing published, no row, the copy's registration withdrawn); `200` into an existing pair; `200` for an explicit writable target; CONTROLs on a single node and on the in-process driver. - Permission-set clone: `409` when the pair is absent (no ensure, no save); `200` into an existing pair; environment-authored source and explicit target `200` with no ensure; CONTROLs on a single node, the in-process driver and no cluster service. ## Acceptance notes - **Not refused, by design.** publish, publish-drafts, discard-drafts, revert, rollback, `commits/:commitId/revert` and adopt-orphans write the shared metadata store, which every replica reads (and the metadata cluster bridge fans out). The CLI's `os plugin disable` (`plugin-installation-store`) is the recipe's own path and is not an HTTP door. - **The clone doors refuse narrowly.** Copying into a pair this replica already serves, or into an explicit writable target, creates no package, so it lands as before. A pair created on another replica only would still be "absent" here and refused, which is the safe answer. - **Protocol-internal ensure callers** inside `@objectstack/metadata-protocol` are outside the claimed surface and are not touched. - **The recipe's wording** follows R6 (#31602) and names the CLI and a single replica; it is one function, `multiReplicaPackageChangeMessage`. ## Verification Head `5eb211c4` (fix `6a362f63`, tests and changeset `cecb6bff`, the collection-time import the test-source-alias gate asks for `5eb211c4`), cut on `origin/main` `cae8d8fe`; `main` has since moved 7 commits, none touching a file this PR changes. <details><summary>Suites (os-verify-lock, every VERDICT command-exit 0)</summary> - `pnpm --filter @objectstack/runtime test`: 563 files / 9117 passed, 19 skipped (`cecb6bff`); `typecheck` exit 0; the edited suite rerun on `5eb211c4`: 134 passed. - `pnpm --filter @objectstack/service-cluster test`: 10 files / 128 tests. - `pnpm --filter @objectstack/spec test`: 823 files / 26079 passed, 1 skipped, 1 todo. `typecheck`: exit 0 with `NODE_OPTIONS=--max-old-space-size=8192`; at the script's default 4096 its `check:test-typecheck` leg ran out of heap in this container before reporting (no diagnostics; the diff to `spec` is one ledger string). - `pnpm --filter @objectstack/spec check:docs`: exit 0, 246 generated files in sync. - `pnpm --filter @objectstack/dogfood test` (full battery, narrowing arm): 440 passed, 3 skipped files / 3652 passed, 41 skipped tests (`5eb211c4`). - Lint (`eslint --no-inline-config`) on `packages/runtime/src` and the ledger file: exit 0. </details> <details><summary>Ablations (negative pins)</summary> `scripts/ablation-replace.mjs` on `cecb6bff`; the tests import the runtime from `src`, so no rebuild leg. - Marker `ABLATED_31599`: `packageChangeReachesOneReplica` always answers `false` (the base behaviour). **19 of 209 red**, exactly the refusal cases: 14 package-door cases (7 doors × 2 declarations), the `isSystem` case, and the two clone doors × 2 declarations. Every CONTROL and every unchanged case green. Restored: blob `aad86398` == HEAD, `git diff HEAD` empty. - Marker `ABLATED_31599_PAIR`: the existing-pair exemption removed. **2 of 75 red**, exactly the two "pair already served is reused" cases. Restored, blob == HEAD. </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 93 families, each run with stdin closed and its exit recorded; `--ran` reconciliation: "93 derived famil(ies) accounted for — 93 run, 0 NOT-MEASURED". All 93 exit 0, among them `check:error-code-provenance`, `check:error-code-casing`, `check:dispatcher-error-vocabulary`, `check:error-status-conformance`, `check:route-envelope` and `check:changeset-no-major`. The first pass on `cecb6bff` had five `spec` surface gates at exit 3 (no `spec` declarations built; green after `pnpm --filter @objectstack/spec build`) and `check:test-source-alias` red (the edited packages suite reaches `@objectstack/metadata` during collection; fixed in `5eb211c4` with the module-top import the gate prescribes, then green). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmPnqZD15YnBkNbm1jJ)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5f26be2 commit 41106b5

9 files changed

Lines changed: 650 additions & 11 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/runtime': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
feat(runtime)!: the runtime package doors refuse to change packages when the deployment declares several replicas on the Redis cluster driver, instead of changing the one replica that served the request
7+
8+
Clause-②: yes (narrowing) — narrowed: `POST /api/v1/packages`, `PATCH /api/v1/packages/:id/enable`, `PATCH /api/v1/packages/:id/disable`, `POST /api/v1/packages/:id/duplicate`, `POST /api/v1/packages/:id/ensure-customization`, `PATCH /api/v1/packages/:id` and `DELETE /api/v1/packages/:id` now answer `409 MULTI_REPLICA_PACKAGE_CHANGE_REFUSED`, right after the caller is admitted (the `manage_metadata` gate and the walled-catalog refusal still answer first) and before the body is judged or anything is written, when the deployment declares several replicas (`OS_CLUSTER_REPLICAS` greater than 1, or `OS_EXPECT_MULTI_NODE=true`) and the composed cluster service runs the `redis` driver; `POST /api/v1/automation/:name/clone` and `POST /api/v1/security/permission-sets/:name/clone` answer the same `409` under the same condition only when their default landing would create the source's paired customization package on this replica. Nothing is written: no package, no package-state file, no metadata row. On a single node, on the in-process driver or with no cluster service composed, every door answers exactly as before. Widened: `ERROR_CODE_LEDGER` (`@objectstack/spec`) registers `MULTI_REPLICA_PACKAGE_CHANGE_REFUSED` under `@objectstack/runtime` too (one row per emitting package; the code itself is unchanged); nothing is removed or renamed.
9+
Metadata-protocol: none
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped and no export is removed: a request that changed one replica's package registry or enable/disable state is now refused, with an already registered error code, only on a deployment that declares replicas on the Redis driver. There is nothing for a migration to rewrite and no tombstone. -->
12+
13+
**BREAKING** for a multi-replica deployment on the Redis cluster driver that installs, enables, disables, duplicates, edits or deletes packages at runtime (Studio's package pages, the Console, the SDK or the HTTP doors), or clones a packaged flow or permission set whose customization package does not exist yet.
14+
15+
- **Before.** The package registry is read from the database at boot only, so a package created, installed, edited or deleted at runtime was seen by the serving replica alone until every other replica restarted; the enable/disable choice was written to the serving replica's own package-state store (a file under its own `OS_HOME` when the host registers none), so restarted replicas could serve different packages for good.
16+
- **Now.** Those doors refuse with `MULTI_REPLICA_PACKAGE_CHANGE_REFUSED` (409), the code the marketplace install-local doors already answer under the same condition, and name the maintenance-window recipe: make the change on a single replica or through the CLI, then restart every replica. A clone whose customization package already exists on the replica, or which names a writable target, still lands, since it creates no package.
17+
- **Unchanged.** A single node, or replicas declared on any driver other than `redis`, change packages as before. The metadata write doors (publish, publish-drafts, discard-drafts, revert, rollback, commit revert, adopt-orphans) write the shared store and are not refused. The split-brain guard is untouched.
18+
- **Who sees it.** An administrator of a multi-replica deployment on the Redis cluster driver who changes packages at runtime, or who clones a packaged flow or permission set before its customization package exists.
19+
20+
The condition is `@objectstack/service-cluster`'s `declaresMultiReplicaOnRedis`, read per request from the composed `cluster` service's driver.

‎packages/runtime/src/domains/automation-flow-clone-custom-package.test.ts‎

Lines changed: 163 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,12 @@
3535

3636
// Pays `@objectstack/metadata`'s first load at collection, never inside a clocked case.
3737
import '@objectstack/metadata';
38-
import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest';
38+
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest';
3939
import { mkdtempSync, rmSync } from 'node:fs';
4040
import { tmpdir } from 'node:os';
4141
import { join } from 'node:path';
4242
import { ObjectQL } from '@objectstack/objectql';
43+
import { MULTI_REPLICA_PACKAGE_CHANGE_REFUSED } from '@objectstack/service-cluster';
4344
import { SqlDriver } from '@objectstack/driver-sql';
4445
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
4546
import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata';
@@ -110,7 +111,18 @@ interface Answer {
110111
* protocol refuses (an illegal machine name among it) throws the way the real
111112
* engine throws. The default rig's engine is a map that accepts anything.
112113
*/
113-
async function boot(options: { parse?: boolean; baseScope?: 'system' | 'cloud' } = {}) {
114+
/**
115+
* [cloud#3814 D1] An installed App and a read-only member of it shipping
116+
* {@link SUITE_FLOW}: the member's pair is its App's, `com.acme.suite.custom`
117+
* (ruling 6691022506). `legacyMemberPair` also installs the per-package pair
118+
* an earlier version created for the member.
119+
*/
120+
const SUITE_APP = { id: 'com.acme.suite', name: 'Suite', version: '2.0.0', type: 'app', namespace: 'suite' };
121+
const SUITE_MEMBER = { id: 'com.acme.suite-crm', name: 'Suite CRM', version: '2.0.0', type: 'module', namespace: 'suitecrm', dependencies: { [SUITE_APP.id]: '^2' } };
122+
const SUITE_PAIR = 'com.acme.suite.custom';
123+
const SUITE_FLOW = 'suite_lead_route';
124+
125+
async function boot(options: { parse?: boolean; baseScope?: 'system' | 'cloud'; clusterDriver?: string; appMember?: boolean; legacyMemberPair?: boolean } = {}) {
114126
const engine = new ObjectQL();
115127
liveEngines.push(engine);
116128
engine.registerDriver(new SqlDriver({
@@ -133,14 +145,25 @@ async function boot(options: { parse?: boolean; baseScope?: 'system' | 'cloud' }
133145
// The base's flow, registered as the loader registers a package's flow.
134146
const shipped = { ...flowOf(SOURCE), _packageId: BASE.id, _packageVersion: BASE.version, _provenance: 'package' };
135147
engine.registry.registerItem('flow', shipped as any, 'name' as any, BASE.id);
148+
const suiteShipped = { ...flowOf(SUITE_FLOW), _packageId: SUITE_MEMBER.id, _packageVersion: SUITE_MEMBER.version, _provenance: 'package' };
149+
if (options.appMember) {
150+
for (const m of [SUITE_APP, SUITE_MEMBER]) {
151+
engine.registry.installPackage(m as any, 'code');
152+
(engine as unknown as { manifests: Map<string, unknown> }).manifests.set(m.id, m);
153+
}
154+
if (options.legacyMemberPair) {
155+
engine.registry.installPackage({ id: `${SUITE_MEMBER.id}.custom`, name: 'Legacy pair', version: '2.0.0', type: 'module', namespace: 'suitecrm_custom', dependencies: { [SUITE_MEMBER.id]: '^2' } } as any, 'authored');
156+
}
157+
engine.registry.registerItem('flow', suiteShipped as any, 'name' as any, SUITE_MEMBER.id);
158+
}
136159

137160
const published: unknown[] = [];
138161
const services = new Map<string, unknown>([
139162
['package', { publish: async ({ manifest }: { manifest: unknown }) => { published.push(manifest); return { success: true }; } }],
140163
]);
141164
const protocol = new ObjectStackProtocolImplementation(engine as any, () => services);
142165

143-
const flows = new Map<string, any>([[SOURCE, shipped], [LOCAL, flowOf(LOCAL)]]);
166+
const flows = new Map<string, any>([[SOURCE, shipped], [LOCAL, flowOf(LOCAL)], ...(options.appMember ? [[SUITE_FLOW, suiteShipped] as [string, any]] : [])]);
144167
const registerFlow = vi.fn((name: string, definition: unknown) => {
145168
if (options.parse) FlowSchema.parse(definition);
146169
flows.set(name, definition);
@@ -153,6 +176,7 @@ async function boot(options: { parse?: boolean; baseScope?: 'system' | 'cloud' }
153176
objectql: engine,
154177
automation: { handlerReady: true, registerFlow, unregisterFlow, getFlow },
155178
};
179+
if (options.clusterDriver !== undefined) named.cluster = { driver: options.clusterDriver };
156180
const get = (name: string) => named[name] ?? null;
157181
const kernel: any = { context: { getService: get }, getService: get, getServiceAsync: async (name: string) => get(name) };
158182
const dispatcher = new HttpDispatcher(kernel);
@@ -473,3 +497,139 @@ describe('[#28149] the contract: the ledger row names the schemas this suite par
473497
expect(await rig.rows('ext_status')).toEqual([]);
474498
}, 60_000);
475499
});
500+
501+
describe('[cloud#3814 D1] declared replicas on the Redis driver: a clone that would create the pair is refused', () => {
502+
const ENV = ['OS_CLUSTER_REPLICAS', 'OS_EXPECT_MULTI_NODE'] as const;
503+
const prior: Partial<Record<(typeof ENV)[number], string | undefined>> = {};
504+
beforeEach(() => { for (const k of ENV) { prior[k] = process.env[k]; delete process.env[k]; } });
505+
afterEach(() => {
506+
for (const k of ENV) {
507+
if (prior[k] === undefined) delete process.env[k];
508+
else process.env[k] = prior[k];
509+
}
510+
});
511+
512+
for (const [label, key, value] of [['OS_CLUSTER_REPLICAS=3', 'OS_CLUSTER_REPLICAS', '3'], ['OS_EXPECT_MULTI_NODE=true', 'OS_EXPECT_MULTI_NODE', 'true']] as const) {
513+
it(`${label}: the default landing needs a pair this replica lacks — 409 ${MULTI_REPLICA_PACKAGE_CHANGE_REFUSED}, no package, no row, no registered copy`, async () => {
514+
const rig = await boot({ clusterDriver: 'redis' });
515+
process.env[key] = value;
516+
517+
const answer = await rig.clone(SOURCE, { name: 'acme_lead_followup', label: 'Lead follow-up (ACME)' });
518+
519+
expect(answer.status, JSON.stringify(answer.body)).toBe(409);
520+
expect(answer.code).toBe(MULTI_REPLICA_PACKAGE_CHANGE_REFUSED);
521+
expect(String(answer.body?.error?.message)).toContain(`'${PAIR}'`);
522+
expect(String(answer.body?.error?.message)).toContain('restart every replica');
523+
expect(rig.installed()).not.toContain(PAIR);
524+
expect(rig.published).toEqual([]);
525+
expect(await rig.rows('acme_lead_followup')).toEqual([]);
526+
// The engine accepted the copy before the landing was asked; the
527+
// refused landing withdrew it (the door's own undo).
528+
expect(rig.flows.has('acme_lead_followup')).toBe(false);
529+
}, 60_000);
530+
}
531+
532+
it('a pair this replica already serves is reused: 200, the copy lands there and no package is created', async () => {
533+
const rig = await boot({ clusterDriver: 'redis' });
534+
const first = await rig.clone(SOURCE, { name: 'acme_lead_followup', label: 'First copy' });
535+
expect(first.status, JSON.stringify(first.body)).toBe(200);
536+
const pairsBefore = rig.published.length;
537+
process.env.OS_CLUSTER_REPLICAS = '3';
538+
539+
const second = await rig.clone(SOURCE, { name: 'acme_lead_followup_two', label: 'Second copy' });
540+
541+
expect(second.status, JSON.stringify(second.body)).toBe(200);
542+
expect(second.data.packageId).toBe(PAIR);
543+
expect(rig.published.length).toBe(pairsBefore);
544+
expect((await rig.rows('acme_lead_followup_two')).map((r) => r.package_id)).toEqual([PAIR]);
545+
}, 60_000);
546+
547+
it('an explicit writable target creates no package and is not refused', async () => {
548+
const rig = await boot({ clusterDriver: 'redis' });
549+
process.env.OS_CLUSTER_REPLICAS = '3';
550+
551+
const answer = await rig.clone(SOURCE, { name: 'ext_lead_followup', label: 'Lead follow-up (ext)', package: EXT.id });
552+
553+
expect(answer.status, JSON.stringify(answer.body)).toBe(200);
554+
expect(answer.data.packageId).toBe(EXT.id);
555+
expect(rig.installed()).not.toContain(PAIR);
556+
}, 60_000);
557+
558+
for (const [label, env, driver] of [
559+
['a single node on redis', {}, 'redis'],
560+
['declared replicas on the in-process driver', { OS_CLUSTER_REPLICAS: '3' }, 'memory'],
561+
] as const) {
562+
it(`CONTROL — ${label}: the default landing ensures the pair, as before`, async () => {
563+
const rig = await boot({ clusterDriver: driver });
564+
Object.assign(process.env, env);
565+
566+
const answer = await rig.clone(SOURCE, { name: 'acme_lead_followup', label: 'Lead follow-up (ACME)' });
567+
568+
expect(answer.status, JSON.stringify(answer.body)).toBe(200);
569+
expect(answer.data.packageId).toBe(PAIR);
570+
expect(rig.installed()).toContain(PAIR);
571+
}, 60_000);
572+
}
573+
});
574+
575+
describe('[cloud#3814 D1] declared replicas on the Redis driver: the pair probed is the App\'s pair (pairOf), as the ensure derives it', () => {
576+
const prior = process.env.OS_CLUSTER_REPLICAS;
577+
afterEach(() => {
578+
if (prior === undefined) delete process.env.OS_CLUSTER_REPLICAS;
579+
else process.env.OS_CLUSTER_REPLICAS = prior;
580+
});
581+
582+
it('precondition — the ensure door pairs the member with its App\'s pair, not a per-member one', async () => {
583+
const rig = await boot({ clusterDriver: 'redis', appMember: true });
584+
const ensured = await rig.protocol.ensureCustomizationPackage({ basePackageId: SUITE_MEMBER.id });
585+
expect(ensured.packageId).toBe(SUITE_PAIR);
586+
}, 60_000);
587+
588+
it('a member of an installed App whose pair is absent: 409 naming the App\'s pair, nothing created', async () => {
589+
const rig = await boot({ clusterDriver: 'redis', appMember: true });
590+
process.env.OS_CLUSTER_REPLICAS = '3';
591+
592+
const answer = await rig.clone(SUITE_FLOW, { name: 'acme_suite_route', label: 'Suite route (ACME)' });
593+
594+
expect(answer.status, JSON.stringify(answer.body)).toBe(409);
595+
expect(answer.code).toBe(MULTI_REPLICA_PACKAGE_CHANGE_REFUSED);
596+
expect(String(answer.body?.error?.message)).toContain(`'${SUITE_PAIR}'`);
597+
expect(rig.installed()).not.toContain(SUITE_PAIR);
598+
expect(rig.published).toEqual([]);
599+
expect(await rig.rows('acme_suite_route')).toEqual([]);
600+
}, 60_000);
601+
602+
it('…refused too while only the member\'s legacy per-package pair is installed: the ensure would still create the App\'s', async () => {
603+
const rig = await boot({ clusterDriver: 'redis', appMember: true, legacyMemberPair: true });
604+
process.env.OS_CLUSTER_REPLICAS = '3';
605+
606+
const answer = await rig.clone(SUITE_FLOW, { name: 'acme_suite_route', label: 'Suite route (ACME)' });
607+
608+
expect(answer.status, JSON.stringify(answer.body)).toBe(409);
609+
expect(answer.code).toBe(MULTI_REPLICA_PACKAGE_CHANGE_REFUSED);
610+
expect(rig.installed()).not.toContain(SUITE_PAIR);
611+
expect(rig.published).toEqual([]);
612+
}, 60_000);
613+
614+
it('a member whose App\'s pair this replica already serves is not refused by this card: the door answers as on a single node, and nothing is created', async () => {
615+
// The App's pair, ensured on a single node.
616+
const single = await boot({ clusterDriver: 'redis', appMember: true });
617+
await single.protocol.ensureCustomizationPackage({ basePackageId: SUITE_MEMBER.id });
618+
const singleAnswer = await single.clone(SUITE_FLOW, { name: 'acme_suite_route', label: 'Suite route (ACME)' });
619+
620+
const rig = await boot({ clusterDriver: 'redis', appMember: true });
621+
await rig.protocol.ensureCustomizationPackage({ basePackageId: SUITE_MEMBER.id });
622+
const pairsBefore = rig.published.length;
623+
process.env.OS_CLUSTER_REPLICAS = '3';
624+
625+
const answer = await rig.clone(SUITE_FLOW, { name: 'acme_suite_route', label: 'Suite route (ACME)' });
626+
627+
// Not this card's refusal: the same answer a single node gives (today
628+
// the door's own closure refusal — the App's pair declares the App,
629+
// not the member; outside this card).
630+
expect(answer.code, JSON.stringify(answer.body)).not.toBe(MULTI_REPLICA_PACKAGE_CHANGE_REFUSED);
631+
expect({ status: answer.status, code: answer.code }).toEqual({ status: singleAnswer.status, code: singleAnswer.code });
632+
expect(rig.published.length).toBe(pairsBefore);
633+
expect(rig.installed().filter((id) => id === SUITE_PAIR)).toHaveLength(1);
634+
}, 60_000);
635+
});

‎packages/runtime/src/domains/automation.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ import {
8888
import { CloneFlowRequestSchema } from '@objectstack/spec/api';
8989
import { newSimilarTargetRefusal, newSimilarTargetRefusalAnswer } from './new-similar-target.js';
9090
import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatcher.js';
91+
import { multiReplicaPairCreationRefusal, multiReplicaPackageChangeError } from '../multi-replica-package-refusal.js';
9192
import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js';
9293
import { readDispatchedBody } from '../deferred-request-body.js';
9394
// [#9416, #25821, #25976] The one value-shape check every door that starts or
@@ -2606,6 +2607,10 @@ async function resolveCloneTarget(
26062607
}
26072608
return {
26082609
land: async () => {
2610+
// [cloud#3814 D1] Declared replicas on the Redis driver: creating
2611+
// the pair here would register a package on this replica alone.
2612+
const oneReplica = await multiReplicaPairCreationRefusal(deps, context, await deps.getObjectQL(context), owner, `Cloning ${subject}`);
2613+
if (oneReplica) return { refused: { handled: true, response: deps.errorFromThrown(multiReplicaPackageChangeError(oneReplica)) } };
26092614
let pair: string;
26102615
try {
26112616
pair = (await ensure.call(protocol, { basePackageId: owner })).packageId;

0 commit comments

Comments
 (0)