@arcadia-eternity/content-sdk 4.4.2 → 4.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
3
- import { isAbsolute, join, relative, resolve } from 'node:path';
3
+ import { join, resolve } from 'node:path';
4
4
  import writeFileAtomic from 'write-file-atomic';
5
5
  import semver from 'semver';
6
6
  import { inspectNpmProject } from '@arcadia-eternity/pack-loader/node';
@@ -8,13 +8,8 @@ import { normalizeEnvironmentDocument } from './debug-environments.js';
8
8
  import { withSourceLock } from './source-lock.js';
9
9
  import { contentError, materialFiles, writeMaterials } from './workspace-materials.js';
10
10
  import { errorCode, isRecord } from './types.js';
11
+ export { normalizeEnvironmentDocument } from './debug-environments.js';
11
12
  const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
12
- // npm ls redacts UUID-shaped path components, so opaque logical identities must
13
- // not also be physical directory names.
14
- const versionDirectory = (id) => 'version-' + id.replaceAll('-', '');
15
- const directoryVersion = (name) => /^version-[a-f0-9]{32}$/.test(name)
16
- ? name.slice(8).replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5')
17
- : undefined;
18
13
  const envId = /^[a-z0-9][a-z0-9_-]{0,79}$/;
19
14
  const revision = (text) => createHash('sha256').update(text).digest('hex');
20
15
  const json = (value) => JSON.stringify(value, null, 2) + '\n';
@@ -42,20 +37,21 @@ async function checkedPreparation(result, document, directory) {
42
37
  !(result.packages === undefined || Array.isArray(result.packages)))
43
38
  throw contentError('STATIC_PREPARATION_INVALID');
44
39
  const packages = Array.isArray(result.packages) ? result.packages : [];
40
+ const inspection = await inspectNpmProject(directory);
45
41
  for (const [name, range] of Object.entries(document.packages)) {
46
- const matches = packages.filter(pkg => isRecord(pkg) && pkg.name === name);
47
- if (!semver.validRange(range) ||
42
+ const matches = inspection.packages.filter(pkg => isRecord(pkg) && pkg.name === name);
43
+ if ((!semver.validRange(range) && !/^file:candidates\/[a-zA-Z0-9_.-]+\.tgz$/.test(range)) ||
48
44
  !matches.some(pkg => {
49
45
  if (!isRecord(pkg) || typeof pkg.version !== 'string')
50
46
  return false;
51
- return semver.valid(pkg.version) !== null && semver.satisfies(pkg.version, range);
47
+ return (semver.valid(pkg.version) !== null &&
48
+ (range.startsWith('file:candidates/') || semver.satisfies(pkg.version, range)));
52
49
  }))
53
50
  throw contentError('ENVIRONMENT_PACKAGE_MISMATCH', `Prepared packages do not satisfy ${name}@${range}`);
54
51
  }
55
52
  for (const name of document.sources)
56
- if (!packages.some(pkg => isRecord(pkg) && pkg.name === name))
53
+ if (!inspection.packages.some(pkg => isRecord(pkg) && pkg.name === name))
57
54
  throw contentError('ENVIRONMENT_SOURCE_MISSING', name);
58
- const inspection = await inspectNpmProject(directory);
59
55
  return {
60
56
  contentRevision: result.contentRevision,
61
57
  packages,
@@ -77,28 +73,21 @@ function activeProcess(pid) {
77
73
  throw error;
78
74
  }
79
75
  }
80
- /** One local owner coordinates files, immutable materials and runtime leases.
81
- * Bindings/grants/retention roots remain owned by the injected durable database.
82
- */
76
+ /** One owner edits persistent npm projects. Prepared metadata is a disposable receipt,
77
+ * never a selectable historical version. Runtime loaders capture their own inputs. */
83
78
  class ContentWorkspaceImplementation {
84
79
  root;
85
- bootId;
80
+ bootId = randomUUID();
86
81
  workspaceId;
87
82
  #queue = Promise.resolve();
88
- #snapshotGeneration = 0;
89
- #snapshotObservations;
90
83
  #closed = false;
91
- #closing = false;
92
- #closePromise;
93
- #pending = new Set();
94
- #activeStaging = new Set();
95
- #leases = new Map();
96
- #external = new Map();
97
84
  #controller = new AbortController();
98
85
  #options;
86
+ #leases = new Map();
87
+ #snapshotGeneration = 0;
88
+ #snapshotFingerprint;
99
89
  constructor(root, options = {}) {
100
90
  this.root = root;
101
- this.bootId = randomUUID();
102
91
  this.#options = options;
103
92
  }
104
93
  static async open(directory, options = {}) {
@@ -106,815 +95,637 @@ class ContentWorkspaceImplementation {
106
95
  const root = await realpath(directory);
107
96
  const workspace = new ContentWorkspaceImplementation(root, options);
108
97
  await withSourceLock(root, 'workspace-owner', async () => {
109
- const ownerFile = join(root, 'workspace-owner.json');
110
- try {
111
- const owner = await readJson(ownerFile);
112
- if (activeProcess(owner.pid ?? 0))
113
- throw contentError('WORKSPACE_BUSY');
114
- await rm(ownerFile);
115
- }
116
- catch (error) {
98
+ const file = join(root, 'workspace-owner.json');
99
+ const owner = await readJson(file).catch(error => {
117
100
  if (errorCode(error) !== 'ENOENT')
118
101
  throw error;
119
- }
120
- await writeFile(ownerFile, json({ pid: process.pid, bootId: workspace.bootId }), { flag: 'wx', mode: 0o600 });
102
+ return undefined;
103
+ });
104
+ if (owner && activeProcess(owner.pid))
105
+ throw contentError('WORKSPACE_BUSY');
106
+ await writeFileAtomic(file, json({ pid: process.pid, bootId: workspace.bootId }));
121
107
  });
122
108
  try {
123
- for (const name of ['environments', 'versions', 'staging', 'imports'])
109
+ for (const name of ['environments', 'staging', 'imports'])
124
110
  await regularDirectory(join(root, name));
125
- try {
126
- const metadata = await readJson(join(root, 'workspace.json'));
127
- if (metadata.format !== 'arcadia.content-workspace/1')
128
- throw contentError('WORKSPACE_FORMAT_INVALID');
129
- workspace.workspaceId = checkId(metadata.workspaceId);
130
- }
131
- catch (error) {
111
+ const file = join(root, 'workspace.json');
112
+ const metadata = await readJson(file).catch(error => {
132
113
  if (errorCode(error) !== 'ENOENT')
133
114
  throw error;
115
+ return undefined;
116
+ });
117
+ if (metadata) {
118
+ if (metadata.format !== 'arcadia.content-workspace/2')
119
+ throw contentError('WORKSPACE_FORMAT_INVALID');
120
+ workspace.workspaceId = checkId(metadata.workspaceId, uuid);
121
+ }
122
+ else {
134
123
  workspace.workspaceId = randomUUID();
135
- await writeFileAtomic(join(root, 'workspace.json'), json({ format: 'arcadia.content-workspace/1', workspaceId: workspace.workspaceId }), { mode: 0o600 });
124
+ await writeFileAtomic(file, json({ format: 'arcadia.content-workspace/2', workspaceId: workspace.workspaceId }));
125
+ }
126
+ // Recover an interrupted directory replacement before exposing projects.
127
+ for (const name of await readdir(join(root, 'staging'))) {
128
+ if (!name.startsWith('replaced-') || !envId.test(name.slice(9)))
129
+ continue;
130
+ const previous = join(root, 'staging', name);
131
+ const target = workspace.#directory(name.slice(9));
132
+ const current = await lstat(target).catch(error => {
133
+ if (errorCode(error) !== 'ENOENT')
134
+ throw error;
135
+ return undefined;
136
+ });
137
+ if (current)
138
+ await rm(previous, { recursive: true });
139
+ else
140
+ await rename(previous, target);
136
141
  }
137
- await workspace.reconcile();
138
142
  return workspace;
139
143
  }
140
144
  catch (error) {
141
- await workspace.close();
145
+ await workspace.close({ force: true });
142
146
  throw error;
143
147
  }
144
148
  }
145
149
  async #assertOwner() {
146
- if (this.#closed || this.#closing)
150
+ if (this.#closed)
147
151
  throw contentError('WORKSPACE_CLOSED');
148
152
  const owner = await readJson(join(this.root, 'workspace-owner.json'));
149
153
  if (owner.bootId !== this.bootId || owner.pid !== process.pid)
150
154
  throw contentError('WORKSPACE_OWNERSHIP_LOST');
151
155
  }
152
- #exclusive(action, mutatesSnapshot = false) {
156
+ #exclusive(action, mutation = false) {
153
157
  const result = this.#queue.then(async () => {
154
158
  await this.#assertOwner();
155
- if (mutatesSnapshot) {
156
- // Invalidate before the first awaited write: an operation may commit
157
- // partially and then fail, including an external DB import boundary.
159
+ if (mutation) {
158
160
  this.#snapshotGeneration++;
159
- this.#snapshotObservations = undefined;
161
+ this.#snapshotFingerprint = undefined;
160
162
  }
161
163
  return action();
162
164
  });
163
165
  this.#queue = result.catch(() => { });
164
166
  return result;
165
167
  }
168
+ #directory(id) {
169
+ return join(this.root, 'environments', checkId(id, envId));
170
+ }
171
+ #manifest(document, previous = {}) {
172
+ const { packages, ...metadata } = document;
173
+ const priorDependencies = isRecord(previous.dependencies) ? previous.dependencies : {};
174
+ return {
175
+ ...previous,
176
+ name: typeof previous.name === 'string' ? previous.name : `arcadia-environment-${document.id}`,
177
+ version: typeof previous.version === 'string' ? previous.version : '1.0.0',
178
+ private: true,
179
+ dependencies: {
180
+ ...packages,
181
+ ...Object.fromEntries(document.sources.flatMap(name => typeof priorDependencies[name] === 'string' ? [[name, priorDependencies[name]]] : [])),
182
+ },
183
+ arcadiaEnvironment: metadata,
184
+ };
185
+ }
166
186
  async #draft(id) {
167
- checkId(id, envId);
168
- const file = join(this.root, 'environments', `${id}.json`);
169
- await readJson(file);
170
- const text = await readFile(file, 'utf8');
171
- const document = normalizeEnvironmentDocument(JSON.parse(text));
187
+ const directory = this.#directory(id);
188
+ if ((await realpath(directory)) !== directory)
189
+ throw contentError('WORKSPACE_PATH_INVALID');
190
+ await readJson(join(directory, 'package.json'));
191
+ const text = await readFile(join(this.#directory(id), 'package.json'), 'utf8');
192
+ const manifest = JSON.parse(text);
193
+ if (!isRecord(manifest.arcadiaEnvironment) || !isRecord(manifest.dependencies))
194
+ throw contentError('ENVIRONMENT_MANIFEST_INVALID');
195
+ const sources = manifest.arcadiaEnvironment.sources;
196
+ if (!Array.isArray(sources))
197
+ throw contentError('ENVIRONMENT_MANIFEST_INVALID');
198
+ const document = normalizeEnvironmentDocument({
199
+ ...manifest.arcadiaEnvironment,
200
+ packages: Object.fromEntries(Object.entries(manifest.dependencies).filter(([name]) => !sources.includes(name))),
201
+ });
172
202
  if (document.id !== id)
173
203
  throw contentError('ENVIRONMENT_ID_MISMATCH');
174
204
  return { document, revision: revision(text) };
175
205
  }
176
- async listDrafts() {
206
+ listDrafts() {
207
+ return this.#exclusive(() => this.#listDrafts());
208
+ }
209
+ async #listDrafts() {
177
210
  await this.#assertOwner();
178
- const result = [];
179
- for (const file of (await readdir(join(this.root, 'environments'))).sort()) {
180
- if (!file.endsWith('.json'))
181
- continue;
182
- result.push(await this.#draft(file.slice(0, -5)));
211
+ const results = [];
212
+ for (const id of (await readdir(join(this.root, 'environments'))).sort()) {
213
+ if (envId.test(id))
214
+ results.push(await this.#draft(id));
183
215
  }
184
- return result;
216
+ return results;
185
217
  }
186
218
  getDraft(id) {
187
219
  return this.#exclusive(() => this.#draft(id));
188
220
  }
189
- saveDraft({ document, expectedRevision, }) {
190
- const next = normalizeEnvironmentDocument(document);
221
+ saveDraft(input) {
191
222
  return this.#exclusive(async () => {
192
- let previous = null;
193
- try {
194
- previous = await this.#draft(next.id);
195
- }
196
- catch (error) {
223
+ const document = normalizeEnvironmentDocument(input.document);
224
+ const directory = this.#directory(document.id);
225
+ const file = join(directory, 'package.json');
226
+ const previous = await readFile(file, 'utf8').catch(error => {
197
227
  if (errorCode(error) !== 'ENOENT')
198
228
  throw error;
199
- }
200
- if (expectedRevision !== (previous?.revision ?? null))
229
+ return null;
230
+ });
231
+ if ((previous === null ? null : revision(previous)) !== input.expectedRevision)
201
232
  throw contentError('REVISION_CONFLICT');
202
- await writeFileAtomic(join(this.root, 'environments', `${next.id}.json`), json(next), { mode: 0o600 });
203
- return this.#draft(next.id);
233
+ await regularDirectory(directory);
234
+ await writeFileAtomic(file, json(this.#manifest(document, previous ? JSON.parse(previous) : {})));
235
+ return this.#draft(document.id);
204
236
  }, true);
205
237
  }
206
- deleteDraft({ environmentId, expectedRevision }) {
238
+ deleteDraft(input) {
207
239
  return this.#exclusive(async () => {
208
- const draft = await this.#draft(environmentId);
209
- if (draft.revision !== expectedRevision)
240
+ const current = await this.#draft(input.environmentId);
241
+ if (current.revision !== input.expectedRevision)
210
242
  throw contentError('REVISION_CONFLICT');
211
- const versions = await this.listVersions();
212
- if (versions.some(version => version.environmentId === environmentId || version.environmentId === undefined))
213
- throw contentError('ENVIRONMENT_HAS_VERSIONS');
214
- await rm(join(this.root, 'environments', `${environmentId}.json`));
243
+ const references = await this.#references(input.environmentId);
244
+ if (references.length)
245
+ throw Object.assign(contentError('ENVIRONMENT_IN_USE'), { references });
246
+ await rm(this.#directory(input.environmentId), { recursive: true });
215
247
  }, true);
216
248
  }
217
- async #materialDirectory(metadata) {
218
- const path = metadata.materialDirectory;
219
- if (typeof path !== 'string' ||
220
- isAbsolute(path) ||
221
- path.includes('\\') ||
222
- path.split('/').some(p => !p || p === '.' || p === '..'))
223
- throw contentError('MATERIAL_PATH_INVALID');
224
- const directory = join(this.root, path);
225
- if ((await realpath(directory)) !== directory)
226
- throw contentError('MATERIAL_PATH_ESCAPE');
227
- return directory;
228
- }
229
- async #version(versionId) {
230
- checkId(versionId);
231
- const metadata = await readJson(join(this.root, 'versions', versionDirectory(versionId), 'version.json'));
232
- if (metadata.format !== 'arcadia.environment-version/1' ||
233
- metadata.versionId !== versionId ||
234
- metadata.workspaceId !== this.workspaceId)
235
- throw contentError('ENVIRONMENT_VERSION_INVALID');
236
- checkId(metadata.environmentId, envId);
237
- const document = normalizeEnvironmentDocument(metadata.document);
238
- if (document.id !== metadata.environmentId ||
239
- typeof metadata.contentRevision !== 'string' ||
240
- !metadata.contentRevision ||
241
- typeof metadata.draftRevision !== 'string')
242
- throw contentError('ENVIRONMENT_VERSION_INVALID');
243
- if (metadata.adopted && !this.#options.acquireMaterials)
244
- throw contentError('MATERIAL_OWNER_REQUIRED');
245
- const directory = await this.#materialDirectory(metadata);
246
- await readJson(join(directory, 'package.json'));
249
+ async #installation(id) {
250
+ const directory = this.#directory(id);
247
251
  await readJson(join(directory, 'package-lock.json'), 16 * 1024 * 1024);
248
- return { ...metadata, document, directory, status: 'ready' };
252
+ await lstat(join(directory, 'node_modules'));
253
+ const draft = await this.#draft(id);
254
+ const metadata = await readJson(join(directory, '.arcadia-prepared.json'));
255
+ if (metadata.format !== 'arcadia.environment-installation/1' ||
256
+ metadata.installationId !== id ||
257
+ typeof metadata.contentRevision !== 'string')
258
+ throw contentError('ENVIRONMENT_INSTALLATION_INVALID');
259
+ // The manifest is authoritative. Metadata describes preparation, not a frozen document.
260
+ return {
261
+ ...metadata,
262
+ installationId: id,
263
+ environmentId: id,
264
+ workspaceId: this.workspaceId,
265
+ document: draft.document,
266
+ directory,
267
+ materialDirectory: `environments/${id}`,
268
+ status: 'ready',
269
+ };
270
+ }
271
+ getInstallation(id) {
272
+ return this.#exclusive(() => this.#installation(id));
249
273
  }
250
- getVersion(versionId) {
251
- return this.#exclusive(() => this.#version(versionId));
274
+ listInstallations(environmentId) {
275
+ return this.#exclusive(() => this.#listInstallations(environmentId));
252
276
  }
253
- async listVersions(environmentId) {
277
+ async #listInstallations(environmentId) {
254
278
  await this.#assertOwner();
255
- if (environmentId !== undefined)
256
- checkId(environmentId, envId);
257
- const result = [];
258
- for (const directory of (await readdir(join(this.root, 'versions'))).sort()) {
259
- const versionId = directoryVersion(directory);
260
- if (!versionId)
261
- continue;
279
+ const drafts = environmentId ? [await this.#draft(environmentId)] : await this.#listDrafts();
280
+ const results = [];
281
+ for (const { document } of drafts) {
262
282
  try {
263
- const version = await this.#version(versionId);
264
- if (environmentId === undefined || version.environmentId === environmentId)
265
- result.push(version);
283
+ results.push(await this.#installation(document.id));
266
284
  }
267
285
  catch (error) {
268
- const metadata = await readJson(join(this.root, 'versions', directory, 'version.json')).catch(() => null);
269
- if (environmentId === undefined || metadata?.environmentId === environmentId)
270
- result.push({
271
- versionId,
272
- environmentId: metadata?.environmentId,
286
+ if (errorCode(error) !== 'ENOENT')
287
+ results.push({
288
+ installationId: document.id,
289
+ environmentId: document.id,
273
290
  workspaceId: this.workspaceId,
274
291
  status: 'unavailable',
275
- reason: errorCode(error) ?? 'ENVIRONMENT_VERSION_INVALID',
292
+ reason: errorCode(error) ?? 'ENVIRONMENT_INSTALLATION_INVALID',
276
293
  });
277
294
  }
278
295
  }
279
- return result;
280
- }
281
- prepareVersion(input, preparer) {
282
- return this.#prepare(input, preparer, false);
296
+ return results;
283
297
  }
284
- adoptVersion(input, preparer) {
285
- return this.#prepare(input, preparer, true);
286
- }
287
- #prepare(input, preparer, adopted) {
288
- if (typeof preparer !== 'function')
289
- throw contentError('STATIC_PREPARER_REQUIRED');
290
- const task = this.#performPrepare(input, preparer, adopted);
291
- this.#pending.add(task);
292
- task.finally(() => this.#pending.delete(task)).catch(() => { });
293
- return task;
298
+ prepareEnvironment(input, preparer) {
299
+ return this.#exclusive(async () => {
300
+ const draft = await this.#draft(input.environmentId).catch(error => {
301
+ if (errorCode(error) !== 'ENOENT')
302
+ throw error;
303
+ return undefined;
304
+ });
305
+ if ((draft?.revision ?? null) !== input.expectedRevision)
306
+ throw contentError('REVISION_CONFLICT');
307
+ const document = normalizeEnvironmentDocument(input.document ?? draft?.document);
308
+ if (document.id !== input.environmentId)
309
+ throw contentError('ENVIRONMENT_ID_MISMATCH');
310
+ const source = input.projectDirectory ??
311
+ input.directory ??
312
+ (await this.#options.resolveProject?.(input.environmentId)) ??
313
+ this.#directory(input.environmentId);
314
+ return this.#install(document, source, preparer, input);
315
+ }, true);
294
316
  }
295
- async #performPrepare({ environmentId, expectedRevision, projectDirectory, directory, signal, beforeCommit, onProgress, }, preparer, adopted) {
296
- const draft = await this.getDraft(environmentId);
297
- if (draft.revision !== expectedRevision)
298
- throw contentError('REVISION_CONFLICT');
299
- const combined = signal ? AbortSignal.any([signal, this.#controller.signal]) : this.#controller.signal;
300
- combined.throwIfAborted();
301
- const sourceDirectory = projectDirectory ?? directory ?? (await this.#options.resolveProject?.(environmentId));
302
- if (typeof sourceDirectory !== 'string')
303
- throw contentError('ENVIRONMENT_SOURCE_MISSING');
304
- const versionId = randomUUID();
305
- const staging = join(this.root, 'staging', 'prepare-' + versionId.replaceAll('-', ''));
306
- await mkdir(staging, { mode: 0o700 });
307
- this.#activeStaging.add(staging);
308
- let releaseExternal, committed = false;
317
+ async #install(document, source, preparer, input = {}) {
318
+ const signal = input.signal ? AbortSignal.any([input.signal, this.#controller.signal]) : this.#controller.signal;
319
+ signal.throwIfAborted();
320
+ const staging = join(this.root, 'staging', `prepare-${randomUUID()}`);
321
+ const target = this.#directory(document.id);
322
+ const previous = join(this.root, 'staging', `replaced-${document.id}`);
323
+ await mkdir(staging);
324
+ let moved = false;
325
+ let journaled = false;
309
326
  try {
310
- await onProgress?.({ stage: 'capturing' });
311
- let materials = join(staging, 'materials');
312
- if (adopted) {
313
- materials = await realpath(sourceDirectory);
314
- const path = relative(this.root, materials);
315
- if (!path || isAbsolute(path) || path === '..' || path.startsWith('../'))
316
- throw contentError('MATERIAL_PATH_ESCAPE');
317
- if (typeof this.#options.acquireMaterials !== 'function')
318
- throw contentError('MATERIAL_OWNER_REQUIRED');
319
- releaseExternal = await this.#options.acquireMaterials(materials, versionId);
320
- if (typeof releaseExternal !== 'function')
321
- throw contentError('MATERIAL_OWNER_REQUIRED');
322
- }
323
- else {
324
- await mkdir(materials);
325
- const files = await materialFiles(sourceDirectory, { ...this.#options, signal: combined });
326
- await writeMaterials(materials, files, { ...this.#options, signal: combined });
327
+ await input.onProgress?.({ stage: 'preparing' });
328
+ await writeMaterials(staging, await materialFiles(source, { ...this.#options, signal }), {
329
+ ...this.#options,
330
+ signal,
331
+ });
332
+ const manifest = await readJson(join(staging, 'package.json'));
333
+ const base = '@arcadia-eternity/data-pack-base';
334
+ if (Object.hasOwn(document.packages, base) || document.sources.includes(base)) {
335
+ const installed = await readJson(join(staging, 'node_modules', base, 'package.json'));
336
+ if (typeof installed.version !== 'string')
337
+ throw contentError('BUNDLED_PACKAGE_INVALID');
338
+ document = {
339
+ ...document,
340
+ packages: { ...document.packages, [base]: installed.version },
341
+ sources: document.sources.filter(name => name !== base),
342
+ };
327
343
  }
328
- combined.throwIfAborted();
329
- await onProgress?.({ stage: 'preparing' });
330
- const result = await checkedPreparation(await preparer({ directory: materials, draft: structuredClone(draft.document), signal: combined }), draft.document, materials);
331
- combined.throwIfAborted();
332
- const metadata = {
333
- format: 'arcadia.environment-version/1',
334
- versionId,
335
- workspaceId: this.workspaceId,
336
- environmentId,
337
- document: draft.document,
338
- draftRevision: draft.revision,
344
+ await writeFile(join(staging, 'package.json'), json({ ...this.#manifest(document, manifest), dependencies: manifest.dependencies ?? {} }));
345
+ const result = await checkedPreparation(await preparer({ directory: staging, draft: document, signal }), document, staging);
346
+ const text = await readFile(join(staging, 'package.json'), 'utf8');
347
+ await writeFile(join(staging, '.arcadia-prepared.json'), json({
348
+ format: 'arcadia.environment-installation/1',
349
+ installationId: document.id,
350
+ draftRevision: revision(text),
339
351
  contentRevision: result.contentRevision,
340
- packages: result.packages ?? [],
341
- members: result.members ?? [],
352
+ packages: result.packages,
353
+ members: result.members,
342
354
  createdAt: Date.now(),
343
- adopted,
344
- materialDirectory: adopted
345
- ? relative(this.root, materials).split('\\').join('/')
346
- : `versions/${versionDirectory(versionId)}/materials`,
347
- };
348
- await writeFile(join(staging, 'version.json'), json(metadata), { flag: 'wx', mode: 0o600 });
349
- return await this.#exclusive(async () => {
350
- combined.throwIfAborted();
351
- await beforeCommit?.();
352
- combined.throwIfAborted();
353
- await rename(staging, join(this.root, 'versions', versionDirectory(versionId)));
354
- committed = true;
355
- if (releaseExternal)
356
- this.#external.set(versionId, releaseExternal);
357
- // The revision is captured, never a mutable "active" pointer. A stale
358
- // candidate can be retained but only the binding owner can publish it.
359
- return this.#version(versionId);
360
- }, true);
355
+ ...(input.importId ? { importId: input.importId } : {}),
356
+ }));
357
+ signal.throwIfAborted();
358
+ if (input.importId) {
359
+ checkId(input.importId, /^[a-f0-9]{64}$/);
360
+ const receipt = join(this.root, 'imports', input.importId + '.json');
361
+ await writeFile(receipt, json({
362
+ environmentId: document.id,
363
+ staging: staging.slice(staging.lastIndexOf('/') + 1),
364
+ expectedRevision: input.expectedRevision ?? null,
365
+ completed: false,
366
+ }), { flag: 'wx' });
367
+ journaled = true;
368
+ }
369
+ await input.beforeCommit?.();
370
+ signal.throwIfAborted();
371
+ if (input.importId)
372
+ return this.#finishImport(input.importId);
373
+ try {
374
+ await rename(target, previous);
375
+ moved = true;
376
+ }
377
+ catch (error) {
378
+ if (errorCode(error) !== 'ENOENT')
379
+ throw error;
380
+ }
381
+ try {
382
+ await rename(staging, target);
383
+ }
384
+ catch (error) {
385
+ if (moved)
386
+ await rename(previous, target);
387
+ throw error;
388
+ }
389
+ await rm(previous, { recursive: true, force: true });
390
+ return this.#installation(document.id);
361
391
  }
362
392
  finally {
363
- this.#activeStaging.delete(staging);
364
- if (!committed) {
393
+ if (!journaled)
365
394
  await rm(staging, { recursive: true, force: true });
366
- await releaseExternal?.();
367
- }
368
395
  }
369
396
  }
370
- acquire(versionId, owner = 'runtime') {
397
+ acquire(id, owner = 'runtime') {
371
398
  return this.#exclusive(async () => {
372
- const version = await this.#version(versionId);
373
- if (this.#closing || this.#closed)
374
- throw contentError('WORKSPACE_CLOSED');
399
+ const installation = await this.#installation(id);
375
400
  const token = randomUUID();
376
- this.#leases.set(token, { versionId, owner, bootId: this.bootId });
377
- let released = false;
401
+ const directory = join(this.root, 'staging', `read-${token}`);
402
+ await mkdir(directory);
403
+ try {
404
+ await writeMaterials(directory, await materialFiles(installation.directory, this.#options), this.#options);
405
+ }
406
+ catch (error) {
407
+ await rm(directory, { recursive: true, force: true });
408
+ throw error;
409
+ }
410
+ this.#leases.set(token, { installationId: id, owner });
378
411
  return {
379
- ...version,
412
+ ...installation,
413
+ directory,
380
414
  release: async () => {
381
- if (released)
382
- return;
383
- released = true;
415
+ await rm(directory, { recursive: true, force: true });
384
416
  this.#leases.delete(token);
385
417
  },
386
418
  };
387
419
  });
388
420
  }
389
- retain(versionId, retentionId) {
421
+ retain(id, retentionId) {
390
422
  return this.#exclusive(async () => {
391
- await this.#version(versionId);
423
+ await this.#draft(id);
392
424
  if (!this.#options.retentions?.put)
393
425
  throw contentError('RETENTION_UNAVAILABLE');
394
- await this.#options.retentions.put(versionId, retentionId);
426
+ await this.#options.retentions.put(id, retentionId);
395
427
  });
396
428
  }
397
429
  releaseRetention(retentionId) {
398
430
  return this.#exclusive(async () => {
399
- if (!this.#options.retentions?.remove)
400
- throw contentError('RETENTION_UNAVAILABLE');
401
- await this.#options.retentions.remove(retentionId);
431
+ await this.#options.retentions?.remove?.(retentionId);
402
432
  });
403
433
  }
404
- async #references(versionId) {
405
- if (!this.#options.retentions?.list)
406
- throw contentError('RETENTION_UNAVAILABLE');
434
+ async #references(id) {
435
+ checkId(id, envId);
407
436
  return [
408
- ...(await this.#importIntents())
409
- .filter(x => x.versionId === versionId)
410
- .map(x => ({ kind: 'import', importId: x.importId })),
411
- ...[...this.#leases.values()].filter(x => x.versionId === versionId).map(x => ({ kind: 'runtime', ...x })),
412
- ...(await this.#options.retentions.list(versionId)).map(x => ({ kind: 'retention', ...x })),
437
+ ...[...this.#leases.values()].filter(x => x.installationId === id).map(x => ({ kind: 'runtime', ...x })),
438
+ ...((await this.#options.retentions?.list(id)) ?? []).map(x => ({ kind: 'retention', ...x })),
413
439
  ];
414
440
  }
415
- references(versionId) {
416
- return this.#exclusive(() => this.#references(checkId(versionId)));
441
+ references(id) {
442
+ return this.#exclusive(() => this.#references(id));
417
443
  }
418
- deleteVersion(versionId) {
444
+ clearInstallation(id) {
419
445
  return this.#exclusive(async () => {
420
- checkId(versionId);
421
- const references = await this.#references(versionId);
446
+ const references = await this.#references(id);
422
447
  if (references.length)
423
448
  throw Object.assign(contentError('ENVIRONMENT_IN_USE'), { references });
424
- // Rename removes it from admission before any bytes are deleted. A crash
425
- // leaves a recognizable staging tombstone, never a half-ready version.
426
- const tombstone = join(this.root, 'staging', `deleted-${versionId.replaceAll('-', '')}-${randomUUID().replaceAll('-', '')}`);
427
- await rename(join(this.root, 'versions', versionDirectory(versionId)), tombstone);
428
- await rm(tombstone, { recursive: true, force: true });
429
- await this.#external.get(versionId)?.();
430
- this.#external.delete(versionId);
449
+ const directory = this.#directory(id);
450
+ await rm(join(directory, 'node_modules'), { recursive: true, force: true });
451
+ await rm(join(directory, '.arcadia-prepared.json'), { force: true });
431
452
  }, true);
432
453
  }
433
- async exportVersion(versionId) {
434
- const lease = await this.acquire(versionId, 'export');
435
- try {
436
- const files = await materialFiles(lease.directory, this.#options);
437
- return {
438
- format: 'arcadia.environment-export/1',
439
- document: lease.document,
440
- contentRevision: lease.contentRevision,
441
- files: files.map(({ path, bytes }) => ({ path, data: bytes.toString('base64') })),
442
- };
443
- }
444
- finally {
445
- await lease.release();
446
- }
447
- }
448
- #observation(path, info) {
454
+ async #export(id) {
455
+ const draft = await this.#draft(id);
456
+ const installation = await this.#installation(id);
457
+ if (installation.draftRevision !== draft.revision)
458
+ throw contentError('ENVIRONMENT_PREPARATION_REQUIRED', '环境已修改,请先准备环境再导出');
459
+ const files = await materialFiles(this.#directory(id), this.#options);
449
460
  return {
450
- path,
451
- dev: info.dev,
452
- ino: info.ino,
453
- mode: info.mode,
454
- size: info.size,
455
- mtimeMs: info.mtimeMs,
456
- ctimeMs: info.ctimeMs,
461
+ format: 'arcadia.environment-export/2',
462
+ document: draft.document,
463
+ contentRevision: installation.contentRevision,
464
+ files: files.map(({ path, bytes }) => ({ path, data: bytes.toString('base64') })),
457
465
  };
458
466
  }
459
- async #observationsCurrent(observations) {
460
- for (const previous of observations) {
461
- const info = await lstat(previous.path).catch(error => {
462
- if (['ENOENT', 'ENOTDIR'].includes(errorCode(error) ?? ''))
463
- return null;
464
- throw error;
465
- });
466
- if (!info)
467
- return false;
468
- const current = this.#observation(previous.path, info);
469
- if (Object.keys(current).some(key => current[key] !== previous[key]))
470
- return false;
471
- }
472
- return true;
467
+ exportEnvironment(id) {
468
+ return this.#exclusive(() => this.#export(id));
473
469
  }
474
- async #snapshotData(observations) {
475
- if ((await this.#importIntents()).some(intent => !intent.completed))
476
- throw contentError('WORKSPACE_SNAPSHOT_UNSETTLED');
477
- const observe = (path, info) => {
478
- if (!observations)
479
- return;
480
- if (observations.length >= 200000)
481
- throw contentError('WORKSPACE_SNAPSHOT_LIMIT');
482
- observations.push(this.#observation(path, info));
483
- };
484
- // Observe control files before reading them; materialFiles supplies the
485
- // matching post-read observations without copying another set of bytes.
486
- if (observations) {
487
- for (const name of ['workspace.json', 'environments', 'versions', 'imports']) {
488
- const path = join(this.root, name);
489
- observe(path, await lstat(path));
490
- }
491
- for (const name of await readdir(join(this.root, 'environments'))) {
492
- const path = join(this.root, 'environments', name);
493
- observe(path, await lstat(path));
494
- }
495
- for (const name of await readdir(join(this.root, 'versions'))) {
496
- if (!directoryVersion(name))
497
- continue;
498
- const path = join(this.root, 'versions', name, 'version.json');
499
- observe(path, await lstat(path));
500
- }
470
+ async #snapshot() {
471
+ for (const name of await readdir(join(this.root, 'imports'))) {
472
+ const receipt = await readJson(join(this.root, 'imports', name));
473
+ if (!receipt.completed)
474
+ throw contentError('WORKSPACE_SNAPSHOT_UNSETTLED');
501
475
  }
502
- const versions = [];
503
- let materialBytes = 0;
504
- for (const entry of await this.listVersions()) {
505
- if (entry.status !== 'ready')
506
- throw contentError('ENVIRONMENT_UNAVAILABLE');
507
- const { versionId, environmentId, document, draftRevision, contentRevision, packages, createdAt } = entry;
508
- const files = await materialFiles(entry.directory, {
509
- ...this.#options,
510
- signal: this.#controller.signal,
511
- onRead: observe,
512
- });
513
- materialBytes += files.reduce((total, file) => total + file.bytes.length, 0);
514
- if (materialBytes > 1024 * 1024 * 1024)
515
- throw contentError('WORKSPACE_SNAPSHOT_LIMIT');
516
- versions.push({
517
- version: { versionId, environmentId, document, draftRevision, contentRevision, packages, createdAt },
518
- files: files.map(({ path, bytes }) => ({ path, data: bytes.toString('base64') })),
476
+ const drafts = await this.#listDrafts();
477
+ const installations = [];
478
+ for (const draft of drafts) {
479
+ const installed = await this.#installation(draft.document.id).catch(error => {
480
+ if (errorCode(error) !== 'ENOENT')
481
+ throw error;
482
+ return undefined;
519
483
  });
484
+ if (!installed) {
485
+ draft.files = (await materialFiles(this.#directory(draft.document.id), { ...this.#options, allowMissingLock: true })).map(({ path, bytes }) => ({ path, data: bytes.toString('base64') }));
486
+ continue;
487
+ }
488
+ const { directory: _dir, materialDirectory: _path, status: _status, ...version } = installed;
489
+ const files = await materialFiles(this.#directory(draft.document.id), this.#options);
490
+ installations.push({ version, files: files.map(({ path, bytes }) => ({ path, data: bytes.toString('base64') })) });
520
491
  }
521
- const snapshot = {
522
- format: 'arcadia.workspace-snapshot/1',
523
- workspaceId: this.workspaceId,
524
- drafts: await this.listDrafts(),
525
- versions,
526
- };
527
- if (observations && !(await this.#observationsCurrent(observations)))
528
- throw contentError('WORKSPACE_SNAPSHOT_UNSETTLED');
529
- return snapshot;
492
+ return { format: 'arcadia.workspace-snapshot/2', workspaceId: this.workspaceId, drafts, installations };
530
493
  }
531
494
  exportSnapshot() {
532
- return this.#exclusive(() => this.#snapshotData());
495
+ return this.#exclusive(() => this.#snapshot());
533
496
  }
534
- /** One-use stamp for an optimistic file/DB consistent snapshot. */
535
497
  captureSnapshot() {
536
498
  return this.#exclusive(async () => {
537
- this.#snapshotGeneration++;
538
- this.#snapshotObservations = undefined;
539
- const observations = [];
540
- const snapshot = await this.#snapshotData(observations);
541
- const stamp = { workspaceId: this.workspaceId, bootId: this.bootId, generation: this.#snapshotGeneration };
542
- this.#snapshotObservations = observations;
499
+ const snapshot = await this.#snapshot();
500
+ this.#snapshotFingerprint = revision(json(snapshot));
501
+ const stamp = { workspaceId: this.workspaceId, bootId: this.bootId, generation: ++this.#snapshotGeneration };
543
502
  return { snapshot, stamp };
544
503
  });
545
504
  }
546
505
  isSnapshotCurrent(stamp) {
547
506
  return this.#exclusive(async () => {
548
- if (!stamp ||
549
- stamp.workspaceId !== this.workspaceId ||
507
+ if (stamp.workspaceId !== this.workspaceId ||
550
508
  stamp.bootId !== this.bootId ||
551
- !Number.isSafeInteger(stamp.generation) ||
552
509
  stamp.generation !== this.#snapshotGeneration ||
553
- !this.#snapshotObservations)
510
+ !this.#snapshotFingerprint)
554
511
  return false;
555
- const observations = this.#snapshotObservations;
556
- this.#snapshotObservations = undefined;
557
- return this.#observationsCurrent(observations);
512
+ const expected = this.#snapshotFingerprint;
513
+ this.#snapshotFingerprint = undefined;
514
+ return revision(json(await this.#snapshot())) === expected;
558
515
  });
559
516
  }
560
- async restoreSnapshot(snapshot, { mode }, preparer) {
561
- if (snapshot?.format !== 'arcadia.workspace-snapshot/1' ||
562
- !['restore', 'clone'].includes(mode) ||
563
- !Array.isArray(snapshot.drafts) ||
564
- !Array.isArray(snapshot.versions) ||
565
- typeof preparer !== 'function')
566
- throw contentError('WORKSPACE_SNAPSHOT_INVALID');
567
- checkId(snapshot.workspaceId);
517
+ restoreSnapshot(snapshot, { mode }, preparer) {
568
518
  return this.#exclusive(async () => {
569
- if ((await this.listDrafts()).length ||
570
- (await this.listVersions()).length ||
571
- this.#pending.size ||
572
- this.#leases.size)
519
+ if (snapshot?.format !== 'arcadia.workspace-snapshot/2' ||
520
+ !['restore', 'clone'].includes(mode) ||
521
+ !Array.isArray(snapshot.drafts) ||
522
+ !Array.isArray(snapshot.installations))
523
+ throw contentError('WORKSPACE_SNAPSHOT_INVALID');
524
+ if ((await this.#listDrafts()).length)
573
525
  throw contentError('WORKSPACE_NOT_EMPTY');
574
- const workspaceId = mode === 'restore' ? snapshot.workspaceId : this.workspaceId;
575
- const versions = new Map();
576
- const drafts = new Map();
577
- for (const draft of snapshot.drafts) {
526
+ const drafts = new Map(snapshot.drafts.map(draft => {
578
527
  const document = normalizeEnvironmentDocument(draft.document);
579
- if (drafts.has(document.id))
528
+ return [document.id, document];
529
+ }));
530
+ if (drafts.size !== snapshot.drafts.length)
531
+ throw contentError('WORKSPACE_SNAPSHOT_INVALID');
532
+ const ids = new Set();
533
+ for (const entry of snapshot.installations) {
534
+ const id = entry.version.environmentId;
535
+ if (!drafts.has(id) || ids.has(id) || entry.version.installationId !== id)
580
536
  throw contentError('WORKSPACE_SNAPSHOT_INVALID');
581
- drafts.set(document.id, document);
582
- }
583
- const staging = join(this.root, 'staging', `restore-${randomUUID().replaceAll('-', '')}`);
584
- await mkdir(staging);
585
- try {
586
- // Validate every received artifact before changing any target document.
587
- for (const entry of snapshot.versions) {
588
- const original = entry.version;
589
- checkId(original?.versionId);
590
- if (versions.has(original.versionId))
591
- throw contentError('WORKSPACE_SNAPSHOT_INVALID');
592
- const document = normalizeEnvironmentDocument(original.document);
593
- if (document.id !== original.environmentId ||
594
- !drafts.has(document.id) ||
595
- typeof original.draftRevision !== 'string' ||
596
- !Number.isSafeInteger(original.createdAt))
597
- throw contentError('WORKSPACE_SNAPSHOT_INVALID');
598
- const versionId = mode === 'restore' ? original.versionId : randomUUID();
599
- const target = join(staging, versionDirectory(versionId));
600
- const materials = join(target, 'materials');
601
- await mkdir(materials, { recursive: true });
602
- await writeMaterials(materials, entry.files, this.#options);
603
- const result = await checkedPreparation(await preparer({ directory: materials, draft: document, signal: this.#controller.signal }), document, materials);
604
- if (result?.contentRevision !== original.contentRevision)
605
- throw contentError('ENVIRONMENT_IMPORT_MISMATCH');
606
- await writeFile(join(target, 'version.json'), json({
607
- format: 'arcadia.environment-version/1',
608
- versionId,
609
- workspaceId,
610
- environmentId: document.id,
611
- document,
612
- draftRevision: original.draftRevision,
537
+ ids.add(id);
538
+ const staging = join(this.root, 'staging', `restore-${randomUUID()}`);
539
+ await mkdir(staging);
540
+ try {
541
+ await writeMaterials(staging, entry.files, this.#options);
542
+ // Validate the installed tree against its lock, preserving pending manifest edits.
543
+ const manifestText = await readFile(join(staging, 'package.json'), 'utf8');
544
+ const manifest = JSON.parse(manifestText);
545
+ const lock = await readJson(join(staging, 'package-lock.json'));
546
+ await writeFile(join(staging, 'package.json'), json({ ...manifest, dependencies: lock.packages['']?.dependencies ?? {} }));
547
+ const result = await preparer({ directory: staging, draft: drafts.get(id) });
548
+ await inspectNpmProject(staging);
549
+ await writeFile(join(staging, 'package.json'), manifestText);
550
+ await writeFile(join(staging, '.arcadia-prepared.json'), json({
551
+ ...entry.version,
552
+ format: 'arcadia.environment-installation/1',
613
553
  contentRevision: result.contentRevision,
614
554
  packages: result.packages ?? [],
615
- members: result.members ?? [],
616
- createdAt: original.createdAt,
617
- adopted: false,
618
- materialDirectory: `versions/${versionDirectory(versionId)}/materials`,
619
- }), { flag: 'wx', mode: 0o600 });
620
- versions.set(original.versionId, versionId);
555
+ }));
556
+ await rename(staging, this.#directory(id));
557
+ }
558
+ finally {
559
+ await rm(staging, { recursive: true, force: true });
621
560
  }
622
- this.#controller.signal.throwIfAborted();
623
- // Callers restore into an inactive staging workspace and switch the whole
624
- // server directory only after DB/files validation. Never merge online.
625
- for (const id of versions.values())
626
- await rename(join(staging, versionDirectory(id)), join(this.root, 'versions', versionDirectory(id)));
627
- for (const [id, document] of drafts)
628
- await writeFileAtomic(join(this.root, 'environments', `${id}.json`), json(document), { mode: 0o600 });
629
- await writeFileAtomic(join(this.root, 'workspace.json'), json({ format: 'arcadia.content-workspace/1', workspaceId }), { mode: 0o600 });
630
- this.workspaceId = workspaceId;
631
- return { workspaceId, versionIds: Object.fromEntries(versions) };
561
+ }
562
+ for (const [id, document] of drafts) {
563
+ if (ids.has(id))
564
+ continue;
565
+ await regularDirectory(this.#directory(id));
566
+ const saved = snapshot.drafts.find(draft => draft.document.id === id);
567
+ if (!saved?.files)
568
+ throw contentError('WORKSPACE_SNAPSHOT_INVALID');
569
+ await writeMaterials(this.#directory(id), saved.files, { ...this.#options, allowMissingLock: true });
570
+ if (json((await this.#draft(id)).document) !== json(document))
571
+ throw contentError('WORKSPACE_SNAPSHOT_INVALID');
572
+ }
573
+ this.workspaceId = mode === 'restore' ? checkId(snapshot.workspaceId, uuid) : this.workspaceId;
574
+ await writeFileAtomic(join(this.root, 'workspace.json'), json({ format: 'arcadia.content-workspace/2', workspaceId: this.workspaceId }));
575
+ return { workspaceId: this.workspaceId, installationIds: Object.fromEntries([...ids].map(id => [id, id])) };
576
+ }, true);
577
+ }
578
+ importEnvironment(bundle, input, preparer) {
579
+ return this.#exclusive(async () => {
580
+ if (bundle?.format !== 'arcadia.environment-export/2')
581
+ throw contentError('ENVIRONMENT_EXPORT_INVALID');
582
+ const document = normalizeEnvironmentDocument({
583
+ ...bundle.document,
584
+ ...(input.environmentId ? { id: input.environmentId } : {}),
585
+ });
586
+ const previous = await this.#draft(document.id).catch(error => {
587
+ if (errorCode(error) !== 'ENOENT')
588
+ throw error;
589
+ return undefined;
590
+ });
591
+ if ((previous?.revision ?? null) !== (input.expectedRevision ?? null))
592
+ throw contentError('REVISION_CONFLICT');
593
+ const staging = join(this.root, 'staging', `import-${randomUUID()}`);
594
+ await mkdir(staging);
595
+ try {
596
+ await writeMaterials(staging, bundle.files, this.#options);
597
+ const result = await this.#install(document, staging, preparer, input);
598
+ return result;
632
599
  }
633
600
  finally {
634
601
  await rm(staging, { recursive: true, force: true });
635
602
  }
636
603
  }, true);
637
604
  }
638
- async #importIntents() {
639
- const intents = [];
640
- for (const name of await readdir(join(this.root, 'imports'))) {
641
- if (!/^[a-f0-9]{64}\.json$/.test(name))
642
- continue;
643
- const intent = await readJson(join(this.root, 'imports', name));
644
- if (intent.format !== 'arcadia.environment-import/1' ||
645
- intent.importId !== name.slice(0, -5) ||
646
- intent.workspaceId !== this.workspaceId)
647
- throw contentError('IMPORT_INTENT_INVALID');
648
- checkId(intent.versionId);
649
- checkId(intent.document?.id, envId);
650
- intents.push(intent);
651
- }
652
- return intents;
653
- }
654
- async #finishImport(importId) {
655
- const intent = (await this.#importIntents()).find(x => x.importId === importId);
656
- if (!intent)
657
- throw contentError('IMPORT_INTENT_NOT_FOUND');
658
- const target = join(this.root, 'versions', versionDirectory(intent.versionId));
659
- const staging = join(this.root, 'staging', `import-${intent.versionId.replaceAll('-', '')}`);
660
- const draftFile = join(this.root, 'environments', `${intent.document.id}.json`);
661
- const text = json(normalizeEnvironmentDocument(intent.document));
662
- let previous = null;
663
- try {
664
- previous = await readFile(draftFile, 'utf8');
665
- }
666
- catch (error) {
605
+ async #finishImport(id) {
606
+ checkId(id, /^[a-f0-9]{64}$/);
607
+ const file = join(this.root, 'imports', id + '.json');
608
+ const receipt = await readJson(file);
609
+ const environmentId = checkId(receipt.environmentId, envId);
610
+ if (typeof receipt.staging !== 'string' || !/^prepare-[0-9a-f-]{36}$/.test(receipt.staging))
611
+ throw contentError('IMPORT_INTENT_INVALID');
612
+ const target = this.#directory(environmentId);
613
+ const metadata = await readJson(join(target, '.arcadia-prepared.json')).catch(error => {
667
614
  if (errorCode(error) !== 'ENOENT')
668
615
  throw error;
616
+ return undefined;
617
+ });
618
+ if (receipt.completed || metadata?.importId === id) {
619
+ if (!receipt.completed)
620
+ await writeFileAtomic(file, json({ ...receipt, completed: true }));
621
+ return this.#installation(environmentId);
669
622
  }
670
- if (!intent.completed &&
671
- previous !== text &&
672
- (previous === null ? null : revision(previous)) !== intent.expectedRevision)
623
+ const current = await this.#draft(environmentId).catch(error => {
624
+ if (errorCode(error) !== 'ENOENT')
625
+ throw error;
626
+ return undefined;
627
+ });
628
+ if ((current?.revision ?? null) !== receipt.expectedRevision)
673
629
  throw contentError('REVISION_CONFLICT');
630
+ const staging = join(this.root, 'staging', receipt.staging);
631
+ const prepared = await readJson(join(staging, '.arcadia-prepared.json'));
632
+ if (prepared.importId !== id || prepared.installationId !== environmentId)
633
+ throw contentError('IMPORT_INTENT_INVALID');
634
+ const previous = join(this.root, 'staging', `replaced-${environmentId}`);
635
+ let moved = false;
674
636
  try {
675
- await lstat(target);
637
+ await rename(target, previous);
638
+ moved = true;
676
639
  }
677
640
  catch (error) {
678
641
  if (errorCode(error) !== 'ENOENT')
679
642
  throw error;
643
+ }
644
+ try {
680
645
  await rename(staging, target);
681
646
  }
682
- const version = await this.#version(intent.versionId);
683
- if (version.draftRevision !== revision(text) || version.contentRevision !== intent.contentRevision)
684
- throw contentError('IMPORT_INTENT_INVALID');
685
- // Replaying a completed receipt must not overwrite a subsequent draft edit.
686
- if (!intent.completed) {
687
- if (previous !== text)
688
- await writeFileAtomic(draftFile, text, { mode: 0o600 });
689
- await writeFileAtomic(join(this.root, 'imports', `${importId}.json`), json({ ...intent, completed: true }), {
690
- mode: 0o600,
691
- });
647
+ catch (error) {
648
+ if (moved)
649
+ await rename(previous, target);
650
+ throw error;
692
651
  }
693
- return version;
652
+ await writeFileAtomic(file, json({ ...receipt, completed: true }));
653
+ await rm(previous, { recursive: true, force: true });
654
+ return this.#installation(environmentId);
694
655
  }
695
- /** The caller must first establish that its durable operation committed. */
696
- recoverImport(importId) {
697
- checkId(importId, /^[a-f0-9]{64}$/);
698
- return this.#exclusive(() => this.#finishImport(importId), true);
656
+ recoverImport(id) {
657
+ return this.#exclusive(() => this.#finishImport(id), true);
699
658
  }
700
- /** Acknowledge a completed receipt, or discard a proven uncommitted operation. */
701
- forgetImport(importId, { discard = false } = {}) {
702
- checkId(importId, /^[a-f0-9]{64}$/);
659
+ forgetImport(id, { discard = false } = {}) {
703
660
  return this.#exclusive(async () => {
704
- const intent = (await this.#importIntents()).find(x => x.importId === importId);
705
- if (!intent)
661
+ checkId(id, /^[a-f0-9]{64}$/);
662
+ const file = join(this.root, 'imports', id + '.json');
663
+ const receipt = await readJson(file).catch(error => {
664
+ if (errorCode(error) !== 'ENOENT')
665
+ throw error;
666
+ return undefined;
667
+ });
668
+ if (!receipt)
706
669
  return;
707
- if (!intent.completed && !discard)
670
+ if (!receipt.completed && !discard)
708
671
  throw contentError('IMPORT_NOT_COMPLETED');
709
- if (discard) {
710
- const published = await lstat(join(this.root, 'versions', versionDirectory(intent.versionId))).catch(error => {
711
- if (errorCode(error) === 'ENOENT')
712
- return null;
713
- throw error;
714
- });
715
- if (published)
716
- throw contentError('IMPORT_ALREADY_PUBLISHED');
717
- await rm(join(this.root, 'staging', `import-${intent.versionId.replaceAll('-', '')}`), {
718
- recursive: true,
719
- force: true,
720
- });
672
+ if (discard && !receipt.completed) {
673
+ if (typeof receipt.staging !== 'string' || !/^prepare-[0-9a-f-]{36}$/.test(receipt.staging))
674
+ throw contentError('IMPORT_INTENT_INVALID');
675
+ await rm(join(this.root, 'staging', receipt.staging), { recursive: true, force: true });
721
676
  }
722
- await rm(join(this.root, 'imports', `${importId}.json`));
677
+ await rm(file);
723
678
  }, true);
724
679
  }
725
- async importVersion(bundle, { environmentId, expectedRevision = null, signal, beforeCommit, importId, } = {}, preparer) {
726
- if (bundle?.format !== 'arcadia.environment-export/1')
727
- throw contentError('ENVIRONMENT_EXPORT_INVALID');
728
- if (typeof preparer !== 'function')
729
- throw contentError('STATIC_PREPARER_REQUIRED');
730
- const document = normalizeEnvironmentDocument({
731
- ...bundle.document,
732
- ...(environmentId ? { id: environmentId } : {}),
733
- });
734
- const versionId = randomUUID();
735
- if (importId !== undefined)
736
- checkId(importId, /^[a-f0-9]{64}$/);
737
- let journaled = false;
738
- const staging = join(this.root, 'staging', `import-${versionId.replaceAll('-', '')}`);
739
- const combined = signal ? AbortSignal.any([signal, this.#controller.signal]) : this.#controller.signal;
740
- await this.#assertOwner();
741
- const materials = join(staging, 'materials');
742
- await mkdir(materials, { recursive: true });
743
- this.#activeStaging.add(staging);
744
- try {
745
- await writeMaterials(materials, bundle.files, { ...this.#options, signal: combined });
746
- // Validate received bytes independently; an archive's revision is not a proof.
747
- const result = await checkedPreparation(await preparer({ directory: materials, draft: document, signal: combined }), document, materials);
748
- if (result.contentRevision !== bundle.contentRevision)
749
- throw contentError('ENVIRONMENT_IMPORT_MISMATCH');
750
- const text = json(document);
751
- const metadata = {
752
- format: 'arcadia.environment-version/1',
753
- versionId,
754
- workspaceId: this.workspaceId,
755
- environmentId: document.id,
756
- document,
757
- draftRevision: revision(text),
758
- contentRevision: result.contentRevision,
759
- packages: result.packages ?? [],
760
- members: result.members ?? [],
761
- createdAt: Date.now(),
762
- adopted: false,
763
- materialDirectory: `versions/${versionDirectory(versionId)}/materials`,
764
- };
765
- await writeFile(join(staging, 'version.json'), json(metadata), { flag: 'wx', mode: 0o600 });
766
- return await this.#exclusive(async () => {
767
- const draftFile = join(this.root, 'environments', `${document.id}.json`);
768
- let previous = null;
769
- try {
770
- previous = await readFile(draftFile, 'utf8');
771
- }
772
- catch (error) {
773
- if (errorCode(error) !== 'ENOENT')
774
- throw error;
775
- }
776
- if (expectedRevision !== (previous === null ? null : revision(previous)))
777
- throw contentError('REVISION_CONFLICT');
778
- combined.throwIfAborted();
779
- if (importId) {
780
- if ((await this.#importIntents()).some(x => x.importId === importId))
781
- throw contentError('IMPORT_ALREADY_EXISTS');
782
- // Persist prepared material intent before the external DB cancellation boundary.
783
- // If its response is lost, only the caller's DB may decide recovery vs discard.
784
- await writeFileAtomic(join(this.root, 'imports', `${importId}.json`), json({
785
- format: 'arcadia.environment-import/1',
786
- importId,
787
- workspaceId: this.workspaceId,
788
- versionId,
789
- document,
790
- expectedRevision,
791
- contentRevision: metadata.contentRevision,
792
- completed: false,
793
- }), { mode: 0o600 });
794
- journaled = true;
795
- await beforeCommit?.();
796
- return this.#finishImport(importId);
797
- }
798
- await beforeCommit?.();
799
- combined.throwIfAborted();
800
- const target = join(this.root, 'versions', versionDirectory(versionId));
801
- await rename(staging, target);
802
- try {
803
- await writeFileAtomic(draftFile, text, { mode: 0o600 });
804
- }
805
- catch (error) {
806
- // An atomic writer can report an fsync error after rename. Compensate
807
- // only our own bytes; never overwrite a subsequent external edit.
808
- const current = await readFile(draftFile, 'utf8').catch(() => null);
809
- if (current === text) {
810
- if (previous === null)
811
- await rm(draftFile);
812
- else
813
- await writeFileAtomic(draftFile, previous, { mode: 0o600 });
814
- }
815
- await rm(target, { recursive: true, force: true });
816
- throw error;
817
- }
818
- return { ...metadata, document, directory: join(target, 'materials'), status: 'ready' };
819
- }, true);
820
- }
821
- finally {
822
- this.#activeStaging.delete(staging);
823
- if (!journaled)
824
- await rm(staging, { recursive: true, force: true });
825
- }
826
- }
827
680
  reconcile() {
828
- return this.#exclusive(() => this.#reconcile());
829
- }
830
- async #reconcile() {
831
- await this.#assertOwner();
832
- const versions = await this.listVersions();
833
- for (const [index, version] of versions.entries()) {
834
- if (version.status !== 'ready' || !version.adopted || this.#external.has(version.versionId))
835
- continue;
836
- if (!this.#options.acquireMaterials) {
837
- versions[index] = {
838
- versionId: version.versionId,
839
- workspaceId: version.workspaceId,
840
- environmentId: version.environmentId,
841
- status: 'unavailable',
842
- reason: 'MATERIAL_OWNER_REQUIRED',
843
- };
844
- continue;
845
- }
846
- const release = await this.#options.acquireMaterials(version.directory, version.versionId);
847
- if (typeof release !== 'function')
848
- throw contentError('MATERIAL_OWNER_REQUIRED');
849
- this.#external.set(version.versionId, release);
850
- }
851
- const abandoned = [];
852
- const pendingImports = new Set((await this.#importIntents()).map(x => `import-${x.versionId.replaceAll('-', '')}`));
853
- for (const name of await readdir(join(this.root, 'staging'))) {
854
- const info = await lstat(join(this.root, 'staging', name));
855
- if (info.isSymbolicLink())
856
- throw contentError('WORKSPACE_PATH_INVALID');
857
- if (!pendingImports.has(name) &&
858
- !this.#activeStaging.has(join(this.root, 'staging', name)) &&
859
- Date.now() - info.mtimeMs >= (this.#options.stagingRetentionMs ?? 24 * 3600 * 1000))
860
- abandoned.push(name);
861
- }
862
- return { workspaceId: this.workspaceId, versions, abandoned };
681
+ return this.#exclusive(async () => ({
682
+ workspaceId: this.workspaceId,
683
+ installations: await this.#listInstallations(),
684
+ abandoned: await readdir(join(this.root, 'staging')),
685
+ }));
863
686
  }
864
687
  cleanupStaging() {
865
688
  return this.#exclusive(async () => {
866
- const { abandoned } = await this.#reconcile();
867
- const removed = [];
868
- for (const name of abandoned) {
869
- if (!/^(?:(?:import|restore|deleted|prepare)-)?[a-f0-9-]+$/.test(name))
689
+ const retained = new Set();
690
+ for (const file of await readdir(join(this.root, 'imports'))) {
691
+ const receipt = await readJson(join(this.root, 'imports', file));
692
+ if (!receipt.completed && typeof receipt.staging === 'string')
693
+ retained.add(receipt.staging);
694
+ }
695
+ const names = [];
696
+ for (const name of await readdir(join(this.root, 'staging'))) {
697
+ if (name.startsWith('read-') && this.#leases.has(name.slice(5)))
870
698
  continue;
871
- const path = join(this.root, 'staging', name);
872
- if (this.#activeStaging.has(path))
699
+ if (retained.has(name) || !/^(?:(?:prepare|import|restore|read)-)?[a-f0-9-]{36}$/.test(name))
873
700
  continue;
874
- await rm(path, { recursive: true, force: true });
875
- removed.push(name);
701
+ const info = await lstat(join(this.root, 'staging', name));
702
+ if (!info.isSymbolicLink() &&
703
+ Date.now() - info.mtimeMs >= (this.#options.stagingRetentionMs ?? 24 * 3600 * 1000))
704
+ names.push(name);
876
705
  }
877
- return removed;
706
+ for (const name of names)
707
+ await rm(join(this.root, 'staging', name), { recursive: true, force: true });
708
+ return names;
878
709
  }, true);
879
710
  }
880
- close({ force = false } = {}) {
881
- if (this.#closed)
882
- return Promise.resolve();
883
- if (this.#closePromise)
884
- return this.#closePromise;
885
- if (this.#leases.size && !force)
886
- return Promise.reject(contentError('WORKSPACE_IN_USE'));
887
- this.#closePromise = this.#close();
888
- return this.#closePromise;
889
- }
890
- async #close() {
711
+ async close({ force = false } = {}) {
891
712
  if (this.#closed)
892
713
  return;
893
- this.#closing = true;
894
- this.#snapshotGeneration++;
895
- this.#snapshotObservations = undefined;
896
- this.#controller.abort(contentError('WORKSPACE_CLOSED'));
897
- await Promise.allSettled([...this.#pending]);
714
+ if (this.#leases.size && !force)
715
+ throw contentError('WORKSPACE_IN_USE');
716
+ this.#controller.abort();
898
717
  await this.#queue;
899
- this.#leases.clear();
900
- for (const release of this.#external.values())
901
- await release();
902
- this.#external.clear();
718
+ this.#closed = true;
903
719
  await withSourceLock(this.root, 'workspace-owner', async () => {
904
720
  const file = join(this.root, 'workspace-owner.json');
905
- const owner = await readJson(file).catch(error => {
906
- if (errorCode(error) === 'ENOENT')
907
- return null;
908
- throw error;
909
- });
721
+ const owner = await readJson(file).catch(() => undefined);
910
722
  if (owner?.bootId === this.bootId)
911
723
  await rm(file);
912
724
  });
913
- this.#closed = true;
914
725
  }
915
726
  }
916
727
  export const ContentWorkspace = ContentWorkspaceImplementation;
917
- /** Change desired roots only. Resolved material and all published versions remain immutable. */
728
+ /** Change desired roots only. Resolved material and all published installations remain immutable. */
918
729
  export async function setEnvironmentPackageEnabled(workspace, input) {
919
730
  const { environmentId, expectedRevision, name, enabled, cascade = false } = input;
920
731
  if (typeof name !== 'string' || typeof enabled !== 'boolean' || typeof cascade !== 'boolean')
@@ -943,7 +754,7 @@ export async function setEnvironmentPackageEnabled(workspace, input) {
943
754
  throw contentError('ENVIRONMENT_PACKAGE_NOT_FOUND');
944
755
  }
945
756
  else {
946
- const version = (await workspace.listVersions())
757
+ const version = (await workspace.listInstallations())
947
758
  .filter((item) => item.status === 'ready')
948
759
  .filter(item => item.environmentId === environmentId && item.members)
949
760
  .sort((a, b) => b.createdAt - a.createdAt)[0];