@rdlabo/ionic-angular-kit 22.0.9 → 22.0.10

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/docs/auth-http.md CHANGED
@@ -90,7 +90,7 @@ export const appConfig: ApplicationConfig = {
90
90
  };
91
91
  ```
92
92
 
93
- Automatic retry is limited to `GET`, `HEAD`, `OPTIONS`, or requests carrying an `Idempotency-Key`. Ordinary writes are never retried automatically. Retries cover transient statuses `0`, `408`, `429`, `502`, `503`, and `504`, and honor `Retry-After`.
93
+ Automatic retry is limited to `GET`, `HEAD`, `OPTIONS`, or requests carrying an `Idempotency-Key`. Ordinary writes are never retried automatically. Retries cover transient statuses `0`, `408`, `429`, `502`, `503`, and `504`, and honor `Retry-After`. When the requested delay exceeds the platform timer limit (2,147,483,647 ms, about 24.9 days), the interceptor stops retrying and applies normal error handling. An eligible `offlineFallback` receives the error with its original header and may return an alternative response. Otherwise the error propagates to the caller.
94
94
 
95
95
  For keyed writes, `isWriteOutcomeUnknown(error)` is true for a lost response, timeout, or server error, including when a later retry returns a different HTTP status. Reuse the original key and payload when retrying such a write.
96
96
 
@@ -107,6 +107,8 @@ An `OfflineRequestPolicy` resolves a matched GET to `kind: 'read'`, a `readLocal
107
107
 
108
108
  Mutation policies prepare the optimistic `HttpResponse`; the product implementation should enqueue the corresponding durable intent before returning it. `enqueue()` generates a UUID by default. Supply a stable `commandId` when product code must correlate the durable intent with surrounding work or immediately send a newly created generated identity. Kit preserves that ID across transport retries.
109
109
 
110
+ When a foreground write may already have reached the server, enqueue the original payload with its original `commandId` and `serverCommitUnknown: true`. Pass `retryAt` as an absolute Unix timestamp in milliseconds when the server has requested a delay. Kit persists both values in the same transaction as the optimistic change.
111
+
110
112
  ```ts
111
113
  import type { OfflineGeneratedCommandLocator } from '@rdlabo/ionic-angular-kit/offline';
112
114
 
@@ -1,6 +1,6 @@
1
1
  import * as i0 from '@angular/core';
2
2
  import { InjectionToken, inject, Injectable, signal, computed, ErrorHandler, effect, untracked, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
3
- import { KitStorageService, isWriteOutcomeUnknown } from '@rdlabo/ionic-angular-kit';
3
+ import { KitStorageService, parseRetryAfterMs, isWriteOutcomeUnknown } from '@rdlabo/ionic-angular-kit';
4
4
  import { toObservable } from '@angular/core/rxjs-interop';
5
5
  import { map as map$1, distinctUntilChanged } from 'rxjs/operators';
6
6
  import { HttpContextToken, HttpClient, HttpContext, HttpErrorResponse, HttpResponse } from '@angular/common/http';
@@ -3443,6 +3443,13 @@ class OfflineSyncService {
3443
3443
  const scope = { userId, scopeId: request.scopeId };
3444
3444
  this.noteScope(scope);
3445
3445
  const commandIdentity = offlineCommandLookupIdentity(request.identity);
3446
+ if (request.serverCommitUnknown && !request.commandId) {
3447
+ throw new Error('A previously attempted write requires its original commandId.');
3448
+ }
3449
+ if (request.retryAt !== undefined && !Number.isSafeInteger(request.retryAt)) {
3450
+ throw new Error('Offline retryAt must be an integer timestamp in milliseconds.');
3451
+ }
3452
+ const retryAt = request.retryAt !== undefined && request.retryAt > Date.now() ? request.retryAt : null;
3446
3453
  const commandId = request.commandId ?? crypto.randomUUID();
3447
3454
  if (typeof commandId !== 'string' || commandId.length === 0 || commandId.length > 255) {
3448
3455
  throw new Error('Offline command id must contain between 1 and 255 characters.');
@@ -3462,9 +3469,10 @@ class OfflineSyncService {
3462
3469
  payload: request.payload,
3463
3470
  replicaMutation: request.replicaMutation ?? 'upsert',
3464
3471
  baseRevision: request.baseRevision ?? null,
3465
- state: 'pending',
3472
+ state: retryAt === null ? 'pending' : 'retry_wait',
3473
+ ...(request.serverCommitUnknown && { serverCommitUnknown: true }),
3466
3474
  attempts: 0,
3467
- retryAt: null,
3475
+ retryAt,
3468
3476
  createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId, repository)),
3469
3477
  lastErrorCode: null,
3470
3478
  };
@@ -3625,8 +3633,8 @@ class OfflineSyncService {
3625
3633
  removeCommandIds: effectiveRemoveCommandIds,
3626
3634
  });
3627
3635
  await this.#refreshState(generation, repository).catch((error) => this.#reportError(error));
3628
- if (options.flush !== false && this.#canSynchronize())
3629
- this.#flushInBackground();
3636
+ if (options.flush !== false)
3637
+ this.#flushAfterMutation(generation);
3630
3638
  }
3631
3639
  #normalizedLocalOnlyFootprint(scope, footprint) {
3632
3640
  if (!footprint || footprint.length === 0)
@@ -3768,6 +3776,15 @@ class OfflineSyncService {
3768
3776
  throw new OfflineCommandInFlightError(ambiguous.map((command) => command.commandId));
3769
3777
  }
3770
3778
  }
3779
+ #flushAfterMutation(generation) {
3780
+ if (!this.#isCurrent(generation) || !this.#canSynchronize())
3781
+ return;
3782
+ // The active flush may already have finished its send loop.
3783
+ if (this.#flushPromise)
3784
+ this.#resumeAfterFlush = true;
3785
+ else
3786
+ this.#flushInBackground();
3787
+ }
3771
3788
  #flushInBackground() {
3772
3789
  void this.#beginFlush(false).catch((error) => this.#reportError(error));
3773
3790
  }
@@ -3812,13 +3829,8 @@ class OfflineSyncService {
3812
3829
  }, () => undefined)
3813
3830
  .finally(() => {
3814
3831
  this.#flushTransitions.delete(transition);
3815
- if (requiresReconciliation && this.#canSynchronize() && this.#isCurrentUser(generation, userId)) {
3816
- // A normal flush may already be in its post-pull phase. Ensure the
3817
- // newly acknowledged command receives a later reconciliation pass.
3818
- if (this.#flushPromise)
3819
- this.#resumeAfterFlush = true;
3820
- queueMicrotask(() => this.#flushInBackground());
3821
- }
3832
+ if (requiresReconciliation && this.#isCurrentUser(generation, userId))
3833
+ this.#flushAfterMutation(generation);
3822
3834
  });
3823
3835
  this.#flushTransitions.add(transition);
3824
3836
  return result;
@@ -3946,17 +3958,21 @@ class OfflineSyncService {
3946
3958
  return this.#flushPromise;
3947
3959
  }
3948
3960
  const generation = this.#generation;
3949
- const promise = this.#runFlush(generation, explicitFull).finally(() => {
3961
+ const finish = (succeeded) => {
3950
3962
  this.#flushTransitions.delete(promise);
3951
- if (this.#flushPromise === promise) {
3952
- this.#flushPromise = null;
3953
- this.#partialFlushInFlight = false;
3954
- }
3955
- const resumeAfterFlush = this.#resumeAfterFlush;
3963
+ if (this.#flushPromise !== promise)
3964
+ return;
3965
+ this.#flushPromise = null;
3966
+ this.#partialFlushInFlight = false;
3967
+ const resume = this.#resumeAfterFlush;
3956
3968
  this.#resumeAfterFlush = false;
3957
- if (resumeAfterFlush && this.#canSynchronize()) {
3958
- queueMicrotask(() => this.#flushInBackground());
3959
- }
3969
+ // A full flush already chained to this partial flush will pick up the new work.
3970
+ if (succeeded && resume && !(isPartial && this.#chainedFullFlush))
3971
+ this.#flushAfterMutation(generation);
3972
+ };
3973
+ const promise = this.#runFlush(generation, explicitFull).then(() => finish(true), (error) => {
3974
+ finish(false);
3975
+ throw error;
3960
3976
  });
3961
3977
  this.#flushLifecycleRevision = lifecycleRevision;
3962
3978
  this.#flushPromise = promise;
@@ -4009,8 +4025,7 @@ class OfflineSyncService {
4009
4025
  const sendWorkerFailures = [];
4010
4026
  while (this.#canSynchronize() && this.#isCurrent(generation) && fatalPullFailure === null) {
4011
4027
  const known = await this.#readKnownCommands();
4012
- const groups = this.#eligibleAggregateGroups(known).filter((group) => group.some((command) => (command.state === 'pending' || command.state === 'retry_wait') &&
4013
- pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId }))));
4028
+ const groups = this.#unsentAggregateGroups(known).filter(([head]) => canSendOfflineCommand(head) && pulledScopeKeys.has(this.#scopeKey(head)));
4014
4029
  if (!this.#isCurrent(generation))
4015
4030
  return;
4016
4031
  if (groups.length === 0)
@@ -4087,7 +4102,8 @@ class OfflineSyncService {
4087
4102
  throw failures[0];
4088
4103
  }
4089
4104
  if (this.#isCurrent(generation)) {
4090
- for (const command of await this.#readKnownCommands()) {
4105
+ // Use the snapshot that armed the retry timer; another async read here can swallow its wake-up.
4106
+ for (const command of this.#commands()) {
4091
4107
  if (command.state !== 'awaiting_pull')
4092
4108
  continue;
4093
4109
  const scope = { userId: command.userId, scopeId: command.scopeId };
@@ -4173,16 +4189,20 @@ class OfflineSyncService {
4173
4189
  attentionScopeKeys.has(this.#scopeKey(scope)) ||
4174
4190
  this.#pendingPullScopes.has(this.#scopeKey(scope)));
4175
4191
  }
4176
- #eligibleAggregateGroups(commands) {
4177
- const now = Date.now();
4192
+ /** Commands are already in durable FIFO order. Only each aggregate's first unsent command can run. */
4193
+ #unsentAggregateGroups(commands) {
4178
4194
  const groups = new Map();
4179
4195
  for (const command of commands) {
4196
+ if (command.state === 'awaiting_pull')
4197
+ continue;
4180
4198
  const key = this.#aggregateKey(command);
4181
- const group = groups.get(key) ?? [];
4182
- group.push(command);
4183
- groups.set(key, group);
4199
+ const group = groups.get(key);
4200
+ if (group)
4201
+ group.push(command);
4202
+ else
4203
+ groups.set(key, [command]);
4184
4204
  }
4185
- return [...groups.values()].filter((group) => group.some((command) => command.state === 'pending' || (command.state === 'retry_wait' && (command.retryAt ?? 0) <= now)));
4205
+ return [...groups.values()];
4186
4206
  }
4187
4207
  async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
4188
4208
  for (const command of commands) {
@@ -4211,9 +4231,7 @@ class OfflineSyncService {
4211
4231
  return false;
4212
4232
  if (command.state === 'awaiting_pull')
4213
4233
  return true;
4214
- if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
4215
- return false;
4216
- if (!['pending', 'retry_wait'].includes(command.state))
4234
+ if (!canSendOfflineCommand(command))
4217
4235
  return false;
4218
4236
  // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
4219
4237
  // belong to scopes that failed pre-pull even when the head was admitted.
@@ -4467,7 +4485,9 @@ class OfflineSyncService {
4467
4485
  if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
4468
4486
  return { ...command, state: 'rejected', lastErrorCode: String(status), serverCommitUnknown };
4469
4487
  }
4470
- const retryAt = Date.now() + offlineRetryDelayMs(command.attempts, this.#retryRandom);
4488
+ const retryAfter = error instanceof HttpErrorResponse ? parseRetryAfterMs(error) : null;
4489
+ const delay = Math.max(offlineRetryDelayMs(command.attempts, this.#retryRandom), retryAfter ?? 0);
4490
+ const retryAt = Math.min(Number.MAX_SAFE_INTEGER, Date.now() + Math.ceil(delay));
4471
4491
  return {
4472
4492
  ...command,
4473
4493
  state: 'retry_wait',
@@ -4666,9 +4686,12 @@ class OfflineSyncService {
4666
4686
  return;
4667
4687
  this.#commands.set(commands);
4668
4688
  this.#pullAttentions.set(attentions);
4669
- const nextRetry = commands
4670
- .filter((command) => command.state === 'retry_wait' && command.retryAt !== null)
4671
- .reduce((earliest, command) => Math.min(earliest ?? command.retryAt, command.retryAt), null);
4689
+ let nextRetry = null;
4690
+ for (const [head] of this.#unsentAggregateGroups(commands)) {
4691
+ if (head.state === 'retry_wait' && head.retryAt !== null) {
4692
+ nextRetry = Math.min(nextRetry ?? head.retryAt, head.retryAt);
4693
+ }
4694
+ }
4672
4695
  this.#scheduleRetry(nextRetry);
4673
4696
  }
4674
4697
  #scheduleRetry(retryAt) {
@@ -4679,9 +4702,11 @@ class OfflineSyncService {
4679
4702
  return;
4680
4703
  this.#retryTimer = setTimeout(() => {
4681
4704
  this.#retryTimer = null;
4682
- if (this.#canSynchronize())
4705
+ if (retryAt > Date.now())
4706
+ this.#scheduleRetry(retryAt);
4707
+ else if (this.#canSynchronize())
4683
4708
  this.#flushInBackground();
4684
- }, Math.max(0, retryAt - Date.now()));
4709
+ }, Math.min(2_147_483_647, Math.max(0, retryAt - Date.now())));
4685
4710
  }
4686
4711
  #invalidateFlush() {
4687
4712
  this.#generation += 1;
@@ -4713,7 +4738,7 @@ class OfflineSyncService {
4713
4738
  return null;
4714
4739
  const scope = { userId: command.userId, scopeId: command.scopeId };
4715
4740
  const current = (await repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4716
- if (!current || !['pending', 'retry_wait'].includes(current.state))
4741
+ if (!current || !canSendOfflineCommand(current))
4717
4742
  return null;
4718
4743
  const sending = {
4719
4744
  ...current,
@@ -4810,6 +4835,9 @@ function assertOfflinePayload(value, ancestors = new Set()) {
4810
4835
  assertOfflinePayload(item, ancestors);
4811
4836
  ancestors.delete(value);
4812
4837
  }
4838
+ function canSendOfflineCommand(command) {
4839
+ return command.state === 'pending' || (command.state === 'retry_wait' && (command.retryAt ?? 0) <= Date.now());
4840
+ }
4813
4841
  function compareOfflineCommands(left, right) {
4814
4842
  return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
4815
4843
  }