durability 4.1.2 → 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.
Files changed (52) hide show
  1. package/README.md +406 -1
  2. package/dist/dev.d.ts +22 -0
  3. package/dist/dev.js +149 -0
  4. package/dist/durability-alarms.d.ts +1 -1
  5. package/dist/durability-alarms.js +6 -4
  6. package/dist/durability.d.ts +1 -1
  7. package/dist/durability.js +8 -5
  8. package/dist/durable-object-target.d.ts +12 -0
  9. package/dist/durable-object-target.js +17 -0
  10. package/dist/errors.d.ts +25 -0
  11. package/dist/errors.js +36 -0
  12. package/dist/experimental.d.ts +8 -0
  13. package/dist/experimental.js +6 -0
  14. package/dist/fanout.js +14 -9
  15. package/dist/index.d.ts +2 -1
  16. package/dist/index.js +1 -1
  17. package/dist/lifecycle.d.ts +14 -3
  18. package/dist/lifecycle.js +3 -2
  19. package/dist/log.js +26 -4
  20. package/dist/migrations.d.ts +74 -2
  21. package/dist/migrations.js +307 -36
  22. package/dist/outbox.d.ts +85 -0
  23. package/dist/outbox.js +433 -0
  24. package/dist/routing.d.ts +2 -9
  25. package/dist/routing.js +2 -14
  26. package/dist/scheduler.d.ts +14 -2
  27. package/dist/scheduler.js +38 -13
  28. package/dist/semaphore-client.d.ts +22 -0
  29. package/dist/semaphore-client.js +61 -0
  30. package/dist/semaphore-leases.d.ts +109 -0
  31. package/dist/semaphore-leases.js +272 -0
  32. package/dist/semaphore-protocol.d.ts +231 -0
  33. package/dist/semaphore-protocol.js +106 -0
  34. package/dist/semaphore-queue-store.d.ts +95 -0
  35. package/dist/semaphore-queue-store.js +248 -0
  36. package/dist/semaphore-queue.d.ts +119 -0
  37. package/dist/semaphore-queue.js +863 -0
  38. package/dist/semaphore-server.d.ts +89 -0
  39. package/dist/semaphore-server.js +518 -0
  40. package/dist/semaphore-store.d.ts +43 -0
  41. package/dist/semaphore-store.js +108 -0
  42. package/dist/semaphore.d.ts +42 -0
  43. package/dist/semaphore.js +57 -0
  44. package/dist/socket.js +19 -10
  45. package/dist/topology-client.d.ts +40 -0
  46. package/dist/topology-client.js +180 -0
  47. package/dist/topology-snapshot.d.ts +70 -0
  48. package/dist/topology-snapshot.js +48 -0
  49. package/dist/topology.d.ts +94 -0
  50. package/dist/topology.js +468 -0
  51. package/dist/tracker.js +2 -0
  52. package/package.json +6 -2
@@ -0,0 +1,89 @@
1
+ import { type DurabilityMigrationResult } from './migrations.js';
2
+ import { type LeaseEvent, type SemaphoreLeaseOptions } from './semaphore-leases.js';
3
+ import { type SchedulerAttachment } from './scheduler.js';
4
+ import { type SemaphoreBlockedReason, type SemaphoreRequest, type SemaphoreResponse } from './semaphore-protocol.js';
5
+ export type DurabilitySemaphoreEvent = {
6
+ entityKind: 'semaphore';
7
+ type: 'round';
8
+ timestamp: number;
9
+ /** Permits asked for and handed out in this round. */
10
+ requested: number;
11
+ granted: number;
12
+ usage: SemaphoreUsage;
13
+ } | {
14
+ entityKind: 'semaphore';
15
+ type: 'blocked';
16
+ timestamp: number;
17
+ group: string;
18
+ reason: SemaphoreBlockedReason;
19
+ /** Permits that stayed queued behind the limit. */
20
+ count: number;
21
+ } | LeaseEvent | {
22
+ entityKind: 'semaphore';
23
+ type: 'grant_reclaimed';
24
+ timestamp: number;
25
+ grantId: string;
26
+ clientId: string;
27
+ group: string;
28
+ /** Unclaimed permits returned to the pool. */
29
+ permits: number;
30
+ };
31
+ export type DurabilitySemaphoreConfig = SchedulerAttachment & {
32
+ /** Evaluated once per round. Lowering it never evicts running work. */
33
+ limit: number | (() => number | Promise<number>);
34
+ /**
35
+ * Per-group ceiling; `undefined` means the group only shares the limit.
36
+ * Throwing fails closed for that group with `limit_resolution_error`.
37
+ */
38
+ groupLimit?: (group: string) => number | undefined | Promise<number | undefined>;
39
+ /** Entitlement gate; `false` blocks the group with `not_permitted`. */
40
+ canGrant?: (group: string) => boolean | Promise<boolean>;
41
+ /** How long a round waits to coalesce requests. Defaults to 1 second. */
42
+ roundWaitMs?: number;
43
+ /** Minimum time between rounds. Defaults to 2 seconds. */
44
+ roundPeriodMs?: number;
45
+ /** Granted permits a client never claims are reclaimed after this. Defaults to 10 seconds. */
46
+ grantTimeoutMs?: number;
47
+ /** Omit to disable leases: clients then admit only through confirmed grants. */
48
+ leases?: SemaphoreLeaseOptions;
49
+ onLifecycleEvent?: (event: DurabilitySemaphoreEvent) => void | Promise<void>;
50
+ };
51
+ export type SemaphoreUsage = {
52
+ limit: number;
53
+ /**
54
+ * Permits granted and not yet released, including unclaimed grants. May
55
+ * exceed `limit` after it was lowered: running work is never evicted.
56
+ */
57
+ granted: number;
58
+ /** Live lease footprint: lease permits not yet released. */
59
+ leased: number;
60
+ /** Permits grants may still receive, under the provisioning mode. */
61
+ available: number;
62
+ groups: ReadonlyMap<string, {
63
+ granted: number;
64
+ limit?: number;
65
+ }>;
66
+ };
67
+ /**
68
+ * The holder half of {@link DurabilitySemaphore}, free of Workers-only imports
69
+ * so it can be tested outside workerd.
70
+ *
71
+ * A composable DO capability holding one concurrency limit for many client
72
+ * Durable Objects. Requests arriving within a round are allocated together in
73
+ * arrival order; clients report claimed and released permits as cumulative
74
+ * counts, so lost or repeated reports can never free capacity twice.
75
+ */
76
+ export declare class DurabilitySemaphoreServer {
77
+ #private;
78
+ constructor(config: DurabilitySemaphoreConfig);
79
+ static migrate(context: Pick<DurableObjectState, 'storage'>, target?: string | null): DurabilityMigrationResult;
80
+ alarm(info?: AlarmInvocationInfo): Promise<void>;
81
+ /**
82
+ * The single entry point the application exposes over RPC. A `request` is
83
+ * answered when its round runs; the caller must keep awaiting it. Pending
84
+ * requests live in memory only: if the object is evicted first, the call
85
+ * fails and the client asks again.
86
+ */
87
+ handle(message: SemaphoreRequest): Promise<SemaphoreResponse>;
88
+ usage(): Promise<SemaphoreUsage>;
89
+ }
@@ -0,0 +1,518 @@
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 _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';
14
+ import { SemaphoreProtocolError, reportFailure } from './errors.js';
15
+ import { durabilitySemaphoreMigrations, migrateCapability, } from './migrations.js';
16
+ import { assertPositiveInteger } from './policy.js';
17
+ import { allocateLeases, applyLeaseReports, budgets, leaseFootprint, resolveLeasePolicy, } from './semaphore-leases.js';
18
+ import { engineFor, } from './scheduler.js';
19
+ import { semaphoreRequestSchema, } from './semaphore-protocol.js';
20
+ import { HolderStore } from './semaphore-store.js';
21
+ const grantsTable = {
22
+ name: 'durability_semaphore_grants',
23
+ key: 'grant_id',
24
+ };
25
+ // setTimeout overflows past 2^31 - 1 ms.
26
+ const maxDelayMs = 2 ** 31 - 1;
27
+ /** Unclaimed permits are reclaimed once the claim window passes. */
28
+ const effectivePermits = (grant, now) => now >= grant.expires_at ? grant.claimed : grant.permits;
29
+ const outstanding = (grant, now) => Math.max(0, effectivePermits(grant, now) - grant.released);
30
+ /** Permits left queued per (group, reason) across one round's allocations. */
31
+ const blockedCounts = (allocations) => {
32
+ const counts = new Map();
33
+ for (const [entry, allocation] of allocations) {
34
+ const given = new Map();
35
+ for (const grant of allocation.grants) {
36
+ given.set(grant.group, (given.get(grant.group) ?? 0) + grant.permits);
37
+ }
38
+ for (const { group, reason } of allocation.blocked) {
39
+ const demanded = entry.request.demand.find((d) => d.group === group);
40
+ const count = (demanded?.count ?? 0) - (given.get(group) ?? 0);
41
+ const key = JSON.stringify([group, reason]);
42
+ counts.set(key, (counts.get(key) ?? 0) + count);
43
+ }
44
+ }
45
+ return [...counts].map(([key, count]) => {
46
+ const [group, reason] = JSON.parse(key);
47
+ return [group, reason, count];
48
+ });
49
+ };
50
+ /**
51
+ * The holder half of {@link DurabilitySemaphore}, free of Workers-only imports
52
+ * so it can be tested outside workerd.
53
+ *
54
+ * A composable DO capability holding one concurrency limit for many client
55
+ * Durable Objects. Requests arriving within a round are allocated together in
56
+ * arrival order; clients report claimed and released permits as cumulative
57
+ * counts, so lost or repeated reports can never free capacity twice.
58
+ */
59
+ export class DurabilitySemaphoreServer {
60
+ constructor(config) {
61
+ _DurabilitySemaphoreServer_instances.add(this);
62
+ _DurabilitySemaphoreServer_engine.set(this, void 0);
63
+ _DurabilitySemaphoreServer_store.set(this, void 0);
64
+ _DurabilitySemaphoreServer_limit.set(this, void 0);
65
+ _DurabilitySemaphoreServer_groupLimit.set(this, void 0);
66
+ _DurabilitySemaphoreServer_canGrant.set(this, void 0);
67
+ _DurabilitySemaphoreServer_roundWaitMs.set(this, void 0);
68
+ _DurabilitySemaphoreServer_roundPeriodMs.set(this, void 0);
69
+ _DurabilitySemaphoreServer_grantTimeoutMs.set(this, void 0);
70
+ _DurabilitySemaphoreServer_leases.set(this, void 0);
71
+ _DurabilitySemaphoreServer_emit.set(this, void 0);
72
+ _DurabilitySemaphoreServer_pending.set(this, []);
73
+ _DurabilitySemaphoreServer_roundTimer.set(this, void 0);
74
+ _DurabilitySemaphoreServer_round.set(this, void 0);
75
+ _DurabilitySemaphoreServer_lastRoundAt.set(this, -Infinity);
76
+ // From the last round; tells clients in later syncs to return idle lease headroom.
77
+ _DurabilitySemaphoreServer_contended.set(this, false);
78
+ const limit = config.limit;
79
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_limit, typeof limit === 'function' ? limit : () => limit, "f");
80
+ if (typeof limit === 'number' &&
81
+ (!Number.isSafeInteger(limit) || limit < 0)) {
82
+ throw new RangeError('limit must be a non-negative safe integer');
83
+ }
84
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_groupLimit, config.groupLimit, "f");
85
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_canGrant, config.canGrant, "f");
86
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_roundWaitMs, config.roundWaitMs ?? 1000, "f");
87
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_roundPeriodMs, config.roundPeriodMs ?? 2000, "f");
88
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_grantTimeoutMs, config.grantTimeoutMs ?? 10000, "f");
89
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_leases, config.leases && resolveLeasePolicy(config.leases), "f");
90
+ for (const [name, value] of [
91
+ ['roundWaitMs', __classPrivateFieldGet(this, _DurabilitySemaphoreServer_roundWaitMs, "f")],
92
+ ['roundPeriodMs', __classPrivateFieldGet(this, _DurabilitySemaphoreServer_roundPeriodMs, "f")],
93
+ ['grantTimeoutMs', __classPrivateFieldGet(this, _DurabilitySemaphoreServer_grantTimeoutMs, "f")],
94
+ ]) {
95
+ assertPositiveInteger(name, value);
96
+ if (value > maxDelayMs) {
97
+ throw new RangeError(`${name} must be at most ${maxDelayMs}`);
98
+ }
99
+ }
100
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_engine, engineFor(config), "f");
101
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_emit, traceLifecycle(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").emitter(config.onLifecycleEvent)), "f");
102
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").migrateSchema('semaphore', durabilitySemaphoreMigrations);
103
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_store, new HolderStore(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").sql), "f");
104
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").register({
105
+ table: grantsTable,
106
+ runDue: () => __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_reclaimExpired).call(this),
107
+ nextPendingAt: () => __classPrivateFieldGet(this, _DurabilitySemaphoreServer_store, "f").nextPendingAt(),
108
+ });
109
+ }
110
+ static migrate(context, target) {
111
+ return migrateCapability(context.storage, 'semaphore', durabilitySemaphoreMigrations, target);
112
+ }
113
+ alarm(info) {
114
+ return __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").alarm(info);
115
+ }
116
+ /**
117
+ * The single entry point the application exposes over RPC. A `request` is
118
+ * answered when its round runs; the caller must keep awaiting it. Pending
119
+ * requests live in memory only: if the object is evicted first, the call
120
+ * fails and the client asks again.
121
+ */
122
+ handle(message) {
123
+ const parsed = semaphoreRequestSchema.safeParse(message);
124
+ if (!parsed.success) {
125
+ return Promise.reject(new SemaphoreProtocolError('Malformed semaphore message'));
126
+ }
127
+ if (parsed.data.type === 'sync') {
128
+ return __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_sync).call(this, parsed.data);
129
+ }
130
+ const request = parsed.data;
131
+ return new Promise((resolve, reject) => {
132
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_pending, "f").push({ request, resolve, reject });
133
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_scheduleRound).call(this);
134
+ });
135
+ }
136
+ async usage() {
137
+ const now = Date.now();
138
+ const limit = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_resolveLimit).call(this);
139
+ const grants = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_store, "f").list();
140
+ const leases = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_store, "f").listLeases();
141
+ const groups = new Map();
142
+ let granted = 0;
143
+ for (const grant of grants) {
144
+ const count = outstanding(grant, now);
145
+ granted += count;
146
+ const group = groups.get(grant.grp) ?? { granted: 0 };
147
+ group.granted += count;
148
+ groups.set(grant.grp, group);
149
+ }
150
+ let leased = 0;
151
+ for (const lease of leases) {
152
+ leased += leaseFootprint(lease);
153
+ }
154
+ await Promise.all([...groups.entries()].map(async ([name, group]) => {
155
+ const policy = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_groupPolicy).call(this, name);
156
+ if (policy.limit !== undefined) {
157
+ group.limit = policy.limit;
158
+ }
159
+ }));
160
+ return {
161
+ limit,
162
+ granted,
163
+ leased,
164
+ available: __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_grantRoom).call(this, limit, granted, leased),
165
+ groups,
166
+ };
167
+ }
168
+ }
169
+ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_store = new WeakMap(), _DurabilitySemaphoreServer_limit = new WeakMap(), _DurabilitySemaphoreServer_groupLimit = new WeakMap(), _DurabilitySemaphoreServer_canGrant = new WeakMap(), _DurabilitySemaphoreServer_roundWaitMs = new WeakMap(), _DurabilitySemaphoreServer_roundPeriodMs = new WeakMap(), _DurabilitySemaphoreServer_grantTimeoutMs = new WeakMap(), _DurabilitySemaphoreServer_leases = new WeakMap(), _DurabilitySemaphoreServer_emit = new WeakMap(), _DurabilitySemaphoreServer_pending = new WeakMap(), _DurabilitySemaphoreServer_roundTimer = new WeakMap(), _DurabilitySemaphoreServer_round = new WeakMap(), _DurabilitySemaphoreServer_lastRoundAt = new WeakMap(), _DurabilitySemaphoreServer_contended = new WeakMap(), _DurabilitySemaphoreServer_instances = new WeakSet(), _DurabilitySemaphoreServer_grantRoom = function _DurabilitySemaphoreServer_grantRoom(limit, granted, leased) {
170
+ if (!__classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f")) {
171
+ return Math.max(0, limit - granted);
172
+ }
173
+ const budget = budgets(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f").provisioning, limit);
174
+ return Math.max(0, budget.grants - granted - (budget.shared ? leased : 0));
175
+ }, _DurabilitySemaphoreServer_scheduleRound = function _DurabilitySemaphoreServer_scheduleRound() {
176
+ if (__classPrivateFieldGet(this, _DurabilitySemaphoreServer_roundTimer, "f") !== undefined || __classPrivateFieldGet(this, _DurabilitySemaphoreServer_round, "f") !== undefined) {
177
+ return;
178
+ }
179
+ const earliest = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_lastRoundAt, "f") + __classPrivateFieldGet(this, _DurabilitySemaphoreServer_roundPeriodMs, "f");
180
+ const delay = Math.max(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_roundWaitMs, "f"), earliest - Date.now());
181
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_roundTimer, setTimeout(() => {
182
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_roundTimer, undefined, "f");
183
+ const onError = (error) => reportFailure('durability.semaphore.round_failed', {}, error);
184
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_round, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_runRound).call(this)
185
+ .catch(onError)
186
+ .finally(() => {
187
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_round, undefined, "f");
188
+ if (__classPrivateFieldGet(this, _DurabilitySemaphoreServer_pending, "f").length > 0) {
189
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_scheduleRound).call(this);
190
+ }
191
+ }), "f");
192
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").waitUntil(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_round, "f"), onError);
193
+ }, delay), "f");
194
+ }, _DurabilitySemaphoreServer_runRound = async function _DurabilitySemaphoreServer_runRound() {
195
+ const pending = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_pending, "f");
196
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_pending, [], "f");
197
+ const now = Date.now();
198
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_lastRoundAt, now, "f");
199
+ let round;
200
+ try {
201
+ const limit = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_resolveLimit).call(this);
202
+ // Held leases are re-checked every round, not only when their group is
203
+ // requested, so a group that became limited or blocked is retired.
204
+ const leaseGroups = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f")
205
+ ? __classPrivateFieldGet(this, _DurabilitySemaphoreServer_store, "f").listLeases().map((lease) => lease.grp)
206
+ : [];
207
+ const groups = new Set([
208
+ ...pending.flatMap(({ request }) => request.demand.map((d) => d.group)),
209
+ ...leaseGroups,
210
+ ]);
211
+ const policies = new Map(await Promise.all([...groups].map(async (group) => [group, await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_groupPolicy).call(this, group)])));
212
+ round = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").transaction(() => __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_allocate).call(this, pending, limit, policies, now));
213
+ }
214
+ catch (error) {
215
+ for (const entry of pending) {
216
+ entry.reject(error);
217
+ }
218
+ throw error;
219
+ }
220
+ const nextRequestAt = now + __classPrivateFieldGet(this, _DurabilitySemaphoreServer_roundPeriodMs, "f");
221
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_contended, round.contended, "f");
222
+ for (const [entry, allocation] of round.allocations) {
223
+ const { leases, ...rest } = allocation;
224
+ entry.resolve({
225
+ type: 'grant',
226
+ v: 1,
227
+ ...rest,
228
+ nextRequestAt,
229
+ ...(entry.request.leases === undefined
230
+ ? {}
231
+ : { leases, ...(round.contended ? { contended: true } : {}) }),
232
+ });
233
+ }
234
+ for (const event of [...round.reclaimed, ...round.leaseEvents]) {
235
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_emit, "f").call(this, event);
236
+ }
237
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_emit, "f").call(this, {
238
+ entityKind: 'semaphore',
239
+ type: 'round',
240
+ timestamp: Date.now(),
241
+ requested: round.requested,
242
+ granted: round.granted,
243
+ usage: round.usage,
244
+ });
245
+ for (const [group, reason, count] of blockedCounts(round.allocations)) {
246
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_emit, "f").call(this, {
247
+ entityKind: 'semaphore',
248
+ type: 'blocked',
249
+ timestamp: Date.now(),
250
+ group,
251
+ reason,
252
+ count,
253
+ });
254
+ }
255
+ }, _DurabilitySemaphoreServer_allocate = function _DurabilitySemaphoreServer_allocate(pending, limit, policies, now) {
256
+ const store = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_store, "f");
257
+ const allocations = new Map();
258
+ let unknownDebt = 0;
259
+ const drawn = new Map();
260
+ for (const entry of pending) {
261
+ const { clientId } = entry.request;
262
+ const grantResults = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_applyReports).call(this, store, clientId, entry.request.grants, now);
263
+ const leases = [];
264
+ if (__classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f") && entry.request.leases) {
265
+ const outcome = applyLeaseReports(store, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f"), clientId, entry.request.leases, now);
266
+ leases.push(...outcome.echoes);
267
+ unknownDebt += outcome.unknownDebt;
268
+ for (const [leaseId, count] of outcome.drawn) {
269
+ drawn.set(leaseId, count);
270
+ }
271
+ }
272
+ allocations.set(entry, { grants: [], blocked: [], grantResults, leases });
273
+ }
274
+ const used = new Map();
275
+ let total = 0;
276
+ const reclaimed = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_reclaim).call(this, store, now);
277
+ for (const grant of reclaimed.grants) {
278
+ const count = outstanding(grant, now);
279
+ total += count;
280
+ used.set(grant.grp, (used.get(grant.grp) ?? 0) + count);
281
+ }
282
+ // In strict mode live lease footprint is reserved from the same pool as grants.
283
+ const budget = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f")
284
+ ? budgets(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f").provisioning, limit)
285
+ : { grants: limit, leases: 0, shared: false };
286
+ let leased = 0;
287
+ if (__classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f") && budget.shared) {
288
+ for (const lease of store.listLeases()) {
289
+ leased += leaseFootprint(lease);
290
+ }
291
+ }
292
+ let remaining = budget.grants - total - (budget.shared ? leased : 0);
293
+ const demands = pending
294
+ .flatMap((entry) => entry.request.demand.map((demand) => ({ entry, ...demand })))
295
+ .sort((left, right) => left.oldestAt - right.oldestAt ||
296
+ left.entry.request.clientId.localeCompare(right.entry.request.clientId));
297
+ let requested = 0;
298
+ let granted = 0;
299
+ for (const demand of demands) {
300
+ requested += demand.count;
301
+ const allocation = allocations.get(demand.entry);
302
+ const policy = policies.get(demand.group) ?? {};
303
+ if (policy.blocked) {
304
+ allocation.blocked.push({
305
+ group: demand.group,
306
+ reason: policy.blocked,
307
+ });
308
+ continue;
309
+ }
310
+ const groupUsed = used.get(demand.group) ?? 0;
311
+ const groupRemaining = policy.limit === undefined ? Infinity : policy.limit - groupUsed;
312
+ const give = Math.max(0, Math.min(demand.count, groupRemaining, remaining));
313
+ if (give > 0) {
314
+ const grant = {
315
+ grant_id: crypto.randomUUID(),
316
+ client_id: demand.entry.request.clientId,
317
+ grp: demand.group,
318
+ permits: give,
319
+ claimed: 0,
320
+ released: 0,
321
+ created_at: now,
322
+ expires_at: now + __classPrivateFieldGet(this, _DurabilitySemaphoreServer_grantTimeoutMs, "f"),
323
+ };
324
+ store.insert(grant);
325
+ allocation.grants.push({
326
+ grantId: grant.grant_id,
327
+ group: demand.group,
328
+ permits: give,
329
+ });
330
+ remaining -= give;
331
+ used.set(demand.group, groupUsed + give);
332
+ granted += give;
333
+ }
334
+ if (give < demand.count) {
335
+ // The group gate is checked first so attribution names the tighter one.
336
+ allocation.blocked.push({
337
+ group: demand.group,
338
+ reason: groupRemaining - give <= 0 ? 'group_limit' : 'limit',
339
+ });
340
+ }
341
+ }
342
+ let leaseEvents = [];
343
+ let contended = false;
344
+ if (__classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f")) {
345
+ const candidates = pending.flatMap((entry) => entry.request.leases === undefined
346
+ ? []
347
+ : entry.request.demand.map((demand) => ({
348
+ clientId: entry.request.clientId,
349
+ group: demand.group,
350
+ oldestAt: demand.oldestAt,
351
+ })));
352
+ // The allocator nets out live footprint itself; hand it gross capacity.
353
+ const leaseBudget = budget.shared
354
+ ? Math.max(0, limit - total - granted)
355
+ : budget.leases;
356
+ const outcome = allocateLeases(store, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f"), {
357
+ budget: leaseBudget,
358
+ unknownDebt,
359
+ drawn,
360
+ candidates,
361
+ policies,
362
+ groupUsed: used,
363
+ now,
364
+ });
365
+ leased = outcome.footprint;
366
+ leaseEvents = outcome.events;
367
+ // Returned headroom helps grants only when they share the limit with leases.
368
+ contended =
369
+ outcome.unserved ||
370
+ (budget.shared &&
371
+ [...allocations.values()].some((allocation) => allocation.blocked.some(({ reason }) => reason === 'limit')));
372
+ for (const [entry, allocation] of allocations) {
373
+ // One echo per lease; the allocator's view (e.g. retired) supersedes the report's.
374
+ const byLease = new Map([
375
+ ...allocation.leases,
376
+ ...(outcome.grants.get(entry.request.clientId) ?? []),
377
+ ].map((lease) => [lease.leaseId, lease]));
378
+ allocation.leases = [...byLease.values()];
379
+ }
380
+ if (budget.shared) {
381
+ remaining = limit - total - granted - leased;
382
+ }
383
+ }
384
+ const groups = new Map([...used].map(([group, count]) => {
385
+ const policy = policies.get(group);
386
+ return [
387
+ group,
388
+ policy?.limit === undefined
389
+ ? { granted: count }
390
+ : { granted: count, limit: policy.limit },
391
+ ];
392
+ }));
393
+ return {
394
+ allocations,
395
+ requested,
396
+ granted,
397
+ reclaimed: reclaimed.events,
398
+ leaseEvents,
399
+ contended,
400
+ usage: {
401
+ limit,
402
+ granted: total + granted,
403
+ leased,
404
+ available: Math.max(0, remaining),
405
+ groups,
406
+ },
407
+ };
408
+ }, _DurabilitySemaphoreServer_sync = async function _DurabilitySemaphoreServer_sync(message) {
409
+ const now = Date.now();
410
+ const result = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").transaction(() => {
411
+ const store = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_store, "f");
412
+ const grantResults = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_applyReports).call(this, store, message.clientId, message.grants, now);
413
+ const leaseOutcome = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f") && message.leases
414
+ ? applyLeaseReports(store, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f"), message.clientId, message.leases, now)
415
+ : undefined;
416
+ return { grantResults, leaseEchoes: leaseOutcome?.echoes };
417
+ });
418
+ return {
419
+ type: 'synced',
420
+ v: 1,
421
+ grantResults: result.grantResults,
422
+ ...(result.leaseEchoes === undefined
423
+ ? {}
424
+ : {
425
+ leases: result.leaseEchoes,
426
+ ...(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_contended, "f") ? { contended: true } : {}),
427
+ }),
428
+ };
429
+ }, _DurabilitySemaphoreServer_applyReports = function _DurabilitySemaphoreServer_applyReports(store, clientId, reports, now) {
430
+ const results = [];
431
+ for (const report of reports) {
432
+ const grant = store.get(report.grantId);
433
+ if (!grant || grant.client_id !== clientId) {
434
+ results.push({
435
+ grantId: report.grantId,
436
+ claimed: 0,
437
+ status: 'not_found',
438
+ });
439
+ continue;
440
+ }
441
+ const expired = now >= grant.expires_at;
442
+ const permits = effectivePermits(grant, now);
443
+ const claimed = Math.max(grant.claimed, Math.min(report.claimed, permits));
444
+ const released = Math.max(grant.released, Math.min(report.released, claimed));
445
+ const updated = { ...grant, permits, claimed, released };
446
+ if (released >= permits) {
447
+ store.remove(grant.grant_id);
448
+ }
449
+ else {
450
+ store.update(updated);
451
+ }
452
+ results.push({
453
+ grantId: grant.grant_id,
454
+ claimed,
455
+ status: expired && report.claimed > claimed ? 'expired' : 'ok',
456
+ });
457
+ }
458
+ return results;
459
+ }, _DurabilitySemaphoreServer_reclaim = function _DurabilitySemaphoreServer_reclaim(store, now) {
460
+ const kept = [];
461
+ const events = [];
462
+ for (const grant of store.list()) {
463
+ if (now < grant.expires_at || grant.claimed >= grant.permits) {
464
+ kept.push(grant);
465
+ continue;
466
+ }
467
+ const updated = { ...grant, permits: grant.claimed };
468
+ if (updated.released >= updated.permits) {
469
+ store.remove(grant.grant_id);
470
+ }
471
+ else {
472
+ store.update(updated);
473
+ kept.push(updated);
474
+ }
475
+ events.push({
476
+ entityKind: 'semaphore',
477
+ type: 'grant_reclaimed',
478
+ timestamp: now,
479
+ grantId: grant.grant_id,
480
+ clientId: grant.client_id,
481
+ group: grant.grp,
482
+ permits: grant.permits - grant.claimed,
483
+ });
484
+ }
485
+ return { grants: kept, events };
486
+ }, _DurabilitySemaphoreServer_reclaimExpired = async function _DurabilitySemaphoreServer_reclaimExpired() {
487
+ const events = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").transaction(() => __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_reclaim).call(this, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_store, "f"), Date.now()).events);
488
+ for (const event of events) {
489
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_emit, "f").call(this, event);
490
+ }
491
+ }, _DurabilitySemaphoreServer_resolveLimit = async function _DurabilitySemaphoreServer_resolveLimit() {
492
+ const limit = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_limit, "f").call(this);
493
+ if (!Number.isSafeInteger(limit) || limit < 0) {
494
+ throw new RangeError('limit must resolve to a non-negative safe integer');
495
+ }
496
+ return limit;
497
+ }, _DurabilitySemaphoreServer_groupPolicy =
498
+ // Resolution failures block the group rather than granting unlimited permits.
499
+ async function _DurabilitySemaphoreServer_groupPolicy(group) {
500
+ try {
501
+ if (__classPrivateFieldGet(this, _DurabilitySemaphoreServer_canGrant, "f") && !(await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_canGrant, "f").call(this, group))) {
502
+ return { blocked: 'not_permitted' };
503
+ }
504
+ const limit = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_groupLimit, "f")?.call(this, group);
505
+ if (limit === undefined) {
506
+ return {};
507
+ }
508
+ if (!Number.isSafeInteger(limit) || limit < 0) {
509
+ throw new RangeError(`groupLimit for "${group}" must be a non-negative safe integer`);
510
+ }
511
+ return { limit };
512
+ }
513
+ catch (error) {
514
+ reportFailure('durability.semaphore.limit_resolution_failed', { group }, error);
515
+ return { blocked: 'limit_resolution_error' };
516
+ }
517
+ };
518
+ traceMethods(DurabilitySemaphoreServer.prototype, 'DurabilitySemaphore');
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+ export declare const grantRowSchema: z.ZodObject<{
3
+ grant_id: z.ZodString;
4
+ client_id: z.ZodString;
5
+ grp: z.ZodString;
6
+ permits: z.ZodNumber;
7
+ claimed: z.ZodNumber;
8
+ released: z.ZodNumber;
9
+ created_at: z.ZodNumber;
10
+ expires_at: z.ZodNumber;
11
+ }, z.core.$strip>;
12
+ export type GrantRow = z.infer<typeof grantRowSchema>;
13
+ /** Permits a client may draw locally without a round trip; held by the holder. */
14
+ export declare const leaseRowSchema: z.ZodObject<{
15
+ lease_id: z.ZodString;
16
+ client_id: z.ZodString;
17
+ grp: z.ZodString;
18
+ permits: z.ZodNumber;
19
+ released: z.ZodNumber;
20
+ created_at: z.ZodNumber;
21
+ expires_at: z.ZodNumber;
22
+ retired: z.ZodNumber;
23
+ }, z.core.$strip>;
24
+ export type LeaseRow = z.infer<typeof leaseRowSchema>;
25
+ /**
26
+ * Permits a semaphore has handed out. Grants and leases are small and bounded
27
+ * by live clients, so aggregates are computed from `list()`.
28
+ */
29
+ export declare class HolderStore {
30
+ private readonly sql;
31
+ constructor(sql: SqlStorage);
32
+ list(): GrantRow[];
33
+ get(grantId: string): GrantRow | undefined;
34
+ nextPendingAt(): number | undefined;
35
+ insert(row: GrantRow): boolean;
36
+ update(row: GrantRow): void;
37
+ remove(grantId: string): void;
38
+ listLeases(): LeaseRow[];
39
+ getLease(leaseId: string): LeaseRow | undefined;
40
+ insertLease(row: LeaseRow): boolean;
41
+ updateLease(row: LeaseRow): void;
42
+ removeLease(leaseId: string): void;
43
+ }