@yaks/mail 0.0.0-stage → 0.2.36
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/LICENSE +202 -0
- package/README.md +676 -2
- package/_dist/addr.d.ts +40 -0
- package/_dist/addr.d.ts.map +1 -0
- package/_dist/answers.d.ts +18 -0
- package/_dist/answers.d.ts.map +1 -0
- package/_dist/arrive.d.ts +64 -0
- package/_dist/arrive.d.ts.map +1 -0
- package/_dist/capture.d.ts +22 -0
- package/_dist/capture.d.ts.map +1 -0
- package/_dist/comp.d.ts +27 -0
- package/_dist/comp.d.ts.map +1 -0
- package/_dist/effects.d.ts +9 -0
- package/_dist/effects.d.ts.map +1 -0
- package/_dist/gmail.d.ts +16 -0
- package/_dist/gmail.d.ts.map +1 -0
- package/_dist/graph.d.ts +9 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/inbound.d.ts +105 -0
- package/_dist/inbound.d.ts.map +1 -0
- package/_dist/invite.d.ts +69 -0
- package/_dist/invite.d.ts.map +1 -0
- package/_dist/md.d.ts +34 -0
- package/_dist/md.d.ts.map +1 -0
- package/_dist/mod.d.ts +109 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/options.d.ts +38 -0
- package/_dist/options.d.ts.map +1 -0
- package/_dist/plugin.d.ts +38 -0
- package/_dist/plugin.d.ts.map +1 -0
- package/_dist/pull.d.ts +99 -0
- package/_dist/pull.d.ts.map +1 -0
- package/_dist/receipts.d.ts +8 -0
- package/_dist/receipts.d.ts.map +1 -0
- package/_dist/recipient.d.ts +24 -0
- package/_dist/recipient.d.ts.map +1 -0
- package/_dist/routes.d.ts +19 -0
- package/_dist/routes.d.ts.map +1 -0
- package/_dist/send.d.ts +80 -0
- package/_dist/send.d.ts.map +1 -0
- package/_dist/service.d.ts +14 -0
- package/_dist/service.d.ts.map +1 -0
- package/_dist/stash.d.ts +23 -0
- package/_dist/stash.d.ts.map +1 -0
- package/_dist/tools.d.ts +27 -0
- package/_dist/tools.d.ts.map +1 -0
- package/_dist/transport.d.ts +6 -0
- package/_dist/transport.d.ts.map +1 -0
- package/_dist/vocab.d.ts +7 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/addr.js +92 -0
- package/addr.js.map +1 -0
- package/addr.ts +106 -0
- package/answers.js +71 -0
- package/answers.js.map +1 -0
- package/answers.ts +95 -0
- package/arrive.js +122 -0
- package/arrive.js.map +1 -0
- package/arrive.ts +198 -0
- package/capture.js +21 -0
- package/capture.js.map +1 -0
- package/capture.ts +43 -0
- package/comp.js +76 -0
- package/comp.js.map +1 -0
- package/comp.ts +91 -0
- package/deno.json +1 -0
- package/effects.js +90 -0
- package/effects.js.map +1 -0
- package/effects.ts +90 -0
- package/gmail.js +262 -0
- package/gmail.js.map +1 -0
- package/gmail.ts +314 -0
- package/graph.js +26 -0
- package/graph.js.map +1 -0
- package/graph.ts +30 -0
- package/inbound.js +206 -0
- package/inbound.js.map +1 -0
- package/inbound.ts +238 -0
- package/invite.js +102 -0
- package/invite.js.map +1 -0
- package/invite.ts +143 -0
- package/md.js +188 -0
- package/md.js.map +1 -0
- package/md.ts +245 -0
- package/mod.js +109 -0
- package/mod.js.map +1 -0
- package/mod.ts +111 -0
- package/options.js +24 -0
- package/options.js.map +1 -0
- package/options.ts +83 -0
- package/package.json +66 -4
- package/plugin.js +97 -0
- package/plugin.js.map +1 -0
- package/plugin.ts +88 -0
- package/pull.js +344 -0
- package/pull.js.map +1 -0
- package/pull.ts +443 -0
- package/readings.js +24 -0
- package/readings.js.map +1 -0
- package/readings.ts +34 -0
- package/receipts.js +45 -0
- package/receipts.js.map +1 -0
- package/receipts.ts +45 -0
- package/recipient.js +92 -0
- package/recipient.js.map +1 -0
- package/recipient.ts +89 -0
- package/routes.js +103 -0
- package/routes.js.map +1 -0
- package/routes.ts +125 -0
- package/send.js +284 -0
- package/send.js.map +1 -0
- package/send.ts +325 -0
- package/service.js +64 -0
- package/service.js.map +1 -0
- package/service.ts +75 -0
- package/stash.js +29 -0
- package/stash.js.map +1 -0
- package/stash.ts +49 -0
- package/tools.js +343 -0
- package/tools.js.map +1 -0
- package/tools.ts +416 -0
- package/transport.js +23 -0
- package/transport.js.map +1 -0
- package/transport.ts +24 -0
- package/vocab.js +14 -0
- package/vocab.js.map +1 -0
- package/vocab.json +415 -0
- package/vocab.ts +16 -0
- package/work.js +121 -0
- package/work.js.map +1 -0
- package/work.ts +134 -0
package/pull.ts
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
// The other way in: pulling what arrived from an edge that cannot reach the
|
|
2
|
+
// graph.
|
|
3
|
+
//
|
|
4
|
+
// ./routes.ts is for an edge that can post a letter to the graph. A graph
|
|
5
|
+
// behind a perimeter cannot be posted to, so its edge keeps what arrived and
|
|
6
|
+
// the graph asks for it. The edge holds two trays: the letters that came to
|
|
7
|
+
// your domain, and the requests posted to its hook paths
|
|
8
|
+
// ({@link https://jsr.io/@yaks/hook | @yaks/hook}). A pull takes what nobody
|
|
9
|
+
// has taken, records each, and tells the edge which ids are done, so its trays
|
|
10
|
+
// drain.
|
|
11
|
+
//
|
|
12
|
+
// GET /messages?unnotified=1&.dir=in&limit=100 letters nobody has taken
|
|
13
|
+
// POST /messages/notified {ids} these are taken
|
|
14
|
+
// GET /requests?unprocessed=1&limit=100 requests (404: no tray)
|
|
15
|
+
// POST /requests/processed {ids} these are taken
|
|
16
|
+
//
|
|
17
|
+
// Taking is first come, first served at the edge: whichever graph acknowledges
|
|
18
|
+
// a letter has it, and no other graph ever sees it. So naming a pull in a
|
|
19
|
+
// config is the whole opt-in, and two graphs must never name the same edge — a
|
|
20
|
+
// copy of a config that pulls takes the mail from the graph it was copied
|
|
21
|
+
// from.
|
|
22
|
+
//
|
|
23
|
+
// Recording comes before acknowledging, and every record is idempotent — a
|
|
24
|
+
// letter by its Message-ID (./arrive.ts), a request by the id derived from it
|
|
25
|
+
// (@yaks/hook `hookEid`) — so a crash between the two is harmless: the next
|
|
26
|
+
// pull gets the same items back, records nothing new, and acknowledges them.
|
|
27
|
+
// An item that cannot be recorded is left unacknowledged and said, so it is
|
|
28
|
+
// tried again rather than lost.
|
|
29
|
+
//
|
|
30
|
+
// An edge that does not answer is tried again on the next pass, which takes
|
|
31
|
+
// everything a blip left behind. Transient failures are logged while retrying;
|
|
32
|
+
// a delayed letter reports the outage that held it up when the edge recovers.
|
|
33
|
+
|
|
34
|
+
import { answered, failing, type Outage } from '@yaks/effects/outage'
|
|
35
|
+
import type { Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
|
|
36
|
+
import { hooked, type Request } from '@yaks/hook'
|
|
37
|
+
import { type Arrivals, arrived, routed } from './arrive.js'
|
|
38
|
+
import type { Arrival, Received } from './inbound.ts'
|
|
39
|
+
import type { Pull } from './options.ts'
|
|
40
|
+
|
|
41
|
+
/** Where a failure is told: the host's telemetry, else the console. */
|
|
42
|
+
export type Report = (
|
|
43
|
+
error: unknown,
|
|
44
|
+
context?: { tags?: Record<string, string> },
|
|
45
|
+
) => unknown
|
|
46
|
+
|
|
47
|
+
/** How long a letter may wait at the edge before taking it is itself a
|
|
48
|
+
* failure: a pull runs every few seconds, so a letter this old, which a pass
|
|
49
|
+
* that began after it arrived did not take, was held up at the edge. */
|
|
50
|
+
export let LATE = 60_000
|
|
51
|
+
|
|
52
|
+
/** A letter as the edge holds it: the envelope and what it parsed out. */
|
|
53
|
+
export type EdgeMessage = {
|
|
54
|
+
/** the edge's key for it: `msg:<ms>:<Message-ID>` */
|
|
55
|
+
id: string
|
|
56
|
+
/** when it arrived, in milliseconds */
|
|
57
|
+
ts?: number | null
|
|
58
|
+
/** when it arrived, as ISO */
|
|
59
|
+
received_at?: string | null
|
|
60
|
+
/** `in` for an arrival */
|
|
61
|
+
dir?: string | null
|
|
62
|
+
/** the envelope sender */
|
|
63
|
+
from?: string | null
|
|
64
|
+
/** the `From:` header — the author */
|
|
65
|
+
from_header?: string | null
|
|
66
|
+
/** the address it was delivered to */
|
|
67
|
+
to?: string | null
|
|
68
|
+
subject?: string | null
|
|
69
|
+
/** the body as text */
|
|
70
|
+
text?: string | null
|
|
71
|
+
/** whether the edge authenticated the From address: an aligned DMARC or
|
|
72
|
+
* DKIM pass, as the fleet's inbox worker grades it, so it also vouches for
|
|
73
|
+
* the author (`Arrival.vouched`) */
|
|
74
|
+
verified?: boolean | null
|
|
75
|
+
/** the `In-Reply-To:` header */
|
|
76
|
+
in_reply_to?: string | null
|
|
77
|
+
/** the `Reply-To:` header, as written */
|
|
78
|
+
reply_to?: string | null
|
|
79
|
+
/** the headers the edge kept: a JSON object, as text */
|
|
80
|
+
headers?: string | null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A request as the edge holds it, captured as it was received. */
|
|
84
|
+
export type EdgeRequest = {
|
|
85
|
+
id: string
|
|
86
|
+
ts?: number | null
|
|
87
|
+
/** who sent it, as the edge named them */
|
|
88
|
+
source?: string | null
|
|
89
|
+
method?: string | null
|
|
90
|
+
path?: string | null
|
|
91
|
+
/** the headers: a JSON object, as text */
|
|
92
|
+
headers?: string | null
|
|
93
|
+
body?: string | null
|
|
94
|
+
/** 1 where the sender's signature verified, 0 where it did not */
|
|
95
|
+
sig_ok?: number | null
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The edge as a pull uses it — a test hands in fixtures instead. `requests`
|
|
99
|
+
* answers null where the edge has no request tray. */
|
|
100
|
+
export type Edge = {
|
|
101
|
+
messages: () => Promise<EdgeMessage[]>
|
|
102
|
+
notified: (ids: string[]) => Promise<void>
|
|
103
|
+
requests: () => Promise<EdgeRequest[] | null>
|
|
104
|
+
processed: (ids: string[]) => Promise<void>
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** How long one request to the edge may make no answer. */
|
|
108
|
+
export let WAIT = 10_000
|
|
109
|
+
|
|
110
|
+
/** A transport failure another pass can recover from. Parsing, authentication
|
|
111
|
+
* and recording failures are unexpected and still report immediately. */
|
|
112
|
+
export class Unavailable extends Error {}
|
|
113
|
+
|
|
114
|
+
/** The edge's HTTP API, with the bearer token it asks for. */
|
|
115
|
+
export let edge = (
|
|
116
|
+
{ url, token }: Pull,
|
|
117
|
+
go: (url: string, init: RequestInit) => Promise<Response> = fetch,
|
|
118
|
+
stop?: AbortSignal,
|
|
119
|
+
wait = WAIT,
|
|
120
|
+
): Edge => {
|
|
121
|
+
let root = url.replace(/\/+$/, '')
|
|
122
|
+
let address = new URL(root)
|
|
123
|
+
if (!['http:', 'https:'].includes(address.protocol)) {
|
|
124
|
+
throw new Error('mail edge URL must use HTTP or HTTPS')
|
|
125
|
+
}
|
|
126
|
+
// The answer's body, parsed, or null where the edge has no such tray.
|
|
127
|
+
let call = async (method: string, path: string, body?: unknown) => {
|
|
128
|
+
let late = AbortSignal.timeout(wait)
|
|
129
|
+
let signal = stop ? AbortSignal.any([stop, late]) : late
|
|
130
|
+
try {
|
|
131
|
+
let res = await go(`${root}${path}`, {
|
|
132
|
+
method,
|
|
133
|
+
signal,
|
|
134
|
+
headers: new Headers({
|
|
135
|
+
authorization: `Bearer ${token}`,
|
|
136
|
+
...(body ? { 'content-type': 'application/json' } : {}),
|
|
137
|
+
}),
|
|
138
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
139
|
+
}).catch((cause) => {
|
|
140
|
+
throw new Unavailable(`${method} ${path}: connection failed`, { cause })
|
|
141
|
+
})
|
|
142
|
+
if (res.status == 404 && path.startsWith('/requests?')) {
|
|
143
|
+
await res.body?.cancel()
|
|
144
|
+
return undefined
|
|
145
|
+
}
|
|
146
|
+
let raw = await res.text().catch((cause) => {
|
|
147
|
+
throw new Unavailable(`${method} ${path}: response interrupted`, {
|
|
148
|
+
cause,
|
|
149
|
+
})
|
|
150
|
+
})
|
|
151
|
+
if (!res.ok) {
|
|
152
|
+
let ErrorType =
|
|
153
|
+
res.status == 408 || res.status == 429 || res.status >= 500
|
|
154
|
+
? Unavailable
|
|
155
|
+
: Error
|
|
156
|
+
throw new ErrorType(`${method} ${path}: ${res.status} ${raw}`)
|
|
157
|
+
}
|
|
158
|
+
return raw ? JSON.parse(raw) : null
|
|
159
|
+
} catch (error) {
|
|
160
|
+
// A host stopping is not a failed pull, including while the body is
|
|
161
|
+
// arriving. A timeout still throws, so the tray reports it and the
|
|
162
|
+
// service tries again on its next pass.
|
|
163
|
+
if (stop?.aborted) return null
|
|
164
|
+
throw error
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
// The edge binds one SQL variable per id, and its store caps a statement at
|
|
168
|
+
// a hundred, so an acknowledgement goes in bites.
|
|
169
|
+
let ack = async (path: string, ids: string[]) => {
|
|
170
|
+
for (let i = 0; i < ids.length; i += 50) {
|
|
171
|
+
await call('POST', path, { ids: ids.slice(i, i + 50) })
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
let list = async (path: string, optional = false) => {
|
|
175
|
+
let items = await call('GET', path)
|
|
176
|
+
if (stop?.aborted || (items === undefined && optional)) return null
|
|
177
|
+
if (
|
|
178
|
+
!Array.isArray(items) ||
|
|
179
|
+
items.some((item) => !item || typeof item.id != 'string')
|
|
180
|
+
) {
|
|
181
|
+
throw new Error(`GET ${path}: expected items with ids`)
|
|
182
|
+
}
|
|
183
|
+
return items
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
messages: async () =>
|
|
187
|
+
(await list('/messages?unnotified=1&.dir=in&limit=100&sort=ts')) ??
|
|
188
|
+
[],
|
|
189
|
+
notified: (ids) => ack('/messages/notified', ids),
|
|
190
|
+
requests: () => list('/requests?unprocessed=1&limit=100', true),
|
|
191
|
+
processed: (ids) => ack('/requests/processed', ids),
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The Message-ID inside the edge's key for a letter.
|
|
197
|
+
*
|
|
198
|
+
* ```ts
|
|
199
|
+
* import { messageIdOf } from '@yaks/mail'
|
|
200
|
+
* messageIdOf('msg:1789861530206:<a1@x.example>') // 'a1@x.example'
|
|
201
|
+
* messageIdOf('a1@x.example') // 'a1@x.example'
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
export let messageIdOf = (key: string): string =>
|
|
205
|
+
(/^(?:msg|out):\d+:(.+)$/.exec(key)?.[1] ?? key).replace(/[<>]/g, '').trim()
|
|
206
|
+
|
|
207
|
+
let parsed = (raw: string | null | undefined): Record<string, unknown> => {
|
|
208
|
+
try {
|
|
209
|
+
let v = JSON.parse(raw ?? '{}')
|
|
210
|
+
return v && typeof v == 'object' ? v : {}
|
|
211
|
+
} catch {
|
|
212
|
+
return {}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** A letter the edge holds, as the message and arrival ./arrive.ts records:
|
|
217
|
+
* the headers it kept, with the ones it parsed out written back over them. */
|
|
218
|
+
export let received = (m: EdgeMessage): [Received, Arrival] => {
|
|
219
|
+
let heads = new Map(
|
|
220
|
+
Object.entries(parsed(m.headers)).map(([k, v]) => [
|
|
221
|
+
k.toLowerCase(),
|
|
222
|
+
String(v),
|
|
223
|
+
]),
|
|
224
|
+
)
|
|
225
|
+
let said: [string, string | null | undefined][] = [
|
|
226
|
+
['from', m.from_header],
|
|
227
|
+
['subject', m.subject],
|
|
228
|
+
['message-id', messageIdOf(m.id)],
|
|
229
|
+
['in-reply-to', m.in_reply_to],
|
|
230
|
+
['reply-to', m.reply_to],
|
|
231
|
+
]
|
|
232
|
+
for (let [k, v] of said) if (v) heads.set(k, v)
|
|
233
|
+
let at = m.received_at ?? new Date(m.ts ?? Date.now()).toISOString()
|
|
234
|
+
return [
|
|
235
|
+
{
|
|
236
|
+
from: m.from ?? '',
|
|
237
|
+
to: m.to ?? '',
|
|
238
|
+
headers: { get: (name) => heads.get(name.toLowerCase()) ?? null },
|
|
239
|
+
},
|
|
240
|
+
{
|
|
241
|
+
at,
|
|
242
|
+
...(m.text == null ? {} : { text: m.text }),
|
|
243
|
+
...(m.verified == null ? {} : { verified: m.verified }),
|
|
244
|
+
vouched: m.verified === true,
|
|
245
|
+
},
|
|
246
|
+
]
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Whom a request is for: the mailbox its first path segment names at your
|
|
250
|
+
* domain — `/hook/books/…` is whoever has `books@<domain>` — else triage. */
|
|
251
|
+
export let hookTo = async (
|
|
252
|
+
{ graph, domain, triage }: Arrivals,
|
|
253
|
+
path: string | null | undefined,
|
|
254
|
+
): Promise<Eid | undefined> => {
|
|
255
|
+
let name = /^\/hook\/([^/?#]+)/.exec(path ?? '')?.[1]
|
|
256
|
+
let found = name && domain
|
|
257
|
+
? await routed(graph, `${name}@${domain}`, domain)
|
|
258
|
+
: null
|
|
259
|
+
return found ?? triage
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// A request the edge holds, as @yaks/hook records one.
|
|
263
|
+
let request = (r: EdgeRequest): Request => ({
|
|
264
|
+
id: r.id,
|
|
265
|
+
source: r.source || 'unknown',
|
|
266
|
+
...(r.method == null ? {} : { method: r.method }),
|
|
267
|
+
...(r.path == null ? {} : { path: r.path }),
|
|
268
|
+
...(r.headers == null ? {} : { headers: r.headers }),
|
|
269
|
+
...(r.body == null ? {} : { body: r.body }),
|
|
270
|
+
...(r.sig_ok == null ? {} : { verified: !!r.sig_ok }),
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
/** Each tray's outage (@yaks/effects/outage), kept until it answers, with
|
|
274
|
+
* the failure a delayed letter reports as its cause. A caller that retries
|
|
275
|
+
* shares this map across passes. */
|
|
276
|
+
export type Down = Map<string, Outage & { error: unknown }>
|
|
277
|
+
|
|
278
|
+
// What every tray of one pass shares.
|
|
279
|
+
type Pass = {
|
|
280
|
+
report: Report
|
|
281
|
+
log: Report
|
|
282
|
+
now: () => number
|
|
283
|
+
down?: Down | undefined
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// One tray: list it, record each item, acknowledge the ones recorded. Nothing
|
|
287
|
+
// here throws — nobody is waiting on a pull to answer — so a failure is said
|
|
288
|
+
// instead, and an item that failed stays at the edge for the next pull.
|
|
289
|
+
let tray = async <T extends { id: string }>(
|
|
290
|
+
{ report, log, now, down }: Pass,
|
|
291
|
+
name: string,
|
|
292
|
+
list: () => Promise<T[] | null>,
|
|
293
|
+
record: (item: T) => Promise<unknown>,
|
|
294
|
+
ack: (ids: string[]) => Promise<void>,
|
|
295
|
+
): Promise<number> => {
|
|
296
|
+
let fail = (what: string, err: unknown, tags: Record<string, string> = {}) =>
|
|
297
|
+
report(new Error(`@yaks/mail — pull could not ${what}`, { cause: err }), {
|
|
298
|
+
tags: { step: 'mail pull', tray: name, ...tags },
|
|
299
|
+
})
|
|
300
|
+
let began = now()
|
|
301
|
+
let done: string[] = []
|
|
302
|
+
try {
|
|
303
|
+
for (let item of await list() ?? []) {
|
|
304
|
+
try {
|
|
305
|
+
await record(item)
|
|
306
|
+
done.push(item.id)
|
|
307
|
+
} catch (err) {
|
|
308
|
+
fail(`record ${name} ${item.id}`, err)
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (done.length) await ack(done)
|
|
312
|
+
let lasted = answered(down?.get(name), now())
|
|
313
|
+
if (lasted != null) {
|
|
314
|
+
down!.delete(name)
|
|
315
|
+
log(`@yaks/mail — ${name} tray recovered after ${lasted} ms`, {
|
|
316
|
+
tags: { tray: name },
|
|
317
|
+
})
|
|
318
|
+
}
|
|
319
|
+
return done.length
|
|
320
|
+
} catch (err) {
|
|
321
|
+
if (!down || !(err instanceof Unavailable)) fail(`take ${name}s`, err)
|
|
322
|
+
else {
|
|
323
|
+
let { outage, fresh } = failing(down.get(name), began)
|
|
324
|
+
down.set(name, { ...outage, error: err })
|
|
325
|
+
if (fresh) {
|
|
326
|
+
log(
|
|
327
|
+
new Error(
|
|
328
|
+
`@yaks/mail — ${name} tray unavailable; retrying next pass`,
|
|
329
|
+
{
|
|
330
|
+
cause: err,
|
|
331
|
+
},
|
|
332
|
+
),
|
|
333
|
+
{ tags: { step: 'mail pull', tray: name } },
|
|
334
|
+
)
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return 0
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** What one pull took: how many letters and requests it recorded and
|
|
342
|
+
* acknowledged. */
|
|
343
|
+
export type Pulled = { messages: number; requests: number }
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* One pull: take the letters and the requests the edge holds, record them, and
|
|
347
|
+
* acknowledge them. Each tray fails alone, so an edge that cannot list its
|
|
348
|
+
* letters still hands over its requests.
|
|
349
|
+
*
|
|
350
|
+
* Requests are recorded only where the graph declares `hook`, and aimed at
|
|
351
|
+
* whom they are for only where it declares `about`; a graph without `hook`
|
|
352
|
+
* leaves the request tray for one that has it.
|
|
353
|
+
*
|
|
354
|
+
* A caller that pulls again hands in the same `down` each pass. Transient
|
|
355
|
+
* failures are logged and retained as the cause of a delayed letter's report;
|
|
356
|
+
* without another pass, every failure reports at once.
|
|
357
|
+
*
|
|
358
|
+
* It also hands in `since`, when its previous pass began. A letter that
|
|
359
|
+
* arrived after that waited only for this pass, however long the process
|
|
360
|
+
* between them was stopped or frozen, so it is not late at the edge; the
|
|
361
|
+
* process's own stall says why the pass was late.
|
|
362
|
+
*/
|
|
363
|
+
export let pull = async (
|
|
364
|
+
at: Arrivals & {
|
|
365
|
+
graph: Graph
|
|
366
|
+
report?: Report
|
|
367
|
+
log?: Report
|
|
368
|
+
now?: () => number
|
|
369
|
+
down?: Down
|
|
370
|
+
since?: number
|
|
371
|
+
},
|
|
372
|
+
from: Edge,
|
|
373
|
+
): Promise<Pulled> => {
|
|
374
|
+
let {
|
|
375
|
+
graph,
|
|
376
|
+
report = console.error,
|
|
377
|
+
log = console.warn,
|
|
378
|
+
now = Date.now,
|
|
379
|
+
down,
|
|
380
|
+
since = Infinity,
|
|
381
|
+
} = at
|
|
382
|
+
let pass: Pass = { report, log, now, down }
|
|
383
|
+
let receive = arrived(at)
|
|
384
|
+
// Where a late letter's time went, per step, so the report says which.
|
|
385
|
+
let took: Record<string, string> = {}
|
|
386
|
+
let timed = async <T>(
|
|
387
|
+
step: string,
|
|
388
|
+
run: () => T | Promise<T>,
|
|
389
|
+
): Promise<T> => {
|
|
390
|
+
let began = now()
|
|
391
|
+
try {
|
|
392
|
+
return await run()
|
|
393
|
+
} finally {
|
|
394
|
+
took[step] = `${now() - began} ms`
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
let messages = await tray(
|
|
398
|
+
pass,
|
|
399
|
+
'message',
|
|
400
|
+
() => timed('list', from.messages),
|
|
401
|
+
async (m) => {
|
|
402
|
+
// An outbound copy has nothing to record; taking it clears the tray.
|
|
403
|
+
if (m.dir && m.dir != 'in') return
|
|
404
|
+
let bundles = await timed('read', () => receive(...received(m)))
|
|
405
|
+
if (bundles.length) await timed('write', () => graph.apply(bundles))
|
|
406
|
+
let came = m.ts ?? (Date.parse(m.received_at ?? '') || now())
|
|
407
|
+
let waited = now() - came
|
|
408
|
+
if (bundles.length && waited > LATE && came <= since) {
|
|
409
|
+
let outage = down?.get('message')
|
|
410
|
+
report(
|
|
411
|
+
new Error('@yaks/mail — a letter waited too long at the edge', {
|
|
412
|
+
cause: outage?.error,
|
|
413
|
+
}),
|
|
414
|
+
{
|
|
415
|
+
tags: {
|
|
416
|
+
step: 'mail stall',
|
|
417
|
+
letter: messageIdOf(m.id),
|
|
418
|
+
waited: `${waited} ms`,
|
|
419
|
+
...(outage ? { down: `${now() - outage.since} ms` } : {}),
|
|
420
|
+
...took,
|
|
421
|
+
},
|
|
422
|
+
},
|
|
423
|
+
)
|
|
424
|
+
}
|
|
425
|
+
},
|
|
426
|
+
from.notified,
|
|
427
|
+
)
|
|
428
|
+
let requests = graph.vocab.comp('hook')
|
|
429
|
+
? await tray(
|
|
430
|
+
pass,
|
|
431
|
+
'request',
|
|
432
|
+
from.requests,
|
|
433
|
+
async (r) => {
|
|
434
|
+
let about = graph.vocab.comp('about')
|
|
435
|
+
? await hookTo(at, r.path)
|
|
436
|
+
: undefined
|
|
437
|
+
await graph.apply(hooked(request(r), about), { trusted: true })
|
|
438
|
+
},
|
|
439
|
+
from.processed,
|
|
440
|
+
)
|
|
441
|
+
: 0
|
|
442
|
+
return { messages, requests }
|
|
443
|
+
}
|
package/readings.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// What other packages make of a letter that arrived. Mail records a letter: its
|
|
2
|
+
// envelope, its words, whom it is for and which letter it answers. Whether it
|
|
3
|
+
// also starts a conversation, answers a question or comments on a task is
|
|
4
|
+
// another package's to say, and only at the door, where the whole message
|
|
5
|
+
// (its headers included) is still in hand.
|
|
6
|
+
//
|
|
7
|
+
// A package says it through a `./mail` facet, the way an application offers
|
|
8
|
+
// @yaks/web its page through `./web`: `reading(options)` takes that package's
|
|
9
|
+
// own options from the config and returns a {@link Reading}. Both receiving
|
|
10
|
+
// doors, `POST /mail/inbound` (./routes.ts) and the pull (./service.ts), ask
|
|
11
|
+
// the configured packages for theirs, so a config that names none records
|
|
12
|
+
// letters and nothing else.
|
|
13
|
+
import { subpath } from "@yaks/cli/facets";
|
|
14
|
+
import { given, used } from "@yaks/host/config";
|
|
15
|
+
/** Every configured package's reading, in the order the config names them. */ export let readings = async (plugins = [])=>{
|
|
16
|
+
let out = [];
|
|
17
|
+
for (let plug of plugins){
|
|
18
|
+
let facet = await subpath(used(plug), 'mail');
|
|
19
|
+
let read = facet?.reading?.(given(plug));
|
|
20
|
+
if (read) out.push(read);
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
};
|
|
24
|
+
//# sourceMappingURL=readings.js.map
|
package/readings.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"readings.js","sources":["./readings.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,8EAA8E;AAC9E,0EAA0E;AAC1E,0EAA0E;AAC1E,2CAA2C;AAC3C,EAAE;AACF,4EAA4E;AAC5E,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,0EAA0E;AAC1E,4BAA4B;AAE5B,SAAS,OAAO,gCAAqC;AACrD,SAAS,KAAK,EAAa,IAAI,iCAAsC;AAQrE,4EAA4E,GAC5E,OAAO,IAAI,WAAW,OAAO,UAA2B,EAAE;EAGxD,IAAI,MAAiB,EAAE;EACvB,KAAK,IAAI,QAAQ,QAAS;IACxB,IAAI,QAAQ,MAAM,QAAmB,KAAK,OAAO;IACjD,IAAI,OAAO,OAAO,UAAU,MAAM;IAClC,IAAI,MAAM,IAAI,IAAI,CAAC;EACrB;EACA,OAAO;AACT,EAAC"}
|
package/readings.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// What other packages make of a letter that arrived. Mail records a letter: its
|
|
2
|
+
// envelope, its words, whom it is for and which letter it answers. Whether it
|
|
3
|
+
// also starts a conversation, answers a question or comments on a task is
|
|
4
|
+
// another package's to say, and only at the door, where the whole message
|
|
5
|
+
// (its headers included) is still in hand.
|
|
6
|
+
//
|
|
7
|
+
// A package says it through a `./mail` facet, the way an application offers
|
|
8
|
+
// @yaks/web its page through `./web`: `reading(options)` takes that package's
|
|
9
|
+
// own options from the config and returns a {@link Reading}. Both receiving
|
|
10
|
+
// doors, `POST /mail/inbound` (./routes.ts) and the pull (./service.ts), ask
|
|
11
|
+
// the configured packages for theirs, so a config that names none records
|
|
12
|
+
// letters and nothing else.
|
|
13
|
+
|
|
14
|
+
import { subpath } from '@yaks/cli/facets'
|
|
15
|
+
import { given, type Plug, used } from '@yaks/host/config'
|
|
16
|
+
import type { Reading } from './arrive.ts'
|
|
17
|
+
|
|
18
|
+
/** A package's `./mail` facet: how it reads an arrival, given its options. */
|
|
19
|
+
export type MailFacet = {
|
|
20
|
+
reading?: (options: Record<string, unknown>) => Reading | undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Every configured package's reading, in the order the config names them. */
|
|
24
|
+
export let readings = async (plugins: readonly Plug[] = []): Promise<
|
|
25
|
+
Reading[]
|
|
26
|
+
> => {
|
|
27
|
+
let out: Reading[] = []
|
|
28
|
+
for (let plug of plugins) {
|
|
29
|
+
let facet = await subpath<MailFacet>(used(plug), 'mail')
|
|
30
|
+
let read = facet?.reading?.(given(plug))
|
|
31
|
+
if (read) out.push(read)
|
|
32
|
+
}
|
|
33
|
+
return out
|
|
34
|
+
}
|
package/receipts.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// A provider's signed delivery receipt updates the same neutral letter the
|
|
2
|
+
// sender wrote. A missing letter is an error to retry: an Operator may still be
|
|
3
|
+
// committing it when the provider calls back. The provider's plugin owns the
|
|
4
|
+
// route that verifies a receipt (@yaks/resend `./routes`). A deleted letter
|
|
5
|
+
// has nothing left to update: a late receipt acknowledges its tombstone.
|
|
6
|
+
import { dead } from "@yaks/graph/bundle";
|
|
7
|
+
import { token } from "@yaks/graph/sha256";
|
|
8
|
+
import { sendable } from "./addr.js";
|
|
9
|
+
/** The validated envelope values the transport files after handing off
|
|
10
|
+
* an outbound letter. Other fields can carry words from outside. */ export let deliveryField = (row, [comp, prop, ...rest])=>{
|
|
11
|
+
if (!row.delivered || comp != 'mail' || rest.length) return false;
|
|
12
|
+
let mail = row.mail;
|
|
13
|
+
return prop == 'to' && typeof mail?.to == 'string' && sendable(mail.to) || prop == 'message_id' && typeof mail?.message_id == 'string' && /^[\w.-]+@[\w.-]+$/.test(mail.message_id);
|
|
14
|
+
};
|
|
15
|
+
/** Apply a provider-neutral receipt to the same recorded letter. */ export let receipted = async (graph, found)=>{
|
|
16
|
+
let [letter] = await graph.get([
|
|
17
|
+
found.letter
|
|
18
|
+
]);
|
|
19
|
+
if (letter && dead(letter)) return;
|
|
20
|
+
if (!letter?.mail) {
|
|
21
|
+
throw new Error('The delivery receipt awaits its recorded letter');
|
|
22
|
+
}
|
|
23
|
+
let prior = letter.mail.message_id;
|
|
24
|
+
if (prior && prior != found.id) {
|
|
25
|
+
throw new Error('The receipt disagrees with the recorded Message-ID');
|
|
26
|
+
}
|
|
27
|
+
if (!prior) {
|
|
28
|
+
await graph.apply([
|
|
29
|
+
{
|
|
30
|
+
entity: letter.entity,
|
|
31
|
+
mail: {
|
|
32
|
+
message_id: found.id
|
|
33
|
+
},
|
|
34
|
+
$was: {
|
|
35
|
+
entity: {
|
|
36
|
+
eid: token(letter.entity.eid)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
], {
|
|
41
|
+
trusted: true
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
//# sourceMappingURL=receipts.js.map
|
package/receipts.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"receipts.js","sources":["./receipts.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,gFAAgF;AAChF,6EAA6E;AAC7E,4EAA4E;AAC5E,yEAAyE;AAEzE,SAAS,IAAI,kCAAuC;AACpD,SAAS,KAAK,kCAAuC;AACrD,SAAS,QAAQ,oBAAmB;AAEpC;kEACkE,GAClE,OAAO,IAAI,gBAAgB,CACzB,KACA,CAAC,MAAM,MAAM,GAAG,KAAe;EAE/B,IAAI,CAAC,IAAI,SAAS,IAAI,QAAQ,UAAU,KAAK,MAAM,EAAE,OAAO;EAC5D,IAAI,OAAO,IAAI,IAAI;EACnB,OAAO,QAAQ,QAAQ,OAAO,MAAM,MAAM,YAAY,SAAS,KAAK,EAAE,KACpE,QAAQ,gBAAgB,OAAO,MAAM,cAAc,YACjD,oBAAoB,IAAI,CAAC,KAAK,UAAU;AAC9C,EAAC;AAED,kEAAkE,GAClE,OAAO,IAAI,YAAY,OACrB,OACA;EAEA,IAAI,CAAC,OAAO,GAAG,MAAM,MAAM,GAAG,CAAC;IAAC,MAAM,MAAM;GAAC;EAC7C,IAAI,UAAU,KAAK,SAAS;EAC5B,IAAI,CAAC,QAAQ,MAAM;IACjB,MAAM,IAAI,MAAM;EAClB;EACA,IAAI,QAAQ,AAAC,OAAO,IAAI,CAAU,UAAU;EAC5C,IAAI,SAAS,SAAS,MAAM,EAAE,EAAE;IAC9B,MAAM,IAAI,MAAM;EAClB;EACA,IAAI,CAAC,OAAO;IACV,MAAM,MAAM,KAAK,CAAC;MAAC;QACjB,QAAQ,OAAO,MAAM;QACrB,MAAM;UAAE,YAAY,MAAM,EAAE;QAAC;QAC7B,MAAM;UAAE,QAAQ;YAAE,KAAK,MAAM,OAAO,MAAM,CAAC,GAAG;UAAE;QAAE;MACpD;KAAE,EAAE;MAAE,SAAS;IAAK;EACtB;AACF,EAAC"}
|
package/receipts.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// A provider's signed delivery receipt updates the same neutral letter the
|
|
2
|
+
// sender wrote. A missing letter is an error to retry: an Operator may still be
|
|
3
|
+
// committing it when the provider calls back. The provider's plugin owns the
|
|
4
|
+
// route that verifies a receipt (@yaks/resend `./routes`). A deleted letter
|
|
5
|
+
// has nothing left to update: a late receipt acknowledges its tombstone.
|
|
6
|
+
import type { Bundle, Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
|
|
7
|
+
import { dead } from '@yaks/graph/bundle'
|
|
8
|
+
import { token } from '@yaks/graph/sha256'
|
|
9
|
+
import { sendable } from './addr.js'
|
|
10
|
+
|
|
11
|
+
/** The validated envelope values the transport files after handing off
|
|
12
|
+
* an outbound letter. Other fields can carry words from outside. */
|
|
13
|
+
export let deliveryField = (
|
|
14
|
+
row: Bundle,
|
|
15
|
+
[comp, prop, ...rest]: string[],
|
|
16
|
+
): boolean => {
|
|
17
|
+
if (!row.delivered || comp != 'mail' || rest.length) return false
|
|
18
|
+
let mail = row.mail as Comp | undefined
|
|
19
|
+
return prop == 'to' && typeof mail?.to == 'string' && sendable(mail.to) ||
|
|
20
|
+
prop == 'message_id' && typeof mail?.message_id == 'string' &&
|
|
21
|
+
/^[\w.-]+@[\w.-]+$/.test(mail.message_id)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Apply a provider-neutral receipt to the same recorded letter. */
|
|
25
|
+
export let receipted = async (
|
|
26
|
+
graph: Pick<Graph, 'get' | 'apply'>,
|
|
27
|
+
found: { letter: string; id: string },
|
|
28
|
+
): Promise<void> => {
|
|
29
|
+
let [letter] = await graph.get([found.letter])
|
|
30
|
+
if (letter && dead(letter)) return
|
|
31
|
+
if (!letter?.mail) {
|
|
32
|
+
throw new Error('The delivery receipt awaits its recorded letter')
|
|
33
|
+
}
|
|
34
|
+
let prior = (letter.mail as Comp).message_id
|
|
35
|
+
if (prior && prior != found.id) {
|
|
36
|
+
throw new Error('The receipt disagrees with the recorded Message-ID')
|
|
37
|
+
}
|
|
38
|
+
if (!prior) {
|
|
39
|
+
await graph.apply([{
|
|
40
|
+
entity: letter.entity,
|
|
41
|
+
mail: { message_id: found.id },
|
|
42
|
+
$was: { entity: { eid: token(letter.entity.eid) } },
|
|
43
|
+
}], { trusted: true })
|
|
44
|
+
}
|
|
45
|
+
}
|