@waffle-os/runtime 0.0.156 → 0.0.157

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 (75) hide show
  1. package/browser/filesystem-backend.ts +11 -1
  2. package/browser/preview-protocol.ts +2 -0
  3. package/browser/preview.ts +128 -18
  4. package/browser/runtime-terminals.ts +65 -24
  5. package/browser/shared-fs.ts +141 -14
  6. package/browser/worker.ts +73 -6
  7. package/core/descriptors.ts +19 -2
  8. package/core/devices.ts +237 -2
  9. package/core/fd-reopen.ts +105 -20
  10. package/core/filesystem.ts +71 -0
  11. package/core/index.ts +4 -0
  12. package/core/open-file.ts +212 -18
  13. package/core/wasi.ts +397 -46
  14. package/dist/browser/filesystem-backend.js +4 -2
  15. package/dist/browser/preview.js +120 -17
  16. package/dist/browser/runtime-terminals.js +53 -10
  17. package/dist/browser/shared-fs.js +124 -11
  18. package/dist/browser/worker.js +59 -6
  19. package/dist/core/descriptors.js +9 -1
  20. package/dist/core/devices.js +211 -1
  21. package/dist/core/fd-reopen.js +79 -18
  22. package/dist/core/filesystem.js +13 -0
  23. package/dist/core/open-file.js +166 -13
  24. package/dist/core/wasi.js +353 -27
  25. package/dist/fs/backend.js +29 -2
  26. package/dist/fs/client.js +199 -6
  27. package/dist/fs/index.js +21 -1
  28. package/dist/fs/indexeddb.js +30 -2
  29. package/dist/fs/locks.js +1112 -0
  30. package/dist/fs/memory.js +109 -1
  31. package/dist/fs/multitab-backend.js +315 -195
  32. package/dist/fs/multitab-protocol.js +1 -0
  33. package/dist/fs/persistent.js +13 -6
  34. package/dist/fs/protocol.js +9 -3
  35. package/dist/fs/service.js +386 -22
  36. package/dist/fs/shared.js +54 -1
  37. package/dist/fs/storage-geometry.js +2 -0
  38. package/dist/interrupt/rewriter-internal.js +4 -1
  39. package/dist/proc/abi.js +80 -6
  40. package/dist/proc/errors.js +1 -0
  41. package/dist/proc/filesystem-codec.js +40 -9
  42. package/dist/proc/index.js +10 -1
  43. package/dist/proc/pty.js +193 -0
  44. package/dist/proc/worker-client.js +11 -2
  45. package/dist/proc/worker-pipes.js +51 -0
  46. package/dist/runtime.js +11 -2
  47. package/dist/search/engine.js +53 -0
  48. package/dist/tooling/program/program-transformer.json +1 -1
  49. package/fs/backend.ts +33 -1
  50. package/fs/client.ts +225 -6
  51. package/fs/index.ts +22 -1
  52. package/fs/indexeddb.ts +36 -2
  53. package/fs/locks.ts +1406 -0
  54. package/fs/memory.ts +114 -1
  55. package/fs/multitab-backend.ts +561 -303
  56. package/fs/multitab-protocol.ts +1 -0
  57. package/fs/persistent.ts +14 -3
  58. package/fs/protocol.ts +17 -5
  59. package/fs/service.ts +468 -23
  60. package/fs/shared.ts +60 -2
  61. package/fs/storage-geometry.ts +3 -0
  62. package/index.ts +2 -0
  63. package/interrupt/rewriter-internal.ts +4 -1
  64. package/package.json +2 -2
  65. package/proc/abi.ts +79 -6
  66. package/proc/errors.ts +1 -0
  67. package/proc/filesystem-codec.ts +39 -9
  68. package/proc/index.ts +11 -0
  69. package/proc/pty.ts +227 -0
  70. package/proc/worker-client.ts +28 -6
  71. package/proc/worker-pipes.ts +57 -0
  72. package/runtime.ts +12 -2
  73. package/search/engine.ts +49 -0
  74. package/testing/indexeddb-storage-browser.ts +173 -2
  75. package/tooling/program/program-transformer.json +1 -1
package/fs/locks.ts ADDED
@@ -0,0 +1,1406 @@
1
+ import {
2
+ F_RDLCK,
3
+ F_UNLCK,
4
+ F_WRLCK,
5
+ LOCK_EX,
6
+ LOCK_NB,
7
+ LOCK_SH,
8
+ LOCK_UN,
9
+ type FileLockConflict,
10
+ type FileLockRange,
11
+ } from "../core/filesystem.js";
12
+
13
+ const EACCES = 2;
14
+ const EAGAIN = 6;
15
+ const EDEADLK = 16;
16
+ const EINVAL = 28;
17
+ const ENOLCK = 46;
18
+ const OFD_FLAG_ORIGIN_CLOSED = 2;
19
+
20
+ const DEFAULT_MAX_RANGE_LOCKS = 4096;
21
+ const DEFAULT_MAX_FLOCKS = 4096;
22
+ const DEFAULT_MAX_WAITERS = 512;
23
+ const DEFAULT_MAX_PENDING_TRANSACTIONS = 256;
24
+
25
+ type FlockMode = "sh" | "ex";
26
+ type RangeType = typeof F_RDLCK | typeof F_WRLCK;
27
+ type PrevRangeType = FileLockRange["type"];
28
+
29
+ interface FlockEntry {
30
+ mode: FlockMode;
31
+ readonly ofdId: string;
32
+ opId: number;
33
+ }
34
+
35
+ interface RangeLock {
36
+ readonly owner: string;
37
+ readonly posixOwner: number | undefined;
38
+ readonly ofdId: string | undefined;
39
+ readonly pid: number;
40
+ type: RangeType;
41
+ start: number;
42
+ end: number;
43
+ opId: number;
44
+ }
45
+
46
+ interface RangeDeltaSegment {
47
+ readonly start: number;
48
+ readonly end: number;
49
+ readonly prevType: PrevRangeType;
50
+ prevOpId: number;
51
+ }
52
+
53
+ interface FlockOpRecord {
54
+ readonly ino: number;
55
+ readonly ofdId: string;
56
+ prevMode: FlockMode | undefined;
57
+ prevOpId: number;
58
+ }
59
+
60
+ interface RangeOpRecord {
61
+ readonly ino: number;
62
+ readonly owner: string;
63
+ delta: RangeDeltaSegment[];
64
+ reservedSlots: number;
65
+ }
66
+
67
+ interface Waiter {
68
+ readonly id: number;
69
+ readonly ino: number;
70
+ readonly owner: string;
71
+ readonly sessionOwner: number;
72
+ readonly blockers: readonly string[];
73
+ readonly trackDeadlock: boolean;
74
+ resolved: boolean;
75
+ readonly wake: () => void;
76
+ readonly cancel: () => void;
77
+ }
78
+
79
+ interface InodeLocks {
80
+ readonly flocks: Map<string, FlockEntry>;
81
+ ranges: RangeLock[];
82
+ waiters: Waiter[];
83
+ }
84
+
85
+ interface OfdReservation {
86
+ readonly targetOwner: number;
87
+ readonly state: Int32Array;
88
+ }
89
+
90
+ interface OfdRecord {
91
+ readonly ino: number;
92
+ readonly handle: number;
93
+ readonly ofdId: string;
94
+ readonly originOwner: number;
95
+ originClosed: boolean;
96
+ pendingOriginTransfer: boolean;
97
+ cells?: Int32Array;
98
+ readonly reservations: OfdReservation[];
99
+ }
100
+
101
+ /** Authoritative liveness callbacks supplied by FilesystemService when reaping shared OFDs. */
102
+ export interface OfdLiveness {
103
+ isSessionLive(sessionOwner: number): boolean;
104
+ hasPendingTransfer(sessionOwner: number, handle: number): boolean;
105
+ }
106
+
107
+ export interface LockTableOptions {
108
+ readonly maxRangeLocks?: number;
109
+ readonly maxFlocks?: number;
110
+ readonly maxWaiters?: number;
111
+ readonly maxPendingTransactions?: number;
112
+ readonly onPosixLockCountChange?: (count: number) => void;
113
+ }
114
+
115
+ export interface LockTableDiagnostics {
116
+ readonly inodes: number;
117
+ readonly flocks: number;
118
+ readonly ranges: number;
119
+ readonly posixRanges: number;
120
+ readonly waiters: number;
121
+ readonly ofdRecords: number;
122
+ readonly pendingTransactions: number;
123
+ }
124
+
125
+ export interface LockCommit {
126
+ readonly errno: number;
127
+ /** Undo this lock acquisition if the service reply is cancelled before the client consumes it. */
128
+ readonly rollback?: () => void;
129
+ /** Finalize this lock acquisition once the client consumes the reply so segments can coalesce. */
130
+ readonly settle?: () => void;
131
+ }
132
+
133
+ export class LockContentionError extends Error {
134
+ constructor(
135
+ readonly wait: Promise<void>,
136
+ readonly cancel: () => void,
137
+ ) {
138
+ super("advisory lock contended");
139
+ }
140
+ }
141
+
142
+ function normalizeFlockOp(operation: number): {
143
+ base: typeof LOCK_SH | typeof LOCK_EX | typeof LOCK_UN;
144
+ nonblocking: boolean;
145
+ } | null {
146
+ if (!Number.isInteger(operation) || operation < 0) return null;
147
+ if ((operation & ~(LOCK_SH | LOCK_EX | LOCK_NB | LOCK_UN)) !== 0) return null;
148
+ const nonblocking = (operation & LOCK_NB) !== 0;
149
+ const base = operation & ~LOCK_NB;
150
+ if (base !== LOCK_SH && base !== LOCK_EX && base !== LOCK_UN) return null;
151
+ return { base, nonblocking };
152
+ }
153
+
154
+ function parseOfdId(ofdId: string): { readonly owner: number; readonly seq: number } | null {
155
+ const colon = ofdId.indexOf(":");
156
+ if (colon <= 0 || colon === ofdId.length - 1) return null;
157
+ const ownerStr = ofdId.slice(0, colon);
158
+ const seqStr = ofdId.slice(colon + 1);
159
+ if (!/^(?:0|[1-9][0-9]*)$/.test(ownerStr) || !/^[1-9][0-9]*$/.test(seqStr)) return null;
160
+ const owner = Number(ownerStr);
161
+ const seq = Number(seqStr);
162
+ if (!Number.isSafeInteger(owner) || !Number.isSafeInteger(seq)) return null;
163
+ return { owner, seq };
164
+ }
165
+
166
+ function rangeEndOf(start: number, len: number): number {
167
+ if (!Number.isSafeInteger(start) || start < 0) return -1;
168
+ if (!Number.isSafeInteger(len) || len < 0) return -1;
169
+ if (len === 0) return Infinity;
170
+ const end = start + len;
171
+ return Number.isSafeInteger(end) ? end : -1;
172
+ }
173
+
174
+ function rangesOverlap(aStart: number, aEnd: number, bStart: number, bEnd: number): boolean {
175
+ return aStart < bEnd && bStart < aEnd;
176
+ }
177
+
178
+ function rangesConflict(aType: RangeType, bType: RangeType): boolean {
179
+ return aType === F_WRLCK || bType === F_WRLCK;
180
+ }
181
+
182
+ function flockConflicts(existing: FlockMode, requested: FlockMode): boolean {
183
+ return existing === "ex" || requested === "ex";
184
+ }
185
+
186
+ function posixOwnerKey(posixOwner: number): string {
187
+ return `p:${posixOwner}`;
188
+ }
189
+
190
+ function ofdOwnerKey(ofdId: string): string {
191
+ return `o:${ofdId}`;
192
+ }
193
+
194
+ function cloneRange(lock: RangeLock): RangeLock {
195
+ return {
196
+ owner: lock.owner,
197
+ posixOwner: lock.posixOwner,
198
+ ofdId: lock.ofdId,
199
+ pid: lock.pid,
200
+ type: lock.type,
201
+ start: lock.start,
202
+ end: lock.end,
203
+ opId: lock.opId,
204
+ };
205
+ }
206
+
207
+ function coalesceOwned(owned: readonly RangeLock[]): RangeLock[] {
208
+ const sorted = owned.toSorted((left, right) => left.start - right.start);
209
+ const merged: RangeLock[] = [];
210
+ for (let i = 0; i < sorted.length; i++) {
211
+ const current = sorted[i]!;
212
+ const prev = merged[merged.length - 1];
213
+ if (
214
+ prev &&
215
+ prev.type === current.type &&
216
+ prev.opId === current.opId &&
217
+ prev.end >= current.start
218
+ ) {
219
+ prev.end = Math.max(prev.end, current.end);
220
+ continue;
221
+ }
222
+ merged.push(cloneRange(current));
223
+ }
224
+ return merged;
225
+ }
226
+
227
+ function computeRangeDelta(
228
+ previousOwned: readonly RangeLock[],
229
+ start: number,
230
+ end: number,
231
+ ): RangeDeltaSegment[] {
232
+ const sorted = previousOwned.toSorted((left, right) => left.start - right.start);
233
+ const delta: RangeDeltaSegment[] = [];
234
+ let cursor = start;
235
+ for (let i = 0; i < sorted.length; i++) {
236
+ const entry = sorted[i]!;
237
+ if (entry.end <= cursor) continue;
238
+ if (entry.start >= end) break;
239
+ const ovStart = Math.max(entry.start, cursor);
240
+ const ovEnd = Math.min(entry.end, end);
241
+ if (ovStart > cursor)
242
+ delta.push({ start: cursor, end: ovStart, prevType: F_UNLCK, prevOpId: 0 });
243
+ delta.push({ start: ovStart, end: ovEnd, prevType: entry.type, prevOpId: entry.opId });
244
+ cursor = ovEnd;
245
+ }
246
+ if (cursor < end) delta.push({ start: cursor, end, prevType: F_UNLCK, prevOpId: 0 });
247
+ return delta;
248
+ }
249
+
250
+ function spliceDeltaSegment(
251
+ seg: RangeDeltaSegment,
252
+ cancelledDelta: readonly RangeDeltaSegment[],
253
+ out: RangeDeltaSegment[],
254
+ ): void {
255
+ let cursor = seg.start;
256
+ for (let i = 0; i < cancelledDelta.length; i++) {
257
+ const piece = cancelledDelta[i]!;
258
+ if (piece.end <= cursor) continue;
259
+ if (piece.start >= seg.end) break;
260
+ const ovStart = Math.max(cursor, piece.start);
261
+ const ovEnd = Math.min(seg.end, piece.end);
262
+ if (ovStart > cursor) out.push({ start: cursor, end: ovStart, prevType: F_UNLCK, prevOpId: 0 });
263
+ out.push({ start: ovStart, end: ovEnd, prevType: piece.prevType, prevOpId: piece.prevOpId });
264
+ cursor = ovEnd;
265
+ }
266
+ if (cursor < seg.end) out.push({ start: cursor, end: seg.end, prevType: F_UNLCK, prevOpId: 0 });
267
+ }
268
+
269
+ interface ByteInterval {
270
+ readonly start: number;
271
+ readonly end: number;
272
+ }
273
+
274
+ function addInterval(
275
+ map: Map<number, ByteInterval[]>,
276
+ opId: number,
277
+ start: number,
278
+ end: number,
279
+ ): void {
280
+ let list = map.get(opId);
281
+ if (!list) {
282
+ list = [];
283
+ map.set(opId, list);
284
+ }
285
+ list.push({ start, end });
286
+ }
287
+
288
+ function intersectDeltaWithIntervals(
289
+ delta: readonly RangeDeltaSegment[],
290
+ intervals: readonly ByteInterval[],
291
+ ): { readonly trimmed: RangeDeltaSegment[]; readonly reserve: number } {
292
+ // Keep incoming spans unmerged and reserve max(0, nonUnlock - 1) per span independently so
293
+ // an unlock-shrinking span under a newer pending op cannot subsidize growth on a live span.
294
+ const spans = intervals.toSorted((left, right) => left.start - right.start);
295
+ const trimmed: RangeDeltaSegment[] = [];
296
+ let reserve = 0;
297
+ for (let i = 0; i < spans.length; i++) {
298
+ const span = spans[i]!;
299
+ let nonUnlockInSpan = 0;
300
+ for (let j = 0; j < delta.length; j++) {
301
+ const piece = delta[j]!;
302
+ if (piece.end <= span.start) continue;
303
+ if (piece.start >= span.end) break;
304
+ if (piece.prevType !== F_UNLCK) nonUnlockInSpan += 1;
305
+ trimmed.push({
306
+ start: Math.max(span.start, piece.start),
307
+ end: Math.min(span.end, piece.end),
308
+ prevType: piece.prevType,
309
+ prevOpId: piece.prevOpId,
310
+ });
311
+ }
312
+ if (nonUnlockInSpan > 1) reserve += nonUnlockInSpan - 1;
313
+ }
314
+ return { trimmed, reserve };
315
+ }
316
+
317
+ function rollbackReserveForDelta(delta: readonly RangeDeltaSegment[]): number {
318
+ let nonUnlock = 0;
319
+ for (let i = 0; i < delta.length; i++) {
320
+ if (delta[i]!.prevType !== F_UNLCK) nonUnlock += 1;
321
+ }
322
+ return nonUnlock > 1 ? nonUnlock - 1 : 0;
323
+ }
324
+
325
+ function spliceRangeDelta(
326
+ targetDelta: readonly RangeDeltaSegment[],
327
+ cancelledOpId: number,
328
+ cancelledDelta: readonly RangeDeltaSegment[],
329
+ ): RangeDeltaSegment[] {
330
+ const out: RangeDeltaSegment[] = [];
331
+ for (let i = 0; i < targetDelta.length; i++) {
332
+ const seg = targetDelta[i]!;
333
+ if (seg.prevOpId !== cancelledOpId) {
334
+ out.push(seg);
335
+ continue;
336
+ }
337
+ spliceDeltaSegment(seg, cancelledDelta, out);
338
+ }
339
+ return out;
340
+ }
341
+
342
+ function editOwnerRanges(
343
+ ranges: readonly RangeLock[],
344
+ owner: string,
345
+ posixOwner: number | undefined,
346
+ ofdId: string | undefined,
347
+ pid: number,
348
+ type: FileLockRange["type"],
349
+ start: number,
350
+ end: number,
351
+ opId: number,
352
+ ): {
353
+ next: RangeLock[];
354
+ delta: RangeDeltaSegment[];
355
+ relaxed: boolean;
356
+ previousCount: number;
357
+ nextCount: number;
358
+ } {
359
+ const others: RangeLock[] = [];
360
+ const owned: RangeLock[] = [];
361
+ const previousOwned: RangeLock[] = [];
362
+ let relaxed = false;
363
+ for (let i = 0; i < ranges.length; i++) {
364
+ const entry = ranges[i]!;
365
+ if (entry.owner !== owner) {
366
+ others.push(entry);
367
+ continue;
368
+ }
369
+ previousOwned.push(entry);
370
+ if (!rangesOverlap(entry.start, entry.end, start, end)) {
371
+ owned.push(entry);
372
+ continue;
373
+ }
374
+ if (type === F_UNLCK || (entry.type === F_WRLCK && type === F_RDLCK)) relaxed = true;
375
+ if (entry.start < start) owned.push({ ...entry, end: start });
376
+ if (entry.end > end) owned.push({ ...entry, start: end });
377
+ }
378
+ const delta = type === F_UNLCK ? [] : computeRangeDelta(previousOwned, start, end);
379
+ if (type !== F_UNLCK) owned.push({ owner, posixOwner, ofdId, pid, type, start, end, opId });
380
+ const coalesced = coalesceOwned(owned);
381
+ return {
382
+ next: others.concat(coalesced),
383
+ delta,
384
+ relaxed,
385
+ previousCount: previousOwned.length,
386
+ nextCount: coalesced.length,
387
+ };
388
+ }
389
+
390
+ /** Inode-keyed advisory lock table implementing Linux/gVisor flock(2) and POSIX/OFD fcntl(2). */
391
+ export class LockTable {
392
+ private readonly byIno = new Map<number, InodeLocks>();
393
+ private readonly posixInos = new Map<number, Set<number>>();
394
+ private readonly ofdRecords = new Map<string, OfdRecord>();
395
+ private readonly ownerOfds = new Map<number, Set<string>>();
396
+ private readonly waitingOn = new Map<string, Set<string>>();
397
+ private readonly deadlockWaiters = new Map<string, Set<Waiter>>();
398
+ private readonly waitersBySession = new Map<number, Set<Waiter>>();
399
+ private readonly pendingOps = new Set<number>();
400
+ private readonly flockOpPrev = new Map<number, FlockOpRecord>();
401
+ private readonly rangeOpDeltas = new Map<number, RangeOpRecord>();
402
+ private readonly maxRangeLocks: number;
403
+ private readonly maxFlocks: number;
404
+ private readonly maxWaiters: number;
405
+ private readonly maxPendingTransactions: number;
406
+ private readonly onPosixLockCountChange?: (count: number) => void;
407
+ private totalRangeLocks = 0;
408
+ private reservedRangeRollbackSlots = 0;
409
+ private totalPosixRangeLocks = 0;
410
+ private totalFlocks = 0;
411
+ private totalWaiters = 0;
412
+ private nextWaiterId = 1;
413
+ private nextOpId = 1;
414
+
415
+ constructor(options: LockTableOptions = {}) {
416
+ this.maxRangeLocks = options.maxRangeLocks ?? DEFAULT_MAX_RANGE_LOCKS;
417
+ this.maxFlocks = options.maxFlocks ?? DEFAULT_MAX_FLOCKS;
418
+ this.maxWaiters = options.maxWaiters ?? DEFAULT_MAX_WAITERS;
419
+ this.maxPendingTransactions =
420
+ options.maxPendingTransactions ?? DEFAULT_MAX_PENDING_TRANSACTIONS;
421
+ this.onPosixLockCountChange = options.onPosixLockCountChange;
422
+ }
423
+
424
+ hasActivePosixLocks(): boolean {
425
+ return this.totalPosixRangeLocks > 0;
426
+ }
427
+
428
+ diagnostics(): LockTableDiagnostics {
429
+ return {
430
+ inodes: this.byIno.size,
431
+ flocks: this.totalFlocks,
432
+ ranges: this.totalRangeLocks,
433
+ posixRanges: this.totalPosixRangeLocks,
434
+ waiters: this.totalWaiters,
435
+ ofdRecords: this.ofdRecords.size,
436
+ pendingTransactions: this.pendingOps.size,
437
+ };
438
+ }
439
+
440
+ /** Register an adopted inherited file description reservation so OFD lock lifetimes track it. */
441
+ adoptReservation(
442
+ ino: number,
443
+ handle: number,
444
+ ofdId: string,
445
+ originOwner: number,
446
+ ofdBuffer: SharedArrayBuffer,
447
+ targetOwner: number,
448
+ reservationState: SharedArrayBuffer,
449
+ ): void {
450
+ const existing = this.ofdRecords.get(ofdId);
451
+ if (existing && existing.ino !== ino) return;
452
+ const record = this.ensureOfdRecord(ino, handle, ofdId, originOwner);
453
+ record.cells ??= new Int32Array(ofdBuffer);
454
+ this.indexOwnerOfd(originOwner, ofdId);
455
+ const state = new Int32Array(reservationState);
456
+ if (Atomics.load(state, 0) === 0) {
457
+ record.reservations.push({ targetOwner, state });
458
+ this.indexOwnerOfd(targetOwner, ofdId);
459
+ }
460
+ }
461
+
462
+ flock(
463
+ ino: number,
464
+ ofdId: string,
465
+ sessionOwner: number,
466
+ operation: number,
467
+ allowWait = false,
468
+ handle = 0,
469
+ trackTransaction = allowWait,
470
+ ): LockCommit {
471
+ const parsed = normalizeFlockOp(operation);
472
+ if (!parsed) return { errno: EINVAL };
473
+ if (!this.isAuthorizedOfd(sessionOwner, ofdId, ino)) return { errno: EACCES };
474
+ if (parsed.base === LOCK_UN) {
475
+ this.removeFlock(ino, ofdId);
476
+ return { errno: 0 };
477
+ }
478
+ const mode: FlockMode = parsed.base === LOCK_EX ? "ex" : "sh";
479
+ const prior = this.byIno.get(ino)?.flocks.get(ofdId);
480
+ const previousMode = prior?.mode;
481
+ const previousOpId = prior?.opId ?? 0;
482
+ const converting = prior !== undefined && prior.mode !== mode;
483
+ // Per Linux fs/locks.c (flock_lock_inode), converting between LOCK_SH and LOCK_EX drops the
484
+ // existing lock before checking contention, even when LOCK_NB is set.
485
+ if (converting) this.detachFlockEntry(ino, ofdId);
486
+ const detachedOpId = converting ? previousOpId : 0;
487
+ const inode = this.byIno.get(ino);
488
+ const existing = inode?.flocks.get(ofdId);
489
+ const blockers = inode ? this.flockBlockers(inode, ofdId, mode) : [];
490
+ if (blockers.length > 0) {
491
+ this.discardFlockChain(detachedOpId);
492
+ if (parsed.nonblocking || !allowWait) return { errno: EAGAIN };
493
+ if (this.totalWaiters >= this.maxWaiters) return { errno: ENOLCK };
494
+ throw this.enqueueWaiter(ino, ofdOwnerKey(ofdId), sessionOwner, blockers, false);
495
+ }
496
+ if (
497
+ (!existing && this.totalFlocks >= this.maxFlocks) ||
498
+ (trackTransaction && this.pendingOps.size >= this.maxPendingTransactions)
499
+ ) {
500
+ this.discardFlockChain(detachedOpId);
501
+ return { errno: ENOLCK };
502
+ }
503
+ const originOwner = parseOfdId(ofdId)?.owner ?? sessionOwner;
504
+ this.ensureOfdRecord(ino, handle, ofdId, originOwner);
505
+ this.indexOwnerOfd(sessionOwner, ofdId);
506
+ return this.installFlock(
507
+ ino,
508
+ ofdId,
509
+ mode,
510
+ existing,
511
+ previousMode,
512
+ previousOpId,
513
+ trackTransaction,
514
+ );
515
+ }
516
+
517
+ releaseOfd(
518
+ ino: number,
519
+ ofdId: string,
520
+ sessionOwner?: number,
521
+ liveness?: OfdLiveness,
522
+ inFlight = false,
523
+ ): void {
524
+ if (sessionOwner !== undefined && !this.isAuthorizedOfd(sessionOwner, ofdId, ino)) return;
525
+ const record = this.ofdRecords.get(ofdId);
526
+ if (!record || !liveness) {
527
+ this.dropOfdLocks(ino, ofdId);
528
+ if (record) this.deleteOfdRecord(record);
529
+ return;
530
+ }
531
+ if (sessionOwner !== undefined && sessionOwner === record.originOwner) {
532
+ record.originClosed = true;
533
+ record.pendingOriginTransfer = inFlight;
534
+ }
535
+ if (!this.isOfdAlive(record, liveness)) {
536
+ this.dropOfdLocks(record.ino, ofdId);
537
+ this.deleteOfdRecord(record);
538
+ }
539
+ }
540
+
541
+ /** Reap any tracked OFDs whose origin, adopted reservations, and pending transfers are gone. */
542
+ reapOfds(liveness: OfdLiveness, ofdIds?: Iterable<string>): void {
543
+ const candidates = ofdIds ? Array.from(ofdIds) : Array.from(this.ofdRecords.keys());
544
+ for (let i = 0; i < candidates.length; i++) {
545
+ const ofdId = candidates[i]!;
546
+ const record = this.ofdRecords.get(ofdId);
547
+ if (!record || this.isOfdAlive(record, liveness)) continue;
548
+ this.dropOfdLocks(record.ino, ofdId);
549
+ this.deleteOfdRecord(record);
550
+ }
551
+ }
552
+
553
+ setRangeLock(
554
+ ino: number,
555
+ ofdId: string | undefined,
556
+ sessionOwner: number,
557
+ pid: number,
558
+ range: FileLockRange,
559
+ blocking: boolean,
560
+ allowWait = false,
561
+ handle = 0,
562
+ posixOwner = sessionOwner,
563
+ trackTransaction = allowWait,
564
+ ): LockCommit {
565
+ if (range.type !== F_RDLCK && range.type !== F_WRLCK && range.type !== F_UNLCK)
566
+ return { errno: EINVAL };
567
+ const end = rangeEndOf(range.start, range.len);
568
+ if (end < 0) return { errno: EINVAL };
569
+ if (ofdId !== undefined && !this.isAuthorizedOfd(sessionOwner, ofdId, ino))
570
+ return { errno: EACCES };
571
+ const effectivePosixOwner = ofdId === undefined ? posixOwner : undefined;
572
+ const owner = ofdId === undefined ? posixOwnerKey(posixOwner) : ofdOwnerKey(ofdId);
573
+ const inode = this.byIno.get(ino);
574
+ if (range.type === F_UNLCK)
575
+ return this.unlockRange(ino, inode, owner, effectivePosixOwner, ofdId, pid, range.start, end);
576
+ const blockers = inode ? this.rangeBlockers(inode, owner, range.type, range.start, end) : [];
577
+ if (blockers.length > 0) {
578
+ if (!blocking || !allowWait) return { errno: EAGAIN };
579
+ const trackDeadlock = ofdId === undefined;
580
+ if (trackDeadlock && this.wouldDeadlock(owner, blockers)) return { errno: EDEADLK };
581
+ if (this.totalWaiters >= this.maxWaiters) return { errno: ENOLCK };
582
+ throw this.enqueueWaiter(ino, owner, sessionOwner, blockers, trackDeadlock);
583
+ }
584
+ return this.installRangeLock(
585
+ ino,
586
+ owner,
587
+ sessionOwner,
588
+ effectivePosixOwner,
589
+ ofdId,
590
+ pid,
591
+ range.type,
592
+ range.start,
593
+ end,
594
+ handle,
595
+ trackTransaction,
596
+ );
597
+ }
598
+
599
+ getRangeLock(
600
+ ino: number,
601
+ ofdId: string | undefined,
602
+ sessionOwner: number,
603
+ range: FileLockRange,
604
+ posixOwner = sessionOwner,
605
+ ): FileLockConflict | number {
606
+ // Per Linux/FreeBSD/gVisor fcntl(2), F_GETLK/F_OFD_GETLK requires F_RDLCK or F_WRLCK.
607
+ if (range.type !== F_RDLCK && range.type !== F_WRLCK) return EINVAL;
608
+ const end = rangeEndOf(range.start, range.len);
609
+ if (end < 0) return EINVAL;
610
+ if (ofdId !== undefined && !this.isAuthorizedOfd(sessionOwner, ofdId, ino)) return EACCES;
611
+ const clear: FileLockConflict = { type: F_UNLCK, pid: 0, start: 0, len: 0 };
612
+ const inode = this.byIno.get(ino);
613
+ if (!inode) return clear;
614
+ const owner = ofdId === undefined ? posixOwnerKey(posixOwner) : ofdOwnerKey(ofdId);
615
+ for (let i = 0; i < inode.ranges.length; i++) {
616
+ const entry = inode.ranges[i]!;
617
+ if (entry.owner === owner) continue;
618
+ if (!rangesConflict(entry.type, range.type)) continue;
619
+ if (!rangesOverlap(entry.start, entry.end, range.start, end)) continue;
620
+ return {
621
+ type: entry.type,
622
+ pid: entry.ofdId === undefined ? entry.pid : -1,
623
+ start: entry.start,
624
+ len: entry.end === Infinity ? 0 : entry.end - entry.start,
625
+ };
626
+ }
627
+ return clear;
628
+ }
629
+
630
+ releasePosix(ino: number, posixOwner: number): void {
631
+ this.unindexPosixIno(posixOwner, ino);
632
+ const owner = posixOwnerKey(posixOwner);
633
+ this.discardOwnerRangeOps(ino, owner);
634
+ const inode = this.byIno.get(ino);
635
+ if (!inode) return;
636
+ const before = inode.ranges.length;
637
+ inode.ranges = inode.ranges.filter((entry) => entry.owner !== owner);
638
+ const removed = before - inode.ranges.length;
639
+ if (removed > 0) {
640
+ this.adjustRangeCounts(-removed, -removed);
641
+ this.wakeInode(ino, inode);
642
+ }
643
+ this.pruneInode(ino, inode);
644
+ }
645
+
646
+ /** Release all POSIX byte-range locks owned by a logical process across all inodes. */
647
+ releasePosixOwner(posixOwner: number): void {
648
+ const inos = this.posixInos.get(posixOwner);
649
+ if (!inos) return;
650
+ this.posixInos.delete(posixOwner);
651
+ for (const ino of Array.from(inos)) this.releasePosix(ino, posixOwner);
652
+ }
653
+
654
+ releaseSession(
655
+ sessionOwner: number,
656
+ liveness?: OfdLiveness,
657
+ posixOwner = sessionOwner,
658
+ releasePosix = true,
659
+ ): void {
660
+ const waiters = this.waitersBySession.get(sessionOwner);
661
+ if (waiters) {
662
+ for (const waiter of Array.from(waiters)) waiter.cancel();
663
+ this.waitersBySession.delete(sessionOwner);
664
+ }
665
+ if (releasePosix) this.releasePosixOwner(posixOwner);
666
+ const ofds = this.ownerOfds.get(sessionOwner);
667
+ if (!ofds) return;
668
+ const snapshot = Array.from(ofds);
669
+ this.ownerOfds.delete(sessionOwner);
670
+ const effectiveLiveness: OfdLiveness = liveness ?? {
671
+ isSessionLive: (owner) => owner !== sessionOwner,
672
+ hasPendingTransfer: () => false,
673
+ };
674
+ this.reapOfds(effectiveLiveness, snapshot);
675
+ }
676
+
677
+ dispose(): void {
678
+ for (const inode of Array.from(this.byIno.values())) {
679
+ for (const waiter of inode.waiters.slice()) waiter.cancel();
680
+ }
681
+ this.byIno.clear();
682
+ this.posixInos.clear();
683
+ this.ofdRecords.clear();
684
+ this.ownerOfds.clear();
685
+ this.waitingOn.clear();
686
+ this.deadlockWaiters.clear();
687
+ this.waitersBySession.clear();
688
+ this.pendingOps.clear();
689
+ this.flockOpPrev.clear();
690
+ this.rangeOpDeltas.clear();
691
+ this.totalRangeLocks = 0;
692
+ this.reservedRangeRollbackSlots = 0;
693
+ this.totalFlocks = 0;
694
+ this.totalWaiters = 0;
695
+ this.setPosixRangeCount(0);
696
+ }
697
+
698
+ private setPosixRangeCount(next: number): void {
699
+ if (this.totalPosixRangeLocks === next) return;
700
+ this.totalPosixRangeLocks = next;
701
+ this.onPosixLockCountChange?.(next);
702
+ }
703
+
704
+ private adjustRangeCounts(totalDelta: number, posixDelta: number): void {
705
+ this.totalRangeLocks += totalDelta;
706
+ if (posixDelta !== 0) this.setPosixRangeCount(this.totalPosixRangeLocks + posixDelta);
707
+ }
708
+
709
+ private isAuthorizedOfd(sessionOwner: number, ofdId: string, ino: number): boolean {
710
+ const existing = this.ofdRecords.get(ofdId);
711
+ if (existing && existing.ino !== ino) return false;
712
+ if (sessionOwner === 0) return ofdId.length > 0;
713
+ const parsed = parseOfdId(ofdId);
714
+ if (!parsed) return false;
715
+ if (parsed.owner === sessionOwner) return true;
716
+ return this.ownerOfds.get(sessionOwner)?.has(ofdId) === true;
717
+ }
718
+
719
+ private unlockRange(
720
+ ino: number,
721
+ inode: InodeLocks | undefined,
722
+ owner: string,
723
+ posixOwner: number | undefined,
724
+ ofdId: string | undefined,
725
+ pid: number,
726
+ start: number,
727
+ end: number,
728
+ ): LockCommit {
729
+ if (!inode) return { errno: 0 };
730
+ const edited = editOwnerRanges(
731
+ inode.ranges,
732
+ owner,
733
+ posixOwner,
734
+ ofdId,
735
+ pid,
736
+ F_UNLCK,
737
+ start,
738
+ end,
739
+ 0,
740
+ );
741
+ const deltaCount = edited.nextCount - edited.previousCount;
742
+ if (
743
+ deltaCount > 0 &&
744
+ this.totalRangeLocks + this.reservedRangeRollbackSlots + deltaCount > this.maxRangeLocks
745
+ )
746
+ return { errno: ENOLCK };
747
+ inode.ranges = edited.next;
748
+ this.adjustRangeCounts(deltaCount, posixOwner !== undefined ? deltaCount : 0);
749
+ if (posixOwner !== undefined && edited.nextCount === 0) this.unindexPosixIno(posixOwner, ino);
750
+ this.recomputeOwnerRangeReserves(ino, owner, inode);
751
+ if (edited.relaxed) this.wakeInode(ino, inode);
752
+ this.pruneInode(ino, inode);
753
+ return { errno: 0 };
754
+ }
755
+
756
+ private isOfdAlive(record: OfdRecord, liveness: OfdLiveness): boolean {
757
+ let writeIndex = 0;
758
+ let dropped: number[] | undefined;
759
+ for (let i = 0; i < record.reservations.length; i++) {
760
+ const entry = record.reservations[i]!;
761
+ if (Atomics.load(entry.state, 0) !== 0 || !liveness.isSessionLive(entry.targetOwner)) {
762
+ (dropped ??= []).push(entry.targetOwner);
763
+ continue;
764
+ }
765
+ record.reservations[writeIndex++] = entry;
766
+ }
767
+ record.reservations.length = writeIndex;
768
+ if (dropped) this.pruneDroppedOwners(record, dropped);
769
+ if (writeIndex > 0) return true;
770
+ const originClosed =
771
+ record.originClosed ||
772
+ (record.cells !== undefined &&
773
+ (Atomics.load(record.cells, 7) & OFD_FLAG_ORIGIN_CLOSED) !== 0);
774
+ if (!originClosed && liveness.isSessionLive(record.originOwner)) return true;
775
+ if (record.cells !== undefined) return Atomics.load(record.cells, 6) > 0;
776
+ if (record.originClosed) {
777
+ return (
778
+ record.pendingOriginTransfer &&
779
+ liveness.hasPendingTransfer(record.originOwner, record.handle)
780
+ );
781
+ }
782
+ return liveness.hasPendingTransfer(record.originOwner, record.handle);
783
+ }
784
+
785
+ private pruneDroppedOwners(record: OfdRecord, dropped: readonly number[]): void {
786
+ for (let i = 0; i < dropped.length; i++) {
787
+ const owner = dropped[i]!;
788
+ if (owner === record.originOwner) continue;
789
+ if (record.reservations.some((res) => res.targetOwner === owner)) continue;
790
+ this.unindexOwnerOfd(owner, record.ofdId);
791
+ }
792
+ }
793
+
794
+ private dropOfdLocks(ino: number, ofdId: string): void {
795
+ const key = ofdOwnerKey(ofdId);
796
+ this.discardOwnerRangeOps(ino, key);
797
+ const inode = this.byIno.get(ino);
798
+ if (!inode) return;
799
+ let changed = false;
800
+ const flock = inode.flocks.get(ofdId);
801
+ if (flock) {
802
+ inode.flocks.delete(ofdId);
803
+ this.totalFlocks -= 1;
804
+ if (flock.opId !== 0) this.discardFlockChain(flock.opId);
805
+ changed = true;
806
+ }
807
+ const before = inode.ranges.length;
808
+ inode.ranges = inode.ranges.filter((entry) => entry.owner !== key);
809
+ const removed = before - inode.ranges.length;
810
+ if (removed > 0) {
811
+ this.adjustRangeCounts(-removed, 0);
812
+ changed = true;
813
+ }
814
+ if (changed) this.wakeInode(ino, inode);
815
+ this.pruneInode(ino, inode);
816
+ }
817
+
818
+ private ensureOfdRecord(
819
+ ino: number,
820
+ handle: number,
821
+ ofdId: string,
822
+ originOwner: number,
823
+ ): OfdRecord {
824
+ let record = this.ofdRecords.get(ofdId);
825
+ if (!record) {
826
+ record = {
827
+ ino,
828
+ handle,
829
+ ofdId,
830
+ originOwner,
831
+ originClosed: false,
832
+ pendingOriginTransfer: false,
833
+ reservations: [],
834
+ };
835
+ this.ofdRecords.set(ofdId, record);
836
+ this.indexOwnerOfd(originOwner, ofdId);
837
+ }
838
+ return record;
839
+ }
840
+
841
+ private deleteOfdRecord(record: OfdRecord): void {
842
+ this.ofdRecords.delete(record.ofdId);
843
+ this.unindexOwnerOfd(record.originOwner, record.ofdId);
844
+ for (let i = 0; i < record.reservations.length; i++)
845
+ this.unindexOwnerOfd(record.reservations[i]!.targetOwner, record.ofdId);
846
+ }
847
+
848
+ private indexOwnerOfd(sessionOwner: number, ofdId: string): void {
849
+ let set = this.ownerOfds.get(sessionOwner);
850
+ if (!set) {
851
+ set = new Set();
852
+ this.ownerOfds.set(sessionOwner, set);
853
+ }
854
+ set.add(ofdId);
855
+ }
856
+
857
+ private unindexOwnerOfd(sessionOwner: number, ofdId: string): void {
858
+ const set = this.ownerOfds.get(sessionOwner);
859
+ if (!set) return;
860
+ set.delete(ofdId);
861
+ if (set.size === 0) this.ownerOfds.delete(sessionOwner);
862
+ }
863
+
864
+ private ensureInode(ino: number): InodeLocks {
865
+ let inode = this.byIno.get(ino);
866
+ if (!inode) {
867
+ inode = { flocks: new Map(), ranges: [], waiters: [] };
868
+ this.byIno.set(ino, inode);
869
+ }
870
+ return inode;
871
+ }
872
+
873
+ private indexPosixIno(posixOwner: number, ino: number): void {
874
+ let set = this.posixInos.get(posixOwner);
875
+ if (!set) {
876
+ set = new Set();
877
+ this.posixInos.set(posixOwner, set);
878
+ }
879
+ set.add(ino);
880
+ }
881
+
882
+ private unindexPosixIno(posixOwner: number, ino: number): void {
883
+ const set = this.posixInos.get(posixOwner);
884
+ if (!set) return;
885
+ set.delete(ino);
886
+ if (set.size === 0) this.posixInos.delete(posixOwner);
887
+ }
888
+
889
+ private flockBlockers(inode: InodeLocks, ofdId: string, mode: FlockMode): string[] {
890
+ const blockers: string[] = [];
891
+ for (const entry of inode.flocks.values()) {
892
+ if (entry.ofdId === ofdId) continue;
893
+ if (flockConflicts(entry.mode, mode)) blockers.push(ofdOwnerKey(entry.ofdId));
894
+ }
895
+ return blockers;
896
+ }
897
+
898
+ private rangeBlockers(
899
+ inode: InodeLocks,
900
+ owner: string,
901
+ type: RangeType,
902
+ start: number,
903
+ end: number,
904
+ ): string[] {
905
+ const blockers = new Set<string>();
906
+ for (let i = 0; i < inode.ranges.length; i++) {
907
+ const entry = inode.ranges[i]!;
908
+ if (entry.owner === owner) continue;
909
+ if (!rangesConflict(entry.type, type)) continue;
910
+ if (rangesOverlap(entry.start, entry.end, start, end)) blockers.add(entry.owner);
911
+ }
912
+ return Array.from(blockers);
913
+ }
914
+
915
+ private discardFlockChain(opId: number): void {
916
+ let cursor = opId;
917
+ while (cursor !== 0) {
918
+ this.pendingOps.delete(cursor);
919
+ const record = this.flockOpPrev.get(cursor);
920
+ this.flockOpPrev.delete(cursor);
921
+ cursor = record?.prevOpId ?? 0;
922
+ }
923
+ }
924
+
925
+ private recomputeOwnerRangeReserves(
926
+ ino: number,
927
+ owner: string,
928
+ inode: InodeLocks | undefined,
929
+ ): void {
930
+ const liveIntervals = new Map<number, ByteInterval[]>();
931
+ if (inode) {
932
+ for (let i = 0; i < inode.ranges.length; i++) {
933
+ const entry = inode.ranges[i]!;
934
+ if (entry.owner !== owner || entry.opId === 0) continue;
935
+ addInterval(liveIntervals, entry.opId, entry.start, entry.end);
936
+ }
937
+ }
938
+ const ownerOps: number[] = [];
939
+ for (const [opId, record] of this.rangeOpDeltas) {
940
+ if (record.ino === ino && record.owner === owner) ownerOps.push(opId);
941
+ }
942
+ ownerOps.sort((left, right) => right - left);
943
+ for (let i = 0; i < ownerOps.length; i++) {
944
+ const opId = ownerOps[i]!;
945
+ const record = this.rangeOpDeltas.get(opId)!;
946
+ const spans = liveIntervals.get(opId);
947
+ const intersected = spans ? intersectDeltaWithIntervals(record.delta, spans) : undefined;
948
+ if (!intersected || intersected.trimmed.length === 0) {
949
+ this.reservedRangeRollbackSlots -= record.reservedSlots;
950
+ this.rangeOpDeltas.delete(opId);
951
+ this.pendingOps.delete(opId);
952
+ continue;
953
+ }
954
+ record.delta = intersected.trimmed;
955
+ for (let j = 0; j < intersected.trimmed.length; j++) {
956
+ const piece = intersected.trimmed[j]!;
957
+ if (piece.prevOpId !== 0)
958
+ addInterval(liveIntervals, piece.prevOpId, piece.start, piece.end);
959
+ }
960
+ this.reservedRangeRollbackSlots += intersected.reserve - record.reservedSlots;
961
+ record.reservedSlots = intersected.reserve;
962
+ }
963
+ }
964
+
965
+ private discardOwnerRangeOps(ino: number, owner: string): void {
966
+ for (const [opId, record] of this.rangeOpDeltas) {
967
+ if (record.ino !== ino || record.owner !== owner) continue;
968
+ this.reservedRangeRollbackSlots -= record.reservedSlots;
969
+ this.rangeOpDeltas.delete(opId);
970
+ this.pendingOps.delete(opId);
971
+ }
972
+ }
973
+
974
+ private detachFlockEntry(ino: number, ofdId: string): void {
975
+ const inode = this.byIno.get(ino);
976
+ const existing = inode?.flocks.get(ofdId);
977
+ if (!inode || !existing) return;
978
+ inode.flocks.delete(ofdId);
979
+ this.totalFlocks -= 1;
980
+ this.wakeInode(ino, inode);
981
+ this.pruneInode(ino, inode);
982
+ }
983
+
984
+ private installFlock(
985
+ ino: number,
986
+ ofdId: string,
987
+ mode: FlockMode,
988
+ existing: FlockEntry | undefined,
989
+ previousMode: FlockMode | undefined,
990
+ previousOpId: number,
991
+ trackTransaction: boolean,
992
+ ): LockCommit {
993
+ const inode = this.ensureInode(ino);
994
+ const opId = trackTransaction ? this.nextOpId++ : 0;
995
+ if (!trackTransaction && previousOpId !== 0) this.discardFlockChain(previousOpId);
996
+ if (existing) {
997
+ existing.mode = mode;
998
+ existing.opId = opId;
999
+ } else {
1000
+ inode.flocks.set(ofdId, { mode, ofdId, opId });
1001
+ this.totalFlocks += 1;
1002
+ }
1003
+ if (!trackTransaction) return { errno: 0 };
1004
+ this.pendingOps.add(opId);
1005
+ this.flockOpPrev.set(opId, { ino, ofdId, prevMode: previousMode, prevOpId: previousOpId });
1006
+ return {
1007
+ errno: 0,
1008
+ rollback: () => this.rollbackFlock(ino, ofdId, opId),
1009
+ settle: () => this.settleFlock(ino, ofdId, opId),
1010
+ };
1011
+ }
1012
+
1013
+ private settleFlock(ino: number, ofdId: string, opId: number): void {
1014
+ if (!this.pendingOps.delete(opId)) return;
1015
+ this.flockOpPrev.delete(opId);
1016
+ const current = this.byIno.get(ino)?.flocks.get(ofdId);
1017
+ if (current && current.opId === opId) current.opId = 0;
1018
+ for (const record of this.flockOpPrev.values()) {
1019
+ if (record.prevOpId === opId) record.prevOpId = 0;
1020
+ }
1021
+ }
1022
+
1023
+ private rollbackFlock(ino: number, ofdId: string, opId: number): void {
1024
+ if (!this.pendingOps.delete(opId)) return;
1025
+ const myPrev = this.flockOpPrev.get(opId);
1026
+ this.flockOpPrev.delete(opId);
1027
+ if (!myPrev) return;
1028
+ for (const record of this.flockOpPrev.values()) {
1029
+ if (record.prevOpId !== opId) continue;
1030
+ record.prevMode = myPrev.prevMode;
1031
+ record.prevOpId = myPrev.prevOpId;
1032
+ }
1033
+ const inode = this.byIno.get(ino);
1034
+ const current = inode?.flocks.get(ofdId);
1035
+ if (!inode || !current || current.opId !== opId) return;
1036
+ if (myPrev.prevMode === undefined) {
1037
+ inode.flocks.delete(ofdId);
1038
+ this.totalFlocks -= 1;
1039
+ this.wakeInode(ino, inode);
1040
+ this.pruneInode(ino, inode);
1041
+ return;
1042
+ }
1043
+ if (this.flockBlockers(inode, ofdId, myPrev.prevMode).length > 0) {
1044
+ current.opId = myPrev.prevOpId;
1045
+ return;
1046
+ }
1047
+ current.mode = myPrev.prevMode;
1048
+ current.opId = myPrev.prevOpId;
1049
+ this.wakeInode(ino, inode);
1050
+ }
1051
+
1052
+ private removeFlock(ino: number, ofdId: string): void {
1053
+ const inode = this.byIno.get(ino);
1054
+ const existing = inode?.flocks.get(ofdId);
1055
+ if (!inode || !existing) return;
1056
+ inode.flocks.delete(ofdId);
1057
+ this.totalFlocks -= 1;
1058
+ if (existing.opId !== 0) this.discardFlockChain(existing.opId);
1059
+ this.wakeInode(ino, inode);
1060
+ this.pruneInode(ino, inode);
1061
+ }
1062
+
1063
+ private installRangeLock(
1064
+ ino: number,
1065
+ owner: string,
1066
+ sessionOwner: number,
1067
+ posixOwner: number | undefined,
1068
+ ofdId: string | undefined,
1069
+ pid: number,
1070
+ type: RangeType,
1071
+ start: number,
1072
+ end: number,
1073
+ handle: number,
1074
+ trackTransaction: boolean,
1075
+ ): LockCommit {
1076
+ const existingInode = this.byIno.get(ino);
1077
+ const opId = trackTransaction ? this.nextOpId++ : 0;
1078
+ const edited = editOwnerRanges(
1079
+ existingInode?.ranges ?? [],
1080
+ owner,
1081
+ posixOwner,
1082
+ ofdId,
1083
+ pid,
1084
+ type,
1085
+ start,
1086
+ end,
1087
+ opId,
1088
+ );
1089
+ const deltaCount = edited.nextCount - edited.previousCount;
1090
+ const reservedSlots = trackTransaction ? rollbackReserveForDelta(edited.delta) : 0;
1091
+ if (
1092
+ this.totalRangeLocks + this.reservedRangeRollbackSlots + deltaCount + reservedSlots >
1093
+ this.maxRangeLocks
1094
+ )
1095
+ return { errno: ENOLCK };
1096
+ if (trackTransaction && this.pendingOps.size >= this.maxPendingTransactions)
1097
+ return { errno: ENOLCK };
1098
+ if (ofdId !== undefined) {
1099
+ const originOwner = parseOfdId(ofdId)?.owner ?? sessionOwner;
1100
+ this.ensureOfdRecord(ino, handle, ofdId, originOwner);
1101
+ this.indexOwnerOfd(sessionOwner, ofdId);
1102
+ }
1103
+ const inode = existingInode ?? this.ensureInode(ino);
1104
+ inode.ranges = edited.next;
1105
+ this.adjustRangeCounts(deltaCount, posixOwner !== undefined ? deltaCount : 0);
1106
+ if (posixOwner !== undefined) this.indexPosixIno(posixOwner, ino);
1107
+ if (edited.relaxed) this.wakeInode(ino, inode);
1108
+ if (!trackTransaction) {
1109
+ this.recomputeOwnerRangeReserves(ino, owner, inode);
1110
+ return { errno: 0 };
1111
+ }
1112
+ this.pendingOps.add(opId);
1113
+ this.reservedRangeRollbackSlots += reservedSlots;
1114
+ this.rangeOpDeltas.set(opId, { ino, owner, delta: edited.delta, reservedSlots });
1115
+ this.recomputeOwnerRangeReserves(ino, owner, inode);
1116
+ return {
1117
+ errno: 0,
1118
+ rollback: () => this.rollbackRange(ino, owner, posixOwner, ofdId, pid, opId),
1119
+ settle: () => this.settleRange(ino, owner, posixOwner, opId),
1120
+ };
1121
+ }
1122
+
1123
+ private clearSettledRangePrevOp(ino: number, owner: string, opId: number): void {
1124
+ for (const record of this.rangeOpDeltas.values()) {
1125
+ if (record.ino !== ino || record.owner !== owner) continue;
1126
+ for (let i = 0; i < record.delta.length; i++) {
1127
+ if (record.delta[i]!.prevOpId === opId) record.delta[i]!.prevOpId = 0;
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ private settleRange(
1133
+ ino: number,
1134
+ owner: string,
1135
+ posixOwner: number | undefined,
1136
+ opId: number,
1137
+ ): void {
1138
+ if (!this.pendingOps.delete(opId)) return;
1139
+ const record = this.rangeOpDeltas.get(opId);
1140
+ if (record) {
1141
+ this.reservedRangeRollbackSlots -= record.reservedSlots;
1142
+ this.rangeOpDeltas.delete(opId);
1143
+ }
1144
+ this.clearSettledRangePrevOp(ino, owner, opId);
1145
+ const inode = this.byIno.get(ino);
1146
+ if (!inode) return;
1147
+ const others: RangeLock[] = [];
1148
+ const owned: RangeLock[] = [];
1149
+ let touched = false;
1150
+ for (let i = 0; i < inode.ranges.length; i++) {
1151
+ const entry = inode.ranges[i]!;
1152
+ if (entry.owner !== owner) {
1153
+ others.push(entry);
1154
+ continue;
1155
+ }
1156
+ if (entry.opId === opId) {
1157
+ entry.opId = 0;
1158
+ touched = true;
1159
+ }
1160
+ owned.push(entry);
1161
+ }
1162
+ if (!touched) {
1163
+ this.recomputeOwnerRangeReserves(ino, owner, inode);
1164
+ return;
1165
+ }
1166
+ const coalesced = coalesceOwned(owned);
1167
+ const deltaCount = coalesced.length - owned.length;
1168
+ inode.ranges = others.concat(coalesced);
1169
+ if (deltaCount !== 0)
1170
+ this.adjustRangeCounts(deltaCount, posixOwner !== undefined ? deltaCount : 0);
1171
+ this.recomputeOwnerRangeReserves(ino, owner, inode);
1172
+ }
1173
+
1174
+ private rollbackRange(
1175
+ ino: number,
1176
+ owner: string,
1177
+ posixOwner: number | undefined,
1178
+ ofdId: string | undefined,
1179
+ pid: number,
1180
+ opId: number,
1181
+ ): void {
1182
+ if (!this.pendingOps.delete(opId)) return;
1183
+ const myRecord = this.rangeOpDeltas.get(opId);
1184
+ this.rangeOpDeltas.delete(opId);
1185
+ if (!myRecord) return;
1186
+ this.reservedRangeRollbackSlots -= myRecord.reservedSlots;
1187
+ for (const record of this.rangeOpDeltas.values()) {
1188
+ if (record.ino !== ino || record.owner !== owner) continue;
1189
+ record.delta = spliceRangeDelta(record.delta, opId, myRecord.delta);
1190
+ }
1191
+ const inode = this.byIno.get(ino);
1192
+ if (!inode) {
1193
+ this.recomputeOwnerRangeReserves(ino, owner, undefined);
1194
+ return;
1195
+ }
1196
+ const others: RangeLock[] = [];
1197
+ const keptOwned: RangeLock[] = [];
1198
+ const targetSegments: RangeLock[] = [];
1199
+ let previousCount = 0;
1200
+ for (let i = 0; i < inode.ranges.length; i++) {
1201
+ const entry = inode.ranges[i]!;
1202
+ if (entry.owner !== owner) {
1203
+ others.push(entry);
1204
+ continue;
1205
+ }
1206
+ previousCount += 1;
1207
+ if (entry.opId === opId) targetSegments.push(entry);
1208
+ else keptOwned.push(entry);
1209
+ }
1210
+ if (targetSegments.length === 0) {
1211
+ this.recomputeOwnerRangeReserves(ino, owner, inode);
1212
+ return;
1213
+ }
1214
+ let woke = false;
1215
+ for (let i = 0; i < targetSegments.length; i++) {
1216
+ const seg = targetSegments[i]!;
1217
+ if (
1218
+ this.applyDeltaToSegment(
1219
+ inode,
1220
+ seg,
1221
+ myRecord.delta,
1222
+ owner,
1223
+ posixOwner,
1224
+ ofdId,
1225
+ pid,
1226
+ keptOwned,
1227
+ )
1228
+ ) {
1229
+ woke = true;
1230
+ }
1231
+ }
1232
+ const coalesced = coalesceOwned(keptOwned);
1233
+ const deltaCount = coalesced.length - previousCount;
1234
+ inode.ranges = others.concat(coalesced);
1235
+ this.adjustRangeCounts(deltaCount, posixOwner !== undefined ? deltaCount : 0);
1236
+ if (posixOwner !== undefined && coalesced.length === 0) this.unindexPosixIno(posixOwner, ino);
1237
+ this.recomputeOwnerRangeReserves(ino, owner, inode);
1238
+ if (woke) this.wakeInode(ino, inode);
1239
+ this.pruneInode(ino, inode);
1240
+ }
1241
+
1242
+ private applyDeltaToSegment(
1243
+ inode: InodeLocks,
1244
+ seg: RangeLock,
1245
+ delta: readonly RangeDeltaSegment[],
1246
+ owner: string,
1247
+ posixOwner: number | undefined,
1248
+ ofdId: string | undefined,
1249
+ pid: number,
1250
+ out: RangeLock[],
1251
+ ): boolean {
1252
+ let woke = false;
1253
+ for (let j = 0; j < delta.length; j++) {
1254
+ const piece = delta[j]!;
1255
+ if (piece.end <= seg.start) continue;
1256
+ if (piece.start >= seg.end) break;
1257
+ const start = Math.max(seg.start, piece.start);
1258
+ const end = Math.min(seg.end, piece.end);
1259
+ if (piece.prevType === F_UNLCK) {
1260
+ woke = true;
1261
+ continue;
1262
+ }
1263
+ if (piece.prevType === F_RDLCK) {
1264
+ if (seg.type === F_WRLCK) woke = true;
1265
+ out.push({
1266
+ owner,
1267
+ posixOwner,
1268
+ ofdId,
1269
+ pid,
1270
+ type: F_RDLCK,
1271
+ start,
1272
+ end,
1273
+ opId: piece.prevOpId,
1274
+ });
1275
+ continue;
1276
+ }
1277
+ const canRestoreWrite = this.rangeBlockers(inode, owner, F_WRLCK, start, end).length === 0;
1278
+ const restoredType: RangeType = canRestoreWrite ? F_WRLCK : F_RDLCK;
1279
+ out.push({
1280
+ owner,
1281
+ posixOwner,
1282
+ ofdId,
1283
+ pid,
1284
+ type: restoredType,
1285
+ start,
1286
+ end,
1287
+ opId: piece.prevOpId,
1288
+ });
1289
+ }
1290
+ return woke;
1291
+ }
1292
+
1293
+ private wouldDeadlock(waiterOwner: string, blockers: readonly string[]): boolean {
1294
+ const visited = new Set<string>();
1295
+ const stack = blockers.slice();
1296
+ while (stack.length > 0) {
1297
+ const current = stack.pop()!;
1298
+ if (current === waiterOwner) return true;
1299
+ if (visited.has(current)) continue;
1300
+ visited.add(current);
1301
+ const next = this.waitingOn.get(current);
1302
+ if (!next) continue;
1303
+ for (const target of next) stack.push(target);
1304
+ }
1305
+ return false;
1306
+ }
1307
+
1308
+ private enqueueWaiter(
1309
+ ino: number,
1310
+ owner: string,
1311
+ sessionOwner: number,
1312
+ blockers: readonly string[],
1313
+ trackDeadlock: boolean,
1314
+ ): LockContentionError {
1315
+ const inode = this.ensureInode(ino);
1316
+ const deferred = Promise.withResolvers<void>();
1317
+ const settle = () => {
1318
+ if (waiter.resolved) return;
1319
+ waiter.resolved = true;
1320
+ this.detachWaiter(waiter);
1321
+ deferred.resolve();
1322
+ };
1323
+ const waiter: Waiter = {
1324
+ id: this.nextWaiterId++,
1325
+ ino,
1326
+ owner,
1327
+ sessionOwner,
1328
+ blockers: blockers.slice(),
1329
+ trackDeadlock,
1330
+ resolved: false,
1331
+ wake: settle,
1332
+ cancel: settle,
1333
+ };
1334
+ inode.waiters.push(waiter);
1335
+ this.totalWaiters += 1;
1336
+ let sessionWaiters = this.waitersBySession.get(sessionOwner);
1337
+ if (!sessionWaiters) {
1338
+ sessionWaiters = new Set();
1339
+ this.waitersBySession.set(sessionOwner, sessionWaiters);
1340
+ }
1341
+ sessionWaiters.add(waiter);
1342
+ if (trackDeadlock) this.addDeadlockWaiter(waiter);
1343
+ return new LockContentionError(deferred.promise, settle);
1344
+ }
1345
+
1346
+ private addDeadlockWaiter(waiter: Waiter): void {
1347
+ let waiters = this.deadlockWaiters.get(waiter.owner);
1348
+ if (!waiters) {
1349
+ waiters = new Set();
1350
+ this.deadlockWaiters.set(waiter.owner, waiters);
1351
+ }
1352
+ waiters.add(waiter);
1353
+ let edges = this.waitingOn.get(waiter.owner);
1354
+ if (!edges) {
1355
+ edges = new Set();
1356
+ this.waitingOn.set(waiter.owner, edges);
1357
+ }
1358
+ for (let i = 0; i < waiter.blockers.length; i++) edges.add(waiter.blockers[i]!);
1359
+ }
1360
+
1361
+ private removeDeadlockWaiter(waiter: Waiter): void {
1362
+ const waiters = this.deadlockWaiters.get(waiter.owner);
1363
+ if (!waiters) return;
1364
+ waiters.delete(waiter);
1365
+ if (waiters.size === 0) {
1366
+ this.deadlockWaiters.delete(waiter.owner);
1367
+ this.waitingOn.delete(waiter.owner);
1368
+ return;
1369
+ }
1370
+ const edges = new Set<string>();
1371
+ for (const active of waiters) {
1372
+ for (let i = 0; i < active.blockers.length; i++) edges.add(active.blockers[i]!);
1373
+ }
1374
+ this.waitingOn.set(waiter.owner, edges);
1375
+ }
1376
+
1377
+ private detachWaiter(waiter: Waiter): void {
1378
+ const inode = this.byIno.get(waiter.ino);
1379
+ if (inode) {
1380
+ const index = inode.waiters.indexOf(waiter);
1381
+ if (index >= 0) {
1382
+ inode.waiters.splice(index, 1);
1383
+ this.totalWaiters -= 1;
1384
+ }
1385
+ this.pruneInode(waiter.ino, inode);
1386
+ }
1387
+ const sessionWaiters = this.waitersBySession.get(waiter.sessionOwner);
1388
+ if (sessionWaiters) {
1389
+ sessionWaiters.delete(waiter);
1390
+ if (sessionWaiters.size === 0) this.waitersBySession.delete(waiter.sessionOwner);
1391
+ }
1392
+ if (waiter.trackDeadlock) this.removeDeadlockWaiter(waiter);
1393
+ }
1394
+
1395
+ private wakeInode(_ino: number, inode: InodeLocks): void {
1396
+ if (inode.waiters.length === 0) return;
1397
+ const pending = inode.waiters.slice();
1398
+ for (let i = 0; i < pending.length; i++) pending[i]!.wake();
1399
+ }
1400
+
1401
+ private pruneInode(ino: number, inode: InodeLocks): void {
1402
+ if (inode.flocks.size === 0 && inode.ranges.length === 0 && inode.waiters.length === 0) {
1403
+ this.byIno.delete(ino);
1404
+ }
1405
+ }
1406
+ }