durability 4.2.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,9 +9,10 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _DurabilitySemaphoreQueue_instances, _DurabilitySemaphoreQueue_engine, _DurabilitySemaphoreQueue_store, _DurabilitySemaphoreQueue_server, _DurabilitySemaphoreQueue_clientId, _DurabilitySemaphoreQueue_admit, _DurabilitySemaphoreQueue_finished, _DurabilitySemaphoreQueue_finishedCheckMs, _DurabilitySemaphoreQueue_maxAdmitBatch, _DurabilitySemaphoreQueue_attemptTimeoutMs, _DurabilitySemaphoreQueue_delay, _DurabilitySemaphoreQueue_emit, _DurabilitySemaphoreQueue_outbox, _DurabilitySemaphoreQueue_requesting, _DurabilitySemaphoreQueue_blocked, _DurabilitySemaphoreQueue_notifying, _DurabilitySemaphoreQueue_checking, _DurabilitySemaphoreQueue_runDue, _DurabilitySemaphoreQueue_request, _DurabilitySemaphoreQueue_claimLocally, _DurabilitySemaphoreQueue_drawLeases, _DurabilitySemaphoreQueue_returnIdleLeases, _DurabilitySemaphoreQueue_applyLeaseGrants, _DurabilitySemaphoreQueue_applyResults, _DurabilitySemaphoreQueue_refreshKey, _DurabilitySemaphoreQueue_stageReport, _DurabilitySemaphoreQueue_stageLeaseReport, _DurabilitySemaphoreQueue_publishReports, _DurabilitySemaphoreQueue_releaseFinished, _DurabilitySemaphoreQueue_checkFinished, _DurabilitySemaphoreQueue_notify, _DurabilitySemaphoreQueue_notifyBatch, _DurabilitySemaphoreQueue_retryDelay, _DurabilitySemaphoreQueue_deadline;
12
+ var _DurabilitySemaphoreQueue_instances, _DurabilitySemaphoreQueue_engine, _DurabilitySemaphoreQueue_store, _DurabilitySemaphoreQueue_server, _DurabilitySemaphoreQueue_clientId, _DurabilitySemaphoreQueue_admit, _DurabilitySemaphoreQueue_finished, _DurabilitySemaphoreQueue_finishedCheckMs, _DurabilitySemaphoreQueue_maxAdmitBatch, _DurabilitySemaphoreQueue_attemptTimeoutMs, _DurabilitySemaphoreQueue_delay, _DurabilitySemaphoreQueue_emit, _DurabilitySemaphoreQueue_outbox, _DurabilitySemaphoreQueue_requesting, _DurabilitySemaphoreQueue_blocked, _DurabilitySemaphoreQueue_notifying, _DurabilitySemaphoreQueue_checking, _DurabilitySemaphoreQueue_runDue, _DurabilitySemaphoreQueue_retrySoon, _DurabilitySemaphoreQueue_request, _DurabilitySemaphoreQueue_claimLocally, _DurabilitySemaphoreQueue_drawLeases, _DurabilitySemaphoreQueue_returnIdleLeases, _DurabilitySemaphoreQueue_applyLeaseGrants, _DurabilitySemaphoreQueue_renewLeases, _DurabilitySemaphoreQueue_applyResults, _DurabilitySemaphoreQueue_refreshKey, _DurabilitySemaphoreQueue_stageReport, _DurabilitySemaphoreQueue_stageLeaseReport, _DurabilitySemaphoreQueue_publishReports, _DurabilitySemaphoreQueue_releaseFinished, _DurabilitySemaphoreQueue_checkFinished, _DurabilitySemaphoreQueue_notify, _DurabilitySemaphoreQueue_notifyBatch, _DurabilitySemaphoreQueue_retryDelay, _DurabilitySemaphoreQueue_deadline;
13
+ import { traceLifecycle, traceMethods } from './dev.js';
13
14
  import { reportFailure, serializeError } from './errors.js';
14
- import { durabilitySemaphoreQueueMigrations, migrate, } from './migrations.js';
15
+ import { durabilitySemaphoreQueueMigrations, migrateCapability, } from './migrations.js';
15
16
  import { DurabilityOutbox, stageWithin } from './outbox.js';
16
17
  import { assertPositiveInteger, } from './policy.js';
17
18
  import { DurabilityScheduler, engineFor, } from './scheduler.js';
@@ -23,6 +24,8 @@ const queueItemsTable = {
23
24
  key: 'id',
24
25
  };
25
26
  const outboxChannel = 'durability.semaphore-queue';
27
+ /** Half the holder's default grantTimeoutMs. */
28
+ const maxReportRetryMs = 5000;
26
29
  /** Queued items read per key when building a request's demand. */
27
30
  const demandScanLimit = 200;
28
31
  const maxDelayMs = 2 ** 31 - 1;
@@ -46,6 +49,15 @@ const leaseReport = (lease) => ({
46
49
  * draws this long before it bounds the window a skewed clock could open.
47
50
  */
48
51
  const leaseDrawMarginMs = 30000;
52
+ /**
53
+ * Renews at half the lifetime the holder last gave the lease. The holder
54
+ * sweeps a lease nobody reports, and a lease with permits in use must not be
55
+ * swept while its work runs: the holder would lease those permits again.
56
+ */
57
+ const renewal = (now, expiresAt) => {
58
+ const renewMs = Math.max(1000, Math.floor((expiresAt - now) / 2));
59
+ return { renew_at: now + renewMs, renew_ms: renewMs };
60
+ };
49
61
  const drawable = (lease, now) => lease.drawn < lease.permits && lease.expires_at - leaseDrawMarginMs > now;
50
62
  /**
51
63
  * A composable DO capability for the client side of {@link DurabilitySemaphore}:
@@ -105,12 +117,17 @@ export class DurabilitySemaphoreQueue {
105
117
  const scheduler = config.scheduler ?? new DurabilityScheduler(config);
106
118
  __classPrivateFieldSet(this, _DurabilitySemaphoreQueue_engine, engineFor({ scheduler }), "f");
107
119
  __classPrivateFieldSet(this, _DurabilitySemaphoreQueue_store, new QueueStore(__classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f").sql), "f");
108
- __classPrivateFieldSet(this, _DurabilitySemaphoreQueue_emit, __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f").emitter(config.onLifecycleEvent), "f");
120
+ __classPrivateFieldSet(this, _DurabilitySemaphoreQueue_emit, traceLifecycle(__classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f").emitter(config.onLifecycleEvent)), "f");
109
121
  __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f").migrateSchema('semaphoreQueue', durabilitySemaphoreQueueMigrations);
110
122
  __classPrivateFieldSet(this, _DurabilitySemaphoreQueue_outbox, new DurabilityOutbox({
111
123
  scheduler,
112
124
  channel: outboxChannel,
113
125
  publish: (entries) => __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_publishReports).call(this, entries),
126
+ // A claim the holder has not heard about within its grant window is
127
+ // reclaimed, so reports retry well inside it instead of backing off for minutes.
128
+ retries: {
129
+ delay: (attempt) => Math.min(__classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_retryDelay).call(this, attempt), maxReportRetryMs),
130
+ },
114
131
  }), "f");
115
132
  __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f").register({
116
133
  table: queueItemsTable,
@@ -119,7 +136,7 @@ export class DurabilitySemaphoreQueue {
119
136
  });
120
137
  }
121
138
  static migrate(context, target) {
122
- return migrate(context.storage, 'semaphoreQueue', durabilitySemaphoreQueueMigrations, target);
139
+ return migrateCapability(context.storage, 'semaphoreQueue', durabilitySemaphoreQueueMigrations, target);
123
140
  }
124
141
  alarm(info) {
125
142
  return __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f").alarm(info);
@@ -288,10 +305,27 @@ _DurabilitySemaphoreQueue_engine = new WeakMap(), _DurabilitySemaphoreQueue_stor
288
305
  __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f").removeSpentLeases(now - __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_attemptTimeoutMs, "f"));
289
306
  });
290
307
  const keys = __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f").listDueKeys(now);
291
- await Promise.all([__classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_notify).call(this), __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_releaseFinished).call(this, now)]);
308
+ await Promise.all([
309
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_notify).call(this),
310
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_releaseFinished).call(this, now),
311
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_renewLeases).call(this, now),
312
+ ]);
292
313
  await Promise.all(keys
293
314
  .filter(({ key }) => !__classPrivateFieldGet(this, _DurabilitySemaphoreQueue_requesting, "f").has(key))
294
315
  .map(({ key }) => __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_request).call(this, key)));
316
+ }, _DurabilitySemaphoreQueue_retrySoon =
317
+ /** Best effort: if this write fails too, the request deadline still applies. */
318
+ async function _DurabilitySemaphoreQueue_retrySoon(key, queued) {
319
+ await __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f")
320
+ .transaction(() => {
321
+ const current = __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f").getKey(key);
322
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f").upsertKey({
323
+ key,
324
+ queued: current?.queued ?? queued,
325
+ next_request_at: Date.now() + __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_retryDelay).call(this, 1),
326
+ });
327
+ })
328
+ .catch(() => undefined);
295
329
  }, _DurabilitySemaphoreQueue_request =
296
330
  /** Asks the holder for permits covering this key's queued items. */
297
331
  async function _DurabilitySemaphoreQueue_request(key) {
@@ -342,45 +376,46 @@ async function _DurabilitySemaphoreQueue_request(key) {
342
376
  }
343
377
  catch (error) {
344
378
  reportFailure('durability.semaphore_queue.request_failed', { key }, error);
379
+ await __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_retrySoon).call(this, key, queued.length);
380
+ return;
381
+ }
382
+ try {
345
383
  await __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f").transaction(() => {
346
- const current = __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f").getKey(key);
347
- __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f").upsertKey({
348
- key,
349
- queued: current?.queued ?? queued.length,
350
- next_request_at: Date.now() + __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_retryDelay).call(this, 1),
351
- });
384
+ const txStore = __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f");
385
+ for (const given of grant.grants) {
386
+ txStore.insertGrant({
387
+ grant_id: given.grantId,
388
+ key,
389
+ grp: given.group,
390
+ permits: given.permits,
391
+ claimed: 0,
392
+ confirmed: 0,
393
+ admitted: 0,
394
+ released: 0,
395
+ created_at: Date.now(),
396
+ });
397
+ }
398
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_applyLeaseGrants).call(this, key, grant.leases ?? []);
399
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_claimLocally).call(this, key);
400
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_applyResults).call(this, key, grant.grantResults);
401
+ if (grant.contended) {
402
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_returnIdleLeases).call(this, key);
403
+ }
404
+ const remaining = __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_refreshKey).call(this, key, grant.nextRequestAt);
405
+ for (const group of new Set(remaining.map((item) => item.grp))) {
406
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_blocked, "f").delete(pairKey(key, group));
407
+ }
408
+ for (const { group, reason } of grant.blocked) {
409
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_blocked, "f").set(pairKey(key, group), reason);
410
+ }
352
411
  });
353
- return;
354
412
  }
355
- await __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f").transaction(() => {
356
- const txStore = __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f");
357
- for (const given of grant.grants) {
358
- txStore.insertGrant({
359
- grant_id: given.grantId,
360
- key,
361
- grp: given.group,
362
- permits: given.permits,
363
- claimed: 0,
364
- confirmed: 0,
365
- admitted: 0,
366
- released: 0,
367
- created_at: Date.now(),
368
- });
369
- }
370
- __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_applyLeaseGrants).call(this, key, grant.leases ?? []);
371
- __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_claimLocally).call(this, key);
372
- __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_applyResults).call(this, key, grant.grantResults);
373
- if (grant.contended) {
374
- __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_returnIdleLeases).call(this, key);
375
- }
376
- const remaining = __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_refreshKey).call(this, key, grant.nextRequestAt);
377
- for (const group of new Set(remaining.map((item) => item.grp))) {
378
- __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_blocked, "f").delete(pairKey(key, group));
379
- }
380
- for (const { group, reason } of grant.blocked) {
381
- __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_blocked, "f").set(pairKey(key, group), reason);
382
- }
383
- });
413
+ catch (error) {
414
+ // The grant is lost with the transaction; ask again soon rather than
415
+ // at the request deadline, which only covers a crash.
416
+ await __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_retrySoon).call(this, key, queued.length);
417
+ throw error;
418
+ }
384
419
  const counts = new Map();
385
420
  for (const item of store.listItems(key, 'queued', demandScanLimit)) {
386
421
  counts.set(item.grp, (counts.get(item.grp) ?? 0) + 1);
@@ -484,7 +519,15 @@ async function _DurabilitySemaphoreQueue_request(key) {
484
519
  for (const grant of grants) {
485
520
  const lease = store.getLease(grant.leaseId);
486
521
  if (grant.expiresAt <= now) {
487
- if (!lease || retiredLocally(lease, now)) {
522
+ if (!lease) {
523
+ continue;
524
+ }
525
+ if (retiredLocally(lease, now)) {
526
+ // The holder settles a stopped lease by echoing it with nothing left
527
+ // counted; until then this client keeps reporting it.
528
+ if (grant.permits <= lease.released && !lease.confirmed) {
529
+ store.updateLease({ ...lease, confirmed: 1 });
530
+ }
488
531
  continue;
489
532
  }
490
533
  // The holder keeps counting the whole lease until this report says
@@ -497,7 +540,11 @@ async function _DurabilitySemaphoreQueue_request(key) {
497
540
  if (lease) {
498
541
  // A refresh sent before this client retired the lease must not revive it.
499
542
  if (!retiredLocally(lease, now)) {
500
- store.updateLease({ ...lease, expires_at: grant.expiresAt });
543
+ store.updateLease({
544
+ ...lease,
545
+ expires_at: grant.expiresAt,
546
+ ...renewal(now, grant.expiresAt),
547
+ });
501
548
  }
502
549
  continue;
503
550
  }
@@ -510,8 +557,26 @@ async function _DurabilitySemaphoreQueue_request(key) {
510
557
  released: 0,
511
558
  created_at: now,
512
559
  expires_at: grant.expiresAt,
560
+ ...renewal(now, grant.expiresAt),
561
+ confirmed: 0,
513
562
  });
514
563
  }
564
+ }, _DurabilitySemaphoreQueue_renewLeases =
565
+ /**
566
+ * Reports leases with permits in use before the holder retires them, and
567
+ * stopped leases until the holder settles them.
568
+ */
569
+ async function _DurabilitySemaphoreQueue_renewLeases(now) {
570
+ // An idle run must not write: every transaction reconciles the alarm.
571
+ if (__classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f").listRenewalsDue(now, 1).length === 0) {
572
+ return;
573
+ }
574
+ await __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_engine, "f").transaction(() => {
575
+ for (const lease of __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f").listRenewalsDue(now, 100)) {
576
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f").updateLease({ ...lease, renew_at: now + lease.renew_ms });
577
+ __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_instances, "m", _DurabilitySemaphoreQueue_stageLeaseReport).call(this, lease);
578
+ }
579
+ });
515
580
  }, _DurabilitySemaphoreQueue_applyResults = function _DurabilitySemaphoreQueue_applyResults(key, results) {
516
581
  const store = __classPrivateFieldGet(this, _DurabilitySemaphoreQueue_store, "f");
517
582
  const now = Date.now();
@@ -795,3 +860,4 @@ async function _DurabilitySemaphoreQueue_publishReports(entries) {
795
860
  }
796
861
  }
797
862
  };
863
+ traceMethods(DurabilitySemaphoreQueue.prototype, 'DurabilitySemaphoreQueue');
@@ -10,8 +10,9 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _DurabilitySemaphoreServer_instances, _DurabilitySemaphoreServer_engine, _DurabilitySemaphoreServer_store, _DurabilitySemaphoreServer_limit, _DurabilitySemaphoreServer_groupLimit, _DurabilitySemaphoreServer_canGrant, _DurabilitySemaphoreServer_roundWaitMs, _DurabilitySemaphoreServer_roundPeriodMs, _DurabilitySemaphoreServer_grantTimeoutMs, _DurabilitySemaphoreServer_leases, _DurabilitySemaphoreServer_emit, _DurabilitySemaphoreServer_pending, _DurabilitySemaphoreServer_roundTimer, _DurabilitySemaphoreServer_round, _DurabilitySemaphoreServer_lastRoundAt, _DurabilitySemaphoreServer_contended, _DurabilitySemaphoreServer_grantRoom, _DurabilitySemaphoreServer_scheduleRound, _DurabilitySemaphoreServer_runRound, _DurabilitySemaphoreServer_allocate, _DurabilitySemaphoreServer_sync, _DurabilitySemaphoreServer_applyReports, _DurabilitySemaphoreServer_reclaim, _DurabilitySemaphoreServer_reclaimExpired, _DurabilitySemaphoreServer_resolveLimit, _DurabilitySemaphoreServer_groupPolicy;
13
+ import { traceLifecycle, traceMethods } from './dev.js';
13
14
  import { SemaphoreProtocolError, reportFailure } from './errors.js';
14
- import { durabilitySemaphoreMigrations, migrate, } from './migrations.js';
15
+ import { durabilitySemaphoreMigrations, migrateCapability, } from './migrations.js';
15
16
  import { assertPositiveInteger } from './policy.js';
16
17
  import { allocateLeases, applyLeaseReports, budgets, leaseFootprint, resolveLeasePolicy, } from './semaphore-leases.js';
17
18
  import { engineFor, } from './scheduler.js';
@@ -97,7 +98,7 @@ export class DurabilitySemaphoreServer {
97
98
  }
98
99
  }
99
100
  __classPrivateFieldSet(this, _DurabilitySemaphoreServer_engine, engineFor(config), "f");
100
- __classPrivateFieldSet(this, _DurabilitySemaphoreServer_emit, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").emitter(config.onLifecycleEvent), "f");
101
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_emit, traceLifecycle(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").emitter(config.onLifecycleEvent)), "f");
101
102
  __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").migrateSchema('semaphore', durabilitySemaphoreMigrations);
102
103
  __classPrivateFieldSet(this, _DurabilitySemaphoreServer_store, new HolderStore(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").sql), "f");
103
104
  __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").register({
@@ -107,7 +108,7 @@ export class DurabilitySemaphoreServer {
107
108
  });
108
109
  }
109
110
  static migrate(context, target) {
110
- return migrate(context.storage, 'semaphore', durabilitySemaphoreMigrations, target);
111
+ return migrateCapability(context.storage, 'semaphore', durabilitySemaphoreMigrations, target);
111
112
  }
112
113
  alarm(info) {
113
114
  return __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").alarm(info);
@@ -148,9 +149,7 @@ export class DurabilitySemaphoreServer {
148
149
  }
149
150
  let leased = 0;
150
151
  for (const lease of leases) {
151
- if (lease.expires_at > now) {
152
- leased += leaseFootprint(lease);
153
- }
152
+ leased += leaseFootprint(lease);
154
153
  }
155
154
  await Promise.all([...groups.entries()].map(async ([name, group]) => {
156
155
  const policy = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_groupPolicy).call(this, name);
@@ -287,9 +286,7 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
287
286
  let leased = 0;
288
287
  if (__classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f") && budget.shared) {
289
288
  for (const lease of store.listLeases()) {
290
- if (lease.expires_at > now) {
291
- leased += leaseFootprint(lease);
292
- }
289
+ leased += leaseFootprint(lease);
293
290
  }
294
291
  }
295
292
  let remaining = budget.grants - total - (budget.shared ? leased : 0);
@@ -518,3 +515,4 @@ async function _DurabilitySemaphoreServer_groupPolicy(group) {
518
515
  return { blocked: 'limit_resolution_error' };
519
516
  }
520
517
  };
518
+ traceMethods(DurabilitySemaphoreServer.prototype, 'DurabilitySemaphore');
package/dist/socket.js CHANGED
@@ -9,9 +9,10 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _DurabilitySocketCore_instances, _DurabilitySocketCore_context, _DurabilitySocketCore_inbound, _DurabilitySocketCore_outboundNames, _DurabilitySocketCore_metadata, _DurabilitySocketCore_retention, _DurabilitySocketCore_call, _DurabilitySocketCore_validate, _DurabilitySocketCore_subscribe, _DurabilitySocketCore_replay, _DurabilitySocketCore_headSeq, _DurabilitySocketCore_publish;
12
+ var _DurabilitySocketCore_instances, _DurabilitySocketCore_context, _DurabilitySocketCore_storage, _DurabilitySocketCore_inbound, _DurabilitySocketCore_outboundNames, _DurabilitySocketCore_metadata, _DurabilitySocketCore_retention, _DurabilitySocketCore_call, _DurabilitySocketCore_validate, _DurabilitySocketCore_subscribe, _DurabilitySocketCore_replay, _DurabilitySocketCore_headSeq, _DurabilitySocketCore_publish;
13
+ import { trace, traceFunction, traceMethods, traceStorage } from './dev.js';
13
14
  import { reportFailure, serializeError } from './errors.js';
14
- import { durabilitySocketMigrations, migrate, } from './migrations.js';
15
+ import { durabilitySocketMigrations, migrateCapability, } from './migrations.js';
15
16
  import { deserialize, serialize } from './serialization.js';
16
17
  import { parseClientFrame, socketMaxFrameLength, socketProtocolErrorCode, socketProtocolVersion, } from './socket-protocol.js';
17
18
  /** Thrown to the caller when an inbound payload fails its schema. */
@@ -24,6 +25,7 @@ export class SocketInputError extends Error {
24
25
  }
25
26
  const reservedOutboundNames = new Set(['status', 'resync']);
26
27
  const sendFrame = (ws, frame) => {
28
+ trace('socket.send', { frame });
27
29
  let text = JSON.stringify(frame);
28
30
  if (text.length > socketMaxFrameLength) {
29
31
  if (frame.type === 'event') {
@@ -64,6 +66,7 @@ class DurabilitySocketCore {
64
66
  constructor(config) {
65
67
  _DurabilitySocketCore_instances.add(this);
66
68
  _DurabilitySocketCore_context.set(this, void 0);
69
+ _DurabilitySocketCore_storage.set(this, void 0);
67
70
  _DurabilitySocketCore_inbound.set(this, void 0);
68
71
  _DurabilitySocketCore_outboundNames.set(this, void 0);
69
72
  _DurabilitySocketCore_metadata.set(this, void 0);
@@ -73,6 +76,7 @@ class DurabilitySocketCore {
73
76
  throw new RangeError('retention must be a positive safe integer');
74
77
  }
75
78
  __classPrivateFieldSet(this, _DurabilitySocketCore_context, config.context, "f");
79
+ __classPrivateFieldSet(this, _DurabilitySocketCore_storage, traceStorage(config.context.storage), "f");
76
80
  // Only own keys are callable; nothing on the prototype chain is reachable.
77
81
  __classPrivateFieldSet(this, _DurabilitySocketCore_inbound, new Map(Object.entries(config.inbound)), "f");
78
82
  __classPrivateFieldSet(this, _DurabilitySocketCore_metadata, config.metadata, "f");
@@ -87,17 +91,17 @@ class DurabilitySocketCore {
87
91
  throw new Error(`"${name}" is reserved by DurabilitySocket`);
88
92
  }
89
93
  Object.defineProperty(this, name, {
90
- value: (payload) => __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_publish).call(this, name, payload),
94
+ value: traceFunction(`DurabilitySocket.${name}`, (payload) => __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_publish).call(this, name, payload)),
91
95
  enumerable: true,
92
96
  });
93
97
  }
94
- migrate(__classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage, 'socket', durabilitySocketMigrations, undefined);
98
+ migrateCapability(__classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f"), 'socket', durabilitySocketMigrations, undefined);
95
99
  // Keep-alive pings are answered by the runtime without waking a hibernated object.
96
100
  __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").setWebSocketAutoResponse(new WebSocketRequestResponsePair(JSON.stringify({ v: socketProtocolVersion, type: 'ping' }), JSON.stringify({ v: socketProtocolVersion, type: 'pong' })));
97
101
  }
98
102
  /** Applies or reverts the `durability_socket_events` schema. */
99
103
  static migrate(context, target) {
100
- return migrate(context.storage, 'socket', durabilitySocketMigrations, target);
104
+ return migrateCapability(context.storage, 'socket', durabilitySocketMigrations, target);
101
105
  }
102
106
  /** Accepts a WebSocket upgrade; call from the Durable Object's `fetch`. */
103
107
  async fetch(request) {
@@ -120,6 +124,10 @@ class DurabilitySocketCore {
120
124
  const text = typeof message === 'string' ? message : new TextDecoder().decode(message);
121
125
  const frame = parseClientFrame(text);
122
126
  if (!frame) {
127
+ trace('socket.close', {
128
+ code: socketProtocolErrorCode,
129
+ reason: 'Invalid frame',
130
+ });
123
131
  ws.close(socketProtocolErrorCode, 'Invalid frame');
124
132
  return;
125
133
  }
@@ -136,7 +144,7 @@ class DurabilitySocketCore {
136
144
  */
137
145
  webSocketClose(_ws) { }
138
146
  }
139
- _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_inbound = new WeakMap(), _DurabilitySocketCore_outboundNames = new WeakMap(), _DurabilitySocketCore_metadata = new WeakMap(), _DurabilitySocketCore_retention = new WeakMap(), _DurabilitySocketCore_instances = new WeakSet(), _DurabilitySocketCore_call = async function _DurabilitySocketCore_call(ws, frame) {
147
+ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = new WeakMap(), _DurabilitySocketCore_inbound = new WeakMap(), _DurabilitySocketCore_outboundNames = new WeakMap(), _DurabilitySocketCore_metadata = new WeakMap(), _DurabilitySocketCore_retention = new WeakMap(), _DurabilitySocketCore_instances = new WeakSet(), _DurabilitySocketCore_call = async function _DurabilitySocketCore_call(ws, frame) {
140
148
  const handler = __classPrivateFieldGet(this, _DurabilitySocketCore_inbound, "f").get(frame.method);
141
149
  if (!handler) {
142
150
  sendFrame(ws, {
@@ -213,13 +221,13 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_inbound = n
213
221
  if (since === head) {
214
222
  return true;
215
223
  }
216
- const oldest = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql
224
+ const oldest = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql
217
225
  .exec('SELECT MIN(seq) AS seq FROM durability_socket_events')
218
226
  .one().seq;
219
227
  if (since + 1 < oldest) {
220
228
  return false;
221
229
  }
222
- const rows = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql
230
+ const rows = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql
223
231
  .exec('SELECT seq, name, payload FROM durability_socket_events WHERE seq > ? ORDER BY seq', since)
224
232
  .toArray();
225
233
  const wanted = new Set(names);
@@ -237,13 +245,13 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_inbound = n
237
245
  }
238
246
  return true;
239
247
  }, _DurabilitySocketCore_headSeq = function _DurabilitySocketCore_headSeq() {
240
- const row = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql
248
+ const row = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql
241
249
  .exec('SELECT MAX(seq) AS seq FROM durability_socket_events')
242
250
  .one();
243
251
  return row.seq ?? 0;
244
252
  }, _DurabilitySocketCore_publish = function _DurabilitySocketCore_publish(name, payload) {
245
253
  const serialized = serialize(payload);
246
- const sql = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql;
254
+ const sql = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql;
247
255
  const { seq } = sql
248
256
  .exec('INSERT INTO durability_socket_events (name, payload, created_at) VALUES (?, ?, ?) RETURNING seq', name, serialized, Date.now())
249
257
  .one();
@@ -265,6 +273,7 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_inbound = n
265
273
  sendFrame(ws, frame);
266
274
  }
267
275
  };
276
+ traceMethods(DurabilitySocketCore.prototype, 'DurabilitySocket');
268
277
  // TypeScript cannot declare class members derived from a generic event map,
269
278
  // so the constructor is typed separately; the constructor installs and
270
279
  // reserves every outbound method at runtime.
@@ -0,0 +1,40 @@
1
+ import { type TopologyFallbackReason } from './errors.js';
2
+ import { type TopologyMemberInput, type TopologySnapshot } from './topology-snapshot.js';
3
+ export type TopologySource = 'published' | 'stale' | 'seed' | 'fallback';
4
+ export type TopologyView<Meta = undefined> = TopologySnapshot<Meta> & {
5
+ source: TopologySource;
6
+ fetchedAt: number;
7
+ };
8
+ export type TopologyClientConfig<Meta = undefined> = {
9
+ /** Returns the `encoded` value the coordinator's publisher stored, or null. */
10
+ read(group: string): Promise<string | null | undefined>;
11
+ /** Defaults to 1 second. */
12
+ readTimeoutMs?: number;
13
+ /** Defaults to 30 seconds, jittered by ±20% so isolates do not refresh together. */
14
+ ttlMs?: number;
15
+ /** How long a missing or failed read is remembered before reading again. Defaults to 5 seconds. */
16
+ negativeTtlMs?: number;
17
+ /** Opt-in: serve this isolate's last good snapshot for this long after it expires when a read fails. */
18
+ staleIfErrorMs?: number;
19
+ /** Opt-in: members derived locally, without I/O. */
20
+ seed?(group: string): readonly TopologyMemberInput<Meta>[] | undefined;
21
+ /** Opt-in and application-owned. Not cached: whatever it calls runs on every fallback. */
22
+ fallback?(group: string, reason: TopologyFallbackReason): Promise<TopologySnapshot<Meta> | undefined>;
23
+ onFallback?(event: {
24
+ group: string;
25
+ reason: TopologyFallbackReason;
26
+ source: TopologySource | 'none';
27
+ }): void;
28
+ };
29
+ /** Read-only. Created by `DurabilityTopology.client`. */
30
+ export declare class TopologyClient<Meta = undefined> {
31
+ #private;
32
+ constructor(config: TopologyClientConfig<Meta>);
33
+ /**
34
+ * Returns the group's snapshot from this isolate's cache or the read store.
35
+ * Concurrent calls share one read, and a newer snapshot is never replaced by
36
+ * an older one. Throws {@link TopologyUnavailableError} when the published
37
+ * snapshot is unusable and no opt-in fallback produced one.
38
+ */
39
+ get(group: string): Promise<TopologyView<Meta>>;
40
+ }
@@ -0,0 +1,180 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _TopologyClient_instances, _TopologyClient_config, _TopologyClient_readTimeoutMs, _TopologyClient_ttlMs, _TopologyClient_negativeTtlMs, _TopologyClient_cache, _TopologyClient_inflight, _TopologyClient_load, _TopologyClient_read, _TopologyClient_fallback, _TopologyClient_remember;
13
+ import { TopologyUnavailableError, } from './errors.js';
14
+ import { assertPositiveInteger } from './policy.js';
15
+ import { decodeSnapshot, } from './topology-snapshot.js';
16
+ // High-cardinality groups (one per tenant) must not grow an isolate without bound; the least recently used go first.
17
+ const maxCachedGroups = 1024;
18
+ class ReadTimeoutError extends Error {
19
+ }
20
+ const jittered = (ms) => Math.round(ms * (0.8 + Math.random() * 0.4));
21
+ /** Read-only. Created by `DurabilityTopology.client`. */
22
+ export class TopologyClient {
23
+ constructor(config) {
24
+ _TopologyClient_instances.add(this);
25
+ _TopologyClient_config.set(this, void 0);
26
+ _TopologyClient_readTimeoutMs.set(this, void 0);
27
+ _TopologyClient_ttlMs.set(this, void 0);
28
+ _TopologyClient_negativeTtlMs.set(this, void 0);
29
+ _TopologyClient_cache.set(this, new Map());
30
+ _TopologyClient_inflight.set(this, new Map());
31
+ if (typeof config.read !== 'function') {
32
+ throw new TypeError('A topology client needs a read function');
33
+ }
34
+ __classPrivateFieldSet(this, _TopologyClient_readTimeoutMs, config.readTimeoutMs ?? 1000, "f");
35
+ __classPrivateFieldSet(this, _TopologyClient_ttlMs, config.ttlMs ?? 30000, "f");
36
+ __classPrivateFieldSet(this, _TopologyClient_negativeTtlMs, config.negativeTtlMs ?? 5000, "f");
37
+ assertPositiveInteger('readTimeoutMs', __classPrivateFieldGet(this, _TopologyClient_readTimeoutMs, "f"));
38
+ assertPositiveInteger('ttlMs', __classPrivateFieldGet(this, _TopologyClient_ttlMs, "f"));
39
+ assertPositiveInteger('negativeTtlMs', __classPrivateFieldGet(this, _TopologyClient_negativeTtlMs, "f"));
40
+ if (config.staleIfErrorMs !== undefined &&
41
+ (!Number.isSafeInteger(config.staleIfErrorMs) ||
42
+ config.staleIfErrorMs < 0)) {
43
+ throw new RangeError('staleIfErrorMs must be a non-negative integer');
44
+ }
45
+ __classPrivateFieldSet(this, _TopologyClient_config, config, "f");
46
+ }
47
+ /**
48
+ * Returns the group's snapshot from this isolate's cache or the read store.
49
+ * Concurrent calls share one read, and a newer snapshot is never replaced by
50
+ * an older one. Throws {@link TopologyUnavailableError} when the published
51
+ * snapshot is unusable and no opt-in fallback produced one.
52
+ */
53
+ get(group) {
54
+ const entry = __classPrivateFieldGet(this, _TopologyClient_cache, "f").get(group);
55
+ if (entry && Date.now() < entry.expiresAt) {
56
+ if (entry.failure) {
57
+ return __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_fallback).call(this, group, entry);
58
+ }
59
+ if (entry.view) {
60
+ __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_remember).call(this, group, entry);
61
+ return Promise.resolve(entry.view);
62
+ }
63
+ }
64
+ const inflight = __classPrivateFieldGet(this, _TopologyClient_inflight, "f").get(group);
65
+ if (inflight) {
66
+ return inflight;
67
+ }
68
+ const run = __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_load).call(this, group).finally(() => __classPrivateFieldGet(this, _TopologyClient_inflight, "f").delete(group));
69
+ __classPrivateFieldGet(this, _TopologyClient_inflight, "f").set(group, run);
70
+ return run;
71
+ }
72
+ }
73
+ _TopologyClient_config = new WeakMap(), _TopologyClient_readTimeoutMs = new WeakMap(), _TopologyClient_ttlMs = new WeakMap(), _TopologyClient_negativeTtlMs = new WeakMap(), _TopologyClient_cache = new WeakMap(), _TopologyClient_inflight = new WeakMap(), _TopologyClient_instances = new WeakSet(), _TopologyClient_load = async function _TopologyClient_load(group) {
74
+ const previous = __classPrivateFieldGet(this, _TopologyClient_cache, "f").get(group);
75
+ const result = await __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_read).call(this, group);
76
+ const now = Date.now();
77
+ if ('snapshot' in result) {
78
+ const { snapshot } = result;
79
+ // The store is eventually consistent; a lagging replica must not move readers backwards.
80
+ // Versions only compare within one coordinator: a group moved to another starts over.
81
+ const keep = previous?.view !== undefined &&
82
+ previous.view.coordinator === snapshot.coordinator &&
83
+ previous.view.version > snapshot.version;
84
+ const view = keep
85
+ ? previous.view
86
+ : { ...snapshot, source: 'published', fetchedAt: now };
87
+ const expiresAt = now + jittered(__classPrivateFieldGet(this, _TopologyClient_ttlMs, "f"));
88
+ __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_remember).call(this, group, {
89
+ view,
90
+ expiresAt,
91
+ staleUntil: expiresAt + (__classPrivateFieldGet(this, _TopologyClient_config, "f").staleIfErrorMs ?? 0),
92
+ });
93
+ return view;
94
+ }
95
+ const entry = {
96
+ // A missing group is not an error, so nothing stale may be served for it.
97
+ ...(result.failure.reason === 'missing' || !previous?.view
98
+ ? {}
99
+ : { view: previous.view }),
100
+ staleUntil: previous?.staleUntil ?? 0,
101
+ expiresAt: now + jittered(__classPrivateFieldGet(this, _TopologyClient_negativeTtlMs, "f")),
102
+ failure: result.failure,
103
+ };
104
+ __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_remember).call(this, group, entry);
105
+ return __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_fallback).call(this, group, entry);
106
+ }, _TopologyClient_read = async function _TopologyClient_read(group) {
107
+ let encoded;
108
+ let timer;
109
+ try {
110
+ encoded = await Promise.race([
111
+ Promise.resolve().then(() => __classPrivateFieldGet(this, _TopologyClient_config, "f").read(group)),
112
+ new Promise((_resolve, reject) => {
113
+ timer = setTimeout(() => reject(new ReadTimeoutError()), __classPrivateFieldGet(this, _TopologyClient_readTimeoutMs, "f"));
114
+ }),
115
+ ]);
116
+ }
117
+ catch (cause) {
118
+ return {
119
+ failure: {
120
+ reason: cause instanceof ReadTimeoutError ? 'timeout' : 'error',
121
+ cause,
122
+ },
123
+ };
124
+ }
125
+ finally {
126
+ clearTimeout(timer);
127
+ }
128
+ if (encoded === null || encoded === undefined) {
129
+ return { failure: { reason: 'missing' } };
130
+ }
131
+ try {
132
+ const snapshot = decodeSnapshot(encoded);
133
+ if (snapshot.group !== group) {
134
+ throw new Error(`Snapshot belongs to group "${snapshot.group}"`);
135
+ }
136
+ return { snapshot };
137
+ }
138
+ catch (cause) {
139
+ return { failure: { reason: 'invalid', cause } };
140
+ }
141
+ }, _TopologyClient_fallback = async function _TopologyClient_fallback(group, entry) {
142
+ const { reason, cause } = entry.failure;
143
+ const notify = (source) => __classPrivateFieldGet(this, _TopologyClient_config, "f").onFallback?.({ group, reason, source });
144
+ if (__classPrivateFieldGet(this, _TopologyClient_config, "f").staleIfErrorMs !== undefined &&
145
+ entry.view !== undefined &&
146
+ Date.now() < entry.staleUntil) {
147
+ notify('stale');
148
+ return { ...entry.view, source: 'stale' };
149
+ }
150
+ const seeded = __classPrivateFieldGet(this, _TopologyClient_config, "f").seed?.(group);
151
+ if (seeded !== undefined && seeded.length > 0) {
152
+ notify('seed');
153
+ return {
154
+ group,
155
+ version: 0,
156
+ coordinator: '',
157
+ members: seeded
158
+ .map((member) => ({ ...member, joinedAt: 0 }))
159
+ .sort((a, b) => (a.id < b.id ? -1 : 1)),
160
+ source: 'seed',
161
+ fetchedAt: Date.now(),
162
+ };
163
+ }
164
+ const fallback = await __classPrivateFieldGet(this, _TopologyClient_config, "f").fallback?.(group, reason);
165
+ if (fallback !== undefined) {
166
+ notify('fallback');
167
+ return { ...fallback, source: 'fallback', fetchedAt: Date.now() };
168
+ }
169
+ notify('none');
170
+ throw new TopologyUnavailableError(group, reason, { cause });
171
+ }, _TopologyClient_remember = function _TopologyClient_remember(group, entry) {
172
+ __classPrivateFieldGet(this, _TopologyClient_cache, "f").delete(group);
173
+ __classPrivateFieldGet(this, _TopologyClient_cache, "f").set(group, entry);
174
+ if (__classPrivateFieldGet(this, _TopologyClient_cache, "f").size > maxCachedGroups) {
175
+ const oldest = __classPrivateFieldGet(this, _TopologyClient_cache, "f").keys().next().value;
176
+ if (oldest !== undefined) {
177
+ __classPrivateFieldGet(this, _TopologyClient_cache, "f").delete(oldest);
178
+ }
179
+ }
180
+ };