@kk-forge/artel-collector 0.4.0 → 0.5.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.
- package/README.md +26 -24
- package/dist/browser.d.ts +8 -8
- package/dist/browser.js +23 -21
- package/dist/calendar.d.ts +5 -5
- package/dist/calendar.js +7 -7
- package/dist/clock.d.ts +4 -4
- package/dist/clock.js +4 -2
- package/dist/collector.d.ts +7 -2
- package/dist/collector.js +85 -49
- package/dist/collectorTypes.d.ts +30 -21
- package/dist/collectorTypes.js +12 -12
- package/dist/desktop.d.ts +4 -4
- package/dist/desktop.js +2 -2
- package/dist/envelope.d.ts +11 -11
- package/dist/envelope.js +12 -12
- package/dist/eventCheck.d.ts +14 -5
- package/dist/eventCheck.js +50 -29
- package/dist/exports.d.ts +10 -10
- package/dist/exports.js +9 -9
- package/dist/extension.d.ts +15 -11
- package/dist/extension.js +120 -61
- package/dist/fields.d.ts +3 -3
- package/dist/fields.js +7 -7
- package/dist/hostInput.d.ts +5 -5
- package/dist/hostInput.js +26 -20
- package/dist/installState.d.ts +4 -4
- package/dist/installState.js +28 -27
- package/dist/outbox.d.ts +11 -9
- package/dist/outbox.js +45 -27
- package/dist/page.d.ts +1 -1
- package/dist/page.js +8 -6
- package/dist/pagePath.js +14 -14
- package/dist/queue.d.ts +6 -4
- package/dist/queue.js +26 -13
- package/dist/stateFields.d.ts +4 -4
- package/dist/stateFields.js +6 -4
- package/dist/testing.d.ts +8 -5
- package/dist/testing.js +27 -17
- package/dist/throttle.d.ts +30 -0
- package/dist/throttle.js +41 -0
- package/dist/transport.d.ts +10 -1
- package/dist/transport.js +35 -8
- package/dist/web.d.ts +4 -4
- package/dist/web.js +30 -17
- package/package.json +6 -4
package/dist/installState.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Period, formatDay, localDateAt, parseDay, periodKey } from
|
|
2
|
-
import { LifecycleEvent } from
|
|
3
|
-
import { newRandomId } from
|
|
1
|
+
import { Period, formatDay, localDateAt, parseDay, periodKey, } from "./calendar.js";
|
|
2
|
+
import { LifecycleEvent } from "./envelope.js";
|
|
3
|
+
import { newRandomId } from "./queue.js";
|
|
4
4
|
const SESSION_ID_LENGTH = 12;
|
|
5
5
|
/**
|
|
6
6
|
* The most active days the collector stores. It reports the count in buckets, and the last bucket is `21+`, so the
|
|
@@ -11,23 +11,23 @@ const MAX_ACTIVE_DAYS = 21;
|
|
|
11
11
|
* The last id after the host forgets the user. It is longer than the 64 characters of any id the collector takes, so
|
|
12
12
|
* the next id reads as another user's.
|
|
13
13
|
*/
|
|
14
|
-
const FORGOTTEN_ID =
|
|
14
|
+
const FORGOTTEN_ID = "<forgotten>".repeat(6);
|
|
15
15
|
/** The install id's form: 16 random bytes as lowercase hex, as the intake expects it. */
|
|
16
16
|
const INSTALL_ID_FORMAT = /^[\da-f]{32}$/;
|
|
17
17
|
const INSTALL_ID_BYTES = 16;
|
|
18
18
|
const StorageKey = {
|
|
19
|
-
InstallDay:
|
|
20
|
-
Installed:
|
|
21
|
-
Version:
|
|
22
|
-
State:
|
|
19
|
+
InstallDay: "install_day",
|
|
20
|
+
Installed: "installed",
|
|
21
|
+
Version: "version",
|
|
22
|
+
State: "state",
|
|
23
23
|
/** The random id of the pseudonymous state, `''` once the user left that state. */
|
|
24
|
-
InstallId:
|
|
24
|
+
InstallId: "install_id",
|
|
25
25
|
/** The last id an envelope named the user by, `''` when none does, or `FORGOTTEN_ID` after the host forgot it. */
|
|
26
|
-
LastId:
|
|
27
|
-
Session:
|
|
28
|
-
SessionSeen:
|
|
26
|
+
LastId: "last_id",
|
|
27
|
+
Session: "session",
|
|
28
|
+
SessionSeen: "session_seen",
|
|
29
29
|
/** The local days with a queued or sent event, as a JSON list of `YYYY-MM-DD`. */
|
|
30
|
-
ActiveDays:
|
|
30
|
+
ActiveDays: "active_days",
|
|
31
31
|
firstOf: (period) => `first.${period}`,
|
|
32
32
|
};
|
|
33
33
|
export function newInstallState({ storage, sessionIdleMs, }) {
|
|
@@ -53,12 +53,12 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
53
53
|
async function readActiveDays() {
|
|
54
54
|
let days;
|
|
55
55
|
try {
|
|
56
|
-
days = JSON.parse((await storage.get(StorageKey.ActiveDays)) ??
|
|
56
|
+
days = JSON.parse((await storage.get(StorageKey.ActiveDays)) ?? "[]");
|
|
57
57
|
}
|
|
58
58
|
catch {
|
|
59
59
|
return [];
|
|
60
60
|
}
|
|
61
|
-
return Array.isArray(days) ? days.filter((day) => typeof day ===
|
|
61
|
+
return Array.isArray(days) ? days.filter((day) => typeof day === "string") : [];
|
|
62
62
|
}
|
|
63
63
|
async function countActiveDay(day) {
|
|
64
64
|
const days = await readActiveDays();
|
|
@@ -73,7 +73,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
73
73
|
}
|
|
74
74
|
async function giveBackMark(period, day) {
|
|
75
75
|
if ((await storage.get(StorageKey.firstOf(period))) === periodKey(period, day)) {
|
|
76
|
-
await storage.set(StorageKey.firstOf(period),
|
|
76
|
+
await storage.set(StorageKey.firstOf(period), "");
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
79
|
async function giveBackFirstMarks(day, first) {
|
|
@@ -91,11 +91,12 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
91
91
|
await giveBackFirstMarks(day, event.first ?? []);
|
|
92
92
|
}
|
|
93
93
|
if (event.name === LifecycleEvent.Installed) {
|
|
94
|
-
await storage.set(StorageKey.Installed,
|
|
94
|
+
await storage.set(StorageKey.Installed, "");
|
|
95
95
|
}
|
|
96
96
|
// A later `updated` of another version stored its own version, which stays.
|
|
97
|
-
if (event.name === LifecycleEvent.Updated &&
|
|
98
|
-
await storage.
|
|
97
|
+
if (event.name === LifecycleEvent.Updated &&
|
|
98
|
+
(await storage.get(StorageKey.Version)) === version) {
|
|
99
|
+
await storage.set(StorageKey.Version, "");
|
|
99
100
|
}
|
|
100
101
|
}
|
|
101
102
|
/**
|
|
@@ -106,7 +107,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
106
107
|
const stored = await storage.get(StorageKey.Session);
|
|
107
108
|
const lastSeen = Number(await storage.get(StorageKey.SessionSeen));
|
|
108
109
|
const isIdle = !(timestamp - lastSeen < sessionIdleMs);
|
|
109
|
-
const session = stored === undefined || stored ===
|
|
110
|
+
const session = stored === undefined || stored === "" || isIdle || isNewDay ? newSessionId() : stored;
|
|
110
111
|
await storage.set(StorageKey.Session, session);
|
|
111
112
|
await storage.set(StorageKey.SessionSeen, String(timestamp));
|
|
112
113
|
return session;
|
|
@@ -115,7 +116,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
115
116
|
state: () => storage.get(StorageKey.State),
|
|
116
117
|
lastId: async () => {
|
|
117
118
|
const id = await storage.get(StorageKey.LastId);
|
|
118
|
-
return id ===
|
|
119
|
+
return id === "" ? undefined : id;
|
|
119
120
|
},
|
|
120
121
|
setLastId: (id) => storage.set(StorageKey.LastId, id),
|
|
121
122
|
forgetLastId: () => storage.set(StorageKey.LastId, FORGOTTEN_ID),
|
|
@@ -128,7 +129,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
128
129
|
await storage.set(StorageKey.InstallId, id);
|
|
129
130
|
return id;
|
|
130
131
|
},
|
|
131
|
-
dropInstallId: () => storage.set(StorageKey.InstallId,
|
|
132
|
+
dropInstallId: () => storage.set(StorageKey.InstallId, ""),
|
|
132
133
|
giveBack: async (envelopes) => {
|
|
133
134
|
for (const { version, events } of envelopes) {
|
|
134
135
|
for (const event of events) {
|
|
@@ -138,15 +139,15 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
138
139
|
},
|
|
139
140
|
setState: (state) => storage.set(StorageKey.State, state),
|
|
140
141
|
// An empty session reads as none, so the next event takes a new one. The storage has no remove.
|
|
141
|
-
endSession: () => storage.set(StorageKey.Session,
|
|
142
|
+
endSession: () => storage.set(StorageKey.Session, ""),
|
|
142
143
|
takeInstall: async (version) => {
|
|
143
144
|
const mark = await storage.get(StorageKey.Installed);
|
|
144
|
-
if (mark !== undefined && mark !==
|
|
145
|
+
if (mark !== undefined && mark !== "") {
|
|
145
146
|
return false;
|
|
146
147
|
}
|
|
147
148
|
// The version goes first, so a failed write leaves the install mark untaken.
|
|
148
149
|
await storage.set(StorageKey.Version, version);
|
|
149
|
-
await storage.set(StorageKey.Installed,
|
|
150
|
+
await storage.set(StorageKey.Installed, "1");
|
|
150
151
|
return true;
|
|
151
152
|
},
|
|
152
153
|
takeVersion: async (version) => {
|
|
@@ -180,7 +181,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
180
181
|
};
|
|
181
182
|
}
|
|
182
183
|
function newSessionId() {
|
|
183
|
-
const alphabet =
|
|
184
|
+
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
184
185
|
const bytes = crypto.getRandomValues(new Uint8Array(SESSION_ID_LENGTH));
|
|
185
|
-
return Array.from(bytes, (byte) => alphabet[byte % alphabet.length]).join(
|
|
186
|
+
return Array.from(bytes, (byte) => alphabet[byte % alphabet.length]).join("");
|
|
186
187
|
}
|
package/dist/outbox.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import type { Clock } from
|
|
2
|
-
import type { Envelope, UsageEvent } from
|
|
3
|
-
import type { Lock } from
|
|
4
|
-
import { type Identity, type QueuedEnvelope } from
|
|
5
|
-
import type { StorageAdapter } from
|
|
6
|
-
import type { Transport } from
|
|
1
|
+
import type { Clock } from "./clock.js";
|
|
2
|
+
import type { Envelope, UsageEvent } from "./envelope.js";
|
|
3
|
+
import type { Lock } from "./lock.js";
|
|
4
|
+
import { type Identity, type QueuedEnvelope } from "./queue.js";
|
|
5
|
+
import type { StorageAdapter } from "./storage.js";
|
|
6
|
+
import type { Transport } from "./transport.js";
|
|
7
7
|
/**
|
|
8
8
|
* Holds the envelopes and the forget requests on their way to the intake. The forget requests leave first, then the
|
|
9
9
|
* envelopes, one at a time, in the order they were made. A request the intake cannot take now goes again later, and
|
|
@@ -15,7 +15,7 @@ interface Outbox {
|
|
|
15
15
|
* Queues the event and sends it within the send delay, at once when its envelope is full, or with the pending retry.
|
|
16
16
|
* Resolves to what the queue dropped to take it, whose marks may go back.
|
|
17
17
|
*/
|
|
18
|
-
add(fields: Omit<Envelope,
|
|
18
|
+
add(fields: Omit<Envelope, "events">, event: UsageEvent, options?: {
|
|
19
19
|
awaitsId?: boolean;
|
|
20
20
|
}): Promise<QueuedEnvelope[]>;
|
|
21
21
|
/** Sends what is queued within the send delay, such as what an earlier run of the host left. */
|
|
@@ -37,10 +37,12 @@ interface Outbox {
|
|
|
37
37
|
forget(id: string): Promise<QueuedEnvelope[]>;
|
|
38
38
|
/** Drops the envelopes that name a user or that await an id. Resolves to those whose marks may go back. */
|
|
39
39
|
discardIdentified(): Promise<QueuedEnvelope[]>;
|
|
40
|
+
/** Resolves to whether the storage holds an envelope or a forget request to send. */
|
|
41
|
+
holdsRequests(): Promise<boolean>;
|
|
40
42
|
}
|
|
41
43
|
/**
|
|
42
|
-
* Expects the caller to run `add`, `discard`, `forget` and `
|
|
43
|
-
* for the whole recording of an event. The sends take the lock themselves.
|
|
44
|
+
* Expects the caller to run `add`, `discard`, `forget`, `discardIdentified` and `holdsRequests` inside its own `lock`,
|
|
45
|
+
* which it holds for the whole recording of an event. The sends take the lock themselves.
|
|
44
46
|
*/
|
|
45
47
|
export declare function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, reportError, }: {
|
|
46
48
|
/** The channel key, which a forget request names. */
|
package/dist/outbox.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { daysBetween, parseDay, utcDateAt } from
|
|
2
|
-
import { isTestKey, isUsableId, quoted } from
|
|
3
|
-
import { newQueue, newRandomId, } from
|
|
1
|
+
import { daysBetween, parseDay, utcDateAt } from "./calendar.js";
|
|
2
|
+
import { isTestKey, isUsableId, quoted } from "./hostInput.js";
|
|
3
|
+
import { newQueue, newRandomId, } from "./queue.js";
|
|
4
4
|
const RETRY_DELAY_MS = 1_000;
|
|
5
5
|
const MAX_RETRY_DELAY_MS = 5 * 60_000;
|
|
6
6
|
/** Names the stored time, in epoch milliseconds, before which no context that shares the storage starts a send. */
|
|
7
|
-
const RETRY_AT_KEY =
|
|
7
|
+
const RETRY_AT_KEY = "retry_at";
|
|
8
8
|
/**
|
|
9
9
|
* The time one send holds the lease on a queued envelope, twice the 30 s request limit of `newHttpTransport` in
|
|
10
10
|
* `src/transport.ts`. The send renews the lease before each request. A host that stops mid-send blocks the envelope
|
|
@@ -18,16 +18,17 @@ const LEASE_MS = 60_000;
|
|
|
18
18
|
const TRANSPORT_LIMIT_MS = 35_000;
|
|
19
19
|
const MAX_HTTP_STATUS = 599;
|
|
20
20
|
/**
|
|
21
|
-
* Expects the caller to run `add`, `discard`, `forget` and `
|
|
22
|
-
* for the whole recording of an event. The sends take the lock themselves.
|
|
21
|
+
* Expects the caller to run `add`, `discard`, `forget`, `discardIdentified` and `holdsRequests` inside its own `lock`,
|
|
22
|
+
* which it holds for the whole recording of an event. The sends take the lock themselves.
|
|
23
23
|
*/
|
|
24
24
|
export function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, reportError, }) {
|
|
25
25
|
const queue = newQueue({ storage, reportError });
|
|
26
26
|
/** Names this outbox's leases, apart from those of other contexts that share the storage. */
|
|
27
27
|
const holder = newRandomId();
|
|
28
|
-
let
|
|
28
|
+
let cancelSendTimer;
|
|
29
29
|
let sendDue = Number.POSITIVE_INFINITY;
|
|
30
|
-
|
|
30
|
+
/** Cancels the timer of the pending retry. Set only while a retry is pending. */
|
|
31
|
+
let cancelRetryTimer;
|
|
31
32
|
let retryDelay = RETRY_DELAY_MS;
|
|
32
33
|
/** Chains the sends, so that one runs at a time and queued envelopes leave in the order they were made. */
|
|
33
34
|
let sending = Promise.resolve();
|
|
@@ -40,23 +41,24 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
40
41
|
return { holder, now: clock.now(), until: clock.now() + LEASE_MS };
|
|
41
42
|
}
|
|
42
43
|
function cancelSend() {
|
|
43
|
-
|
|
44
|
+
cancelSendTimer?.();
|
|
45
|
+
cancelSendTimer = undefined;
|
|
44
46
|
sendDue = Number.POSITIVE_INFINITY;
|
|
45
47
|
}
|
|
46
48
|
function cancelRetry() {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
+
cancelRetryTimer?.();
|
|
50
|
+
cancelRetryTimer = undefined;
|
|
49
51
|
}
|
|
50
52
|
/** Starts a send within `delayMs`, unless a send is due sooner or a retry is pending. */
|
|
51
53
|
function sendWithin(delayMs) {
|
|
52
54
|
// The pending retry carries the new events too. An earlier send would reach an intake that asked the outbox to
|
|
53
55
|
// wait.
|
|
54
|
-
if (
|
|
56
|
+
if (cancelRetryTimer !== undefined || sendDue <= clock.now() + delayMs) {
|
|
55
57
|
return;
|
|
56
58
|
}
|
|
57
|
-
|
|
59
|
+
cancelSendTimer?.();
|
|
58
60
|
sendDue = clock.now() + delayMs;
|
|
59
|
-
|
|
61
|
+
cancelSendTimer = clock.setTimeout(() => void sendUnlessRetryPending(), delayMs);
|
|
60
62
|
}
|
|
61
63
|
/** Sends at once, cancelling a pending retry, as `flush` and a retry timer do. */
|
|
62
64
|
function send() {
|
|
@@ -71,7 +73,9 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
71
73
|
*/
|
|
72
74
|
function sendUnlessRetryPending() {
|
|
73
75
|
cancelSend();
|
|
74
|
-
sending = sending
|
|
76
|
+
sending = sending
|
|
77
|
+
.then(async () => (cancelRetryTimer === undefined ? sendLeased() : undefined))
|
|
78
|
+
.catch(reportError);
|
|
75
79
|
return sending;
|
|
76
80
|
}
|
|
77
81
|
/**
|
|
@@ -80,7 +84,7 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
80
84
|
* now, so it holds no send for longer. The caller holds `lock`.
|
|
81
85
|
*/
|
|
82
86
|
async function retryWaitMs() {
|
|
83
|
-
const stored = (await storage.get(RETRY_AT_KEY)) ??
|
|
87
|
+
const stored = (await storage.get(RETRY_AT_KEY)) ?? "";
|
|
84
88
|
const waitMs = Math.max(0, Number(stored) - clock.now());
|
|
85
89
|
if (waitMs <= MAX_RETRY_DELAY_MS) {
|
|
86
90
|
return waitMs;
|
|
@@ -103,7 +107,9 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
103
107
|
const wait = await retryWaitMs();
|
|
104
108
|
return {
|
|
105
109
|
waitMs: wait,
|
|
106
|
-
taken: wait > 0
|
|
110
|
+
taken: wait > 0
|
|
111
|
+
? undefined
|
|
112
|
+
: { forgets: await queue.forgets(), leased: await queue.lease(leaseTerms()) },
|
|
107
113
|
};
|
|
108
114
|
});
|
|
109
115
|
if (taken === undefined) {
|
|
@@ -148,7 +154,7 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
148
154
|
cancelSend();
|
|
149
155
|
cancelRetry();
|
|
150
156
|
const waitMs = Math.min(Math.max(retryDelay, askedWaitMs ?? 0), MAX_RETRY_DELAY_MS);
|
|
151
|
-
|
|
157
|
+
cancelRetryTimer = clock.setTimeout(() => void send(), waitMs);
|
|
152
158
|
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY_MS);
|
|
153
159
|
await lock(async () => keepRetryWait(waitMs));
|
|
154
160
|
}
|
|
@@ -166,7 +172,7 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
166
172
|
const { isSettled, askedWaitMs } = await deliver({
|
|
167
173
|
body: JSON.stringify({ key, id }),
|
|
168
174
|
transport: forgetTransport,
|
|
169
|
-
what:
|
|
175
|
+
what: "a forget",
|
|
170
176
|
reportError,
|
|
171
177
|
clock,
|
|
172
178
|
});
|
|
@@ -201,7 +207,13 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
201
207
|
unsettled.delete(item.qid);
|
|
202
208
|
continue;
|
|
203
209
|
}
|
|
204
|
-
const { isSettled, askedWaitMs } = await deliver({
|
|
210
|
+
const { isSettled, askedWaitMs } = await deliver({
|
|
211
|
+
body,
|
|
212
|
+
transport,
|
|
213
|
+
what: "an envelope",
|
|
214
|
+
reportError,
|
|
215
|
+
clock,
|
|
216
|
+
});
|
|
205
217
|
if (!isSettled) {
|
|
206
218
|
await waitForRetry(askedWaitMs);
|
|
207
219
|
return;
|
|
@@ -232,6 +244,7 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
232
244
|
return queue.removeId(id);
|
|
233
245
|
},
|
|
234
246
|
discardIdentified: () => queue.removeIdentified(),
|
|
247
|
+
holdsRequests: () => queue.holdsRequests(),
|
|
235
248
|
};
|
|
236
249
|
}
|
|
237
250
|
/**
|
|
@@ -259,10 +272,13 @@ async function deliver({ body, transport, what, reportError, clock, }) {
|
|
|
259
272
|
* Only a product's own transport, outside TypeScript or with a bug, gives such a value.
|
|
260
273
|
*/
|
|
261
274
|
function httpStatus(status, reportError) {
|
|
262
|
-
if (typeof status ===
|
|
275
|
+
if (typeof status === "number" &&
|
|
276
|
+
Number.isInteger(status) &&
|
|
277
|
+
status >= 0 &&
|
|
278
|
+
status <= MAX_HTTP_STATUS) {
|
|
263
279
|
return status;
|
|
264
280
|
}
|
|
265
|
-
reportError(new Error(
|
|
281
|
+
reportError(new Error("artel: the transport answered a status that is no whole number from 0 to 599, read as 0"));
|
|
266
282
|
return 0;
|
|
267
283
|
}
|
|
268
284
|
/**
|
|
@@ -270,20 +286,22 @@ function httpStatus(status, reportError) {
|
|
|
270
286
|
* answers null or undefined, as only a product's own transport outside TypeScript does.
|
|
271
287
|
*/
|
|
272
288
|
async function answerOf(transport, body, clock) {
|
|
273
|
-
let
|
|
289
|
+
let cancelLate;
|
|
274
290
|
const late = new Promise((resolve) => {
|
|
275
|
-
|
|
291
|
+
cancelLate = clock.setTimeout(() => resolve({ status: 0 }), TRANSPORT_LIMIT_MS);
|
|
276
292
|
});
|
|
277
293
|
try {
|
|
278
294
|
const answer = await Promise.race([transport(body), late]);
|
|
279
295
|
// A null or undefined answer throws here, and reads as status 0.
|
|
280
|
-
return typeof answer ===
|
|
296
|
+
return typeof answer === "number"
|
|
297
|
+
? { status: answer }
|
|
298
|
+
: { status: answer.status, retryAfter: answer.retryAfter };
|
|
281
299
|
}
|
|
282
300
|
catch {
|
|
283
301
|
return { status: 0 };
|
|
284
302
|
}
|
|
285
303
|
finally {
|
|
286
|
-
|
|
304
|
+
cancelLate?.();
|
|
287
305
|
}
|
|
288
306
|
}
|
|
289
307
|
/**
|
|
@@ -292,7 +310,7 @@ async function answerOf(transport, body, clock) {
|
|
|
292
310
|
* only a product's own transport outside TypeScript gives.
|
|
293
311
|
*/
|
|
294
312
|
function retryAfterMs(value, now) {
|
|
295
|
-
if (typeof value !==
|
|
313
|
+
if (typeof value !== "string") {
|
|
296
314
|
return undefined;
|
|
297
315
|
}
|
|
298
316
|
if (/^\d+$/.test(value)) {
|
package/dist/page.d.ts
CHANGED
package/dist/page.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { PAGE_VIEW } from
|
|
2
|
-
import { pagePath, referrerHost } from
|
|
1
|
+
import { PAGE_VIEW } from "./envelope.js";
|
|
2
|
+
import { pagePath, referrerHost } from "./pagePath.js";
|
|
3
3
|
/**
|
|
4
4
|
* Returns the reader of an event's page fields from `getPage`. It sends the referrer only with the first recorded
|
|
5
5
|
* `page_view`, as the referrer belongs to the page load. It sends nothing for a `page_view` that repeats the last page.
|
|
@@ -12,8 +12,10 @@ export function newPageReader({ getPage, reportError, }) {
|
|
|
12
12
|
// A host outside TypeScript can return any value, or fields whose getters throw.
|
|
13
13
|
try {
|
|
14
14
|
const fields = getPage?.(name);
|
|
15
|
-
const page = stringField(
|
|
16
|
-
const referrer = mayCarryReferrer
|
|
15
|
+
const page = stringField("page", fields?.page, reportError);
|
|
16
|
+
const referrer = mayCarryReferrer
|
|
17
|
+
? stringField("referrer", fields?.referrer, reportError)
|
|
18
|
+
: undefined;
|
|
17
19
|
const path = page === undefined ? undefined : checkedPath(page, reportError);
|
|
18
20
|
const host = referrer === undefined ? undefined : referrerHost(referrer);
|
|
19
21
|
const isPageHost = page !== undefined && host === referrerHost(page);
|
|
@@ -50,7 +52,7 @@ export function newPageReader({ getPage, reportError, }) {
|
|
|
50
52
|
}
|
|
51
53
|
/** Returns a page field that is a string, or reports and leaves out one that is not. */
|
|
52
54
|
function stringField(name, value, reportError) {
|
|
53
|
-
if (value === undefined || typeof value ===
|
|
55
|
+
if (value === undefined || typeof value === "string") {
|
|
54
56
|
return value;
|
|
55
57
|
}
|
|
56
58
|
reportError(new TypeError(`artel: the ${name} getPage gave is a ${typeof value}, not a string, left out`));
|
|
@@ -63,7 +65,7 @@ function stringField(name, value, reportError) {
|
|
|
63
65
|
function checkedPath(page, reportError) {
|
|
64
66
|
const path = pagePath(page);
|
|
65
67
|
if (path === undefined) {
|
|
66
|
-
reportError(new Error(
|
|
68
|
+
reportError(new Error("artel: a page that is neither a path nor a URL with a path was left out"));
|
|
67
69
|
}
|
|
68
70
|
return path;
|
|
69
71
|
}
|
package/dist/pagePath.js
CHANGED
|
@@ -6,9 +6,9 @@ const MAX_PAGE_LENGTH = 256;
|
|
|
6
6
|
/** The length of a referrer host the intake keeps. */
|
|
7
7
|
const MAX_REFERRER_LENGTH = 128;
|
|
8
8
|
/** What the collector sends in place of a segment that holds an address. */
|
|
9
|
-
const ADDRESS_SEGMENT =
|
|
9
|
+
const ADDRESS_SEGMENT = ":address";
|
|
10
10
|
/** The base `URL` reads a page against, so a page given as a path reads too. */
|
|
11
|
-
const PAGE_BASE =
|
|
11
|
+
const PAGE_BASE = "https://page.invalid";
|
|
12
12
|
/** The most times the collector decodes a segment, so an address escaped twice, as `%2540`, still shows. */
|
|
13
13
|
const MAX_DECODING_PASSES = 2;
|
|
14
14
|
/** The at sign and its look-alikes U+FF20 and U+FE6B. */
|
|
@@ -44,15 +44,15 @@ export function pagePath(page) {
|
|
|
44
44
|
catch {
|
|
45
45
|
return undefined;
|
|
46
46
|
}
|
|
47
|
-
return path.startsWith(
|
|
47
|
+
return path.startsWith("/") ? cut(withoutAddresses(path)) : undefined;
|
|
48
48
|
}
|
|
49
49
|
/** Returns the path cut to 256 characters, never inside an escape or inside the escapes of one UTF-8 character. */
|
|
50
50
|
function cut(path) {
|
|
51
51
|
if (path.length <= MAX_PAGE_LENGTH) {
|
|
52
52
|
return path;
|
|
53
53
|
}
|
|
54
|
-
const kept = path.slice(0, MAX_PAGE_LENGTH).replace(CUT_ESCAPE,
|
|
55
|
-
const lastCharacter = LAST_ENCODED_CHARACTER.exec(kept)?.[0] ??
|
|
54
|
+
const kept = path.slice(0, MAX_PAGE_LENGTH).replace(CUT_ESCAPE, "");
|
|
55
|
+
const lastCharacter = LAST_ENCODED_CHARACTER.exec(kept)?.[0] ?? "";
|
|
56
56
|
return isWholeCharacter(lastCharacter) ? kept : kept.slice(0, kept.length - lastCharacter.length);
|
|
57
57
|
}
|
|
58
58
|
/** Tells whether escapes spell one whole UTF-8 character, or are none. */
|
|
@@ -78,18 +78,18 @@ export function referrerHost(referrer) {
|
|
|
78
78
|
catch {
|
|
79
79
|
return undefined;
|
|
80
80
|
}
|
|
81
|
-
const isIp = host.startsWith(
|
|
81
|
+
const isIp = host.startsWith("[") || /^\d+$/.test(host.slice(host.lastIndexOf(".") + 1));
|
|
82
82
|
// The check decodes the host, since `URL` leaves an at sign or a look-alike escaped in the host of a scheme other
|
|
83
83
|
// than http or https.
|
|
84
84
|
const isAddress = isIp || AT_SIGN.test(decodedOrSame(host));
|
|
85
|
-
return host ===
|
|
85
|
+
return host === "" || host.length > MAX_REFERRER_LENGTH || isAddress ? undefined : host;
|
|
86
86
|
}
|
|
87
87
|
/**
|
|
88
88
|
* Returns the path with `:address` for each segment that holds an address, and one `:address` for the rest of the path
|
|
89
89
|
* from a segment that starts a URL.
|
|
90
90
|
*/
|
|
91
91
|
function withoutAddresses(path) {
|
|
92
|
-
const segments = path.split(
|
|
92
|
+
const segments = path.split("/");
|
|
93
93
|
const kept = [];
|
|
94
94
|
let length = 0;
|
|
95
95
|
for (const [index, whole] of segments.entries()) {
|
|
@@ -97,25 +97,25 @@ function withoutAddresses(path) {
|
|
|
97
97
|
if (length > MAX_PAGE_LENGTH) {
|
|
98
98
|
break;
|
|
99
99
|
}
|
|
100
|
-
const segment = whole.replace(PATH_PARAMETER,
|
|
100
|
+
const segment = whole.replace(PATH_PARAMETER, "");
|
|
101
101
|
const texts = decodings(segment);
|
|
102
102
|
if (startsUrl(texts, segments[index + 1])) {
|
|
103
|
-
return [...kept, ADDRESS_SEGMENT].join(
|
|
103
|
+
return [...kept, ADDRESS_SEGMENT].join("/");
|
|
104
104
|
}
|
|
105
105
|
const sent = texts.some(holdsAddress) ? ADDRESS_SEGMENT : segment;
|
|
106
106
|
kept.push(sent);
|
|
107
107
|
length += sent.length + 1;
|
|
108
108
|
}
|
|
109
|
-
return kept.join(
|
|
109
|
+
return kept.join("/");
|
|
110
110
|
}
|
|
111
111
|
/**
|
|
112
112
|
* Tells whether a segment, given as written and decoded, starts a URL: it holds a scheme and `://` or a special scheme,
|
|
113
113
|
* or it ends in a scheme's colon before an empty segment.
|
|
114
114
|
*/
|
|
115
115
|
function startsUrl(texts, next) {
|
|
116
|
-
const [written =
|
|
116
|
+
const [written = ""] = texts;
|
|
117
117
|
return (texts.some((text) => SCHEME_SLASHES.test(text) || SPECIAL_SCHEME.test(text)) ||
|
|
118
|
-
(next ===
|
|
118
|
+
(next === "" && SCHEME_END.test(written)));
|
|
119
119
|
}
|
|
120
120
|
/** Returns the segment as written and after each decoding pass, until a pass changes nothing or the passes run out. */
|
|
121
121
|
function decodings(segment) {
|
|
@@ -159,5 +159,5 @@ function holdsAddress(text) {
|
|
|
159
159
|
* `::1`.
|
|
160
160
|
*/
|
|
161
161
|
function holdsShortIpv6(text) {
|
|
162
|
-
return text.split(NON_WORD).some((word) => word.includes(
|
|
162
|
+
return text.split(NON_WORD).some((word) => word.includes("::") && HEX_AND_COLONS.test(word));
|
|
163
163
|
}
|
package/dist/queue.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type Envelope, type IdKind, type UsageEvent } from
|
|
2
|
-
import type { StorageAdapter } from
|
|
1
|
+
import { type Envelope, type IdKind, type UsageEvent } from "./envelope.js";
|
|
2
|
+
import type { StorageAdapter } from "./storage.js";
|
|
3
3
|
export declare const QUEUE_KEY = "queue";
|
|
4
4
|
export interface QueuedEnvelope {
|
|
5
5
|
qid: string;
|
|
@@ -22,7 +22,7 @@ export interface QueuedEnvelope {
|
|
|
22
22
|
export interface Identity {
|
|
23
23
|
id: string;
|
|
24
24
|
id_kind: IdKind;
|
|
25
|
-
browser?: Envelope[
|
|
25
|
+
browser?: Envelope["browser"];
|
|
26
26
|
}
|
|
27
27
|
/** Holds a sealed envelope and the body each send attempt carries. */
|
|
28
28
|
export interface SealedEnvelope {
|
|
@@ -49,7 +49,7 @@ interface Queue {
|
|
|
49
49
|
* kB, else to a new one. An `opted_out` takes an envelope of its own. Resolves to whether that envelope holds 100
|
|
50
50
|
* events, and to what the queue dropped: the oldest envelope past 20.
|
|
51
51
|
*/
|
|
52
|
-
add(fields: Omit<Envelope,
|
|
52
|
+
add(fields: Omit<Envelope, "events">, event: UsageEvent, options?: {
|
|
53
53
|
awaitsId?: boolean;
|
|
54
54
|
}): Promise<{
|
|
55
55
|
isFull: boolean;
|
|
@@ -83,6 +83,8 @@ interface Queue {
|
|
|
83
83
|
/** Resolves to the ids of the stored forget requests, oldest first. */
|
|
84
84
|
forgets(): Promise<string[]>;
|
|
85
85
|
removeForget(id: string): Promise<void>;
|
|
86
|
+
/** Resolves to whether the storage holds an envelope or a forget request. Writes and reports nothing. */
|
|
87
|
+
holdsRequests(): Promise<boolean>;
|
|
86
88
|
}
|
|
87
89
|
/** Returns a queue in `storage`. The caller holds a lock around each call. */
|
|
88
90
|
export declare function newQueue({ storage, reportError, }: {
|
package/dist/queue.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { LifecycleEvent } from
|
|
2
|
-
export const QUEUE_KEY =
|
|
1
|
+
import { LifecycleEvent } from "./envelope.js";
|
|
2
|
+
export const QUEUE_KEY = "queue";
|
|
3
3
|
/** Names the ids of the stored forget requests, a JSON list. */
|
|
4
|
-
const FORGETS_KEY =
|
|
4
|
+
const FORGETS_KEY = "forgets";
|
|
5
5
|
const MAX_ENVELOPE_EVENTS = 100;
|
|
6
6
|
/**
|
|
7
7
|
* The largest request body, under 64 KiB with some margin. A keepalive request and the intake both refuse a larger
|
|
@@ -24,7 +24,7 @@ export function newQueue({ storage, reportError, }) {
|
|
|
24
24
|
async function read() {
|
|
25
25
|
const queued = parseQueue(await storage.get(QUEUE_KEY));
|
|
26
26
|
if (queued === undefined) {
|
|
27
|
-
reportError(new Error(
|
|
27
|
+
reportError(new Error("artel: the stored queue is not a JSON list, so it was dropped"));
|
|
28
28
|
await write([]);
|
|
29
29
|
return [];
|
|
30
30
|
}
|
|
@@ -57,12 +57,14 @@ export function newQueue({ storage, reportError, }) {
|
|
|
57
57
|
async function readForgets() {
|
|
58
58
|
let bodies;
|
|
59
59
|
try {
|
|
60
|
-
bodies = JSON.parse((await storage.get(FORGETS_KEY)) ??
|
|
60
|
+
bodies = JSON.parse((await storage.get(FORGETS_KEY)) ?? "[]");
|
|
61
61
|
}
|
|
62
62
|
catch {
|
|
63
63
|
return [];
|
|
64
64
|
}
|
|
65
|
-
return Array.isArray(bodies)
|
|
65
|
+
return Array.isArray(bodies)
|
|
66
|
+
? bodies.filter((body) => typeof body === "string")
|
|
67
|
+
: [];
|
|
66
68
|
}
|
|
67
69
|
async function writeForgets(ids) {
|
|
68
70
|
await storage.set(FORGETS_KEY, JSON.stringify(ids));
|
|
@@ -123,7 +125,9 @@ export function newQueue({ storage, reportError, }) {
|
|
|
123
125
|
seal: async (qid, terms, identity) => {
|
|
124
126
|
const items = await read();
|
|
125
127
|
const item = items.find((candidate) => candidate.qid === qid);
|
|
126
|
-
if (item === undefined ||
|
|
128
|
+
if (item === undefined ||
|
|
129
|
+
!isFree(item, terms) ||
|
|
130
|
+
(item.awaitsId === true && identity === undefined)) {
|
|
127
131
|
return undefined;
|
|
128
132
|
}
|
|
129
133
|
if (item.awaitsId === true && identity !== undefined) {
|
|
@@ -165,6 +169,8 @@ export function newQueue({ storage, reportError, }) {
|
|
|
165
169
|
}
|
|
166
170
|
},
|
|
167
171
|
forgets: readForgets,
|
|
172
|
+
holdsRequests: async () => (parseQueue(await storage.get(QUEUE_KEY))?.length ?? 0) > 0 ||
|
|
173
|
+
(await readForgets()).length > 0,
|
|
168
174
|
removeForget: async (id) => writeForgets((await readForgets()).filter((stored) => stored !== id)),
|
|
169
175
|
};
|
|
170
176
|
}
|
|
@@ -175,7 +181,7 @@ export function newQueue({ storage, reportError, }) {
|
|
|
175
181
|
export function parseQueue(stored) {
|
|
176
182
|
let queued;
|
|
177
183
|
try {
|
|
178
|
-
queued = JSON.parse(stored ??
|
|
184
|
+
queued = JSON.parse(stored ?? "[]");
|
|
179
185
|
}
|
|
180
186
|
catch {
|
|
181
187
|
// The caller reports a queue that is no list. The parser's message quotes the stored text, which may hold an id or
|
|
@@ -193,7 +199,10 @@ function unsent(items) {
|
|
|
193
199
|
*/
|
|
194
200
|
function isFree(item, { holder, now, until }) {
|
|
195
201
|
const { leasedUntil } = item;
|
|
196
|
-
return leasedUntil === undefined ||
|
|
202
|
+
return (leasedUntil === undefined ||
|
|
203
|
+
item.leasedBy === holder ||
|
|
204
|
+
leasedUntil <= now ||
|
|
205
|
+
leasedUntil > until);
|
|
197
206
|
}
|
|
198
207
|
function sameFields(envelope, fields) {
|
|
199
208
|
const { events: _, ...envelopeFields } = envelope;
|
|
@@ -209,12 +218,16 @@ function fits(envelope, event) {
|
|
|
209
218
|
/** Returns `byteCount` random bytes, 8 by default, as lowercase hex. */
|
|
210
219
|
export function newRandomId(byteCount = 8) {
|
|
211
220
|
const bytes = crypto.getRandomValues(new Uint8Array(byteCount));
|
|
212
|
-
return Array.from(bytes, (byte) => byte.toString(16).padStart(2,
|
|
221
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
213
222
|
}
|
|
214
223
|
function isQueuedEnvelope(value) {
|
|
215
|
-
if (typeof value !==
|
|
224
|
+
if (typeof value !== "object" ||
|
|
225
|
+
value === null ||
|
|
226
|
+
typeof Reflect.get(value, "qid") !== "string") {
|
|
216
227
|
return false;
|
|
217
228
|
}
|
|
218
|
-
const envelope = Reflect.get(value,
|
|
219
|
-
return typeof envelope ===
|
|
229
|
+
const envelope = Reflect.get(value, "envelope");
|
|
230
|
+
return (typeof envelope === "object" &&
|
|
231
|
+
envelope !== null &&
|
|
232
|
+
Array.isArray(Reflect.get(envelope, "events")));
|
|
220
233
|
}
|