@kk-forge/artel-collector 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +226 -84
- package/dist/browser.d.ts +41 -0
- package/dist/browser.js +99 -0
- package/dist/collector.d.ts +12 -81
- package/dist/collector.js +252 -123
- package/dist/collectorTypes.d.ts +193 -0
- package/dist/collectorTypes.js +25 -0
- package/dist/desktop.d.ts +29 -0
- package/dist/desktop.js +10 -0
- package/dist/envelope.d.ts +29 -7
- package/dist/envelope.js +19 -3
- package/dist/eventCheck.d.ts +12 -0
- package/dist/eventCheck.js +110 -0
- package/dist/exports.d.ts +4 -2
- package/dist/exports.js +3 -1
- package/dist/extension.d.ts +44 -7
- package/dist/extension.js +98 -117
- package/dist/fields.d.ts +34 -0
- package/dist/fields.js +103 -0
- package/dist/hostInput.d.ts +39 -0
- package/dist/hostInput.js +182 -0
- package/dist/installState.d.ts +30 -4
- package/dist/installState.js +110 -25
- package/dist/lock.d.ts +10 -1
- package/dist/lock.js +12 -1
- package/dist/outbox.d.ts +31 -12
- package/dist/outbox.js +161 -52
- package/dist/page.d.ts +30 -0
- package/dist/page.js +69 -0
- package/dist/pagePath.d.ts +12 -0
- package/dist/pagePath.js +163 -0
- package/dist/queue.d.ts +37 -14
- package/dist/queue.js +98 -35
- package/dist/stateFields.d.ts +36 -0
- package/dist/stateFields.js +36 -0
- package/dist/storage.d.ts +9 -1
- package/dist/storage.js +11 -0
- package/dist/transport.d.ts +11 -5
- package/dist/transport.js +5 -3
- package/dist/web.d.ts +37 -9
- package/dist/web.js +94 -18
- package/package.json +5 -1
package/dist/page.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { PageFields } from './collectorTypes.js';
|
|
2
|
+
/** What `getPage` gave when a method was called, shaped as the collector sends it. */
|
|
3
|
+
export interface PageRead {
|
|
4
|
+
name: string;
|
|
5
|
+
/** The page fields the event carries, the referrer only when it may be the first `page_view` recorded. */
|
|
6
|
+
fields?: PageFields | undefined;
|
|
7
|
+
}
|
|
8
|
+
/** What a recorded event carries of its page, from `PageReader.view`. */
|
|
9
|
+
interface PageView {
|
|
10
|
+
fields?: PageFields | undefined;
|
|
11
|
+
/** Whether the event is a `page_view` of the page the last recorded `page_view` sent, which sends nothing. */
|
|
12
|
+
isRepeatedView: boolean;
|
|
13
|
+
/** Notes the event as recorded, so a later `page_view` reads it as the last one. */
|
|
14
|
+
recorded(): void;
|
|
15
|
+
}
|
|
16
|
+
/** Reads the page fields of an event when a method is called, and decides what they carry when it is recorded. */
|
|
17
|
+
export interface PageReader {
|
|
18
|
+
read(name: string): PageRead;
|
|
19
|
+
view(read: PageRead): PageView;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Returns the reader of an event's page fields from `getPage`. It sends the referrer only with the first recorded
|
|
23
|
+
* `page_view`, as the referrer belongs to the page load. It sends nothing for a `page_view` that repeats the last page.
|
|
24
|
+
* It never throws: it reports a bad `getPage` result and leaves that field out.
|
|
25
|
+
*/
|
|
26
|
+
export declare function newPageReader({ getPage, reportError, }: {
|
|
27
|
+
getPage: ((name: string) => PageFields | undefined) | undefined;
|
|
28
|
+
reportError: (error: unknown) => void;
|
|
29
|
+
}): PageReader;
|
|
30
|
+
export {};
|
package/dist/page.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { PAGE_VIEW } from './envelope.js';
|
|
2
|
+
import { pagePath, referrerHost } from './pagePath.js';
|
|
3
|
+
/**
|
|
4
|
+
* Returns the reader of an event's page fields from `getPage`. It sends the referrer only with the first recorded
|
|
5
|
+
* `page_view`, as the referrer belongs to the page load. It sends nothing for a `page_view` that repeats the last page.
|
|
6
|
+
* It never throws: it reports a bad `getPage` result and leaves that field out.
|
|
7
|
+
*/
|
|
8
|
+
export function newPageReader({ getPage, reportError, }) {
|
|
9
|
+
let isPageViewRecorded = false;
|
|
10
|
+
let lastViewedPage;
|
|
11
|
+
function fieldsOf(name, mayCarryReferrer) {
|
|
12
|
+
// A host outside TypeScript can return any value, or fields whose getters throw.
|
|
13
|
+
try {
|
|
14
|
+
const fields = getPage?.(name);
|
|
15
|
+
const page = stringField('page', fields?.page, reportError);
|
|
16
|
+
const referrer = mayCarryReferrer ? stringField('referrer', fields?.referrer, reportError) : undefined;
|
|
17
|
+
const path = page === undefined ? undefined : checkedPath(page, reportError);
|
|
18
|
+
const host = referrer === undefined ? undefined : referrerHost(referrer);
|
|
19
|
+
const isPageHost = page !== undefined && host === referrerHost(page);
|
|
20
|
+
return {
|
|
21
|
+
...(path !== undefined && { page: path }),
|
|
22
|
+
...(host !== undefined && !isPageHost && { referrer: host }),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
reportError(error);
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
read: (name) => ({ name, fields: fieldsOf(name, name === PAGE_VIEW && !isPageViewRecorded) }),
|
|
32
|
+
view: ({ name, fields }) => {
|
|
33
|
+
if (name !== PAGE_VIEW) {
|
|
34
|
+
return { fields, isRepeatedView: false, recorded: () => undefined };
|
|
35
|
+
}
|
|
36
|
+
// The view drops the referrer if another call recorded a page_view since this call read it. Only the first
|
|
37
|
+
// recorded page_view has a referrer.
|
|
38
|
+
const { referrer: _referrer, ...withoutReferrer } = fields ?? {};
|
|
39
|
+
const page = fields?.page;
|
|
40
|
+
return {
|
|
41
|
+
fields: isPageViewRecorded ? withoutReferrer : fields,
|
|
42
|
+
isRepeatedView: page !== undefined && page === lastViewedPage,
|
|
43
|
+
recorded: () => {
|
|
44
|
+
isPageViewRecorded = true;
|
|
45
|
+
lastViewedPage = page;
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Returns a page field that is a string, or reports and leaves out one that is not. */
|
|
52
|
+
function stringField(name, value, reportError) {
|
|
53
|
+
if (value === undefined || typeof value === 'string') {
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
reportError(new TypeError(`artel: the ${name} getPage gave is a ${typeof value}, not a string, left out`));
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Returns the path `pagePath` gives, or reports and leaves out a page it cannot read. The report names no part of the
|
|
61
|
+
* page, which may hold an address or a secret.
|
|
62
|
+
*/
|
|
63
|
+
function checkedPath(page, reportError) {
|
|
64
|
+
const path = pagePath(page);
|
|
65
|
+
if (path === undefined) {
|
|
66
|
+
reportError(new Error('artel: a page that is neither a path nor a URL with a path was left out'));
|
|
67
|
+
}
|
|
68
|
+
return path;
|
|
69
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns the path of a page given as a path or a URL, cut to 256 characters, or undefined where `URL` fails or the
|
|
3
|
+
* path lacks a leading `/`. The function drops each `;` path parameter, which can carry a session ID. A segment with an
|
|
4
|
+
* address becomes `:address`, and a URL turns the rest into one `:address`.
|
|
5
|
+
*/
|
|
6
|
+
export declare function pagePath(page: string): string | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* Returns the lowercased host of a referrer URL, or undefined for no URL, no host, a host past 128 characters, an IP
|
|
9
|
+
* address or a host with an `@`. The IP check relies on `URL`, which writes each IPv4 form as four decimal numbers and
|
|
10
|
+
* an IPv6 address in brackets.
|
|
11
|
+
*/
|
|
12
|
+
export declare function referrerHost(referrer: string): string | undefined;
|
package/dist/pagePath.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Shapes the page and the referrer an event carries, so an e-mail address, an IP address or a URL in them never leaves
|
|
2
|
+
// the browser. The intake masks the page and refuses such a referrer itself too, so the rules here need not match its
|
|
3
|
+
// own to the character.
|
|
4
|
+
/** The length of a page path the intake keeps. */
|
|
5
|
+
const MAX_PAGE_LENGTH = 256;
|
|
6
|
+
/** The length of a referrer host the intake keeps. */
|
|
7
|
+
const MAX_REFERRER_LENGTH = 128;
|
|
8
|
+
/** What the collector sends in place of a segment that holds an address. */
|
|
9
|
+
const ADDRESS_SEGMENT = ':address';
|
|
10
|
+
/** The base `URL` reads a page against, so a page given as a path reads too. */
|
|
11
|
+
const PAGE_BASE = 'https://page.invalid';
|
|
12
|
+
/** The most times the collector decodes a segment, so an address escaped twice, as `%2540`, still shows. */
|
|
13
|
+
const MAX_DECODING_PASSES = 2;
|
|
14
|
+
/** The at sign and its look-alikes U+FF20 and U+FE6B. */
|
|
15
|
+
const AT_SIGN = /[@@﹫]/u;
|
|
16
|
+
const IPV4 = /(?<!\d)\d{1,3}(?:\.\d{1,3}){3}(?!\d)/;
|
|
17
|
+
const IPV6_FULL = /(?:[\da-f]{1,4}:){7}[\da-f]{1,4}/i;
|
|
18
|
+
const NON_WORD = /[^\w:]+/;
|
|
19
|
+
const HEX_AND_COLONS = /^[\da-f:]+$/i;
|
|
20
|
+
/** A scheme and `://`, as in `next=https://site.com`. */
|
|
21
|
+
const SCHEME_SLASHES = /[\da-z+.-]:\/\//i;
|
|
22
|
+
/** A special scheme and its colon. A browser reads `https:site.com` as a URL even without `//` after the colon. */
|
|
23
|
+
const SPECIAL_SCHEME = /(?<![\da-z])(?:https?|wss?|ftp|file):/i;
|
|
24
|
+
/** A scheme and its colon at the end of a segment. An empty segment after it makes `scheme://`. */
|
|
25
|
+
const SCHEME_END = /[\da-z+.-]:$/i;
|
|
26
|
+
/** A path parameter: the first `;` of a segment and the rest of it. */
|
|
27
|
+
const PATH_PARAMETER = /;.*/s;
|
|
28
|
+
/** A `%` that lost one or both of its hex digits to the cut. */
|
|
29
|
+
const CUT_ESCAPE = /%[\da-f]?$/i;
|
|
30
|
+
const ESCAPE_RUN = /(?:%[\da-f]{2})+/gi;
|
|
31
|
+
const ASCII_ESCAPE = /%[0-7][\da-f]/gi;
|
|
32
|
+
/** The escapes of the last character a path ends in: a UTF-8 lead byte and the continuation bytes after it. */
|
|
33
|
+
const LAST_ENCODED_CHARACTER = /(?:%[c-f][\da-f])?(?:%[89ab][\da-f]){0,3}$/i;
|
|
34
|
+
/**
|
|
35
|
+
* Returns the path of a page given as a path or a URL, cut to 256 characters, or undefined where `URL` fails or the
|
|
36
|
+
* path lacks a leading `/`. The function drops each `;` path parameter, which can carry a session ID. A segment with an
|
|
37
|
+
* address becomes `:address`, and a URL turns the rest into one `:address`.
|
|
38
|
+
*/
|
|
39
|
+
export function pagePath(page) {
|
|
40
|
+
let path;
|
|
41
|
+
try {
|
|
42
|
+
path = new URL(page, PAGE_BASE).pathname;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
return path.startsWith('/') ? cut(withoutAddresses(path)) : undefined;
|
|
48
|
+
}
|
|
49
|
+
/** Returns the path cut to 256 characters, never inside an escape or inside the escapes of one UTF-8 character. */
|
|
50
|
+
function cut(path) {
|
|
51
|
+
if (path.length <= MAX_PAGE_LENGTH) {
|
|
52
|
+
return path;
|
|
53
|
+
}
|
|
54
|
+
const kept = path.slice(0, MAX_PAGE_LENGTH).replace(CUT_ESCAPE, '');
|
|
55
|
+
const lastCharacter = LAST_ENCODED_CHARACTER.exec(kept)?.[0] ?? '';
|
|
56
|
+
return isWholeCharacter(lastCharacter) ? kept : kept.slice(0, kept.length - lastCharacter.length);
|
|
57
|
+
}
|
|
58
|
+
/** Tells whether escapes spell one whole UTF-8 character, or are none. */
|
|
59
|
+
function isWholeCharacter(escapes) {
|
|
60
|
+
try {
|
|
61
|
+
decodeURIComponent(escapes);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Returns the lowercased host of a referrer URL, or undefined for no URL, no host, a host past 128 characters, an IP
|
|
70
|
+
* address or a host with an `@`. The IP check relies on `URL`, which writes each IPv4 form as four decimal numbers and
|
|
71
|
+
* an IPv6 address in brackets.
|
|
72
|
+
*/
|
|
73
|
+
export function referrerHost(referrer) {
|
|
74
|
+
let host;
|
|
75
|
+
try {
|
|
76
|
+
host = new URL(referrer).hostname.toLowerCase();
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
const isIp = host.startsWith('[') || /^\d+$/.test(host.slice(host.lastIndexOf('.') + 1));
|
|
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
|
+
// than http or https.
|
|
84
|
+
const isAddress = isIp || AT_SIGN.test(decodedOrSame(host));
|
|
85
|
+
return host === '' || host.length > MAX_REFERRER_LENGTH || isAddress ? undefined : host;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Returns the path with `:address` for each segment that holds an address, and one `:address` for the rest of the path
|
|
89
|
+
* from a segment that starts a URL.
|
|
90
|
+
*/
|
|
91
|
+
function withoutAddresses(path) {
|
|
92
|
+
const segments = path.split('/');
|
|
93
|
+
const kept = [];
|
|
94
|
+
let length = 0;
|
|
95
|
+
for (const [index, whole] of segments.entries()) {
|
|
96
|
+
// The loop stops past the 256 characters the cut keeps, so a long page costs little.
|
|
97
|
+
if (length > MAX_PAGE_LENGTH) {
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
const segment = whole.replace(PATH_PARAMETER, '');
|
|
101
|
+
const texts = decodings(segment);
|
|
102
|
+
if (startsUrl(texts, segments[index + 1])) {
|
|
103
|
+
return [...kept, ADDRESS_SEGMENT].join('/');
|
|
104
|
+
}
|
|
105
|
+
const sent = texts.some(holdsAddress) ? ADDRESS_SEGMENT : segment;
|
|
106
|
+
kept.push(sent);
|
|
107
|
+
length += sent.length + 1;
|
|
108
|
+
}
|
|
109
|
+
return kept.join('/');
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Tells whether a segment, given as written and decoded, starts a URL: it holds a scheme and `://` or a special scheme,
|
|
113
|
+
* or it ends in a scheme's colon before an empty segment.
|
|
114
|
+
*/
|
|
115
|
+
function startsUrl(texts, next) {
|
|
116
|
+
const [written = ''] = texts;
|
|
117
|
+
return (texts.some((text) => SCHEME_SLASHES.test(text) || SPECIAL_SCHEME.test(text)) ||
|
|
118
|
+
(next === '' && SCHEME_END.test(written)));
|
|
119
|
+
}
|
|
120
|
+
/** Returns the segment as written and after each decoding pass, until a pass changes nothing or the passes run out. */
|
|
121
|
+
function decodings(segment) {
|
|
122
|
+
const texts = [segment];
|
|
123
|
+
let text = segment;
|
|
124
|
+
for (let pass = 0; pass < MAX_DECODING_PASSES; pass++) {
|
|
125
|
+
const decoded = decodedOrSame(text);
|
|
126
|
+
if (decoded === text) {
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
texts.push(decoded);
|
|
130
|
+
text = decoded;
|
|
131
|
+
}
|
|
132
|
+
return texts;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Returns the text with each run of escapes decoded once. In a run that is not valid UTF-8, only the ASCII escapes
|
|
136
|
+
* decode.
|
|
137
|
+
*/
|
|
138
|
+
function decodedOrSame(text) {
|
|
139
|
+
return text.replaceAll(ESCAPE_RUN, (run) => {
|
|
140
|
+
try {
|
|
141
|
+
return decodeURIComponent(run);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// The catch decodes the ASCII escapes of a run that is not UTF-8, so an `@` beside a stray byte, as in `%E9%40`,
|
|
145
|
+
// still shows.
|
|
146
|
+
return run.replaceAll(ASCII_ESCAPE, (escape) => String.fromCodePoint(Number.parseInt(escape.slice(1), 16)));
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Tells whether the text holds an e-mail address or an IP address. An at sign or a look-alike counts as an e-mail
|
|
152
|
+
* address.
|
|
153
|
+
*/
|
|
154
|
+
function holdsAddress(text) {
|
|
155
|
+
return AT_SIGN.test(text) || IPV4.test(text) || IPV6_FULL.test(text) || holdsShortIpv6(text);
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Tells whether a word of the text is a short IPv6 address, hex digits and colons with a `::`, such as `fe80::1` or
|
|
159
|
+
* `::1`.
|
|
160
|
+
*/
|
|
161
|
+
function holdsShortIpv6(text) {
|
|
162
|
+
return text.split(NON_WORD).some((word) => word.includes('::') && HEX_AND_COLONS.test(word));
|
|
163
|
+
}
|
package/dist/queue.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type Envelope, type UsageEvent } from './envelope.js';
|
|
2
2
|
import type { StorageAdapter } from './storage.js';
|
|
3
3
|
export interface QueuedEnvelope {
|
|
4
4
|
qid: string;
|
|
@@ -11,12 +11,23 @@ export interface QueuedEnvelope {
|
|
|
11
11
|
leasedBy?: string;
|
|
12
12
|
/** The time the lease ends, in epoch milliseconds. */
|
|
13
13
|
leasedUntil?: number;
|
|
14
|
+
/** Marks an identified envelope whose user the product does not know yet. It waits for the id and goes with it. */
|
|
15
|
+
awaitsId?: true;
|
|
16
|
+
/** Marks the envelope of an `opted_out`, which the intake takes only alone. No other event joins it. */
|
|
17
|
+
isOptOut?: true;
|
|
14
18
|
envelope: Envelope;
|
|
15
19
|
}
|
|
20
|
+
/** The user that an identified envelope names, known once the product knows the id. */
|
|
21
|
+
export interface Identity {
|
|
22
|
+
id: string;
|
|
23
|
+
browser?: Envelope['browser'];
|
|
24
|
+
}
|
|
16
25
|
/** Holds a sealed envelope and the body each send attempt carries. */
|
|
17
26
|
export interface SealedEnvelope {
|
|
18
27
|
envelope: Envelope;
|
|
19
28
|
body: string;
|
|
29
|
+
/** Whether an earlier seal stored the body, so a request may have carried it to the intake. */
|
|
30
|
+
isRepeat: boolean;
|
|
20
31
|
}
|
|
21
32
|
/** Names the lease holder, the time of the call and the time the lease ends. Both times are in epoch milliseconds. */
|
|
22
33
|
export interface LeaseTerms {
|
|
@@ -26,37 +37,49 @@ export interface LeaseTerms {
|
|
|
26
37
|
}
|
|
27
38
|
/**
|
|
28
39
|
* Keeps envelopes in storage until the intake takes them, so a host that stops, such as an idle extension service
|
|
29
|
-
* worker, loses none.
|
|
30
|
-
*
|
|
40
|
+
* worker, loses none. A method that drops envelopes resolves to those whose marks may go back: the ones no seal stored
|
|
41
|
+
* a body for, since the intake may keep a request that failed for the sender. `removeId` resolves to all of them.
|
|
31
42
|
*/
|
|
32
|
-
|
|
43
|
+
interface Queue {
|
|
33
44
|
/**
|
|
34
45
|
* Adds the event to the newest envelope with the same fields while it has no body and stays within 100 events and 60
|
|
35
|
-
* kB, else to a new one.
|
|
36
|
-
*
|
|
46
|
+
* kB, else to a new one. An `opted_out` takes an envelope of its own. Resolves to whether that envelope holds 100
|
|
47
|
+
* events, and to what the queue dropped: the oldest envelope past 20.
|
|
37
48
|
*/
|
|
38
|
-
add(fields: Omit<Envelope, 'events'>, event: UsageEvent
|
|
49
|
+
add(fields: Omit<Envelope, 'events'>, event: UsageEvent, options?: {
|
|
50
|
+
awaitsId?: boolean;
|
|
51
|
+
}): Promise<{
|
|
52
|
+
isFull: boolean;
|
|
53
|
+
dropped: QueuedEnvelope[];
|
|
54
|
+
}>;
|
|
39
55
|
/**
|
|
40
56
|
* Leases to `holder`, until `until`, every envelope no other holder has a current lease on. Resolves to them, oldest
|
|
41
57
|
* first.
|
|
42
58
|
*/
|
|
43
59
|
lease(terms: LeaseTerms): Promise<QueuedEnvelope[]>;
|
|
44
60
|
/**
|
|
45
|
-
* Seals one envelope before its request and extends the lease of `holder`.
|
|
46
|
-
* queue id as `batch`. Resolves to undefined when the
|
|
47
|
-
* opt-out, a forget or an expired lease.
|
|
61
|
+
* Seals one envelope before its request and extends the lease of `holder`. An envelope that awaits an id takes
|
|
62
|
+
* `identity` first. The first seal stores the body, with the queue id as `batch`. Resolves to undefined when the
|
|
63
|
+
* envelope is gone or another holder took it, as after an opt-out, a forget or an expired lease.
|
|
48
64
|
*/
|
|
49
|
-
seal(qid: string, terms: LeaseTerms): Promise<SealedEnvelope | undefined>;
|
|
65
|
+
seal(qid: string, terms: LeaseTerms, identity?: Identity): Promise<SealedEnvelope | undefined>;
|
|
50
66
|
/** Drops an envelope the intake took or refused for good. */
|
|
51
67
|
remove(qid: string): Promise<void>;
|
|
52
68
|
/** Ends the lease of `holder` on these envelopes, which keep their place. */
|
|
53
69
|
release(holder: string, qids: readonly string[]): Promise<void>;
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
70
|
+
/**
|
|
71
|
+
* Drops the envelopes that carry this id, as when the host forgets the user. Resolves to all of them, since the
|
|
72
|
+
* intake deletes their events too.
|
|
73
|
+
*/
|
|
74
|
+
removeId(id: string): Promise<QueuedEnvelope[]>;
|
|
75
|
+
/** Drops the envelopes that name a user or wait to, as when the user stops being identified. */
|
|
76
|
+
removeIdentified(): Promise<QueuedEnvelope[]>;
|
|
77
|
+
removeAllButOptOuts(): Promise<QueuedEnvelope[]>;
|
|
57
78
|
}
|
|
79
|
+
/** Returns a queue in `storage`. The caller holds a lock around each call. */
|
|
58
80
|
export declare function newQueue({ storage, reportError, }: {
|
|
59
81
|
storage: StorageAdapter;
|
|
60
82
|
reportError: (error: unknown) => void;
|
|
61
83
|
}): Queue;
|
|
62
84
|
export declare function newRandomId(): string;
|
|
85
|
+
export {};
|
package/dist/queue.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import { LifecycleEvent } from './envelope.js';
|
|
2
|
+
const QUEUE_KEY = 'queue';
|
|
2
3
|
const MAX_ENVELOPE_EVENTS = 100;
|
|
3
4
|
/**
|
|
4
5
|
* The largest request body, under 64 KiB with some margin. A keepalive request and the intake both refuse a larger
|
|
@@ -6,40 +7,86 @@ const MAX_ENVELOPE_EVENTS = 100;
|
|
|
6
7
|
*/
|
|
7
8
|
const MAX_ENVELOPE_BYTES = 60_000;
|
|
8
9
|
const MAX_QUEUED_ENVELOPES = 20;
|
|
10
|
+
/**
|
|
11
|
+
* The most `opted_out` envelopes the queue keeps. The cap of 20 never drops one, so without this limit opt-outs that
|
|
12
|
+
* never went could fill the queue, and the cap would then drop every new envelope.
|
|
13
|
+
*/
|
|
14
|
+
const MAX_QUEUED_OPT_OUTS = 2;
|
|
15
|
+
/** Returns a queue in `storage`. The caller holds a lock around each call. */
|
|
9
16
|
export function newQueue({ storage, reportError, }) {
|
|
17
|
+
/**
|
|
18
|
+
* Returns the stored envelopes. A stored queue that is no JSON list is reported once and dropped. An item without a
|
|
19
|
+
* queue id and an envelope with a list of events is skipped, so a value another script wrote never makes a method
|
|
20
|
+
* throw.
|
|
21
|
+
*/
|
|
10
22
|
async function read() {
|
|
11
|
-
const stored = await storage.get(QUEUE_KEY);
|
|
23
|
+
const stored = (await storage.get(QUEUE_KEY)) ?? '[]';
|
|
24
|
+
let queued;
|
|
12
25
|
try {
|
|
13
|
-
|
|
14
|
-
return Array.isArray(queued) ? queued.filter(isQueuedEnvelope) : [];
|
|
26
|
+
queued = JSON.parse(stored);
|
|
15
27
|
}
|
|
16
|
-
catch
|
|
17
|
-
// The
|
|
18
|
-
//
|
|
19
|
-
|
|
28
|
+
catch {
|
|
29
|
+
// The check below reports its own error and drops the parser's error. The parser's message quotes the stored
|
|
30
|
+
// text, which may hold an id or a page.
|
|
31
|
+
}
|
|
32
|
+
if (!Array.isArray(queued)) {
|
|
33
|
+
reportError(new Error('artel: the stored queue is not a JSON list, so it was dropped'));
|
|
34
|
+
await write([]);
|
|
20
35
|
return [];
|
|
21
36
|
}
|
|
37
|
+
return queued.filter(isQueuedEnvelope);
|
|
22
38
|
}
|
|
23
39
|
async function write(items) {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
40
|
+
await storage.set(QUEUE_KEY, JSON.stringify(items));
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Keeps the newest two `opted_out` envelopes, and then the newest other envelopes while the queue holds at most 20,
|
|
44
|
+
* and reports what it drops. Returns the kept envelopes, and the other dropped ones that no request carried, since an
|
|
45
|
+
* `opted_out` carries no marks.
|
|
46
|
+
*/
|
|
47
|
+
function withinCaps(items) {
|
|
48
|
+
const optOuts = items.filter((item) => item.isOptOut === true);
|
|
49
|
+
const others = items.filter((item) => item.isOptOut !== true);
|
|
50
|
+
const droppedOptOuts = optOuts.slice(0, Math.max(0, optOuts.length - MAX_QUEUED_OPT_OUTS));
|
|
51
|
+
const keptOptOuts = optOuts.length - droppedOptOuts.length;
|
|
52
|
+
const dropped = others.slice(0, Math.max(0, others.length - Math.max(0, MAX_QUEUED_ENVELOPES - keptOptOuts)));
|
|
53
|
+
if (droppedOptOuts.length > 0) {
|
|
54
|
+
reportError(new Error(`artel: the queue holds at most ${MAX_QUEUED_OPT_OUTS} opted_out envelopes, so the oldest ${droppedOptOuts.length} were dropped`));
|
|
27
55
|
}
|
|
28
|
-
|
|
56
|
+
if (dropped.length > 0) {
|
|
57
|
+
reportError(new Error(`artel: the queue holds at most ${MAX_QUEUED_ENVELOPES} envelopes, so the oldest ${dropped.length} were dropped`));
|
|
58
|
+
}
|
|
59
|
+
const gone = new Set([...droppedOptOuts, ...dropped]);
|
|
60
|
+
return { kept: items.filter((item) => !gone.has(item)), dropped: unsent(dropped) };
|
|
29
61
|
}
|
|
30
62
|
async function update(change) {
|
|
31
63
|
await write(change(await read()));
|
|
32
64
|
}
|
|
65
|
+
/** Drops the envelopes `isDropped` picks and resolves to them. Writes nothing when it picks none. */
|
|
66
|
+
async function removeWhere(isDropped) {
|
|
67
|
+
const items = await read();
|
|
68
|
+
const dropped = items.filter(isDropped);
|
|
69
|
+
if (dropped.length > 0) {
|
|
70
|
+
await write(items.filter((item) => !isDropped(item)));
|
|
71
|
+
}
|
|
72
|
+
return dropped;
|
|
73
|
+
}
|
|
33
74
|
return {
|
|
34
|
-
add: async (fields, event) => {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
75
|
+
add: async (fields, event, { awaitsId = false } = {}) => {
|
|
76
|
+
const isOptOut = event.name === LifecycleEvent.OptedOut;
|
|
77
|
+
const newItem = () => ({
|
|
78
|
+
qid: newRandomId(),
|
|
79
|
+
...(awaitsId && { awaitsId: true }),
|
|
80
|
+
...(isOptOut && { isOptOut: true }),
|
|
81
|
+
envelope: { ...fields, events: [event] },
|
|
82
|
+
});
|
|
39
83
|
const items = await read();
|
|
40
84
|
const last = items.at(-1);
|
|
41
85
|
const isOpen = last !== undefined &&
|
|
86
|
+
!isOptOut &&
|
|
87
|
+
last.isOptOut !== true &&
|
|
42
88
|
last.body === undefined &&
|
|
89
|
+
(last.awaitsId === true) === awaitsId &&
|
|
43
90
|
sameFields(last.envelope, fields) &&
|
|
44
91
|
last.envelope.events.length < MAX_ENVELOPE_EVENTS &&
|
|
45
92
|
fits(last.envelope, event);
|
|
@@ -47,10 +94,11 @@ export function newQueue({ storage, reportError, }) {
|
|
|
47
94
|
last.envelope.events.push(event);
|
|
48
95
|
}
|
|
49
96
|
else {
|
|
50
|
-
items.push(
|
|
97
|
+
items.push(newItem());
|
|
51
98
|
}
|
|
52
|
-
|
|
53
|
-
|
|
99
|
+
const { kept, dropped } = withinCaps(items);
|
|
100
|
+
await write(kept);
|
|
101
|
+
return { isFull: kept.at(-1)?.envelope.events.length === MAX_ENVELOPE_EVENTS, dropped };
|
|
54
102
|
},
|
|
55
103
|
lease: async (terms) => {
|
|
56
104
|
const items = await read();
|
|
@@ -64,25 +112,31 @@ export function newQueue({ storage, reportError, }) {
|
|
|
64
112
|
}
|
|
65
113
|
return free;
|
|
66
114
|
},
|
|
67
|
-
seal: async (qid, terms) => {
|
|
115
|
+
seal: async (qid, terms, identity) => {
|
|
68
116
|
const items = await read();
|
|
69
117
|
const item = items.find((candidate) => candidate.qid === qid);
|
|
70
|
-
if (item === undefined || !isFree(item, terms)) {
|
|
118
|
+
if (item === undefined || !isFree(item, terms) || (item.awaitsId === true && identity === undefined)) {
|
|
71
119
|
return undefined;
|
|
72
120
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
121
|
+
if (item.awaitsId === true && identity !== undefined) {
|
|
122
|
+
// The browser, the session and the id go after the other fields and the events. The body stored at this seal
|
|
123
|
+
// keeps that order on every attempt.
|
|
124
|
+
const { session, ...fields } = item.envelope;
|
|
125
|
+
item.envelope = {
|
|
126
|
+
...fields,
|
|
127
|
+
...(identity.browser !== undefined && { browser: identity.browser }),
|
|
128
|
+
session,
|
|
129
|
+
id: identity.id,
|
|
130
|
+
};
|
|
131
|
+
delete item.awaitsId;
|
|
80
132
|
}
|
|
133
|
+
const isRepeat = item.body !== undefined;
|
|
134
|
+
const body = item.body ?? bodyOf(item);
|
|
81
135
|
item.body = body;
|
|
82
136
|
item.leasedBy = terms.holder;
|
|
83
137
|
item.leasedUntil = terms.until;
|
|
84
138
|
await write(items);
|
|
85
|
-
return { envelope: item.envelope, body };
|
|
139
|
+
return { envelope: item.envelope, body, isRepeat };
|
|
86
140
|
},
|
|
87
141
|
remove: (qid) => update((items) => items.filter((item) => item.qid !== qid)),
|
|
88
142
|
release: (holder, qids) => update((items) => items.map((item) => {
|
|
@@ -92,18 +146,27 @@ export function newQueue({ storage, reportError, }) {
|
|
|
92
146
|
const { leasedBy: _holder, leasedUntil: _until, ...released } = item;
|
|
93
147
|
return released;
|
|
94
148
|
})),
|
|
95
|
-
removeId: (id) =>
|
|
96
|
-
|
|
149
|
+
removeId: (id) => removeWhere((item) => item.envelope.id === id),
|
|
150
|
+
removeIdentified: async () => unsent(await removeWhere((item) => item.envelope.id !== undefined || item.awaitsId === true)),
|
|
151
|
+
removeAllButOptOuts: async () => unsent(await removeWhere((item) => item.isOptOut !== true)),
|
|
97
152
|
};
|
|
98
153
|
}
|
|
99
|
-
|
|
100
|
-
|
|
154
|
+
/** Returns the envelopes no seal stored a body for, which no request carried to the intake. */
|
|
155
|
+
function unsent(items) {
|
|
156
|
+
return items.filter((item) => item.body === undefined);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Tells whether `holder` may lease or seal the envelope. A lease that ends later than a new one would counts as ended:
|
|
160
|
+
* the clock was set back, and the lease would otherwise hold the envelope for as long.
|
|
161
|
+
*/
|
|
162
|
+
function isFree(item, { holder, now, until }) {
|
|
163
|
+
const { leasedUntil } = item;
|
|
164
|
+
return leasedUntil === undefined || item.leasedBy === holder || leasedUntil <= now || leasedUntil > until;
|
|
101
165
|
}
|
|
102
166
|
function sameFields(envelope, fields) {
|
|
103
167
|
const { events: _, ...envelopeFields } = envelope;
|
|
104
168
|
return JSON.stringify(envelopeFields) === JSON.stringify(fields);
|
|
105
169
|
}
|
|
106
|
-
/** Returns the request body of an envelope. Each call gives the same bytes, since a sealed envelope does not change. */
|
|
107
170
|
function bodyOf({ qid, envelope }) {
|
|
108
171
|
return JSON.stringify({ ...envelope, batch: qid });
|
|
109
172
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { AnalyticsState, Mode } from './collectorTypes.js';
|
|
2
|
+
import { Platform, type Envelope } from './envelope.js';
|
|
3
|
+
export interface Build {
|
|
4
|
+
platform: Platform;
|
|
5
|
+
version: string;
|
|
6
|
+
}
|
|
7
|
+
/** The fields that name the product build, as an envelope and the uninstall page carry them. */
|
|
8
|
+
export type ProductFields = Pick<Envelope, 'platform' | 'version' | 'browser_language' | 'ui_language'>;
|
|
9
|
+
/** Everything the collector shapes by the user's state. */
|
|
10
|
+
export interface StateFields {
|
|
11
|
+
/** Whether the state records the user's events. Only `opted_out` records none. */
|
|
12
|
+
recordsEvents: boolean;
|
|
13
|
+
/** The build fields, with each language cut to its primary subtag unless the envelope names the user. */
|
|
14
|
+
product: ProductFields;
|
|
15
|
+
/** Whether the install ages go exact, rather than as the lowest value of their bucket. */
|
|
16
|
+
isAgeExact: boolean;
|
|
17
|
+
/** Whether an envelope may carry the id `getId` gives and the browser. */
|
|
18
|
+
mayName: boolean;
|
|
19
|
+
/** Whether an event may carry its page and referrer. The intake keeps them only from a site channel. */
|
|
20
|
+
mayCarryPage: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** Tells whether a channel of `mode` takes `state`. An anonymous channel never takes `identified`. */
|
|
23
|
+
export declare function channelTakes(mode: Mode, state: unknown): state is AnalyticsState;
|
|
24
|
+
/** Returns whether events of this build may carry a page, which the intake keeps only from a site channel. */
|
|
25
|
+
export declare function carriesPage(build: Pick<Build, 'platform'>): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Returns what the collector sends in `state` for this build and these languages. Only the identified state carries the
|
|
28
|
+
* full languages and the exact ages: with the platform and version they can single out a user, so they go only with the
|
|
29
|
+
* consent the id needs.
|
|
30
|
+
*/
|
|
31
|
+
export declare function fieldsForState({ state, build, browserLanguage, uiLanguage, }: {
|
|
32
|
+
state: AnalyticsState;
|
|
33
|
+
build: Build;
|
|
34
|
+
browserLanguage: string | undefined;
|
|
35
|
+
uiLanguage: string | undefined;
|
|
36
|
+
}): StateFields;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { AnalyticsState, Mode } from './collectorTypes.js';
|
|
2
|
+
import { Platform } from './envelope.js';
|
|
3
|
+
import { primaryLanguage } from './fields.js';
|
|
4
|
+
/** Tells whether a channel of `mode` takes `state`. An anonymous channel never takes `identified`. */
|
|
5
|
+
export function channelTakes(mode, state) {
|
|
6
|
+
return (Object.values(AnalyticsState).includes(state) &&
|
|
7
|
+
(state !== AnalyticsState.Identified || mode === Mode.Identified));
|
|
8
|
+
}
|
|
9
|
+
/** Returns whether events of this build may carry a page, which the intake keeps only from a site channel. */
|
|
10
|
+
export function carriesPage(build) {
|
|
11
|
+
return build.platform === Platform.Web;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Returns what the collector sends in `state` for this build and these languages. Only the identified state carries the
|
|
15
|
+
* full languages and the exact ages: with the platform and version they can single out a user, so they go only with the
|
|
16
|
+
* consent the id needs.
|
|
17
|
+
*/
|
|
18
|
+
export function fieldsForState({ state, build, browserLanguage, uiLanguage, }) {
|
|
19
|
+
const isIdentified = state === AnalyticsState.Identified;
|
|
20
|
+
const shape = (tag) => tag === undefined || isIdentified ? tag : primaryLanguage(tag);
|
|
21
|
+
const shapedBrowserLanguage = shape(browserLanguage);
|
|
22
|
+
const shapedUiLanguage = shape(uiLanguage);
|
|
23
|
+
const recordsEvents = state !== AnalyticsState.OptedOut;
|
|
24
|
+
return {
|
|
25
|
+
recordsEvents,
|
|
26
|
+
product: {
|
|
27
|
+
platform: build.platform,
|
|
28
|
+
version: build.version,
|
|
29
|
+
...(shapedBrowserLanguage !== undefined && { browser_language: shapedBrowserLanguage }),
|
|
30
|
+
...(shapedUiLanguage !== undefined && { ui_language: shapedUiLanguage }),
|
|
31
|
+
},
|
|
32
|
+
isAgeExact: isIdentified,
|
|
33
|
+
mayName: isIdentified,
|
|
34
|
+
mayCarryPage: recordsEvents && carriesPage(build),
|
|
35
|
+
};
|
|
36
|
+
}
|