-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcontract-space-aggregate-loader.ts
More file actions
396 lines (372 loc) · 15.5 KB
/
contract-space-aggregate-loader.ts
File metadata and controls
396 lines (372 loc) · 15.5 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import { readFile } from 'node:fs/promises';
import type { PrismaNextConfig } from '@prisma-next/config/config-types';
import type { Contract } from '@prisma-next/contract/types';
import type { ControlExtensionDescriptor } from '@prisma-next/framework-components/control';
import { createControlStack } from '@prisma-next/framework-components/control';
import type {
ContractSpaceAggregate,
DeclaredExtensionEntry,
IntegrityQueryOptions,
IntegrityViolation,
} from '@prisma-next/migration-tools/aggregate';
import { loadContractSpaceAggregate } from '@prisma-next/migration-tools/aggregate';
import { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';
import { MigrationToolsError } from '@prisma-next/migration-tools/errors';
import { blindCast } from '@prisma-next/utils/casts';
import { notOk, ok, type Result } from '@prisma-next/utils/result';
import { CliStructuredError, errorUnexpected, mapMigrationToolsError } from './cli-errors';
import { readContractEnvelope, resolveContractPath } from './command-helpers';
import { toDeclaredExtensionsFromRaw } from './extension-pack-inputs';
const CONTRACT_SPACES_DOCS_URL = 'https://pris.ly/contract-spaces';
function contractSpaceError5002(
summary: string,
options: {
readonly why: string;
readonly fix: string;
readonly violations: readonly IntegrityViolation[];
},
): CliStructuredError {
return new CliStructuredError('5002', summary, {
domain: 'MIG',
why: options.why,
fix: options.fix,
docsUrl: CONTRACT_SPACES_DOCS_URL,
meta: { violations: options.violations },
});
}
/**
* Build the `5002` structured-error envelope for a contract-space
* target mismatch. Shared between the declared-extension precheck (the
* descriptor's configured target disagrees with the project target) and
* the on-disk-contract check surfaced by `checkIntegrity`.
*/
function targetMismatchError(
spaceId: string,
expected: string,
actual: string,
): CliStructuredError {
return contractSpaceError5002(`Contract-space target mismatch for "${spaceId}"`, {
why: `Space "${spaceId}" targets "${actual}" but the project's adapter targets "${expected}".`,
fix: 'Update the extension descriptor to target the configured database, or change the project adapter.',
violations: [{ kind: 'targetMismatch', spaceId, expected, actual }],
});
}
/**
* Human-readable detail for an integrity violation, used as the `why`
* of the `integrityFailure` envelope. Mirrors the messages the prior
* throw-on-load loader produced so downstream consumers see the same
* text for the same on-disk state.
*/
function describeIntegrityViolation(violation: IntegrityViolation): string {
switch (violation.kind) {
case 'hashMismatch':
return `Migration "${violation.dirName}" stored hash "${violation.stored}" does not match computed hash "${violation.computed}".`;
case 'providedInvariantsMismatch':
return `Migration "${violation.dirName}" providedInvariants in migration.json disagrees with ops.json.`;
case 'packageUnloadable':
return `Migration "${violation.dirName}" could not be loaded: ${violation.detail}`;
case 'sameSourceAndTarget':
return `Migration "${violation.dirName}" has source equal to target (${violation.hash}) with no data invariant — a true no-op self-edge.`;
case 'headRefMissing':
return `Head ref \`refs/head.json\` is missing for contract space "${violation.spaceId}".`;
case 'headRefNotInGraph':
return `Head ref ${violation.hash} for contract space "${violation.spaceId}" is not present in the migration graph.`;
case 'refUnreadable':
return `Ref "${violation.refName}" for contract space "${violation.spaceId}" is unreadable: ${violation.detail}`;
case 'duplicateMigrationHash':
return `Multiple migrations in space "${violation.spaceId}" share migrationHash "${violation.migrationHash}" (${violation.dirNames.join(', ')}).`;
default: {
const spaceId = 'spaceId' in violation ? violation.spaceId : '*';
return `Integrity violation "${violation.kind}" for contract space "${spaceId}".`;
}
}
}
/**
* Map the integrity violations `checkIntegrity` reports into a single
* CLI structured-error envelope, preserving the error codes the prior
* throw-on-load loader emitted: `5001` (layout drift, bundled) and
* `5002` (target / disjointness / contract-validation / structural
* integrity). Returns `null` when there is nothing to refuse on.
*
* Precedence reproduces the prior loader's first-failure ordering:
* layout drift first (every offence bundled into one envelope), then
* target mismatch, then disjointness, then a contract-validation
* failure, then any remaining structural integrity violation.
*/
export function mapIntegrityViolations(
violations: readonly IntegrityViolation[],
): CliStructuredError | null {
if (violations.length === 0) return null;
const layout = violations.filter(
(v): v is Extract<IntegrityViolation, { kind: 'orphanSpaceDir' | 'declaredButUnmigrated' }> =>
v.kind === 'orphanSpaceDir' || v.kind === 'declaredButUnmigrated',
);
if (layout.length > 0) {
const lines = layout.map((v) => `- [${v.kind}] ${v.spaceId}`);
const summary =
layout.length === 1
? 'Contract-space layout violation detected'
: `Contract-space layout violations detected (${layout.length})`;
return new CliStructuredError('5001', summary, {
domain: 'MIG',
why: `The on-disk \`migrations/\` directory and your \`extensionPacks\` declaration are not in agreement.\n${lines.join('\n')}`,
fix: 'Declare the extension in `extensionPacks` and re-emit its contract-space artefacts, or remove the orphan `migrations/<space>` directory.',
docsUrl: CONTRACT_SPACES_DOCS_URL,
meta: { violations: layout },
});
}
const targetMismatch = violations.find((v) => v.kind === 'targetMismatch');
if (targetMismatch && targetMismatch.kind === 'targetMismatch') {
return targetMismatchError(
targetMismatch.spaceId,
targetMismatch.expected,
targetMismatch.actual,
);
}
const disjointness = violations.find((v) => v.kind === 'disjointness');
if (disjointness && disjointness.kind === 'disjointness') {
return contractSpaceError5002(
`Contract-space disjointness violation: storage element "${disjointness.element}" claimed by multiple spaces`,
{
why: `Spaces ${disjointness.claimedBy.map((s) => `"${s}"`).join(', ')} all claim the storage element "${disjointness.element}". Each storage element must be owned by exactly one contract space.`,
fix: 'Update the conflicting contracts so each storage element is claimed by exactly one space.',
violations: [disjointness],
},
);
}
const contractUnreadable = violations.find((v) => v.kind === 'contractUnreadable');
if (contractUnreadable && contractUnreadable.kind === 'contractUnreadable') {
return contractSpaceError5002(
`Contract-space contract validation failed for "${contractUnreadable.spaceId}"`,
{
why: contractUnreadable.detail,
fix: 'Re-emit the extension contract with `prisma-next contract emit`, or fix the extension pack descriptor producing the invalid contract.',
violations: [contractUnreadable],
},
);
}
// Any remaining recoverable structural violation refuses as an
// integrity failure, surfacing the first one's detail (every violation
// is still computed; the gate just renders one envelope).
const structural = violations[0]!;
const spaceId = 'spaceId' in structural ? structural.spaceId : '*';
return contractSpaceError5002(`Contract-space integrity failure for "${spaceId}"`, {
why: describeIntegrityViolation(structural),
fix: 'Re-emit the affected migration package(s) or restore the on-disk `migrations/` directory from version control.',
violations: [structural],
});
}
/**
* Inputs needed to compose the aggregate loader at the CLI surface.
*
* Keeps the loader framework-neutral (no `Config` import) by accepting
* already-resolved structural inputs: validated app contract, target
* id, migrations root directory, and the set of extension descriptors.
*/
export interface BuildAggregateInputs<TFamilyId extends string, TTargetId extends string> {
readonly targetId: TTargetId;
readonly migrationsDir: string;
readonly appContract: Contract;
readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;
readonly deserializeContract: (contractJson: unknown) => Contract;
}
function declaredExtensionsFromInputs(
extensionPacks: BuildAggregateInputs<string, string>['extensionPacks'],
): readonly DeclaredExtensionEntry[] {
return toDeclaredExtensionsFromRaw(extensionPacks as ReadonlyArray<unknown>);
}
/**
* Reject extension descriptors whose configured target disagrees with
* the project target before any on-disk read.
*/
export function refuseDeclaredExtensionTargetMismatch<
TFamilyId extends string,
TTargetId extends string,
>(inputs: BuildAggregateInputs<TFamilyId, TTargetId>): CliStructuredError | null {
for (const declared of declaredExtensionsFromInputs(inputs.extensionPacks)) {
if (declared.targetId !== inputs.targetId) {
return targetMismatchError(declared.id, inputs.targetId, declared.targetId);
}
}
return null;
}
/**
* Load the tolerant {@link ContractSpaceAggregate} once at the CLI
* surface. Construction never throws on disk content; callers query
* {@link ContractSpaceAggregate.app} / extension facets instead of
* re-reading `migrations/`.
*/
export async function loadContractSpaceAggregateForCli<
TFamilyId extends string,
TTargetId extends string,
>(
inputs: BuildAggregateInputs<TFamilyId, TTargetId>,
): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {
const targetFailure = refuseDeclaredExtensionTargetMismatch(inputs);
if (targetFailure) {
return notOk(targetFailure);
}
const aggregate = await loadContractSpaceAggregate({
migrationsDir: inputs.migrationsDir,
deserializeContract: inputs.deserializeContract,
appContract: inputs.appContract,
});
return ok(aggregate);
}
/**
* Run `checkIntegrity` on a loaded aggregate and map violations into
* the contract-space refusal envelope, or return `null` when the model
* is acceptable for the requested check scope.
*/
export function refuseContractSpaceIntegrity(
aggregate: ContractSpaceAggregate,
options: IntegrityQueryOptions,
): CliStructuredError | null {
return mapIntegrityViolations(aggregate.checkIntegrity(options));
}
const PACKAGE_CORRUPTION_KINDS = new Set<IntegrityViolation['kind']>([
'hashMismatch',
'providedInvariantsMismatch',
'packageUnloadable',
]);
/**
* Reader-subset integrity refusal for `migration status`: package
* corruptions only (`hashMismatch`, `providedInvariantsMismatch`,
* `packageUnloadable`).
*/
export function refusePackageCorruptionOnAggregate(
aggregate: ContractSpaceAggregate,
): CliStructuredError | null {
const corruption = aggregate.checkIntegrity().filter((v) => PACKAGE_CORRUPTION_KINDS.has(v.kind));
return mapIntegrityViolations(corruption);
}
/**
* Construct the tolerant {@link ContractSpaceAggregate} at the CLI
* surface and apply the explicit integrity refusal.
*
* App-space migration packages are read from `migrations/<app>/` by the
* loader itself; callers no longer thread them through.
*/
export async function buildContractSpaceAggregate<
TFamilyId extends string,
TTargetId extends string,
>(
inputs: BuildAggregateInputs<TFamilyId, TTargetId>,
): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {
const declaredExtensions = declaredExtensionsFromInputs(inputs.extensionPacks);
const loaded = await loadContractSpaceAggregateForCli(inputs);
if (!loaded.ok) {
return loaded;
}
const failure = refuseContractSpaceIntegrity(loaded.value, {
declaredExtensions,
checkContracts: true,
});
if (failure) {
return notOk(failure);
}
return ok(loaded.value);
}
/**
* Build a minimal app {@link Contract} carrying only the project's
* contract-identity (`storage.storageHash` + `target` / `targetFamily`)
* when the real `contract.json` is absent or undeserializable.
*
* `loadContractSpaceAggregate` requires an `appContract` to synthesise the
* app space's head ref from its storage hash. Read commands query only that
* hash and the target — never `models` — so an empty-`models` stand-in is
* sufficient for them. It is *not* a valid contract for any consumer that
* reads schema, which is why this is confined to the read-aggregate path.
*/
export function appContractStandInFromIdentity(args: {
readonly contractHash: string;
readonly targetId: string;
readonly targetFamily: string;
}): Contract {
return blindCast<
Contract,
'read-aggregate consumers query only storage.storageHash and target; empty models stand in for an unreadable contract.json'
>({
storage: { storageHash: args.contractHash },
schemaVersion: '0.0.0',
target: args.targetId,
targetFamily: args.targetFamily,
models: {},
profileHash: EMPTY_CONTRACT_HASH,
});
}
export async function loadContractRawSafely(config: {
contract?: { output?: string };
}): Promise<unknown | null> {
try {
const path = resolveContractPath(config);
const raw = await readFile(path, 'utf-8');
return JSON.parse(raw);
} catch {
return null;
}
}
/**
* Tolerant {@link ContractSpaceAggregate} assembly for read-only CLI
* commands. No integrity gate — callers query `aggregate.app` (or other
* facets) without re-reading `migrations/`. When `contract.json` is absent
* or undeserializable, the app contract falls back to an identity-only
* stand-in ({@link appContractStandInFromIdentity}), so these commands
* load without requiring a readable contract.
*/
export async function buildReadAggregate(
config: PrismaNextConfig,
options: { readonly migrationsDir: string },
): Promise<
Result<
{ readonly aggregate: ContractSpaceAggregate; readonly contractHash: string },
CliStructuredError
>
> {
let contractHash: string = EMPTY_CONTRACT_HASH;
try {
const envelope = await readContractEnvelope(config);
contractHash = envelope.storageHash;
} catch {
// Contract unreadable — marker uses EMPTY_CONTRACT_HASH
}
try {
const contractRawForAggregate = await loadContractRawSafely(config);
const stack = createControlStack(config);
const familyInstance = config.family.create(stack);
const deserializeContract = (json: unknown): Contract =>
familyInstance.deserializeContract(json);
let appContractForLoad: Contract = appContractStandInFromIdentity({
contractHash,
targetId: config.target.id,
targetFamily: config.target.familyId,
});
if (contractRawForAggregate !== null) {
try {
appContractForLoad = deserializeContract(contractRawForAggregate);
} catch {
// Deserialization failed — identity-only stand-in fallback
}
}
const loaded = await loadContractSpaceAggregateForCli({
targetId: config.target.id,
migrationsDir: options.migrationsDir,
appContract: appContractForLoad,
extensionPacks: config.extensionPacks ?? [],
deserializeContract,
});
if (!loaded.ok) {
return loaded;
}
return ok({ aggregate: loaded.value, contractHash });
} catch (error) {
if (MigrationToolsError.is(error)) {
return notOk(mapMigrationToolsError(error));
}
return notOk(
errorUnexpected(error instanceof Error ? error.message : String(error), {
why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}`,
}),
);
}
}