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
@@ -1,18 +1,19 @@
1
1
  import { parseArgs } from 'node:util'
2
2
 
3
3
  /** One command grammar for both engines; engine and transport lifecycle remain injectable. */
4
- export async function runDocumentCommand({ engine, startMcp, serve, doctor, setup, run }) {
4
+ export async function runDocumentCommand({ engine, defaultPorts, startMcp, serve, doctor, setup, run }) {
5
5
  const { values, positionals } = parseArgs({ allowPositionals: true, options: {
6
6
  transport: { type: 'string', default: 'stdio' }, backend: { type: 'string', default: 'local' }, url: { type: 'string' },
7
7
  'data-dir': { type: 'string' }, 'input-root': { type: 'string', multiple: true }, 'output-root': { type: 'string' },
8
8
  host: { type: 'string' }, port: { type: 'string' }, python: { type: 'string' }, resources: { type: 'string' },
9
9
  concurrency: { type: 'string' }, 'timeout-ms': { type: 'string' }, 'retention-days': { type: 'string' }, 'max-storage-mib': { type: 'string' },
10
+ 'worker-storage-mib': { type: 'string' }, 'min-free-gib': { type: 'string' }, 'resume-extra-gib': { type: 'string' }, 'storage-estimate-factor': { type: 'string' },
10
11
  'allowed-host': { type: 'string', multiple: true }, 'allowed-origin': { type: 'string', multiple: true },
11
12
  input: { type: 'string' }, output: { type: 'string' }, request: { type: 'string' }, help: { type: 'boolean', short: 'h' },
12
13
  } })
13
14
  const command = positionals[0], env = key => process.env[engine.toUpperCase() + '_' + key]
14
15
  if (values.help || !command) {
15
- console.log(`zelos-${engine} <serve|mcp|doctor|setup|run>\n\nserve: REST document service; --host --port --data-dir\nmcp: --transport stdio|http --backend local|remote --url URL\n --input-root PATH (repeatable, stdio) --output-root PATH\n --allowed-host HOST:PORT --allowed-origin ORIGIN (HTTP)\nrun: --input FILE --output NEW_DIRECTORY --request REQUEST_JSON\n\nCredentials: ${engine.toUpperCase()}_TOKEN for HTTP, ${engine.toUpperCase()}_BACKEND_TOKEN for remote engines.\nData/config: --data-dir, --python (CAD), --resources (CAD), --concurrency 1..4,\n--timeout-ms, --retention-days, --max-storage-mib; matching ${engine.toUpperCase()}_* environment variables supported.`)
16
+ console.log(`zelos-${engine} <serve|mcp|doctor|setup|run>\n\nserve: REST document service; --host --port --data-dir\nmcp: --transport stdio|http --backend local|remote --url URL\n --input-root PATH (repeatable, stdio) --output-root PATH\n --allowed-host HOST:PORT --allowed-origin ORIGIN (HTTP)\nrun: --input FILE --output NEW_DIRECTORY --request REQUEST_JSON\n\nCredentials: ${engine.toUpperCase()}_TOKEN for HTTP, ${engine.toUpperCase()}_BACKEND_TOKEN for remote engines.\nData/config: --data-dir, --python (CAD), --resources (CAD), --concurrency 1..4,\n--timeout-ms, --retention-days, --max-storage-mib.\nCAD storage: --worker-storage-mib, --min-free-gib, --resume-extra-gib,\n--storage-estimate-factor; matching ${engine.toUpperCase()}_* environment variables supported.`)
16
17
  return
17
18
  }
18
19
  if (positionals.length !== 1) throw new Error('Expected one subcommand')
@@ -22,6 +23,10 @@ export async function runDocumentCommand({ engine, startMcp, serve, doctor, setu
22
23
  if (!Number.isFinite(parsed) || parsed < min || parsed > max || (integer && !Number.isInteger(parsed))) throw new Error(name + ' is outside its supported range')
23
24
  return parsed
24
25
  }
26
+ const amount = (name, value, unit, min, max) => {
27
+ const parsed = number(name, value, min, max)
28
+ return parsed === undefined ? undefined : Math.ceil(parsed * unit)
29
+ }
25
30
  const options = {
26
31
  transport: values.transport, backend: values.backend, url: values.url || env('BACKEND_URL'), backendToken: env('BACKEND_TOKEN'),
27
32
  data: values['data-dir'] || env('DATA_DIR'), python: values.python || env('PYTHON'), resources: values.resources || env('RESOURCES'),
@@ -30,8 +35,12 @@ export async function runDocumentCommand({ engine, startMcp, serve, doctor, setu
30
35
  allowedHosts: values['allowed-host'], allowedOrigins: values['allowed-origin'],
31
36
  concurrency: number('concurrency', values.concurrency || env('CONCURRENCY') || '1', 1, 4, true),
32
37
  timeoutMs: number('timeout-ms', values['timeout-ms'] || env('TIMEOUT_MS'), 1, 86400000, true),
33
- retentionMs: number('retention-days', values['retention-days'] || env('RETENTION_DAYS'), 0.001, 36500) * 86400000 || undefined,
34
- maxStorageBytes: number('max-storage-mib', values['max-storage-mib'] || env('MAX_STORAGE_MIB'), 0, 1e9) * 1024 ** 2 || undefined,
38
+ retentionMs: amount('retention-days', values['retention-days'] || env('RETENTION_DAYS'), 86400000, 0.001, 36500),
39
+ maxStorageBytes: amount('max-storage-mib', values['max-storage-mib'] || env('MAX_STORAGE_MIB'), 1024 ** 2, 0, 1e9),
40
+ workerStorageBytes: amount('worker-storage-mib', values['worker-storage-mib'] || env('WORKER_STORAGE_MIB'), 1024 ** 2, 0.001, 1e9),
41
+ minimumFreeBytes: amount('min-free-gib', values['min-free-gib'], 1024 ** 3, 0, 1e6),
42
+ resumeExtraBytes: amount('resume-extra-gib', values['resume-extra-gib'], 1024 ** 3, 0, 1e6),
43
+ storageEstimateFactor: number('storage-estimate-factor', values['storage-estimate-factor'], 1, 100),
35
44
  }
36
45
  if (!['local', 'remote'].includes(options.backend) || !['stdio', 'http'].includes(options.transport)) throw new Error('Use backend local|remote and transport stdio|http')
37
46
  if (command === 'doctor') { const result = await doctor(options); console.log(JSON.stringify(result)); if (!result.ready) process.exitCode = 1; return }
@@ -39,6 +48,8 @@ export async function runDocumentCommand({ engine, startMcp, serve, doctor, setu
39
48
  if (command === 'run') { await run(values); return }
40
49
  if (!['serve', 'mcp'].includes(command)) throw new Error('Unknown command: ' + command)
41
50
  if (command === 'serve' && options.backend === 'remote') throw new Error('serve owns a local engine; use mcp --backend remote for a gateway')
51
+ options.port ??= defaultPorts?.[command];
52
+ const managed = process.connected === true
42
53
  const active = command === 'serve' ? await serve(options) : await startMcp(options)
43
54
  if (active.address) console.error(`zelos-${engine} ${command}: ${active.address}`)
44
55
  let closing
@@ -46,11 +57,18 @@ export async function runDocumentCommand({ engine, startMcp, serve, doctor, setu
46
57
  if (parentTimer) clearInterval(parentTimer)
47
58
  process.stdin.pause()
48
59
  process.removeListener('SIGINT', close); process.removeListener('SIGTERM', close)
60
+ process.removeListener('message', shutdown); process.removeListener('disconnect', close)
61
+ if (process.connected) process.disconnect()
49
62
  })
63
+ const shutdown = message => { if (message?.type === 'shutdown') void close() }
50
64
  const stdio = command === 'mcp' && options.transport === 'stdio'
51
65
  const parent = process.ppid
52
66
  const parentTimer = stdio ? setInterval(() => { try { process.kill(parent, 0) } catch { void close() } }, 1000) : undefined
53
67
  parentTimer?.unref()
54
68
  process.once('SIGINT', close); process.once('SIGTERM', close)
69
+ if (managed) {
70
+ process.on('message', shutdown); process.once('disconnect', close)
71
+ if (!process.connected) await close()
72
+ }
55
73
  if (stdio) { process.stdin.once('end', close); if (process.stdin.readableEnded) await close() }
56
74
  }
@@ -0,0 +1,33 @@
1
+ import {existsSync,realpathSync,lstatSync} from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ export function containedPath(root: string, relative: string): string {
5
+ // Task reports can originate on Windows and resume in a Linux container.
6
+ // Interpret both separators consistently before absolute/containment checks.
7
+ relative = relative.replaceAll('\\', '/')
8
+ if (!relative || relative.includes('\0') || relative.includes(':') || path.isAbsolute(relative))
9
+ throw new Error('路径必须相对于任务目录')
10
+ const target = path.resolve(root, relative)
11
+ const rel = path.relative(path.resolve(root), target)
12
+ if (!rel || rel.startsWith('..' + path.sep) || rel === '..' || path.isAbsolute(rel))
13
+ throw new Error('路径超出任务目录')
14
+ // Resolve every existing ancestor: junctions/symlinks must never bypass containment.
15
+ let ancestor = target
16
+ while (!existsSync(ancestor)) ancestor = path.dirname(ancestor)
17
+ const realRoot = realpathSync(root)
18
+ const realAncestor = realpathSync(ancestor)
19
+ const resolved = path.relative(realRoot, realAncestor)
20
+ if (resolved === '..' || resolved.startsWith('..' + path.sep) || path.isAbsolute(resolved))
21
+ throw new Error('不允许链接到任务目录之外')
22
+ if (existsSync(target) && lstatSync(target).isSymbolicLink())
23
+ throw new Error('不接受符号链接文件')
24
+ return target
25
+ }
26
+
27
+ /** Relativize native absolute inputs in one namespace; callers still enforce containment. */
28
+ export function relativeInputPath(root: string, file: string): string {
29
+ return path.isAbsolute(file)
30
+ ? path.relative(path.toNamespacedPath(path.resolve(root)), path.toNamespacedPath(file))
31
+ : file
32
+ }
33
+
@@ -4,6 +4,7 @@ export interface McpOptions {
4
4
  backend?: 'local' | 'remote'; transport?: 'stdio' | 'http'; url?: string; backendToken?: string;
5
5
  data?: string; python?: string; resources?: string; inputRoots?: string[]; outputRoot?: string;
6
6
  concurrency?: number; timeoutMs?: number; retentionMs?: number; maxStorageBytes?: number;
7
+ workerStorageBytes?: number; minimumFreeBytes?: number; resumeExtraBytes?: number; storageEstimateFactor?: number;
7
8
  host?: string; port?: number; token?: string; allowedOrigins?: string[]; allowedHosts?: string[];
8
9
  sessionTtlMs?: number; maxSessions?: number;
9
10
  }
@@ -0,0 +1,101 @@
1
+ import { existsSync, realpathSync, statSync, statfsSync } from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ const GiB = 1024 ** 3
5
+ export const capacityPolicy = {
6
+ version: '2026.11.09.1',
7
+ safetyBytes: 5 * GiB,
8
+ resumeExtraBytes: 2 * GiB,
9
+ estimateFactor: 1.2,
10
+ }
11
+ export type CapacityPolicy = typeof capacityPolicy
12
+ export type VolumeSpace = { id: string; path: string; freeBytes: number; totalBytes: number }
13
+ export type CapacityAllocation = {
14
+ key: string
15
+ directory: string
16
+ estimatedBytes: number
17
+ materializedBytes?: number
18
+ }
19
+ export type CapacityVolume = VolumeSpace & {
20
+ estimatedBytes: number
21
+ materializedBytes: number
22
+ remainingBytes: number
23
+ otherReservedBytes: number
24
+ requiredBytes: number
25
+ shortageBytes: number
26
+ }
27
+
28
+ /** Device identity merges directories and mount aliases on the same local volume. */
29
+ export function volumeSpace(directory: string): VolumeSpace {
30
+ let ancestor = path.resolve(directory)
31
+ while (!existsSync(ancestor)) {
32
+ const parent = path.dirname(ancestor)
33
+ if (parent === ancestor) throw new Error('存储卷路径不存在:' + directory)
34
+ ancestor = parent
35
+ }
36
+ ancestor = realpathSync(ancestor)
37
+ const stat = statSync(ancestor, { bigint: true }),
38
+ disk = statfsSync(ancestor, { bigint: true })
39
+ return {
40
+ id: process.platform + ':' + stat.dev,
41
+ path: ancestor,
42
+ freeBytes: Number(disk.bavail * disk.bsize),
43
+ totalBytes: Number(disk.blocks * disk.bsize),
44
+ }
45
+ }
46
+
47
+ /** Pure admission calculation; the caller owns atomic reservations and watermark persistence. */
48
+ export function capacityVolumes(
49
+ allocations: CapacityAllocation[],
50
+ reserved: (id: string) => number,
51
+ paused: (id: string) => boolean,
52
+ probe = volumeSpace,
53
+ policy = capacityPolicy,
54
+ ): CapacityVolume[] {
55
+ if (
56
+ !allocations.length ||
57
+ new Set(allocations.map((item) => item.key)).size !== allocations.length
58
+ )
59
+ throw new Error('容量申请需要唯一的分配项')
60
+ const groups = new Map<string, CapacityVolume>()
61
+ for (const item of allocations) {
62
+ if (
63
+ !Number.isSafeInteger(item.estimatedBytes) ||
64
+ item.estimatedBytes < 0 ||
65
+ !Number.isSafeInteger(item.materializedBytes || 0) ||
66
+ (item.materializedBytes || 0) < 0
67
+ )
68
+ throw new Error('容量估计与已落盘字节需要为非负整数')
69
+ const space = probe(item.directory),
70
+ group = groups.get(space.id) || {
71
+ ...space,
72
+ estimatedBytes: 0,
73
+ materializedBytes: 0,
74
+ remainingBytes: 0,
75
+ otherReservedBytes: 0,
76
+ requiredBytes: 0,
77
+ shortageBytes: 0,
78
+ }
79
+ group.freeBytes = Math.min(group.freeBytes, space.freeBytes)
80
+ const estimated = Math.ceil(item.estimatedBytes * policy.estimateFactor)
81
+ group.estimatedBytes += estimated
82
+ group.materializedBytes += Math.min(estimated, item.materializedBytes || 0)
83
+ groups.set(space.id, group)
84
+ }
85
+ for (const group of groups.values()) {
86
+ group.remainingBytes = group.estimatedBytes - group.materializedBytes
87
+ group.otherReservedBytes = reserved(group.id)
88
+ const wasPaused = paused(group.id)
89
+ group.requiredBytes =
90
+ group.otherReservedBytes +
91
+ group.remainingBytes +
92
+ policy.safetyBytes +
93
+ (wasPaused ? policy.resumeExtraBytes : 0)
94
+ group.shortageBytes = Math.max(0, group.requiredBytes - group.freeBytes)
95
+ if (group.shortageBytes && !wasPaused) {
96
+ group.requiredBytes += policy.resumeExtraBytes
97
+ group.shortageBytes = Math.max(0, group.requiredBytes - group.freeBytes)
98
+ }
99
+ }
100
+ return [...groups.values()]
101
+ }
@@ -0,0 +1,45 @@
1
+ import { canonical, hash, StorageError } from './files.ts'
2
+
3
+ export interface ConsumptionReceipt {
4
+ status: 'succeeded' | 'failed' | 'cancelled' | 'interrupted'
5
+ sourceSha256?: string
6
+ artifacts: { name: string; bytes: number; sha256: string }[]
7
+ }
8
+ export interface Consumption {
9
+ at: string
10
+ sha256: string
11
+ }
12
+ /** Order-independent, complete receipt: missing, extra, duplicate or changed artifacts conflict. */
13
+ export function consumptionHash(raw: unknown): string {
14
+ const value = raw as ConsumptionReceipt
15
+ if (
16
+ !value ||
17
+ !['succeeded', 'failed', 'cancelled', 'interrupted'].includes(value.status) ||
18
+ (value.sourceSha256 !== undefined && !/^[a-f0-9]{64}$/.test(value.sourceSha256)) ||
19
+ !Array.isArray(value.artifacts) ||
20
+ value.artifacts.length > 10000
21
+ )
22
+ throw new StorageError('CONSUMPTION_RECEIPT', '消费回执格式无效')
23
+ const seen = new Set<string>()
24
+ const artifacts = value.artifacts
25
+ .map((artifact) => {
26
+ if (
27
+ !artifact ||
28
+ typeof artifact.name !== 'string' ||
29
+ !/^[^\\/:\x00-\x1f]{1,255}$/.test(artifact.name) ||
30
+ !Number.isSafeInteger(artifact.bytes) ||
31
+ artifact.bytes < 0 ||
32
+ !/^[a-f0-9]{64}$/.test(artifact.sha256) ||
33
+ seen.has(artifact.name)
34
+ )
35
+ throw new StorageError('CONSUMPTION_RECEIPT', '消费回执的成果清单无效')
36
+ seen.add(artifact.name)
37
+ return { name: artifact.name, bytes: artifact.bytes, sha256: artifact.sha256 }
38
+ })
39
+ .sort((a, b) => a.name.localeCompare(b.name))
40
+ return hash(
41
+ JSON.stringify(
42
+ canonical({ status: value.status, sourceSha256: value.sourceSha256, artifacts }),
43
+ ),
44
+ )
45
+ }
@@ -0,0 +1,262 @@
1
+ import {
2
+ createWriteStream,
3
+ mkdirSync,
4
+ readFileSync,
5
+ existsSync,
6
+ lstatSync,
7
+ readdirSync,
8
+ writeFileSync,
9
+ renameSync,
10
+ rmSync,
11
+ } from 'node:fs'
12
+ import { createHash, randomUUID } from 'node:crypto'
13
+ import { Transform, type Readable } from 'node:stream'
14
+ import { pipeline } from 'node:stream/promises'
15
+ import path from 'node:path'
16
+ import {
17
+ atomicJson,
18
+ checkedId,
19
+ fileHash,
20
+ linkImmutable,
21
+ idPattern,
22
+ dataRoot,
23
+ removeJob,
24
+ StorageError,
25
+ } from './files.ts'
26
+ import { DEFAULT_RETENTION_MS } from './retention.ts'
27
+ import { StorageQuota } from './quota.ts'
28
+ import { StagedDirectories } from './staging.ts'
29
+
30
+ export interface StoredDocument {
31
+ id: string
32
+ path: string
33
+ bytes: number
34
+ sha256: string
35
+ fileName: string
36
+ accessedAt: number
37
+ }
38
+ export interface DocumentFormat {
39
+ sourceName: string
40
+ defaultName: string
41
+ fileName: RegExp
42
+ inputBytes: number
43
+ validPrefix?: (prefix: Buffer) => boolean
44
+ }
45
+
46
+ function verifySource(source: StoredDocument) {
47
+ const stat = lstatSync(source.path)
48
+ if (
49
+ stat.isSymbolicLink() ||
50
+ !stat.isFile() ||
51
+ stat.size !== source.bytes ||
52
+ fileHash(source.path) !== source.sha256
53
+ )
54
+ throw new StorageError('DOCUMENT_CHANGED', '源文档内容与登记不一致', 409)
55
+ }
56
+
57
+ /** Store a private writable upload, or share a verified immutable document. */
58
+ export function storeSource(source: Buffer | StoredDocument, target: string, quota: StorageQuota) {
59
+ if (Buffer.isBuffer(source)) {
60
+ quota.require(source.length)
61
+ writeFileSync(target, source, { flag: 'wx', flush: true })
62
+ return 'written' as const
63
+ }
64
+ verifySource(source)
65
+ return linkImmutable(source.path, target, () => quota.require(source.bytes))
66
+ }
67
+
68
+ export class DocumentStore {
69
+ readonly root: string
70
+ readonly storageWarnings: { directory: string; message: string }[] = []
71
+ private timer: ReturnType<typeof setInterval>
72
+ private staging: StagedDirectories
73
+ private contents = new Map<string, Set<string>>()
74
+ constructor(
75
+ private data: string,
76
+ private format: DocumentFormat,
77
+ private retentionMs = DEFAULT_RETENTION_MS,
78
+ maxStorageBytes = 0,
79
+ private quota = new StorageQuota(data, maxStorageBytes),
80
+ ) {
81
+ this.data = dataRoot(data)
82
+ this.root = path.join(this.data, '.documents')
83
+ mkdirSync(this.root, { recursive: true })
84
+ if (lstatSync(this.root).isSymbolicLink())
85
+ throw new StorageError('STORAGE_LINK', '源文档目录包含链接')
86
+ this.staging = new StagedDirectories(
87
+ this.root,
88
+ path.join(this.data, '.staging-documents'),
89
+ 'document.json',
90
+ (id, error) => this.warn(id, error),
91
+ )
92
+ this.staging.cleanup()
93
+ for (const id of readdirSync(this.root).filter((id) => idPattern.test(id))) {
94
+ try {
95
+ this.remember(this.read(id))
96
+ } catch (error) {
97
+ this.warn(id, error)
98
+ }
99
+ }
100
+ this.timer = setInterval(() => this.cleanup(), 60000)
101
+ this.timer.unref()
102
+ }
103
+ close() {
104
+ clearInterval(this.timer)
105
+ }
106
+ private key(document: Pick<StoredDocument, 'sha256' | 'bytes'>) {
107
+ return document.sha256 + ':' + document.bytes
108
+ }
109
+ private remember(document: StoredDocument) {
110
+ const key = this.key(document),
111
+ ids = this.contents.get(key) ?? new Set<string>()
112
+ ids.add(document.id)
113
+ this.contents.set(key, ids)
114
+ }
115
+ private shared(document: StoredDocument) {
116
+ const key = this.key(document),
117
+ ids = this.contents.get(key)
118
+ for (const id of ids ?? []) {
119
+ try {
120
+ const stored = this.read(id)
121
+ if (this.key(stored) !== key)
122
+ throw new StorageError('DOCUMENT_CHANGED', '共享源文档内容与登记不一致', 409)
123
+ verifySource(stored)
124
+ return stored
125
+ } catch (error) {
126
+ ids!.delete(id)
127
+ this.warn(id, error)
128
+ }
129
+ }
130
+ if (!ids?.size) this.contents.delete(key)
131
+ }
132
+ private read(id: string): StoredDocument {
133
+ const folder = path.join(this.root, checkedId(id)),
134
+ file = path.join(folder, this.format.sourceName),
135
+ receipt = path.join(folder, 'document.json')
136
+ if (!existsSync(receipt))
137
+ throw new StorageError('DOCUMENT_EXPIRED', '源文档已过期,请重新上传', 410)
138
+ if (
139
+ [folder, file, receipt].some((p) => lstatSync(p).isSymbolicLink()) ||
140
+ !lstatSync(file).isFile()
141
+ )
142
+ throw new StorageError('STORAGE_LINK', '源文档路径包含链接')
143
+ const stored = JSON.parse(readFileSync(receipt, 'utf8')) as StoredDocument
144
+ if (
145
+ stored.id !== id ||
146
+ stored.bytes !== lstatSync(file).size ||
147
+ !/^[a-f0-9]{64}$/.test(stored.sha256)
148
+ )
149
+ throw new StorageError('DOCUMENT_CHANGED', '源文档登记不一致')
150
+ stored.path = file
151
+ return stored
152
+ }
153
+ get(id: string): StoredDocument {
154
+ const stored = this.read(id)
155
+ stored.accessedAt = Date.now()
156
+ atomicJson(path.join(this.root, id, 'document.json'), stored)
157
+ return stored
158
+ }
159
+ async upload(stream: Readable, fileName = this.format.defaultName) {
160
+ if (!this.format.fileName.test(fileName))
161
+ throw new StorageError('INPUT_NAME', '请提供支持格式的源文件名')
162
+ const id = randomUUID(),
163
+ folder = path.join(this.root, id),
164
+ file = path.join(folder, this.format.sourceName)
165
+ const stage = this.staging.begin(id),
166
+ reservation = this.quota.upload(file)
167
+ let bytes = 0,
168
+ prefix = Buffer.alloc(0)
169
+ const digest = createHash('sha256')
170
+ const inputBytes = this.format.inputBytes
171
+ const counter = new Transform({
172
+ transform(chunk: Buffer, _encoding, callback) {
173
+ bytes += chunk.length
174
+ if (bytes > inputBytes)
175
+ return callback(new StorageError('INPUT_SIZE', '源文件超过单文件大小上限', 413))
176
+ try {
177
+ reservation.ensure(bytes)
178
+ } catch (error) {
179
+ return callback(error as Error)
180
+ }
181
+ if (prefix.length < 1024)
182
+ prefix = Buffer.concat([prefix, chunk.subarray(0, 1024 - prefix.length)])
183
+ digest.update(chunk)
184
+ callback(null, chunk)
185
+ },
186
+ })
187
+ try {
188
+ await pipeline(stream, counter, createWriteStream(file, { flags: 'wx', flush: true }))
189
+ if (!bytes || (this.format.validPrefix && !this.format.validPrefix(prefix)))
190
+ throw new StorageError('INPUT_FORMAT', '请选择有效的源文件')
191
+ const stored: StoredDocument = {
192
+ id,
193
+ path: file,
194
+ bytes,
195
+ sha256: digest.digest('hex'),
196
+ fileName,
197
+ accessedAt: Date.now(),
198
+ }
199
+ reservation.release()
200
+ const shared = this.shared(stored)
201
+ if (shared) {
202
+ // Keep the independently verified upload until the shared/copy target
203
+ // exists. StagedDirectories owns both paths until the receipt commits.
204
+ const uploaded = path.join(folder, 'upload.part')
205
+ renameSync(file, uploaded)
206
+ linkImmutable(shared.path, file, () => this.quota.require(shared.bytes))
207
+ rmSync(uploaded)
208
+ }
209
+ this.quota.require(Buffer.byteLength(JSON.stringify(stored, null, 2) + '\n'))
210
+ atomicJson(path.join(folder, 'document.json'), stored)
211
+ stage.commit()
212
+ this.remember(stored)
213
+ return stored
214
+ } finally {
215
+ reservation.release()
216
+ stage.close()
217
+ }
218
+ }
219
+ cleanup(now = Date.now()) {
220
+ this.staging.cleanup()
221
+ let entries: string[]
222
+ try {
223
+ entries = readdirSync(this.root)
224
+ } catch (error) {
225
+ this.warn('.', error)
226
+ return
227
+ }
228
+ for (const id of entries) {
229
+ if (!idPattern.test(id)) continue
230
+ const folder = path.join(this.root, id),
231
+ receipt = path.join(folder, 'document.json')
232
+ try {
233
+ if (
234
+ lstatSync(folder).isSymbolicLink() ||
235
+ !existsSync(receipt) ||
236
+ lstatSync(receipt).isSymbolicLink()
237
+ )
238
+ continue
239
+ const value = JSON.parse(readFileSync(receipt, 'utf8'))
240
+ if (
241
+ value.id === id &&
242
+ Number.isFinite(value.accessedAt) &&
243
+ now - value.accessedAt > this.retentionMs &&
244
+ path.dirname(folder) === this.root
245
+ ) {
246
+ removeJob(this.root, id)
247
+ const key = this.key(value),
248
+ ids = this.contents.get(key)
249
+ ids?.delete(id)
250
+ if (!ids?.size) this.contents.delete(key)
251
+ }
252
+ } catch (error) {
253
+ this.warn(id, error)
254
+ }
255
+ }
256
+ }
257
+ private warn(directory: string, error: unknown) {
258
+ const message = String(error)
259
+ if (!this.storageWarnings.some((w) => w.directory === directory && w.message === message))
260
+ this.storageWarnings.push({ directory, message })
261
+ }
262
+ }
@@ -0,0 +1,62 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { lstatSync } from 'node:fs'
3
+ import { open } from 'node:fs/promises'
4
+ import path from 'node:path'
5
+ import { StorageError } from './files.ts'
6
+
7
+ export class DownloadLeases {
8
+ private counts = new Map<string, number>()
9
+ has(id: string) {
10
+ return this.counts.has(id)
11
+ }
12
+ hold(id: string) {
13
+ this.counts.set(id, (this.counts.get(id) ?? 0) + 1)
14
+ let released = false
15
+ return () => {
16
+ if (released) return
17
+ released = true
18
+ const remaining = this.counts.get(id)! - 1
19
+ if (remaining) this.counts.set(id, remaining)
20
+ else this.counts.delete(id)
21
+ }
22
+ }
23
+ }
24
+
25
+ /** The lease spans hash verification and streaming; both use the same open file. */
26
+ export async function artifactStream(
27
+ folder: string,
28
+ name: string,
29
+ receipt: { bytes: number; sha256: string },
30
+ release: () => void,
31
+ ) {
32
+ let handle: Awaited<ReturnType<typeof open>> | undefined
33
+ try {
34
+ const file = path.resolve(folder, name)
35
+ if (
36
+ path.dirname(file) !== path.resolve(folder) ||
37
+ lstatSync(folder).isSymbolicLink() ||
38
+ lstatSync(file).isSymbolicLink() ||
39
+ !lstatSync(file).isFile()
40
+ )
41
+ throw new StorageError('ARTIFACT_CHANGED', '成果路径发生变化')
42
+ handle = await open(file, 'r')
43
+ const digest = createHash('sha256')
44
+ let size = 0
45
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
46
+ size += chunk.length
47
+ digest.update(chunk)
48
+ }
49
+ if (size !== receipt.bytes || digest.digest('hex') !== receipt.sha256)
50
+ throw new StorageError('ARTIFACT_CHANGED', '成果与登记哈希不一致')
51
+ const stream = handle.createReadStream({ start: 0, autoClose: true })
52
+ stream.once('close', release)
53
+ return stream
54
+ } catch (error) {
55
+ try {
56
+ await handle?.close()
57
+ } finally {
58
+ release()
59
+ }
60
+ throw error
61
+ }
62
+ }