heyquilt 0.3.171 → 0.3.172
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/RELEASES.md +8 -0
- package/package.json +1 -1
- package/src/base-pick.js +180 -59
- package/src/live-merge.js +20 -13
- package/src/relay-live-write.js +9 -3
- package/src/session.js +203 -57
- package/src/source-live/live-block.js +154 -43
- package/src/swap-in.js +81 -0
package/RELEASES.md
CHANGED
|
@@ -11,6 +11,14 @@ Format: `## <version> — <YYYY-MM-DD>`, an optional one-line summary, then bull
|
|
|
11
11
|
Lead each bullet with a short bold phrase. Inline `code` and **bold** are rendered;
|
|
12
12
|
nothing else is.
|
|
13
13
|
|
|
14
|
+
## 0.3.172 — 2026-11-14
|
|
15
|
+
|
|
16
|
+
An editor's save is never replaced by a partner's change, new files merge like edits, and a deliberate edit of a partner's line goes in.
|
|
17
|
+
|
|
18
|
+
- **An editor's save is no longer replaced by a partner's change.** When Quilt is about to write a partner's change into your folder just as your editor saves the file (by renaming its own copy into place), Quilt now sees your save, leaves it in place, takes it in, and writes the partner's change on top of it. The file is never missing from its folder while this happens. In the rare case your save lands in the very last instant, Quilt tells you to save again. A new file arriving from the session is also never put over a file you made at that moment.
|
|
19
|
+
- **New files and git pulls merge like any other save.** A file you create, and the edits a git pull brings into your folder, now go to the session the same way your saves do: one at a time, in whole lines. When you and a partner create the same file at once, the first to land is kept and the other is held for its writer to resolve, instead of one silently replacing the other.
|
|
20
|
+
- **A deliberate edit of a partner's fresh line goes in.** Changing a line a partner just wrote is no longer held for confirmation because your version drops some of their words. Quilt holds your line only when your folder shows you never saw theirs: nobody read the file after their change was written into it, or your save was already on its way. Lines your stale save never touched simply take the partner's version, with nothing held.
|
|
21
|
+
|
|
14
22
|
## 0.3.171 — 2026-11-13
|
|
15
23
|
|
|
16
24
|
Nobody holds files any more, and when two edits change the same lines, the first one to land stays and the second waits to be resolved.
|
package/package.json
CHANGED
package/src/base-pick.js
CHANGED
|
@@ -1,47 +1,49 @@
|
|
|
1
|
-
// Which version a save on disk was made from. A folder's last synced text is the usual base of a
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
1
|
+
// Which version a save on disk was made from. A folder's last synced text is the usual base of a save,
|
|
2
|
+
// but an editor or AI that read the file before a partner's change reached disk saves a whole file made
|
|
3
|
+
// from the older version: taken against the newer one, its line would replace the partner's line as if
|
|
4
|
+
// it were an edit of it (2026-11-14: two saves of one line within a second, the second silently kept).
|
|
5
|
+
//
|
|
6
|
+
// So a folder keeps, for each path, the texts a partner's change was lately written over on its disk
|
|
7
|
+
// (since its own last save there), with proof of who read the file Quilt wrote: a save is merged against
|
|
8
|
+
// an older text only when its writer never saw the newer one, and that is shown by the disk, never
|
|
9
|
+
// guessed from what the save looks like (a deliberate edit of a partner's line, however much of it it
|
|
10
|
+
// changes, is an edit of it):
|
|
11
|
+
//
|
|
12
|
+
// - Quilt keeps the file it wrote open (keepWritten), and when it next looks at the path it asks whether
|
|
13
|
+
// anyone read that file since it was written (its access time; Linux's relatime and macOS update it on
|
|
14
|
+
// the first read after a change, `atimeWorks` checks this file system does). Quilt never reads its own
|
|
15
|
+
// unchanged write (session.js ingest, live-block.js diskChanges), so a read is someone else's: an
|
|
16
|
+
// editor reloading it, an AI reading it, or a tool (git) looking at it. Nobody read it: the save that
|
|
17
|
+
// is there now was made from what the file had before (`unseen`). Read: the writer may have seen it
|
|
18
|
+
// (`seen`), and the save is an edit of it.
|
|
19
|
+
// - A save that took the path in a file of its own made before Quilt's file was (its birth time) was
|
|
20
|
+
// made before Quilt's write: `unseen`, whatever read Quilt's file since.
|
|
21
|
+
// - A save that landed in the file Quilt replaced (session.js rescueSave, live-block.js rescue) is marked
|
|
22
|
+
// as made from the text before (`mark`).
|
|
23
|
+
//
|
|
24
|
+
// Where the disk cannot tell (a file system that does not keep access times, Windows, a file Quilt wrote
|
|
25
|
+
// before it could keep it open, or one Quilt read itself), nothing is proven: the save is merged against
|
|
26
|
+
// the last synced text, and the folder does not vouch for it (`sure` false), so the relay's own check of a
|
|
27
|
+
// stale write applies (live-merge.js editsOlder). Where it can, the folder vouches (`seen` on the write)
|
|
28
|
+
// and the relay holds nothing for looking like an older read.
|
|
29
|
+
//
|
|
30
|
+
// The folder's own saves never make a candidate (`forget`), so saving one line again and again is never
|
|
31
|
+
// held against itself. Choosing an older version than the save was made from loses nothing: what the save
|
|
32
|
+
// shares with the newer one is the same change on both sides of the merge.
|
|
33
|
+
import fs from 'node:fs'
|
|
34
|
+
import path from 'node:path'
|
|
35
|
+
import crypto from 'node:crypto'
|
|
13
36
|
import { diffLines as diffIndices } from './textdiff.js'
|
|
14
37
|
|
|
15
38
|
/** How long, and how many, texts a folder keeps per path as possible bases (as long as the stale-write window). */
|
|
16
39
|
export const RECENT_MS = 15 * 60 * 1000
|
|
17
40
|
export const RECENT_MAX = 6
|
|
18
|
-
/** Texts past this are not kept (
|
|
41
|
+
/** Texts past this are not kept (too long to merge against twice). */
|
|
19
42
|
export const RECENT_TEXT = 256 * 1024
|
|
43
|
+
/** Files Quilt wrote kept open at once, across paths, waiting for the next look (past it the oldest are closed: no proof for those). */
|
|
44
|
+
export const MAX_KEPT = 64
|
|
20
45
|
|
|
21
46
|
const lines = (s) => String(s).split('\n')
|
|
22
|
-
const words = (ls) => new Set(ls.join(' ').match(/\w+/g) || [])
|
|
23
|
-
|
|
24
|
-
/** The lines `b` has where it differs from `a` (its side of each hunk). */
|
|
25
|
-
function changed (a, b) {
|
|
26
|
-
const out = []
|
|
27
|
-
for (const h of diffIndices(lines(a), lines(b))) out.push(...h.buffer2Content)
|
|
28
|
-
return out
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Whether a save `text`, as near to the older text `older` as to `current`, was made from `current`: it
|
|
33
|
-
* keeps every word `current`'s changes brought in (a deliberate edit of the partner's line keeps what they
|
|
34
|
-
* wrote; a write from the older read never saw it, and two writers adding the same word is no proof).
|
|
35
|
-
*/
|
|
36
|
-
export function madeFrom (older, current, text) {
|
|
37
|
-
const was = words(changed(current, older))
|
|
38
|
-
const novel = [...words(changed(older, current))].filter((w) => !was.has(w))
|
|
39
|
-
if (!novel.length) return false
|
|
40
|
-
const ws = words(changed(current, text))
|
|
41
|
-
// What the save left as the current text has is kept too.
|
|
42
|
-
const keep = (w) => ws.has(w) || !words(changed(text, current)).has(w)
|
|
43
|
-
return novel.every(keep)
|
|
44
|
-
}
|
|
45
47
|
|
|
46
48
|
/** How many lines `a` and `b` differ by (each changed, added or removed line counts once on each side). */
|
|
47
49
|
export function lineDistance (a, b) {
|
|
@@ -51,41 +53,160 @@ export function lineDistance (a, b) {
|
|
|
51
53
|
return n
|
|
52
54
|
}
|
|
53
55
|
|
|
56
|
+
const probed = new Map() // device -> whether a read moves the access time there
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Whether reading a file on `dir`'s file system moves its access time (once per device): a file of
|
|
60
|
+
* Quilt's own is written, read, and looked at again. False on Windows, and where atime is not kept.
|
|
61
|
+
*/
|
|
62
|
+
export function atimeWorks (dir) {
|
|
63
|
+
if (process.platform === 'win32') return false
|
|
64
|
+
let dev
|
|
65
|
+
try { dev = fs.statSync(dir).dev } catch { return false }
|
|
66
|
+
if (probed.has(dev)) return probed.get(dev)
|
|
67
|
+
let ok = false
|
|
68
|
+
const f = path.join(dir, `.atime-${process.pid}-${crypto.randomBytes(4).toString('hex')}.quilt-tmp`)
|
|
69
|
+
try {
|
|
70
|
+
fs.writeFileSync(f, 'quilt')
|
|
71
|
+
const a = fs.statSync(f).atimeMs
|
|
72
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3) // a clock tick, so a moved time shows
|
|
73
|
+
fs.readFileSync(f)
|
|
74
|
+
ok = fs.statSync(f).atimeMs > a
|
|
75
|
+
} catch {} finally { try { fs.rmSync(f, { force: true }) } catch {} }
|
|
76
|
+
probed.set(dev, ok)
|
|
77
|
+
return ok
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The finished file `tmp` Quilt is about to put in place, kept open (opening it reads nothing) so that who
|
|
82
|
+
* read it after it took its place can be asked even once a save has replaced it: { fd, ino, dev, atimeMs,
|
|
83
|
+
* birthtimeMs, size, mtimeMs }, or null.
|
|
84
|
+
*/
|
|
85
|
+
export function keepWritten (tmp) {
|
|
86
|
+
let fd = null
|
|
87
|
+
try {
|
|
88
|
+
fd = fs.openSync(tmp, 'r')
|
|
89
|
+
const st = fs.fstatSync(fd)
|
|
90
|
+
return { fd, ino: st.ino, dev: st.dev, atimeMs: st.atimeMs, birthtimeMs: st.birthtimeMs || 0, size: st.size, mtimeMs: st.mtimeMs }
|
|
91
|
+
} catch {
|
|
92
|
+
if (fd !== null) { try { fs.closeSync(fd) } catch {} }
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Closes a kept file (keepWritten). */
|
|
98
|
+
export function letGo (w) {
|
|
99
|
+
if (w && w.fd !== null && w.fd !== undefined) { try { fs.closeSync(w.fd) } catch {} w.fd = null }
|
|
100
|
+
}
|
|
101
|
+
|
|
54
102
|
export class RecentTexts {
|
|
55
|
-
constructor ({ ms = RECENT_MS, max = RECENT_MAX } = {}) {
|
|
103
|
+
constructor ({ ms = RECENT_MS, max = RECENT_MAX, kept = MAX_KEPT } = {}) {
|
|
56
104
|
this.ms = ms
|
|
57
105
|
this.max = max
|
|
58
|
-
this.
|
|
106
|
+
this.kept = kept
|
|
107
|
+
this.map = new Map() // path -> [{ text, ts, wrote, verdict }], newest last
|
|
108
|
+
this.marks = new Map() // path -> { text, base }: a rescued save, made from base
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* `text` was on disk at `p` when a partner's change was written over it; `wrote` is the file Quilt put
|
|
113
|
+
* there (keepWritten), or null when it could not keep it (nothing is proven for this write then).
|
|
114
|
+
*/
|
|
115
|
+
note (p, text, wrote = null, now = Date.now()) {
|
|
116
|
+
if (typeof text !== 'string' || text.length > RECENT_TEXT) { letGo(wrote); this.forget(p); return }
|
|
117
|
+
const list = (this.map.get(p) || []).filter((v) => {
|
|
118
|
+
const keep = now - v.ts <= this.ms && v.text !== text
|
|
119
|
+
if (!keep) letGo(v.wrote)
|
|
120
|
+
return keep
|
|
121
|
+
})
|
|
122
|
+
list.push({ text, ts: now, wrote: wrote || null, verdict: wrote ? null : 'unknown' })
|
|
123
|
+
while (list.length > this.max) letGo(list.shift().wrote)
|
|
124
|
+
this.map.set(p, list)
|
|
125
|
+
if (this.map.size > 2000) this.forget(this.map.keys().next().value)
|
|
126
|
+
this.limitKept()
|
|
59
127
|
}
|
|
60
128
|
|
|
61
|
-
/** `
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const list
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
129
|
+
/** Past `kept` files held open, the oldest are closed (their writes prove nothing any more). */
|
|
130
|
+
limitKept () {
|
|
131
|
+
const open = []
|
|
132
|
+
for (const list of this.map.values()) for (const v of list) if (v.wrote && v.wrote.fd !== null) open.push(v)
|
|
133
|
+
if (open.length <= this.kept) return
|
|
134
|
+
open.sort((a, b) => a.ts - b.ts)
|
|
135
|
+
for (const v of open.slice(0, open.length - this.kept)) { letGo(v.wrote); if (!v.verdict) v.verdict = 'unknown' }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
has (p) { return this.map.has(p) || this.marks.has(p) }
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Quilt is about to read the file at `p` (`st`: its lstat, taken before the read): for each write not
|
|
142
|
+
* judged yet, did its writer see it? Asked now, before Quilt's own read moves the access time. Quilt
|
|
143
|
+
* reading its own write unchanged spends the proof (`unknown`).
|
|
144
|
+
*/
|
|
145
|
+
look (p, st, { atime = true } = {}) {
|
|
146
|
+
for (const v of this.map.get(p) || []) {
|
|
147
|
+
if (v.verdict) continue
|
|
148
|
+
v.verdict = judge(v.wrote, st, atime)
|
|
149
|
+
letGo(v.wrote)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A save of `p` with exactly `text` was made from `base` (it landed in the file Quilt replaced). */
|
|
154
|
+
mark (p, text, base) {
|
|
155
|
+
if (typeof text === 'string' && typeof base === 'string') this.marks.set(p, { text, base })
|
|
68
156
|
}
|
|
69
157
|
|
|
70
158
|
/** A save of this folder's at `p` was taken in: the texts before it are no save's base any more. */
|
|
71
|
-
forget (p) {
|
|
159
|
+
forget (p) {
|
|
160
|
+
for (const v of this.map.get(p) || []) letGo(v.wrote)
|
|
161
|
+
this.map.delete(p)
|
|
162
|
+
this.marks.delete(p)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Closes every kept file (the folder stops). */
|
|
166
|
+
close () { for (const p of [...this.map.keys()]) this.forget(p) }
|
|
167
|
+
|
|
168
|
+
fresh (p, current, now) {
|
|
169
|
+
return (this.map.get(p) || []).filter((v) => now - v.ts <= this.ms && v.text !== current)
|
|
170
|
+
}
|
|
72
171
|
|
|
73
172
|
/**
|
|
74
|
-
* The base to merge a save `text` of `p` against: `current` (the last synced text), or
|
|
75
|
-
*
|
|
173
|
+
* The base to merge a save `text` of `p` against: `current` (the last synced text), or the text before
|
|
174
|
+
* the partner's changes its writer is shown never to have seen (newest first: each write written over a
|
|
175
|
+
* text the writer never read past steps the base back one).
|
|
76
176
|
*/
|
|
77
177
|
pick (p, current, text, now = Date.now()) {
|
|
178
|
+
const mk = this.marks.get(p)
|
|
179
|
+
if (mk && mk.text === text) return mk.base
|
|
78
180
|
if (typeof current !== 'string' || typeof text !== 'string' || text.length > RECENT_TEXT || current.length > RECENT_TEXT) return current
|
|
79
|
-
const older =
|
|
80
|
-
|
|
81
|
-
let
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
181
|
+
const older = this.fresh(p, current, now)
|
|
182
|
+
let base = current
|
|
183
|
+
for (let i = older.length - 1; i >= 0 && older[i].verdict === 'unseen'; i--) base = older[i].text
|
|
184
|
+
return base
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Whether the folder vouches for a save of `p` merged against what pick gave: it could tell, for every
|
|
189
|
+
* partner's change written here lately, whether its writer saw it (none is `unknown`). `on`: this
|
|
190
|
+
* folder's disk keeps access times (atimeWorks).
|
|
191
|
+
*/
|
|
192
|
+
sure (p, current, on, now = Date.now()) {
|
|
193
|
+
if (!on) return false
|
|
194
|
+
return this.fresh(p, current, now).every((v) => v.verdict === 'seen' || v.verdict === 'unseen')
|
|
90
195
|
}
|
|
91
196
|
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Whether the save now at the path (`st`) was made without seeing the file Quilt wrote (`w`): 'unseen',
|
|
200
|
+
* 'seen' or 'unknown'.
|
|
201
|
+
*/
|
|
202
|
+
function judge (w, st, atime) {
|
|
203
|
+
if (!w) return 'unknown'
|
|
204
|
+
// A file of its own, made before Quilt's was: prepared before Quilt wrote.
|
|
205
|
+
if (st && (st.ino !== w.ino || st.dev !== w.dev) && st.birthtimeMs > 0 && w.birthtimeMs > 0 && st.birthtimeMs < w.birthtimeMs) return 'unseen'
|
|
206
|
+
if (!atime || w.fd === null || w.fd === undefined) return 'unknown'
|
|
207
|
+
let now
|
|
208
|
+
try { now = fs.fstatSync(w.fd) } catch { return 'unknown' }
|
|
209
|
+
// Quilt's own write, as written: nobody saved, and Quilt reading it now would read it itself.
|
|
210
|
+
if (st && st.ino === w.ino && st.dev === w.dev && st.size === w.size && st.mtimeMs === w.mtimeMs) return 'unknown'
|
|
211
|
+
return now.atimeMs === w.atimeMs ? 'unseen' : 'seen'
|
|
212
|
+
}
|
package/src/live-merge.js
CHANGED
|
@@ -79,9 +79,10 @@ export function editsOlder (l, n, o) {
|
|
|
79
79
|
* stay; each undone change is a hunk held for the writer to confirm. A line changed into a similar
|
|
80
80
|
* one (an edit of it, not its removal) is not protected, unless the new line edits the older line the
|
|
81
81
|
* protected one replaced (`was`: protected line -> the line it replaced; editsOlder): that hunk is
|
|
82
|
-
* held too, marked `older` (the same line changed by two writers).
|
|
82
|
+
* held too, marked `older` (the same line changed by two writers). `edits`: any lines in a protected
|
|
83
|
+
* line's place make it an edit (its writer saw it); only a removal is held. { text, held, lines }.
|
|
83
84
|
*/
|
|
84
|
-
export function protectLines (cur, next, protect, { was = null } = {}) {
|
|
85
|
+
export function protectLines (cur, next, protect, { was = null, edits = false } = {}) {
|
|
85
86
|
const P = new Set((protect || []).filter(significant))
|
|
86
87
|
if (!P.size || cur === next) return { text: next, held: [], lines: [] }
|
|
87
88
|
const older = (l, n) => !!(was && was.has(l) && editsOlder(l, n, was.get(l)))
|
|
@@ -96,7 +97,8 @@ export function protectLines (cur, next, protect, { was = null } = {}) {
|
|
|
96
97
|
for (const h of diffIndices(a, b)) {
|
|
97
98
|
const [bs, bl] = h.buffer2
|
|
98
99
|
out.push(...b.slice(pos, bs))
|
|
99
|
-
|
|
100
|
+
// `edits`: a line replaced by others in its place is edited, not removed (the writer saw it: base-pick.js).
|
|
101
|
+
const lost = edits && h.buffer2Content.some(significant) ? [] : h.buffer1Content.filter((l) => P.has(l) && (cb.get(l) || 0) < (ca.get(l) || 0) && !h.buffer2Content.some((n) => similar(l, n) && !older(l, n)))
|
|
100
102
|
if (lost.length) {
|
|
101
103
|
const edited = lost.every((l) => h.buffer2Content.some((n) => older(l, n)))
|
|
102
104
|
held.push({ at: out.length, base: h.buffer1Content, ours: h.buffer2Content, theirs: h.buffer1Content, ...(edited ? { older: true } : {}) })
|
|
@@ -402,8 +404,12 @@ export class LiveRules {
|
|
|
402
404
|
* landed first; `union`: the project marks the path merge=union (.gitattributes), so both sides'
|
|
403
405
|
* lines go in where both changed them. Returns { text, held: [records], warnings: [strings] }:
|
|
404
406
|
* `text` is what the shared file and the writer's folder get.
|
|
407
|
+
* `seen`: the writer's folder vouches that `ours` was made on `base` (or `older`): it can tell who read its
|
|
408
|
+
* files (base-pick.js). A line someone added lately that this write changes is then its edit, whatever it
|
|
409
|
+
* changes of it: never held for looking like an edit of the line before it (editsOlder), nor for being
|
|
410
|
+
* unlike it (only a removal, with nothing in its place, asks its writer to confirm).
|
|
405
411
|
*/
|
|
406
|
-
write ({ doc, where = {}, path: p, base = null, ours, theirs = null, by, byId = null, others = [], texts = null, union = false, strict = false, nameSearch = true, older = null }) {
|
|
412
|
+
write ({ doc, where = {}, path: p, base = null, ours, theirs = null, by, byId = null, others = [], texts = null, union = false, strict = false, nameSearch = true, older = null, seen = false }) {
|
|
407
413
|
const now = Date.now()
|
|
408
414
|
const map = this.heldMap()
|
|
409
415
|
const all = map ? readHeld(map) : []
|
|
@@ -415,15 +421,16 @@ export class LiveRules {
|
|
|
415
421
|
let olderHeld = []
|
|
416
422
|
let olderKind = 'lines'
|
|
417
423
|
let olderLines = []
|
|
424
|
+
// Held are only the lines both the save and the newer text changed: a line the save merely has as the older
|
|
425
|
+
// text had it (it never touched it) takes the newer one, with nothing held.
|
|
418
426
|
if (typeof older === 'string' && typeof base === 'string' && older !== base && older !== ours) {
|
|
419
|
-
const
|
|
420
|
-
if (
|
|
421
|
-
|
|
422
|
-
olderHeld = hunks.map((h) => ({ at: h.buffer2[0], base: h.buffer2Content, ours: h.buffer1Content, theirs: h.buffer2Content }))
|
|
427
|
+
const r0 = mergeLive(older, ours, base, { union })
|
|
428
|
+
if (r0.text !== ours) {
|
|
429
|
+
olderHeld = r0.held.map((h) => ({ at: h.at, base: h.base, ours: h.ours, theirs: h.theirs }))
|
|
423
430
|
// Only lines the save lacks: a stale write's (confirmable as one); anything else, the same lines.
|
|
424
|
-
if (
|
|
431
|
+
if (olderHeld.length && olderHeld.every((h) => !h.ours.length)) { olderKind = 'stale'; olderLines = olderHeld.flatMap((h) => h.theirs).filter(significant) }
|
|
425
432
|
if (olderKind === 'stale' && !olderLines.length) olderKind = 'lines'
|
|
426
|
-
ours =
|
|
433
|
+
ours = r0.text
|
|
427
434
|
}
|
|
428
435
|
}
|
|
429
436
|
// Same lines: merged against what landed first (only when something did since the writer's base).
|
|
@@ -469,13 +476,13 @@ export class LiveRules {
|
|
|
469
476
|
const protect = vanished(adds, text)
|
|
470
477
|
// The line each recent addition replaced, so a write that edits the older line is told apart (editsOlder).
|
|
471
478
|
const was = new Map()
|
|
472
|
-
for (const e of adds) for (const [n, o] of e.was || []) was.set(n, o)
|
|
479
|
+
if (!seen) for (const e of adds) for (const [n, o] of e.was || []) was.set(n, o)
|
|
473
480
|
const honored = protect.filter((l) => told.has(l))
|
|
474
481
|
const keep = protect.filter((l) => !told.has(l))
|
|
475
|
-
stale = protectLines(cur, text, keep, { was })
|
|
482
|
+
stale = protectLines(cur, text, keep, { was, edits: seen })
|
|
476
483
|
preStale = text
|
|
477
484
|
text = stale.text
|
|
478
|
-
if (kind === 'lines') mine = protectLines(cur, mine, keep, { was }).text
|
|
485
|
+
if (kind === 'lines') mine = protectLines(cur, mine, keep, { was, edits: seen }).text
|
|
479
486
|
// Removed again after being told: honoured, and what told them is settled.
|
|
480
487
|
if (honored.length && map) {
|
|
481
488
|
for (const r of all) if (r.state === 'open' && r.kind === 'stale' && r.path === p && r.by === by && r.lines.some((l) => honored.includes(l))) settleHeld(this.room(), map, r.id, { how: 'mine', by }, this.origin)
|
package/src/relay-live-write.js
CHANGED
|
@@ -3,12 +3,16 @@
|
|
|
3
3
|
// check-then-write race."). A folder that saw a text file change on disk (live-block.js scan, a
|
|
4
4
|
// square's live document; session.js ingest, a branch document) sends the relay
|
|
5
5
|
//
|
|
6
|
-
// MSG_BRANCH { op: 'live-write', branch, path, base, baseText?, text, older?, mode?, at?, trusted?, retry?, baseUnknown? }
|
|
6
|
+
// MSG_BRANCH { op: 'live-write', branch, path, base, baseText?, text, older?, mode?, at?, trusted?, retry?, baseUnknown?, fromGit?, seen? }
|
|
7
7
|
//
|
|
8
8
|
// `base`: the version (sha1, read-bases.js versionOf) of the shared text the folder last synced for the
|
|
9
9
|
// path, null for a file it never had; `baseText`: that text itself, when the relay may not know it
|
|
10
10
|
// (the folder sends it when it is small, or when the relay asked for it); `text`: what disk holds now;
|
|
11
|
-
// `older`: the text the save was found to be made from, when older than the base (base-pick.js)
|
|
11
|
+
// `older`: the text the save was found to be made from, when older than the base (base-pick.js);
|
|
12
|
+
// `fromGit`: a diff branch's first edit of a file only git had, `base` being git's text (the shared file
|
|
13
|
+
// has no entry: it is git's, so the base is what it holds); `seen`: the folder can tell who read its files
|
|
14
|
+
// and vouches that the save was made on `base` (or `older`), so nothing is held for merely looking like an
|
|
15
|
+
// edit made from an older read (live-merge.js LiveRules.write `seen`).
|
|
12
16
|
// The relay merges it here, synchronously (nothing else runs on the room between the read of the
|
|
13
17
|
// shared text and the write of the result), through the same engine every live write uses
|
|
14
18
|
// (live-merge.js LiveRules: same lines keep what landed first and the writer's are held, the stale-write,
|
|
@@ -102,6 +106,8 @@ export function liveWrite (room, ws, req, { origin = WRITE_ORIGIN, now = Date.no
|
|
|
102
106
|
} else if (req.baseUnknown === true) strict = true // the folder knew the file but no longer has the text it synced (a restart)
|
|
103
107
|
// A head file: the shared text is the head's, which is the folder's base (null for a file new to the square).
|
|
104
108
|
let theirs = headOnly ? base : t0 ? t0.toString() : null
|
|
109
|
+
// A diff branch's file only git has (no entry, not deleted in the session): it holds git's text, the base.
|
|
110
|
+
if (!live && req.fromGit === true && !t0 && typeof base === 'string' && !doc.getMap('gone').has(rel)) theirs = base
|
|
105
111
|
if (strict) base = bases.oldest(k, rel) ?? theirs
|
|
106
112
|
// Made by two at once (the folder never had it, the session has it now): both whole, at one spot.
|
|
107
113
|
if (!v && req.baseUnknown !== true && theirs !== null) { base = ''; strict = true }
|
|
@@ -137,7 +143,7 @@ export function liveWrite (room, ws, req, { origin = WRITE_ORIGIN, now = Date.no
|
|
|
137
143
|
// The merge, what it notes in the file's document (additions, for the next stale check) and the result: one
|
|
138
144
|
// transaction, so every member gets the write as one update.
|
|
139
145
|
doc.transact(() => {
|
|
140
|
-
r = rules.write({ doc, where, path: rel, base, ours: req.text, theirs, by, byId, others, strict, nameSearch: false, older })
|
|
146
|
+
r = rules.write({ doc, where, path: rel, base, ours: req.text, theirs, by, byId, others, strict, nameSearch: false, older, seen: req.seen === true && !strict })
|
|
141
147
|
let t = files.get(rel)
|
|
142
148
|
if (live) {
|
|
143
149
|
m.clean.delete(rel); m.gone.delete(rel); m.blobs.delete(rel)
|
package/src/session.js
CHANGED
|
@@ -54,7 +54,8 @@ import { sameEditClient, asClient } from './same-edit.js'
|
|
|
54
54
|
import { openMerge, updateMerge, readMerges, pruneMerges, cleanName } from './merges.js'
|
|
55
55
|
import { LiveRules, applyMine, findUses, removedNameWarning } from './live-merge.js'
|
|
56
56
|
import { versionOf } from './read-bases.js'
|
|
57
|
-
import { RecentTexts } from './base-pick.js'
|
|
57
|
+
import { RecentTexts, atimeWorks, keepWritten, letGo } from './base-pick.js'
|
|
58
|
+
import { swapIn } from './swap-in.js'
|
|
58
59
|
import { HELD_MAP, SETTINGS_MAP, readHeld, findHeld, settleHeld, staleWriteMinutes, setStaleWriteMinutes, renderHeld, heldLandingNote } from './held.js'
|
|
59
60
|
import { RELAY_NAME as RELAY_BY, isRelay } from './ui/chat.js'
|
|
60
61
|
import { cleanTyping, TYPING_MS, AGENT_TYPING_MS } from './ui/chat.js'
|
|
@@ -207,6 +208,11 @@ const readTokenLine = (why) => `The session's read token for its quilt was ${why
|
|
|
207
208
|
const QUILT_TEMP = /^\..+\.quilt-(tmp|save)$/
|
|
208
209
|
// A file emptied this recently may be a save half done (truncated, not written yet): looked at again first.
|
|
209
210
|
const SETTLE_MS = 250
|
|
211
|
+
// A text Quilt wrote up to this long is kept in memory while the file is untouched (noteWritten, readDisk).
|
|
212
|
+
const WROTE_TEXT = 1024 * 1024
|
|
213
|
+
const WROTE_BYTES = 32 * 1024 * 1024 // all of them together; past it the oldest are read from disk again
|
|
214
|
+
// After a write-out, the file it replaced is looked at once more this much later: a save into it, opened just before.
|
|
215
|
+
const LATE_WRITE_MS = 100
|
|
210
216
|
|
|
211
217
|
function writeAndStat (abs, data, mode = undefined) {
|
|
212
218
|
const fd = fs.openSync(abs, 'w', mode)
|
|
@@ -350,6 +356,8 @@ export class Session extends EventEmitter {
|
|
|
350
356
|
this.relayAgain = new Set() // of those, the ones saved again meanwhile: taken in once the answer is here
|
|
351
357
|
this.relayLocal = new Set() // paths the relay asked to be edited here as before (its answer's `fallback`), once
|
|
352
358
|
this.overwritten = new RecentTexts() // the texts a partner's change was lately written over here: a save's possible base (base-pick.js)
|
|
359
|
+
this.wroteHere = new Map() // path -> { ino, size, mtimeMs, text }: the text file Quilt last wrote there, read back from memory while untouched
|
|
360
|
+
this.wroteBytes = 0 // their texts' length, together
|
|
353
361
|
// path -> sha1 of lastKnown when state.json was last saved (null: a state file from before this was kept).
|
|
354
362
|
this.known = null
|
|
355
363
|
// path -> why the shared version could not be written. Tried again by
|
|
@@ -1582,6 +1590,12 @@ export class Session extends EventEmitter {
|
|
|
1582
1590
|
if (!st.isFile()) return { skip: true }
|
|
1583
1591
|
if (st.size > MAX_STORED_BINARY_BYTES) return { tooLarge: true }
|
|
1584
1592
|
const exec = process.platform !== 'win32' && !!(st.mode & 0o111)
|
|
1593
|
+
// The text Quilt wrote there, untouched since (same file, size and time): not read again. Quilt never
|
|
1594
|
+
// reads its own write, so a read of it is someone else's (base-pick.js: did a save's writer see it?).
|
|
1595
|
+
const w = this.wroteHere.get(rel)
|
|
1596
|
+
if (w && w.ino === st.ino && w.size === st.size && w.mtimeMs === st.mtimeMs) return { text: w.text, key: w.text, exec, mtime: st.mtimeMs }
|
|
1597
|
+
// About to read a file a partner's change was written into: who read it since is asked first.
|
|
1598
|
+
if (this.overwritten.has(rel)) this.overwritten.look(rel, st, { atime: this.atimeOn() })
|
|
1585
1599
|
const buf = fs.readFileSync(abs)
|
|
1586
1600
|
// `settle` (taking it in, or writing over it): being written as it was read (it changed during the read, or
|
|
1587
1601
|
// reads empty just after being emptied, as a save that truncates first does) is `unsettled`, looked at again
|
|
@@ -2311,12 +2325,25 @@ export class Session extends EventEmitter {
|
|
|
2311
2325
|
// the shared version; this folder gets the result back, and its own lines are held (held.js).
|
|
2312
2326
|
let text = disk.binary ? null : disk.text
|
|
2313
2327
|
let rewrite = false
|
|
2314
|
-
|
|
2328
|
+
// A diff branch: the edit of a file only git had starts from git's text, so its history says what changed.
|
|
2329
|
+
const fromGit = this.diffForm && !this.files.has(rel) && !this.blobs.has(rel) && !this.gone.has(rel) && typeof gitWas === 'string' && !gitWas.startsWith('bin:') ? gitWas : null
|
|
2330
|
+
if (!disk.binary && !same && this.ready && !this.seeding) {
|
|
2315
2331
|
const known = this.lastKnown.get(rel)
|
|
2316
2332
|
const t = this.files.get(rel)
|
|
2333
|
+
const knownText = typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known)
|
|
2317
2334
|
// The relay takes it as a write (relay-live-write.js): merged there, one write at a time per file, and
|
|
2318
2335
|
// applied in whole lines, never as an edit of the text here that a CRDT would mix with someone else's.
|
|
2319
|
-
|
|
2336
|
+
// So does a git pull's edit, and a file new to the branch (against git's text, for a diff branch's
|
|
2337
|
+
// first edit of a file git has): made by two folders at once, both are kept, never one over the other.
|
|
2338
|
+
if (this.relayWriting.has(rel)) { this.relayAgain.add(rel); return true } // its write's answer first, then this save, on it
|
|
2339
|
+
if (t && knownText && this.relayWritesOn() && !this.relayLocal.delete(rel)) return this.relayIngest(rel, disk, known, { pulled })
|
|
2340
|
+
// A file this folder never had the session's text of (made here while a partner made it too): both kept, never one over the other.
|
|
2341
|
+
if (t && known === undefined && this.relayWritesOn() && !this.relayLocal.delete(rel)) return this.relayIngest(rel, disk, null, { pulled })
|
|
2342
|
+
if (!t && !this.blobs.has(rel) && this.relayWritesOn() && !this.relayLocal.delete(rel)) return this.relayIngest(rel, disk, fromGit, { pulled, fromGit: fromGit !== null })
|
|
2343
|
+
}
|
|
2344
|
+
if (!disk.binary && !pulled && !same && this.ready && !this.seeding) {
|
|
2345
|
+
const known = this.lastKnown.get(rel)
|
|
2346
|
+
const t = this.files.get(rel)
|
|
2320
2347
|
if (t && typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known)) {
|
|
2321
2348
|
const r = this.liveRules().write({ doc: this.bdoc, where: { branch: this.branchKey() }, path: rel, base: known, ours: disk.text, theirs: t.toString(), by: this.name, byId: this.myKey(), others: [this.lastEditorOf(rel)].filter(Boolean) })
|
|
2322
2349
|
if (r.text !== disk.text) { text = r.text; rewrite = true }
|
|
@@ -2332,8 +2359,6 @@ export class Session extends EventEmitter {
|
|
|
2332
2359
|
}
|
|
2333
2360
|
}
|
|
2334
2361
|
let detail = ''
|
|
2335
|
-
// A diff branch: the edit of a file only git had starts from git's text, so its history says what changed.
|
|
2336
|
-
const fromGit = this.diffForm && !this.files.has(rel) && !this.blobs.has(rel) && !this.gone.has(rel) && typeof gitWas === 'string' && !gitWas.startsWith('bin:') ? gitWas : null
|
|
2337
2362
|
this.transact(() => {
|
|
2338
2363
|
const existed = this.files.has(rel) || this.blobs.has(rel) || fromGit !== null
|
|
2339
2364
|
let texts
|
|
@@ -2381,54 +2406,74 @@ export class Session extends EventEmitter {
|
|
|
2381
2406
|
|
|
2382
2407
|
/**
|
|
2383
2408
|
* An edit of a text the session has, sent to the relay as a live write against `base` (what this
|
|
2384
|
-
* folder last synced of it
|
|
2385
|
-
*
|
|
2386
|
-
*
|
|
2409
|
+
* folder last synced of it; null for a file new to the branch, or git's text with `fromGit`: a diff
|
|
2410
|
+
* branch's first edit of a file only git had). Until the relay answers, the path waits: a remote change
|
|
2411
|
+
* is not written over the edit (writeOut sees disk differ), and a further save is taken in after the
|
|
2412
|
+
* answer, on it. `pulled`: a git pull brought it (counted as the pull's). True (the session's version
|
|
2413
|
+
* changes, or the edit is held).
|
|
2387
2414
|
*/
|
|
2388
|
-
relayIngest (rel, disk, base) {
|
|
2415
|
+
relayIngest (rel, disk, base, { pulled = false, fromGit = false } = {}) {
|
|
2389
2416
|
if (this.relayWriting.has(rel)) { this.relayAgain.add(rel); return true }
|
|
2390
2417
|
this.relayWriting.add(rel)
|
|
2391
2418
|
const text = disk.text
|
|
2392
|
-
|
|
2393
|
-
//
|
|
2394
|
-
|
|
2419
|
+
const created = base === null && !this.files.has(rel) && !this.blobs.has(rel)
|
|
2420
|
+
// Made from the text a partner's change was just written over, by a writer who never read the newer one
|
|
2421
|
+
// (base-pick.js)? It goes too (`older`): the relay puts the save onto the base, and where the partner
|
|
2422
|
+
// changed it since, the newer lines stay. Where this folder can tell who read its files, it vouches for
|
|
2423
|
+
// the base (`seen`): nothing is held for merely looking like an older read.
|
|
2424
|
+
const older = typeof base === 'string' ? this.overwritten.pick(rel, base, text) : base
|
|
2425
|
+
const seen = typeof base === 'string' && !fromGit && this.overwritten.sure(rel, base, this.atimeOn())
|
|
2395
2426
|
const trusted = !!(this.liveEngine && this.liveEngine.trusted.get(rel) === text)
|
|
2396
2427
|
const key = this.conn.branchKey
|
|
2397
|
-
const req = {
|
|
2428
|
+
const req = {
|
|
2429
|
+
path: rel,
|
|
2430
|
+
base: typeof base === 'string' ? versionOf(base) : null,
|
|
2431
|
+
...(typeof base === 'string' && base.length <= 256 * 1024 ? { baseText: base } : {}),
|
|
2432
|
+
text,
|
|
2433
|
+
...(older !== base && typeof older === 'string' ? { older } : {}),
|
|
2434
|
+
...(fromGit ? { fromGit: true } : {}),
|
|
2435
|
+
...(seen ? { seen: true } : {}),
|
|
2436
|
+
...(trusted ? { trusted: true } : {})
|
|
2437
|
+
}
|
|
2398
2438
|
// What does not touch the text stays an edit here: its mode, and where a diff branch's entry started.
|
|
2399
2439
|
this.transact(() => {
|
|
2400
2440
|
if (disk.exec) { if (this.modes.get(rel) !== 'x') this.modes.set(rel, 'x') } else if (this.modes.has(rel)) this.modes.delete(rel)
|
|
2401
2441
|
this.notePresentHere(rel, this.entryBase())
|
|
2402
2442
|
}, LOCAL)
|
|
2403
|
-
this
|
|
2443
|
+
// A new file of this folder's: with a deletion of the same text here, a move (edits others make to the old path follow it).
|
|
2444
|
+
if (created && !pulled) { try { this.liveRules().noteNew({ doc: this.bdoc, path: rel, text, by: this.name }) } catch {} }
|
|
2445
|
+
this.noteMyEdit(rel, { pulled })
|
|
2404
2446
|
this.conn.liveWrite(req, { baseOf: () => base }).then(
|
|
2405
|
-
(r) => this.relayWrote(rel, disk, r, key, trusted),
|
|
2447
|
+
(r) => this.relayWrote(rel, disk, r, key, trusted, { pulled, created }),
|
|
2406
2448
|
(err) => this.relayFailed(rel, err)
|
|
2407
2449
|
)
|
|
2408
2450
|
return true
|
|
2409
2451
|
}
|
|
2410
2452
|
|
|
2411
2453
|
/** The relay's answer to a live write of rel: the activity record, the result on disk (unless saved again since), what the writer must hear. */
|
|
2412
|
-
relayWrote (rel, disk, r, key, trusted) {
|
|
2454
|
+
relayWrote (rel, disk, r, key, trusted, { pulled = false, created = false } = {}) {
|
|
2413
2455
|
this.relayWriting.delete(rel)
|
|
2414
2456
|
if (this.stopped) return
|
|
2415
|
-
if (r.fallback) { this.relayLocal.add(rel); this.relayAgain.delete(rel); try { this.ingest(rel) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) } return }
|
|
2457
|
+
if (r.fallback) { this.relayLocal.add(rel); this.relayAgain.delete(rel); try { this.ingest(rel, { pulled }) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) } return }
|
|
2416
2458
|
if (trusted && this.liveEngine) this.liveEngine.trusted.delete(rel)
|
|
2417
2459
|
if (this.conn.branchKey !== key) { this.relayAgain.delete(rel); this.queue(rel); return } // the folder moved to another branch meanwhile
|
|
2418
2460
|
const result = r.same ? disk.text : r.text
|
|
2419
2461
|
this.overwritten.forget(rel)
|
|
2420
|
-
if (r.detail) this.transact(() => this.recordActivity(rel, 'edited', r.detail, { before: r.before ?? '', after: result }), LOCAL)
|
|
2462
|
+
if (r.detail) this.transact(() => this.recordActivity(rel, created && !r.before ? 'created' : 'edited', r.detail, { before: r.before ?? '', after: result }, { pulled }), LOCAL)
|
|
2421
2463
|
let now = null
|
|
2422
2464
|
try { now = this.readDisk(rel) } catch {}
|
|
2423
2465
|
if (now && !now.binary && now.text === disk.text) {
|
|
2424
2466
|
// Disk still has what was sent: it gets the result (the lines that landed first, with this edit's others).
|
|
2425
2467
|
let over = true
|
|
2426
2468
|
if (result !== disk.text) {
|
|
2469
|
+
const kept = {}
|
|
2427
2470
|
try {
|
|
2428
2471
|
const abs = resolveInside(this.root, rel)
|
|
2429
|
-
over = this.writeOver(rel, abs, result, now)
|
|
2472
|
+
over = this.writeOver(rel, abs, result, now, kept)
|
|
2430
2473
|
if (over === null) { this.writeFile(rel, abs, result); over = true }
|
|
2431
2474
|
} catch (err) { this.log(`could not write ${rel}: ${err.message}`) }
|
|
2475
|
+
// What landed first was written over this save: a next save made without reading it is told apart (base-pick.js).
|
|
2476
|
+
if (over === true) this.overwritten.note(rel, disk.text, kept.wrote || null); else letGo(kept.wrote)
|
|
2432
2477
|
}
|
|
2433
2478
|
// Saved again in that instant: that save is taken in next, merged on what was sent.
|
|
2434
2479
|
this.lastKnown.set(rel, over === false ? disk.text : result)
|
|
@@ -2737,7 +2782,8 @@ export class Session extends EventEmitter {
|
|
|
2737
2782
|
// The file changed here in the instant before this remote change arrived: a text both sides
|
|
2738
2783
|
// have is merged as a live write (ingest, against what this folder last had), never overwritten.
|
|
2739
2784
|
const t = this.files.get(rel)
|
|
2740
|
-
|
|
2785
|
+
// So is a save at the relay right now (a file new to the branch too): its answer comes first, then this.
|
|
2786
|
+
if ((this.relayWriting.has(rel) || (!disk.binary && t && typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known))) && !this.writeFailed.has(rel) && !this.downloading.has(rel)) {
|
|
2741
2787
|
queueMicrotask(() => { try { this.ingest(rel) } catch (err) { this.log(`could not merge ${rel}: ${err.message}`) } })
|
|
2742
2788
|
return
|
|
2743
2789
|
}
|
|
@@ -2762,14 +2808,16 @@ export class Session extends EventEmitter {
|
|
|
2762
2808
|
// Saved again since the look above (or made since, when there was nothing): that save is taken in
|
|
2763
2809
|
// and merged, never written over (2026-11-14).
|
|
2764
2810
|
if (this.savedSince(abs, disk)) { this.queue(rel); return }
|
|
2765
|
-
// What a partner's change is written over: a save made from it is told apart (base-pick.js).
|
|
2766
|
-
|
|
2811
|
+
// What a partner's change is written over: a save made from it is told apart (base-pick.js), by who reads the file written.
|
|
2812
|
+
const was = disk && !disk.binary && disk.key === known && this.files.has(rel) ? disk.text : null
|
|
2767
2813
|
fs.mkdirSync(path.dirname(abs), { recursive: true })
|
|
2768
2814
|
const t = this.files.get(rel)
|
|
2769
2815
|
const data = t ? t.toString() : Buffer.from(b.data, 'base64')
|
|
2770
|
-
const
|
|
2816
|
+
const kept = was !== null ? {} : null
|
|
2817
|
+
const over = this.writeOver(rel, abs, data, disk, kept)
|
|
2771
2818
|
if (over === false) { this.queue(rel); return }
|
|
2772
2819
|
if (over === null) this.writeFile(rel, abs, data)
|
|
2820
|
+
if (was !== null) this.overwritten.note(rel, was, kept.wrote || null)
|
|
2773
2821
|
}
|
|
2774
2822
|
if (!b || !b.stored) this.setOnDisk(rel, null)
|
|
2775
2823
|
this.lastKnown.set(rel, shared)
|
|
@@ -2828,27 +2876,69 @@ export class Session extends EventEmitter {
|
|
|
2828
2876
|
|
|
2829
2877
|
/**
|
|
2830
2878
|
* Writes the session's version over a file of this folder's that a save may land in at the same moment:
|
|
2831
|
-
* in a file of its own put in place by
|
|
2832
|
-
*
|
|
2833
|
-
*
|
|
2834
|
-
*
|
|
2879
|
+
* in a file of its own put in place by one rename (the file is never absent at its path), only over the
|
|
2880
|
+
* file `disk` read (savedSince, then swap-in.js: a save that took its place by a rename of its own before
|
|
2881
|
+
* Quilt's last look stays and is taken in next), and the file replaced stays open across it (and is looked
|
|
2882
|
+
* at again LATE_WRITE_MS later), so a save into it in that instant is put back as a save of its own
|
|
2883
|
+
* (rescueSave), never lost with the old file. True written; false saved since (not written); null
|
|
2884
|
+
* where this can't be done (Windows, a read-only file: the caller writes it as before). `disk` null (no file
|
|
2885
|
+
* there): made only if there still is none.
|
|
2886
|
+
* `kept`: an object that gets the written file kept open (`wrote`, base-pick.js keepWritten).
|
|
2835
2887
|
*/
|
|
2836
|
-
writeOver (rel, abs, data, disk) {
|
|
2888
|
+
writeOver (rel, abs, data, disk, kept = null) {
|
|
2837
2889
|
if (process.platform === 'win32') return null
|
|
2838
2890
|
const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-tmp`)
|
|
2891
|
+
if (!disk) {
|
|
2892
|
+
// Nothing there when looked at: put in with a hard link, which never replaces a file made meanwhile (a save: taken in next).
|
|
2893
|
+
try {
|
|
2894
|
+
const st = writeAndStat(tmp, data)
|
|
2895
|
+
try { fs.linkSync(tmp, abs) } catch (err) {
|
|
2896
|
+
fs.rmSync(tmp, { force: true })
|
|
2897
|
+
let dir = false
|
|
2898
|
+
try { dir = fs.lstatSync(abs).isDirectory() } catch {}
|
|
2899
|
+
return err.code === 'EEXIST' && !dir ? false : null // a folder there: written as before (and refused as before)
|
|
2900
|
+
}
|
|
2901
|
+
fs.rmSync(tmp, { force: true })
|
|
2902
|
+
this.noteWritten(rel, abs, st, data)
|
|
2903
|
+
return true
|
|
2904
|
+
} catch { try { fs.rmSync(tmp, { force: true }) } catch {} return null }
|
|
2905
|
+
}
|
|
2839
2906
|
let old = null
|
|
2907
|
+
let wrote = null
|
|
2840
2908
|
try {
|
|
2841
2909
|
old = fs.openSync(abs, 'r')
|
|
2842
2910
|
// As it was before the look below: a save into it after this is either seen by that look or after the rename.
|
|
2843
2911
|
const seen = fs.fstatSync(old)
|
|
2912
|
+
const look = fs.lstatSync(abs)
|
|
2844
2913
|
const st = writeAndStat(tmp, data, seen.mode & 0o7777)
|
|
2845
|
-
|
|
2846
|
-
fs.
|
|
2847
|
-
|
|
2914
|
+
// Replaced since it was opened (look is another file), or saved since disk was read: not written.
|
|
2915
|
+
if ((!look.isSymbolicLink() && look.ino !== seen.ino) || this.savedSince(abs, disk)) { fs.rmSync(tmp, { force: true }); return false }
|
|
2916
|
+
if (kept) wrote = keepWritten(tmp)
|
|
2917
|
+
let r = { placed: true, displaced: null, replaced: false }
|
|
2918
|
+
if (look.isSymbolicLink()) fs.renameSync(tmp, abs)
|
|
2919
|
+
else r = this.swapIn(rel, abs, tmp, look)
|
|
2920
|
+
// Not the file looked at any more (a save took its place): taken in next, and written again after it.
|
|
2921
|
+
if (!r.placed) { letGo(wrote); return false }
|
|
2922
|
+
this.noteWritten(rel, abs, st, data)
|
|
2923
|
+
if (kept) { kept.wrote = wrote; wrote = null }
|
|
2924
|
+
const before = disk && typeof disk.text === 'string' ? disk.text : null
|
|
2848
2925
|
const now = fs.fstatSync(old)
|
|
2849
|
-
|
|
2926
|
+
// A save written into the file replaced: back as a save of its own, once whole (rescueSave), or at once.
|
|
2927
|
+
if (now.size !== seen.size || now.mtimeMs !== seen.mtimeMs) { this.rescueSave(rel, abs, old, data, before); old = null } else if (r.displaced) { const bytes = r.displaced; setImmediate(() => this.putBackSave(rel, abs, bytes, data, before)) } else {
|
|
2928
|
+
// An editor that opened the file just before the rename may write into it a moment after: looked at once more.
|
|
2929
|
+
const fd = old
|
|
2930
|
+
old = null
|
|
2931
|
+
const t = setTimeout(() => {
|
|
2932
|
+
let later = null
|
|
2933
|
+
try { later = fs.fstatSync(fd) } catch {}
|
|
2934
|
+
if (!this.stopped && later && (later.size !== seen.size || later.mtimeMs !== seen.mtimeMs)) this.rescueSave(rel, abs, fd, data, before)
|
|
2935
|
+
else { try { fs.closeSync(fd) } catch {} }
|
|
2936
|
+
}, LATE_WRITE_MS)
|
|
2937
|
+
t.unref?.()
|
|
2938
|
+
}
|
|
2850
2939
|
return true
|
|
2851
2940
|
} catch {
|
|
2941
|
+
letGo(wrote)
|
|
2852
2942
|
try { fs.rmSync(tmp, { force: true }) } catch {}
|
|
2853
2943
|
return null
|
|
2854
2944
|
} finally { if (old !== null) { try { fs.closeSync(old) } catch {} } }
|
|
@@ -2873,32 +2963,69 @@ export class Session extends EventEmitter {
|
|
|
2873
2963
|
let off = 0
|
|
2874
2964
|
while (off < size) { const n = fs.readSync(fd, bytes, off, size - off, off); if (!n) break; off += n }
|
|
2875
2965
|
if (this.stopped) return
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2966
|
+
this.putBackSave(rel, abs, bytes, wrote, before)
|
|
2967
|
+
} catch {} finally { try { fs.closeSync(fd) } catch {} }
|
|
2968
|
+
}
|
|
2969
|
+
|
|
2970
|
+
/**
|
|
2971
|
+
* A save of `rel` (`bytes`) that Quilt's write took out of the path (it landed in the file replaced, or took
|
|
2972
|
+
* that file's place in the instant before) goes back on disk: over what Quilt wrote (`wrote`), whole; saved
|
|
2973
|
+
* again since, its own change (against `before`, what disk had before the write) goes onto that newer save,
|
|
2974
|
+
* both kept where both changed a line. Then it is taken in.
|
|
2975
|
+
*/
|
|
2976
|
+
putBackSave (rel, abs, bytes, wrote, before = null) {
|
|
2977
|
+
try {
|
|
2978
|
+
if (this.stopped) return
|
|
2979
|
+
const w = Buffer.isBuffer(wrote) ? wrote : Buffer.from(String(wrote), 'utf8')
|
|
2980
|
+
if (bytes.equals(w)) return // nothing of its own
|
|
2882
2981
|
const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-save`)
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
const
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
let
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2982
|
+
// Put back only over the file as looked at here (swap-in.js): saved again in that instant, it is looked at again.
|
|
2983
|
+
let placed = false
|
|
2984
|
+
let ours = false
|
|
2985
|
+
for (let attempt = 0; attempt < 5 && !placed; attempt++) {
|
|
2986
|
+
let look = null
|
|
2987
|
+
try { look = fs.lstatSync(abs) } catch {}
|
|
2988
|
+
const now = (() => { try { return fs.readFileSync(abs) } catch { return null } })()
|
|
2989
|
+
if (!now || !look) return // gone
|
|
2990
|
+
// Disk still has a version Quilt wrote (this one, or a newer one it wrote since): the save goes back over it.
|
|
2991
|
+
const k = this.lastKnown.get(rel)
|
|
2992
|
+
ours = now.equals(w) || (typeof k === 'string' && !k.startsWith('bin:') && now.toString('utf8') === k)
|
|
2993
|
+
let put = bytes
|
|
2994
|
+
if (!ours) {
|
|
2995
|
+
// Saved again since, from what Quilt wrote: the late save's own change goes onto that save.
|
|
2996
|
+
if (typeof before !== 'string' || looksBinary(bytes) || looksBinary(now)) return
|
|
2997
|
+
const onto = mergeLive(before, bytes.toString('utf8'), w.toString('utf8')).text
|
|
2998
|
+
// Both saves are this folder's: where they changed the same place, both go in (nothing is lost; its writer sees both).
|
|
2999
|
+
const merged = mergeLive(w.toString('utf8'), onto, now.toString('utf8'), { union: true }).text
|
|
3000
|
+
if (merged === now.toString('utf8')) return
|
|
3001
|
+
put = Buffer.from(merged, 'utf8')
|
|
3002
|
+
}
|
|
3003
|
+
fs.writeFileSync(tmp, put, { mode: look.mode & 0o7777 })
|
|
3004
|
+
if (look.isSymbolicLink()) { fs.renameSync(tmp, abs); placed = true; continue }
|
|
3005
|
+
const r = this.swapIn(rel, abs, tmp, look)
|
|
3006
|
+
placed = r.placed
|
|
3007
|
+
if (r.displaced) { const again = r.displaced; setImmediate(() => this.putBackSave(rel, abs, again, put, now.toString('utf8'))) }
|
|
2898
3008
|
}
|
|
3009
|
+
if (!placed) return // saved again and again meanwhile: what is there now is taken in
|
|
3010
|
+
// Made from what disk had before Quilt's write: merged against that (base-pick.js).
|
|
3011
|
+
if (ours && typeof before === 'string' && !looksBinary(bytes)) this.overwritten.mark(rel, bytes.toString('utf8'), before)
|
|
2899
3012
|
this.log(`${rel}: a save landed while Quilt wrote the session's version; it is taken in now`)
|
|
2900
3013
|
this.queue(rel)
|
|
2901
|
-
} catch {}
|
|
3014
|
+
} catch {}
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3017
|
+
/**
|
|
3018
|
+
* swap-in.js for this folder (the second name in .quilt/tmp, so no file of Quilt's ever shows in the
|
|
3019
|
+
* project); a save replaced in the one system call it cannot cover is said to its writer.
|
|
3020
|
+
*/
|
|
3021
|
+
swapIn (rel, abs, tmp, look) {
|
|
3022
|
+
const r = swapIn(abs, tmp, look, { asideDir: path.join(this.stateDir, 'tmp') })
|
|
3023
|
+
if (r.replaced) {
|
|
3024
|
+
const w = `A save of ${rel} landed in the same instant Quilt wrote the session's version over it, and could not be kept: save ${rel} again (your editor still has it).`
|
|
3025
|
+
this.notice(w)
|
|
3026
|
+
this.log(`⚠️ ${w}`)
|
|
3027
|
+
}
|
|
3028
|
+
return r
|
|
2902
3029
|
}
|
|
2903
3030
|
|
|
2904
3031
|
/** A file read half-written (readDisk `unsettled`): taken in a moment later. */
|
|
@@ -2927,7 +3054,7 @@ export class Session extends EventEmitter {
|
|
|
2927
3054
|
/** Writes the shared version of rel. A read-only copy of ours is made writable, or moved aside if it can't be. */
|
|
2928
3055
|
writeFile (rel, abs, data) {
|
|
2929
3056
|
try {
|
|
2930
|
-
return this.noteWritten(rel, abs, writeAndStat(abs, data))
|
|
3057
|
+
return this.noteWritten(rel, abs, writeAndStat(abs, data), data)
|
|
2931
3058
|
} catch (err) {
|
|
2932
3059
|
if (err.code !== 'EACCES' && err.code !== 'EPERM') throw err
|
|
2933
3060
|
}
|
|
@@ -2939,7 +3066,7 @@ export class Session extends EventEmitter {
|
|
|
2939
3066
|
this.moveAside(rel, abs)
|
|
2940
3067
|
st = writeAndStat(abs, data)
|
|
2941
3068
|
}
|
|
2942
|
-
this.noteWritten(rel, abs, st)
|
|
3069
|
+
this.noteWritten(rel, abs, st, data)
|
|
2943
3070
|
}
|
|
2944
3071
|
|
|
2945
3072
|
/**
|
|
@@ -2947,14 +3074,32 @@ export class Session extends EventEmitter {
|
|
|
2947
3074
|
* events in a folder Quilt just created, and a file the re-scan never saw
|
|
2948
3075
|
* would never be noticed gone. `st`: the file as this write left it (read
|
|
2949
3076
|
* before it was closed), so a save landing right after it is never taken for it.
|
|
3077
|
+
* `data`: what was written; a text is kept (wroteHere), so reading it back while untouched reads nothing.
|
|
2950
3078
|
*/
|
|
2951
|
-
noteWritten (rel, abs, st = null) {
|
|
3079
|
+
noteWritten (rel, abs, st = null, data = null) {
|
|
2952
3080
|
try {
|
|
2953
3081
|
if (!st) st = fs.lstatSync(abs)
|
|
2954
3082
|
this.diskStats.set(rel, `${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`)
|
|
3083
|
+
const was = this.wroteHere.get(rel)
|
|
3084
|
+
if (was) { this.wroteBytes -= was.text.length; this.wroteHere.delete(rel) }
|
|
3085
|
+
if (typeof data === 'string' && data.length <= WROTE_TEXT) {
|
|
3086
|
+
this.wroteHere.set(rel, { ino: st.ino, size: st.size, mtimeMs: st.mtimeMs, text: data })
|
|
3087
|
+
this.wroteBytes = (this.wroteBytes || 0) + data.length
|
|
3088
|
+
while (this.wroteBytes > WROTE_BYTES && this.wroteHere.size) {
|
|
3089
|
+
const [k, v] = this.wroteHere.entries().next().value
|
|
3090
|
+
this.wroteBytes -= v.text.length
|
|
3091
|
+
this.wroteHere.delete(k)
|
|
3092
|
+
}
|
|
3093
|
+
}
|
|
2955
3094
|
} catch {}
|
|
2956
3095
|
}
|
|
2957
3096
|
|
|
3097
|
+
/** Whether this folder's disk shows who read a file (base-pick.js atimeWorks), looked at once. */
|
|
3098
|
+
atimeOn () {
|
|
3099
|
+
if (this.atimeSeen === undefined) this.atimeSeen = atimeWorks(this.root)
|
|
3100
|
+
return this.atimeSeen
|
|
3101
|
+
}
|
|
3102
|
+
|
|
2958
3103
|
/** Moves whatever sits at rel (first join: a folder, or a file where a folder must go) into the backup folder. */
|
|
2959
3104
|
moveToBackup (rel, backupDir) {
|
|
2960
3105
|
const dest = path.join(backupDir, ...rel.split('/'))
|
|
@@ -5688,6 +5833,7 @@ export class Session extends EventEmitter {
|
|
|
5688
5833
|
clearTimeout(this.typingTimer)
|
|
5689
5834
|
clearTimeout(this.typingExpiryTimer)
|
|
5690
5835
|
if (this.conn) this.conn.close()
|
|
5836
|
+
this.overwritten.close()
|
|
5691
5837
|
this.saveState()
|
|
5692
5838
|
this.emit('stopped')
|
|
5693
5839
|
await new Promise((r) => setTimeout(r, 100))
|
|
@@ -26,7 +26,8 @@ import { FEATURES } from '../protocol.js'
|
|
|
26
26
|
import { applyTextDiff } from '../textdiff.js'
|
|
27
27
|
import { mergeLive } from '../merge3.js'
|
|
28
28
|
import { versionOf } from '../read-bases.js'
|
|
29
|
-
import { RecentTexts } from '../base-pick.js'
|
|
29
|
+
import { RecentTexts, atimeWorks, keepWritten, letGo } from '../base-pick.js'
|
|
30
|
+
import { swapIn } from '../swap-in.js'
|
|
30
31
|
import { findUses, removedNameWarning } from '../live-merge.js'
|
|
31
32
|
// Seam's block folders and ids come from Seam's client package (@heyquilt/seam), never Seam's server code.
|
|
32
33
|
import { blobId, under } from '@heyquilt/seam/lib/quilts/records.js'
|
|
@@ -409,7 +410,11 @@ export class LiveBlock {
|
|
|
409
410
|
* big folder is not read on every scan, nor one that is a repository of its own (a submodule).
|
|
410
411
|
*/
|
|
411
412
|
diskChanges (files) {
|
|
412
|
-
if (!this.inPlace)
|
|
413
|
+
if (!this.inPlace) {
|
|
414
|
+
// Seam's localChanges reads what changed: who read a file a partner's change was written into is asked first.
|
|
415
|
+
for (const p of [...this.overwritten.map.keys()]) { try { this.lookBeforeRead(p, fs.lstatSync(path.join(this.dir, ...p.split('/'))), files) } catch {} }
|
|
416
|
+
return localChanges(this.dir, { paths: this.block.paths, files })
|
|
417
|
+
}
|
|
413
418
|
const out = []
|
|
414
419
|
const seen = new Set()
|
|
415
420
|
const visit = (rel) => {
|
|
@@ -427,6 +432,7 @@ export class LiveBlock {
|
|
|
427
432
|
seen.add(r)
|
|
428
433
|
const k = files[r]
|
|
429
434
|
if (k && k.size === st.size && k.mtimeMs === st.mtimeMs) continue
|
|
435
|
+
this.lookBeforeRead(r, st, files)
|
|
430
436
|
let bytes
|
|
431
437
|
try { bytes = st.isSymbolicLink() ? Buffer.from(fs.readlinkSync(abs)) : fs.readFileSync(abs) } catch { continue }
|
|
432
438
|
const mode = st.isSymbolicLink() ? 'symlink' : (st.mode & 0o111) && process.platform !== 'win32' ? 'exec' : 'file'
|
|
@@ -677,6 +683,8 @@ export class LiveBlock {
|
|
|
677
683
|
// Made from the text a partner's change was just written over (an editor's older read)? It goes too
|
|
678
684
|
// (`older`): the relay puts the save onto the base, and where the partner changed it since, the newer lines stay.
|
|
679
685
|
const older = !mv && typeof base === 'string' ? this.overwritten.pick(p, base, text) : base
|
|
686
|
+
// Where this folder can tell who read its files, it vouches for the base (`seen`): nothing is held for merely looking like an older read.
|
|
687
|
+
const seen = !mv && typeof base === 'string' && this.overwritten.sure(p, base, this.atimeOn())
|
|
680
688
|
const known = !!this.known[p]
|
|
681
689
|
const trusted = !!(this.rules && this.rules.trusted && this.rules.trusted.get(target) === text)
|
|
682
690
|
const req = {
|
|
@@ -688,6 +696,7 @@ export class LiveBlock {
|
|
|
688
696
|
...(typeof base !== 'string' && known && !mv ? { baseUnknown: true } : {}),
|
|
689
697
|
text,
|
|
690
698
|
...(older !== base && typeof older === 'string' ? { older } : {}),
|
|
699
|
+
...(seen ? { seen: true } : {}),
|
|
691
700
|
mode: c.mode,
|
|
692
701
|
at: this.block.at,
|
|
693
702
|
...(trusted ? { trusted: true } : {})
|
|
@@ -716,7 +725,12 @@ export class LiveBlock {
|
|
|
716
725
|
this.overwritten.forget(p)
|
|
717
726
|
this.known[p] = { blob: c.blob, mode: c.mode, ...this.seenStat(p, c, readAt) }
|
|
718
727
|
this.lastText.set(p, { id: c.blob, text })
|
|
719
|
-
if (result !== text
|
|
728
|
+
if (result !== text) {
|
|
729
|
+
// What landed first is written over this save: a next save made without reading it is told apart (base-pick.js).
|
|
730
|
+
const kept = {}
|
|
731
|
+
if (this.write(p, { bytes: Buffer.from(result, 'utf8'), mode: c.mode }, { guard: true, keep: kept, before: text }) === false) this.scanSoon()
|
|
732
|
+
else this.overwritten.note(p, text, kept.wrote || null)
|
|
733
|
+
}
|
|
720
734
|
}
|
|
721
735
|
for (const n of r.notices || []) { try { if (this.rules) this.rules.notice(n) } catch {} }
|
|
722
736
|
for (const l of r.logs || []) if (this.logFn) this.logFn(l)
|
|
@@ -747,6 +761,38 @@ export class LiveBlock {
|
|
|
747
761
|
} catch { return { size: -1, mtimeMs: -1 } }
|
|
748
762
|
}
|
|
749
763
|
|
|
764
|
+
/**
|
|
765
|
+
* The file at `p` (`st`, its lstat) changed since this block saw it and is about to be read: if a partner's
|
|
766
|
+
* change was written into it lately, who read it since is asked first (base-pick.js), before this read.
|
|
767
|
+
*/
|
|
768
|
+
lookBeforeRead (p, st, files = this.known) {
|
|
769
|
+
if (!this.overwritten.has(p)) return
|
|
770
|
+
const k = files[p]
|
|
771
|
+
if (k && st && k.size === st.size && k.mtimeMs === st.mtimeMs) return
|
|
772
|
+
this.overwritten.look(p, st, { atime: this.atimeOn() })
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* swap-in.js for this block (the second name beside its record, in .quilt/tmp): false when the file at the
|
|
777
|
+
* path is a save not taken in (nothing replaced); else the bytes of a save written into the file replaced
|
|
778
|
+
* (or null). A save replaced in the one system call swap-in.js cannot cover is said to its writer.
|
|
779
|
+
*/
|
|
780
|
+
swapInto (p, abs, tmp, look) {
|
|
781
|
+
const r = swapIn(abs, tmp, look, { asideDir: this.record ? path.join(path.dirname(this.record), 'tmp') : null })
|
|
782
|
+
if (r.replaced) {
|
|
783
|
+
const w = `A save of ${p} landed in the same instant Quilt wrote the square's version over it, and could not be kept: save ${p} again (your editor still has it).`
|
|
784
|
+
try { if (this.rules) this.rules.notice(w) } catch {}
|
|
785
|
+
if (this.logFn) this.logFn(`⚠️ ${w}`)
|
|
786
|
+
}
|
|
787
|
+
return r.placed ? r.displaced : false
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** Whether this folder's disk shows who read a file (base-pick.js atimeWorks), looked at once. */
|
|
791
|
+
atimeOn () {
|
|
792
|
+
if (this.atimeSeen === undefined) this.atimeSeen = atimeWorks(this.dir)
|
|
793
|
+
return this.atimeSeen
|
|
794
|
+
}
|
|
795
|
+
|
|
750
796
|
/**
|
|
751
797
|
* Whether `p` on disk changed since this block last read or wrote it (a save not taken in yet): then
|
|
752
798
|
* nothing is written over it. A different size or time with the same bytes is no change (and is
|
|
@@ -759,6 +805,7 @@ export class LiveBlock {
|
|
|
759
805
|
try { st = fs.lstatSync(abs) } catch { return !!k } // gone here but known: a deletion not taken in yet
|
|
760
806
|
if (!k) return true // a file here this block never took in
|
|
761
807
|
if (k.size === st.size && k.mtimeMs === st.mtimeMs) return false
|
|
808
|
+
this.lookBeforeRead(p, st)
|
|
762
809
|
let bytes
|
|
763
810
|
try { bytes = st.isSymbolicLink() ? Buffer.from(fs.readlinkSync(abs)) : fs.readFileSync(abs) } catch { return true }
|
|
764
811
|
const mode = st.isSymbolicLink() ? 'symlink' : (st.mode & 0o111) && process.platform !== 'win32' ? 'exec' : 'file'
|
|
@@ -810,7 +857,7 @@ export class LiveBlock {
|
|
|
810
857
|
* read or wrote there (diskMoved), looked at again just before the file is replaced; false when it was
|
|
811
858
|
* left alone, so a save made meanwhile is taken in (and merged) rather than overwritten.
|
|
812
859
|
*/
|
|
813
|
-
write (p, want, { guard = false } = {}) {
|
|
860
|
+
write (p, want, { guard = false, keep = null, before: was = null } = {}) {
|
|
814
861
|
const abs = path.join(this.dir, ...p.split('/'))
|
|
815
862
|
if (guard && this.diskMoved(p)) return false
|
|
816
863
|
if (!want) { fs.rmSync(abs, { force: true }); delete this.known[p]; this.lastText.delete(p); this.wrote(p); return true }
|
|
@@ -824,8 +871,9 @@ export class LiveBlock {
|
|
|
824
871
|
fs.writeFileSync(tmp, want.bytes, { mode: want.mode === 'exec' ? 0o755 : 0o644 })
|
|
825
872
|
st = fs.lstatSync(tmp)
|
|
826
873
|
const last = this.lastText.get(p)
|
|
827
|
-
|
|
828
|
-
const
|
|
874
|
+
// What disk had (`was`, when the caller read it): a save that lands in or takes the place of the file replaced was made from it.
|
|
875
|
+
const before = typeof was === 'string' ? was : last && this.known[p] && last.id === this.known[p].blob ? last.text : null
|
|
876
|
+
const placed = this.place(p, abs, tmp, { guard, before, wrote: want.bytes, keep })
|
|
829
877
|
if (!placed) return false
|
|
830
878
|
}
|
|
831
879
|
this.known[p] = { blob: blobId(want.bytes), mode: want.mode, size: st.size, mtimeMs: st.mtimeMs }
|
|
@@ -843,22 +891,61 @@ export class LiveBlock {
|
|
|
843
891
|
* saw it (diskMoved): false then. A save into the file being replaced, landing in the instant between
|
|
844
892
|
* that look and the rename (an editor that truncates and writes, opened just before it), would be
|
|
845
893
|
* gone with the old file: the old file stays open across the rename, and what was saved into it after
|
|
846
|
-
* the look is put back as a save of its own (rescue), taken in by the next
|
|
894
|
+
* the look is put back as a save of its own (rescue, looked at again 100 ms later too), taken in by the next
|
|
895
|
+
* scan. The replace is always one rename (the file is never absent); a save that took the file's place by a
|
|
896
|
+
* rename of its own before the last look is never replaced (swap-in.js): false, and it is taken in. `keep`: an object that gets the written file kept open (`wrote`, base-pick.js keepWritten).
|
|
847
897
|
*/
|
|
848
|
-
place (p, abs, tmp, { guard = false, before = null, wrote = null } = {}) {
|
|
898
|
+
place (p, abs, tmp, { guard = false, before = null, wrote = null, keep = null } = {}) {
|
|
849
899
|
let old = null
|
|
850
|
-
|
|
900
|
+
let look = null
|
|
901
|
+
let kept = null
|
|
902
|
+
let displaced = null
|
|
903
|
+
if (guard) { try { old = fs.openSync(abs, 'r'); look = fs.lstatSync(abs) } catch {} }
|
|
851
904
|
try {
|
|
852
905
|
// As it was before the look below: a save into it after this is either seen by that look or after the rename.
|
|
853
906
|
const seen = old !== null ? fs.fstatSync(old) : null
|
|
854
|
-
|
|
855
|
-
fs.
|
|
907
|
+
// Changed since this block saw it, or replaced since it was opened (look is another file): left alone.
|
|
908
|
+
if (guard && (this.diskMoved(p) || (look && seen && !look.isSymbolicLink() && look.ino !== seen.ino))) { fs.rmSync(tmp, { force: true }); return false }
|
|
909
|
+
if (keep) kept = keepWritten(tmp)
|
|
910
|
+
if (guard && old === null) {
|
|
911
|
+
// Nothing there at the look: put in only if nothing is there now (a hard link never replaces a save made meanwhile).
|
|
912
|
+
try { fs.linkSync(tmp, abs); fs.rmSync(tmp, { force: true }) } catch (err) {
|
|
913
|
+
if (err.code !== 'EEXIST') fs.renameSync(tmp, abs)
|
|
914
|
+
else {
|
|
915
|
+
fs.rmSync(tmp, { force: true })
|
|
916
|
+
let dir = false
|
|
917
|
+
try { dir = fs.lstatSync(abs).isDirectory() } catch {}
|
|
918
|
+
if (dir) throw err // a folder where the file goes: as a rename would fail
|
|
919
|
+
return false
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
} else if (old !== null && look && !look.isSymbolicLink()) {
|
|
923
|
+
// Never over a save it can see (swap-in.js): one that took the file's place since the look is taken in first.
|
|
924
|
+
displaced = this.swapInto(p, abs, tmp, look)
|
|
925
|
+
if (displaced === false) return false
|
|
926
|
+
} else fs.renameSync(tmp, abs)
|
|
927
|
+
if (keep) { keep.wrote = kept; kept = null }
|
|
856
928
|
if (old !== null) {
|
|
857
929
|
const now = fs.fstatSync(old)
|
|
858
|
-
|
|
930
|
+
// A save written into the file replaced: back as a save of its own, once whole (rescue), or at once.
|
|
931
|
+
if (now.size !== seen.size || now.mtimeMs !== seen.mtimeMs) { this.rescue(p, old, { before, wrote }); old = null } else if (displaced) { const bytes = displaced; setImmediate(() => { this.run(() => this.putBack(p, bytes, { before, wrote })).catch(() => {}) }) } else {
|
|
932
|
+
// An editor that opened the file just before the rename may write into it a moment after: looked at once more.
|
|
933
|
+
const fd = old
|
|
934
|
+
old = null
|
|
935
|
+
const t = setTimeout(() => {
|
|
936
|
+
let later = null
|
|
937
|
+
try { later = fs.fstatSync(fd) } catch {}
|
|
938
|
+
if (!this.closed && later && (later.size !== seen.size || later.mtimeMs !== seen.mtimeMs)) this.rescue(p, fd, { before, wrote })
|
|
939
|
+
else { try { fs.closeSync(fd) } catch {} }
|
|
940
|
+
}, 100)
|
|
941
|
+
t.unref?.()
|
|
942
|
+
}
|
|
859
943
|
}
|
|
860
944
|
return true
|
|
861
|
-
} finally {
|
|
945
|
+
} finally {
|
|
946
|
+
letGo(kept)
|
|
947
|
+
if (old !== null) { try { fs.closeSync(old) } catch {} }
|
|
948
|
+
}
|
|
862
949
|
}
|
|
863
950
|
|
|
864
951
|
/**
|
|
@@ -881,37 +968,58 @@ export class LiveBlock {
|
|
|
881
968
|
let off = 0
|
|
882
969
|
while (off < size) { const n = fs.readSync(fd, bytes, off, size - off, off); if (!n) break; off += n }
|
|
883
970
|
if (this.closed) return
|
|
884
|
-
await this.run(
|
|
885
|
-
const abs = path.join(this.dir, ...p.split('/'))
|
|
886
|
-
const k = this.known[p]
|
|
887
|
-
if (k && k.blob === blobId(bytes)) return
|
|
888
|
-
const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-save`)
|
|
889
|
-
const mode = k && k.mode === 'exec' ? 0o755 : 0o644
|
|
890
|
-
if (!this.diskMoved(p)) {
|
|
891
|
-
// Disk still has what this block wrote: the save goes back over it.
|
|
892
|
-
fs.writeFileSync(tmp, bytes, { mode })
|
|
893
|
-
this.place(p, abs, tmp, { guard: true })
|
|
894
|
-
} else {
|
|
895
|
-
let now = null
|
|
896
|
-
try { now = fs.readFileSync(abs) } catch {}
|
|
897
|
-
if (!now || typeof before !== 'string' || !wrote || !isText(bytes) || !isText(now)) return
|
|
898
|
-
const onto = mergeLive(before, bytes.toString('utf8'), wrote.toString('utf8')).text
|
|
899
|
-
// Both saves are this folder's: where they changed the same place, both go in (nothing is lost; its writer sees both).
|
|
900
|
-
const merged = mergeLive(wrote.toString('utf8'), onto, now.toString('utf8'), { union: true }).text
|
|
901
|
-
if (merged === now.toString('utf8')) return
|
|
902
|
-
fs.writeFileSync(tmp, merged, { mode })
|
|
903
|
-
// Only over that newer save as it is (it is taken in with the late one's change on it).
|
|
904
|
-
let again = null
|
|
905
|
-
try { again = fs.readFileSync(abs) } catch {}
|
|
906
|
-
if (!again || !again.equals(now)) { fs.rmSync(tmp, { force: true }); return }
|
|
907
|
-
fs.renameSync(tmp, abs)
|
|
908
|
-
}
|
|
909
|
-
if (this.logFn) this.logFn(`${p}: a save landed while Quilt wrote the session's version; it is taken in now`)
|
|
910
|
-
this.scanSoon()
|
|
911
|
-
})
|
|
971
|
+
await this.run(() => this.putBack(p, bytes, { before, wrote }))
|
|
912
972
|
} catch {} finally { try { fs.closeSync(fd) } catch {} }
|
|
913
973
|
}
|
|
914
974
|
|
|
975
|
+
/**
|
|
976
|
+
* A save of `p` (`bytes`) that this block's write took out of the path (it landed in the file replaced, or
|
|
977
|
+
* took that file's place in the instant before) goes back on disk as a save of its own: over what this block
|
|
978
|
+
* wrote, whole; saved again since (from what this block wrote, without it), its own change (`before`: what
|
|
979
|
+
* disk had before the write, `wrote`: the write) goes onto that newer save, both kept where both changed a
|
|
980
|
+
* line. Run in the block's queue.
|
|
981
|
+
*/
|
|
982
|
+
async putBack (p, bytes, { before = null, wrote = null } = {}) {
|
|
983
|
+
const abs = path.join(this.dir, ...p.split('/'))
|
|
984
|
+
const k = this.known[p]
|
|
985
|
+
if (k && k.blob === blobId(bytes)) return
|
|
986
|
+
const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-save`)
|
|
987
|
+
const mode = k && k.mode === 'exec' ? 0o755 : 0o644
|
|
988
|
+
// Put back only over the file as looked at (place, swap-in.js): saved again in that instant, looked at again.
|
|
989
|
+
let placed = false
|
|
990
|
+
let ours = false
|
|
991
|
+
for (let attempt = 0; attempt < 5 && !placed; attempt++) {
|
|
992
|
+
if (!this.diskMoved(p)) {
|
|
993
|
+
// Disk still has what this block wrote: the save goes back over it.
|
|
994
|
+
ours = true
|
|
995
|
+
fs.writeFileSync(tmp, bytes, { mode })
|
|
996
|
+
placed = this.place(p, abs, tmp, { guard: true })
|
|
997
|
+
continue
|
|
998
|
+
}
|
|
999
|
+
ours = false
|
|
1000
|
+
let look = null
|
|
1001
|
+
try { look = fs.lstatSync(abs) } catch {}
|
|
1002
|
+
let now = null
|
|
1003
|
+
try { now = fs.readFileSync(abs) } catch {}
|
|
1004
|
+
if (!now || !look || typeof before !== 'string' || !wrote || !isText(bytes) || !isText(now)) return
|
|
1005
|
+
const onto = mergeLive(before, bytes.toString('utf8'), wrote.toString('utf8')).text
|
|
1006
|
+
// Both saves are this folder's: where they changed the same place, both go in (nothing is lost; its writer sees both).
|
|
1007
|
+
const merged = mergeLive(wrote.toString('utf8'), onto, now.toString('utf8'), { union: true }).text
|
|
1008
|
+
if (merged === now.toString('utf8')) return
|
|
1009
|
+
fs.writeFileSync(tmp, merged, { mode })
|
|
1010
|
+
// Only over that newer save as it is (it is taken in with the late one's change on it).
|
|
1011
|
+
if (look.isSymbolicLink()) { fs.rmSync(tmp, { force: true }); return }
|
|
1012
|
+
const again = this.swapInto(p, abs, tmp, look)
|
|
1013
|
+
placed = again !== false
|
|
1014
|
+
if (again) { const was = now; setImmediate(() => { this.run(() => this.putBack(p, again, { before: was.toString('utf8'), wrote: Buffer.from(merged, 'utf8') })).catch(() => {}) }) }
|
|
1015
|
+
}
|
|
1016
|
+
if (!placed) { this.scanSoon(); return }
|
|
1017
|
+
// Made from what disk had before this block's write, which it landed in: merged against that (base-pick.js).
|
|
1018
|
+
if (ours && typeof before === 'string' && isText(bytes)) this.overwritten.mark(p, bytes.toString('utf8'), before)
|
|
1019
|
+
if (this.logFn) this.logFn(`${p}: a save landed while Quilt wrote the session's version; it is taken in now`)
|
|
1020
|
+
this.scanSoon()
|
|
1021
|
+
}
|
|
1022
|
+
|
|
915
1023
|
/** Moves the block to the document's head (a commit by anyone in the square), then writes the overlay out. */
|
|
916
1024
|
async pull () {
|
|
917
1025
|
if (this.closed) return
|
|
@@ -931,8 +1039,9 @@ export class LiveBlock {
|
|
|
931
1039
|
// Never over a save not taken in yet (one made since the scan above): the next scan merges it.
|
|
932
1040
|
if (id !== have || (want && this.known[p].mode !== want.mode)) {
|
|
933
1041
|
const was = have && want ? await this.syncedText(p) : null
|
|
934
|
-
|
|
935
|
-
|
|
1042
|
+
const kept = typeof was === 'string' ? {} : null
|
|
1043
|
+
if (this.write(p, want, { guard: true, keep: kept, before: was }) === false) this.scanSoon()
|
|
1044
|
+
else if (typeof was === 'string') this.overwritten.note(p, was, kept.wrote || null) // a save made from it is told apart (base-pick.js), by who reads the file written
|
|
936
1045
|
}
|
|
937
1046
|
} catch (err) { failed.push({ path: p, err }) }
|
|
938
1047
|
}
|
|
@@ -1062,6 +1171,7 @@ export class LiveBlock {
|
|
|
1062
1171
|
clearInterval(this.stepTimer)
|
|
1063
1172
|
for (const t of this.settleTimers || []) clearTimeout(t)
|
|
1064
1173
|
if (this.watcher) this.watcher.close()
|
|
1174
|
+
this.overwritten.close()
|
|
1065
1175
|
if (this.conn) this.conn.close()
|
|
1066
1176
|
}
|
|
1067
1177
|
|
|
@@ -1073,6 +1183,7 @@ export class LiveBlock {
|
|
|
1073
1183
|
for (const t of this.settleTimers || []) clearTimeout(t)
|
|
1074
1184
|
if (this.watcher) this.watcher.close()
|
|
1075
1185
|
await this.queue.catch(() => {})
|
|
1186
|
+
this.overwritten.close()
|
|
1076
1187
|
if (this.record && this.block && this.block.at) { try { this.save() } catch {} }
|
|
1077
1188
|
if (this.conn) this.conn.close()
|
|
1078
1189
|
}
|
package/src/swap-in.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Putting Quilt's version of a file in place without replacing a save that took its place, and without the
|
|
2
|
+
// file ever being absent at its path (a `git add -A`, a build watcher or an AI's read in that instant would
|
|
3
|
+
// take it for deleted: the replace is always one rename).
|
|
4
|
+
//
|
|
5
|
+
// A plain rename of Quilt's finished file over the path replaces whatever is there at that instant: an
|
|
6
|
+
// editor that saves by renaming its own file into place between Quilt's last look and Quilt's rename would
|
|
7
|
+
// lose that save with the file it replaced. Node has no atomic exchange or conditional replace (renameat2's
|
|
8
|
+
// RENAME_EXCHANGE / RENAME_NOREPLACE, macOS's renamex_np RENAME_SWAP need a compiled addon), so the race is
|
|
9
|
+
// narrowed and what is left of it is detected:
|
|
10
|
+
//
|
|
11
|
+
// 1. The file at the path is hard-linked into Quilt's own folder (.quilt/tmp): whatever it is, it now has a
|
|
12
|
+
// second name, and the path is untouched. Not the file Quilt looked at (a save took its place, or wrote
|
|
13
|
+
// into it): nothing is replaced ({ placed: false }); the save is taken in, and the write tried again.
|
|
14
|
+
// 2. Looked at once more (one system call before the rename): another file at the path now, the same.
|
|
15
|
+
// 3. The rename. Then the linked file says what the rename replaced: written into since the look (in place),
|
|
16
|
+
// its bytes come back as `displaced`, to put back as a save. Its link count dropped before the rename
|
|
17
|
+
// (its change time is earlier than that of Quilt's file, which one rename stamps on both): some other
|
|
18
|
+
// file took the path in the one system call between 2 and 3 and Quilt's rename replaced it. That save's
|
|
19
|
+
// bytes are gone with it (no second name was possible for a file not there yet): `replaced` says so, and
|
|
20
|
+
// the caller tells its writer to save again (NOT-DONE.md).
|
|
21
|
+
import fs from 'node:fs'
|
|
22
|
+
import path from 'node:path'
|
|
23
|
+
import crypto from 'node:crypto'
|
|
24
|
+
|
|
25
|
+
// One rename stamps the file it replaces and the file it moves within this much of each other (up to about
|
|
26
|
+
// 2 µs seen on APFS under load): an earlier unlink by more than this is another file's rename.
|
|
27
|
+
const REPLACED_GAP_MS = 0.01
|
|
28
|
+
|
|
29
|
+
const rm = (f) => { try { fs.rmSync(f, { force: true }) } catch {} }
|
|
30
|
+
|
|
31
|
+
/** Whether `a` and `b` (lstat results) are the same file, unchanged: same inode, size and time. */
|
|
32
|
+
export const sameFile = (a, b) => !!(a && b && a.ino === b.ino && a.dev === b.dev && a.size === b.size && a.mtimeMs === b.mtimeMs)
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Puts the finished file `tmp` at `abs` with one rename, only over the file `seen` (an lstat of `abs` as
|
|
36
|
+
* Quilt looked at it). `asideDir`: Quilt's own folder on the same disk for the second name (.quilt/tmp).
|
|
37
|
+
* { placed, displaced, replaced }: `placed` false when the file at the path is no longer the one looked at
|
|
38
|
+
* (`tmp` is removed; take that save in, then write again); `displaced`, the bytes of a save written into
|
|
39
|
+
* the file Quilt replaced after the look, or null; `replaced`, a save that took the path in the last
|
|
40
|
+
* instant was replaced by Quilt's file (its bytes could not be kept).
|
|
41
|
+
*/
|
|
42
|
+
export function swapIn (abs, tmp, seen, { asideDir = null } = {}) {
|
|
43
|
+
const none = { placed: false, displaced: null, replaced: false }
|
|
44
|
+
let snap = null
|
|
45
|
+
if (asideDir) {
|
|
46
|
+
snap = path.join(asideDir, `${path.basename(abs)}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.quilt-old`)
|
|
47
|
+
try { fs.mkdirSync(asideDir, { recursive: true }); fs.linkSync(abs, snap) } catch (err) {
|
|
48
|
+
if (err.code === 'ENOENT' && !fs.existsSync(abs)) { rm(tmp); return none } // gone since the look: a change of its own
|
|
49
|
+
snap = null // another disk, or no hard links: the look and the rename as before
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
let st = null
|
|
53
|
+
try { st = fs.lstatSync(snap || abs) } catch {}
|
|
54
|
+
if (!sameFile(st, seen)) { if (snap) rm(snap); rm(tmp); return none }
|
|
55
|
+
// Quilt's file, held open across the rename: the time the rename stamps on it, unless written since.
|
|
56
|
+
let fd = null
|
|
57
|
+
let pre = null
|
|
58
|
+
if (snap) { try { fd = fs.openSync(tmp, 'r'); pre = fs.fstatSync(fd) } catch {} }
|
|
59
|
+
const drop = () => { if (snap) rm(snap); rm(tmp); if (fd !== null) { try { fs.closeSync(fd) } catch {} } return none }
|
|
60
|
+
// One last look, right before the rename: another file there now is a save, never replaced.
|
|
61
|
+
let at = null
|
|
62
|
+
try { at = fs.lstatSync(abs) } catch {}
|
|
63
|
+
if (!at || at.ino !== st.ino || at.dev !== st.dev) return drop()
|
|
64
|
+
try { fs.renameSync(tmp, abs) } catch (err) { if (snap) rm(snap); if (fd !== null) fs.closeSync(fd); throw err }
|
|
65
|
+
if (!snap) return { placed: true, displaced: null, replaced: false }
|
|
66
|
+
let after = null
|
|
67
|
+
let mine = null
|
|
68
|
+
try { after = fs.lstatSync(snap) } catch {}
|
|
69
|
+
try { if (fd !== null) { const m = fs.fstatSync(fd); if (pre && m.mtimeMs === pre.mtimeMs && m.size === pre.size) mine = m } } catch {}
|
|
70
|
+
if (fd !== null) { try { fs.closeSync(fd) } catch {} }
|
|
71
|
+
let displaced = null
|
|
72
|
+
let replaced = false
|
|
73
|
+
if (after && (after.size !== seen.size || after.mtimeMs !== seen.mtimeMs)) {
|
|
74
|
+
try { displaced = fs.readFileSync(snap) } catch {}
|
|
75
|
+
} else if (after && mine && after.ctimeMs > st.ctimeMs && after.ctimeMs < mine.ctimeMs - REPLACED_GAP_MS) {
|
|
76
|
+
// Unlinked from the path after the link above, well before Quilt's rename stamped its file: another file took its place.
|
|
77
|
+
replaced = true
|
|
78
|
+
}
|
|
79
|
+
rm(snap)
|
|
80
|
+
return { placed: true, displaced, replaced }
|
|
81
|
+
}
|