@kk-forge/artel-collector 0.3.0 → 0.4.1
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 +127 -110
- 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/collector.d.ts +11 -8
- package/dist/collector.js +176 -106
- package/dist/collectorTypes.d.ts +67 -42
- package/dist/collectorTypes.js +24 -14
- package/dist/desktop.d.ts +9 -12
- package/dist/desktop.js +8 -3
- package/dist/envelope.d.ts +14 -10
- package/dist/envelope.js +12 -12
- package/dist/eventCheck.d.ts +17 -7
- package/dist/eventCheck.js +64 -23
- package/dist/exports.d.ts +10 -8
- package/dist/exports.js +9 -7
- package/dist/extension.d.ts +27 -37
- package/dist/extension.js +200 -51
- package/dist/fields.d.ts +3 -3
- package/dist/fields.js +7 -7
- package/dist/hostInput.d.ts +13 -4
- package/dist/hostInput.js +44 -22
- package/dist/installState.d.ts +11 -7
- package/dist/installState.js +42 -25
- package/dist/outbox.d.ts +28 -17
- package/dist/outbox.js +89 -31
- package/dist/page.d.ts +1 -1
- package/dist/page.js +8 -6
- package/dist/pagePath.js +14 -14
- package/dist/queue.d.ts +26 -10
- package/dist/queue.js +70 -23
- package/dist/stateFields.d.ts +9 -8
- package/dist/stateFields.js +28 -11
- package/dist/testing.d.ts +31 -0
- package/dist/testing.js +85 -0
- package/dist/throttle.d.ts +30 -0
- package/dist/throttle.js +41 -0
- package/dist/transport.d.ts +15 -5
- package/dist/transport.js +34 -7
- package/dist/web.d.ts +8 -18
- package/dist/web.js +32 -33
- package/package.json +10 -5
package/dist/hostInput.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { copyBrowser } from
|
|
2
|
-
import { Platform } from
|
|
3
|
-
import { isVersion } from
|
|
1
|
+
import { copyBrowser } from "./browser.js";
|
|
2
|
+
import { Platform } from "./envelope.js";
|
|
3
|
+
import { isVersion } from "./fields.js";
|
|
4
4
|
/** The most characters an id may have for the intake to take it. */
|
|
5
5
|
const MAX_ID_LENGTH = 64;
|
|
6
6
|
/** The hosts an http endpoint may name: this machine, as `URL` writes its hostname. */
|
|
7
|
-
const DEVELOPMENT_HOSTS = new Set([
|
|
7
|
+
const DEVELOPMENT_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
8
8
|
/** The most characters of host or stored text a report quotes. A planted value can be megabytes long. */
|
|
9
9
|
const MAX_QUOTED_LENGTH = 64;
|
|
10
10
|
/**
|
|
@@ -12,9 +12,9 @@ const MAX_QUOTED_LENGTH = 64;
|
|
|
12
12
|
* key, then 10 characters of `[0-9a-z]`. The intake refuses an envelope of a platform its channel's kind does not take.
|
|
13
13
|
*/
|
|
14
14
|
const CHANNEL_KINDS = [
|
|
15
|
-
{ kind:
|
|
16
|
-
{ kind:
|
|
17
|
-
{ kind:
|
|
15
|
+
{ kind: "extension", platforms: [Platform.Extension] },
|
|
16
|
+
{ kind: "desktop", platforms: [Platform.MacOs, Platform.Windows, Platform.Linux] },
|
|
17
|
+
{ kind: "site", platforms: [Platform.Web] },
|
|
18
18
|
].map(({ kind, platforms }) => ({
|
|
19
19
|
kind,
|
|
20
20
|
keyFormat: new RegExp(String.raw `^${kind}-(?:test-)?[\da-z]{10}$`),
|
|
@@ -34,7 +34,9 @@ export function quoted(value) {
|
|
|
34
34
|
return typeof value;
|
|
35
35
|
}
|
|
36
36
|
const characters = Array.from(text.slice(0, 2 * MAX_QUOTED_LENGTH));
|
|
37
|
-
return characters.length > MAX_QUOTED_LENGTH
|
|
37
|
+
return characters.length > MAX_QUOTED_LENGTH
|
|
38
|
+
? `${characters.slice(0, MAX_QUOTED_LENGTH).join("")}…`
|
|
39
|
+
: text;
|
|
38
40
|
}
|
|
39
41
|
/** Hands `error` to the host's `onError` as an Error. A handler that throws reaches no caller. */
|
|
40
42
|
export function reportTo(onError, error) {
|
|
@@ -60,6 +62,20 @@ export function accepted(name, value, check, reportError) {
|
|
|
60
62
|
* platform that names none. A mistake in the build then fails its first run and its tests.
|
|
61
63
|
*/
|
|
62
64
|
export function checkedBuild(options) {
|
|
65
|
+
checkOptions(options);
|
|
66
|
+
const { platform, version } = options;
|
|
67
|
+
if (options.browser !== undefined &&
|
|
68
|
+
platform !== Platform.Web &&
|
|
69
|
+
platform !== Platform.Extension) {
|
|
70
|
+
throw new TypeError(`artel: platform ${platform} names no browser`);
|
|
71
|
+
}
|
|
72
|
+
return { platform, version };
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Throws the `TypeError` a constructor throws for a key, a version, a platform, an endpoint or a transport the intake
|
|
76
|
+
* would refuse every envelope of, and returns otherwise. It reads no host API, so a product's build or test can call it.
|
|
77
|
+
*/
|
|
78
|
+
export function checkOptions(options) {
|
|
63
79
|
checkDelivery(options);
|
|
64
80
|
const { platform, version } = options;
|
|
65
81
|
if (!Object.values(Platform).includes(platform)) {
|
|
@@ -69,10 +85,10 @@ export function checkedBuild(options) {
|
|
|
69
85
|
if (!isVersion(version)) {
|
|
70
86
|
throw new TypeError(`artel: version ${quoted(version)} is not one the intake takes`);
|
|
71
87
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
return {
|
|
88
|
+
}
|
|
89
|
+
/** Tells whether `key` is a channel's test key, `<kind>-test-<10 characters>`. */
|
|
90
|
+
export function isTestKey(key) {
|
|
91
|
+
return CHANNEL_KINDS.some(({ kind, keyFormat }) => key.startsWith(`${kind}-test-`) && keyFormat.test(key));
|
|
76
92
|
}
|
|
77
93
|
/**
|
|
78
94
|
* Throws unless the options name a transport that is a function, or an endpoint that is an https URL, or an http URL of
|
|
@@ -82,30 +98,32 @@ export function checkedBuild(options) {
|
|
|
82
98
|
*/
|
|
83
99
|
function checkDelivery({ endpoint, transport }) {
|
|
84
100
|
if (transport !== undefined) {
|
|
85
|
-
if (typeof transport !==
|
|
101
|
+
if (typeof transport !== "function") {
|
|
86
102
|
throw new TypeError(`artel: transport is a ${typeof transport}, not a function`);
|
|
87
103
|
}
|
|
88
104
|
return;
|
|
89
105
|
}
|
|
90
106
|
let url;
|
|
91
107
|
try {
|
|
92
|
-
url = typeof endpoint ===
|
|
108
|
+
url = typeof endpoint === "string" ? new URL(endpoint) : undefined;
|
|
93
109
|
}
|
|
94
110
|
catch {
|
|
95
111
|
// The throw below covers an endpoint that is no URL.
|
|
96
112
|
}
|
|
97
|
-
const isHttps = url?.protocol ===
|
|
98
|
-
if (!isHttps || url?.username !==
|
|
99
|
-
throw new TypeError(
|
|
113
|
+
const isHttps = url?.protocol === "https:" || (url?.protocol === "http:" && isDevelopmentHost(url.hostname));
|
|
114
|
+
if (!isHttps || url?.username !== "" || url.password !== "") {
|
|
115
|
+
throw new TypeError("artel: endpoint is not an https URL without a user or password, or http to a development host");
|
|
100
116
|
}
|
|
101
117
|
}
|
|
102
118
|
/** Tells whether a URL's host is one only this machine or a development setup serves. */
|
|
103
119
|
function isDevelopmentHost(hostname) {
|
|
104
|
-
return DEVELOPMENT_HOSTS.has(hostname) || hostname.endsWith(
|
|
120
|
+
return (DEVELOPMENT_HOSTS.has(hostname) || hostname.endsWith(".localhost") || hostname.endsWith(".test"));
|
|
105
121
|
}
|
|
106
122
|
/** Throws unless `key` has the intake's form, and its channel kind takes `platform`. */
|
|
107
123
|
function checkKey(key, platform) {
|
|
108
|
-
const channel = typeof key ===
|
|
124
|
+
const channel = typeof key === "string"
|
|
125
|
+
? CHANNEL_KINDS.find(({ keyFormat }) => keyFormat.test(key))
|
|
126
|
+
: undefined;
|
|
109
127
|
if (channel === undefined) {
|
|
110
128
|
throw new TypeError(`artel: key ${quoted(key)} is not <kind>-<10 characters> or <kind>-test-<10 characters>`);
|
|
111
129
|
}
|
|
@@ -119,7 +137,7 @@ function checkKey(key, platform) {
|
|
|
119
137
|
* leaves out a value that is not a browser, which only a host outside TypeScript passes.
|
|
120
138
|
*/
|
|
121
139
|
export function newBrowserReader(browser, reportError) {
|
|
122
|
-
if (typeof browser !==
|
|
140
|
+
if (typeof browser !== "function") {
|
|
123
141
|
const copy = acceptedBrowser(browser, reportError);
|
|
124
142
|
return () => copy;
|
|
125
143
|
}
|
|
@@ -149,6 +167,10 @@ function acceptedBrowser(browser, reportError) {
|
|
|
149
167
|
}
|
|
150
168
|
return copy;
|
|
151
169
|
}
|
|
170
|
+
/** Tells whether `id` is an id the intake takes: a string of 1 to 64 characters. */
|
|
171
|
+
export function isUsableId(id) {
|
|
172
|
+
return typeof id === "string" && id !== "" && Array.from(id).length <= MAX_ID_LENGTH;
|
|
173
|
+
}
|
|
152
174
|
/**
|
|
153
175
|
* Returns a `getId` that gives a non-empty string of at most 64 characters, or undefined. A host outside TypeScript may
|
|
154
176
|
* return null or an empty string, which then reads as an id the product does not know yet.
|
|
@@ -156,7 +178,7 @@ function acceptedBrowser(browser, reportError) {
|
|
|
156
178
|
export function usableId(getId, reportError) {
|
|
157
179
|
return async () => {
|
|
158
180
|
const id = await getId();
|
|
159
|
-
if (typeof id !==
|
|
181
|
+
if (typeof id !== "string" || id === "") {
|
|
160
182
|
return undefined;
|
|
161
183
|
}
|
|
162
184
|
// The intake refuses the whole envelope of an id past 64 characters. The event waits as for an unknown id instead.
|
|
@@ -175,7 +197,7 @@ export function newStringStorage(storage) {
|
|
|
175
197
|
return {
|
|
176
198
|
get: async (key) => {
|
|
177
199
|
const value = await storage.get(key);
|
|
178
|
-
return typeof value ===
|
|
200
|
+
return typeof value === "string" ? value : undefined;
|
|
179
201
|
},
|
|
180
202
|
set: (key, value) => storage.set(key, value),
|
|
181
203
|
};
|
package/dist/installState.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Period, type CalendarDate } from
|
|
2
|
-
import { type Envelope } from
|
|
3
|
-
import type { StorageAdapter } from
|
|
1
|
+
import { Period, type CalendarDate } from "./calendar.js";
|
|
2
|
+
import { type Envelope } from "./envelope.js";
|
|
3
|
+
import type { StorageAdapter } from "./storage.js";
|
|
4
4
|
/** What the collector knows about one event when it records it. */
|
|
5
5
|
export interface EventStamp {
|
|
6
6
|
today: CalendarDate;
|
|
@@ -18,20 +18,24 @@ interface InstallState {
|
|
|
18
18
|
state(): Promise<string | undefined>;
|
|
19
19
|
setState(state: string): Promise<void>;
|
|
20
20
|
/**
|
|
21
|
-
* Returns the last id
|
|
22
|
-
* value no id equals.
|
|
21
|
+
* Returns the last id an envelope named the user by, the install id or the id from `getId`, or undefined. After
|
|
22
|
+
* `forgetLastId` it returns a value no id equals.
|
|
23
23
|
*/
|
|
24
24
|
lastId(): Promise<string | undefined>;
|
|
25
|
-
/** Stores the id
|
|
25
|
+
/** Stores the id an envelope names the user by, or `''` once no id does. */
|
|
26
26
|
setLastId(id: string): Promise<void>;
|
|
27
27
|
/** Stores a last id that no id equals, so the next id counts as another user. */
|
|
28
28
|
forgetLastId(): Promise<void>;
|
|
29
|
+
/** Returns the install id, and stores a new one when none is stored or the stored one breaks its form. */
|
|
30
|
+
installId(): Promise<string>;
|
|
31
|
+
/** Deletes the install id, so the next one is new. */
|
|
32
|
+
dropInstallId(): Promise<void>;
|
|
29
33
|
/**
|
|
30
34
|
* Gives back the marks these envelopes' events took that no later event took over, so the next such event takes them
|
|
31
35
|
* again: first-of-period marks, the `installed` mark, and the `updated` version while it is still stored. A
|
|
32
36
|
* first-of-day event also removes its day from the active days.
|
|
33
37
|
*/
|
|
34
|
-
giveBack(envelopes: readonly Pick<Envelope,
|
|
38
|
+
giveBack(envelopes: readonly Pick<Envelope, "version" | "events">[]): Promise<void>;
|
|
35
39
|
/** Ends the session, so the next event starts a new one. */
|
|
36
40
|
endSession(): Promise<void>;
|
|
37
41
|
/** Marks the install and stores `version`. Resolves to true, or to false when the install was marked before. */
|
package/dist/installState.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { Period, formatDay, localDateAt, parseDay, periodKey } from
|
|
2
|
-
import { LifecycleEvent } from
|
|
1
|
+
import { Period, formatDay, localDateAt, parseDay, periodKey, } from "./calendar.js";
|
|
2
|
+
import { LifecycleEvent } from "./envelope.js";
|
|
3
|
+
import { newRandomId } from "./queue.js";
|
|
3
4
|
const SESSION_ID_LENGTH = 12;
|
|
4
5
|
/**
|
|
5
6
|
* The most active days the collector stores. It reports the count in buckets, and the last bucket is `21+`, so the
|
|
@@ -10,18 +11,23 @@ const MAX_ACTIVE_DAYS = 21;
|
|
|
10
11
|
* The last id after the host forgets the user. It is longer than the 64 characters of any id the collector takes, so
|
|
11
12
|
* the next id reads as another user's.
|
|
12
13
|
*/
|
|
13
|
-
const FORGOTTEN_ID =
|
|
14
|
+
const FORGOTTEN_ID = "<forgotten>".repeat(6);
|
|
15
|
+
/** The install id's form: 16 random bytes as lowercase hex, as the intake expects it. */
|
|
16
|
+
const INSTALL_ID_FORMAT = /^[\da-f]{32}$/;
|
|
17
|
+
const INSTALL_ID_BYTES = 16;
|
|
14
18
|
const StorageKey = {
|
|
15
|
-
InstallDay:
|
|
16
|
-
Installed:
|
|
17
|
-
Version:
|
|
18
|
-
State:
|
|
19
|
-
/** The
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
19
|
+
InstallDay: "install_day",
|
|
20
|
+
Installed: "installed",
|
|
21
|
+
Version: "version",
|
|
22
|
+
State: "state",
|
|
23
|
+
/** The random id of the pseudonymous state, `''` once the user left that state. */
|
|
24
|
+
InstallId: "install_id",
|
|
25
|
+
/** The last id an envelope named the user by, `''` when none does, or `FORGOTTEN_ID` after the host forgot it. */
|
|
26
|
+
LastId: "last_id",
|
|
27
|
+
Session: "session",
|
|
28
|
+
SessionSeen: "session_seen",
|
|
23
29
|
/** The local days with a queued or sent event, as a JSON list of `YYYY-MM-DD`. */
|
|
24
|
-
ActiveDays:
|
|
30
|
+
ActiveDays: "active_days",
|
|
25
31
|
firstOf: (period) => `first.${period}`,
|
|
26
32
|
};
|
|
27
33
|
export function newInstallState({ storage, sessionIdleMs, }) {
|
|
@@ -47,12 +53,12 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
47
53
|
async function readActiveDays() {
|
|
48
54
|
let days;
|
|
49
55
|
try {
|
|
50
|
-
days = JSON.parse((await storage.get(StorageKey.ActiveDays)) ??
|
|
56
|
+
days = JSON.parse((await storage.get(StorageKey.ActiveDays)) ?? "[]");
|
|
51
57
|
}
|
|
52
58
|
catch {
|
|
53
59
|
return [];
|
|
54
60
|
}
|
|
55
|
-
return Array.isArray(days) ? days.filter((day) => typeof day ===
|
|
61
|
+
return Array.isArray(days) ? days.filter((day) => typeof day === "string") : [];
|
|
56
62
|
}
|
|
57
63
|
async function countActiveDay(day) {
|
|
58
64
|
const days = await readActiveDays();
|
|
@@ -67,7 +73,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
67
73
|
}
|
|
68
74
|
async function giveBackMark(period, day) {
|
|
69
75
|
if ((await storage.get(StorageKey.firstOf(period))) === periodKey(period, day)) {
|
|
70
|
-
await storage.set(StorageKey.firstOf(period),
|
|
76
|
+
await storage.set(StorageKey.firstOf(period), "");
|
|
71
77
|
}
|
|
72
78
|
}
|
|
73
79
|
async function giveBackFirstMarks(day, first) {
|
|
@@ -85,11 +91,12 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
85
91
|
await giveBackFirstMarks(day, event.first ?? []);
|
|
86
92
|
}
|
|
87
93
|
if (event.name === LifecycleEvent.Installed) {
|
|
88
|
-
await storage.set(StorageKey.Installed,
|
|
94
|
+
await storage.set(StorageKey.Installed, "");
|
|
89
95
|
}
|
|
90
96
|
// A later `updated` of another version stored its own version, which stays.
|
|
91
|
-
if (event.name === LifecycleEvent.Updated &&
|
|
92
|
-
await storage.
|
|
97
|
+
if (event.name === LifecycleEvent.Updated &&
|
|
98
|
+
(await storage.get(StorageKey.Version)) === version) {
|
|
99
|
+
await storage.set(StorageKey.Version, "");
|
|
93
100
|
}
|
|
94
101
|
}
|
|
95
102
|
/**
|
|
@@ -100,7 +107,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
100
107
|
const stored = await storage.get(StorageKey.Session);
|
|
101
108
|
const lastSeen = Number(await storage.get(StorageKey.SessionSeen));
|
|
102
109
|
const isIdle = !(timestamp - lastSeen < sessionIdleMs);
|
|
103
|
-
const session = stored === undefined || stored ===
|
|
110
|
+
const session = stored === undefined || stored === "" || isIdle || isNewDay ? newSessionId() : stored;
|
|
104
111
|
await storage.set(StorageKey.Session, session);
|
|
105
112
|
await storage.set(StorageKey.SessionSeen, String(timestamp));
|
|
106
113
|
return session;
|
|
@@ -109,10 +116,20 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
109
116
|
state: () => storage.get(StorageKey.State),
|
|
110
117
|
lastId: async () => {
|
|
111
118
|
const id = await storage.get(StorageKey.LastId);
|
|
112
|
-
return id ===
|
|
119
|
+
return id === "" ? undefined : id;
|
|
113
120
|
},
|
|
114
121
|
setLastId: (id) => storage.set(StorageKey.LastId, id),
|
|
115
122
|
forgetLastId: () => storage.set(StorageKey.LastId, FORGOTTEN_ID),
|
|
123
|
+
installId: async () => {
|
|
124
|
+
const stored = await storage.get(StorageKey.InstallId);
|
|
125
|
+
if (stored !== undefined && INSTALL_ID_FORMAT.test(stored)) {
|
|
126
|
+
return stored;
|
|
127
|
+
}
|
|
128
|
+
const id = newRandomId(INSTALL_ID_BYTES);
|
|
129
|
+
await storage.set(StorageKey.InstallId, id);
|
|
130
|
+
return id;
|
|
131
|
+
},
|
|
132
|
+
dropInstallId: () => storage.set(StorageKey.InstallId, ""),
|
|
116
133
|
giveBack: async (envelopes) => {
|
|
117
134
|
for (const { version, events } of envelopes) {
|
|
118
135
|
for (const event of events) {
|
|
@@ -122,15 +139,15 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
122
139
|
},
|
|
123
140
|
setState: (state) => storage.set(StorageKey.State, state),
|
|
124
141
|
// 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,
|
|
142
|
+
endSession: () => storage.set(StorageKey.Session, ""),
|
|
126
143
|
takeInstall: async (version) => {
|
|
127
144
|
const mark = await storage.get(StorageKey.Installed);
|
|
128
|
-
if (mark !== undefined && mark !==
|
|
145
|
+
if (mark !== undefined && mark !== "") {
|
|
129
146
|
return false;
|
|
130
147
|
}
|
|
131
148
|
// The version goes first, so a failed write leaves the install mark untaken.
|
|
132
149
|
await storage.set(StorageKey.Version, version);
|
|
133
|
-
await storage.set(StorageKey.Installed,
|
|
150
|
+
await storage.set(StorageKey.Installed, "1");
|
|
134
151
|
return true;
|
|
135
152
|
},
|
|
136
153
|
takeVersion: async (version) => {
|
|
@@ -164,7 +181,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
164
181
|
};
|
|
165
182
|
}
|
|
166
183
|
function newSessionId() {
|
|
167
|
-
const alphabet =
|
|
184
|
+
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
168
185
|
const bytes = crypto.getRandomValues(new Uint8Array(SESSION_ID_LENGTH));
|
|
169
|
-
return Array.from(bytes, (byte) => alphabet[byte % alphabet.length]).join(
|
|
186
|
+
return Array.from(bytes, (byte) => alphabet[byte % alphabet.length]).join("");
|
|
170
187
|
}
|
package/dist/outbox.d.ts
CHANGED
|
@@ -1,46 +1,57 @@
|
|
|
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
|
-
* Holds the envelopes on their way to the intake.
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* Holds the envelopes and the forget requests on their way to the intake. The forget requests leave first, then the
|
|
9
|
+
* envelopes, one at a time, in the order they were made. A request the intake cannot take now goes again later, and
|
|
10
|
+
* each wait doubles, up to five minutes. A longer `Retry-After` of a 429 or 503 sets the wait instead. Every context
|
|
11
|
+
* that shares the storage keeps the longest wait any of them stored.
|
|
11
12
|
*/
|
|
12
13
|
interface Outbox {
|
|
13
14
|
/**
|
|
14
15
|
* Queues the event and sends it within the send delay, at once when its envelope is full, or with the pending retry.
|
|
15
16
|
* Resolves to what the queue dropped to take it, whose marks may go back.
|
|
16
17
|
*/
|
|
17
|
-
add(fields: Omit<Envelope,
|
|
18
|
+
add(fields: Omit<Envelope, "events">, event: UsageEvent, options?: {
|
|
18
19
|
awaitsId?: boolean;
|
|
19
20
|
}): Promise<QueuedEnvelope[]>;
|
|
20
21
|
/** Sends what is queued within the send delay, such as what an earlier run of the host left. */
|
|
21
22
|
sendSoon(): void;
|
|
22
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* Sends what is queued now, in turn after any send in progress, or once the retry wait is over. A request in progress
|
|
25
|
+
* that carries a forgotten id thus reaches the intake before the forget does.
|
|
26
|
+
*/
|
|
23
27
|
send(): Promise<void>;
|
|
24
28
|
/**
|
|
25
29
|
* Drops every envelope not sent yet but those of an `opted_out`. Resolves to those whose marks may go back, as
|
|
26
30
|
* `src/queue.ts` describes.
|
|
27
31
|
*/
|
|
28
32
|
discard(): Promise<QueuedEnvelope[]>;
|
|
29
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Drops the envelopes of this id and stores the request that asks the intake to delete the id's events, except with
|
|
35
|
+
* a test key. Resolves to all of them, since the intake deletes their events too.
|
|
36
|
+
*/
|
|
30
37
|
forget(id: string): Promise<QueuedEnvelope[]>;
|
|
31
38
|
/** Drops the envelopes that name a user or that await an id. Resolves to those whose marks may go back. */
|
|
32
39
|
discardIdentified(): Promise<QueuedEnvelope[]>;
|
|
33
|
-
/** Resolves
|
|
34
|
-
|
|
40
|
+
/** Resolves to whether the storage holds an envelope or a forget request to send. */
|
|
41
|
+
holdsRequests(): Promise<boolean>;
|
|
35
42
|
}
|
|
36
43
|
/**
|
|
37
|
-
* Expects the caller to run `add`, `discard`, `forget` and `
|
|
38
|
-
* 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.
|
|
39
46
|
*/
|
|
40
|
-
export declare function newOutbox({ storage, lock, transport, identify, giveBack, sendDelayMs, clock, reportError, }: {
|
|
47
|
+
export declare function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, reportError, }: {
|
|
48
|
+
/** The channel key, which a forget request names. */
|
|
49
|
+
key: string;
|
|
41
50
|
storage: StorageAdapter;
|
|
42
51
|
lock: Lock;
|
|
43
52
|
transport: Transport;
|
|
53
|
+
/** Delivers a forget request, whose body is `{ key, id }`. */
|
|
54
|
+
forgetTransport: Transport;
|
|
44
55
|
/** The longest an event waits in the queue before a send starts. */
|
|
45
56
|
sendDelayMs: number;
|
|
46
57
|
/**
|
package/dist/outbox.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { daysBetween, parseDay, utcDateAt } from
|
|
2
|
-
import { 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,10 +18,10 @@ 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
|
-
export function newOutbox({ storage, lock, transport, identify, giveBack, sendDelayMs, clock, reportError, }) {
|
|
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();
|
|
@@ -71,7 +71,9 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
71
71
|
*/
|
|
72
72
|
function sendUnlessRetryPending() {
|
|
73
73
|
cancelSend();
|
|
74
|
-
sending = sending
|
|
74
|
+
sending = sending
|
|
75
|
+
.then(async () => (retryTimer === undefined ? sendLeased() : undefined))
|
|
76
|
+
.catch(reportError);
|
|
75
77
|
return sending;
|
|
76
78
|
}
|
|
77
79
|
/**
|
|
@@ -80,7 +82,7 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
80
82
|
* now, so it holds no send for longer. The caller holds `lock`.
|
|
81
83
|
*/
|
|
82
84
|
async function retryWaitMs() {
|
|
83
|
-
const stored = (await storage.get(RETRY_AT_KEY)) ??
|
|
85
|
+
const stored = (await storage.get(RETRY_AT_KEY)) ?? "";
|
|
84
86
|
const waitMs = Math.max(0, Number(stored) - clock.now());
|
|
85
87
|
if (waitMs <= MAX_RETRY_DELAY_MS) {
|
|
86
88
|
return waitMs;
|
|
@@ -99,18 +101,26 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
99
101
|
* when the send stops goes back to the queue.
|
|
100
102
|
*/
|
|
101
103
|
async function sendLeased() {
|
|
102
|
-
const {
|
|
104
|
+
const { taken, waitMs } = await lock(async () => {
|
|
103
105
|
const wait = await retryWaitMs();
|
|
104
|
-
return {
|
|
106
|
+
return {
|
|
107
|
+
waitMs: wait,
|
|
108
|
+
taken: wait > 0
|
|
109
|
+
? undefined
|
|
110
|
+
: { forgets: await queue.forgets(), leased: await queue.lease(leaseTerms()) },
|
|
111
|
+
};
|
|
105
112
|
});
|
|
106
|
-
if (
|
|
113
|
+
if (taken === undefined) {
|
|
107
114
|
// The pending retry of this context sends at the end of the wait. Without one, a send of its own does.
|
|
108
115
|
sendWithin(waitMs);
|
|
109
116
|
return;
|
|
110
117
|
}
|
|
118
|
+
const { forgets, leased } = taken;
|
|
111
119
|
const unsettled = new Set(leased.map((item) => item.qid));
|
|
112
120
|
try {
|
|
113
|
-
await
|
|
121
|
+
if (await sendForgets(forgets)) {
|
|
122
|
+
await sendInOrder(leased, unsettled);
|
|
123
|
+
}
|
|
114
124
|
}
|
|
115
125
|
finally {
|
|
116
126
|
if (unsettled.size > 0) {
|
|
@@ -134,6 +144,44 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
134
144
|
}
|
|
135
145
|
return sealed;
|
|
136
146
|
}
|
|
147
|
+
/**
|
|
148
|
+
* Starts the retry wait after a request the intake could not take now. The retry carries the requests that came
|
|
149
|
+
* during the wait. A send they armed skips its turn while the retry is pending.
|
|
150
|
+
*/
|
|
151
|
+
async function waitForRetry(askedWaitMs) {
|
|
152
|
+
cancelSend();
|
|
153
|
+
cancelRetry();
|
|
154
|
+
const waitMs = Math.min(Math.max(retryDelay, askedWaitMs ?? 0), MAX_RETRY_DELAY_MS);
|
|
155
|
+
retryTimer = clock.setTimeout(() => void send(), waitMs);
|
|
156
|
+
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY_MS);
|
|
157
|
+
await lock(async () => keepRetryWait(waitMs));
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Sends the stored forget requests, and resolves to whether the intake answered each one. Another context may send
|
|
161
|
+
* the same request at once, which deletes nothing more. The body names this collector's own key, and an id the
|
|
162
|
+
* intake would refuse is dropped unsent: any script of the origin can write the stored ids.
|
|
163
|
+
*/
|
|
164
|
+
async function sendForgets(ids) {
|
|
165
|
+
for (const id of ids) {
|
|
166
|
+
if (!isUsableId(id)) {
|
|
167
|
+
await lock(async () => queue.removeForget(id));
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
const { isSettled, askedWaitMs } = await deliver({
|
|
171
|
+
body: JSON.stringify({ key, id }),
|
|
172
|
+
transport: forgetTransport,
|
|
173
|
+
what: "a forget",
|
|
174
|
+
reportError,
|
|
175
|
+
clock,
|
|
176
|
+
});
|
|
177
|
+
if (!isSettled) {
|
|
178
|
+
await waitForRetry(askedWaitMs);
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
await lock(async () => queue.removeForget(id));
|
|
182
|
+
}
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
137
185
|
/**
|
|
138
186
|
* Sends the envelopes in order. The function seals and reads each one just before its request, so the request carries
|
|
139
187
|
* every event added since the lease. From the first envelope the intake cannot take now, the rest wait for a retry.
|
|
@@ -157,16 +205,15 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
157
205
|
unsettled.delete(item.qid);
|
|
158
206
|
continue;
|
|
159
207
|
}
|
|
160
|
-
const { isSettled, askedWaitMs } = await deliver({
|
|
208
|
+
const { isSettled, askedWaitMs } = await deliver({
|
|
209
|
+
body,
|
|
210
|
+
transport,
|
|
211
|
+
what: "an envelope",
|
|
212
|
+
reportError,
|
|
213
|
+
clock,
|
|
214
|
+
});
|
|
161
215
|
if (!isSettled) {
|
|
162
|
-
|
|
163
|
-
// retry is pending.
|
|
164
|
-
cancelSend();
|
|
165
|
-
cancelRetry();
|
|
166
|
-
const waitMs = Math.min(Math.max(retryDelay, askedWaitMs ?? 0), MAX_RETRY_DELAY_MS);
|
|
167
|
-
retryTimer = clock.setTimeout(() => void send(), waitMs);
|
|
168
|
-
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY_MS);
|
|
169
|
-
await lock(async () => keepRetryWait(waitMs));
|
|
216
|
+
await waitForRetry(askedWaitMs);
|
|
170
217
|
return;
|
|
171
218
|
}
|
|
172
219
|
await lock(async () => queue.remove(item.qid));
|
|
@@ -187,18 +234,24 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
187
234
|
// A send in progress holds leases on what it took. Dropping those envelopes here keeps that send from sending them
|
|
188
235
|
// again.
|
|
189
236
|
discard: () => queue.removeAllButOptOuts(),
|
|
190
|
-
forget: (id) =>
|
|
237
|
+
forget: async (id) => {
|
|
238
|
+
// The intake answers a forget with a test key 403, since it would delete the user's live events too.
|
|
239
|
+
if (!isTestKey(key)) {
|
|
240
|
+
await queue.addForget(id);
|
|
241
|
+
}
|
|
242
|
+
return queue.removeId(id);
|
|
243
|
+
},
|
|
191
244
|
discardIdentified: () => queue.removeIdentified(),
|
|
192
|
-
|
|
245
|
+
holdsRequests: () => queue.holdsRequests(),
|
|
193
246
|
};
|
|
194
247
|
}
|
|
195
248
|
/**
|
|
196
|
-
* Sends one
|
|
249
|
+
* Sends one request, and resolves to whether it is settled. It is not on 429, a rate limit, on 5xx, a store that
|
|
197
250
|
* missed the write, or on status 0, which a browser also gives for a refusal without CORS headers. Then it resolves to
|
|
198
251
|
* the wait the `Retry-After` of a 429 or 503 asks for too. Any other status outside 2xx means a wrong envelope or
|
|
199
252
|
* channel, so a retry would fail the same way.
|
|
200
253
|
*/
|
|
201
|
-
async function deliver({ body, transport, reportError, clock, }) {
|
|
254
|
+
async function deliver({ body, transport, what, reportError, clock, }) {
|
|
202
255
|
const result = await answerOf(transport, body, clock);
|
|
203
256
|
const status = httpStatus(result.status, reportError);
|
|
204
257
|
if (status === 429 || status === 503) {
|
|
@@ -208,7 +261,7 @@ async function deliver({ body, transport, reportError, clock, }) {
|
|
|
208
261
|
return { isSettled: false };
|
|
209
262
|
}
|
|
210
263
|
if (status < 200 || status >= 300) {
|
|
211
|
-
reportError(new Error(`artel: intake answered ${status}`));
|
|
264
|
+
reportError(new Error(`artel: intake answered ${status} to ${what}`));
|
|
212
265
|
}
|
|
213
266
|
return { isSettled: true };
|
|
214
267
|
}
|
|
@@ -217,10 +270,13 @@ async function deliver({ body, transport, reportError, clock, }) {
|
|
|
217
270
|
* Only a product's own transport, outside TypeScript or with a bug, gives such a value.
|
|
218
271
|
*/
|
|
219
272
|
function httpStatus(status, reportError) {
|
|
220
|
-
if (typeof status ===
|
|
273
|
+
if (typeof status === "number" &&
|
|
274
|
+
Number.isInteger(status) &&
|
|
275
|
+
status >= 0 &&
|
|
276
|
+
status <= MAX_HTTP_STATUS) {
|
|
221
277
|
return status;
|
|
222
278
|
}
|
|
223
|
-
reportError(new Error(
|
|
279
|
+
reportError(new Error("artel: the transport answered a status that is no whole number from 0 to 599, read as 0"));
|
|
224
280
|
return 0;
|
|
225
281
|
}
|
|
226
282
|
/**
|
|
@@ -235,7 +291,9 @@ async function answerOf(transport, body, clock) {
|
|
|
235
291
|
try {
|
|
236
292
|
const answer = await Promise.race([transport(body), late]);
|
|
237
293
|
// A null or undefined answer throws here, and reads as status 0.
|
|
238
|
-
return typeof answer ===
|
|
294
|
+
return typeof answer === "number"
|
|
295
|
+
? { status: answer }
|
|
296
|
+
: { status: answer.status, retryAfter: answer.retryAfter };
|
|
239
297
|
}
|
|
240
298
|
catch {
|
|
241
299
|
return { status: 0 };
|
|
@@ -250,7 +308,7 @@ async function answerOf(transport, body, clock) {
|
|
|
250
308
|
* only a product's own transport outside TypeScript gives.
|
|
251
309
|
*/
|
|
252
310
|
function retryAfterMs(value, now) {
|
|
253
|
-
if (typeof value !==
|
|
311
|
+
if (typeof value !== "string") {
|
|
254
312
|
return undefined;
|
|
255
313
|
}
|
|
256
314
|
if (/^\d+$/.test(value)) {
|
package/dist/page.d.ts
CHANGED