-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyncService.js
More file actions
222 lines (195 loc) · 9.4 KB
/
SyncService.js
File metadata and controls
222 lines (195 loc) · 9.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/**
* SyncService.js — Orchestrates the sync protocol.
*
* Accepts a client changeset (array of changed documents), applies field-level
* merge against the server's stored versions, persists the results, and returns
* server-side changes the client hasn't seen yet.
*
* Merge strategy — field revision comparison:
* For each field, the service compares each side's fieldRev against the
* client's baseClock (the last clock the client had synced from the server).
*
* clientChanged = clientFieldRevs[field] > baseClock
* serverChanged = serverFieldRevs[field] > baseClock
*
* - Neither changed → take server value (shared state)
* - Only client changed → take client value
* - Only server changed → take server value
* - Both changed, string fields → attempt line-level text auto-merge first.
* If hunks are non-overlapping: store merged text, report as
* winner:'auto-merged', mergeStrategy:'text-auto-merged'.
* If hunks overlap → fall through to HLC winner.
* - Both changed, non-string fields → HLC winner; higher fieldRev wins;
* local wins on tie.
*
* Storage namespacing:
* The internal collection key is namespaced as
* {userId}:{application}:{collection} (with ':' in segments encoded as %3A).
* This ensures per-user, per-application isolation at the storage layer.
*
* Dependencies (CDI autowired by name):
* this.syncRepository — SyncRepository instance
* this.logger — optional logger
*/
import { HLC, textMerge } from '@alt-javascript/jsmdma-core';
import { namespaceKey } from './namespaceKey.js';
export default class SyncService {
constructor() {
// CDI will autowire these; direct injection used in tests
this.syncRepository = null;
this.logger = null;
this.documentIndexRepository = null;
}
/**
* Process a sync request from a client.
*
* @param {string} collection — logical collection name (from request body)
* @param {string} clientClock — the client's current HLC (highest clock it has seen)
* @param {Array<{key, doc, fieldRevs, baseClock}>} changes — client's local changes
* @param {string} [userId] — identity from JWT sub claim (required for namespacing)
* @param {string} [application] — application name from URL path (required for namespacing)
* @returns {Promise<{ serverClock: string, serverChanges: Object[], conflicts: Conflict[] }>}
*/
async sync(collection, clientClock, changes = [], userId, application) {
const wallMs = Date.now();
// Advance server clock past the client's clock to maintain causality
const serverClock = HLC.recv(
HLC.create('server', wallMs),
clientClock,
wallMs,
);
// Compute the namespaced collection key for storage isolation.
// Fall back to bare collection if userId/application not provided (e.g. tests).
const storageCollection = (userId != null && application != null)
? namespaceKey(userId, application, collection)
: collection;
const allConflicts = [];
// Apply each client change
for (const change of changes) {
const { key, doc, fieldRevs, baseClock } = change;
const clientFieldRevs = fieldRevs ?? {};
const baseHLC = baseClock ?? HLC.zero();
// Load current server version
const serverDoc = await this.syncRepository.get(storageCollection, key);
let mergedDoc;
let mergedFieldRevs;
if (serverDoc == null) {
// No server version — accept client doc as-is
mergedDoc = doc;
mergedFieldRevs = clientFieldRevs;
} else {
const serverFieldRevs = serverDoc._fieldRevs ?? {};
const allFields = new Set([
...Object.keys(doc),
...Object.keys(serverDoc),
].filter((f) => !f.startsWith('_')));
mergedDoc = {};
mergedFieldRevs = {};
for (const field of allFields) {
const clientRev = clientFieldRevs[field] ?? HLC.zero();
const serverRev = serverFieldRevs[field] ?? HLC.zero();
const clientChanged = HLC.compare(clientRev, baseHLC) > 0;
const serverChanged = HLC.compare(serverRev, baseHLC) > 0;
if (!clientChanged && !serverChanged) {
mergedDoc[field] = serverDoc[field];
mergedFieldRevs[field] = serverRev;
} else if (clientChanged && !serverChanged) {
mergedDoc[field] = doc[field];
mergedFieldRevs[field] = clientRev;
} else if (!clientChanged && serverChanged) {
mergedDoc[field] = serverDoc[field];
mergedFieldRevs[field] = serverRev;
} else {
// Both changed — attempt text auto-merge for string fields first
const clientVal = doc[field];
const serverVal = serverDoc[field];
if (typeof clientVal === 'string' && typeof serverVal === 'string') {
// Reconstruct best-guess base value: the server value at baseClock.
// We don't store a snapshot at baseClock, so we use an empty string
// as a conservative base — this means we treat the field as if both
// sides added their content independently. For a true 3-way merge
// the base would need to be stored; absent that, we rely on the
// stored server doc and report auto-merged when one side is a
// strict prefix/suffix of the other or hunks don't overlap.
const baseVal = serverDoc[`_base_${field}`] ?? '';
const { merged: autoMergedText, autoMerged } = textMerge(baseVal, clientVal, serverVal);
if (autoMerged) {
mergedDoc[field] = autoMergedText;
mergedFieldRevs[field] = HLC.merge(clientRev, serverRev);
allConflicts.push({
key,
collection,
field,
localRev: clientRev,
remoteRev: serverRev,
localValue: clientVal,
remoteValue: serverVal,
winner: 'auto-merged',
winnerValue: autoMergedText,
mergeStrategy: 'text-auto-merged',
});
continue;
}
}
// HLC fallback — higher rev wins; local wins on tie
const winner = HLC.compare(clientRev, serverRev) >= 0 ? 'local' : 'remote';
mergedDoc[field] = winner === 'local' ? clientVal ?? doc[field] : serverVal ?? serverDoc[field];
mergedFieldRevs[field] = winner === 'local' ? clientRev : serverRev;
allConflicts.push({
key,
collection,
field,
localRev: clientRev,
remoteRev: serverRev,
localValue: doc[field],
remoteValue: serverDoc[field],
winner,
winnerValue: mergedDoc[field],
});
}
}
}
await this.syncRepository.store(storageCollection, key, mergedDoc, mergedFieldRevs, serverClock);
}
// Return everything the client hasn't seen yet (own namespace)
const serverChanges = await this.syncRepository.changesSince(storageCollection, clientClock);
// ACL fan-out: aggregate cross-namespace shared docs when documentIndexRepository is wired
if (this.documentIndexRepository != null && userId != null && application != null) {
// Get all docIndex entries visible to this user for this app
const accessibleEntries = await this.documentIndexRepository.listAccessibleDocs(userId, application);
// Group cross-namespace entries by owner (skip own docs — already fetched above)
const byOwner = new Map();
for (const entry of accessibleEntries) {
if (entry.userId === userId) continue; // own docs handled by storageCollection query
if (!byOwner.has(entry.userId)) byOwner.set(entry.userId, []);
byOwner.get(entry.userId).push(entry);
}
// For each distinct owner, fetch their namespace changes and filter to accessible keys
for (const [ownerId, entries] of byOwner) {
// Build a set of accessible docKeys for fast lookup
const accessibleKeys = new Set(entries.map((e) => e.docKey));
// Group entries by collection so we make one changesSince call per owner:collection
const byCollection = new Map();
for (const entry of entries) {
if (!byCollection.has(entry.collection)) byCollection.set(entry.collection, []);
byCollection.get(entry.collection).push(entry);
}
for (const [col, colEntries] of byCollection) {
const crossNamespaceKey = namespaceKey(ownerId, application, col);
const crossChanges = await this.syncRepository.changesSince(crossNamespaceKey, clientClock);
// Keep only docs whose _key appears in the accessible docIndex entries
const colAccessibleKeys = new Set(colEntries.map((e) => e.docKey));
for (const doc of crossChanges) {
if (colAccessibleKeys.has(doc._key)) {
serverChanges.push(doc);
}
}
}
}
}
this.logger?.info?.(
`[SyncService] sync userId=${userId ?? 'anon'} app=${application ?? 'none'} collection=${collection} storageKey=${storageCollection} clientClock=${clientClock} applied=${changes.length} returning=${serverChanges.length} conflicts=${allConflicts.length}`,
);
return { serverClock, serverChanges, conflicts: allConflicts };
}
}