Skip to content

Commit f67aad6

Browse files
author
hzq
committed
Share contended upload writes fairly and release disconnected waiters
1 parent b171dca commit f67aad6

8 files changed

Lines changed: 759 additions & 137 deletions

File tree

‎docs/stability.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,8 +254,13 @@ This applies to creating the run, not to every database write. File-byte reserva
254254
publication have their own cooperative writer wait (at most five seconds). Contended writers
255255
and followers of an identical in-flight image are separately bounded to eight waiters / 32 MiB
256256
per owner and 64 waiters / 64 MiB overall. These are buffered byte budgets, not a limit on total
257-
process memory or the duration of a file transfer.
258-
If a waiting request abandons an inline image, another waiting request can still use its copy.
257+
process memory or the duration of a file transfer. One timer probes the writer lock for all
258+
queued file writes. Admitted owners take turns, FIFO within each owner; new arrivals cannot
259+
bypass the queue. A turn is one reservation or publication, not an entire upload. A disconnect
260+
notification releases that caller's wait budget without waiting for the next lock probe.
261+
Another caller waiting for the same inline image can still use its copy. Worker-result
262+
artifacts do not use this upload queue: their metadata publication still waits synchronously
263+
on a competing SQLite writer and can delay unrelated gateway requests.
259264
The input journal rolls back abandoned materialization even after restart, independently of
260265
retention. It records deletion before unlinking and keeps the receipt until absence is confirmed.
261266
It does not sweep unmarked files. In particular, an empty filesystem entry left before the first

‎docs/zh-CN/stability.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,9 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
123123
等待期间重新核对授权;提交前断开会放弃等待,不会取消已经提交的任务。这个保证针对运行创建,不涵盖所有数据库写入。
124124
文件字节预留和文件发布另行异步等写锁,最长五秒。竞争写锁与等待相同图片的请求分别限流:
125125
每个 owner 最多 8 个、32 MiB,全网关最多 64 个、64 MiB。这里限制的是等待中的文件字节,不是整个进程内存或传输耗时。
126-
放弃等待的请求不会删除其他请求仍在复用的内联图片。新的临时输入有持久归属记录,重启后仍可回收,无需启用保留策略。
126+
同一网关的文件写入队列只用一个定时器探测写锁;已经入队的 owner 轮流写,同一 owner 内先进先出,新请求不能插队。一轮是一次预留或发布,不代表整个上传先完成。
127+
收到断开通知就释放该调用方的等待名额,不必等下一次试锁,也不会删除其他请求仍在复用的内联图片。worker 返回的产物不经过这条上传队列:发布其元数据时仍会同步等 SQLite 写锁,可能拖慢无关的网关请求。
128+
新的临时输入有持久归属记录,重启后仍可回收,无需启用保留策略。
127129
先提交删除凭据,再删除磁盘文件,确认文件已不存在才清除凭据。不会扫目录猜测旧文件归属;首次登记之前若仅留下空的文件系统条目,其中没有图片数据,也不占文件配额,仍由普通孤立文件清理处理。
128130

129131
## 3. 升级、备份与降级

‎src/gateway/image-staging.ts‎

Lines changed: 97 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -2,65 +2,128 @@ import type { Store } from '../store/store.js';
22
import { Fault } from '../core/util.js';
33
import { UploadWaitBudget, type UploadPolicy } from '../store/upload-budget.js';
44

5-
type Flight = { guards: Set<() => void>; file: Promise<string> };
5+
type Subscriber = { check: () => void; accept: (id: string) => void; fail: (e: unknown) => void };
6+
type Flight = { callers: Set<Subscriber>; listeners: Set<() => void> };
67
const staging = new WeakMap<Store, Map<string, Flight>>();
78
const joiners = new WeakMap<Store, UploadWaitBudget>();
89
const key = (owner: string, subject: string, digest: string) =>
910
JSON.stringify([owner, subject, digest]);
1011
export function stagingCopy(store: Store, owner: string, subject: string, digest: string) {
1112
return staging.get(store)?.has(key(owner, subject, digest)) ?? false;
1213
}
13-
/** Share only the private materialization, not a run, its grants or its acceptance. */
14-
export async function stageImage(
14+
function materialize(
1515
store: Store,
16+
flight: Flight,
1617
owner: string,
1718
subject: string,
18-
digest: string,
1919
name: string,
2020
bytes: Buffer,
2121
policy: UploadPolicy,
22-
held: string[],
2322
) {
24-
let pool = staging.get(store);
25-
if (!pool) staging.set(store, (pool = new Map()));
26-
const id = key(owner, subject, digest),
27-
check = () => policy.guard?.();
28-
check();
29-
let flight = pool.get(id);
30-
let leave: (() => void) | undefined;
31-
if (!flight) {
32-
const guards = new Set([check]);
33-
const guard = () => {
23+
const guard = Object.assign(
24+
() => {
3425
let failure: unknown;
35-
for (const check of guards) {
26+
for (const c of flight.callers) {
3627
try {
37-
check();
28+
c.check();
3829
return;
3930
} catch (e) {
4031
failure = e;
4132
}
4233
}
4334
throw failure ?? new Fault('request_cancelled', 'No caller is waiting for this image.', 499);
44-
};
45-
const file = store
46-
.addFile(owner, name, bytes, undefined, undefined, subject, { ...policy, guard })
47-
.then((f) => f.id)
48-
.finally(() => pool.delete(id));
49-
flight = { guards, file };
50-
pool.set(id, flight);
51-
} else {
35+
},
36+
{
37+
onDisconnect(notify: () => void) {
38+
flight.listeners.add(notify);
39+
return () => {
40+
flight.listeners.delete(notify);
41+
};
42+
},
43+
},
44+
);
45+
void store
46+
.addFile(owner, name, bytes, undefined, undefined, subject, { ...policy, guard })
47+
.then(async (file) => {
48+
// Even if every caller left after commit, retire this unclaimed input through its journal.
49+
const handoff = store.provisionalInputs.hold(owner, [file.id]);
50+
try {
51+
for (const c of flight.callers) c.accept(file.id);
52+
} finally {
53+
await store.provisionalInputs.release(handoff);
54+
}
55+
})
56+
.catch((error) => {
57+
for (const c of flight.callers) c.fail(error);
58+
});
59+
}
60+
61+
/** Share only the private materialization, not a run, its grants or its acceptance. */
62+
export async function stageImage(
63+
store: Store,
64+
owner: string,
65+
subject: string,
66+
digest: string,
67+
name: string,
68+
bytes: Buffer,
69+
policy: UploadPolicy,
70+
held: string[],
71+
) {
72+
let pool = staging.get(store);
73+
if (!pool) staging.set(store, (pool = new Map()));
74+
const id = key(owner, subject, digest),
75+
existing = pool.get(id);
76+
const check = () => policy.guard?.();
77+
check();
78+
const flight: Flight = existing ?? { callers: new Set(), listeners: new Set() };
79+
let leave: (() => void) | undefined, unsubscribe: (() => void) | undefined;
80+
if (existing) {
5281
let budget = joiners.get(store);
5382
if (!budget) joiners.set(store, (budget = new UploadWaitBudget()));
5483
leave = budget.take(owner, bytes.length);
55-
flight.guards.add(check);
56-
}
57-
try {
58-
const file = await flight.file;
59-
held.push(...store.provisionalInputs.hold(owner, [file]));
60-
check();
61-
return file;
62-
} finally {
63-
flight.guards.delete(check);
84+
} else pool.set(id, flight);
85+
const { promise, resolve, reject } = Promise.withResolvers<string>();
86+
const detach = () => {
87+
if (!flight.callers.delete(caller)) return;
6488
leave?.();
89+
unsubscribe?.();
90+
if (!flight.callers.size) {
91+
if (pool.get(id) === flight) pool.delete(id);
92+
for (const notify of flight.listeners) notify();
93+
}
94+
};
95+
const caller: Subscriber = {
96+
check,
97+
accept(file) {
98+
try {
99+
check();
100+
held.push(...store.provisionalInputs.hold(owner, [file]));
101+
resolve(file);
102+
} catch (error) {
103+
reject(error);
104+
} finally {
105+
detach();
106+
}
107+
},
108+
fail(error) {
109+
detach();
110+
reject(error);
111+
},
112+
};
113+
flight.callers.add(caller);
114+
try {
115+
unsubscribe = policy.guard?.onDisconnect?.(() => {
116+
try {
117+
check();
118+
} catch (error) {
119+
caller.fail(error);
120+
}
121+
});
122+
if (!flight.callers.has(caller)) unsubscribe?.();
123+
} catch (error) {
124+
caller.fail(error);
65125
}
126+
if (!existing && flight.callers.size)
127+
materialize(store, flight, owner, subject, name, bytes, policy);
128+
return promise;
66129
}

‎src/store/upload-budget.ts‎

Lines changed: 5 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,22 @@
11
import type { DatabaseSync, StatementSync } from 'node:sqlite';
2-
import { setTimeout as delay } from 'node:timers/promises';
3-
import { Fault, RetryLaterFault } from '../core/util.js';
2+
import { Fault } from '../core/util.js';
43
import { bi } from '../core/locale.js';
5-
import { isWriteContended, isWriteUnavailable } from './checkpoint.js';
6-
import { tryBeginWrite } from './write-lock.js';
4+
import type { UploadGuard } from './upload-writer.js';
5+
export { UploadWaitBudget, UploadWriter } from './upload-writer.js';
76
import { fileBytes, fileDigest as digest } from './upload-facts.js';
87
import { fileScopeIndexSpec, fileScopeLayout, scopeOnlyIndexSpec } from './file-scope-index.js';
98
import { uploadUsage, type UsageConnection } from './upload-usage.js';
109

1110
export type UploadPolicy = {
1211
kind: 'inline' | 'upload';
1312
limit?: number;
14-
guard?: () => void;
13+
guard?: UploadGuard;
1514
coldReads?: {
1615
retry(
1716
owner: string,
1817
subject: string,
1918
retainedBytes: number,
20-
guard: (() => void) | undefined,
19+
guard: UploadGuard | undefined,
2120
reserve: () => Promise<void>,
2221
): Promise<void>;
2322
};
@@ -88,92 +87,3 @@ export function checkUploadRoom(
8887
413,
8988
);
9089
}
91-
92-
const busy = () =>
93-
new RetryLaterFault(
94-
'upload_busy',
95-
'File storage could not admit this upload within its wait budget.',
96-
503,
97-
1,
98-
);
99-
/** Capacity for buffered callers, not a limit on total process memory or on durable files. */
100-
export class UploadWaitBudget {
101-
private waiting = new Set<{ owner: string; bytes: number }>();
102-
take(owner: string, bytes: number) {
103-
let all = bytes,
104-
own = bytes,
105-
n = 1;
106-
for (const w of this.waiting) {
107-
all += w.bytes;
108-
if (w.owner === owner) {
109-
own += w.bytes;
110-
n++;
111-
}
112-
}
113-
if (this.waiting.size >= 64 || n > 8 || all > 64 * 1024 ** 2 || own > 32 * 1024 ** 2)
114-
throw busy();
115-
const held = { owner, bytes };
116-
this.waiting.add(held);
117-
return () => this.waiting.delete(held);
118-
}
119-
}
120-
// Only acquisition is retried, never a write or a quota reservation.
121-
export class UploadWriter {
122-
private budget = new UploadWaitBudget();
123-
private stopped = false;
124-
private timeout?: StatementSync;
125-
constructor(private db: DatabaseSync) {}
126-
close() {
127-
this.stopped = true;
128-
this.timeout = undefined;
129-
}
130-
async run<T>(
131-
owner: string,
132-
bytes: number,
133-
guard: (() => void) | undefined,
134-
work: () => T,
135-
confirm?: () => boolean,
136-
): Promise<T> {
137-
if (this.stopped) throw new Fault('shutting_down', 'File storage is shutting down.', 503);
138-
let release: (() => void) | undefined;
139-
const timeout = Number(
140-
(this.timeout ??= this.db.prepare('PRAGMA busy_timeout')).get()!.timeout,
141-
);
142-
const until = performance.now() + Math.min(5000, timeout);
143-
let backoff = 10;
144-
try {
145-
for (;;) {
146-
if (this.stopped) throw new Fault('shutting_down', 'File storage is shutting down.', 503);
147-
if (this.db.isTransaction)
148-
throw new Fault('persistence_failed', 'An upload cannot use another transaction.', 500);
149-
guard?.();
150-
if (release && performance.now() >= until) throw busy();
151-
try {
152-
tryBeginWrite(this.db, release ? Number(this.timeout!.get()!.timeout) : timeout);
153-
break;
154-
} catch (e) {
155-
if (!isWriteContended(e) || this.db.isTransaction) throw e;
156-
const left = until - performance.now();
157-
if (left <= 0) throw busy();
158-
release ??= this.budget.take(owner, bytes);
159-
await delay(Math.min(backoff, left));
160-
backoff = Math.min(100, backoff * 2);
161-
}
162-
}
163-
try {
164-
const result = work();
165-
try {
166-
this.db.exec('COMMIT');
167-
} catch (error) {
168-
if (this.db.isTransaction || !isWriteUnavailable(error) || !confirm?.()) throw error;
169-
}
170-
return result;
171-
} catch (e) {
172-
if (this.db.isTransaction) this.db.exec('ROLLBACK');
173-
throw e;
174-
}
175-
} finally {
176-
release?.();
177-
}
178-
}
179-
}

0 commit comments

Comments
 (0)