emailengine-app 2.78.0 → 2.79.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 (155) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +68 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +112 -36
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +401 -0
  24. package/lib/api-routes/route-helpers.js +294 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +66 -38
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +526 -72
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/arf-detect.js +17 -4
  33. package/lib/auth-token.js +80 -8
  34. package/lib/bounce-detect.js +28 -17
  35. package/lib/consts.js +16 -0
  36. package/lib/db.js +26 -2
  37. package/lib/delivery-error.js +30 -1
  38. package/lib/email-client/base-client.js +27 -41
  39. package/lib/email-client/gmail-client.js +23 -17
  40. package/lib/email-client/imap/mailbox.js +58 -59
  41. package/lib/email-client/imap/subconnection.js +10 -7
  42. package/lib/email-client/imap/sync-operations.js +46 -46
  43. package/lib/email-client/imap-client.js +85 -28
  44. package/lib/email-client/message-builder.js +3 -3
  45. package/lib/email-client/notification-handler.js +1 -1
  46. package/lib/email-client/outlook/graph-api.js +10 -4
  47. package/lib/email-client/outlook-client.js +56 -64
  48. package/lib/email-client/smtp-pool-manager.js +1 -1
  49. package/lib/enum-descriptions.js +92 -2
  50. package/lib/export.js +1 -1
  51. package/lib/field-usage.js +133 -0
  52. package/lib/gateway.js +1 -1
  53. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  54. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  55. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  57. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  58. package/lib/imapproxy/imap-server.js +27 -7
  59. package/lib/license-beacon.js +4 -9
  60. package/lib/lists.js +49 -1
  61. package/lib/llm-pre-process.js +5 -5
  62. package/lib/logger.js +5 -1
  63. package/lib/lua/h-set-new-mark.lua +36 -0
  64. package/lib/message-port-stream.js +84 -1
  65. package/lib/metrics-collector.js +2 -2
  66. package/lib/oauth/gmail.js +9 -12
  67. package/lib/oauth/mail-ru.js +5 -7
  68. package/lib/oauth/outlook.js +9 -9
  69. package/lib/oauth/pubsub/google.js +25 -10
  70. package/lib/oauth/scope-checker.js +1 -1
  71. package/lib/oauth2-apps.js +290 -292
  72. package/lib/openapi/build-document.js +20 -8
  73. package/lib/openapi/joi-schema.js +20 -0
  74. package/lib/outbox.js +85 -17
  75. package/lib/pre-process.js +8 -8
  76. package/lib/queue-stats.js +49 -0
  77. package/lib/read-env-value.js +1 -1
  78. package/lib/reconnection-manager.js +2 -2
  79. package/lib/rewrite-text-nodes.js +4 -3
  80. package/lib/routes-ui.js +4 -0
  81. package/lib/schemas.js +218 -162
  82. package/lib/settings.js +98 -5
  83. package/lib/sub-script.js +2 -1
  84. package/lib/swagger-options.js +2 -1
  85. package/lib/templates.js +4 -4
  86. package/lib/threads.js +2 -2
  87. package/lib/token-audit-log.js +231 -0
  88. package/lib/token-permission-view.js +219 -0
  89. package/lib/token-permissions.js +172 -0
  90. package/lib/tokens.js +247 -66
  91. package/lib/tools.js +142 -37
  92. package/lib/ui-routes/account-routes.js +42 -15
  93. package/lib/ui-routes/admin-config-routes.js +18 -10
  94. package/lib/ui-routes/admin-entities-routes.js +117 -38
  95. package/lib/ui-routes/auth-routes.js +30 -24
  96. package/lib/ui-routes/export-routes.js +10 -4
  97. package/lib/ui-routes/oauth-config-routes.js +12 -12
  98. package/lib/ui-routes/reference-routes.js +3 -3
  99. package/lib/ui-routes/route-helpers.js +78 -2
  100. package/lib/ui-routes/settings-page.js +1 -1
  101. package/lib/ui-routes/smtp-test-routes.js +1 -1
  102. package/lib/ui-routes/suppression-list-routes.js +299 -0
  103. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  104. package/lib/utils/decode-headers.js +42 -0
  105. package/lib/utils/header-map.js +48 -0
  106. package/lib/utils/network.js +2 -2
  107. package/lib/utils/unsafe-key.js +59 -0
  108. package/lib/web-safe-html.js +1 -1
  109. package/lib/webhook-routing.js +84 -0
  110. package/lib/webhooks.js +48 -14
  111. package/package.json +11 -10
  112. package/sbom.json +1 -1
  113. package/server.js +116 -55
  114. package/static/css/flyonui.css +1 -1
  115. package/static/css/src/app.tailwind.css +136 -9
  116. package/static/js/reference.js +456 -10
  117. package/static/js/ui.js +43 -0
  118. package/static/licenses.html +51 -41
  119. package/translations/messages.pot +59 -59
  120. package/views/accounts/account.hbs +75 -13
  121. package/views/accounts/browse.hbs +19 -36
  122. package/views/accounts/edit.hbs +2 -2
  123. package/views/config/logging.hbs +6 -0
  124. package/views/config/oauth/app.hbs +0 -2
  125. package/views/config/security.hbs +13 -0
  126. package/views/gateways/edit.hbs +1 -1
  127. package/views/gateways/gateway.hbs +2 -2
  128. package/views/gateways/index.hbs +7 -7
  129. package/views/partials/accounts_table.hbs +7 -7
  130. package/views/partials/oauth_form.hbs +0 -15
  131. package/views/partials/reference/disclosure.hbs +8 -2
  132. package/views/partials/reference/operation.hbs +47 -13
  133. package/views/partials/reference/params.hbs +17 -1
  134. package/views/partials/reference/schema-node.hbs +110 -52
  135. package/views/partials/reference/schema-tools.hbs +25 -0
  136. package/views/partials/reference/try-it.hbs +84 -11
  137. package/views/partials/side_menu.hbs +1 -0
  138. package/views/partials/ui/checkbox.hbs +2 -2
  139. package/views/partials/ui/tabs.hbs +7 -1
  140. package/views/reference/token.hbs +4 -0
  141. package/views/suppression-lists/index.hbs +85 -0
  142. package/views/suppression-lists/list.hbs +87 -0
  143. package/views/templates/index.hbs +10 -4
  144. package/views/templates/template.hbs +1 -1
  145. package/views/tokens/index.hbs +53 -6
  146. package/views/tokens/new.hbs +334 -5
  147. package/workers/api.js +185 -102
  148. package/workers/documents.js +46 -26
  149. package/workers/export.js +20 -8
  150. package/workers/imap-proxy.js +2 -2
  151. package/workers/imap.js +77 -78
  152. package/workers/smtp.js +13 -7
  153. package/workers/submit.js +40 -30
  154. package/workers/webhooks.js +80 -26
  155. 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
@@ -19,7 +19,7 @@ const { BaseClient } = require('../lib/email-client/base-client');
19
19
  const { Account } = require('../lib/account');
20
20
  const { oauth2Apps, isApiBasedApp } = require('../lib/oauth2-apps');
21
21
  const { redis, notifyQueue, submitQueue, documentsQueue, getFlowProducer } = require('../lib/db');
22
- const { MessagePortWritable, pipeToMessagePort } = require('../lib/message-port-stream');
22
+ const { sendToMessagePort, MessagePortWritable } = require('../lib/message-port-stream');
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');
@@ -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';
@@ -741,89 +741,82 @@ class ConnectionHandler {
741
741
  }
742
742
 
743
743
  async getRawMessage(message) {
744
- if (!this.accounts.has(message.account)) {
745
- throw NO_ACTIVE_HANDLER_RESP_ERR;
746
- }
744
+ // Built before the fetch rather than after it: the fetch can take minutes, and a consumer
745
+ // whose thread dies in the meantime closes the port with nothing queued, which only reaches
746
+ // a listener that was already attached. See the MessagePortWritable constructor.
747
+ const writable = new MessagePortWritable(message.port);
748
+ try {
749
+ if (!this.accounts.has(message.account)) {
750
+ throw NO_ACTIVE_HANDLER_RESP_ERR;
751
+ }
747
752
 
748
- let accountData = this.accounts.get(message.account);
749
- if (!accountData.connection) {
750
- throw NO_ACTIVE_HANDLER_RESP_ERR;
751
- }
752
- let source = await accountData.connection.getRawMessage(message.message);
753
- if (!source) {
754
- let err = new Error('Requested file not found');
755
- err.statusCode = 404;
753
+ let accountData = this.accounts.get(message.account);
754
+ if (!accountData.connection) {
755
+ throw NO_ACTIVE_HANDLER_RESP_ERR;
756
+ }
757
+ let source = await accountData.connection.getRawMessage(message.message);
758
+ if (!source) {
759
+ let err = new Error('Requested file not found');
760
+ err.statusCode = 404;
761
+ throw err;
762
+ }
763
+
764
+ sendToMessagePort(writable, source, accountData.connection.logger);
765
+
766
+ return {
767
+ headers: {
768
+ 'content-type': 'message/rfc822',
769
+ 'content-disposition': `attachment; filename=message.eml`
770
+ },
771
+ contentType: 'message/rfc822'
772
+ };
773
+ } catch (err) {
774
+ // Nothing to send, so the port goes back untouched - the consumer is about to be handed
775
+ // this error, and a closed port would reach it as a failed transfer instead.
776
+ writable.releaseListeners();
756
777
  throw err;
757
778
  }
779
+ }
758
780
 
759
- // Build the cross-thread writable only after we know there is content to send.
760
- // Constructing it earlier leaks the transferred MessagePort (and its message
761
- // listener) whenever the lookup above throws (e.g. a 404).
762
- let stream = new MessagePortWritable(message.port);
781
+ async getAttachment(message) {
782
+ // Built before the download starts, not after: an attachment is the longest wait on this
783
+ // worker, and a consumer thread that dies during it closes the port with nothing queued -
784
+ // which only a listener attached beforehand ever sees. See the MessagePortWritable
785
+ // constructor.
786
+ const writable = new MessagePortWritable(message.port);
787
+ try {
788
+ if (!this.accounts.has(message.account)) {
789
+ throw NO_ACTIVE_HANDLER_RESP_ERR;
790
+ }
763
791
 
764
- setImmediate(() => {
765
- if (Buffer.isBuffer(source)) {
766
- // The consumer may have aborted and destroyed the writable (via a cancel
767
- // message) before this runs; ending a destroyed stream would emit an
768
- // unhandled 'error' and take down the worker. The streaming branch is
769
- // safe because pipeline() tears down a destroyed destination cleanly.
770
- if (!stream.destroyed) {
771
- stream.end(source);
772
- }
773
- } else {
774
- pipeToMessagePort(source, stream, accountData.connection.logger);
792
+ let accountData = this.accounts.get(message.account);
793
+ if (!accountData.connection) {
794
+ throw NO_ACTIVE_HANDLER_RESP_ERR;
775
795
  }
776
- });
777
796
 
778
- return {
779
- headers: {
780
- 'content-type': 'message/rfc822',
781
- 'content-disposition': `attachment; filename=message.eml`
782
- },
783
- contentType: 'message/rfc822'
784
- };
785
- }
797
+ let source = await accountData.connection.getAttachment(message.attachment);
798
+ if (!source) {
799
+ let err = new Error('Requested file not found');
800
+ err.statusCode = 404;
801
+ throw err;
802
+ }
786
803
 
787
- async getAttachment(message) {
788
- if (!this.accounts.has(message.account)) {
789
- throw NO_ACTIVE_HANDLER_RESP_ERR;
790
- }
804
+ // IMAP resolves an attachment to the download stream itself, Gmail and Graph to a Buffer
805
+ // wrapped alongside the headers.
806
+ let payload = Buffer.isBuffer(source.data) ? source.data : source;
791
807
 
792
- let accountData = this.accounts.get(message.account);
793
- if (!accountData.connection) {
794
- throw NO_ACTIVE_HANDLER_RESP_ERR;
795
- }
808
+ sendToMessagePort(writable, payload, accountData.connection.logger);
796
809
 
797
- let source = await accountData.connection.getAttachment(message.attachment);
798
- if (!source) {
799
- let err = new Error('Requested file not found');
800
- err.statusCode = 404;
810
+ return {
811
+ headers: source.headers,
812
+ contentType: source.contentType
813
+ };
814
+ } catch (err) {
815
+ // Nothing to send, so the port goes back untouched - the consumer is about to be handed
816
+ // this error, and a closed port would reach it as a failed transfer instead.
817
+ writable.releaseListeners();
801
818
  throw err;
802
819
  }
803
-
804
- // Build the cross-thread writable only after we know there is content to send.
805
- // Constructing it earlier leaks the transferred MessagePort (and its message
806
- // listener) whenever the lookup above throws (e.g. a 404).
807
- let stream = new MessagePortWritable(message.port);
808
-
809
- setImmediate(() => {
810
- if (Buffer.isBuffer(source.data)) {
811
- // The consumer may have aborted and destroyed the writable (via a cancel
812
- // message) before this runs; ending a destroyed stream would emit an
813
- // unhandled 'error' and take down the worker. The streaming branch is
814
- // safe because pipeline() tears down a destroyed destination cleanly.
815
- if (!stream.destroyed) {
816
- stream.end(source.data);
817
- }
818
- } else {
819
- pipeToMessagePort(source, stream, accountData.connection.logger);
820
- }
821
- });
822
-
823
- return {
824
- headers: source.headers,
825
- contentType: source.contentType
826
- };
827
820
  }
828
821
 
829
822
  // Shutdown teardown: closes every account connection this worker owns. The main thread owns
@@ -1031,7 +1024,13 @@ parentPort.on('message', message => {
1031
1024
  if (message.message && message.message.data && message.message.data.raw) {
1032
1025
  message.message.data.raw = message.message.data.raw.length;
1033
1026
  }
1034
- logger.error(Object.assign({ msg: 'Command failed' }, message, { err }));
1027
+ // Anything with a client-facing status (404 not found, 503 no active handler) is
1028
+ // reported back to the caller as the command response, so it is not a server fault.
1029
+ // 503 is excluded from the error branch on purpose: both "no active handler" and
1030
+ // IMAPConnectionClosing carry it, and a worker taking over accounts answers every
1031
+ // in-flight command with one until the reassignment settles.
1032
+ let isServerFault = !err.statusCode || (err.statusCode >= 500 && err.statusCode !== 503);
1033
+ logger[isServerFault ? 'error' : 'debug'](Object.assign({ msg: 'Command failed' }, message, { err }));
1035
1034
  parentPort.postMessage(Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err)));
1036
1035
  });
1037
1036
  }
@@ -1044,6 +1043,6 @@ parentPort.on('message', message => {
1044
1043
  // server.js instead; see onCommand().
1045
1044
 
1046
1045
  main().catch(err => {
1047
- logger.fatal({ msg: 'Execution failed', err });
1046
+ logger.fatal({ msg: 'IMAP worker startup failed', err });
1048
1047
  logger.flush(() => process.exit(6));
1049
1048
  });
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
  });