When both sides changed a part, the newer stays: this computer's
change wins when changed(p), the part's file time here, is After
remote.Created, the other computer's push, taken with time.Now(). A
file's time comes from the kernel's clock, which moves in ticks (4 ms
at HZ=250 on this Linux box) and is behind time.Now() by up to a tick
or two: of 20,000 files written right after a time.Now(), 19,954 to
20,000 had a modification time before it, by up to 8 ms.
TestSync ("…and the newer one stays") and
TestSyncTeraCloudStillSeesOtherWrites save this computer's change a
few ms after the other's push and expect it to be the newer. A save
inside the push's tick reads as the older, and the other's copy
replaces it:
davsync_test.go:309: newer here: &{... Here:[settings] There:[] ...}
teracloud_test.go:303: a wrote over b's providers without seeing
them: &{... Here:[providers] There:[] ...}
TestSync was red so in 3 of my full suites (10-19, 10-20, 10-23).
Alone on b437e4ad, -count=100: TestSync red 13 times,
TestSyncTeraCloudStillSeesOtherWrites 21. With the gap from the push's
Created to the saved file's time logged, every red run had a gap of
0 or less (down to -1.9 ms and -3.2 ms), and no green one did.
Each test now dates its change to time.Now(), the clock the push's
Created comes from, right after the save (os.Chtimes, as TestSync
already dates its older change an hour back). The rule itself is
unchanged: a change inside a tick of another computer's push is as
good as at the same moment, and two computers' clocks differ by more.
What was run (tree 77adaa75, on b437e4ad):
the tick injected, on b437e4ad: the save dated 1 ms before the
push's Created. -count=20 of both tests: red 20 of 20 each, at
davsync_test.go's newer-here check and teracloud_test.go's
wrote-over check
with this change, -count=200 of both: ok
broken by hand, with this change:
davsync.go's both-changed case never taking this computer's:
davsync_test.go:316: newer here: ... Here:[settings] There:[]
teracloud_test.go:310: a wrote over b's providers without
seeing them: ... Here:[providers] There:[]
always taking it:
davsync_test.go:294: older here: ... Here:[] There:[settings]
gofmt -l internal/davsync: nothing
GOOS=linux, darwin, windows go vet -tags nogui ./internal/davsync:
exit 0
full suite, go test -tags nogui -count=1 -timeout 45m ./...
(go1.26.8, 467 s): 62 packages ok, internal/davsync among them. 16
reds in 7 packages, none in a file this change touches:
internal/agent TestInstalledVersion, TestHowInstalled,
TestOmpDetectedWithPiDir, TestCursorFolderFromTheEditorIsNotTheCLI,
TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
TestQoderSettingsFromAnIDEPluginIsNotTheCLI and TestZedAppPath:
proc.Look keeps "not found" for a tool written in the tick of its
folder's last change (#3141).
internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
/tmp meets a /tmp/.git that isn't a repository of this user's
("error obtaining VCS status: exit status 128").
internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
internal/gui TestGatewayHeldByAContainer and
TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
their outgoing connections sent through a proxy (graftcp).
internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
TestProgram: umask 077 here; the fixtures' own modes go through it
(0444 is written as 0400).
internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: macOS, Windows.
Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
077; agent, provider, library and gateway with an empty .git above
TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
changed tests in agent, provider, gateway and gui; the timing tests
-count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
at umask 077 and two Reasonix tests under an empty .git; on Linux
(wsl-run) TestProgram at umask 077 with the old program.go. With
each fix's code taken back to main's, the Gemini imageConfig tests,
TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
plugin-github-hooks, plugins-more-discover, plugin-namesake were
red. Broken by hand: claudeKeyed always true (both
OwnEndpointNeverAsked tests red), claudeAsk a no-op
(TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
(the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
plugin-card-update, plugin-github, plugin-move*, segs-glide,
tray-totals, update-*), and run again side by side they fail the
same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
there). They are click-scroll guards ("the click must not scroll
the page"), varying by language from run to run (#4385).
copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
too. In Chromium on mote, Chromium segfaulted partway through files
(#4125): context-map, context-scroll-end and context-tune fail the
same on origin/main 0911a65e7, so the batch's own files
(plugin-namesake, update-auto, plugins-more-discover,
plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
whose five reds were #4362's (Antigravity turned-away and
TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
the rebase on 244d80e23 the five pass, and gofmt, the three vets
and the targeted runs above were run again: ok. In Linux the
sign-in, copilot, plugin-github*, plugins-more-discover,
plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
#1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
gui, gateway, provider and plugin, TestCoreScriptBudget (core
1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
update-mirror, plugin-namesake, plugins-more-discover,
plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
321 lines
10 KiB
Go
321 lines
10 KiB
Go
package davsync
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/backup"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// apacheDAV answers as InfiniCLOUD's (TeraCloud's) WebDAV plausibly does
|
|
// (#1362). Its server is Apache with mod_dav_fs (OPTIONS on
|
|
// https://domi.teracloud.jp/dav/ says "Server: Apache" and
|
|
// "DAV: <http://apache.org/dav/propset/fs/1>"), and mod_deflate runs with
|
|
// its default DeflateAlterETag AddSuffix: a GET of its own page asked with
|
|
// Accept-Encoding: gzip comes back gzip with ETag "fb-5d88268abcf08-gzip",
|
|
// asked without it comes back plain with "fb-5d88268abcf08", and a GET with
|
|
// If-Match: "fb-5d88268abcf08-gzip" is answered 412 (all seen 2026-10-09,
|
|
// without an account). So, as httpd 2.4's source does:
|
|
// - a PUT answers 201 or 204 with no ETag (mod_dav.c's dav_created: "###
|
|
// insert an ETag header?");
|
|
// - If-Match and If-None-Match are compared with the file's own ETag;
|
|
// - a GET that may be gzip is sent gzip, its ETag with "-gzip" added
|
|
// inside the quotes;
|
|
// - a HEAD says the file's own ETag and length.
|
|
//
|
|
// Whether TeraCloud's mod_deflate compresses files under /dav/ wasn't seen:
|
|
// that needs an account. It is what "works once, then always fails" needs.
|
|
type apacheDAV struct {
|
|
mu sync.Mutex
|
|
files map[string][]byte
|
|
etags map[string]string
|
|
dirs map[string]bool
|
|
n int
|
|
// gzipped are the GETs answered compressed; refused the PUTs answered
|
|
// 412; between, when set, runs before the next PUT with If-Match is
|
|
// looked at — another computer's write landing in between
|
|
gzipped, refused int
|
|
between func()
|
|
}
|
|
|
|
func newApacheDAV() *apacheDAV {
|
|
return &apacheDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}}
|
|
}
|
|
|
|
// write is a write to p as mod_dav_fs makes it: a new ETag (Apache's is
|
|
// the size and the time, in hex).
|
|
func (a *apacheDAV) write(p string, b []byte) {
|
|
a.n++
|
|
a.files[p], a.etags[p] = b, fmt.Sprintf(`"%x-%x"`, len(b), 0x5d88268abcf08+a.n)
|
|
}
|
|
|
|
func (a *apacheDAV) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if u, p, ok := r.BasicAuth(); !ok || u != "me" || p != "pw" {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="InfiniCLOUD Basic Authentication dav"`)
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
w.Header().Set("Server", "Apache")
|
|
p := r.URL.Path
|
|
body, there := a.files[p]
|
|
etag := a.etags[p]
|
|
switch r.Method {
|
|
case http.MethodGet, http.MethodHead:
|
|
if !there {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
if m := r.Header.Get("If-None-Match"); m != "" && m == etag {
|
|
w.Header().Set("ETag", etag)
|
|
w.WriteHeader(http.StatusNotModified)
|
|
return
|
|
}
|
|
gz := r.Method == http.MethodGet && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
|
|
w.Header().Set("Content-Type", "application/octet-stream")
|
|
w.Header().Set("Vary", "Accept-Encoding")
|
|
if !gz {
|
|
w.Header().Set("ETag", etag)
|
|
w.Header().Set("Content-Length", fmt.Sprint(len(body)))
|
|
w.WriteHeader(http.StatusOK)
|
|
if r.Method == http.MethodGet {
|
|
w.Write(body)
|
|
}
|
|
return
|
|
}
|
|
a.gzipped++
|
|
w.Header().Set("ETag", strings.TrimSuffix(etag, `"`)+`-gzip"`)
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
w.WriteHeader(http.StatusOK)
|
|
zw := gzip.NewWriter(w)
|
|
zw.Write(body)
|
|
zw.Close()
|
|
case http.MethodPut:
|
|
if !a.dirs[urlDir(p)] {
|
|
w.WriteHeader(http.StatusConflict)
|
|
return
|
|
}
|
|
if m := r.Header.Get("If-Match"); m != "" {
|
|
if a.between != nil {
|
|
a.between()
|
|
a.between = nil
|
|
etag = a.etags[p]
|
|
}
|
|
if m != etag || strings.HasPrefix(m, "W/") {
|
|
a.refused++
|
|
w.WriteHeader(http.StatusPreconditionFailed)
|
|
return
|
|
}
|
|
}
|
|
b, _ := io.ReadAll(r.Body)
|
|
a.write(p, b)
|
|
if there {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
w.Header().Set("Location", "http://"+r.Host+p)
|
|
w.WriteHeader(http.StatusCreated)
|
|
case "MKCOL":
|
|
d := strings.TrimSuffix(p, "/")
|
|
if a.dirs[d] {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
a.dirs[d] = true
|
|
w.WriteHeader(http.StatusCreated)
|
|
default:
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
|
|
// Sync with TeraCloud worked the first time and failed every time after
|
|
// with "the file on the server changed meanwhile" (#1362): its PUT says no
|
|
// ETag, so the next sync read the file in full, Go asked for it gzip, and
|
|
// the ETag that came back was the gzip copy's — which no If-Match matches.
|
|
// The file is read as it is now, and every sync after the first writes.
|
|
func TestSyncTeraCloudGzipETag(t *testing.T) {
|
|
fake := newApacheDAV()
|
|
srv := httptest.NewServer(fake)
|
|
defer srv.Close()
|
|
ctx := context.Background()
|
|
cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse", Keys: true, Agents: true}
|
|
|
|
a, b := newComputer(t), newComputer(t)
|
|
a.use(t)
|
|
provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k1"})
|
|
if err := Configure(cfg); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := Now(ctx); err != nil {
|
|
t.Fatalf("first sync: %v", err)
|
|
}
|
|
for i, id := range []string{"kimi", "three", "four"} {
|
|
provider.Save(provider.Provider{ID: id, Name: id, Chat: "https://" + id + "/v1", Key: "k" + id})
|
|
if err := Now(ctx); err != nil {
|
|
t.Fatalf("sync %d after the first: %v (%d writes refused, %d reads sent gzip)", i+2, err, fake.refused, fake.gzipped)
|
|
}
|
|
}
|
|
if fake.refused != 0 || fake.gzipped != 0 {
|
|
t.Fatalf("%d writes refused, %d reads sent gzip", fake.refused, fake.gzipped)
|
|
}
|
|
remote, err := backup.Open(fake.files["/dav/magpie/magpie.magpie-backup"], "correct horse")
|
|
if err != nil || len(remote.Providers) != 4 {
|
|
t.Fatalf("on the server: %v %+v", err, remote.Providers)
|
|
}
|
|
|
|
// another computer joins, adds one, and a gets it
|
|
b.use(t)
|
|
if err := Configure(cfg); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := Now(ctx); err != nil {
|
|
t.Fatalf("b's first sync: %v", err)
|
|
}
|
|
provider.Save(provider.Provider{ID: "five", Name: "Five", Chat: "https://five/v1", Key: "k5"})
|
|
if err := Now(ctx); err != nil {
|
|
t.Fatalf("b's sync: %v", err)
|
|
}
|
|
a.use(t)
|
|
if err := Now(ctx); err != nil {
|
|
t.Fatalf("a after b: %v", err)
|
|
}
|
|
if got := ids(); !slices.Equal(got, []string{"deepseek=k1", "five=k5", "four=kfour", "kimi=kkimi", "three=kthree"}) {
|
|
t.Fatalf("a after b added: %v", got)
|
|
}
|
|
}
|
|
|
|
// A server that sends the file gzip though it was asked for as it is: the
|
|
// file is still read whole.
|
|
func TestDAVGetGzipAnyway(t *testing.T) {
|
|
want := []byte(`{"app":"magpie"}`)
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("ETag", `"1-gzip"`)
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
zw := gzip.NewWriter(w)
|
|
zw.Write(want)
|
|
zw.Close()
|
|
}))
|
|
defer srv.Close()
|
|
d, err := newDAV(Config{URL: srv.URL + "/dav/"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, _, err := d.get(context.Background(), version{})
|
|
if err != nil || string(got) != string(want) {
|
|
t.Fatalf("read %q, %v", got, err)
|
|
}
|
|
}
|
|
|
|
// Reading the file as it is doesn't loosen the check that another
|
|
// computer wrote in between: on the same server, a write over the version
|
|
// read is refused once another write landed after the read, and the sync
|
|
// then merges over the other computer's version, losing none of it.
|
|
func TestSyncTeraCloudStillSeesOtherWrites(t *testing.T) {
|
|
fake := newApacheDAV()
|
|
srv := httptest.NewServer(fake)
|
|
defer srv.Close()
|
|
ctx := context.Background()
|
|
const name = "/dav/magpie/magpie.magpie-backup"
|
|
|
|
// the remote alone: a write over a version another write replaced
|
|
d, err := newDAV(Config{URL: srv.URL + "/dav/", User: "me", Password: "pw"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := d.put(ctx, []byte("one"), ""); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, v, err := d.get(ctx, version{})
|
|
if err != nil || v.ETag == "" {
|
|
t.Fatalf("read: %+v %v", v, err)
|
|
}
|
|
fake.mu.Lock()
|
|
fake.write(name, []byte("other computer"))
|
|
fake.mu.Unlock()
|
|
if _, err := d.put(ctx, []byte("two"), v.ETag); !errors.Is(err, errChanged) {
|
|
t.Fatalf("write over a replaced version: %v, want errChanged", err)
|
|
}
|
|
if got := string(fake.files[name]); got != "other computer" {
|
|
t.Fatalf("the other computer's write was overwritten: %q", got)
|
|
}
|
|
delete(fake.files, name)
|
|
delete(fake.etags, name)
|
|
|
|
// the whole sync: b's write lands between a's read and a's write
|
|
cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse", Keys: true, Agents: true}
|
|
a, b := newComputer(t), newComputer(t)
|
|
a.use(t)
|
|
provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k1"})
|
|
if err := Configure(cfg); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := Now(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
b.use(t)
|
|
if err := Configure(cfg); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := Now(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Chat: "https://api.moonshot.cn/v1", Key: "k2"})
|
|
// b's sealed file, made by a sync whose result is then taken back off
|
|
// the server, to land in the middle of a's
|
|
fake.mu.Lock()
|
|
before, beforeTag := fake.files[name], fake.etags[name]
|
|
fake.mu.Unlock()
|
|
if err := Now(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
fake.mu.Lock()
|
|
bs := fake.files[name]
|
|
fake.files[name], fake.etags[name] = before, beforeTag
|
|
fake.between = func() { fake.write(name, bs) }
|
|
refused := fake.refused
|
|
fake.mu.Unlock()
|
|
|
|
a.use(t)
|
|
provider.Save(provider.Provider{ID: "three", Name: "Three", Chat: "https://z/v1", Key: "k3"})
|
|
// dated to the moment, as b's push is: the file's own time, a tick of
|
|
// the kernel's clock behind, made a's newer providers read as the
|
|
// older (red 21 of 100 alone on a Linux box), as in TestSync
|
|
if at := time.Now(); os.Chtimes(provider.Path(), at, at) != nil {
|
|
t.Fatal("dating a's providers")
|
|
}
|
|
if err := Now(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if fake.refused != refused+1 {
|
|
t.Fatalf("a's write over b's: %d refused, want 1", fake.refused-refused)
|
|
}
|
|
// both changed the providers: the newer, a's, stays, and b's is kept
|
|
// aside and told — as any sync that saw the other's write does
|
|
n := Status().Notice
|
|
if n == nil || !slices.Contains(n.There, "providers") || n.Saved == "" {
|
|
t.Fatalf("a wrote over b's providers without seeing them: %+v", n)
|
|
}
|
|
saved, _ := filepath.Glob(filepath.Join(n.Saved, "*-server"+backup.Ext))
|
|
if len(saved) != 1 {
|
|
t.Fatalf("b's file kept aside: %v", saved)
|
|
}
|
|
kept, err := os.ReadFile(saved[0])
|
|
if err != nil || string(kept) != string(bs) {
|
|
t.Fatalf("the copy kept aside isn't b's file: %v", err)
|
|
}
|
|
}
|