emailengine-app 2.77.0 → 2.79.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 (189) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.ncurc.js +23 -13
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +60 -0
  5. package/bin/emailengine.js +1 -1
  6. package/config/e2e.toml +2 -1
  7. package/config/test.toml +2 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +1 -1
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +145 -61
  12. package/lib/api-reference/format.js +105 -4
  13. package/lib/api-reference/index.js +24 -7
  14. package/lib/api-reference/model.js +148 -21
  15. package/lib/api-reference/schema-tree.js +282 -28
  16. package/lib/api-routes/account-routes.js +99 -36
  17. package/lib/api-routes/behavior-notes.js +3 -0
  18. package/lib/api-routes/blocklist-routes.js +21 -47
  19. package/lib/api-routes/chat-routes.js +10 -12
  20. package/lib/api-routes/delivery-test-routes.js +6 -26
  21. package/lib/api-routes/export-routes.js +2 -0
  22. package/lib/api-routes/gateway-routes.js +52 -11
  23. package/lib/api-routes/license-routes.js +2 -0
  24. package/lib/api-routes/mailbox-routes.js +29 -26
  25. package/lib/api-routes/message-routes.js +27 -21
  26. package/lib/api-routes/oauth2-app-routes.js +11 -29
  27. package/lib/api-routes/operation-impact.js +80 -0
  28. package/lib/api-routes/outbox-routes.js +15 -5
  29. package/lib/api-routes/permission-map.js +397 -0
  30. package/lib/api-routes/route-helpers.js +223 -9
  31. package/lib/api-routes/route-metadata.js +28 -0
  32. package/lib/api-routes/settings-routes.js +30 -25
  33. package/lib/api-routes/stats-routes.js +2 -2
  34. package/lib/api-routes/submit-routes.js +53 -31
  35. package/lib/api-routes/template-routes.js +3 -0
  36. package/lib/api-routes/token-routes.js +319 -33
  37. package/lib/api-routes/webhook-route-routes.js +14 -4
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/auth-token.js +80 -8
  41. package/lib/autodetect-imap-settings.js +40 -16
  42. package/lib/base32.js +30 -0
  43. package/lib/bounce-detect.js +182 -62
  44. package/lib/consts.js +10 -0
  45. package/lib/db.js +20 -2
  46. package/lib/delivery-error.js +30 -1
  47. package/lib/egress-filter.js +89 -8
  48. package/lib/email-client/base-client.js +35 -113
  49. package/lib/email-client/gmail-client.js +22 -13
  50. package/lib/email-client/imap/listing-diff.js +3 -3
  51. package/lib/email-client/imap/mailbox.js +28 -93
  52. package/lib/email-client/imap/subconnection.js +10 -7
  53. package/lib/email-client/imap/sync-operations.js +46 -46
  54. package/lib/email-client/imap-client.js +39 -28
  55. package/lib/email-client/message-builder.js +15 -15
  56. package/lib/email-client/notification-handler.js +1 -1
  57. package/lib/email-client/outlook/graph-api.js +10 -4
  58. package/lib/email-client/outlook-client.js +54 -55
  59. package/lib/email-client/smtp-pool-manager.js +1 -1
  60. package/lib/enum-descriptions.js +92 -2
  61. package/lib/export.js +2 -2
  62. package/lib/field-usage.js +133 -0
  63. package/lib/gateway.js +2 -2
  64. package/lib/get-raw-email.js +1 -1
  65. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  66. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  67. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  68. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  69. package/lib/imapproxy/imap-core/lib/imap-connection.js +17 -7
  70. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  71. package/lib/imapproxy/imap-server.js +40 -10
  72. package/lib/license-beacon.js +5 -10
  73. package/lib/lists.js +49 -1
  74. package/lib/llm-pre-process.js +6 -6
  75. package/lib/logger.js +5 -1
  76. package/lib/metrics-collector.js +2 -2
  77. package/lib/msgpack.js +62 -0
  78. package/lib/oauth/decode-jwt-payload.js +39 -0
  79. package/lib/oauth/gmail.js +9 -12
  80. package/lib/oauth/mail-ru.js +5 -7
  81. package/lib/oauth/outlook-identity.js +61 -0
  82. package/lib/oauth/outlook.js +9 -9
  83. package/lib/oauth/pubsub/google.js +25 -10
  84. package/lib/oauth/retry-setup.js +38 -0
  85. package/lib/oauth/scope-checker.js +1 -1
  86. package/lib/oauth2-apps.js +224 -295
  87. package/lib/openapi/build-document.js +15 -7
  88. package/lib/openapi/joi-schema.js +20 -0
  89. package/lib/outbox.js +145 -14
  90. package/lib/pre-process.js +9 -9
  91. package/lib/queue-stats.js +49 -0
  92. package/lib/read-env-value.js +37 -0
  93. package/lib/reconnection-manager.js +2 -2
  94. package/lib/rewrite-text-nodes.js +4 -3
  95. package/lib/routes-ui.js +4 -0
  96. package/lib/schemas.js +223 -155
  97. package/lib/settings.js +84 -5
  98. package/lib/sub-script.js +2 -1
  99. package/lib/swagger-options.js +2 -1
  100. package/lib/templates.js +5 -5
  101. package/lib/threads.js +2 -2
  102. package/lib/token-audit-log.js +208 -0
  103. package/lib/token-permission-view.js +219 -0
  104. package/lib/token-permissions.js +172 -0
  105. package/lib/tokens.js +100 -16
  106. package/lib/tools.js +259 -85
  107. package/lib/totp.js +67 -0
  108. package/lib/ui-routes/account-routes.js +122 -26
  109. package/lib/ui-routes/admin-config-routes.js +20 -17
  110. package/lib/ui-routes/admin-entities-routes.js +66 -22
  111. package/lib/ui-routes/auth-routes.js +36 -48
  112. package/lib/ui-routes/export-routes.js +10 -4
  113. package/lib/ui-routes/oauth-config-routes.js +5 -5
  114. package/lib/ui-routes/reference-routes.js +11 -8
  115. package/lib/ui-routes/route-helpers.js +79 -2
  116. package/lib/ui-routes/settings-page.js +1 -1
  117. package/lib/ui-routes/smtp-test-routes.js +1 -1
  118. package/lib/ui-routes/suppression-list-routes.js +294 -0
  119. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  120. package/lib/utils/is-email.js +34 -0
  121. package/lib/utils/network.js +2 -2
  122. package/lib/utils/to-camel-case.js +17 -0
  123. package/lib/web-safe-html.js +1 -1
  124. package/lib/webhook-egress.js +37 -0
  125. package/lib/webhook-routing.js +80 -0
  126. package/lib/webhooks.js +21 -15
  127. package/package.json +26 -27
  128. package/sbom.json +1 -0
  129. package/server.js +81 -42
  130. package/static/css/flyonui.css +1 -1
  131. package/static/css/public.css +3 -0
  132. package/static/css/src/app.tailwind.css +159 -9
  133. package/static/js/app.js +69 -0
  134. package/static/js/reference.js +741 -10
  135. package/static/js/ui.js +43 -0
  136. package/static/licenses.html +698 -1590
  137. package/translations/README.md +64 -0
  138. package/translations/de.mo +0 -0
  139. package/translations/de.po +164 -120
  140. package/translations/en.po +200 -161
  141. package/translations/et.mo +0 -0
  142. package/translations/et.po +163 -120
  143. package/translations/fr.mo +0 -0
  144. package/translations/fr.po +163 -120
  145. package/translations/ja.mo +0 -0
  146. package/translations/ja.po +163 -120
  147. package/translations/messages.pot +94 -64
  148. package/translations/nl.mo +0 -0
  149. package/translations/nl.po +164 -120
  150. package/translations/pl.mo +0 -0
  151. package/translations/pl.po +163 -120
  152. package/views/account-identity-error.hbs +34 -0
  153. package/views/accounts/account.hbs +69 -7
  154. package/views/accounts/browse.hbs +18 -35
  155. package/views/accounts/edit.hbs +1 -0
  156. package/views/accounts/register/imap.hbs +12 -2
  157. package/views/config/logging.hbs +6 -0
  158. package/views/config/oauth/app.hbs +0 -2
  159. package/views/config/security.hbs +13 -0
  160. package/views/layout/app.hbs +29 -5
  161. package/views/oauth-scope-error.hbs +1 -1
  162. package/views/partials/oauth_form.hbs +0 -15
  163. package/views/partials/reference/disclosure.hbs +8 -2
  164. package/views/partials/reference/nav.hbs +36 -9
  165. package/views/partials/reference/operation.hbs +48 -14
  166. package/views/partials/reference/params.hbs +17 -1
  167. package/views/partials/reference/schema-node.hbs +112 -54
  168. package/views/partials/reference/schema-tools.hbs +25 -0
  169. package/views/partials/reference/token-alert.hbs +35 -10
  170. package/views/partials/reference/try-it.hbs +84 -11
  171. package/views/partials/side_menu.hbs +1 -0
  172. package/views/partials/ui/checkbox.hbs +2 -2
  173. package/views/partials/ui/tabs.hbs +7 -1
  174. package/views/reference/index.hbs +1 -1
  175. package/views/reference/token.hbs +4 -0
  176. package/views/suppression-lists/index.hbs +85 -0
  177. package/views/suppression-lists/list.hbs +87 -0
  178. package/views/templates/index.hbs +8 -2
  179. package/views/tokens/index.hbs +31 -4
  180. package/views/tokens/new.hbs +324 -2
  181. package/workers/api.js +299 -140
  182. package/workers/documents.js +46 -26
  183. package/workers/export.js +20 -8
  184. package/workers/imap-proxy.js +2 -2
  185. package/workers/imap.js +13 -7
  186. package/workers/smtp.js +13 -7
  187. package/workers/submit.js +41 -31
  188. package/workers/webhooks.js +60 -37
  189. package/lib/feature-flags.js +0 -48
@@ -9,6 +9,7 @@ const settings = require('../lib/settings');
9
9
  const crypto = require('crypto');
10
10
 
11
11
  const { readEnvValue, threadStats, getDuration } = require('../lib/tools');
12
+ const { isFinalFailedAttempt } = require('../lib/delivery-error');
12
13
 
13
14
  const GB_COLLECT_DELAY = 6 * 3600 * 1000; // 6h
14
15
  const GB_FAILURE_DELAY = 3 * 1000;
@@ -189,7 +190,7 @@ const documentsWorker = new Worker(
189
190
  });
190
191
  deletedCount += deleteResult[indexName].deleted || 0;
191
192
  } catch (err) {
192
- logger.error({
193
+ logger.warn({
193
194
  msg: 'Failed to delete account emails from index',
194
195
  action: 'document',
195
196
  queue: job.queue.name,
@@ -254,7 +255,7 @@ const documentsWorker = new Worker(
254
255
  query: filterQuery
255
256
  });
256
257
  } catch (err) {
257
- logger.error({
258
+ logger.warn({
258
259
  msg: 'Failed to delete messages from a mailbox',
259
260
  action: 'document',
260
261
  queue: job.queue.name,
@@ -305,15 +306,15 @@ const documentsWorker = new Worker(
305
306
  .exec();
306
307
 
307
308
  if (err1) {
308
- logger.trace({ msg: 'Failed checking tombstone', key: tombstoneTdy, err: err1 });
309
+ logger.trace({ msg: 'Failed to check tombstone', key: tombstoneTdy, err: err1 });
309
310
  }
310
311
 
311
312
  if (err2) {
312
- logger.trace({ msg: 'Failed checking tombstone', key: tombstoneYdy, err: err2 });
313
+ logger.trace({ msg: 'Failed to check tombstone', key: tombstoneYdy, err: err2 });
313
314
  }
314
315
 
315
316
  if (isDeleted1 || isDeleted2) {
316
- logger.info({
317
+ logger.debug({
317
318
  msg: 'Skipped deleted email',
318
319
  action: 'document',
319
320
  queue: job.queue.name,
@@ -419,7 +420,7 @@ const documentsWorker = new Worker(
419
420
  throw new Error('Empty index response');
420
421
  }
421
422
  } catch (err) {
422
- logger.error({
423
+ logger.warn({
423
424
  msg: 'Failed to index new email',
424
425
  action: 'document',
425
426
  queue: job.queue.name,
@@ -428,7 +429,7 @@ const documentsWorker = new Worker(
428
429
  event: job.name,
429
430
  account: job.data.account,
430
431
  entryId: messageId,
431
- request: { index, id: `${job.data.account}:${messageId}`, document: messageData },
432
+ request: { index, id: `${job.data.account}:${messageId}` },
432
433
  err
433
434
  });
434
435
  throw err;
@@ -550,8 +551,9 @@ const documentsWorker = new Worker(
550
551
  });
551
552
  storedEmbeddings = false;
552
553
  } else {
553
- logger.info({
554
+ logger.debug({
554
555
  msg: 'Stored embeddings for a message',
556
+ account: job.data.account,
555
557
  messageId: messageData.messageId,
556
558
  items: bulkResponse.items?.length
557
559
  });
@@ -568,7 +570,7 @@ const documentsWorker = new Worker(
568
570
  }
569
571
  }
570
572
  } else {
571
- logger.info({ msg: 'Skipped embeddings, already exist', account: job.data.account, messageId: messageData.messageId });
573
+ logger.debug({ msg: 'Skipped embeddings, already exist', account: job.data.account, messageId: messageData.messageId });
572
574
  storedEmbeddings = false;
573
575
  }
574
576
  }
@@ -654,7 +656,7 @@ const documentsWorker = new Worker(
654
656
 
655
657
  break;
656
658
  default:
657
- logger.error({
659
+ logger.warn({
658
660
  msg: 'Failed to delete email',
659
661
  action: 'document',
660
662
  queue: job.queue.name,
@@ -753,7 +755,7 @@ ${Object.keys(params)
753
755
  updateResult = Object.assign({ failed: true }, err.meta.body);
754
756
  break;
755
757
  default:
756
- logger.error({
758
+ logger.warn({
757
759
  msg: 'Failed to update email',
758
760
  action: 'document',
759
761
  queue: job.queue.name,
@@ -856,7 +858,7 @@ if( ctx._source.bounces != null) {
856
858
  updateResult = Object.assign({ failed: true }, err.meta.body);
857
859
  break;
858
860
  default:
859
- logger.error({
861
+ logger.warn({
860
862
  msg: 'Failed to update email',
861
863
  action: 'document',
862
864
  queue: job.queue.name,
@@ -913,7 +915,7 @@ documentsWorker.on('completed', async job => {
913
915
  status: 'completed'
914
916
  });
915
917
 
916
- logger.info({
918
+ logger.debug({
917
919
  msg: 'Document queue entry completed',
918
920
  action: 'document',
919
921
  queue: job.queue.name,
@@ -923,19 +925,23 @@ documentsWorker.on('completed', async job => {
923
925
  });
924
926
  });
925
927
 
926
- documentsWorker.on('failed', async job => {
928
+ documentsWorker.on('failed', async (job, err) => {
927
929
  metrics(logger, 'queuesProcessed', 'inc', {
928
- queue: 'document',
930
+ queue: 'documents',
929
931
  status: 'failed'
930
932
  });
931
933
 
932
- logger.info({
934
+ let isFinal = isFinalFailedAttempt(job);
935
+
936
+ logger[isFinal ? 'error' : 'debug']({
933
937
  msg: 'Document queue entry failed',
934
938
  action: 'document',
935
939
  queue: job.queue.name,
936
940
  code: 'failed',
937
941
  job: job.id,
942
+ event: job.name,
938
943
  account: job.data.account,
944
+ err,
939
945
 
940
946
  failedReason: job.failedReason,
941
947
  stacktrace: job.stacktrace,
@@ -991,7 +997,12 @@ const clearExpungedEmbeddings = async () => {
991
997
 
992
998
  const { index, client } = await getESClient(logger);
993
999
  if (!client) {
994
- // Document store not enabled
1000
+ // Document store not enabled. Returning bare would spin, because the collector
1001
+ // re-invokes itself as soon as this resolves and the queue is not empty.
1002
+ await new Promise(resolve => {
1003
+ let timer = setTimeout(resolve, GB_EMPTY_DELAY);
1004
+ timer.unref();
1005
+ });
995
1006
  return;
996
1007
  }
997
1008
 
@@ -1005,12 +1016,6 @@ const clearExpungedEmbeddings = async () => {
1005
1016
  });
1006
1017
 
1007
1018
  if (!existingResult || !existingResult.hits) {
1008
- logger.error({
1009
- msg: 'Failed to run query to find emails by Message-ID. Empty result.',
1010
- account,
1011
- messageId,
1012
- existingResult
1013
- });
1014
1019
  throw new Error('Empty result');
1015
1020
  }
1016
1021
  } catch (err) {
@@ -1067,12 +1072,18 @@ const clearExpungedEmbeddings = async () => {
1067
1072
  messageId
1068
1073
  });
1069
1074
  } catch (err) {
1070
- logger.info({
1071
- msg: 'Dailed to delete embeddings for a missing email',
1075
+ // The zrem that retires this entry sits after the delete, so a failure
1076
+ // leaves it at the head of the queue. Push it back instead of retrying
1077
+ // straight away, otherwise a permanently failing entry (a missing
1078
+ // .embeddings index, say) blocks every other entry and re-logs on every
1079
+ // pass of the collector.
1080
+ logger.warn({
1081
+ msg: 'Failed to delete embeddings for a missing email',
1072
1082
  account,
1073
1083
  messageId,
1074
1084
  err
1075
1085
  });
1086
+ await redis.zadd(`${REDIS_PREFIX}expungequeue`, Date.now(), expungedEntry);
1076
1087
  }
1077
1088
  } else {
1078
1089
  // clear existing entry
@@ -1083,10 +1094,19 @@ const clearExpungedEmbeddings = async () => {
1083
1094
  messageId
1084
1095
  });
1085
1096
  }
1097
+ } else {
1098
+ // A member that does not split into both halves can never be processed. Retire it
1099
+ // rather than fall through, because the collector re-invokes itself immediately and
1100
+ // this entry would otherwise stay at the head of the queue and pin the loop.
1101
+ logger.warn({ msg: 'Removing malformed expunge queue entry', entry: expungedEntry });
1102
+ await redis.zrem(`${REDIS_PREFIX}expungequeue`, expungedEntry);
1086
1103
  }
1087
1104
  }
1088
1105
  } catch (err) {
1089
- logger.error({ msg: 'Failed to retrieve expunged entries', rangeStart: 0, rangeEnd, err });
1106
+ // The collector re-runs itself immediately, so this pass repeats every GB_FAILURE_DELAY for
1107
+ // as long as the failure lasts. Keep it visible: nothing else reports that embedding
1108
+ // cleanup has stopped making progress.
1109
+ logger.warn({ msg: 'Failed to retrieve expunged entries', rangeStart: 0, rangeEnd, err });
1090
1110
  await new Promise(resolve => {
1091
1111
  let timer = setTimeout(resolve, GB_FAILURE_DELAY);
1092
1112
  timer.unref();
package/workers/export.js CHANGED
@@ -658,8 +658,7 @@ async function exportMessages(job, exportData) {
658
658
  attempt,
659
659
  maxAttempts: IMAP_MESSAGE_MAX_RETRIES,
660
660
  delayMs: delay,
661
- errorCode: err.code,
662
- errorMessage: err.message
661
+ err
663
662
  });
664
663
  await new Promise(resolve => setTimeout(resolve, delay));
665
664
  continue;
@@ -785,7 +784,13 @@ const exportWorker = new Worker(
785
784
 
786
785
  logger.info({ msg: 'Export job completed', account, exportId, duration: Date.now() - startTime });
787
786
  } catch (err) {
788
- logger.error({ msg: 'Export job failed', account, exportId, err });
787
+ // a user-requested cancellation or a deleted account is not an operational failure
788
+ let failLevel = err.code === 'ExportCancelled' ? 'info' : err.code === 'AccountDeleted' ? 'warn' : 'error';
789
+ logger[failLevel]({ msg: 'Export job failed', account, exportId, err });
790
+
791
+ // Tells the 'failed' handler that this failure has already been reported with full
792
+ // context. Failures that never reach this catch (see that handler) have not been.
793
+ job.__failureLogged = true;
789
794
 
790
795
  const exportData = await redis.hgetall(`${REDIS_PREFIX}exp:${account}:${exportId}`).catch(() => ({}));
791
796
 
@@ -834,22 +839,29 @@ const exportWorker = new Worker(
834
839
 
835
840
  exportWorker.on('completed', async job => {
836
841
  metrics(logger, 'queuesProcessed', 'inc', { queue: 'export', status: 'completed' });
837
- logger.info({ msg: 'Export queue entry completed', queue: job.queue.name, job: job.id, account: job.data.account, exportId: job.data.exportId });
842
+ logger.debug({ msg: 'Export queue entry completed', queue: job.queue.name, job: job.id, account: job.data.account, exportId: job.data.exportId });
838
843
  });
839
844
 
840
845
  exportWorker.on('failed', async (job, err) => {
841
846
  metrics(logger, 'queuesProcessed', 'inc', { queue: 'export', status: 'failed' });
842
847
  if (!job) {
843
- logger.error({ msg: 'Export queue entry failed', err: err.message });
848
+ logger.error({ msg: 'Export queue entry failed', err });
844
849
  return;
845
850
  }
846
- logger.error({
851
+ // A stalled job (worker killed mid-export, lock lost) is failed by BullMQ through its
852
+ // deferred-failure path, which skips the processor entirely - so its catch never logged the
853
+ // failure and never ran Export.fail(). That leaves a dead export recoverable only by the
854
+ // startup pass, and this event is the sole record of it. Anything the processor did report is
855
+ // demoted to debug to avoid logging the same failure twice.
856
+ let level = job.__failureLogged ? 'debug' : 'error';
857
+ logger[level]({
847
858
  msg: 'Export queue entry failed',
848
859
  queue: job.queue.name,
849
860
  job: job.id,
850
861
  account: job.data.account,
851
862
  exportId: job.data.exportId,
852
- failedReason: job.failedReason
863
+ failedReason: job.failedReason,
864
+ reachedProcessor: !!job.__failureLogged
853
865
  });
854
866
  });
855
867
 
@@ -969,4 +981,4 @@ parentPort.on('message', message => {
969
981
  }
970
982
  });
971
983
 
972
- logger.info({ msg: 'Started export worker thread', version: packageData.version });
984
+ logger.info({ msg: 'Started Export worker thread', version: packageData.version });
@@ -59,13 +59,13 @@ parentPort.on('message', message => {
59
59
  run()
60
60
  .then(imapServer => {
61
61
  let address = imapServer.server.address();
62
- logger.debug({
62
+ logger.info({
63
63
  msg: 'Started IMAP proxy server thread',
64
64
  address,
65
65
  version: packageData.version
66
66
  });
67
67
  })
68
68
  .catch(err => {
69
- logger.error({ msg: 'Failed to initialize IMAP server', err });
69
+ logger.fatal({ msg: 'Failed to initialize IMAP proxy server', err });
70
70
  logger.flush(() => process.exit(3));
71
71
  });
package/workers/imap.js CHANGED
@@ -23,7 +23,7 @@ const { MessagePortWritable, pipeToMessagePort } = require('../lib/message-port-
23
23
  const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
24
24
  const { getESClient } = require('../lib/document-store');
25
25
  const settings = require('../lib/settings');
26
- const msgpack = require('msgpack5')();
26
+ const msgpack = require('../lib/msgpack');
27
27
 
28
28
  const getSecret = require('../lib/get-secret');
29
29
 
@@ -187,7 +187,7 @@ class ConnectionHandler {
187
187
  }
188
188
 
189
189
  async assignConnection(account, runIndex, initOpts) {
190
- logger.info({ msg: 'Assigned account to worker', account });
190
+ logger.debug({ msg: 'Assigned account to worker', account });
191
191
 
192
192
  if (!this.runIndex) {
193
193
  this.runIndex = runIndex;
@@ -306,7 +306,7 @@ class ConnectionHandler {
306
306
 
307
307
  // do not wait before returning as it may take forever
308
308
  accountObject.connection.init(initOpts).catch(err => {
309
- logger.error({ account, err });
309
+ logger.error({ msg: 'Failed to initialize account connection', account, err });
310
310
  });
311
311
  }
312
312
 
@@ -322,7 +322,7 @@ class ConnectionHandler {
322
322
  }
323
323
 
324
324
  async updateConnection(account) {
325
- logger.info({ msg: 'Account reconnect requested', account });
325
+ logger.info({ msg: 'Account update requested', account });
326
326
  if (this.accounts.has(account)) {
327
327
  let accountObject = this.accounts.get(account);
328
328
  if (accountObject.connection) {
@@ -330,7 +330,7 @@ class ConnectionHandler {
330
330
  level: 'info',
331
331
  t: Date.now(),
332
332
  cid: accountObject.connection.cid,
333
- msg: 'Account reconnect requested'
333
+ msg: 'Account update requested'
334
334
  });
335
335
 
336
336
  let state = 'connecting';
@@ -1031,7 +1031,13 @@ parentPort.on('message', message => {
1031
1031
  if (message.message && message.message.data && message.message.data.raw) {
1032
1032
  message.message.data.raw = message.message.data.raw.length;
1033
1033
  }
1034
- logger.error(Object.assign({ msg: 'Command failed' }, message, { err }));
1034
+ // Anything with a client-facing status (404 not found, 503 no active handler) is
1035
+ // reported back to the caller as the command response, so it is not a server fault.
1036
+ // 503 is excluded from the error branch on purpose: both "no active handler" and
1037
+ // IMAPConnectionClosing carry it, and a worker taking over accounts answers every
1038
+ // in-flight command with one until the reassignment settles.
1039
+ let isServerFault = !err.statusCode || (err.statusCode >= 500 && err.statusCode !== 503);
1040
+ logger[isServerFault ? 'error' : 'debug'](Object.assign({ msg: 'Command failed' }, message, { err }));
1035
1041
  parentPort.postMessage(Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err)));
1036
1042
  });
1037
1043
  }
@@ -1044,6 +1050,6 @@ parentPort.on('message', message => {
1044
1050
  // server.js instead; see onCommand().
1045
1051
 
1046
1052
  main().catch(err => {
1047
- logger.fatal({ msg: 'Execution failed', err });
1053
+ logger.fatal({ msg: 'IMAP worker startup failed', err });
1048
1054
  logger.flush(() => process.exit(6));
1049
1055
  });
package/workers/smtp.js CHANGED
@@ -124,10 +124,10 @@ async function checkAccountData(session, messageMeta) {
124
124
  accountData = await accountObject.loadAccountData();
125
125
  if (accountData) {
126
126
  ACCOUNT_CACHE.set(session, accountObject);
127
- logger.info({ msg: 'Resolved requested account', account: messageMeta.requestedAccount });
127
+ logger.debug({ msg: 'Resolved requested account', account: messageMeta.requestedAccount });
128
128
  }
129
129
  } catch (err) {
130
- logger.error({ msg: 'Failed resolving requested account', account: messageMeta.requestedAccount, err });
130
+ logger.warn({ msg: 'Failed to resolve requested account', account: messageMeta.requestedAccount, err });
131
131
  }
132
132
  } else {
133
133
  accountObject = ACCOUNT_CACHE.get(session);
@@ -254,7 +254,7 @@ async function init() {
254
254
 
255
255
  logger.info({
256
256
  msg: 'Message queued',
257
- account: session.user,
257
+ account: accountObject.account,
258
258
  messageId: res.messageId,
259
259
  sendAt: res.sendAt,
260
260
  queueId: res.queueId,
@@ -267,7 +267,13 @@ async function init() {
267
267
  metrics(logger, 'events', 'inc', {
268
268
  event: 'smtpSubmitFail'
269
269
  });
270
- logger.error({ msg: 'Failed to submit message', account: session.user, err });
270
+ // a responseCode means the submission was refused with an SMTP reply,
271
+ // which is a client-caused rejection rather than a server fault
272
+ logger[err.responseCode ? 'warn' : 'error']({
273
+ msg: 'Failed to submit message',
274
+ account: session.user || messageMeta.requestedAccount,
275
+ err
276
+ });
271
277
  callback(err);
272
278
  });
273
279
  };
@@ -315,7 +321,7 @@ async function init() {
315
321
  return;
316
322
  }
317
323
  logger.error({
318
- msg: 'SMTP Server Error',
324
+ msg: 'SMTP server error',
319
325
  err
320
326
  });
321
327
  });
@@ -398,13 +404,13 @@ parentPort.on('message', message => {
398
404
  init()
399
405
  .then(smtpServer => {
400
406
  let address = smtpServer.server.address();
401
- logger.debug({
407
+ logger.info({
402
408
  msg: 'Started SMTP server thread',
403
409
  address,
404
410
  version: packageData.version
405
411
  });
406
412
  })
407
413
  .catch(err => {
408
- logger.error({ msg: 'Failed to initialize SMTP', err });
414
+ logger.fatal({ msg: 'Failed to initialize SMTP server', err });
409
415
  logger.flush(() => process.exit(3));
410
416
  });
package/workers/submit.js CHANGED
@@ -16,10 +16,10 @@ initSentry('submit');
16
16
 
17
17
  const util = require('util');
18
18
  const { redis, queueConf, submitQueue } = require('../lib/db');
19
- const { Worker } = require('bullmq');
19
+ const { Worker, UnrecoverableError } = require('bullmq');
20
20
  const { Account } = require('../lib/account');
21
21
  const getSecret = require('../lib/get-secret');
22
- const msgpack = require('msgpack5')();
22
+ const msgpack = require('../lib/msgpack');
23
23
 
24
24
  const { EMAIL_FAILED_NOTIFY } = require('../lib/consts');
25
25
 
@@ -42,7 +42,7 @@ const SUBMIT_QC = (readEnvValue('EENGINE_SUBMIT_QC') && Number(readEnvValue('EEN
42
42
 
43
43
  const SUBMIT_DELAY = getDuration(readEnvValue('EENGINE_SUBMIT_DELAY') || config.submitDelay) || null;
44
44
 
45
- const { shouldDiscardJob } = require('../lib/delivery-error');
45
+ const { shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
46
46
  const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
47
47
 
48
48
  let callQueue = new Map();
@@ -157,7 +157,7 @@ const submitWorker = new Worker(
157
157
  try {
158
158
  queueEntry = msgpack.decode(queueEntryBuf);
159
159
  } catch (err) {
160
- logger.error({ msg: 'Failed to parse queued email entry', job: job.data, err });
160
+ logger.error({ msg: 'Failed to parse queued email entry', job: job.id, account: job.data.account, queueId: job.data.queueId, err });
161
161
  try {
162
162
  await redis.hdel(`${REDIS_PREFIX}iaq:${job.data.account}`, job.data.queueId);
163
163
  } catch (err) {
@@ -197,7 +197,7 @@ const submitWorker = new Worker(
197
197
  let backoffDelay = Number(job.opts.backoff && job.opts.backoff.delay) || 0;
198
198
  // job.attemptsMade is not yet incremented for the ongoing attempt, so the
199
199
  // next retry (if this attempt fails) is delayed by 2^attemptsMade * base
200
- let nextAttempt = job.attemptsMade + 1 < job.opts.attempts ? Math.round(job.processedOn + Math.pow(2, job.attemptsMade) * backoffDelay) : false;
200
+ let nextAttempt = !willBeFinalAttempt(job) ? Math.round(job.processedOn + Math.pow(2, job.attemptsMade) * backoffDelay) : false;
201
201
 
202
202
  queueEntry.job = {
203
203
  id: job.id,
@@ -248,13 +248,17 @@ const submitWorker = new Worker(
248
248
  }
249
249
  } catch (err) {
250
250
  logger.error({
251
- msg: 'Job listing failed',
251
+ msg: 'Failed to fetch job status',
252
252
  job: job.id,
253
+ account: job.data.account,
253
254
  err
254
255
  });
255
256
  }
256
257
 
257
- logger.error({
258
+ const discardJob = shouldDiscardJob(err, job);
259
+ const isFinalAttempt = discardJob || willBeFinalAttempt(job);
260
+
261
+ logger[isFinalAttempt ? 'error' : 'warn']({
258
262
  msg: 'Message submission failed',
259
263
  action: 'submit',
260
264
  queue: job.queue.name,
@@ -281,28 +285,30 @@ const submitWorker = new Worker(
281
285
  // ignore
282
286
  }
283
287
 
284
- if (shouldDiscardJob(err, job)) {
285
- try {
286
- // do not retry after 5xx error (except 503 which is transient)
287
- await job.discard();
288
- logger.info({
289
- msg: 'Job discarded',
290
- account: queueEntry.account,
291
- queueId: job.data.queueId
292
- });
293
- } catch (E) {
294
- logger.error({
295
- msg: 'Failed to discard job',
296
- action: 'submit',
297
- queue: job.queue.name,
298
- code: 'discard_fail',
299
- job: job.id,
300
- event: job.name,
301
- data: job.data,
302
- account: job.data.account,
303
- err: E
304
- });
305
- }
288
+ if (discardJob) {
289
+ // Do not retry after a permanent rejection (5xx except 503, which is transient).
290
+ // BullMQ 6 removed Job#discard(), so the way to end a job before its attempts are
291
+ // spent is to throw UnrecoverableError. The stack is carried over because the
292
+ // 'failed' handler reports job.stacktrace[0] as the error in the failure webhook -
293
+ // constructing a bare UnrecoverableError would replace the SMTP reason with
294
+ // "UnrecoverableError" there.
295
+ let unrecoverableErr = new UnrecoverableError(err.message);
296
+ unrecoverableErr.stack = err.stack;
297
+ unrecoverableErr.code = err.code;
298
+ unrecoverableErr.responseCode = err.responseCode;
299
+ unrecoverableErr.statusCode = err.statusCode;
300
+
301
+ logger.info({
302
+ msg: 'Job discarded',
303
+ job: job.id,
304
+ account: queueEntry.account,
305
+ queueId: job.data.queueId,
306
+ messageId: job.data.messageId,
307
+ errorCode: err.code,
308
+ responseCode: err.responseCode
309
+ });
310
+
311
+ throw unrecoverableErr;
306
312
  }
307
313
 
308
314
  throw err;
@@ -369,7 +375,9 @@ submitWorker.on('failed', async job => {
369
375
  status: 'failed'
370
376
  });
371
377
 
372
- if (job.finishedOn || job.discarded) {
378
+ // BullMQ sets finishedOn only when the job is done for good, which covers both exhausting its
379
+ // attempts and being ended early by the UnrecoverableError thrown for a permanent rejection.
380
+ if (job.finishedOn) {
373
381
  // this was final attempt, remove it
374
382
  if (!job.data.queueId && job.data.qId) {
375
383
  // this value was used to be called qId
@@ -403,7 +411,9 @@ submitWorker.on('failed', async job => {
403
411
  }
404
412
  }
405
413
 
406
- logger.info({
414
+ let isFinal = isFinalFailedAttempt(job);
415
+
416
+ logger[isFinal ? 'error' : 'debug']({
407
417
  msg: 'Submission queue entry failed',
408
418
  action: 'submit',
409
419
  queue: job.queue.name,