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