-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathindex.ts
More file actions
309 lines (268 loc) · 11.3 KB
/
Copy pathindex.ts
File metadata and controls
309 lines (268 loc) · 11.3 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import { RxReplicationState, startReplicationOnLeaderShip } from '../replication/index.ts';
import { SupabaseCheckpoint, SyncOptionsSupabase } from './types.ts';
import { addRxPlugin } from '../../plugin.ts';
import { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';
import {
ReplicationPullOptions,
ReplicationPushOptions,
RxCollection,
RxDocumentData,
RxJsonSchema,
RxReplicationPullStreamItem,
RxReplicationWriteToMasterRow,
WithDeleted
} from '../../types/index';
import { Subject } from 'rxjs';
import {
DEFAULT_DELETED_FIELD,
DEFAULT_MODIFIED_FIELD,
POSTGRES_INSERT_CONFLICT_CODE
} from './helper.ts';
import { ensureNotFalsy, flatClone, lastOfArray } from '../utils/index.ts';
export class RxSupabaseReplicationState<RxDocType> extends RxReplicationState<RxDocType, SupabaseCheckpoint> {
constructor(
public readonly replicationIdentifier: string,
public readonly collection: RxCollection<RxDocType, any, any, any>,
public readonly pull?: ReplicationPullOptions<RxDocType, SupabaseCheckpoint>,
public readonly push?: ReplicationPushOptions<RxDocType>,
public readonly live: boolean = true,
public retryTime: number = 1000 * 5,
public autoStart: boolean = true
) {
super(
replicationIdentifier,
collection,
'_deleted',
pull,
push,
live,
retryTime,
autoStart
);
}
}
export function replicateSupabase<RxDocType>(
options: SyncOptionsSupabase<RxDocType>
) {
options = flatClone(options);
addRxPlugin(RxDBLeaderElectionPlugin);
const collection = options.collection;
const primaryPath = collection.schema.primaryPath;
// set defaults
options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;
options.live = typeof options.live === 'undefined' ? true : options.live;
const modifiedField = options.modifiedField ? options.modifiedField : DEFAULT_MODIFIED_FIELD;
const deletedField = options.deletedField ? options.deletedField : DEFAULT_DELETED_FIELD;
const pullStream$: Subject<RxReplicationPullStreamItem<RxDocType, SupabaseCheckpoint>> = new Subject();
let replicationPrimitivesPull: ReplicationPullOptions<RxDocType, SupabaseCheckpoint> | undefined;
function rowToDoc(row: any): WithDeleted<RxDocType> {
const deleted = !!row[deletedField];
const modified = row[modifiedField];
const doc: WithDeleted<RxDocType> = flatClone(row);
delete (doc as any)[deletedField];
delete (doc as any)[modifiedField];
doc._deleted = deleted;
/**
* Only keep the modified value if that field is defined
* in the schema.
*/
if ((collection.schema.jsonSchema.properties as any)[modifiedField]) {
(doc as any)[modifiedField] = modified;
}
return doc;
}
async function fetchById(id: string): Promise<WithDeleted<RxDocType>> {
const { data, error } = await options.client
.from(options.tableName)
.select()
.eq(primaryPath, id)
.limit(1)
if (error) throw error
if (data.length != 1) throw new Error('doc not found ' + id)
return rowToDoc(data[0])
}
if (options.pull) {
replicationPrimitivesPull = {
async handler(
lastPulledCheckpoint: SupabaseCheckpoint | undefined,
batchSize: number
) {
let query = options.client
.from(options.tableName)
.select('*');
if (options.pull?.queryBuilder) {
const maybeNewQuery = options.pull.queryBuilder({
query,
lastPulledCheckpoint,
batchSize,
});
if (maybeNewQuery) {
query = maybeNewQuery;
}
}
if (lastPulledCheckpoint) {
const { modified, id } = lastPulledCheckpoint;
// WHERE modified > :m OR (modified = :m AND id > :id)
// PostgREST or() takes comma-separated disjuncts; use nested and() for the tie-breaker.
// Wrap identifiers with double quotes to be safe if they're mixed-case.
query = query.or(
`"${modifiedField}".gt.${modified},and("${modifiedField}".eq.${modified},"${primaryPath}".gt.${id})`
);
}
// deterministic order & batch size
query = query
.order(modifiedField as any, { ascending: true })
.order(primaryPath as any, { ascending: true })
.limit(batchSize);
const { data, error } = await query;
if (error) {
throw error;
}
const lastDoc: any = lastOfArray(data);
const newCheckpoint: SupabaseCheckpoint | undefined = lastDoc ? {
id: lastDoc[primaryPath],
modified: lastDoc[modifiedField]
} : undefined;
const docs = data.map((row: any) => rowToDoc(row))
return {
documents: docs,
checkpoint: newCheckpoint
};
},
batchSize: ensureNotFalsy(options.pull).batchSize,
modifier: ensureNotFalsy(options.pull).modifier,
stream$: pullStream$.asObservable(),
initialCheckpoint: options.pull.initialCheckpoint
};
}
const replicationPrimitivesPush: ReplicationPushOptions<RxDocType> | undefined = options.push ? {
batchSize: options.push.batchSize,
initialCheckpoint: options.push.initialCheckpoint,
modifier: options.push.modifier,
async handler(
rows: RxReplicationWriteToMasterRow<RxDocType>[]
) {
async function insertOrReturnConflict(doc: WithDeleted<RxDocType>): Promise<WithDeleted<RxDocType> | undefined> {
const id = (doc as any)[primaryPath];
const { error } = await options.client.from(options.tableName).insert(doc)
if (!error) {
return;
} else if (error.code == POSTGRES_INSERT_CONFLICT_CODE) {
// conflict!
const conflict = await fetchById(id);
return conflict;
} else {
throw error
}
}
async function updateOrReturnConflict(
doc: WithDeleted<RxDocType>,
assumedMasterState: WithDeleted<RxDocType>
): Promise<WithDeleted<RxDocType> | undefined> {
ensureNotFalsy(assumedMasterState);
const primaryKey: string = primaryPath;
const id = (doc as any)[primaryKey];
const toRow: Record<string, any> = flatClone(doc);
if (doc._deleted) {
toRow[deletedField] = !!doc._deleted;
if (deletedField !== '_deleted') {
delete toRow._deleted;
}
}
// modified field will be set server-side
delete toRow[modifiedField];
// fetch the current document state from the server
const docOnServer: WithDeleted<RxDocType> = await fetchById(id);
if (!docOnServer) {
// the document does not exist on the server -> treat as conflict
return docOnServer;
}
const isSame = (Object.keys(assumedMasterState) as (keyof WithDeleted<RxDocType>)[])
.every((prop) => docOnServer[prop] === assumedMasterState[prop])
// check whether the server state matches the assumed master state
if (isSame) {
// no conflict -> proceed with the update
await options.client
.from(options.tableName)
.update(toRow)
.eq(primaryKey, id);
return;
}
// conflict detected -> return the current server state
return docOnServer;
}
const conflicts: WithDeleted<RxDocType>[] = [];
await Promise.all(
rows.map(async (row) => {
const newDoc = row.newDocumentState as WithDeleted<RxDocType>;
if (!row.assumedMasterState) {
const c = await insertOrReturnConflict(newDoc);
if (c) conflicts.push(c);
} else {
const c = await updateOrReturnConflict(newDoc, row.assumedMasterState as any);
if (c) conflicts.push(c);
}
})
);
return conflicts;
}
} : undefined;
const replicationState = new RxSupabaseReplicationState<RxDocType>(
options.replicationIdentifier,
collection,
replicationPrimitivesPull,
replicationPrimitivesPush,
options.live,
options.retryTime,
options.autoStart
);
/**
* Subscribe to changes for the pull.stream$
*/
if (options.live && options.pull) {
const startBefore = replicationState.start.bind(replicationState);
const cancelBefore = replicationState.cancel.bind(replicationState);
replicationState.start = () => {
const sub = options.client
.channel('realtime:' + options.tableName)
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: options.tableName },
(payload: any) => {
/**
* We assume soft-deletes in supabase
* and therefore cleanup-hard-deletes
* are not relevant for the sync.
*/
if (payload.eventType === 'DELETE') {
return;
}
const row = payload.new;
const doc = rowToDoc(row);
pullStream$.next({
checkpoint: {
id: (doc as any)[primaryPath],
modified: (row as any)[modifiedField]
},
documents: [doc as any],
});
}
)
.subscribe((status: string) => {
/**
* Trigger resync flag on reconnects
*/
if (status === 'SUBSCRIBED') {
pullStream$.next('RESYNC');
}
});
replicationState.cancel = () => {
sub.unsubscribe();
return cancelBefore();
};
return startBefore();
};
}
startReplicationOnLeaderShip(options.waitForLeadership, replicationState);
return replicationState;
}