@vite-hub/workspace 0.0.4 → 0.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/README.md +339 -115
- package/dist/abort-BCwpdrN0.js +32 -0
- package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
- package/dist/blob-database.d.ts +474 -0
- package/dist/blob-database.js +608 -0
- package/dist/checkout.d.ts +128 -0
- package/dist/checkout.js +849 -0
- package/dist/cloudflare.d.ts +6 -7
- package/dist/cloudflare.js +1 -1
- package/dist/config-B-863EgC.js +15 -0
- package/dist/config-BAgL2dtB.js +1076 -0
- package/dist/{config-DE9xlaIw.d.ts → config-BQKcPawI.d.ts} +1 -2
- package/dist/discard-CNNtCozM.js +8 -0
- package/dist/durability.d.ts +22 -0
- package/dist/durability.js +70 -0
- package/dist/error-diagnostics-CtKjGtGb.js +188 -0
- package/dist/error-diagnostics-DSkCJC_L.js +266 -0
- package/dist/file-2pFYNtsU.js +22 -0
- package/dist/{files-Q6xZjDHA.js → files-BOo4SbwE.js} +3 -3
- package/dist/files.d.ts +38 -0
- package/dist/files.js +6 -0
- package/dist/{github-DHnjxQIX.js → github-CrYp4v8k.js} +44 -24
- package/dist/glob-B8YGvTrZ.js +21 -0
- package/dist/glob-Cjxms1t7.js +30 -0
- package/dist/{host-DJH8cuoU.js → host-BFBpXn0N.js} +144 -77
- package/dist/{hosted-RPeJOCFz.js → hosted-KcUR_jPv.js} +303 -97
- package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
- package/dist/hosted-vercel-blob.d.ts +6 -7
- package/dist/hosted-vercel-blob.js +1 -1
- package/dist/hosted.d.ts +10 -9
- package/dist/hosted.js +2 -2
- package/dist/index.d.ts +26 -47
- package/dist/index.js +30 -100
- package/dist/internal/path.d.ts +2 -0
- package/dist/internal/path.js +2 -0
- package/dist/lifecycle-B-enk_4A.js +596 -0
- package/dist/lineage.d.ts +26 -0
- package/dist/lineage.js +76 -0
- package/dist/loader.d.ts +5 -6
- package/dist/loader.js +3 -2
- package/dist/mcp-resources-DF0F5rcL.js +39 -0
- package/dist/memory-BOexthyW.js +247 -0
- package/dist/metadata-target-CWz6KHKq.js +1589 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-C6FpR8Rr.js +389 -0
- package/dist/operations-CE2drFih.js +1234 -0
- package/dist/operations.d.ts +90 -0
- package/dist/operations.js +3 -0
- package/dist/path--wrT_Azm.js +113 -0
- package/dist/path-AxMho1wo.d.ts +7 -0
- package/dist/path-DrSIenjj.js +59 -0
- package/dist/path-zHxQUbqa.d.ts +9 -0
- package/dist/plugins-C8C0auoW.d.ts +10 -0
- package/dist/provider-9s4Ufkm5.js +1479 -0
- package/dist/providers/github/store.d.ts +3 -5
- package/dist/providers/github/store.js +1 -1
- package/dist/registry-B3BBm4Ts.d.ts +19 -0
- package/dist/{registry-D3yzt8HQ.js → registry-CNphafBx.js} +60 -23
- package/dist/registry-CYNN623b.d.ts +9 -0
- package/dist/request-scope-Dw5n8bMC.js +83 -0
- package/dist/results-DgkZUmTL.js +8 -0
- package/dist/{chunk-2rV9d50f.js → rolldown-runtime-rQ84J-ij.js} +3 -4
- package/dist/runtime/assets.d.ts +3 -5
- package/dist/runtime/assets.js +7 -6
- package/dist/runtime/empty-assets-registry.d.ts +1 -2
- package/dist/runtime/empty-registry.d.ts +2 -2
- package/dist/runtime/registry.d.ts +2 -0
- package/dist/runtime/registry.js +23 -0
- package/dist/runtime/request.d.ts +4 -0
- package/dist/runtime/request.js +8 -0
- package/dist/runtime/state.d.ts +5 -4
- package/dist/runtime/state.js +8 -18
- package/dist/runtime/workspace.d.ts +1 -1
- package/dist/runtime/workspace.js +1 -1
- package/dist/runtime.d.ts +52 -17
- package/dist/runtime.js +324 -67
- package/dist/{search-BpiCF2Tw.js → search-C_RfoM2j.js} +10 -9
- package/dist/server-8tGltlGz.js +303 -0
- package/dist/server.d.ts +36 -39
- package/dist/server.js +2 -328
- package/dist/shared-B3_EUk89.js +848 -0
- package/dist/source-metadata.d.ts +10 -7
- package/dist/source-metadata.js +12 -12
- package/dist/state-BISnUf1s.d.ts +35 -0
- package/dist/{ai-BqCC8BpY.js → state-DbrW-njQ.js} +237 -114
- package/dist/store-ybhyD38Z.js +1873 -0
- package/dist/{sync-DnTQwt8r.js → sync-CCD_VYC8.js} +61 -41
- package/dist/target-jWhTdIuF.js +89 -0
- package/dist/test.d.ts +1 -1
- package/dist/test.js +1 -1
- package/dist/{types-CYuwjJ4V.d.ts → types-BbtwmBZ5.d.ts} +321 -35
- package/dist/use-C6lV3-wC.d.ts +321 -0
- package/dist/{use-BTNDR5Rd.js → use-CSpT5W87.js} +141 -107
- package/dist/utils-CgMZCHsX.js +616 -0
- package/dist/vite.d.ts +585 -2
- package/dist/vite.js +21369 -2
- package/dist/workspace-CYB2xZ1T.d.ts +7 -0
- package/dist/{workspace-Dq08Yn72.js → workspace-sPWn2Jxj.js} +441 -225
- package/package.json +97 -72
- package/dist/ai-CjxvGqM0.d.ts +0 -162
- package/dist/ai.d.ts +0 -3
- package/dist/ai.js +0 -2
- package/dist/collections/client.d.ts +0 -39
- package/dist/collections/client.js +0 -137
- package/dist/collections.d.ts +0 -59
- package/dist/collections.js +0 -159
- package/dist/config-Bc3c4Su1.js +0 -7904
- package/dist/config-CHLLWklZ.js +0 -36
- package/dist/file-Bc1X7pco.js +0 -23
- package/dist/glob-CEZKeZFC.js +0 -18
- package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
- package/dist/lifecycle-LrL3sA4n.js +0 -316
- package/dist/metadata-target-B0tOmVW7.js +0 -717
- package/dist/mountx.d.ts +0 -10
- package/dist/mountx.js +0 -143
- package/dist/nitro.d.ts +0 -2
- package/dist/nitro.js +0 -2
- package/dist/nuxt.d.ts +0 -26
- package/dist/nuxt.js +0 -42
- package/dist/path-Cp59koVz.js +0 -139
- package/dist/provider-B1yLjCJJ.js +0 -746
- package/dist/publish.d.ts +0 -35
- package/dist/publish.js +0 -112
- package/dist/registry-Uj6IVxes.d.ts +0 -11
- package/dist/request-execution-B-dSFlGB.js +0 -84
- package/dist/runtime-options-BsPSv5O7.js +0 -13
- package/dist/runtime-type-iEE6BjQJ.js +0 -34
- package/dist/shared-DTR1Hhma.js +0 -331
- package/dist/state-tYcRWEh2.d.ts +0 -26
- package/dist/store-Dt_Jyys3.js +0 -608
- package/dist/target-D4Bqb1eH.js +0 -11
- package/dist/token-CVzURBxC.js +0 -61
- package/dist/use-BiHzt0xA.d.ts +0 -103
- package/dist/vite-BptCrpv2.js +0 -4526
- package/dist/vite-CtA9guIM.d.ts +0 -66
- package/dist/workspace-Xddf4G1B.d.ts +0 -6
|
@@ -0,0 +1,1589 @@
|
|
|
1
|
+
import { s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
|
|
2
|
+
import { n as resolveWorkspaceStoreTarget, o as copyJsonFileMetadata, t as forwardWorkspaceStoreTarget } from "./target-jWhTdIuF.js";
|
|
3
|
+
import { f as sha256, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, o as isWorkspaceBytes, t as contentStreamChunks } from "./path--wrT_Azm.js";
|
|
4
|
+
import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
|
|
5
|
+
import { t as searchText } from "./search-C_RfoM2j.js";
|
|
6
|
+
import { a as normalizeWorkspaceSources, c as sourceMountIntersectsPath, f as prepareWorkspaceSource, n as createSourceContext, s as sourceMountContainsPath } from "./config-BAgL2dtB.js";
|
|
7
|
+
import { posix } from "node:path";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
//#region src/storage/identity.ts
|
|
10
|
+
const aliases = /* @__PURE__ */ new WeakMap();
|
|
11
|
+
const stableIdentities = /* @__PURE__ */ new WeakSet();
|
|
12
|
+
function workspaceStoreIdentity(store) {
|
|
13
|
+
let identity = store;
|
|
14
|
+
const seen = /* @__PURE__ */ new Set();
|
|
15
|
+
while (true) {
|
|
16
|
+
const next = aliases.get(identity);
|
|
17
|
+
if (!next || seen.has(next)) return identity;
|
|
18
|
+
seen.add(identity);
|
|
19
|
+
identity = next;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function registerWorkspaceStoreAlias(alias, store) {
|
|
23
|
+
const aliasIdentity = workspaceStoreIdentity(alias);
|
|
24
|
+
const storeIdentity = workspaceStoreIdentity(store);
|
|
25
|
+
if (aliasIdentity === storeIdentity) return;
|
|
26
|
+
if (stableIdentities.has(aliasIdentity)) aliases.set(storeIdentity, aliasIdentity);
|
|
27
|
+
else {
|
|
28
|
+
aliases.set(aliasIdentity, storeIdentity);
|
|
29
|
+
stableIdentities.add(storeIdentity);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/sources/file-ownership.ts
|
|
34
|
+
const activeCheckpoints = /* @__PURE__ */ new WeakMap();
|
|
35
|
+
const checkpointMetaKey = (path) => `workspace-file-checkpoint:${encodeURIComponent(normalizeWorkspacePath(path))}`;
|
|
36
|
+
const volatileOwners = /* @__PURE__ */ new WeakMap();
|
|
37
|
+
const fileOwnerMetaKey = (path) => `workspace-file-owner:${encodeURIComponent(normalizeWorkspacePath(path))}`;
|
|
38
|
+
function volatileFileOwners(store) {
|
|
39
|
+
const identity = workspaceStoreIdentity(store);
|
|
40
|
+
let owners = volatileOwners.get(identity);
|
|
41
|
+
if (!owners) {
|
|
42
|
+
owners = /* @__PURE__ */ new Map();
|
|
43
|
+
volatileOwners.set(identity, owners);
|
|
44
|
+
}
|
|
45
|
+
return owners;
|
|
46
|
+
}
|
|
47
|
+
async function beginWorkspaceFileCheckpoint(store, path) {
|
|
48
|
+
if (!store.getMeta || !store.setMeta) return void 0;
|
|
49
|
+
const token = crypto.randomUUID();
|
|
50
|
+
const current = await store.getMeta(checkpointMetaKey(path));
|
|
51
|
+
const currentRecord = current && typeof current === "object" ? current : void 0;
|
|
52
|
+
const previous = currentRecord ? Object.hasOwn(currentRecord, "committed") && currentRecord.committed === true && Object.hasOwn(currentRecord, "token") ? currentRecord.token : Object.hasOwn(currentRecord, "previous") ? currentRecord.previous : void 0 : void 0;
|
|
53
|
+
await store.setMeta(checkpointMetaKey(path), {
|
|
54
|
+
token,
|
|
55
|
+
committed: false,
|
|
56
|
+
previous
|
|
57
|
+
});
|
|
58
|
+
const identity = workspaceStoreIdentity(store);
|
|
59
|
+
let checkpoints = activeCheckpoints.get(identity);
|
|
60
|
+
if (!checkpoints) {
|
|
61
|
+
checkpoints = /* @__PURE__ */ new Map();
|
|
62
|
+
activeCheckpoints.set(identity, checkpoints);
|
|
63
|
+
}
|
|
64
|
+
checkpoints.set(normalizeWorkspacePath(path), token);
|
|
65
|
+
return token;
|
|
66
|
+
}
|
|
67
|
+
function endWorkspaceFileCheckpoint(store, path) {
|
|
68
|
+
activeCheckpoints.get(workspaceStoreIdentity(store))?.delete(normalizeWorkspacePath(path));
|
|
69
|
+
}
|
|
70
|
+
async function commitWorkspaceFileCheckpoint(store, path, token) {
|
|
71
|
+
if (token) await store.setMeta(checkpointMetaKey(path), {
|
|
72
|
+
token,
|
|
73
|
+
committed: true
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async function recordWorkspaceFileOwner(store, path, owner) {
|
|
77
|
+
const checkpoint = activeCheckpoints.get(workspaceStoreIdentity(store))?.get(normalizeWorkspacePath(path));
|
|
78
|
+
if (checkpoint) owner = {
|
|
79
|
+
...owner,
|
|
80
|
+
checkpoint
|
|
81
|
+
};
|
|
82
|
+
if (!store.getMeta || !store.setMeta) {
|
|
83
|
+
volatileFileOwners(store).set(fileOwnerMetaKey(path), owner);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
await store.setMeta(fileOwnerMetaKey(path), owner);
|
|
88
|
+
volatileOwners.get(workspaceStoreIdentity(store))?.delete(fileOwnerMetaKey(path));
|
|
89
|
+
} catch (error) {
|
|
90
|
+
volatileFileOwners(store).set(fileOwnerMetaKey(path), owner);
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async function readWorkspaceFileOwner(store, path, retireInvalidRemoval = false) {
|
|
95
|
+
const volatile = volatileOwners.get(workspaceStoreIdentity(store))?.get(fileOwnerMetaKey(path));
|
|
96
|
+
const value = volatile !== void 0 ? volatile : await store.getMeta?.(fileOwnerMetaKey(path));
|
|
97
|
+
const owner = value && typeof value === "object" ? value : void 0;
|
|
98
|
+
if (!owner || !Object.hasOwn(owner, "workspace") || typeof owner.workspace !== "string" || !Object.hasOwn(owner, "source") || typeof owner.source !== "string" || Object.hasOwn(owner, "digest") && owner.digest !== void 0 && typeof owner.digest !== "string") return void 0;
|
|
99
|
+
if (Object.hasOwn(owner, "checkpoint") && owner.checkpoint !== activeCheckpoints.get(workspaceStoreIdentity(store))?.get(normalizeWorkspacePath(path))) {
|
|
100
|
+
const checkpointRecord = await store.getMeta?.(checkpointMetaKey(path));
|
|
101
|
+
if (!checkpointRecord || typeof checkpointRecord !== "object" || !(Object.hasOwn(checkpointRecord, "token") && checkpointRecord.token === owner.checkpoint && Object.hasOwn(checkpointRecord, "committed") && checkpointRecord.committed === true || Object.hasOwn(checkpointRecord, "previous") && checkpointRecord.previous === owner.checkpoint)) {
|
|
102
|
+
if (retireInvalidRemoval) await removeWorkspaceFileOwner(store, path);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (Object.hasOwn(owner, "removing") && owner.removing === true) {
|
|
107
|
+
const current = await store.stat(path);
|
|
108
|
+
if (current?.type === "file" && (!Object.hasOwn(owner, "revision") || !owner.revision || !current.revision)) throw workspaceErrorDiagnostics.WORKSPACE_R0074({ message: `[vitehub] Cannot retry interrupted removal without a file revision: ${path}. Inspect the file and remove it explicitly if cleanup is still needed.` });
|
|
109
|
+
const remaining = current?.type === "file" ? await store.readFile(path) : void 0;
|
|
110
|
+
if (current?.type !== "file" || !Object.hasOwn(owner, "revision") || current.revision !== owner.revision || !Object.hasOwn(owner, "digest") || !owner.digest || !remaining || await sha256(remaining.content) !== owner.digest) {
|
|
111
|
+
if (retireInvalidRemoval) await removeWorkspaceFileOwner(store, path);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
workspace: owner.workspace,
|
|
117
|
+
source: owner.source,
|
|
118
|
+
digest: Object.hasOwn(owner, "digest") && typeof owner.digest === "string" ? owner.digest : void 0
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
async function removeWorkspaceFileOwner(store, path) {
|
|
122
|
+
const owners = volatileFileOwners(store);
|
|
123
|
+
owners.set(fileOwnerMetaKey(path), null);
|
|
124
|
+
if (store.getMeta && store.setMeta) {
|
|
125
|
+
await store.setMeta(fileOwnerMetaKey(path), null);
|
|
126
|
+
owners.delete(fileOwnerMetaKey(path));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async function markWorkspaceFileRemoval(store, path) {
|
|
130
|
+
const owner = await readWorkspaceFileOwner(store, path);
|
|
131
|
+
if (owner) {
|
|
132
|
+
const revision = (await store.stat(path))?.revision;
|
|
133
|
+
const removal = {
|
|
134
|
+
...owner,
|
|
135
|
+
removing: true
|
|
136
|
+
};
|
|
137
|
+
if (revision) removal.revision = revision;
|
|
138
|
+
await recordWorkspaceFileOwner(store, path, removal);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async function removeWorkspaceOwnedFile(store, path) {
|
|
142
|
+
await markWorkspaceFileRemoval(store, path);
|
|
143
|
+
await store.rm(path, { force: true });
|
|
144
|
+
await removeWorkspaceFileOwner(store, path);
|
|
145
|
+
}
|
|
146
|
+
async function withWorkspaceFileCheckpoint(store, path, write, checkpoint, rollbackCheckpoint) {
|
|
147
|
+
const previous = (await store.stat(path))?.type === "file" ? await store.readFile(path) : void 0;
|
|
148
|
+
const owner = await readWorkspaceFileOwner(store, path);
|
|
149
|
+
const token = previous ? await beginWorkspaceFileCheckpoint(store, path) : void 0;
|
|
150
|
+
try {
|
|
151
|
+
const result = await write();
|
|
152
|
+
try {
|
|
153
|
+
await checkpoint(result);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
try {
|
|
156
|
+
if (previous) try {
|
|
157
|
+
await markWorkspaceFileRemoval(store, path);
|
|
158
|
+
} finally {
|
|
159
|
+
endWorkspaceFileCheckpoint(store, path);
|
|
160
|
+
await store.writeFile(path, previous);
|
|
161
|
+
try {
|
|
162
|
+
if (owner) await recordWorkspaceFileOwner(store, path, owner);
|
|
163
|
+
else await removeWorkspaceFileOwner(store, path);
|
|
164
|
+
} finally {
|
|
165
|
+
await rollbackCheckpoint?.();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
await removeWorkspaceOwnedFile(store, path);
|
|
170
|
+
await rollbackCheckpoint?.();
|
|
171
|
+
}
|
|
172
|
+
} catch (rollbackError) {
|
|
173
|
+
throw new AggregateError([error, rollbackError], `Workspace file checkpoint and rollback failed for "${path}".`);
|
|
174
|
+
}
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
await commitWorkspaceFileCheckpoint(store, path, token);
|
|
178
|
+
return result;
|
|
179
|
+
} finally {
|
|
180
|
+
endWorkspaceFileCheckpoint(store, path);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
//#endregion
|
|
184
|
+
//#region src/sources/file-metadata.ts
|
|
185
|
+
function normalizeMetadataValue(value) {
|
|
186
|
+
if (Array.isArray(value)) return value.map(normalizeMetadataValue);
|
|
187
|
+
if (!value || Object.getPrototypeOf(value) !== Object.prototype) return value;
|
|
188
|
+
return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => [key, normalizeMetadataValue(entry)]));
|
|
189
|
+
}
|
|
190
|
+
function normalizeSourceFileMetadata(metadata) {
|
|
191
|
+
return copyJsonFileMetadata("Source", metadata, true);
|
|
192
|
+
}
|
|
193
|
+
//#endregion
|
|
194
|
+
//#region src/sources/source-items.ts
|
|
195
|
+
function normalizeWorkspaceSourceItemPath(source, rawSourcePath, options = {}) {
|
|
196
|
+
const sourcePath = normalizeSafeWorkspacePath(rawSourcePath, {
|
|
197
|
+
allowEmpty: false,
|
|
198
|
+
allowReserved: true
|
|
199
|
+
});
|
|
200
|
+
const label = options.operation ? `${options.operation} item path` : "source item path";
|
|
201
|
+
if (sourcePath.split("/").some((part) => part === ".git" || part === ".vitehub")) throw workspaceError(`[vitehub] Workspace ${label} is reserved: ${rawSourcePath}.`);
|
|
202
|
+
const mountedPath = source.mountPath ? `${source.mountPath}/${sourcePath}` : sourcePath;
|
|
203
|
+
const path = normalizeSafeWorkspacePath(mountedPath, { allowEmpty: false });
|
|
204
|
+
if (source.mountPath && !sourceMountContainsPath(source, path)) throw workspaceError(`[vitehub] Workspace ${label} escapes source mount: ${rawSourcePath}.`);
|
|
205
|
+
return {
|
|
206
|
+
path,
|
|
207
|
+
sourcePath
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function normalizeSourceItemPath(source, item, options = {}) {
|
|
211
|
+
return normalizeWorkspaceSourceItemPath(source, item.path || item.key, options);
|
|
212
|
+
}
|
|
213
|
+
//#endregion
|
|
214
|
+
//#region src/storage/mutation.ts
|
|
215
|
+
const workspaceStoreMutations = /* @__PURE__ */ new WeakMap();
|
|
216
|
+
async function withWorkspaceStoreMutation(store, operation) {
|
|
217
|
+
const identity = workspaceStoreIdentity(store);
|
|
218
|
+
const pending = (workspaceStoreMutations.get(identity) ?? Promise.resolve()).then(operation);
|
|
219
|
+
const settled = pending.then(() => {}, () => {});
|
|
220
|
+
workspaceStoreMutations.set(identity, settled);
|
|
221
|
+
try {
|
|
222
|
+
return await pending;
|
|
223
|
+
} finally {
|
|
224
|
+
if (workspaceStoreMutations.get(identity) === settled) workspaceStoreMutations.delete(identity);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
//#endregion
|
|
228
|
+
//#region src/sources/mount-grants.ts
|
|
229
|
+
/**
|
|
230
|
+
* Proof that one Source owner may change Workspace files inside one Source mount.
|
|
231
|
+
* Only the authority of the owner creates a grant. A grant is request-scoped. Do not persist it.
|
|
232
|
+
*/
|
|
233
|
+
var WorkspaceSourceMountGrant = class {
|
|
234
|
+
#mountPath;
|
|
235
|
+
#source;
|
|
236
|
+
constructor(source, mountPath) {
|
|
237
|
+
this.#mountPath = mountPath;
|
|
238
|
+
this.#source = source;
|
|
239
|
+
Object.freeze(this);
|
|
240
|
+
}
|
|
241
|
+
get mountPath() {
|
|
242
|
+
return this.#mountPath;
|
|
243
|
+
}
|
|
244
|
+
get source() {
|
|
245
|
+
return this.#source;
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
/** A root Source (empty mount) owns every Workspace path. */
|
|
249
|
+
function sourceMountOwnsPath(source, path) {
|
|
250
|
+
return !source.mountPath || path === source.mountPath || path.startsWith(`${source.mountPath}/`);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Creates the grant authority of one Source owner, for example Source Sync or Source materialization.
|
|
254
|
+
* Keep the authority private to its owner module. Grants from one authority do not unlock another authority.
|
|
255
|
+
*/
|
|
256
|
+
function createWorkspaceSourceMountAuthority(owner) {
|
|
257
|
+
const grants = /* @__PURE__ */ new WeakMap();
|
|
258
|
+
return {
|
|
259
|
+
/** Creates a grant bound to the Source key and its normalized mount. */
|
|
260
|
+
grant(source) {
|
|
261
|
+
const mountPath = normalizeSafeWorkspacePath(source.mountPath, { allowEmpty: true });
|
|
262
|
+
const grant = new WorkspaceSourceMountGrant(source.key, mountPath);
|
|
263
|
+
grants.set(grant, {
|
|
264
|
+
mountPath,
|
|
265
|
+
source: source.key
|
|
266
|
+
});
|
|
267
|
+
return grant;
|
|
268
|
+
},
|
|
269
|
+
/**
|
|
270
|
+
* Returns the Store limited to the mount of a grant from this authority.
|
|
271
|
+
* File writes, `mkdir`, and `rm` must stay inside the mount. `removeEmptyDirectory` can also remove
|
|
272
|
+
* an ancestor of the mount, because the owner created it for the mount.
|
|
273
|
+
*/
|
|
274
|
+
store(grant, store) {
|
|
275
|
+
const scope = grants.get(grant);
|
|
276
|
+
if (!scope) throw workspaceError(`[vitehub] ${owner} requires a Source mount grant to change Workspace files.`);
|
|
277
|
+
const assertInMount = (path, allowAncestor = false) => {
|
|
278
|
+
const workspacePath = normalizeSafeWorkspacePath(path, {
|
|
279
|
+
allowEmpty: true,
|
|
280
|
+
allowReserved: true
|
|
281
|
+
});
|
|
282
|
+
if (sourceMountOwnsPath(scope, workspacePath) || allowAncestor && scope.mountPath.startsWith(`${workspacePath}/`)) return path;
|
|
283
|
+
throw workspaceError(`[vitehub] ${owner} for Source ${JSON.stringify(scope.source)} cannot change ${path} outside its mount ${JSON.stringify(scope.mountPath)}.`);
|
|
284
|
+
};
|
|
285
|
+
const scoped = {
|
|
286
|
+
readFile: async (path) => await store.readFile(path),
|
|
287
|
+
writeFile: async (path, file) => await store.writeFile(assertInMount(path), file),
|
|
288
|
+
list: async (prefix, options) => await store.list(prefix, options),
|
|
289
|
+
glob: async (pattern, options) => await store.glob(pattern, options),
|
|
290
|
+
stat: async (path) => await store.stat(path),
|
|
291
|
+
mkdir: async (path, options) => await store.mkdir(assertInMount(path), options),
|
|
292
|
+
rm: async (path, options) => await store.rm(assertInMount(path), options),
|
|
293
|
+
snapshot: async (options) => await store.snapshot(options),
|
|
294
|
+
diff: async (options) => await store.diff(options)
|
|
295
|
+
};
|
|
296
|
+
if (store.writeFileConditional) scoped.writeFileConditional = async (path, file, ifDigest) => await store.writeFileConditional(assertInMount(path), file, ifDigest);
|
|
297
|
+
if (store.writeFileStream) scoped.writeFileStream = async (path, file) => await store.writeFileStream(assertInMount(path), file);
|
|
298
|
+
if (store.removeEmptyDirectory) scoped.removeEmptyDirectory = async (path) => await store.removeEmptyDirectory(assertInMount(path, true));
|
|
299
|
+
if (store.getMeta) scoped.getMeta = async (key) => await store.getMeta(key);
|
|
300
|
+
if (store.setMeta) scoped.setMeta = async (key, value) => await store.setMeta(key, value);
|
|
301
|
+
registerWorkspaceStoreAlias(scoped, store);
|
|
302
|
+
forwardWorkspaceStoreTarget(store, scoped);
|
|
303
|
+
return scoped;
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
//#endregion
|
|
308
|
+
//#region src/sources/materialization.ts
|
|
309
|
+
const startupSourcesMetaKey = (workspace) => `workspace:${workspace}:startup-sources`;
|
|
310
|
+
const startupWorkspacesMetaKey = "workspace:startup-source-workspaces";
|
|
311
|
+
const volatileSnapshots = /* @__PURE__ */ new WeakMap();
|
|
312
|
+
const volatileStartupIndexes = /* @__PURE__ */ new WeakMap();
|
|
313
|
+
const startupReconciliationByStore = /* @__PURE__ */ new WeakMap();
|
|
314
|
+
const activeStartupSourcesByStore = /* @__PURE__ */ new WeakMap();
|
|
315
|
+
const sourceMaterializationGrants = createWorkspaceSourceMountAuthority("Source materialization");
|
|
316
|
+
function sourceSnapshotMetaKey(workspace, sourceKey) {
|
|
317
|
+
return `workspace:${encodeURIComponent(workspace)}:source:${encodeURIComponent(sourceKey)}:snapshot`;
|
|
318
|
+
}
|
|
319
|
+
function sourceConfigFingerprint(source) {
|
|
320
|
+
return {
|
|
321
|
+
cache: source.cache,
|
|
322
|
+
key: source.key,
|
|
323
|
+
materialize: source.materialize,
|
|
324
|
+
mountPath: source.mountPath,
|
|
325
|
+
source: source.source.fingerprint
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
async function sourceConfigHash(source, store) {
|
|
329
|
+
const target = await resolveWorkspaceStoreTarget(store);
|
|
330
|
+
const version = {};
|
|
331
|
+
if (target?.provider === "local") version.fileMetadataVersion = 1;
|
|
332
|
+
return await sha256({
|
|
333
|
+
...version,
|
|
334
|
+
...sourceConfigFingerprint(source)
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
function isSnapshotFresh(meta, source, configHash) {
|
|
338
|
+
if (!meta || meta.status !== "ready" || meta.configHash !== configHash) return false;
|
|
339
|
+
if (!source.cache) return false;
|
|
340
|
+
const maxAge = source.cache.maxAge ?? NaN;
|
|
341
|
+
if (!Number.isFinite(maxAge)) return false;
|
|
342
|
+
if (!meta.materializedAt) return false;
|
|
343
|
+
return Date.now() - Date.parse(meta.materializedAt) <= maxAge * 1e3;
|
|
344
|
+
}
|
|
345
|
+
async function readSourceSnapshotMetadata(store, workspace, sourceKey, source) {
|
|
346
|
+
const volatile = volatileSnapshots.get(workspaceStoreIdentity(store));
|
|
347
|
+
const key = sourceSnapshotMetaKey(workspace, sourceKey);
|
|
348
|
+
if (volatile?.has(key)) return volatile.get(key);
|
|
349
|
+
const snapshot = await store.getMeta?.(sourceSnapshotMetaKey(workspace, sourceKey));
|
|
350
|
+
const recovery = await store.getMeta?.(`${sourceSnapshotMetaKey(workspace, sourceKey)}:recovery`);
|
|
351
|
+
if (recovery?.status === "ready" && snapshot?.status !== "ready") return recovery;
|
|
352
|
+
if (recovery?.status === "ready" && snapshot?.ownsMount === false && recovery.ownsMount !== false) return recovery;
|
|
353
|
+
if (snapshot?.status === "ready") return snapshot;
|
|
354
|
+
if (snapshot || !source) return snapshot;
|
|
355
|
+
const legacy = await store.getMeta?.(`source:${sourceKey}:snapshot`);
|
|
356
|
+
return legacy?.configHash === await sourceConfigHash(source, store) ? legacy : void 0;
|
|
357
|
+
}
|
|
358
|
+
async function invalidateSourceSnapshot(store, workspace, sourceKey) {
|
|
359
|
+
const snapshot = await readSourceSnapshotMetadata(store, workspace, sourceKey);
|
|
360
|
+
if (snapshot) await writeSourceSnapshotMetadata(store, workspace, {
|
|
361
|
+
...snapshot,
|
|
362
|
+
status: "updating"
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
async function hasCurrentSourceSnapshot(store, workspace, source, verifyOwnership = false, activeSources = [], path) {
|
|
366
|
+
const configHash = await sourceConfigHash(source, store);
|
|
367
|
+
const meta = await readSourceSnapshotMetadata(store, workspace, source.key, source);
|
|
368
|
+
if (meta?.status !== "ready" || meta.configHash !== configHash) return false;
|
|
369
|
+
if (verifyOwnership === "workspace") {
|
|
370
|
+
if (Object.keys(meta.items || {}).length === 0 && meta.ownsMount !== false && meta.mountPath && (await store.stat(meta.mountPath))?.type !== "directory") return false;
|
|
371
|
+
const paths = path === void 0 ? Object.keys(meta.items || {}) : Object.hasOwn(meta.items || {}, path) ? [path] : [];
|
|
372
|
+
for (const path of paths) {
|
|
373
|
+
const file = await store.readFile(path);
|
|
374
|
+
if (!file) return false;
|
|
375
|
+
const inlineOwner = file.metadata?.workspaceSourceOwner;
|
|
376
|
+
if (inlineOwner !== void 0 && inlineOwner !== workspace) return false;
|
|
377
|
+
const owner = await readWorkspaceFileOwner(store, path);
|
|
378
|
+
if (!owner || owner.workspace === workspace || !owner.digest) continue;
|
|
379
|
+
if (await sha256(file.content) === owner.digest) return false;
|
|
380
|
+
}
|
|
381
|
+
return true;
|
|
382
|
+
}
|
|
383
|
+
return !verifyOwnership || await snapshotHasCurrentOwners(store, workspace, source, meta, activeSources, path);
|
|
384
|
+
}
|
|
385
|
+
async function snapshotHasCurrentOwners(store, workspace, source, meta, activeSources = [], path) {
|
|
386
|
+
if (Object.keys(meta.items || {}).length === 0 && meta.mountPath && (await store.stat(meta.mountPath))?.type !== "directory") return false;
|
|
387
|
+
const listed = path === void 0 && source.mountPath ? new Map((await store.list(source.mountPath, { recursive: true })).map((entry) => [entry.path, entry])) : void 0;
|
|
388
|
+
const paths = path === void 0 ? Object.keys(meta.items || {}) : Object.hasOwn(meta.items || {}, path) ? [path] : [];
|
|
389
|
+
for (const path of paths) {
|
|
390
|
+
const stat = listed?.get(path) ?? await store.stat(path);
|
|
391
|
+
if (await materializedFileHasCurrentOwner(store, workspace, source.key, path, stat)) continue;
|
|
392
|
+
const owner = await readWorkspaceFileOwner(store, path);
|
|
393
|
+
const currentSource = activeSources.find((item) => item.key === owner?.source && item.materialize === "startup");
|
|
394
|
+
if (source.materialize !== "startup" || owner?.workspace !== workspace || !owner.digest || !currentSource) return false;
|
|
395
|
+
const currentSnapshot = await readCurrentSourceSnapshot(store, workspace, currentSource);
|
|
396
|
+
if (currentSnapshot?.status !== "ready" || !Object.hasOwn(currentSnapshot.items || {}, path)) return false;
|
|
397
|
+
if (!await materializedFileHasCurrentOwner(store, workspace, currentSource.key, path, stat)) return false;
|
|
398
|
+
const file = await store.readFile(path);
|
|
399
|
+
if (!file || await sha256(file.content) !== owner.digest) return false;
|
|
400
|
+
}
|
|
401
|
+
return true;
|
|
402
|
+
}
|
|
403
|
+
async function materializedFileHasCurrentOwner(store, workspace, source, path, stat) {
|
|
404
|
+
if (stat?.type !== "file") return false;
|
|
405
|
+
if (stat.metadata?.workspaceSourceOwner === workspace && stat.metadata.source === source) return true;
|
|
406
|
+
if (stat.metadata?.workspaceSourceOwner !== void 0 && stat.metadata.workspaceSourceOwner !== workspace) return false;
|
|
407
|
+
if (stat.metadata?.source !== void 0 && stat.metadata.source !== source) return false;
|
|
408
|
+
const durable = await readWorkspaceFileOwner(store, path);
|
|
409
|
+
if (durable?.workspace !== workspace || durable.source !== source || !durable.digest) return false;
|
|
410
|
+
const file = await store.readFile(path);
|
|
411
|
+
return !!file && await sha256(file.content) === durable.digest;
|
|
412
|
+
}
|
|
413
|
+
async function hasFreshSourceSnapshot(store, workspace, source) {
|
|
414
|
+
const configHash = await sourceConfigHash(source, store);
|
|
415
|
+
const meta = await readSourceSnapshotMetadata(store, workspace, source.key, source);
|
|
416
|
+
return !!meta && isSnapshotFresh(meta, source, configHash) && await snapshotHasCurrentOwners(store, workspace, source, meta);
|
|
417
|
+
}
|
|
418
|
+
async function readCurrentSourceSnapshot(store, workspace, source) {
|
|
419
|
+
const configHash = await sourceConfigHash(source, store);
|
|
420
|
+
const snapshot = await readSourceSnapshotMetadata(store, workspace, source.key, source);
|
|
421
|
+
return snapshot?.configHash === configHash ? snapshot : void 0;
|
|
422
|
+
}
|
|
423
|
+
async function readSourceSnapshotPaths(store, workspace, sourceKey) {
|
|
424
|
+
const snapshot = await readSourceSnapshotMetadata(store, workspace, sourceKey);
|
|
425
|
+
return Object.keys(snapshot?.items || {});
|
|
426
|
+
}
|
|
427
|
+
async function sourceSnapshotOwnsAnyPath(store, workspace, sourceKey, paths) {
|
|
428
|
+
const meta = await readSourceSnapshotMetadata(store, workspace, sourceKey);
|
|
429
|
+
if (!meta || meta.status !== "ready") return void 0;
|
|
430
|
+
const ownedPaths = new Set(Object.keys(meta.items || {}));
|
|
431
|
+
return [...paths].some((path) => ownedPaths.has(normalizeWorkspacePath(path)));
|
|
432
|
+
}
|
|
433
|
+
async function writeSourceSnapshotMetadata(store, workspace, metadata) {
|
|
434
|
+
let snapshots = volatileSnapshots.get(workspaceStoreIdentity(store));
|
|
435
|
+
if (!snapshots) {
|
|
436
|
+
snapshots = /* @__PURE__ */ new Map();
|
|
437
|
+
volatileSnapshots.set(workspaceStoreIdentity(store), snapshots);
|
|
438
|
+
}
|
|
439
|
+
const key = sourceSnapshotMetaKey(workspace, metadata.source);
|
|
440
|
+
snapshots.set(key, metadata);
|
|
441
|
+
if (store.getMeta && store.setMeta) {
|
|
442
|
+
if (!key.endsWith(":recovery")) await store.setMeta(`${key}:recovery`, void 0);
|
|
443
|
+
await store.setMeta(key, metadata);
|
|
444
|
+
snapshots.delete(key);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
function materializedItemMeta(snapshot, configHash, path) {
|
|
448
|
+
if (!snapshot || snapshot.configHash !== configHash) return void 0;
|
|
449
|
+
if (snapshot.status !== "ready" && snapshot.status !== "updating" && snapshot.status !== "error") return void 0;
|
|
450
|
+
const item = snapshot.items?.[path];
|
|
451
|
+
return item?.migrationPending ? void 0 : item;
|
|
452
|
+
}
|
|
453
|
+
function checkpointItems(items) {
|
|
454
|
+
return Object.keys(items).length ? items : void 0;
|
|
455
|
+
}
|
|
456
|
+
function contentSize(content) {
|
|
457
|
+
return isWorkspaceBytes(content) ? content.byteLength : new TextEncoder().encode(content).byteLength;
|
|
458
|
+
}
|
|
459
|
+
function observableFileMetadata(metadata) {
|
|
460
|
+
return Object.fromEntries(Object.entries(metadata || {}).filter(([key, value]) => key !== "materializedAt" && key !== "validatedAt" && value !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => [key, normalizeMetadataValue(value)]));
|
|
461
|
+
}
|
|
462
|
+
function isDeepStrictEqual(left, right) {
|
|
463
|
+
if (Object.is(left, right)) return true;
|
|
464
|
+
if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
|
|
465
|
+
if (Array.isArray(left) !== Array.isArray(right)) return false;
|
|
466
|
+
const prototype = Object.getPrototypeOf(left);
|
|
467
|
+
if (prototype !== Object.getPrototypeOf(right)) return false;
|
|
468
|
+
if (left instanceof Date) return right instanceof Date && Object.is(left.getTime(), right.getTime());
|
|
469
|
+
if (!Array.isArray(left) && prototype !== Object.prototype && prototype !== null) return false;
|
|
470
|
+
if (Array.isArray(left)) return left.length === right.length && left.every((value, index) => isDeepStrictEqual(value, right[index]));
|
|
471
|
+
const leftRecord = left;
|
|
472
|
+
const rightRecord = right;
|
|
473
|
+
const leftKeys = Object.keys(leftRecord);
|
|
474
|
+
const rightKeys = Object.keys(rightRecord);
|
|
475
|
+
return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(rightRecord, key) && isDeepStrictEqual(leftRecord[key], rightRecord[key]));
|
|
476
|
+
}
|
|
477
|
+
function fileAttributesEqual(previous, previousSnapshot, mediaType, metadata) {
|
|
478
|
+
if (previousSnapshot?.materializedAttributes) return previousSnapshot.materializedMediaType === mediaType && isDeepStrictEqual(observableFileMetadata(previousSnapshot.materializedMetadata), observableFileMetadata(metadata));
|
|
479
|
+
return (previous.mediaType === void 0 || previous.mediaType === mediaType) && (previous.metadata === void 0 || isDeepStrictEqual(observableFileMetadata(previous.metadata), observableFileMetadata(metadata)));
|
|
480
|
+
}
|
|
481
|
+
function sourcePathMatches(path, source, options) {
|
|
482
|
+
if (options?.sources && !options.sources.includes(source.key)) return false;
|
|
483
|
+
const requested = normalizeWorkspacePath(options?.path || "");
|
|
484
|
+
if (!requested) return true;
|
|
485
|
+
return sourceMountIntersectsPath(source, requested);
|
|
486
|
+
}
|
|
487
|
+
function pathContains(container, path) {
|
|
488
|
+
return !container || path === container || path.startsWith(`${container}/`);
|
|
489
|
+
}
|
|
490
|
+
function materializationPathMatches(path, options) {
|
|
491
|
+
return pathContains(normalizeWorkspacePath(options?.path || ""), path);
|
|
492
|
+
}
|
|
493
|
+
function materializesCompleteSource(source, options) {
|
|
494
|
+
const requested = normalizeWorkspacePath(options?.path || "");
|
|
495
|
+
return !requested || Boolean(source.mountPath && pathContains(requested, source.mountPath));
|
|
496
|
+
}
|
|
497
|
+
function shouldMaterializeSource(source, options) {
|
|
498
|
+
if (source.requestOnly || !sourcePathMatches("", source, options)) return false;
|
|
499
|
+
if (source.materialize === "lazy" || source.materialize === "startup") return true;
|
|
500
|
+
return source.materialize === "build" && Boolean(options?.path);
|
|
501
|
+
}
|
|
502
|
+
function throwIfAborted(signal) {
|
|
503
|
+
if (!signal?.aborted) return;
|
|
504
|
+
throw signal.reason instanceof Error ? signal.reason : workspaceError("[vitehub] Workspace source materialization aborted.");
|
|
505
|
+
}
|
|
506
|
+
async function reportMaterializationProgress(options, source, event) {
|
|
507
|
+
await options?.onProgress?.({
|
|
508
|
+
...event,
|
|
509
|
+
mountPath: source.mountPath,
|
|
510
|
+
path: normalizeWorkspacePath(options?.path || ""),
|
|
511
|
+
provider: source.source.name,
|
|
512
|
+
source: source.key
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
function emptyMaterializationCounts() {
|
|
516
|
+
return {
|
|
517
|
+
added: 0,
|
|
518
|
+
removed: 0,
|
|
519
|
+
unchanged: 0,
|
|
520
|
+
updated: 0
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
function materializationCacheStatus(source, complete, hit) {
|
|
524
|
+
if (!complete) return "bypassed";
|
|
525
|
+
if (!source.cache) return "disabled";
|
|
526
|
+
return hit ? "hit" : "miss";
|
|
527
|
+
}
|
|
528
|
+
function materializationPaths(options, paths) {
|
|
529
|
+
return options?.details === "paths" ? paths.slice().sort((left, right) => left.path.localeCompare(right.path) || left.status.localeCompare(right.status)) : void 0;
|
|
530
|
+
}
|
|
531
|
+
function contentEquals(left, right) {
|
|
532
|
+
const leftBytes = isWorkspaceBytes(left) ? left : new TextEncoder().encode(left);
|
|
533
|
+
const rightBytes = isWorkspaceBytes(right) ? right : new TextEncoder().encode(right);
|
|
534
|
+
return leftBytes.byteLength === rightBytes.byteLength && leftBytes.every((byte, index) => byte === rightBytes[index]);
|
|
535
|
+
}
|
|
536
|
+
function shouldReportMaterializationUpdate(lastReportedAt, files) {
|
|
537
|
+
return files === 1 || files % 25 === 0 || Date.now() - lastReportedAt >= 1e3;
|
|
538
|
+
}
|
|
539
|
+
function looksLikeConcreteFilePath(path) {
|
|
540
|
+
const name = posix.basename(path);
|
|
541
|
+
return name.includes(".") || [
|
|
542
|
+
"Dockerfile",
|
|
543
|
+
"LICENSE",
|
|
544
|
+
"Makefile",
|
|
545
|
+
"Procfile",
|
|
546
|
+
"README"
|
|
547
|
+
].includes(name);
|
|
548
|
+
}
|
|
549
|
+
function directMaterializationSourceKey(source, options) {
|
|
550
|
+
const requested = normalizeWorkspacePath(options?.path || "");
|
|
551
|
+
if (!requested || !sourceMountContainsPath(source, requested) || requested === source.mountPath) return;
|
|
552
|
+
const sourcePath = source.mountPath ? requested.slice(source.mountPath.length + 1) : requested;
|
|
553
|
+
return sourcePath && looksLikeConcreteFilePath(sourcePath) ? sourcePath : void 0;
|
|
554
|
+
}
|
|
555
|
+
function parentDirectoryPaths(path) {
|
|
556
|
+
const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
|
|
557
|
+
const paths = [];
|
|
558
|
+
for (let index = 1; index < parts.length; index++) paths.push(parts.slice(0, index).join("/"));
|
|
559
|
+
return paths;
|
|
560
|
+
}
|
|
561
|
+
function sourceOwnsDirectory(source, path) {
|
|
562
|
+
return !source.mountPath || path === source.mountPath || path.startsWith(`${source.mountPath}/`);
|
|
563
|
+
}
|
|
564
|
+
async function removeStaleMaterializedSourceFiles(store, grant, workspace, source, sources, nextPaths, scope, control, previousSnapshot, ownedDirectories, checkpointDirectoryOwnership, onRemoved) {
|
|
565
|
+
const sourceStore = sourceMaterializationGrants.store(grant, store);
|
|
566
|
+
const previousPaths = new Set(Object.keys(previousSnapshot?.items || {}));
|
|
567
|
+
const scopedPreviousPaths = [...previousPaths].filter((path) => materializationPathMatches(path, scope));
|
|
568
|
+
const nextDirectories = new Set([...nextPaths].flatMap((path) => parentDirectoryPaths(path)));
|
|
569
|
+
const staleDirectories = new Set((previousSnapshot?.ownedDirectories || []).filter((path) => sourceOwnsDirectory(source, path) && materializationPathMatches(path, scope)));
|
|
570
|
+
const retainedMounts = /* @__PURE__ */ new Map();
|
|
571
|
+
if (source.materialize === "startup" && source.mountPath) {
|
|
572
|
+
const workspaces = await readStartupIndex(store, startupWorkspacesMetaKey);
|
|
573
|
+
for (const otherWorkspace of Array.isArray(workspaces) ? workspaces.filter((name) => name !== workspace) : []) {
|
|
574
|
+
const indexedSources = await readStartupIndex(store, startupSourcesMetaKey(otherWorkspace));
|
|
575
|
+
for (const indexedSource of Array.isArray(indexedSources) ? indexedSources.filter(isMaterializedStartupSource) : []) {
|
|
576
|
+
if (indexedSource.mountPath !== source.mountPath) continue;
|
|
577
|
+
const snapshot = await readSourceSnapshotMetadata(store, otherWorkspace, indexedSource.key);
|
|
578
|
+
if (snapshot && snapshot.ownsMount !== false) retainedMounts.set(source.mountPath, snapshot);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
const removedDirectories = /* @__PURE__ */ new Set();
|
|
583
|
+
const entries = source.materialize === "startup" && store.getMeta && store.setMeta && previousSnapshot?.mountPath !== void 0 ? await Promise.all(scopedPreviousPaths.map(async (path) => await store.stat(path))) : source.mountPath ? await store.list(source.mountPath, { recursive: true }) : previousPaths.size || store.getMeta && store.setMeta && (!previousSnapshot || previousSnapshot.items) ? await Promise.all(scopedPreviousPaths.map(async (path) => await store.stat(path))) : await store.list("", { recursive: true });
|
|
584
|
+
for (const path of previousPaths) {
|
|
585
|
+
if (source.mountPath && !sourceMountContainsPath(source, path)) {
|
|
586
|
+
if (previousSnapshot?.mountPath === source.mountPath) throw workspaceError(`[vitehub] Source materialization path ${path} is outside its mount ${source.mountPath}.`);
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
if (!nextPaths.has(path) && materializationPathMatches(path, scope)) await control.mutate(() => withWorkspaceStoreMutation(store, () => readWorkspaceFileOwner(store, path, true)));
|
|
590
|
+
}
|
|
591
|
+
for (const entry of entries) {
|
|
592
|
+
if (!entry || source.mountPath && !sourceMountContainsPath(source, entry.path) || !materializationPathMatches(entry.path, scope) || nextPaths.has(entry.path) || entry.type !== "file") continue;
|
|
593
|
+
await control.mutate(() => withWorkspaceStoreMutation(store, async () => {
|
|
594
|
+
const file = await store.readFile(entry.path);
|
|
595
|
+
const durableOwner = await readWorkspaceFileOwner(store, entry.path);
|
|
596
|
+
if (file?.metadata?.workspaceSourceOwner !== workspace && durableOwner?.workspace !== workspace) return;
|
|
597
|
+
const currentOwner = file?.metadata?.source ?? durableOwner?.source;
|
|
598
|
+
if (source.materialize === "startup" && store.getMeta && store.setMeta && !previousSnapshot && currentOwner !== void 0) return;
|
|
599
|
+
const recordedDigest = previousSnapshot?.items?.[entry.path]?.materializedContentDigest;
|
|
600
|
+
if (file?.metadata?.source === void 0 && durableOwner?.digest !== void 0 && recordedDigest !== void 0 && durableOwner.digest !== recordedDigest) return;
|
|
601
|
+
if (file?.metadata?.source === void 0 && (!durableOwner?.digest || !file || await sha256(file.content) !== durableOwner.digest)) {
|
|
602
|
+
if (durableOwner?.workspace === workspace && durableOwner.source === source.key) await removeWorkspaceFileOwner(store, entry.path);
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
if (previousSnapshot?.items && (!recordedDigest || !file || await sha256(file.content) !== recordedDigest)) {
|
|
606
|
+
if (durableOwner?.workspace === workspace && durableOwner.source === source.key) await removeWorkspaceFileOwner(store, entry.path);
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
if (currentOwner === void 0 && previousSnapshot?.items && !recordedDigest) return;
|
|
610
|
+
const overlapsAnotherSource = sources.some((candidate) => candidate.key !== source.key && candidate.mountPath.length >= source.mountPath.length && sourceMountContainsPath(candidate, entry.path));
|
|
611
|
+
if (currentOwner === source.key || currentOwner === void 0 && (previousPaths.has(entry.path) || Boolean(source.mountPath) && !overlapsAnotherSource)) {
|
|
612
|
+
for (const directory of parentDirectoryPaths(entry.path)) if (sourceOwnsDirectory(source, directory) && (directory !== source.mountPath || previousSnapshot?.ownsMount)) staleDirectories.add(directory);
|
|
613
|
+
for (const candidate of sources) {
|
|
614
|
+
if (candidate.key === source.key) continue;
|
|
615
|
+
const retainedSnapshot = await readSourceSnapshotMetadata(store, workspace, candidate.key);
|
|
616
|
+
if (retainedSnapshot?.status !== "ready" || !retainedSnapshot.items?.[entry.path]) continue;
|
|
617
|
+
await writeSourceSnapshotMetadata(store, workspace, {
|
|
618
|
+
...retainedSnapshot,
|
|
619
|
+
status: "updating"
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
await removeWorkspaceOwnedFile(sourceStore, entry.path);
|
|
623
|
+
onRemoved?.(entry.path, file ? contentSize(file.content) : 0);
|
|
624
|
+
}
|
|
625
|
+
}));
|
|
626
|
+
}
|
|
627
|
+
const cleanupDirectories = [...staleDirectories].filter((path) => !nextDirectories.has(path)).sort((a, b) => b.length - a.length);
|
|
628
|
+
for (const path of cleanupDirectories) ownedDirectories.add(path);
|
|
629
|
+
for (const path of cleanupDirectories) {
|
|
630
|
+
if (retainedMounts.has(path)) {
|
|
631
|
+
await checkpointDirectoryOwnership(path, false);
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
if ((await store.stat(path))?.type === "file") {
|
|
635
|
+
ownedDirectories.delete(path);
|
|
636
|
+
removedDirectories.add(path);
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
if ((await store.list(path)).length || !sourceStore.removeEmptyDirectory) continue;
|
|
640
|
+
try {
|
|
641
|
+
if (await control.mutate(async () => {
|
|
642
|
+
if ((await store.list(path)).length) return false;
|
|
643
|
+
if ((await store.stat(path))?.type !== "directory") return true;
|
|
644
|
+
await checkpointDirectoryOwnership(path, false);
|
|
645
|
+
try {
|
|
646
|
+
await sourceStore.removeEmptyDirectory(path);
|
|
647
|
+
} catch (error) {
|
|
648
|
+
await checkpointDirectoryOwnership(path, true);
|
|
649
|
+
throw error;
|
|
650
|
+
}
|
|
651
|
+
return true;
|
|
652
|
+
})) {
|
|
653
|
+
ownedDirectories.delete(path);
|
|
654
|
+
removedDirectories.add(path);
|
|
655
|
+
}
|
|
656
|
+
} catch (error) {
|
|
657
|
+
if (!(await store.list(path)).length) throw error;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
return removedDirectories;
|
|
661
|
+
}
|
|
662
|
+
async function reconcileRemovedStartupSources(workspace, store, currentSources, control = {
|
|
663
|
+
isCurrent: () => true,
|
|
664
|
+
async mutate(operation) {
|
|
665
|
+
return await operation();
|
|
666
|
+
},
|
|
667
|
+
async checkpoint(operation) {
|
|
668
|
+
return await operation();
|
|
669
|
+
}
|
|
670
|
+
}, materializationStore = store) {
|
|
671
|
+
const previous = startupReconciliationByStore.get(materializationStore);
|
|
672
|
+
const current = (async () => {
|
|
673
|
+
await previous;
|
|
674
|
+
await reconcileRemovedStartupSourcesInternal(workspace, store, currentSources, control, activeStartupSourcesByStore.get(materializationStore)?.get(workspace));
|
|
675
|
+
})();
|
|
676
|
+
const tail = current.catch(() => {});
|
|
677
|
+
startupReconciliationByStore.set(materializationStore, tail);
|
|
678
|
+
try {
|
|
679
|
+
await current;
|
|
680
|
+
} finally {
|
|
681
|
+
if (startupReconciliationByStore.get(materializationStore) === tail) startupReconciliationByStore.delete(materializationStore);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
async function reconcileRemovedStartupSourcesInternal(workspace, store, currentSources, control, activeSources = /* @__PURE__ */ new Set()) {
|
|
685
|
+
const workspaceIndex = await readStartupIndex(store, startupWorkspacesMetaKey);
|
|
686
|
+
const workspaces = new Set(Array.isArray(workspaceIndex) ? workspaceIndex.filter((name) => typeof name === "string") : []);
|
|
687
|
+
workspaces.add(workspace);
|
|
688
|
+
await control.checkpoint(() => writeStartupIndex(store, startupWorkspacesMetaKey, [...workspaces]));
|
|
689
|
+
const value = await readStartupIndex(store, startupSourcesMetaKey(workspace));
|
|
690
|
+
const previousSources = Array.isArray(value) ? value.filter(isMaterializedStartupSource) : [];
|
|
691
|
+
const currentMounts = new Map(currentSources.map((source) => [source.key, source.mountPath]));
|
|
692
|
+
const activeOwners = [...activeSources];
|
|
693
|
+
const isActive = (source) => activeOwners.some((active) => active.key === source.key && active.mountPath === source.mountPath);
|
|
694
|
+
const retainedSources = currentSources.map((source) => ({
|
|
695
|
+
workspace,
|
|
696
|
+
source
|
|
697
|
+
}));
|
|
698
|
+
for (const otherWorkspace of workspaces) {
|
|
699
|
+
if (otherWorkspace === workspace) continue;
|
|
700
|
+
const sources = await readStartupIndex(store, startupSourcesMetaKey(otherWorkspace));
|
|
701
|
+
if (!Array.isArray(sources)) continue;
|
|
702
|
+
for (const source of sources.filter(isMaterializedStartupSource)) retainedSources.push({
|
|
703
|
+
workspace: otherWorkspace,
|
|
704
|
+
source
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
const pendingDirectoryCleanup = [];
|
|
708
|
+
for (const source of previousSources.filter((source) => currentMounts.get(source.key) !== source.mountPath && !isActive(source))) {
|
|
709
|
+
const sourceStore = sourceMaterializationGrants.store(sourceMaterializationGrants.grant(source), store);
|
|
710
|
+
const snapshot = await readSourceSnapshotMetadata(store, workspace, source.key);
|
|
711
|
+
const invalidatedSnapshot = snapshot && snapshot.mountPath === void 0 && snapshot.items === void 0;
|
|
712
|
+
if (snapshot?.mountPath !== source.mountPath && !invalidatedSnapshot) continue;
|
|
713
|
+
const previousPaths = invalidatedSnapshot ? (await store.list(source.mountPath, { recursive: true })).filter((entry) => entry.type === "file").map((entry) => entry.path) : Object.keys(snapshot?.items || {});
|
|
714
|
+
const staleDirectories = /* @__PURE__ */ new Set([...snapshot?.ownedAncestors || [], ...(snapshot?.ownedDirectories || []).filter((path) => sourceOwnsDirectory(source, path))]);
|
|
715
|
+
if (source.mountPath && snapshot?.ownsMount) staleDirectories.add(source.mountPath);
|
|
716
|
+
for (const path of previousPaths) {
|
|
717
|
+
if (source.mountPath && !sourceMountContainsPath(source, path)) continue;
|
|
718
|
+
await control.mutate(() => withWorkspaceStoreMutation(store, async () => {
|
|
719
|
+
const file = await store.readFile(path);
|
|
720
|
+
const durableOwner = await readWorkspaceFileOwner(store, path, true);
|
|
721
|
+
if (!file) return;
|
|
722
|
+
if (file.metadata?.workspaceSourceOwner !== workspace && durableOwner?.workspace !== workspace) return;
|
|
723
|
+
const owner = file.metadata?.source ?? durableOwner?.source;
|
|
724
|
+
const recordedDigest = snapshot?.items?.[path]?.materializedContentDigest;
|
|
725
|
+
if (file.metadata?.source === void 0 && (!durableOwner?.digest || await sha256(file.content) !== durableOwner.digest)) {
|
|
726
|
+
if (durableOwner?.workspace === workspace && durableOwner.source === source.key) await removeWorkspaceFileOwner(store, path);
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (snapshot?.items && (!recordedDigest || await sha256(file.content) !== recordedDigest)) {
|
|
730
|
+
if (durableOwner?.workspace === workspace && durableOwner.source === source.key) await removeWorkspaceFileOwner(store, path);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
if (owner !== source.key && !(owner === void 0 && recordedDigest && await sha256(file.content) === recordedDigest)) return;
|
|
734
|
+
for (const currentSource of currentSources) {
|
|
735
|
+
const retainedSnapshot = await readSourceSnapshotMetadata(store, workspace, currentSource.key);
|
|
736
|
+
if (retainedSnapshot?.status !== "ready" || !retainedSnapshot.items?.[path]) continue;
|
|
737
|
+
await writeSourceSnapshotMetadata(store, workspace, {
|
|
738
|
+
...retainedSnapshot,
|
|
739
|
+
status: "updating"
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
await removeWorkspaceOwnedFile(sourceStore, path);
|
|
743
|
+
}));
|
|
744
|
+
}
|
|
745
|
+
let directoryCleanupUnavailable = false;
|
|
746
|
+
let cleanupSnapshot = snapshot;
|
|
747
|
+
const retireDirectory = async (path) => {
|
|
748
|
+
if (!cleanupSnapshot) return;
|
|
749
|
+
const previous = cleanupSnapshot;
|
|
750
|
+
const retired = {
|
|
751
|
+
...cleanupSnapshot,
|
|
752
|
+
ownsMount: path === source.mountPath ? false : cleanupSnapshot.ownsMount,
|
|
753
|
+
ownedAncestors: cleanupSnapshot.ownedAncestors?.filter((directory) => directory !== path),
|
|
754
|
+
ownedDirectories: cleanupSnapshot.ownedDirectories?.filter((directory) => directory !== path)
|
|
755
|
+
};
|
|
756
|
+
try {
|
|
757
|
+
await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, retired));
|
|
758
|
+
} catch (error) {
|
|
759
|
+
try {
|
|
760
|
+
await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, previous));
|
|
761
|
+
} catch {
|
|
762
|
+
if (store.setMeta) await store.setMeta(`${sourceSnapshotMetaKey(workspace, source.key)}:recovery`, previous);
|
|
763
|
+
}
|
|
764
|
+
throw error;
|
|
765
|
+
}
|
|
766
|
+
cleanupSnapshot = retired;
|
|
767
|
+
};
|
|
768
|
+
for (const path of [...staleDirectories].sort((a, b) => b.length - a.length)) {
|
|
769
|
+
let ownershipTransferred = false;
|
|
770
|
+
const retainedMount = path === source.mountPath ? retainedSources.find(({ workspace: retainedWorkspace, source: retainedSource }) => retainedWorkspace !== workspace && retainedSource.mountPath === path) : void 0;
|
|
771
|
+
if (retainedMount) {
|
|
772
|
+
await retireDirectory(path);
|
|
773
|
+
const retainedSnapshot = await readSourceSnapshotMetadata(store, retainedMount.workspace, retainedMount.source.key);
|
|
774
|
+
if (retainedSnapshot) await control.checkpoint(() => writeSourceSnapshotMetadata(store, retainedMount.workspace, {
|
|
775
|
+
...retainedSnapshot,
|
|
776
|
+
ownsMount: true
|
|
777
|
+
}));
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
for (const { workspace: retainedWorkspace, source: currentSource } of retainedSources) {
|
|
781
|
+
const retainedSnapshot = await readSourceSnapshotMetadata(store, retainedWorkspace, currentSource.key);
|
|
782
|
+
if (retainedSnapshot?.mountPath !== currentSource.mountPath) continue;
|
|
783
|
+
const containsMount = pathContains(path, currentSource.mountPath);
|
|
784
|
+
if (!containsMount && !Object.keys(retainedSnapshot.items || {}).some((item) => pathContains(path, item))) continue;
|
|
785
|
+
if (!ownershipTransferred) await retireDirectory(path);
|
|
786
|
+
await control.checkpoint(() => writeSourceSnapshotMetadata(store, retainedWorkspace, {
|
|
787
|
+
...retainedSnapshot,
|
|
788
|
+
...path === currentSource.mountPath ? { ownsMount: true } : containsMount ? { ownedAncestors: [.../* @__PURE__ */ new Set([...retainedSnapshot.ownedAncestors || [], path])] } : { ownedDirectories: [.../* @__PURE__ */ new Set([...retainedSnapshot.ownedDirectories || [], path])] }
|
|
789
|
+
}));
|
|
790
|
+
ownershipTransferred = true;
|
|
791
|
+
}
|
|
792
|
+
if (ownershipTransferred) continue;
|
|
793
|
+
if ((await store.stat(path))?.type !== "directory" || (await store.list(path)).length) continue;
|
|
794
|
+
if (!sourceStore.removeEmptyDirectory) {
|
|
795
|
+
directoryCleanupUnavailable = true;
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
await control.mutate(async () => {
|
|
799
|
+
if ((await store.list(path)).length || (await store.stat(path))?.type !== "directory") return;
|
|
800
|
+
const previousSnapshot = cleanupSnapshot;
|
|
801
|
+
await retireDirectory(path);
|
|
802
|
+
try {
|
|
803
|
+
await sourceStore.removeEmptyDirectory(path);
|
|
804
|
+
} catch (error) {
|
|
805
|
+
if (previousSnapshot) {
|
|
806
|
+
try {
|
|
807
|
+
await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, previousSnapshot));
|
|
808
|
+
} catch {
|
|
809
|
+
if (store.setMeta) await store.setMeta(`${sourceSnapshotMetaKey(workspace, source.key)}:recovery`, previousSnapshot);
|
|
810
|
+
}
|
|
811
|
+
cleanupSnapshot = previousSnapshot;
|
|
812
|
+
}
|
|
813
|
+
throw error;
|
|
814
|
+
}
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
if (directoryCleanupUnavailable) {
|
|
818
|
+
pendingDirectoryCleanup.push(source);
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
await control.checkpoint(async () => {
|
|
822
|
+
const key = sourceSnapshotMetaKey(workspace, source.key);
|
|
823
|
+
if (!store.getMeta || !store.setMeta) {
|
|
824
|
+
let snapshots = volatileSnapshots.get(workspaceStoreIdentity(store));
|
|
825
|
+
if (!snapshots) {
|
|
826
|
+
snapshots = /* @__PURE__ */ new Map();
|
|
827
|
+
volatileSnapshots.set(workspaceStoreIdentity(store), snapshots);
|
|
828
|
+
}
|
|
829
|
+
snapshots.set(key, void 0);
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
await store.setMeta(key, {});
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
const trackedSources = [
|
|
836
|
+
...currentSources,
|
|
837
|
+
...activeOwners,
|
|
838
|
+
...previousSources.filter(isActive),
|
|
839
|
+
...pendingDirectoryCleanup
|
|
840
|
+
];
|
|
841
|
+
const uniqueSources = trackedSources.filter((source, index) => trackedSources.findIndex((candidate) => candidate.key === source.key && candidate.mountPath === source.mountPath) === index);
|
|
842
|
+
await control.checkpoint(() => writeStartupIndex(store, startupSourcesMetaKey(workspace), uniqueSources.map(({ key, mountPath }) => ({
|
|
843
|
+
key,
|
|
844
|
+
mountPath
|
|
845
|
+
}))));
|
|
846
|
+
if (!uniqueSources.length) {
|
|
847
|
+
workspaces.delete(workspace);
|
|
848
|
+
await control.checkpoint(() => writeStartupIndex(store, startupWorkspacesMetaKey, [...workspaces]));
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
async function readStartupIndex(store, key) {
|
|
852
|
+
return volatileStartupIndexes.get(workspaceStoreIdentity(store))?.get(key) ?? await store.getMeta?.(key);
|
|
853
|
+
}
|
|
854
|
+
async function writeStartupIndex(store, key, value) {
|
|
855
|
+
if (!store.getMeta || !store.setMeta) {
|
|
856
|
+
let indexes = volatileStartupIndexes.get(workspaceStoreIdentity(store));
|
|
857
|
+
if (!indexes) {
|
|
858
|
+
indexes = /* @__PURE__ */ new Map();
|
|
859
|
+
volatileStartupIndexes.set(workspaceStoreIdentity(store), indexes);
|
|
860
|
+
}
|
|
861
|
+
indexes.set(key, value);
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
await store.setMeta(key, value);
|
|
865
|
+
}
|
|
866
|
+
function isMaterializedStartupSource(value) {
|
|
867
|
+
if (typeof value !== "object" || value === null) return false;
|
|
868
|
+
const source = value;
|
|
869
|
+
return readStringMeta(source, "key") !== void 0 && readStringMeta(source, "mountPath") !== void 0;
|
|
870
|
+
}
|
|
871
|
+
async function* iterateSourceItems(source, ctx) {
|
|
872
|
+
if (source.source.getItems) {
|
|
873
|
+
yield* await source.source.getItems(ctx);
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
for (const key of await source.source.getKeys(ctx)) yield await source.source.getItem(key, ctx);
|
|
877
|
+
}
|
|
878
|
+
function createMaterializationEntry(source, item, upstreamMeta) {
|
|
879
|
+
const { path, sourcePath } = normalizeSourceItemPath(source, item, { operation: "source materialization" });
|
|
880
|
+
return {
|
|
881
|
+
item,
|
|
882
|
+
metadata: createLazyMaterializedMetadata({
|
|
883
|
+
sourceKey: source.key,
|
|
884
|
+
sourcePath,
|
|
885
|
+
validate: source.validate
|
|
886
|
+
}, item, upstreamMeta),
|
|
887
|
+
path,
|
|
888
|
+
...sourceItemContent(item)
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
function sourceItemContent(item) {
|
|
892
|
+
if (item.contentStream) {
|
|
893
|
+
if (item.content !== void 0 || item.data !== void 0) throw workspaceError("[vitehub] Workspace source items cannot define contentStream with content or data.");
|
|
894
|
+
return { contentStream: item.contentStream };
|
|
895
|
+
}
|
|
896
|
+
return { content: item.content ?? (item.data === void 0 ? "" : JSON.stringify(item.data, null, 2)) };
|
|
897
|
+
}
|
|
898
|
+
async function* iterateMaterializationEntries(source, ctx, store, snapshot, configHash, options, workspace) {
|
|
899
|
+
const directKey = directMaterializationSourceKey(source, options);
|
|
900
|
+
if (directKey) {
|
|
901
|
+
const entry = createMaterializationEntry(source, await source.source.getItem(directKey, ctx), void 0);
|
|
902
|
+
if (materializationPathMatches(entry.path, options)) yield entry;
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
if (source.source.getItems) {
|
|
906
|
+
for await (const item of iterateSourceItems(source, ctx)) {
|
|
907
|
+
const entry = createMaterializationEntry(source, item, item.metadata ?? await source.source.getMeta?.(item.key, ctx));
|
|
908
|
+
if (materializationPathMatches(entry.path, options)) yield entry;
|
|
909
|
+
}
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
for (const key of await source.source.getKeys(ctx)) {
|
|
913
|
+
const upstreamMeta = await source.source.getMeta?.(key, ctx);
|
|
914
|
+
const { path, sourcePath } = normalizeWorkspaceSourceItemPath(source, key, { operation: "source materialization" });
|
|
915
|
+
if (!materializationPathMatches(path, options)) continue;
|
|
916
|
+
const previous = materializedItemMeta(snapshot, configHash, path);
|
|
917
|
+
if (upstreamMeta && previous?.source === source.key && previous.sourcePath === sourcePath && !hasSourceMetaChanged(previous, upstreamMeta)) {
|
|
918
|
+
const stat = await store.stat(path);
|
|
919
|
+
if (stat && await materializedFileHasCurrentOwner(store, workspace, source.key, path, stat)) {
|
|
920
|
+
yield {
|
|
921
|
+
metadata: previous,
|
|
922
|
+
path,
|
|
923
|
+
reused: stat
|
|
924
|
+
};
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
yield createMaterializationEntry(source, await source.source.getItem(key, ctx), upstreamMeta);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
async function materializeWorkspaceSources(definition, store, options = {}, control = {
|
|
932
|
+
isCurrent: () => true,
|
|
933
|
+
async mutate(operation) {
|
|
934
|
+
return await operation();
|
|
935
|
+
},
|
|
936
|
+
async checkpoint(operation) {
|
|
937
|
+
return await operation();
|
|
938
|
+
}
|
|
939
|
+
}) {
|
|
940
|
+
const activeByWorkspace = activeStartupSourcesByStore.get(store) ?? /* @__PURE__ */ new Map();
|
|
941
|
+
const activeSources = activeByWorkspace.get(definition.name) ?? /* @__PURE__ */ new Set();
|
|
942
|
+
const selectedSources = normalizeWorkspaceSources(definition.sources).filter((source) => source.materialize === "startup" && shouldMaterializeSource(source, options));
|
|
943
|
+
for (const source of selectedSources) activeSources.add(source);
|
|
944
|
+
activeByWorkspace.set(definition.name, activeSources);
|
|
945
|
+
activeStartupSourcesByStore.set(store, activeByWorkspace);
|
|
946
|
+
try {
|
|
947
|
+
return await materializeWorkspaceSourcesInternal(definition, store, options, control);
|
|
948
|
+
} finally {
|
|
949
|
+
for (const source of selectedSources) activeSources.delete(source);
|
|
950
|
+
if (!activeSources.size) activeByWorkspace.delete(definition.name);
|
|
951
|
+
if (!activeByWorkspace.size) activeStartupSourcesByStore.delete(store);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
async function materializeWorkspaceSourcesInternal(definition, store, options, control) {
|
|
955
|
+
const workspace = definition.name;
|
|
956
|
+
const assertCurrent = () => {
|
|
957
|
+
if (!control.isCurrent()) throw options.abortSignal?.reason ?? workspaceError("[vitehub] Workspace source materialization was superseded.");
|
|
958
|
+
};
|
|
959
|
+
const started = Date.now();
|
|
960
|
+
const configuredSources = normalizeWorkspaceSources(definition.sources);
|
|
961
|
+
const sources = configuredSources.filter((source) => shouldMaterializeSource(source, options));
|
|
962
|
+
const startupSources = configuredSources.filter((source) => source.materialize === "startup");
|
|
963
|
+
const rootMaterialization = !normalizeWorkspacePath(options.path || "");
|
|
964
|
+
if (sources.some((source) => source.materialize === "startup") || rootMaterialization && !options.sources?.length) await reconcileRemovedStartupSources(definition.name, store, startupSources, control);
|
|
965
|
+
const resultSources = [];
|
|
966
|
+
let files = 0;
|
|
967
|
+
let directories = 0;
|
|
968
|
+
let bytes = 0;
|
|
969
|
+
for (const source of sources) {
|
|
970
|
+
throwIfAborted(options.abortSignal);
|
|
971
|
+
const sourceStarted = Date.now();
|
|
972
|
+
await reportMaterializationProgress(options, source, { status: "started" });
|
|
973
|
+
let configHash;
|
|
974
|
+
let existing;
|
|
975
|
+
try {
|
|
976
|
+
configHash = await sourceConfigHash(source, store);
|
|
977
|
+
existing = await readSourceSnapshotMetadata(store, workspace, source.key, source);
|
|
978
|
+
if (existing && !await store.getMeta?.(sourceSnapshotMetaKey(workspace, source.key))) {
|
|
979
|
+
const adopted = existing;
|
|
980
|
+
await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, adopted));
|
|
981
|
+
}
|
|
982
|
+
} catch (error) {
|
|
983
|
+
const durationMs = Date.now() - sourceStarted;
|
|
984
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
985
|
+
const failed = {
|
|
986
|
+
counts: emptyMaterializationCounts(),
|
|
987
|
+
durationMs,
|
|
988
|
+
error: message,
|
|
989
|
+
mountPath: source.mountPath,
|
|
990
|
+
provider: source.source.name,
|
|
991
|
+
source: source.key,
|
|
992
|
+
status: "error"
|
|
993
|
+
};
|
|
994
|
+
resultSources.push(failed);
|
|
995
|
+
await reportMaterializationProgress(options, source, {
|
|
996
|
+
counts: failed.counts,
|
|
997
|
+
durationMs,
|
|
998
|
+
error: message,
|
|
999
|
+
status: "failed"
|
|
1000
|
+
});
|
|
1001
|
+
if (options.abortSignal?.aborted) throw error;
|
|
1002
|
+
continue;
|
|
1003
|
+
}
|
|
1004
|
+
const completeSource = materializesCompleteSource(source, options);
|
|
1005
|
+
const cacheHit = completeSource && !!existing && isSnapshotFresh(existing, source, configHash) && await snapshotHasCurrentOwners(store, workspace, source, existing);
|
|
1006
|
+
const cacheStatus = materializationCacheStatus(source, completeSource, cacheHit);
|
|
1007
|
+
if (cacheHit) {
|
|
1008
|
+
const durationMs = Date.now() - sourceStarted;
|
|
1009
|
+
const cachedPaths = Object.keys(existing?.items || {});
|
|
1010
|
+
const cachedFiles = cachedPaths.length || existing?.files || 0;
|
|
1011
|
+
const counts = {
|
|
1012
|
+
...emptyMaterializationCounts(),
|
|
1013
|
+
unchanged: cachedFiles
|
|
1014
|
+
};
|
|
1015
|
+
const ready = {
|
|
1016
|
+
cacheStatus,
|
|
1017
|
+
counts,
|
|
1018
|
+
durationMs,
|
|
1019
|
+
source: source.key,
|
|
1020
|
+
mountPath: source.mountPath,
|
|
1021
|
+
provider: source.source.name,
|
|
1022
|
+
status: "ready",
|
|
1023
|
+
revision: existing?.revision,
|
|
1024
|
+
materializedAt: existing?.materializedAt,
|
|
1025
|
+
files: existing?.files,
|
|
1026
|
+
bytes: existing?.bytes
|
|
1027
|
+
};
|
|
1028
|
+
const paths = materializationPaths(options, cachedPaths.map((path) => ({
|
|
1029
|
+
path,
|
|
1030
|
+
status: "unchanged"
|
|
1031
|
+
})));
|
|
1032
|
+
if (paths) ready.paths = paths;
|
|
1033
|
+
resultSources.push(ready);
|
|
1034
|
+
files += cachedFiles;
|
|
1035
|
+
bytes += existing?.bytes || 0;
|
|
1036
|
+
await reportMaterializationProgress(options, source, {
|
|
1037
|
+
bytes: existing?.bytes || 0,
|
|
1038
|
+
cacheStatus,
|
|
1039
|
+
counts,
|
|
1040
|
+
durationMs,
|
|
1041
|
+
files: cachedFiles,
|
|
1042
|
+
revision: existing?.revision,
|
|
1043
|
+
status: "completed"
|
|
1044
|
+
});
|
|
1045
|
+
continue;
|
|
1046
|
+
}
|
|
1047
|
+
let ownsMount = Boolean(source.mountPath) && existing?.mountPath === source.mountPath && existing.ownsMount === true && Boolean(await store.stat(source.mountPath));
|
|
1048
|
+
const ownedAncestors = [...existing?.mountPath === source.mountPath ? existing.ownedAncestors || [] : []];
|
|
1049
|
+
const ownedDirectories = new Set(existing?.mountPath === source.mountPath ? existing.ownedDirectories : []);
|
|
1050
|
+
let revision = existing?.revision;
|
|
1051
|
+
const retainPriorItems = existing?.configHash === configHash || !completeSource && source.materialize === "startup" && existing?.mountPath === source.mountPath;
|
|
1052
|
+
const itemMetadata = existing?.configHash === configHash ? { ...existing.items } : Object.fromEntries(Object.entries(existing?.items || {}).map(([path, metadata]) => [path, {
|
|
1053
|
+
...metadata,
|
|
1054
|
+
migrationPending: true
|
|
1055
|
+
}]));
|
|
1056
|
+
if (completeSource) {
|
|
1057
|
+
assertCurrent();
|
|
1058
|
+
await control.mutate(() => writeSourceSnapshotMetadata(store, workspace, {
|
|
1059
|
+
configHash,
|
|
1060
|
+
source: source.key,
|
|
1061
|
+
mountPath: source.mountPath,
|
|
1062
|
+
ownsMount,
|
|
1063
|
+
ownedAncestors,
|
|
1064
|
+
ownedDirectories: [...ownedDirectories],
|
|
1065
|
+
status: "updating",
|
|
1066
|
+
revision,
|
|
1067
|
+
items: checkpointItems(itemMetadata),
|
|
1068
|
+
cacheMaxAge: source.cache ? source.cache.maxAge : void 0
|
|
1069
|
+
}));
|
|
1070
|
+
}
|
|
1071
|
+
const grant = sourceMaterializationGrants.grant(source);
|
|
1072
|
+
const sourceStore = sourceMaterializationGrants.store(grant, store);
|
|
1073
|
+
let sourceFiles = 0;
|
|
1074
|
+
let sourceBytes = 0;
|
|
1075
|
+
let persistedBytesDelta = 0;
|
|
1076
|
+
let lastProgressAt = 0;
|
|
1077
|
+
const counts = emptyMaterializationCounts();
|
|
1078
|
+
const paths = [];
|
|
1079
|
+
try {
|
|
1080
|
+
const ctx = createSourceContext(definition, source, store, { abortSignal: options.abortSignal });
|
|
1081
|
+
throwIfAborted(options.abortSignal);
|
|
1082
|
+
await prepareWorkspaceSource(source.source, ctx);
|
|
1083
|
+
throwIfAborted(options.abortSignal);
|
|
1084
|
+
if (source.mountPath) await control.mutate(async () => {
|
|
1085
|
+
const mountExists = Boolean(await store.stat(source.mountPath));
|
|
1086
|
+
const missingAncestors = [];
|
|
1087
|
+
for (const path of parentDirectoryPaths(source.mountPath)) if (!await store.stat(path)) missingAncestors.push(path);
|
|
1088
|
+
await sourceStore.mkdir(source.mountPath, { recursive: true });
|
|
1089
|
+
ownsMount = ownsMount || !mountExists;
|
|
1090
|
+
for (const path of missingAncestors) if (!ownedAncestors.includes(path)) ownedAncestors.push(path);
|
|
1091
|
+
});
|
|
1092
|
+
revision = ctx.revision;
|
|
1093
|
+
const directorySet = new Set(source.mountPath ? [source.mountPath] : []);
|
|
1094
|
+
const nextPaths = /* @__PURE__ */ new Set();
|
|
1095
|
+
for await (const entry of iterateMaterializationEntries(source, ctx, store, existing, configHash, options, workspace)) {
|
|
1096
|
+
throwIfAborted(options.abortSignal);
|
|
1097
|
+
const path = entry.path;
|
|
1098
|
+
nextPaths.add(path);
|
|
1099
|
+
const parts = path.split("/");
|
|
1100
|
+
for (let index = 1; index < parts.length; index++) directorySet.add(parts.slice(0, index).join("/"));
|
|
1101
|
+
if (entry.reused) {
|
|
1102
|
+
itemMetadata[path] = entry.metadata;
|
|
1103
|
+
sourceFiles++;
|
|
1104
|
+
const reusedFile = entry.reused.size === void 0 ? await store.readFile(path) : void 0;
|
|
1105
|
+
sourceBytes += entry.reused.size ?? (reusedFile ? contentSize(reusedFile.content) : 0);
|
|
1106
|
+
counts.unchanged++;
|
|
1107
|
+
paths.push({
|
|
1108
|
+
path,
|
|
1109
|
+
status: "unchanged"
|
|
1110
|
+
});
|
|
1111
|
+
if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
|
|
1112
|
+
await reportMaterializationProgress(options, source, {
|
|
1113
|
+
bytes: sourceBytes,
|
|
1114
|
+
cacheStatus,
|
|
1115
|
+
counts: { ...counts },
|
|
1116
|
+
files: sourceFiles,
|
|
1117
|
+
revision,
|
|
1118
|
+
status: "updating"
|
|
1119
|
+
});
|
|
1120
|
+
lastProgressAt = Date.now();
|
|
1121
|
+
}
|
|
1122
|
+
continue;
|
|
1123
|
+
}
|
|
1124
|
+
const item = entry.item;
|
|
1125
|
+
const metadata = normalizeSourceFileMetadata(item.metadata || {});
|
|
1126
|
+
const previousStat = await store.stat(path);
|
|
1127
|
+
const previous = entry.contentStream && store.writeFileStream ? void 0 : await store.readFile(path);
|
|
1128
|
+
const previousExists = previousStat?.type === "file" || Boolean(previous);
|
|
1129
|
+
const fileMetadata = normalizeSourceFileMetadata({
|
|
1130
|
+
...metadata,
|
|
1131
|
+
...entry.metadata,
|
|
1132
|
+
source: source.key,
|
|
1133
|
+
workspaceSourceOwner: workspace
|
|
1134
|
+
});
|
|
1135
|
+
const missingDirectories = [];
|
|
1136
|
+
for (const directory of parentDirectoryPaths(path)) if (directory !== source.mountPath && sourceOwnsDirectory(source, directory) && !await store.stat(directory)) missingDirectories.push(directory);
|
|
1137
|
+
const tracked = Object.hasOwn(itemMetadata, path);
|
|
1138
|
+
const previousItemMetadata = itemMetadata[path];
|
|
1139
|
+
const written = await control.mutate(() => withWorkspaceStoreMutation(store, async () => {
|
|
1140
|
+
const write = () => writeMaterializedFile(sourceStore, path, {
|
|
1141
|
+
path,
|
|
1142
|
+
content: entry.content,
|
|
1143
|
+
contentStream: entry.contentStream,
|
|
1144
|
+
mediaType: item.mediaType,
|
|
1145
|
+
metadata: fileMetadata
|
|
1146
|
+
}, previous?.content);
|
|
1147
|
+
const checkpoint = async (result) => {
|
|
1148
|
+
for (const directory of missingDirectories) ownedDirectories.add(directory);
|
|
1149
|
+
itemMetadata[path] = {
|
|
1150
|
+
...entry.metadata,
|
|
1151
|
+
materializedAttributes: true,
|
|
1152
|
+
materializedContentDigest: result.digest,
|
|
1153
|
+
materializedBytes: result.size || 0,
|
|
1154
|
+
materializedMediaType: item.mediaType,
|
|
1155
|
+
materializedMetadata: observableFileMetadata(fileMetadata)
|
|
1156
|
+
};
|
|
1157
|
+
await recordWorkspaceFileOwner(store, path, {
|
|
1158
|
+
workspace,
|
|
1159
|
+
source: source.key,
|
|
1160
|
+
digest: result.digest
|
|
1161
|
+
});
|
|
1162
|
+
};
|
|
1163
|
+
if (source.materialize !== "startup") {
|
|
1164
|
+
const result = await write();
|
|
1165
|
+
await checkpoint(result);
|
|
1166
|
+
return result;
|
|
1167
|
+
}
|
|
1168
|
+
return await withWorkspaceFileCheckpoint(sourceStore, path, write, checkpoint, async () => {
|
|
1169
|
+
if (previousItemMetadata) itemMetadata[path] = previousItemMetadata;
|
|
1170
|
+
else delete itemMetadata[path];
|
|
1171
|
+
});
|
|
1172
|
+
}));
|
|
1173
|
+
sourceFiles++;
|
|
1174
|
+
sourceBytes += written.size || 0;
|
|
1175
|
+
persistedBytesDelta += (written.size || 0) - (tracked ? previousItemMetadata?.materializedBytes ?? previousStat?.size ?? (previous ? contentSize(previous.content) : 0) : 0);
|
|
1176
|
+
const status = (entry.contentStream ? store.writeFileStream ? previousStat?.type === "file" && previousStat.digest !== void 0 && previousStat.digest === written.storeDigest : written.contentEqual === true : previous !== void 0 && contentEquals(previous.content, entry.content ?? "")) && fileAttributesEqual(previous ?? previousStat ?? {}, previousItemMetadata, item.mediaType, fileMetadata) ? "unchanged" : previousExists ? "updated" : "added";
|
|
1177
|
+
counts[status]++;
|
|
1178
|
+
paths.push({
|
|
1179
|
+
path,
|
|
1180
|
+
status
|
|
1181
|
+
});
|
|
1182
|
+
if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
|
|
1183
|
+
await reportMaterializationProgress(options, source, {
|
|
1184
|
+
bytes: sourceBytes,
|
|
1185
|
+
cacheStatus,
|
|
1186
|
+
counts: { ...counts },
|
|
1187
|
+
files: sourceFiles,
|
|
1188
|
+
revision,
|
|
1189
|
+
status: "updating"
|
|
1190
|
+
});
|
|
1191
|
+
lastProgressAt = Date.now();
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
throwIfAborted(options.abortSignal);
|
|
1195
|
+
const removedDirectories = await removeStaleMaterializedSourceFiles(store, grant, workspace, source, configuredSources, nextPaths, options, control, existing, ownedDirectories, async (path, owned) => {
|
|
1196
|
+
const previouslyOwned = ownedDirectories.has(path);
|
|
1197
|
+
const previouslyOwnedMount = ownsMount;
|
|
1198
|
+
if (owned) ownedDirectories.add(path);
|
|
1199
|
+
else ownedDirectories.delete(path);
|
|
1200
|
+
if (path === source.mountPath) ownsMount = owned;
|
|
1201
|
+
try {
|
|
1202
|
+
await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, {
|
|
1203
|
+
configHash,
|
|
1204
|
+
source: source.key,
|
|
1205
|
+
mountPath: source.mountPath,
|
|
1206
|
+
ownsMount,
|
|
1207
|
+
ownedAncestors,
|
|
1208
|
+
ownedDirectories: [...ownedDirectories],
|
|
1209
|
+
status: "updating",
|
|
1210
|
+
revision,
|
|
1211
|
+
items: checkpointItems(itemMetadata),
|
|
1212
|
+
cacheMaxAge: source.cache ? source.cache.maxAge : void 0
|
|
1213
|
+
}));
|
|
1214
|
+
} catch (error) {
|
|
1215
|
+
if (!owned) {
|
|
1216
|
+
if (previouslyOwned) ownedDirectories.add(path);
|
|
1217
|
+
else ownedDirectories.delete(path);
|
|
1218
|
+
ownsMount = previouslyOwnedMount;
|
|
1219
|
+
}
|
|
1220
|
+
throw error;
|
|
1221
|
+
}
|
|
1222
|
+
}, (path, removedBytes) => {
|
|
1223
|
+
counts.removed++;
|
|
1224
|
+
if (Object.hasOwn(itemMetadata, path)) persistedBytesDelta -= itemMetadata[path]?.materializedBytes ?? removedBytes;
|
|
1225
|
+
delete itemMetadata[path];
|
|
1226
|
+
paths.push({
|
|
1227
|
+
path,
|
|
1228
|
+
status: "removed"
|
|
1229
|
+
});
|
|
1230
|
+
});
|
|
1231
|
+
if (removedDirectories.has(source.mountPath)) ownsMount = false;
|
|
1232
|
+
for (const directory of removedDirectories) ownedDirectories.delete(directory);
|
|
1233
|
+
const readyItems = Object.fromEntries([...nextPaths].flatMap((path) => {
|
|
1234
|
+
const metadata = itemMetadata[path];
|
|
1235
|
+
return metadata ? [[path, metadata]] : [];
|
|
1236
|
+
}));
|
|
1237
|
+
const ready = {
|
|
1238
|
+
configHash,
|
|
1239
|
+
source: source.key,
|
|
1240
|
+
mountPath: source.mountPath,
|
|
1241
|
+
ownsMount,
|
|
1242
|
+
ownedAncestors,
|
|
1243
|
+
ownedDirectories: [...ownedDirectories],
|
|
1244
|
+
status: "ready",
|
|
1245
|
+
revision,
|
|
1246
|
+
materializedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1247
|
+
files: sourceFiles,
|
|
1248
|
+
bytes: sourceBytes,
|
|
1249
|
+
items: readyItems,
|
|
1250
|
+
cacheMaxAge: source.cache ? source.cache.maxAge : void 0
|
|
1251
|
+
};
|
|
1252
|
+
if (completeSource) await control.mutate(() => writeSourceSnapshotMetadata(store, workspace, ready));
|
|
1253
|
+
else if (existing?.configHash === configHash) {
|
|
1254
|
+
const scopedItems = checkpointItems(itemMetadata);
|
|
1255
|
+
await control.mutate(() => writeSourceSnapshotMetadata(store, workspace, {
|
|
1256
|
+
...existing,
|
|
1257
|
+
ownsMount,
|
|
1258
|
+
ownedAncestors,
|
|
1259
|
+
ownedDirectories: [...ownedDirectories],
|
|
1260
|
+
bytes: Math.max(0, (existing.bytes || 0) + persistedBytesDelta),
|
|
1261
|
+
files: scopedItems ? Object.keys(scopedItems).length : 0,
|
|
1262
|
+
items: scopedItems
|
|
1263
|
+
}));
|
|
1264
|
+
} else if (existing || source.materialize === "startup") {
|
|
1265
|
+
const migratedItems = checkpointItems(itemMetadata);
|
|
1266
|
+
await control.mutate(() => writeSourceSnapshotMetadata(store, workspace, {
|
|
1267
|
+
...ready,
|
|
1268
|
+
status: "updating",
|
|
1269
|
+
items: migratedItems,
|
|
1270
|
+
files: migratedItems ? Object.keys(migratedItems).length : 0,
|
|
1271
|
+
bytes: retainPriorItems ? Math.max(0, (existing?.bytes || 0) + persistedBytesDelta) : sourceBytes
|
|
1272
|
+
}));
|
|
1273
|
+
}
|
|
1274
|
+
const durationMs = Date.now() - sourceStarted;
|
|
1275
|
+
const resultSource = {
|
|
1276
|
+
...ready,
|
|
1277
|
+
cacheStatus,
|
|
1278
|
+
counts: { ...counts },
|
|
1279
|
+
durationMs,
|
|
1280
|
+
provider: source.source.name
|
|
1281
|
+
};
|
|
1282
|
+
const reportedPaths = materializationPaths(options, paths);
|
|
1283
|
+
if (reportedPaths) resultSource.paths = reportedPaths;
|
|
1284
|
+
resultSources.push(resultSource);
|
|
1285
|
+
files += sourceFiles;
|
|
1286
|
+
bytes += sourceBytes;
|
|
1287
|
+
directories += directorySet.size;
|
|
1288
|
+
await reportMaterializationProgress(options, source, {
|
|
1289
|
+
bytes: sourceBytes,
|
|
1290
|
+
cacheStatus,
|
|
1291
|
+
counts: { ...counts },
|
|
1292
|
+
directories: directorySet.size,
|
|
1293
|
+
durationMs,
|
|
1294
|
+
files: sourceFiles,
|
|
1295
|
+
revision,
|
|
1296
|
+
status: "completed"
|
|
1297
|
+
});
|
|
1298
|
+
} catch (error) {
|
|
1299
|
+
const checkpointItemsMetadata = checkpointItems(itemMetadata);
|
|
1300
|
+
const resumesExistingSnapshot = existing?.configHash === configHash;
|
|
1301
|
+
const failed = {
|
|
1302
|
+
configHash,
|
|
1303
|
+
source: source.key,
|
|
1304
|
+
mountPath: source.mountPath,
|
|
1305
|
+
ownsMount,
|
|
1306
|
+
ownedAncestors,
|
|
1307
|
+
ownedDirectories: [...ownedDirectories],
|
|
1308
|
+
status: "error",
|
|
1309
|
+
revision,
|
|
1310
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1311
|
+
files: resumesExistingSnapshot && checkpointItemsMetadata ? Object.keys(checkpointItemsMetadata).length : sourceFiles,
|
|
1312
|
+
bytes: resumesExistingSnapshot ? Math.max(0, (existing?.bytes || 0) + persistedBytesDelta) : sourceBytes,
|
|
1313
|
+
items: checkpointItemsMetadata,
|
|
1314
|
+
cacheMaxAge: source.cache ? source.cache.maxAge : void 0
|
|
1315
|
+
};
|
|
1316
|
+
const checkpoint = options.abortSignal?.aborted ? completeSource ? {
|
|
1317
|
+
...failed,
|
|
1318
|
+
status: "updating",
|
|
1319
|
+
error: void 0
|
|
1320
|
+
} : existing?.configHash === configHash ? {
|
|
1321
|
+
...existing,
|
|
1322
|
+
ownsMount,
|
|
1323
|
+
ownedAncestors,
|
|
1324
|
+
ownedDirectories: [...ownedDirectories],
|
|
1325
|
+
items: checkpointItemsMetadata
|
|
1326
|
+
} : source.materialize === "startup" ? {
|
|
1327
|
+
...failed,
|
|
1328
|
+
status: "updating",
|
|
1329
|
+
error: void 0
|
|
1330
|
+
} : void 0 : failed;
|
|
1331
|
+
if (checkpoint && control.isCurrent()) await control.checkpoint(() => writeSourceSnapshotMetadata(store, workspace, checkpoint));
|
|
1332
|
+
const durationMs = Date.now() - sourceStarted;
|
|
1333
|
+
const failedSource = {
|
|
1334
|
+
...failed,
|
|
1335
|
+
cacheStatus,
|
|
1336
|
+
counts: { ...counts },
|
|
1337
|
+
durationMs,
|
|
1338
|
+
provider: source.source.name
|
|
1339
|
+
};
|
|
1340
|
+
const reportedPaths = materializationPaths(options, paths);
|
|
1341
|
+
if (reportedPaths) failedSource.paths = reportedPaths;
|
|
1342
|
+
resultSources.push(failedSource);
|
|
1343
|
+
await reportMaterializationProgress(options, source, {
|
|
1344
|
+
bytes: sourceBytes,
|
|
1345
|
+
cacheStatus,
|
|
1346
|
+
counts: { ...counts },
|
|
1347
|
+
durationMs,
|
|
1348
|
+
error: failed.error,
|
|
1349
|
+
files: sourceFiles,
|
|
1350
|
+
revision,
|
|
1351
|
+
status: "failed"
|
|
1352
|
+
});
|
|
1353
|
+
if (options.abortSignal?.aborted) throw error;
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
return {
|
|
1357
|
+
bytes,
|
|
1358
|
+
directories,
|
|
1359
|
+
durationMs: Date.now() - started,
|
|
1360
|
+
files,
|
|
1361
|
+
path: normalizeWorkspacePath(options.path || ""),
|
|
1362
|
+
sources: resultSources
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
async function readResolvedSourceFile(resolution, store, ctx, options) {
|
|
1366
|
+
const file = await store.readFile(resolution.workspacePath);
|
|
1367
|
+
if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${resolution.workspacePath}.`);
|
|
1368
|
+
return decodeFile(file.content, options);
|
|
1369
|
+
}
|
|
1370
|
+
async function writeMaterializedFile(store, path, file, previousContent) {
|
|
1371
|
+
if (file.contentStream) {
|
|
1372
|
+
if (store.writeFileStream) {
|
|
1373
|
+
let size = 0;
|
|
1374
|
+
const hash = createHash("sha256");
|
|
1375
|
+
const content = (async function* () {
|
|
1376
|
+
for await (const chunk of contentStreamChunks(file.contentStream)) {
|
|
1377
|
+
size += chunk.byteLength;
|
|
1378
|
+
hash.update(chunk);
|
|
1379
|
+
yield chunk;
|
|
1380
|
+
}
|
|
1381
|
+
})();
|
|
1382
|
+
const write = () => store.writeFileStream(path, {
|
|
1383
|
+
path: file.path,
|
|
1384
|
+
content,
|
|
1385
|
+
mediaType: file.mediaType,
|
|
1386
|
+
metadata: file.metadata
|
|
1387
|
+
});
|
|
1388
|
+
const written = await write();
|
|
1389
|
+
if (!written.digest) throw workspaceError("[vitehub] Workspace Store writeFileStream() must return a content digest.");
|
|
1390
|
+
return {
|
|
1391
|
+
digest: hash.digest("hex"),
|
|
1392
|
+
storeDigest: written.digest,
|
|
1393
|
+
size
|
|
1394
|
+
};
|
|
1395
|
+
}
|
|
1396
|
+
const content = await contentStreamToBytes(file.contentStream);
|
|
1397
|
+
await store.writeFile(path, {
|
|
1398
|
+
path: file.path,
|
|
1399
|
+
content,
|
|
1400
|
+
mediaType: file.mediaType,
|
|
1401
|
+
metadata: file.metadata
|
|
1402
|
+
});
|
|
1403
|
+
return {
|
|
1404
|
+
contentEqual: previousContent !== void 0 && contentEquals(previousContent, content),
|
|
1405
|
+
digest: await sha256(content),
|
|
1406
|
+
size: content.byteLength
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
const content = file.content ?? "";
|
|
1410
|
+
await store.writeFile(path, {
|
|
1411
|
+
path: file.path,
|
|
1412
|
+
content,
|
|
1413
|
+
mediaType: file.mediaType,
|
|
1414
|
+
metadata: file.metadata
|
|
1415
|
+
});
|
|
1416
|
+
return {
|
|
1417
|
+
digest: await sha256(content),
|
|
1418
|
+
size: contentSize(content)
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
async function statVirtualSourcePath(source, workspacePath, store, ctx) {
|
|
1422
|
+
const stored = await store.stat(workspacePath);
|
|
1423
|
+
if (stored) return stored;
|
|
1424
|
+
const keys = await source.source.getKeys(ctx);
|
|
1425
|
+
const sourcePath = normalizeSourcePath(source, workspacePath);
|
|
1426
|
+
if (!sourcePath && keys.length > 0) return {
|
|
1427
|
+
path: source.mountPath,
|
|
1428
|
+
type: "directory"
|
|
1429
|
+
};
|
|
1430
|
+
if (keys.includes(sourcePath)) return {
|
|
1431
|
+
path: workspacePath,
|
|
1432
|
+
type: "file",
|
|
1433
|
+
digest: readDigest(await source.source.getMeta?.(sourcePath, ctx))
|
|
1434
|
+
};
|
|
1435
|
+
if (keys.some((key) => key.startsWith(`${sourcePath}/`))) return {
|
|
1436
|
+
path: workspacePath,
|
|
1437
|
+
type: "directory"
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
async function searchMaterializedStore(store, query) {
|
|
1441
|
+
const limit = query.limit ?? 100;
|
|
1442
|
+
const result = [];
|
|
1443
|
+
const entries = query.paths?.length ? (await Promise.all(query.paths.map(async (path) => {
|
|
1444
|
+
const [stat, nested] = await Promise.all([store.stat(path), store.glob(`${path}/**/*`)]);
|
|
1445
|
+
return [...stat?.type === "file" ? [stat] : [], ...nested];
|
|
1446
|
+
}))).flat() : await store.glob("**/*");
|
|
1447
|
+
for (const entry of entries) {
|
|
1448
|
+
if (entry.type !== "file") continue;
|
|
1449
|
+
const file = await store.readFile(entry.path);
|
|
1450
|
+
if (!file) continue;
|
|
1451
|
+
const text = isWorkspaceBytes(file.content) ? new TextDecoder().decode(file.content) : file.content;
|
|
1452
|
+
result.push(...searchText(entry.path, text, {
|
|
1453
|
+
...query,
|
|
1454
|
+
limit: limit - result.length
|
|
1455
|
+
}));
|
|
1456
|
+
if (result.length >= limit) break;
|
|
1457
|
+
}
|
|
1458
|
+
return result.slice(0, limit);
|
|
1459
|
+
}
|
|
1460
|
+
function createLazyMaterializedMetadata(resolution, item, upstreamMeta) {
|
|
1461
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1462
|
+
const metadata = {
|
|
1463
|
+
source: resolution.sourceKey,
|
|
1464
|
+
sourcePath: resolution.sourcePath,
|
|
1465
|
+
materializedAt: now,
|
|
1466
|
+
validatedAt: resolution.validate === "request" ? now : void 0,
|
|
1467
|
+
etag: readStringMeta(upstreamMeta, "etag"),
|
|
1468
|
+
sha: readStringMeta(upstreamMeta, "sha"),
|
|
1469
|
+
digest: readStringMeta(upstreamMeta, "digest") || readStringMeta(item.metadata, "digest"),
|
|
1470
|
+
ref: readStringMeta(upstreamMeta, "ref")
|
|
1471
|
+
};
|
|
1472
|
+
for (const key of [
|
|
1473
|
+
"validatedAt",
|
|
1474
|
+
"etag",
|
|
1475
|
+
"sha",
|
|
1476
|
+
"digest",
|
|
1477
|
+
"ref"
|
|
1478
|
+
]) if (metadata[key] === void 0) delete metadata[key];
|
|
1479
|
+
return metadata;
|
|
1480
|
+
}
|
|
1481
|
+
function hasSourceMetaChanged(current, upstreamMeta) {
|
|
1482
|
+
const next = {
|
|
1483
|
+
etag: readStringMeta(upstreamMeta, "etag"),
|
|
1484
|
+
sha: readStringMeta(upstreamMeta, "sha"),
|
|
1485
|
+
digest: readStringMeta(upstreamMeta, "digest"),
|
|
1486
|
+
ref: readStringMeta(upstreamMeta, "ref")
|
|
1487
|
+
};
|
|
1488
|
+
return current.etag !== next.etag || current.sha !== next.sha || current.digest !== next.digest || current.ref !== next.ref;
|
|
1489
|
+
}
|
|
1490
|
+
function normalizeSourcePath(source, workspacePath) {
|
|
1491
|
+
if (workspacePath === source.mountPath) return "";
|
|
1492
|
+
return source.mountPath && workspacePath.startsWith(`${source.mountPath}/`) ? normalizeWorkspacePath(workspacePath.slice(source.mountPath.length + 1)) : normalizeWorkspacePath(workspacePath);
|
|
1493
|
+
}
|
|
1494
|
+
function readStringMeta(meta, key) {
|
|
1495
|
+
const value = meta?.[key];
|
|
1496
|
+
return Object.prototype.toString.call(value) === "[object String]" ? String(value) : void 0;
|
|
1497
|
+
}
|
|
1498
|
+
function readDigest(meta) {
|
|
1499
|
+
return readStringMeta(meta, "digest") || readStringMeta(meta, "sha");
|
|
1500
|
+
}
|
|
1501
|
+
//#endregion
|
|
1502
|
+
//#region src/storage/metadata-target.ts
|
|
1503
|
+
/** Internal capability used only by Source Sync through wrapped writable facades. */
|
|
1504
|
+
const workspaceInternalMetadataCapability = Symbol("vitehub.workspace.internalMetadata");
|
|
1505
|
+
const metadataTargetResolvers = /* @__PURE__ */ new WeakMap();
|
|
1506
|
+
const metadataTargetsByStore = /* @__PURE__ */ new WeakMap();
|
|
1507
|
+
const metadataSetters = /* @__PURE__ */ new WeakMap();
|
|
1508
|
+
const facadeMetadataTargets = /* @__PURE__ */ new WeakMap();
|
|
1509
|
+
const privateMetadataTargets = /* @__PURE__ */ new WeakMap();
|
|
1510
|
+
function createWorkspaceMetadataTarget(store, workspaceName) {
|
|
1511
|
+
const targets = metadataTargetsByStore.get(store) ?? /* @__PURE__ */ new Map();
|
|
1512
|
+
const existing = targets.get(workspaceName);
|
|
1513
|
+
if (existing) return existing;
|
|
1514
|
+
const setMeta = store.setMeta?.bind(store);
|
|
1515
|
+
const target = {
|
|
1516
|
+
workspaceName,
|
|
1517
|
+
readFile: store.readFile?.bind(store),
|
|
1518
|
+
writeFile: store.writeFile?.bind(store),
|
|
1519
|
+
mkdir: store.mkdir?.bind(store),
|
|
1520
|
+
rm: store.rm?.bind(store),
|
|
1521
|
+
getMeta: store.getMeta?.bind(store),
|
|
1522
|
+
list: store.list?.bind(store)
|
|
1523
|
+
};
|
|
1524
|
+
if (setMeta) metadataSetters.set(target, setMeta);
|
|
1525
|
+
const publicTarget = {
|
|
1526
|
+
workspaceName,
|
|
1527
|
+
readFile: target.readFile,
|
|
1528
|
+
getMeta: target.getMeta,
|
|
1529
|
+
list: target.list
|
|
1530
|
+
};
|
|
1531
|
+
privateMetadataTargets.set(publicTarget, target);
|
|
1532
|
+
forwardWorkspaceStoreTarget(store, target);
|
|
1533
|
+
forwardWorkspaceStoreTarget(store, publicTarget);
|
|
1534
|
+
targets.set(workspaceName, publicTarget);
|
|
1535
|
+
metadataTargetsByStore.set(store, targets);
|
|
1536
|
+
return publicTarget;
|
|
1537
|
+
}
|
|
1538
|
+
/** Writes internal metadata without exposing the privileged setter on a facade. */
|
|
1539
|
+
async function setWorkspaceMetadata(target, key, value) {
|
|
1540
|
+
const setter = metadataSetters.get(target) || metadataSetters.get(privateMetadataTargets.get(target) ?? target);
|
|
1541
|
+
if (!setter) return false;
|
|
1542
|
+
await setter(key, value, workspaceInternalMetadataCapability);
|
|
1543
|
+
return true;
|
|
1544
|
+
}
|
|
1545
|
+
function attachWorkspaceMetadataTarget(carrier, resolve) {
|
|
1546
|
+
metadataTargetResolvers.set(carrier, resolve);
|
|
1547
|
+
if ("fs" in carrier) facadeMetadataTargets.set(carrier.fs, async () => await resolve());
|
|
1548
|
+
}
|
|
1549
|
+
function forwardWorkspaceMetadataTarget(source, target) {
|
|
1550
|
+
const resolve = metadataTargetResolver(source);
|
|
1551
|
+
if (resolve) attachWorkspaceMetadataTarget(target, resolve);
|
|
1552
|
+
}
|
|
1553
|
+
async function resolveWorkspaceMetadataTarget(source) {
|
|
1554
|
+
return await metadataTargetResolver(source)?.();
|
|
1555
|
+
}
|
|
1556
|
+
/**
|
|
1557
|
+
* Attaches a read-only metadata view of `source` to `target`.
|
|
1558
|
+
* The view has the Workspace name, `getMeta`, `list`, and the Store target. It never has Store writes.
|
|
1559
|
+
* `filterEntries` limits the listed entries, for example to an access scope.
|
|
1560
|
+
* Internal: `@vite-hub/agent` uses this for its Workspace facades.
|
|
1561
|
+
*/
|
|
1562
|
+
function forwardWorkspaceMetadataView(source, target, filterEntries) {
|
|
1563
|
+
const resolve = metadataTargetResolver(source);
|
|
1564
|
+
if (!resolve) return;
|
|
1565
|
+
metadataTargetResolvers.set(target, async () => {
|
|
1566
|
+
const metadata = await resolve();
|
|
1567
|
+
if (!metadata) return;
|
|
1568
|
+
const list = metadata.list?.bind(metadata);
|
|
1569
|
+
const view = {
|
|
1570
|
+
workspaceName: metadata.workspaceName,
|
|
1571
|
+
getMeta: metadata.getMeta?.bind(metadata),
|
|
1572
|
+
list: list ? async (path, options) => {
|
|
1573
|
+
const entries = await list(path, options);
|
|
1574
|
+
return filterEntries ? filterEntries(entries) : entries;
|
|
1575
|
+
} : void 0
|
|
1576
|
+
};
|
|
1577
|
+
forwardWorkspaceStoreTarget(metadata, view);
|
|
1578
|
+
return view;
|
|
1579
|
+
});
|
|
1580
|
+
}
|
|
1581
|
+
function metadataTargetResolver(source) {
|
|
1582
|
+
if (source === null || !(typeof source === "object" || typeof source === "function")) return void 0;
|
|
1583
|
+
return metadataTargetResolvers.get(source) ?? ("fs" in source && source.fs !== null && typeof source.fs === "object" ? facadeMetadataTargets.get(source.fs) : void 0);
|
|
1584
|
+
}
|
|
1585
|
+
function resolveWorkspaceMetadataMutationTarget(target) {
|
|
1586
|
+
return privateMetadataTargets.get(target) ?? target;
|
|
1587
|
+
}
|
|
1588
|
+
//#endregion
|
|
1589
|
+
export { removeWorkspaceOwnedFile as A, withWorkspaceStoreMutation as C, readWorkspaceFileOwner as D, normalizeSourceFileMetadata as E, registerWorkspaceStoreAlias as M, workspaceStoreIdentity as N, recordWorkspaceFileOwner as O, sourceMountOwnsPath as S, normalizeMetadataValue as T, reconcileRemovedStartupSources as _, resolveWorkspaceMetadataMutationTarget as a, statVirtualSourcePath as b, workspaceInternalMetadataCapability as c, invalidateSourceSnapshot as d, materializeWorkspaceSources as f, readSourceSnapshotPaths as g, readResolvedSourceFile as h, forwardWorkspaceMetadataView as i, withWorkspaceFileCheckpoint as j, removeWorkspaceFileOwner as k, hasCurrentSourceSnapshot as l, readCurrentSourceSnapshot as m, createWorkspaceMetadataTarget as n, resolveWorkspaceMetadataTarget as o, materializesCompleteSource as p, forwardWorkspaceMetadataTarget as r, setWorkspaceMetadata as s, attachWorkspaceMetadataTarget as t, hasFreshSourceSnapshot as u, searchMaterializedStore as v, normalizeSourceItemPath as w, createWorkspaceSourceMountAuthority as x, sourceSnapshotOwnsAnyPath as y };
|