@dsh-ray/assistant-delivery 0.0.1-seed.0 → 0.2.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 +610 -1
- package/bin/dsh-restart-supervisor.js +102 -0
- package/cordis.patch.yml +29 -0
- package/lib/acceptance.d.ts +54 -0
- package/lib/acceptance.d.ts.map +1 -0
- package/lib/acceptance.js +2 -0
- package/lib/acceptance.js.map +1 -0
- package/lib/agent-runtime.d.ts +247 -0
- package/lib/agent-runtime.d.ts.map +1 -0
- package/lib/agent-runtime.js +4458 -0
- package/lib/agent-runtime.js.map +1 -0
- package/lib/approval-status-context.d.ts +8 -0
- package/lib/approval-status-context.d.ts.map +1 -0
- package/lib/approval-status-context.js +55 -0
- package/lib/approval-status-context.js.map +1 -0
- package/lib/attention-audit-store.d.ts +54 -0
- package/lib/attention-audit-store.d.ts.map +1 -0
- package/lib/attention-audit-store.js +213 -0
- package/lib/attention-audit-store.js.map +1 -0
- package/lib/attention-enforcement.d.ts +75 -0
- package/lib/attention-enforcement.d.ts.map +1 -0
- package/lib/attention-enforcement.js +84 -0
- package/lib/attention-enforcement.js.map +1 -0
- package/lib/attention.d.ts +208 -0
- package/lib/attention.d.ts.map +1 -0
- package/lib/attention.js +288 -0
- package/lib/attention.js.map +1 -0
- package/lib/canonical.d.ts +28 -0
- package/lib/canonical.d.ts.map +1 -0
- package/lib/canonical.js +190 -0
- package/lib/canonical.js.map +1 -0
- package/lib/coordinator.d.ts +134 -0
- package/lib/coordinator.d.ts.map +1 -0
- package/lib/coordinator.js +746 -0
- package/lib/coordinator.js.map +1 -0
- package/lib/feedback-command.d.ts +105 -0
- package/lib/feedback-command.d.ts.map +1 -0
- package/lib/feedback-command.js +547 -0
- package/lib/feedback-command.js.map +1 -0
- package/lib/foreground-observation.d.ts +66 -0
- package/lib/foreground-observation.d.ts.map +1 -0
- package/lib/foreground-observation.js +13 -0
- package/lib/foreground-observation.js.map +1 -0
- package/lib/foreground-termination.d.ts +31 -0
- package/lib/foreground-termination.d.ts.map +1 -0
- package/lib/foreground-termination.js +42 -0
- package/lib/foreground-termination.js.map +1 -0
- package/lib/goal-wake-types.d.ts +93 -0
- package/lib/goal-wake-types.d.ts.map +1 -0
- package/lib/goal-wake-types.js +70 -0
- package/lib/goal-wake-types.js.map +1 -0
- package/lib/in-process-reload-runtime.d.ts +120 -0
- package/lib/in-process-reload-runtime.d.ts.map +1 -0
- package/lib/in-process-reload-runtime.js +1280 -0
- package/lib/in-process-reload-runtime.js.map +1 -0
- package/lib/inbound-images.d.ts +38 -0
- package/lib/inbound-images.d.ts.map +1 -0
- package/lib/inbound-images.js +269 -0
- package/lib/inbound-images.js.map +1 -0
- package/lib/index.d.ts +41 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +25 -0
- package/lib/index.js.map +1 -0
- package/lib/learning-command.d.ts +40 -0
- package/lib/learning-command.d.ts.map +1 -0
- package/lib/learning-command.js +57 -0
- package/lib/learning-command.js.map +1 -0
- package/lib/native-termination.d.ts +12 -0
- package/lib/native-termination.d.ts.map +1 -0
- package/lib/native-termination.js +57 -0
- package/lib/native-termination.js.map +1 -0
- package/lib/native-web-owner.d.ts +97 -0
- package/lib/native-web-owner.d.ts.map +1 -0
- package/lib/native-web-owner.js +338 -0
- package/lib/native-web-owner.js.map +1 -0
- package/lib/operator-snapshot.d.ts +107 -0
- package/lib/operator-snapshot.d.ts.map +1 -0
- package/lib/operator-snapshot.js +1013 -0
- package/lib/operator-snapshot.js.map +1 -0
- package/lib/operator.d.ts +25 -0
- package/lib/operator.d.ts.map +1 -0
- package/lib/operator.js +48 -0
- package/lib/operator.js.map +1 -0
- package/lib/progress-attention.d.ts +55 -0
- package/lib/progress-attention.d.ts.map +1 -0
- package/lib/progress-attention.js +128 -0
- package/lib/progress-attention.js.map +1 -0
- package/lib/reply-replay.d.ts +52 -0
- package/lib/reply-replay.d.ts.map +1 -0
- package/lib/reply-replay.js +122 -0
- package/lib/reply-replay.js.map +1 -0
- package/lib/restart-native.d.ts +47 -0
- package/lib/restart-native.d.ts.map +1 -0
- package/lib/restart-native.js +170 -0
- package/lib/restart-native.js.map +1 -0
- package/lib/restart-runtime.d.ts +38 -0
- package/lib/restart-runtime.d.ts.map +1 -0
- package/lib/restart-runtime.js +335 -0
- package/lib/restart-runtime.js.map +1 -0
- package/lib/restart-store.d.ts +132 -0
- package/lib/restart-store.d.ts.map +1 -0
- package/lib/restart-store.js +757 -0
- package/lib/restart-store.js.map +1 -0
- package/lib/restart-supervisor.d.ts +129 -0
- package/lib/restart-supervisor.d.ts.map +1 -0
- package/lib/restart-supervisor.js +615 -0
- package/lib/restart-supervisor.js.map +1 -0
- package/lib/service.d.ts +1279 -0
- package/lib/service.d.ts.map +1 -0
- package/lib/service.js +8694 -0
- package/lib/service.js.map +1 -0
- package/lib/session-commands.d.ts +52 -0
- package/lib/session-commands.d.ts.map +1 -0
- package/lib/session-commands.js +180 -0
- package/lib/session-commands.js.map +1 -0
- package/lib/session-lease-runtime.d.ts +70 -0
- package/lib/session-lease-runtime.d.ts.map +1 -0
- package/lib/session-lease-runtime.js +395 -0
- package/lib/session-lease-runtime.js.map +1 -0
- package/lib/session-lease-types.d.ts +27 -0
- package/lib/session-lease-types.d.ts.map +1 -0
- package/lib/session-lease-types.js +2 -0
- package/lib/session-lease-types.js.map +1 -0
- package/lib/sqlite.d.ts +8 -0
- package/lib/sqlite.d.ts.map +1 -0
- package/lib/sqlite.js +1665 -0
- package/lib/sqlite.js.map +1 -0
- package/lib/store.d.ts +1267 -0
- package/lib/store.d.ts.map +1 -0
- package/lib/store.js +8039 -0
- package/lib/store.js.map +1 -0
- package/lib/tools.d.ts +4 -0
- package/lib/tools.d.ts.map +1 -0
- package/lib/tools.js +73 -0
- package/lib/tools.js.map +1 -0
- package/lib/types.d.ts +1091 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +10 -0
- package/lib/types.js.map +1 -0
- package/lib/version-query.d.ts +77 -0
- package/lib/version-query.d.ts.map +1 -0
- package/lib/version-query.js +2208 -0
- package/lib/version-query.js.map +1 -0
- package/lib/version.d.ts +2 -0
- package/lib/version.d.ts.map +1 -0
- package/lib/version.js +2 -0
- package/lib/version.js.map +1 -0
- package/lib/work-item-engineering-context.d.ts +127 -0
- package/lib/work-item-engineering-context.d.ts.map +1 -0
- package/lib/work-item-engineering-context.js +151 -0
- package/lib/work-item-engineering-context.js.map +1 -0
- package/lib/work-item-feedback-schema.d.ts +2 -0
- package/lib/work-item-feedback-schema.d.ts.map +1 -0
- package/lib/work-item-feedback-schema.js +29 -0
- package/lib/work-item-feedback-schema.js.map +1 -0
- package/lib/work-item-feedback-store.d.ts +29 -0
- package/lib/work-item-feedback-store.d.ts.map +1 -0
- package/lib/work-item-feedback-store.js +111 -0
- package/lib/work-item-feedback-store.js.map +1 -0
- package/lib/work-item-feedback.d.ts +157 -0
- package/lib/work-item-feedback.d.ts.map +1 -0
- package/lib/work-item-feedback.js +2 -0
- package/lib/work-item-feedback.js.map +1 -0
- package/lib/work-item-replies-schema.d.ts +3 -0
- package/lib/work-item-replies-schema.d.ts.map +1 -0
- package/lib/work-item-replies-schema.js +45 -0
- package/lib/work-item-replies-schema.js.map +1 -0
- package/lib/work-item-replies-store.d.ts +43 -0
- package/lib/work-item-replies-store.d.ts.map +1 -0
- package/lib/work-item-replies-store.js +203 -0
- package/lib/work-item-replies-store.js.map +1 -0
- package/lib/work-item-replies.d.ts +93 -0
- package/lib/work-item-replies.d.ts.map +1 -0
- package/lib/work-item-replies.js +15 -0
- package/lib/work-item-replies.js.map +1 -0
- package/lib/workflow-auto-producer.d.ts +37 -0
- package/lib/workflow-auto-producer.d.ts.map +1 -0
- package/lib/workflow-auto-producer.js +58 -0
- package/lib/workflow-auto-producer.js.map +1 -0
- package/lib/workflow-command.d.ts +16 -0
- package/lib/workflow-command.d.ts.map +1 -0
- package/lib/workflow-command.js +52 -0
- package/lib/workflow-command.js.map +1 -0
- package/package.json +174 -4
|
@@ -0,0 +1,1280 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
|
+
/**
|
|
7
|
+
* Host-side adapter for the control plane's in-process reload protocol.
|
|
8
|
+
*
|
|
9
|
+
* Supports two verified operating modes inside a running Host process:
|
|
10
|
+
*
|
|
11
|
+
* 1. **Config-only in-place reload** (default when `target.artifact` is omitted
|
|
12
|
+
* and `mode !== 'artifact-replace'`): updates profile config and restarts
|
|
13
|
+
* the existing fiber in place (`fibersDisposed: 0`, preserved `uid`, rebuilt
|
|
14
|
+
* `committed` store, unchanged `moduleNamespace`, unchanged Host generation).
|
|
15
|
+
* 2. **Immutable digest-verified artifact replacement** (`mode: 'artifact-replace'`
|
|
16
|
+
* or `target.artifact` supplied): stages the candidate artifact under an
|
|
17
|
+
* immutable `<version>-<artifactDigest>` directory (avoiding ESM cache
|
|
18
|
+
* collisions across reload rounds), verifies SHA-256 `artifactDigest` and
|
|
19
|
+
* `patchDigest` before `tree.refresh()`, cleanly disposes the prior fiber
|
|
20
|
+
* (`state === DISPOSED`, `fibersDisposed >= 1`, clean disposers), mounts the
|
|
21
|
+
* new entry with rebuilt `committed` store and updated `moduleNamespace`,
|
|
22
|
+
* keeps non-target sibling plugins undisturbed, and automatically rolls back
|
|
23
|
+
* to the exact prior immutable artifact and profile patch if disposers,
|
|
24
|
+
* missing injections, startup, or post-reload probe assertions fail.
|
|
25
|
+
*/
|
|
26
|
+
// Cordis 4.1.0 exports `FiberState` as an ambient const enum that is unavailable
|
|
27
|
+
// at runtime, so the numeric values are used directly.
|
|
28
|
+
const PENDING = 0;
|
|
29
|
+
const LOADING = 1;
|
|
30
|
+
const ACTIVE = 2;
|
|
31
|
+
const FAILED = 3;
|
|
32
|
+
const DISPOSED = 4;
|
|
33
|
+
const DIGEST = /^[a-f0-9]{64}$/u;
|
|
34
|
+
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
35
|
+
const MAX_TIMEOUT_MS = 120_000;
|
|
36
|
+
/** Packages that must never be hot-reloaded in-process. */
|
|
37
|
+
export const IN_PROCESS_RELOAD_DENYLIST = Object.freeze([
|
|
38
|
+
'@dsh-ray/plugin-control-plane',
|
|
39
|
+
'@dsh-ray/assistant-delivery',
|
|
40
|
+
]);
|
|
41
|
+
const DENIED_PACKAGES = new Set(IN_PROCESS_RELOAD_DENYLIST);
|
|
42
|
+
function canonical(value) {
|
|
43
|
+
if (Array.isArray(value))
|
|
44
|
+
return `[${value.map(canonical).join(',')}]`;
|
|
45
|
+
if (typeof value === 'object' && value !== null) {
|
|
46
|
+
return `{${Object.entries(value).filter(([, item]) => item !== undefined)
|
|
47
|
+
.sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(',')}}`;
|
|
48
|
+
}
|
|
49
|
+
return JSON.stringify(value);
|
|
50
|
+
}
|
|
51
|
+
function digestOf(value) { return createHash('sha256').update(canonical(value)).digest('hex'); }
|
|
52
|
+
function isInsideRoot(rootDir, candidatePath) {
|
|
53
|
+
const rel = relative(resolve(rootDir), resolve(candidatePath));
|
|
54
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
55
|
+
}
|
|
56
|
+
function sanitizeSlug(value) {
|
|
57
|
+
const cleaned = value.replace(/^@/u, '').replace(/[^a-zA-Z0-9._-]+/gu, '__').replace(/^\.+/u, '');
|
|
58
|
+
if (!cleaned || cleaned === '.' || cleaned === '..')
|
|
59
|
+
throw new Error(`in-process reload identifier is unsafe: ${value}`);
|
|
60
|
+
return cleaned;
|
|
61
|
+
}
|
|
62
|
+
function walkRegularFiles(rootDir) {
|
|
63
|
+
const rootStat = lstatSync(rootDir);
|
|
64
|
+
if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
|
|
65
|
+
throw new Error(`in-process artifact source must be a non-symlink directory: ${rootDir}`);
|
|
66
|
+
}
|
|
67
|
+
const files = [];
|
|
68
|
+
const visit = (currentDir) => {
|
|
69
|
+
const entries = readdirSync(currentDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
70
|
+
for (const entry of entries) {
|
|
71
|
+
if (entry.name === 'node_modules') {
|
|
72
|
+
throw new Error('in-process artifact must not bundle a node_modules dependency subtree');
|
|
73
|
+
}
|
|
74
|
+
const fullPath = join(currentDir, entry.name);
|
|
75
|
+
const stat = lstatSync(fullPath);
|
|
76
|
+
if (stat.isSymbolicLink()) {
|
|
77
|
+
throw new Error(`in-process artifact must not contain symlinks: ${fullPath}`);
|
|
78
|
+
}
|
|
79
|
+
if (stat.isDirectory()) {
|
|
80
|
+
visit(fullPath);
|
|
81
|
+
}
|
|
82
|
+
else if (stat.isFile()) {
|
|
83
|
+
files.push(relative(rootDir, fullPath).split(sep).join('/'));
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
throw new Error(`in-process artifact contains non-regular file: ${fullPath}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
visit(rootDir);
|
|
91
|
+
files.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
92
|
+
return files;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Compute the canonical SHA-256 digest of a plugin directory or standalone entry file.
|
|
96
|
+
* Rejects symlinks and nested `node_modules` dependency subtrees.
|
|
97
|
+
*/
|
|
98
|
+
export function computeInProcessArtifactDigest(source) {
|
|
99
|
+
if (source.sourceDir !== undefined) {
|
|
100
|
+
const files = walkRegularFiles(source.sourceDir);
|
|
101
|
+
if (files.length === 0)
|
|
102
|
+
throw new Error(`in-process artifact directory is empty: ${source.sourceDir}`);
|
|
103
|
+
const hash = createHash('sha256').update('dsh-in-process-artifact-v1\0');
|
|
104
|
+
for (const relPath of files) {
|
|
105
|
+
const bytes = readFileSync(join(source.sourceDir, ...relPath.split('/')));
|
|
106
|
+
hash.update(`${relPath}\0${bytes.length}\0`);
|
|
107
|
+
hash.update(bytes);
|
|
108
|
+
hash.update('\0');
|
|
109
|
+
}
|
|
110
|
+
return hash.digest('hex');
|
|
111
|
+
}
|
|
112
|
+
if (source.entryPath !== undefined) {
|
|
113
|
+
const stat = lstatSync(source.entryPath);
|
|
114
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
115
|
+
throw new Error(`in-process artifact entry must be a regular non-symlink file: ${source.entryPath}`);
|
|
116
|
+
}
|
|
117
|
+
return createHash('sha256').update(readFileSync(source.entryPath)).digest('hex');
|
|
118
|
+
}
|
|
119
|
+
throw new Error('in-process artifact source requires sourceDir or entryPath');
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Compute the canonical SHA-256 digest for a profile patch text, buffer, or canonical patch object.
|
|
123
|
+
*/
|
|
124
|
+
export function computeInProcessPatchDigest(input) {
|
|
125
|
+
if (typeof input === 'string')
|
|
126
|
+
return createHash('sha256').update(Buffer.from(input, 'utf8')).digest('hex');
|
|
127
|
+
if (Buffer.isBuffer(input))
|
|
128
|
+
return createHash('sha256').update(input).digest('hex');
|
|
129
|
+
const normalized = canonical({ config: input.config ?? null, inject: input.inject ?? null });
|
|
130
|
+
return createHash('sha256').update(Buffer.from(normalized, 'utf8')).digest('hex');
|
|
131
|
+
}
|
|
132
|
+
function pickManifestExport(manifest) {
|
|
133
|
+
const exportsField = manifest.exports;
|
|
134
|
+
if (typeof exportsField === 'string')
|
|
135
|
+
return exportsField;
|
|
136
|
+
if (typeof exportsField === 'object' && exportsField !== null && !Array.isArray(exportsField)) {
|
|
137
|
+
const rootExport = exportsField['.'];
|
|
138
|
+
if (typeof rootExport === 'string')
|
|
139
|
+
return rootExport;
|
|
140
|
+
if (typeof rootExport === 'object' && rootExport !== null && !Array.isArray(rootExport)) {
|
|
141
|
+
const record = rootExport;
|
|
142
|
+
for (const key of ['import', 'default', 'node']) {
|
|
143
|
+
if (typeof record[key] === 'string')
|
|
144
|
+
return record[key];
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (typeof manifest.module === 'string')
|
|
149
|
+
return manifest.module;
|
|
150
|
+
if (typeof manifest.main === 'string')
|
|
151
|
+
return manifest.main;
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
function resolvePackageEntry(sourceDir, packageName, version, overrideSpecifier) {
|
|
155
|
+
const pkgJsonPath = join(sourceDir, 'package.json');
|
|
156
|
+
const pkgStat = lstatSync(pkgJsonPath, { throwIfNoEntry: false });
|
|
157
|
+
if (!pkgStat || pkgStat.isSymbolicLink() || !pkgStat.isFile()) {
|
|
158
|
+
throw new Error(`in-process artifact source is missing package.json: ${sourceDir}`);
|
|
159
|
+
}
|
|
160
|
+
const manifest = JSON.parse(readFileSync(pkgJsonPath, 'utf8'));
|
|
161
|
+
if (manifest.name !== packageName) {
|
|
162
|
+
throw new Error(`in-process artifact package name mismatch: expected ${packageName}, got ${String(manifest.name)}`);
|
|
163
|
+
}
|
|
164
|
+
if (manifest.version !== version) {
|
|
165
|
+
throw new Error(`in-process artifact version mismatch: expected ${version}, got ${String(manifest.version)}`);
|
|
166
|
+
}
|
|
167
|
+
const entrySpec = overrideSpecifier ?? pickManifestExport(manifest) ?? './lib/index.js';
|
|
168
|
+
const resolvedEntry = resolve(sourceDir, entrySpec);
|
|
169
|
+
if (!isInsideRoot(sourceDir, resolvedEntry)) {
|
|
170
|
+
throw new Error(`in-process artifact entry escapes package directory: ${entrySpec}`);
|
|
171
|
+
}
|
|
172
|
+
const entryStat = lstatSync(resolvedEntry, { throwIfNoEntry: false });
|
|
173
|
+
if (!entryStat || entryStat.isSymbolicLink() || !entryStat.isFile()) {
|
|
174
|
+
throw new Error(`in-process artifact entry does not exist as a regular file: ${entrySpec}`);
|
|
175
|
+
}
|
|
176
|
+
return resolvedEntry;
|
|
177
|
+
}
|
|
178
|
+
function copyRegularTree(sourceDir, destDir, relFiles) {
|
|
179
|
+
mkdirSync(destDir, { recursive: true });
|
|
180
|
+
for (const relPath of relFiles) {
|
|
181
|
+
const src = join(sourceDir, ...relPath.split('/'));
|
|
182
|
+
const dst = join(destDir, ...relPath.split('/'));
|
|
183
|
+
mkdirSync(dirname(dst), { recursive: true });
|
|
184
|
+
copyFileSync(src, dst);
|
|
185
|
+
chmodSync(dst, lstatSync(src).mode & 0o777);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Verify SHA-256 `target.artifactDigest` and stage an immutable versioned/digest-addressed
|
|
190
|
+
* copy under `stagingDir/<pkgSlug>/<version>-<artifactDigest>/` so repeated reloads and
|
|
191
|
+
* rollbacks never collide in Node's ESM module cache or mutate an active directory.
|
|
192
|
+
*/
|
|
193
|
+
export function stageInProcessArtifact(options) {
|
|
194
|
+
const { target, artifact, stagingDir } = options;
|
|
195
|
+
if (DENIED_PACKAGES.has(target.package)) {
|
|
196
|
+
throw new Error(`in-process reload target ${target.package} is denied and requires a process restart`);
|
|
197
|
+
}
|
|
198
|
+
if (target.holdsUnprovenProcessAuthority) {
|
|
199
|
+
throw new Error(`in-process reload target ${target.package} requires a process restart`);
|
|
200
|
+
}
|
|
201
|
+
if (!DIGEST.test(target.artifactDigest)) {
|
|
202
|
+
throw new Error('in-process reload target artifactDigest is invalid');
|
|
203
|
+
}
|
|
204
|
+
const computedDigest = computeInProcessArtifactDigest(artifact);
|
|
205
|
+
if (computedDigest !== target.artifactDigest) {
|
|
206
|
+
throw new Error(`in-process artifact digest mismatch: expected ${target.artifactDigest}, got ${computedDigest}`);
|
|
207
|
+
}
|
|
208
|
+
const destDir = resolve(stagingDir, sanitizeSlug(target.package), `${sanitizeSlug(target.version)}-${target.artifactDigest}`);
|
|
209
|
+
if (!isInsideRoot(stagingDir, destDir)) {
|
|
210
|
+
throw new Error('in-process artifact staging path escaped stagingDir');
|
|
211
|
+
}
|
|
212
|
+
mkdirSync(dirname(destDir), { recursive: true });
|
|
213
|
+
if (artifact.sourceDir !== undefined) {
|
|
214
|
+
resolvePackageEntry(artifact.sourceDir, target.package, target.version, artifact.entrySpecifier);
|
|
215
|
+
if (existsSync(destDir)) {
|
|
216
|
+
const existingDigest = computeInProcessArtifactDigest({ sourceDir: destDir });
|
|
217
|
+
if (existingDigest !== target.artifactDigest) {
|
|
218
|
+
throw new Error(`staged immutable artifact digest mismatch at ${destDir}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
const tmpDir = `${destDir}.tmp-${process.pid}-${randomUUID()}`;
|
|
223
|
+
const relFiles = walkRegularFiles(artifact.sourceDir);
|
|
224
|
+
try {
|
|
225
|
+
copyRegularTree(artifact.sourceDir, tmpDir, relFiles);
|
|
226
|
+
if (computeInProcessArtifactDigest({ sourceDir: tmpDir }) !== target.artifactDigest) {
|
|
227
|
+
throw new Error('staged artifact digest verification failed');
|
|
228
|
+
}
|
|
229
|
+
try {
|
|
230
|
+
renameSync(tmpDir, destDir);
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
234
|
+
if (!existsSync(destDir) || computeInProcessArtifactDigest({ sourceDir: destDir }) !== target.artifactDigest) {
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const entryFilePath = resolvePackageEntry(destDir, target.package, target.version, artifact.entrySpecifier);
|
|
245
|
+
return { stagedDir: destDir, entryFilePath, artifactDigest: target.artifactDigest };
|
|
246
|
+
}
|
|
247
|
+
if (artifact.entryPath !== undefined) {
|
|
248
|
+
const fileName = sanitizeSlug(basename(artifact.entryPath));
|
|
249
|
+
const stagedEntryPath = join(destDir, fileName);
|
|
250
|
+
if (existsSync(destDir)) {
|
|
251
|
+
const existingDigest = computeInProcessArtifactDigest({ entryPath: stagedEntryPath });
|
|
252
|
+
if (existingDigest !== target.artifactDigest) {
|
|
253
|
+
throw new Error(`staged immutable entry digest mismatch at ${stagedEntryPath}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
const tmpDir = `${destDir}.tmp-${process.pid}-${randomUUID()}`;
|
|
258
|
+
const tmpEntry = join(tmpDir, fileName);
|
|
259
|
+
try {
|
|
260
|
+
mkdirSync(tmpDir, { recursive: true });
|
|
261
|
+
copyFileSync(artifact.entryPath, tmpEntry);
|
|
262
|
+
chmodSync(tmpEntry, lstatSync(artifact.entryPath).mode & 0o777);
|
|
263
|
+
if (computeInProcessArtifactDigest({ entryPath: tmpEntry }) !== target.artifactDigest) {
|
|
264
|
+
throw new Error('staged entry digest verification failed');
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
renameSync(tmpDir, destDir);
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
271
|
+
if (!existsSync(stagedEntryPath) || computeInProcessArtifactDigest({ entryPath: stagedEntryPath }) !== target.artifactDigest) {
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
278
|
+
throw error;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return { stagedDir: destDir, entryFilePath: stagedEntryPath, artifactDigest: target.artifactDigest };
|
|
282
|
+
}
|
|
283
|
+
throw new Error('in-process artifact source requires sourceDir or entryPath');
|
|
284
|
+
}
|
|
285
|
+
function fiberOf(entry) {
|
|
286
|
+
const fiber = entry?.fiber;
|
|
287
|
+
return fiber && typeof fiber === 'object' ? fiber : undefined;
|
|
288
|
+
}
|
|
289
|
+
function normalizeEntryId(entryId) {
|
|
290
|
+
const local = entryId.startsWith('include:') ? entryId.slice('include:'.length) : entryId;
|
|
291
|
+
if (!local || local.includes(':'))
|
|
292
|
+
throw new Error(`in-process reload entry id is invalid: ${entryId}`);
|
|
293
|
+
return local;
|
|
294
|
+
}
|
|
295
|
+
function resolveProfileFilePath(profilePath) {
|
|
296
|
+
return /\.(ya?ml|json)$/iu.test(profilePath) ? profilePath : join(profilePath, 'cordis.yml');
|
|
297
|
+
}
|
|
298
|
+
function toRelativeImportSpecifier(fromDir, targetFile) {
|
|
299
|
+
const rel = relative(fromDir, targetFile).split(sep).join('/');
|
|
300
|
+
return rel.startsWith('./') || rel.startsWith('../') || rel === '.' || rel === '..' ? rel : `./${rel}`;
|
|
301
|
+
}
|
|
302
|
+
function writeTextAtomic(filePath, content) {
|
|
303
|
+
const tmpPath = join(dirname(filePath), `.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`);
|
|
304
|
+
try {
|
|
305
|
+
writeFileSync(tmpPath, content, 'utf8');
|
|
306
|
+
renameSync(tmpPath, filePath);
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
rmSync(tmpPath, { force: true });
|
|
310
|
+
throw error;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
function findPackageRootForEntry(entryFilePath) {
|
|
314
|
+
let current = dirname(resolve(entryFilePath));
|
|
315
|
+
for (let depth = 0; depth < 4; depth += 1) {
|
|
316
|
+
const pkgPath = join(current, 'package.json');
|
|
317
|
+
const stat = lstatSync(pkgPath, { throwIfNoEntry: false });
|
|
318
|
+
if (stat && !stat.isSymbolicLink() && stat.isFile()) {
|
|
319
|
+
const parsed = JSON.parse(readFileSync(pkgPath, 'utf8'));
|
|
320
|
+
if (typeof parsed.name === 'string' && parsed.name !== 'dsh-ray-monorepo') {
|
|
321
|
+
return { packageRoot: current, packageName: parsed.name };
|
|
322
|
+
}
|
|
323
|
+
return undefined;
|
|
324
|
+
}
|
|
325
|
+
const parent = dirname(current);
|
|
326
|
+
if (parent === current)
|
|
327
|
+
return undefined;
|
|
328
|
+
current = parent;
|
|
329
|
+
}
|
|
330
|
+
return undefined;
|
|
331
|
+
}
|
|
332
|
+
function readRegularFile(filePath, label) {
|
|
333
|
+
const stat = lstatSync(filePath, { throwIfNoEntry: false });
|
|
334
|
+
if (!stat || stat.isSymbolicLink() || !stat.isFile()) {
|
|
335
|
+
throw new Error(`in-process ${label} must be an existing regular non-symlink file: ${filePath}`);
|
|
336
|
+
}
|
|
337
|
+
return readFileSync(filePath);
|
|
338
|
+
}
|
|
339
|
+
function cloneEntryList(tree) {
|
|
340
|
+
const raw = tree.cache?.data;
|
|
341
|
+
if (!Array.isArray(raw))
|
|
342
|
+
throw new Error('the Cordis include tree cache is unavailable');
|
|
343
|
+
return raw.map(item => (typeof item === 'object' && item !== null ? { ...item } : {}));
|
|
344
|
+
}
|
|
345
|
+
function serializeTreeData(tree, data) {
|
|
346
|
+
if (typeof tree.dump === 'function')
|
|
347
|
+
return tree.dump(data);
|
|
348
|
+
if (tree.type === 'application/json')
|
|
349
|
+
return JSON.stringify(data, null, 2);
|
|
350
|
+
throw new Error('the Cordis include tree does not expose dump() for profile serialization');
|
|
351
|
+
}
|
|
352
|
+
function captureNonTargetEntries(tree, targetLocalId) {
|
|
353
|
+
const result = [];
|
|
354
|
+
for (const [id, entry] of Object.entries(tree.store ?? {})) {
|
|
355
|
+
if (id === targetLocalId || !entry)
|
|
356
|
+
continue;
|
|
357
|
+
result.push({
|
|
358
|
+
id,
|
|
359
|
+
entry,
|
|
360
|
+
fiber: entry.fiber,
|
|
361
|
+
uid: entry.fiber?.uid,
|
|
362
|
+
state: entry.fiber?.state,
|
|
363
|
+
committed: entry.fiber?.committed ?? null,
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
return result;
|
|
367
|
+
}
|
|
368
|
+
function verifyNonTargetEntries(tree, snapshots) {
|
|
369
|
+
const store = tree.store ?? {};
|
|
370
|
+
for (const snap of snapshots) {
|
|
371
|
+
const current = store[snap.id];
|
|
372
|
+
if (!current || current !== snap.entry)
|
|
373
|
+
return false;
|
|
374
|
+
if (current.fiber !== snap.fiber || current.fiber?.uid !== snap.uid)
|
|
375
|
+
return false;
|
|
376
|
+
if (snap.state !== undefined && current.fiber?.state !== snap.state)
|
|
377
|
+
return false;
|
|
378
|
+
if (snap.committed !== undefined && (current.fiber?.committed ?? null) !== snap.committed)
|
|
379
|
+
return false;
|
|
380
|
+
}
|
|
381
|
+
return true;
|
|
382
|
+
}
|
|
383
|
+
export function createInProcessReloadRuntime(ctx, options) {
|
|
384
|
+
if (options.package !== undefined && DENIED_PACKAGES.has(options.package)) {
|
|
385
|
+
throw new Error(`in-process reload target ${options.package} is denied and requires a process restart`);
|
|
386
|
+
}
|
|
387
|
+
const defaultEntryId = options.entryId !== undefined ? normalizeEntryId(options.entryId) : undefined;
|
|
388
|
+
const timeoutMs = Math.min(MAX_TIMEOUT_MS, Math.max(1_000, options.timeoutMs ?? DEFAULT_TIMEOUT_MS));
|
|
389
|
+
const pid = process.pid;
|
|
390
|
+
const invocationId = /^[a-f0-9]{32}$/u.test(process.env.INVOCATION_ID ?? '') ? process.env.INVOCATION_ID : null;
|
|
391
|
+
let inProcessGeneration = 1;
|
|
392
|
+
let lastBaseline;
|
|
393
|
+
function assertRuntimeActive() {
|
|
394
|
+
if (options.isActive && !options.isActive()) {
|
|
395
|
+
throw new Error('assistant-delivery inProcessReload runtime is disposed');
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
function resolveIncludeRootEntry(activeLoader) {
|
|
399
|
+
const active = activeLoader ?? loader();
|
|
400
|
+
let root;
|
|
401
|
+
try {
|
|
402
|
+
root = active.resolve('include');
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
throw new Error('the Cordis include root is not mounted');
|
|
406
|
+
}
|
|
407
|
+
if (!root || typeof root !== 'object')
|
|
408
|
+
throw new Error('the Cordis include root is not mounted');
|
|
409
|
+
const rootEntry = root;
|
|
410
|
+
const tree = rootEntry.subtree;
|
|
411
|
+
if (rootEntry.options?.id !== 'include' || rootEntry.options.name !== 'cordis:include'
|
|
412
|
+
|| rootEntry.parent !== active.root || !tree || tree.ctx?.fiber?.entry !== rootEntry) {
|
|
413
|
+
throw new Error('the Cordis include root is not the profile include tree');
|
|
414
|
+
}
|
|
415
|
+
return rootEntry;
|
|
416
|
+
}
|
|
417
|
+
function resolveProfileContext(activeLoader) {
|
|
418
|
+
if (options.profilePath !== undefined) {
|
|
419
|
+
const profileFile = resolveProfileFilePath(options.profilePath);
|
|
420
|
+
return {
|
|
421
|
+
profileFile,
|
|
422
|
+
profileUrl: pathToFileURL(profileFile).href,
|
|
423
|
+
stagingDir: options.stagingDir ?? join(dirname(profileFile), '.dsh-in-process-artifacts'),
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
const rootEntry = resolveIncludeRootEntry(activeLoader);
|
|
427
|
+
const tree = rootEntry.subtree;
|
|
428
|
+
const config = rootEntry.options?.config;
|
|
429
|
+
const configuredPath = config && typeof config === 'object' && !Array.isArray(config)
|
|
430
|
+
? config.path : undefined;
|
|
431
|
+
let rawProfilePath;
|
|
432
|
+
if (typeof tree?.filename === 'string' && tree.filename.length > 0) {
|
|
433
|
+
rawProfilePath = tree.filename.startsWith('file://') ? fileURLToPath(tree.filename) : tree.filename;
|
|
434
|
+
}
|
|
435
|
+
else if (typeof configuredPath === 'string' && configuredPath.length > 0) {
|
|
436
|
+
if (configuredPath.startsWith('file://')) {
|
|
437
|
+
rawProfilePath = fileURLToPath(configuredPath);
|
|
438
|
+
}
|
|
439
|
+
else {
|
|
440
|
+
const base = tree?.ctx?.baseUrl;
|
|
441
|
+
rawProfilePath = base ? fileURLToPath(new URL(configuredPath, base)) : configuredPath;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (!rawProfilePath) {
|
|
445
|
+
throw new Error('the Cordis include root does not expose a profile file path');
|
|
446
|
+
}
|
|
447
|
+
const profileFile = resolveProfileFilePath(rawProfilePath);
|
|
448
|
+
return {
|
|
449
|
+
profileFile,
|
|
450
|
+
profileUrl: pathToFileURL(profileFile).href,
|
|
451
|
+
stagingDir: options.stagingDir ?? join(dirname(profileFile), '.dsh-in-process-artifacts'),
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function withDeadline(work, label = 'operation') {
|
|
455
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
456
|
+
const timer = setTimeout(() => rejectPromise(new Error(`in-process reload ${label} exceeded its ${timeoutMs}ms deadline`)), timeoutMs);
|
|
457
|
+
void work().then(value => { clearTimeout(timer); resolvePromise(value); }, error => { clearTimeout(timer); rejectPromise(error); });
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
function loader() {
|
|
461
|
+
const value = ctx.get('loader');
|
|
462
|
+
if (!value || typeof value.resolve !== 'function')
|
|
463
|
+
throw new Error('the Cordis Loader service is not available');
|
|
464
|
+
return value;
|
|
465
|
+
}
|
|
466
|
+
function resolveEntryId(active, target, profileFile, allowSearch) {
|
|
467
|
+
if (target.entryId !== undefined)
|
|
468
|
+
return normalizeEntryId(target.entryId);
|
|
469
|
+
if (defaultEntryId !== undefined)
|
|
470
|
+
return defaultEntryId;
|
|
471
|
+
if (!allowSearch)
|
|
472
|
+
throw new Error('in-process reload requires an entryId');
|
|
473
|
+
const rootEntry = active.resolve('include');
|
|
474
|
+
const store = rootEntry?.subtree?.store ?? {};
|
|
475
|
+
for (const [id, entry] of Object.entries(store)) {
|
|
476
|
+
if (entry?.options?.name === target.package)
|
|
477
|
+
return id;
|
|
478
|
+
if (typeof entry?.options?.name === 'string') {
|
|
479
|
+
try {
|
|
480
|
+
const baseUrl = rootEntry?.subtree?.ctx?.baseUrl ?? pathToFileURL(profileFile).href;
|
|
481
|
+
const resolved = fileURLToPath(new URL(entry.options.name, baseUrl));
|
|
482
|
+
const pkgInfo = findPackageRootForEntry(resolved);
|
|
483
|
+
if (pkgInfo?.packageName === target.package)
|
|
484
|
+
return id;
|
|
485
|
+
}
|
|
486
|
+
catch { }
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
throw new Error(`unable to resolve a mounted include entry for ${target.package}`);
|
|
490
|
+
}
|
|
491
|
+
function resolveMount(target, optionsResolve) {
|
|
492
|
+
const active = loader();
|
|
493
|
+
const rootEntry = resolveIncludeRootEntry(active);
|
|
494
|
+
const tree = rootEntry.subtree;
|
|
495
|
+
const profile = resolveProfileContext(active);
|
|
496
|
+
const config = rootEntry.options?.config;
|
|
497
|
+
const configuredPath = config && typeof config === 'object' && !Array.isArray(config)
|
|
498
|
+
? config.path : undefined;
|
|
499
|
+
if (options.profilePath !== undefined && configuredPath !== profile.profileUrl && tree.filename !== profile.profileFile) {
|
|
500
|
+
throw new Error('the Cordis include root is not bound to this profile');
|
|
501
|
+
}
|
|
502
|
+
const rootFiber = fiberOf(rootEntry);
|
|
503
|
+
if (!rootFiber || rootFiber.state !== ACTIVE)
|
|
504
|
+
throw new Error('the Cordis include root is not active');
|
|
505
|
+
const localEntryId = resolveEntryId(active, target, profile.profileFile, true);
|
|
506
|
+
let resolvedTarget;
|
|
507
|
+
try {
|
|
508
|
+
resolvedTarget = active.resolve(`include:${localEntryId}`);
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
resolvedTarget = undefined;
|
|
512
|
+
}
|
|
513
|
+
if (!resolvedTarget || typeof resolvedTarget !== 'object') {
|
|
514
|
+
if (optionsResolve?.allowMissingTarget) {
|
|
515
|
+
return {
|
|
516
|
+
loader: active,
|
|
517
|
+
root: rootEntry,
|
|
518
|
+
tree,
|
|
519
|
+
target: undefined,
|
|
520
|
+
localEntryId,
|
|
521
|
+
profileFile: profile.profileFile,
|
|
522
|
+
stagingDir: profile.stagingDir,
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
throw new Error(`the target entry ${localEntryId} is not mounted`);
|
|
526
|
+
}
|
|
527
|
+
const targetEntry = resolvedTarget;
|
|
528
|
+
if (targetEntry.options?.id !== localEntryId || targetEntry.parent !== tree.root) {
|
|
529
|
+
throw new Error(`the target entry ${localEntryId} is not a child of the include root`);
|
|
530
|
+
}
|
|
531
|
+
if (optionsResolve?.verifyPackageMatch !== false) {
|
|
532
|
+
const mountedName = targetEntry.options.name;
|
|
533
|
+
if (typeof mountedName !== 'string') {
|
|
534
|
+
throw new Error(`the target entry ${localEntryId} is not mounted from ${target.package}`);
|
|
535
|
+
}
|
|
536
|
+
if (mountedName !== target.package) {
|
|
537
|
+
// When mounted from a file/relative specifier (including an immutable staged directory),
|
|
538
|
+
// confirm the nearest package.json manifest (when present) matches the target package name.
|
|
539
|
+
const isPathSpec = mountedName.startsWith('.') || mountedName.startsWith('file://') || isAbsolute(mountedName);
|
|
540
|
+
if (!isPathSpec) {
|
|
541
|
+
throw new Error(`the target entry ${localEntryId} is not mounted from ${target.package}`);
|
|
542
|
+
}
|
|
543
|
+
const entryAbs = mountedName.startsWith('file://')
|
|
544
|
+
? fileURLToPath(mountedName)
|
|
545
|
+
: tree.ctx?.baseUrl
|
|
546
|
+
? fileURLToPath(new URL(mountedName, tree.ctx.baseUrl))
|
|
547
|
+
: resolve(dirname(profile.profileFile), mountedName);
|
|
548
|
+
const pkgInfo = existsSync(entryAbs) ? findPackageRootForEntry(entryAbs) : undefined;
|
|
549
|
+
if (pkgInfo && pkgInfo.packageName !== target.package && (!options.package || pkgInfo.packageName !== options.package)) {
|
|
550
|
+
throw new Error(`the target entry ${localEntryId} is not mounted from ${target.package}`);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
return {
|
|
555
|
+
loader: active,
|
|
556
|
+
root: rootEntry,
|
|
557
|
+
tree,
|
|
558
|
+
target: targetEntry,
|
|
559
|
+
localEntryId,
|
|
560
|
+
profileFile: profile.profileFile,
|
|
561
|
+
stagingDir: profile.stagingDir,
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
async function profileDigest(profileFile) {
|
|
565
|
+
return createHash('sha256').update(await readFile(profileFile)).digest('hex');
|
|
566
|
+
}
|
|
567
|
+
async function capture(target) {
|
|
568
|
+
const resolved = resolveMount(target);
|
|
569
|
+
const entry = resolved.target;
|
|
570
|
+
const fiber = fiberOf(entry);
|
|
571
|
+
if (!fiber)
|
|
572
|
+
throw new Error(`the target entry ${resolved.localEntryId} has no running fiber`);
|
|
573
|
+
return {
|
|
574
|
+
mount: { ...resolved, target: entry },
|
|
575
|
+
identity: {
|
|
576
|
+
fiber,
|
|
577
|
+
uid: fiber.uid,
|
|
578
|
+
committed: fiber.committed ?? null,
|
|
579
|
+
state: fiber.state,
|
|
580
|
+
moduleNamespace: entry.moduleNamespace,
|
|
581
|
+
profileDigest: await profileDigest(resolved.profileFile),
|
|
582
|
+
pid,
|
|
583
|
+
invocationId,
|
|
584
|
+
hostGeneration: options.hostGeneration(),
|
|
585
|
+
entry,
|
|
586
|
+
},
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
function makeProbeResult(checks, failures, reloaded, fibersDisposed, failedChecks, observations, extra) {
|
|
590
|
+
observations.failedChecks = failedChecks;
|
|
591
|
+
observations.fibersDisposed = fibersDisposed;
|
|
592
|
+
observations.reloaded = reloaded;
|
|
593
|
+
return {
|
|
594
|
+
checks,
|
|
595
|
+
failures,
|
|
596
|
+
reloaded,
|
|
597
|
+
fibersDisposed,
|
|
598
|
+
failedChecks,
|
|
599
|
+
probeDigest: digestOf(observations),
|
|
600
|
+
...(extra?.rolledBack === undefined ? {} : { rolledBack: extra.rolledBack }),
|
|
601
|
+
...(extra?.rollbackProbe === undefined ? {} : { rollbackProbe: extra.rollbackProbe }),
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
async function probeConfigOnly(target, before, expectedHostGeneration) {
|
|
605
|
+
let checks = 0;
|
|
606
|
+
let failures = 0;
|
|
607
|
+
const failedChecks = [];
|
|
608
|
+
const bad = (check) => { checks += 1; failures += 1; failedChecks.push(check); };
|
|
609
|
+
const good = () => { checks += 1; };
|
|
610
|
+
const observations = {};
|
|
611
|
+
let after = null;
|
|
612
|
+
try {
|
|
613
|
+
const mount = resolveMount(target);
|
|
614
|
+
const entry = mount.target;
|
|
615
|
+
const fiber = fiberOf(entry);
|
|
616
|
+
const currentProfileDigest = await profileDigest(mount.profileFile);
|
|
617
|
+
const hostGeneration = options.hostGeneration();
|
|
618
|
+
after = {
|
|
619
|
+
fiber: fiber ?? before.fiber,
|
|
620
|
+
uid: fiber?.uid ?? null, committed: fiber?.committed ?? null, state: fiber?.state ?? -1,
|
|
621
|
+
moduleNamespace: entry.moduleNamespace, profileDigest: currentProfileDigest,
|
|
622
|
+
pid, invocationId, hostGeneration, entry,
|
|
623
|
+
};
|
|
624
|
+
if (currentProfileDigest !== before.profileDigest)
|
|
625
|
+
good();
|
|
626
|
+
else
|
|
627
|
+
bad('profile-changed');
|
|
628
|
+
if (fiber !== undefined && fiber.state === ACTIVE)
|
|
629
|
+
good();
|
|
630
|
+
else
|
|
631
|
+
bad('fiber-active');
|
|
632
|
+
if (fiber !== undefined && fiber.uid !== null && fiber.uid === before.uid)
|
|
633
|
+
good();
|
|
634
|
+
else
|
|
635
|
+
bad('fiber-preserved');
|
|
636
|
+
if (fiber !== undefined && fiber.committed !== undefined && fiber.committed !== null && fiber.committed !== before.committed)
|
|
637
|
+
good();
|
|
638
|
+
else
|
|
639
|
+
bad('store-rebuilt');
|
|
640
|
+
if (entry.moduleNamespace === before.moduleNamespace)
|
|
641
|
+
good();
|
|
642
|
+
else
|
|
643
|
+
bad('module-reused');
|
|
644
|
+
if (hostGeneration === expectedHostGeneration && after.hostGeneration === expectedHostGeneration)
|
|
645
|
+
good();
|
|
646
|
+
else
|
|
647
|
+
bad('host-generation-unchanged');
|
|
648
|
+
if (before.hostGeneration === expectedHostGeneration)
|
|
649
|
+
good();
|
|
650
|
+
else
|
|
651
|
+
bad('host-generation-before');
|
|
652
|
+
if (pid === before.pid && invocationId === before.invocationId)
|
|
653
|
+
good();
|
|
654
|
+
else
|
|
655
|
+
bad('process-identity');
|
|
656
|
+
if (before.fiber.state === ACTIVE && fiber === before.fiber)
|
|
657
|
+
good();
|
|
658
|
+
else
|
|
659
|
+
bad('same-fiber-live');
|
|
660
|
+
observations.profileChanged = currentProfileDigest !== before.profileDigest;
|
|
661
|
+
observations.fiberPreserved = after.uid === before.uid;
|
|
662
|
+
observations.storeRebuilt = after.committed !== before.committed;
|
|
663
|
+
observations.moduleReused = entry.moduleNamespace === before.moduleNamespace;
|
|
664
|
+
observations.probe = { pid, invocationId, hostGeneration };
|
|
665
|
+
}
|
|
666
|
+
catch (error) {
|
|
667
|
+
bad('mount-resolvable');
|
|
668
|
+
observations.error = error instanceof Error ? error.message : String(error);
|
|
669
|
+
observations.probe = { pid, invocationId, hostGeneration: options.hostGeneration() };
|
|
670
|
+
}
|
|
671
|
+
const fibersDisposed = 0;
|
|
672
|
+
const reloaded = after !== null && failures === 0
|
|
673
|
+
&& after.profileDigest !== before.profileDigest
|
|
674
|
+
&& after.committed !== before.committed && after.uid === before.uid && after.state === ACTIVE;
|
|
675
|
+
observations.before = { uid: before.uid, state: before.state, profileDigest: before.profileDigest };
|
|
676
|
+
observations.after = after === null ? null : { uid: after.uid, state: after.state, profileDigest: after.profileDigest };
|
|
677
|
+
return { probe: makeProbeResult(checks, failures, reloaded, fibersDisposed, failedChecks, observations), after };
|
|
678
|
+
}
|
|
679
|
+
async function refreshTree(tree) {
|
|
680
|
+
if (typeof tree.refresh !== 'function')
|
|
681
|
+
throw new Error('the Cordis include tree does not expose refresh()');
|
|
682
|
+
await tree.refresh();
|
|
683
|
+
if (tree.persistenceError !== undefined) {
|
|
684
|
+
throw tree.persistenceError instanceof Error
|
|
685
|
+
? tree.persistenceError
|
|
686
|
+
: new Error(String(tree.persistenceError));
|
|
687
|
+
}
|
|
688
|
+
if (typeof tree.await === 'function')
|
|
689
|
+
await tree.await();
|
|
690
|
+
}
|
|
691
|
+
function assertTarget(target, optionsAssert) {
|
|
692
|
+
if (DENIED_PACKAGES.has(target.package)) {
|
|
693
|
+
throw new Error(`in-process reload target ${target.package} is denied and requires a process restart`);
|
|
694
|
+
}
|
|
695
|
+
if (options.package !== undefined && target.package !== options.package) {
|
|
696
|
+
throw new Error(`in-process reload target ${target.package} is not the mounted package ${options.package}`);
|
|
697
|
+
}
|
|
698
|
+
if (!DIGEST.test(target.artifactDigest) || !DIGEST.test(target.patchDigest)) {
|
|
699
|
+
throw new Error('in-process reload target digests are invalid');
|
|
700
|
+
}
|
|
701
|
+
if ((!optionsAssert?.allowSubtreeChange && target.changesProcessSubtree) || target.holdsUnprovenProcessAuthority) {
|
|
702
|
+
throw new Error(`in-process reload target ${target.package} requires a process restart`);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
function attachErrorCollector() {
|
|
706
|
+
const errors = [];
|
|
707
|
+
const rootLogger = ctx.root.logger;
|
|
708
|
+
if (typeof rootLogger?.exporter !== 'function') {
|
|
709
|
+
return { errors, detach: () => { } };
|
|
710
|
+
}
|
|
711
|
+
const detach = rootLogger.exporter({
|
|
712
|
+
levels: { default: 3 },
|
|
713
|
+
export(message) {
|
|
714
|
+
if (message.type !== 'error' && message.level !== 0 && message.level !== 1)
|
|
715
|
+
return;
|
|
716
|
+
const detail = (message.args ?? []).map(arg => (arg instanceof Error ? arg.message : String(arg))).join(' ');
|
|
717
|
+
errors.push(detail || 'cordis error');
|
|
718
|
+
},
|
|
719
|
+
});
|
|
720
|
+
return { errors, detach };
|
|
721
|
+
}
|
|
722
|
+
async function settleEntryAndFiber(entry) {
|
|
723
|
+
const errors = [];
|
|
724
|
+
if (!entry)
|
|
725
|
+
return errors;
|
|
726
|
+
if (entry._initTask) {
|
|
727
|
+
await entry._initTask.catch(error => {
|
|
728
|
+
errors.push(error instanceof Error ? error.message : String(error));
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
const fiber = fiberOf(entry);
|
|
732
|
+
if (fiber && typeof fiber.await === 'function' && (fiber.state === LOADING || fiber.inertia)) {
|
|
733
|
+
try {
|
|
734
|
+
await fiber.await();
|
|
735
|
+
}
|
|
736
|
+
catch (error) {
|
|
737
|
+
errors.push(error instanceof Error ? error.message : String(error));
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
return errors;
|
|
741
|
+
}
|
|
742
|
+
async function disposeTargetEntry(tree, localEntryId, entry) {
|
|
743
|
+
if (!entry)
|
|
744
|
+
return { disposedCount: 0, oldFiberDisposed: true, errors: [] };
|
|
745
|
+
const oldFiber = fiberOf(entry);
|
|
746
|
+
const collector = attachErrorCollector();
|
|
747
|
+
try {
|
|
748
|
+
const group = entry.parent ?? tree.root;
|
|
749
|
+
if (typeof group?.remove === 'function') {
|
|
750
|
+
group.remove(localEntryId, true);
|
|
751
|
+
}
|
|
752
|
+
else {
|
|
753
|
+
if (tree.store)
|
|
754
|
+
delete tree.store[localEntryId];
|
|
755
|
+
await oldFiber?.dispose?.();
|
|
756
|
+
}
|
|
757
|
+
if (oldFiber) {
|
|
758
|
+
await withDeadline(async () => {
|
|
759
|
+
while (oldFiber.inertia)
|
|
760
|
+
await oldFiber.inertia;
|
|
761
|
+
if (entry._initTask)
|
|
762
|
+
await entry._initTask.catch(() => { });
|
|
763
|
+
}, 'dispose');
|
|
764
|
+
}
|
|
765
|
+
const oldFiberDisposed = oldFiber === undefined
|
|
766
|
+
|| (oldFiber.state === DISPOSED && oldFiber.uid === null
|
|
767
|
+
&& (typeof oldFiber.getEffects !== 'function' || oldFiber.getEffects().length === 0));
|
|
768
|
+
return {
|
|
769
|
+
disposedCount: oldFiber?.state === DISPOSED ? 1 : 0,
|
|
770
|
+
oldFiberDisposed,
|
|
771
|
+
errors: [...collector.errors],
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
finally {
|
|
775
|
+
collector.detach();
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
function verifyCandidatePatchDigest(artifact, target, stagedDir, candidateProfileText) {
|
|
779
|
+
if (artifact.patchContent !== undefined) {
|
|
780
|
+
const actual = computeInProcessPatchDigest(artifact.patchContent);
|
|
781
|
+
if (actual !== target.patchDigest) {
|
|
782
|
+
throw new Error(`in-process patch digest mismatch: expected ${target.patchDigest}, got ${actual}`);
|
|
783
|
+
}
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
if (artifact.patchPath !== undefined) {
|
|
787
|
+
const actual = computeInProcessPatchDigest(readRegularFile(artifact.patchPath, 'patch file'));
|
|
788
|
+
if (actual !== target.patchDigest) {
|
|
789
|
+
throw new Error(`in-process patch digest mismatch: expected ${target.patchDigest}, got ${actual}`);
|
|
790
|
+
}
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
const manifestPatch = join(stagedDir, 'cordis.patch.yml');
|
|
794
|
+
const manifestStat = lstatSync(manifestPatch, { throwIfNoEntry: false });
|
|
795
|
+
if (manifestStat && !manifestStat.isSymbolicLink() && manifestStat.isFile()
|
|
796
|
+
&& artifact.config === undefined && artifact.inject === undefined && candidateProfileText === undefined) {
|
|
797
|
+
const actual = computeInProcessPatchDigest(readFileSync(manifestPatch));
|
|
798
|
+
if (actual !== target.patchDigest) {
|
|
799
|
+
throw new Error(`in-process patch digest mismatch: expected ${target.patchDigest}, got ${actual}`);
|
|
800
|
+
}
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
if (candidateProfileText !== undefined) {
|
|
804
|
+
const profilePatch = computeInProcessPatchDigest(candidateProfileText);
|
|
805
|
+
if (profilePatch === target.patchDigest)
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
const canonicalPatch = computeInProcessPatchDigest({ config: artifact.config, inject: artifact.inject });
|
|
809
|
+
if (canonicalPatch === target.patchDigest)
|
|
810
|
+
return;
|
|
811
|
+
if (manifestStat && !manifestStat.isSymbolicLink() && manifestStat.isFile()) {
|
|
812
|
+
const actual = computeInProcessPatchDigest(readFileSync(manifestPatch));
|
|
813
|
+
if (actual === target.patchDigest)
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
throw new Error(`in-process patch digest mismatch: expected ${target.patchDigest}`);
|
|
817
|
+
}
|
|
818
|
+
function buildNextProfileText(tree, localEntryId, nextSpecifier, artifact) {
|
|
819
|
+
const entries = cloneEntryList(tree);
|
|
820
|
+
const idx = entries.findIndex(item => item.id === localEntryId);
|
|
821
|
+
if (idx === -1)
|
|
822
|
+
throw new Error(`entry ${localEntryId} is missing from profile cache`);
|
|
823
|
+
const updated = { ...entries[idx], name: nextSpecifier };
|
|
824
|
+
if (artifact.config !== undefined)
|
|
825
|
+
updated.config = artifact.config;
|
|
826
|
+
if (artifact.inject !== undefined)
|
|
827
|
+
updated.inject = artifact.inject;
|
|
828
|
+
entries[idx] = updated;
|
|
829
|
+
return serializeTreeData(tree, entries);
|
|
830
|
+
}
|
|
831
|
+
function snapshotOriginalArtifactBackup(beforeSpec, tree, targetPackage, profileFile, stagingDir) {
|
|
832
|
+
const isPathSpec = beforeSpec.startsWith('.') || beforeSpec.startsWith('file://') || isAbsolute(beforeSpec);
|
|
833
|
+
if (!isPathSpec)
|
|
834
|
+
return undefined;
|
|
835
|
+
const entryAbs = beforeSpec.startsWith('file://')
|
|
836
|
+
? fileURLToPath(beforeSpec)
|
|
837
|
+
: tree.ctx?.baseUrl
|
|
838
|
+
? fileURLToPath(new URL(beforeSpec, tree.ctx.baseUrl))
|
|
839
|
+
: resolve(dirname(profileFile), beforeSpec);
|
|
840
|
+
if (!existsSync(entryAbs) || isInsideRoot(stagingDir, entryAbs))
|
|
841
|
+
return undefined;
|
|
842
|
+
const pkgRoot = findPackageRootForEntry(entryAbs);
|
|
843
|
+
const backupRoot = join(stagingDir, '.baseline-backups', sanitizeSlug(targetPackage));
|
|
844
|
+
mkdirSync(backupRoot, { recursive: true });
|
|
845
|
+
if (pkgRoot && pkgRoot.packageName === targetPackage) {
|
|
846
|
+
const beforeDigest = computeInProcessArtifactDigest({ sourceDir: pkgRoot.packageRoot });
|
|
847
|
+
const dest = join(backupRoot, `${beforeDigest}`);
|
|
848
|
+
if (!existsSync(dest)) {
|
|
849
|
+
copyRegularTree(pkgRoot.packageRoot, dest, walkRegularFiles(pkgRoot.packageRoot));
|
|
850
|
+
}
|
|
851
|
+
const relEntry = relative(pkgRoot.packageRoot, entryAbs);
|
|
852
|
+
return { kind: 'dir', backupPath: join(dest, relEntry), beforeDigest, targetName: beforeSpec };
|
|
853
|
+
}
|
|
854
|
+
const stat = lstatSync(entryAbs);
|
|
855
|
+
if (!stat.isSymbolicLink() && stat.isFile()) {
|
|
856
|
+
const beforeDigest = computeInProcessArtifactDigest({ entryPath: entryAbs });
|
|
857
|
+
const destDir = join(backupRoot, `${beforeDigest}`);
|
|
858
|
+
const dest = join(destDir, sanitizeSlug(basename(entryAbs)));
|
|
859
|
+
if (!existsSync(dest)) {
|
|
860
|
+
mkdirSync(destDir, { recursive: true });
|
|
861
|
+
copyFileSync(entryAbs, dest);
|
|
862
|
+
}
|
|
863
|
+
return { kind: 'file', backupPath: dest, beforeDigest, targetName: beforeSpec };
|
|
864
|
+
}
|
|
865
|
+
return undefined;
|
|
866
|
+
}
|
|
867
|
+
async function probeRestoredBaseline(baseline, target, expectedHostGeneration, nonTargetSnapshots, profileFile) {
|
|
868
|
+
let checks = 0;
|
|
869
|
+
let failures = 0;
|
|
870
|
+
const failedChecks = [];
|
|
871
|
+
const bad = (check) => { checks += 1; failures += 1; failedChecks.push(check); };
|
|
872
|
+
const good = () => { checks += 1; };
|
|
873
|
+
const observations = {};
|
|
874
|
+
try {
|
|
875
|
+
const mount = resolveMount(target, { verifyPackageMatch: false });
|
|
876
|
+
const entry = mount.target;
|
|
877
|
+
const fiber = fiberOf(entry);
|
|
878
|
+
const restoredContent = await readFile(profileFile, 'utf8');
|
|
879
|
+
const hostGeneration = options.hostGeneration();
|
|
880
|
+
if (restoredContent === baseline.beforeProfileContent
|
|
881
|
+
|| computeInProcessPatchDigest(restoredContent) === computeInProcessPatchDigest(baseline.beforeProfileContent)) {
|
|
882
|
+
good();
|
|
883
|
+
}
|
|
884
|
+
else {
|
|
885
|
+
bad('profile-restored');
|
|
886
|
+
}
|
|
887
|
+
if (fiber !== undefined && fiber.state === ACTIVE && fiber.uid !== null)
|
|
888
|
+
good();
|
|
889
|
+
else
|
|
890
|
+
bad('restored-fiber-active');
|
|
891
|
+
if (fiber?.committed !== undefined && fiber.committed !== null)
|
|
892
|
+
good();
|
|
893
|
+
else
|
|
894
|
+
bad('restored-store-committed');
|
|
895
|
+
if (entry?.moduleNamespace !== undefined && entry.moduleNamespace === baseline.beforeModuleNamespace) {
|
|
896
|
+
good();
|
|
897
|
+
}
|
|
898
|
+
else {
|
|
899
|
+
bad('restored-module-namespace');
|
|
900
|
+
}
|
|
901
|
+
if (verifyNonTargetEntries(mount.tree, nonTargetSnapshots))
|
|
902
|
+
good();
|
|
903
|
+
else
|
|
904
|
+
bad('non-target-undisturbed');
|
|
905
|
+
if (hostGeneration === expectedHostGeneration)
|
|
906
|
+
good();
|
|
907
|
+
else
|
|
908
|
+
bad('host-generation-unchanged');
|
|
909
|
+
observations.hostGeneration = hostGeneration;
|
|
910
|
+
observations.restoredUid = fiber?.uid ?? null;
|
|
911
|
+
observations.restoredState = fiber?.state ?? -1;
|
|
912
|
+
}
|
|
913
|
+
catch (error) {
|
|
914
|
+
bad('restore-mount-resolvable');
|
|
915
|
+
observations.error = error instanceof Error ? error.message : String(error);
|
|
916
|
+
}
|
|
917
|
+
return makeProbeResult(checks, failures, failures === 0, 1, failedChecks, observations);
|
|
918
|
+
}
|
|
919
|
+
async function executeArtifactRollback(baseline, tree, target, expectedHostGeneration, nonTargetSnapshots, profileFile) {
|
|
920
|
+
const existingCandidate = tree.store?.[baseline.localEntryId];
|
|
921
|
+
if (existingCandidate) {
|
|
922
|
+
await disposeTargetEntry(tree, baseline.localEntryId, existingCandidate);
|
|
923
|
+
}
|
|
924
|
+
let profileContentToRestore = baseline.beforeProfileContent;
|
|
925
|
+
// If the prior unstaged file vanished on disk, swap the baseline entry name to our backup copy.
|
|
926
|
+
if (baseline.backedUpSource !== undefined) {
|
|
927
|
+
const priorTarget = baseline.backedUpSource.targetName;
|
|
928
|
+
const resolvedPrior = priorTarget.startsWith('file://')
|
|
929
|
+
? fileURLToPath(priorTarget)
|
|
930
|
+
: tree.ctx?.baseUrl
|
|
931
|
+
? fileURLToPath(new URL(priorTarget, tree.ctx.baseUrl))
|
|
932
|
+
: resolve(dirname(profileFile), priorTarget);
|
|
933
|
+
if (!existsSync(resolvedPrior)) {
|
|
934
|
+
const entries = cloneEntryList(tree);
|
|
935
|
+
const idx = entries.findIndex(item => item.id === baseline.localEntryId);
|
|
936
|
+
if (idx !== -1) {
|
|
937
|
+
entries[idx] = {
|
|
938
|
+
...entries[idx],
|
|
939
|
+
name: toRelativeImportSpecifier(dirname(profileFile), baseline.backedUpSource.backupPath),
|
|
940
|
+
};
|
|
941
|
+
profileContentToRestore = serializeTreeData(tree, entries);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
await withDeadline(async () => {
|
|
946
|
+
writeTextAtomic(profileFile, profileContentToRestore);
|
|
947
|
+
// Force Include._read() to apply restored entries even if profileFile was never mutated (e.g. disposer failure).
|
|
948
|
+
if (tree.cache && tree.cache.content === profileContentToRestore) {
|
|
949
|
+
tree.cache.content = '';
|
|
950
|
+
}
|
|
951
|
+
await refreshTree(tree);
|
|
952
|
+
if (!tree.store?.[baseline.localEntryId] && typeof tree.root?.update === 'function') {
|
|
953
|
+
await tree.root.update(cloneEntryList(tree));
|
|
954
|
+
if (typeof tree.await === 'function')
|
|
955
|
+
await tree.await();
|
|
956
|
+
}
|
|
957
|
+
const restoredEntry = tree.store?.[baseline.localEntryId];
|
|
958
|
+
await settleEntryAndFiber(restoredEntry);
|
|
959
|
+
}, 'rollback');
|
|
960
|
+
const rollbackProbe = await probeRestoredBaseline(baseline, target, expectedHostGeneration, nonTargetSnapshots, profileFile);
|
|
961
|
+
return { restored: rollbackProbe.failures === 0 && rollbackProbe.reloaded, rollbackProbe };
|
|
962
|
+
}
|
|
963
|
+
return {
|
|
964
|
+
snapshot: () => ({ hostGeneration: options.hostGeneration(), inProcessGeneration }),
|
|
965
|
+
async activate(input) {
|
|
966
|
+
assertRuntimeActive();
|
|
967
|
+
if (!DIGEST.test(input.warrantDigest))
|
|
968
|
+
throw new Error('in-process reload warrant digest is invalid');
|
|
969
|
+
const artifactReplace = input.target.artifact !== undefined || input.mode === 'artifact-replace';
|
|
970
|
+
assertTarget(input.target, { allowSubtreeChange: artifactReplace });
|
|
971
|
+
const currentHostGeneration = options.hostGeneration();
|
|
972
|
+
if (input.previousHostGeneration !== currentHostGeneration) {
|
|
973
|
+
throw new Error('in-process reload warrant is bound to another Host generation');
|
|
974
|
+
}
|
|
975
|
+
if (input.mode === 'artifact-replace' && input.target.artifact === undefined) {
|
|
976
|
+
throw new Error('in-process artifact replacement requires a target artifact descriptor');
|
|
977
|
+
}
|
|
978
|
+
const before = await capture(input.target);
|
|
979
|
+
const observedGeneration = before.identity.hostGeneration;
|
|
980
|
+
if (observedGeneration !== input.previousHostGeneration) {
|
|
981
|
+
throw new Error('in-process reload started across a Host generation change');
|
|
982
|
+
}
|
|
983
|
+
const { profileFile, stagingDir } = before.mount;
|
|
984
|
+
if (!artifactReplace) {
|
|
985
|
+
try {
|
|
986
|
+
await withDeadline(async () => {
|
|
987
|
+
assertRuntimeActive();
|
|
988
|
+
if (options.apply)
|
|
989
|
+
await options.apply();
|
|
990
|
+
await refreshTree(before.mount.tree);
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
catch (error) {
|
|
994
|
+
inProcessGeneration += 1;
|
|
995
|
+
throw error;
|
|
996
|
+
}
|
|
997
|
+
inProcessGeneration += 1;
|
|
998
|
+
const { probe: result } = await probeConfigOnly(input.target, before.identity, input.previousHostGeneration);
|
|
999
|
+
return {
|
|
1000
|
+
previousHostGeneration: before.identity.hostGeneration,
|
|
1001
|
+
currentHostGeneration: options.hostGeneration(),
|
|
1002
|
+
previousInProcessGeneration: input.previousInProcessGeneration,
|
|
1003
|
+
currentInProcessGeneration: inProcessGeneration,
|
|
1004
|
+
probe: result,
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
// Immutable digest-verified artifact replacement path.
|
|
1008
|
+
const artifactSpec = input.target.artifact;
|
|
1009
|
+
const staged = stageInProcessArtifact({ target: input.target, artifact: artifactSpec, stagingDir });
|
|
1010
|
+
const beforeProfileContent = await readFile(profileFile, 'utf8');
|
|
1011
|
+
const nextRelativeSpecifier = toRelativeImportSpecifier(dirname(profileFile), staged.entryFilePath);
|
|
1012
|
+
const hasExplicitPatch = artifactSpec.patchContent !== undefined || artifactSpec.patchPath !== undefined;
|
|
1013
|
+
if (hasExplicitPatch) {
|
|
1014
|
+
verifyCandidatePatchDigest(artifactSpec, input.target, staged.stagedDir, undefined);
|
|
1015
|
+
}
|
|
1016
|
+
let nextProfileText;
|
|
1017
|
+
if (options.apply) {
|
|
1018
|
+
try {
|
|
1019
|
+
await withDeadline(async () => {
|
|
1020
|
+
assertRuntimeActive();
|
|
1021
|
+
await options.apply();
|
|
1022
|
+
}, 'apply');
|
|
1023
|
+
nextProfileText = await readFile(profileFile, 'utf8');
|
|
1024
|
+
if (!hasExplicitPatch) {
|
|
1025
|
+
verifyCandidatePatchDigest(artifactSpec, input.target, staged.stagedDir, nextProfileText);
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
catch (error) {
|
|
1029
|
+
writeTextAtomic(profileFile, beforeProfileContent);
|
|
1030
|
+
throw error;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
else {
|
|
1034
|
+
nextProfileText = buildNextProfileText(before.mount.tree, before.mount.localEntryId, nextRelativeSpecifier, artifactSpec);
|
|
1035
|
+
if (!hasExplicitPatch) {
|
|
1036
|
+
verifyCandidatePatchDigest(artifactSpec, input.target, staged.stagedDir, nextProfileText);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
const backedUpSource = snapshotOriginalArtifactBackup(before.identity.entry.options?.name ?? '', before.mount.tree, input.target.package, profileFile, stagingDir);
|
|
1040
|
+
const baseline = {
|
|
1041
|
+
warrantDigest: input.warrantDigest,
|
|
1042
|
+
localEntryId: before.mount.localEntryId,
|
|
1043
|
+
targetPackage: input.target.package,
|
|
1044
|
+
beforeProfileContent,
|
|
1045
|
+
beforeModuleNamespace: before.identity.moduleNamespace,
|
|
1046
|
+
beforeSpec: before.identity.entry.options?.name ?? '',
|
|
1047
|
+
...(backedUpSource === undefined ? {} : { backedUpSource }),
|
|
1048
|
+
};
|
|
1049
|
+
const nonTargetSnapshots = captureNonTargetEntries(before.mount.tree, before.mount.localEntryId);
|
|
1050
|
+
let fibersDisposed = 0;
|
|
1051
|
+
const failedChecks = [];
|
|
1052
|
+
const startupErrors = [];
|
|
1053
|
+
let afterEntry;
|
|
1054
|
+
let afterFiber;
|
|
1055
|
+
let disposeOutcome;
|
|
1056
|
+
// Phase 1: Dispose the existing fiber cleanly before updating the profile and refreshing the tree.
|
|
1057
|
+
disposeOutcome = await disposeTargetEntry(before.mount.tree, before.mount.localEntryId, before.identity.entry);
|
|
1058
|
+
fibersDisposed += disposeOutcome.disposedCount;
|
|
1059
|
+
if (!disposeOutcome.oldFiberDisposed || disposeOutcome.errors.length > 0) {
|
|
1060
|
+
if (!disposeOutcome.oldFiberDisposed)
|
|
1061
|
+
failedChecks.push('old-fiber-disposed');
|
|
1062
|
+
if (disposeOutcome.errors.length > 0)
|
|
1063
|
+
failedChecks.push('disposer-clean');
|
|
1064
|
+
}
|
|
1065
|
+
else {
|
|
1066
|
+
// Phase 2: Persist verified profile update (if not already written by options.apply) & reload entry.
|
|
1067
|
+
const collector = attachErrorCollector();
|
|
1068
|
+
try {
|
|
1069
|
+
assertRuntimeActive();
|
|
1070
|
+
if (!options.apply)
|
|
1071
|
+
writeTextAtomic(profileFile, nextProfileText);
|
|
1072
|
+
await withDeadline(async () => {
|
|
1073
|
+
await refreshTree(before.mount.tree);
|
|
1074
|
+
afterEntry = before.mount.tree.store?.[before.mount.localEntryId];
|
|
1075
|
+
const settleErrors = await settleEntryAndFiber(afterEntry);
|
|
1076
|
+
startupErrors.push(...settleErrors);
|
|
1077
|
+
}, 'refresh');
|
|
1078
|
+
afterFiber = fiberOf(afterEntry);
|
|
1079
|
+
}
|
|
1080
|
+
catch (error) {
|
|
1081
|
+
startupErrors.push(error instanceof Error ? error.message : String(error));
|
|
1082
|
+
}
|
|
1083
|
+
finally {
|
|
1084
|
+
startupErrors.push(...collector.errors);
|
|
1085
|
+
collector.detach();
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
// Phase 3: Run strict post-reload lifecycle assertions.
|
|
1089
|
+
let checks = 0;
|
|
1090
|
+
let failures = 0;
|
|
1091
|
+
const failCheck = (name) => { checks += 1; failures += 1; if (!failedChecks.includes(name))
|
|
1092
|
+
failedChecks.push(name); };
|
|
1093
|
+
const passCheck = () => { checks += 1; };
|
|
1094
|
+
const afterHostGeneration = options.hostGeneration();
|
|
1095
|
+
if (afterHostGeneration === input.previousHostGeneration && observedGeneration === input.previousHostGeneration)
|
|
1096
|
+
passCheck();
|
|
1097
|
+
else
|
|
1098
|
+
failCheck('host-generation-unchanged');
|
|
1099
|
+
if (pid === before.identity.pid && invocationId === before.identity.invocationId)
|
|
1100
|
+
passCheck();
|
|
1101
|
+
else
|
|
1102
|
+
failCheck('process-identity');
|
|
1103
|
+
if (disposeOutcome.oldFiberDisposed && fibersDisposed >= 1)
|
|
1104
|
+
passCheck();
|
|
1105
|
+
else
|
|
1106
|
+
failCheck('old-fiber-disposed');
|
|
1107
|
+
if (disposeOutcome.errors.length === 0)
|
|
1108
|
+
passCheck();
|
|
1109
|
+
else
|
|
1110
|
+
failCheck('disposer-clean');
|
|
1111
|
+
if (startupErrors.length === 0)
|
|
1112
|
+
passCheck();
|
|
1113
|
+
else
|
|
1114
|
+
failCheck('startup-clean');
|
|
1115
|
+
const afterProfileDigest = await profileDigest(profileFile);
|
|
1116
|
+
if (afterProfileDigest !== before.identity.profileDigest)
|
|
1117
|
+
passCheck();
|
|
1118
|
+
else
|
|
1119
|
+
failCheck('profile-changed');
|
|
1120
|
+
if (afterEntry !== undefined && afterEntry !== before.identity.entry && afterFiber !== undefined)
|
|
1121
|
+
passCheck();
|
|
1122
|
+
else
|
|
1123
|
+
failCheck('target-present');
|
|
1124
|
+
if (afterFiber !== undefined && afterFiber !== before.identity.fiber && afterFiber.uid !== null && afterFiber.uid !== before.identity.uid)
|
|
1125
|
+
passCheck();
|
|
1126
|
+
else
|
|
1127
|
+
failCheck('new-fiber-replaced');
|
|
1128
|
+
if (afterFiber?.state === PENDING) {
|
|
1129
|
+
failCheck('injections-satisfied');
|
|
1130
|
+
}
|
|
1131
|
+
else if (afterFiber?.state === FAILED) {
|
|
1132
|
+
failCheck('fiber-failed');
|
|
1133
|
+
}
|
|
1134
|
+
else if (afterFiber?.state === ACTIVE) {
|
|
1135
|
+
passCheck();
|
|
1136
|
+
}
|
|
1137
|
+
else {
|
|
1138
|
+
failCheck('fiber-active');
|
|
1139
|
+
}
|
|
1140
|
+
if (afterFiber?.committed !== undefined && afterFiber.committed !== null && afterFiber.committed !== before.identity.committed)
|
|
1141
|
+
passCheck();
|
|
1142
|
+
else
|
|
1143
|
+
failCheck('store-rebuilt');
|
|
1144
|
+
if (afterEntry?.moduleNamespace !== undefined && afterEntry.moduleNamespace !== before.identity.moduleNamespace)
|
|
1145
|
+
passCheck();
|
|
1146
|
+
else
|
|
1147
|
+
failCheck('module-namespace-updated');
|
|
1148
|
+
if (verifyNonTargetEntries(before.mount.tree, nonTargetSnapshots))
|
|
1149
|
+
passCheck();
|
|
1150
|
+
else
|
|
1151
|
+
failCheck('non-target-undisturbed');
|
|
1152
|
+
inProcessGeneration += 1;
|
|
1153
|
+
const observations = {
|
|
1154
|
+
mode: 'artifact-replace',
|
|
1155
|
+
stagedArtifactDigest: staged.artifactDigest,
|
|
1156
|
+
fibersDisposed,
|
|
1157
|
+
beforeUid: before.identity.uid,
|
|
1158
|
+
afterUid: afterFiber?.uid ?? null,
|
|
1159
|
+
afterState: afterFiber?.state ?? -1,
|
|
1160
|
+
beforeProfileDigest: before.identity.profileDigest,
|
|
1161
|
+
afterProfileDigest,
|
|
1162
|
+
pid,
|
|
1163
|
+
invocationId,
|
|
1164
|
+
hostGeneration: afterHostGeneration,
|
|
1165
|
+
startupErrors,
|
|
1166
|
+
disposerErrors: disposeOutcome.errors,
|
|
1167
|
+
};
|
|
1168
|
+
if (failures === 0) {
|
|
1169
|
+
lastBaseline = baseline;
|
|
1170
|
+
return {
|
|
1171
|
+
previousHostGeneration: observedGeneration,
|
|
1172
|
+
currentHostGeneration: options.hostGeneration(),
|
|
1173
|
+
previousInProcessGeneration: input.previousInProcessGeneration,
|
|
1174
|
+
currentInProcessGeneration: inProcessGeneration,
|
|
1175
|
+
probe: makeProbeResult(checks, failures, true, fibersDisposed, failedChecks, observations),
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
// Phase 4: Automatic rollback to the exact prior immutable artifact and profile patch.
|
|
1179
|
+
const rollbackResult = await executeArtifactRollback(baseline, before.mount.tree, input.target, input.previousHostGeneration, nonTargetSnapshots, profileFile);
|
|
1180
|
+
if (rollbackResult.restored) {
|
|
1181
|
+
baseline.autoRolledBack = {
|
|
1182
|
+
inProcessGeneration,
|
|
1183
|
+
restoredProfileDigest: computeInProcessPatchDigest(baseline.beforeProfileContent),
|
|
1184
|
+
nonTargetSnapshots,
|
|
1185
|
+
};
|
|
1186
|
+
lastBaseline = baseline;
|
|
1187
|
+
}
|
|
1188
|
+
return {
|
|
1189
|
+
previousHostGeneration: observedGeneration,
|
|
1190
|
+
currentHostGeneration: options.hostGeneration(),
|
|
1191
|
+
previousInProcessGeneration: input.previousInProcessGeneration,
|
|
1192
|
+
currentInProcessGeneration: inProcessGeneration,
|
|
1193
|
+
probe: makeProbeResult(checks, failures, false, fibersDisposed, failedChecks, observations, {
|
|
1194
|
+
rolledBack: rollbackResult.restored,
|
|
1195
|
+
rollbackProbe: rollbackResult.rollbackProbe,
|
|
1196
|
+
}),
|
|
1197
|
+
};
|
|
1198
|
+
},
|
|
1199
|
+
async rollback(input) {
|
|
1200
|
+
assertRuntimeActive();
|
|
1201
|
+
if (!DIGEST.test(input.warrantDigest))
|
|
1202
|
+
throw new Error('in-process reload warrant digest is invalid');
|
|
1203
|
+
const allowSubtreeChange = input.target.artifact !== undefined
|
|
1204
|
+
|| (lastBaseline !== undefined
|
|
1205
|
+
&& lastBaseline.warrantDigest === input.warrantDigest
|
|
1206
|
+
&& lastBaseline.targetPackage === input.target.package);
|
|
1207
|
+
assertTarget(input.target, { allowSubtreeChange });
|
|
1208
|
+
const currentHostGeneration = options.hostGeneration();
|
|
1209
|
+
const mountBefore = resolveMount(input.target, { allowMissingTarget: true, verifyPackageMatch: false });
|
|
1210
|
+
// If this runtime instance already auto-rolled back cleanly for this transition, confirm the live serving tree.
|
|
1211
|
+
if (lastBaseline !== undefined
|
|
1212
|
+
&& lastBaseline.warrantDigest === input.warrantDigest
|
|
1213
|
+
&& lastBaseline.targetPackage === input.target.package
|
|
1214
|
+
&& !options.restore) {
|
|
1215
|
+
const baseline = lastBaseline;
|
|
1216
|
+
if (baseline.autoRolledBack !== undefined
|
|
1217
|
+
&& (baseline.autoRolledBack.inProcessGeneration === input.reloadedInProcessGeneration
|
|
1218
|
+
|| baseline.autoRolledBack.inProcessGeneration === input.reloadedInProcessGeneration + 1)) {
|
|
1219
|
+
inProcessGeneration += 1;
|
|
1220
|
+
const resultProbe = await probeRestoredBaseline(baseline, input.target, currentHostGeneration, baseline.autoRolledBack.nonTargetSnapshots, mountBefore.profileFile);
|
|
1221
|
+
const profileRestored = resultProbe.failures === 0;
|
|
1222
|
+
return {
|
|
1223
|
+
hostGeneration: options.hostGeneration(),
|
|
1224
|
+
inProcessGeneration,
|
|
1225
|
+
restored: profileRestored && resultProbe.reloaded,
|
|
1226
|
+
profileRestored,
|
|
1227
|
+
probe: resultProbe,
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
// Explicit rollback after a previously succeeded artifact replacement (`status === 'reloaded'`).
|
|
1231
|
+
const nonTargetSnapshots = captureNonTargetEntries(mountBefore.tree, baseline.localEntryId);
|
|
1232
|
+
try {
|
|
1233
|
+
const outcome = await executeArtifactRollback(baseline, mountBefore.tree, input.target, currentHostGeneration, nonTargetSnapshots, mountBefore.profileFile);
|
|
1234
|
+
inProcessGeneration += 1;
|
|
1235
|
+
return {
|
|
1236
|
+
hostGeneration: options.hostGeneration(),
|
|
1237
|
+
inProcessGeneration,
|
|
1238
|
+
restored: outcome.restored,
|
|
1239
|
+
profileRestored: outcome.rollbackProbe.failures === 0,
|
|
1240
|
+
probe: outcome.rollbackProbe,
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
catch (error) {
|
|
1244
|
+
inProcessGeneration += 1;
|
|
1245
|
+
throw error;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
// Legacy / config-only rollback path (including external caller-supplied `options.restore`).
|
|
1249
|
+
const before = await capture(input.target);
|
|
1250
|
+
if (before.identity.hostGeneration !== currentHostGeneration) {
|
|
1251
|
+
throw new Error('in-process rollback started across a Host generation change');
|
|
1252
|
+
}
|
|
1253
|
+
let profileRestored = false;
|
|
1254
|
+
try {
|
|
1255
|
+
await withDeadline(async () => {
|
|
1256
|
+
assertRuntimeActive();
|
|
1257
|
+
if (options.restore) {
|
|
1258
|
+
await options.restore();
|
|
1259
|
+
profileRestored = true;
|
|
1260
|
+
}
|
|
1261
|
+
await refreshTree(before.mount.tree);
|
|
1262
|
+
});
|
|
1263
|
+
}
|
|
1264
|
+
catch (error) {
|
|
1265
|
+
inProcessGeneration += 1;
|
|
1266
|
+
throw error;
|
|
1267
|
+
}
|
|
1268
|
+
inProcessGeneration += 1;
|
|
1269
|
+
const { probe: result } = await probeConfigOnly(input.target, before.identity, currentHostGeneration);
|
|
1270
|
+
return {
|
|
1271
|
+
hostGeneration: options.hostGeneration(),
|
|
1272
|
+
inProcessGeneration,
|
|
1273
|
+
restored: profileRestored && result.failures === 0 && result.reloaded,
|
|
1274
|
+
profileRestored,
|
|
1275
|
+
probe: result,
|
|
1276
|
+
};
|
|
1277
|
+
},
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
//# sourceMappingURL=in-process-reload-runtime.js.map
|