emailengine-app 2.81.1 → 2.82.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.
Files changed (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
@@ -2,7 +2,7 @@
2
2
 
3
3
  const { Gateway } = require('../gateway');
4
4
  const { oauth2ProviderData } = require('../oauth2-apps');
5
- const { useAuthServerForConnection } = require('../tools');
5
+ const { useAuthServerForConnection, redactUrlCredentials } = require('../tools');
6
6
  const { resolveAuthServerCredentials } = require('./credential-errors');
7
7
  const { getLocalAddress } = require('../utils/network');
8
8
  const settings = require('../settings');
@@ -45,18 +45,11 @@ class SmtpConfigBuilder {
45
45
  secret: this.secret
46
46
  });
47
47
 
48
- try {
49
- const gatewayData = await gatewayObject.loadGatewayData();
50
- return { gatewayData, gatewayObject };
51
- } catch (err) {
52
- this.logger.warn({
53
- msg: 'Failed to load gateway data',
54
- messageId,
55
- gateway: gatewayId,
56
- err
57
- });
58
- return { gatewayData: null, gatewayObject };
59
- }
48
+ // The message was queued for this gateway, so it must not go out through the account's
49
+ // own SMTP server instead: a Redis failure is thrown as is and the job retries, a gateway
50
+ // that no longer exists throws GatewayNotFound and the job is discarded
51
+ const gatewayData = await gatewayObject.loadGatewayData();
52
+ return { gatewayData, gatewayObject };
60
53
  }
61
54
 
62
55
  /**
@@ -305,7 +298,9 @@ class NetworkRoutingBuilder {
305
298
  }
306
299
 
307
300
  if (smtpSettings.proxy) {
308
- networkRouting.proxy = smtpSettings.proxy;
301
+ // This object ends up in messageSent / messageDeliveryError webhooks, job progress and
302
+ // the gateway's lastError, so the proxy password must not travel with it.
303
+ networkRouting.proxy = redactUrlCredentials(smtpSettings.proxy);
309
304
  }
310
305
 
311
306
  if (smtpSettings.name) {
@@ -1,39 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const { parentPort } = require('worker_threads');
4
- const logger = require('../logger');
5
4
  const { webhooks: Webhooks } = require('../webhooks');
6
- const { getESClient, isDocumentStoreEnabled } = require('../document-store');
7
- const { getThread } = require('../threads');
8
5
  const settings = require('../settings');
9
- const { buildRetentionPolicy } = require('../queue-retention');
10
-
11
- // Import notification-related constants
12
- const { MESSAGE_NEW_NOTIFY, MESSAGE_DELETED_NOTIFY, MESSAGE_UPDATED_NOTIFY, EMAIL_BOUNCE_NOTIFY, MAILBOX_DELETED_NOTIFY } = require('../consts');
13
-
14
- /**
15
- * Events that should sync with the document store (ElasticSearch)
16
- */
17
- const DOCUMENT_SYNC_EVENTS = [MESSAGE_NEW_NOTIFY, MESSAGE_DELETED_NOTIFY, MESSAGE_UPDATED_NOTIFY, EMAIL_BOUNCE_NOTIFY, MAILBOX_DELETED_NOTIFY];
18
-
19
- /**
20
- * Default job options for notification queue
21
- */
22
- const DEFAULT_JOB_OPTIONS = {
23
- removeOnComplete: { age: 24 * 3600, count: 1000 },
24
- removeOnFail: { age: 24 * 3600, count: 1000 },
25
- attempts: 10,
26
- backoff: {
27
- type: 'exponential',
28
- delay: 5000,
29
- jitter: 0.2 // 20% randomization to prevent thundering herd
30
- }
31
- };
32
-
33
- /**
34
- * Job options for document store updates (more retry attempts)
35
- */
36
- const DOCUMENT_JOB_OPTIONS = Object.assign({}, DEFAULT_JOB_OPTIONS, { attempts: 16 });
37
6
 
38
7
  /**
39
8
  * Sends metrics data to the parent thread for aggregation
@@ -59,7 +28,7 @@ function postMetrics(meta, loggerInstance, key, method, ...args) {
59
28
 
60
29
  /**
61
30
  * Handles notification delivery for email events
62
- * Manages webhook delivery, document store sync, and queue processing
31
+ * Manages webhook delivery and event metrics
63
32
  */
64
33
  class NotificationHandler {
65
34
  /**
@@ -67,14 +36,10 @@ class NotificationHandler {
67
36
  * @param {Object} options - Handler options
68
37
  * @param {string} options.account - Account identifier
69
38
  * @param {Object} options.logger - Logger instance
70
- * @param {Object} options.flowProducer - BullMQ flow producer for queue jobs
71
- * @param {Object} options.documentsQueue - Queue for document store updates
72
39
  */
73
40
  constructor(options) {
74
41
  this.account = options.account;
75
42
  this.logger = options.logger;
76
- this.flowProducer = options.flowProducer;
77
- this.documentsQueue = options.documentsQueue;
78
43
  }
79
44
 
80
45
  /**
@@ -114,171 +79,15 @@ class NotificationHandler {
114
79
  return payload;
115
80
  }
116
81
 
117
- /**
118
- * Determines if an event should sync with the document store
119
- * @param {string} event - Event type
120
- * @param {boolean} canSync - Whether sync is allowed
121
- * @returns {Promise<boolean>} Whether to add document queue job
122
- */
123
- async shouldSyncDocuments(event, canSync) {
124
- if (!canSync || !this.documentsQueue) {
125
- return false;
126
- }
127
-
128
- if (!DOCUMENT_SYNC_EVENTS.includes(event)) {
129
- return false;
130
- }
131
-
132
- return await isDocumentStoreEnabled();
133
- }
134
-
135
- /**
136
- * Generates a thread ID for new messages using ElasticSearch
137
- * @param {Object} payload - Notification payload with message data
138
- * @returns {Promise<void>}
139
- */
140
- async generateThreadId(payload) {
141
- if (!payload.data || payload.data.threadId) {
142
- return;
143
- }
144
-
145
- const { index, client } = await getESClient(logger);
146
- if (!client) {
147
- return;
148
- }
149
-
150
- try {
151
- const thread = await getThread(client, index, this.account, payload.data, logger);
152
- if (thread) {
153
- payload.data.threadId = thread;
154
- this.logger.debug({
155
- msg: 'Provisioned thread ID for a message',
156
- account: this.account,
157
- message: payload.data.id,
158
- threadId: payload.data.threadId
159
- });
160
- }
161
- } catch (err) {
162
- if (this.logger.notifyError) {
163
- this.logger.notifyError(err, { user: this.account, meta: { index } });
164
- }
165
- this.logger.error({
166
- msg: 'Failed to resolve thread',
167
- account: this.account,
168
- message: payload.data.id,
169
- err
170
- });
171
- }
172
- }
173
-
174
- /**
175
- * Processes notification with both webhook and document store sync
176
- * Uses BullMQ flow to ensure proper ordering
177
- * @param {string} event - Event type
178
- * @param {Object} payload - Notification payload
179
- * @param {boolean} queueKeep - Whether to keep completed jobs
180
- */
181
- async processWithFlow(event, payload, queueKeep) {
182
- const notifyPayload = await Webhooks.formatPayload(event, payload);
183
-
184
- const queueFlow = [
185
- {
186
- name: event,
187
- data: payload,
188
- queueName: 'documents'
189
- }
190
- ];
191
-
192
- await Webhooks.pushToQueue(event, notifyPayload, {
193
- routesOnly: true,
194
- queueFlow
195
- });
196
-
197
- // A child that fails for good (the document store job or a custom-route delivery out
198
- // of attempts) has to be moved to the parent's failed-dependencies set, otherwise the
199
- // main webhook job sits in waiting-children until retention prunes it
200
- for (let child of queueFlow) {
201
- child.opts = Object.assign({ ignoreDependencyOnFailure: true }, child.opts);
202
- }
203
-
204
- const jobOptions = this.buildJobOptions(queueKeep);
205
-
206
- await this.flowProducer.add(
207
- {
208
- name: event,
209
- data: notifyPayload,
210
- queueName: 'notify',
211
- children: queueFlow
212
- },
213
- {
214
- queuesOptions: {
215
- notify: {
216
- defaultJobOptions: jobOptions.notify
217
- },
218
- documents: {
219
- defaultJobOptions: jobOptions.documents
220
- }
221
- }
222
- }
223
- );
224
- }
225
-
226
- /**
227
- * Processes notification with webhook only (no document sync)
228
- * @param {string} event - Event type
229
- * @param {Object} payload - Notification payload
230
- */
231
- async processWebhookOnly(event, payload) {
232
- const notifyPayload = await Webhooks.formatPayload(event, payload);
233
- await Webhooks.pushToQueue(event, notifyPayload);
234
- }
235
-
236
- /**
237
- * Processes notification with document store sync only (no webhook)
238
- * @param {string} event - Event type
239
- * @param {Object} payload - Notification payload
240
- * @param {boolean|number} queueKeep - Whether/how many jobs to keep
241
- */
242
- async processDocumentOnly(event, payload, queueKeep) {
243
- // Goes through buildJobOptions like every other enqueue. Passing DOCUMENT_JOB_OPTIONS
244
- // straight through left this path on the hardcoded baseline: it ignored the queueKeep
245
- // setting and, more importantly, never picked up the failed-entry floor.
246
- await this.documentsQueue.add(event, payload, this.buildJobOptions(queueKeep).documents);
247
- }
248
-
249
- /**
250
- * Builds job options based on queue keep setting
251
- * @param {boolean|number} queueKeep - Whether/how many jobs to keep
252
- * @returns {Object} Job options for notify and documents queues
253
- */
254
- buildJobOptions(queueKeep) {
255
- const retention = buildRetentionPolicy(queueKeep);
256
-
257
- const notifyOptions = Object.assign({}, DEFAULT_JOB_OPTIONS, retention);
258
-
259
- const documentOptions = Object.assign({}, DOCUMENT_JOB_OPTIONS, retention);
260
-
261
- return {
262
- notify: notifyOptions,
263
- documents: documentOptions
264
- };
265
- }
266
-
267
82
  /**
268
83
  * Sends a notification for an email event
269
- * Handles webhook delivery, document store sync, and metrics tracking
84
+ * Handles webhook delivery and metrics tracking
270
85
  * @param {Object} mailbox - Mailbox information
271
86
  * @param {string} event - Event type constant
272
87
  * @param {Object} data - Event data payload
273
- * @param {Object} extraOpts - Additional options
274
- * @param {boolean} extraOpts.skipWebhook - Skip webhook delivery
275
- * @param {boolean} extraOpts.canSync - Allow document store sync (default: true)
276
88
  * @returns {Promise<void>}
277
89
  */
278
- async notify(mailbox, event, data, extraOpts) {
279
- extraOpts = extraOpts || {};
280
- const { skipWebhook, canSync = true } = extraOpts;
281
-
90
+ async notify(mailbox, event, data) {
282
91
  // Track event metrics
283
92
  postMetrics({ account: this.account }, this.logger, 'events', 'inc', { event });
284
93
 
@@ -288,35 +97,12 @@ class NotificationHandler {
288
97
  // Build notification payload
289
98
  const payload = this.buildPayload(mailbox, event, data, serviceUrl);
290
99
 
291
- // Determine if we need to sync with document store
292
- const addDocumentQueueJob = await this.shouldSyncDocuments(event, canSync);
293
-
294
- // Generate thread ID for new messages if needed
295
- if (addDocumentQueueJob && event === MESSAGE_NEW_NOTIFY) {
296
- await this.generateThreadId(payload);
297
- }
298
-
299
- // Get queue retention setting
300
- const queueKeep = (await settings.get('queueKeep')) ?? true;
301
-
302
- // Process notification based on required destinations
303
- if (!skipWebhook && addDocumentQueueJob) {
304
- // Add both webhook and document jobs as a flow
305
- await this.processWithFlow(event, payload, queueKeep);
306
- } else if (!skipWebhook) {
307
- // Webhook only
308
- await this.processWebhookOnly(event, payload);
309
- } else if (addDocumentQueueJob) {
310
- // Document store only
311
- await this.processDocumentOnly(event, payload, queueKeep);
312
- }
100
+ const notifyPayload = await Webhooks.formatPayload(event, payload);
101
+ await Webhooks.pushToQueue(event, notifyPayload);
313
102
  }
314
103
  }
315
104
 
316
105
  module.exports = {
317
106
  NotificationHandler,
318
- DOCUMENT_SYNC_EVENTS,
319
- DEFAULT_JOB_OPTIONS,
320
- DOCUMENT_JOB_OPTIONS,
321
107
  postMetrics
322
108
  };
@@ -1,9 +1,11 @@
1
1
  'use strict';
2
2
 
3
3
  const { metricsMeta, markRejectedAccessToken, renewRejectedAccessToken } = require('../base-client');
4
- const { isTransientNetworkError } = require('../credential-errors');
4
+ const apiRetry = require('../api-retry');
5
+ const { parseRetryAfter } = require('../../tools');
6
+ const timers = require('timers/promises');
5
7
 
6
- const { OUTLOOK_MAX_BATCH_SIZE, OUTLOOK_MAX_RETRY_ATTEMPTS, OUTLOOK_RETRY_BASE_DELAY, OUTLOOK_RETRY_MAX_DELAY } = require('../../consts');
8
+ const { OUTLOOK_MAX_BATCH_SIZE } = require('../../consts');
7
9
 
8
10
  // Maximum number of operations in a single batch request to Microsoft Graph API
9
11
  const MAX_BATCH_SIZE = OUTLOOK_MAX_BATCH_SIZE;
@@ -174,9 +176,24 @@ function handleRequestError(context, err) {
174
176
  }
175
177
  }
176
178
 
179
+ // Graph asks for a retry on these
180
+ const RETRYABLE_SERVER_STATUSES = new Set([502, 503, 504]);
181
+
182
+ // $batch items are answered one by one, so a throttled or failed item is retried on its own
183
+ const BATCH_ITEM_RETRIES = 2;
184
+
177
185
  /**
178
- * Makes authenticated requests to Microsoft Graph API with automatic retry on rate limiting
179
- * Implements exponential backoff using Retry-After header or default delays
186
+ * Whether a failed request was throttled. Graph answers throttling with a 429 only
187
+ * @param {Error} err - The error
188
+ * @returns {boolean}
189
+ */
190
+ function isRateLimitError(err) {
191
+ return err.oauthRequest?.status === 429;
192
+ }
193
+
194
+ /**
195
+ * Makes authenticated requests to Microsoft Graph API, retried under the policy of
196
+ * lib/email-client/api-retry.js
180
197
  *
181
198
  * @param {Object} context - The client context (OutlookClient instance)
182
199
  * @param {string} url - API endpoint URL
@@ -184,189 +201,193 @@ function handleRequestError(context, err) {
184
201
  * @param {*} payload - Request payload
185
202
  * @param {Object} options - Request options
186
203
  * @param {number} options.maxRetries - Maximum number of retries (default: 3)
204
+ * @param {boolean} options.noRetry - Send exactly once (sends)
187
205
  * @returns {Promise<*>} API response
188
206
  */
189
207
  async function requestWithRetry(context, url, method, payload, options = {}) {
190
- const maxRetries = options.maxRetries ?? OUTLOOK_MAX_RETRY_ATTEMPTS;
191
- let lastError;
192
-
193
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
194
- try {
195
- return await request(context, url, method, payload, options);
196
- } catch (err) {
197
- // Retry on transient network errors
198
- if (isTransientNetworkError(err) && attempt < maxRetries) {
199
- lastError = err;
200
- const delay = Math.min(OUTLOOK_RETRY_BASE_DELAY * Math.pow(2, attempt), OUTLOOK_RETRY_MAX_DELAY);
201
-
202
- context.logger.warn({
203
- msg: 'Transient network error during Graph API request, retrying',
204
- account: context.account,
205
- attempt: attempt + 1,
206
- maxRetries,
207
- delay,
208
- code: err.code,
209
- url
210
- });
211
-
212
- await new Promise(resolve => setTimeout(resolve, delay * 1000));
213
- continue;
214
- }
215
-
216
- // Only retry on 429 (rate limit) errors
217
- if (err.oauthRequest?.status !== 429 || attempt === maxRetries) {
218
- throw err;
219
- }
220
-
221
- lastError = err;
222
-
223
- // Use Retry-After header if available, otherwise use exponential backoff
224
- const retryAfter = err.retryAfter || Math.min(OUTLOOK_RETRY_BASE_DELAY * Math.pow(2, attempt), OUTLOOK_RETRY_MAX_DELAY);
225
-
226
- context.logger.debug({
227
- msg: 'Rate limited, retrying after delay',
228
- account: context.account,
229
- attempt: attempt + 1,
230
- maxRetries,
231
- retryAfterSeconds: retryAfter,
232
- url
233
- });
234
-
235
- await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
236
- }
237
- }
238
-
239
- throw lastError;
240
- }
241
-
242
- /**
243
- * Creates common headers for batch requests
244
- * @returns {Object} Headers object with Content-Type and ImmutableId preference
245
- */
246
- function getBatchHeaders() {
247
- return {
248
- 'Content-Type': 'application/json',
249
- Prefer: 'IdType="ImmutableId"'
250
- };
208
+ return await apiRetry.requestWithRetry(() => request(context, url, method, payload, options), {
209
+ context,
210
+ provider: context.oAuth2Client?.provider || 'outlook',
211
+ url,
212
+ method,
213
+ options,
214
+ isRateLimited: isRateLimitError,
215
+ serverErrorStatuses: RETRYABLE_SERVER_STATUSES
216
+ });
251
217
  }
252
218
 
253
219
  /**
254
- * Submits a batch request to the Graph API
220
+ * Submits a batch request to the Graph API through the client's own retrying method, so a
221
+ * client subclass or test double sees batch traffic the same way as every other request
255
222
  *
256
223
  * @param {Object} context - The client context (OutlookClient instance)
257
224
  * @param {Array} requests - Array of batch request items
258
225
  * @returns {Promise<Object>} Batch response with responses array
259
226
  */
260
227
  async function submitBatchRequest(context, requests) {
261
- return await requestWithRetry(context, '/$batch', 'post', { requests });
228
+ return await context.requestWithRetry('/$batch', 'post', { requests });
229
+ }
230
+
231
+ /**
232
+ * Whether a failed $batch item is worth sending again: throttled (429) or a server error
233
+ * @param {Object} response - One entry of the batch response
234
+ * @returns {boolean}
235
+ */
236
+ function isRetryableBatchItem(response) {
237
+ return response?.status === 429 || response?.status >= 500;
262
238
  }
263
239
 
264
240
  /**
265
- * Processes batch responses and categorizes them as successful or failed
241
+ * Processes batch responses and categorizes them as successful, failed or retryable
266
242
  *
267
243
  * @param {Object} responseData - The batch response from Graph API
268
244
  * @param {Map} messageMap - Map of request IDs to email IDs
269
245
  * @param {Object} logger - Logger instance
270
246
  * @param {string} account - Account identifier for logging
271
247
  * @param {string} operation - Operation name for logging (e.g., 'delete', 'update', 'move')
272
- * @returns {Object} Object with successIds and failedIds arrays
248
+ * @param {Object} [opts]
249
+ * @param {boolean} [opts.retryable] - Put throttled and 5xx items in `retryIds` instead of `failedIds`
250
+ * @returns {Object} successIds, failedIds and retryIds arrays, `bodies` (email ID to the response
251
+ * body of each successful item) and `retryAfter` (largest Retry-After of the retryable items, seconds)
273
252
  */
274
- function processBatchResponses(responseData, messageMap, logger, account, operation) {
253
+ function processBatchResponses(responseData, messageMap, logger, account, operation, opts = {}) {
275
254
  const successIds = [];
276
255
  const failedIds = [];
256
+ const retryIds = [];
257
+ const bodies = new Map();
258
+ const answered = new Set();
259
+ let retryAfter = 0;
277
260
 
278
261
  for (const response of responseData?.responses || []) {
279
- const emailId = messageMap.get(response.id);
280
- if (response?.status >= 200 && response?.status < 300) {
281
- if (emailId) {
282
- successIds.push(emailId);
283
- }
284
- } else {
285
- if (emailId) {
286
- failedIds.push(emailId);
287
- }
288
- // Log individual batch item failures for debugging
289
- logger.warn({
290
- msg: 'Batch item failed',
291
- account,
292
- operation,
293
- emailId,
294
- status: response?.status,
295
- error: response?.body?.error
296
- });
262
+ const emailId = messageMap.get(response?.id);
263
+ if (!emailId) {
264
+ continue;
265
+ }
266
+ answered.add(response.id);
267
+
268
+ if (response.status >= 200 && response.status < 300) {
269
+ successIds.push(emailId);
270
+ bodies.set(emailId, response.body);
271
+ continue;
297
272
  }
273
+
274
+ if (opts.retryable && isRetryableBatchItem(response)) {
275
+ retryIds.push(emailId);
276
+ retryAfter = Math.max(retryAfter, parseRetryAfter(response.headers) || 0);
277
+ continue;
278
+ }
279
+
280
+ failedIds.push(emailId);
281
+ // Log individual batch item failures for debugging
282
+ logger.warn({
283
+ msg: 'Batch item failed',
284
+ account,
285
+ operation,
286
+ emailId,
287
+ status: response.status,
288
+ error: response.body?.error
289
+ });
298
290
  }
299
291
 
300
- return { successIds, failedIds };
292
+ // An item the batch response does not mention at all was not processed
293
+ for (const [reqId, emailId] of messageMap) {
294
+ if (!answered.has(reqId)) {
295
+ failedIds.push(emailId);
296
+ }
297
+ }
298
+
299
+ return { successIds, failedIds, retryIds, bodies, retryAfter };
301
300
  }
302
301
 
303
302
  /**
304
- * Executes batch operations on messages with automatic chunking
303
+ * Executes batch operations on messages with automatic chunking. Items Graph throttled (429) or
304
+ * failed with a 5xx are collected from every chunk and sent again together, up to
305
+ * BATCH_ITEM_RETRIES times, after one wait per round (their largest Retry-After, or a short
306
+ * backoff, bounded like every other retry wait). They used to be logged and dropped, and the
307
+ * operation reported success for whatever was left; then each chunk waited on its own, so a
308
+ * throttled thousand-message call could sleep once per chunk per round
305
309
  *
306
310
  * @param {Object} context - The client context (OutlookClient instance)
307
311
  * @param {Array<string>} emailIds - Array of email IDs to process
308
312
  * @param {Function} formatRequest - Function that takes (emailId, requestId) and returns a batch request object
309
313
  * @param {string} operation - Operation name for logging
310
- * @returns {Promise<Array<string>>} Array of successfully processed email IDs
314
+ * @returns {Promise<Object>} successIds and failedIds arrays, and `bodies` (email ID to the
315
+ * response body of each successful item)
311
316
  */
312
317
  async function executeBatchOperation(context, emailIds, formatRequest, operation) {
313
- let batch = [];
314
318
  let idGen = 0;
315
- let successfulIds = [];
316
- const messageMap = new Map();
319
+ const successIds = [];
320
+ const failedIds = [];
321
+ const bodies = new Map();
322
+
323
+ let pending = emailIds;
324
+ for (let round = 0; pending.length; round++) {
325
+ const retryable = round < BATCH_ITEM_RETRIES;
326
+ const retryIds = [];
327
+ let retryAfter = 0;
328
+
329
+ for (let i = 0; i < pending.length; i += MAX_BATCH_SIZE) {
330
+ const messageMap = new Map();
331
+ const requests = pending.slice(i, i + MAX_BATCH_SIZE).map(emailId => {
332
+ const reqId = `msg_${++idGen}`;
333
+ messageMap.set(reqId, emailId);
334
+ return formatRequest(emailId, reqId);
335
+ });
317
336
 
318
- const submitBatch = async () => {
319
- if (batch.length === 0) {
320
- return;
337
+ let responseData;
338
+ try {
339
+ responseData = await submitBatchRequest(context, requests);
340
+ } catch (err) {
341
+ context.logger.error({
342
+ msg: 'Failed to run batch operation',
343
+ account: context.account,
344
+ operation,
345
+ err
346
+ });
347
+ throw err;
348
+ }
349
+
350
+ const result = processBatchResponses(responseData, messageMap, context.logger, context.account, operation, { retryable });
351
+
352
+ successIds.push(...result.successIds);
353
+ failedIds.push(...result.failedIds);
354
+ for (const [emailId, body] of result.bodies) {
355
+ bodies.set(emailId, body);
356
+ }
357
+ retryIds.push(...result.retryIds);
358
+ retryAfter = Math.max(retryAfter, result.retryAfter);
321
359
  }
322
360
 
323
- try {
324
- const responseData = await submitBatchRequest(context, batch);
325
- const { successIds } = processBatchResponses(responseData, messageMap, context.logger, context.account, operation);
326
- successfulIds = successfulIds.concat(successIds);
327
- } catch (err) {
328
- context.logger.error({
329
- msg: 'Failed to run batch operation',
361
+ pending = retryIds;
362
+ if (pending.length) {
363
+ const delay = apiRetry.retryDelay({ retryAfter }, round);
364
+ context.logger.warn({
365
+ msg: 'Batch items were throttled, retrying',
330
366
  account: context.account,
331
367
  operation,
332
- err
368
+ items: pending.length,
369
+ delay: Math.round(delay)
333
370
  });
334
- throw err;
335
- } finally {
336
- batch = [];
337
- messageMap.clear();
338
- }
339
- };
340
-
341
- for (const emailId of emailIds) {
342
- const reqId = `msg_${++idGen}`;
343
- messageMap.set(reqId, emailId);
344
- batch.push(formatRequest(emailId, reqId));
345
-
346
- if (batch.length >= MAX_BATCH_SIZE) {
347
- await submitBatch();
371
+ // Looked up on the module at call time, so a test can stand in for the wait
372
+ await timers.setTimeout(delay);
348
373
  }
349
374
  }
350
375
 
351
- // Submit remaining batch
352
- if (batch.length > 0) {
353
- await submitBatch();
354
- }
355
-
356
- return successfulIds;
376
+ return { successIds, failedIds, bodies };
357
377
  }
358
378
 
359
379
  module.exports = {
360
380
  // Constants
361
381
  GRAPH_ERROR_MAP,
362
382
  MAX_BATCH_SIZE,
383
+ RETRYABLE_SERVER_STATUSES,
384
+ BATCH_ITEM_RETRIES,
363
385
 
364
386
  // Request functions
365
387
  request,
366
388
  requestWithRetry,
367
389
 
368
390
  // Batch operation helpers
369
- getBatchHeaders,
370
391
  submitBatchRequest,
371
392
  processBatchResponses,
372
393
  executeBatchOperation,