-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathcollab-api.ts
More file actions
367 lines (321 loc) · 10.2 KB
/
collab-api.ts
File metadata and controls
367 lines (321 loc) · 10.2 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import { toBase64 } from 'lib0/buffer';
import { getOrCreateDeviceId } from '@/application/services/js-services/device-id';
import {
RowId,
Types,
User,
View,
} from '@/application/types';
import { database_blob } from '@/proto/database_blob';
import { collab } from '@/proto/messages';
import { Log } from '@/utils/log';
import { APIResponse, APIError, executeAPIRequest, executeAPIVoidRequest, getAxios, parseRetryAfterSecs } from './core';
export interface CollabFullSyncBatchResult {
objectId: string;
collabType: Types;
missingUpdate: Uint8Array;
serverStateVector: Uint8Array;
error?: string;
}
export async function updateCollab(
workspaceId: string,
objectId: string,
collabType: Types,
docState: Uint8Array,
context: {
version_vector: number;
}
) {
const url = `/api/workspace/v1/${workspaceId}/collab/${objectId}/web-update`;
const deviceId = getOrCreateDeviceId();
await executeAPIVoidRequest(() =>
getAxios()?.post<APIResponse>(
url,
{
doc_state: Array.from(docState),
collab_type: collabType,
},
{
headers: {
'client-version': 'web',
'device-id': deviceId,
},
}
)
);
return context;
}
/**
* Batch sync multiple collab documents to the server.
* This is the same API that desktop uses before duplicating to ensure
* the server has the latest state of all documents.
*
* @param workspaceId - The workspace ID
* @param items - Array of collab items to sync, each containing objectId, collabType, stateVector, and docState
* @returns The batch sync response containing results for each collab
*/
export async function collabFullSyncBatch(
workspaceId: string,
items: Array<{
objectId: string;
collabType: Types;
stateVector: Uint8Array;
docState: Uint8Array;
}>
): Promise<CollabFullSyncBatchResult[]> {
const url = `/api/workspace/v1/${workspaceId}/collab/full-sync/batch`;
// Build the protobuf request
const request = collab.CollabBatchSyncRequest.create({
items: items.map((item) => ({
objectId: item.objectId,
collabType: item.collabType,
compression: collab.PayloadCompressionType.COMPRESSION_NONE,
sv: item.stateVector,
docState: item.docState,
})),
responseCompression: collab.PayloadCompressionType.COMPRESSION_NONE,
});
// Encode the request to binary
const encoded = collab.CollabBatchSyncRequest.encode(request).finish();
const deviceId = getOrCreateDeviceId();
const axiosInstance = getAxios();
// Send the request with protobuf content type.
// Use validateStatus to prevent axios from throwing on 429/503 so we can
// extract the Retry-After header and surface it to callers.
const response = await axiosInstance?.post(url, encoded, {
headers: {
'Content-Type': 'application/octet-stream',
'client-version': 'web',
'device-id': deviceId,
},
responseType: 'arraybuffer',
// Axios' default transform sends typed-array `.buffer`, which can include
// protobufjs' pooled zero padding beyond this Uint8Array view.
transformRequest: [(data: Uint8Array) => data],
validateStatus: (status) => status === 200 || status === 429 || status === 503,
});
if (!response) {
const err = new Error('No response received from server');
Object.assign(err, { code: -1 } satisfies Partial<APIError>);
throw err;
}
if (response.status === 429 || response.status === 503) {
const retryAfterSecs = parseRetryAfterSecs(response.headers);
const err = new Error(`Batch sync rate-limited (${response.status})`);
Object.assign(err, { code: response.status, retryAfterSecs } satisfies Partial<APIError>);
throw err;
}
// Decode and check the response for errors
const responseData = new Uint8Array(response.data);
const batchResponse = collab.CollabBatchSyncResponse.decode(responseData);
const results: CollabFullSyncBatchResult[] = [];
// Check for any errors in the results
for (const result of batchResponse.results) {
if (result.error) {
Log.warn('Collab sync error', {
objectId: result.objectId,
collabType: result.collabType,
error: result.error,
});
}
results.push({
objectId: result.objectId ?? '',
collabType: result.collabType as Types,
missingUpdate: result.missingUpdate ?? new Uint8Array(),
serverStateVector: result.serverStateVector ?? new Uint8Array(),
error: result.error || undefined,
});
}
return results;
}
export async function getCollab(workspaceId: string, objectId: string, collabType: Types) {
const url = `/api/workspace/v1/${workspaceId}/collab/${objectId}`;
const data = await executeAPIRequest<{
doc_state: number[];
object_id: string;
}>(() =>
getAxios()?.get<APIResponse<{
doc_state: number[];
object_id: string;
}>>(url, {
params: {
collab_type: collabType,
},
})
);
return {
data: new Uint8Array(data.doc_state),
};
}
export async function getPageCollab(workspaceId: string, viewId: string) {
const url = `/api/workspace/${workspaceId}/page-view/${viewId}`;
const response = await executeAPIRequest<{
view: View;
data: {
encoded_collab: number[];
row_data: Record<RowId, number[]>;
owner?: User;
last_editor?: User;
};
}>(() =>
getAxios()?.get<APIResponse<{
view: View;
data: {
encoded_collab: number[];
row_data: Record<RowId, number[]>;
owner?: User;
last_editor?: User;
};
}>>(url)
);
const { encoded_collab, row_data, owner, last_editor } = response.data;
return {
data: new Uint8Array(encoded_collab),
rows: row_data,
owner,
lastEditor: last_editor,
};
}
export async function duplicateRowDocument(
workspaceId: string,
databaseId: string,
sourceRowId: string,
newRowId: string,
clientDocStateB64?: string,
): Promise<void> {
const url = `/api/workspace/${workspaceId}/database/${databaseId}/row/${sourceRowId}/duplicate-document`;
await executeAPIVoidRequest(() =>
getAxios()?.post<APIResponse>(url, {
new_row_id: newRowId,
client_doc_state_b64: clientDocStateB64,
})
);
}
export async function databaseBlobDiff(
workspaceId: string,
databaseId: string,
request: database_blob.IDatabaseBlobDiffRequest
) {
const axiosInstance = getAxios();
if (!axiosInstance) {
return Promise.reject({
code: -1,
message: 'API service not initialized',
});
}
const url = `/api/workspace/${workspaceId}/database/${databaseId}/blob/diff`;
const payload = database_blob.DatabaseBlobDiffRequest.encode(request).finish();
const response = await axiosInstance.post<ArrayBuffer>(url, payload, {
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/octet-stream',
},
transformRequest: [(data) => data],
validateStatus: (status) => status === 200 || status === 202,
});
const bytes = new Uint8Array(response.data);
return database_blob.DatabaseBlobDiffResponse.decode(bytes);
}
export async function getCollabVersions(workspaceId: string, objectId: string, since?: Date) {
const url = `/api/workspace/${workspaceId}/collab/${objectId}/history`;
const from = since?.getTime() || null;
const data = await executeAPIRequest<Array<{
version: string;
parent: string | null;
name: string | null;
created_at: string;
created_by: number | null;
deleted_at?: string | null;
// Backward compatibility for older server payloads.
is_deleted?: boolean;
editors: number[];
}>>(() =>
getAxios()?.get<APIResponse<Array<{
version: string;
parent: string | null;
name: string | null;
created_at: string;
created_by: number | null;
deleted_at?: string | null;
// Backward compatibility for older server payloads.
is_deleted?: boolean;
editors: number[];
}>>>(url, {
params: {
since: from,
},
})
);
return data.map((data) => {
return {
versionId: data.version,
parentId: data.parent,
name: data.name,
createdAt: new Date(data.created_at),
deletedAt: data.deleted_at ? new Date(data.deleted_at) : (data.is_deleted ? new Date(0) : null),
editors: data.editors,
};
});
}
export async function previewCollabVersion(workspaceId: string, objectId: string, version: string, collabType: Types) {
const url = `/api/workspace/${workspaceId}/collab/${objectId}/history/${version}?collab_type=${collabType}`;
const response = await getAxios()?.get(url, {
responseType: 'arraybuffer'
});
if (!response) {
throw new Error('No response');
}
return new Uint8Array(response.data);
}
export async function createCollabVersion(
workspaceId: string,
objectId: string,
collabType: Types,
name: string,
ySnapshot: Uint8Array
) {
const snapshot = toBase64(ySnapshot);
const url = `/api/workspace/${workspaceId}/collab/${objectId}/history`;
return executeAPIRequest<string>(() =>
getAxios()?.post<APIResponse<string>>(url, {
snapshot,
name,
collab_type: collabType,
})
);
}
export async function deleteCollabVersion(workspaceId: string, objectId: string, version: string) {
const url = `/api/workspace/${workspaceId}/collab/${objectId}/history`;
return executeAPIVoidRequest(() =>
getAxios()?.delete<APIResponse>(url, {
data: JSON.stringify(version),
headers: {
'Content-Type': 'application/json',
},
})
);
}
export async function revertCollabVersion(workspaceId: string, objectId: string, collabType: Types, version: string) {
const url = `/api/workspace/${workspaceId}/collab/${objectId}/revert`;
const data = await executeAPIRequest<{
state_vector: number[];
doc_state: number[];
collab_version: string | null;
version: number; // this is encoder version (lib0 v1 encoding is 0, while lib0 v2 encoding is 1, we only use 0 atm.)
}>(() =>
getAxios()?.post<APIResponse<{
state_vector: number[];
doc_state: number[];
collab_version: string | null;
version: number;
}>>(url, {
version,
collab_type: collabType,
})
);
return {
stateVector: new Uint8Array(data.state_vector),
docState: new Uint8Array(data.doc_state),
version: data.collab_version,
};
}