@zabaca/zbc 0.6.2 → 0.8.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.
@@ -1,4 +1,5 @@
1
1
  import { DurableObject } from 'cloudflare:workers'
2
+ import { type MailEnv, emitWebhook, sendMail } from './shared'
2
3
 
3
4
  /**
4
5
  * Inbox — a single SQLite-backed Durable Object holding message metadata and
@@ -20,6 +21,21 @@ export interface MessageMeta {
20
21
  created_at: string
21
22
  direction: 'inbound' | 'outbound'
22
23
  thread_id: string
24
+ /**
25
+ * 'sent' for everything visible in the inbox (inbound rows included);
26
+ * 'draft' = unsent draft, 'scheduled' = queued for the alarm,
27
+ * 'failed' = a scheduled send the alarm could not dispatch (see send_error
28
+ * in the scheduled listing).
29
+ */
30
+ status: 'draft' | 'scheduled' | 'sent' | 'failed'
31
+ /** Classifier label ('' until/unless labeling runs). */
32
+ label: string
33
+ }
34
+
35
+ /** A scheduled/failed row as returned by listScheduled. */
36
+ export interface ScheduledMeta extends MessageMeta {
37
+ scheduled_at: string
38
+ send_error: string
23
39
  }
24
40
 
25
41
  export interface ThreadMeta extends MessageMeta {
@@ -50,6 +66,13 @@ export interface InsertMessage {
50
66
  size: number
51
67
  direction: 'inbound' | 'outbound'
52
68
  in_reply_to: string
69
+ /**
70
+ * 'draft'/'scheduled' skip thread resolution (resolved at actual send
71
+ * time). Default 'sent'.
72
+ */
73
+ status?: 'draft' | 'scheduled' | 'sent'
74
+ /** Required when status is 'scheduled': ISO time the alarm should send at. */
75
+ scheduled_at?: string
53
76
  }
54
77
 
55
78
  /** Strip Re:/Fwd: prefixes + whitespace so replies fall into the same thread. */
@@ -61,11 +84,11 @@ function normalizeSubject(subject: string): string {
61
84
  .toLowerCase()
62
85
  }
63
86
 
64
- export class Inbox extends DurableObject {
87
+ export class Inbox extends DurableObject<MailEnv> {
65
88
  private sql: SqlStorage
66
89
 
67
- constructor(ctx: DurableObjectState, env: unknown) {
68
- super(ctx, env as never)
90
+ constructor(ctx: DurableObjectState, env: MailEnv) {
91
+ super(ctx, env)
69
92
  this.sql = ctx.storage.sql
70
93
  this.sql.exec(`
71
94
  CREATE TABLE IF NOT EXISTS messages (
@@ -107,6 +130,16 @@ export class Inbox extends DurableObject {
107
130
  )
108
131
  this.sql.exec(`UPDATE messages SET thread_id = id WHERE thread_id = ''`)
109
132
  }
133
+ if (!names.has('status')) {
134
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN status TEXT NOT NULL DEFAULT 'sent'`)
135
+ }
136
+ if (!names.has('label')) {
137
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN label TEXT NOT NULL DEFAULT ''`)
138
+ }
139
+ if (!names.has('scheduled_at')) {
140
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN scheduled_at TEXT NOT NULL DEFAULT ''`)
141
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN send_error TEXT NOT NULL DEFAULT ''`)
142
+ }
110
143
  this.sql.exec(`CREATE INDEX IF NOT EXISTS idx_messages_thread ON messages (thread_id, id)`)
111
144
  }
112
145
 
@@ -126,7 +159,10 @@ export class Inbox extends DurableObject {
126
159
  ): string {
127
160
  if (inReplyTo) {
128
161
  const byRef = this.sql
129
- .exec(`SELECT thread_id FROM messages WHERE message_id = ? LIMIT 1`, inReplyTo)
162
+ .exec(
163
+ `SELECT thread_id FROM messages WHERE message_id = ? AND status = 'sent' LIMIT 1`,
164
+ inReplyTo,
165
+ )
130
166
  .toArray()[0] as unknown as { thread_id: string } | undefined
131
167
  if (byRef?.thread_id) return byRef.thread_id
132
168
  }
@@ -135,7 +171,7 @@ export class Inbox extends DurableObject {
135
171
  const participants = [fromAddr, toAddr].map((a) => a.toLowerCase())
136
172
  const rows = this.sql
137
173
  .exec(
138
- `SELECT thread_id, subject, from_addr, to_addr FROM messages ORDER BY id DESC LIMIT 200`,
174
+ `SELECT thread_id, subject, from_addr, to_addr FROM messages WHERE status = 'sent' ORDER BY id DESC LIMIT 200`,
139
175
  )
140
176
  .toArray() as unknown as Array<{
141
177
  thread_id: string
@@ -154,19 +190,19 @@ export class Inbox extends DurableObject {
154
190
  }
155
191
 
156
192
  insert(msg: InsertMessage): { threadId: string } {
157
- const threadId = this.resolveThreadId(
158
- msg.id,
159
- msg.in_reply_to,
160
- msg.subject,
161
- msg.from_addr,
162
- msg.to_addr,
163
- )
193
+ const status = msg.status ?? 'sent'
194
+ // Drafts/scheduled get no thread until they're actually sent — resolving
195
+ // early could anchor a thread to a message that never goes out.
196
+ const threadId =
197
+ status === 'sent'
198
+ ? this.resolveThreadId(msg.id, msg.in_reply_to, msg.subject, msg.from_addr, msg.to_addr)
199
+ : ''
164
200
  this.sql.exec(
165
201
  `INSERT INTO messages
166
202
  (id, message_id, from_addr, to_addr, subject, date, snippet,
167
203
  text_body, html_body, r2_key, attachments_json, size, created_at,
168
- direction, in_reply_to, thread_id)
169
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
204
+ direction, in_reply_to, thread_id, status, scheduled_at)
205
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
170
206
  msg.id,
171
207
  msg.message_id,
172
208
  msg.from_addr,
@@ -183,29 +219,247 @@ export class Inbox extends DurableObject {
183
219
  msg.direction,
184
220
  msg.in_reply_to,
185
221
  threadId,
222
+ status,
223
+ msg.scheduled_at ?? '',
186
224
  )
225
+ if (status === 'scheduled') this.armAlarm()
187
226
  return { threadId }
188
227
  }
189
228
 
190
- /** Newest-first page. `cursor` is the last-seen id (ids are time-ordered). */
191
- list(limit = 50, cursor?: string): { messages: MessageMeta[]; nextCursor: string | null } {
229
+ /**
230
+ * (Re)arm the DO alarm for the earliest pending scheduled send. Safe to
231
+ * call any time — a DO has ONE alarm, so we always point it at MIN(
232
+ * scheduled_at); alarm() re-arms for the next one after each batch.
233
+ */
234
+ private armAlarm(): void {
235
+ const next = this.sql
236
+ .exec(`SELECT MIN(scheduled_at) AS next FROM messages WHERE status = 'scheduled'`)
237
+ .toArray()[0] as unknown as { next: string | null } | undefined
238
+ if (next?.next) {
239
+ void this.ctx.storage.setAlarm(new Date(next.next).getTime())
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Dispatch every due scheduled send. Handles past-due backlogs (missed
245
+ * alarms after redeploys/hibernation): everything with scheduled_at <= now
246
+ * goes out in this pass, then the alarm re-arms for the next future one.
247
+ * A failed dispatch marks the row 'failed' with send_error rather than
248
+ * blocking the rest of the batch.
249
+ */
250
+ async alarm(): Promise<void> {
251
+ const now = new Date().toISOString()
252
+ const due = this.sql
253
+ .exec(
254
+ `SELECT id, from_addr, to_addr, subject, text_body, html_body, in_reply_to, snippet
255
+ FROM messages WHERE status = 'scheduled' AND scheduled_at <= ? ORDER BY scheduled_at ASC`,
256
+ now,
257
+ )
258
+ .toArray() as unknown as Array<{
259
+ id: string
260
+ from_addr: string
261
+ to_addr: string
262
+ subject: string
263
+ text_body: string
264
+ html_body: string
265
+ in_reply_to: string
266
+ snippet: string
267
+ }>
268
+ for (const row of due) {
269
+ try {
270
+ await sendMail(this.env, {
271
+ from: row.from_addr,
272
+ to: row.to_addr,
273
+ subject: row.subject,
274
+ text: row.text_body || undefined,
275
+ html: row.html_body || undefined,
276
+ inReplyTo: row.in_reply_to,
277
+ })
278
+ const threadId = this.resolveThreadId(
279
+ row.id,
280
+ row.in_reply_to,
281
+ row.subject,
282
+ row.from_addr,
283
+ row.to_addr,
284
+ )
285
+ const sentAt = new Date().toISOString()
286
+ this.sql.exec(
287
+ `UPDATE messages SET status = 'sent', thread_id = ?, date = ? WHERE id = ?`,
288
+ threadId,
289
+ sentAt,
290
+ row.id,
291
+ )
292
+ await emitWebhook(this.env, 'message.sent', {
293
+ id: row.id,
294
+ threadId,
295
+ from: row.from_addr,
296
+ to: row.to_addr,
297
+ subject: row.subject,
298
+ snippet: row.snippet,
299
+ direction: 'outbound',
300
+ scheduled: true,
301
+ })
302
+ } catch (err) {
303
+ this.sql.exec(
304
+ `UPDATE messages SET status = 'failed', send_error = ? WHERE id = ?`,
305
+ (err as Error).message ?? 'send failed',
306
+ row.id,
307
+ )
308
+ }
309
+ }
310
+ this.armAlarm()
311
+ }
312
+
313
+ /** Scheduled + failed rows, soonest first (failed sort by original slot). */
314
+ listScheduled(limit = 50): ScheduledMeta[] {
192
315
  const capped = Math.min(Math.max(limit, 1), 200)
193
- const rows = (cursor
194
- ? this.sql
195
- .exec(
196
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id
197
- FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?`,
198
- cursor,
199
- capped + 1,
200
- )
201
- .toArray()
202
- : this.sql
203
- .exec(
204
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id
205
- FROM messages ORDER BY id DESC LIMIT ?`,
206
- capped + 1,
207
- )
208
- .toArray()) as unknown as MessageMeta[]
316
+ return this.sql
317
+ .exec(
318
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction,
319
+ thread_id, status, label, scheduled_at, send_error
320
+ FROM messages WHERE status IN ('scheduled', 'failed')
321
+ ORDER BY scheduled_at ASC LIMIT ?`,
322
+ capped,
323
+ )
324
+ .toArray() as unknown as ScheduledMeta[]
325
+ }
326
+
327
+ /**
328
+ * Cancel a pending scheduled send (deletes the row). Failed rows can be
329
+ * cancelled too — that's how they're dismissed. Returns false if the id
330
+ * isn't a scheduled/failed row.
331
+ */
332
+ cancelScheduled(id: string): boolean {
333
+ const row = this.sql
334
+ .exec(`SELECT status FROM messages WHERE id = ?`, id)
335
+ .toArray()[0] as unknown as { status: string } | undefined
336
+ if (!row || (row.status !== 'scheduled' && row.status !== 'failed')) return false
337
+ this.sql.exec(`DELETE FROM messages WHERE id = ?`, id)
338
+ this.armAlarm()
339
+ return true
340
+ }
341
+
342
+ /** Update an unsent draft's editable fields. Returns false if not a draft. */
343
+ updateDraft(
344
+ id: string,
345
+ fields: Partial<
346
+ Pick<
347
+ InsertMessage,
348
+ 'from_addr' | 'to_addr' | 'subject' | 'text_body' | 'html_body' | 'in_reply_to' | 'snippet'
349
+ >
350
+ >,
351
+ ): boolean {
352
+ const row = this.sql
353
+ .exec(`SELECT status FROM messages WHERE id = ?`, id)
354
+ .toArray()[0] as unknown as { status: string } | undefined
355
+ if (!row || row.status !== 'draft') return false
356
+ const cols = Object.keys(fields) as Array<keyof typeof fields>
357
+ if (cols.length === 0) return true
358
+ this.sql.exec(
359
+ `UPDATE messages SET ${cols.map((c) => `${c} = ?`).join(', ')} WHERE id = ?`,
360
+ ...cols.map((c) => fields[c] ?? ''),
361
+ id,
362
+ )
363
+ return true
364
+ }
365
+
366
+ /**
367
+ * Flip a draft to sent: resolve its thread NOW (against what actually
368
+ * exists at send time) and stamp the send date. Returns null if the row
369
+ * isn't an unsent draft.
370
+ */
371
+ markDraftSent(id: string, date: string): { threadId: string } | null {
372
+ const row = this.sql
373
+ .exec(
374
+ `SELECT status, in_reply_to, subject, from_addr, to_addr FROM messages WHERE id = ?`,
375
+ id,
376
+ )
377
+ .toArray()[0] as unknown as
378
+ | { status: string; in_reply_to: string; subject: string; from_addr: string; to_addr: string }
379
+ | undefined
380
+ if (!row || row.status !== 'draft') return null
381
+ const threadId = this.resolveThreadId(
382
+ id,
383
+ row.in_reply_to,
384
+ row.subject,
385
+ row.from_addr,
386
+ row.to_addr,
387
+ )
388
+ this.sql.exec(
389
+ `UPDATE messages SET status = 'sent', thread_id = ?, date = ? WHERE id = ?`,
390
+ threadId,
391
+ date,
392
+ id,
393
+ )
394
+ return { threadId }
395
+ }
396
+
397
+ /** Newest-first drafts (metadata only). */
398
+ listDrafts(limit = 50): MessageMeta[] {
399
+ const capped = Math.min(Math.max(limit, 1), 200)
400
+ return this.sql
401
+ .exec(
402
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
403
+ FROM messages WHERE status = 'draft' ORDER BY id DESC LIMIT ?`,
404
+ capped,
405
+ )
406
+ .toArray() as unknown as MessageMeta[]
407
+ }
408
+
409
+ /**
410
+ * Case-insensitive keyword search over subject + text_body. Plain LIKE —
411
+ * fine at this table's scale; revisit with an FTS index if volume grows.
412
+ * Drafts included; newest first.
413
+ */
414
+ search(q: string, limit = 50): MessageMeta[] {
415
+ const capped = Math.min(Math.max(limit, 1), 200)
416
+ const term = `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
417
+ return this.sql
418
+ .exec(
419
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
420
+ FROM messages
421
+ WHERE subject LIKE ? ESCAPE '\\' OR text_body LIKE ? ESCAPE '\\'
422
+ ORDER BY id DESC LIMIT ?`,
423
+ term,
424
+ term,
425
+ capped,
426
+ )
427
+ .toArray() as unknown as MessageMeta[]
428
+ }
429
+
430
+ /** Set the classifier label. No-op if the row is gone (delete raced it). */
431
+ setLabel(id: string, label: string): void {
432
+ this.sql.exec(`UPDATE messages SET label = ? WHERE id = ?`, label, id)
433
+ }
434
+
435
+ /**
436
+ * Newest-first page (drafts excluded — see listDrafts). `cursor` is the
437
+ * last-seen id (ids are time-ordered). `label` filters to one label.
438
+ */
439
+ list(
440
+ limit = 50,
441
+ cursor?: string,
442
+ label?: string,
443
+ ): { messages: MessageMeta[]; nextCursor: string | null } {
444
+ const capped = Math.min(Math.max(limit, 1), 200)
445
+ const where = [`status = 'sent'`]
446
+ const params: unknown[] = []
447
+ if (cursor) {
448
+ where.push('id < ?')
449
+ params.push(cursor)
450
+ }
451
+ if (label) {
452
+ where.push('label = ?')
453
+ params.push(label)
454
+ }
455
+ const rows = this.sql
456
+ .exec(
457
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
458
+ FROM messages WHERE ${where.join(' AND ')} ORDER BY id DESC LIMIT ?`,
459
+ ...params,
460
+ capped + 1,
461
+ )
462
+ .toArray() as unknown as MessageMeta[]
209
463
  const hasMore = rows.length > capped
210
464
  const page = hasMore ? rows.slice(0, capped) : rows
211
465
  return { messages: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
@@ -219,10 +473,11 @@ export class Inbox extends DurableObject {
219
473
  const capped = Math.min(Math.max(limit, 1), 200)
220
474
  const base = `
221
475
  SELECT m.id, m.from_addr, m.to_addr, m.subject, m.date, m.snippet, m.size,
222
- m.created_at, m.direction, m.thread_id,
476
+ m.created_at, m.direction, m.thread_id, m.status, m.label,
223
477
  (SELECT COUNT(*) FROM messages c WHERE c.thread_id = m.thread_id) AS thread_count
224
478
  FROM messages m
225
- WHERE m.id = (SELECT MAX(id) FROM messages x WHERE x.thread_id = m.thread_id)`
479
+ WHERE m.status = 'sent'
480
+ AND m.id = (SELECT MAX(id) FROM messages x WHERE x.thread_id = m.thread_id)`
226
481
  const rows = (cursor
227
482
  ? this.sql
228
483
  .exec(`${base} AND m.id < ? ORDER BY m.id DESC LIMIT ?`, cursor, capped + 1)
@@ -241,7 +496,7 @@ export class Inbox extends DurableObject {
241
496
  .exec(
242
497
  `SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
243
498
  text_body, html_body, r2_key, attachments_json, size, created_at,
244
- direction, in_reply_to, thread_id
499
+ direction, in_reply_to, thread_id, status, label
245
500
  FROM messages WHERE thread_id = ? ORDER BY id ASC`,
246
501
  threadId,
247
502
  )
@@ -257,7 +512,7 @@ export class Inbox extends DurableObject {
257
512
  .exec(
258
513
  `SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
259
514
  text_body, html_body, r2_key, attachments_json, size, created_at,
260
- direction, in_reply_to, thread_id
515
+ direction, in_reply_to, thread_id, status, label
261
516
  FROM messages WHERE id = ?`,
262
517
  id,
263
518
  )