@wirecat/cli-core 0.710.0 → 0.712.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/background/deliver.d.ts +11 -4
  3. package/dist/background/deliver.js +47 -19
  4. package/dist/background/report/render.d.ts +10 -4
  5. package/dist/background/report/render.js +96 -8
  6. package/dist/background/report/templates/morning-digest.telegram.en.liquid +2 -2
  7. package/dist/background/report/templates/morning-digest.telegram.ru.liquid +2 -2
  8. package/dist/background/report/view.d.ts +4 -0
  9. package/dist/background/report/view.js +12 -8
  10. package/dist/background/schedules.js +4 -2
  11. package/dist/cli/effects.d.ts +1 -1
  12. package/dist/cli/effects.js +6 -1
  13. package/dist/crm/digest.js +3 -2
  14. package/dist/documents/file-mirror-model.d.ts +9 -1
  15. package/dist/documents/index.d.ts +2 -1
  16. package/dist/documents/index.js +2 -1
  17. package/dist/errors/reasons.js +7 -0
  18. package/dist/http/listen.js +3 -3
  19. package/dist/mount/index.d.ts +3 -0
  20. package/dist/mount/index.js +2 -0
  21. package/dist/mount/serve.d.ts +28 -0
  22. package/dist/mount/serve.js +31 -0
  23. package/dist/mount/source.d.ts +31 -0
  24. package/dist/mount/source.js +1 -0
  25. package/dist/mount/webdav.d.ts +18 -0
  26. package/dist/mount/webdav.js +241 -0
  27. package/dist/ports/wirecat-tools.js +7 -0
  28. package/dist/services/documents/mirrors.d.ts +2 -0
  29. package/dist/services/documents/push.d.ts +1 -1
  30. package/dist/services/documents/push.js +3 -1
  31. package/dist/services/files/exclusions.d.ts +8 -0
  32. package/dist/services/files/exclusions.js +39 -0
  33. package/dist/services/files/mirror.d.ts +43 -7
  34. package/dist/services/files/mirror.js +176 -31
  35. package/dist/services/files/versions.d.ts +2 -0
  36. package/dist/services/files/versions.js +1 -0
  37. package/package.json +5 -1
@@ -1,18 +1,30 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdir, rm, stat, unlink } from "node:fs/promises";
2
+ import { mkdir, rm, stat, statfs, unlink } from "node:fs/promises";
3
3
  import { dirname, join, posix } from "node:path";
4
4
  import { CliError, isCliError } from "@wirecat/cli-base";
5
5
  import * as v from "valibot";
6
6
  import { eachMirror, heldCheck, jsonState } from "../documents/mirrors.js";
7
7
  import { assertNoLink, hashFile, localTemp, placeNew, replaceLocal, safePath, scanLocal, skippedName, } from "../documents/push.js";
8
- const HINTS = { preview: "--dry-run", repin: "--repin", allowDeletions: "explicitly" };
8
+ import { excludedBy } from "./exclusions.js";
9
+ const HINTS = {
10
+ preview: "--dry-run",
11
+ repin: "--repin",
12
+ sync: "sync",
13
+ allowDeletions: "--allow-deletions <count>",
14
+ allowReplacements: "--allow-replacements <count>",
15
+ exclude: "--exclude <glob>",
16
+ };
9
17
  /**
10
- * A run that would delete more than `ALWAYS_DELETED` files and more than `MAX_DELETIONS` files or `MAX_DELETED_SHARE`
11
- * of the mirror stops before writing.
18
+ * A run that would delete more than `MAX_DELETIONS` files, or replace more than `MAX_REPLACEMENTS` existing files on
19
+ * either side, stops before writing until the owner allows the count. Replacements get the higher bar: every content
20
+ * one replaces is kept in the version store first, and bulk edits (a find-and-replace, a branch switch) are common.
12
21
  */
13
- const ALWAYS_DELETED = 2;
14
- const MAX_DELETIONS = 50;
15
- const MAX_DELETED_SHARE = 0.25;
22
+ export const MAX_DELETIONS = 10;
23
+ export const MAX_REPLACEMENTS = 50;
24
+ /** What a run leaves free on a drive it writes to: a tenth of what it writes, from 100 MB up to 1 GB. */
25
+ const spareFor = (needed) => Math.min(1024 ** 3, Math.max(100 * 1024 ** 2, needed / 10));
26
+ const MAX_FILES = 100_000;
27
+ const CHECKS = 8;
16
28
  const TRASH = ".wirecat-trash";
17
29
  const SAVE_EVERY_MS = 1_000;
18
30
  /** A temporary file's tag from any operation id, safe in a file name. */
@@ -119,12 +131,12 @@ const renameLocal = async (root, from, to, hash) => {
119
131
  await unlink(source);
120
132
  return true;
121
133
  };
122
- /** Every local file, hashed only when its size or mtime moved since the last sync. */
123
- const scan = async (root, entries, maxFiles) => {
134
+ /** Every local file but excluded ones, hashed only when its size or mtime moved since the last sync. */
135
+ const scan = async (root, entries, excluded, maxFiles = MAX_FILES) => {
124
136
  const { files, links } = await scanLocal(root, () => "file", maxFiles, (path) => {
125
137
  const entry = entries[path];
126
138
  return entry && { size: entry.localSize, mtimeMs: entry.localMtimeMs, hash: entry.sha256 };
127
- });
139
+ }, excluded);
128
140
  return { files: files, links };
129
141
  };
130
142
  /** Remote files the mirror covers: hidden files and editor leftovers are skipped, as they are locally. */
@@ -146,6 +158,20 @@ const whole = async (absolute, hashes) => {
146
158
  };
147
159
  /** True when `path` is `link` or lies under it. */
148
160
  const under = (path, link) => path === link || path.startsWith(`${link}/`);
161
+ /** Free bytes and the device of the file system holding `path`, or of its nearest folder that exists. */
162
+ const freeSpace = async (path) => {
163
+ for (let at = path;; at = dirname(at)) {
164
+ try {
165
+ const [{ bavail, bsize }, { dev }] = await Promise.all([statfs(at), stat(at)]);
166
+ return { free: bavail * bsize, dev };
167
+ }
168
+ catch (error) {
169
+ if (error.code !== "ENOENT" || dirname(at) === at)
170
+ throw error;
171
+ }
172
+ }
173
+ };
174
+ const gigabytes = (bytes) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
149
175
  /**
150
176
  * Syncs a local folder and a remote folder of plain files both ways, whole files at a time. Each path is compared
151
177
  * three ways (local now, remote now, last sync): a change on one side is copied to the other, the same content on
@@ -156,6 +182,8 @@ const under = (path, link) => path === link || path.startsWith(`${link}/`);
156
182
  export const syncFileMirror = async (options) => {
157
183
  const { root, folder, target, principal, keep, signal, versions } = options;
158
184
  const hints = { ...HINTS, ...options.hints };
185
+ const fill = (hint, count) => hint.replaceAll("<id>", options.id ?? "<id>").replaceAll("<count>", count === undefined ? "<count>" : `${count}`);
186
+ const excluded = excludedBy(options.exclude);
159
187
  const now = options.now ?? Date.now;
160
188
  if (signal?.aborted)
161
189
  throw new CliError("cancelled", "sync was cancelled");
@@ -166,7 +194,7 @@ export const syncFileMirror = async (options) => {
166
194
  const state = options.state.read();
167
195
  if (state.principal !== principal || state.root !== root || state.target !== folder)
168
196
  throw new CliError("configuration_error", "mirror state belongs to another account or mirror");
169
- const listed = await target.list(folder, signal);
197
+ const listed = await target.list(folder, signal, { excluded });
170
198
  const localRoot = await stat(root).catch(() => undefined);
171
199
  const remoteReplaced = listed !== undefined && state.rootId !== undefined && listed.rootId !== state.rootId;
172
200
  const localReplaced = localRoot?.isDirectory() === true &&
@@ -174,9 +202,13 @@ export const syncFileMirror = async (options) => {
174
202
  (state.localRoot.dev !== localRoot.dev || state.localRoot.ino !== localRoot.ino);
175
203
  // Only a mirror whose root really was replaced is re-pinned; `repin` on a sync of every mirror leaves the others be.
176
204
  const repin = options.repin === true && (remoteReplaced || localReplaced);
205
+ // An excluded path is absent by filter, never deleted: the last sync's entries under it are left out.
206
+ const synced = Object.fromEntries(Object.entries(state.entries).filter(([path]) => !excluded(path)));
177
207
  // A re-pinned mirror starts over: the last sync's entries describe the folder it replaced.
178
- const entries = repin ? {} : state.entries;
179
- const scanned = localRoot?.isDirectory() ? await scan(root, entries, options.maxFiles) : { files: [], links: [] };
208
+ const entries = repin ? {} : synced;
209
+ const scanned = localRoot?.isDirectory()
210
+ ? await scan(root, entries, excluded, options.maxFiles)
211
+ : { files: [], links: [] };
180
212
  const local = new Map(scanned.files.map((file) => [file.path, file]));
181
213
  const problem = (side, code, reason, repinnable = false) => ({ side, code, reason, repinnable });
182
214
  // A folder that is gone, replaced, or empty where the state had files (an unmounted drive) is not this mirror.
@@ -188,22 +220,23 @@ export const syncFileMirror = async (options) => {
188
220
  ? problem("local", "not_found", "the local folder is gone")
189
221
  : localReplaced && !repin
190
222
  ? problem("local", "confirmation_required", "the local folder was replaced by another one", true)
191
- : Object.keys(state.entries).length > 0 && !local.size
223
+ : Object.keys(synced).length > 0 && !local.size
192
224
  ? problem("local", "validation_error", "the local folder is empty; it may be an unmounted drive. Mount it, or if the files were really " +
193
225
  "deleted, add a file to the folder or remove the mirror's state to start over")
194
226
  : undefined;
195
227
  const refused = rootProblem ? [] : (listed?.files ?? []).filter((file) => !safePath(file.path));
196
228
  const refusedIds = new Set(refused.map((file) => file.id));
197
- const remote = new Map(rootProblem
198
- ? []
199
- : mirrored((listed?.files ?? []).filter((file) => safePath(file.path))).map((file) => [file.path, file]));
229
+ const visible = rootProblem ? [] : mirrored((listed?.files ?? []).filter((file) => safePath(file.path)));
230
+ const remote = new Map(visible.filter((file) => !excluded(file.path)).map((file) => [file.path, file]));
231
+ // Where a synced file went when it moved into an excluded folder on the remote.
232
+ const excludedIds = new Set(visible.filter((file) => excluded(file.path)).map((file) => file.id));
200
233
  const sure = {
201
234
  local: rootProblem?.side !== "local",
202
235
  remote: rootProblem?.side !== "remote" && listed?.complete === true,
203
236
  };
204
237
  const base = { ...entries };
205
238
  const steps = [];
206
- const byId = new Map([...remote.values()].map((file) => [file.id, file]));
239
+ const byId = new Map(visible.map((file) => [file.id, file]));
207
240
  for (const [path, entry] of Object.entries(entries)) {
208
241
  const moved = remote.has(path) ? undefined : byId.get(entry.id);
209
242
  const file = local.get(path);
@@ -231,12 +264,12 @@ export const syncFileMirror = async (options) => {
231
264
  };
232
265
  if (rootProblem) {
233
266
  const { side, code, reason, repinnable } = rootProblem;
234
- result.unknown = Object.keys(state.entries).map((path) => ({ path, side, reason }));
267
+ result.unknown = Object.keys(synced).map((path) => ({ path, side, reason }));
235
268
  result.errors.push({
236
269
  path: ".",
237
270
  code,
238
271
  message: repinnable
239
- ? `${reason}; if it is the right folder now, sync again with ${hints.repin} to record it ` +
272
+ ? `${reason}; if it is the right folder now, sync again with ${fill(hints.repin)} to record it ` +
240
273
  "(that run deletes nothing)"
241
274
  : reason,
242
275
  });
@@ -250,6 +283,9 @@ export const syncFileMirror = async (options) => {
250
283
  });
251
284
  const cutOff = new Set();
252
285
  for (const path of paths) {
286
+ // A synced file moved into an excluded folder is renamed there above, and then left alone.
287
+ if (excluded(path))
288
+ continue;
253
289
  const entry = base[path];
254
290
  if (entry && !local.has(path) && scanned.links.some((link) => under(path, link))) {
255
291
  steps.push({
@@ -264,6 +300,15 @@ export const syncFileMirror = async (options) => {
264
300
  steps.push({ kind: "unknown", path, reason: "remote", why: `moved on the ${options.remote} to a refused path` });
265
301
  continue;
266
302
  }
303
+ if (entry && !remote.has(path) && excludedIds.has(entry.id)) {
304
+ steps.push({
305
+ kind: "unknown",
306
+ path,
307
+ reason: "remote",
308
+ why: `moved on the ${options.remote} into an excluded folder`,
309
+ });
310
+ continue;
311
+ }
267
312
  const file = remote.get(path);
268
313
  if (file && file.sha256 === undefined) {
269
314
  result.errors.push({ path, code: "provider_error", message: `the ${options.remote} has no hash for it yet` });
@@ -297,6 +342,20 @@ export const syncFileMirror = async (options) => {
297
342
  touched.push(path);
298
343
  }
299
344
  result.unchanged = unchanged;
345
+ const remotePath = (path) => posix.join(folder, path);
346
+ // A listing read in pages can miss a file that moved while it was read, and a provider's flat listing may lag: a
347
+ // file missing from it is deleted locally only once a direct read, made after the listing, finds nothing there.
348
+ const absent = steps.filter((step) => step.kind === "trash-local");
349
+ for (let at = 0; at < absent.length; at += CHECKS)
350
+ await Promise.all(absent.slice(at, at + CHECKS).map(async (step) => {
351
+ const why = await target.exists(remotePath(step.path), signal).then((there) => (there ? `missing from the ${options.remote} listing, but still there` : undefined), (error) => {
352
+ if (signal?.aborted)
353
+ throw error;
354
+ return `the ${options.remote} could not say whether it was deleted: ${options.errorOf(error).message}`;
355
+ });
356
+ if (why)
357
+ Object.assign(step, { kind: "unknown", reason: "remote", why });
358
+ }));
300
359
  const conflict = (step, reason) => result.conflicts.push({
301
360
  path: step.path,
302
361
  reason,
@@ -314,17 +373,60 @@ export const syncFileMirror = async (options) => {
314
373
  });
315
374
  }
316
375
  const deletions = steps.filter((step) => step.kind === "trash-local" || step.kind === "trash-remote").length;
317
- const tooMany = deletions > ALWAYS_DELETED &&
318
- (deletions > MAX_DELETIONS || deletions > Object.keys(state.entries).length * MAX_DELETED_SHARE);
376
+ const replacements = steps.filter((step) => (step.kind === "upload" && step.remote) || (step.kind === "download" && step.local) || step.kind === "keep-both").length;
377
+ const over = [
378
+ ...(deletions > MAX_DELETIONS
379
+ ? [
380
+ {
381
+ reason: "mirror.too-many-deletions",
382
+ what: `delete ${deletions} files (more than ${MAX_DELETIONS})`,
383
+ flag: fill(hints.allowDeletions, deletions),
384
+ allowed: (options.allowDeletions ?? 0) >= deletions,
385
+ },
386
+ ]
387
+ : []),
388
+ ...(replacements > MAX_REPLACEMENTS
389
+ ? [
390
+ {
391
+ reason: "mirror.too-many-replacements",
392
+ what: `replace ${replacements} existing files (more than ${MAX_REPLACEMENTS})`,
393
+ flag: fill(hints.allowReplacements, replacements),
394
+ allowed: (options.allowReplacements ?? 0) >= replacements,
395
+ },
396
+ ]
397
+ : []),
398
+ ];
399
+ if (deletions > MAX_DELETIONS)
400
+ result.tooManyDeletions = deletions;
401
+ if (replacements > MAX_REPLACEMENTS)
402
+ result.tooManyReplacements = replacements;
403
+ const noSpace = await shortOfSpace(steps, root, versions, options.space ?? freeSpace);
404
+ if (noSpace)
405
+ result.noSpace = noSpace;
319
406
  if (options.dryRun) {
320
407
  result.plan = steps.map(({ kind, path, to }) => ({ kind, path, ...(to ? { to } : {}) }));
321
- if (tooMany)
322
- result.tooManyDeletions = deletions;
323
408
  return result;
324
409
  }
325
- if (tooMany && (options.allowDeletions ?? 0) < deletions)
326
- throw new CliError("confirmation_required", `this sync would delete ${deletions} files; ` +
327
- `check them with ${hints.preview} and allow them ${hints.allowDeletions}`, { reason: "mirror.too-many-deletions", deletions });
410
+ const unapproved = over.find((one) => !one.allowed);
411
+ if (unapproved)
412
+ result.errors.push({
413
+ path: ".",
414
+ code: "confirmation_required",
415
+ reason: unapproved.reason,
416
+ message: `this sync would ${over.map((one) => one.what).join(" and ")}; check them with \`${fill(hints.preview)}\`, ` +
417
+ `then allow them with \`${fill(hints.sync)} ${over.map((one) => one.flag).join(" ")}\``,
418
+ });
419
+ if (noSpace)
420
+ result.errors.push({
421
+ path: ".",
422
+ code: "validation_error",
423
+ reason: "mirror.no-space",
424
+ message: `this sync needs ${gigabytes(noSpace.needed)} on the drive of ${noSpace.path}, which has ` +
425
+ `${gigabytes(noSpace.free)} free, and leaves ${gigabytes(spareFor(noSpace.needed))} of it free; free some space, or ` +
426
+ `leave big folders out with \`${fill(hints.exclude)}\``,
427
+ });
428
+ if (unapproved || noSpace)
429
+ return result;
328
430
  if (repin) {
329
431
  state.entries = {};
330
432
  state.rootId = listed?.rootId;
@@ -344,8 +446,10 @@ export const syncFileMirror = async (options) => {
344
446
  delete state.pending[path];
345
447
  }
346
448
  let savedAt = now();
449
+ // A big mirror's state is megabytes of JSON: saved less often, it costs no more than a small one's.
450
+ const saveEvery = SAVE_EVERY_MS * Math.max(1, Object.keys(state.entries).length / 10_000);
347
451
  const save = (force = false) => {
348
- if (!force && now() - savedAt < SAVE_EVERY_MS)
452
+ if (!force && now() - savedAt < saveEvery)
349
453
  return;
350
454
  options.state.save(state);
351
455
  savedAt = now();
@@ -358,7 +462,6 @@ export const syncFileMirror = async (options) => {
358
462
  }
359
463
  save(true);
360
464
  const date = new Date(now()).toISOString().slice(0, 10);
361
- const remotePath = (path) => posix.join(folder, path);
362
465
  const folders = new Set([...remote.keys()].map((path) => posix.dirname(path)));
363
466
  for (const path of [...folders])
364
467
  for (let up = path; up !== "."; up = posix.dirname(up))
@@ -574,12 +677,51 @@ export const syncFileMirror = async (options) => {
574
677
  }
575
678
  }
576
679
  finally {
680
+ // Forgotten, so a file whose exclusion is removed later is a new file, never a deletion.
681
+ for (const path of Object.keys(state.entries))
682
+ if (excluded(path))
683
+ delete state.entries[path];
577
684
  save(true);
578
685
  }
579
686
  await options.assertHeld();
580
687
  await versions.prune();
581
688
  return result;
582
689
  };
690
+ /**
691
+ * The free space a run needs that a file system lacks: downloads land under `root`, and the store keeps every
692
+ * content they replace or a deletion removes, plus each remote content an upload replaces that it lacks.
693
+ */
694
+ const shortOfSpace = async (steps, root, versions, space) => {
695
+ let incoming = 0;
696
+ let kept = 0;
697
+ for (const step of steps) {
698
+ const local = step.local?.size ?? 0;
699
+ const remote = step.remote?.size ?? 0;
700
+ if (step.kind === "download") {
701
+ incoming += remote;
702
+ kept += local;
703
+ }
704
+ if (step.kind === "keep-both") {
705
+ incoming += remote;
706
+ kept += remote;
707
+ }
708
+ if (step.kind === "trash-local")
709
+ kept += local;
710
+ if (step.kind === "upload" && step.remote && !versions.has(step.remote.sha256))
711
+ kept += remote;
712
+ }
713
+ if (!incoming && !kept)
714
+ return undefined;
715
+ const here = await space(root);
716
+ const store = versions.dir === undefined ? here : await space(versions.dir);
717
+ const needs = store.dev === here.dev
718
+ ? [{ path: root, needed: incoming + kept, free: here.free }]
719
+ : [
720
+ { path: root, needed: incoming, free: here.free },
721
+ { path: versions.dir, needed: kept, free: store.free },
722
+ ];
723
+ return needs.find((need) => need.needed > 0 && need.free < need.needed + spareFor(need.needed));
724
+ };
583
725
  const ancestors = (path) => {
584
726
  const found = [];
585
727
  for (let up = posix.dirname(path); up !== "."; up = posix.dirname(up))
@@ -619,8 +761,9 @@ export const fileSyncState = (dir, mirror, principal) => jsonState(join(dir, `${
619
761
  export const fileMirrorStatus = async (mirrors, stateOf) => {
620
762
  const items = [];
621
763
  for (const mirror of mirrors) {
622
- const { entries } = stateOf(mirror).read();
623
- const { files, links } = await scan(mirror.path, entries);
764
+ const excluded = excludedBy(mirror.exclude);
765
+ const entries = Object.fromEntries(Object.entries(stateOf(mirror).read().entries).filter(([path]) => !excluded(path)));
766
+ const { files, links } = await scan(mirror.path, entries, excluded);
624
767
  const seen = new Set(files.map((file) => file.path));
625
768
  items.push({
626
769
  id: mirror.id,
@@ -654,6 +797,8 @@ export const syncFileMirrors = (options) => eachMirror(options.mirrors, options.
654
797
  ...options,
655
798
  root: mirror.path,
656
799
  folder: mirror.folder,
800
+ id: mirror.id,
801
+ ...(mirror.exclude ? { exclude: mirror.exclude } : {}),
657
802
  state: options.stateOf(mirror),
658
803
  versions: options.versionsOf(mirror),
659
804
  assertHeld: heldCheck(held),
@@ -23,6 +23,8 @@ export interface FileVersion extends VersionEvent {
23
23
  available: boolean;
24
24
  }
25
25
  export interface FileVersions {
26
+ /** The folder the store keeps its copies in, when it is on disk: a sync checks its free space first. */
27
+ readonly dir?: string;
26
28
  /**
27
29
  * Copies a content into the store before the sync overwrites or deletes it; returns the hash of what it copied. The
28
30
  * source is a local file, or a writer that creates the temporary file it is given, such as a target's `download`.
@@ -61,6 +61,7 @@ export const fileVersions = (dir, now = Date.now) => {
61
61
  };
62
62
  const has = (sha256) => existsSync(join(objects, sha256));
63
63
  return {
64
+ dir,
64
65
  keep: async (source) => {
65
66
  await stored(() => mkdir(objects, { recursive: true, mode: 0o700 }));
66
67
  const temp = join(objects, `.${randomUUID()}.tmp`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.710.0",
3
+ "version": "0.712.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -215,6 +215,10 @@
215
215
  "types": "./dist/sftp/index.d.ts",
216
216
  "default": "./dist/sftp/index.js"
217
217
  },
218
+ "./mount": {
219
+ "types": "./dist/mount/index.d.ts",
220
+ "default": "./dist/mount/index.js"
221
+ },
218
222
  "./sql": {
219
223
  "types": "./dist/sql/index.d.ts",
220
224
  "default": "./dist/sql/index.js"