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
@@ -4,14 +4,20 @@ import { readFileSync, lstatSync } from 'node:fs'
4
4
  import type { Readable } from 'node:stream'
5
5
  import path from 'node:path'
6
6
  import { CadError, capabilities } from '../contracts.ts'
7
- import { hashFile } from '../io.ts'
7
+ import { sha256 } from '../io.ts'
8
8
  import { decodeBundle } from '../bundle.ts'
9
- import { fallbackArtifacts, drawingArtifacts, type ArtifactReceipt } from '../dwg-fallback.ts'
9
+ import { fallbackArtifacts, isDrawingArtifact, type ArtifactReceipt } from '../dwg-fallback.ts'
10
10
  import { JobQueue, type RuntimeOptions } from './jobs.ts'
11
11
  import { DocumentStore } from './documents.ts'
12
12
  import { checkReadiness } from './readiness.ts'
13
+ import { StorageQuota } from '../../shared/service-storage/src/quota.ts'
14
+ import { artifactStream } from '../../shared/service-storage/src/downloads.ts'
15
+ import { recadStorageOptions } from './storage-policy.ts'
16
+ import { getRecadBuildInfo } from '../build-info.ts'
13
17
 
14
18
  export * from '../runner.ts'
19
+ export { runManagedWorker, withRecadStorage, type ManagedStorageOptions } from './managed-worker.ts'
20
+ export { recadStorageOptions, type StorageSettings } from './storage-policy.ts'
15
21
  export type { RuntimeOptions, Job, JobStatus } from './jobs.ts'
16
22
  export type { StoredDocument } from './documents.ts'
17
23
  export interface Submission {
@@ -28,10 +34,12 @@ export class RecadRuntime {
28
34
  private closing?: Promise<void>
29
35
  private readonly releaseLock: () => void
30
36
  private lockFailure?: Error
37
+ private readonly artifactRequests = new Set<Promise<unknown>>()
38
+ private readonly downloads = new Set<Readable>()
31
39
 
32
40
  constructor(private readonly options: RuntimeOptions) {
33
41
  mkdirSync(options.data, { recursive: true })
34
- options = { ...options, data: realpathSync(options.data) }
42
+ options = { ...options, ...recadStorageOptions(options), data: realpathSync(options.data) }
35
43
  this.options = options
36
44
  try {
37
45
  this.releaseLock = lockSync(options.data, {
@@ -55,12 +63,14 @@ export class RecadRuntime {
55
63
  }
56
64
  let documents: DocumentStore | undefined
57
65
  try {
66
+ const quota = new StorageQuota(options.data, options.maxStorageBytes, options.storageCapacity)
58
67
  this.documents = documents = new DocumentStore(
59
68
  options.data,
60
69
  options.retentionMs,
61
70
  options.maxStorageBytes,
71
+ quota,
62
72
  )
63
- this.queue = new JobQueue(options)
73
+ this.queue = new JobQueue(options, quota)
64
74
  } catch (error) {
65
75
  void documents?.close()
66
76
  this.releaseLock()
@@ -92,8 +102,17 @@ export class RecadRuntime {
92
102
  const result = await this.readiness()
93
103
  return {
94
104
  ...capabilities,
105
+ build: getRecadBuildInfo(),
95
106
  pngRuntimeConfigured: result.printRuntimeReady,
96
107
  printRuntimeConfigured: result.printRuntimeReady,
108
+ consumptionReceipts: 1,
109
+ storage: {
110
+ version: 1,
111
+ retentionMs: this.options.retentionMs,
112
+ maxStorageBytes: this.options.maxStorageBytes ?? 0,
113
+ workerStorageBytes: this.options.workerStorageBytes,
114
+ policy: this.options.storageCapacity?.policy,
115
+ },
97
116
  }
98
117
  }
99
118
  uploadDocument(stream: Readable, fileName?: string) {
@@ -143,46 +162,81 @@ export class RecadRuntime {
143
162
  return this.queue.cancelOwner(id)
144
163
  }
145
164
 
146
- artifact(id: string, name: string): ArtifactReceipt & { buffer: Buffer; contentType: string } {
165
+ consume(id: string, receipt: unknown) {
166
+ this.assertOpen()
167
+ return this.queue.consume(id, receipt)
168
+ }
169
+
170
+ private artifactEntry(id: string, name: string) {
147
171
  this.assertOpen()
148
172
  const job = this.queue.get(id)
149
173
  if (!job || !['succeeded', 'failed', 'cancelled', 'interrupted'].includes(job.status))
150
174
  throw new CadError('NOT_FOUND', '任务成果尚未就绪')
151
175
  const diagnostic = fallbackArtifacts.includes(name)
152
- if (!diagnostic && (job.status !== 'succeeded' || !drawingArtifacts.includes(name)))
176
+ if (!diagnostic && (job.status !== 'succeeded' || !isDrawingArtifact(name)))
153
177
  throw new CadError('NOT_FOUND', '成果不存在')
154
178
  const artifact = (diagnostic ? job.diagnostics : job.result?.artifacts)?.find(
155
179
  (a: any) => a.name === name,
156
180
  )
157
181
  if (!artifact) throw new CadError('NOT_FOUND', '成果不存在')
158
- const file = path.join(this.queue.directory(id), name)
182
+ const directory = this.queue.directory(id)
183
+ const contentType = name.endsWith('.pdf') ? 'application/pdf'
184
+ : name.endsWith('.png') ? 'image/png'
185
+ : name.endsWith('.dxf') ? 'application/dxf'
186
+ : name.endsWith('.ttf') ? 'font/ttf'
187
+ : name.endsWith('.otf') ? 'font/otf'
188
+ : name.endsWith('.shx') ? 'application/octet-stream' : 'application/json'
189
+ return { artifact: artifact as ArtifactReceipt, directory, contentType }
190
+ }
191
+
192
+ streamArtifact(id: string, name: string) {
193
+ const { artifact, directory, contentType } = this.artifactEntry(id, name)
194
+ const operation = (async () => {
195
+ const stream = await artifactStream(directory, name, artifact, this.queue.holdDownload(id))
196
+ if (this.closing) {
197
+ await new Promise<void>(resolve => { stream.once('close', resolve); stream.destroy() })
198
+ throw new CadError('SERVICE_CLOSING', 'CAD 运行实例正在停止')
199
+ }
200
+ this.downloads.add(stream)
201
+ stream.once('close', () => this.downloads.delete(stream))
202
+ return { ...artifact, contentType, stream }
203
+ })().finally(() => this.artifactRequests.delete(operation))
204
+ this.artifactRequests.add(operation)
205
+ return operation
206
+ }
207
+
208
+ artifact(id: string, name: string): ArtifactReceipt & { buffer: Buffer; contentType: string } {
209
+ const { artifact, directory, contentType } = this.artifactEntry(id, name)
210
+ const file = path.join(directory, name)
159
211
  const stat = lstatSync(file)
160
212
  if (
161
213
  !stat.isFile() ||
162
214
  stat.isSymbolicLink() ||
163
- stat.size !== artifact.bytes ||
164
- hashFile(file) !== artifact.sha256
215
+ stat.size !== artifact.bytes
165
216
  )
166
217
  throw new CadError('ARTIFACT_CHANGED', '成果与本次核验哈希不一致')
218
+ const buffer = readFileSync(file)
219
+ if (sha256(buffer) !== artifact.sha256)
220
+ throw new CadError('ARTIFACT_CHANGED', '成果与本次核验哈希不一致')
167
221
  return {
168
222
  ...artifact,
169
- buffer: readFileSync(file),
170
- contentType: name.endsWith('.pdf')
171
- ? 'application/pdf'
172
- : name.endsWith('.png')
173
- ? 'image/png'
174
- : name.endsWith('.dxf')
175
- ? 'application/dxf'
176
- : 'application/json',
223
+ buffer,
224
+ contentType,
177
225
  }
178
226
  }
179
227
  close() {
180
228
  if (!this.closing) {
181
229
  this.closing = (async () => {
230
+ const closingDownloads = [...this.downloads].map(stream => new Promise<void>(resolve => {
231
+ if (stream.closed) resolve()
232
+ else { stream.once('close', resolve); stream.destroy() }
233
+ }))
182
234
  const results = await Promise.allSettled([
183
235
  this.documents.close(),
184
236
  this.queue.close(),
185
237
  this.pending,
238
+ Promise.allSettled(this.artifactRequests),
239
+ ...closingDownloads,
186
240
  ])
187
241
 
188
242
  try {
@@ -1,31 +1,21 @@
1
- import { randomUUID } from 'node:crypto'
2
- import {
3
- mkdirSync,
4
- readFileSync,
5
- readdirSync,
6
- existsSync,
7
- writeFileSync,
8
- lstatSync,
9
- copyFileSync,
10
- } from 'node:fs'
1
+ import { JobRetention } from '../../shared/service-storage/src/retention.ts'
2
+ import { StorageQuota, type ServiceCapacityOptions } from '../../shared/service-storage/src/quota.ts'
3
+ import { StagedDirectories } from '../../shared/service-storage/src/staging.ts'
4
+ import { storeSource } from '../../shared/service-storage/src/documents.ts'
5
+ import { consumptionHash, type Consumption, type ConsumptionReceipt } from '../../shared/service-storage/src/consumption.ts'
6
+ import { randomUUID, createHash } from 'node:crypto'
7
+ import { mkdirSync, readFileSync, readdirSync, existsSync, writeFileSync, lstatSync } from 'node:fs'
11
8
  import type { StoredDocument } from './documents.ts'
12
9
  import path from 'node:path'
13
10
  import { CadError, requestSchema, type CadRequest } from '../contracts.ts'
14
- import { writeJson, hashFile, sha256 } from '../io.ts'
11
+ import { writeJson, hashFile } from '../io.ts'
15
12
  import { runWorker } from '../runner.ts'
16
13
  import { CAD_INPUT_LIMITS } from 'zelos-recad/protocol'
17
14
  import type { FallbackReceipt, ArtifactReceipt } from '../dwg-fallback.ts'
18
15
  import type { ResourceBundle } from '../bundle.ts'
19
16
  import { serverResourceFingerprint } from '../base-fonts.ts'
20
17
  import type { ServerFonts } from '../font-options.ts'
21
- import {
22
- atomicJson,
23
- canonical,
24
- checkedId,
25
- directoryBytes,
26
- jobIdPattern,
27
- removeJobDirectory,
28
- } from './storage.ts'
18
+ import { atomicJson, dataRoot, canonical, checkedId, jobIdPattern } from './storage.ts'
29
19
 
30
20
  export type JobStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled' | 'interrupted'
31
21
  export interface Job {
@@ -42,6 +32,9 @@ export interface Job {
42
32
  fingerprint?: string
43
33
  owner?: string
44
34
  serverResourceFingerprint?: string
35
+ sourceSha256?: string
36
+ consumed?: Consumption
37
+ consumedAt?: string
45
38
  }
46
39
  export interface RuntimeOptions {
47
40
  /** Internal process boundary; omitted by the standalone service. */
@@ -52,10 +45,13 @@ export interface RuntimeOptions {
52
45
  baseFonts?: boolean
53
46
  missingText?: 'strict' | ServerFonts['missingText']
54
47
  python?: string
48
+ token?: string
55
49
  concurrency?: number
56
50
  timeoutMs?: number
57
51
  retentionMs?: number
58
52
  maxStorageBytes?: number
53
+ workerStorageBytes?: number
54
+ storageCapacity?: ServiceCapacityOptions
59
55
  cleanupIntervalMs?: number
60
56
  downloadGraceMs?: number
61
57
  }
@@ -64,14 +60,38 @@ export function sourceTextPolicy(options: Pick<RuntimeOptions, 'baseFonts' | 'mi
64
60
  ? undefined
65
61
  : (options.missingText ?? (options.baseFonts === false ? undefined : 'best-effort'))
66
62
  }
63
+ function jobConsumption(job: Job): ConsumptionReceipt {
64
+ return {
65
+ status: job.status as ConsumptionReceipt['status'],
66
+ sourceSha256: job.sourceSha256 ?? job.result?.sourceSha256,
67
+ artifacts: [...new Map<string, ArtifactReceipt>(
68
+ [...(job.result?.artifacts ?? []), ...(job.diagnostics ?? [])].map(a => [a.name, a]),
69
+ ).values()],
70
+ }
71
+ }
67
72
  export class JobQueue {
73
+ readonly quota: StorageQuota
74
+ private staging: StagedDirectories
68
75
  private jobs = new Map<string, Job>()
69
76
  private running = new Map<string, { controller: AbortController; promise: Promise<void> }>()
77
+ private retention: JobRetention<Job>
70
78
  private closing = false
71
79
  private cleanupTimer?: ReturnType<typeof setInterval>
72
80
  readonly storageWarnings: { directory: string; message: string }[] = []
73
- constructor(private options: RuntimeOptions) {
74
- mkdirSync(options.data, { recursive: true })
81
+ constructor(private options: RuntimeOptions, quota?: StorageQuota) {
82
+ options.data = dataRoot(options.data)
83
+ this.quota = quota ?? new StorageQuota(options.data, options.maxStorageBytes, options.storageCapacity)
84
+ this.staging = new StagedDirectories(
85
+ options.data,
86
+ path.join(options.data, '.staging-jobs'),
87
+ 'job.json',
88
+ (directory, error) => {
89
+ const message = String(error)
90
+ if (!this.storageWarnings.some((w) => w.directory === directory && w.message === message))
91
+ this.storageWarnings.push({ directory, message })
92
+ },
93
+ )
94
+ this.staging.cleanup()
75
95
  for (const name of ['.retired', '.cancelled', '.owners']) {
76
96
  const directory = path.join(options.data, name)
77
97
  mkdirSync(directory, { recursive: true })
@@ -87,6 +107,7 @@ export class JobQueue {
87
107
  })
88
108
  continue
89
109
  }
110
+ if (existsSync(this.marker('.retired', directory.name))) continue
90
111
  const file = path.join(options.data, directory.name, 'job.json')
91
112
  if (!existsSync(file)) {
92
113
  this.storageWarnings.push({
@@ -113,14 +134,6 @@ export class JobQueue {
113
134
  this.storageWarnings.push({ directory: directory.name, message: String(error) })
114
135
  continue
115
136
  }
116
- if (existsSync(this.marker('.retired', job.id))) {
117
- try {
118
- removeJobDirectory(options.data, job.id)
119
- } catch (error) {
120
- this.storageWarnings.push({ directory: job.id, message: String(error) })
121
- }
122
- continue
123
- }
124
137
  if (['queued', 'running'].includes(job.status)) {
125
138
  job.status = 'interrupted'
126
139
  job.error = { code: 'SERVICE_RESTARTED', message: '服务重启中断了任务,请重新提交' }
@@ -142,13 +155,39 @@ export class JobQueue {
142
155
  }
143
156
  atomicJson(file, job)
144
157
  }
158
+ if (!job.consumed && job.consumedAt && job.status === 'succeeded' && Number.isFinite(Date.parse(job.consumedAt)))
159
+ job.consumed = { at: job.consumedAt, sha256: consumptionHash(jobConsumption(job)) }
145
160
  this.jobs.set(job.id, job)
146
161
  }
162
+ this.retention = new JobRetention({
163
+ data: options.data,
164
+ options,
165
+ jobs: this.jobs,
166
+ running: (id) => this.running.has(id),
167
+ consumption: jobConsumption,
168
+ receipt: (job, now) => ({
169
+ id: job.id,
170
+ owner: job.owner,
171
+ fingerprint: job.fingerprint,
172
+ status: job.status,
173
+ endedAt: job.endedAt,
174
+ cleanedAt: new Date(now).toISOString(),
175
+ sourceSha256: job.result?.sourceSha256,
176
+ error: job.error,
177
+ }),
178
+ warn: (directory, error) => {
179
+ const message = String(error)
180
+ if (!this.storageWarnings.some((w) => w.directory === directory && w.message === message))
181
+ this.storageWarnings.push({ directory, message })
182
+ },
183
+ temporaryWorkspaces: (job) =>
184
+ ['', 'fallback-convert', 'fallback-read'].map((name) =>
185
+ path.join(options.data, job.id, name),
186
+ ),
187
+ })
147
188
  this.cleanup()
148
- if (options.retentionMs || options.maxStorageBytes) {
149
- this.cleanupTimer = setInterval(() => this.cleanup(), options.cleanupIntervalMs ?? 60000)
150
- this.cleanupTimer.unref()
151
- }
189
+ this.cleanupTimer = setInterval(() => this.cleanup(), options.cleanupIntervalMs ?? 60000)
190
+ this.cleanupTimer.unref()
152
191
  }
153
192
  private marker(kind: string, id: string) {
154
193
  return path.join(this.options.data, kind, checkedId(id) + '.json')
@@ -187,24 +226,31 @@ export class JobQueue {
187
226
  bundled: this.options.baseFonts !== false,
188
227
  missingText: sourceTextPolicy(this.options),
189
228
  })
190
- const fingerprint = sha256(
191
- JSON.stringify(
192
- canonical({
193
- fileName,
194
- source: Buffer.isBuffer(bytes) ? sha256(bytes) : bytes.sha256,
195
- request,
196
- owner,
197
- resources: resources
198
- ? {
199
- manifest: resources.manifest,
200
- files: [...resources.files].map(([name, data]) => [name, sha256(data)]).sort(),
201
- }
202
- : {
203
- serverResourceFingerprint: serverFingerprint,
204
- },
205
- }),
206
- ),
207
- )
229
+ const sourceSha256 = Buffer.isBuffer(bytes)
230
+ ? createHash('sha256').update(bytes).digest('hex')
231
+ : bytes.sha256
232
+ const fingerprint = createHash('sha256')
233
+ .update(
234
+ JSON.stringify(
235
+ canonical({
236
+ fileName,
237
+ source: sourceSha256,
238
+ request,
239
+ owner,
240
+ resources: resources
241
+ ? {
242
+ manifest: resources.manifest,
243
+ files: [...resources.files]
244
+ .map(([name, data]) => [name, createHash('sha256').update(data).digest('hex')])
245
+ .sort(),
246
+ }
247
+ : {
248
+ serverResourceFingerprint: serverFingerprint,
249
+ },
250
+ }),
251
+ ),
252
+ )
253
+ .digest('hex')
208
254
  const old = this.get(id)
209
255
  if (old) {
210
256
  if (old.fingerprint !== fingerprint)
@@ -219,50 +265,49 @@ export class JobQueue {
219
265
  if ([...this.jobs.values()].filter((j) => j.status === 'queued').length >= 20)
220
266
  throw new CadError('QUEUE_FULL', '待处理任务已满')
221
267
  this.cleanup()
222
- if (
223
- this.options.maxStorageBytes &&
224
- this.storageBytes() +
225
- byteLength +
226
- [...(resources?.files.values() ?? [])].reduce((sum, b) => sum + b.length, 0) >
227
- this.options.maxStorageBytes
228
- )
229
- throw new CadError(
230
- 'STORAGE_FULL',
231
- 'CAD 服务存储容量不足,活跃任务和下载保护期成果不会自动删除',
232
- )
233
268
  if (existsSync(directory))
234
269
  throw new CadError(
235
270
  'JOB_STORAGE_CONFLICT',
236
271
  '任务目录已存在但没有有效提交记录,请检查服务存储诊断',
237
272
  )
238
- mkdirSync(directory)
239
- if (resources) {
240
- const resourceRoot = path.join(directory, 'resources')
241
- mkdirSync(resourceRoot)
242
- for (const [name, bytes] of resources.files) {
243
- const target = path.join(resourceRoot, name)
244
- mkdirSync(path.dirname(target), { recursive: true })
245
- writeFileSync(target, bytes, { flag: 'wx' })
273
+ const stage = this.staging.begin(id)
274
+ try {
275
+ if (resources) {
276
+ this.quota.require(
277
+ [...resources.files.values()].reduce((sum, b) => sum + b.length, 0) +
278
+ Buffer.byteLength(JSON.stringify(resources.manifest, null, 2) + '\n'),
279
+ )
280
+ const resourceRoot = path.join(directory, 'resources')
281
+ mkdirSync(resourceRoot)
282
+ for (const [name, bytes] of resources.files) {
283
+ const target = path.join(resourceRoot, name)
284
+ mkdirSync(path.dirname(target), { recursive: true })
285
+ writeFileSync(target, bytes, { flag: 'wx', flush: true })
286
+ }
287
+ writeJson(path.join(resourceRoot, 'manifest.json'), resources.manifest)
246
288
  }
247
- writeJson(path.join(resourceRoot, 'manifest.json'), resources.manifest)
248
- }
249
- const sourcePath = path.join(directory, 'source' + path.extname(fileName).toLowerCase())
250
- if (Buffer.isBuffer(bytes)) writeFileSync(sourcePath, bytes, { flag: 'wx' })
251
- else copyFileSync(bytes.path, sourcePath)
252
- const job: Job = {
253
- id,
254
- status: 'queued',
255
- fileName,
256
- request,
257
- createdAt: new Date().toISOString(),
258
- fingerprint,
259
- serverResourceFingerprint: serverFingerprint,
260
- ...(owner ? { owner } : {}),
289
+ const sourcePath = path.join(directory, 'source' + path.extname(fileName).toLowerCase())
290
+ storeSource(bytes, sourcePath, this.quota)
291
+ const job: Job = {
292
+ id,
293
+ status: 'queued',
294
+ fileName,
295
+ request,
296
+ createdAt: new Date().toISOString(),
297
+ fingerprint,
298
+ sourceSha256,
299
+ serverResourceFingerprint: serverFingerprint,
300
+ ...(owner ? { owner } : {}),
301
+ }
302
+ this.quota.require(Buffer.byteLength(JSON.stringify(job, null, 2) + '\n'))
303
+ atomicJson(path.join(directory, 'job.json'), job)
304
+ stage.commit()
305
+ this.jobs.set(id, job)
306
+ queueMicrotask(() => this.pump())
307
+ return job
308
+ } finally {
309
+ stage.close()
261
310
  }
262
- atomicJson(path.join(directory, 'job.json'), job)
263
- this.jobs.set(id, job)
264
- queueMicrotask(() => this.pump())
265
- return job
266
311
  }
267
312
  private save(job: Job) {
268
313
  try {
@@ -313,27 +358,34 @@ export class JobQueue {
313
358
  serverResourceFingerprint(this.options.resources, serverFonts)
314
359
  )
315
360
  throw new CadError('RESOURCE_CHANGED', '提交后服务字体或资源发生改变,请重新检查图纸并提交')
316
- job.result = await (this.options.worker || runWorker)(
317
- {
318
- source: path.join(directory, 'source' + path.extname(job.fileName).toLowerCase()),
319
- output: directory,
320
- request: job.request,
321
- resources: existsSync(path.join(directory, 'resources/manifest.json'))
322
- ? path.join(directory, 'resources/manifest.json')
323
- : this.options.resources,
324
- python: this.options.python,
325
- serverFonts,
326
- recovery: !hasBundle && job.request.operation !== 'readback' ? 'best-effort' : 'strict',
327
- },
328
- {
329
- signal: controller.signal,
330
- timeoutMs: this.options.timeoutMs,
331
- onFallback: (receipt, artifacts) => {
332
- job.dwgFallback = receipt
333
- job.diagnostics = artifacts
334
- if (!this.save(job)) throw new CadError('STORAGE_WRITE', 'DWG 兜底进度保存失败')
335
- },
336
- },
361
+ job.result = await this.quota.runWorker(
362
+ directory,
363
+ controller,
364
+ () =>
365
+ (this.options.worker || runWorker)(
366
+ {
367
+ source: path.join(directory, 'source' + path.extname(job.fileName).toLowerCase()),
368
+ output: directory,
369
+ request: job.request,
370
+ resources: existsSync(path.join(directory, 'resources/manifest.json'))
371
+ ? path.join(directory, 'resources/manifest.json')
372
+ : this.options.resources,
373
+ python: this.options.python,
374
+ serverFonts,
375
+ recovery:
376
+ !hasBundle && job.request.operation !== 'readback' ? 'best-effort' : 'strict',
377
+ },
378
+ {
379
+ signal: controller.signal,
380
+ timeoutMs: this.options.timeoutMs,
381
+ onFallback: (receipt, artifacts) => {
382
+ job.dwgFallback = receipt
383
+ job.diagnostics = artifacts
384
+ if (!this.save(job)) throw new CadError('STORAGE_WRITE', 'DWG 兜底进度保存失败')
385
+ },
386
+ },
387
+ ),
388
+ this.options.workerStorageBytes,
337
389
  )
338
390
  job.status = 'succeeded'
339
391
  } catch (error: any) {
@@ -379,52 +431,23 @@ export class JobQueue {
379
431
  jobs: [...this.jobs.values()].filter((job) => job.owner === owner),
380
432
  }
381
433
  }
382
- private storageBytes() {
383
- return directoryBytes(this.options.data)
434
+ holdDownload(id: string) {
435
+ checkedId(id)
436
+ return this.retention.downloads.hold(id)
384
437
  }
385
- cleanup(now = Date.now()) {
386
- if (!this.options.retentionMs && !this.options.maxStorageBytes)
387
- return { removed: [] as string[] }
388
- const removed: string[] = []
389
- try {
390
- let bytes = this.storageBytes()
391
- const grace = this.options.downloadGraceMs ?? 3600000
392
- const candidates = [...this.jobs.values()]
393
- .filter(
394
- (job) =>
395
- !['queued', 'running'].includes(job.status) &&
396
- !this.running.has(job.id) &&
397
- job.endedAt &&
398
- now - Date.parse(job.endedAt) >= grace,
399
- )
400
- .sort((a, b) => Date.parse(a.endedAt!) - Date.parse(b.endedAt!))
401
- for (const job of candidates) {
402
- const expired =
403
- this.options.retentionMs && now - Date.parse(job.endedAt!) >= this.options.retentionMs
404
- if (!expired && !(this.options.maxStorageBytes && bytes > this.options.maxStorageBytes))
405
- continue
406
- const size = directoryBytes(this.directory(job.id))
407
- atomicJson(this.marker('.retired', job.id), {
408
- id: job.id,
409
- owner: job.owner,
410
- fingerprint: job.fingerprint,
411
- status: job.status,
412
- endedAt: job.endedAt,
413
- cleanedAt: new Date(now).toISOString(),
414
- sourceSha256: job.result?.sourceSha256,
415
- error: job.error,
416
- })
417
- removeJobDirectory(this.options.data, job.id)
418
- this.jobs.delete(job.id)
419
- bytes -= size
420
- removed.push(job.id)
421
- }
422
- } catch (error) {
423
- const message = String(error)
424
- if (!this.storageWarnings.some((w) => w.message === message))
425
- this.storageWarnings.push({ directory: '.', message })
438
+ consume(id: string, receipt: unknown) {
439
+ const raw = receipt as Partial<ConsumptionReceipt> & { owner?: unknown } | null
440
+ if (raw && raw.status === undefined && typeof raw.owner === 'string') {
441
+ const job = this.get(id)
442
+ if (!job || job.status !== 'succeeded' || !job.owner || job.owner !== raw.owner)
443
+ throw new CadError('CONSUMPTION_CONFLICT', '成果消费回执与任务不一致')
444
+ return { ...this.retention.consume(id, { ...raw, status: 'succeeded' }), consumed: true }
426
445
  }
427
- return { removed }
446
+ return this.retention.consume(id, receipt)
447
+ }
448
+ cleanup(now = Date.now()) {
449
+ this.staging.cleanup()
450
+ return this.retention.cleanup(now)
428
451
  }
429
452
  async close() {
430
453
  this.closing = true
@@ -0,0 +1,37 @@
1
+ import { mkdirSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import { StorageQuota } from '../../shared/service-storage/src/quota.ts'
4
+ import { runWorker, type WorkerOptions, type WorkerControls } from '../runner.ts'
5
+ import { recadStorageOptions, type StorageSettings } from './storage-policy.ts'
6
+ import { CadError } from '../contracts.ts'
7
+
8
+ export interface ManagedStorageOptions extends StorageSettings { data: string }
9
+
10
+ /** The caller owns its temporary directory; the shared quota owns admission, growth and release. */
11
+ export async function withRecadStorage<T>(
12
+ options: ManagedStorageOptions,
13
+ operation: (signal: AbortSignal) => Promise<T>,
14
+ signal?: AbortSignal,
15
+ ) {
16
+ const data = path.resolve(options.data)
17
+ mkdirSync(data, { recursive: true })
18
+ const storage = recadStorageOptions(options)
19
+ const quota = new StorageQuota(data, storage.maxStorageBytes, storage.storageCapacity)
20
+ const controller = new AbortController()
21
+ const abort = () => controller.abort(signal?.reason)
22
+ signal?.addEventListener('abort', abort, { once: true })
23
+ if (signal?.aborted) abort()
24
+ try {
25
+ if (controller.signal.aborted) throw new CadError('CANCELLED', '任务已取消')
26
+ return await quota.runWorker(data, controller, () => operation(controller.signal), storage.workerStorageBytes)
27
+ } finally { signal?.removeEventListener('abort', abort) }
28
+ }
29
+
30
+ export function runManagedWorker(
31
+ options: WorkerOptions,
32
+ controls: WorkerControls = {},
33
+ storage: Partial<ManagedStorageOptions> = {},
34
+ ) {
35
+ return withRecadStorage({ ...storage, data: storage.data ?? options.output },
36
+ signal => runWorker(options, { ...controls, signal }), controls.signal)
37
+ }