-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1731 lines (1458 loc) · 60.6 KB
/
index.js
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 } = require("diamond-types-node")
let braidify = require("braid-http").http_server
let fs = require("fs")
let MISSING_PARENT_VERSION = 'missing parent version'
let braid_text = {
verbose: false,
db_folder: './braid-text-db',
length_cache_size: 10,
cache: {},
delete_cache: {}
}
let waiting_puts = 0
let prev_put_p = null
let max_encoded_key_size = 240
braid_text.serve = async (req, res, options = {}) => {
options = {
key: req.url.split('?')[0], // Default key
put_cb: (key, val) => { }, // Default callback when a PUT changes a key
...options // Override with all options passed in
}
// free CORS
res.setHeader("Access-Control-Allow-Origin", "*")
res.setHeader("Access-Control-Allow-Methods", "*")
res.setHeader("Access-Control-Allow-Headers", "*")
res.setHeader("Access-Control-Expose-Headers", "*")
function my_end(statusCode, x) {
res.statusCode = statusCode
res.end(x ?? '')
}
let resource = null
try {
resource = await get_resource(options.key)
braidify(req, res)
} catch (e) {
return my_end(400, "The server failed to process this request. The error generated was: " + e)
}
let peer = req.headers["peer"]
let merge_type = req.headers["merge-type"]
if (!merge_type) merge_type = 'simpleton'
if (merge_type !== 'simpleton' && merge_type !== 'dt') return my_end(400, `Unknown merge type: ${merge_type}`)
// set default content type of text/plain
if (!res.getHeader('content-type')) res.setHeader('Content-Type', 'text/plain')
// no matter what the content type is,
// we want to set the charset to utf-8
const contentType = res.getHeader('Content-Type')
const parsedContentType = contentType.split(';').map(part => part.trim())
const charsetParam = parsedContentType.find(part => part.toLowerCase().startsWith('charset='))
if (!charsetParam)
res.setHeader('Content-Type', `${contentType}; charset=utf-8`)
else if (charsetParam.toLowerCase() !== 'charset=utf-8') {
// Replace the existing charset with utf-8
const updatedContentType = parsedContentType
.map(part => (part.toLowerCase().startsWith('charset=') ? 'charset=utf-8' : part))
.join('; ');
res.setHeader('Content-Type', updatedContentType);
}
if (req.method == "OPTIONS") return my_end(200)
if (req.method == "DELETE") {
await braid_text.delete(resource)
return my_end(200)
}
if (req.method == "GET" || req.method == "HEAD") {
if (!req.subscribe) {
res.setHeader("Accept-Subscribe", "true")
let x = null
try {
x = await braid_text.get(resource, { version: req.version, parents: req.parents })
} catch (e) {
return my_end(400, "The server failed to get something. The error generated was: " + e)
}
res.setHeader("Version", x.version.map((x) => JSON.stringify(x)).join(", "))
const buffer = Buffer.from(x.body, "utf8")
res.setHeader("Repr-Digest", `sha-256=:${require('crypto').createHash('sha256').update(buffer).digest('base64')}:`)
res.setHeader("Content-Length", buffer.length)
if (req.method === "HEAD") return my_end(200)
return my_end(200, buffer)
} else {
if (!res.hasHeader("editable")) res.setHeader("Editable", "true")
res.setHeader("Merge-Type", merge_type)
if (req.method == "HEAD") return my_end(200)
let options = {
peer,
version: req.version,
parents: req.parents,
merge_type,
subscribe: x => res.sendVersion(x),
write: (x) => res.write(x)
}
res.startSubscription({
onClose: () => {
if (merge_type === "dt") resource.clients.delete(options)
else resource.simpleton_clients.delete(options)
}
})
try {
return await braid_text.get(resource, options)
} catch (e) {
return my_end(400, "The server failed to get something. The error generated was: " + e)
}
}
}
if (req.method == "PUT" || req.method == "POST" || req.method == "PATCH") {
if (waiting_puts >= 100) {
console.log(`The server is busy.`)
return my_end(503, "The server is busy.")
}
waiting_puts++
if (braid_text.verbose) console.log(`waiting_puts(after++) = ${waiting_puts}`)
let my_prev_put_p = prev_put_p
let done_my_turn = null
prev_put_p = new Promise(
(done) =>
(done_my_turn = (statusCode, x) => {
waiting_puts--
if (braid_text.verbose) console.log(`waiting_puts(after--) = ${waiting_puts}`)
my_end(statusCode, x)
done()
})
)
let patches = null
let ee = null
try {
patches = await req.patches()
for (let p of patches) p.content = p.content_text
} catch (e) { ee = e }
await my_prev_put_p
try {
if (ee) throw ee
let body = null
if (patches[0]?.unit === 'everything') {
body = patches[0].content
patches = null
}
await braid_text.put(resource, { peer, version: req.version, parents: req.parents, patches, body, merge_type })
res.setHeader("Version", resource.doc.getRemoteVersion().map((x) => x.join("-")).sort())
options.put_cb(options.key, resource.val)
} catch (e) {
console.log(`${req.method} ERROR: ${e.stack}`)
if (e.message?.startsWith(MISSING_PARENT_VERSION)) {
// we couldn't apply the version, because we're missing its parents,
// we want to send a 4XX error, so the client will resend this request later,
// hopefully after we've received the necessary parents.
// here are some 4XX error code options..
//
// - 425 Too Early
// - pros: our message is too early
// - cons: associated with some "Early-Data" http thing, which we're not using
// - 400 Bad Request
// - pros: pretty generic
// - cons: implies client shouldn't resend as-is
// - 409 Conflict
// - pros: doesn't imply modifications needed
// - cons: the message is not conflicting with anything
// - 412 Precondition Failed
// - pros: kindof true.. the precondition of having another version has failed..
// - cons: not strictly true, as this code is associated with http's If-Unmodified-Since stuff
// - 422 Unprocessable Content
// - pros: it's true
// - cons: implies client shouldn't resend as-is (at least, it says that here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422)
// - 428 Precondition Required
// - pros: the name sounds right
// - cons: typically implies that the request was missing an http conditional field like If-Match. that is to say, it implies that the request is missing a precondition, not that the server is missing a precondition
return done_my_turn(425, e.message)
} else {
return done_my_turn(400, "The server failed to apply this version. The error generated was: " + e)
}
}
return done_my_turn(200)
}
throw new Error("unknown")
}
braid_text.delete = async (key) => {
let resource = (typeof key == 'string') ? await get_resource(key) : key
await resource.delete_me()
}
braid_text.get = async (key, options) => {
if (!options) {
// if it doesn't exist already, don't create it in this case
if (!braid_text.cache[key]) return
return (await get_resource(key)).val
}
if (options.version) validate_version_array(options.version)
if (options.parents) validate_version_array(options.parents)
let resource = (typeof key == 'string') ? await get_resource(key) : key
if (!options.subscribe) {
let doc = resource.doc
if (options.version || options.parents) doc = dt_get(doc, options.version || options.parents)
let ret = {
version: doc.getRemoteVersion().map((x) => x.join("-")).sort(),
body: doc.get()
}
if (options.version || options.parents) doc.free()
return ret
} else {
if (options.merge_type != "dt") {
let version = resource.doc.getRemoteVersion().map((x) => x.join("-")).sort()
let x = { version }
if (!options.parents && !options.version) {
x.parents = []
x.body = resource.doc.get()
options.subscribe(x)
} else {
x.parents = options.version ? options.version : options.parents
options.my_last_seen_version = x.parents
// only send them a version from these parents if we have these parents (otherwise we'll assume these parents are more recent, probably versions they created but haven't sent us yet, and we'll send them appropriate rebased updates when they send us these versions)
let local_version = OpLog_remote_to_local(resource.doc, x.parents)
if (local_version) {
x.patches = get_xf_patches(resource.doc, local_version)
options.subscribe(x)
}
}
options.my_last_sent_version = x.version
resource.simpleton_clients.add(options)
} else {
let updates = null
if (resource.need_defrag) {
if (braid_text.verbose) console.log(`doing defrag..`)
resource.need_defrag = false
resource.doc = defrag_dt(resource.doc)
}
if (!options.parents && !options.version) {
options.subscribe({
version: [],
parents: [],
body: "",
})
updates = dt_get_patches(resource.doc)
} else {
// Then start the subscription from the parents in options
updates = dt_get_patches(resource.doc, options.parents || options.version)
}
for (let u of updates)
options.subscribe({
version: [u.version],
parents: u.parents,
patches: [{ unit: u.unit, range: u.range, content: u.content }],
})
// Output at least *some* data, or else chrome gets confused and
// thinks the connection failed. This isn't strictly necessary,
// but it makes fewer scary errors get printed out in the JS
// console.
if (updates.length === 0) options.write?.("\r\n")
resource.clients.add(options)
}
}
}
braid_text.forget = async (key, options) => {
if (!options) throw new Error('options is required')
let resource = (typeof key == 'string') ? await get_resource(key) : key
if (options.merge_type != "dt")
resource.simpleton_clients.delete(options)
else resource.clients.delete(options)
}
braid_text.put = async (key, options) => {
let { version, patches, body, peer } = options
// support for json patch puts..
if (patches?.length && patches.every(x => x.unit === 'json')) {
let resource = (typeof key == 'string') ? await get_resource(key) : key
let x = JSON.parse(resource.doc.get())
for (let p of patches)
apply_patch(x, p.range, p.content === '' ? undefined : JSON.parse(p.content))
return await braid_text.put(key, {
body: JSON.stringify(x, null, 4)
})
}
if (version) validate_version_array(version)
// translate a single parent of "root" to the empty array (same meaning)
let options_parents = options.parents
if (options_parents?.length === 1 && options_parents[0] === 'root')
options_parents = []
if (options_parents) validate_version_array(options_parents)
if (body != null && patches) throw new Error(`cannot have a body and patches`)
if (body != null && (typeof body !== 'string')) throw new Error(`body must be a string`)
if (patches) validate_patches(patches)
let resource = (typeof key == 'string') ? await get_resource(key) : key
if (options_parents) {
// make sure we have all these parents
for (let p of options_parents) {
let P = decode_version(p)
if (P[1] > (resource.actor_seqs[P[0]] ?? -1)) throw new Error(`${MISSING_PARENT_VERSION}: ${p}`)
}
}
let parents = resource.doc.getRemoteVersion().map((x) => x.join("-")).sort()
let og_parents = options_parents || parents
function get_len() {
let d = dt_get(resource.doc, og_parents)
let len = d.len()
d.free()
return len
}
let max_pos = resource.length_cache.get('' + og_parents) ??
(v_eq(parents, og_parents) ? resource.doc.len() : get_len())
if (body != null) {
patches = [{
unit: 'text',
range: `[0:${max_pos}]`,
content: body
}]
}
let og_patches = patches
patches = patches.map((p) => ({
...p,
range: p.range.match(/\d+/g).map((x) => parseInt(x)),
content_codepoints: [...p.content],
})).sort((a, b) => a.range[0] - b.range[0])
// validate patch positions
let must_be_at_least = 0
for (let p of patches) {
if (p.range[0] < must_be_at_least || p.range[0] > max_pos) throw new Error(`invalid patch range position: ${p.range[0]}`)
if (p.range[1] < p.range[0] || p.range[1] > max_pos) throw new Error(`invalid patch range position: ${p.range[1]}`)
must_be_at_least = p.range[1]
}
let change_count = patches.reduce((a, b) => a + b.content_codepoints.length + (b.range[1] - b.range[0]), 0)
let og_v = version?.[0] || `${(is_valid_actor(peer) && peer) || Math.random().toString(36).slice(2, 7)}-${change_count - 1}`
// reduce the version sequence by the number of char-edits
let v = decode_version(og_v)
// validate version: make sure we haven't seen it already
if (v[1] <= (resource.actor_seqs[v[0]] ?? -1)) {
if (!options.validate_already_seen_versions) return
// if we have seen it already, make sure it's the same as before
let updates = dt_get_patches(resource.doc, og_parents)
let seen = {}
for (let u of updates) {
u.version = decode_version(u.version)
if (!u.content) {
// delete
let v = u.version
for (let i = 0; i < u.end - u.start; i++) {
let ps = (i < u.end - u.start - 1) ? [`${v[0]}-${v[1] - i - 1}`] : u.parents
seen[JSON.stringify([v[0], v[1] - i, ps, u.start + i])] = true
}
} else {
// insert
let v = u.version
let content = [...u.content]
for (let i = 0; i < content.length; i++) {
let ps = (i > 0) ? [`${v[0]}-${v[1] - content.length + i}`] : u.parents
seen[JSON.stringify([v[0], v[1] + 1 - content.length + i, ps, u.start + i, content[i]])] = true
}
}
}
v = `${v[0]}-${v[1] + 1 - change_count}`
let ps = og_parents
let offset = 0
for (let p of patches) {
// delete
for (let i = p.range[0]; i < p.range[1]; i++) {
let vv = decode_version(v)
if (!seen[JSON.stringify([vv[0], vv[1], ps, p.range[1] - 1 + offset])]) throw new Error('invalid update: different from previous update with same version')
offset--
ps = [v]
v = vv
v = `${v[0]}-${v[1] + 1}`
}
// insert
for (let i = 0; i < p.content_codepoints?.length ?? 0; i++) {
let vv = decode_version(v)
let c = p.content_codepoints[i]
if (!seen[JSON.stringify([vv[0], vv[1], ps, p.range[1] + offset, c])]) throw new Error('invalid update: different from previous update with same version')
offset++
ps = [v]
v = vv
v = `${v[0]}-${v[1] + 1}`
}
}
// we already have this version, so nothing left to do
return
}
resource.actor_seqs[v[0]] = v[1]
resource.length_cache.put(`${v[0]}-${v[1]}`, patches.reduce((a, b) =>
a + (b.content_codepoints.length ? b.content_codepoints.length : -(b.range[1] - b.range[0])),
max_pos))
v = `${v[0]}-${v[1] + 1 - change_count}`
let ps = og_parents
let v_before = resource.doc.getLocalVersion()
let bytes = []
let offset = 0
for (let p of patches) {
// delete
let del = p.range[1] - p.range[0]
if (del) {
bytes.push(dt_create_bytes(v, ps, p.range[0] + offset, del, null))
offset -= del
v = decode_version(v)
ps = [`${v[0]}-${v[1] + (del - 1)}`]
v = `${v[0]}-${v[1] + del}`
}
// insert
if (p.content?.length) {
bytes.push(dt_create_bytes(v, ps, p.range[1] + offset, 0, p.content))
offset += p.content_codepoints.length
v = decode_version(v)
ps = [`${v[0]}-${v[1] + (p.content_codepoints.length - 1)}`]
v = `${v[0]}-${v[1] + p.content_codepoints.length}`
}
}
for (let b of bytes) resource.doc.mergeBytes(b)
resource.val = resource.doc.get()
resource.need_defrag = true
if (options.merge_type != "dt") {
patches = get_xf_patches(resource.doc, v_before)
if (braid_text.verbose) console.log(JSON.stringify({ patches }))
let version = resource.doc.getRemoteVersion().map((x) => x.join("-")).sort()
for (let client of resource.simpleton_clients) {
if (client.peer == peer) {
client.my_last_seen_version = [og_v]
}
function set_timeout(time_override) {
if (client.my_timeout) clearTimeout(client.my_timeout)
client.my_timeout = setTimeout(() => {
let version = resource.doc.getRemoteVersion().map((x) => x.join("-")).sort()
let x = { version }
x.parents = client.my_last_seen_version
if (braid_text.verbose) console.log("rebasing after timeout.. ")
if (braid_text.verbose) console.log(" client.my_unused_version_count = " + client.my_unused_version_count)
x.patches = get_xf_patches(resource.doc, OpLog_remote_to_local(resource.doc, client.my_last_seen_version))
if (braid_text.verbose) console.log(`sending from rebase: ${JSON.stringify(x)}`)
client.subscribe(x)
client.my_last_sent_version = x.version
delete client.my_timeout
}, time_override ?? Math.min(3000, 23 * Math.pow(1.5, client.my_unused_version_count - 1)))
}
if (client.my_timeout) {
if (client.peer == peer) {
if (!v_eq(client.my_last_sent_version, og_parents)) {
// note: we don't add to client.my_unused_version_count,
// because we're already in a timeout;
// we'll just extend it here..
set_timeout()
} else {
// hm.. it appears we got a correctly parented version,
// which suggests that maybe we can stop the timeout early
set_timeout(0)
}
}
continue
}
let x = { version }
if (client.peer == peer) {
if (!v_eq(client.my_last_sent_version, og_parents)) {
client.my_unused_version_count = (client.my_unused_version_count ?? 0) + 1
set_timeout()
continue
} else {
delete client.my_unused_version_count
}
x.parents = options.version
if (!v_eq(version, options.version)) {
if (braid_text.verbose) console.log("rebasing..")
x.patches = get_xf_patches(resource.doc, OpLog_remote_to_local(resource.doc, [og_v]))
} else {
// this client already has this version,
// so let's pretend to send it back, but not
if (braid_text.verbose) console.log(`not reflecting back to simpleton`)
client.my_last_sent_version = x.version
continue
}
} else {
x.parents = parents
x.patches = patches
}
if (braid_text.verbose) console.log(`sending: ${JSON.stringify(x)}`)
client.subscribe(x)
client.my_last_sent_version = x.version
}
} else {
if (resource.simpleton_clients.size) {
let version = resource.doc.getRemoteVersion().map((x) => x.join("-")).sort()
patches = get_xf_patches(resource.doc, v_before)
let x = { version, parents, patches }
if (braid_text.verbose) console.log(`sending: ${JSON.stringify(x)}`)
for (let client of resource.simpleton_clients) {
if (client.my_timeout) continue
client.subscribe(x)
client.my_last_sent_version = x.version
}
}
}
let x = {
version: [og_v],
parents: og_parents,
patches: og_patches,
}
for (let client of resource.clients) {
if (client.peer != peer) client.subscribe(x)
}
await resource.db_delta(resource.doc.getPatchSince(v_before))
}
braid_text.list = async () => {
try {
if (braid_text.db_folder) {
await db_folder_init()
var pages = new Set()
for (let x of await require('fs').promises.readdir(braid_text.db_folder)) pages.add(decode_filename(x.replace(/\.\w+$/, '')))
return [...pages.keys()]
} else return Object.keys(braid_text.cache)
} catch (e) { return [] }
}
async function get_resource(key) {
if (braid_text.delete_cache[key]) await braid_text.delete_cache[key]
let cache = braid_text.cache
if (!cache[key]) cache[key] = new Promise(async done => {
let resource = {key}
resource.clients = new Set()
resource.simpleton_clients = new Set()
resource.doc = new Doc("server")
let { change, delete_me } = braid_text.db_folder
? await file_sync(key,
(bytes) => resource.doc.mergeBytes(bytes),
() => resource.doc.toBytes())
: { change: () => { }, delete_me: () => { } }
resource.db_delta = change
resource.doc = defrag_dt(resource.doc)
resource.need_defrag = false
resource.actor_seqs = {}
let max_version = Math.max(...resource.doc.getLocalVersion()) ?? -1
for (let i = 0; i <= max_version; i++) {
let v = resource.doc.localToRemoteVersion([i])[0]
resource.actor_seqs[v[0]] = Math.max(v[1], resource.actor_seqs[v[0]] ?? -1)
}
resource.delete_me = async () => {
delete cache[key]
await (braid_text.delete_cache[key] = delete_me())
}
resource.val = resource.doc.get()
resource.length_cache = createSimpleCache(braid_text.length_cache_size)
done(resource)
})
return await cache[key]
}
async function db_folder_init() {
if (braid_text.verbose) console.log('__!')
if (!db_folder_init.p) db_folder_init.p = new Promise(async done => {
await fs.promises.mkdir(braid_text.db_folder, { recursive: true });
// 0.0.13 -> 0.0.14
// look for files with key-encodings over max_encoded_key_size,
// and convert them using the new method
// for (let x of await fs.promises.readdir(braid_text.db_folder)) {
// let k = x.replace(/(_[0-9a-f]{64})?\.\w+$/, '')
// if (k.length > max_encoded_key_size) {
// k = decode_filename(k)
// await fs.promises.rename(`${braid_text.db_folder}/${x}`, `${braid_text.db_folder}/${encode_filename(k)}${x.match(/\.\w+$/)[0]}`)
// await fs.promises.writeFile(`${braid_text.db_folder}/${encode_filename(k)}.name`, k)
// }
// }
// 0.0.14 -> 0.0.15
// basically convert the 0.0.14 files back
let convert_us = {}
for (let x of await fs.promises.readdir(braid_text.db_folder)) {
if (x.endsWith('.name')) {
let encoded = convert_us[x.slice(0, -'.name'.length)] = encode_filename(await fs.promises.readFile(`${braid_text.db_folder}/${x}`, { encoding: 'utf8' }))
if (encoded.length > max_encoded_key_size) {
console.log(`trying to convert file to new format, but the key is too big: ${braid_text.db_folder}/${x}`)
process.exit()
}
if (braid_text.verbose) console.log(`deleting: ${braid_text.db_folder}/${x}`)
await fs.promises.unlink(`${braid_text.db_folder}/${x}`)
}
}
if (Object.keys(convert_us).length) {
for (let x of await fs.promises.readdir(braid_text.db_folder)) {
let [_, k, num] = x.match(/^(.*)\.(\d+)$/s)
if (!convert_us[k]) continue
if (braid_text.verbose) console.log(`renaming: ${braid_text.db_folder}/${x} -> ${braid_text.db_folder}/${convert_us[k]}.${num}`)
if (convert_us[k]) await fs.promises.rename(`${braid_text.db_folder}/${x}`, `${braid_text.db_folder}/${convert_us[k]}.${num}`)
}
}
done()
})
await db_folder_init.p
}
async function get_files_for_key(key) {
await db_folder_init()
try {
let re = new RegExp("^" + encode_filename(key).replace(/[^a-zA-Z0-9]/g, "\\$&") + "\\.\\w+$")
return (await fs.promises.readdir(braid_text.db_folder))
.filter((a) => re.test(a))
.map((a) => `${braid_text.db_folder}/${a}`)
} catch (e) { return [] }
}
async function file_sync(key, process_delta, get_init) {
let encoded = encode_filename(key)
if (encoded.length > max_encoded_key_size) throw new Error(`invalid key: too long (max ${max_encoded_key_size})`)
let currentNumber = 0
let currentSize = 0
let threshold = 0
// Read existing files and sort by numbers.
const files = (await get_files_for_key(key))
.filter(x => x.match(/\.\d+$/))
.sort((a, b) => parseInt(a.match(/\d+$/)[0]) - parseInt(b.match(/\d+$/)[0]))
// Try to process files starting from the highest number.
let done = false
for (let i = files.length - 1; i >= 0; i--) {
if (done) {
await fs.promises.unlink(files[i])
continue
}
try {
const filename = files[i]
if (braid_text.verbose) console.log(`trying to process file: ${filename}`)
const data = await fs.promises.readFile(filename)
let cursor = 0
let isFirstChunk = true
while (cursor < data.length) {
const chunkSize = data.readUInt32LE(cursor)
cursor += 4
const chunk = data.slice(cursor, cursor + chunkSize)
cursor += chunkSize
if (isFirstChunk) {
isFirstChunk = false
threshold = chunkSize * 10
}
process_delta(chunk)
}
currentSize = data.length
currentNumber = parseInt(filename.match(/\d+$/)[0])
done = true
} catch (error) {
console.error(`Error processing file: ${files[i]}`)
await fs.promises.unlink(files[i])
}
}
let deleted = false
let chain = Promise.resolve()
return {
change: async (bytes) => {
if (deleted) return
await (chain = chain.then(async () => {
currentSize += bytes.length + 4 // we account for the extra 4 bytes for uint32
const filename = `${braid_text.db_folder}/${encoded}.${currentNumber}`
if (currentSize < threshold) {
if (braid_text.verbose) console.log(`appending to db..`)
let buffer = Buffer.allocUnsafe(4)
buffer.writeUInt32LE(bytes.length, 0)
await fs.promises.appendFile(filename, buffer)
await fs.promises.appendFile(filename, bytes)
if (braid_text.verbose) console.log("wrote to : " + filename)
} else {
try {
if (braid_text.verbose) console.log(`starting new db..`)
currentNumber++
const init = get_init()
const buffer = Buffer.allocUnsafe(4)
buffer.writeUInt32LE(init.length, 0)
const newFilename = `${braid_text.db_folder}/${encoded}.${currentNumber}`
await fs.promises.writeFile(newFilename, buffer)
await fs.promises.appendFile(newFilename, init)
if (braid_text.verbose) console.log("wrote to : " + newFilename)
currentSize = 4 + init.length
threshold = currentSize * 10
try {
await fs.promises.unlink(filename)
} catch (e) { }
} catch (e) {
if (braid_text.verbose) console.log(`e = ${e.stack}`)
}
}
}))
},
delete_me: async () => {
deleted = true
await (chain = chain.then(async () => {
await Promise.all(
(
await get_files_for_key(key)
).map((file) => {
return new Promise((resolve, reject) => {
fs.unlink(file, (err) => {
if (err) {
console.error(`Error deleting file: ${file}`)
reject(err)
} else {
if (braid_text.verbose) console.log(`Deleted file: ${file}`)
resolve()
}
})
})
})
)
}))
},
}
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
function dt_get(doc, version, agent = null) {
if (dt_get.last_doc) dt_get.last_doc.free()
let bytes = doc.toBytes()
dt_get.last_doc = doc = Doc.fromBytes(bytes, agent)
let [_agents, versions, parentss] = dt_parse([...bytes])
let frontier = {}
version.forEach((x) => frontier[x] = true)
let local_version = []
for (let i = 0; i < versions.length; i++)
if (frontier[versions[i].join("-")]) local_version.push(i)
dt_get.last_local_version = local_version = new Uint32Array(local_version)
let after_versions = {}
let [_, after_versions_array, __] = dt_parse([...doc.getPatchSince(local_version)])
for (let v of after_versions_array) after_versions[v.join("-")] = true
let new_doc = new Doc(agent)
let op_runs = doc.getOpsSince([])
let i = 0
op_runs.forEach((op_run) => {
if (op_run.content) op_run.content = [...op_run.content]
let len = op_run.end - op_run.start
let base_i = i
for (let j = 1; j <= len; j++) {
let I = base_i + j
if (
j == len ||
parentss[I].length != 1 ||
parentss[I][0][0] != versions[I - 1][0] ||
parentss[I][0][1] != versions[I - 1][1] ||
versions[I][0] != versions[I - 1][0] ||
versions[I][1] != versions[I - 1][1] + 1
) {
for (; i < I; i++) {
let version = versions[i].join("-")
if (!after_versions[version]) new_doc.mergeBytes(
dt_create_bytes(
version,
parentss[i].map((x) => x.join("-")),
op_run.fwd ?
(op_run.content ?
op_run.start + (i - base_i) :
op_run.start) :
op_run.end - 1 - (i - base_i),
op_run.content?.[i - base_i] != null ? 0 : 1,
op_run.content?.[i - base_i]
)
)
}
}
}
})
return new_doc
}
function dt_get_patches(doc, version = null) {
let bytes = doc.toBytes()
doc = Doc.fromBytes(bytes)
let [_agents, versions, parentss] = dt_parse([...bytes])
let op_runs = []
if (version) {
let frontier = {}
version.forEach((x) => frontier[x] = true)
let local_version = []
for (let i = 0; i < versions.length; i++)
if (frontier[versions[i].join("-")]) local_version.push(i)
let after_bytes = doc.getPatchSince(new Uint32Array(local_version))
;[_agents, versions, parentss] = dt_parse([...after_bytes])
let before_doc = dt_get(doc, version)
let before_doc_frontier = before_doc.getLocalVersion()
before_doc.mergeBytes(after_bytes)
op_runs = before_doc.getOpsSince(before_doc_frontier)
before_doc.free()
} else op_runs = doc.getOpsSince([])
doc.free()
let i = 0
let patches = []
op_runs.forEach((op_run) => {
let version = versions[i]
let parents = parentss[i].map((x) => x.join("-")).sort()
let start = op_run.start
let end = start + 1
if (op_run.content) op_run.content = [...op_run.content]
let len = op_run.end - op_run.start
for (let j = 1; j <= len; j++) {
let I = i + j
if (
(!op_run.content && op_run.fwd) ||
j == len ||
parentss[I].length != 1 ||
parentss[I][0][0] != versions[I - 1][0] ||
parentss[I][0][1] != versions[I - 1][1] ||
versions[I][0] != versions[I - 1][0] ||
versions[I][1] != versions[I - 1][1] + 1
) {
let s = op_run.fwd ?
(op_run.content ?
start :
op_run.start) :
(op_run.start + (op_run.end - end))
let e = op_run.fwd ?
(op_run.content ?
end :
op_run.start + (end - start)) :
(op_run.end - (start - op_run.start))
patches.push({
version: `${version[0]}-${version[1] + e - s - 1}`,
parents,
unit: "text",
range: op_run.content ? `[${s}:${s}]` : `[${s}:${e}]`,
content: op_run.content?.slice(start - op_run.start, end - op_run.start).join("") ?? "",
start: s,
end: e,
})
if (j == len) break
version = versions[I]
parents = parentss[I].map((x) => x.join("-")).sort()
start = op_run.start + j
}
end++
}
i += len
})
return patches
}
function dt_parse(byte_array) {
if (new TextDecoder().decode(new Uint8Array(byte_array.splice(0, 8))) !== "DMNDTYPS") throw new Error("dt parse error, expected DMNDTYPS")
if (byte_array.shift() != 0) throw new Error("dt parse error, expected version 0")
let agents = []
let versions = []
let parentss = []
while (byte_array.length) {
let id = byte_array.shift()
let len = read_varint(byte_array)
if (id == 1) {
} else if (id == 3) {
let goal = byte_array.length - len
while (byte_array.length > goal) {
agents.push(read_string(byte_array))
}
} else if (id == 20) {
} else if (id == 21) {
let seqs = {}
let goal = byte_array.length - len
while (byte_array.length > goal) {
let part0 = read_varint(byte_array)
let has_jump = part0 & 1
let agent_i = (part0 >> 1) - 1
let run_length = read_varint(byte_array)
let jump = 0
if (has_jump) {
let part2 = read_varint(byte_array)
jump = part2 >> 1
if (part2 & 1) jump *= -1
}
let base = (seqs[agent_i] || 0) + jump