@kennra/app-sdk 0.1.0 → 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 +2 -0
- package/dist/addresses.d.ts +12 -0
- package/dist/addresses.js +105 -0
- package/dist/admin-links.d.ts +17 -0
- package/dist/admin-links.js +22 -0
- package/dist/app.d.ts +1 -1
- package/dist/app.js +1 -1
- package/dist/capture-backfill.d.ts +95 -0
- package/dist/capture-backfill.js +198 -0
- package/dist/capture.d.ts +110 -0
- package/dist/capture.js +321 -0
- package/dist/client.d.ts +14 -3
- package/dist/client.js +41 -4
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/manifest.d.ts +127 -4
- package/dist/manifest.js +152 -11
- package/dist/protocol.d.ts +334 -24
- package/dist/signature.d.ts +8 -0
- package/package.json +17 -1
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# @kennra/app-sdk
|
|
2
2
|
|
|
3
|
+
[](https://www.npmjs.com/package/@kennra/app-sdk)
|
|
4
|
+
|
|
3
5
|
Build apps for [Kennra](https://kennra.com), the headless customer memory. An app connects a
|
|
4
6
|
source system to Kennra through the public API: it answers live lookups, polls on a schedule,
|
|
5
7
|
reacts to webhooks and writes facts with stable idempotency keys.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Addresses that are not a person (decision 21 November 2026): automated senders and role
|
|
3
|
+
* addresses (shared mailboxes). Pure rules, shared by the core's suggested contacts (docs/15 §9.3)
|
|
4
|
+
* and by apps that add people from another system (a sending tool's subscribers, docs/15 §9.13),
|
|
5
|
+
* so neither invents a person called "Info" or "Noreply".
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Why an address is not a person: `automated` (no-reply, bounces, newsletters …) or `role_address`
|
|
9
|
+
* (info@, post@, support@ …), or null for an address that may be a person. The local part is read
|
|
10
|
+
* before any `+tag`, case-insensitive, with `-`, `_` and `.` ignored.
|
|
11
|
+
*/
|
|
12
|
+
export declare function sharedMailboxReason(email: string): 'automated' | 'role_address' | null;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Addresses that are not a person (decision 21 November 2026): automated senders and role
|
|
3
|
+
* addresses (shared mailboxes). Pure rules, shared by the core's suggested contacts (docs/15 §9.3)
|
|
4
|
+
* and by apps that add people from another system (a sending tool's subscribers, docs/15 §9.13),
|
|
5
|
+
* so neither invents a person called "Info" or "Noreply".
|
|
6
|
+
*/
|
|
7
|
+
/** Automated senders: matched anywhere in the local part (`jira-noreply`, `bounces+123`). */
|
|
8
|
+
const AUTOMATED = [
|
|
9
|
+
'noreply',
|
|
10
|
+
'donotreply',
|
|
11
|
+
'dontreply',
|
|
12
|
+
'mailerdaemon',
|
|
13
|
+
'postmaster',
|
|
14
|
+
'bounce',
|
|
15
|
+
'notification',
|
|
16
|
+
'notifications',
|
|
17
|
+
'notify',
|
|
18
|
+
'newsletter',
|
|
19
|
+
'unsubscribe',
|
|
20
|
+
'autoreply',
|
|
21
|
+
'autoconfirm',
|
|
22
|
+
'daemon',
|
|
23
|
+
];
|
|
24
|
+
/** Role addresses: the whole local part (before a `+tag`) is one of these. */
|
|
25
|
+
const ROLES = new Set([
|
|
26
|
+
'abuse',
|
|
27
|
+
'accounting',
|
|
28
|
+
'accounts',
|
|
29
|
+
'admin',
|
|
30
|
+
'administrator',
|
|
31
|
+
'alert',
|
|
32
|
+
'alerts',
|
|
33
|
+
'billing',
|
|
34
|
+
'booking',
|
|
35
|
+
'bestilling',
|
|
36
|
+
'careers',
|
|
37
|
+
'contact',
|
|
38
|
+
'customerservice',
|
|
39
|
+
'dpo',
|
|
40
|
+
'faktura',
|
|
41
|
+
'firmapost',
|
|
42
|
+
'hallo',
|
|
43
|
+
'hei',
|
|
44
|
+
'hello',
|
|
45
|
+
'help',
|
|
46
|
+
'helpdesk',
|
|
47
|
+
'hostmaster',
|
|
48
|
+
'hr',
|
|
49
|
+
'info',
|
|
50
|
+
'invoice',
|
|
51
|
+
'invoices',
|
|
52
|
+
'jobb',
|
|
53
|
+
'jobs',
|
|
54
|
+
'kontakt',
|
|
55
|
+
'kontor',
|
|
56
|
+
'kundesenter',
|
|
57
|
+
'kundeservice',
|
|
58
|
+
'legal',
|
|
59
|
+
'mailer',
|
|
60
|
+
'marketing',
|
|
61
|
+
'mottak',
|
|
62
|
+
'news',
|
|
63
|
+
'office',
|
|
64
|
+
'order',
|
|
65
|
+
'orders',
|
|
66
|
+
'ordre',
|
|
67
|
+
'personvern',
|
|
68
|
+
'post',
|
|
69
|
+
'postmottak',
|
|
70
|
+
'presse',
|
|
71
|
+
'press',
|
|
72
|
+
'privacy',
|
|
73
|
+
'reception',
|
|
74
|
+
'regnskap',
|
|
75
|
+
'rekruttering',
|
|
76
|
+
'resepsjon',
|
|
77
|
+
'root',
|
|
78
|
+
'salg',
|
|
79
|
+
'sales',
|
|
80
|
+
'security',
|
|
81
|
+
'service',
|
|
82
|
+
'support',
|
|
83
|
+
'system',
|
|
84
|
+
'team',
|
|
85
|
+
'webmaster',
|
|
86
|
+
'okonomi',
|
|
87
|
+
'økonomi',
|
|
88
|
+
]);
|
|
89
|
+
/**
|
|
90
|
+
* Why an address is not a person: `automated` (no-reply, bounces, newsletters …) or `role_address`
|
|
91
|
+
* (info@, post@, support@ …), or null for an address that may be a person. The local part is read
|
|
92
|
+
* before any `+tag`, case-insensitive, with `-`, `_` and `.` ignored.
|
|
93
|
+
*/
|
|
94
|
+
export function sharedMailboxReason(email) {
|
|
95
|
+
const at = email.lastIndexOf('@');
|
|
96
|
+
if (at < 1)
|
|
97
|
+
return null;
|
|
98
|
+
const local = email.slice(0, at).toLowerCase().split('+')[0] ?? '';
|
|
99
|
+
const squashed = local.replace(/[-_.]/g, '');
|
|
100
|
+
if (AUTOMATED.some((w) => squashed.includes(w)))
|
|
101
|
+
return 'automated';
|
|
102
|
+
if (ROLES.has(squashed) || ROLES.has(local))
|
|
103
|
+
return 'role_address';
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Links into Kennra's admin carry the workspace (decision 26 November 2026): every page lives
|
|
3
|
+
* under `/@<workspace identifier>/…`, e.g. `https://app.kennra.com/@fjellsport/people/p1`. A link
|
|
4
|
+
* without the prefix opens in whichever workspace the reader used last, so links Kennra and its
|
|
5
|
+
* apps build for people (MCP answers, mail, Slack, CLI) always name the workspace.
|
|
6
|
+
*
|
|
7
|
+
* Pages outside a workspace keep their plain address: `/login`, `/signup`, `/join`, `/welcome`,
|
|
8
|
+
* `/connect` and `/console`.
|
|
9
|
+
*/
|
|
10
|
+
/** The admin base of a workspace: `workspaceAdminBase('https://app.kennra.com/', 'fjellsport')` → `https://app.kennra.com/@fjellsport`. */
|
|
11
|
+
export declare function workspaceAdminBase(adminUrl: string, workspace: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* A page of the admin in a workspace: `workspaceAdminUrl('https://app.kennra.com', 'fjellsport',
|
|
14
|
+
* '/deals?deal=d1')` → `https://app.kennra.com/@fjellsport/deals?deal=d1`. Without a workspace
|
|
15
|
+
* (not known to the caller) the link has no prefix and the admin sends it to the reader's last one.
|
|
16
|
+
*/
|
|
17
|
+
export declare function workspaceAdminUrl(adminUrl: string, workspace: string | null | undefined, path: string): string;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Links into Kennra's admin carry the workspace (decision 26 November 2026): every page lives
|
|
3
|
+
* under `/@<workspace identifier>/…`, e.g. `https://app.kennra.com/@fjellsport/people/p1`. A link
|
|
4
|
+
* without the prefix opens in whichever workspace the reader used last, so links Kennra and its
|
|
5
|
+
* apps build for people (MCP answers, mail, Slack, CLI) always name the workspace.
|
|
6
|
+
*
|
|
7
|
+
* Pages outside a workspace keep their plain address: `/login`, `/signup`, `/join`, `/welcome`,
|
|
8
|
+
* `/connect` and `/console`.
|
|
9
|
+
*/
|
|
10
|
+
/** The admin base of a workspace: `workspaceAdminBase('https://app.kennra.com/', 'fjellsport')` → `https://app.kennra.com/@fjellsport`. */
|
|
11
|
+
export function workspaceAdminBase(adminUrl, workspace) {
|
|
12
|
+
return `${adminUrl.replace(/\/+$/, '')}/@${encodeURIComponent(workspace)}`;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A page of the admin in a workspace: `workspaceAdminUrl('https://app.kennra.com', 'fjellsport',
|
|
16
|
+
* '/deals?deal=d1')` → `https://app.kennra.com/@fjellsport/deals?deal=d1`. Without a workspace
|
|
17
|
+
* (not known to the caller) the link has no prefix and the admin sends it to the reader's last one.
|
|
18
|
+
*/
|
|
19
|
+
export function workspaceAdminUrl(adminUrl, workspace, path) {
|
|
20
|
+
const p = path.startsWith('/') ? path : `/${path}`;
|
|
21
|
+
return workspace ? `${workspaceAdminBase(adminUrl, workspace)}${p}` : `${adminUrl.replace(/\/+$/, '')}${p}`;
|
|
22
|
+
}
|
package/dist/app.d.ts
CHANGED
|
@@ -152,7 +152,7 @@ export declare class KennraApp {
|
|
|
152
152
|
lookup(object: string, handler: LookupHandler): this;
|
|
153
153
|
schedule(id: string, handler: ScheduleHandler): this;
|
|
154
154
|
on(eventType: string, handler: EventHandler): this;
|
|
155
|
-
/**
|
|
155
|
+
/** A member disconnected in Kennra (`userConnections[].disconnectUrl`): revoke and delete the token. */
|
|
156
156
|
onDisconnect(kind: string, handler: DisconnectHandler): this;
|
|
157
157
|
onLifecycle(handler: LifecycleHandler): this;
|
|
158
158
|
/** Erasure of a person (manifest `capabilities.privacy.erasure: receipt`): answer with a receipt. */
|
package/dist/app.js
CHANGED
|
@@ -70,7 +70,7 @@ export class KennraApp {
|
|
|
70
70
|
this.events.set(eventType, handler);
|
|
71
71
|
return this;
|
|
72
72
|
}
|
|
73
|
-
/**
|
|
73
|
+
/** A member disconnected in Kennra (`userConnections[].disconnectUrl`): revoke and delete the token. */
|
|
74
74
|
onDisconnect(kind, handler) {
|
|
75
75
|
if (!this.manifest.capabilities.userConnections.some((c) => c.kind === kind && c.disconnectUrl))
|
|
76
76
|
throw new Error(`The manifest declares no disconnectUrl for ${kind} connections`);
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* History backfill for a new contact, provider-neutral (docs/15 §9.3, decision 21 November 2026).
|
|
3
|
+
*
|
|
4
|
+
* When a person or company becomes known in Kennra, Kennra asks capture apps to look back. For
|
|
5
|
+
* every member who connected their own calendar or mailbox in the installation, the app searches
|
|
6
|
+
* back `historyYears` for the person's addresses or the company's domains and sends each item
|
|
7
|
+
* through its ordinary capture path. This module runs the requests: the cursor per request in the
|
|
8
|
+
* installation state (`backfill:<partyId>`), calendars before mailboxes, a budget per run, a rate
|
|
9
|
+
* limit that pauses only that connection, and the progress reports (`running`, `partial` with what
|
|
10
|
+
* waits, `done`, `failed`). The app supplies the searches: one page of its provider's calendar or
|
|
11
|
+
* mailbox for a task, as capture items.
|
|
12
|
+
*/
|
|
13
|
+
import type { AppContext } from './app.js';
|
|
14
|
+
import type { IngestItem } from './protocol.js';
|
|
15
|
+
export declare const DEFAULT_HISTORY_YEARS = 3;
|
|
16
|
+
export declare const MAX_HISTORY_YEARS = 10;
|
|
17
|
+
/** How many years back the installation looks for a new contact (the `historyYears` setting, clamped). */
|
|
18
|
+
export declare function historyYearsOf(ctx: Pick<AppContext, 'config'>): number;
|
|
19
|
+
/** One search: a member's calendar or mailbox, for one address or domain (or all of a request's). */
|
|
20
|
+
export interface BackfillTask {
|
|
21
|
+
kind: 'calendar' | 'mailbox';
|
|
22
|
+
userId: string;
|
|
23
|
+
connectionKey: string;
|
|
24
|
+
/** The address or domain; for a search over all of a request's terms, them joined by commas. */
|
|
25
|
+
term: string;
|
|
26
|
+
/** Every term this task searches, when the search takes them all at once (`perTerm: false`). */
|
|
27
|
+
terms?: string[];
|
|
28
|
+
pageToken?: string;
|
|
29
|
+
done?: boolean;
|
|
30
|
+
error?: string;
|
|
31
|
+
}
|
|
32
|
+
/** The run's budget, spent by the searches: calendar pages and messages read. */
|
|
33
|
+
export interface BackfillBudget {
|
|
34
|
+
messages: number;
|
|
35
|
+
pages: number;
|
|
36
|
+
}
|
|
37
|
+
/** One page of a search, as capture items for the ordinary capture path. */
|
|
38
|
+
export interface BackfillPage {
|
|
39
|
+
items: IngestItem[];
|
|
40
|
+
/** Items looked at on this page. */
|
|
41
|
+
seen: number;
|
|
42
|
+
/** Items left out before they were sent (spam, drafts, notifications, automated mail). */
|
|
43
|
+
skipped?: number;
|
|
44
|
+
/** The next page; none when the search is done. */
|
|
45
|
+
nextPageToken?: string;
|
|
46
|
+
}
|
|
47
|
+
export interface BackfillSearch {
|
|
48
|
+
/** Which budget the search spends: `pages` (calendar) or `messages` (mailbox). */
|
|
49
|
+
budget: keyof BackfillBudget;
|
|
50
|
+
/** One task per address or domain (default), or one per connection with every term. */
|
|
51
|
+
perTerm?: boolean;
|
|
52
|
+
/** Reads one page and spends from `budget`. */
|
|
53
|
+
page(input: {
|
|
54
|
+
task: BackfillTask;
|
|
55
|
+
token: string;
|
|
56
|
+
since: Date;
|
|
57
|
+
now: Date;
|
|
58
|
+
budget: BackfillBudget;
|
|
59
|
+
signal: AbortSignal;
|
|
60
|
+
}): Promise<BackfillPage>;
|
|
61
|
+
}
|
|
62
|
+
export interface CaptureBackfillDeps {
|
|
63
|
+
searches: {
|
|
64
|
+
calendar: BackfillSearch;
|
|
65
|
+
mailbox: BackfillSearch;
|
|
66
|
+
};
|
|
67
|
+
accessToken: (userId: string, connectionKey: string) => Promise<string | null>;
|
|
68
|
+
internalDomains: readonly string[];
|
|
69
|
+
now: () => Date;
|
|
70
|
+
/** The provider refused for now (quota): pause the connection for this run and keep the cursor. */
|
|
71
|
+
rateLimited: (e: unknown) => boolean;
|
|
72
|
+
/** The provider's name in the run's errors ("<provider> asks to slow down"). */
|
|
73
|
+
provider: string;
|
|
74
|
+
/** The run's budget (default 300 messages and 20 calendar pages). */
|
|
75
|
+
limits?: Partial<BackfillBudget>;
|
|
76
|
+
}
|
|
77
|
+
/** Messages read per tick across every request. */
|
|
78
|
+
export declare const BACKFILL_MESSAGES_PER_RUN = 300;
|
|
79
|
+
/** Calendar pages per tick across every request. */
|
|
80
|
+
export declare const BACKFILL_EVENT_PAGES_PER_RUN = 20;
|
|
81
|
+
export interface BackfillRunReport {
|
|
82
|
+
requests: number;
|
|
83
|
+
finished: number;
|
|
84
|
+
meetings: number;
|
|
85
|
+
emails: number;
|
|
86
|
+
seen: number;
|
|
87
|
+
/** Requests where all that is left waits for the provider's rate limit. */
|
|
88
|
+
waiting: number;
|
|
89
|
+
errors: string[];
|
|
90
|
+
}
|
|
91
|
+
export declare const emptyBackfillReport: () => BackfillRunReport;
|
|
92
|
+
/** An address or domain an item is with (an attendee or the organizer). */
|
|
93
|
+
export declare function hasTerm(emails: readonly string[], term: string): boolean;
|
|
94
|
+
/** One tick: the requests Kennra has for this installation, oldest first, within the run's budget. */
|
|
95
|
+
export declare function runCaptureBackfills(ctx: AppContext, deps: CaptureBackfillDeps): Promise<BackfillRunReport>;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
export const DEFAULT_HISTORY_YEARS = 3;
|
|
2
|
+
export const MAX_HISTORY_YEARS = 10;
|
|
3
|
+
/** How many years back the installation looks for a new contact (the `historyYears` setting, clamped). */
|
|
4
|
+
export function historyYearsOf(ctx) {
|
|
5
|
+
const raw = Number(ctx.config['historyYears'] ?? DEFAULT_HISTORY_YEARS);
|
|
6
|
+
if (!Number.isFinite(raw))
|
|
7
|
+
return DEFAULT_HISTORY_YEARS;
|
|
8
|
+
return Math.min(MAX_HISTORY_YEARS, Math.max(1, Math.round(raw)));
|
|
9
|
+
}
|
|
10
|
+
/** Messages read per tick across every request. */
|
|
11
|
+
export const BACKFILL_MESSAGES_PER_RUN = 300;
|
|
12
|
+
/** Calendar pages per tick across every request. */
|
|
13
|
+
export const BACKFILL_EVENT_PAGES_PER_RUN = 20;
|
|
14
|
+
export const emptyBackfillReport = () => ({
|
|
15
|
+
requests: 0,
|
|
16
|
+
finished: 0,
|
|
17
|
+
meetings: 0,
|
|
18
|
+
emails: 0,
|
|
19
|
+
seen: 0,
|
|
20
|
+
waiting: 0,
|
|
21
|
+
errors: [],
|
|
22
|
+
});
|
|
23
|
+
const connOf = (t) => `${t.userId}|${t.connectionKey}`;
|
|
24
|
+
const kindOf = (t) => (t.kind === 'calendar' ? 'meetings' : 'emails');
|
|
25
|
+
const stateKey = (partyId) => `backfill:${partyId}`;
|
|
26
|
+
/** Whether an ingest result means the item is in Kennra now (captured now or before). */
|
|
27
|
+
const kept = (r) => r.ok && r.outcome !== 'skipped' && r.outcome !== 'cancelled';
|
|
28
|
+
/** An address or domain an item is with (an attendee or the organizer). */
|
|
29
|
+
export function hasTerm(emails, term) {
|
|
30
|
+
return emails.some((a) => {
|
|
31
|
+
const x = a.toLowerCase();
|
|
32
|
+
return term.includes('@') ? x === term : x.endsWith(`@${term}`);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/** One tick: the requests Kennra has for this installation, oldest first, within the run's budget. */
|
|
36
|
+
export async function runCaptureBackfills(ctx, deps) {
|
|
37
|
+
const report = emptyBackfillReport();
|
|
38
|
+
let requests;
|
|
39
|
+
try {
|
|
40
|
+
requests = await ctx.kennra.captureBackfills();
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
// An installation on a grant without backfill (or Kennra without it): nothing to do.
|
|
44
|
+
report.errors.push(`backfill: ${e.message}`.slice(0, 300));
|
|
45
|
+
return report;
|
|
46
|
+
}
|
|
47
|
+
if (!requests.length)
|
|
48
|
+
return report;
|
|
49
|
+
const conns = (await ctx.kennra.userConnections()).filter((c) => c.status === 'connected' && (c.kind === 'calendar' || c.kind === 'mailbox'));
|
|
50
|
+
const internal = new Set(deps.internalDomains.map((d) => d.toLowerCase()));
|
|
51
|
+
const budget = {
|
|
52
|
+
messages: deps.limits?.messages ?? BACKFILL_MESSAGES_PER_RUN,
|
|
53
|
+
pages: deps.limits?.pages ?? BACKFILL_EVENT_PAGES_PER_RUN,
|
|
54
|
+
};
|
|
55
|
+
// Connections the provider asked to slow down for, for the rest of this run (across requests).
|
|
56
|
+
const limited = new Set();
|
|
57
|
+
for (const req of requests) {
|
|
58
|
+
// Stopped (the run's deadline, a shutdown): each request's cursor is saved; the next run goes on.
|
|
59
|
+
if ((budget.messages <= 0 && budget.pages <= 0) || ctx.signal.aborted)
|
|
60
|
+
break;
|
|
61
|
+
report.requests++;
|
|
62
|
+
await runRequest(ctx, deps, req, conns, internal, budget, limited, report);
|
|
63
|
+
}
|
|
64
|
+
return report;
|
|
65
|
+
}
|
|
66
|
+
/** Works on one request until it is done, the budget is spent or what is left waits for the provider. */
|
|
67
|
+
async function runRequest(ctx, deps, req, conns, internal, budget, limited, report) {
|
|
68
|
+
const now = deps.now();
|
|
69
|
+
const terms = [
|
|
70
|
+
...new Set((req.partyType === 'person' ? req.emails : req.domains)
|
|
71
|
+
.map((t) => t.trim().toLowerCase())
|
|
72
|
+
// Never the workspace's own domain or its people: those are internal.
|
|
73
|
+
.filter((t) => t && !internal.has(t.includes('@') ? (t.split('@')[1] ?? '') : t))),
|
|
74
|
+
];
|
|
75
|
+
const saved = await ctx.state.get(stateKey(req.partyId));
|
|
76
|
+
let cursor;
|
|
77
|
+
if (saved?.backfillId === req.backfillId)
|
|
78
|
+
cursor = saved;
|
|
79
|
+
else {
|
|
80
|
+
const since = new Date(now.getTime() - historyYearsOf(ctx) * 365.25 * 86_400_000);
|
|
81
|
+
cursor = {
|
|
82
|
+
backfillId: req.backfillId,
|
|
83
|
+
since: since.toISOString(),
|
|
84
|
+
// Each member's own connections only: their own token, captured as theirs.
|
|
85
|
+
tasks: conns.flatMap((c) => {
|
|
86
|
+
const kind = c.kind;
|
|
87
|
+
const base = { kind, userId: c.userId, connectionKey: c.connectionKey };
|
|
88
|
+
if (deps.searches[kind].perTerm === false)
|
|
89
|
+
return terms.length ? [{ ...base, term: terms.join(','), terms }] : [];
|
|
90
|
+
return terms.map((term) => ({ ...base, term }));
|
|
91
|
+
}),
|
|
92
|
+
meetings: 0,
|
|
93
|
+
emails: 0,
|
|
94
|
+
seen: 0,
|
|
95
|
+
skipped: 0,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const since = new Date(cursor.since);
|
|
99
|
+
const progress = async (status, error, waiting = []) => {
|
|
100
|
+
await ctx.kennra
|
|
101
|
+
.reportCaptureBackfill({
|
|
102
|
+
backfillId: req.backfillId,
|
|
103
|
+
status,
|
|
104
|
+
counters: {
|
|
105
|
+
meetings: cursor.meetings,
|
|
106
|
+
emails: cursor.emails,
|
|
107
|
+
seen: cursor.seen,
|
|
108
|
+
skipped: cursor.skipped,
|
|
109
|
+
},
|
|
110
|
+
since: cursor.since,
|
|
111
|
+
...(waiting.length ? { waiting } : {}),
|
|
112
|
+
...(error ? { error: error.slice(0, 500) } : {}),
|
|
113
|
+
})
|
|
114
|
+
.catch((e) => report.errors.push(`backfill report: ${e.message}`.slice(0, 300)));
|
|
115
|
+
};
|
|
116
|
+
const counted = { meetings: cursor.meetings, emails: cursor.emails, seen: cursor.seen };
|
|
117
|
+
const tally = () => {
|
|
118
|
+
report.meetings += cursor.meetings - counted.meetings;
|
|
119
|
+
report.emails += cursor.emails - counted.emails;
|
|
120
|
+
report.seen += cursor.seen - counted.seen;
|
|
121
|
+
Object.assign(counted, { meetings: cursor.meetings, emails: cursor.emails, seen: cursor.seen });
|
|
122
|
+
};
|
|
123
|
+
if (!req.progress)
|
|
124
|
+
await progress('running');
|
|
125
|
+
// Calendars first: meetings show up even when a mailbox waits for the provider's quota.
|
|
126
|
+
const order = [
|
|
127
|
+
...cursor.tasks.filter((t) => t.kind === 'calendar'),
|
|
128
|
+
...cursor.tasks.filter((t) => t.kind !== 'calendar'),
|
|
129
|
+
];
|
|
130
|
+
for (const task of order) {
|
|
131
|
+
if (ctx.signal.aborted)
|
|
132
|
+
break;
|
|
133
|
+
const search = deps.searches[task.kind];
|
|
134
|
+
if (task.done || limited.has(connOf(task)))
|
|
135
|
+
continue;
|
|
136
|
+
if (budget[search.budget] <= 0)
|
|
137
|
+
continue;
|
|
138
|
+
try {
|
|
139
|
+
const token = await deps.accessToken(task.userId, task.connectionKey);
|
|
140
|
+
if (!token)
|
|
141
|
+
throw new Error('no refresh token stored (reconnect)');
|
|
142
|
+
while (budget[search.budget] > 0 && !ctx.signal.aborted) {
|
|
143
|
+
const page = await search.page({ task, token, since, now, budget, signal: ctx.signal });
|
|
144
|
+
cursor.seen += page.seen;
|
|
145
|
+
cursor.skipped += page.skipped ?? 0;
|
|
146
|
+
if (page.items.length)
|
|
147
|
+
for (const r of await ctx.kennra.ingest('live', page.items)) {
|
|
148
|
+
if (kept(r))
|
|
149
|
+
cursor[kindOf(task)]++;
|
|
150
|
+
else
|
|
151
|
+
cursor.skipped++;
|
|
152
|
+
}
|
|
153
|
+
if (page.nextPageToken)
|
|
154
|
+
task.pageToken = page.nextPageToken;
|
|
155
|
+
else {
|
|
156
|
+
delete task.pageToken;
|
|
157
|
+
task.done = true;
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
catch (e) {
|
|
163
|
+
if (deps.rateLimited(e)) {
|
|
164
|
+
// Only this connection waits; the cursor keeps its place for the next run.
|
|
165
|
+
limited.add(connOf(task));
|
|
166
|
+
report.errors.push(`backfill ${task.kind}: ${deps.provider} asks to slow down; going on next run`);
|
|
167
|
+
await ctx.state.put(stateKey(req.partyId), cursor);
|
|
168
|
+
tally();
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
// This connection can't be read (revoked, refused): the others go on.
|
|
172
|
+
task.done = true;
|
|
173
|
+
task.error = String(e.message ?? e).slice(0, 200);
|
|
174
|
+
report.errors.push(`backfill ${task.kind} ${task.userId}: ${task.error}`);
|
|
175
|
+
}
|
|
176
|
+
await ctx.state.put(stateKey(req.partyId), cursor);
|
|
177
|
+
tally();
|
|
178
|
+
await progress('running');
|
|
179
|
+
}
|
|
180
|
+
tally();
|
|
181
|
+
const left = cursor.tasks.filter((t) => !t.done);
|
|
182
|
+
if (!left.length) {
|
|
183
|
+
const failed = cursor.tasks.length > 0 && cursor.tasks.every((t) => t.error);
|
|
184
|
+
await progress(failed ? 'failed' : 'done', failed ? cursor.tasks[0].error : undefined);
|
|
185
|
+
await ctx.state.put(stateKey(req.partyId), null);
|
|
186
|
+
report.finished++;
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
await ctx.state.put(stateKey(req.partyId), cursor);
|
|
190
|
+
const waiting = [...new Set(left.filter((t) => limited.has(connOf(t))).map(kindOf))].sort();
|
|
191
|
+
if (left.every((t) => limited.has(connOf(t)))) {
|
|
192
|
+
// All that is left waits for the provider: say what was found and what waits (no endless spinner).
|
|
193
|
+
report.waiting++;
|
|
194
|
+
await progress('partial', undefined, waiting);
|
|
195
|
+
}
|
|
196
|
+
else if (waiting.length)
|
|
197
|
+
await progress('running', undefined, waiting);
|
|
198
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Building blocks for capture apps that read each member's own calendar and mailbox (docs/15
|
|
3
|
+
* §9.3): a per-member throttle that waits out a provider's rate limit within a run's budget, a
|
|
4
|
+
* bounded pool, and the rules for reading an email that do not depend on the provider (addresses
|
|
5
|
+
* and display names in a header, the new part of a reply, HTML to text, automated mail and
|
|
6
|
+
* internal-only messages). Pure and provider-neutral: each app keeps its provider's API, error
|
|
7
|
+
* classes and wording, and decides which errors are a rate limit.
|
|
8
|
+
*/
|
|
9
|
+
export interface ThrottleOptions {
|
|
10
|
+
/** Quota units per second per member. */
|
|
11
|
+
unitsPerSecond: number;
|
|
12
|
+
/** Units that may be spent at once after a quiet spell. */
|
|
13
|
+
burst: number;
|
|
14
|
+
/** Calls in flight per member. */
|
|
15
|
+
concurrency: number;
|
|
16
|
+
/** The longest a run waits in total for rate limits per member before it stops. */
|
|
17
|
+
maxBackoffMs: number;
|
|
18
|
+
now: () => number;
|
|
19
|
+
sleep: (ms: number) => Promise<void>;
|
|
20
|
+
random: () => number;
|
|
21
|
+
}
|
|
22
|
+
export declare const DEFAULT_THROTTLE: ThrottleOptions;
|
|
23
|
+
/** One member's token bucket and in-flight limit. */
|
|
24
|
+
export declare class UserThrottle {
|
|
25
|
+
private readonly o;
|
|
26
|
+
private tokens;
|
|
27
|
+
private last;
|
|
28
|
+
private active;
|
|
29
|
+
private readonly waiting;
|
|
30
|
+
private pausedUntil;
|
|
31
|
+
constructor(o: ThrottleOptions);
|
|
32
|
+
private refill;
|
|
33
|
+
/** Waits for a free slot and `cost` units. Call `release` when the call is done. */
|
|
34
|
+
acquire(cost: number): Promise<void>;
|
|
35
|
+
release(): void;
|
|
36
|
+
/** The provider said to slow down: no call for this member for `ms`. */
|
|
37
|
+
pause(ms: number): void;
|
|
38
|
+
}
|
|
39
|
+
/** The wait budget for rate limits in one run for one member. */
|
|
40
|
+
export interface BackoffBudget {
|
|
41
|
+
spentMs: number;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Whether an error is the provider's rate limit, and how long it asked to wait (null: no
|
|
45
|
+
* Retry-After). Null for any other error, which is never retried.
|
|
46
|
+
*/
|
|
47
|
+
export type RateLimitOf = (err: unknown) => {
|
|
48
|
+
retryAfterMs: number | null;
|
|
49
|
+
} | null;
|
|
50
|
+
/**
|
|
51
|
+
* Runs one provider call through the member's throttle, and tries again after a rate limit
|
|
52
|
+
* (Retry-After, else exponential backoff with jitter) while the run's budget lasts. When the
|
|
53
|
+
* budget is spent the error goes up, so the run stops with its progress saved.
|
|
54
|
+
*/
|
|
55
|
+
export declare function throttledCall<T>(t: UserThrottle, o: ThrottleOptions, budget: BackoffBudget, cost: number, call: () => Promise<T>, rateLimitOf: RateLimitOf): Promise<T>;
|
|
56
|
+
/** Runs `fn` over `items` with at most `n` at a time; the results keep the items' order. */
|
|
57
|
+
export declare function pool<A, B>(items: readonly A[], n: number, fn: (a: A) => Promise<B>): Promise<B[]>;
|
|
58
|
+
/** A Retry-After header in seconds or as an HTTP date, in milliseconds (null when absent). */
|
|
59
|
+
export declare function retryAfterHeader(header: string | null | undefined, now?: number): number | null;
|
|
60
|
+
/** The addresses in an address header (`"Kari, N." <kari@x.no>, per@x.no`), lower case. */
|
|
61
|
+
export declare function addresses(value: string | undefined): string[];
|
|
62
|
+
/**
|
|
63
|
+
* Display names in an address header, by address (`"Nordmann, Kari" <kari@x.no>` → kari@x.no:
|
|
64
|
+
* Nordmann, Kari). Only names given with an address in angle brackets; bare addresses have none.
|
|
65
|
+
*/
|
|
66
|
+
export declare function displayNames(value: string | undefined): Map<string, string>;
|
|
67
|
+
/** HTML as plain text: no styles or scripts, line breaks kept, entities decoded. */
|
|
68
|
+
export declare const htmlToText: (html: string) => string;
|
|
69
|
+
/**
|
|
70
|
+
* Whether the quoted part starts at `lines[i]`: a `>` line, an attribution line (also when the
|
|
71
|
+
* client wrapped it over two lines), a forwarded or original-message marker, the underline before
|
|
72
|
+
* a quoted header block, or the header block itself (`From:` followed within three lines by `Sent:`,
|
|
73
|
+
* `Date:` or `To:`, or all on one line).
|
|
74
|
+
*/
|
|
75
|
+
export declare function isQuoteStart(lines: readonly string[], i: number): boolean;
|
|
76
|
+
/** The index of the first quoted line, or `lines.length` when nothing is quoted. */
|
|
77
|
+
export declare function quoteStart(lines: readonly string[]): number;
|
|
78
|
+
/**
|
|
79
|
+
* The new part of a reply: the body up to the quoted earlier messages (`isQuoteStart`). Only this
|
|
80
|
+
* is sent to the core for the summary.
|
|
81
|
+
*/
|
|
82
|
+
export declare function newText(body: string): string;
|
|
83
|
+
/**
|
|
84
|
+
* The new part of an HTML reply as text: the HTML is cut before its first quote container, then
|
|
85
|
+
* converted, then cut by the text rules (`newText`) too.
|
|
86
|
+
*/
|
|
87
|
+
export declare function htmlNewText(html: string): string;
|
|
88
|
+
/**
|
|
89
|
+
* The new part of a message that has a text and an HTML body: each is cut by its own rules, and
|
|
90
|
+
* the shorter wins (the cut that found the quote earliest). Either may be empty.
|
|
91
|
+
*/
|
|
92
|
+
export declare function newPart(text: string | null | undefined, html: string | null | undefined): string;
|
|
93
|
+
/**
|
|
94
|
+
* Mailing lists and automated mail, by their headers (`List-Id`, `List-Unsubscribe`,
|
|
95
|
+
* `Precedence: bulk|list|junk`, `Auto-Submitted` other than `no`). `header` reads one header by
|
|
96
|
+
* name, case-insensitively.
|
|
97
|
+
*/
|
|
98
|
+
export declare function isAutomatedMail(header: (name: string) => string | undefined): boolean;
|
|
99
|
+
/** Every participant other than the mailbox's owner is on the workspace's own domains. */
|
|
100
|
+
export declare function isInternalOnly(participants: readonly string[], mailbox: string, internalDomains: readonly string[]): boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Subjects that calendars put on invitations, updates, replies and cancellations, in English and
|
|
103
|
+
* Norwegian (the common calendars' wording and variants). Matched at the start of the subject only:
|
|
104
|
+
* "Re: Invitation: …" is a person replying, and is kept.
|
|
105
|
+
*/
|
|
106
|
+
export declare const CALENDAR_NOTICE_SUBJECTS: readonly RegExp[];
|
|
107
|
+
/** Whether a subject starts like a calendar's notification (`extra`: an app's own wording on top). */
|
|
108
|
+
export declare function isCalendarNoticeSubject(subject: string | undefined, extra?: readonly RegExp[]): boolean;
|
|
109
|
+
/** The workspace's own email domains from a comma-separated setting (`internalDomains`). */
|
|
110
|
+
export declare const domainsOf: (setting: unknown) => string[];
|