@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.
Files changed (131) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +676 -2
  3. package/_dist/addr.d.ts +40 -0
  4. package/_dist/addr.d.ts.map +1 -0
  5. package/_dist/answers.d.ts +18 -0
  6. package/_dist/answers.d.ts.map +1 -0
  7. package/_dist/arrive.d.ts +64 -0
  8. package/_dist/arrive.d.ts.map +1 -0
  9. package/_dist/capture.d.ts +22 -0
  10. package/_dist/capture.d.ts.map +1 -0
  11. package/_dist/comp.d.ts +27 -0
  12. package/_dist/comp.d.ts.map +1 -0
  13. package/_dist/effects.d.ts +9 -0
  14. package/_dist/effects.d.ts.map +1 -0
  15. package/_dist/gmail.d.ts +16 -0
  16. package/_dist/gmail.d.ts.map +1 -0
  17. package/_dist/graph.d.ts +9 -0
  18. package/_dist/graph.d.ts.map +1 -0
  19. package/_dist/inbound.d.ts +105 -0
  20. package/_dist/inbound.d.ts.map +1 -0
  21. package/_dist/invite.d.ts +69 -0
  22. package/_dist/invite.d.ts.map +1 -0
  23. package/_dist/md.d.ts +34 -0
  24. package/_dist/md.d.ts.map +1 -0
  25. package/_dist/mod.d.ts +109 -0
  26. package/_dist/mod.d.ts.map +1 -0
  27. package/_dist/options.d.ts +38 -0
  28. package/_dist/options.d.ts.map +1 -0
  29. package/_dist/plugin.d.ts +38 -0
  30. package/_dist/plugin.d.ts.map +1 -0
  31. package/_dist/pull.d.ts +99 -0
  32. package/_dist/pull.d.ts.map +1 -0
  33. package/_dist/receipts.d.ts +8 -0
  34. package/_dist/receipts.d.ts.map +1 -0
  35. package/_dist/recipient.d.ts +24 -0
  36. package/_dist/recipient.d.ts.map +1 -0
  37. package/_dist/routes.d.ts +19 -0
  38. package/_dist/routes.d.ts.map +1 -0
  39. package/_dist/send.d.ts +80 -0
  40. package/_dist/send.d.ts.map +1 -0
  41. package/_dist/service.d.ts +14 -0
  42. package/_dist/service.d.ts.map +1 -0
  43. package/_dist/stash.d.ts +23 -0
  44. package/_dist/stash.d.ts.map +1 -0
  45. package/_dist/tools.d.ts +27 -0
  46. package/_dist/tools.d.ts.map +1 -0
  47. package/_dist/transport.d.ts +6 -0
  48. package/_dist/transport.d.ts.map +1 -0
  49. package/_dist/vocab.d.ts +7 -0
  50. package/_dist/vocab.d.ts.map +1 -0
  51. package/addr.js +92 -0
  52. package/addr.js.map +1 -0
  53. package/addr.ts +106 -0
  54. package/answers.js +71 -0
  55. package/answers.js.map +1 -0
  56. package/answers.ts +95 -0
  57. package/arrive.js +122 -0
  58. package/arrive.js.map +1 -0
  59. package/arrive.ts +198 -0
  60. package/capture.js +21 -0
  61. package/capture.js.map +1 -0
  62. package/capture.ts +43 -0
  63. package/comp.js +76 -0
  64. package/comp.js.map +1 -0
  65. package/comp.ts +91 -0
  66. package/deno.json +1 -0
  67. package/effects.js +90 -0
  68. package/effects.js.map +1 -0
  69. package/effects.ts +90 -0
  70. package/gmail.js +262 -0
  71. package/gmail.js.map +1 -0
  72. package/gmail.ts +314 -0
  73. package/graph.js +26 -0
  74. package/graph.js.map +1 -0
  75. package/graph.ts +30 -0
  76. package/inbound.js +206 -0
  77. package/inbound.js.map +1 -0
  78. package/inbound.ts +238 -0
  79. package/invite.js +102 -0
  80. package/invite.js.map +1 -0
  81. package/invite.ts +143 -0
  82. package/md.js +188 -0
  83. package/md.js.map +1 -0
  84. package/md.ts +245 -0
  85. package/mod.js +109 -0
  86. package/mod.js.map +1 -0
  87. package/mod.ts +111 -0
  88. package/options.js +24 -0
  89. package/options.js.map +1 -0
  90. package/options.ts +83 -0
  91. package/package.json +66 -4
  92. package/plugin.js +97 -0
  93. package/plugin.js.map +1 -0
  94. package/plugin.ts +88 -0
  95. package/pull.js +344 -0
  96. package/pull.js.map +1 -0
  97. package/pull.ts +443 -0
  98. package/readings.js +24 -0
  99. package/readings.js.map +1 -0
  100. package/readings.ts +34 -0
  101. package/receipts.js +45 -0
  102. package/receipts.js.map +1 -0
  103. package/receipts.ts +45 -0
  104. package/recipient.js +92 -0
  105. package/recipient.js.map +1 -0
  106. package/recipient.ts +89 -0
  107. package/routes.js +103 -0
  108. package/routes.js.map +1 -0
  109. package/routes.ts +125 -0
  110. package/send.js +284 -0
  111. package/send.js.map +1 -0
  112. package/send.ts +325 -0
  113. package/service.js +64 -0
  114. package/service.js.map +1 -0
  115. package/service.ts +75 -0
  116. package/stash.js +29 -0
  117. package/stash.js.map +1 -0
  118. package/stash.ts +49 -0
  119. package/tools.js +343 -0
  120. package/tools.js.map +1 -0
  121. package/tools.ts +416 -0
  122. package/transport.js +23 -0
  123. package/transport.js.map +1 -0
  124. package/transport.ts +24 -0
  125. package/vocab.js +14 -0
  126. package/vocab.js.map +1 -0
  127. package/vocab.json +415 -0
  128. package/vocab.ts +16 -0
  129. package/work.js +121 -0
  130. package/work.js.map +1 -0
  131. package/work.ts +134 -0
package/plugin.js ADDED
@@ -0,0 +1,97 @@
1
+ // The package as one graph plugin: the components, the address canonicalizer,
2
+ // and — when you pass it an effect registry — the code behind `mail_post`.
3
+ //
4
+ // The canonicalizer runs in the `normalize` phase, which is the earliest phase
5
+ // there is: before anything is validated or written, so an address reaches
6
+ // storage in one form and only one. That is the difference between "we
7
+ // lowercase addresses somewhere" and "the address book cannot hold two rows
8
+ // for one person" — the rule is applied once on the way in rather than by each
9
+ // caller.
10
+ //
11
+ // Naming your domain is what turns it on. Without one, every address belongs to
12
+ // somebody else's domain and passes through untouched (see ./addr.ts).
13
+ import { canon } from "./addr.js";
14
+ import { EMAIL, MAIL, mailDoc } from "./comp.js";
15
+ import { sending } from "./send.js";
16
+ // The properties that hold an address, and are therefore canonicalized on
17
+ // write.
18
+ let ADDRESSES = [
19
+ [
20
+ EMAIL,
21
+ 'address'
22
+ ],
23
+ [
24
+ MAIL,
25
+ 'from'
26
+ ],
27
+ [
28
+ MAIL,
29
+ 'to'
30
+ ]
31
+ ];
32
+ let clean = (fix)=>(b)=>{
33
+ let out = b;
34
+ for (let [name, prop] of ADDRESSES){
35
+ let comp = out[name];
36
+ if (!comp || comp[prop] == null) continue;
37
+ out = {
38
+ ...out,
39
+ [name]: {
40
+ ...comp,
41
+ [prop]: fix(String(comp[prop]))
42
+ }
43
+ };
44
+ }
45
+ return out;
46
+ };
47
+ /**
48
+ * The mail plugin: the `mail`, `email`, `deliver`, `delivered`, `bounced` and
49
+ * `notified` components, the address canonicalizer, and the sending effect.
50
+ *
51
+ * ```ts
52
+ * import { graph } from '@yaks/graph'
53
+ * import { effects } from '@yaks/effects'
54
+ * import { ram } from '@yaks/ram'
55
+ * import { loadVocab } from '@yaks/vocab'
56
+ * import { docDoc, docs } from '@yaks/doc'
57
+ * import { mailbox, mailDoc, stash } from '@yaks/mail'
58
+ *
59
+ * let vocab = loadVocab([docDoc, mailDoc])
60
+ * let fx = effects(vocab, { write: (b) => g.apply(b, { trusted: true }) })
61
+ * let box = mailbox({ domain: 'books.example', sender: stash(), effects: fx })
62
+ * let g = graph({ storage: ram(vocab), vocab, plugins: [fx, docs(), box] })
63
+ * ```
64
+ *
65
+ * {@link https://jsr.io/@yaks/doc | @yaks/doc} is composed beside this plugin
66
+ * rather than inside it: a letter's subject and body are `doc{title, body}`, and
67
+ * a vocabulary rejects a component declared twice — so `doc` keeps one home and
68
+ * an application that already declares it is not fought over it.
69
+ *
70
+ * Pass `effects` and a `sender` together and outbound letters are sent
71
+ * automatically; pass neither and this is the vocabulary and the canonicalizer,
72
+ * which is all a graph that only receives mail needs.
73
+ */ export let mailbox = ({ domain, effects, sender, now, local, mentions } = {})=>{
74
+ if (effects && sender) {
75
+ effects.handle({
76
+ mail_post: sending({
77
+ sender,
78
+ now,
79
+ local,
80
+ mentions
81
+ })
82
+ });
83
+ }
84
+ let fix = domain ? clean(canon(domain)) : null;
85
+ return {
86
+ name: '@yaks/mail',
87
+ vocab: [
88
+ mailDoc
89
+ ],
90
+ ...fix ? {
91
+ hooks: {
92
+ normalize: (bundles)=>bundles.map(fix)
93
+ }
94
+ } : {}
95
+ };
96
+ };
97
+ //# sourceMappingURL=plugin.js.map
package/plugin.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sources":["./plugin.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,2EAA2E;AAC3E,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,uEAAuE;AACvE,4EAA4E;AAC5E,+EAA+E;AAC/E,UAAU;AACV,EAAE;AACF,gFAAgF;AAChF,uEAAuE;AAIvE,SAAS,KAAK,oBAAmB;AACjC,SAAS,KAAK,EAAE,IAAI,EAAE,OAAO,oBAAmB;AAChD,SAAoB,OAAO,oBAAmB;AAa9C,0EAA0E;AAC1E,SAAS;AACT,IAAI,YAAgC;EAClC;IAAC;IAAO;GAAU;EAClB;IAAC;IAAM;GAAO;EACd;IAAC;IAAM;GAAK;CACb;AAED,IAAI,QAAQ,CAAC,MAA+B,CAAC;IAC3C,IAAI,MAAM;IACV,KAAK,IAAI,CAAC,MAAM,KAAK,IAAI,UAAW;MAClC,IAAI,OAAO,GAAG,CAAC,KAAK;MACpB,IAAI,CAAC,QAAQ,IAAI,CAAC,KAAK,IAAI,MAAM;MACjC,MAAM;QAAE,GAAG,GAAG;QAAE,CAAC,KAAK,EAAE;UAAE,GAAG,IAAI;UAAE,CAAC,KAAK,EAAE,IAAI,OAAO,IAAI,CAAC,KAAK;QAAG;MAAE;IACvE;IACA,OAAO;EACT;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,IAAI,UAAU,CACnB,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,QAAQ,EAAW,GAAG,CAAC,CAAC;EAE/D,IAAI,WAAW,QAAQ;IACrB,QAAQ,MAAM,CAAC;MAAE,WAAW,QAAQ;QAAE;QAAQ;QAAK;QAAO;MAAS;IAAG;EACxE;EACA,IAAI,MAAM,SAAS,MAAM,MAAM,WAAW;EAC1C,OAAO;IACL,MAAM;IACN,OAAO;MAAC;KAAQ;IAChB,GAAI,MAAM;MAAE,OAAO;QAAE,WAAW,CAAC,UAAY,QAAQ,GAAG,CAAC;MAAK;IAAE,IAAI,CAAC,CAAC;EACxE;AACF,EAAC"}
package/plugin.ts ADDED
@@ -0,0 +1,88 @@
1
+ // The package as one graph plugin: the components, the address canonicalizer,
2
+ // and — when you pass it an effect registry — the code behind `mail_post`.
3
+ //
4
+ // The canonicalizer runs in the `normalize` phase, which is the earliest phase
5
+ // there is: before anything is validated or written, so an address reaches
6
+ // storage in one form and only one. That is the difference between "we
7
+ // lowercase addresses somewhere" and "the address book cannot hold two rows
8
+ // for one person" — the rule is applied once on the way in rather than by each
9
+ // caller.
10
+ //
11
+ // Naming your domain is what turns it on. Without one, every address belongs to
12
+ // somebody else's domain and passes through untouched (see ./addr.ts).
13
+
14
+ import type { Bundle, Comp, Plugin } from 'jsr:@yaks/graph@0.2.36'
15
+ import type { Effects } from 'jsr:@yaks/effects@0.2.36'
16
+ import { canon } from './addr.js'
17
+ import { EMAIL, MAIL, mailDoc } from './comp.js'
18
+ import { type Post, sending } from './send.js'
19
+
20
+ /** How the plugin is built. */
21
+ export type Mailbox = {
22
+ /** your own mail domain — the addresses this graph canonicalizes on write */
23
+ domain?: string
24
+ /** handle `mail_post` on this registry, so letters actually go. The
25
+ * registry's vocabulary carries {@link mailDoc}, which declares it, and it
26
+ * needs a write function — `effects(vocab, { write })`, applied trusted —
27
+ * since that is how the outcome is written back onto the letter. */
28
+ effects?: Effects
29
+ } & Partial<Post>
30
+
31
+ // The properties that hold an address, and are therefore canonicalized on
32
+ // write.
33
+ let ADDRESSES: [string, string][] = [
34
+ [EMAIL, 'address'],
35
+ [MAIL, 'from'],
36
+ [MAIL, 'to'],
37
+ ]
38
+
39
+ let clean = (fix: (a: string) => string) => (b: Bundle): Bundle => {
40
+ let out = b
41
+ for (let [name, prop] of ADDRESSES) {
42
+ let comp = out[name] as Comp | null | undefined
43
+ if (!comp || comp[prop] == null) continue
44
+ out = { ...out, [name]: { ...comp, [prop]: fix(String(comp[prop])) } }
45
+ }
46
+ return out
47
+ }
48
+
49
+ /**
50
+ * The mail plugin: the `mail`, `email`, `deliver`, `delivered`, `bounced` and
51
+ * `notified` components, the address canonicalizer, and the sending effect.
52
+ *
53
+ * ```ts
54
+ * import { graph } from '@yaks/graph'
55
+ * import { effects } from '@yaks/effects'
56
+ * import { ram } from '@yaks/ram'
57
+ * import { loadVocab } from '@yaks/vocab'
58
+ * import { docDoc, docs } from '@yaks/doc'
59
+ * import { mailbox, mailDoc, stash } from '@yaks/mail'
60
+ *
61
+ * let vocab = loadVocab([docDoc, mailDoc])
62
+ * let fx = effects(vocab, { write: (b) => g.apply(b, { trusted: true }) })
63
+ * let box = mailbox({ domain: 'books.example', sender: stash(), effects: fx })
64
+ * let g = graph({ storage: ram(vocab), vocab, plugins: [fx, docs(), box] })
65
+ * ```
66
+ *
67
+ * {@link https://jsr.io/@yaks/doc | @yaks/doc} is composed beside this plugin
68
+ * rather than inside it: a letter's subject and body are `doc{title, body}`, and
69
+ * a vocabulary rejects a component declared twice — so `doc` keeps one home and
70
+ * an application that already declares it is not fought over it.
71
+ *
72
+ * Pass `effects` and a `sender` together and outbound letters are sent
73
+ * automatically; pass neither and this is the vocabulary and the canonicalizer,
74
+ * which is all a graph that only receives mail needs.
75
+ */
76
+ export let mailbox = (
77
+ { domain, effects, sender, now, local, mentions }: Mailbox = {},
78
+ ): Plugin => {
79
+ if (effects && sender) {
80
+ effects.handle({ mail_post: sending({ sender, now, local, mentions }) })
81
+ }
82
+ let fix = domain ? clean(canon(domain)) : null
83
+ return {
84
+ name: '@yaks/mail',
85
+ vocab: [mailDoc],
86
+ ...(fix ? { hooks: { normalize: (bundles) => bundles.map(fix) } } : {}),
87
+ }
88
+ }
package/pull.js ADDED
@@ -0,0 +1,344 @@
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
+ import { answered, failing } from "@yaks/effects/outage";
34
+ import { hooked } from "@yaks/hook";
35
+ import { arrived, routed } from "./arrive.js";
36
+ /** How long a letter may wait at the edge before taking it is itself a
37
+ * failure: a pull runs every few seconds, so a letter this old, which a pass
38
+ * that began after it arrived did not take, was held up at the edge. */ export let LATE = 60_000;
39
+ /** How long one request to the edge may make no answer. */ export let WAIT = 10_000;
40
+ /** A transport failure another pass can recover from. Parsing, authentication
41
+ * and recording failures are unexpected and still report immediately. */ export class Unavailable extends Error {
42
+ }
43
+ /** The edge's HTTP API, with the bearer token it asks for. */ export let edge = ({ url, token }, go = fetch, stop, wait = WAIT)=>{
44
+ let root = url.replace(/\/+$/, '');
45
+ let address = new URL(root);
46
+ if (![
47
+ 'http:',
48
+ 'https:'
49
+ ].includes(address.protocol)) {
50
+ throw new Error('mail edge URL must use HTTP or HTTPS');
51
+ }
52
+ // The answer's body, parsed, or null where the edge has no such tray.
53
+ let call = async (method, path, body)=>{
54
+ let late = AbortSignal.timeout(wait);
55
+ let signal = stop ? AbortSignal.any([
56
+ stop,
57
+ late
58
+ ]) : late;
59
+ try {
60
+ let res = await go(`${root}${path}`, {
61
+ method,
62
+ signal,
63
+ headers: new Headers({
64
+ authorization: `Bearer ${token}`,
65
+ ...body ? {
66
+ 'content-type': 'application/json'
67
+ } : {}
68
+ }),
69
+ ...body ? {
70
+ body: JSON.stringify(body)
71
+ } : {}
72
+ }).catch((cause)=>{
73
+ throw new Unavailable(`${method} ${path}: connection failed`, {
74
+ cause
75
+ });
76
+ });
77
+ if (res.status == 404 && path.startsWith('/requests?')) {
78
+ await res.body?.cancel();
79
+ return undefined;
80
+ }
81
+ let raw = await res.text().catch((cause)=>{
82
+ throw new Unavailable(`${method} ${path}: response interrupted`, {
83
+ cause
84
+ });
85
+ });
86
+ if (!res.ok) {
87
+ let ErrorType = res.status == 408 || res.status == 429 || res.status >= 500 ? Unavailable : Error;
88
+ throw new ErrorType(`${method} ${path}: ${res.status} ${raw}`);
89
+ }
90
+ return raw ? JSON.parse(raw) : null;
91
+ } catch (error) {
92
+ // A host stopping is not a failed pull, including while the body is
93
+ // arriving. A timeout still throws, so the tray reports it and the
94
+ // service tries again on its next pass.
95
+ if (stop?.aborted) return null;
96
+ throw error;
97
+ }
98
+ };
99
+ // The edge binds one SQL variable per id, and its store caps a statement at
100
+ // a hundred, so an acknowledgement goes in bites.
101
+ let ack = async (path, ids)=>{
102
+ for(let i = 0; i < ids.length; i += 50){
103
+ await call('POST', path, {
104
+ ids: ids.slice(i, i + 50)
105
+ });
106
+ }
107
+ };
108
+ let list = async (path, optional = false)=>{
109
+ let items = await call('GET', path);
110
+ if (stop?.aborted || items === undefined && optional) return null;
111
+ if (!Array.isArray(items) || items.some((item)=>!item || typeof item.id != 'string')) {
112
+ throw new Error(`GET ${path}: expected items with ids`);
113
+ }
114
+ return items;
115
+ };
116
+ return {
117
+ messages: async ()=>await list('/messages?unnotified=1&.dir=in&limit=100&sort=ts') ?? [],
118
+ notified: (ids)=>ack('/messages/notified', ids),
119
+ requests: ()=>list('/requests?unprocessed=1&limit=100', true),
120
+ processed: (ids)=>ack('/requests/processed', ids)
121
+ };
122
+ };
123
+ /**
124
+ * The Message-ID inside the edge's key for a letter.
125
+ *
126
+ * ```ts
127
+ * import { messageIdOf } from '@yaks/mail'
128
+ * messageIdOf('msg:1789861530206:<a1@x.example>') // 'a1@x.example'
129
+ * messageIdOf('a1@x.example') // 'a1@x.example'
130
+ * ```
131
+ */ export let messageIdOf = (key)=>(/^(?:msg|out):\d+:(.+)$/.exec(key)?.[1] ?? key).replace(/[<>]/g, '').trim();
132
+ let parsed = (raw)=>{
133
+ try {
134
+ let v = JSON.parse(raw ?? '{}');
135
+ return v && typeof v == 'object' ? v : {};
136
+ } catch {
137
+ return {};
138
+ }
139
+ };
140
+ /** A letter the edge holds, as the message and arrival ./arrive.ts records:
141
+ * the headers it kept, with the ones it parsed out written back over them. */ export let received = (m)=>{
142
+ let heads = new Map(Object.entries(parsed(m.headers)).map(([k, v])=>[
143
+ k.toLowerCase(),
144
+ String(v)
145
+ ]));
146
+ let said = [
147
+ [
148
+ 'from',
149
+ m.from_header
150
+ ],
151
+ [
152
+ 'subject',
153
+ m.subject
154
+ ],
155
+ [
156
+ 'message-id',
157
+ messageIdOf(m.id)
158
+ ],
159
+ [
160
+ 'in-reply-to',
161
+ m.in_reply_to
162
+ ],
163
+ [
164
+ 'reply-to',
165
+ m.reply_to
166
+ ]
167
+ ];
168
+ for (let [k, v] of said)if (v) heads.set(k, v);
169
+ let at = m.received_at ?? new Date(m.ts ?? Date.now()).toISOString();
170
+ return [
171
+ {
172
+ from: m.from ?? '',
173
+ to: m.to ?? '',
174
+ headers: {
175
+ get: (name)=>heads.get(name.toLowerCase()) ?? null
176
+ }
177
+ },
178
+ {
179
+ at,
180
+ ...m.text == null ? {} : {
181
+ text: m.text
182
+ },
183
+ ...m.verified == null ? {} : {
184
+ verified: m.verified
185
+ },
186
+ vouched: m.verified === true
187
+ }
188
+ ];
189
+ };
190
+ /** Whom a request is for: the mailbox its first path segment names at your
191
+ * domain — `/hook/books/…` is whoever has `books@<domain>` — else triage. */ export let hookTo = async ({ graph, domain, triage }, path)=>{
192
+ let name = /^\/hook\/([^/?#]+)/.exec(path ?? '')?.[1];
193
+ let found = name && domain ? await routed(graph, `${name}@${domain}`, domain) : null;
194
+ return found ?? triage;
195
+ };
196
+ // A request the edge holds, as @yaks/hook records one.
197
+ let request = (r)=>({
198
+ id: r.id,
199
+ source: r.source || 'unknown',
200
+ ...r.method == null ? {} : {
201
+ method: r.method
202
+ },
203
+ ...r.path == null ? {} : {
204
+ path: r.path
205
+ },
206
+ ...r.headers == null ? {} : {
207
+ headers: r.headers
208
+ },
209
+ ...r.body == null ? {} : {
210
+ body: r.body
211
+ },
212
+ ...r.sig_ok == null ? {} : {
213
+ verified: !!r.sig_ok
214
+ }
215
+ });
216
+ // One tray: list it, record each item, acknowledge the ones recorded. Nothing
217
+ // here throws — nobody is waiting on a pull to answer — so a failure is said
218
+ // instead, and an item that failed stays at the edge for the next pull.
219
+ let tray = async ({ report, log, now, down }, name, list, record, ack)=>{
220
+ let fail = (what, err, tags = {})=>report(new Error(`@yaks/mail — pull could not ${what}`, {
221
+ cause: err
222
+ }), {
223
+ tags: {
224
+ step: 'mail pull',
225
+ tray: name,
226
+ ...tags
227
+ }
228
+ });
229
+ let began = now();
230
+ let done = [];
231
+ try {
232
+ for (let item of await list() ?? []){
233
+ try {
234
+ await record(item);
235
+ done.push(item.id);
236
+ } catch (err) {
237
+ fail(`record ${name} ${item.id}`, err);
238
+ }
239
+ }
240
+ if (done.length) await ack(done);
241
+ let lasted = answered(down?.get(name), now());
242
+ if (lasted != null) {
243
+ down.delete(name);
244
+ log(`@yaks/mail — ${name} tray recovered after ${lasted} ms`, {
245
+ tags: {
246
+ tray: name
247
+ }
248
+ });
249
+ }
250
+ return done.length;
251
+ } catch (err) {
252
+ if (!down || !(err instanceof Unavailable)) fail(`take ${name}s`, err);
253
+ else {
254
+ let { outage, fresh } = failing(down.get(name), began);
255
+ down.set(name, {
256
+ ...outage,
257
+ error: err
258
+ });
259
+ if (fresh) {
260
+ log(new Error(`@yaks/mail — ${name} tray unavailable; retrying next pass`, {
261
+ cause: err
262
+ }), {
263
+ tags: {
264
+ step: 'mail pull',
265
+ tray: name
266
+ }
267
+ });
268
+ }
269
+ }
270
+ }
271
+ return 0;
272
+ };
273
+ /**
274
+ * One pull: take the letters and the requests the edge holds, record them, and
275
+ * acknowledge them. Each tray fails alone, so an edge that cannot list its
276
+ * letters still hands over its requests.
277
+ *
278
+ * Requests are recorded only where the graph declares `hook`, and aimed at
279
+ * whom they are for only where it declares `about`; a graph without `hook`
280
+ * leaves the request tray for one that has it.
281
+ *
282
+ * A caller that pulls again hands in the same `down` each pass. Transient
283
+ * failures are logged and retained as the cause of a delayed letter's report;
284
+ * without another pass, every failure reports at once.
285
+ *
286
+ * It also hands in `since`, when its previous pass began. A letter that
287
+ * arrived after that waited only for this pass, however long the process
288
+ * between them was stopped or frozen, so it is not late at the edge; the
289
+ * process's own stall says why the pass was late.
290
+ */ export let pull = async (at, from)=>{
291
+ let { graph, report = console.error, log = console.warn, now = Date.now, down, since = Infinity } = at;
292
+ let pass = {
293
+ report,
294
+ log,
295
+ now,
296
+ down
297
+ };
298
+ let receive = arrived(at);
299
+ // Where a late letter's time went, per step, so the report says which.
300
+ let took = {};
301
+ let timed = async (step, run)=>{
302
+ let began = now();
303
+ try {
304
+ return await run();
305
+ } finally{
306
+ took[step] = `${now() - began} ms`;
307
+ }
308
+ };
309
+ let messages = await tray(pass, 'message', ()=>timed('list', from.messages), async (m)=>{
310
+ // An outbound copy has nothing to record; taking it clears the tray.
311
+ if (m.dir && m.dir != 'in') return;
312
+ let bundles = await timed('read', ()=>receive(...received(m)));
313
+ if (bundles.length) await timed('write', ()=>graph.apply(bundles));
314
+ let came = m.ts ?? (Date.parse(m.received_at ?? '') || now());
315
+ let waited = now() - came;
316
+ if (bundles.length && waited > LATE && came <= since) {
317
+ let outage = down?.get('message');
318
+ report(new Error('@yaks/mail — a letter waited too long at the edge', {
319
+ cause: outage?.error
320
+ }), {
321
+ tags: {
322
+ step: 'mail stall',
323
+ letter: messageIdOf(m.id),
324
+ waited: `${waited} ms`,
325
+ ...outage ? {
326
+ down: `${now() - outage.since} ms`
327
+ } : {},
328
+ ...took
329
+ }
330
+ });
331
+ }
332
+ }, from.notified);
333
+ let requests = graph.vocab.comp('hook') ? await tray(pass, 'request', from.requests, async (r)=>{
334
+ let about = graph.vocab.comp('about') ? await hookTo(at, r.path) : undefined;
335
+ await graph.apply(hooked(request(r), about), {
336
+ trusted: true
337
+ });
338
+ }, from.processed) : 0;
339
+ return {
340
+ messages,
341
+ requests
342
+ };
343
+ };
344
+ //# sourceMappingURL=pull.js.map
package/pull.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull.js","sources":["./pull.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,SAAS;AACT,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,4EAA4E;AAC5E,yDAAyD;AACzD,6EAA6E;AAC7E,+EAA+E;AAC/E,SAAS;AACT,EAAE;AACF,6EAA6E;AAC7E,qEAAqE;AACrE,6EAA6E;AAC7E,qEAAqE;AACrE,EAAE;AACF,+EAA+E;AAC/E,0EAA0E;AAC1E,+EAA+E;AAC/E,0EAA0E;AAC1E,QAAQ;AACR,EAAE;AACF,2EAA2E;AAC3E,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,4EAA4E;AAC5E,gC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