@kk-forge/artel-collector 0.2.0 → 0.4.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 +136 -121
- package/dist/collector.d.ts +5 -7
- package/dist/collector.js +112 -78
- package/dist/collectorTypes.d.ts +40 -24
- package/dist/collectorTypes.js +14 -4
- package/dist/desktop.d.ts +26 -0
- package/dist/desktop.js +15 -0
- package/dist/envelope.d.ts +4 -0
- package/dist/eventCheck.d.ts +6 -5
- package/dist/eventCheck.js +22 -2
- package/dist/exports.d.ts +2 -0
- package/dist/exports.js +2 -0
- package/dist/extension.d.ts +20 -25
- package/dist/extension.js +119 -31
- package/dist/hostInput.d.ts +10 -1
- package/dist/hostInput.js +20 -4
- package/dist/installState.d.ts +7 -3
- package/dist/installState.js +17 -1
- package/dist/outbox.d.ts +17 -8
- package/dist/outbox.js +62 -20
- package/dist/queue.d.ts +21 -7
- package/dist/queue.js +50 -16
- package/dist/stateFields.d.ts +6 -5
- package/dist/stateFields.js +23 -8
- package/dist/testing.d.ts +28 -0
- package/dist/testing.js +75 -0
- package/dist/transport.d.ts +5 -4
- package/dist/transport.js +1 -1
- package/dist/web.d.ts +5 -16
- package/dist/web.js +3 -17
- package/package.json +12 -4
package/dist/extension.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { type Clock } from './clock.js';
|
|
2
1
|
import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions } from './collectorTypes.js';
|
|
3
2
|
import { type EventParams } from './envelope.js';
|
|
4
3
|
import type { StorageAdapter } from './storage.js';
|
|
@@ -11,21 +10,25 @@ export type ExtensionCollectorOptions = Omit<CommonOptions, 'storage' | 'version
|
|
|
11
10
|
storage?: StorageAdapter | undefined;
|
|
12
11
|
/** The product version, the manifest's by default. */
|
|
13
12
|
version?: string | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* The address of the page Chrome opens when the user removes the extension. The collector sets it with the fields of
|
|
15
|
+
* `uninstallParams()` in its query at construction and after each `setState`. Left out, the collector sets none.
|
|
16
|
+
*/
|
|
17
|
+
uninstallPage?: string | undefined;
|
|
14
18
|
/** An extension sends no page. */
|
|
15
19
|
getPage?: never;
|
|
16
20
|
} & Delivery & ModeOptions;
|
|
17
21
|
/**
|
|
18
22
|
* Returns a collector for an extension's worker or page. It needs the `storage` permission. In the worker it first
|
|
19
|
-
* closes the storage to content scripts, which could otherwise change the user's
|
|
20
|
-
*
|
|
23
|
+
* closes the storage to content scripts, which could otherwise change the user's analytics state and the queue. The
|
|
24
|
+
* worker's collector also sends `installed` and `updated` at Chrome's `onInstalled`, and tracks the events content
|
|
25
|
+
* scripts forward. Chrome needs these listeners registered synchronously at the worker's top level on every start of
|
|
26
|
+
* the worker, so the product builds it there. The worker's collector also sends what the pages queue, even after the
|
|
27
|
+
* page closed.
|
|
21
28
|
*/
|
|
22
|
-
export declare function newExtensionCollector(options: ExtensionCollectorOptions & {
|
|
23
|
-
mode:
|
|
24
|
-
}): Collector<
|
|
25
|
-
export declare function newExtensionCollector(options: ExtensionCollectorOptions & {
|
|
26
|
-
mode: typeof Mode.Anonymous;
|
|
27
|
-
}): Collector<'anonymous'>;
|
|
28
|
-
export declare function newExtensionCollector(options: ExtensionCollectorOptions): Collector;
|
|
29
|
+
export declare function newExtensionCollector<M extends Mode>(options: ExtensionCollectorOptions & {
|
|
30
|
+
mode: M;
|
|
31
|
+
}): Collector<M>;
|
|
29
32
|
/**
|
|
30
33
|
* Returns a storage adapter over `chrome.storage.local`, which the service worker and the extension pages share. It
|
|
31
34
|
* needs the `storage` permission.
|
|
@@ -36,20 +39,12 @@ export declare function newChromeStorageAdapter(): StorageAdapter;
|
|
|
36
39
|
* script's own requests, which carry the page's origin.
|
|
37
40
|
*/
|
|
38
41
|
export declare function forwardTrack(name: string, params?: EventParams): Promise<void>;
|
|
42
|
+
/** The part of the collector a content script uses: it tracks events, and the worker keeps the analytics state. */
|
|
43
|
+
export type ContentScriptCollector = Pick<Collector, 'track'>;
|
|
39
44
|
/**
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
45
|
+
* Returns the collector of a content script. Its `track` hands each event to the service worker with `forwardTrack`,
|
|
46
|
+
* and the worker's collector checks, queues and sends it under the user's analytics state. The state lives in the
|
|
47
|
+
* worker and the extension pages, so a content script can neither read nor change it. It reads no storage, needs no
|
|
48
|
+
* key, version or endpoint, and never throws.
|
|
43
49
|
*/
|
|
44
|
-
export declare function
|
|
45
|
-
clock?: Clock;
|
|
46
|
-
}): () => void;
|
|
47
|
-
/**
|
|
48
|
-
* Sets the uninstall page to `pageUrl` with the fields of `uninstallParams()` added to its query, or to `pageUrl` alone
|
|
49
|
-
* when `uninstallParams()` resolves to undefined. Chrome keeps the address as it was set, so the service worker calls
|
|
50
|
-
* this on each start and after each change of state. It resolves and never rejects. A failure of `uninstallParams()`
|
|
51
|
-
* goes to the collector's `onError`, and any other failure to its own `onError`.
|
|
52
|
-
*/
|
|
53
|
-
export declare function refreshUninstallUrl(collector: Collector, pageUrl: string, { onError }?: {
|
|
54
|
-
onError?: (error: Error) => void;
|
|
55
|
-
}): Promise<void>;
|
|
50
|
+
export declare function newContentScriptCollector(): ContentScriptCollector;
|
package/dist/extension.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { detectBrowser } from './browser.js';
|
|
2
2
|
import { systemClock } from './clock.js';
|
|
3
|
-
import { newCollector } from './collector.js';
|
|
4
|
-
import { Mode } from './collectorTypes.js';
|
|
3
|
+
import { newCollector, sendDelayMsOf } from './collector.js';
|
|
4
|
+
import { AnalyticsState, Mode, } from './collectorTypes.js';
|
|
5
5
|
import { Platform, SYSTEM_EVENTS } from './envelope.js';
|
|
6
|
-
import {
|
|
6
|
+
import { checkEvent } from './eventCheck.js';
|
|
7
7
|
import { reportTo } from './hostInput.js';
|
|
8
|
+
import { parseQueue, QUEUE_KEY } from './queue.js';
|
|
8
9
|
import { newWebLock } from './web.js';
|
|
9
|
-
/** The message in each of the extension's `_locales` that holds that locale's code, such as `pt-BR`. */
|
|
10
|
-
const UI_LANGUAGE_MESSAGE = 'ui_language';
|
|
11
10
|
const FORWARD_TYPE = 'artel.track';
|
|
12
11
|
/**
|
|
13
12
|
* The event names the worker refuses from a content script: every system event, which the intake counts from any page
|
|
@@ -22,20 +21,108 @@ const REFUSED_NAMES = new Set(SYSTEM_EVENTS);
|
|
|
22
21
|
const FORWARDS_PER_MINUTE = 60;
|
|
23
22
|
const MINUTE_MS = 60_000;
|
|
24
23
|
export function newExtensionCollector(options) {
|
|
25
|
-
const
|
|
24
|
+
const isWorker = isServiceWorker();
|
|
25
|
+
const closed = isWorker ? closeToContentScripts(options.onError) : Promise.resolve();
|
|
26
26
|
const defaults = {
|
|
27
27
|
platform: Platform.Extension,
|
|
28
|
-
// The function reads each default only when the caller leaves the option out
|
|
29
|
-
//
|
|
28
|
+
// The function reads each default only when the caller leaves the option out, so outside an extension it needs only
|
|
29
|
+
// `version`.
|
|
30
30
|
version: options.version ?? chromeApi().runtime.getManifest().version,
|
|
31
31
|
storage: after(closed, options.storage ?? newChromeStorageAdapter()),
|
|
32
32
|
lock: options.lock ?? newWebLock(),
|
|
33
33
|
browserLanguage: options.browserLanguage ?? navigator.language,
|
|
34
|
-
uiLanguage: options.uiLanguage ?? localeOfExtension(),
|
|
35
34
|
};
|
|
36
|
-
|
|
37
|
-
? newCollector({ ...options, ...defaults
|
|
38
|
-
: newCollector({ ...options, ...defaults });
|
|
35
|
+
const built = options.mode === Mode.Anonymous
|
|
36
|
+
? newCollector({ ...options, ...defaults })
|
|
37
|
+
: newCollector({ ...options, ...defaults, browser: options.browser ?? (() => detectBrowser(navigator)) });
|
|
38
|
+
const collector = withUninstallPage(built, options.uninstallPage, options.onError);
|
|
39
|
+
if (isWorker) {
|
|
40
|
+
listenAsWorker(collector, {
|
|
41
|
+
queueKey: `artel.${options.key}.${QUEUE_KEY}`,
|
|
42
|
+
sendDelayMs: sendDelayMsOf(options),
|
|
43
|
+
clock: options.clock ?? systemClock,
|
|
44
|
+
onError: options.onError,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return collector;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Registers the worker's listeners: `installed` and `updated` at `onInstalled`, the events content scripts forward, the
|
|
51
|
+
* events pages queue, and an empty `onStartup` listener. Chrome starts a worker with an `onStartup` listener when the
|
|
52
|
+
* browser starts, so the access level is set again before any page or content script runs.
|
|
53
|
+
*/
|
|
54
|
+
function listenAsWorker(collector, { queueKey, sendDelayMs, clock, onError, }) {
|
|
55
|
+
const { runtime, storage } = chromeApi();
|
|
56
|
+
// A page's own send cannot finish once the page closes, as when a popup closes right after an event. The worker
|
|
57
|
+
// sends what pages queue within the send delay. Its own sends add no event to the queue, so they schedule nothing.
|
|
58
|
+
let isSendScheduled = false;
|
|
59
|
+
storage.onChanged.addListener((changes, area) => {
|
|
60
|
+
const change = changes[queueKey];
|
|
61
|
+
if (area !== 'local' || change === undefined || isSendScheduled || !addsEvents(change)) {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
isSendScheduled = true;
|
|
65
|
+
clock.setTimeout(() => {
|
|
66
|
+
isSendScheduled = false;
|
|
67
|
+
void collector.flush();
|
|
68
|
+
}, sendDelayMs);
|
|
69
|
+
});
|
|
70
|
+
runtime.onInstalled.addListener(({ reason }) => {
|
|
71
|
+
if (reason === 'install') {
|
|
72
|
+
void collector.installed();
|
|
73
|
+
}
|
|
74
|
+
else if (reason === 'update') {
|
|
75
|
+
void collector.updated();
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
runtime.onStartup.addListener(() => undefined);
|
|
79
|
+
acceptForwarded(collector, clock, onError);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Returns the collector, which sets the uninstall page now and after each `setState` when `pageUrl` is given. Chrome
|
|
83
|
+
* keeps the address as it was set, so the query must follow the user's state.
|
|
84
|
+
*/
|
|
85
|
+
function withUninstallPage(collector, pageUrl, onError) {
|
|
86
|
+
if (pageUrl === undefined) {
|
|
87
|
+
return collector;
|
|
88
|
+
}
|
|
89
|
+
// Every write of this context goes in turn on one chain. A write that started before the latest `setState` is
|
|
90
|
+
// dropped, so a slow refresh never puts back the fields of a state the user has left.
|
|
91
|
+
let writes = Promise.resolve();
|
|
92
|
+
let changes = 0;
|
|
93
|
+
const write = (params) => {
|
|
94
|
+
const startedAt = changes;
|
|
95
|
+
const earlier = writes;
|
|
96
|
+
writes = (async () => {
|
|
97
|
+
await earlier;
|
|
98
|
+
const fields = await params();
|
|
99
|
+
if (startedAt === changes) {
|
|
100
|
+
await setUninstallUrl(pageUrl, fields, onError);
|
|
101
|
+
}
|
|
102
|
+
})();
|
|
103
|
+
return writes;
|
|
104
|
+
};
|
|
105
|
+
const refresh = () => write(() => collector.uninstallParams());
|
|
106
|
+
void refresh();
|
|
107
|
+
return {
|
|
108
|
+
...collector,
|
|
109
|
+
setState: async (state) => {
|
|
110
|
+
changes++;
|
|
111
|
+
if (state === AnalyticsState.OptedOut || state === AnalyticsState.Anonymous) {
|
|
112
|
+
// A change of state can take 30 seconds or more, as for the opted_out or forget request it sends, and the page
|
|
113
|
+
// must not carry the earlier state's fields meanwhile. The page alone carries fewer than any state's.
|
|
114
|
+
await write(async () => undefined);
|
|
115
|
+
}
|
|
116
|
+
await collector.setState(state);
|
|
117
|
+
await refresh();
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/** Tells whether a change of the stored queue adds an event to it, as a new envelope or one more event of an envelope. */
|
|
122
|
+
function addsEvents({ oldValue, newValue }) {
|
|
123
|
+
const queueOf = (value) => parseQueue(typeof value === 'string' ? value : undefined) ?? [];
|
|
124
|
+
const before = new Map(queueOf(oldValue).map(({ qid, envelope }) => [qid, envelope.events.length]));
|
|
125
|
+
return queueOf(newValue).some(({ qid, envelope }) => envelope.events.length > (before.get(qid) ?? 0));
|
|
39
126
|
}
|
|
40
127
|
/** Tells whether the caller runs in the extension's service worker, the one context that may set the access level. */
|
|
41
128
|
function isServiceWorker() {
|
|
@@ -71,14 +158,6 @@ function after(ready, storage) {
|
|
|
71
158
|
},
|
|
72
159
|
};
|
|
73
160
|
}
|
|
74
|
-
/**
|
|
75
|
-
* Returns the locale Chrome picked from the extension's `_locales`, which each locale names in its `ui_language`
|
|
76
|
-
* message, or undefined when the extension has no such message. Chrome gives no other way to read that choice.
|
|
77
|
-
*/
|
|
78
|
-
function localeOfExtension() {
|
|
79
|
-
const locale = chromeApi().i18n?.getMessage(UI_LANGUAGE_MESSAGE);
|
|
80
|
-
return locale === undefined || locale === '' ? undefined : locale;
|
|
81
|
-
}
|
|
82
161
|
/**
|
|
83
162
|
* Returns a storage adapter over `chrome.storage.local`, which the service worker and the extension pages share. It
|
|
84
163
|
* needs the `storage` permission.
|
|
@@ -106,12 +185,22 @@ export async function forwardTrack(name, params) {
|
|
|
106
185
|
// The send fails while the service worker updates or is gone. The content script drops the event and does not fail.
|
|
107
186
|
}
|
|
108
187
|
}
|
|
188
|
+
/**
|
|
189
|
+
* Returns the collector of a content script. Its `track` hands each event to the service worker with `forwardTrack`,
|
|
190
|
+
* and the worker's collector checks, queues and sends it under the user's analytics state. The state lives in the
|
|
191
|
+
* worker and the extension pages, so a content script can neither read nor change it. It reads no storage, needs no
|
|
192
|
+
* key, version or endpoint, and never throws.
|
|
193
|
+
*/
|
|
194
|
+
export function newContentScriptCollector() {
|
|
195
|
+
return { track: forwardTrack };
|
|
196
|
+
}
|
|
109
197
|
/**
|
|
110
198
|
* Tracks the events content scripts forward with `forwardTrack`, at most 60 a minute. It takes them only from this
|
|
111
199
|
* extension, and only the product's own events: never a system event of the intake, such as `installed` or
|
|
112
|
-
* `uninstalled`, which a content script has no reason to send.
|
|
200
|
+
* `uninstalled`, which a content script has no reason to send. The limit guards the queue against a flood, and the
|
|
201
|
+
* first event it drops in a minute goes to `onError`, so the drop is not silent.
|
|
113
202
|
*/
|
|
114
|
-
|
|
203
|
+
function acceptForwarded(collector, clock, onError) {
|
|
115
204
|
let minuteStart = Number.NEGATIVE_INFINITY;
|
|
116
205
|
let tracked = 0;
|
|
117
206
|
const onMessage = (message, sender) => {
|
|
@@ -125,24 +214,23 @@ export function acceptForwarded(collector, { clock = systemClock } = {}) {
|
|
|
125
214
|
tracked = 0;
|
|
126
215
|
}
|
|
127
216
|
if (tracked < FORWARDS_PER_MINUTE) {
|
|
128
|
-
tracked++;
|
|
129
217
|
void collector.track(message.name, message.params);
|
|
130
218
|
}
|
|
219
|
+
else if (tracked === FORWARDS_PER_MINUTE) {
|
|
220
|
+
reportTo(onError, new Error(`artel: the worker tracks at most ${FORWARDS_PER_MINUTE} forwarded events a minute, so it dropped the rest`));
|
|
221
|
+
}
|
|
222
|
+
tracked++;
|
|
131
223
|
return undefined;
|
|
132
224
|
};
|
|
133
225
|
chromeApi().runtime.onMessage.addListener(onMessage);
|
|
134
|
-
return () => chromeApi().runtime.onMessage.removeListener(onMessage);
|
|
135
226
|
}
|
|
136
227
|
/**
|
|
137
|
-
* Sets the uninstall page to `pageUrl` with
|
|
138
|
-
*
|
|
139
|
-
* this on each start and after each change of state. It resolves and never rejects. A failure of `uninstallParams()`
|
|
140
|
-
* goes to the collector's `onError`, and any other failure to its own `onError`.
|
|
228
|
+
* Sets the uninstall page to `pageUrl` with `params` added to its query, or to `pageUrl` alone without them. It
|
|
229
|
+
* resolves and never rejects: a failure goes to `onError`.
|
|
141
230
|
*/
|
|
142
|
-
|
|
231
|
+
async function setUninstallUrl(pageUrl, params, onError) {
|
|
143
232
|
try {
|
|
144
233
|
const url = new URL(pageUrl);
|
|
145
|
-
const params = await collector.uninstallParams();
|
|
146
234
|
for (const [name, value] of Object.entries(params ?? {})) {
|
|
147
235
|
url.searchParams.set(name, String(value));
|
|
148
236
|
}
|
|
@@ -175,5 +263,5 @@ function isForwarded(message) {
|
|
|
175
263
|
const name = Reflect.get(message, 'name');
|
|
176
264
|
return (typeof name === 'string' &&
|
|
177
265
|
!REFUSED_NAMES.has(name) &&
|
|
178
|
-
|
|
266
|
+
checkEvent(name, Reflect.get(message, 'params')) === undefined);
|
|
179
267
|
}
|
package/dist/hostInput.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Browser } from './browser.js';
|
|
2
|
-
import type { CollectorOptions, GetId } from './collectorTypes.js';
|
|
2
|
+
import type { CollectorOptions, Delivery, GetId } from './collectorTypes.js';
|
|
3
3
|
import type { Build } from './stateFields.js';
|
|
4
4
|
import type { StorageAdapter } from './storage.js';
|
|
5
5
|
type ReportError = (error: unknown) => void;
|
|
@@ -20,12 +20,21 @@ export declare function accepted(name: string, value: string | undefined, check:
|
|
|
20
20
|
* platform that names none. A mistake in the build then fails its first run and its tests.
|
|
21
21
|
*/
|
|
22
22
|
export declare function checkedBuild(options: CollectorOptions): Build;
|
|
23
|
+
/**
|
|
24
|
+
* Throws the `TypeError` a constructor throws for a key, a version, a platform, an endpoint or a transport the intake
|
|
25
|
+
* would refuse every envelope of, and returns otherwise. It reads no host API, so a product's build or test can call it.
|
|
26
|
+
*/
|
|
27
|
+
export declare function checkOptions(options: Pick<CollectorOptions, 'key' | 'version' | 'platform'> & Delivery): void;
|
|
28
|
+
/** Tells whether `key` is a channel's test key, `<kind>-test-<10 characters>`. */
|
|
29
|
+
export declare function isTestKey(key: string): boolean;
|
|
23
30
|
/**
|
|
24
31
|
* Returns a function that gives the host's browser as the intake keeps it, or undefined when there is none. A function
|
|
25
32
|
* the host passes runs only at the first call, which the collector makes only for an event with an id. Reports and
|
|
26
33
|
* leaves out a value that is not a browser, which only a host outside TypeScript passes.
|
|
27
34
|
*/
|
|
28
35
|
export declare function newBrowserReader(browser: Browser | (() => Browser | undefined) | undefined, reportError: ReportError): () => Browser | undefined;
|
|
36
|
+
/** Tells whether `id` is an id the intake takes: a string of 1 to 64 characters. */
|
|
37
|
+
export declare function isUsableId(id: unknown): id is string;
|
|
29
38
|
/**
|
|
30
39
|
* Returns a `getId` that gives a non-empty string of at most 64 characters, or undefined. A host outside TypeScript may
|
|
31
40
|
* return null or an empty string, which then reads as an id the product does not know yet.
|
package/dist/hostInput.js
CHANGED
|
@@ -60,6 +60,18 @@ export function accepted(name, value, check, reportError) {
|
|
|
60
60
|
* platform that names none. A mistake in the build then fails its first run and its tests.
|
|
61
61
|
*/
|
|
62
62
|
export function checkedBuild(options) {
|
|
63
|
+
checkOptions(options);
|
|
64
|
+
const { platform, version } = options;
|
|
65
|
+
if (options.browser !== undefined && platform !== Platform.Web && platform !== Platform.Extension) {
|
|
66
|
+
throw new TypeError(`artel: platform ${platform} names no browser`);
|
|
67
|
+
}
|
|
68
|
+
return { platform, version };
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Throws the `TypeError` a constructor throws for a key, a version, a platform, an endpoint or a transport the intake
|
|
72
|
+
* would refuse every envelope of, and returns otherwise. It reads no host API, so a product's build or test can call it.
|
|
73
|
+
*/
|
|
74
|
+
export function checkOptions(options) {
|
|
63
75
|
checkDelivery(options);
|
|
64
76
|
const { platform, version } = options;
|
|
65
77
|
if (!Object.values(Platform).includes(platform)) {
|
|
@@ -69,10 +81,10 @@ export function checkedBuild(options) {
|
|
|
69
81
|
if (!isVersion(version)) {
|
|
70
82
|
throw new TypeError(`artel: version ${quoted(version)} is not one the intake takes`);
|
|
71
83
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
return {
|
|
84
|
+
}
|
|
85
|
+
/** Tells whether `key` is a channel's test key, `<kind>-test-<10 characters>`. */
|
|
86
|
+
export function isTestKey(key) {
|
|
87
|
+
return CHANNEL_KINDS.some(({ kind, keyFormat }) => key.startsWith(`${kind}-test-`) && keyFormat.test(key));
|
|
76
88
|
}
|
|
77
89
|
/**
|
|
78
90
|
* Throws unless the options name a transport that is a function, or an endpoint that is an https URL, or an http URL of
|
|
@@ -149,6 +161,10 @@ function acceptedBrowser(browser, reportError) {
|
|
|
149
161
|
}
|
|
150
162
|
return copy;
|
|
151
163
|
}
|
|
164
|
+
/** Tells whether `id` is an id the intake takes: a string of 1 to 64 characters. */
|
|
165
|
+
export function isUsableId(id) {
|
|
166
|
+
return typeof id === 'string' && id !== '' && Array.from(id).length <= MAX_ID_LENGTH;
|
|
167
|
+
}
|
|
152
168
|
/**
|
|
153
169
|
* Returns a `getId` that gives a non-empty string of at most 64 characters, or undefined. A host outside TypeScript may
|
|
154
170
|
* return null or an empty string, which then reads as an id the product does not know yet.
|
package/dist/installState.d.ts
CHANGED
|
@@ -18,14 +18,18 @@ 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
|
package/dist/installState.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Period, formatDay, localDateAt, parseDay, periodKey } from './calendar.js';
|
|
2
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
|
|
@@ -11,12 +12,17 @@ const MAX_ACTIVE_DAYS = 21;
|
|
|
11
12
|
* the next id reads as another user's.
|
|
12
13
|
*/
|
|
13
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
19
|
InstallDay: 'install_day',
|
|
16
20
|
Installed: 'installed',
|
|
17
21
|
Version: 'version',
|
|
18
22
|
State: 'state',
|
|
19
|
-
/** The
|
|
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. */
|
|
20
26
|
LastId: 'last_id',
|
|
21
27
|
Session: 'session',
|
|
22
28
|
SessionSeen: 'session_seen',
|
|
@@ -113,6 +119,16 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
113
119
|
},
|
|
114
120
|
setLastId: (id) => storage.set(StorageKey.LastId, id),
|
|
115
121
|
forgetLastId: () => storage.set(StorageKey.LastId, FORGOTTEN_ID),
|
|
122
|
+
installId: async () => {
|
|
123
|
+
const stored = await storage.get(StorageKey.InstallId);
|
|
124
|
+
if (stored !== undefined && INSTALL_ID_FORMAT.test(stored)) {
|
|
125
|
+
return stored;
|
|
126
|
+
}
|
|
127
|
+
const id = newRandomId(INSTALL_ID_BYTES);
|
|
128
|
+
await storage.set(StorageKey.InstallId, id);
|
|
129
|
+
return id;
|
|
130
|
+
},
|
|
131
|
+
dropInstallId: () => storage.set(StorageKey.InstallId, ''),
|
|
116
132
|
giveBack: async (envelopes) => {
|
|
117
133
|
for (const { version, events } of envelopes) {
|
|
118
134
|
for (const event of events) {
|
package/dist/outbox.d.ts
CHANGED
|
@@ -5,9 +5,10 @@ import { type Identity, type QueuedEnvelope } from './queue.js';
|
|
|
5
5
|
import type { StorageAdapter } from './storage.js';
|
|
6
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
|
/**
|
|
@@ -19,28 +20,36 @@ interface Outbox {
|
|
|
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 once the send in progress, if any, has ended. */
|
|
34
|
-
settled(): Promise<void>;
|
|
35
40
|
}
|
|
36
41
|
/**
|
|
37
42
|
* Expects the caller to run `add`, `discard`, `forget` and `discardIdentified` inside its own `lock`, which it holds
|
|
38
43
|
* for the whole recording of an event. The sends take the lock themselves.
|
|
39
44
|
*/
|
|
40
|
-
export declare function newOutbox({ storage, lock, transport, identify, giveBack, sendDelayMs, clock, reportError, }: {
|
|
45
|
+
export declare function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, reportError, }: {
|
|
46
|
+
/** The channel key, which a forget request names. */
|
|
47
|
+
key: string;
|
|
41
48
|
storage: StorageAdapter;
|
|
42
49
|
lock: Lock;
|
|
43
50
|
transport: Transport;
|
|
51
|
+
/** Delivers a forget request, whose body is `{ key, id }`. */
|
|
52
|
+
forgetTransport: Transport;
|
|
44
53
|
/** The longest an event waits in the queue before a send starts. */
|
|
45
54
|
sendDelayMs: number;
|
|
46
55
|
/**
|
package/dist/outbox.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { daysBetween, parseDay, utcDateAt } from './calendar.js';
|
|
2
|
-
import { quoted } from './hostInput.js';
|
|
2
|
+
import { isTestKey, isUsableId, quoted } from './hostInput.js';
|
|
3
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;
|
|
@@ -21,7 +21,7 @@ const MAX_HTTP_STATUS = 599;
|
|
|
21
21
|
* Expects the caller to run `add`, `discard`, `forget` and `discardIdentified` inside its own `lock`, which it holds
|
|
22
22
|
* 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();
|
|
@@ -99,18 +99,24 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
99
99
|
* when the send stops goes back to the queue.
|
|
100
100
|
*/
|
|
101
101
|
async function sendLeased() {
|
|
102
|
-
const {
|
|
102
|
+
const { taken, waitMs } = await lock(async () => {
|
|
103
103
|
const wait = await retryWaitMs();
|
|
104
|
-
return {
|
|
104
|
+
return {
|
|
105
|
+
waitMs: wait,
|
|
106
|
+
taken: wait > 0 ? undefined : { forgets: await queue.forgets(), leased: await queue.lease(leaseTerms()) },
|
|
107
|
+
};
|
|
105
108
|
});
|
|
106
|
-
if (
|
|
109
|
+
if (taken === undefined) {
|
|
107
110
|
// The pending retry of this context sends at the end of the wait. Without one, a send of its own does.
|
|
108
111
|
sendWithin(waitMs);
|
|
109
112
|
return;
|
|
110
113
|
}
|
|
114
|
+
const { forgets, leased } = taken;
|
|
111
115
|
const unsettled = new Set(leased.map((item) => item.qid));
|
|
112
116
|
try {
|
|
113
|
-
await
|
|
117
|
+
if (await sendForgets(forgets)) {
|
|
118
|
+
await sendInOrder(leased, unsettled);
|
|
119
|
+
}
|
|
114
120
|
}
|
|
115
121
|
finally {
|
|
116
122
|
if (unsettled.size > 0) {
|
|
@@ -134,6 +140,44 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
134
140
|
}
|
|
135
141
|
return sealed;
|
|
136
142
|
}
|
|
143
|
+
/**
|
|
144
|
+
* Starts the retry wait after a request the intake could not take now. The retry carries the requests that came
|
|
145
|
+
* during the wait. A send they armed skips its turn while the retry is pending.
|
|
146
|
+
*/
|
|
147
|
+
async function waitForRetry(askedWaitMs) {
|
|
148
|
+
cancelSend();
|
|
149
|
+
cancelRetry();
|
|
150
|
+
const waitMs = Math.min(Math.max(retryDelay, askedWaitMs ?? 0), MAX_RETRY_DELAY_MS);
|
|
151
|
+
retryTimer = clock.setTimeout(() => void send(), waitMs);
|
|
152
|
+
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY_MS);
|
|
153
|
+
await lock(async () => keepRetryWait(waitMs));
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Sends the stored forget requests, and resolves to whether the intake answered each one. Another context may send
|
|
157
|
+
* the same request at once, which deletes nothing more. The body names this collector's own key, and an id the
|
|
158
|
+
* intake would refuse is dropped unsent: any script of the origin can write the stored ids.
|
|
159
|
+
*/
|
|
160
|
+
async function sendForgets(ids) {
|
|
161
|
+
for (const id of ids) {
|
|
162
|
+
if (!isUsableId(id)) {
|
|
163
|
+
await lock(async () => queue.removeForget(id));
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const { isSettled, askedWaitMs } = await deliver({
|
|
167
|
+
body: JSON.stringify({ key, id }),
|
|
168
|
+
transport: forgetTransport,
|
|
169
|
+
what: 'a forget',
|
|
170
|
+
reportError,
|
|
171
|
+
clock,
|
|
172
|
+
});
|
|
173
|
+
if (!isSettled) {
|
|
174
|
+
await waitForRetry(askedWaitMs);
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
await lock(async () => queue.removeForget(id));
|
|
178
|
+
}
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
137
181
|
/**
|
|
138
182
|
* Sends the envelopes in order. The function seals and reads each one just before its request, so the request carries
|
|
139
183
|
* every event added since the lease. From the first envelope the intake cannot take now, the rest wait for a retry.
|
|
@@ -157,16 +201,9 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
157
201
|
unsettled.delete(item.qid);
|
|
158
202
|
continue;
|
|
159
203
|
}
|
|
160
|
-
const { isSettled, askedWaitMs } = await deliver({ body, transport, reportError, clock });
|
|
204
|
+
const { isSettled, askedWaitMs } = await deliver({ body, transport, what: 'an envelope', reportError, clock });
|
|
161
205
|
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));
|
|
206
|
+
await waitForRetry(askedWaitMs);
|
|
170
207
|
return;
|
|
171
208
|
}
|
|
172
209
|
await lock(async () => queue.remove(item.qid));
|
|
@@ -187,18 +224,23 @@ export function newOutbox({ storage, lock, transport, identify, giveBack, sendDe
|
|
|
187
224
|
// A send in progress holds leases on what it took. Dropping those envelopes here keeps that send from sending them
|
|
188
225
|
// again.
|
|
189
226
|
discard: () => queue.removeAllButOptOuts(),
|
|
190
|
-
forget: (id) =>
|
|
227
|
+
forget: async (id) => {
|
|
228
|
+
// The intake answers a forget with a test key 403, since it would delete the user's live events too.
|
|
229
|
+
if (!isTestKey(key)) {
|
|
230
|
+
await queue.addForget(id);
|
|
231
|
+
}
|
|
232
|
+
return queue.removeId(id);
|
|
233
|
+
},
|
|
191
234
|
discardIdentified: () => queue.removeIdentified(),
|
|
192
|
-
settled: () => sending,
|
|
193
235
|
};
|
|
194
236
|
}
|
|
195
237
|
/**
|
|
196
|
-
* Sends one
|
|
238
|
+
* Sends one request, and resolves to whether it is settled. It is not on 429, a rate limit, on 5xx, a store that
|
|
197
239
|
* missed the write, or on status 0, which a browser also gives for a refusal without CORS headers. Then it resolves to
|
|
198
240
|
* the wait the `Retry-After` of a 429 or 503 asks for too. Any other status outside 2xx means a wrong envelope or
|
|
199
241
|
* channel, so a retry would fail the same way.
|
|
200
242
|
*/
|
|
201
|
-
async function deliver({ body, transport, reportError, clock, }) {
|
|
243
|
+
async function deliver({ body, transport, what, reportError, clock, }) {
|
|
202
244
|
const result = await answerOf(transport, body, clock);
|
|
203
245
|
const status = httpStatus(result.status, reportError);
|
|
204
246
|
if (status === 429 || status === 503) {
|
|
@@ -208,7 +250,7 @@ async function deliver({ body, transport, reportError, clock, }) {
|
|
|
208
250
|
return { isSettled: false };
|
|
209
251
|
}
|
|
210
252
|
if (status < 200 || status >= 300) {
|
|
211
|
-
reportError(new Error(`artel: intake answered ${status}`));
|
|
253
|
+
reportError(new Error(`artel: intake answered ${status} to ${what}`));
|
|
212
254
|
}
|
|
213
255
|
return { isSettled: true };
|
|
214
256
|
}
|