@rdlabo/ionic-angular-kit 22.0.8 → 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,9 @@ 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
+
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.
94
96
 
95
97
  When offline support is enabled, register `offlineInterceptor` before `kitAuthInterceptor`. Local mode then prevents credential generation and network transport while allowing a matched read policy to serve the scoped replica.
96
98
 
@@ -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 } 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';
@@ -997,6 +997,13 @@ function normalizeOfflineReplicaTransientWriteError(error) {
997
997
  return error;
998
998
  }
999
999
 
1000
+ /** Restore timeouts stored as permanent rejections by older versions of the outbox. */
1001
+ function recoverOfflineCommand(command) {
1002
+ return command.state === 'rejected' && command.lastErrorCode === '408'
1003
+ ? { ...command, state: 'retry_wait', retryAt: null, serverCommitUnknown: true }
1004
+ : command;
1005
+ }
1006
+
1000
1007
  /** Current durable storage schema used by both web and native repositories. */
1001
1008
  const OFFLINE_SCHEMA_VERSION = 2;
1002
1009
  const settledRepositoryOperation = async () => undefined;
@@ -1104,7 +1111,8 @@ class IonicOfflineRepository {
1104
1111
  async runReadSnapshot(read) {
1105
1112
  return this.#withCommittedRead(() => read(this.#reader()));
1106
1113
  }
1107
- #normalizeCommand(command) {
1114
+ #normalizeCommand(stored) {
1115
+ const command = recoverOfflineCommand(stored);
1108
1116
  if (command.serverCommitUnknown !== undefined)
1109
1117
  return command;
1110
1118
  const legacyAmbiguousFailure = command.attempts >= 2 && ['blocked_auth', 'conflict', 'rejected'].includes(command.state);
@@ -3435,6 +3443,13 @@ class OfflineSyncService {
3435
3443
  const scope = { userId, scopeId: request.scopeId };
3436
3444
  this.noteScope(scope);
3437
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;
3438
3453
  const commandId = request.commandId ?? crypto.randomUUID();
3439
3454
  if (typeof commandId !== 'string' || commandId.length === 0 || commandId.length > 255) {
3440
3455
  throw new Error('Offline command id must contain between 1 and 255 characters.');
@@ -3454,9 +3469,10 @@ class OfflineSyncService {
3454
3469
  payload: request.payload,
3455
3470
  replicaMutation: request.replicaMutation ?? 'upsert',
3456
3471
  baseRevision: request.baseRevision ?? null,
3457
- state: 'pending',
3472
+ state: retryAt === null ? 'pending' : 'retry_wait',
3473
+ ...(request.serverCommitUnknown && { serverCommitUnknown: true }),
3458
3474
  attempts: 0,
3459
- retryAt: null,
3475
+ retryAt,
3460
3476
  createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId, repository)),
3461
3477
  lastErrorCode: null,
3462
3478
  };
@@ -3617,8 +3633,8 @@ class OfflineSyncService {
3617
3633
  removeCommandIds: effectiveRemoveCommandIds,
3618
3634
  });
3619
3635
  await this.#refreshState(generation, repository).catch((error) => this.#reportError(error));
3620
- if (options.flush !== false && this.#canSynchronize())
3621
- this.#flushInBackground();
3636
+ if (options.flush !== false)
3637
+ this.#flushAfterMutation(generation);
3622
3638
  }
3623
3639
  #normalizedLocalOnlyFootprint(scope, footprint) {
3624
3640
  if (!footprint || footprint.length === 0)
@@ -3760,6 +3776,15 @@ class OfflineSyncService {
3760
3776
  throw new OfflineCommandInFlightError(ambiguous.map((command) => command.commandId));
3761
3777
  }
3762
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
+ }
3763
3788
  #flushInBackground() {
3764
3789
  void this.#beginFlush(false).catch((error) => this.#reportError(error));
3765
3790
  }
@@ -3804,13 +3829,8 @@ class OfflineSyncService {
3804
3829
  }, () => undefined)
3805
3830
  .finally(() => {
3806
3831
  this.#flushTransitions.delete(transition);
3807
- if (requiresReconciliation && this.#canSynchronize() && this.#isCurrentUser(generation, userId)) {
3808
- // A normal flush may already be in its post-pull phase. Ensure the
3809
- // newly acknowledged command receives a later reconciliation pass.
3810
- if (this.#flushPromise)
3811
- this.#resumeAfterFlush = true;
3812
- queueMicrotask(() => this.#flushInBackground());
3813
- }
3832
+ if (requiresReconciliation && this.#isCurrentUser(generation, userId))
3833
+ this.#flushAfterMutation(generation);
3814
3834
  });
3815
3835
  this.#flushTransitions.add(transition);
3816
3836
  return result;
@@ -3938,17 +3958,21 @@ class OfflineSyncService {
3938
3958
  return this.#flushPromise;
3939
3959
  }
3940
3960
  const generation = this.#generation;
3941
- const promise = this.#runFlush(generation, explicitFull).finally(() => {
3961
+ const finish = (succeeded) => {
3942
3962
  this.#flushTransitions.delete(promise);
3943
- if (this.#flushPromise === promise) {
3944
- this.#flushPromise = null;
3945
- this.#partialFlushInFlight = false;
3946
- }
3947
- const resumeAfterFlush = this.#resumeAfterFlush;
3963
+ if (this.#flushPromise !== promise)
3964
+ return;
3965
+ this.#flushPromise = null;
3966
+ this.#partialFlushInFlight = false;
3967
+ const resume = this.#resumeAfterFlush;
3948
3968
  this.#resumeAfterFlush = false;
3949
- if (resumeAfterFlush && this.#canSynchronize()) {
3950
- queueMicrotask(() => this.#flushInBackground());
3951
- }
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;
3952
3976
  });
3953
3977
  this.#flushLifecycleRevision = lifecycleRevision;
3954
3978
  this.#flushPromise = promise;
@@ -4001,8 +4025,7 @@ class OfflineSyncService {
4001
4025
  const sendWorkerFailures = [];
4002
4026
  while (this.#canSynchronize() && this.#isCurrent(generation) && fatalPullFailure === null) {
4003
4027
  const known = await this.#readKnownCommands();
4004
- const groups = this.#eligibleAggregateGroups(known).filter((group) => group.some((command) => (command.state === 'pending' || command.state === 'retry_wait') &&
4005
- 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)));
4006
4029
  if (!this.#isCurrent(generation))
4007
4030
  return;
4008
4031
  if (groups.length === 0)
@@ -4079,7 +4102,8 @@ class OfflineSyncService {
4079
4102
  throw failures[0];
4080
4103
  }
4081
4104
  if (this.#isCurrent(generation)) {
4082
- 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()) {
4083
4107
  if (command.state !== 'awaiting_pull')
4084
4108
  continue;
4085
4109
  const scope = { userId: command.userId, scopeId: command.scopeId };
@@ -4165,16 +4189,20 @@ class OfflineSyncService {
4165
4189
  attentionScopeKeys.has(this.#scopeKey(scope)) ||
4166
4190
  this.#pendingPullScopes.has(this.#scopeKey(scope)));
4167
4191
  }
4168
- #eligibleAggregateGroups(commands) {
4169
- const now = Date.now();
4192
+ /** Commands are already in durable FIFO order. Only each aggregate's first unsent command can run. */
4193
+ #unsentAggregateGroups(commands) {
4170
4194
  const groups = new Map();
4171
4195
  for (const command of commands) {
4196
+ if (command.state === 'awaiting_pull')
4197
+ continue;
4172
4198
  const key = this.#aggregateKey(command);
4173
- const group = groups.get(key) ?? [];
4174
- group.push(command);
4175
- groups.set(key, group);
4199
+ const group = groups.get(key);
4200
+ if (group)
4201
+ group.push(command);
4202
+ else
4203
+ groups.set(key, [command]);
4176
4204
  }
4177
- return [...groups.values()].filter((group) => group.some((command) => command.state === 'pending' || (command.state === 'retry_wait' && (command.retryAt ?? 0) <= now)));
4205
+ return [...groups.values()];
4178
4206
  }
4179
4207
  async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
4180
4208
  for (const command of commands) {
@@ -4203,9 +4231,7 @@ class OfflineSyncService {
4203
4231
  return false;
4204
4232
  if (command.state === 'awaiting_pull')
4205
4233
  return true;
4206
- if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
4207
- return false;
4208
- if (!['pending', 'retry_wait'].includes(command.state))
4234
+ if (!canSendOfflineCommand(command))
4209
4235
  return false;
4210
4236
  // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
4211
4237
  // belong to scopes that failed pre-pull even when the head was admitted.
@@ -4456,10 +4482,12 @@ class OfflineSyncService {
4456
4482
  if (status === 409 || status === 412) {
4457
4483
  return { ...command, state: 'conflict', lastErrorCode: String(status), serverCommitUnknown };
4458
4484
  }
4459
- if (status >= 400 && status < 500 && status !== 429) {
4485
+ if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
4460
4486
  return { ...command, state: 'rejected', lastErrorCode: String(status), serverCommitUnknown };
4461
4487
  }
4462
- 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));
4463
4491
  return {
4464
4492
  ...command,
4465
4493
  state: 'retry_wait',
@@ -4504,7 +4532,7 @@ class OfflineSyncService {
4504
4532
  }
4505
4533
  #serverCommitCouldBeUnknown(error) {
4506
4534
  const status = this.#errorStatus(error);
4507
- return status === 0 || status === 429 || status >= 500;
4535
+ return status === 0 || status === 429 || isWriteOutcomeUnknown(error);
4508
4536
  }
4509
4537
  #reportError(error) {
4510
4538
  queueMicrotask(() => this.#dispatchError(error));
@@ -4658,9 +4686,12 @@ class OfflineSyncService {
4658
4686
  return;
4659
4687
  this.#commands.set(commands);
4660
4688
  this.#pullAttentions.set(attentions);
4661
- const nextRetry = commands
4662
- .filter((command) => command.state === 'retry_wait' && command.retryAt !== null)
4663
- .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
+ }
4664
4695
  this.#scheduleRetry(nextRetry);
4665
4696
  }
4666
4697
  #scheduleRetry(retryAt) {
@@ -4671,9 +4702,11 @@ class OfflineSyncService {
4671
4702
  return;
4672
4703
  this.#retryTimer = setTimeout(() => {
4673
4704
  this.#retryTimer = null;
4674
- if (this.#canSynchronize())
4705
+ if (retryAt > Date.now())
4706
+ this.#scheduleRetry(retryAt);
4707
+ else if (this.#canSynchronize())
4675
4708
  this.#flushInBackground();
4676
- }, Math.max(0, retryAt - Date.now()));
4709
+ }, Math.min(2_147_483_647, Math.max(0, retryAt - Date.now())));
4677
4710
  }
4678
4711
  #invalidateFlush() {
4679
4712
  this.#generation += 1;
@@ -4705,7 +4738,7 @@ class OfflineSyncService {
4705
4738
  return null;
4706
4739
  const scope = { userId: command.userId, scopeId: command.scopeId };
4707
4740
  const current = (await repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4708
- if (!current || !['pending', 'retry_wait'].includes(current.state))
4741
+ if (!current || !canSendOfflineCommand(current))
4709
4742
  return null;
4710
4743
  const sending = {
4711
4744
  ...current,
@@ -4802,6 +4835,9 @@ function assertOfflinePayload(value, ancestors = new Set()) {
4802
4835
  assertOfflinePayload(item, ancestors);
4803
4836
  ancestors.delete(value);
4804
4837
  }
4838
+ function canSendOfflineCommand(command) {
4839
+ return command.state === 'pending' || (command.state === 'retry_wait' && (command.retryAt ?? 0) <= Date.now());
4840
+ }
4805
4841
  function compareOfflineCommands(left, right) {
4806
4842
  return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
4807
4843
  }
@@ -6862,7 +6898,7 @@ class SqliteOfflineRepository {
6862
6898
  return this.#number(rows[0]?.['data_version']);
6863
6899
  }
6864
6900
  #command(row) {
6865
- return {
6901
+ const command = {
6866
6902
  commandId: this.#string(row['command_id']),
6867
6903
  userId: parseOfflinePrincipalId(this.#string(row['user_id'])),
6868
6904
  scopeId: this.#string(row['scope_id']),
@@ -6895,6 +6931,7 @@ class SqliteOfflineRepository {
6895
6931
  ? {}
6896
6932
  : { reconciliationIdentity: this.#parse(row['reconciliation_identity_json']) }),
6897
6933
  };
6934
+ return recoverOfflineCommand(command);
6898
6935
  }
6899
6936
  #putCommand(databaseId, command) {
6900
6937
  return this.#execute(databaseId, `INSERT INTO offline_sync_commands