zelos-recad 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +18 -5
  2. package/UPSTREAM-LICENSE +21 -21
  3. package/build-info.json +26 -0
  4. package/mcp/index.js +2 -1
  5. package/package.json +22 -10
  6. package/protocol/src/bundle.d.ts +7 -1
  7. package/protocol/src/contracts.d.ts +18 -6
  8. package/protocol/src/contracts.js +20 -7
  9. package/protocol/src/native-evidence.d.ts +20 -0
  10. package/service/app.js +4 -2
  11. package/service/options.d.ts +2 -1
  12. package/service/options.js +2 -1
  13. package/shared/build-identity.d.mts +6 -0
  14. package/shared/build-identity.mjs +63 -0
  15. package/shared/client.d.mts +1 -0
  16. package/shared/client.mjs +9 -0
  17. package/shared/command.d.mts +1 -0
  18. package/shared/command.mjs +22 -4
  19. package/shared/contracts/src/paths.d.ts +3 -0
  20. package/shared/contracts/src/paths.js +31 -0
  21. package/shared/mcp.d.mts +1 -0
  22. package/shared/service-storage/src/capacity.d.ts +36 -0
  23. package/shared/service-storage/src/capacity.js +71 -0
  24. package/shared/service-storage/src/consumption.d.ts +15 -0
  25. package/shared/service-storage/src/consumption.js +27 -0
  26. package/shared/service-storage/src/documents.d.ts +43 -0
  27. package/shared/service-storage/src/documents.js +210 -0
  28. package/shared/service-storage/src/downloads.d.ts +10 -0
  29. package/shared/service-storage/src/downloads.js +58 -0
  30. package/shared/service-storage/src/files.d.ts +18 -0
  31. package/shared/service-storage/src/files.js +118 -0
  32. package/shared/service-storage/src/footprint.d.ts +14 -0
  33. package/shared/service-storage/src/footprint.js +72 -0
  34. package/shared/service-storage/src/process-temp.d.ts +22 -0
  35. package/shared/service-storage/src/process-temp.js +181 -0
  36. package/shared/service-storage/src/quota.d.ts +30 -0
  37. package/shared/service-storage/src/quota.js +166 -0
  38. package/shared/service-storage/src/retention.d.ts +38 -0
  39. package/shared/service-storage/src/retention.js +148 -0
  40. package/shared/service-storage/src/staging.d.ts +15 -0
  41. package/shared/service-storage/src/staging.js +116 -0
  42. package/source/README.md +1 -3
  43. package/source/mcp/index.ts +2 -1
  44. package/source/package.json +4 -2
  45. package/source/protocol/src/contracts.ts +20 -7
  46. package/source/protocol/src/native-evidence.ts +21 -0
  47. package/source/rebuild.mjs +12 -4
  48. package/source/service/app.ts +6 -2
  49. package/source/service/options.ts +3 -2
  50. package/source/shared/build-identity.d.mts +6 -0
  51. package/source/shared/build-identity.mjs +63 -0
  52. package/source/shared/client.d.mts +1 -0
  53. package/source/shared/client.mjs +9 -0
  54. package/source/shared/command.d.mts +1 -0
  55. package/source/shared/command.mjs +22 -4
  56. package/source/shared/contracts/src/paths.ts +33 -0
  57. package/source/shared/mcp.d.mts +1 -0
  58. package/source/shared/service-storage/src/capacity.ts +101 -0
  59. package/source/shared/service-storage/src/consumption.ts +45 -0
  60. package/source/shared/service-storage/src/documents.ts +262 -0
  61. package/source/shared/service-storage/src/downloads.ts +62 -0
  62. package/source/shared/service-storage/src/files.ts +135 -0
  63. package/source/shared/service-storage/src/footprint.ts +78 -0
  64. package/source/shared/service-storage/src/process-temp.ts +205 -0
  65. package/source/shared/service-storage/src/quota.ts +198 -0
  66. package/source/shared/service-storage/src/retention.ts +180 -0
  67. package/source/shared/service-storage/src/staging.ts +106 -0
  68. package/source/src/application-objects.ts +2 -2
  69. package/source/src/assets.ts +15 -0
  70. package/source/src/block-clip.ts +1 -1
  71. package/source/src/block-metadata.ts +12 -5
  72. package/source/src/build-info.ts +15 -0
  73. package/source/src/cad-engine.ts +18 -8
  74. package/source/src/command.ts +2 -2
  75. package/source/src/constraints.ts +2 -2
  76. package/source/src/conversion.ts +2 -0
  77. package/source/src/dwg-fallback.ts +2 -0
  78. package/source/src/dwg.ts +7 -0
  79. package/source/src/dxf-export.ts +3 -3
  80. package/source/src/dxf.ts +7 -4
  81. package/source/src/native-evidence.ts +33 -1
  82. package/source/src/native-segmented-path.ts +22 -35
  83. package/source/src/point-dictionaries.ts +65 -0
  84. package/source/src/readback.ts +7 -6
  85. package/source/src/reader.ts +19 -10
  86. package/source/src/render-operation.ts +39 -7
  87. package/source/src/runner.ts +5 -4
  88. package/source/src/runtime/documents.ts +23 -142
  89. package/source/src/runtime/index.ts +71 -17
  90. package/source/src/runtime/jobs.ts +176 -153
  91. package/source/src/runtime/managed-worker.ts +37 -0
  92. package/source/src/runtime/storage-policy.ts +39 -0
  93. package/source/src/runtime/storage.ts +9 -44
  94. package/source/src/source-scene.ts +125 -23
  95. package/source/src/text/glyphs.ts +63 -0
  96. package/source/src/text/ink-bounds.ts +7 -36
  97. package/source/src/text/scene-geometry.ts +92 -0
  98. package/source/src/text/source-fonts.ts +31 -0
  99. package/source/src/vendor-object-data.ts +265 -0
  100. package/source/src/xref.ts +4 -3
  101. package/source/tsconfig.json +4 -2
  102. package/src/application-objects.js +2 -2
  103. package/src/assets.d.ts +9 -0
  104. package/src/assets.js +14 -0
  105. package/src/block-clip.js +1 -1
  106. package/src/block-metadata.js +11 -5
  107. package/src/build-info.d.ts +2 -0
  108. package/src/build-info.js +14 -0
  109. package/src/cad-engine.js +19 -8
  110. package/src/command.js +2 -2
  111. package/src/constraints.js +2 -2
  112. package/src/conversion.d.ts +2 -0
  113. package/src/conversion.js +2 -0
  114. package/src/dwg-fallback.d.ts +1 -0
  115. package/src/dwg-fallback.js +2 -0
  116. package/src/dwg.d.ts +3 -0
  117. package/src/dwg.js +7 -0
  118. package/src/dxf-export.js +3 -3
  119. package/src/dxf.d.ts +14 -1
  120. package/src/dxf.js +7 -3
  121. package/src/native-evidence.d.ts +33 -1
  122. package/src/native-evidence.js +33 -0
  123. package/src/native-segmented-path.js +1 -3
  124. package/src/point-dictionaries.d.ts +12 -0
  125. package/src/point-dictionaries.js +88 -0
  126. package/src/readback.d.ts +12 -4
  127. package/src/readback.js +7 -6
  128. package/src/reader.d.ts +12 -1
  129. package/src/reader.js +22 -11
  130. package/src/render-operation.js +36 -7
  131. package/src/runner.js +5 -4
  132. package/src/runtime/documents.d.ts +8 -20
  133. package/src/runtime/documents.js +17 -116
  134. package/src/runtime/index.d.ts +41 -4
  135. package/src/runtime/index.js +72 -18
  136. package/src/runtime/jobs.d.ts +21 -2
  137. package/src/runtime/jobs.js +120 -100
  138. package/src/runtime/managed-worker.d.ts +8 -0
  139. package/src/runtime/managed-worker.js +29 -0
  140. package/src/runtime/storage-policy.d.ts +25 -0
  141. package/src/runtime/storage-policy.js +29 -0
  142. package/src/runtime/storage.d.ts +1 -7
  143. package/src/runtime/storage.js +1 -38
  144. package/src/source-scene.d.ts +4 -2
  145. package/src/source-scene.js +136 -20
  146. package/src/text/glyphs.d.ts +12 -0
  147. package/src/text/glyphs.js +53 -0
  148. package/src/text/ink-bounds.d.ts +2 -1
  149. package/src/text/ink-bounds.js +6 -34
  150. package/src/text/scene-geometry.d.ts +21 -0
  151. package/src/text/scene-geometry.js +70 -0
  152. package/src/text/source-fonts.d.ts +7 -0
  153. package/src/text/source-fonts.js +30 -0
  154. package/src/vendor-object-data.d.ts +19 -0
  155. package/src/vendor-object-data.js +241 -0
  156. package/src/xref.js +3 -3
  157. package/vendor/libredwg/COPYING +674 -674
  158. package/vendor/libredwg/Dockerfile +2 -0
  159. package/vendor/libredwg/README.md +41 -28
  160. package/vendor/libredwg/build-local.sh +1 -1
  161. package/vendor/libredwg/libredwg-web.wasm +0 -0
  162. package/vendor/libredwg/manifest.json +5 -3
  163. package/vendor/libredwg/opaque-object-binding.patch +29 -0
  164. package/vendor/libredwg/rebuild.mjs +2 -1
  165. package/source/service/README.md +0 -152
  166. package/source/src/text/UPSTREAM.md +0 -26
@@ -0,0 +1,118 @@
1
+ export { containedPath } from "../../contracts/src/paths.js";
2
+ import { randomUUID, createHash } from 'node:crypto';
3
+ import { mkdirSync, realpathSync, lstatSync, writeFileSync, renameSync, readdirSync, rmSync, linkSync, copyFileSync, constants, openSync, readSync, closeSync, fsyncSync, } from 'node:fs';
4
+ import path from 'node:path';
5
+ export class StorageError extends Error {
6
+ code;
7
+ statusCode;
8
+ constructor(code, message, statusCode = 400) {
9
+ super(message);
10
+ this.code = code;
11
+ this.statusCode = statusCode;
12
+ }
13
+ }
14
+ export const idPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
15
+ export function checkedId(value) {
16
+ if (typeof value !== 'string' || !idPattern.test(value))
17
+ throw new StorageError('JOB_ID', '任务标识必须是小写 UUID');
18
+ return value;
19
+ }
20
+ export const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
21
+ export function fileHash(file) {
22
+ const digest = createHash('sha256'), buffer = Buffer.allocUnsafe(1024 * 1024);
23
+ const fd = openSync(file, 'r');
24
+ try {
25
+ let size;
26
+ while ((size = readSync(fd, buffer, 0, buffer.length, null)))
27
+ digest.update(buffer.subarray(0, size));
28
+ return digest.digest('hex');
29
+ }
30
+ finally {
31
+ closeSync(fd);
32
+ }
33
+ }
34
+ /** Only published, immutable content may share a file identity. */
35
+ export function linkImmutable(source, target, beforeCopy) {
36
+ try {
37
+ linkSync(source, target);
38
+ return 'shared';
39
+ }
40
+ catch (error) {
41
+ if (!['EXDEV', 'ENOTSUP', 'EOPNOTSUPP', 'EPERM', 'EACCES', 'ENOSYS'].includes(error.code || ''))
42
+ throw error;
43
+ beforeCopy?.();
44
+ copyFileSync(source, target, constants.COPYFILE_EXCL);
45
+ const fd = openSync(target, 'r+');
46
+ try {
47
+ fsyncSync(fd);
48
+ }
49
+ finally {
50
+ closeSync(fd);
51
+ }
52
+ return 'copied';
53
+ }
54
+ }
55
+ export function atomicJson(file, value) {
56
+ const temporary = file + '.' + randomUUID() + '.tmp';
57
+ try {
58
+ writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', flush: true });
59
+ renameSync(temporary, file);
60
+ }
61
+ finally {
62
+ rmSync(temporary, { force: true });
63
+ }
64
+ }
65
+ export function dataRoot(directory) {
66
+ mkdirSync(directory, { recursive: true });
67
+ if (lstatSync(directory).isSymbolicLink())
68
+ throw new StorageError('STORAGE_LINK', '服务存储包含链接');
69
+ return realpathSync(directory);
70
+ }
71
+ /** Validate every descendant before measuring or deleting owned storage. */
72
+ export function directoryBytes(directory, allowMissing = false) {
73
+ const seen = new Set();
74
+ function visit(file) {
75
+ try {
76
+ return measure(file);
77
+ }
78
+ catch (error) {
79
+ if (allowMissing && error.code === 'ENOENT')
80
+ return 0;
81
+ throw error;
82
+ }
83
+ }
84
+ function measure(file) {
85
+ const stat = lstatSync(file, { bigint: true });
86
+ if (stat.isSymbolicLink())
87
+ throw new StorageError('STORAGE_LINK', '服务存储包含链接');
88
+ if (stat.isDirectory())
89
+ return readdirSync(file).reduce((size, name) => size + visit(path.join(file, name)), 0);
90
+ if (!stat.isFile())
91
+ throw new StorageError('STORAGE_TYPE', '服务存储需要普通文件');
92
+ // BigInt preserves large NTFS file IDs. A missing identity is conservatively counted per path.
93
+ const key = stat.ino ? `${stat.dev}:${stat.ino}` : file;
94
+ if (seen.has(key))
95
+ return 0;
96
+ seen.add(key);
97
+ return Number(stat.size);
98
+ }
99
+ return visit(directory);
100
+ }
101
+ export function removeJob(data, id) {
102
+ const root = realpathSync(data), target = path.resolve(root, checkedId(id));
103
+ if (path.dirname(target) !== root ||
104
+ lstatSync(target).isSymbolicLink() ||
105
+ realpathSync(target) !== target)
106
+ throw new StorageError('STORAGE_PATH', '清理目标超出任务目录');
107
+ directoryBytes(target);
108
+ rmSync(target, { recursive: true });
109
+ }
110
+ export function canonical(value) {
111
+ if (Array.isArray(value))
112
+ return value.map(canonical);
113
+ if (value && typeof value === 'object')
114
+ return Object.fromEntries(Object.keys(value)
115
+ .sort()
116
+ .map((key) => [key, canonical(value[key])]));
117
+ return value;
118
+ }
@@ -0,0 +1,14 @@
1
+ export interface StorageFootprint {
2
+ startedAt: number;
3
+ files: {
4
+ id: string;
5
+ volumeId: string;
6
+ allocatedBytes: number;
7
+ links: number;
8
+ bornAt: number;
9
+ }[];
10
+ }
11
+ /** Workers inspect metadata only. Hard links are counted once; source bytes are never read. */
12
+ export declare function storageFootprint(roots: string | readonly string[], check?: () => void): StorageFootprint;
13
+ /** Only attributable live allocations reduce unspent reservation; shared/unknown bytes stay conservative. */
14
+ export declare function materializedStorage(baseline: StorageFootprint, current: StorageFootprint): Map<string, number>;
@@ -0,0 +1,72 @@
1
+ import { existsSync, lstatSync, readdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { containedPath } from "./files.js";
4
+ /** Workers inspect metadata only. Hard links are counted once; source bytes are never read. */
5
+ export function storageFootprint(roots, check = () => { }) {
6
+ const result = { startedAt: Date.now(), files: [] };
7
+ const seen = new Set(), pending = (typeof roots === 'string' ? [roots] : roots)
8
+ .filter((root) => existsSync(root))
9
+ .map((root) => ({ root, folder: root }));
10
+ let entries = 0;
11
+ while (pending.length) {
12
+ const { root, folder } = pending.pop();
13
+ let names;
14
+ try {
15
+ names = readdirSync(folder);
16
+ }
17
+ catch (error) {
18
+ if (error.code === 'ENOENT')
19
+ continue;
20
+ throw error;
21
+ }
22
+ for (const name of names) {
23
+ check();
24
+ if (++entries > 40_000)
25
+ throw new Error('运行空间盘点达到单轮条目预算,保留上次预留');
26
+ let file, stat;
27
+ try {
28
+ file = containedPath(root, path.relative(root, path.join(folder, name)));
29
+ stat = lstatSync(file, { bigint: true });
30
+ }
31
+ catch (error) {
32
+ if (error.code === 'ENOENT')
33
+ continue;
34
+ throw error;
35
+ }
36
+ if (stat.isSymbolicLink())
37
+ throw new Error('运行空间含链接,保留上次预留');
38
+ if (stat.isDirectory()) {
39
+ pending.push({ root, folder: file });
40
+ continue;
41
+ }
42
+ if (!stat.isFile())
43
+ continue;
44
+ const id = `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
45
+ if (seen.has(id))
46
+ continue;
47
+ seen.add(id);
48
+ result.files.push({
49
+ id,
50
+ volumeId: process.platform + ':' + stat.dev,
51
+ allocatedBytes: Number(stat.blocks) * 512,
52
+ links: Number(stat.nlink),
53
+ bornAt: Number(stat.birthtimeMs),
54
+ });
55
+ }
56
+ }
57
+ return result;
58
+ }
59
+ /** Only attributable live allocations reduce unspent reservation; shared/unknown bytes stay conservative. */
60
+ export function materializedStorage(baseline, current) {
61
+ const before = new Map(baseline.files.map((file) => [file.id, file.allocatedBytes])), totals = new Map();
62
+ for (const file of current.files) {
63
+ if (file.links !== 1 || !Number.isSafeInteger(file.allocatedBytes) || file.allocatedBytes < 0)
64
+ continue;
65
+ const previous = before.get(file.id);
66
+ if (previous === undefined && file.bornAt < baseline.startedAt)
67
+ continue;
68
+ const added = Math.max(0, file.allocatedBytes - (previous || 0));
69
+ totals.set(file.volumeId, (totals.get(file.volumeId) || 0) + added);
70
+ }
71
+ return totals;
72
+ }
@@ -0,0 +1,22 @@
1
+ import { spawn, fork, type ExecFileOptions } from 'node:child_process';
2
+ export declare const isProcessTemporaryPath: (relative: string) => boolean;
3
+ type Warning = (id: string, error: unknown) => void;
4
+ /** A process receives a private TEMP on the same volume as its owning workspace.
5
+ * Only close (including inherited stdio closing) authorizes retirement. A stale
6
+ * active record remains under the enclosing job/Run lifecycle after a crash.
7
+ */
8
+ type TemporaryOptions = {
9
+ shellPathVariables?: readonly string[];
10
+ };
11
+ export declare const spawnTemporary: (workspace: string, registration?: string, options?: TemporaryOptions) => typeof spawn;
12
+ export declare const forkTemporary: (workspace: string, registration?: string) => typeof fork;
13
+ /** execFile may reject on abort before stdio closes; retirement still follows close. */
14
+ export declare function executeTemporary(workspace: string, registration?: string): (file: string, args: readonly string[], options?: ExecFileOptions) => Promise<{
15
+ stdout: string;
16
+ stderr: string;
17
+ }>;
18
+ /** Retry only directories whose original parent observed process close. */
19
+ export declare function sweepProcessTemporary(workspace: string, report?: Warning): void;
20
+ /** Application subprocesses register their workspace once; the existing sweep owns retries. */
21
+ export declare function sweepRegisteredProcessTemporary(data: string, report?: Warning): void;
22
+ export {};
@@ -0,0 +1,181 @@
1
+ import { spawn, fork, execFile } from 'node:child_process';
2
+ import { existsSync, lstatSync, readFileSync, readdirSync, rmSync, rmdirSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { atomicJson, dataRoot, hash, StorageError } from "./files.js";
6
+ import { StagedDirectories } from "./staging.js";
7
+ const area = '.process-temp', pending = '.process-temp-pending', registry = 'process-temp-roots';
8
+ const sweepCursors = new Map();
9
+ export const isProcessTemporaryPath = (relative) => relative.split(/[\\/]/).some(name => name === area || name === pending);
10
+ const identity = (directory) => {
11
+ const stat = lstatSync(directory, { bigint: true });
12
+ if (!stat.isDirectory() || stat.isSymbolicLink())
13
+ throw new StorageError('STORAGE_LINK', '进程临时目录需要普通目录');
14
+ return `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
15
+ };
16
+ const warn = (id, error) => console.warn('进程临时文件待回收', id, String(error));
17
+ function removeEmpty(directory) {
18
+ try {
19
+ rmdirSync(directory);
20
+ }
21
+ catch (error) {
22
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code || ''))
23
+ throw error;
24
+ }
25
+ }
26
+ function temporary(workspace, registration, options = {}) {
27
+ workspace = dataRoot(workspace);
28
+ const workspaceIdentity = identity(workspace);
29
+ const directories = new StagedDirectories(path.join(workspace, area), path.join(workspace, pending), undefined, warn);
30
+ const id = randomUUID(), stage = directories.begin(id), directory = path.join(workspace, area, id);
31
+ let record;
32
+ try {
33
+ if (registration) {
34
+ const root = dataRoot(path.join(registration, registry));
35
+ record = path.join(root, hash(workspace) + '.json');
36
+ atomicJson(record, { workspace, identity: workspaceIdentity });
37
+ }
38
+ }
39
+ catch (error) {
40
+ stage.close();
41
+ throw error;
42
+ }
43
+ let closed = false;
44
+ // Keep Python and native tools on the owned directory even beyond MAX_PATH.
45
+ // This changes only the Windows spelling of the same filesystem location.
46
+ const environmentPath = path.toNamespacedPath(directory);
47
+ // Shell-specific variables use a portable spelling of the same owned directory;
48
+ // native TEMP/TMP/TMPDIR retain MAX_PATH support for nested Python tools.
49
+ const shellEnvironment = Object.fromEntries((options.shellPathVariables || []).map(name => [name, directory.replaceAll('\\', '/')]));
50
+ return {
51
+ environment: { TEMP: environmentPath, TMP: environmentPath, TMPDIR: environmentPath, ...shellEnvironment },
52
+ close() {
53
+ if (closed)
54
+ return;
55
+ closed = true;
56
+ try {
57
+ if (identity(workspace) !== workspaceIdentity)
58
+ throw new StorageError('STORAGE_CHANGED', '进程临时目录所属工作区已变化');
59
+ stage.retire(); // Persist the proof of process exit before recursive cleanup.
60
+ stage.close();
61
+ if (!readdirSync(path.join(workspace, pending)).length) {
62
+ removeEmpty(path.join(workspace, area));
63
+ removeEmpty(path.join(workspace, pending));
64
+ if (record)
65
+ rmSync(record, { force: true });
66
+ }
67
+ }
68
+ catch (error) {
69
+ warn(id, error);
70
+ }
71
+ },
72
+ };
73
+ }
74
+ /** Preserve the native spawn/fork overloads and process ownership in the caller. */
75
+ function processEnvironment(env, temporary) {
76
+ // Each job already has an execution slot; nested BLAS pools otherwise allocate one workspace per CPU.
77
+ return { OPENBLAS_NUM_THREADS: '1', OMP_NUM_THREADS: '1', MKL_NUM_THREADS: '1', NUMEXPR_NUM_THREADS: '1',
78
+ ...(env ?? process.env), ...temporary };
79
+ }
80
+ function launchTemporary(launch, workspace, registration, temporaryOptions = {}) {
81
+ return ((command, args, options) => {
82
+ if (!Array.isArray(args)) {
83
+ options = args;
84
+ args = [];
85
+ }
86
+ const lease = temporary(workspace, registration, temporaryOptions);
87
+ try {
88
+ const child = Reflect.apply(launch, undefined, [
89
+ command,
90
+ args,
91
+ { ...options, env: processEnvironment(options?.env, lease.environment) },
92
+ ]);
93
+ child.once('close', () => lease.close());
94
+ return child;
95
+ }
96
+ catch (error) {
97
+ lease.close();
98
+ throw error;
99
+ }
100
+ });
101
+ }
102
+ export const spawnTemporary = (workspace, registration, options = {}) => launchTemporary(spawn, workspace, registration, options);
103
+ export const forkTemporary = (workspace, registration) => launchTemporary(fork, workspace, registration);
104
+ /** execFile may reject on abort before stdio closes; retirement still follows close. */
105
+ export function executeTemporary(workspace, registration) {
106
+ return (file, args, options = {}) => {
107
+ const lease = temporary(workspace, registration);
108
+ return new Promise((resolve, reject) => {
109
+ try {
110
+ const child = execFile(file, args, {
111
+ ...options,
112
+ encoding: 'utf8',
113
+ env: processEnvironment(options.env, lease.environment),
114
+ }, (error, stdout, stderr) => {
115
+ if (error)
116
+ reject(Object.assign(error, { stdout, stderr }));
117
+ else
118
+ resolve({ stdout, stderr });
119
+ });
120
+ child.once('close', () => lease.close());
121
+ }
122
+ catch (error) {
123
+ lease.close();
124
+ reject(error);
125
+ }
126
+ });
127
+ };
128
+ }
129
+ /** Retry only directories whose original parent observed process close. */
130
+ export function sweepProcessTemporary(workspace, report = warn) {
131
+ const root = path.join(workspace, area), markers = path.join(workspace, pending);
132
+ if (!existsSync(root) || !existsSync(markers))
133
+ return;
134
+ new StagedDirectories(root, markers, undefined, report).cleanup(true);
135
+ removeEmpty(root);
136
+ removeEmpty(markers);
137
+ }
138
+ /** Application subprocesses register their workspace once; the existing sweep owns retries. */
139
+ export function sweepRegisteredProcessTemporary(data, report = warn) {
140
+ const root = path.join(data, registry);
141
+ if (!existsSync(root)) {
142
+ sweepCursors.delete(root);
143
+ return;
144
+ }
145
+ identity(root);
146
+ const names = readdirSync(root)
147
+ .filter((name) => /^[a-f0-9]{64}\.json$/.test(name))
148
+ .sort();
149
+ if (!names.length) {
150
+ sweepCursors.delete(root);
151
+ return;
152
+ }
153
+ // Advance past active/locked roots so one old group cannot starve later owners.
154
+ const after = sweepCursors.get(root) ?? '', start = Math.max(0, names.findIndex(name => name > after));
155
+ for (const name of [...names.slice(start), ...names.slice(0, start)].slice(0, 100)) {
156
+ sweepCursors.set(root, name);
157
+ try {
158
+ const file = path.join(root, name);
159
+ if (lstatSync(file).isSymbolicLink())
160
+ throw new StorageError('STORAGE_LINK', '进程临时目录登记包含链接');
161
+ const record = JSON.parse(readFileSync(file, 'utf8'));
162
+ if (typeof record.workspace !== 'string' ||
163
+ !path.isAbsolute(record.workspace) ||
164
+ hash(record.workspace) + '.json' !== name)
165
+ throw new StorageError('STORAGE_CHANGED', '进程临时目录登记无效');
166
+ if (!existsSync(record.workspace)) {
167
+ rmSync(file);
168
+ continue;
169
+ }
170
+ if (identity(record.workspace) !== record.identity)
171
+ throw new StorageError('STORAGE_CHANGED', '进程临时目录所属工作区已变化');
172
+ sweepProcessTemporary(record.workspace, report);
173
+ const markers = path.join(record.workspace, pending);
174
+ if (!existsSync(markers) || !readdirSync(markers).length)
175
+ rmSync(file);
176
+ }
177
+ catch (error) {
178
+ report(name, error);
179
+ }
180
+ }
181
+ }
@@ -0,0 +1,30 @@
1
+ import { volumeSpace, type CapacityPolicy } from './capacity.js';
2
+ export declare const workerStorageBytes: number;
3
+ export interface ServiceCapacityOptions {
4
+ /** Testable OS boundary; production uses the actual filesystem and shared policy. */
5
+ probe?: typeof volumeSpace;
6
+ policy?: CapacityPolicy;
7
+ }
8
+ /** One service ledger covers uploads, submitted inputs and running worker outputs.
9
+ * Physical admission uses the same volume/watermark calculation as the application.
10
+ */
11
+ export declare class StorageQuota {
12
+ readonly data: string;
13
+ readonly limit: number;
14
+ private capacity;
15
+ private uploads;
16
+ private workers;
17
+ private paused;
18
+ constructor(data: string, limit?: number, capacity?: ServiceCapacityOptions);
19
+ private written;
20
+ private growth;
21
+ private reserved;
22
+ private available;
23
+ private admit;
24
+ require(bytes: number): void;
25
+ upload(file: string): {
26
+ ensure: (bytes: number) => void;
27
+ release: () => void;
28
+ };
29
+ runWorker<T>(directory: string, controller: AbortController, work: () => Promise<T>, estimate?: number): Promise<T>;
30
+ }
@@ -0,0 +1,166 @@
1
+ import { lstatSync, readFileSync } from 'node:fs';
2
+ import { atomicJson, containedPath, directoryBytes, StorageError } from "./files.js";
3
+ import { capacityPolicy, capacityVolumes, volumeSpace } from "./capacity.js";
4
+ import { materializedStorage, storageFootprint } from "./footprint.js";
5
+ const WINDOW = 4 * 1024 * 1024;
6
+ export const workerStorageBytes = 600 * 1024 ** 2;
7
+ /** One service ledger covers uploads, submitted inputs and running worker outputs.
8
+ * Physical admission uses the same volume/watermark calculation as the application.
9
+ */
10
+ export class StorageQuota {
11
+ data;
12
+ limit;
13
+ capacity;
14
+ uploads = new Map();
15
+ workers = new Map();
16
+ paused = false;
17
+ constructor(data, limit = 0, capacity = {}) {
18
+ this.data = data;
19
+ this.limit = limit;
20
+ this.capacity = capacity;
21
+ if (!Number.isSafeInteger(limit) || limit < 0)
22
+ throw new StorageError('CONFIG', '临时存储配额需要非负整数');
23
+ try {
24
+ const saved = JSON.parse(readFileSync(containedPath(data, '.capacity-watermark.json'), 'utf8'));
25
+ if (saved.version !== 1 ||
26
+ typeof saved.paused !== 'boolean' ||
27
+ typeof saved.volumeId !== 'string')
28
+ throw new StorageError('STORAGE_CAPACITY_STATE', '服务容量水位记录损坏');
29
+ this.paused = saved.volumeId === (capacity.probe ?? volumeSpace)(data).id && saved.paused;
30
+ }
31
+ catch (error) {
32
+ if (error.code !== 'ENOENT')
33
+ throw error;
34
+ }
35
+ }
36
+ written(file, allocated = false) {
37
+ try {
38
+ const stat = lstatSync(file);
39
+ if (!stat.isFile() || stat.isSymbolicLink())
40
+ throw new StorageError('STORAGE_TYPE', '上传路径需要普通文件');
41
+ return allocated ? (stat.nlink === 1 ? stat.blocks * 512 : 0) : stat.size;
42
+ }
43
+ catch (error) {
44
+ if (error.code !== 'ENOENT')
45
+ throw error;
46
+ return 0;
47
+ }
48
+ }
49
+ growth(directory, budget, physical = false) {
50
+ return physical
51
+ ? [...materializedStorage(budget.footprint, storageFootprint(directory)).values()].reduce((a, b) => a + b, 0)
52
+ : Math.max(0, directoryBytes(directory, true) - budget.baseline);
53
+ }
54
+ reserved(except, physical = false) {
55
+ const factor = physical ? (this.capacity.policy ?? capacityPolicy).estimateFactor : 1;
56
+ let reserved = 0;
57
+ for (const [file, bytes] of this.uploads)
58
+ if (file !== except)
59
+ reserved += Math.max(0, Math.ceil(bytes * factor) - this.written(file, physical));
60
+ for (const [directory, budget] of this.workers)
61
+ if (directory !== except)
62
+ reserved += Math.max(0, Math.ceil(budget.bytes * factor) - this.growth(directory, budget, physical));
63
+ return reserved;
64
+ }
65
+ available(except) {
66
+ return this.limit
67
+ ? this.limit - directoryBytes(this.data, true) - this.reserved(except)
68
+ : Infinity;
69
+ }
70
+ admit(bytes, except, logicalBytes = 0, materializedBytes = 0) {
71
+ if (!Number.isSafeInteger(bytes) || bytes < 0)
72
+ throw new StorageError('STORAGE_SIZE', '存储申请需要非负整数字节');
73
+ if (Math.max(0, bytes - logicalBytes) > this.available(except))
74
+ throw new StorageError('STORAGE_FULL', '服务存储配额不足,请在已有任务回收后重试', 507);
75
+ const policy = this.capacity.policy ?? capacityPolicy;
76
+ const volumes = capacityVolumes([{ key: 'service', directory: this.data, estimatedBytes: bytes, materializedBytes }], () => this.reserved(except, true), () => this.paused, this.capacity.probe ?? volumeSpace, policy);
77
+ const volume = volumes[0];
78
+ const paused = volumes.some((volume) => volume.shortageBytes > 0);
79
+ if (paused !== this.paused) {
80
+ this.paused = paused;
81
+ atomicJson(containedPath(this.data, '.capacity-watermark.json'), {
82
+ version: 1,
83
+ volumeId: volume.id,
84
+ paused,
85
+ });
86
+ }
87
+ if (this.paused)
88
+ throw Object.assign(new StorageError('STORAGE_CAPACITY', `服务磁盘空间不足:当前 ${(volume.freeBytes / 1024 ** 3).toFixed(2)} GiB,需要 ${(volume.requiredBytes / 1024 ** 3).toFixed(2)} GiB;释放空间后接续。`, 507), { volumes });
89
+ return volume;
90
+ }
91
+ require(bytes) {
92
+ this.admit(bytes);
93
+ }
94
+ upload(file) {
95
+ if (this.uploads.has(file))
96
+ throw new StorageError('STORAGE_CONFLICT', '上传文件已有空间申请');
97
+ this.uploads.set(file, 0);
98
+ let released = false;
99
+ return {
100
+ ensure: (bytes) => {
101
+ if (released)
102
+ throw new StorageError('STORAGE_CONFLICT', '上传空间申请已结束');
103
+ if (!Number.isSafeInteger(bytes) || bytes < 0)
104
+ throw new StorageError('STORAGE_SIZE', '上传字节需要非负整数');
105
+ if (bytes <= this.uploads.get(file))
106
+ return;
107
+ const written = this.written(file);
108
+ const volume = this.admit(bytes, file, written, this.written(file, true)), factor = (this.capacity.policy ?? capacityPolicy).estimateFactor;
109
+ const headroom = Math.floor(Math.max(0, volume.freeBytes - volume.requiredBytes) / factor);
110
+ this.uploads.set(file, Math.min(Math.ceil(bytes / WINDOW) * WINDOW, written + this.available(file), bytes + headroom));
111
+ },
112
+ release: () => {
113
+ this.uploads.delete(file);
114
+ released = true;
115
+ },
116
+ };
117
+ }
118
+ async runWorker(directory, controller, work, estimate = workerStorageBytes) {
119
+ if (!Number.isSafeInteger(estimate) || estimate <= 0)
120
+ throw new StorageError('CONFIG', 'Worker初始空间预算需要正整数字节');
121
+ if (this.workers.has(directory))
122
+ throw new StorageError('STORAGE_CONFLICT', 'Worker目录已有空间申请');
123
+ this.admit(estimate);
124
+ const budget = {
125
+ baseline: directoryBytes(directory),
126
+ footprint: storageFootprint(directory),
127
+ bytes: estimate,
128
+ };
129
+ this.workers.set(directory, budget);
130
+ let failure;
131
+ const check = () => {
132
+ const growth = this.growth(directory, budget), window = Math.min(WINDOW, estimate);
133
+ const next = Math.max(budget.bytes, Math.ceil((growth + window) / window) * window);
134
+ this.admit(next, directory, growth, this.growth(directory, budget, true));
135
+ budget.bytes = next;
136
+ };
137
+ const timer = setInterval(() => {
138
+ if (failure || controller.signal.aborted)
139
+ return;
140
+ try {
141
+ check();
142
+ }
143
+ catch (error) {
144
+ failure = error;
145
+ controller.abort(error);
146
+ }
147
+ }, 1000);
148
+ timer.unref();
149
+ try {
150
+ const result = await work();
151
+ if (failure)
152
+ throw failure;
153
+ // Fast workers also pass a final check before the service publishes success.
154
+ // The remaining speculative growth budget is released at this boundary.
155
+ this.admit(0, directory);
156
+ return result;
157
+ }
158
+ catch (error) {
159
+ throw failure ?? error;
160
+ }
161
+ finally {
162
+ clearInterval(timer);
163
+ this.workers.delete(directory);
164
+ }
165
+ }
166
+ }
@@ -0,0 +1,38 @@
1
+ import { DownloadLeases } from './downloads.js';
2
+ import { type Consumption, type ConsumptionReceipt } from './consumption.js';
3
+ export declare const DEFAULT_RETENTION_MS: number;
4
+ export interface RetainedJob {
5
+ id: string;
6
+ status: string;
7
+ endedAt?: string;
8
+ consumed?: Consumption;
9
+ }
10
+ export interface RetentionOptions {
11
+ retentionMs?: number;
12
+ maxStorageBytes?: number;
13
+ downloadGraceMs?: number;
14
+ }
15
+ /** One cleanup algorithm for both services; persistent tombstones also resume partial deletions. */
16
+ export declare class JobRetention<J extends RetainedJob> {
17
+ private context;
18
+ readonly downloads: DownloadLeases;
19
+ constructor(context: {
20
+ data: string;
21
+ options: RetentionOptions;
22
+ jobs: Map<string, J>;
23
+ running: (id: string) => boolean;
24
+ receipt: (job: J, now: number) => object;
25
+ consumption: (job: J) => ConsumptionReceipt;
26
+ warn: (id: string, error: unknown) => void;
27
+ temporaryWorkspaces?: (job: J) => string[];
28
+ });
29
+ private protected;
30
+ private checkedConsumption;
31
+ consume(id: string, raw: unknown): {
32
+ id: string;
33
+ consumedAt: any;
34
+ };
35
+ cleanup(now?: number): {
36
+ removed: string[];
37
+ };
38
+ }