tandem-kit-core 0.0.0 → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +7 -1
- package/dist/src/browser.d.ts +19 -0
- package/dist/src/browser.js +19 -0
- package/dist/src/client-tools.d.ts +31 -0
- package/dist/src/client-tools.js +82 -0
- package/dist/src/client.d.ts +179 -0
- package/dist/src/client.js +213 -0
- package/dist/src/delta.d.ts +16 -0
- package/dist/src/delta.js +99 -0
- package/dist/src/durable.d.ts +39 -0
- package/dist/src/durable.js +104 -0
- package/dist/src/errors.d.ts +5 -0
- package/dist/src/errors.js +10 -0
- package/dist/src/eventlog-file.d.ts +12 -0
- package/dist/src/eventlog-file.js +39 -0
- package/dist/src/eventlog.d.ts +31 -0
- package/dist/src/eventlog.js +63 -0
- package/dist/src/events.d.ts +15 -0
- package/dist/src/events.js +79 -0
- package/dist/src/events.json +80 -0
- package/dist/src/files.d.ts +34 -0
- package/dist/src/files.js +122 -0
- package/dist/src/fsutil.d.ts +8 -0
- package/dist/src/fsutil.js +68 -0
- package/dist/src/hash.d.ts +3 -0
- package/dist/src/hash.js +65 -0
- package/dist/src/images.d.ts +24 -0
- package/dist/src/images.js +70 -0
- package/dist/src/index.d.ts +25 -0
- package/dist/src/index.js +25 -0
- package/dist/src/json.d.ts +10 -0
- package/dist/src/json.js +68 -0
- package/dist/src/merge.d.ts +34 -0
- package/dist/src/merge.js +111 -0
- package/dist/src/persist.d.ts +49 -0
- package/dist/src/persist.js +29 -0
- package/dist/src/proposals-file.d.ts +12 -0
- package/dist/src/proposals-file.js +36 -0
- package/dist/src/proposals.d.ts +149 -0
- package/dist/src/proposals.js +296 -0
- package/dist/src/reconcile.d.ts +63 -0
- package/dist/src/reconcile.js +61 -0
- package/dist/src/replica.d.ts +147 -0
- package/dist/src/replica.js +320 -0
- package/dist/src/revisions-file.d.ts +14 -0
- package/dist/src/revisions-file.js +28 -0
- package/dist/src/revisions.d.ts +78 -0
- package/dist/src/revisions.js +152 -0
- package/dist/src/revisions.json +19 -0
- package/dist/src/schema.d.ts +12 -0
- package/dist/src/schema.js +49 -0
- package/dist/src/session-state.d.ts +36 -0
- package/dist/src/session-state.js +95 -0
- package/dist/src/sse.d.ts +17 -0
- package/dist/src/sse.js +59 -0
- package/dist/src/workcopy.d.ts +145 -0
- package/dist/src/workcopy.js +556 -0
- package/package.json +34 -4
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { canonicalJson, sha256Hex } from "./hash.js";
|
|
2
|
+
import { merge3 } from "./merge.js";
|
|
3
|
+
export const defaultPrint = (state) => canonicalJson(state);
|
|
4
|
+
export function reconcileStates(input) {
|
|
5
|
+
const print = input.print ?? defaultPrint;
|
|
6
|
+
const wins = input.wins ?? ((actor) => actor === 'human');
|
|
7
|
+
const same = (a, b) => a === b || print(a) === print(b);
|
|
8
|
+
const { client, server } = input;
|
|
9
|
+
const done = (step, state, extra = {}) => ({ step, state, clashes: [], ...extra });
|
|
10
|
+
if (client.state === undefined)
|
|
11
|
+
return done('pull', server.state);
|
|
12
|
+
if (same(client.state, server.state))
|
|
13
|
+
return done('synced', server.state);
|
|
14
|
+
if (input.base === undefined) {
|
|
15
|
+
if (server.pristine && !client.pristine)
|
|
16
|
+
return done('push', client.state);
|
|
17
|
+
if (client.pristine && !server.pristine)
|
|
18
|
+
return done('pull', server.state);
|
|
19
|
+
const first = input.first ?? 'compare';
|
|
20
|
+
if (first === 'client')
|
|
21
|
+
return done('push', client.state);
|
|
22
|
+
if (first === 'server')
|
|
23
|
+
return done('pull', server.state);
|
|
24
|
+
return done('compare', server.state);
|
|
25
|
+
}
|
|
26
|
+
const clientEdited = !same(client.state, input.base);
|
|
27
|
+
const serverEdited = !same(server.state, input.base);
|
|
28
|
+
if (!clientEdited && !serverEdited)
|
|
29
|
+
return done('synced', server.state);
|
|
30
|
+
if (clientEdited && !serverEdited)
|
|
31
|
+
return done('push', client.state);
|
|
32
|
+
if (!clientEdited && serverEdited)
|
|
33
|
+
return done('pull', server.state);
|
|
34
|
+
const clientHuman = client.actors.some(wins);
|
|
35
|
+
const serverHuman = server.actors.some(wins);
|
|
36
|
+
const winner = clientHuman && !serverHuman ? 'client' : serverHuman && !clientHuman ? 'server' : (input.tie ?? 'server');
|
|
37
|
+
const mine = winner === 'client' ? client.state : server.state;
|
|
38
|
+
const theirs = winner === 'client' ? server.state : client.state;
|
|
39
|
+
const merged = input.merge ? input.merge(input.base, mine, theirs, { writerWins: winner === 'client' }) : merge3(input.base, mine, theirs, { keyed: input.keyed });
|
|
40
|
+
return done('merge', merged.merged, { winner, clashes: merged.clashes });
|
|
41
|
+
}
|
|
42
|
+
export function contentClashId(path, kept, dropped) {
|
|
43
|
+
const identity = { path, kept: kept ?? null, dropped: dropped ?? null };
|
|
44
|
+
return `x${sha256Hex(canonicalJson(identity)).slice(0, 12)}`;
|
|
45
|
+
}
|
|
46
|
+
export function clashIdOf(clash) {
|
|
47
|
+
return contentClashId(clash.path, clash.mine, clash.theirs);
|
|
48
|
+
}
|
|
49
|
+
export function syncClashRecord(clash, keptActor, droppedActor) {
|
|
50
|
+
return {
|
|
51
|
+
id: clashIdOf(clash),
|
|
52
|
+
path: clash.path,
|
|
53
|
+
kept: clash.mine === undefined ? null : clash.mine,
|
|
54
|
+
dropped: clash.theirs === undefined ? null : clash.theirs,
|
|
55
|
+
kept_actor: keptActor,
|
|
56
|
+
dropped_actor: droppedActor,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
export function primaryActor(actors, wins, fallback) {
|
|
60
|
+
return actors.find(wins) ?? actors[0] ?? fallback;
|
|
61
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { type Json } from './json.js';
|
|
2
|
+
import { type SyncRequest, type SyncResponse, type SyncStep } from './reconcile.js';
|
|
3
|
+
import type { TandemClient } from './client.js';
|
|
4
|
+
import type { Finding } from './revisions.js';
|
|
5
|
+
import type { ClashRecord, Workcopy } from './workcopy.js';
|
|
6
|
+
export interface Link {
|
|
7
|
+
base: Json;
|
|
8
|
+
mark: Json;
|
|
9
|
+
peer_mark?: number;
|
|
10
|
+
synced_at: string;
|
|
11
|
+
}
|
|
12
|
+
export interface LinkStore {
|
|
13
|
+
load(): Link | null;
|
|
14
|
+
save(link: Link): void;
|
|
15
|
+
}
|
|
16
|
+
export declare class MemoryLinkStore implements LinkStore {
|
|
17
|
+
private link;
|
|
18
|
+
load(): Link | null;
|
|
19
|
+
save(link: Link): void;
|
|
20
|
+
}
|
|
21
|
+
export interface ReplicaTransport {
|
|
22
|
+
sync(request: SyncRequest): Promise<SyncResponse>;
|
|
23
|
+
watch?(notify: () => void): () => void;
|
|
24
|
+
}
|
|
25
|
+
export declare class MemoryTransport implements ReplicaTransport {
|
|
26
|
+
private readonly peer;
|
|
27
|
+
constructor(peer: Workcopy);
|
|
28
|
+
sync(request: SyncRequest): Promise<SyncResponse>;
|
|
29
|
+
watch(notify: () => void): () => void;
|
|
30
|
+
}
|
|
31
|
+
export interface HttpTransportOptions {
|
|
32
|
+
client: TandemClient;
|
|
33
|
+
doc: string;
|
|
34
|
+
retryMs?: number;
|
|
35
|
+
}
|
|
36
|
+
export declare class HttpTransport implements ReplicaTransport {
|
|
37
|
+
private readonly client;
|
|
38
|
+
private readonly doc;
|
|
39
|
+
private readonly retryMs;
|
|
40
|
+
constructor(options: HttpTransportOptions);
|
|
41
|
+
sync(request: SyncRequest): Promise<SyncResponse>;
|
|
42
|
+
watch(notify: () => void): () => void;
|
|
43
|
+
}
|
|
44
|
+
export interface SideSnapshot {
|
|
45
|
+
state?: Json;
|
|
46
|
+
actors: string[];
|
|
47
|
+
pristine: boolean;
|
|
48
|
+
clashes: ClashRecord[];
|
|
49
|
+
closed: string[];
|
|
50
|
+
token: Json;
|
|
51
|
+
}
|
|
52
|
+
export interface AdoptInput {
|
|
53
|
+
snapshot: SideSnapshot;
|
|
54
|
+
state: Json;
|
|
55
|
+
actors: string[];
|
|
56
|
+
clashes: ClashRecord[];
|
|
57
|
+
closed: string[];
|
|
58
|
+
site: string;
|
|
59
|
+
}
|
|
60
|
+
export interface AdoptResult {
|
|
61
|
+
mark: Json;
|
|
62
|
+
changed: boolean;
|
|
63
|
+
findings?: Finding[];
|
|
64
|
+
}
|
|
65
|
+
export interface ReplicaSide {
|
|
66
|
+
snapshot(mark: Json | undefined, site: string): SideSnapshot | Promise<SideSnapshot>;
|
|
67
|
+
adopt(input: AdoptInput): AdoptResult | Promise<AdoptResult>;
|
|
68
|
+
subscribe?(notify: () => void): () => void;
|
|
69
|
+
acceptsClashes?: boolean;
|
|
70
|
+
}
|
|
71
|
+
export declare class ConcurrentEdit extends Error {
|
|
72
|
+
constructor(message?: string);
|
|
73
|
+
}
|
|
74
|
+
export declare class InvalidCopy extends Error {
|
|
75
|
+
readonly problems: {
|
|
76
|
+
path?: string;
|
|
77
|
+
message: string;
|
|
78
|
+
}[];
|
|
79
|
+
constructor(problems: {
|
|
80
|
+
path?: string;
|
|
81
|
+
message: string;
|
|
82
|
+
}[]);
|
|
83
|
+
}
|
|
84
|
+
export interface WorkcopySideOptions {
|
|
85
|
+
wins?: (actor: string) => boolean;
|
|
86
|
+
}
|
|
87
|
+
export declare function workcopySide(workcopy: Workcopy, options?: WorkcopySideOptions): ReplicaSide;
|
|
88
|
+
export type ReplicaStatus = 'idle' | 'syncing' | 'offline' | 'error';
|
|
89
|
+
export interface SyncOutcome {
|
|
90
|
+
step: SyncStep | 'offline' | 'error' | 'invalid';
|
|
91
|
+
changed_local: boolean;
|
|
92
|
+
changed_remote: boolean;
|
|
93
|
+
opened: ClashRecord[];
|
|
94
|
+
findings: Finding[];
|
|
95
|
+
error?: string;
|
|
96
|
+
local?: Json;
|
|
97
|
+
remote?: Json;
|
|
98
|
+
}
|
|
99
|
+
export interface ReplicaOptions {
|
|
100
|
+
side: ReplicaSide;
|
|
101
|
+
transport: ReplicaTransport;
|
|
102
|
+
links?: LinkStore;
|
|
103
|
+
site?: string;
|
|
104
|
+
tie?: 'local' | 'remote';
|
|
105
|
+
first?: 'compare' | 'local' | 'remote';
|
|
106
|
+
debounceMs?: number;
|
|
107
|
+
pollMs?: number;
|
|
108
|
+
retryMs?: {
|
|
109
|
+
min: number;
|
|
110
|
+
max: number;
|
|
111
|
+
};
|
|
112
|
+
onStatus?: (status: ReplicaStatus, outcome?: SyncOutcome) => void;
|
|
113
|
+
clock?: () => string;
|
|
114
|
+
}
|
|
115
|
+
export declare class Replica {
|
|
116
|
+
readonly site: string;
|
|
117
|
+
private readonly options;
|
|
118
|
+
private readonly links;
|
|
119
|
+
private readonly retry;
|
|
120
|
+
private running;
|
|
121
|
+
private queued;
|
|
122
|
+
private unsubscribe;
|
|
123
|
+
private debounce;
|
|
124
|
+
private poll;
|
|
125
|
+
private retryTimer;
|
|
126
|
+
private failures;
|
|
127
|
+
private current;
|
|
128
|
+
private started;
|
|
129
|
+
private last;
|
|
130
|
+
constructor(options: ReplicaOptions);
|
|
131
|
+
get status(): ReplicaStatus;
|
|
132
|
+
get lastOutcome(): SyncOutcome | undefined;
|
|
133
|
+
get linked(): boolean;
|
|
134
|
+
sync(options?: {
|
|
135
|
+
first?: 'compare' | 'local' | 'remote';
|
|
136
|
+
}): Promise<SyncOutcome>;
|
|
137
|
+
start(): void;
|
|
138
|
+
stop(): Promise<void>;
|
|
139
|
+
changed(): void;
|
|
140
|
+
private setStatus;
|
|
141
|
+
private round;
|
|
142
|
+
private scheduleRetry;
|
|
143
|
+
private attempt;
|
|
144
|
+
}
|
|
145
|
+
export declare function replicate(workcopy: Workcopy, transport: ReplicaTransport, options?: Omit<ReplicaOptions, 'side' | 'transport'> & {
|
|
146
|
+
wins?: (actor: string) => boolean;
|
|
147
|
+
}): Replica;
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { TandemError } from "./errors.js";
|
|
2
|
+
import { clone, equal } from "./json.js";
|
|
3
|
+
import { primaryActor } from "./reconcile.js";
|
|
4
|
+
export class MemoryLinkStore {
|
|
5
|
+
link = null;
|
|
6
|
+
load() {
|
|
7
|
+
return this.link ? clone(this.link) : null;
|
|
8
|
+
}
|
|
9
|
+
save(link) {
|
|
10
|
+
this.link = clone(link);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export class MemoryTransport {
|
|
14
|
+
peer;
|
|
15
|
+
constructor(peer) {
|
|
16
|
+
this.peer = peer;
|
|
17
|
+
}
|
|
18
|
+
async sync(request) {
|
|
19
|
+
return clone(this.peer.reconcile(clone(request)));
|
|
20
|
+
}
|
|
21
|
+
watch(notify) {
|
|
22
|
+
return this.peer.log.subscribe(this.peer.log.lastSeq, () => notify());
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export class HttpTransport {
|
|
26
|
+
client;
|
|
27
|
+
doc;
|
|
28
|
+
retryMs;
|
|
29
|
+
constructor(options) {
|
|
30
|
+
this.client = options.client;
|
|
31
|
+
this.doc = options.doc;
|
|
32
|
+
this.retryMs = options.retryMs ?? 2000;
|
|
33
|
+
}
|
|
34
|
+
async sync(request) {
|
|
35
|
+
const { status, body } = await this.client.request('POST', `/v1/workcopies/${encodeURIComponent(this.doc)}/sync`, request);
|
|
36
|
+
if (status >= 400 && status !== 422)
|
|
37
|
+
throw new TandemError(status, body?.error?.code ?? 'http_error', body?.error?.message ?? `HTTP ${status}`);
|
|
38
|
+
return body;
|
|
39
|
+
}
|
|
40
|
+
watch(notify) {
|
|
41
|
+
const abort = new AbortController();
|
|
42
|
+
const path = `/v1/workcopies/${encodeURIComponent(this.doc)}/events`;
|
|
43
|
+
const run = async () => {
|
|
44
|
+
let after = -1;
|
|
45
|
+
while (!abort.signal.aborted) {
|
|
46
|
+
try {
|
|
47
|
+
if (after < 0)
|
|
48
|
+
after = (await this.client.request('GET', `${path}?after=${Number.MAX_SAFE_INTEGER}&format=json`)).body.last_seq;
|
|
49
|
+
for await (const event of this.client.stream(path, after, abort.signal)) {
|
|
50
|
+
if (event.seq !== undefined)
|
|
51
|
+
after = event.seq;
|
|
52
|
+
if (event.type === 'change' || event.type === 'clash' || event.type === 'clash_resolved')
|
|
53
|
+
notify();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
if (abort.signal.aborted)
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
await new Promise((resolve) => {
|
|
61
|
+
const timer = setTimeout(resolve, this.retryMs);
|
|
62
|
+
timer.unref?.();
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
void run();
|
|
67
|
+
return () => abort.abort();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export class ConcurrentEdit extends Error {
|
|
71
|
+
constructor(message = 'the local copy changed while syncing') {
|
|
72
|
+
super(message);
|
|
73
|
+
this.name = 'ConcurrentEdit';
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export class InvalidCopy extends Error {
|
|
77
|
+
problems;
|
|
78
|
+
constructor(problems) {
|
|
79
|
+
super(problems.map((p) => (p.path ? `${p.path}: ${p.message}` : p.message)).join('; '));
|
|
80
|
+
this.name = 'InvalidCopy';
|
|
81
|
+
this.problems = problems;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export function workcopySide(workcopy, options = {}) {
|
|
85
|
+
const wins = options.wins ?? ((actor) => actor === 'human');
|
|
86
|
+
let adopting = false;
|
|
87
|
+
workcopy.useContentClashIds();
|
|
88
|
+
return {
|
|
89
|
+
acceptsClashes: true,
|
|
90
|
+
snapshot(mark, site) {
|
|
91
|
+
return {
|
|
92
|
+
state: workcopy.state,
|
|
93
|
+
actors: workcopy.actorsSince(typeof mark === 'number' ? mark : 0, site),
|
|
94
|
+
pristine: workcopy.pristine,
|
|
95
|
+
clashes: workcopy.clashes,
|
|
96
|
+
closed: workcopy.closedClashes,
|
|
97
|
+
token: { version: workcopy.version, seq: workcopy.seq },
|
|
98
|
+
};
|
|
99
|
+
},
|
|
100
|
+
adopt({ snapshot, state, actors, clashes, closed, site }) {
|
|
101
|
+
adopting = true;
|
|
102
|
+
try {
|
|
103
|
+
workcopy.adoptClashes(clashes, closed);
|
|
104
|
+
const token = snapshot.token;
|
|
105
|
+
if (equal(state, workcopy.state))
|
|
106
|
+
return { mark: token.seq, changed: false };
|
|
107
|
+
const actor = primaryActor(actors, wins, 'sync');
|
|
108
|
+
const untouched = workcopy.version === token.version;
|
|
109
|
+
const result = workcopy.write({
|
|
110
|
+
version: workcopy.version,
|
|
111
|
+
state,
|
|
112
|
+
actor,
|
|
113
|
+
reason: `sync from ${site}`,
|
|
114
|
+
commit: true,
|
|
115
|
+
via: site,
|
|
116
|
+
...(untouched ? {} : { base: snapshot.state, prefer: 'current' }),
|
|
117
|
+
});
|
|
118
|
+
if (result.status === 'rejected')
|
|
119
|
+
return { mark: token.seq, changed: false, findings: result.findings };
|
|
120
|
+
return { mark: token.seq, changed: result.changed };
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
adopting = false;
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
subscribe(notify) {
|
|
127
|
+
return workcopy.log.subscribe(workcopy.log.lastSeq, (event) => {
|
|
128
|
+
if (adopting)
|
|
129
|
+
return;
|
|
130
|
+
if (event.type === 'change' || event.type === 'clash' || event.type === 'clash_resolved')
|
|
131
|
+
notify();
|
|
132
|
+
});
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const wireSide = { local: 'client', remote: 'server' };
|
|
137
|
+
export class Replica {
|
|
138
|
+
site;
|
|
139
|
+
options;
|
|
140
|
+
links;
|
|
141
|
+
retry;
|
|
142
|
+
running = Promise.resolve();
|
|
143
|
+
queued;
|
|
144
|
+
unsubscribe = [];
|
|
145
|
+
debounce;
|
|
146
|
+
poll;
|
|
147
|
+
retryTimer;
|
|
148
|
+
failures = 0;
|
|
149
|
+
current = 'idle';
|
|
150
|
+
started = false;
|
|
151
|
+
last;
|
|
152
|
+
constructor(options) {
|
|
153
|
+
this.options = options;
|
|
154
|
+
this.site = options.site ?? `site-${Math.random().toString(36).slice(2, 10)}`;
|
|
155
|
+
this.links = options.links ?? new MemoryLinkStore();
|
|
156
|
+
this.retry = options.retryMs ?? { min: 500, max: 30_000 };
|
|
157
|
+
}
|
|
158
|
+
get status() {
|
|
159
|
+
return this.current;
|
|
160
|
+
}
|
|
161
|
+
get lastOutcome() {
|
|
162
|
+
return this.last;
|
|
163
|
+
}
|
|
164
|
+
get linked() {
|
|
165
|
+
return this.links.load() !== null;
|
|
166
|
+
}
|
|
167
|
+
sync(options = {}) {
|
|
168
|
+
if (options.first === undefined && this.queued)
|
|
169
|
+
return this.queued;
|
|
170
|
+
const run = this.running.then(() => {
|
|
171
|
+
if (this.queued === run)
|
|
172
|
+
this.queued = undefined;
|
|
173
|
+
return this.round(options.first);
|
|
174
|
+
});
|
|
175
|
+
this.running = run.catch(() => undefined);
|
|
176
|
+
if (options.first === undefined)
|
|
177
|
+
this.queued = run;
|
|
178
|
+
return run;
|
|
179
|
+
}
|
|
180
|
+
start() {
|
|
181
|
+
if (this.started)
|
|
182
|
+
return;
|
|
183
|
+
this.started = true;
|
|
184
|
+
const notify = () => this.changed();
|
|
185
|
+
const local = this.options.side.subscribe?.(notify);
|
|
186
|
+
if (local)
|
|
187
|
+
this.unsubscribe.push(local);
|
|
188
|
+
const remote = this.options.transport.watch?.(notify);
|
|
189
|
+
if (remote)
|
|
190
|
+
this.unsubscribe.push(remote);
|
|
191
|
+
const pollMs = this.options.pollMs ?? 30_000;
|
|
192
|
+
if (pollMs > 0) {
|
|
193
|
+
this.poll = setInterval(() => void this.sync(), pollMs);
|
|
194
|
+
this.poll.unref?.();
|
|
195
|
+
}
|
|
196
|
+
void this.sync();
|
|
197
|
+
}
|
|
198
|
+
async stop() {
|
|
199
|
+
this.started = false;
|
|
200
|
+
for (const off of this.unsubscribe.splice(0))
|
|
201
|
+
off();
|
|
202
|
+
if (this.debounce)
|
|
203
|
+
clearTimeout(this.debounce);
|
|
204
|
+
if (this.retryTimer)
|
|
205
|
+
clearTimeout(this.retryTimer);
|
|
206
|
+
if (this.poll)
|
|
207
|
+
clearInterval(this.poll);
|
|
208
|
+
this.debounce = this.retryTimer = this.poll = undefined;
|
|
209
|
+
await this.running;
|
|
210
|
+
}
|
|
211
|
+
changed() {
|
|
212
|
+
if (!this.started)
|
|
213
|
+
return;
|
|
214
|
+
if (this.debounce)
|
|
215
|
+
clearTimeout(this.debounce);
|
|
216
|
+
this.debounce = setTimeout(() => {
|
|
217
|
+
this.debounce = undefined;
|
|
218
|
+
void this.sync();
|
|
219
|
+
}, this.options.debounceMs ?? 800);
|
|
220
|
+
this.debounce.unref?.();
|
|
221
|
+
}
|
|
222
|
+
setStatus(status, outcome) {
|
|
223
|
+
this.current = status;
|
|
224
|
+
this.options.onStatus?.(status, outcome);
|
|
225
|
+
}
|
|
226
|
+
async round(first) {
|
|
227
|
+
let outcome;
|
|
228
|
+
for (let attempt = 0;; attempt++) {
|
|
229
|
+
try {
|
|
230
|
+
outcome = await this.attempt(first);
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
outcome = { step: 'error', changed_local: false, changed_remote: false, opened: [], findings: [], error: error.message };
|
|
234
|
+
}
|
|
235
|
+
if (outcome.error !== 'concurrent' || attempt >= 3)
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
this.last = outcome;
|
|
239
|
+
if (outcome.step === 'offline' || outcome.step === 'error') {
|
|
240
|
+
this.failures++;
|
|
241
|
+
this.setStatus(outcome.step, outcome);
|
|
242
|
+
this.scheduleRetry();
|
|
243
|
+
}
|
|
244
|
+
else {
|
|
245
|
+
this.failures = 0;
|
|
246
|
+
this.setStatus('idle', outcome);
|
|
247
|
+
}
|
|
248
|
+
return outcome;
|
|
249
|
+
}
|
|
250
|
+
scheduleRetry() {
|
|
251
|
+
if (!this.started || this.retryTimer)
|
|
252
|
+
return;
|
|
253
|
+
const delay = Math.min(this.retry.max, this.retry.min * 2 ** Math.min(this.failures - 1, 16));
|
|
254
|
+
this.retryTimer = setTimeout(() => {
|
|
255
|
+
this.retryTimer = undefined;
|
|
256
|
+
void this.sync();
|
|
257
|
+
}, delay);
|
|
258
|
+
this.retryTimer.unref?.();
|
|
259
|
+
}
|
|
260
|
+
async attempt(first) {
|
|
261
|
+
const { side, transport } = this.options;
|
|
262
|
+
const base = { step: 'synced', changed_local: false, changed_remote: false, opened: [], findings: [] };
|
|
263
|
+
this.setStatus('syncing');
|
|
264
|
+
const link = this.links.load();
|
|
265
|
+
let snapshot;
|
|
266
|
+
try {
|
|
267
|
+
snapshot = await side.snapshot(link?.mark, this.site);
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
if (error instanceof InvalidCopy)
|
|
271
|
+
return { ...base, step: 'invalid', error: error.message, findings: error.problems.map((p) => ({ level: 'block', message: p.message, ...(p.path ? { path: [p.path] } : {}) })) };
|
|
272
|
+
return { ...base, step: 'error', error: error.message };
|
|
273
|
+
}
|
|
274
|
+
const firstChoice = first ?? this.options.first ?? 'compare';
|
|
275
|
+
const request = {
|
|
276
|
+
...(link ? { base: link.base } : {}),
|
|
277
|
+
...(snapshot.state !== undefined ? { state: snapshot.state } : {}),
|
|
278
|
+
actors: snapshot.actors,
|
|
279
|
+
pristine: snapshot.pristine,
|
|
280
|
+
...(link?.peer_mark !== undefined ? { mark: link.peer_mark } : {}),
|
|
281
|
+
site: this.site,
|
|
282
|
+
tie: wireSide[this.options.tie ?? 'remote'],
|
|
283
|
+
first: firstChoice === 'compare' ? 'compare' : wireSide[firstChoice],
|
|
284
|
+
...(side.acceptsClashes ? { clashes: snapshot.clashes, closed: snapshot.closed } : {}),
|
|
285
|
+
};
|
|
286
|
+
let response;
|
|
287
|
+
try {
|
|
288
|
+
response = await transport.sync(request);
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
const permanent = error instanceof TandemError && error.status >= 400 && error.status < 500;
|
|
292
|
+
return { ...base, step: permanent ? 'error' : 'offline', error: error.message };
|
|
293
|
+
}
|
|
294
|
+
const remoteChanged = response.changed;
|
|
295
|
+
if (response.step === 'rejected')
|
|
296
|
+
return { ...base, step: 'rejected', changed_remote: false, findings: response.findings };
|
|
297
|
+
if (response.step === 'compare')
|
|
298
|
+
return { ...base, step: 'compare', local: snapshot.state, remote: response.state };
|
|
299
|
+
let adopted;
|
|
300
|
+
try {
|
|
301
|
+
adopted = await side.adopt({ snapshot, state: response.state, actors: response.actors ?? [], clashes: side.acceptsClashes ? response.clashes : [], closed: side.acceptsClashes ? response.closed : [], site: this.site });
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
if (error instanceof ConcurrentEdit)
|
|
305
|
+
return { ...base, step: response.step, changed_remote: remoteChanged, error: 'concurrent' };
|
|
306
|
+
if (error instanceof InvalidCopy)
|
|
307
|
+
return { ...base, step: 'invalid', error: error.message, changed_remote: remoteChanged };
|
|
308
|
+
return { ...base, step: 'error', error: error.message, changed_remote: remoteChanged };
|
|
309
|
+
}
|
|
310
|
+
const opened = side.acceptsClashes ? response.clashes.filter((c) => !snapshot.clashes.some((own) => own.id === c.id)) : [];
|
|
311
|
+
if (adopted.findings?.some((f) => f.level === 'block'))
|
|
312
|
+
return { ...base, step: 'rejected', changed_remote: remoteChanged, findings: adopted.findings, opened };
|
|
313
|
+
this.links.save({ base: response.state, mark: adopted.mark, peer_mark: response.mark, synced_at: (this.options.clock ?? (() => new Date().toISOString()))() });
|
|
314
|
+
return { ...base, step: response.step, changed_local: adopted.changed, changed_remote: remoteChanged, opened, findings: response.findings };
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
export function replicate(workcopy, transport, options = {}) {
|
|
318
|
+
const { wins, ...rest } = options;
|
|
319
|
+
return new Replica({ ...rest, side: workcopySide(workcopy, { wins }), transport });
|
|
320
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type FileOptions } from './fsutil.js';
|
|
2
|
+
import { type Revision, type RevisionStore } from './revisions.js';
|
|
3
|
+
export interface FileRevisionOptions extends FileOptions {
|
|
4
|
+
portable?: boolean;
|
|
5
|
+
}
|
|
6
|
+
export declare class FileRevisionStore implements RevisionStore {
|
|
7
|
+
private readonly path;
|
|
8
|
+
private readonly options;
|
|
9
|
+
private revisions;
|
|
10
|
+
constructor(path: string, options?: FileRevisionOptions);
|
|
11
|
+
append(revision: Revision): void;
|
|
12
|
+
list(): Revision[];
|
|
13
|
+
head(): Revision | undefined;
|
|
14
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { appendLine, repairLines } from "./fsutil.js";
|
|
4
|
+
import { parseRevisionLines, revisionLine } from "./revisions.js";
|
|
5
|
+
export class FileRevisionStore {
|
|
6
|
+
path;
|
|
7
|
+
options;
|
|
8
|
+
revisions;
|
|
9
|
+
constructor(path, options = {}) {
|
|
10
|
+
this.path = path;
|
|
11
|
+
this.options = options;
|
|
12
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
13
|
+
this.revisions = [];
|
|
14
|
+
repairLines(path);
|
|
15
|
+
if (existsSync(path))
|
|
16
|
+
this.revisions = parseRevisionLines(readFileSync(path, 'utf8'));
|
|
17
|
+
}
|
|
18
|
+
append(revision) {
|
|
19
|
+
appendLine(this.path, revisionLine(revision, this.options.portable), this.options);
|
|
20
|
+
this.revisions.push(revision);
|
|
21
|
+
}
|
|
22
|
+
list() {
|
|
23
|
+
return this.revisions.slice();
|
|
24
|
+
}
|
|
25
|
+
head() {
|
|
26
|
+
return this.revisions.at(-1);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { type Delta, type Path } from './delta.js';
|
|
2
|
+
import type { Json } from './json.js';
|
|
3
|
+
export declare const REVISION_FORMAT: string;
|
|
4
|
+
export interface Finding {
|
|
5
|
+
level: 'block' | 'warn';
|
|
6
|
+
message: string;
|
|
7
|
+
path?: Path;
|
|
8
|
+
}
|
|
9
|
+
export interface Revision {
|
|
10
|
+
format?: string;
|
|
11
|
+
id: string;
|
|
12
|
+
parent: string | null;
|
|
13
|
+
version: number;
|
|
14
|
+
actor: string;
|
|
15
|
+
reason: string | null;
|
|
16
|
+
at: string;
|
|
17
|
+
op: 'init' | 'write' | 'revert';
|
|
18
|
+
delta: Delta;
|
|
19
|
+
state: Json;
|
|
20
|
+
findings: Finding[];
|
|
21
|
+
of?: string;
|
|
22
|
+
via?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface RevisionStore {
|
|
25
|
+
append(revision: Revision): void;
|
|
26
|
+
list(): Revision[];
|
|
27
|
+
head?(): Revision | undefined;
|
|
28
|
+
}
|
|
29
|
+
export declare class MemoryRevisionStore implements RevisionStore {
|
|
30
|
+
private readonly keep;
|
|
31
|
+
private revisions;
|
|
32
|
+
constructor(keep?: number);
|
|
33
|
+
append(revision: Revision): void;
|
|
34
|
+
list(): Revision[];
|
|
35
|
+
head(): Revision | undefined;
|
|
36
|
+
}
|
|
37
|
+
export declare function validateRevision(record: unknown): string[];
|
|
38
|
+
export interface RevisionInput {
|
|
39
|
+
state: Json;
|
|
40
|
+
actor: string;
|
|
41
|
+
reason?: string | null;
|
|
42
|
+
op?: Revision['op'];
|
|
43
|
+
of?: string;
|
|
44
|
+
via?: string;
|
|
45
|
+
at?: string;
|
|
46
|
+
id?: string;
|
|
47
|
+
version?: number;
|
|
48
|
+
findings?: Finding[];
|
|
49
|
+
}
|
|
50
|
+
export declare function makeRevision(previous: Revision | null, input: RevisionInput): Revision;
|
|
51
|
+
export declare function encodeRevision(record: Revision): string;
|
|
52
|
+
export declare function decodeRevision(line: string): Revision;
|
|
53
|
+
export declare function revisionLine(record: Revision, portable?: boolean): string;
|
|
54
|
+
export declare function parseRevisionLines(text: string | null | undefined): Revision[];
|
|
55
|
+
export interface RevisionText {
|
|
56
|
+
read(): string | null | undefined;
|
|
57
|
+
write(text: string): void;
|
|
58
|
+
append?(line: string): void;
|
|
59
|
+
}
|
|
60
|
+
export interface TextRevisionOptions {
|
|
61
|
+
keep?: number;
|
|
62
|
+
portable?: boolean;
|
|
63
|
+
}
|
|
64
|
+
export declare class TextRevisionStore implements RevisionStore {
|
|
65
|
+
private readonly source;
|
|
66
|
+
private readonly options;
|
|
67
|
+
private revisions;
|
|
68
|
+
private text;
|
|
69
|
+
constructor(source: RevisionText, options?: TextRevisionOptions);
|
|
70
|
+
append(revision: Revision): void;
|
|
71
|
+
list(): Revision[];
|
|
72
|
+
head(): Revision | undefined;
|
|
73
|
+
}
|
|
74
|
+
export interface RevisionStorage {
|
|
75
|
+
getItem(key: string): string | null;
|
|
76
|
+
setItem(key: string, value: string): void;
|
|
77
|
+
}
|
|
78
|
+
export declare const storageRevisionStore: (storage: RevisionStorage, key: string, options?: TextRevisionOptions) => TextRevisionStore;
|