emailengine-app 2.81.1 → 2.81.2

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.
package/.ncurc.js CHANGED
@@ -11,7 +11,8 @@ module.exports = {
11
11
  // is a major we are deliberately soaking. Using 'minor' instead of a blanket reject so these
12
12
  // still receive security/patch updates within the safe major instead of being frozen at one
13
13
  // exact version. Verified against Node 20 (Docker) 2026-06-17.
14
- target: name => (['nanoid', 'ical.js', 'gettext-parser', 'xgettext-template', 'chai', 'undici', 'marked'].includes(name) ? 'minor' : 'latest'),
14
+ target: name =>
15
+ ['nanoid', 'ical.js', 'gettext-parser', 'xgettext-template', 'chai', 'undici', 'marked', '@sentry/node'].includes(name) ? 'minor' : 'latest',
15
16
  // nanoid - 4.x dropped the CommonJS require export (ESM-only)
16
17
  // ical.js - 2.x is ESM-only
17
18
  // gettext-parser - 8.x is ESM-only
@@ -22,6 +23,10 @@ module.exports = {
22
23
  // marked - 16.x dropped the CommonJS build (ESM-only, needs require(esm)/Node >=20.19); 15.x is the
23
24
  // last require()-compatible line. 15.0.12 verified on Node 20-24 and in a yao/pkg node24 build.
24
25
  // Permanent while the Node 20 floor above stands.
26
+ // @sentry/node - 11.x requires Node >=20.19 (the DigitalOcean images are not guaranteed to be on a 20.x
27
+ // that new), and it depends on @sentry/bundler-plugins, which pulls the 16 MB Sentry CLI
28
+ // (package `sentry`, licensed FSL-1.1-Apache-2.0, not an OSI license) into the runtime
29
+ // tree and the pkg bundle. Reconsider if a later 11.x drops that dependency.
25
30
  //
26
31
  // bullmq was capped at 5.x until 2026-08-17, when both stated reasons had expired. Now on 6.x, which
27
32
  // moves cron-parser off the deprecated 4.9.0 onto 5.x - but not off luxon, which cron-parser depends
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.81.1"
2
+ ".": "2.81.2"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.81.2](https://github.com/postalsys/emailengine/compare/v2.81.1...v2.81.2) (2026-09-27)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **api:** check isBounce for messages in the Inbox only ([de05eff](https://github.com/postalsys/emailengine/commit/de05eff7d684cd7beeb227a912afa6aa0988b421))
9
+ * **api:** decide isBounce at fetch time instead of storing a marker ([2c81311](https://github.com/postalsys/emailengine/commit/2c813117f95757c6cf656ae3f904042c3b458a7a))
10
+ * **api:** remove the bounces field and the store behind it ([b67acb9](https://github.com/postalsys/emailengine/commit/b67acb9618754a108e32e4bafbef0b05d4773ade))
11
+ * **api:** report isBounce and relatedMessageId in message responses ([b551bfd](https://github.com/postalsys/emailengine/commit/b551bfd7457466e8f51ff77540d0bb4afd59eb21))
12
+ * **deps:** update dependencies, hold @sentry/node at 10.x ([6c74381](https://github.com/postalsys/emailengine/commit/6c7438108559fa5eef36a022756515f623ac965f))
13
+ * **deps:** update imapflow to 2.0.6 ([07d5ea7](https://github.com/postalsys/emailengine/commit/07d5ea7eb42cdb01fd9a091db043837ecd8e58d3))
14
+ * **deps:** update imapflow to 2.1.0, dedupe nodemailer and undici ([13da944](https://github.com/postalsys/emailengine/commit/13da944e7ffee2943a91bfd4a0ade21b60c8f2b1))
15
+ * **docker:** bump the node:24-alpine base image digest ([0cb6d23](https://github.com/postalsys/emailengine/commit/0cb6d23a8e975e09bce10158434332b3f1131e89))
16
+ * **gmail:** retry new messages that fail on a transient API error ([f7d45f9](https://github.com/postalsys/emailengine/commit/f7d45f9edc1afaaf44b0d145caddb13aef0e76c1))
17
+ * **imap:** run the shared arrival checks instead of IMAP wrappers ([26cd53c](https://github.com/postalsys/emailengine/commit/26cd53c771ed8f6abbd740c22ef62319b54401a8))
18
+ * **imap:** share the bounce shape check with the API clients ([a0302a2](https://github.com/postalsys/emailengine/commit/a0302a2ff40ab62f8fd5dfc68f26cbc9175d0059))
19
+ * **imap:** share the complaint shape check with the API clients ([90a9825](https://github.com/postalsys/emailengine/commit/90a9825044fc024cf5977c5c56ccf5a484973cd4))
20
+ * **imap:** share the delivery-report shape check with the API clients ([aa777df](https://github.com/postalsys/emailengine/commit/aa777dfefbe8047f7b7a6df7000fb95b89189a2c))
21
+ * keep assigning accounts when an IMAP worker exits mid-assignment ([ed87eee](https://github.com/postalsys/emailengine/commit/ed87eee43ff6eba3b53d6556d7fc33e6ebfca0dc))
22
+ * keep throttled IMAP arrivals and harden the deferred change retries ([4830bb4](https://github.com/postalsys/emailengine/commit/4830bb451c5ee166c2ee0e6beef9cc759424341a))
23
+ * **outlook:** recover missed Graph notifications durably ([ff0eca6](https://github.com/postalsys/emailengine/commit/ff0eca6dbdfdbda34776b0b5c92b9c07cfbe5d04))
24
+ * **outlook:** retry change notifications that fail on a transient Graph error ([9d1301c](https://github.com/postalsys/emailengine/commit/9d1301cff3bd2b505e0d3402c40c2eefaf1c44ed))
25
+ * **submit:** warn when the sent copy is skipped for lack of a Sent mailbox ([47fd10b](https://github.com/postalsys/emailengine/commit/47fd10bdef5dc732265b10619122456d574942de))
26
+ * **sync:** defer Gmail and Graph changes that fail on a transient error ([b778adf](https://github.com/postalsys/emailengine/commit/b778adfab637ce7b2afc801e7eedd4f31f3a50a9))
27
+
3
28
  ## [2.81.1](https://github.com/postalsys/emailengine/compare/v2.81.0...v2.81.1) (2026-09-15)
4
29
 
5
30
 
package/Dockerfile CHANGED
@@ -11,7 +11,7 @@
11
11
  # here; the runtime stage below copies out only the finished tree, so npm and its dependencies never
12
12
  # reach the published image. npm accounted for 38 of the 59 HIGH/CRITICAL findings in the old image
13
13
  # (a vendored tar, pacote, sigstore, minimatch) and nothing at runtime ever invokes it.
14
- FROM node:24-alpine@sha256:50c8e8ca1d27439048670df5883f32d57cf81cff6233222c893fd0d9884cbd81 AS builder
14
+ FROM node:24-alpine@sha256:ebfe2f90462722a7a4de65e91990e97fe0d401c70e0e762c5b53302f905ec1c1 AS builder
15
15
 
16
16
  ARG BUILDPLATFORM
17
17
  ARG TARGETPLATFORM
@@ -74,7 +74,7 @@ RUN : "${EE_COMMIT_HASH:?EE_COMMIT_HASH build arg is required, e.g. --build-arg
74
74
  && rm -f update-info.sh
75
75
 
76
76
  # Runtime stage.
77
- FROM node:24-alpine@sha256:50c8e8ca1d27439048670df5883f32d57cf81cff6233222c893fd0d9884cbd81
77
+ FROM node:24-alpine@sha256:ebfe2f90462722a7a4de65e91990e97fe0d401c70e0e762c5b53302f905ec1c1
78
78
 
79
79
  # `apk upgrade` patches the Alpine packages that the base image itself lags on - at the time of
80
80
  # writing node:24-alpine still carries an openssl below 3.5.8-r0. dumb-init reaps zombies as PID 1.
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-09-14T14:46:42.000000",
2
+ "creationTime": "2026-09-25T14:47:24.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ // One-time sweep of the store behind the retired `bounces` response field: the per-account hash
4
+ // `iar:b:<account>` every detected bounce used to append to, which nothing trimmed and nothing reads
5
+ // or writes any more. The accounts are walked rather than the keyspace scanned, because the store
6
+ // only ever existed for an account in the set (deleting the account unlinked it). A completion key
7
+ // makes the sweep run once; delete SWEEP_KEY and restart to re-arm it.
8
+
9
+ const { redis } = require('../db');
10
+ const logger = require('../logger');
11
+ const { REDIS_PREFIX } = require('../consts');
12
+
13
+ // Marks the sweep as done for this Redis. Value is the ISO time of the run.
14
+ const SWEEP_KEY = `${REDIS_PREFIX}migration:bounceStoreRemoved`;
15
+
16
+ // Accounts unlinked per pipeline, matching the chunking of the auth-failure backfill
17
+ const CHUNK_SIZE = 500;
18
+
19
+ /**
20
+ * Deletes every account's bounce store, once.
21
+ *
22
+ * @param {Object} [opts] - Overrides for tests; the defaults are the shared clients
23
+ * @param {Object} [opts.redis] - ioredis client
24
+ * @param {Object} [opts.logger] - Logger
25
+ * @returns {Promise<Number>} How many stores were deleted
26
+ */
27
+ async function sweepBounceStore(opts = {}) {
28
+ const { redis: client = redis, logger: log = logger } = opts;
29
+
30
+ // The common case is an instance that has already swept, and this is the whole cost for it
31
+ if (await client.exists(SWEEP_KEY)) {
32
+ return 0;
33
+ }
34
+
35
+ const accounts = await client.smembers(`${REDIS_PREFIX}ia:accounts`);
36
+
37
+ // Counted from the replies: UNLINK answers 1 only for a key that existed. A failed reply throws
38
+ // before the completion key is written, so the next startup runs the sweep again
39
+ let deleted = 0;
40
+ for (let i = 0; i < accounts.length; i += CHUNK_SIZE) {
41
+ const req = client.pipeline();
42
+ for (const account of accounts.slice(i, i + CHUNK_SIZE)) {
43
+ req.unlink(`${REDIS_PREFIX}iar:b:${account}`);
44
+ }
45
+ for (const [err, count] of await req.exec()) {
46
+ if (err) {
47
+ throw err;
48
+ }
49
+ deleted += count ? 1 : 0;
50
+ }
51
+ }
52
+
53
+ // Written last, so a crash mid-sweep re-enters and finishes it
54
+ await client.set(SWEEP_KEY, new Date().toISOString());
55
+
56
+ if (deleted) {
57
+ log.info({ msg: 'Deleted the bounce store of earlier versions', accounts: deleted });
58
+ }
59
+
60
+ return deleted;
61
+ }
62
+
63
+ module.exports = { sweepBounceStore, SWEEP_KEY };
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ // Bookkeeping shared by assignAccounts() and the IMAP worker exit handler in server.js, kept apart
4
+ // so a worker exiting in the middle of an assignment pass can be tested without the main thread.
5
+ // The exit handler runs while a pass is awaiting a worker, so the pass cannot assume a worker it
6
+ // picked, or that worker's account set, still exists.
7
+
8
+ /**
9
+ * The least loaded running worker below `targetPerWorker`, else the least loaded running one
10
+ * @param {Set<Object>} availableWorkers
11
+ * @param {Map<Object, number>} workerLoadMap - worker -> accounts counted in this pass
12
+ * @param {number} targetPerWorker
13
+ * @returns {Object|undefined}
14
+ */
15
+ function pickLeastLoadedWorker(availableWorkers, workerLoadMap, targetPerWorker) {
16
+ const byLoad = Array.from(availableWorkers).sort((a, b) => (workerLoadMap.get(a) || 0) - (workerLoadMap.get(b) || 0));
17
+ return byLoad.find(worker => (workerLoadMap.get(worker) || 0) < targetPerWorker) || byLoad[0];
18
+ }
19
+
20
+ /**
21
+ * Undoes the bookkeeping for an account whose `assign` call failed. The worker's account set is
22
+ * already gone when the worker exited while the call was in flight
23
+ * @param {Object} state - `workerAssigned`, `assigned` and `workerLoadMap`
24
+ * @param {string} account
25
+ * @param {Object} worker
26
+ * @param {boolean} countedLoad - Whether the account was counted in workerLoadMap
27
+ */
28
+ function rollbackAssignment({ workerAssigned, assigned, workerLoadMap }, account, worker, countedLoad) {
29
+ workerAssigned.get(worker)?.delete(account);
30
+ assigned.delete(account);
31
+ if (countedLoad) {
32
+ workerLoadMap.set(worker, workerLoadMap.get(worker) - 1);
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Moves the accounts of an exited worker back to unassigned
38
+ * @param {Object} state - `workerAssigned`, `assigned` and `unassigned`
39
+ * @param {Object} worker
40
+ * @returns {Set<string>|null} The accounts released, null when the worker had none tracked
41
+ */
42
+ function releaseWorkerAccounts({ workerAssigned, assigned, unassigned }, worker) {
43
+ const accounts = workerAssigned.get(worker);
44
+ if (!accounts) {
45
+ return null;
46
+ }
47
+ workerAssigned.delete(worker);
48
+ for (const account of accounts) {
49
+ assigned.delete(account);
50
+ unassigned.add(account);
51
+ }
52
+ return accounts;
53
+ }
54
+
55
+ /**
56
+ * Returns the accounts that failed in a pass to unassigned, except the ones assigned since: the
57
+ * exit handler requeues an account whose worker exited mid-call, and the same pass can pick it up
58
+ * again from there
59
+ * @param {Object} state - `assigned` and `unassigned`
60
+ * @param {string[]} failedAccounts
61
+ */
62
+ function requeueFailedAccounts({ assigned, unassigned }, failedAccounts) {
63
+ for (const account of failedAccounts) {
64
+ if (!assigned.has(account)) {
65
+ unassigned.add(account);
66
+ }
67
+ }
68
+ }
69
+
70
+ module.exports = { pickLeastLoadedWorker, rollbackAssignment, releaseWorkerAccounts, requeueFailedAccounts };
package/lib/account.js CHANGED
@@ -418,6 +418,11 @@ class Account {
418
418
  return `${REDIS_PREFIX}iap:${this.account}`;
419
419
  }
420
420
 
421
+ // Mailbox changes waiting for a retry (Gmail and MS Graph), scored by the time they are due
422
+ getDeferredQueueKey() {
423
+ return `${REDIS_PREFIX}iap:${this.account}:r`;
424
+ }
425
+
421
426
  // Shared log entry for unserializeAccountData() failures. The raw value is withheld on
422
427
  // purpose: imap/smtp/oauth2 payloads may carry cleartext credentials when no EENGINE_SECRET is
423
428
  // set, so only its length is logged. `ownerAccount` is the row's own marker when available -
@@ -1508,11 +1513,12 @@ class Account {
1508
1513
  .srem(`${REDIS_PREFIX}ia:accounts`, this.account)
1509
1514
  .unlink(this.getMailboxListKey()) // mailbox list
1510
1515
  .unlink(this.getMailboxHashKey()) // mailbox list for ID references
1511
- .unlink(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce list
1516
+ .unlink(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
1512
1517
  .unlink(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
1513
1518
  .unlink(`${REDIS_PREFIX}iaq:${this.account}`) // delayed message queue
1514
1519
  .unlink(`${REDIS_PREFIX}iac:${this.account}`) // cache hash
1515
1520
  .unlink(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
1521
+ .unlink(this.getDeferredQueueKey()) // mailbox changes waiting for a retry
1516
1522
 
1517
1523
  .unlink(tombstoneTdy)
1518
1524
  .unlink(tombstoneYdy)
@@ -2070,7 +2076,7 @@ class Account {
2070
2076
  const reqOpts = {
2071
2077
  index,
2072
2078
  id: `${this.account}:${message}`,
2073
- _source_excludes: 'preview,seemsLikeNew,account,created,updateTime'
2079
+ _source_excludes: 'preview,seemsLikeNew,account,created,updateTime,bounces'
2074
2080
  };
2075
2081
 
2076
2082
  switch (options.textType) {
@@ -2318,7 +2324,7 @@ class Account {
2318
2324
  from: pageSize * page,
2319
2325
  query: searchQuery,
2320
2326
  sort: { uid: 'desc' },
2321
- _source_excludes: 'headers,text.plain,text.html,text._generatedHtml,seemsLikeNew,attachments.content,summary,riskAssessment,updateTime'
2327
+ _source_excludes: 'headers,text.plain,text.html,text._generatedHtml,seemsLikeNew,attachments.content,summary,riskAssessment,updateTime,bounces'
2322
2328
  });
2323
2329
 
2324
2330
  this.logger.trace({
@@ -2688,7 +2694,7 @@ class Account {
2688
2694
  from: pageSize * page,
2689
2695
  query: searchQuery,
2690
2696
  sort: { [!searchOpts.unified ? 'uid' : 'date']: 'desc' },
2691
- _source_excludes: 'headers,text.plain,text.html,text._generatedHtml,seemsLikeNew,attachments.content,summary,riskAssessment,updateTime'
2697
+ _source_excludes: 'headers,text.plain,text.html,text._generatedHtml,seemsLikeNew,attachments.content,summary,riskAssessment,updateTime,bounces'
2692
2698
  });
2693
2699
 
2694
2700
  this.logger.trace({
@@ -2933,7 +2939,7 @@ class Account {
2933
2939
  // Note: mailbox ID hash (iah:) and listRegistry are intentionally NOT deleted
2934
2940
  // to preserve message ID stability across reconnections. Message IDs depend on
2935
2941
  // the specific mailbox ID entries, so deleting them would invalidate existing IDs.
2936
- .del(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce list
2942
+ .del(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
2937
2943
  .del(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
2938
2944
  .del(tombstoneTdy)
2939
2945
  .del(tombstoneYdy);
@@ -3299,24 +3305,24 @@ class Account {
3299
3305
  return await oAuth2Client.request(tokenData?.accessToken, url, method, payload, options);
3300
3306
  }
3301
3307
 
3302
- async pushQueueEvent(event) {
3303
- let evObj = {
3304
- t: new Date(),
3305
- e: event
3306
- };
3307
- try {
3308
- let res = await this.redis.lpush(this.getExternalQueueKey(), msgpack.encode(evObj));
3308
+ /**
3309
+ * Queues the events of one Graph notification delivery, encoded as the envelope
3310
+ * pullQueueEvent() decodes. One write, so it is all or nothing, and not caught: the webhook
3311
+ * route has to answer with an error for Graph to deliver the notification again - a 202 after
3312
+ * a failed write lost it for good, and a partial write would repeat the events already queued
3313
+ * @param {Object[]} events - Queue events
3314
+ */
3315
+ async pushQueueEvents(events) {
3316
+ const t = new Date();
3317
+ let res = await this.redis.lpush(this.getExternalQueueKey(), ...events.map(e => msgpack.encode({ t, e })));
3309
3318
 
3310
- this.logger.debug({
3311
- msg: 'MS Graph subscription event',
3312
- type: 'event',
3313
- account: this.account,
3314
- event,
3315
- res
3316
- });
3317
- } catch (err) {
3318
- this.logger.error({ msg: 'Failed to insert event to account queue', account: this.account, event, err });
3319
- }
3319
+ this.logger.debug({
3320
+ msg: 'MS Graph subscription event',
3321
+ type: 'event',
3322
+ account: this.account,
3323
+ events,
3324
+ res
3325
+ });
3320
3326
 
3321
3327
  try {
3322
3328
  await this.call({ cmd: 'externalNotify', accounts: [this.account] });
@@ -3340,8 +3346,103 @@ class Account {
3340
3346
 
3341
3347
  return event || null;
3342
3348
  }
3349
+
3350
+ /**
3351
+ * Parks a mailbox change until `dueTime`. Kept in Redis rather than a timer so a restart in
3352
+ * between does not lose it
3353
+ * @param {Object} event - Any JSON-serializable description of the change
3354
+ * @param {number} dueTime - Epoch milliseconds
3355
+ */
3356
+ async deferChangeEvent(event, dueTime) {
3357
+ await this.redis.zadd(this.getDeferredQueueKey(), dueTime, JSON.stringify(event));
3358
+ }
3359
+
3360
+ /**
3361
+ * Lists the deferred changes that are due, a bounded batch per call. Nothing is removed here:
3362
+ * each is swapped for its next attempt by leaseChangeEvent() only when it is processed, so a
3363
+ * worker that dies mid-batch loses none of them
3364
+ * @returns {Promise<{due: {event: Object, member: string}[], next: number|null}>} The due
3365
+ * changes, and when the next one is due (epoch ms, null when none is left)
3366
+ */
3367
+ async listDueChangeEvents() {
3368
+ const deferredKey = this.getDeferredQueueKey();
3369
+ const now = Date.now();
3370
+ const [[, members], [, nextDue]] = await this.redis
3371
+ .multi()
3372
+ .zrangebyscore(deferredKey, '-inf', now, 'LIMIT', 0, DEFERRED_CHANGE_BATCH)
3373
+ .zrangebyscore(deferredKey, `(${now}`, '+inf', 'WITHSCORES', 'LIMIT', 0, 1)
3374
+ .exec();
3375
+
3376
+ const due = [];
3377
+ for (const member of members) {
3378
+ try {
3379
+ due.push({ event: JSON.parse(member), member });
3380
+ } catch (err) {
3381
+ // one unreadable entry must not block every deferred change of the account
3382
+ this.logger.error({ msg: 'Dropping unreadable deferred mailbox change', account: this.account, member, err });
3383
+ await this.redis.zrem(deferredKey, member);
3384
+ }
3385
+ }
3386
+
3387
+ let next = nextDue.length ? Number(nextDue[1]) : null;
3388
+ if (members.length === DEFERRED_CHANGE_BATCH) {
3389
+ // a full batch was due, there may be more behind it
3390
+ next = now;
3391
+ }
3392
+
3393
+ return { due, next };
3394
+ }
3395
+
3396
+ /**
3397
+ * Stores a request to recover missed MS Graph change notifications as a deferred change that
3398
+ * is due now, so it survives a worker that is not running, is retried when it fails, and
3399
+ * several requests are served by one recovery pass (see OutlookClient.syncMissedMessages())
3400
+ */
3401
+ async queueMissedRecovery() {
3402
+ const now = Date.now();
3403
+ await this.deferChangeEvent({ type: 'missedRecovery', receivedAt: now }, now);
3404
+ }
3405
+
3406
+ /**
3407
+ * Swaps a deferred change for its next attempt before it is processed, see
3408
+ * BaseClient.processDueDeferredEvents()
3409
+ * @param {string} member - As listDueChangeEvents() returned it
3410
+ * @param {Object|null} next - The next attempt, null when the attempts are used up
3411
+ * @param {number} dueTime - When the next attempt is due
3412
+ * @returns {Promise<string|null>} The stored member of the next attempt
3413
+ */
3414
+ async leaseChangeEvent(member, next, dueTime) {
3415
+ const deferredKey = this.getDeferredQueueKey();
3416
+ let pipeline = this.redis.multi().zrem(deferredKey, member);
3417
+ const nextMember = next ? JSON.stringify(next) : null;
3418
+ if (nextMember) {
3419
+ pipeline = pipeline.zadd(deferredKey, dueTime, nextMember);
3420
+ }
3421
+ await pipeline.exec();
3422
+ return nextMember;
3423
+ }
3424
+
3425
+ /**
3426
+ * Moves a stored change to a new due time, when the change is already stored as the attempt
3427
+ * that is being deferred
3428
+ * @param {string} member - As leaseChangeEvent() returned it
3429
+ * @param {number} dueTime - Epoch milliseconds
3430
+ */
3431
+ async rescheduleChangeEvent(member, dueTime) {
3432
+ await this.redis.zadd(this.getDeferredQueueKey(), 'XX', dueTime, member);
3433
+ }
3434
+
3435
+ /**
3436
+ * Drops a leased change once it was processed or given up on
3437
+ * @param {string} member - As listDueChangeEvents() returned it
3438
+ */
3439
+ async completeChangeEvent(member) {
3440
+ await this.redis.zrem(this.getDeferredQueueKey(), member);
3441
+ }
3343
3442
  }
3344
3443
 
3444
+ const DEFERRED_CHANGE_BATCH = 100;
3445
+
3345
3446
  // Cheap existence probe that does not load or decrypt account data. The `account` field is
3346
3447
  // the mandatory marker field of the account hash (the same idiom the notify worker and
3347
3448
  // genId() rely on), so its presence is the canonical "this account exists" signal.
@@ -158,7 +158,10 @@ async function init(args) {
158
158
  });
159
159
 
160
160
  try {
161
- return await accountObject.getMessage(request.params.message, request.query);
161
+ // detectBounce is not a query option: it is what this route asks of the client, and
162
+ // the internal fetches (a reply's reference, the sync path) do not pay for it
163
+ let options = Object.assign({}, request.query, { detectBounce: true });
164
+ return await accountObject.getMessage(request.params.message, options);
162
165
  } catch (err) {
163
166
  handleError(request, err);
164
167
  }
package/lib/arf-detect.js CHANGED
@@ -6,6 +6,13 @@ const { toCamelCase } = require('./utils/to-camel-case');
6
6
  const { decodeHeaders } = require('./utils/decode-headers');
7
7
  const { isUnsafeTransformedKey } = require('./utils/unsafe-key');
8
8
 
9
+ // The attachment types a complaint is read from: the ARF report itself, and the copy of the
10
+ // original message beside it, which some feedback loops send as text/rfc822-headers. Both arrival
11
+ // paths gate and download on these lists, and the switch in arfDetect() parses every type in them
12
+ const FEEDBACK_REPORT_TYPE = 'message/feedback-report';
13
+ const ORIGINAL_MESSAGE_TYPES = ['message/rfc822', 'message/rfc822-headers', 'text/rfc822-headers', 'text/rfc822-header'];
14
+ const COMPLAINT_ATTACHMENT_TYPES = [FEEDBACK_REPORT_TYPE, ...ORIGINAL_MESSAGE_TYPES];
15
+
9
16
  const ARF_SINGLE = [
10
17
  'feedback-type',
11
18
  'user-agent',
@@ -234,4 +241,4 @@ function camelCaseComplaint(report) {
234
241
  return complaint;
235
242
  }
236
243
 
237
- module.exports = { arfDetect, camelCaseComplaint };
244
+ module.exports = { arfDetect, camelCaseComplaint, FEEDBACK_REPORT_TYPE, ORIGINAL_MESSAGE_TYPES, COMPLAINT_ATTACHMENT_TYPES };
package/lib/consts.js CHANGED
@@ -357,10 +357,19 @@ module.exports = {
357
357
  OUTLOOK_RETRY_BASE_DELAY: 30, // seconds - base delay for exponential backoff
358
358
  OUTLOOK_RETRY_MAX_DELAY: 120, // seconds - maximum delay between retries
359
359
  OUTLOOK_CLOCK_SKEW_BUFFER: 60 * 1000, // ms - buffer for clock skew between EmailEngine and MS Graph servers
360
+ // Graph retries an undeliverable change notification for up to 4 hours before dropping it and
361
+ // sending a `missed` lifecycle event, so the lost changes can be that old when recovery runs
362
+ OUTLOOK_MISSED_LOOKBACK: 4 * 60 * 60 * 1000, // ms
363
+ // How long announced new messages are remembered, so a recovery pass does not announce them again
364
+ OUTLOOK_ANNOUNCED_RETENTION: 6 * 60 * 60 * 1000, // ms
360
365
 
361
366
  // Google Pub/Sub subscription defaults
362
367
  GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL: '2678400s', // 31 days in seconds (Google's default)
363
368
  GMAIL_PUBSUB_ACK_DEADLINE_SECONDS: 30,
369
+ // A mailbox change the API clients (Gmail, MS Graph) failed to process on a transient provider
370
+ // error (5xx, 408, 429, network) is retried after each of these delays (ms), about 3.5 hours in all
371
+ CHANGE_EVENT_RETRY_DELAYS: [1, 4, 16, 60, 60, 60].map(minutes => minutes * 60 * 1000),
372
+
364
373
  // Transient network error codes that indicate a retry-worthy connection failure
365
374
  TRANSIENT_NETWORK_CODES: new Set([
366
375
  'ENOTFOUND',
package/lib/db.js CHANGED
@@ -128,7 +128,6 @@ const zGetByUidScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get-by-ui
128
128
  const zGetMailboxIdScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get-mailbox-id.lua'), 'utf-8');
129
129
  const zGetMailboxPathScript = fs.readFileSync(pathlib.join(__dirname, 'lua/z-get-mailbox-path.lua'), 'utf-8');
130
130
  const sListAccountsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/s-list-accounts.lua'), 'utf-8');
131
- const hPushScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-push.lua'), 'utf-8');
132
131
  const hSetBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-bigger.lua'), 'utf-8');
133
132
  const hUpdateBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-update-bigger.lua'), 'utf-8');
134
133
  const hSetExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-exists.lua'), 'utf-8');
@@ -156,11 +155,6 @@ redis.defineCommand('zGet', {
156
155
  lua: zGetScript
157
156
  });
158
157
 
159
- redis.defineCommand('hPush', {
160
- numberOfKeys: 1,
161
- lua: hPushScript
162
- });
163
-
164
158
  redis.defineCommand('zGetByUid', {
165
159
  numberOfKeys: 1,
166
160
  lua: zGetByUidScript