db forward task 7: the worker protocol and ServeWorker, with the 5 s exit and the /proc self-view
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+677
−0
internal/dbreads/protocol.go+113 −0internal/dbreads/worker.go+291 −0internal/dbreads/worker_test.go+273 −0
diff --git a/internal/dbreads/protocol.go b/internal/dbreads/protocol.go| new file mode 100644 |
| index 000000000..52c35458d |
| --- /dev/null |
| +++ b/internal/dbreads/protocol.go |
| @@ -0,0 +1,113 @@ |
| +package dbreads |
| + |
| +import ( |
| + "encoding/binary" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| +) |
| + |
| +// ProtocolVersion is the worker protocol's version, answered in hello. A |
| +// worker that speaks another one never advertises anything (spec §7.1). |
| +const ProtocolVersion = 1 |
| + |
| +// Frames are one type byte, a four-byte big-endian length and the payload, |
| +// at most maxFrame bytes (spec §8.3: length-framed with a fixed maximum). |
| +const ( |
| + maxFrame = 1 << 20 |
| + fileFrameBytes = 256 << 10 |
| + outputFrameBytes = 64 << 10 |
| +) |
| + |
| +const ( |
| + frameHello byte = 'H' // agent: the readiness probe |
| + frameHelloReply byte = 'h' // worker: its version and its view of its sandbox |
| + frameHeader byte = 'P' // agent: the plan |
| + frameFile byte = 'F' // agent: file bytes, in the header's order |
| + frameReady byte = 'R' // worker: restored and checked; runs nothing yet |
| + frameRun byte = 'X' // agent: check B passed; the statement |
| + frameStop byte = 'S' // agent: end without running |
| + frameOutput byte = 'O' // worker: output bytes |
| + frameEnd byte = 'E' // worker: how it ended |
| +) |
| + |
| +var ( |
| + errFrameTooLarge = errors.New("dbreads: frame over the protocol's maximum") |
| + errProtocol = errors.New("dbreads: unexpected frame") |
| +) |
| + |
| +type hello struct { |
| + V int `json:"v"` |
| +} |
| + |
| +// HelloReply is the worker's answer to the probe: its protocol version and |
| +// what it can see of the box (spec §7.1). A sandboxed worker sees only the |
| +// loopback interface, an empty /data and no /etc/carlos. |
| +type HelloReply struct { |
| + V int `json:"v"` |
| + Interfaces []string `json:"interfaces"` |
| + DataEntries int `json:"data_entries"` |
| + EtcReadable bool `json:"etc_readable"` |
| + // Errors names every observation the worker could not make. A probe |
| + // fails on any: an unobserved sandbox is not a sandbox. |
| + Errors []string `json:"errors,omitempty"` |
| +} |
| + |
| +type planHeader struct { |
| + V int `json:"v"` |
| + Op string `json:"op"` |
| + Files []dbdoor.LTXFile `json:"files"` |
| + Target uint64 `json:"target"` |
| + MaxRestored int64 `json:"max_restored"` |
| +} |
| + |
| +type readyMsg struct { |
| + TXID uint64 `json:"txid"` |
| +} |
| + |
| +type runMsg struct { |
| + SQL string `json:"sql"` |
| +} |
| + |
| +type endMsg struct { |
| + Code string `json:"code"` |
| + Error string `json:"error"` |
| +} |
| + |
| +// writeFrame writes one frame in a single Write. |
| +func writeFrame(w io.Writer, typ byte, p []byte) error { |
| + if len(p) > maxFrame { |
| + return errFrameTooLarge |
| + } |
| + buf := make([]byte, 5, 5+len(p)) |
| + buf[0] = typ |
| + binary.BigEndian.PutUint32(buf[1:], uint32(len(p))) |
| + _, err := w.Write(append(buf, p...)) |
| + return err |
| +} |
| + |
| +func writeJSONFrame(w io.Writer, typ byte, v any) error { |
| + p, err := json.Marshal(v) |
| + if err != nil { |
| + return err |
| + } |
| + return writeFrame(w, typ, p) |
| +} |
| + |
| +func readFrame(r io.Reader) (byte, []byte, error) { |
| + var hdr [5]byte |
| + if _, err := io.ReadFull(r, hdr[:]); err != nil { |
| + return 0, nil, err |
| + } |
| + n := binary.BigEndian.Uint32(hdr[1:]) |
| + if n > maxFrame { |
| + return 0, nil, errFrameTooLarge |
| + } |
| + p := make([]byte, n) |
| + if _, err := io.ReadFull(r, p); err != nil { |
| + return 0, nil, err |
| + } |
| + return hdr[0], p, nil |
| +} |
diff --git a/internal/dbreads/worker.go b/internal/dbreads/worker.go| new file mode 100644 |
| index 000000000..cc5aadf80 |
| --- /dev/null |
| +++ b/internal/dbreads/worker.go |
| @@ -0,0 +1,291 @@ |
| +package dbreads |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/superfly/ltx" |
| + |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/dbquery" |
| +) |
| + |
| +// WorkerOptions are ServeWorker's settings. Production (RunWorker) sets |
| +// Scratch and leaves the rest zero. |
| +type WorkerOptions struct { |
| + // Scratch is where the read's private directory goes: /var/tmp, the |
| + // unit's own PrivateTmp, which systemd removes at stop. |
| + Scratch string |
| + // QueryTimeout is QueryTimeout when zero; Grace is WorkerExitGrace. |
| + QueryTimeout time.Duration |
| + Grace time.Duration |
| + // Exit ends the process (os.Exit when nil): the 5 s backstop for a step |
| + // that ignores its context (spec §8.3, codex 8). |
| + Exit func(code int) |
| + // Self is the hello's view of the sandbox (SelfView when nil). |
| + Self func() HelloReply |
| + // Restore is dbdoor.RestoreLocal when nil. Tests replace it. |
| + Restore func(ctx context.Context, c litestream.ReplicaClient, out string, target uint64) error |
| +} |
| + |
| +type frame struct { |
| + typ byte |
| + p []byte |
| +} |
| + |
| +var errAgentGone = errors.New("dbreads: the agent closed the connection") |
| + |
| +// ServeWorker is the worker's whole job on one connection (spec §8.3): a |
| +// hello, or a plan, its files, a restore, ready, then run or stop. One |
| +// goroutine reads the connection from the start; EOF or an error cancels |
| +// the one context everything runs under, and if the work has not returned |
| +// Grace later, the process exits. |
| +func ServeWorker(conn io.ReadWriter, opt WorkerOptions) error { |
| + if opt.QueryTimeout == 0 { |
| + opt.QueryTimeout = QueryTimeout |
| + } |
| + if opt.Grace == 0 { |
| + opt.Grace = WorkerExitGrace |
| + } |
| + if opt.Exit == nil { |
| + opt.Exit = os.Exit |
| + } |
| + if opt.Self == nil { |
| + opt.Self = SelfView |
| + } |
| + if opt.Restore == nil { |
| + opt.Restore = dbdoor.RestoreLocal |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + frames := make(chan frame) |
| + done := make(chan struct{}) |
| + defer close(done) |
| + go func() { |
| + defer close(frames) |
| + for { |
| + typ, p, err := readFrame(conn) |
| + if err != nil { |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-time.After(opt.Grace): |
| + opt.Exit(3) |
| + } |
| + return |
| + } |
| + select { |
| + case frames <- frame{typ, p}: |
| + case <-done: |
| + return |
| + } |
| + } |
| + }() |
| + next := func() (frame, error) { |
| + select { |
| + case f, ok := <-frames: |
| + if !ok { |
| + return frame{}, errAgentGone |
| + } |
| + return f, nil |
| + case <-ctx.Done(): |
| + return frame{}, errAgentGone |
| + } |
| + } |
| + end := func(code string, err error) error { |
| + msg := endMsg{Code: code} |
| + if err != nil { |
| + msg.Error = err.Error() |
| + } |
| + return writeJSONFrame(conn, frameEnd, msg) |
| + } |
| + |
| + f, err := next() |
| + if err != nil { |
| + return err |
| + } |
| + switch f.typ { |
| + case frameHello: |
| + var h hello |
| + if json.Unmarshal(f.p, &h) != nil { |
| + return errProtocol |
| + } |
| + return writeJSONFrame(conn, frameHelloReply, opt.Self()) |
| + case frameHeader: |
| + default: |
| + return errProtocol |
| + } |
| + var h planHeader |
| + if err := json.Unmarshal(f.p, &h); err != nil || h.V != ProtocolVersion || h.Op != OpQuery { |
| + return errProtocol |
| + } |
| + dir, err := os.MkdirTemp(opt.Scratch, "dbread-") |
| + if err != nil { |
| + return err |
| + } |
| + defer os.RemoveAll(dir) |
| + root := filepath.Join(dir, "replica") |
| + for _, lf := range h.Files { |
| + path := litestream.LTXFilePath(root, lf.Level, ltx.TXID(lf.MinTXID), ltx.TXID(lf.MaxTXID)) |
| + if err := receiveFile(next, path, lf.Size); err != nil { |
| + if errors.Is(err, errAgentGone) { |
| + return err |
| + } |
| + return end(CodeCheckFailed, err) |
| + } |
| + } |
| + db := filepath.Join(dir, "copy.db") |
| + if err := opt.Restore(ctx, lsfile.NewReplicaClient(root), db, h.Target); err != nil { |
| + if ctx.Err() != nil { |
| + return errAgentGone |
| + } |
| + return end(CodeCheckFailed, err) |
| + } |
| + if st, err := os.Stat(db); err != nil || st.Size() > h.MaxRestored { |
| + return end(CodeTooLarge, err) |
| + } |
| + if err := writeJSONFrame(conn, frameReady, readyMsg{TXID: h.Target}); err != nil { |
| + return err |
| + } |
| + f, err = next() |
| + if err != nil { |
| + return err |
| + } |
| + switch f.typ { |
| + case frameStop: |
| + return nil |
| + case frameRun: |
| + default: |
| + return errProtocol |
| + } |
| + var run runMsg |
| + if err := json.Unmarshal(f.p, &run); err != nil { |
| + return errProtocol |
| + } |
| + qctx, qcancel := context.WithTimeout(ctx, opt.QueryTimeout) |
| + defer qcancel() |
| + out := &frameWriter{w: conn} |
| + qerr := dbquery.RunContext(qctx, out, db, run.SQL, dbquery.Options{Immutable: true}) |
| + if ferr := out.flush(); ferr != nil { |
| + return ferr |
| + } |
| + switch { |
| + case qerr == nil: |
| + return end("", nil) |
| + case errors.Is(qctx.Err(), context.DeadlineExceeded): |
| + return end(CodeTimeout, nil) |
| + case ctx.Err() != nil: |
| + return errAgentGone |
| + } |
| + return end(CodeSQLError, qerr) |
| +} |
| + |
| +// receiveFile writes exactly size bytes of file frames to path, refusing a |
| +// file larger than its header said (spec §8.3). |
| +func receiveFile(next func() (frame, error), path string, size int64) error { |
| + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| + return err |
| + } |
| + out, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) |
| + if err != nil { |
| + return err |
| + } |
| + defer out.Close() |
| + var got int64 |
| + for got < size { |
| + f, err := next() |
| + if err != nil { |
| + return err |
| + } |
| + if f.typ != frameFile { |
| + return errProtocol |
| + } |
| + if got+int64(len(f.p)) > size { |
| + return fmt.Errorf("dbreads: %s is larger than its header said (%d bytes)", filepath.Base(path), size) |
| + } |
| + if _, err := out.Write(f.p); err != nil { |
| + return err |
| + } |
| + got += int64(len(f.p)) |
| + } |
| + return out.Close() |
| +} |
| + |
| +// frameWriter frames the query's output in outputFrameBytes pieces. |
| +type frameWriter struct { |
| + w io.Writer |
| + buf []byte |
| +} |
| + |
| +func (f *frameWriter) Write(p []byte) (int, error) { |
| + f.buf = append(f.buf, p...) |
| + for len(f.buf) >= outputFrameBytes { |
| + if err := writeFrame(f.w, frameOutput, f.buf[:outputFrameBytes]); err != nil { |
| + return 0, err |
| + } |
| + f.buf = f.buf[outputFrameBytes:] |
| + } |
| + return len(p), nil |
| +} |
| + |
| +func (f *frameWriter) flush() error { |
| + if len(f.buf) == 0 { |
| + return nil |
| + } |
| + err := writeFrame(f.w, frameOutput, f.buf) |
| + f.buf = nil |
| + return err |
| +} |
| + |
| +// SelfView is what the worker can see of the box: in the unit, the loopback |
| +// interface alone, an empty /data and no readable /etc/carlos. |
| +// |
| +// Interfaces come from /proc/self/net/dev, this process's own network |
| +// namespace. net.Interfaces cannot be used: on Linux it opens an AF_NETLINK |
| +// socket, which the unit's RestrictAddressFamilies=AF_UNIX refuses, and an |
| +// empty list would read as "no network" (plan review finding 1). Every |
| +// observation that fails is reported in Errors, and a probe fails on any. |
| +func SelfView() HelloReply { |
| + h := HelloReply{V: ProtocolVersion} |
| + if raw, err := os.ReadFile("/proc/self/net/dev"); err != nil { |
| + h.Errors = append(h.Errors, "interfaces: "+err.Error()) |
| + } else { |
| + h.Interfaces = parseNetDev(string(raw)) |
| + } |
| + switch ents, err := os.ReadDir("/data"); { |
| + case err == nil: |
| + h.DataEntries = len(ents) |
| + case !errors.Is(err, os.ErrNotExist): |
| + h.Errors = append(h.Errors, "/data: "+err.Error()) |
| + } |
| + if f, err := os.Open("/etc/carlos/host.env"); err == nil { |
| + f.Close() |
| + h.EtcReadable = true |
| + } |
| + return h |
| +} |
| + |
| +// parseNetDev reads /proc/net/dev's interface names: two header lines, then |
| +// one "<name>: <counters>" line per interface. |
| +func parseNetDev(s string) []string { |
| + var out []string |
| + for i, line := range strings.Split(s, "\n") { |
| + if i < 2 { |
| + continue |
| + } |
| + name, _, ok := strings.Cut(line, ":") |
| + if name = strings.TrimSpace(name); ok && name != "" { |
| + out = append(out, name) |
| + } |
| + } |
| + return out |
| +} |
diff --git a/internal/dbreads/worker_test.go b/internal/dbreads/worker_test.go| new file mode 100644 |
| index 000000000..2e4882aa1 |
| --- /dev/null |
| +++ b/internal/dbreads/worker_test.go |
| @@ -0,0 +1,273 @@ |
| +package dbreads |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/superfly/ltx" |
| + |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| + "github.com/carlosframework/platform/internal/dbquery" |
| +) |
| + |
| +// workerPipe starts ServeWorker on one end of a pipe and returns the other. |
| +// Not acceptance: the units are Task 15's. |
| +func workerPipe(t *testing.T, opt WorkerOptions) (net.Conn, <-chan error) { |
| + t.Helper() |
| + agent, worker := net.Pipe() |
| + if opt.Scratch == "" { |
| + opt.Scratch = t.TempDir() |
| + } |
| + if opt.Exit == nil { |
| + opt.Exit = func(int) { t.Error("the worker asked to exit the process") } |
| + } |
| + done := make(chan error, 1) |
| + go func() { |
| + err := ServeWorker(worker, opt) |
| + worker.Close() |
| + done <- err |
| + }() |
| + t.Cleanup(func() { agent.Close() }) |
| + return agent, done |
| +} |
| + |
| +// sendPlan sends a header and the planned files of dir's replica. |
| +func sendPlan(t *testing.T, conn net.Conn, dir string) dbdoor.RestorePlan { |
| + t.Helper() |
| + rd := lsfile.NewReplicaClient(dir) |
| + plan, err := dbdoor.PlanFrom(context.Background(), rd, time.Time{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := writeJSONFrame(conn, frameHeader, planHeader{V: ProtocolVersion, Op: OpQuery, Files: plan.Planned, Target: plan.TXID, MaxRestored: DefaultMaxRestored}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, f := range plan.Planned { |
| + rc, err := rd.OpenLTXFile(context.Background(), f.Level, ltx.TXID(f.MinTXID), ltx.TXID(f.MaxTXID), 0, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _ := io.ReadAll(rc) |
| + rc.Close() |
| + if err := writeFrame(conn, frameFile, body); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return plan |
| +} |
| + |
| +func readTyped(t *testing.T, conn net.Conn, want byte, v any) { |
| + t.Helper() |
| + typ, p, err := readFrame(conn) |
| + if err != nil || typ != want { |
| + t.Fatalf("frame %q (%s), want %q: %v", typ, p, want, err) |
| + } |
| + if v != nil { |
| + if err := json.Unmarshal(p, v); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +func TestWorkerAnswersHelloWithItsSelfView(t *testing.T) { |
| + t.Parallel() |
| + conn, done := workerPipe(t, WorkerOptions{Self: func() HelloReply { |
| + return HelloReply{V: ProtocolVersion, Interfaces: []string{"lo"}} |
| + }}) |
| + if err := writeJSONFrame(conn, frameHello, hello{V: ProtocolVersion}); err != nil { |
| + t.Fatal(err) |
| + } |
| + var h HelloReply |
| + readTyped(t, conn, frameHelloReply, &h) |
| + if h.V != ProtocolVersion || len(h.Interfaces) != 1 { |
| + t.Fatalf("hello = %+v", h) |
| + } |
| + if err := <-done; err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// The default self-view reads /proc/self/net/dev, which needs no socket |
| +// (plan review finding 1). Mutation: SelfView back on net.Interfaces makes |
| +// TestRootDBReadReadiness's baseline red inside the installed unit. |
| +func TestParseNetDev(t *testing.T) { |
| + t.Parallel() |
| + only := "Inter-| Receive\n face |bytes\n lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" |
| + if got := parseNetDev(only); len(got) != 1 || got[0] != "lo" { |
| + t.Fatalf("%q", got) |
| + } |
| + two := only + " eth0: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n" |
| + if got := parseNetDev(two); len(got) != 2 || got[1] != "eth0" { |
| + t.Fatalf("%q", got) |
| + } |
| + if got := SelfView(); len(got.Errors) != 0 && !strings.Contains(strings.Join(got.Errors, " "), "/proc") { |
| + t.Fatalf("SelfView on this machine: %+v", got) |
| + } |
| +} |
| + |
| +func TestWorkerRestoresThenRunsOnlyWhenTold(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + dbdoortest.Replicate(t, dir, 3) |
| + conn, done := workerPipe(t, WorkerOptions{}) |
| + plan := sendPlan(t, conn, dir) |
| + var ready readyMsg |
| + readTyped(t, conn, frameReady, &ready) |
| + if ready.TXID != plan.TXID { |
| + t.Fatalf("ready at %d, planned %d", ready.TXID, plan.TXID) |
| + } |
| + if err := writeJSONFrame(conn, frameRun, runMsg{SQL: "SELECT count(*) AS n FROM t"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + var out bytes.Buffer |
| + for { |
| + typ, p, err := readFrame(conn) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if typ == frameOutput { |
| + out.Write(p) |
| + continue |
| + } |
| + var end endMsg |
| + if typ != frameEnd || json.Unmarshal(p, &end) != nil || end.Code != "" { |
| + t.Fatalf("end %q %s", typ, p) |
| + } |
| + break |
| + } |
| + if out.String() != "n\n30\n" { |
| + t.Fatalf("output %q", out.String()) |
| + } |
| + if err := <-done; err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestWorkerStopRunsNothing(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + dbdoortest.Replicate(t, dir, 1) |
| + conn, done := workerPipe(t, WorkerOptions{}) |
| + sendPlan(t, conn, dir) |
| + readTyped(t, conn, frameReady, nil) |
| + if err := writeFrame(conn, frameStop, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := <-done; err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// The worker refuses a file larger than its header said (spec §8.3). |
| +func TestWorkerRefusesAFileLargerThanItsHeader(t *testing.T) { |
| + t.Parallel() |
| + conn, done := workerPipe(t, WorkerOptions{}) |
| + files := []dbdoor.LTXFile{{Level: 0, MinTXID: 1, MaxTXID: 1, Size: 4}} |
| + if err := writeJSONFrame(conn, frameHeader, planHeader{V: ProtocolVersion, Op: OpQuery, Files: files, Target: 1, MaxRestored: DefaultMaxRestored}); err != nil { |
| + t.Fatal(err) |
| + } |
| + go writeFrame(conn, frameFile, []byte("12345")) |
| + var end endMsg |
| + readTyped(t, conn, frameEnd, &end) |
| + if end.Code != CodeCheckFailed { |
| + t.Fatalf("end = %+v", end) |
| + } |
| + <-done |
| +} |
| + |
| +func TestWorkerSQLErrorIsSQLitesText(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + dbdoortest.Replicate(t, dir, 1) |
| + conn, done := workerPipe(t, WorkerOptions{}) |
| + sendPlan(t, conn, dir) |
| + readTyped(t, conn, frameReady, nil) |
| + writeJSONFrame(conn, frameRun, runMsg{SQL: "SELECT * FROM nope"}) |
| + var end endMsg |
| + readTyped(t, conn, frameEnd, &end) |
| + if end.Code != CodeSQLError || end.Error == "" { |
| + t.Fatalf("end = %+v", end) |
| + } |
| + if err := dbquery.CheckSQL("SELECT * FROM nope"); err != nil { |
| + t.Fatal(err) |
| + } |
| + <-done |
| +} |
| + |
| +func TestWorkerQueryTimeout(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + dbdoortest.Replicate(t, dir, 1) |
| + conn, done := workerPipe(t, WorkerOptions{QueryTimeout: 50 * time.Millisecond}) |
| + sendPlan(t, conn, dir) |
| + readTyped(t, conn, frameReady, nil) |
| + writeJSONFrame(conn, frameRun, runMsg{SQL: "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c) SELECT count(*) FROM c"}) |
| + for { |
| + typ, p, err := readFrame(conn) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if typ == frameEnd { |
| + var end endMsg |
| + json.Unmarshal(p, &end) |
| + if end.Code != CodeTimeout { |
| + t.Fatalf("end = %+v", end) |
| + } |
| + break |
| + } |
| + } |
| + <-done |
| +} |
| + |
| +// The worker stops when its agent goes (spec §8.3, codex 8): EOF cancels the |
| +// context, and a step that ignores the context is ended by the exit after |
| +// the grace. |
| +func TestWorkerExitsWhenTheAgentGoesMidRestore(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + dbdoortest.Replicate(t, dir, 1) |
| + var exited atomic.Int32 |
| + hang := make(chan struct{}) |
| + t.Cleanup(func() { close(hang) }) |
| + conn, _ := workerPipe(t, WorkerOptions{ |
| + Grace: 50 * time.Millisecond, |
| + Exit: func(code int) { exited.Store(int32(code)) }, |
| + Restore: func(context.Context, litestream.ReplicaClient, string, uint64) error { |
| + <-hang // a compaction that ignores its context |
| + return nil |
| + }, |
| + }) |
| + sendPlan(t, conn, dir) |
| + conn.Close() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for exited.Load() == 0 && time.Now().Before(deadline) { |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + if exited.Load() == 0 { |
| + t.Fatal("the worker outlived its agent past the grace") |
| + } |
| +} |
| + |
| +func TestWorkerCheckFailsAMissingFile(t *testing.T) { |
| + t.Parallel() |
| + conn, done := workerPipe(t, WorkerOptions{}) |
| + if err := writeJSONFrame(conn, frameHeader, planHeader{V: ProtocolVersion, Op: OpQuery, Files: nil, Target: 9, MaxRestored: DefaultMaxRestored}); err != nil { |
| + t.Fatal(err) |
| + } |
| + var end endMsg |
| + readTyped(t, conn, frameEnd, &end) |
| + if end.Code != CodeCheckFailed { |
| + t.Fatalf("an empty plan = %+v", end) |
| + } |
| + <-done |
| +} |