@kk-forge/artel-collector 0.1.1 → 0.2.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,4 +1,5 @@
1
1
  import { Period, type CalendarDate } from './calendar.js';
2
+ import { type Envelope } from './envelope.js';
2
3
  import type { StorageAdapter } from './storage.js';
3
4
  /** What the collector knows about one event when it records it. */
4
5
  export interface EventStamp {
@@ -12,17 +13,41 @@ export interface EventStamp {
12
13
  * The state one install keeps in storage between runs of the host. The caller runs each method under its lock, since
13
14
  * each method reads and then writes.
14
15
  */
15
- export interface InstallState {
16
- isEnabled(): Promise<boolean>;
17
- setEnabled(on: boolean): Promise<void>;
16
+ interface InstallState {
17
+ /** Returns the stored analytics state, or undefined when the user never chose one. */
18
+ state(): Promise<string | undefined>;
19
+ setState(state: string): Promise<void>;
20
+ /**
21
+ * Returns the last id `getId` gave while the user was identified, or undefined. After `forgetLastId` it returns a
22
+ * value no id equals.
23
+ */
24
+ lastId(): Promise<string | undefined>;
25
+ /** Stores the id `getId` gave, or `''` once no id names the user. */
26
+ setLastId(id: string): Promise<void>;
27
+ /** Stores a last id that no id equals, so the next id counts as another user. */
28
+ forgetLastId(): Promise<void>;
29
+ /**
30
+ * Gives back the marks these envelopes' events took that no later event took over, so the next such event takes them
31
+ * again: first-of-period marks, the `installed` mark, and the `updated` version while it is still stored. A
32
+ * first-of-day event also removes its day from the active days.
33
+ */
34
+ giveBack(envelopes: readonly Pick<Envelope, 'version' | 'events'>[]): Promise<void>;
35
+ /** Ends the session, so the next event starts a new one. */
36
+ endSession(): Promise<void>;
18
37
  /** Marks the install and stores `version`. Resolves to true, or to false when the install was marked before. */
19
38
  takeInstall(version: string): Promise<boolean>;
20
39
  /** Stores `version` and resolves to true when it differs from the stored one. */
21
40
  takeVersion(version: string): Promise<boolean>;
22
41
  /** Returns the stored install day, or stores and returns `today` when none is stored. */
23
42
  installDayOr(today: CalendarDate): Promise<CalendarDate>;
24
- /** Takes the first-of-period marks for an event at `timestamp`, counts a new active day and renews the session. */
43
+ /**
44
+ * Takes the first-of-period marks for an event at `timestamp`, counts a new active day and renews the session. A
45
+ * failure gives back the marks it took.
46
+ */
25
47
  stamp(timestamp: number): Promise<EventStamp>;
48
+ /** Renews the session for an event at `timestamp` that takes no mark and counts no active day. */
49
+ session(timestamp: number): Promise<string>;
50
+ /** Returns the number of local days with a queued or sent event. */
26
51
  activeDays(): Promise<number>;
27
52
  }
28
53
  export declare function newInstallState({ storage, sessionIdleMs, }: {
@@ -30,3 +55,4 @@ export declare function newInstallState({ storage, sessionIdleMs, }: {
30
55
  /** Time without events that ends a session. */
31
56
  sessionIdleMs: number;
32
57
  }): InstallState;
58
+ export {};
@@ -1,14 +1,28 @@
1
1
  import { Period, formatDay, localDateAt, parseDay, periodKey } from './calendar.js';
2
+ import { LifecycleEvent } from './envelope.js';
2
3
  const SESSION_ID_LENGTH = 12;
4
+ /**
5
+ * The most active days the collector stores. It reports the count in buckets, and the last bucket is `21+`, so the
6
+ * collector needs no more days.
7
+ */
8
+ const MAX_ACTIVE_DAYS = 21;
9
+ /**
10
+ * The last id after the host forgets the user. It is longer than the 64 characters of any id the collector takes, so
11
+ * the next id reads as another user's.
12
+ */
13
+ const FORGOTTEN_ID = '<forgotten>'.repeat(6);
3
14
  const StorageKey = {
4
- InstallDay: 'artel.install_day',
5
- Installed: 'artel.installed',
6
- Version: 'artel.version',
7
- Enabled: 'artel.enabled',
8
- Session: 'artel.session',
9
- SessionSeen: 'artel.session_seen',
10
- ActiveDays: 'artel.active_days',
11
- firstOf: (period) => `artel.first.${period}`,
15
+ InstallDay: 'install_day',
16
+ Installed: 'installed',
17
+ Version: 'version',
18
+ State: 'state',
19
+ /** The last id `getId` gave, `''` when none names the user, or `FORGOTTEN_ID` after the host forgot the user. */
20
+ LastId: 'last_id',
21
+ Session: 'session',
22
+ SessionSeen: 'session_seen',
23
+ /** The local days with a queued or sent event, as a JSON list of `YYYY-MM-DD`. */
24
+ ActiveDays: 'active_days',
25
+ firstOf: (period) => `first.${period}`,
12
26
  };
13
27
  export function newInstallState({ storage, sessionIdleMs, }) {
14
28
  async function installDayOr(today) {
@@ -19,19 +33,64 @@ export function newInstallState({ storage, sessionIdleMs, }) {
19
33
  await storage.set(StorageKey.InstallDay, formatDay(today));
20
34
  return today;
21
35
  }
22
- async function takeFirstMarks(today) {
23
- const marks = [];
36
+ /** Takes the first-of-period marks not taken yet for `today` and adds each to `marks` once taken. */
37
+ async function takeFirstMarks(today, marks) {
24
38
  for (const period of Object.values(Period)) {
25
39
  const key = periodKey(period, today);
26
40
  if ((await storage.get(StorageKey.firstOf(period))) !== key) {
27
- marks.push(period);
28
41
  await storage.set(StorageKey.firstOf(period), key);
42
+ marks.push(period);
29
43
  }
30
44
  }
31
- return marks;
32
45
  }
33
- async function activeDays() {
34
- return Number(await storage.get(StorageKey.ActiveDays)) || 0;
46
+ /** Returns the stored active days. A stored value that is not a list reads as no days, and only its strings count. */
47
+ async function readActiveDays() {
48
+ let days;
49
+ try {
50
+ days = JSON.parse((await storage.get(StorageKey.ActiveDays)) ?? '[]');
51
+ }
52
+ catch {
53
+ return [];
54
+ }
55
+ return Array.isArray(days) ? days.filter((day) => typeof day === 'string') : [];
56
+ }
57
+ async function countActiveDay(day) {
58
+ const days = await readActiveDays();
59
+ if (days.length < MAX_ACTIVE_DAYS) {
60
+ await storage.set(StorageKey.ActiveDays, JSON.stringify([...new Set([...days, day])]));
61
+ }
62
+ }
63
+ /** Removes a day from the active days. The cap of 21 stops only the count of new days. */
64
+ async function uncountActiveDay(day) {
65
+ const days = await readActiveDays();
66
+ await storage.set(StorageKey.ActiveDays, JSON.stringify(days.filter((candidate) => candidate !== day)));
67
+ }
68
+ async function giveBackMark(period, day) {
69
+ if ((await storage.get(StorageKey.firstOf(period))) === periodKey(period, day)) {
70
+ await storage.set(StorageKey.firstOf(period), '');
71
+ }
72
+ }
73
+ async function giveBackFirstMarks(day, first) {
74
+ for (const period of first) {
75
+ await giveBackMark(period, day);
76
+ }
77
+ // The event that took the day's first mark was the day's first. Its give-back takes the day out of the count.
78
+ if (first.includes(Period.Day)) {
79
+ await uncountActiveDay(formatDay(day));
80
+ }
81
+ }
82
+ async function giveBackMarksOf(event, version) {
83
+ const day = parseDay(event.day);
84
+ if (day !== undefined) {
85
+ await giveBackFirstMarks(day, event.first ?? []);
86
+ }
87
+ if (event.name === LifecycleEvent.Installed) {
88
+ await storage.set(StorageKey.Installed, '');
89
+ }
90
+ // A later `updated` of another version stored its own version, which stays.
91
+ if (event.name === LifecycleEvent.Updated && (await storage.get(StorageKey.Version)) === version) {
92
+ await storage.set(StorageKey.Version, '');
93
+ }
35
94
  }
36
95
  /**
37
96
  * Returns the session id. A session ends after the idle time without events or at local midnight. The midnight end
@@ -41,20 +100,37 @@ export function newInstallState({ storage, sessionIdleMs, }) {
41
100
  const stored = await storage.get(StorageKey.Session);
42
101
  const lastSeen = Number(await storage.get(StorageKey.SessionSeen));
43
102
  const isIdle = !(timestamp - lastSeen < sessionIdleMs);
44
- const session = stored === undefined || isIdle || isNewDay ? newSessionId() : stored;
103
+ const session = stored === undefined || stored === '' || isIdle || isNewDay ? newSessionId() : stored;
45
104
  await storage.set(StorageKey.Session, session);
46
105
  await storage.set(StorageKey.SessionSeen, String(timestamp));
47
106
  return session;
48
107
  }
49
108
  return {
50
- isEnabled: async () => (await storage.get(StorageKey.Enabled)) !== '0',
51
- setEnabled: (on) => storage.set(StorageKey.Enabled, on ? '1' : '0'),
109
+ state: () => storage.get(StorageKey.State),
110
+ lastId: async () => {
111
+ const id = await storage.get(StorageKey.LastId);
112
+ return id === '' ? undefined : id;
113
+ },
114
+ setLastId: (id) => storage.set(StorageKey.LastId, id),
115
+ forgetLastId: () => storage.set(StorageKey.LastId, FORGOTTEN_ID),
116
+ giveBack: async (envelopes) => {
117
+ for (const { version, events } of envelopes) {
118
+ for (const event of events) {
119
+ await giveBackMarksOf(event, version);
120
+ }
121
+ }
122
+ },
123
+ setState: (state) => storage.set(StorageKey.State, state),
124
+ // An empty session reads as none, so the next event takes a new one. The storage has no remove.
125
+ endSession: () => storage.set(StorageKey.Session, ''),
52
126
  takeInstall: async (version) => {
53
- if ((await storage.get(StorageKey.Installed)) !== undefined) {
127
+ const mark = await storage.get(StorageKey.Installed);
128
+ if (mark !== undefined && mark !== '') {
54
129
  return false;
55
130
  }
56
- await storage.set(StorageKey.Installed, '1');
131
+ // The version goes first, so a failed write leaves the install mark untaken.
57
132
  await storage.set(StorageKey.Version, version);
133
+ await storage.set(StorageKey.Installed, '1');
58
134
  return true;
59
135
  },
60
136
  takeVersion: async (version) => {
@@ -68,14 +144,23 @@ export function newInstallState({ storage, sessionIdleMs, }) {
68
144
  stamp: async (timestamp) => {
69
145
  const today = localDateAt(timestamp);
70
146
  const installDay = await installDayOr(today);
71
- const first = await takeFirstMarks(today);
72
- const isNewDay = first.includes(Period.Day);
73
- if (isNewDay) {
74
- await storage.set(StorageKey.ActiveDays, String((await activeDays()) + 1));
147
+ const first = [];
148
+ try {
149
+ await takeFirstMarks(today, first);
150
+ const isNewDay = first.includes(Period.Day);
151
+ if (isNewDay) {
152
+ await countActiveDay(formatDay(today));
153
+ }
154
+ return { today, installDay, first, session: await currentSession(timestamp, isNewDay) };
155
+ }
156
+ catch (error) {
157
+ await giveBackFirstMarks(today, first);
158
+ throw error;
75
159
  }
76
- return { today, installDay, first, session: await currentSession(timestamp, isNewDay) };
77
160
  },
78
- activeDays,
161
+ // The only caller ends the session first, so the session it renews is always a new one.
162
+ session: (timestamp) => currentSession(timestamp, false),
163
+ activeDays: async () => (await readActiveDays()).length,
79
164
  };
80
165
  }
81
166
  function newSessionId() {
package/dist/lock.d.ts CHANGED
@@ -1,2 +1,11 @@
1
- /** Runs `operation` while no other context that shares the storage runs one, such as through Web Locks. */
1
+ /**
2
+ * Runs `operation` once while no other context that shares the storage runs one, such as through Web Locks. It holds
3
+ * the lock until the operation's promise settles, and it resolves or rejects as the operation does. The collector never
4
+ * asks for the lock while it holds it.
5
+ */
2
6
  export type Lock = <T>(operation: () => Promise<T>) => Promise<T>;
7
+ /**
8
+ * Returns a lock that runs one operation at a time within this collector, inside the host's lock when there is one.
9
+ * Without it, two operations over an asynchronous storage could interleave reads and writes and lose an event.
10
+ */
11
+ export declare function exclusive(hostLock: Lock | undefined): Lock;
package/dist/lock.js CHANGED
@@ -1 +1,12 @@
1
- export {};
1
+ /**
2
+ * Returns a lock that runs one operation at a time within this collector, inside the host's lock when there is one.
3
+ * Without it, two operations over an asynchronous storage could interleave reads and writes and lose an event.
4
+ */
5
+ export function exclusive(hostLock) {
6
+ let tail = Promise.resolve();
7
+ return (operation) => {
8
+ const run = tail.then(async () => (hostLock === undefined ? operation() : hostLock(operation)));
9
+ tail = run.catch(() => undefined);
10
+ return run;
11
+ };
12
+ }
package/dist/outbox.d.ts CHANGED
@@ -1,39 +1,58 @@
1
1
  import type { Clock } from './clock.js';
2
2
  import type { Envelope, UsageEvent } from './envelope.js';
3
3
  import type { Lock } from './lock.js';
4
+ import { type Identity, type QueuedEnvelope } from './queue.js';
4
5
  import type { StorageAdapter } from './storage.js';
5
6
  import type { Transport } from './transport.js';
6
7
  /**
7
8
  * Holds the envelopes on their way to the intake. They leave one at a time, in the order they were made. An envelope
8
- * the intake cannot take now goes again later, and each wait doubles, up to five minutes.
9
+ * the intake cannot take now goes again later, and each wait doubles, up to five minutes. A longer `Retry-After` of a
10
+ * 429 or 503 sets the wait instead. Every context that shares the storage keeps the longest wait any of them stored.
9
11
  */
10
- export interface Outbox {
12
+ interface Outbox {
11
13
  /**
12
14
  * Queues the event and sends it within the send delay, at once when its envelope is full, or with the pending retry.
15
+ * Resolves to what the queue dropped to take it, whose marks may go back.
13
16
  */
14
- add(fields: Omit<Envelope, 'events'>, event: UsageEvent): Promise<void>;
17
+ add(fields: Omit<Envelope, 'events'>, event: UsageEvent, options?: {
18
+ awaitsId?: boolean;
19
+ }): Promise<QueuedEnvelope[]>;
15
20
  /** Sends what is queued within the send delay, such as what an earlier run of the host left. */
16
21
  sendSoon(): void;
17
- /** Sends what is queued now, in turn after any send in progress. */
22
+ /** Sends what is queued now, in turn after any send in progress, or once the retry wait is over. */
18
23
  send(): Promise<void>;
19
- /** Drops every envelope not sent yet and cancels the next retry. */
20
- discard(): Promise<void>;
21
- /** Drops the envelopes of this id. */
22
- forget(id: string): Promise<void>;
24
+ /**
25
+ * Drops every envelope not sent yet but those of an `opted_out`. Resolves to those whose marks may go back, as
26
+ * `src/queue.ts` describes.
27
+ */
28
+ discard(): Promise<QueuedEnvelope[]>;
29
+ /** Drops the envelopes of this id. Resolves to all of them, since the intake deletes their events too. */
30
+ forget(id: string): Promise<QueuedEnvelope[]>;
31
+ /** Drops the envelopes that name a user or that await an id. Resolves to those whose marks may go back. */
32
+ discardIdentified(): Promise<QueuedEnvelope[]>;
23
33
  /** Resolves once the send in progress, if any, has ended. */
24
34
  settled(): Promise<void>;
25
35
  }
26
36
  /**
27
- * Expects the caller to run `add`, `discard` and `forget` inside its own `lock`, which it holds for the whole recording
28
- * of an event. The sends take the lock themselves.
37
+ * Expects the caller to run `add`, `discard`, `forget` and `discardIdentified` inside its own `lock`, which it holds
38
+ * for the whole recording of an event. The sends take the lock themselves.
29
39
  */
30
- export declare function newOutbox({ storage, lock, transport, getId, sendDelayMs, clock, reportError, }: {
40
+ export declare function newOutbox({ storage, lock, transport, identify, giveBack, sendDelayMs, clock, reportError, }: {
31
41
  storage: StorageAdapter;
32
42
  lock: Lock;
33
43
  transport: Transport;
34
44
  /** The longest an event waits in the queue before a send starts. */
35
45
  sendDelayMs: number;
36
- getId: (() => string | undefined | Promise<string | undefined>) | undefined;
46
+ /**
47
+ * Resolves to the user that an envelope awaiting an id will name, or to undefined while the product does not know the
48
+ * id yet. The envelope then stays queued. It takes `lock` itself, so the outbox calls it outside the lock.
49
+ */
50
+ identify: () => Promise<Identity | undefined>;
51
+ /**
52
+ * Gives back the marks of an envelope too old to send that no request carried. The outbox calls it under `lock`.
53
+ */
54
+ giveBack: (items: readonly QueuedEnvelope[]) => Promise<void>;
37
55
  clock: Clock;
38
56
  reportError: (error: unknown) => void;
39
57
  }): Outbox;
58
+ export {};
package/dist/outbox.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { daysBetween, parseDay, utcDateAt } from './calendar.js';
2
- import { newQueue, newRandomId } from './queue.js';
2
+ import { quoted } from './hostInput.js';
3
+ import { newQueue, newRandomId, } from './queue.js';
3
4
  const RETRY_DELAY_MS = 1_000;
4
5
  const MAX_RETRY_DELAY_MS = 5 * 60_000;
6
+ /** Names the stored time, in epoch milliseconds, before which no context that shares the storage starts a send. */
7
+ const RETRY_AT_KEY = 'retry_at';
5
8
  /**
6
9
  * The time one send holds the lease on a queued envelope, twice the 30 s request limit of `newHttpTransport` in
7
10
  * `src/transport.ts`. The send renews the lease before each request. A host that stops mid-send blocks the envelope
@@ -9,10 +12,16 @@ const MAX_RETRY_DELAY_MS = 5 * 60_000;
9
12
  */
10
13
  const LEASE_MS = 60_000;
11
14
  /**
12
- * Expects the caller to run `add`, `discard` and `forget` inside its own `lock`, which it holds for the whole recording
13
- * of an event. The sends take the lock themselves.
15
+ * The longest the outbox waits for a transport's answer, a little over the 30 s a transport must answer in. A request
16
+ * that took longer counts as status 0, so a broken transport stops no send, `flush`, `forget` or opt-out for good.
14
17
  */
15
- export function newOutbox({ storage, lock, transport, getId, sendDelayMs, clock, reportError, }) {
18
+ const TRANSPORT_LIMIT_MS = 35_000;
19
+ const MAX_HTTP_STATUS = 599;
20
+ /**
21
+ * Expects the caller to run `add`, `discard`, `forget` and `discardIdentified` inside its own `lock`, which it holds
22
+ * for the whole recording of an event. The sends take the lock themselves.
23
+ */
24
+ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDelayMs, clock, reportError, }) {
16
25
  const queue = newQueue({ storage, reportError });
17
26
  /** Names this outbox's leases, apart from those of other contexts that share the storage. */
18
27
  const holder = newRandomId();
@@ -24,7 +33,7 @@ export function newOutbox({ storage, lock, transport, getId, sendDelayMs, clock,
24
33
  let sending = Promise.resolve();
25
34
  function reportDropped(count) {
26
35
  if (count > 0) {
27
- reportError(new Error(`artel: ${count} queued events dropped as too old or under a withdrawn id`));
36
+ reportError(new Error(`artel: ${count} queued events dropped as too old`));
28
37
  }
29
38
  }
30
39
  function leaseTerms() {
@@ -47,17 +56,58 @@ export function newOutbox({ storage, lock, transport, getId, sendDelayMs, clock,
47
56
  }
48
57
  clock.clearTimeout(sendTimer);
49
58
  sendDue = clock.now() + delayMs;
50
- sendTimer = clock.setTimeout(() => void send(), delayMs);
59
+ sendTimer = clock.setTimeout(() => void sendUnlessRetryPending(), delayMs);
51
60
  }
61
+ /** Sends at once, cancelling a pending retry, as `flush` and a retry timer do. */
52
62
  function send() {
53
63
  cancelSend();
54
64
  cancelRetry();
55
65
  sending = sending.then(sendLeased).catch(reportError);
56
66
  return sending;
57
67
  }
58
- /** Leases what is queued and sends it. An envelope not settled when the send stops goes back to the queue. */
68
+ /**
69
+ * Sends in turn after any send in progress, unless that send failed and left a retry pending. The intake asked the
70
+ * outbox to wait, and the retry carries these events too.
71
+ */
72
+ function sendUnlessRetryPending() {
73
+ cancelSend();
74
+ sending = sending.then(async () => (retryTimer === undefined ? sendLeased() : undefined)).catch(reportError);
75
+ return sending;
76
+ }
77
+ /**
78
+ * Resolves to the time left of the retry wait any context stored. A stored wait longer than five minutes, as after a
79
+ * clock set back, or a value another script wrote that is no time, is reported and stored again as five minutes from
80
+ * now, so it holds no send for longer. The caller holds `lock`.
81
+ */
82
+ async function retryWaitMs() {
83
+ const stored = (await storage.get(RETRY_AT_KEY)) ?? '';
84
+ const waitMs = Math.max(0, Number(stored) - clock.now());
85
+ if (waitMs <= MAX_RETRY_DELAY_MS) {
86
+ return waitMs;
87
+ }
88
+ reportError(new Error(`artel: the stored retry wait ${quoted(stored)} is no time within five minutes, so the wait is five minutes`));
89
+ await storage.set(RETRY_AT_KEY, String(clock.now() + MAX_RETRY_DELAY_MS));
90
+ return MAX_RETRY_DELAY_MS;
91
+ }
92
+ /** Stores a retry wait of `waitMs` from now, unless a longer one is stored. The caller holds `lock`. */
93
+ async function keepRetryWait(waitMs) {
94
+ const longest = Math.max(waitMs, await retryWaitMs());
95
+ await storage.set(RETRY_AT_KEY, String(clock.now() + longest));
96
+ }
97
+ /**
98
+ * Leases what is queued and sends it, or schedules the send for the end of the retry wait. An envelope not settled
99
+ * when the send stops goes back to the queue.
100
+ */
59
101
  async function sendLeased() {
60
- const leased = await lock(async () => queue.lease(leaseTerms()));
102
+ const { leased, waitMs } = await lock(async () => {
103
+ const wait = await retryWaitMs();
104
+ return { waitMs: wait, leased: wait > 0 ? undefined : await queue.lease(leaseTerms()) };
105
+ });
106
+ if (leased === undefined) {
107
+ // The pending retry of this context sends at the end of the wait. Without one, a send of its own does.
108
+ sendWithin(waitMs);
109
+ return;
110
+ }
61
111
  const unsettled = new Set(leased.map((item) => item.qid));
62
112
  try {
63
113
  await sendInOrder(leased, unsettled);
@@ -68,93 +118,152 @@ export function newOutbox({ storage, lock, transport, getId, sendDelayMs, clock,
68
118
  }
69
119
  }
70
120
  }
121
+ /**
122
+ * Seals the envelope for its request, or resolves to undefined when it does not go now. An envelope gone from the
123
+ * queue, or one another holder took, is settled. One that waits for an id the product does not know yet stays leased
124
+ * until the send ends.
125
+ */
126
+ async function sealIfItMayLeave(item, unsettled) {
127
+ const identity = item.awaitsId === true ? await identify() : undefined;
128
+ if (item.awaitsId === true && identity === undefined) {
129
+ return undefined;
130
+ }
131
+ const sealed = await lock(async () => queue.seal(item.qid, leaseTerms(), identity));
132
+ if (sealed === undefined) {
133
+ unsettled.delete(item.qid);
134
+ }
135
+ return sealed;
136
+ }
71
137
  /**
72
138
  * Sends the envelopes in order. The function seals and reads each one just before its request, so the request carries
73
139
  * every event added since the lease. From the first envelope the intake cannot take now, the rest wait for a retry.
74
140
  */
75
141
  async function sendInOrder(leased, unsettled) {
76
- const mayGo = sendableCheck({ id: await getId?.(), today: utcDateAt(clock.now()) });
142
+ const today = utcDateAt(clock.now());
77
143
  for (const item of leased) {
78
- const sealed = await lock(async () => queue.seal(item.qid, leaseTerms()));
144
+ const sealed = await sealIfItMayLeave(item, unsettled);
79
145
  if (sealed === undefined) {
80
- unsettled.delete(item.qid);
81
146
  continue;
82
147
  }
83
148
  // An envelope goes whole or not at all. The intake drops a repeat only when it matches the first body byte for
84
149
  // byte, and a repeat with fewer events would not match.
85
- const { envelope, body } = sealed;
86
- const isFresh = envelope.events.every((event) => mayGo(envelope, event));
87
- if (!isFresh) {
150
+ const { envelope, body, isRepeat } = sealed;
151
+ if (!envelope.events.every((event) => isRecent(event, today))) {
88
152
  reportDropped(envelope.events.length);
153
+ await lock(async () => {
154
+ await queue.remove(item.qid);
155
+ await giveBack(isRepeat ? [] : [{ ...item, envelope }]);
156
+ });
157
+ unsettled.delete(item.qid);
158
+ continue;
89
159
  }
90
- if (isFresh && !(await deliver({ body, transport, reportError }))) {
91
- // An event that came during the request armed a send. The retry carries that event, so the intake gets its
92
- // wait.
160
+ const { isSettled, askedWaitMs } = await deliver({ body, transport, reportError, clock });
161
+ if (!isSettled) {
162
+ // The retry carries the events that came during the request. A send they armed skips its turn while the
163
+ // retry is pending.
93
164
  cancelSend();
94
165
  cancelRetry();
95
- retryTimer = clock.setTimeout(() => void send(), retryDelay);
166
+ const waitMs = Math.min(Math.max(retryDelay, askedWaitMs ?? 0), MAX_RETRY_DELAY_MS);
167
+ retryTimer = clock.setTimeout(() => void send(), waitMs);
96
168
  retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY_MS);
169
+ await lock(async () => keepRetryWait(waitMs));
97
170
  return;
98
171
  }
99
172
  await lock(async () => queue.remove(item.qid));
100
173
  unsettled.delete(item.qid);
101
174
  }
102
175
  retryDelay = RETRY_DELAY_MS;
103
- // A failed send may have armed a retry while this send waited its turn. An event that came meanwhile armed no send
104
- // of its own, so it gets one now.
105
- if (retryTimer !== undefined) {
106
- cancelRetry();
107
- sendWithin(sendDelayMs);
108
- }
109
176
  }
110
177
  return {
111
- add: async (fields, event) => {
112
- const isFull = await queue.add(fields, event);
178
+ add: async (fields, event, options) => {
179
+ const { isFull, dropped } = await queue.add(fields, event, options);
113
180
  // A full envelope goes at once. Otherwise the send waits, so that the events of the next few seconds share one
114
181
  // request.
115
182
  sendWithin(isFull ? 0 : sendDelayMs);
183
+ return dropped;
116
184
  },
117
185
  sendSoon: () => sendWithin(sendDelayMs),
118
186
  send,
119
- discard: async () => {
120
- cancelRetry();
121
- // A send in progress holds leases on what it took. Dropping those envelopes here keeps that send from sending
122
- // them again.
123
- await queue.clear();
124
- },
187
+ // A send in progress holds leases on what it took. Dropping those envelopes here keeps that send from sending them
188
+ // again.
189
+ discard: () => queue.removeAllButOptOuts(),
125
190
  forget: (id) => queue.removeId(id),
191
+ discardIdentified: () => queue.removeIdentified(),
126
192
  settled: () => sending,
127
193
  };
128
194
  }
129
195
  /**
130
- * Sends one envelope, and resolves to false when it must go again later: on 429, a rate limit, on 5xx, a store that
131
- * missed the write, or on status 0, which a browser also gives for a refusal without CORS headers. Any other 4xx means
132
- * a wrong envelope or channel, so a retry would fail the same way.
196
+ * Sends one envelope, and resolves to whether it is settled. It is not on 429, a rate limit, on 5xx, a store that
197
+ * missed the write, or on status 0, which a browser also gives for a refusal without CORS headers. Then it resolves to
198
+ * the wait the `Retry-After` of a 429 or 503 asks for too. Any other status outside 2xx means a wrong envelope or
199
+ * channel, so a retry would fail the same way.
200
+ */
201
+ async function deliver({ body, transport, reportError, clock, }) {
202
+ const result = await answerOf(transport, body, clock);
203
+ const status = httpStatus(result.status, reportError);
204
+ if (status === 429 || status === 503) {
205
+ return { isSettled: false, askedWaitMs: retryAfterMs(result.retryAfter, clock.now()) };
206
+ }
207
+ if (status === 0 || status >= 500) {
208
+ return { isSettled: false };
209
+ }
210
+ if (status < 200 || status >= 300) {
211
+ reportError(new Error(`artel: intake answered ${status}`));
212
+ }
213
+ return { isSettled: true };
214
+ }
215
+ /**
216
+ * Returns the status, or reports a value that is not a whole number from 0 to 599 and returns 0, a failed request.
217
+ * Only a product's own transport, outside TypeScript or with a bug, gives such a value.
133
218
  */
134
- async function deliver({ body, transport, reportError, }) {
135
- let status;
219
+ function httpStatus(status, reportError) {
220
+ if (typeof status === 'number' && Number.isInteger(status) && status >= 0 && status <= MAX_HTTP_STATUS) {
221
+ return status;
222
+ }
223
+ reportError(new Error('artel: the transport answered a status that is no whole number from 0 to 599, read as 0'));
224
+ return 0;
225
+ }
226
+ /**
227
+ * Resolves to the transport's answer, or to status 0 for a transport that throws, rejects or answers too late, or that
228
+ * answers null or undefined, as only a product's own transport outside TypeScript does.
229
+ */
230
+ async function answerOf(transport, body, clock) {
231
+ let timer;
232
+ const late = new Promise((resolve) => {
233
+ timer = clock.setTimeout(() => resolve({ status: 0 }), TRANSPORT_LIMIT_MS);
234
+ });
136
235
  try {
137
- status = await transport(body);
236
+ const answer = await Promise.race([transport(body), late]);
237
+ // A null or undefined answer throws here, and reads as status 0.
238
+ return typeof answer === 'number' ? { status: answer } : { status: answer.status, retryAfter: answer.retryAfter };
138
239
  }
139
240
  catch {
140
- status = 0;
241
+ return { status: 0 };
141
242
  }
142
- if (status === 0 || status === 429 || status >= 500) {
143
- return false;
243
+ finally {
244
+ clock.clearTimeout(timer);
144
245
  }
145
- if (status < 200 || status >= 300) {
146
- reportError(new Error(`artel: intake answered ${status}`));
246
+ }
247
+ /**
248
+ * Returns the wait a `Retry-After` value asks for at `now`, in milliseconds: its delta-seconds, or the time to its HTTP
249
+ * date, none for a date in the past. Returns undefined for a missing or invalid value, or one that is no string, which
250
+ * only a product's own transport outside TypeScript gives.
251
+ */
252
+ function retryAfterMs(value, now) {
253
+ if (typeof value !== 'string') {
254
+ return undefined;
147
255
  }
148
- return true;
256
+ if (/^\d+$/.test(value)) {
257
+ return Number(value) * 1_000;
258
+ }
259
+ const time = Date.parse(value);
260
+ return Number.isFinite(time) ? Math.max(0, time - now) : undefined;
149
261
  }
150
262
  /**
151
- * Returns the check whether an event may still go: its envelope carries no id or the current `id`, and its day is UTC
152
- * yesterday or later. The intake moves an older day to its own today, and first-of-period marks would count the user
153
- * twice. An old id may belong to a user who withdrew consent and was forgotten.
263
+ * Tells whether an event may still go: its day is UTC yesterday or later. The intake moves an older day to its own
264
+ * today, and first-of-period marks would count the user twice.
154
265
  */
155
- function sendableCheck({ id, today, }) {
156
- return (envelope, event) => {
157
- const day = parseDay(event.day);
158
- return (envelope.id === undefined || envelope.id === id) && day !== undefined && daysBetween(day, today) <= 1;
159
- };
266
+ function isRecent(event, today) {
267
+ const day = parseDay(event.day);
268
+ return day !== undefined && daysBetween(day, today) <= 1;
160
269
  }