@classic-homes/offline-core 0.1.4 → 0.2.0
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/README.md +2 -2
- package/dist/cache/index.d.ts +17 -1
- package/dist/cache/index.js +6 -6
- package/dist/{chunk-XHMX3BYT.js → chunk-34PR6T4B.js} +231 -59
- package/dist/{chunk-IDRYBB6Z.js → chunk-4KL3GDYP.js} +204 -80
- package/dist/{chunk-ZDXEYCDZ.js → chunk-JPXEFKZO.js} +99 -28
- package/dist/{chunk-4QWZX3LM.js → chunk-MA4ZHPQS.js} +110 -27
- package/dist/{chunk-ZC7F2HDV.js → chunk-QS7N4PTV.js} +5 -2
- package/dist/{chunk-U27TKOYZ.js → chunk-R2IP2AA5.js} +2 -2
- package/dist/{chunk-IIG4QLLN.js → chunk-UL7MZBSF.js} +2 -2
- package/dist/drafts/index.d.ts +46 -9
- package/dist/drafts/index.js +3 -3
- package/dist/files/index.js +2 -2
- package/dist/index.d.ts +7 -4
- package/dist/index.js +7 -7
- package/dist/storage/index.d.ts +11 -1
- package/dist/storage/index.js +2 -2
- package/dist/sync/index.d.ts +64 -7
- package/dist/sync/index.js +3 -3
- package/dist/{types-Ho1JiLQR.d.ts → types-CRMTQnjY.d.ts} +6 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -238,8 +238,8 @@ import { createCacheService } from '@classic-homes/offline-core/cache';
|
|
|
238
238
|
## Default Expirations
|
|
239
239
|
|
|
240
240
|
- **Files**: 7 days
|
|
241
|
-
- **Drafts**:
|
|
242
|
-
- **Cache**:
|
|
241
|
+
- **Drafts**: 7 days (extended on every edit)
|
|
242
|
+
- **Cache**: 1 hour
|
|
243
243
|
|
|
244
244
|
These can be overridden per-operation.
|
|
245
245
|
|
package/dist/cache/index.d.ts
CHANGED
|
@@ -26,6 +26,11 @@ interface CacheOptions {
|
|
|
26
26
|
ttl?: number;
|
|
27
27
|
/** Tags for bulk invalidation */
|
|
28
28
|
tags?: string[];
|
|
29
|
+
/**
|
|
30
|
+
* How long an expired entry is kept for stale reads before storage cleanup
|
|
31
|
+
* deletes it (default: ttl)
|
|
32
|
+
*/
|
|
33
|
+
staleTime?: number;
|
|
29
34
|
}
|
|
30
35
|
/**
|
|
31
36
|
* Options for the getOrSet operation
|
|
@@ -109,7 +114,7 @@ interface CacheServiceOptions {
|
|
|
109
114
|
maxInFlight?: number;
|
|
110
115
|
/** Maximum number of cache entries (default: 1000) */
|
|
111
116
|
maxEntries?: number;
|
|
112
|
-
/** Maximum total cache
|
|
117
|
+
/** Maximum total size of this cache's entries in bytes, approximate (default: 50MB) */
|
|
113
118
|
maxSizeBytes?: number;
|
|
114
119
|
}
|
|
115
120
|
/**
|
|
@@ -124,6 +129,8 @@ declare class CacheService {
|
|
|
124
129
|
private readonly maxEntries;
|
|
125
130
|
private readonly maxSizeBytes;
|
|
126
131
|
private accessOrder;
|
|
132
|
+
private entrySizes;
|
|
133
|
+
private entrySizesLoading;
|
|
127
134
|
constructor(adapter: StorageAdapter, options?: CacheServiceOptions);
|
|
128
135
|
/**
|
|
129
136
|
* Clean up stale in-flight requests
|
|
@@ -137,11 +144,20 @@ declare class CacheService {
|
|
|
137
144
|
* Set a cached value
|
|
138
145
|
*/
|
|
139
146
|
set<T>(key: string, value: T, options?: CacheOptions): Promise<void>;
|
|
147
|
+
/**
|
|
148
|
+
* Sizes of this cache's entries, read from storage the first time
|
|
149
|
+
*/
|
|
150
|
+
private getEntrySizes;
|
|
140
151
|
/**
|
|
141
152
|
* Enforce cache size limits using LRU eviction
|
|
142
153
|
* @param newKey - Key being added (skip count check if it already exists)
|
|
154
|
+
* @param newSize - Approximate size of the entry being written
|
|
143
155
|
*/
|
|
144
156
|
private enforceLimit;
|
|
157
|
+
/**
|
|
158
|
+
* Sort keys by access time, oldest first
|
|
159
|
+
*/
|
|
160
|
+
private sortByAccess;
|
|
145
161
|
/**
|
|
146
162
|
* Evict least recently used entries
|
|
147
163
|
*/
|
package/dist/cache/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import '../chunk-
|
|
4
|
-
import '../chunk-
|
|
5
|
-
import '../chunk-
|
|
6
|
-
import '../chunk-
|
|
1
|
+
export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-JPXEFKZO.js';
|
|
2
|
+
import '../chunk-4KL3GDYP.js';
|
|
3
|
+
import '../chunk-R2IP2AA5.js';
|
|
4
|
+
import '../chunk-UL7MZBSF.js';
|
|
5
|
+
import '../chunk-MA4ZHPQS.js';
|
|
6
|
+
import '../chunk-QS7N4PTV.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { generateDraftId, DraftManagerService } from './chunk-
|
|
1
|
+
import { generateDraftId, DraftManagerService } from './chunk-MA4ZHPQS.js';
|
|
2
2
|
|
|
3
3
|
// src/sync/types.ts
|
|
4
4
|
var SyncConflictError = class extends Error {
|
|
@@ -550,10 +550,48 @@ function compareDrafts(local, remote) {
|
|
|
550
550
|
};
|
|
551
551
|
}
|
|
552
552
|
|
|
553
|
+
// src/sync/lock.ts
|
|
554
|
+
var SYNC_LOCK_NAME = "classic-offline-sync";
|
|
555
|
+
var localLockHeld = false;
|
|
556
|
+
function getLockManager() {
|
|
557
|
+
if (typeof navigator === "undefined") return null;
|
|
558
|
+
const locks = navigator.locks;
|
|
559
|
+
return locks && typeof locks.request === "function" ? locks : null;
|
|
560
|
+
}
|
|
561
|
+
async function withSyncLock(fn) {
|
|
562
|
+
const locks = getLockManager();
|
|
563
|
+
if (locks) {
|
|
564
|
+
return locks.request(
|
|
565
|
+
SYNC_LOCK_NAME,
|
|
566
|
+
{ ifAvailable: true },
|
|
567
|
+
async (lock) => lock ? { acquired: true, value: await fn() } : { acquired: false }
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
if (localLockHeld) {
|
|
571
|
+
return { acquired: false };
|
|
572
|
+
}
|
|
573
|
+
localLockHeld = true;
|
|
574
|
+
try {
|
|
575
|
+
return { acquired: true, value: await fn() };
|
|
576
|
+
} finally {
|
|
577
|
+
localLockHeld = false;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
553
581
|
// src/sync/service.ts
|
|
554
582
|
var DEFAULT_SYNC_INTERVAL = 3e4;
|
|
555
583
|
var DEFAULT_BATCH_SIZE = 50;
|
|
556
584
|
var CONFLICTS_STORAGE_KEY = "sync-conflicts";
|
|
585
|
+
var RETRY_BASE_DELAY_MS = 5e3;
|
|
586
|
+
var RETRY_MAX_DELAY_MS = 15 * 60 * 1e3;
|
|
587
|
+
var PENDING_STATUSES = ["pending-upload", "local-only"];
|
|
588
|
+
function errorMessage(error) {
|
|
589
|
+
return error instanceof Error ? error.message : String(error);
|
|
590
|
+
}
|
|
591
|
+
function hasLocalEdits(metadata) {
|
|
592
|
+
if (metadata.syncStatus !== "synced") return true;
|
|
593
|
+
return metadata.syncedVersion !== void 0 && metadata.version !== metadata.syncedVersion;
|
|
594
|
+
}
|
|
557
595
|
var SyncService = class {
|
|
558
596
|
constructor(adapter, config) {
|
|
559
597
|
this.adapter = adapter;
|
|
@@ -563,6 +601,9 @@ var SyncService = class {
|
|
|
563
601
|
this.conflicts = [];
|
|
564
602
|
this.eventListeners = /* @__PURE__ */ new Map();
|
|
565
603
|
this.connectivityUnsubscribe = null;
|
|
604
|
+
this.pendingDraftCount = 0;
|
|
605
|
+
/** Upload backoff per local draft ID */
|
|
606
|
+
this.uploadFailures = /* @__PURE__ */ new Map();
|
|
566
607
|
this.syncAdapter = config.adapter;
|
|
567
608
|
this.config = {
|
|
568
609
|
syncIntervalMs: config.syncIntervalMs ?? DEFAULT_SYNC_INTERVAL,
|
|
@@ -577,7 +618,7 @@ var SyncService = class {
|
|
|
577
618
|
this.connectivity = createConnectivityMonitor();
|
|
578
619
|
this.queue = createSyncQueue(adapter);
|
|
579
620
|
this.connectivityUnsubscribe = this.connectivity.subscribe((online) => {
|
|
580
|
-
this.emit("online", online);
|
|
621
|
+
this.emit(online ? "online" : "offline", online);
|
|
581
622
|
this.onOnlineStatusChange?.(online);
|
|
582
623
|
if (online && this.config.autoSyncOnReconnect) {
|
|
583
624
|
void this.syncAll();
|
|
@@ -590,6 +631,7 @@ var SyncService = class {
|
|
|
590
631
|
async initialize() {
|
|
591
632
|
await this.queue.initialize();
|
|
592
633
|
await this.loadConflicts();
|
|
634
|
+
await this.refreshPendingCount();
|
|
593
635
|
}
|
|
594
636
|
// ============================================
|
|
595
637
|
// Properties
|
|
@@ -613,10 +655,24 @@ var SyncService = class {
|
|
|
613
655
|
return this.queue.lastSyncAt;
|
|
614
656
|
}
|
|
615
657
|
/**
|
|
616
|
-
*
|
|
658
|
+
* Number of local drafts waiting to be uploaded ('local-only' or
|
|
659
|
+
* 'pending-upload'), as of the last sync, `initialize()` or
|
|
660
|
+
* `refreshPendingCount()`
|
|
617
661
|
*/
|
|
618
662
|
get pendingCount() {
|
|
619
|
-
return this.
|
|
663
|
+
return this.pendingDraftCount;
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* Recount the local drafts waiting to be uploaded
|
|
667
|
+
*/
|
|
668
|
+
async refreshPendingCount() {
|
|
669
|
+
try {
|
|
670
|
+
const pending = await this.draftManager.listDrafts({ syncStatus: PENDING_STATUSES });
|
|
671
|
+
this.pendingDraftCount = pending.length;
|
|
672
|
+
} catch (error) {
|
|
673
|
+
console.warn("[SyncService] Failed to count pending drafts:", error);
|
|
674
|
+
}
|
|
675
|
+
return this.pendingDraftCount;
|
|
620
676
|
}
|
|
621
677
|
/**
|
|
622
678
|
* Get current conflicts
|
|
@@ -644,18 +700,31 @@ var SyncService = class {
|
|
|
644
700
|
return this.createErrorResult("Device is offline");
|
|
645
701
|
}
|
|
646
702
|
this.isSyncing = true;
|
|
703
|
+
try {
|
|
704
|
+
const locked = await withSyncLock(() => this.runSyncAll());
|
|
705
|
+
return locked.acquired ? locked.value : this.createErrorResult("Sync already in progress");
|
|
706
|
+
} finally {
|
|
707
|
+
this.isSyncing = false;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
async runSyncAll() {
|
|
647
711
|
const startTime = Date.now();
|
|
648
712
|
this.emit("sync:start", null);
|
|
649
713
|
try {
|
|
650
714
|
const result = await this.performSync();
|
|
651
715
|
this.lastSyncResult = result;
|
|
652
716
|
if (result.conflicts.length > 0) {
|
|
653
|
-
this.conflicts
|
|
717
|
+
const byId = new Map(this.conflicts.map((c) => [c.localDraftId, c]));
|
|
718
|
+
for (const conflict of result.conflicts) {
|
|
719
|
+
byId.set(conflict.localDraftId, conflict);
|
|
720
|
+
}
|
|
721
|
+
this.conflicts = [...byId.values()];
|
|
654
722
|
await this.saveConflicts();
|
|
655
723
|
this.emit("sync:conflict", result.conflicts);
|
|
656
724
|
this.onConflictDetected?.(result.conflicts);
|
|
657
725
|
}
|
|
658
726
|
await this.queue.updateLastSyncAt(Date.now());
|
|
727
|
+
await this.refreshPendingCount();
|
|
659
728
|
this.emit("sync:complete", result);
|
|
660
729
|
this.onSyncComplete?.(result);
|
|
661
730
|
return result;
|
|
@@ -664,27 +733,45 @@ var SyncService = class {
|
|
|
664
733
|
error instanceof Error ? error.message : "Unknown error",
|
|
665
734
|
startTime
|
|
666
735
|
);
|
|
736
|
+
await this.refreshPendingCount();
|
|
667
737
|
this.emit("sync:error", error);
|
|
668
738
|
this.onSyncError?.(error instanceof Error ? error : new Error(String(error)));
|
|
669
739
|
return errorResult;
|
|
670
|
-
} finally {
|
|
671
|
-
this.isSyncing = false;
|
|
672
740
|
}
|
|
673
741
|
}
|
|
674
742
|
/**
|
|
675
743
|
* Sync a specific draft
|
|
676
744
|
*/
|
|
677
745
|
async syncDraft(draftId) {
|
|
746
|
+
if (this.isSyncing) {
|
|
747
|
+
return this.createErrorResult("Sync already in progress");
|
|
748
|
+
}
|
|
678
749
|
if (!this.isOnline) {
|
|
679
750
|
return this.createErrorResult("Device is offline");
|
|
680
751
|
}
|
|
752
|
+
this.isSyncing = true;
|
|
753
|
+
try {
|
|
754
|
+
const locked = await withSyncLock(() => this.runSyncDraft(draftId));
|
|
755
|
+
return locked.acquired ? locked.value : this.createErrorResult("Sync already in progress");
|
|
756
|
+
} finally {
|
|
757
|
+
this.isSyncing = false;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
async runSyncDraft(draftId) {
|
|
681
761
|
const startTime = Date.now();
|
|
682
762
|
try {
|
|
683
763
|
const draft = await this.draftManager.getDraft(draftId);
|
|
684
764
|
if (!draft) {
|
|
685
765
|
return this.createErrorResult("Draft not found");
|
|
686
766
|
}
|
|
687
|
-
|
|
767
|
+
let result;
|
|
768
|
+
try {
|
|
769
|
+
result = await this.syncSingleDraft(draft);
|
|
770
|
+
this.uploadFailures.delete(draftId);
|
|
771
|
+
} catch (error) {
|
|
772
|
+
this.recordUploadFailure(draftId, startTime);
|
|
773
|
+
throw error;
|
|
774
|
+
}
|
|
688
775
|
return {
|
|
689
776
|
success: true,
|
|
690
777
|
uploaded: result.uploaded ? 1 : 0,
|
|
@@ -700,6 +787,8 @@ var SyncService = class {
|
|
|
700
787
|
error instanceof Error ? error.message : "Unknown error",
|
|
701
788
|
startTime
|
|
702
789
|
);
|
|
790
|
+
} finally {
|
|
791
|
+
await this.refreshPendingCount();
|
|
703
792
|
}
|
|
704
793
|
}
|
|
705
794
|
/**
|
|
@@ -713,13 +802,10 @@ var SyncService = class {
|
|
|
713
802
|
const payload = this.createPayload(draft);
|
|
714
803
|
if (draft.metadata.remoteId) {
|
|
715
804
|
await this.syncAdapter.updateDraft(draft.metadata.remoteId, payload);
|
|
805
|
+
await this.markUploaded(draft, draft.metadata.remoteId);
|
|
716
806
|
} else {
|
|
717
807
|
const remote = await this.syncAdapter.createDraft(payload);
|
|
718
|
-
await this.
|
|
719
|
-
remoteId: remote.id,
|
|
720
|
-
syncStatus: "synced",
|
|
721
|
-
lastSyncedAt: Date.now()
|
|
722
|
-
});
|
|
808
|
+
await this.markUploaded(draft, remote.id);
|
|
723
809
|
}
|
|
724
810
|
await this.removeConflict(draftId);
|
|
725
811
|
}
|
|
@@ -847,66 +933,122 @@ var SyncService = class {
|
|
|
847
933
|
// Private Methods
|
|
848
934
|
// ============================================
|
|
849
935
|
/**
|
|
850
|
-
* Perform the actual sync
|
|
936
|
+
* Perform the actual sync. One draft failing does not stop the rest: each
|
|
937
|
+
* failure is recorded in `failures` and the sync carries on.
|
|
851
938
|
*/
|
|
852
939
|
async performSync() {
|
|
853
940
|
const startTime = Date.now();
|
|
854
941
|
let uploaded = 0;
|
|
855
942
|
let downloaded = 0;
|
|
856
|
-
|
|
943
|
+
const deletedRemote = 0;
|
|
857
944
|
let deletedLocal = 0;
|
|
858
945
|
const conflicts = [];
|
|
946
|
+
const failures = [];
|
|
859
947
|
const localDrafts = await this.draftManager.listDrafts();
|
|
860
|
-
const pendingDrafts = localDrafts.filter(
|
|
861
|
-
(d) => d.syncStatus === "pending-upload" || d.syncStatus === "local-only"
|
|
862
|
-
);
|
|
948
|
+
const pendingDrafts = localDrafts.filter((d) => PENDING_STATUSES.includes(d.syncStatus));
|
|
863
949
|
const remoteDrafts = await this.syncAdapter.fetchDrafts();
|
|
864
950
|
const remoteMap = new Map(remoteDrafts.map((r) => [r.id, r]));
|
|
865
951
|
for (const metadata of pendingDrafts) {
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
952
|
+
if (this.isBackedOff(metadata.id, startTime)) continue;
|
|
953
|
+
try {
|
|
954
|
+
const draft = await this.draftManager.getDraft(metadata.id);
|
|
955
|
+
if (!draft) continue;
|
|
956
|
+
const result = await this.syncSingleDraft(draft);
|
|
957
|
+
this.uploadFailures.delete(metadata.id);
|
|
958
|
+
if (result.uploaded) uploaded++;
|
|
959
|
+
if (result.conflict) conflicts.push(result.conflict);
|
|
960
|
+
} catch (error) {
|
|
961
|
+
this.recordUploadFailure(metadata.id, startTime);
|
|
962
|
+
failures.push({
|
|
963
|
+
operation: "upload",
|
|
964
|
+
draftId: metadata.id,
|
|
965
|
+
remoteId: metadata.remoteId ?? void 0,
|
|
966
|
+
error: errorMessage(error)
|
|
967
|
+
});
|
|
968
|
+
}
|
|
871
969
|
}
|
|
872
970
|
for (const remote of remoteDrafts) {
|
|
873
971
|
const localDraft = localDrafts.find((d) => d.remoteId === remote.id);
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
if (local.
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
await this.downloadRemoteDraft(remote,
|
|
887
|
-
|
|
972
|
+
try {
|
|
973
|
+
if (!localDraft) {
|
|
974
|
+
await this.downloadRemoteDraft(remote);
|
|
975
|
+
downloaded++;
|
|
976
|
+
} else if (localDraft.syncStatus === "synced") {
|
|
977
|
+
const local = await this.draftManager.getDraft(localDraft.id);
|
|
978
|
+
if (local && remote.updatedAt > (local.metadata.lastSyncedAt ?? 0)) {
|
|
979
|
+
if (hasLocalEdits(local.metadata)) {
|
|
980
|
+
conflicts.push(createConflict(local, remote));
|
|
981
|
+
await this.draftManager.updateDraftMetadata(localDraft.id, {
|
|
982
|
+
syncStatus: "conflict"
|
|
983
|
+
});
|
|
984
|
+
} else if (await this.downloadRemoteDraft(remote, local)) {
|
|
985
|
+
downloaded++;
|
|
986
|
+
}
|
|
888
987
|
}
|
|
889
988
|
}
|
|
989
|
+
} catch (error) {
|
|
990
|
+
failures.push({
|
|
991
|
+
operation: "download",
|
|
992
|
+
draftId: localDraft?.id,
|
|
993
|
+
remoteId: remote.id,
|
|
994
|
+
error: errorMessage(error)
|
|
995
|
+
});
|
|
890
996
|
}
|
|
891
997
|
}
|
|
892
998
|
const syncedDrafts = localDrafts.filter((d) => d.remoteId && d.syncStatus === "synced");
|
|
893
999
|
for (const metadata of syncedDrafts) {
|
|
894
|
-
if (
|
|
895
|
-
|
|
896
|
-
|
|
1000
|
+
if (remoteMap.has(metadata.remoteId)) continue;
|
|
1001
|
+
try {
|
|
1002
|
+
const current = await this.draftManager.getDraftMetadata(metadata.id);
|
|
1003
|
+
if (!current || current.syncStatus !== "synced" || current.version !== metadata.version || current.remoteId !== metadata.remoteId) {
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
const deleted = await this.draftManager.deleteDraft(metadata.id, false, {
|
|
1007
|
+
expectedVersion: metadata.version
|
|
1008
|
+
});
|
|
1009
|
+
if (deleted) {
|
|
1010
|
+
deletedLocal++;
|
|
1011
|
+
this.emit("draft:deleted", { draftId: metadata.id, remoteId: metadata.remoteId });
|
|
1012
|
+
}
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
failures.push({
|
|
1015
|
+
operation: "delete",
|
|
1016
|
+
draftId: metadata.id,
|
|
1017
|
+
remoteId: metadata.remoteId ?? void 0,
|
|
1018
|
+
error: errorMessage(error)
|
|
1019
|
+
});
|
|
897
1020
|
}
|
|
898
1021
|
}
|
|
899
1022
|
return {
|
|
900
|
-
success:
|
|
1023
|
+
success: failures.length === 0,
|
|
901
1024
|
uploaded,
|
|
902
1025
|
downloaded,
|
|
903
1026
|
deletedRemote,
|
|
904
1027
|
deletedLocal,
|
|
905
1028
|
conflicts,
|
|
1029
|
+
failures,
|
|
1030
|
+
...failures.length > 0 && {
|
|
1031
|
+
error: `${failures.length} draft(s) failed to sync: ${failures[0].error}`
|
|
1032
|
+
},
|
|
906
1033
|
timestamp: Date.now(),
|
|
907
1034
|
durationMs: Date.now() - startTime
|
|
908
1035
|
};
|
|
909
1036
|
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Whether a failing draft is still waiting out its retry delay
|
|
1039
|
+
*/
|
|
1040
|
+
isBackedOff(draftId, now) {
|
|
1041
|
+
const failure = this.uploadFailures.get(draftId);
|
|
1042
|
+
return failure !== void 0 && now < failure.nextAttemptAt;
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Record a failed upload and schedule its next attempt (exponential backoff)
|
|
1046
|
+
*/
|
|
1047
|
+
recordUploadFailure(draftId, now) {
|
|
1048
|
+
const attempts = (this.uploadFailures.get(draftId)?.attempts ?? 0) + 1;
|
|
1049
|
+
const delay = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (attempts - 1));
|
|
1050
|
+
this.uploadFailures.set(draftId, { attempts, nextAttemptAt: now + delay });
|
|
1051
|
+
}
|
|
910
1052
|
/**
|
|
911
1053
|
* Sync a single draft
|
|
912
1054
|
*/
|
|
@@ -915,18 +1057,16 @@ var SyncService = class {
|
|
|
915
1057
|
try {
|
|
916
1058
|
if (draft.metadata.remoteId) {
|
|
917
1059
|
await this.syncAdapter.updateDraft(draft.metadata.remoteId, payload);
|
|
918
|
-
await this.
|
|
919
|
-
|
|
920
|
-
|
|
1060
|
+
await this.markUploaded(draft, draft.metadata.remoteId);
|
|
1061
|
+
this.emit("draft:uploaded", {
|
|
1062
|
+
draftId: draft.metadata.id,
|
|
1063
|
+
remoteId: draft.metadata.remoteId
|
|
921
1064
|
});
|
|
922
1065
|
return { uploaded: true, downloaded: false, conflict: null };
|
|
923
1066
|
} else {
|
|
924
1067
|
const remote = await this.syncAdapter.createDraft(payload);
|
|
925
|
-
await this.
|
|
926
|
-
|
|
927
|
-
syncStatus: "synced",
|
|
928
|
-
lastSyncedAt: Date.now()
|
|
929
|
-
});
|
|
1068
|
+
await this.markUploaded(draft, remote.id);
|
|
1069
|
+
this.emit("draft:uploaded", { draftId: draft.metadata.id, remoteId: remote.id });
|
|
930
1070
|
return { uploaded: true, downloaded: false, conflict: null };
|
|
931
1071
|
}
|
|
932
1072
|
} catch (error) {
|
|
@@ -945,17 +1085,46 @@ var SyncService = class {
|
|
|
945
1085
|
}
|
|
946
1086
|
}
|
|
947
1087
|
/**
|
|
948
|
-
*
|
|
1088
|
+
* Mark an uploaded draft as synced, but only if it was not edited while the
|
|
1089
|
+
* upload was in flight (compare-and-set on `version`). An edited draft stays
|
|
1090
|
+
* pending so the edit is uploaded next time; its remote ID is still
|
|
1091
|
+
* recorded so that upload updates the remote copy instead of creating another.
|
|
949
1092
|
*/
|
|
950
|
-
async
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1093
|
+
async markUploaded(draft, remoteId) {
|
|
1094
|
+
const { id, version } = draft.metadata;
|
|
1095
|
+
const marked = await this.draftManager.updateDraftMetadata(
|
|
1096
|
+
id,
|
|
1097
|
+
{ remoteId, syncStatus: "synced", lastSyncedAt: Date.now(), syncedVersion: version },
|
|
1098
|
+
{ expectedVersion: version }
|
|
1099
|
+
);
|
|
1100
|
+
if (!marked) {
|
|
1101
|
+
await this.draftManager.updateDraftMetadata(id, { remoteId });
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* Download a remote draft. Into an existing local draft only if that draft
|
|
1106
|
+
* is unchanged since it was read; returns false when a local edit won.
|
|
1107
|
+
*/
|
|
1108
|
+
async downloadRemoteDraft(remote, existing) {
|
|
1109
|
+
if (existing) {
|
|
1110
|
+
const { id, version } = existing.metadata;
|
|
1111
|
+
const applied = await this.draftManager.updateDraft(id, remote.data, remote.fileRefs, {
|
|
1112
|
+
expectedVersion: version,
|
|
1113
|
+
replace: true
|
|
958
1114
|
});
|
|
1115
|
+
if (!applied) {
|
|
1116
|
+
return false;
|
|
1117
|
+
}
|
|
1118
|
+
await this.draftManager.updateDraftMetadata(
|
|
1119
|
+
id,
|
|
1120
|
+
{
|
|
1121
|
+
name: remote.name,
|
|
1122
|
+
syncStatus: "synced",
|
|
1123
|
+
remoteId: remote.id,
|
|
1124
|
+
lastSyncedAt: Date.now()
|
|
1125
|
+
},
|
|
1126
|
+
{ expectedVersion: version + 1 }
|
|
1127
|
+
);
|
|
959
1128
|
} else {
|
|
960
1129
|
const metadata = await this.draftManager.createDraft(remote.formKey, {
|
|
961
1130
|
name: remote.name,
|
|
@@ -969,6 +1138,7 @@ var SyncService = class {
|
|
|
969
1138
|
});
|
|
970
1139
|
}
|
|
971
1140
|
this.emit("draft:downloaded", remote);
|
|
1141
|
+
return true;
|
|
972
1142
|
}
|
|
973
1143
|
/**
|
|
974
1144
|
* Create a payload from a draft
|
|
@@ -981,7 +1151,9 @@ var SyncService = class {
|
|
|
981
1151
|
fileRefs: draft.fileRefs,
|
|
982
1152
|
version: draft.metadata.version,
|
|
983
1153
|
updatedAt: draft.metadata.updatedAt,
|
|
984
|
-
deviceId: draft.metadata.deviceId
|
|
1154
|
+
deviceId: draft.metadata.deviceId,
|
|
1155
|
+
// Idempotency key for creates
|
|
1156
|
+
localId: draft.metadata.id
|
|
985
1157
|
};
|
|
986
1158
|
}
|
|
987
1159
|
/**
|