loopzero-gateway-email 0.1.0 → 0.1.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 414ebff: A lost IMAP connection is reopened with growing delays (1 s doubling to 60 s) until it succeeds or `disconnect()` is called, and the mail that arrived meanwhile is dispatched from the kept cursor. Before, a reset or timeout ended inbound mail for the life of the process while `connect()` had answered true, and an `error` event on an open connection had no listener.
8
+
3
9
  ## 0.6.1
4
10
 
5
11
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -84,16 +84,33 @@ var ImapClient = class {
84
84
  config;
85
85
  client;
86
86
  idleAbort;
87
+ lostListener;
88
+ /** Set by `disconnect()`, so the close it causes is not reported as a loss. */
89
+ closing = false;
90
+ onConnectionLost(listener) {
91
+ this.lostListener = listener;
92
+ }
87
93
  async connect() {
88
- this.client = new imapflow.ImapFlow({
94
+ const client = new imapflow.ImapFlow({
89
95
  host: this.config.host,
90
96
  port: this.config.port,
91
97
  secure: this.config.secure,
92
98
  auth: this.config.auth,
93
99
  logger: false
94
100
  });
95
- await this.client.connect();
96
- await this.client.mailboxOpen("INBOX");
101
+ this.client = client;
102
+ let lastError;
103
+ client.on("error", (err) => {
104
+ lastError = err;
105
+ });
106
+ let opened = false;
107
+ client.on("close", () => {
108
+ if (!opened || this.closing) return;
109
+ this.lostListener?.(lastError);
110
+ });
111
+ await client.connect();
112
+ await client.mailboxOpen("INBOX");
113
+ opened = true;
97
114
  }
98
115
  // eslint-disable-next-line @typescript-eslint/require-await
99
116
  async mailboxStatus() {
@@ -161,6 +178,7 @@ var ImapClient = class {
161
178
  }
162
179
  }
163
180
  async disconnect() {
181
+ this.closing = true;
164
182
  await this.stopIdle();
165
183
  if (this.client !== void 0) {
166
184
  try {
@@ -361,6 +379,7 @@ var ThreadStore = class _ThreadStore {
361
379
 
362
380
  // src/adapter.ts
363
381
  var DEFAULT_POLL_INTERVAL_MS = 15e3;
382
+ var MAX_RECONNECT_DELAY_MS = 6e4;
364
383
  function reportDrainFailure(err) {
365
384
  console.error("[email] drain failed:", err instanceof Error ? err.message : err);
366
385
  }
@@ -383,6 +402,13 @@ var EmailAdapter = class extends loopzeroGateway.BasePlatformAdapter {
383
402
  // EC-4: serialize concurrent _dispatchInbound calls.
384
403
  dispatchQueue = Promise.resolve();
385
404
  pollTimer;
405
+ /** Set by `disconnect()`: a lost connection is then not reopened. */
406
+ stopping = false;
407
+ reconnectTimer;
408
+ reconnectBackoff = new loopzeroGateway.ReconnectBackoff({
409
+ initialDelayMs: 1e3,
410
+ maxDelayMs: MAX_RECONNECT_DELAY_MS
411
+ });
386
412
  /** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
387
413
  cursor;
388
414
  constructor(opts) {
@@ -395,39 +421,55 @@ var EmailAdapter = class extends loopzeroGateway.BasePlatformAdapter {
395
421
  }
396
422
  this.options = opts;
397
423
  }
398
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: connect orchestrates factory-vs-real, verify(), connect(), IDLE-vs-poll choice, and rollback-on-throw — a linear single-transaction sequence; splitting hurts the disconnect-on-failure invariant.
399
424
  async connect() {
400
425
  if (this.connected) return true;
426
+ this.stopping = false;
401
427
  try {
402
- const imapFactory = this.options.__imapFactory;
403
428
  const smtpFactory = this.options.__smtpFactory;
404
- this.imap = imapFactory !== void 0 ? imapFactory({
405
- host: this.options.imapHost,
406
- port: this.options.imapPort ?? 993,
407
- secure: true,
408
- auth: { user: this.options.address, pass: this.options.password }
409
- }) : new ImapClient({
410
- host: this.options.imapHost,
411
- port: this.options.imapPort ?? 993,
412
- secure: true,
413
- auth: { user: this.options.address, pass: this.options.password }
414
- });
415
- this.smtp = smtpFactory !== void 0 ? smtpFactory({
429
+ const smtpConfig = {
416
430
  host: this.options.smtpHost,
417
431
  port: this.options.smtpPort ?? 587,
418
432
  secure: (this.options.smtpPort ?? 587) === 465,
419
433
  auth: { user: this.options.address, pass: this.options.password }
420
- }) : new SmtpClient({
421
- host: this.options.smtpHost,
422
- port: this.options.smtpPort ?? 587,
423
- secure: (this.options.smtpPort ?? 587) === 465,
424
- auth: { user: this.options.address, pass: this.options.password }
425
- });
434
+ };
435
+ this.smtp = smtpFactory !== void 0 ? smtpFactory(smtpConfig) : new SmtpClient(smtpConfig);
426
436
  await this.smtp.verify();
427
- await this.imap.connect();
428
- await this._establishCursor(this.imap);
429
- if (this.imap.supportsIdle()) {
430
- await this.imap.startIdle(() => {
437
+ await this._openImap();
438
+ this.connected = true;
439
+ return true;
440
+ } catch (err) {
441
+ console.error("[email] connect failed:", err instanceof Error ? err.message : err);
442
+ await this.disconnect().catch(() => {
443
+ });
444
+ return false;
445
+ }
446
+ }
447
+ /** A fresh IMAP client, watched for loss of its connection. */
448
+ _newImapClient() {
449
+ const imapFactory = this.options.__imapFactory;
450
+ const config = {
451
+ host: this.options.imapHost,
452
+ port: this.options.imapPort ?? 993,
453
+ secure: true,
454
+ auth: { user: this.options.address, pass: this.options.password }
455
+ };
456
+ const client = imapFactory !== void 0 ? imapFactory(config) : new ImapClient(config);
457
+ client.onConnectionLost((cause) => this._imapLost(client, cause));
458
+ return client;
459
+ }
460
+ /**
461
+ * Open IMAP, keep or take the cursor, and start watching: IDLE when the server has it, a poll
462
+ * otherwise. Used by `connect()` and by every reconnect, so a reconnect resumes from the cursor
463
+ * and dispatches what arrived while the connection was down.
464
+ */
465
+ async _openImap() {
466
+ const imap = this._newImapClient();
467
+ this.imap = imap;
468
+ try {
469
+ await imap.connect();
470
+ await this._establishCursor(imap);
471
+ if (imap.supportsIdle()) {
472
+ await imap.startIdle(() => {
431
473
  void this._drainUnseen().catch(reportDrainFailure);
432
474
  });
433
475
  void this._drainUnseen().catch(reportDrainFailure);
@@ -437,20 +479,75 @@ var EmailAdapter = class extends loopzeroGateway.BasePlatformAdapter {
437
479
  void this._drainUnseen().catch(reportDrainFailure);
438
480
  }, intervalMs);
439
481
  }
440
- this.connected = true;
441
- return true;
482
+ this.reconnectBackoff.opened();
442
483
  } catch (err) {
443
- console.error("[email] connect failed:", err instanceof Error ? err.message : err);
444
- await this.disconnect().catch(() => {
484
+ if (this.imap === imap) this.imap = void 0;
485
+ await imap.disconnect().catch(() => {
445
486
  });
446
- return false;
487
+ throw err;
447
488
  }
448
489
  }
449
- async disconnect() {
490
+ /**
491
+ * The IMAP connection dropped (a reset, a timeout, the server going away). The adapter stays
492
+ * connected from its caller's view and opens a new IMAP connection with growing delays until
493
+ * one succeeds or `disconnect()` is called. Without this a dropped link ended inbound mail for
494
+ * the life of the process while `connect()` had answered true.
495
+ */
496
+ _imapLost(client, cause) {
497
+ if (this.stopping || this.imap !== client) return;
498
+ console.error(
499
+ `[email] IMAP connection lost (${cause?.message ?? "closed by the server"}); reconnecting`
500
+ );
501
+ this.imap = void 0;
502
+ this._stopPolling();
503
+ void client.disconnect().catch(() => {
504
+ });
505
+ this._scheduleReconnect();
506
+ }
507
+ _scheduleReconnect() {
508
+ if (this.stopping || this.reconnectTimer !== void 0) return;
509
+ const delay = this.reconnectBackoff.nextDelayMs() ?? MAX_RECONNECT_DELAY_MS;
510
+ this.reconnectTimer = setTimeout(() => {
511
+ this.reconnectTimer = void 0;
512
+ this._reconnectImap().catch((err) => {
513
+ console.error(
514
+ "[email] IMAP reconnect crashed (will retry):",
515
+ err instanceof Error ? err.message : err
516
+ );
517
+ this._scheduleReconnect();
518
+ });
519
+ }, delay);
520
+ }
521
+ async _reconnectImap() {
522
+ if (this.stopping) return;
523
+ try {
524
+ await this._openImap();
525
+ if (this.stopping) {
526
+ await this.imap?.disconnect().catch(() => {
527
+ });
528
+ this.imap = void 0;
529
+ }
530
+ } catch (err) {
531
+ console.error(
532
+ "[email] IMAP reconnect failed (will retry):",
533
+ err instanceof Error ? err.message : err
534
+ );
535
+ this._scheduleReconnect();
536
+ }
537
+ }
538
+ _stopPolling() {
450
539
  if (this.pollTimer !== void 0) {
451
540
  clearInterval(this.pollTimer);
452
541
  this.pollTimer = void 0;
453
542
  }
543
+ }
544
+ async disconnect() {
545
+ this.stopping = true;
546
+ if (this.reconnectTimer !== void 0) {
547
+ clearTimeout(this.reconnectTimer);
548
+ this.reconnectTimer = void 0;
549
+ }
550
+ this._stopPolling();
454
551
  if (this.imap !== void 0) {
455
552
  await this.imap.disconnect().catch(() => {
456
553
  });