@1agh/maude 1.6.13 → 1.8.1
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/apps/studio/acp/bridge.ts +1 -0
- package/apps/studio/acp/login-state.ts +1 -0
- package/apps/studio/acp/probe.ts +1 -0
- package/apps/studio/annotations/ai-read.ts +3 -0
- package/apps/studio/annotations/ai-write.ts +15 -1
- package/apps/studio/annotations/lock.ts +174 -0
- package/apps/studio/annotations/migrate-v1.ts +1 -0
- package/apps/studio/annotations/registry.ts +3 -0
- package/apps/studio/annotations/v1-adapter.ts +1 -0
- package/apps/studio/annotations-context-toolbar.tsx +39 -0
- package/apps/studio/annotations-layer.tsx +167 -17
- package/apps/studio/annotations-model.ts +9 -0
- package/apps/studio/api.ts +412 -35
- package/apps/studio/asset-upload.ts +174 -0
- package/apps/studio/assets-s3.ts +37 -2
- package/apps/studio/bin/_pdf-playwright.mjs +22 -1
- package/apps/studio/bin/_png-playwright.mjs +20 -1
- package/apps/studio/bin/_region.mjs +92 -0
- package/apps/studio/canvas-build.ts +59 -4
- package/apps/studio/canvas-icons.tsx +18 -0
- package/apps/studio/canvas-lib.tsx +48 -1
- package/apps/studio/canvas-shell.tsx +28 -4
- package/apps/studio/client/app.jsx +109 -22
- package/apps/studio/client/canvas-url.js +9 -0
- package/apps/studio/client/embed-view.jsx +284 -0
- package/apps/studio/client/embed.js +101 -0
- package/apps/studio/client/export-center.jsx +2 -0
- package/apps/studio/client/github.js +36 -3
- package/apps/studio/client/report-bug.jsx +8 -2
- package/apps/studio/context.ts +7 -0
- package/apps/studio/dist/client.bundle.js +2682 -2682
- package/apps/studio/dist/comment-mount.js +2 -2
- package/apps/studio/embed-origins.ts +52 -0
- package/apps/studio/export-dialog.tsx +55 -3
- package/apps/studio/exporters/format-scopes.ts +11 -3
- package/apps/studio/exporters/index.ts +17 -2
- package/apps/studio/exporters/jobs.ts +16 -8
- package/apps/studio/exporters/pdf.ts +10 -2
- package/apps/studio/exporters/png.ts +10 -2
- package/apps/studio/exporters/scope.ts +74 -3
- package/apps/studio/generation/runtime-probe.ts +1 -1
- package/apps/studio/git/service.ts +1 -0
- package/apps/studio/http.ts +186 -13
- package/apps/studio/input-router.tsx +7 -1
- package/apps/studio/path-containment.ts +72 -0
- package/apps/studio/paths.ts +14 -1
- package/apps/studio/read-only-mode.ts +53 -0
- package/apps/studio/server.ts +9 -0
- package/apps/studio/sync/index.ts +74 -13
- package/apps/studio/sync/park.ts +39 -0
- package/apps/studio/sync/presentation.ts +9 -3
- package/apps/studio/sync/writer-registry.ts +5 -0
- package/apps/studio/use-annotation-resize.tsx +4 -1
- package/apps/studio/use-canvas-media-drop.tsx +8 -28
- package/apps/studio/whats-new.json +36 -0
- package/cli/commands/design.mjs +9 -2
- package/cli/commands/hub-workspace.mjs +25 -0
- package/cli/lib/workspace-plan.mjs +51 -0
- package/package.json +9 -9
- package/plugins/design/templates/_shell.html +58 -0
package/apps/studio/api.ts
CHANGED
|
@@ -125,6 +125,7 @@ import {
|
|
|
125
125
|
import { createHistory } from './history.ts';
|
|
126
126
|
import { clearLocatorSlug, readLocator, writeLocator } from './locator.ts';
|
|
127
127
|
import { listMaterializable } from './materialize-client.ts';
|
|
128
|
+
import { resolveUrlPathUnder } from './path-containment.ts';
|
|
128
129
|
import { STICKERS_DIR } from './paths.ts';
|
|
129
130
|
import { getPaperPreset, MAX_PRINT_MM } from './print/units.ts';
|
|
130
131
|
import { sessionDir } from './session-scope.ts';
|
|
@@ -561,6 +562,22 @@ export interface Api {
|
|
|
561
562
|
/** DDR-148 — streaming variant for the HTTP route (100 MB video without a
|
|
562
563
|
* full in-RAM buffer). Sniffs + caps + content-addresses like saveAsset. */
|
|
563
564
|
saveAssetFromStream(stream: ReadableStream<Uint8Array>): Promise<SaveAssetResult>;
|
|
565
|
+
/** Issue #126 — chunked upload for video/audio past the one-shot cap. */
|
|
566
|
+
startAssetChunkSession(
|
|
567
|
+
totalSize: unknown
|
|
568
|
+
): Promise<
|
|
569
|
+
| { ok: true; session: string; chunkBytes: number; chunkCount: number }
|
|
570
|
+
| { ok: false; status: number; error: string }
|
|
571
|
+
>;
|
|
572
|
+
writeAssetChunk(
|
|
573
|
+
sessionId: unknown,
|
|
574
|
+
index: unknown,
|
|
575
|
+
stream: ReadableStream<Uint8Array>
|
|
576
|
+
): Promise<{ ok: true } | { ok: false; status: number; error: string }>;
|
|
577
|
+
finishAssetChunkSession(sessionId: unknown): Promise<SaveAssetResult>;
|
|
578
|
+
abortAssetChunkSession(
|
|
579
|
+
sessionId: unknown
|
|
580
|
+
): Promise<{ ok: true } | { ok: false; status: number; error: string }>;
|
|
564
581
|
// Persist a clipboard-pasted ACP composer image → runtime `_chat/attachments/`,
|
|
565
582
|
// returns an absolute path (Phase 31 follow-up — POST /_api/acp/attachment).
|
|
566
583
|
saveChatAttachment(bytes: Uint8Array): Promise<SaveAssetResult>;
|
|
@@ -1004,10 +1021,11 @@ export const ASSET_MAX_BYTES = (() => {
|
|
|
1004
1021
|
*/
|
|
1005
1022
|
export const ASSET_SESSION_BUDGET = (() => {
|
|
1006
1023
|
const env = Number(process.env.MAUDE_ASSET_SESSION_BUDGET);
|
|
1007
|
-
// DDR-148
|
|
1008
|
-
//
|
|
1009
|
-
// aggregate per-server-instance disk-fill bound
|
|
1010
|
-
|
|
1024
|
+
// DDR-148 raised 256 MB → 1 GB for video/audio; issue #126 raised it to 4 GB
|
|
1025
|
+
// once chunked upload allowed 512 MB clips (1 GB = two drops, then 429 until
|
|
1026
|
+
// restart). Still an aggregate per-server-instance disk-fill bound, now also
|
|
1027
|
+
// charged up front by chunk-session reservations; env-overridable.
|
|
1028
|
+
return Number.isFinite(env) && env > 0 ? env : 4 * 1024 * 1024 * 1024;
|
|
1011
1029
|
})();
|
|
1012
1030
|
|
|
1013
1031
|
/**
|
|
@@ -1127,14 +1145,55 @@ export function assetCapForCategory(category: AssetCategory): number {
|
|
|
1127
1145
|
return category === 'image' ? ASSET_MAX_BYTES : ASSET_MAX_VIDEO_BYTES;
|
|
1128
1146
|
}
|
|
1129
1147
|
|
|
1148
|
+
function envBytes(name: string, fallback: number): number {
|
|
1149
|
+
const env = Number(process.env[name]);
|
|
1150
|
+
return Number.isFinite(env) && env > 0 ? env : fallback;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
/**
|
|
1154
|
+
* Issue #126 — chunked upload for video/audio past {@link ASSET_MAX_VIDEO_BYTES}.
|
|
1155
|
+
* Each request carries one fixed-size chunk, so Bun's global body ceiling
|
|
1156
|
+
* (`MAX_REQUEST_BODY`, server.ts) never has to rise; only the reassembled file
|
|
1157
|
+
* may be larger. The default ceiling equals the desktop sync lane's 512 MiB
|
|
1158
|
+
* push/pull cap (sync/asset-push.ts) — a bigger clip would land locally and
|
|
1159
|
+
* silently never reach a peer.
|
|
1160
|
+
*/
|
|
1161
|
+
// Whole bytes, and never above the one-shot cap: a chunk must always fit under
|
|
1162
|
+
// the global request ceiling (`MAX_REQUEST_BODY`) that this whole design keeps.
|
|
1163
|
+
export const ASSET_CHUNK_BYTES = Math.min(
|
|
1164
|
+
Math.floor(envBytes('MAUDE_ASSET_CHUNK_BYTES', 16 * 1024 * 1024)),
|
|
1165
|
+
ASSET_MAX_VIDEO_BYTES
|
|
1166
|
+
);
|
|
1167
|
+
export const ASSET_MAX_CHUNKED_BYTES = Math.floor(
|
|
1168
|
+
envBytes('MAUDE_ASSET_MAX_CHUNKED_BYTES', 512 * 1024 * 1024)
|
|
1169
|
+
);
|
|
1170
|
+
/** Idle time after which an unfinished chunk session is swept. */
|
|
1171
|
+
export const ASSET_CHUNK_SESSION_TTL_MS = envBytes(
|
|
1172
|
+
'MAUDE_ASSET_CHUNK_SESSION_TTL_MS',
|
|
1173
|
+
30 * 60 * 1000
|
|
1174
|
+
);
|
|
1175
|
+
/** A session that never received a chunk holds a slot + reservation for no
|
|
1176
|
+
* reason — a blind cross-site or scripted start must not pin it for the TTL. */
|
|
1177
|
+
export const ASSET_CHUNK_EMPTY_SESSION_TTL_MS = envBytes(
|
|
1178
|
+
'MAUDE_ASSET_CHUNK_EMPTY_SESSION_TTL_MS',
|
|
1179
|
+
60 * 1000
|
|
1180
|
+
);
|
|
1181
|
+
/** Absolute age cap — re-sending a chunk keeps a session idle-fresh, not alive forever. */
|
|
1182
|
+
export const ASSET_CHUNK_SESSION_MAX_AGE_MS = envBytes(
|
|
1183
|
+
'MAUDE_ASSET_CHUNK_SESSION_MAX_AGE_MS',
|
|
1184
|
+
2 * 60 * 60 * 1000
|
|
1185
|
+
);
|
|
1186
|
+
/** Open chunk sessions per server instance — bounds dirs/fds beyond the byte budget. */
|
|
1187
|
+
export const ASSET_CHUNK_MAX_SESSIONS = Math.floor(envBytes('MAUDE_ASSET_CHUNK_MAX_SESSIONS', 4));
|
|
1188
|
+
|
|
1130
1189
|
const UNSUPPORTED_ASSET_MSG =
|
|
1131
1190
|
'unsupported media type — png/jpeg/gif/webp images or mp4/mov/webm/mp3/wav/m4a media only (SVG/script rejected)';
|
|
1132
1191
|
|
|
1133
|
-
function capError(category
|
|
1192
|
+
function capError(category: AssetCategory | undefined, mediaCap = ASSET_MAX_VIDEO_BYTES): string {
|
|
1134
1193
|
if (category === 'image') {
|
|
1135
1194
|
return `image exceeds the ${Math.round(ASSET_MAX_BYTES / (1024 * 1024))} MB cap`;
|
|
1136
1195
|
}
|
|
1137
|
-
const mb = Math.round(
|
|
1196
|
+
const mb = Math.round(mediaCap / (1024 * 1024));
|
|
1138
1197
|
return `media exceeds the ${mb} MB cap`;
|
|
1139
1198
|
}
|
|
1140
1199
|
|
|
@@ -1455,6 +1514,7 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
1455
1514
|
try {
|
|
1456
1515
|
const proc = Bun.spawn(['git', 'config', 'user.name'], {
|
|
1457
1516
|
cwd: paths.repoRoot,
|
|
1517
|
+
windowsHide: true,
|
|
1458
1518
|
stdout: 'pipe',
|
|
1459
1519
|
stderr: 'pipe',
|
|
1460
1520
|
});
|
|
@@ -1478,6 +1538,7 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
1478
1538
|
try {
|
|
1479
1539
|
const proc = Bun.spawn(['git', 'shortlog', '-sne', 'HEAD'], {
|
|
1480
1540
|
cwd: paths.repoRoot,
|
|
1541
|
+
windowsHide: true,
|
|
1481
1542
|
stdout: 'pipe',
|
|
1482
1543
|
stderr: 'pipe',
|
|
1483
1544
|
});
|
|
@@ -1799,8 +1860,10 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
1799
1860
|
/* ignore */
|
|
1800
1861
|
}
|
|
1801
1862
|
if (p.includes('..')) return null;
|
|
1802
|
-
|
|
1803
|
-
|
|
1863
|
+
// #145 — the static route's resolver, so both agree on Windows (`:` would
|
|
1864
|
+
// name an NTFS stream, `\\` a separator the canvas gate never saw).
|
|
1865
|
+
const abs = resolveUrlPathUnder(`/${p}`, paths.repoRoot);
|
|
1866
|
+
if (!abs || abs === paths.repoRoot) return null;
|
|
1804
1867
|
const ext = path.extname(abs).toLowerCase();
|
|
1805
1868
|
if (ext !== '.tsx' && ext !== '.html') return null;
|
|
1806
1869
|
return abs;
|
|
@@ -2468,14 +2531,27 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
2468
2531
|
ctx.bus.emit('fs:any', rel);
|
|
2469
2532
|
}
|
|
2470
2533
|
|
|
2471
|
-
|
|
2534
|
+
interface ConsumeAssetOpts {
|
|
2535
|
+
/** Ceiling for video/audio; images always get {@link ASSET_MAX_BYTES}. */
|
|
2536
|
+
mediaCap: number;
|
|
2537
|
+
/** 'reserved' — a chunk session already charged the budget at chunk-start. */
|
|
2538
|
+
budget: 'check' | 'reserved';
|
|
2539
|
+
allowImages: boolean;
|
|
2540
|
+
}
|
|
2541
|
+
|
|
2542
|
+
async function consumeAssetStream(
|
|
2543
|
+
stream: ReadableStream<Uint8Array>,
|
|
2544
|
+
opts: ConsumeAssetOpts
|
|
2545
|
+
): Promise<SaveAssetResult> {
|
|
2472
2546
|
const assetsDir = path.join(paths.designRoot, 'assets');
|
|
2473
2547
|
const tmpName = `.tmp-${crypto.randomBytes(8).toString('hex')}`;
|
|
2474
2548
|
const tmpAbs = path.join(assetsDir, tmpName);
|
|
2475
2549
|
const hash = crypto.createHash('sha256');
|
|
2476
2550
|
let sink: Bun.FileSink | null = null;
|
|
2477
2551
|
let typeInfo: AssetTypeInfo | null = null;
|
|
2478
|
-
let cap =
|
|
2552
|
+
let cap = opts.mediaCap; // provisional max until the head is sniffed
|
|
2553
|
+
const capFor = (info: AssetTypeInfo) =>
|
|
2554
|
+
info.category === 'image' ? ASSET_MAX_BYTES : opts.mediaCap;
|
|
2479
2555
|
let total = 0;
|
|
2480
2556
|
const headChunks: Uint8Array[] = [];
|
|
2481
2557
|
let headLen = 0;
|
|
@@ -2515,21 +2591,17 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
2515
2591
|
total += chunk.length;
|
|
2516
2592
|
if (total > cap) {
|
|
2517
2593
|
await cleanup();
|
|
2518
|
-
return { ok: false, status: 413, error: capError(typeInfo?.category) };
|
|
2594
|
+
return { ok: false, status: 413, error: capError(typeInfo?.category, opts.mediaCap) };
|
|
2519
2595
|
}
|
|
2520
2596
|
if (!typeInfo) {
|
|
2521
2597
|
headChunks.push(chunk);
|
|
2522
2598
|
headLen += chunk.length;
|
|
2523
2599
|
if (headLen >= 12) {
|
|
2524
2600
|
typeInfo = sniffAssetType(concatBytes(headChunks));
|
|
2525
|
-
|
|
2601
|
+
const refused = acceptType(typeInfo);
|
|
2602
|
+
if (refused) {
|
|
2526
2603
|
await cleanup(); // nothing written yet — no temp file to remove
|
|
2527
|
-
return
|
|
2528
|
-
}
|
|
2529
|
-
cap = assetCapForCategory(typeInfo.category);
|
|
2530
|
-
if (total > cap) {
|
|
2531
|
-
await cleanup();
|
|
2532
|
-
return { ok: false, status: 413, error: capError(typeInfo.category) };
|
|
2604
|
+
return refused;
|
|
2533
2605
|
}
|
|
2534
2606
|
sink = Bun.file(tmpAbs).writer();
|
|
2535
2607
|
flushHead();
|
|
@@ -2547,21 +2619,19 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
2547
2619
|
// A body shorter than 12 bytes never triggered the mid-stream sniff.
|
|
2548
2620
|
if (!typeInfo) {
|
|
2549
2621
|
typeInfo = sniffAssetType(concatBytes(headChunks));
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
return { ok: false, status: 415, error: UNSUPPORTED_ASSET_MSG };
|
|
2553
|
-
}
|
|
2554
|
-
cap = assetCapForCategory(typeInfo.category);
|
|
2555
|
-
if (total > cap) {
|
|
2622
|
+
const refused = acceptType(typeInfo);
|
|
2623
|
+
if (refused) {
|
|
2556
2624
|
await cleanup();
|
|
2557
|
-
return
|
|
2625
|
+
return refused;
|
|
2558
2626
|
}
|
|
2559
2627
|
sink = Bun.file(tmpAbs).writer();
|
|
2560
2628
|
flushHead();
|
|
2561
2629
|
}
|
|
2630
|
+
if (!typeInfo) throw new Error('unreachable: asset type unresolved');
|
|
2562
2631
|
if (sink) await sink.end();
|
|
2563
2632
|
|
|
2564
|
-
const
|
|
2633
|
+
const digest = hash.digest('hex');
|
|
2634
|
+
const sha8 = digest.slice(0, 8);
|
|
2565
2635
|
const name = `${sha8}.${typeInfo.ext}`;
|
|
2566
2636
|
const fileAbs = path.join(assetsDir, name);
|
|
2567
2637
|
// Containment backstop — the name is content-addressed (sha8 hex + sniffed
|
|
@@ -2576,8 +2646,13 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
2576
2646
|
return { ok: true, path: `assets/${name}` };
|
|
2577
2647
|
}
|
|
2578
2648
|
// Aggregate write budget — bounds a scripted disk-fill loop from the
|
|
2579
|
-
// untrusted canvas origin. Only a genuinely NEW file counts.
|
|
2580
|
-
|
|
2649
|
+
// untrusted canvas origin. Only a genuinely NEW file counts. Bytes held by
|
|
2650
|
+
// open chunk sessions count too, or one-shot writes could oversubscribe
|
|
2651
|
+
// what those sessions were promised.
|
|
2652
|
+
if (
|
|
2653
|
+
opts.budget === 'check' &&
|
|
2654
|
+
assetBytesWritten + assetBytesReserved + total > ASSET_SESSION_BUDGET
|
|
2655
|
+
) {
|
|
2581
2656
|
await rm(tmpAbs, { force: true });
|
|
2582
2657
|
return {
|
|
2583
2658
|
ok: false,
|
|
@@ -2590,13 +2665,13 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
2590
2665
|
const rel = `assets/${name}`;
|
|
2591
2666
|
announceWritten(rel);
|
|
2592
2667
|
// S3/R2 lane (Cloud Phase 3) — mirror the bytes so a second machine can
|
|
2593
|
-
// resolve them without the file riding git.
|
|
2594
|
-
//
|
|
2595
|
-
//
|
|
2596
|
-
//
|
|
2597
|
-
// every dedupe hit.
|
|
2668
|
+
// resolve them without the file riding git. Never able to fail the save:
|
|
2669
|
+
// the asset is already on disk, the mirror is the redundant copy, and
|
|
2670
|
+
// `maude hub asset-check` reconciles a miss. Streamed from disk — a 512 MB
|
|
2671
|
+
// clip must not be read whole into RAM. Only a genuinely NEW file reaches
|
|
2672
|
+
// here, so this is not re-uploading on every dedupe hit.
|
|
2598
2673
|
if (assetMirror.configured) {
|
|
2599
|
-
void assetMirror.
|
|
2674
|
+
void assetMirror.pushFile(rel, fileAbs, digest);
|
|
2600
2675
|
}
|
|
2601
2676
|
return { ok: true, path: rel };
|
|
2602
2677
|
} catch (err) {
|
|
@@ -2609,6 +2684,304 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
2609
2684
|
/* already released */
|
|
2610
2685
|
}
|
|
2611
2686
|
}
|
|
2687
|
+
|
|
2688
|
+
function acceptType(info: AssetTypeInfo | null): SaveAssetResult | null {
|
|
2689
|
+
if (!info) return { ok: false, status: 415, error: UNSUPPORTED_ASSET_MSG };
|
|
2690
|
+
if (info.category === 'image' && !opts.allowImages) {
|
|
2691
|
+
return { ok: false, status: 415, error: 'images upload in one request, not in chunks' };
|
|
2692
|
+
}
|
|
2693
|
+
cap = capFor(info);
|
|
2694
|
+
if (total > cap) {
|
|
2695
|
+
return { ok: false, status: 413, error: capError(info.category, opts.mediaCap) };
|
|
2696
|
+
}
|
|
2697
|
+
return null;
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
|
|
2701
|
+
/** DDR-148 — the one-shot streamed write behind `POST /_api/asset`. */
|
|
2702
|
+
function saveAssetFromStream(stream: ReadableStream<Uint8Array>): Promise<SaveAssetResult> {
|
|
2703
|
+
return consumeAssetStream(stream, {
|
|
2704
|
+
mediaCap: ASSET_MAX_VIDEO_BYTES,
|
|
2705
|
+
budget: 'check',
|
|
2706
|
+
allowImages: true,
|
|
2707
|
+
});
|
|
2708
|
+
}
|
|
2709
|
+
|
|
2710
|
+
// Issue #126 — chunked upload. Same untrusted canvas origin as the one-shot
|
|
2711
|
+
// route, so: fixed chunk sizes (bounded file count per session), a cap on open
|
|
2712
|
+
// sessions, the byte budget charged at chunk-start before any byte is
|
|
2713
|
+
// accepted, one write in flight per session, idle / empty / over-age sessions
|
|
2714
|
+
// swept, and the sniff run on the REASSEMBLED stream by the shared core —
|
|
2715
|
+
// never per chunk. Session scratch lives under the runtime `_state/` tree,
|
|
2716
|
+
// never the versioned + synced `assets/`. See DDR-248.
|
|
2717
|
+
interface ChunkSession {
|
|
2718
|
+
id: string;
|
|
2719
|
+
dir: string;
|
|
2720
|
+
totalSize: number;
|
|
2721
|
+
chunkCount: number;
|
|
2722
|
+
received: Set<number>;
|
|
2723
|
+
createdAt: number;
|
|
2724
|
+
lastActivity: number;
|
|
2725
|
+
/** A chunk write is streaming — a second write or a finish is refused (409). */
|
|
2726
|
+
writing: boolean;
|
|
2727
|
+
/** Set once finish/abort starts — later chunk writes are refused. */
|
|
2728
|
+
closing: boolean;
|
|
2729
|
+
}
|
|
2730
|
+
const CHUNK_SESSION_ID = /^[0-9a-f]{32}$/;
|
|
2731
|
+
const chunkSessions = new Map<string, ChunkSession>();
|
|
2732
|
+
let assetBytesReserved = 0;
|
|
2733
|
+
const chunkRoot = () => path.join(paths.designRoot, '_state', 'asset-chunks');
|
|
2734
|
+
|
|
2735
|
+
/** Unregister + release synchronously; the directory removal is best-effort. */
|
|
2736
|
+
async function dropChunkSession(s: ChunkSession): Promise<void> {
|
|
2737
|
+
if (chunkSessions.get(s.id) === s) {
|
|
2738
|
+
chunkSessions.delete(s.id);
|
|
2739
|
+
assetBytesReserved = Math.max(0, assetBytesReserved - s.totalSize);
|
|
2740
|
+
}
|
|
2741
|
+
try {
|
|
2742
|
+
await rm(s.dir, { recursive: true, force: true });
|
|
2743
|
+
} catch {
|
|
2744
|
+
/* a racing write recreated a temp file — the orphan sweep collects it */
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
|
|
2748
|
+
function chunkSessionExpired(s: ChunkSession, now: number): boolean {
|
|
2749
|
+
if (s.closing || s.writing) return false;
|
|
2750
|
+
if (now - s.createdAt > ASSET_CHUNK_SESSION_MAX_AGE_MS) return true;
|
|
2751
|
+
if (s.received.size === 0 && now - s.createdAt > ASSET_CHUNK_EMPTY_SESSION_TTL_MS) return true;
|
|
2752
|
+
return now - s.lastActivity > ASSET_CHUNK_SESSION_TTL_MS;
|
|
2753
|
+
}
|
|
2754
|
+
|
|
2755
|
+
/**
|
|
2756
|
+
* Drop expired sessions (idle, never fed, or past their absolute age), and
|
|
2757
|
+
* orphan dirs left by an earlier process (its sessions died with it). An
|
|
2758
|
+
* orphan is only removed once it is itself idle past the TTL, so a second
|
|
2759
|
+
* server on the same project is never undercut mid-upload.
|
|
2760
|
+
*/
|
|
2761
|
+
async function sweepStaleChunkSessions(now = Date.now()): Promise<void> {
|
|
2762
|
+
for (const s of [...chunkSessions.values()]) {
|
|
2763
|
+
if (chunkSessionExpired(s, now)) await dropChunkSession(s);
|
|
2764
|
+
}
|
|
2765
|
+
let names: string[];
|
|
2766
|
+
try {
|
|
2767
|
+
names = await readdir(chunkRoot());
|
|
2768
|
+
} catch {
|
|
2769
|
+
return; // nothing ever chunked here
|
|
2770
|
+
}
|
|
2771
|
+
for (const name of names) {
|
|
2772
|
+
if (chunkSessions.has(name)) continue;
|
|
2773
|
+
const dir = path.join(chunkRoot(), name);
|
|
2774
|
+
try {
|
|
2775
|
+
const st = await statp(dir);
|
|
2776
|
+
if (now - st.mtimeMs > ASSET_CHUNK_SESSION_TTL_MS) {
|
|
2777
|
+
await rm(dir, { recursive: true, force: true });
|
|
2778
|
+
}
|
|
2779
|
+
} catch {
|
|
2780
|
+
/* raced with another sweep */
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
void sweepStaleChunkSessions();
|
|
2785
|
+
|
|
2786
|
+
function chunkSessionFor(
|
|
2787
|
+
id: unknown
|
|
2788
|
+
): { session: ChunkSession } | { ok: false; status: number; error: string } {
|
|
2789
|
+
if (typeof id !== 'string' || !CHUNK_SESSION_ID.test(id)) {
|
|
2790
|
+
return { ok: false, status: 400, error: 'invalid upload session' };
|
|
2791
|
+
}
|
|
2792
|
+
const session = chunkSessions.get(id);
|
|
2793
|
+
if (!session) return { ok: false, status: 404, error: 'upload session not found or expired' };
|
|
2794
|
+
if (session.closing) return { ok: false, status: 409, error: 'upload session is closing' };
|
|
2795
|
+
return { session };
|
|
2796
|
+
}
|
|
2797
|
+
|
|
2798
|
+
async function startAssetChunkSession(
|
|
2799
|
+
totalSize: unknown
|
|
2800
|
+
): Promise<
|
|
2801
|
+
| { ok: true; session: string; chunkBytes: number; chunkCount: number }
|
|
2802
|
+
| { ok: false; status: number; error: string }
|
|
2803
|
+
> {
|
|
2804
|
+
if (typeof totalSize !== 'number' || !Number.isSafeInteger(totalSize) || totalSize <= 0) {
|
|
2805
|
+
return { ok: false, status: 400, error: 'totalSize must be a positive integer' };
|
|
2806
|
+
}
|
|
2807
|
+
if (totalSize > ASSET_MAX_CHUNKED_BYTES) {
|
|
2808
|
+
return { ok: false, status: 413, error: capError('video', ASSET_MAX_CHUNKED_BYTES) };
|
|
2809
|
+
}
|
|
2810
|
+
await sweepStaleChunkSessions();
|
|
2811
|
+
// Check, register and reserve with NO await in between: concurrent
|
|
2812
|
+
// chunk-starts must each see the ones before them, or N parallel requests
|
|
2813
|
+
// all pass the session cap and the budget against the same empty state.
|
|
2814
|
+
if (chunkSessions.size >= ASSET_CHUNK_MAX_SESSIONS) {
|
|
2815
|
+
return { ok: false, status: 429, error: 'too many uploads in progress — try again shortly' };
|
|
2816
|
+
}
|
|
2817
|
+
if (assetBytesWritten + assetBytesReserved + totalSize > ASSET_SESSION_BUDGET) {
|
|
2818
|
+
return {
|
|
2819
|
+
ok: false,
|
|
2820
|
+
status: 429,
|
|
2821
|
+
error: 'asset write budget exceeded for this server session',
|
|
2822
|
+
};
|
|
2823
|
+
}
|
|
2824
|
+
const id = crypto.randomBytes(16).toString('hex');
|
|
2825
|
+
const dir = path.join(chunkRoot(), id);
|
|
2826
|
+
if (path.resolve(dir) !== path.join(path.resolve(chunkRoot()), id)) {
|
|
2827
|
+
return { ok: false, status: 400, error: 'resolved chunk dir escapes _state' };
|
|
2828
|
+
}
|
|
2829
|
+
const now = Date.now();
|
|
2830
|
+
const session: ChunkSession = {
|
|
2831
|
+
id,
|
|
2832
|
+
dir,
|
|
2833
|
+
totalSize,
|
|
2834
|
+
chunkCount: Math.ceil(totalSize / ASSET_CHUNK_BYTES),
|
|
2835
|
+
received: new Set(),
|
|
2836
|
+
createdAt: now,
|
|
2837
|
+
lastActivity: now,
|
|
2838
|
+
writing: false,
|
|
2839
|
+
closing: false,
|
|
2840
|
+
};
|
|
2841
|
+
chunkSessions.set(id, session);
|
|
2842
|
+
assetBytesReserved += totalSize;
|
|
2843
|
+
try {
|
|
2844
|
+
await mkdir(dir, { recursive: true });
|
|
2845
|
+
} catch (err) {
|
|
2846
|
+
await dropChunkSession(session);
|
|
2847
|
+
return { ok: false, status: 500, error: err instanceof Error ? err.message : 'mkdir failed' };
|
|
2848
|
+
}
|
|
2849
|
+
return { ok: true, session: id, chunkBytes: ASSET_CHUNK_BYTES, chunkCount: session.chunkCount };
|
|
2850
|
+
}
|
|
2851
|
+
|
|
2852
|
+
async function writeAssetChunk(
|
|
2853
|
+
sessionId: unknown,
|
|
2854
|
+
indexRaw: unknown,
|
|
2855
|
+
stream: ReadableStream<Uint8Array>
|
|
2856
|
+
): Promise<{ ok: true } | { ok: false; status: number; error: string }> {
|
|
2857
|
+
const found = chunkSessionFor(sessionId);
|
|
2858
|
+
if (!('session' in found)) return found;
|
|
2859
|
+
const s = found.session;
|
|
2860
|
+
if (typeof indexRaw !== 'string' || !/^\d{1,9}$/.test(indexRaw)) {
|
|
2861
|
+
return { ok: false, status: 400, error: 'invalid chunk index' };
|
|
2862
|
+
}
|
|
2863
|
+
const index = Number(indexRaw);
|
|
2864
|
+
if (index >= s.chunkCount) return { ok: false, status: 400, error: 'chunk index out of range' };
|
|
2865
|
+
// One write at a time per session: the client is sequential, and parallel
|
|
2866
|
+
// writes would each hold an uncounted temp file + fd outside the budget.
|
|
2867
|
+
if (s.writing) return { ok: false, status: 409, error: 'another chunk is still uploading' };
|
|
2868
|
+
s.writing = true;
|
|
2869
|
+
const expected =
|
|
2870
|
+
index === s.chunkCount - 1 ? s.totalSize - index * ASSET_CHUNK_BYTES : ASSET_CHUNK_BYTES;
|
|
2871
|
+
|
|
2872
|
+
// Written under a unique temp name, then renamed — a retried chunk can
|
|
2873
|
+
// never leave a torn `.part` behind.
|
|
2874
|
+
const partAbs = path.join(s.dir, `${index}.part`);
|
|
2875
|
+
const tmpAbs = path.join(s.dir, `${index}.part.tmp-${crypto.randomBytes(6).toString('hex')}`);
|
|
2876
|
+
const reader = stream.getReader();
|
|
2877
|
+
let got = 0;
|
|
2878
|
+
let failure: { ok: false; status: number; error: string } | null = null;
|
|
2879
|
+
try {
|
|
2880
|
+
const sink = Bun.file(tmpAbs).writer();
|
|
2881
|
+
for (;;) {
|
|
2882
|
+
const { done, value } = await reader.read();
|
|
2883
|
+
if (done) break;
|
|
2884
|
+
if (!value || value.length === 0) continue;
|
|
2885
|
+
got += value.length;
|
|
2886
|
+
if (got > expected) {
|
|
2887
|
+
failure = { ok: false, status: 413, error: `chunk exceeds its ${expected}-byte size` };
|
|
2888
|
+
break;
|
|
2889
|
+
}
|
|
2890
|
+
sink.write(value);
|
|
2891
|
+
}
|
|
2892
|
+
await sink.end();
|
|
2893
|
+
if (!failure && got !== expected) {
|
|
2894
|
+
failure = { ok: false, status: 400, error: `chunk must be exactly ${expected} bytes` };
|
|
2895
|
+
}
|
|
2896
|
+
if (!failure && s.closing) {
|
|
2897
|
+
failure = { ok: false, status: 409, error: 'upload session is closing' };
|
|
2898
|
+
}
|
|
2899
|
+
if (failure) {
|
|
2900
|
+
await rm(tmpAbs, { force: true });
|
|
2901
|
+
return failure;
|
|
2902
|
+
}
|
|
2903
|
+
await rename(tmpAbs, partAbs);
|
|
2904
|
+
s.received.add(index);
|
|
2905
|
+
s.lastActivity = Date.now();
|
|
2906
|
+
return { ok: true };
|
|
2907
|
+
} catch (err) {
|
|
2908
|
+
await rm(tmpAbs, { force: true }).catch(() => undefined);
|
|
2909
|
+
return { ok: false, status: 500, error: err instanceof Error ? err.message : 'write failed' };
|
|
2910
|
+
} finally {
|
|
2911
|
+
s.writing = false;
|
|
2912
|
+
try {
|
|
2913
|
+
reader.releaseLock();
|
|
2914
|
+
} catch {
|
|
2915
|
+
/* already released */
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
|
|
2920
|
+
/** The session's `.part` files, in index order, as one byte stream. */
|
|
2921
|
+
function reassembledStream(s: ChunkSession): ReadableStream<Uint8Array> {
|
|
2922
|
+
let index = 0;
|
|
2923
|
+
let current: ReadableStreamDefaultReader<Uint8Array> | null = null;
|
|
2924
|
+
return new ReadableStream<Uint8Array>({
|
|
2925
|
+
async pull(controller) {
|
|
2926
|
+
for (;;) {
|
|
2927
|
+
if (!current) {
|
|
2928
|
+
if (index >= s.chunkCount) {
|
|
2929
|
+
controller.close();
|
|
2930
|
+
return;
|
|
2931
|
+
}
|
|
2932
|
+
const part = Bun.file(path.join(s.dir, `${index}.part`)).stream();
|
|
2933
|
+
current = part.getReader() as ReadableStreamDefaultReader<Uint8Array>;
|
|
2934
|
+
index += 1;
|
|
2935
|
+
}
|
|
2936
|
+
const { done, value } = await current.read();
|
|
2937
|
+
if (done) {
|
|
2938
|
+
current = null;
|
|
2939
|
+
continue;
|
|
2940
|
+
}
|
|
2941
|
+
controller.enqueue(value);
|
|
2942
|
+
return;
|
|
2943
|
+
}
|
|
2944
|
+
},
|
|
2945
|
+
async cancel() {
|
|
2946
|
+
await current?.cancel();
|
|
2947
|
+
},
|
|
2948
|
+
});
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2951
|
+
async function finishAssetChunkSession(sessionId: unknown): Promise<SaveAssetResult> {
|
|
2952
|
+
const found = chunkSessionFor(sessionId);
|
|
2953
|
+
if (!('session' in found)) return found;
|
|
2954
|
+
const s = found.session;
|
|
2955
|
+
if (s.writing) return { ok: false, status: 409, error: 'a chunk is still uploading' };
|
|
2956
|
+
s.closing = true;
|
|
2957
|
+
try {
|
|
2958
|
+
if (s.received.size !== s.chunkCount) {
|
|
2959
|
+
return {
|
|
2960
|
+
ok: false,
|
|
2961
|
+
status: 400,
|
|
2962
|
+
error: `incomplete upload — ${s.received.size} of ${s.chunkCount} chunks received`,
|
|
2963
|
+
};
|
|
2964
|
+
}
|
|
2965
|
+
// The reservation covers this write; releasing it happens in finally, on
|
|
2966
|
+
// success, dedupe and failure alike.
|
|
2967
|
+
return await consumeAssetStream(reassembledStream(s), {
|
|
2968
|
+
mediaCap: ASSET_MAX_CHUNKED_BYTES,
|
|
2969
|
+
budget: 'reserved',
|
|
2970
|
+
allowImages: false,
|
|
2971
|
+
});
|
|
2972
|
+
} finally {
|
|
2973
|
+
await dropChunkSession(s);
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
async function abortAssetChunkSession(
|
|
2978
|
+
sessionId: unknown
|
|
2979
|
+
): Promise<{ ok: true } | { ok: false; status: number; error: string }> {
|
|
2980
|
+
const found = chunkSessionFor(sessionId);
|
|
2981
|
+
if (!('session' in found)) return found;
|
|
2982
|
+
found.session.closing = true;
|
|
2983
|
+
await dropChunkSession(found.session);
|
|
2984
|
+
return { ok: true };
|
|
2612
2985
|
}
|
|
2613
2986
|
|
|
2614
2987
|
async function saveAsset(bytes: Uint8Array): Promise<SaveAssetResult> {
|
|
@@ -2947,7 +3320,7 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
2947
3320
|
}
|
|
2948
3321
|
try {
|
|
2949
3322
|
if (!(await Bun.file(fileAbs).exists())) {
|
|
2950
|
-
if (assetBytesWritten + bytes.length > ASSET_SESSION_BUDGET) {
|
|
3323
|
+
if (assetBytesWritten + assetBytesReserved + bytes.length > ASSET_SESSION_BUDGET) {
|
|
2951
3324
|
return {
|
|
2952
3325
|
ok: false,
|
|
2953
3326
|
status: 429,
|
|
@@ -6880,6 +7253,10 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
|
|
|
6880
7253
|
searchAudioLibrary,
|
|
6881
7254
|
listStickers,
|
|
6882
7255
|
saveAssetFromStream,
|
|
7256
|
+
startAssetChunkSession,
|
|
7257
|
+
writeAssetChunk,
|
|
7258
|
+
finishAssetChunkSession,
|
|
7259
|
+
abortAssetChunkSession,
|
|
6883
7260
|
saveChatAttachment,
|
|
6884
7261
|
resolveChatAttachment,
|
|
6885
7262
|
createCanvas,
|