emailengine-app 2.81.2 → 2.82.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.
Files changed (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  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-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -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,
@@ -24,7 +24,9 @@ function buildRawSendMailRequest(raw, oauth2UserPath) {
24
24
  // NOT application/json - Graph rejects a base64 MIME body sent as JSON
25
25
  contentType: 'text/plain',
26
26
  // sendMail answers 202 Accepted with an empty body
27
- returnText: true
27
+ returnText: true,
28
+ // never repeated, see buildStructuredSendMailRequest()
29
+ noRetry: true
28
30
  }
29
31
  };
30
32
  }
@@ -40,8 +42,10 @@ function buildStructuredSendMailRequest(messagePayload, oauth2UserPath) {
40
42
  return {
41
43
  path: `/${oauth2UserPath}/sendMail`,
42
44
  body: { message: messagePayload },
43
- // No contentType: an object body is serialized as application/json
44
- options: { returnText: true }
45
+ // No contentType: an object body is serialized as application/json. noRetry: a send is
46
+ // never repeated, not even after a 429 - a socket that drops after Graph accepted the
47
+ // message would otherwise send it again
48
+ options: { returnText: true, noRetry: true }
45
49
  };
46
50
  }
47
51
 
@@ -58,7 +62,9 @@ function buildDraftSendRequest(emailId, oauth2UserPath) {
58
62
  path: `/${oauth2UserPath}/messages/${emailId}/send`,
59
63
  // An empty Buffer keeps the request body at Content-Length: 0
60
64
  body: Buffer.alloc(0),
61
- options: { returnText: true }
65
+ // noRetry: a replayed /send after the first one was accepted answers 404 (the draft is
66
+ // gone), which reported a sent message as failed
67
+ options: { returnText: true, noRetry: true }
62
68
  };
63
69
  }
64
70