-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
3827 lines (3304 loc) · 154 KB
/
server.js
File metadata and controls
3827 lines (3304 loc) · 154 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let { Doc, OpLog, Branch } = require("@braid.org/diamond-types-node")
let {http_server: braidify, fetch: braid_fetch} = require("braid-http")
let fs = require("fs")
let Y = null
try { Y = require('yjs') } catch(e) {}
var all_subscriptions = new Set()
// Converts this to a forced serialized function, that is only called one at a
// time, and in order. Even if the inner `fun` is async, it will guarantee
// that the prior one is always finished before the next one is called.
//
// We use this to guarantee that updates are all sent in order, with the prior
// one sent before the next one begins to send.
function one_at_a_time(fun) {
var queue = Promise.resolve()
return (message) => queue = queue.then(() => fun(message))
}
function create_braid_text() {
let braid_text = {
verbose: false,
db_folder: './braid-text-db',
length_cache_size: 10,
meta_file_save_period_ms: 1000,
debug_sync_checks: false,
simpletonSetTimeout: setTimeout, // Can be customized for fuzz testing
cache: {}
}
function require_yjs() {
if (!Y) throw new Error('yjs is not installed. Install it with: npm install yjs')
return Y
}
braid_text.end_all_subscriptions = function() {
var subs = [...all_subscriptions]
for (var res of subs) res.end()
}
let waiting_puts = 0
let max_encoded_key_size = 240
// Bidirectional sync between a local resource and a remote server.
// Keeps them in sync by forwarding DT updates in both directions.
// Reconnects automatically on disconnect.
braid_text.sync = async (local_key, remote_url, options = {}) => {
if (!options.merge_type) options.merge_type = 'dt'
// ── Setup: identify local vs remote, prepare headers ──
if ((local_key instanceof URL) === (remote_url instanceof URL))
throw new Error(`one parameter should be local string key, and the other a remote URL object`)
// Normalize so local_key is the string, remote_url is the URL
if (local_key instanceof URL) { var swap = local_key; local_key = remote_url; remote_url = swap }
// Split caller's headers into GET headers (Accept) vs PUT headers (Content-Type)
var content_type
var get_headers = {}
var put_headers = {}
if (options.headers) {
for (var [k, v] of Object.entries(options.headers)) {
var lk = k.toLowerCase()
if (lk === 'accept' || lk === 'content-type')
content_type = v
else {
get_headers[k] = v
put_headers[k] = v
}
}
}
if (content_type) {
get_headers['Accept'] = content_type
put_headers['Content-Type'] = content_type
}
// ── Load the local resource and initialize the fork point ──
//
// The fork point is the most recent set of versions that both local
// and remote are known to share. It's persisted in resource meta
// so reconnections don't start from scratch.
var resource = (typeof local_key == 'string') ? await get_resource(local_key) : local_key
await ensure_dt_exists(resource)
if (!resource.meta.fork_point && options.fork_point_hint) {
resource.meta.fork_point = options.fork_point_hint
resource.save_meta()
}
// When we get an ackowledgement that a remote server has a version
// that we have:
//
// - In a PUT acknowledgement
// - Or a GET response
//
// ...then we extend our known fork point "frontier" to include that
// version.
function extend_fork_point(update) {
// Given a version frontier, incorporate a new update (version +
// parents) to compute the new frontier. Walks the DT version DAG
// if needed.
function extend_frontier(frontier, version, parents) {
var frontier_set = new Set(frontier)
// Fast path: if the frontier contains all the update's parents,
// just swap them out for the new version
if (parents.length &&
parents.every(p => frontier_set.has(p))) {
parents.forEach(p => frontier_set.delete(p))
for (var event of version) frontier_set.add(event)
frontier = [...frontier_set.values()]
} else {
// Slow path: walk the full DT history to compute the frontier
var looking_for = frontier_set
for (var event of version) looking_for.add(event)
frontier = []
var shadow = new Set()
var bytes = resource.dt.doc.toBytes()
var [_, events, parentss] = braid_text.dt_parse([...bytes])
for (var i = events.length - 1; i >= 0 && looking_for.size; i--) {
var e = events[i].join('-')
if (looking_for.has(e)) {
looking_for.delete(e)
if (!shadow.has(e)) frontier.push(e)
shadow.add(e)
}
if (shadow.has(e))
parentss[i].forEach(p => shadow.add(p.join('-')))
}
}
return frontier.sort()
}
resource.meta.fork_point = extend_frontier(resource.meta.fork_point,
update.version,
update.parents)
resource.save_meta()
}
// ── Reconnection wrapper ──
//
// Everything below runs inside reconnector(), which retries
// the entire connection on failure with backoff.
reconnector(options.signal, (_e, count) => {
var delay = Math.min(count, 3) * 1000
console.log(`disconnected from ${remote_url}, retrying in ${delay}ms`)
return delay
}, async (signal, handle_error) => {
if (options.on_pre_connect) await options.on_pre_connect()
if (signal.aborted) return
try {
// ── Find the fork point ──
//
// The fork point tells us where to start syncing from.
// First check if the remote still has our saved fork point.
// If not, binary search through local history to find the
// latest version the remote recognizes.
async function check_version(version) {
var r = await braid_fetch(remote_url.href, {
signal, method: 'HEAD', version, headers: get_headers
})
if (signal.aborted) return
if (!r.ok && r.status !== 309 && r.status !== 404 && r.status !== 500)
throw new Error(`unexpected HEAD status: ${r.status}`)
return r.ok
}
if (resource.meta.fork_point &&
!(await check_version(resource.meta.fork_point))) {
if (signal.aborted) return
resource.meta.fork_point = null
resource.save_meta()
}
if (signal.aborted) return
if (!resource.meta.fork_point) {
// Binary search through local DT history
var bytes = resource.dt.doc.toBytes()
var [_, events, __] = braid_text.dt_parse([...bytes])
events = events.map(x => x.join('-'))
var min = -1
var max = events.length
while (min + 1 < max) {
var i = Math.floor((min + max) / 2)
var version = [events[i]]
if (await check_version(version)) {
if (signal.aborted) return
min = i
resource.meta.fork_point = version
} else max = i
}
}
// ── Local → Remote ──
//
// Subscribe to local changes (history since fork_point,
// then live updates) and forward each one to the remote
// server via PUT. Up to 10 PUTs in flight for throughput.
var local_updates = []
var in_flight = 0
var max_in_flight = 10
// PUT a single update to the remote server.
// Extends the fork point on success so the next
// reconnection starts from where we left off.
async function send_to_remote(update) {
var {response} = await braid_text.put(remote_url, {
...update,
signal,
dont_retry: true,
peer: options.peer,
headers: put_headers,
})
if (signal.aborted) return
if (response.ok)
extend_fork_point(update)
else if (response.status === 401 || response.status === 403)
await options.on_unauthorized?.()
else
throw new Error('failed to PUT: ' + response.status)
}
// Forward pending local updates to the remote,
// up to max_in_flight concurrent PUTs.
// When each PUT completes, check for more work.
function send_local_updates() {
if (signal.aborted) return
while (local_updates.length && in_flight < max_in_flight) {
var update = local_updates.shift()
if (!update.version?.length) continue
in_flight++
send_to_remote(update).then(() => {
if (signal.aborted) return
in_flight--
if (local_updates.length) send_local_updates()
}).catch(handle_error)
}
}
braid_text.get(local_key, {
signal,
merge_type: 'dt',
peer: options.peer,
...resource.meta.fork_point && {parents: resource.meta.fork_point},
subscribe: update => {
if (signal.aborted) return
if (update.version?.length) {
local_updates.push(update)
send_local_updates()
}
}
})
// ── Remote → Local ──
//
// Subscribe to remote changes and apply them locally via .put().
// Requests DT binary encoding for efficiency.
var remote_current_version = null
var remote_status = null
await braid_text.get(remote_url, {
signal,
dont_retry: true,
headers: { ...get_headers, 'Merge-Type': 'dt', 'accept-encoding': 'updates(dt)' },
parents: resource.meta.fork_point,
peer: options.peer,
heartbeats: 120,
on_response: res => {
remote_status = res.status
remote_current_version = res.headers.get('current-version')
options.on_res?.(res)
},
subscribe: async update => {
if (signal.aborted) return
if (update.extra_headers?.encoding === 'dt') {
// DT binary: apply directly
await braid_text.put(local_key, {
body: update.body,
transfer_encoding: 'dt',
peer: options.peer
})
if (signal.aborted) return
if (remote_current_version) extend_fork_point({
version: JSON.parse(`[${remote_current_version}]`),
parents: resource.meta.fork_point || []
})
} else {
// Text patches: forward as-is
if (options.peer) update.peer = options.peer
await braid_text.put(local_key, update)
if (signal.aborted) return
if (update.version) extend_fork_point(update)
}
},
on_error: e => {
options.on_disconnect?.()
handle_error(e)
}
})
if (signal.aborted) return
// If remote returned 404, reconnect with backoff
// (the resource might be created later by our local→remote PUTs)
if (remote_status === 404) {
return handle_error(new Error('remote returned 404'))
}
} catch (e) { handle_error(e) }
})
}
braid_text.serve = async (req, res, options = {}) => {
options = {
key: req.url.split('?')[0],
put_cb: (key, val, params) => { },
...options
}
// ── Setup: prepare the response and load the resource ──
if (braid_text.cors !== false) braid_text.free_cors(res)
function my_end(statusCode, x, statusText, headers) {
res.writeHead(statusCode, statusText, headers)
res.end(x ?? '')
}
var resource = null
try {
resource = await get_resource(options.key)
// Add braid protocol support to the req/res objects
braidify(req, res)
if (res.is_multiplexer) return
if (req.version) req.version.sort()
if (req.parents) req.parents.sort()
} catch (e) {
return my_end(500, 'The server failed to process this request. The error generated was: ' + e)
}
// ── Cursors get their own content-type and are handled independently ──
if (await handle_cursors(resource, req, res)) return
// ── Classify the request ──
var peer = req.headers['peer'],
merge_type = req.headers['merge-type'] || 'simpleton'
if (merge_type !== 'simpleton' && merge_type !== 'dt' && merge_type !== 'yjs')
return my_end(400, `Unknown merge type: ${merge_type}`)
var is_read = req.method === 'GET' || req.method === 'HEAD',
is_write = req.method === 'PUT' || req.method === 'POST' || req.method === 'PATCH',
is_head = req.method === 'HEAD'
// ── Ensure the response is labeled as utf-8 text ──
if (!res.getHeader('content-type')) res.setHeader('Content-Type', 'text/plain')
var ct = res.getHeader('Content-Type'),
ct_parts = ct.split(';').map(p => p.trim())
var charset = ct_parts.find(p => p.toLowerCase().startsWith('charset='))
if (!charset)
res.setHeader('Content-Type', `${ct}; charset=utf-8`)
else if (charset.toLowerCase() !== 'charset=utf-8')
res.setHeader('Content-Type', ct_parts
.map(p => p.toLowerCase().startsWith('charset=') ? 'charset=utf-8' : p)
.join('; '))
// ── Handle simple methods that don't need further processing ──
if (req.method === 'OPTIONS') return my_end(200)
if (req.method === 'DELETE') {
await braid_text.delete(resource)
return my_end(200)
}
var current_version = () => ascii_ify(
resource.version.map(x => JSON.stringify(x)).join(', '))
// ── Read state (with GET or HEAD) ──
if (is_read) {
// Validate requested versions exist
var unknowns = []
for (var event of (req.version || []).concat(req.parents || [])) {
var [actor, seq] = decode_version(event)
if (!resource.dt?.known_versions[actor]?.has(seq))
unknowns.push(event)
}
if (unknowns.length)
return my_end(309, '', 'Version Unknown Here', {
Version: ascii_ify(unknowns.map(e => JSON.stringify(e)).join(', '))
})
var has_parents = req.parents && req.parents.length > 0
var has_version = req.version && req.version.length > 0
if (req.subscribe && has_version)
return my_end(400, 'Version header is not allowed with Subscribe — use Parents instead')
var getting = {
subscribe: !!req.subscribe,
history: (has_parents && v_eq(req.parents, resource.version)) ? false
: has_parents ? 'since-parents'
: (req.subscribe || req.parents || req.headers['accept-transfer-encoding']) ? 'up-to-version'
: false,
transfer_encoding: req.headers['accept-transfer-encoding'],
}
getting.single_snapshot = !getting.subscribe && !getting.history
// Response headers
if (getting.subscribe && !res.hasHeader('editable'))
// BUG: This shouldn't be guarded behind "subscribe" because
// clients can also edit text without subscribing to it, just
// by doing PUTs and polling to see the updates to the state.
//
// But this should only be editable if the client can actually
// edit it, and so I am guessing that whoever wrote this might
// have been actually trying to guard something that happens
// to correlate with subscriptions, which is bogus, but needs
// to be thought through and fixed.
res.setHeader('Editable', 'true')
res.setHeader('Current-Version', current_version())
res.setHeader('Merge-Type', merge_type)
res.setHeader('Accept-Subscribe', 'true')
// HEAD: headers only, no body needed
if (is_head) {
// Always include the version of what would be returned
if (!getting.history)
res.setHeader('Version', current_version())
return my_end(200)
}
if (!getting.subscribe) {
// ── One-shot read ──
try {
var result = await braid_text.get(resource, {
version: req.version,
parents: req.parents,
transfer_encoding: getting.transfer_encoding,
full_response: true,
})
} catch (e) {
return my_end(500, 'The server at ' + resource + ' failed: ' + e)
}
if (getting.transfer_encoding === 'dt') {
res.setHeader('X-Transfer-Encoding', 'dt')
res.setHeader('Content-Length', result.body.length)
return my_end(209, result.body, 'Multiresponse')
} else if (Array.isArray(result)) {
// Range of history: send as 209 Multiresponse
res.startSubscription()
for (var u of result)
res.sendVersion({
version: [u.version],
parents: u.parents,
patches: [{ unit: u.unit, range: u.range, content: u.content }],
})
return res.end()
} else {
res.setHeader('Version', ascii_ify(result.version
.map(v => JSON.stringify(v))
.join(', ')))
var buffer = Buffer.from(result.body, 'utf8')
res.setHeader('Repr-Digest', get_digest(buffer))
res.setHeader('Content-Length', buffer.length)
return my_end(200, buffer)
}
} else {
// ── Subscribe ──
all_subscriptions.add(res)
var aborter = new AbortController()
res.startSubscription({
onClose: () => {
all_subscriptions.delete(res)
aborter.abort()
}
})
try {
await braid_text.get(resource, {
peer,
version: req.version,
parents: req.parents,
merge_type,
signal: aborter.signal,
accept_encoding:
req.headers['x-accept-encoding'] ?? req.headers['accept-encoding'],
subscribe: update => {
// Add digest for integrity checking on the client
if (update.version && v_eq(update.version, resource.version))
update['Repr-Digest'] = get_digest(resource.val)
// Collapse single-element patches array for HTTP
if (update.patches && update.patches.length === 1) {
update.patch = update.patches[0]
delete update.patches
}
res.sendVersion(update)
},
})
// Ensure headers are sent even if .get() didn't send
// any initial data (e.g. subscribe when already current)
res.flushHeaders()
} catch (e) {
return my_end(500, 'The server failed to get something. The error generated was: ' + e)
}
return
}
}
// ── Write (PUT / POST / PATCH) ──
if (is_write) {
if (waiting_puts >= 100)
return my_end(503, 'The server is busy.')
waiting_puts++
var done_my_turn = (statusCode, x, statusText, headers) => {
waiting_puts--
my_end(statusCode, x, statusText, headers)
}
try {
// Parse patches from request body
var patches = await req.patches()
for (var p of patches) p.content = p.content_text
var body = null
if (patches[0]?.unit === 'everything') {
body = patches[0].content
patches = null
}
// Wait for parent versions to arrive (if needed)
if (req.parents) {
await ensure_dt_exists(resource)
await wait_for_events(
options.key, req.parents,
resource.dt.known_versions,
body != null ? body.length :
patches.reduce((a, b) => a + b.range.length + b.content.length, 0),
options.recv_buffer_max_time,
options.recv_buffer_max_space)
var unknowns = []
for (var event of req.parents) {
var [actor, seq] = decode_version(event)
if (!resource.dt.known_versions[actor]?.has(seq))
unknowns.push(event)
}
if (unknowns.length)
return done_my_turn(309, '', 'Version Unknown Here', {
Version: ascii_ify(unknowns.map(e => JSON.stringify(e)).join(', ')),
'Retry-After': '1'
})
}
// Apply the edit
var old_val = resource.val
var old_version = resource.version
var put_patches = patches?.map(p => ({
unit: p.unit, range: p.range, content: p.content
})) || null
var {dt: {change_count}} = await braid_text.put(resource, {
peer, version: req.version, parents: req.parents,
patches, body, merge_type
})
// Verify Repr-Digest if present
if (req.headers['repr-digest'] &&
v_eq(req.version, resource.version) &&
req.headers['repr-digest'] !== get_digest(resource.val))
return done_my_turn(550, 'repr-digest mismatch!')
if (req.version?.length)
got_event(options.key, req.version[0], change_count)
res.setHeader('Version', current_version())
options.put_cb(options.key, resource.val, {
old_val, patches: put_patches,
version: resource.version, parents: old_version
})
} catch (e) {
console.log(`${req.method} ERROR: ${e.stack}`)
return done_my_turn(500, 'The server failed to apply this version. The error generated was: ' + e)
}
return done_my_turn(200)
}
throw new Error('unknown method: ' + req.method)
}
braid_text.delete = async (key, options) => {
if (!options) options = {}
// Handle URL - make a DELETE request
if (key instanceof URL) {
var params = {
method: 'DELETE',
signal: options.signal,
}
for (var x of ['headers', 'peer'])
if (options[x] != null) params[x] = options[x]
return await braid_fetch(key.href, params)
}
// Accept either a key string or a resource object
let resource = (typeof key == 'string') ? await get_resource(key) : key
await resource.delete()
}
// Fetch from a remote braid-text server via HTTP
async function get_remote(url, options) {
if (!options) options = {}
var params = {
signal: options.signal,
subscribe: !!options.subscribe,
heartbeats: options.heartbeats ?? 120,
heartbeat_cb: options.heartbeat_cb
}
if (!options.dont_retry)
params.retry = (res) => res.status !== 404
for (var x of ['headers', 'parents', 'version', 'peer'])
if (options[x] != null) params[x] = options[x]
var res = await braid_fetch(url.href, params)
if (options.on_response) options.on_response(res)
if (res.status === 404) return ''
if (options.subscribe) {
res.subscribe(async update => {
// Convert binary to text, except for dt-encoded blobs
// which are passed through as-is for .sync() to handle
if (update.extra_headers?.encoding !== 'dt') {
update.body = update.body_text
if (update.patches)
for (var p of update.patches) p.content = p.content_text
}
await options.subscribe(update)
}, e => options.on_error?.(e))
} else return await res.text()
}
braid_text.get = async (key, options) => {
if (options && options.version) {
validate_version_array(options.version)
options.version.sort()
}
if (options && options.parents) {
validate_version_array(options.parents)
options.parents.sort()
}
if (key instanceof URL) return await get_remote(key, options)
if (!options) options = {}
var resource = (typeof key == 'string') ? await get_resource(key) : key
var version = resource.version
var merge_type = options.range_unit === 'yjs-text' ? 'yjs'
: (options.merge_type || 'simpleton')
var has_parents = options.parents && options.parents.length > 0
var has_version = options.version && options.version.length > 0
if (options.subscribe && has_version)
throw new Error('version is not allowed with subscribe — use parents instead')
var getting = {
subscribe: !!options.subscribe,
// 'since-parents' = range of updates from parents to current
// 'up-to-version' = bring client up to current (from scratch)
// false = no history needed
history: (has_parents && v_eq(options.parents, version)) ? false
: has_parents ? 'since-parents'
: (options.subscribe || options.parents || options.transfer_encoding) ? 'up-to-version'
: false,
transfer_encoding: options.transfer_encoding,
}
getting.single_snapshot = !getting.subscribe && !getting.history
// Single snapshot: return the text (optionally at a specific version)
if (getting.single_snapshot) {
if (has_version) {
await ensure_dt_exists(resource)
return options.full_response
? { version: options.version, body: dt_get_string(resource.dt.doc, options.version) }
: dt_get_string(resource.dt.doc, options.version)
}
return options.full_response ? { version, body: resource.val } : resource.val
}
// DT binary encoding: a transport optimization usable by any merge type.
// Returns raw DT bytes instead of text.
if (getting.history && !getting.subscribe && getting.transfer_encoding === 'dt') {
// TODO: move this into the dt/simpleton merge_type cases below
await ensure_dt_exists(resource)
// If requesting the current version, skip the version lookup
// (faster than asking DT about a version we already have)
var req_version = options.version
if (req_version && v_eq(req_version, version)) req_version = null
var bytes = null
if (req_version || options.parents) {
if (req_version) {
var doc = dt_get(resource.dt.doc, req_version)
bytes = doc.toBytes()
} else {
bytes = resource.dt.doc.toBytes()
var doc = Doc.fromBytes(bytes)
}
if (options.parents)
bytes = doc.getPatchSince(
dt_get_local_version(bytes, options.parents))
doc.free()
} else bytes = resource.dt.doc.toBytes()
return { body: bytes }
}
// Each merge-type has a different way of getting history
switch (merge_type) {
case 'yjs':
await ensure_yjs_exists(resource)
// Send history (for both one-shot and subscribe)
if (getting.history) {
if (getting.history === 'since-parents')
throw new Error('yjs-text from arbitrary parents not yet implemented')
var yjs_updates = braid_text.from_yjs_binary(
Y.encodeStateAsUpdate(resource.yjs.doc))
if (!getting.subscribe)
return yjs_updates
for (var u of yjs_updates)
options.subscribe(u)
}
if (getting.subscribe) {
// Register for live updates
// NOTE: This stream mixes two version spaces:
// update.version: DT version space (frontier after this edit)
// update.patches[].version: Yjs version space (clientID-clock)
var client = {
merge_type: 'yjs',
peer: options.peer,
send_update: one_at_a_time(options.subscribe),
abort() { resource.yjs.clients.delete(client) },
}
resource.yjs.clients.add(client)
options.signal?.addEventListener('abort', () => client.abort())
}
break
case 'simpleton':
await ensure_dt_exists(resource)
if (getting.history && !getting.subscribe)
return dt_get_patches(resource.dt.doc,
getting.history === 'since-parents' ? options.parents : undefined)
if (getting.subscribe) {
var client = {
merge_type: 'simpleton',
peer: options.peer,
send_update: one_at_a_time(options.subscribe),
}
// Send initial history
if (getting.history === 'up-to-version')
client.send_update({ version, parents: [], body: resource.val })
else if (getting.history === 'since-parents') {
var from = options.version || options.parents
var local_version = OpLog_remote_to_local(resource.dt.doc, from)
if (local_version)
client.send_update({
version, parents: from,
patches: get_xf_patches(resource.dt.doc, local_version)
})
}
client.abort = () => resource.simpleton.clients.delete(client)
resource.simpleton.clients.add(client)
options.signal?.addEventListener('abort', () => client.abort())
}
break
case 'dt':
await ensure_dt_exists(resource)
if (getting.history && !getting.subscribe)
return dt_get_patches(resource.dt.doc,
getting.history === 'since-parents' ? options.parents : undefined)
if (getting.subscribe) {
var client = {
merge_type: 'dt',
peer: options.peer,
send_update: one_at_a_time(options.subscribe),
accept_encoding_dt: !!options.accept_encoding?.match(/updates\s*\((.*)\)/)?.[1]?.split(',').map(x=>x.trim()).includes('dt'),
}
// Send initial history
if (client.accept_encoding_dt) {
if (!getting.history)
client.send_update({ encoding: 'dt', body: new Doc().toBytes() })
else {
var bytes = resource.dt.doc.toBytes()
if (getting.history === 'since-parents') {
var doc = Doc.fromBytes(bytes)
bytes = doc.getPatchSince(
dt_get_local_version(bytes, options.parents))
doc.free()
}
client.send_update({ encoding: 'dt', body: bytes })
}
} else {
if (getting.history === 'up-to-version') {
client.send_update({ version: [], parents: [], body: "" })
var updates = dt_get_patches(resource.dt.doc)
} else if (getting.history === 'since-parents')
var updates = dt_get_patches(resource.dt.doc, options.parents || options.version)
if (updates) {
for (var u of updates)
client.send_update({
version: [u.version], parents: u.parents,
patches: [{ unit: u.unit, range: u.range, content: u.content }],
})
}
}
client.abort = () => resource.dt.clients.delete(client)
resource.dt.clients.add(client)
options.signal?.addEventListener('abort', () => client.abort())
}
break
}
}
// Deprecated: Use client.abort() instead
braid_text.forget = async (key, client) => {
console.warn('braid_text.forget() is deprecated. Use client.abort() instead.')
if (client && client.abort) client.abort()
}
braid_text.put = async (key, options) => {
if (options.version) {
validate_version_array(options.version)
options.version.sort()
}
if (options.parents) {
validate_version_array(options.parents)
options.parents.sort()
}
if (key instanceof URL) {
var params = {
method: 'PUT',
signal: options.signal,
}
if (!options.dont_retry)
params.retry = () => true
for (var x of ['headers', 'parents', 'version', 'peer', 'body', 'patches'])
if (options[x] != null) params[x] = options[x]
return { response: await braid_fetch(key.href, params) }
}
let resource = (typeof key == 'string') ? await get_resource(key) : key
return await within_fiber('put:' + resource.key, async () => {
// support for json patch puts..
if (options.patches && options.patches.length &&
options.patches.every(x => x.unit === 'json')) {
let x = JSON.parse(resource.val)
for (let p of options.patches)
apply_patch(x, p.range, p.content === '' ? undefined : JSON.parse(p.content))
options = { body: JSON.stringify(x, null, 4) }
}
let { version, parents, patches, body, peer } = options
// Yjs update: either raw binary (yjs_update) or yjs-text patches
var yjs_binary = null
var yjs_text_patches = null
if (options.yjs_update) {
yjs_binary = options.yjs_update instanceof Uint8Array
? options.yjs_update : new Uint8Array(options.yjs_update)
} else if (patches && patches.length && patches[0].unit === 'yjs-text') {
yjs_text_patches = patches
yjs_binary = braid_text.to_yjs_binary([{
version: options.version?.[0],
patches
}])
}
if (yjs_binary) {
await ensure_yjs_exists(resource)
// Apply binary update to Y.Doc, capturing the delta
var prev_text = resource.yjs.text.toString()
var delta = null
var observer = (e) => { delta = e.changes.delta }
resource.yjs.text.observe(observer)
try {
Y.applyUpdate(resource.yjs.doc, yjs_binary)
} finally {
resource.yjs.text.unobserve(observer)
}
resource.val = resource.yjs.text.toString()
// Sync to DT if it exists
if (resource.dt && delta) {
var text_patches = yjs_delta_to_patches(delta, prev_text)
if (text_patches.length) {
var syn_actor = `yjs-${Date.now()}-${Math.random().toString(36).slice(2)}`
var syn_seq = 0
var version_before_yjs_sync = resource.version
var yjs_v_before = resource.dt.doc.getLocalVersion()
var dt_bytes = []
var dt_ps = resource.version
for (var tp of text_patches) {
var tp_range = tp.range.match(/-?\d+/g).map(Number)
var tp_del = tp_range[1] - tp_range[0]
var syn_v = `${syn_actor}-${syn_seq}`
if (tp_del) {
dt_bytes.push(dt_create_bytes(syn_v, dt_ps, tp_range[0], tp_del, null))
dt_ps = [`${syn_actor}-${syn_seq + tp_del - 1}`]
syn_seq += tp_del
syn_v = `${syn_actor}-${syn_seq}`
}
if (tp.content.length) {
dt_bytes.push(dt_create_bytes(syn_v, dt_ps, tp_range[0], 0, tp.content))
var cp_len = [...tp.content].length
dt_ps = [`${syn_actor}-${syn_seq + cp_len - 1}`]
syn_seq += cp_len
}
}
for (var b of dt_bytes) resource.dt.doc.mergeBytes(b)
resource.version = resource.dt.doc.getRemoteVersion().map(x => x.join("-")).sort()
if (!resource.dt.known_versions[syn_actor])
resource.dt.known_versions[syn_actor] = new RangeSet()
resource.dt.known_versions[syn_actor].add_range(0, syn_seq - 1)
await resource.dt.log.save(resource.dt.doc.getPatchSince(yjs_v_before))
// Broadcast to simpleton and DT clients
var xf = get_xf_patches(resource.dt.doc, yjs_v_before)
for (let client of resource.simpleton.clients) {
if (!peer || client.peer !== peer)
await client.send_update({
version: resource.version,
parents: version_before_yjs_sync,
patches: xf
})
}
for (let client of resource.dt.clients) {
if (!peer || client.peer !== peer)
await client.send_update(
client.accept_encoding_dt
? { version: resource.version,
parents: version_before_yjs_sync,
body: resource.dt.doc.getPatchSince(yjs_v_before),
encoding: 'dt'
}
: { version: resource.version,
parents: version_before_yjs_sync,
patches: xf
}
)