durability 5.2.0 → 5.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.
@@ -1,29 +1,34 @@
1
- import { z } from 'zod';
2
- export declare const grantRowSchema: z.ZodObject<{
3
- grant_id: z.ZodString;
4
- client_id: z.ZodString;
5
- client_channel: z.ZodString;
6
- grp: z.ZodString;
7
- permits: z.ZodNumber;
8
- claimed: z.ZodNumber;
9
- released: z.ZodNumber;
10
- created_at: z.ZodNumber;
11
- expires_at: z.ZodNumber;
12
- }, z.core.$strip>;
13
- export type GrantRow = z.infer<typeof grantRowSchema>;
1
+ import * as v from 'valibot';
2
+ export declare const grantRowSchema: v.ObjectSchema<{
3
+ readonly grant_id: v.StringSchema<undefined>;
4
+ readonly client_id: v.StringSchema<undefined>;
5
+ /** The client's queue channel; `clientId` alone does not identify a client. */
6
+ readonly client_channel: v.StringSchema<undefined>;
7
+ readonly grp: v.StringSchema<undefined>;
8
+ readonly permits: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
9
+ readonly claimed: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
10
+ readonly released: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
11
+ readonly created_at: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
12
+ /** Unclaimed permits are reclaimed once this passes. */
13
+ readonly expires_at: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
14
+ }, undefined>;
15
+ export type GrantRow = v.InferOutput<typeof grantRowSchema>;
14
16
  /** Permits a client may draw locally without a round trip; held by the holder. */
15
- export declare const leaseRowSchema: z.ZodObject<{
16
- lease_id: z.ZodString;
17
- client_id: z.ZodString;
18
- client_channel: z.ZodString;
19
- grp: z.ZodString;
20
- permits: z.ZodNumber;
21
- released: z.ZodNumber;
22
- created_at: z.ZodNumber;
23
- expires_at: z.ZodNumber;
24
- retired: z.ZodNumber;
25
- }, z.core.$strip>;
26
- export type LeaseRow = z.infer<typeof leaseRowSchema>;
17
+ export declare const leaseRowSchema: v.ObjectSchema<{
18
+ readonly lease_id: v.StringSchema<undefined>;
19
+ readonly client_id: v.StringSchema<undefined>;
20
+ readonly client_channel: v.StringSchema<undefined>;
21
+ readonly grp: v.StringSchema<undefined>;
22
+ readonly permits: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
23
+ /** Drawn permits the client has returned, as a high-water mark. */
24
+ readonly released: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
25
+ readonly created_at: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
26
+ /** Refreshed by every report; the lease is swept once this passes. */
27
+ readonly expires_at: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
28
+ /** 1 once no more permits may be drawn; footprint stays until released. */
29
+ readonly retired: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.SafeIntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>, v.MaxValueAction<number, 1, undefined>]>;
30
+ }, undefined>;
31
+ export type LeaseRow = v.InferOutput<typeof leaseRowSchema>;
27
32
  /**
28
33
  * Permits one semaphore channel has handed out. Every query is scoped to the
29
34
  * channel, so semaphores sharing an object never see each other's grants or
@@ -1,34 +1,34 @@
1
- import { z } from 'zod';
2
- export const grantRowSchema = z.object({
3
- grant_id: z.string(),
4
- client_id: z.string(),
1
+ import * as v from 'valibot';
2
+ export const grantRowSchema = v.object({
3
+ grant_id: v.string(),
4
+ client_id: v.string(),
5
5
  /** The client's queue channel; `clientId` alone does not identify a client. */
6
- client_channel: z.string(),
7
- grp: z.string(),
8
- permits: z.number().int().nonnegative(),
9
- claimed: z.number().int().nonnegative(),
10
- released: z.number().int().nonnegative(),
11
- created_at: z.number().int().nonnegative(),
6
+ client_channel: v.string(),
7
+ grp: v.string(),
8
+ permits: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
9
+ claimed: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
10
+ released: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
11
+ created_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
12
12
  /** Unclaimed permits are reclaimed once this passes. */
13
- expires_at: z.number().int().nonnegative(),
13
+ expires_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
14
14
  });
15
15
  /** Permits a client may draw locally without a round trip; held by the holder. */
16
- export const leaseRowSchema = z.object({
17
- lease_id: z.string(),
18
- client_id: z.string(),
19
- client_channel: z.string(),
20
- grp: z.string(),
21
- permits: z.number().int().nonnegative(),
16
+ export const leaseRowSchema = v.object({
17
+ lease_id: v.string(),
18
+ client_id: v.string(),
19
+ client_channel: v.string(),
20
+ grp: v.string(),
21
+ permits: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
22
22
  /** Drawn permits the client has returned, as a high-water mark. */
23
- released: z.number().int().nonnegative(),
24
- created_at: z.number().int().nonnegative(),
23
+ released: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
24
+ created_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
25
25
  /** Refreshed by every report; the lease is swept once this passes. */
26
- expires_at: z.number().int().nonnegative(),
26
+ expires_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
27
27
  /** 1 once no more permits may be drawn; footprint stays until released. */
28
- retired: z.number().int().min(0).max(1),
28
+ retired: v.pipe(v.number(), v.safeInteger(), v.minValue(0), v.maxValue(1)),
29
29
  });
30
- const grantColumns = grantRowSchema.keyof().options;
31
- const leaseColumns = leaseRowSchema.keyof().options;
30
+ const grantColumns = v.keyof(grantRowSchema).options;
31
+ const leaseColumns = v.keyof(leaseRowSchema).options;
32
32
  /**
33
33
  * Permits one semaphore channel has handed out. Every query is scoped to the
34
34
  * channel, so semaphores sharing an object never see each other's grants or
@@ -41,26 +41,23 @@ export class HolderStore {
41
41
  this.channel = channel;
42
42
  }
43
43
  list() {
44
- return grantRowSchema.array().parse(this.sql
44
+ return v.parse(v.array(grantRowSchema), this.sql
45
45
  .exec(`SELECT * FROM durability_semaphore_grants
46
46
  WHERE channel = ? ORDER BY created_at`, this.channel)
47
47
  .toArray());
48
48
  }
49
49
  get(grantId) {
50
- return grantRowSchema.optional().parse(this.sql
50
+ return v.parse(v.optional(grantRowSchema), this.sql
51
51
  .exec(`SELECT * FROM durability_semaphore_grants
52
52
  WHERE channel = ? AND grant_id = ? LIMIT 1`, this.channel, grantId)
53
53
  .toArray()[0]);
54
54
  }
55
55
  nextPendingAt() {
56
- return grantRowSchema
57
- .pick({ expires_at: true })
58
- .optional()
59
- .parse(this.sql
56
+ return v.parse(v.optional(v.pick(grantRowSchema, ['expires_at'])), this.sql
60
57
  .exec(`SELECT expires_at FROM durability_semaphore_grants
61
- WHERE channel = ? AND claimed < permits
62
- ORDER BY expires_at ASC
63
- LIMIT 1`, this.channel)
58
+ WHERE channel = ? AND claimed < permits
59
+ ORDER BY expires_at ASC
60
+ LIMIT 1`, this.channel)
64
61
  .toArray()[0])?.expires_at;
65
62
  }
66
63
  insert(row) {
@@ -80,13 +77,13 @@ export class HolderStore {
80
77
  this.sql.exec('DELETE FROM durability_semaphore_grants WHERE channel = ? AND grant_id = ?', this.channel, grantId);
81
78
  }
82
79
  listLeases() {
83
- return leaseRowSchema.array().parse(this.sql
80
+ return v.parse(v.array(leaseRowSchema), this.sql
84
81
  .exec(`SELECT * FROM durability_semaphore_leases
85
82
  WHERE channel = ? ORDER BY created_at`, this.channel)
86
83
  .toArray());
87
84
  }
88
85
  getLease(leaseId) {
89
- return leaseRowSchema.optional().parse(this.sql
86
+ return v.parse(v.optional(leaseRowSchema), this.sql
90
87
  .exec(`SELECT * FROM durability_semaphore_leases
91
88
  WHERE channel = ? AND lease_id = ? LIMIT 1`, this.channel, leaseId)
92
89
  .toArray()[0]);
@@ -1,3 +1,8 @@
1
+ import * as v from 'valibot';
2
+ export type Json = string | number | boolean | null | Json[] | {
3
+ [key: string]: Json;
4
+ };
5
+ export declare const jsonSchema: v.CustomSchema<Json, v.ErrorMessage<v.CustomIssue> | undefined>;
1
6
  export declare const serialize: (value: unknown) => string;
2
7
  export declare const deserialize: (value: string) => unknown;
3
8
  /**
@@ -1,11 +1,40 @@
1
- import { z } from 'zod';
2
- const storedValueSchema = z.discriminatedUnion('kind', [
3
- z.object({ kind: z.literal('value'), value: z.json() }),
4
- z.object({ kind: z.literal('undefined') }),
1
+ import * as v from 'valibot';
2
+ const isPlainObject = (value) => {
3
+ if (value === null || typeof value !== 'object') {
4
+ return false;
5
+ }
6
+ const prototype = Object.getPrototypeOf(value);
7
+ return prototype === Object.prototype || prototype === null;
8
+ };
9
+ const isJson = (value) => {
10
+ if (value === null ||
11
+ typeof value === 'string' ||
12
+ typeof value === 'boolean') {
13
+ return true;
14
+ }
15
+ if (typeof value === 'number') {
16
+ return Number.isFinite(value);
17
+ }
18
+ if (Array.isArray(value)) {
19
+ // `every` would skip the holes of a sparse array, which are not JSON.
20
+ for (const item of value) {
21
+ if (!isJson(item)) {
22
+ return false;
23
+ }
24
+ }
25
+ return true;
26
+ }
27
+ return isPlainObject(value) && Object.values(value).every(isJson);
28
+ };
29
+ // Not built from `v.record`, which silently drops `constructor` and `prototype` keys.
30
+ export const jsonSchema = v.custom(isJson, 'Invalid JSON value');
31
+ const storedValueSchema = v.variant('kind', [
32
+ v.object({ kind: v.literal('value'), value: jsonSchema }),
33
+ v.object({ kind: v.literal('undefined') }),
5
34
  ]);
6
35
  /**
7
36
  * What `JSON.stringify` would produce: `undefined` properties are dropped and
8
- * `undefined` array elements become `null`. `z.json()` rejects both as given,
37
+ * `undefined` array elements become `null`. `jsonSchema` rejects both as given,
9
38
  * although they are routine in values such as lifecycle events whose handler
10
39
  * returned nothing.
11
40
  */
@@ -13,24 +42,20 @@ const asJson = (value) => {
13
42
  if (Array.isArray(value)) {
14
43
  return value.map((item) => (item === undefined ? null : asJson(item)));
15
44
  }
16
- if (value === null || typeof value !== 'object') {
17
- return value;
18
- }
19
45
  // Only plain objects are rewritten; anything else must fail validation as is.
20
- const prototype = Object.getPrototypeOf(value);
21
- if (prototype === Object.prototype || prototype === null) {
22
- return Object.fromEntries(Object.entries(value)
23
- .filter(([, item]) => item !== undefined)
24
- .map(([key, item]) => [key, asJson(item)]));
46
+ if (!isPlainObject(value)) {
47
+ return value;
25
48
  }
26
- return value;
49
+ return Object.fromEntries(Object.entries(value)
50
+ .filter(([, item]) => item !== undefined)
51
+ .map(([key, item]) => [key, asJson(item)]));
27
52
  };
28
53
  // Wrapping preserves a successful `undefined` result, which bare JSON cannot represent.
29
54
  export const serialize = (value) => JSON.stringify(value === undefined
30
55
  ? { kind: 'undefined' }
31
- : { kind: 'value', value: z.json().parse(asJson(value)) });
56
+ : { kind: 'value', value: v.parse(jsonSchema, asJson(value)) });
32
57
  export const deserialize = (value) => {
33
- const stored = storedValueSchema.parse(JSON.parse(value));
58
+ const stored = v.parse(storedValueSchema, JSON.parse(value));
34
59
  return stored.kind === 'undefined' ? undefined : stored.value;
35
60
  };
36
61
  const canonicalize = (value) => {
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Runs callbacks after a delay like `setTimeout`, but keeps every pending
3
+ * callback in a min-heap ordered by due time and sets one native timer for the
4
+ * earliest. workerd makes `setTimeout` throw once 10,000 native timers are
5
+ * pending, so an object whose open timeouts grow with its workload schedules
6
+ * them here instead of setting a native timer for each.
7
+ *
8
+ * Callbacks due together run one after another in the same task, so promise
9
+ * reactions queued by one do not run before the next as they would between
10
+ * separate native timers. A callback scheduled by one of them runs in a later
11
+ * task even with no delay.
12
+ *
13
+ * A native timer belongs to the request or Durable Object that set it, so an
14
+ * instance must not be shared between them.
15
+ */
16
+ export declare class SharedTimer {
17
+ #private;
18
+ /** Callbacks that have neither run nor been cancelled. */
19
+ get pendingCount(): number;
20
+ /** Runs `callback` once after `delayMs` and returns a function that cancels it. */
21
+ schedule(callback: () => void, delayMs: number): () => void;
22
+ /**
23
+ * Settles like `work`, or rejects with the error from `onTimeout` when
24
+ * `work` is still pending after `timeoutMs`.
25
+ */
26
+ withTimeout<T>(work: Promise<T>, timeoutMs: number, onTimeout: () => Error): Promise<T>;
27
+ }
@@ -0,0 +1,191 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ 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");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
6
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7
+ if (kind === "m") throw new TypeError("Private method is not writable");
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
9
+ 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");
10
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
+ };
12
+ var _SharedTimer_instances, _SharedTimer_heap, _SharedTimer_scheduledCount, _SharedTimer_nativeTimer, _SharedTimer_setNativeTimer, _SharedTimer_runDue, _SharedTimer_remove, _SharedTimer_place, _SharedTimer_moveUp, _SharedTimer_moveDown;
13
+ import { reportFailure } from './errors.js';
14
+ // setTimeout overflows past 2^31 - 1 ms and fires at once. A longer wait is
15
+ // set for this long, finds nothing due when it fires, and is set again.
16
+ const maxNativeDelayMs = 2 ** 31 - 1;
17
+ const isBefore = (firstEntry, secondEntry) => firstEntry.dueAt < secondEntry.dueAt ||
18
+ (firstEntry.dueAt === secondEntry.dueAt &&
19
+ firstEntry.order < secondEntry.order);
20
+ /**
21
+ * Runs callbacks after a delay like `setTimeout`, but keeps every pending
22
+ * callback in a min-heap ordered by due time and sets one native timer for the
23
+ * earliest. workerd makes `setTimeout` throw once 10,000 native timers are
24
+ * pending, so an object whose open timeouts grow with its workload schedules
25
+ * them here instead of setting a native timer for each.
26
+ *
27
+ * Callbacks due together run one after another in the same task, so promise
28
+ * reactions queued by one do not run before the next as they would between
29
+ * separate native timers. A callback scheduled by one of them runs in a later
30
+ * task even with no delay.
31
+ *
32
+ * A native timer belongs to the request or Durable Object that set it, so an
33
+ * instance must not be shared between them.
34
+ */
35
+ export class SharedTimer {
36
+ constructor() {
37
+ _SharedTimer_instances.add(this);
38
+ _SharedTimer_heap.set(this, []);
39
+ _SharedTimer_scheduledCount.set(this, 0);
40
+ _SharedTimer_nativeTimer.set(this, void 0);
41
+ }
42
+ /** Callbacks that have neither run nor been cancelled. */
43
+ get pendingCount() {
44
+ return __classPrivateFieldGet(this, _SharedTimer_heap, "f").length;
45
+ }
46
+ /** Runs `callback` once after `delayMs` and returns a function that cancels it. */
47
+ schedule(callback, delayMs) {
48
+ var _a, _b;
49
+ const entry = {
50
+ // performance.now() rather than Date.now(): a native timer counts
51
+ // elapsed time, which a change to the wall clock does not affect.
52
+ dueAt: performance.now() + (delayMs > 0 ? delayMs : 0),
53
+ order: (__classPrivateFieldSet(this, _SharedTimer_scheduledCount, (_b = __classPrivateFieldGet(this, _SharedTimer_scheduledCount, "f"), _a = _b++, _b), "f"), _a),
54
+ index: __classPrivateFieldGet(this, _SharedTimer_heap, "f").length,
55
+ callback,
56
+ };
57
+ __classPrivateFieldGet(this, _SharedTimer_heap, "f").push(entry);
58
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_moveUp).call(this, entry);
59
+ // The native timer is also missing if setting it failed in #runDue; the
60
+ // entries left without one get it back here.
61
+ if (entry.index === 0 || __classPrivateFieldGet(this, _SharedTimer_nativeTimer, "f") === undefined) {
62
+ try {
63
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_setNativeTimer).call(this);
64
+ }
65
+ catch (error) {
66
+ // The caller gets the error instead of a cancel function, so the
67
+ // callback must not stay behind and run later.
68
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_remove).call(this, entry);
69
+ throw error;
70
+ }
71
+ }
72
+ return () => {
73
+ entry.callback = undefined;
74
+ if (entry.index === -1) {
75
+ return;
76
+ }
77
+ const wasEarliest = entry.index === 0;
78
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_remove).call(this, entry);
79
+ if (wasEarliest) {
80
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_setNativeTimer).call(this);
81
+ }
82
+ };
83
+ }
84
+ /**
85
+ * Settles like `work`, or rejects with the error from `onTimeout` when
86
+ * `work` is still pending after `timeoutMs`.
87
+ */
88
+ async withTimeout(work, timeoutMs, onTimeout) {
89
+ let cancelTimeout;
90
+ try {
91
+ return await Promise.race([
92
+ work,
93
+ new Promise((_resolve, reject) => {
94
+ cancelTimeout = this.schedule(() => reject(onTimeout()), timeoutMs);
95
+ }),
96
+ ]);
97
+ }
98
+ finally {
99
+ cancelTimeout?.();
100
+ }
101
+ }
102
+ }
103
+ _SharedTimer_heap = new WeakMap(), _SharedTimer_scheduledCount = new WeakMap(), _SharedTimer_nativeTimer = new WeakMap(), _SharedTimer_instances = new WeakSet(), _SharedTimer_setNativeTimer = function _SharedTimer_setNativeTimer() {
104
+ clearTimeout(__classPrivateFieldGet(this, _SharedTimer_nativeTimer, "f"));
105
+ __classPrivateFieldSet(this, _SharedTimer_nativeTimer, undefined, "f");
106
+ const earliest = __classPrivateFieldGet(this, _SharedTimer_heap, "f")[0];
107
+ if (earliest === undefined) {
108
+ return;
109
+ }
110
+ const now = performance.now();
111
+ const wakeAt = Math.min(earliest.dueAt, now + maxNativeDelayMs);
112
+ __classPrivateFieldSet(this, _SharedTimer_nativeTimer, setTimeout(() => __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_runDue).call(this, wakeAt), Math.max(wakeAt - now, 0)), "f");
113
+ }, _SharedTimer_runDue = function _SharedTimer_runDue(wakeAt) {
114
+ // setTimeout drops the fraction of a delay, so it can fire just before the
115
+ // clock reaches `wakeAt`. Counting that as reached runs the callback now
116
+ // instead of setting another timer for the remaining fraction.
117
+ const now = Math.max(performance.now(), wakeAt);
118
+ const due = [];
119
+ let earliest = __classPrivateFieldGet(this, _SharedTimer_heap, "f")[0];
120
+ while (earliest !== undefined && earliest.dueAt <= now) {
121
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_remove).call(this, earliest);
122
+ due.push(earliest);
123
+ earliest = __classPrivateFieldGet(this, _SharedTimer_heap, "f")[0];
124
+ }
125
+ // Set before the callbacks run, and by clearing the native timer that is
126
+ // firing: workerd counts it as pending until this function returns, and a
127
+ // callback could take the last one the runtime allows. Clearing one and
128
+ // setting one cannot fail at that limit, so the entries still in the heap
129
+ // always keep a native timer.
130
+ try {
131
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_setNativeTimer).call(this);
132
+ }
133
+ catch (error) {
134
+ reportFailure('durability.timer.set_failed', { pendingCount: __classPrivateFieldGet(this, _SharedTimer_heap, "f").length }, error);
135
+ }
136
+ for (const entry of due) {
137
+ try {
138
+ entry.callback?.();
139
+ }
140
+ catch (error) {
141
+ // A throw must not keep the callbacks behind it from running.
142
+ reportFailure('durability.timer.callback_failed', { dueAt: entry.dueAt, scheduledOrder: entry.order }, error);
143
+ }
144
+ }
145
+ }, _SharedTimer_remove = function _SharedTimer_remove(entry) {
146
+ const { index } = entry;
147
+ entry.index = -1;
148
+ const last = __classPrivateFieldGet(this, _SharedTimer_heap, "f").pop();
149
+ if (last === undefined || last === entry) {
150
+ return;
151
+ }
152
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_place).call(this, last, index);
153
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_moveUp).call(this, last);
154
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_moveDown).call(this, last);
155
+ }, _SharedTimer_place = function _SharedTimer_place(entry, index) {
156
+ __classPrivateFieldGet(this, _SharedTimer_heap, "f")[index] = entry;
157
+ entry.index = index;
158
+ }, _SharedTimer_moveUp = function _SharedTimer_moveUp(entry) {
159
+ let { index } = entry;
160
+ while (index > 0) {
161
+ const parentIndex = (index - 1) >> 1;
162
+ const parent = __classPrivateFieldGet(this, _SharedTimer_heap, "f")[parentIndex];
163
+ if (parent === undefined || !isBefore(entry, parent)) {
164
+ break;
165
+ }
166
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_place).call(this, parent, index);
167
+ index = parentIndex;
168
+ }
169
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_place).call(this, entry, index);
170
+ }, _SharedTimer_moveDown = function _SharedTimer_moveDown(entry) {
171
+ let { index } = entry;
172
+ for (;;) {
173
+ const leftIndex = 2 * index + 1;
174
+ const left = __classPrivateFieldGet(this, _SharedTimer_heap, "f")[leftIndex];
175
+ if (left === undefined) {
176
+ break;
177
+ }
178
+ const right = __classPrivateFieldGet(this, _SharedTimer_heap, "f")[leftIndex + 1];
179
+ let child = left;
180
+ if (right !== undefined && isBefore(right, left)) {
181
+ child = right;
182
+ }
183
+ if (!isBefore(child, entry)) {
184
+ break;
185
+ }
186
+ const childIndex = child.index;
187
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_place).call(this, child, index);
188
+ index = childIndex;
189
+ }
190
+ __classPrivateFieldGet(this, _SharedTimer_instances, "m", _SharedTimer_place).call(this, entry, index);
191
+ };
@@ -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 _Connection_instances, _Connection_config, _Connection_url, _Connection_transforms, _Connection_pending, _Connection_handlers, _Connection_statusHandlers, _Connection_resyncHandlers, _Connection_subscribes, _Connection_acknowledged, _Connection_status, _Connection_ws, _Connection_generation, _Connection_nextId, _Connection_lastSeq, _Connection_attempt, _Connection_retryTimer, _Connection_pingTimer, _Connection_lastReceivedAt, _Connection_send, _Connection_subscribe, _Connection_subscribed, _Connection_flush, _Connection_connect, _Connection_receive, _Connection_settle, _Connection_dispatch, _Connection_invoke, _Connection_disconnected, _Connection_abandon, _Connection_startPing, _Connection_stopTimers, _Connection_setStatus, _DurabilitySocketClient_config, _DurabilitySocketClient_transforms;
12
+ var _Connection_instances, _Connection_config, _Connection_url, _Connection_transforms, _Connection_pending, _Connection_handlers, _Connection_statusHandlers, _Connection_resyncHandlers, _Connection_subscribes, _Connection_acknowledged, _Connection_status, _Connection_ws, _Connection_generation, _Connection_nextId, _Connection_lastSeq, _Connection_attempt, _Connection_timer, _Connection_cancelRetry, _Connection_cancelPing, _Connection_lastReceivedAt, _Connection_send, _Connection_subscribe, _Connection_subscribed, _Connection_flush, _Connection_connect, _Connection_receive, _Connection_settle, _Connection_dispatch, _Connection_invoke, _Connection_disconnected, _Connection_abandon, _Connection_startPing, _Connection_stopTimers, _Connection_setStatus, _DurabilitySocketClient_config, _DurabilitySocketClient_transforms;
13
13
  import { reportFailure } from '../errors.js';
14
14
  import { parseServerFrame, socketProtocolErrorCode, socketProtocolVersion, } from './protocol.js';
15
+ import { SharedTimer } from '../shared-timer.js';
15
16
  import { exponential, jitter } from '../utils.js';
16
17
  /** Rejection for calls still waiting when `close()` was called. */
17
18
  export class SocketClosedError extends Error {
@@ -71,8 +72,10 @@ class Connection {
71
72
  _Connection_nextId.set(this, 0);
72
73
  _Connection_lastSeq.set(this, void 0);
73
74
  _Connection_attempt.set(this, 0);
74
- _Connection_retryTimer.set(this, void 0);
75
- _Connection_pingTimer.set(this, void 0);
75
+ // Every pending call holds a timeout, and nothing limits how many are pending.
76
+ _Connection_timer.set(this, new SharedTimer());
77
+ _Connection_cancelRetry.set(this, void 0);
78
+ _Connection_cancelPing.set(this, void 0);
76
79
  _Connection_lastReceivedAt.set(this, 0);
77
80
  __classPrivateFieldSet(this, _Connection_config, config, "f");
78
81
  __classPrivateFieldSet(this, _Connection_url, config.url(id), "f");
@@ -132,7 +135,7 @@ class Connection {
132
135
  __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_stopTimers).call(this);
133
136
  __classPrivateFieldSet(this, _Connection_generation, __classPrivateFieldGet(this, _Connection_generation, "f") + 1, "f");
134
137
  for (const pending of __classPrivateFieldGet(this, _Connection_pending, "f").values()) {
135
- clearTimeout(pending.timer);
138
+ pending.cancelTimeout();
136
139
  pending.reject(new SocketClosedError());
137
140
  }
138
141
  __classPrivateFieldGet(this, _Connection_pending, "f").clear();
@@ -143,7 +146,7 @@ class Connection {
143
146
  __classPrivateFieldSet(this, _Connection_ws, undefined, "f");
144
147
  }
145
148
  }
146
- _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection_transforms = new WeakMap(), _Connection_pending = new WeakMap(), _Connection_handlers = new WeakMap(), _Connection_statusHandlers = new WeakMap(), _Connection_resyncHandlers = new WeakMap(), _Connection_subscribes = new WeakMap(), _Connection_acknowledged = new WeakMap(), _Connection_status = new WeakMap(), _Connection_ws = new WeakMap(), _Connection_generation = new WeakMap(), _Connection_nextId = new WeakMap(), _Connection_lastSeq = new WeakMap(), _Connection_attempt = new WeakMap(), _Connection_retryTimer = new WeakMap(), _Connection_pingTimer = new WeakMap(), _Connection_lastReceivedAt = new WeakMap(), _Connection_instances = new WeakSet(), _Connection_send = function _Connection_send(method, input) {
149
+ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection_transforms = new WeakMap(), _Connection_pending = new WeakMap(), _Connection_handlers = new WeakMap(), _Connection_statusHandlers = new WeakMap(), _Connection_resyncHandlers = new WeakMap(), _Connection_subscribes = new WeakMap(), _Connection_acknowledged = new WeakMap(), _Connection_status = new WeakMap(), _Connection_ws = new WeakMap(), _Connection_generation = new WeakMap(), _Connection_nextId = new WeakMap(), _Connection_lastSeq = new WeakMap(), _Connection_attempt = new WeakMap(), _Connection_timer = new WeakMap(), _Connection_cancelRetry = new WeakMap(), _Connection_cancelPing = new WeakMap(), _Connection_lastReceivedAt = new WeakMap(), _Connection_instances = new WeakSet(), _Connection_send = function _Connection_send(method, input) {
147
150
  var _a;
148
151
  if (__classPrivateFieldGet(this, _Connection_status, "f") === 'closed') {
149
152
  return Promise.reject(new SocketClosedError());
@@ -163,7 +166,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
163
166
  sent: false,
164
167
  resolve,
165
168
  reject,
166
- timer: setTimeout(() => {
169
+ cancelTimeout: __classPrivateFieldGet(this, _Connection_timer, "f").schedule(() => {
167
170
  __classPrivateFieldGet(this, _Connection_pending, "f").delete(id);
168
171
  reject(new SocketTimeoutError(method, __classPrivateFieldGet(this, _Connection_config, "f").timeoutMs));
169
172
  }, __classPrivateFieldGet(this, _Connection_config, "f").timeoutMs),
@@ -215,7 +218,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
215
218
  }
216
219
  }, _Connection_connect = function _Connection_connect() {
217
220
  var _a;
218
- if (__classPrivateFieldGet(this, _Connection_status, "f") !== 'disconnected' || __classPrivateFieldGet(this, _Connection_retryTimer, "f") !== undefined) {
221
+ if (__classPrivateFieldGet(this, _Connection_status, "f") !== 'disconnected' || __classPrivateFieldGet(this, _Connection_cancelRetry, "f") !== undefined) {
219
222
  return;
220
223
  }
221
224
  __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_setStatus).call(this, 'connecting');
@@ -288,7 +291,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
288
291
  return;
289
292
  }
290
293
  __classPrivateFieldGet(this, _Connection_pending, "f").delete(frame.id);
291
- clearTimeout(pending.timer);
294
+ pending.cancelTimeout();
292
295
  settle(pending);
293
296
  }, _Connection_dispatch = function _Connection_dispatch(name, payload) {
294
297
  for (const handler of __classPrivateFieldGet(this, _Connection_handlers, "f").get(name) ?? []) {
@@ -310,7 +313,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
310
313
  continue;
311
314
  }
312
315
  __classPrivateFieldGet(this, _Connection_pending, "f").delete(id);
313
- clearTimeout(pending.timer);
316
+ pending.cancelTimeout();
314
317
  pending.reject(new SocketConnectionLostError(pending.method));
315
318
  }
316
319
  if (code === socketProtocolErrorCode) {
@@ -319,36 +322,36 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
319
322
  }
320
323
  __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_setStatus).call(this, 'disconnected');
321
324
  __classPrivateFieldSet(this, _Connection_attempt, __classPrivateFieldGet(this, _Connection_attempt, "f") + 1, "f");
322
- __classPrivateFieldSet(this, _Connection_retryTimer, setTimeout(() => {
323
- __classPrivateFieldSet(this, _Connection_retryTimer, undefined, "f");
325
+ __classPrivateFieldSet(this, _Connection_cancelRetry, __classPrivateFieldGet(this, _Connection_timer, "f").schedule(() => {
326
+ __classPrivateFieldSet(this, _Connection_cancelRetry, undefined, "f");
324
327
  __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_connect).call(this);
325
328
  }, jitter(exponential(__classPrivateFieldGet(this, _Connection_attempt, "f"), 250, 60000))), "f");
326
329
  }, _Connection_abandon = function _Connection_abandon(error) {
327
330
  reportFailure('durability.socket.protocol_error', {}, error);
328
331
  for (const pending of __classPrivateFieldGet(this, _Connection_pending, "f").values()) {
329
- clearTimeout(pending.timer);
332
+ pending.cancelTimeout();
330
333
  pending.reject(error);
331
334
  }
332
335
  __classPrivateFieldGet(this, _Connection_pending, "f").clear();
333
336
  this.close();
334
337
  }, _Connection_startPing = function _Connection_startPing() {
335
338
  const interval = __classPrivateFieldGet(this, _Connection_config, "f").pingIntervalMs;
336
- __classPrivateFieldSet(this, _Connection_pingTimer, setInterval(() => {
339
+ const ping = () => {
340
+ // Scheduled before the socket is used, so a close that stops the timers
341
+ // also stops the next ping.
342
+ __classPrivateFieldSet(this, _Connection_cancelPing, __classPrivateFieldGet(this, _Connection_timer, "f").schedule(ping, interval), "f");
337
343
  if (Date.now() - __classPrivateFieldGet(this, _Connection_lastReceivedAt, "f") > interval * 2) {
338
344
  __classPrivateFieldGet(this, _Connection_ws, "f")?.close(4000, 'Keep-alive timeout');
339
345
  return;
340
346
  }
341
347
  __classPrivateFieldGet(this, _Connection_ws, "f")?.send(pingText);
342
- }, interval), "f");
348
+ };
349
+ __classPrivateFieldSet(this, _Connection_cancelPing, __classPrivateFieldGet(this, _Connection_timer, "f").schedule(ping, interval), "f");
343
350
  }, _Connection_stopTimers = function _Connection_stopTimers() {
344
- if (__classPrivateFieldGet(this, _Connection_pingTimer, "f") !== undefined) {
345
- clearInterval(__classPrivateFieldGet(this, _Connection_pingTimer, "f"));
346
- __classPrivateFieldSet(this, _Connection_pingTimer, undefined, "f");
347
- }
348
- if (__classPrivateFieldGet(this, _Connection_retryTimer, "f") !== undefined) {
349
- clearTimeout(__classPrivateFieldGet(this, _Connection_retryTimer, "f"));
350
- __classPrivateFieldSet(this, _Connection_retryTimer, undefined, "f");
351
- }
351
+ __classPrivateFieldGet(this, _Connection_cancelPing, "f")?.call(this);
352
+ __classPrivateFieldSet(this, _Connection_cancelPing, undefined, "f");
353
+ __classPrivateFieldGet(this, _Connection_cancelRetry, "f")?.call(this);
354
+ __classPrivateFieldSet(this, _Connection_cancelRetry, undefined, "f");
352
355
  }, _Connection_setStatus = function _Connection_setStatus(status) {
353
356
  if (__classPrivateFieldGet(this, _Connection_status, "f") === status) {
354
357
  return;