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