emailengine-app 2.81.0 → 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.
@@ -321,6 +321,7 @@ class GmailClient extends BaseClient {
321
321
 
322
322
  this.state = 'connecting';
323
323
  this.cancelInitRetry();
324
+ this.cancelDeferredRetryTimer();
324
325
  await this.setStateVal();
325
326
 
326
327
  await this.getAccount();
@@ -513,6 +514,7 @@ class GmailClient extends BaseClient {
513
514
  clearTimeout(this.renewWatchTimer);
514
515
  clearTimeout(this.fallbackPollingTimer);
515
516
  this.cancelInitRetry();
517
+ this.cancelDeferredRetryTimer();
516
518
  this.closed = true;
517
519
 
518
520
  // A graceful close means the in-flight history entry did not kill this
@@ -589,6 +591,7 @@ class GmailClient extends BaseClient {
589
591
  clearTimeout(this.renewWatchTimer);
590
592
  clearTimeout(this.fallbackPollingTimer);
591
593
  this.cancelInitRetry();
594
+ this.cancelDeferredRetryTimer();
592
595
  this.closed = true;
593
596
 
594
597
  // Clean up cached data
@@ -1333,10 +1336,8 @@ class GmailClient extends BaseClient {
1333
1336
  }
1334
1337
  }
1335
1338
 
1336
- // Bounces recorded against this message by processNew(). The sync path fetches new
1337
- // messages through here as well and never reads the field, so it skips the lookup
1338
- if (!options.skipBounces) {
1339
- await this.attachBounces(formattedMessage);
1339
+ if (options.detectBounce) {
1340
+ await this.detectBounce(formattedMessage);
1340
1341
  }
1341
1342
 
1342
1343
  // Generate web-safe HTML if requested
@@ -2119,19 +2120,8 @@ class GmailClient extends BaseClient {
2119
2120
  timeSinceNotification
2120
2121
  });
2121
2122
 
2122
- try {
2123
- const historyId = await this.redis.hget(this.getAccountKey(), 'googleHistoryId');
2124
- if (historyId) {
2125
- // Trigger sync to check for any missed changes
2126
- this.triggerSync(Number(historyId), Number(historyId));
2127
- }
2128
- } catch (err) {
2129
- this.logger.error({
2130
- msg: 'Failed to trigger fallback sync',
2131
- account: this.account,
2132
- err
2133
- });
2134
- }
2123
+ // Trigger sync to check for any missed changes
2124
+ this.triggerSyncFromCursor();
2135
2125
  }
2136
2126
 
2137
2127
  // Restart the timer
@@ -2946,17 +2936,15 @@ class GmailClient extends BaseClient {
2946
2936
  })
2947
2937
  .finally(() => {
2948
2938
  this.processingHistory = false;
2939
+ this.scheduleDeferredRetryTimer();
2949
2940
  // Process any queued sync notifications
2950
2941
  if (this.pendingHistoryId && this.pendingHistoryId > processedHistoryId) {
2951
2942
  const pending = this.pendingHistoryId;
2952
2943
  this.pendingHistoryId = null;
2953
- this.logger.debug({
2954
- msg: 'Processing queued historyId',
2955
- account: this.account,
2956
- fromHistoryId: processedHistoryId,
2957
- toHistoryId: pending
2958
- });
2959
- this.triggerSync(processedHistoryId, pending);
2944
+ // From the stored cursor, not from where the finished run was headed: a run that
2945
+ // failed partway left the cursor behind that, and the entries in between would
2946
+ // never be fetched
2947
+ this.triggerSyncFromCursor(pending);
2960
2948
  } else {
2961
2949
  this.pendingHistoryId = null;
2962
2950
  }
@@ -2967,8 +2955,8 @@ class GmailClient extends BaseClient {
2967
2955
  * Processes a single history entry for changes
2968
2956
  * @param {Object} historyEntry - Gmail history entry
2969
2957
  */
2970
- async processHistoryEntry(historyEntry) {
2971
- let labels = await this.getLabels();
2958
+ async processHistoryEntry(historyEntry, context) {
2959
+ const { labels, newMessageOptions } = context || (await this.getHistoryContext());
2972
2960
 
2973
2961
  /**
2974
2962
  * Processes label changes and sends update notifications
@@ -3081,8 +3069,8 @@ class GmailClient extends BaseClient {
3081
3069
  await this.notify(this, MESSAGE_DELETED_NOTIFY, messageUpdate);
3082
3070
  }
3083
3071
 
3084
- // Process new messages
3085
- const newMessageOptions = await this.getMessageFetchOptions();
3072
+ // Process new messages. Each is fetched on its own, so one that fails is retried on its own
3073
+ // and does not take the rest of the entry with it
3086
3074
  for (let entry of historyEntry?.messagesAdded || []) {
3087
3075
  if (!entry?.message) {
3088
3076
  continue;
@@ -3097,13 +3085,62 @@ class GmailClient extends BaseClient {
3097
3085
  category: messageCategory
3098
3086
  };
3099
3087
 
3100
- const messageData = await this.prepareNewMessage(eventEntry, newMessageOptions);
3088
+ await this.processAddedMessage(eventEntry, newMessageOptions);
3089
+ }
3090
+ }
3091
+
3092
+ /**
3093
+ * Fetches a message reported as added and announces it, deferring it for a retry on failure
3094
+ * @param {Object} eventEntry - Message event data
3095
+ * @param {Object} options - Message fetch options
3096
+ * @param {Object} [event] - The deferred change being retried, when this is a retry
3097
+ */
3098
+ async processAddedMessage(eventEntry, options, event) {
3099
+ try {
3100
+ const messageData = await this.prepareNewMessage(eventEntry, options);
3101
3101
  if (messageData) {
3102
- await this.processNew(messageData, newMessageOptions);
3102
+ await this.processNew(messageData, options);
3103
3103
  }
3104
+ } catch (err) {
3105
+ await this.deferFailedChangeEvent(event || { type: 'created', message: eventEntry }, err);
3104
3106
  }
3105
3107
  }
3106
3108
 
3109
+ /**
3110
+ * What every history entry of a run needs from the API and the settings, resolved once per
3111
+ * run. Fetched before any entry is processed, so a failure here ends the run with the cursor
3112
+ * where it was and the next run fetches the same entries again: deferring each entry instead
3113
+ * would replay its label changes hours later, over whatever changed since
3114
+ * @returns {Promise<{labels: Object[], newMessageOptions: Object}>}
3115
+ */
3116
+ async getHistoryContext() {
3117
+ const [labels, newMessageOptions] = await Promise.all([this.getLabels(), this.getMessageFetchOptions()]);
3118
+ return { labels, newMessageOptions };
3119
+ }
3120
+
3121
+ retryDeferredEvents() {
3122
+ // the same run a fallback poll makes, which picks up the due changes
3123
+ this.triggerSyncFromCursor();
3124
+ }
3125
+
3126
+ /**
3127
+ * Starts a history run from the stored cursor
3128
+ * @param {number} [updatedHistoryId] - Where the run is headed, the cursor itself by default
3129
+ */
3130
+ triggerSyncFromCursor(updatedHistoryId) {
3131
+ this.redis
3132
+ .hget(this.getAccountKey(), 'googleHistoryId')
3133
+ .then(historyId => {
3134
+ if (historyId && !this.closed) {
3135
+ this.logger.debug({ msg: 'Processing history from the stored cursor', account: this.account, historyId, updatedHistoryId });
3136
+ this.triggerSync(Number(historyId), Math.max(Number(historyId), updatedHistoryId || 0));
3137
+ }
3138
+ })
3139
+ .catch(err => {
3140
+ this.logger.error({ msg: 'Failed to read the history cursor', account: this.account, err });
3141
+ });
3142
+ }
3143
+
3107
3144
  /**
3108
3145
  * Processes Gmail history changes since last sync
3109
3146
  * @param {number} currentHistoryId - Starting history ID
@@ -3113,6 +3150,18 @@ class GmailClient extends BaseClient {
3113
3150
  let newestHistoryId = currentHistoryId;
3114
3151
  let lastHistoryId = currentHistoryId;
3115
3152
 
3153
+ // Resolved on first use, and once for the whole run, a failure included
3154
+ let contextPromise;
3155
+ const getContext = () => (contextPromise = contextPromise || this.getHistoryContext());
3156
+
3157
+ // Messages deferred for a retry, every one of them a message reported as added. A context
3158
+ // failure is thrown, and processDueDeferredEvents() defers the message for it
3159
+ try {
3160
+ await this.processDueDeferredEvents(async event => this.processAddedMessage(event.message, (await getContext()).newMessageOptions, event));
3161
+ } catch (err) {
3162
+ this.logger.error({ msg: 'Failed to process deferred mailbox changes', account: this.account, err });
3163
+ }
3164
+
3116
3165
  // The history cursor only advances after an entry is processed, so an
3117
3166
  // entry that kills the worker (OOM, heartbeat restart) is refetched by
3118
3167
  // the restarted worker and would loop forever. The in-flight marker
@@ -3166,8 +3215,17 @@ class GmailClient extends BaseClient {
3166
3215
  type: 'historyIdExpired',
3167
3216
  message: 'Some email changes may have been missed due to expired history ID'
3168
3217
  });
3169
- // Set to newest known value
3218
+ // Set to newest known value. A fallback poll or a retry is headed nowhere past
3219
+ // the expired cursor, so ask for the current one, or every run would 404 again
3170
3220
  newestHistoryId = updatedHistoryId;
3221
+ if (!(updatedHistoryId > currentHistoryId)) {
3222
+ try {
3223
+ const profileRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`);
3224
+ newestHistoryId = Number(profileRes?.historyId) || newestHistoryId;
3225
+ } catch (profileErr) {
3226
+ this.logger.warn({ msg: 'Failed to fetch the current history ID', account: this.account, err: profileErr });
3227
+ }
3228
+ }
3171
3229
  return;
3172
3230
  }
3173
3231
  default:
@@ -3175,6 +3233,10 @@ class GmailClient extends BaseClient {
3175
3233
  }
3176
3234
  }
3177
3235
 
3236
+ // Before any entry is marked in flight: a failure here ends the run with the cursor
3237
+ // where it was, see getHistoryContext()
3238
+ const context = historyRes?.history?.length ? await getContext() : null;
3239
+
3178
3240
  // Process each history entry
3179
3241
  for (let entry of historyRes?.history || []) {
3180
3242
  let historyEntryId = Number(entry?.id) || null;
@@ -3210,7 +3272,8 @@ class GmailClient extends BaseClient {
3210
3272
  }
3211
3273
 
3212
3274
  try {
3213
- await this.processHistoryEntry(entry);
3275
+ // A message in the entry that fails to fetch is deferred on its own inside
3276
+ await this.processHistoryEntry(entry, context);
3214
3277
  await advanceHistoryCursor(historyEntryId);
3215
3278
  } catch (err) {
3216
3279
  this.logger.error({
@@ -3263,9 +3326,6 @@ class GmailClient extends BaseClient {
3263
3326
  options.headers = 'headers' in options ? options.headers : false;
3264
3327
  }
3265
3328
 
3266
- // The sync path never reads the bounces field
3267
- options.skipBounces = true;
3268
-
3269
3329
  let messageData;
3270
3330
  try {
3271
3331
  messageData = await this.getMessage(eventEntry.id, options);