Repository navigation
Expand file tree
/
Copy pathprotocol-environment-rows.ts
More file actions
352 lines (339 loc) · 19.4 KB
/
Copy pathprotocol-environment-rows.ts
File metadata and controls
352 lines (339 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#25467 cut 35] The environment's own `sys_metadata` rows (ADR-0131
* D6/D7), from `ObjectStackProtocolImplementation`, moved out of
* `protocol.ts` whole:
*
* - `findEnvironmentRows` — the family read, without a legacy
* organization's rows;
* - `findEnvironmentRow` — the same for one row;
* - `findServedOverlayRow` — the stored row a by-name read serves;
* - `packagelessAddress` — the package a write that names none addresses.
*
* [#28238] Beside them, `packagelessContentPackage`: the package a by-name
* read that names none takes its stored content from, given that address and
* the code packages that ship the name. Not a moved body: the rule the two
* by-name reads share. [#28409] …and `shippingPackageIds` /
* `soleShippingPackage`, the code packages that ship a name, read one way by
* those reads and by the env-wide list. [#28802] …and
* `baseAddressServesMember`, the member grain both apply to a bundle.
*
* A MOVE, not a redesign. Each function below is the body of the
* `ObjectStackProtocolImplementation` method of the same name as it stood,
* re-indented one level and otherwise unedited.
*
* ## How the moved bodies reach the class
*
* The shape #23050 set for `rest-server.ts` (its `data-action-routes.ts`
* header carries the full reasoning), as `protocol-batch-data.ts` applies it.
* The class keeps each method — the published `dist/*.d.ts` lists its name,
* docblock and declared signature — and its body is one literal of exactly
* the {@link EnvironmentRowsHost} members it reads, plus a `.call`. The `engine`
* field is handed over as a getter, so each read reaches the class field as
* it stands at call time; each call to another member is a closure, so it
* still reaches the class method.
* Every caller keeps calling the class methods.
*
* The read-seam census follows both directions of this shape (its
* `HOST_SPLIT` note in `scripts/check-durability-degradation-log-level.mjs`),
* so the storage reads below are still counted as the seams they were.
*
* What the bodies read from elsewhere, they import from where `protocol.ts`
* imports it. Nothing re-exports this module, so the published surface does
* not move.
*/
import { isPairOf, type InstalledManifestLookup } from '@objectstack/metadata-core';
import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared';
import type { StoredOverlayRow } from './item-lock.js';
import { overlayMemberWhere } from './migrations/overlay-index.js';
import type { ObjectStackProtocolImplementation } from './protocol.js';
import { rowMatchesOverlayWhere, servedOverlayRowCandidates } from './protocol.js';
import { holdsServedOverlayCandidate } from './protocol-overlay-merge.js';
import { installedManifestsOfEngine } from './installed-manifests.js';
/**
* The `ObjectStackProtocolImplementation` members the functions below read —
* every one of them, and no other; each function's `this` is the `Pick` of
* the members it reads. Each is typed AS the class member (an indexed access
* on the class), so a change to a member's signature on the class is a change
* here too, and naming a member the class does not have is a compile error.
*/
export interface EnvironmentRowsHost {
readonly engine: ObjectStackProtocolImplementation['engine'];
readonly findEnvironmentRow: ObjectStackProtocolImplementation['findEnvironmentRow'];
readonly findEnvironmentRows: ObjectStackProtocolImplementation['findEnvironmentRows'];
readonly shippedArtifactsOf: ObjectStackProtocolImplementation['shippedArtifactsOf'];
readonly legacyOrganizationRowsOf: ObjectStackProtocolImplementation['legacyOrganizationRowsOf'];
readonly rethrowUnlessMetadataStoreUnprovisioned: ObjectStackProtocolImplementation['rethrowUnlessMetadataStoreUnprovisioned'];
readonly withoutLegacyOrganizationRows: ObjectStackProtocolImplementation['withoutLegacyOrganizationRows'];
}
/** The body of `ObjectStackProtocolImplementation#findEnvironmentRows`; the method's docblock there is its contract. */
export async function findEnvironmentRows(this: Pick<EnvironmentRowsHost, 'engine' | 'legacyOrganizationRowsOf' | 'withoutLegacyOrganizationRows'>, table: string, query: { where: Record<string, unknown>; context?: unknown; [key: string]: unknown }): Promise<any[]> {
const rows = (await this.engine.find(table, query as never)) as any[] | null | undefined;
if (query.limit === undefined && query.offset === undefined) {
return this.withoutLegacyOrganizationRows(table, rows, query.context);
}
// An offset counts rows before the page, so any legacy row can shift
// it; a limit alone, only one the page itself holds.
if ((!rows || rows.length === 0) && query.offset === undefined) return rows ?? [];
const legacy = await this.legacyOrganizationRowsOf(table, query.context);
if (legacy.size === 0) return rows ?? [];
if (query.offset === undefined && !(rows ?? []).some((row) => legacy.has(String(row?.id)))) return rows ?? [];
const where = { $and: [query.where, { id: { $nin: [...legacy.keys()] } }] };
return ((await this.engine.find(table, { ...query, where } as never)) as any[] | null | undefined) ?? [];
}
/** The body of `ObjectStackProtocolImplementation#findEnvironmentRow`; the method's docblock there is its contract. */
export async function findEnvironmentRow(this: Pick<EnvironmentRowsHost, 'engine' | 'legacyOrganizationRowsOf'>, table: string, query: { where: Record<string, unknown>; context?: unknown; [key: string]: unknown }): Promise<any> {
const row = await this.engine.findOne(table, query as never);
if (!row) return row ?? null;
const legacy = await this.legacyOrganizationRowsOf(table, query.context);
if (!legacy.has(String((row as { id?: unknown }).id))) return row;
const rows = (await this.engine.find(table, query as never)) as any[] | null | undefined;
return (rows ?? []).find((r) => !legacy.has(String(r?.id))) ?? null;
}
/** The body of `ObjectStackProtocolImplementation#findServedOverlayRow`; the method's docblock there is its contract. */
export async function findServedOverlayRow(
this: Pick<EnvironmentRowsHost, 'engine' | 'findEnvironmentRow' | 'findEnvironmentRows' | 'shippedArtifactsOf'>,
args: {
type: string;
name: string;
state: 'active' | 'draft';
/** [#23715] `null`: the package-unbound row alone (see {@link servedOverlayRowCandidates}). */
packageId?: string | null;
/** [#22877] The bundle member a by-name door's selector named; omitted, the canonical one. */
member?: string;
/** [#28409] The package's declared override first — see {@link servedOverlayRowCandidates}. */
servedOverride?: boolean;
},
activeRows?: readonly StoredOverlayRow[],
): Promise<{ row: any; overrideOf?: string } | undefined> {
// [#21804] The order is {@link servedOverlayRowCandidates}, the one
// the list's merge takes over the rows it read: the canonical
// spelling then the other, and within each, the package's
// own row then the package-less row (never another package's, or a
// collision would serve package B's customization for a package A
// read); with no package context (legacy/runtime reader), any row.
const other = PLURAL_TO_SINGULAR[args.type] ?? SINGULAR_TO_PLURAL[args.type];
const installed = installedManifestsOfEngine(this.engine);
// [#31593] The code packages that ship the item, read once, when a
// moved edit of it can be a candidate (`suite-moved-overlay.ts`).
let shippers: ReadonlySet<string> | undefined;
const ships = (packageId: string): boolean => {
shippers ??= shippingPackageIds(this.shippedArtifactsOf(args.type, args.name, undefined, args.member));
return shippers.has(packageId);
};
for (const candidate of servedOverlayRowCandidates({ packageId: args.packageId, servedOverride: args.servedOverride, installed, ships })) {
const type = candidate.spelling === 'canonical' ? args.type : other;
if (type === undefined) continue;
const where: Record<string, unknown> = {
type, name: args.name, state: args.state,
// [#22877] A by-name read of a bundled type answers the member
// its selector named, else its CANONICAL member, as the
// registry's bare-name read does; nothing for every other type.
...overlayMemberWhere(type, args.member),
};
if (candidate.packageId !== undefined) where.package_id = candidate.packageId;
if (candidate.moved === 'base') {
// [#31593] A row bound to a former owner of the item, at any
// binding: every row of the item is read and the predicate
// picks; two former owners' rows are never guessed between.
const rows = activeRows !== undefined && args.state === 'active'
? activeRows.filter((stored) => rowMatchesOverlayWhere(stored, where))
: await this.findEnvironmentRows('sys_metadata', { where, context: { isSystem: true } });
const moved = (rows ?? []).filter((row) => holdsServedOverlayCandidate(candidate, row, installed, ships));
if (moved.length === 1) return { row: moved[0], overrideOf: candidate.overrideOf };
continue;
}
// [#21911, ADR-0096] The explicit system opt-in: a platform store
// read, which no caller's grants scope — the door that asked
// already authorized the caller, and the protocol scopes the row
// itself ({@link findEnvironmentRow}: the environment's rows only).
// It no longer reaches the data engine as a principal-less context.
const row = activeRows !== undefined && args.state === 'active'
? activeRows.find((stored) => rowMatchesOverlayWhere(stored, where))
: await this.findEnvironmentRow('sys_metadata', { where, context: { isSystem: true } });
if (!row) continue;
// [#28409, ADR-0146 D8 item 2] The pair's row holds the override
// candidate only when it declares the override of the address's
// package ({@link isServedOverrideRowOf}, on the row's own binding and
// body): an undeclared row of the pair is the pair's own item.
// [#31593] …and the moved-override candidate only when its body
// declares a former owner of the item ({@link isMovedOverrideRowOf}).
if (candidate.overrideOf !== undefined) {
if (holdsServedOverlayCandidate(candidate, row, installed, ships)) return { row, overrideOf: candidate.overrideOf };
continue;
}
return { row };
}
return undefined;
}
/** The body of `ObjectStackProtocolImplementation#packagelessAddress`; the method's docblock there is its contract. */
export async function packagelessAddress(
this: Pick<EnvironmentRowsHost, 'findEnvironmentRows' | 'rethrowUnlessMetadataStoreUnprovisioned'>,
type: string,
name: string,
member?: string,
state: 'active' | 'draft' = 'active',
activeRows?: readonly StoredOverlayRow[],
): Promise<{ packageId: string | null; candidates: readonly string[]; unbound: boolean }> {
let rows: Array<{ package_id?: unknown }> | null | undefined;
const where = { type, name, state, ...overlayMemberWhere(type, member) };
try {
// [#21911] The explicit system opt-in — see findServedOverlayRow.
rows = activeRows !== undefined && state === 'active'
? activeRows.filter((row) => rowMatchesOverlayWhere(row, where))
: await this.findEnvironmentRows('sys_metadata', { where, context: { isSystem: true } });
} catch (error) {
// [#5532] An unprovisioned store holds no row, so no binding; any
// other failure is a read that did not happen, never "no binding".
this.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata');
}
const bindings = new Set<string>();
let unbound = false;
for (const row of rows ?? []) {
if (typeof row?.package_id === 'string' && row.package_id !== '') bindings.add(row.package_id);
else unbound = true;
}
const candidates = [...bindings].sort();
return { packageId: candidates.length === 1 ? candidates[0] ?? null : null, candidates, unbound };
}
/**
* [#28238, ADR-0048 §3.3] The package a by-name read that names no package
* takes its stored CONTENT from: {@link findServedOverlayRow}'s `packageId`
* for {@link ObjectStackProtocolImplementation.getMetaItem} and
* {@link ObjectStackProtocolImplementation.getMetaItemLayered}, so the plain
* read and the layered read's `effective` serve one row.
*
* `address` is the item's package-less write address
* ({@link packagelessAddress}, at `active`); `shipped` is every artifact an
* installed code package registered under the name
* (`ObjectStackProtocolImplementation#shippedArtifactsOf`). The code packages
* that ship the name are candidates of the address beside the stored rows'
* bindings:
*
* - no code package ships the name, or the one package the stored rows are
* bound to ships it: the write address's package, as before (#23291) —
* else `undefined`, any row, the best-effort first match;
* - exactly one code package ships it: that package. Its own stored row,
* else the package-unbound row (ADR-0005), else its code item. A row bound
* to another package, the only stored row of a dependent package that saved
* the same name, is never served for it: that row stood in for the base's
* item on every read naming no package and in the base's own app;
* - several ship it, and no stored row is bound to one of them: `null`, the
* package-unbound row alone, else the code item the registry answers;
* several ship it and a row is bound to one: `undefined`, as before.
*
* Content only, and the read's alone. The write address does not move: a
* save, a delete and the read's `version` still resolve
* {@link packagelessAddress}'s `packageId`.
*/
export function packagelessContentPackage(
address: { readonly packageId: string | null; readonly candidates: readonly string[] },
shipped: readonly unknown[],
): string | null | undefined {
const shippers = shippingPackageIds(shipped);
if (shippers.size === 0 || (address.packageId !== null && shippers.has(address.packageId))) {
return address.packageId ?? undefined;
}
if (shippers.size === 1) return [...shippers][0];
return address.candidates.some((id) => shippers.has(id)) ? undefined : null;
}
/**
* [#28238, #28409] The code packages `shipped` belongs to — every artifact an
* installed code package registered under one name
* (`ObjectStackProtocolImplementation#shippedArtifactsOf`), by its
* `_packageId`, the `'sys_metadata'` sentinel left out. The candidates
* {@link packagelessContentPackage} weighs for the by-name reads, and the set
* the env-wide list asks for the same name ({@link soleShippingPackage}), so
* the two read the code packages that ship a name one way.
*/
export function shippingPackageIds(shipped: readonly unknown[]): ReadonlySet<string> {
const shippers = new Set<string>();
for (const artifact of shipped) {
const id = (artifact as { _packageId?: unknown } | null | undefined)?._packageId;
if (typeof id === 'string' && id !== '' && id !== 'sys_metadata') shippers.add(id);
}
return shippers;
}
/**
* [ADR-0150 D4, #32552] Whether `judge` holds for SOME code package that ships
* `(type, name)`: the package the bare-name artifact lookup answers first (the
* one-holder answer, read alone while it holds), then every shipper
* ({@link shippingPackageIds} over `shippedArtifactsOf`).
*
* The question a pair's row asks of its base — is this row a declared
* override of the item, may this removal or restore treat it as one — when two
* namespaces' packages each ship the name (ADR-0150 D9): each holder has its
* own pair, so a row is judged against its own base, never against whichever
* shipper registered first. No shipper is picked: the row judged is the one
* its own `package_id` names. A name one package ships answers exactly as the
* bare lookup alone did.
*/
export function someShipperOf(
host: {
packagedArtifactOwner(request: { type: string; name: string }): string | undefined;
shippedArtifactsOf(type: string, name: string): unknown[];
},
type: string,
name: string,
judge: (basePackageId: string | undefined) => boolean,
): boolean {
if (judge(host.packagedArtifactOwner({ type, name }))) return true;
return [...shippingPackageIds(host.shippedArtifactsOf(type, name))].some((shipper) => judge(shipper));
}
/**
* [ADR-0146 D11] The READ-ONLY code packages that ship a name, sorted: the
* {@link shippingPackageIds} of `shipped` less every package
* `isWritablePackage` answers for — a writable package's item is edited in
* place (ADR-0070) and has no pair (ADR-0146 D3), and the pair itself is
* writable. ONE reading for both halves of D11: the bases
* `os migrate packageless-overlays` classifies a package-less row against,
* and the bases whose package-less write the doors close
* (`packagelessOverlayWriteRefusal`), so the close never reaches a name the
* ceremony would call environment metadata, nor misses one it would move.
*/
export function readOnlyShippingPackages(
shipped: readonly unknown[],
isWritablePackage: (packageId: string) => boolean,
): string[] {
return [...shippingPackageIds(shipped)].filter((id) => !isWritablePackage(id)).sort();
}
/**
* [#28409, ADR-0146 D8 items 1–2] The one code package that ships a name, or
* `undefined` when none or several do: the case in which
* {@link packagelessContentPackage} answers that package for every stored row
* the name has. The env-wide list (`readFlattenedMetaItems`, naming no
* package) then lists the name once, as that package's item, which is what
* the by-name read naming no package serves: a row another package stored
* under the name is that package's own item, served under its own address
* (the read naming it, the list scoped to it), never a second item of the
* name beside the base's. Several packages that ship a name keep one item
* each (ADR-0048 §3.3), as the by-name read keeps its best-effort answer.
*/
export function soleShippingPackage(shipped: readonly unknown[]): string | undefined {
const shippers = shippingPackageIds(shipped);
return shippers.size === 1 ? [...shippers][0] : undefined;
}
/**
* [#28802, ADR-0146 D2, #28390 ruling A] Whether the address of `base`, a
* code package that ships a bundle's name (a type in
* `ITEM_KEY_DISCRIMINATORS`), serves a member of that name bound to `bound`.
* Member grain: the base's own members and a member bound to no package, and
* the pair's own ADDED members, a member of the name the base does not ship
* (`baseShipsMember` false), as the pair is the customer layer the base's
* address serves. A member another package binds under the base's name (a
* dependent's addition) is that package's own item, served under its own
* address only: "a dependent adds items under its own names". So is a pair's
* undeclared row at a member the base ships (refused at the write gate since
* PR #28777). A declared override is served as the base's item by the
* served-row resolution and is never asked about here.
*/
export function baseAddressServesMember(
base: string,
bound: string | undefined,
baseShipsMember: boolean,
installed: InstalledManifestLookup,
): boolean {
if (bound === undefined || bound === base) return true;
if (baseShipsMember) return false;
return isPairOf(bound, base, installed);
}