emailengine-app 2.72.2 → 2.72.4

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.
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { ImapFlow } = require('imapflow');
4
4
  const { backOff } = require('exponential-backoff');
5
+ const { ReconnectBackoff } = require('../reconnect-backoff');
5
6
  const EventEmitter = require('events').EventEmitter;
6
7
 
7
8
  const MAX_WAIT_DELAY = 450; //ms
@@ -30,10 +31,7 @@ class Subconnection extends EventEmitter {
30
31
  this.emitTimer = false;
31
32
 
32
33
  // Reconnection tracking for capped exponential backoff
33
- this.reconnectAttempts = 0;
34
- this.reconnectBaseDelay = 2000;
35
- this.reconnectMaxDelay = 30000; // Cap at 30 seconds
36
- this.lastReconnectTime = 0;
34
+ this.reconnectBackoff = new ReconnectBackoff({ baseDelay: 2000, maxDelay: 30000, jitter: 1000 });
37
35
  }
38
36
 
39
37
  isConnected() {
@@ -63,44 +61,48 @@ class Subconnection extends EventEmitter {
63
61
  await this.reconnect();
64
62
  }
65
63
 
66
- async reconnect(force) {
67
- if (this._connecting || this.isClosing || (this.isClosed && !force)) {
64
+ async reconnect() {
65
+ if (this._connecting || this.isClosing || this.isClosed) {
68
66
  return false;
69
67
  }
70
68
 
71
- // Calculate delay with cap (never stops trying)
72
- const delay = Math.min(this.reconnectMaxDelay, this.reconnectBaseDelay * Math.pow(1.5, Math.min(this.reconnectAttempts, 10)));
73
-
74
- // Add jitter to prevent thundering herd
75
- const jitter = Math.random() * 1000; // 0-1 second jitter
76
- const totalDelay = delay + jitter;
77
-
78
- this.reconnectAttempts++;
69
+ // Block overlapping cycles right away. The 'error' and 'close' handlers
70
+ // check this flag, so setting it before the backoff sleep prevents them
71
+ // from starting a second reconnection cycle while this one is waiting
72
+ this._connecting = true;
79
73
 
80
- this.logger.info({
81
- msg: 'Scheduling subconnection reconnect',
82
- attempt: this.reconnectAttempts,
83
- delay: totalDelay,
84
- path: this.path
85
- });
74
+ try {
75
+ // Calculate delay with cap and jitter (never stops trying)
76
+ const totalDelay = this.reconnectBackoff.nextDelay();
77
+
78
+ this.logger.info({
79
+ msg: 'Scheduling subconnection reconnect',
80
+ attempt: this.reconnectBackoff.attempts,
81
+ delay: totalDelay,
82
+ path: this.path
83
+ });
86
84
 
87
- // Wait before attempting reconnect
88
- await new Promise(resolve => setTimeout(resolve, totalDelay));
85
+ // Wait before attempting reconnect
86
+ await new Promise(resolve => setTimeout(resolve, totalDelay));
89
87
 
90
- this._connecting = true;
91
- this.isClosed = false;
88
+ if (this.isClosing || this.isClosed) {
89
+ // close() was called during the delay. Do not revive a closed
90
+ // subconnection - the parent has already discarded this instance,
91
+ // so a new connection would be unreachable and leak
92
+ return false;
93
+ }
92
94
 
93
- try {
94
95
  await backOff(() => this.start(), {
95
- maxDelay: this.reconnectMaxDelay,
96
+ maxDelay: this.reconnectBackoff.maxDelay,
96
97
  numOfAttempts: Infinity,
97
98
  retry: () => !this.isClosing && !this.isClosed,
98
99
  startingDelay: 2000
99
100
  });
100
-
101
- // Success - reset counter
102
- this.reconnectAttempts = 0;
103
101
  } finally {
102
+ // Cleared before the mailbox validation below on purpose: if the
103
+ // server drops the connection while the monitored mailbox is being
104
+ // opened, the 'close' handler must still be able to schedule the
105
+ // single retry cycle
104
106
  this._connecting = false;
105
107
  }
106
108
 
@@ -110,7 +112,61 @@ class Subconnection extends EventEmitter {
110
112
 
111
113
  this.state = 'connected';
112
114
  this.disabledReason = false;
115
+
116
+ // Reset the backoff counter only after the monitored mailbox is open.
117
+ // Connect/login success alone does not validate the setup - resetting
118
+ // already there would restart the close-triggered retry loop from the
119
+ // base delay on every cycle when the mailbox itself can not be opened
120
+ this.reconnectBackoff.reset();
113
121
  } catch (err) {
122
+ if (err.responseStatus === 'NO' && this.imapClient?.usable) {
123
+ // SELECT failed with NO - verify whether the mailbox exists at
124
+ // all, mirroring the verification ImapFlow runs in
125
+ // getMailboxLock(). mailboxOpen() itself does not set the
126
+ // mailboxMissing marker
127
+ try {
128
+ let folders = await this.imapClient.run('LIST', '', this.mailbox.path, { listOnly: true });
129
+ // The path goes into the LIST command as the match pattern
130
+ // verbatim, so IMAP wildcards (% and *) in the folder name
131
+ // can match sibling folders. Only an entry with the exact
132
+ // same path proves the monitored mailbox still exists
133
+ // (monitored paths come from the account listing, so the
134
+ // stored spelling matches what the server returns)
135
+ if (!folders || !folders.some(folder => folder.path === this.mailbox.path)) {
136
+ err.mailboxMissing = true;
137
+ }
138
+ } catch (E) {
139
+ this.logger.debug({ msg: 'Failed to verify missing mailbox', path: this.mailbox.path, err: E });
140
+ }
141
+ }
142
+
143
+ if (err.mailboxMissing) {
144
+ // The monitored folder does not exist anymore, so retrying can
145
+ // not succeed. Shut the subconnection down and mark it as
146
+ // disabled - setupSubConnections() replaces it with a live
147
+ // connection if the folder is re-created later
148
+ this.logger.warn({ msg: 'Monitored mailbox is missing, disabling subconnection', path: this.mailbox.path, err });
149
+
150
+ this.close();
151
+ this.imapClient = null;
152
+
153
+ // close() resets these, so set the disabled state afterwards.
154
+ // mailboxMissing is the machine-readable marker consumed by the
155
+ // revival trigger in syncMailboxes() - the disabledReason text
156
+ // is display copy and must not carry behavior
157
+ this.disabled = true;
158
+ this.state = 'disabled';
159
+ this.disabledReason = 'Mailbox folder not found';
160
+ this.mailboxMissing = true;
161
+
162
+ // Process the folder deletion (stored listing, webhooks) right away
163
+ this.parent.refreshAndProcessListing().catch(err => {
164
+ this.logger.error({ msg: 'Failed to refresh folder listing', err });
165
+ });
166
+
167
+ return;
168
+ }
169
+
114
170
  // ended in an unconncted state
115
171
  this.logger.warn({ msg: 'Failed to set up subconnection', err });
116
172
  }
@@ -133,6 +189,10 @@ class Subconnection extends EventEmitter {
133
189
  if (prevImapClient === this.imapClient) {
134
190
  this.imapClient = null;
135
191
  }
192
+
193
+ // The close handler that maintains the connection count was removed
194
+ // above, so update the tracking for the replaced client manually
195
+ await this.parent.untrackConnection(prevImapClient);
136
196
  }
137
197
  }
138
198
 
@@ -164,8 +224,7 @@ class Subconnection extends EventEmitter {
164
224
 
165
225
  imapClient.on('close', async () => {
166
226
  try {
167
- this.parent.connections.delete(imapClient);
168
- await this.parent.redis.hSetExists(this.parent.getAccountKey(), 'connections', this.parent.connections.size.toString());
227
+ await this.parent.untrackConnection(imapClient);
169
228
  imapClient.log.info({ msg: 'Connection closed', account: this.account });
170
229
  } catch (err) {
171
230
  this.logger.error({ msg: 'Error updating connection count on close', account: this.account, err });
@@ -183,7 +242,14 @@ class Subconnection extends EventEmitter {
183
242
  });
184
243
 
185
244
  try {
186
- await this.connect();
245
+ let connectResponse = await this.connect();
246
+ if (connectResponse === false) {
247
+ // connect() bailed because close() landed while the connection
248
+ // was being set up - no socket was opened, so the 'close'
249
+ // listener that maintains the connection count never fires.
250
+ // Drop the tracking entry manually
251
+ await this.parent.untrackConnection(imapClient);
252
+ }
187
253
  } catch (err) {
188
254
  if (err.authenticationFailed) {
189
255
  this.logger.error({ msg: 'Failed to authenticate subconnection', account: this.account, err });
@@ -263,10 +329,13 @@ class Subconnection extends EventEmitter {
263
329
  this.imapClient.close();
264
330
  }
265
331
 
266
- clearTimeout(this.refreshListingTimer);
267
- clearTimeout(this.untaggedExpungeTimer);
268
- clearTimeout(this.resyncTimer);
269
- clearTimeout(this.completedTimer);
332
+ // Drop the pending 'changes' debounce. The mailboxMissing disable path
333
+ // closes the subconnection while the parent's listeners are still
334
+ // attached (they are only detached at the next reconcile), so a timer
335
+ // armed just before close would otherwise still emit on the closed
336
+ // instance and trigger a pointless sync for the removed folder
337
+ clearTimeout(this.emitTimer);
338
+ this.emitTimer = false;
270
339
 
271
340
  this.isClosing = false;
272
341
  this.isClosed = true;