-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
sync-fs.ts
422 lines (349 loc) · 11.6 KB
/
sync-fs.ts
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
import { walk } from "https://deno.land/std@0.154.0/fs/walk.ts";
import {
dirname,
extname,
join,
relative,
resolve,
} from "https://deno.land/std@0.154.0/path/mod.ts";
import { Crypto } from "../crypto/crypto.ts";
import { EarthstarError, isErr } from "../util/errors.ts";
import {
IGNORED_FILES,
MANIFEST_FILE_NAME,
MIN_TIMESTAMP_MS,
} from "./constants.ts";
import {
FileInfoEntry,
SyncFsManifest,
SyncFsOptions,
} from "./sync-fs-types.ts";
import {
dirBelongsToDifferentShare,
getDirAssociatedShare,
getTupleWinners,
hasFilesButNoManifest,
isAbsenceEntry,
isFileInfoEntry,
removeEmptyDir,
writeDocToDir,
writeEntryToReplica,
writeManifest,
zipByPath,
} from "./util.ts";
import { AttachmentStreamInfo } from "../util/attachment_stream_info.ts";
import { ConfigEs5, DocEs5, FormatEs5 } from "../formats/format_es5.ts";
const textEncoder = new TextEncoder();
export async function reconcileManifestWithDirContents(
fsDirPath: string,
forShare: string,
): Promise<SyncFsManifest> {
// Open up existing manifest.
let manifest: SyncFsManifest = {
share: forShare,
entries: {},
};
try {
const contents = await Deno.readTextFile(
join(fsDirPath, MANIFEST_FILE_NAME),
);
manifest = JSON.parse(contents);
} catch {
// No manifest was present.
}
const fileEntries: Record<string, FileInfoEntry> = {};
for await (const entry of walk(fsDirPath)) {
if (IGNORED_FILES.includes(entry.name)) {
continue;
}
if (entry.isFile) {
const { path } = entry;
const stat = await Deno.stat(path);
const extension = extname(path);
let exposedContentSize = 0;
let exposedContentHash = "";
if (extension !== "") {
const file = await Deno.open(path);
const streamInfo = new AttachmentStreamInfo();
await file.readable.pipeThrough(streamInfo).pipeTo(
new WritableStream(),
);
exposedContentSize = await streamInfo.size;
exposedContentHash = await streamInfo.hash;
} else {
const contents = await Deno.readTextFile(path);
exposedContentHash = await Crypto.sha256base32(contents);
exposedContentSize = textEncoder.encode(contents).byteLength;
}
const esPath = `/${relative(fsDirPath, path)}`;
const record: FileInfoEntry = {
dirName: dirname(path),
path: esPath,
abspath: resolve(path),
exposedContentSize,
mtimeMs: stat.mtime?.getTime() || MIN_TIMESTAMP_MS,
birthtimeMs: stat.birthtime?.getTime() || MIN_TIMESTAMP_MS,
exposedContentHash,
};
fileEntries[esPath] = record;
}
}
const zipped = zipByPath(manifest.entries, fileEntries);
const winners = getTupleWinners(zipped, (entryA, entryB) => {
// This shouldn't happen but let's get it out the way.
if (!entryA && !entryB) {
return entryA as never;
}
// Manifest entry exists but file has disappeared.
if (entryA && !entryB) {
// If the entry is an absence entry, that's still valid.
if (isAbsenceEntry(entryA)) {
return entryA;
}
return {
fileLastSeenMs: entryA.mtimeMs,
path: entryA.path,
};
}
// No manifest entry, but a file present.
if (!entryA && entryB) {
return entryB;
}
// An existing manifest entry AND a file present.
if (entryA && entryB) {
// If entryA is absence entry, B should win.
if (isAbsenceEntry(entryA)) {
return entryB;
}
const latestA = Math.max(
entryA.birthtimeMs || 0,
entryA.mtimeMs || 0,
);
const latestB = Math.max(
entryB.birthtimeMs || 0,
entryB.mtimeMs || 0,
);
// If entry a has been modified more recently, it should win.
// But if the content hasn't changed, we want to preserve the old timestamp.
if (
latestA > latestB ||
entryA.exposedContentHash === entryB.exposedContentHash
) {
return entryA;
}
return entryB;
}
// This should never happen.
return entryA as never;
});
const nextManifest: SyncFsManifest = {
share: forShare,
entries: {},
};
for (const path in winners) {
const entry = winners[path];
// All paths accounted for, none of them should return null.
if (!entry) {
console.error("This shouldn't happen!");
continue;
}
nextManifest.entries[path] = entry;
}
return nextManifest;
}
/*
Outline of how this function works:
1. The contents of the directory are compared with the manifest of that directory, and a new manifest is compiled.
2. The latest docs from the replica are retrieved before any operations are performed.
3. The entries from the manifest
are iterated over, writing contents to the replica
4. The docs retrieved from the replica earlier are iterated over, writing contents to the file system.
*/
/**
* Syncs an earthstar replica with a directory on the filesystem, representing Earthstar documents as files and vice versa. *Make sure you understand the changes this function could enact upon a given directory before using it, as it can delete files in certain circumstances.*
* - Changes from the filesystem which are superseded by writes from the replica will still be synced to the replica as an older version of the document, provided they were authored by different identities.
* - If a file has a path containing a `!` (i.e. an ephemeral path), *it will be deleted unless a correspending document is found in the replica*.
*/
export async function syncReplicaAndFsDir(
opts: SyncFsOptions,
) {
// Check if dir was every synced with a different share, throw if so.
if (await dirBelongsToDifferentShare(opts.dirPath, opts.replica.share)) {
const manifestShare = await getDirAssociatedShare(opts.dirPath);
throw new EarthstarError(
`Tried to sync a replica for ${opts.replica.share} with a directory which had been synced with ${manifestShare}`,
);
}
// Check if dir has files but no manifest
// and abort if a clean dir is required for no manifest.
if (
opts.allowDirtyDirWithoutManifest === false &&
await hasFilesButNoManifest(opts.dirPath)
) {
throw new EarthstarError(
"Tried to sync a directory for the first time, but it was not empty.",
);
}
// First reconcile any existing manifest with the contents of the directory.
const reconciledManifest = await reconcileManifestWithDirContents(
opts.dirPath,
opts.replica.share,
);
const errors = [];
for (const key in reconciledManifest.entries) {
const entry = reconciledManifest.entries[key];
if (!entry) {
continue;
}
if (isAbsenceEntry(entry)) {
const isAttachmentPath = extname(entry.path) !== "";
const result = await FormatEs5.generateDocument({
keypair: opts.keypair,
share: opts.replica.share,
timestamp: entry.fileLastSeenMs * 1000,
input: {
path: entry.path,
text: "",
format: "es.5",
},
config: opts.replica.formatsConfig["es.5"] as ConfigEs5,
});
if (isErr(result)) {
errors.push(result);
} else {
let docToValidate = result.doc;
if (isAttachmentPath) {
docToValidate = await FormatEs5.updateAttachmentFields(
opts.keypair,
result.doc,
0,
"b4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq",
opts.replica.formatsConfig["es.5"] as ConfigEs5,
) as DocEs5;
}
const isValidDoc = await FormatEs5.checkDocumentIsValid(docToValidate);
if (isErr(isValidDoc) && !opts.overwriteFilesAtOwnedPaths) {
errors.push(isValidDoc);
}
}
}
if (isFileInfoEntry(entry)) {
const isAttachmentPath = extname(entry.abspath) !== "";
const sizeIsOkay = isAttachmentPath || entry.exposedContentSize <= 8000;
if (!sizeIsOkay) {
errors.push(
new EarthstarError(
`File too big for the es.5 format's text field: ${entry.path}`,
),
);
}
// New change is valid
const result = await FormatEs5.generateDocument({
keypair: opts.keypair,
share: opts.replica.share,
timestamp: Date.now() * 1000,
input: {
path: entry.path,
text: "fake",
format: "es.5",
},
config: opts.replica.formatsConfig["es.5"] as ConfigEs5,
});
if (isErr(result)) {
errors.push(result);
} else {
let docToValidate = result.doc;
if (isAttachmentPath) {
docToValidate = await FormatEs5.updateAttachmentFields(
opts.keypair,
result.doc,
1,
"bwxkuyopgmzy4s4y3t5dr4wc5qjrm2t2usy7qzeyifwg46m2njr4a",
opts.replica.formatsConfig["es.5"] as ConfigEs5,
) as DocEs5;
}
const isValidDoc = await FormatEs5.checkDocumentIsValid(docToValidate);
if (isErr(isValidDoc)) {
const cantWrite = isValidDoc.message.includes("can't write to path");
if (cantWrite && !opts.overwriteFilesAtOwnedPaths) {
// Check if there's already a doc at this path
const correspondingDoc = await opts.replica.getLatestDocAtPath(
entry.path,
);
if (!correspondingDoc) {
errors.push(isValidDoc);
}
// Only push this error if the corresponding doc's timestamp is older than the fileinfoentry's
// AND if the hash is different.
const hashToCompare = isAttachmentPath
? correspondingDoc?.attachmentHash
: correspondingDoc?.textHash;
if (
correspondingDoc && entry.mtimeMs &&
((entry.mtimeMs * 1000 > correspondingDoc.timestamp) &&
hashToCompare !== entry.exposedContentHash)
) {
errors.push(isValidDoc);
}
} else if (
cantWrite && opts.overwriteFilesAtOwnedPaths === true
) {
delete reconciledManifest.entries[key];
} else {
errors.push(isValidDoc);
}
}
}
}
}
if (errors.length > 0) {
throw errors[0];
}
for (const path in reconciledManifest.entries) {
const entry = reconciledManifest.entries[path];
if (entry.path.indexOf("!") !== -1 && isFileInfoEntry(entry)) {
const correspondingEphemeralDoc = await opts.replica.getLatestDocAtPath(
path,
);
if (
!correspondingEphemeralDoc ||
(correspondingEphemeralDoc && correspondingEphemeralDoc.deleteAfter &&
Date.now() * 1000 > correspondingEphemeralDoc.deleteAfter)
) {
await Deno.remove(entry.abspath);
await removeEmptyDir(entry.dirName, opts.dirPath);
continue;
}
}
await writeEntryToReplica(
entry,
opts.replica,
opts.keypair,
opts.dirPath,
);
}
const latestDocs = await opts.replica.getLatestDocs();
for (const doc of latestDocs) {
// Make sure not to re-write any ephemeral docs to the filesystem.
if (doc.deleteAfter && Date.now() * 1000 > doc.deleteAfter) {
return;
}
try {
const newEntry = await writeDocToDir(doc, opts.replica, opts.dirPath);
reconciledManifest.entries[newEntry.path] = newEntry;
} catch (err) {
// Maybe we log something here...
}
}
// Wipe any empty dirs
try {
for await (const entry of walk(opts.dirPath)) {
if (entry.isDirectory) {
await removeEmptyDir(entry.path, opts.dirPath);
}
}
} catch {
// Not sure why this fails sometimes...
}
await writeManifest(reconciledManifest, opts.dirPath);
}