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
package/workers/export.js CHANGED
@@ -5,9 +5,6 @@ const { parentPort } = require('worker_threads');
5
5
  const packageData = require('../package.json');
6
6
  const config = require('@zone-eu/wild-config');
7
7
  const logger = require('../lib/logger');
8
- const fs = require('fs');
9
- const zlib = require('zlib');
10
- const { pipeline } = require('stream');
11
8
 
12
9
  const {
13
10
  REDIS_PREFIX,
@@ -30,13 +27,15 @@ const {
30
27
  isExportLimitReached,
31
28
  parseActiveEntry,
32
29
  getExportKey,
30
+ exportFilePath,
31
+ openExportOutput,
33
32
  ACTIVE_EXPORTS_KEY
34
33
  } = require('../lib/export');
35
34
 
36
35
  const { initSentry } = require('../lib/sentry');
37
36
  initSentry('export');
38
37
 
39
- const { redis, queueConf } = require('../lib/db');
38
+ const { redis, queueConf, logBullErrors } = require('../lib/db');
40
39
  const { Worker } = require('bullmq');
41
40
  const { Account } = require('../lib/account');
42
41
  const getSecret = require('../lib/get-secret');
@@ -359,7 +358,8 @@ async function indexFolder(accountObject, account, exportId, folderPath, startDa
359
358
 
360
359
  async function exportMessages(job, exportData) {
361
360
  const { account, exportId } = job.data;
362
- const { filePath } = exportData;
361
+ // Derived from the id like every other reader of the record, never the stored path as such
362
+ const filePath = exportFilePath(exportId, exportData);
363
363
  const includeAttachments = exportData.includeAttachments === '1';
364
364
  const textType = exportData.textType || '*';
365
365
  const rawMaxBytes = Number(exportData.maxBytes);
@@ -377,31 +377,19 @@ async function exportMessages(job, exportData) {
377
377
  timeout: EXPORT_TIMEOUT
378
378
  });
379
379
 
380
- const gzipStream = zlib.createGzip();
381
- const fileStream = fs.createWriteStream(filePath, { mode: 0o600 });
382
-
383
- let encryptStream = null;
384
- let streamError = null;
385
-
386
- const secret = isEncrypted ? await getSecret() : null;
387
-
388
- const streams = [gzipStream];
389
- if (secret) {
390
- const { createEncryptStream } = require('../lib/stream-encrypt');
391
- encryptStream = await createEncryptStream(secret);
392
- streams.push(encryptStream);
393
- }
394
- streams.push(fileStream);
380
+ // Everything that can fail before the export starts writing runs before the output file is
381
+ // opened: a failure here used to leave the file descriptor (and the unlinked file's disk space)
382
+ // held for the life of the worker.
383
+ const accountData = await accountObject.loadAccountData(account);
384
+ const isApiAccount = await accountObject.isApiClient(accountData);
395
385
 
396
- pipeline(...streams, err => {
397
- if (err && !streamError) {
398
- streamError = err;
399
- }
400
- });
386
+ const output = await openExportOutput(filePath, isEncrypted ? await getSecret() : null);
387
+ const gzipStream = output.input;
388
+ const fileStream = output.output;
401
389
 
402
390
  function writeWithBackpressure(data) {
403
- if (streamError) {
404
- return Promise.reject(streamError);
391
+ if (output.error()) {
392
+ return Promise.reject(output.error());
405
393
  }
406
394
 
407
395
  if (gzipStream.write(data)) {
@@ -436,8 +424,6 @@ async function exportMessages(job, exportData) {
436
424
  // from inside the retry backoff so a batch stuck retrying does not let the lock lapse.
437
425
  const maybeExtendLease = createLeaseExtender(job, account, exportId);
438
426
 
439
- const accountData = await accountObject.loadAccountData(account);
440
- const isApiAccount = await accountObject.isApiClient(accountData);
441
427
  const MESSAGE_FETCH_BATCH_SIZE = 10; // Batch size for parallel message fetching
442
428
  const MAX_BATCH_RETRIES = 5; // Max retries for rate-limited or transient per-message errors within a batch
443
429
  const BATCH_RETRY_BASE_DELAY = 5000; // Base delay for batch retry backoff (5 seconds)
@@ -490,8 +476,8 @@ async function exportMessages(job, exportData) {
490
476
 
491
477
  try {
492
478
  while (true) {
493
- if (streamError) {
494
- throw streamError;
479
+ if (output.error()) {
480
+ throw output.error();
495
481
  }
496
482
 
497
483
  if (sizeLimitReached) {
@@ -536,8 +522,8 @@ async function exportMessages(job, exportData) {
536
522
 
537
523
  if (isApiAccount && entriesToFetch.length > 1) {
538
524
  for (let i = 0; i < entriesToFetch.length; i += MESSAGE_FETCH_BATCH_SIZE) {
539
- if (streamError) {
540
- throw streamError;
525
+ if (output.error()) {
526
+ throw output.error();
541
527
  }
542
528
  if (sizeLimitReached) {
543
529
  break;
@@ -630,8 +616,8 @@ async function exportMessages(job, exportData) {
630
616
  }
631
617
  } else {
632
618
  for (const entry of entriesToFetch) {
633
- if (streamError) {
634
- throw streamError;
619
+ if (output.error()) {
620
+ throw output.error();
635
621
  }
636
622
 
637
623
  let message = null;
@@ -697,25 +683,17 @@ async function exportMessages(job, exportData) {
697
683
  processingError = err;
698
684
  }
699
685
 
700
- if (sizeLimitReached) {
701
- logger.warn({
702
- msg: 'Export truncated: size limit reached',
703
- account,
704
- exportId,
705
- totalBytesWritten,
706
- limit: maxExportSize,
707
- messagesExported: processed
708
- });
709
- await Export.update(account, exportId, { truncated: '1' });
710
- }
711
-
712
686
  const FINALIZATION_TIMEOUT = 30000;
713
687
  await new Promise((resolve, reject) => {
688
+ if (output.error()) {
689
+ // The chain already failed and pipeline() tore it down, so no 'finish' or 'error'
690
+ // is coming; waiting would only run out the timeout
691
+ output.destroy();
692
+ return reject(output.error());
693
+ }
714
694
  const timeout = setTimeout(() => {
715
- gzipStream.destroy();
716
- if (encryptStream) encryptStream.destroy();
717
- fileStream.destroy();
718
- reject(streamError || new Error('Stream finalization timed out'));
695
+ output.destroy();
696
+ reject(output.error() || new Error('Stream finalization timed out'));
719
697
  }, FINALIZATION_TIMEOUT);
720
698
  gzipStream.end();
721
699
  fileStream.once('finish', () => {
@@ -724,15 +702,28 @@ async function exportMessages(job, exportData) {
724
702
  });
725
703
  fileStream.once('error', err => {
726
704
  clearTimeout(timeout);
727
- reject(streamError || err);
705
+ reject(output.error() || err);
728
706
  });
729
707
  });
730
708
 
731
709
  if (processingError) {
732
710
  throw processingError;
733
711
  }
734
- if (streamError) {
735
- throw streamError;
712
+ if (output.error()) {
713
+ throw output.error();
714
+ }
715
+
716
+ // Written after the file is closed, so a failure here cannot leave the streams open
717
+ if (sizeLimitReached) {
718
+ logger.warn({
719
+ msg: 'Export truncated: size limit reached',
720
+ account,
721
+ exportId,
722
+ totalBytesWritten,
723
+ limit: maxExportSize,
724
+ messagesExported: processed
725
+ });
726
+ await Export.update(account, exportId, { truncated: '1' });
736
727
  }
737
728
 
738
729
  logger.info({ msg: 'Export messages completed', account, exportId, messagesExported: processed, bytesWritten: totalBytesWritten });
@@ -794,9 +785,7 @@ const exportWorker = new Worker(
794
785
 
795
786
  const exportData = await redis.hgetall(`${REDIS_PREFIX}exp:${account}:${exportId}`).catch(() => ({}));
796
787
 
797
- if (exportData.filePath) {
798
- await fs.promises.unlink(exportData.filePath).catch(() => {});
799
- }
788
+ await Export.removeFile(exportId, exportData);
800
789
 
801
790
  if (err.code === 'ExportCancelled') {
802
791
  await Export.deleteFully(account, exportId);
@@ -837,6 +826,8 @@ const exportWorker = new Worker(
837
826
  }
838
827
  );
839
828
 
829
+ logBullErrors(exportWorker, 'worker:export');
830
+
840
831
  exportWorker.on('completed', async job => {
841
832
  metrics(logger, 'queuesProcessed', 'inc', { queue: 'export', status: 'completed' });
842
833
  logger.debug({ msg: 'Export queue entry completed', queue: job.queue.name, job: job.id, account: job.data.account, exportId: job.data.exportId });
@@ -898,9 +889,13 @@ async function onCommand(command) {
898
889
  }
899
890
 
900
891
  // Now that interrupted exports have been reconciled and orphaned files cleaned, start consuming
901
- // jobs. Mirrors BullMQ's own autorun: a fatal run() failure is surfaced as an 'error' event,
902
- // which (no listener) crashes the worker thread so the main process can restart it.
903
- exportWorker.run().catch(error => exportWorker.emit('error', error));
892
+ // jobs. A fatal run() failure leaves a thread that keeps sending heartbeats while consuming
893
+ // nothing, so it exits instead and the main process respawns it. (Re-emitting it as an 'error'
894
+ // event did not crash anything: BullMQ catches an unlistened 'error' and prints it.)
895
+ exportWorker.run().catch(err => {
896
+ logger.fatal({ msg: 'Export queue processing stopped, exiting worker', err });
897
+ logger.flush(() => process.exit(1));
898
+ });
904
899
 
905
900
  setInterval(() => {
906
901
  try {
package/workers/imap.js CHANGED
@@ -18,18 +18,15 @@ const { OutlookClient } = require('../lib/email-client/outlook-client');
18
18
  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
- const { redis, notifyQueue, submitQueue, documentsQueue, getFlowProducer } = require('../lib/db');
21
+ const { redis, notifyQueue, submitQueue, watchRedisReconnect } = require('../lib/db');
22
22
  const { sendToMessagePort, MessagePortWritable } = require('../lib/message-port-stream');
23
- const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
23
+ const { packRpcError, unpackRpcError, describeRpcCommand } = require('../lib/worker-rpc-error');
24
24
  const { ImapFlowErrorCode } = require('imapflow');
25
- const { getESClient } = require('../lib/document-store');
26
25
  const settings = require('../lib/settings');
27
26
  const msgpack = require('../lib/msgpack');
28
27
 
29
28
  const getSecret = require('../lib/get-secret');
30
29
 
31
- const flowProducer = getFlowProducer();
32
-
33
30
  config.service = config.service || {};
34
31
 
35
32
  config.log = config.log || {
@@ -63,35 +60,29 @@ class ConnectionHandler {
63
60
  this.mids = 0;
64
61
 
65
62
  this.accounts = new Map();
63
+
64
+ // account -> token of the latest assign. An unassign or a newer assign replaces or drops it,
65
+ // which is how an assign still awaiting its setup learns it has been superseded. The one
66
+ // supersession check there is: the identity of the this.accounts entry cannot serve, because
67
+ // nothing is registered there until the Account object exists, so an unassign that lands
68
+ // during the loads before that leaves nothing to compare against. Entry identity is only
69
+ // consulted to decide whether a cleanup or an init retry still concerns the entry this
70
+ // assign registered.
71
+ this.assignTokens = new Map();
66
72
  }
67
73
 
68
74
  async init() {
69
- // Track Redis connection state for reconnection detection
70
- let hasSeenStableConnection = false;
71
- let redisWasDisconnected = false;
72
-
73
- // Check initial Redis state
74
- if (redis.status === 'ready') {
75
- hasSeenStableConnection = true;
76
- }
77
-
78
- redis.on('ready', () => {
79
- if (redisWasDisconnected && hasSeenStableConnection) {
80
- // Redis reconnected after being disconnected during our lifetime
75
+ // Redis reconnected after being disconnected during our lifetime. In-memory account state
76
+ // may no longer match Redis (a restart or a flush), so exit cleanly: the main thread
77
+ // treats exit code 0 as this case, respawns the worker and reassigns its accounts.
78
+ watchRedisReconnect(
79
+ redis,
80
+ () => {
81
81
  logger.info({ msg: 'Redis reconnected after disconnection, exiting worker for clean restart', worker: 'imap' });
82
- // Exit gracefully - the main process will restart this worker
83
82
  process.exit(0);
84
- }
85
- // Mark that we've seen a stable connection
86
- hasSeenStableConnection = true;
87
- });
88
-
89
- redis.on('end', () => {
90
- if (hasSeenStableConnection) {
91
- logger.warn({ msg: 'Redis connection lost', worker: 'imap' });
92
- redisWasDisconnected = true;
93
- }
94
- });
83
+ },
84
+ () => logger.warn({ msg: 'Redis connection lost', worker: 'imap' })
85
+ );
95
86
 
96
87
  // indicate that we are ready to process connections
97
88
  parentPort.postMessage({ cmd: 'ready' });
@@ -187,6 +178,34 @@ class ConnectionHandler {
187
178
  return accountLogger;
188
179
  }
189
180
 
181
+ /**
182
+ * Closes an account connection this worker no longer tracks. Nothing is deleted, the account
183
+ * is only moving to another worker or being assigned here again
184
+ * @param {string} account - Account ID
185
+ * @param {Object} accountObject - The entry that was removed from this.accounts
186
+ */
187
+ async closeReleasedConnection(account, accountObject) {
188
+ if (!accountObject || !accountObject.connection) {
189
+ return;
190
+ }
191
+ try {
192
+ await accountObject.connection.close();
193
+ } catch (err) {
194
+ logger.error({ msg: 'Failed to close released account connection', account, err });
195
+ }
196
+ }
197
+
198
+ // The main thread takes an account back after an `assign` it gave up waiting for, or to move
199
+ // it onto another worker. An assignment still being set up notices the missing entry and stops.
200
+ async unassignConnection(account) {
201
+ logger.info({ msg: 'Account unassign requested', account });
202
+ this.assignTokens.delete(account);
203
+ let accountObject = this.accounts.get(account);
204
+ this.accounts.delete(account);
205
+ await this.closeReleasedConnection(account, accountObject);
206
+ return true;
207
+ }
208
+
190
209
  async assignConnection(account, runIndex, initOpts) {
191
210
  logger.debug({ msg: 'Assigned account to worker', account });
192
211
 
@@ -198,6 +217,10 @@ class ConnectionHandler {
198
217
  runIndex = this.runIndex;
199
218
  }
200
219
 
220
+ const token = Symbol(account);
221
+ this.assignTokens.set(account, token);
222
+ const isCurrent = () => this.assignTokens.get(account) === token;
223
+
201
224
  let accountLogger = await this.getAccountLogger(account);
202
225
  let secret = await getSecret();
203
226
  let accountObject = new Account({
@@ -206,12 +229,65 @@ class ConnectionHandler {
206
229
  secret,
207
230
  // Needed so Account.update() can dispatch reconnect/update commands back to
208
231
  // this worker (e.g. auto-reconnect after OAuth re-auth in an error state).
209
- call: msg => this.call(msg),
210
- esClient: await getESClient(logger)
232
+ call: msg => this.call(msg)
211
233
  });
212
234
 
235
+ if (!isCurrent()) {
236
+ logger.info({ msg: 'Dropped superseded account assignment', account });
237
+ return false;
238
+ }
239
+
240
+ // Assigning an account this worker already runs replaces the connection. A retried assign
241
+ // (the main thread timed out on the first one) used to overwrite the map entry and leave the
242
+ // first connection running with nothing able to reach it. Swapped without an await in
243
+ // between, so two overlapping assigns cannot both keep a connection.
244
+ let previous = this.accounts.get(account);
213
245
  this.accounts.set(account, accountObject);
246
+ await this.closeReleasedConnection(account, previous);
247
+
248
+ let current;
249
+ try {
250
+ current = await this.setupConnection(account, accountObject, { runIndex, accountLogger, secret, isCurrent });
251
+ } catch (err) {
252
+ // Leave no connection-less entry behind: it answered commands with "no active handler"
253
+ // and counted as a disconnected account for as long as the worker lived. Only the entry
254
+ // this assign registered is its to remove, a newer assign may have replaced it
255
+ if (this.accounts.get(account) === accountObject) {
256
+ this.accounts.delete(account);
257
+ }
258
+ if (isCurrent()) {
259
+ this.assignTokens.delete(account);
260
+ }
261
+ if (err.isBoom && !err.statusCode && err.output) {
262
+ // Lets the main thread tell an account that is gone (404) from a transient failure
263
+ err.statusCode = err.output.statusCode;
264
+ }
265
+ throw err;
266
+ }
267
+
268
+ if (!current) {
269
+ // Unassigned or assigned again while this was being set up; the client was never
270
+ // started, so there is nothing to close
271
+ if (this.accounts.get(account) === accountObject) {
272
+ this.accounts.delete(account);
273
+ }
274
+ logger.info({ msg: 'Dropped superseded account assignment', account });
275
+ return false;
276
+ }
277
+
278
+ // do not wait before returning as it may take forever
279
+ this.startConnection(account, accountObject, initOpts);
280
+ }
214
281
 
282
+ /**
283
+ * Loads the account and builds its client, without starting it
284
+ * @param {string} account - Account ID
285
+ * @param {Object} accountObject - The entry assignConnection() registered
286
+ * @param {Object} opts - runIndex, accountLogger, secret and isCurrent, the assign's own
287
+ * supersession check (see the assignTokens comment in the constructor)
288
+ * @returns {Promise<boolean>} false when the assign was superseded in the meantime
289
+ */
290
+ async setupConnection(account, accountObject, { runIndex, accountLogger, secret, isCurrent }) {
215
291
  const accountData = await accountObject.loadAccountData();
216
292
 
217
293
  if (accountData.oauth2 && accountData.oauth2.auth) {
@@ -245,8 +321,6 @@ class ConnectionHandler {
245
321
 
246
322
  notifyQueue,
247
323
  submitQueue,
248
- documentsQueue,
249
- flowProducer,
250
324
 
251
325
  call: msg => this.call(msg)
252
326
  });
@@ -265,8 +339,6 @@ class ConnectionHandler {
265
339
 
266
340
  notifyQueue,
267
341
  submitQueue,
268
- documentsQueue,
269
- flowProducer,
270
342
 
271
343
  call: msg => this.call(msg)
272
344
  });
@@ -291,8 +363,6 @@ class ConnectionHandler {
291
363
 
292
364
  notifyQueue,
293
365
  submitQueue,
294
- documentsQueue,
295
- flowProducer,
296
366
 
297
367
  call: msg => this.call(msg),
298
368
  logRaw: EENGINE_LOG_RAW
@@ -300,13 +370,16 @@ class ConnectionHandler {
300
370
  accountObject.logger = accountObject.connection.logger;
301
371
  }
302
372
 
373
+ if (!isCurrent()) {
374
+ return false;
375
+ }
376
+
303
377
  if (accountData.state) {
304
378
  await redis.hSetExists(accountObject.connection.getAccountKey(), 'state', accountData.state);
305
379
  await emitChangeEvent(logger, account, 'state', accountData.state);
306
380
  }
307
381
 
308
- // do not wait before returning as it may take forever
309
- this.startConnection(account, accountObject, initOpts);
382
+ return isCurrent();
310
383
  }
311
384
 
312
385
  /**
@@ -342,6 +415,7 @@ class ConnectionHandler {
342
415
 
343
416
  async deleteConnection(account) {
344
417
  logger.info({ msg: 'Deleting connection', account });
418
+ this.assignTokens.delete(account);
345
419
  if (this.accounts.has(account)) {
346
420
  let accountObject = this.accounts.get(account);
347
421
  if (accountObject.connection) {
@@ -372,7 +446,7 @@ class ConnectionHandler {
372
446
  }
373
447
  }
374
448
 
375
- async syncConnection(account) {
449
+ async syncConnection(account, opts = {}) {
376
450
  logger.info({ msg: 'Account sync requested', account });
377
451
  if (this.accounts.has(account)) {
378
452
  let accountObject = this.accounts.get(account);
@@ -384,7 +458,8 @@ class ConnectionHandler {
384
458
  msg: 'Account sync requested'
385
459
  });
386
460
 
387
- await accountObject.connection.syncMailboxes();
461
+ // only the Graph client reads the options, the others sync their own way
462
+ await accountObject.connection.syncMailboxes(opts);
388
463
 
389
464
  return true;
390
465
  }
@@ -441,7 +516,12 @@ class ConnectionHandler {
441
516
  msg: 'Account reconnection requested'
442
517
  });
443
518
 
444
- await accountObject.connection.close();
519
+ try {
520
+ await accountObject.connection.close();
521
+ } catch (err) {
522
+ // a failed state write during close must not stop the reconnect
523
+ logger.error({ msg: 'Failed to close connection', account, err });
524
+ }
445
525
  }
446
526
 
447
527
  await this.assignConnection(account, false, { forceWatchRenewal: true });
@@ -860,9 +940,12 @@ class ConnectionHandler {
860
940
  logger.info({ msg: 'Closing account connections', accounts: this.accounts.size });
861
941
  this.connectionsClosed = true;
862
942
 
863
- this.accounts.forEach(accountObject => {
943
+ this.accounts.forEach((accountObject, account) => {
864
944
  if (accountObject && accountObject.connection) {
865
- accountObject.connection.close();
945
+ // Gmail and Graph close() write state to Redis; a rejection here is only worth a log line
946
+ Promise.resolve()
947
+ .then(() => accountObject.connection.close())
948
+ .catch(err => logger.error({ msg: 'Failed to close connection', account, err }));
866
949
  }
867
950
  });
868
951
  }
@@ -912,9 +995,12 @@ class ConnectionHandler {
912
995
  await this.closeConnections();
913
996
  return true;
914
997
 
998
+ case 'sync':
999
+ return await this.syncConnection(message.account, { since: message.since });
1000
+
915
1001
  case 'delete':
1002
+ case 'unassign':
916
1003
  case 'update':
917
- case 'sync':
918
1004
  case 'pause':
919
1005
  case 'resume':
920
1006
  case 'reconnect':
@@ -1050,9 +1136,6 @@ parentPort.on('message', message => {
1050
1136
  });
1051
1137
  })
1052
1138
  .catch(err => {
1053
- if (message.message && message.message.data && message.message.data.raw) {
1054
- message.message.data.raw = message.message.data.raw.length;
1055
- }
1056
1139
  // Anything with a client-facing status (404 not found, 503 no active handler) is
1057
1140
  // reported back to the caller as the command response, so it is not a server fault.
1058
1141
  // 503 is excluded from the error branch on purpose: both "no active handler" and
@@ -1064,7 +1147,7 @@ parentPort.on('message', message => {
1064
1147
  err.statusCode = 429;
1065
1148
  }
1066
1149
  let isServerFault = !err.statusCode || (err.statusCode >= 500 && err.statusCode !== 503);
1067
- logger[isServerFault ? 'error' : 'debug'](Object.assign({ msg: 'Command failed' }, message, { err }));
1150
+ logger[isServerFault ? 'error' : 'debug'](Object.assign(describeRpcCommand(message), { msg: 'Command failed', err }));
1068
1151
  parentPort.postMessage(Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err)));
1069
1152
  });
1070
1153
  }
package/workers/submit.js CHANGED
@@ -15,7 +15,7 @@ const { initSentry } = require('../lib/sentry');
15
15
  initSentry('submit');
16
16
 
17
17
  const util = require('util');
18
- const { redis, queueConf, submitQueue } = require('../lib/db');
18
+ const { redis, queueConf, submitQueue, logBullErrors } = require('../lib/db');
19
19
  const { Worker, UnrecoverableError } = require('bullmq');
20
20
  const { Account } = require('../lib/account');
21
21
  const getSecret = require('../lib/get-secret');
@@ -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, willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
45
+ const { shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt, nextAttemptWhileProcessing } = require('../lib/delivery-error');
46
46
  const { isAlreadySent } = require('../lib/submit-progress');
47
47
  const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
48
48
 
@@ -216,10 +216,7 @@ const submitWorker = new Worker(
216
216
  // ignore
217
217
  }
218
218
 
219
- let backoffDelay = Number(job.opts.backoff && job.opts.backoff.delay) || 0;
220
- // job.attemptsMade is not yet incremented for the ongoing attempt, so the
221
- // next retry (if this attempt fails) is delayed by 2^attemptsMade * base
222
- let nextAttempt = !willBeFinalAttempt(job) ? Math.round(job.processedOn + Math.pow(2, job.attemptsMade) * backoffDelay) : false;
219
+ let nextAttempt = nextAttemptWhileProcessing(job);
223
220
 
224
221
  queueEntry.job = {
225
222
  id: job.id,
@@ -362,6 +359,8 @@ const submitWorker = new Worker(
362
359
  )
363
360
  );
364
361
 
362
+ logBullErrors(submitWorker, 'worker:submit');
363
+
365
364
  submitWorker.on('completed', async job => {
366
365
  metrics(logger, 'queuesProcessed', 'inc', {
367
366
  queue: 'submit',