region HA P1a Task 10: fix round 1 (final sync budget after the files publish; incomplete snapshots retried; snapshots beside the 1 s cadence; no manifest read on a keep or first wake)
- releaseHAClean starts the final sync's own 30 s budget after Final. - A snapshot records its digest only after a complete, committed pass. - A snapshot reads the tree beside the platform passes (one publisher, commits serialized); Run waits for it before returning. - The HA restore opens the wake's publisher on the manifest it holds (hostfiles.Baseline/OpenBaseline): none on a first wake, the one it read on a restore, the one the release record keeps on a keep (only when its hash is the marker's files_gen). Whole-wake request counts. - The FIFO test moves to a linux-tagged file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+592
−68
internal/activator/backend_unit.go+2 −2internal/activator/hafiles.go+137 −27internal/activator/hafiles_test.go+126 −0internal/activator/harelease.go+20 −9internal/activator/harelease_linux_test.go+23 −0internal/activator/harelease_test.go+114 −19internal/activator/hawake.go+34 −1internal/hafresh/keep.go+13 −0internal/hostfiles/hostfiles_test.go+58 −0internal/hostfiles/publisher.go+46 −5internal/hostfiles/restore.go+19 −5
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index dea58c65e..efd59cbcb 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -365,9 +365,9 @@ func (b *SplitBackend) haReleaseBase(rt registry.Route) hafresh.Marker { |
| } |
| return hafresh.Marker{V: 1} |
| } |
| -func (b *SplitBackend) writeHARecord(rt registry.Route, m hafresh.Marker) error { |
| +func (b *SplitBackend) writeHARecord(rt registry.Route, m hafresh.Marker, files *hafresh.FilesBaseline) error { |
| if r, ok := b.pick(rt).(haReleaser); ok { |
| - return r.writeHARecord(rt, m) |
| + return r.writeHARecord(rt, m, files) |
| } |
| return errors.New("this row's backend keeps no release record") |
| } |
diff --git a/internal/activator/hafiles.go b/internal/activator/hafiles.go| index cc090f94c..3f240f97e 100644 |
| --- a/internal/activator/hafiles.go |
| +++ b/internal/activator/hafiles.go |
| @@ -11,6 +11,7 @@ import ( |
| "sync" |
| "time" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/hostfiles" |
| "github.com/carlosframework/platform/internal/instancefs" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -46,9 +47,20 @@ var haTrio = map[string]bool{"instance.key": true, "report.token": true} |
| // lists the files directory's root and reads nothing else. |
| func trioOnly(rel string, isDir bool) bool { return isDir || !haTrio[rel] } |
| +// snapshotSkip is the snapshot pass's skip: the trio, which the platform |
| +// pass owns. A snapshot runs beside platform passes, so it neither stages |
| +// nor tombstones a trio file one of them may be publishing. |
| +func snapshotSkip(rel string, isDir bool) bool { return !isDir && haTrio[rel] } |
| + |
| +// syncFilesAt is the one sync of the files tree (a test seam). |
| +var syncFilesAt = hostfiles.SyncDirAt |
| + |
| // hostFiles is one HA host's files publisher, owned by its awake entry. |
| -// Every pass holds mu, so Run's passes, PublishPlatformNow and Final never |
| -// interleave. |
| +// One publisher, so every commit is serialized by it. mu guards the |
| +// pass state and is held by a platform pass and by a snapshot's staging |
| +// of the platform items and its commit, never across a snapshot's tree |
| +// read, so the trio's cadence holds while an app snapshot runs. snapMu |
| +// admits one snapshot at a time, and Final takes it before mu. |
| type hostFiles struct { |
| pub *hostfiles.Publisher |
| paths instancePaths |
| @@ -57,8 +69,9 @@ type hostFiles struct { |
| platformEvery, snapshotEvery time.Duration |
| + snapMu sync.Mutex |
| mu sync.Mutex |
| - lastDigest string // the tree digest the last full publish committed |
| + lastDigest string // the tree digest of the last complete, committed full publish |
| final bool // Final has run: no pass publishes again |
| } |
| @@ -66,10 +79,63 @@ type hostFiles struct { |
| // last write, so nothing publishes once the final publish has been made. |
| var errFilesFinal = errors.New("the host's files were published for the last time") |
| -// openHostFiles opens rt's files publisher over the manifest under |
| -// filesPrefix (one GET). The store is FilesStore, the one the HA restore |
| -// reads (lease.NewFilesStore in production). Only an HA host in the nested |
| -// layout has one. |
| +// newHostFiles is rt's publisher over pub. |
| +func (b *ExecBackend) newHostFiles(rt registry.Route, pub *hostfiles.Publisher) *hostFiles { |
| + return &hostFiles{pub: pub, paths: b.pathsFor(rt), host: rt.Host, reg: b.Registry, |
| + platformEvery: haPlatformEvery, snapshotEvery: haSnapshotEvery} |
| +} |
| + |
| +// stageWakeFiles opens this wake's files publisher on a manifest the HA |
| +// restore already holds (hostfiles.OpenBaseline, no read) and keeps it for |
| +// the wake's entry (openHostFiles). A restore that holds none stages |
| +// nothing, and the entry's open reads the manifest. Nil FilesStore stages |
| +// nothing either: the open then fails the wake. |
| +func (b *ExecBackend) stageWakeFiles(rt registry.Route, base hostfiles.Baseline) { |
| + if b.FilesStore == nil { |
| + return |
| + } |
| + pub, err := hostfiles.OpenBaseline(b.FilesStore, b.filesPrefix(rt.Host), base) |
| + if err != nil { |
| + log.Printf("activator: %s: files: %v (the publisher reads the manifest again)", rt.Host, err) |
| + return |
| + } |
| + b.haWakes.setFiles(rt.Host, b.newHostFiles(rt, pub)) |
| +} |
| + |
| +// stageKeptFiles stages a kept wake's publisher on the manifest its local |
| +// release record carries (none: the prefix held no manifest), but only |
| +// when that is the revision the marker names (gen, which carries the |
| +// body's hash): the record is on ground the tenant can write, and the |
| +// marker is not. Anything else stages nothing, and the entry's open reads |
| +// the manifest. |
| +func (b *ExecBackend) stageKeptFiles(rt registry.Route, rec hafresh.LocalRecord, gen string) { |
| + if b.FilesStore == nil { |
| + return |
| + } |
| + base := hostfiles.Baseline{} |
| + if rec.Files != nil { |
| + base = hostfiles.Baseline{Found: true, Body: rec.Files.Body, ETag: rec.Files.ETag} |
| + } |
| + pub, err := hostfiles.OpenBaseline(b.FilesStore, b.filesPrefix(rt.Host), base) |
| + if err != nil || pub.Gen() != gen { |
| + log.Printf("activator: %s: files: the release record's manifest is not the marker's (%v); the publisher reads it again", rt.Host, err) |
| + return |
| + } |
| + b.haWakes.setFiles(rt.Host, b.newHostFiles(rt, pub)) |
| +} |
| + |
| +// wakeFiles is the files publisher this wake's HA restore opened for the |
| +// host, if it opened one: the one the entry will own, which a launch |
| +// before the entry exists publishes through. |
| +func (b *ExecBackend) wakeFiles(host string) (*hostFiles, bool) { |
| + return b.haWakes.files(host) |
| +} |
| + |
| +// openHostFiles is rt's files publisher for its entry: the one this |
| +// wake's HA restore opened on the manifest it held (no request), else one |
| +// opened by reading the manifest (one GET). The store is FilesStore, the |
| +// one the HA restore reads (lease.NewFilesStore in production). Only an |
| +// HA host in the nested layout has one. |
| func (b *ExecBackend) openHostFiles(ctx context.Context, rt registry.Route) (*hostFiles, error) { |
| if b.FilesStore == nil { |
| return nil, errors.New("no files store configured") |
| @@ -78,24 +144,33 @@ func (b *ExecBackend) openHostFiles(ctx context.Context, rt registry.Route) (*ho |
| if p.layout != LayoutNested { |
| return nil, fmt.Errorf("the row's layout is %s, not nested", p.layout) |
| } |
| + if f, ok := b.haWakes.takeFiles(rt.Host); ok { |
| + return f, nil |
| + } |
| pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host)) |
| if err != nil { |
| return nil, err |
| } |
| - return &hostFiles{pub: pub, paths: p, host: rt.Host, reg: b.Registry, |
| - platformEvery: haPlatformEvery, snapshotEvery: haSnapshotEvery}, nil |
| + return b.newHostFiles(rt, pub), nil |
| } |
| // Run publishes until ctx ends: the trio and the wake state every |
| -// platformEvery when they changed, the whole tree every snapshotEvery when |
| -// its digest changed. A failed pass is logged and retried at the next |
| -// tick; a superseded manifest (another writer) stops Run, and Final then |
| -// fails, so the release is not clean. |
| +// platformEvery when they changed, and the whole tree every snapshotEvery |
| +// when its digest changed. A snapshot runs beside the platform passes, |
| +// one at a time, and Run waits for it before it returns. A failed pass is |
| +// logged and retried at the next tick; a superseded manifest (another |
| +// writer) stops Run, and Final then fails, so the release is not clean. |
| func (f *hostFiles) Run(ctx context.Context) { |
| platform := time.NewTicker(f.platformEvery) |
| defer platform.Stop() |
| snapshot := time.NewTicker(f.snapshotEvery) |
| defer snapshot.Stop() |
| + var snapDone chan error // the running snapshot's answer; nil when none runs |
| + defer func() { |
| + if snapDone != nil { |
| + <-snapDone |
| + } |
| + }() |
| failing := "" |
| for { |
| var err error |
| @@ -105,7 +180,13 @@ func (f *hostFiles) Run(ctx context.Context) { |
| case <-platform.C: |
| err = f.PublishPlatformNow(ctx) |
| case <-snapshot.C: |
| - err = f.publishSnapshot(ctx) |
| + if snapDone == nil { |
| + snapDone = make(chan error, 1) |
| + go func(done chan<- error) { done <- f.publishSnapshot(ctx) }(snapDone) |
| + } |
| + continue |
| + case err = <-snapDone: |
| + snapDone = nil |
| } |
| if ctx.Err() != nil || errors.Is(err, errFilesFinal) { |
| return |
| @@ -133,7 +214,7 @@ func (f *hostFiles) PublishPlatformNow(ctx context.Context) error { |
| if f.final { |
| return errFilesFinal |
| } |
| - if _, _, err := f.syncLocked(ctx, trioOnly); err != nil { |
| + if _, _, err := f.syncFiles(ctx, trioOnly); err != nil { |
| return err |
| } |
| if err := f.stageItemsLocked(ctx); err != nil { |
| @@ -143,28 +224,45 @@ func (f *hostFiles) PublishPlatformNow(ctx context.Context) error { |
| return err |
| } |
| -// publishSnapshot is the snapshot pass: the whole tree and the platform |
| -// items, skipped when the tree's metadata digest is the one the last full |
| -// publish committed (where the digest cannot be read, it always runs). |
| +// publishSnapshot is the snapshot pass: the tree but the trio, then the |
| +// platform items, committed. It is skipped when the tree's metadata |
| +// digest is the one the last complete, committed snapshot recorded (where |
| +// the digest cannot be read, it always runs). A pass that was not |
| +// complete (a file unreadable, replaced or torn, say) records nothing, so |
| +// the next snapshot runs again even if no metadata changed. The tree is |
| +// read without mu, so platform passes go on meanwhile. |
| func (f *hostFiles) publishSnapshot(ctx context.Context) error { |
| + f.snapMu.Lock() |
| + defer f.snapMu.Unlock() |
| f.mu.Lock() |
| - defer f.mu.Unlock() |
| - if f.final { |
| + final, last := f.final, f.lastDigest |
| + f.mu.Unlock() |
| + if final { |
| return errFilesFinal |
| } |
| digest, derr := treeDigest(hostFilesDir(f.paths, f.host), f.paths.envFile) |
| - if derr == nil && digest != "" && digest == f.lastDigest { |
| + if derr == nil && digest != "" && digest == last { |
| return nil |
| } |
| - if _, _, err := f.syncLocked(ctx, nil); err != nil { |
| + st, _, err := f.syncFiles(ctx, snapshotSkip) |
| + if err != nil { |
| return err |
| } |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.final { |
| + return errFilesFinal |
| + } |
| if err := f.stageItemsLocked(ctx); err != nil { |
| return err |
| } |
| if _, err := f.pub.Commit(ctx); err != nil { |
| return err |
| } |
| + if !st.Complete() { |
| + return fmt.Errorf("the snapshot was not complete (too large %q, not regular %q, unreadable %q, replaced %q, torn %q); the next one runs again", |
| + st.TooLarge, st.NotRegular, st.Unreadable, st.Retry, st.Torn) |
| + } |
| if derr == nil { |
| f.lastDigest = digest |
| } |
| @@ -179,10 +277,12 @@ func (f *hostFiles) publishSnapshot(ctx context.Context) error { |
| // manifest holds no file, since absence proves nothing about one it does. |
| // After Final no pass publishes. |
| func (f *hostFiles) Final(ctx context.Context) (gen string, complete bool, err error) { |
| + f.snapMu.Lock() |
| + defer f.snapMu.Unlock() |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.final = true |
| - st, present, err := f.syncLocked(ctx, nil) |
| + st, present, err := f.syncFiles(ctx, nil) |
| if err != nil { |
| return f.pub.Gen(), false, err |
| } |
| @@ -204,11 +304,21 @@ func (f *hostFiles) Final(ctx context.Context) (gen string, complete bool, err e |
| return f.pub.Gen(), complete, nil |
| } |
| -// syncLocked syncs the files directory (skip as SyncDirAt takes it), |
| +// baseline is the manifest the publisher last committed, as the local |
| +// release record keeps it: nil when there is none. |
| +func (f *hostFiles) baseline() *hafresh.FilesBaseline { |
| + b := f.pub.Baseline() |
| + if !b.Found { |
| + return nil |
| + } |
| + return &hafresh.FilesBaseline{Body: b.Body, ETag: b.ETag} |
| +} |
| + |
| +// syncFiles syncs the files directory (skip as SyncDirAt takes it), |
| // opened beneath the instance directory without following a link: the |
| // directory is the tenant's to write. present is false when there is no |
| -// files directory, and nothing is staged then. f.mu is held. |
| -func (f *hostFiles) syncLocked(ctx context.Context, skip func(string, bool) bool) (hostfiles.SyncStats, bool, error) { |
| +// files directory, and nothing is staged then. |
| +func (f *hostFiles) syncFiles(ctx context.Context, skip func(string, bool) bool) (hostfiles.SyncStats, bool, error) { |
| root, err := instancefs.OpenDirBeneath(f.paths.dataDir, f.host) |
| if errors.Is(err, fs.ErrNotExist) { |
| return hostfiles.SyncStats{}, false, nil |
| @@ -217,7 +327,7 @@ func (f *hostFiles) syncLocked(ctx context.Context, skip func(string, bool) bool |
| return hostfiles.SyncStats{}, false, fmt.Errorf("open the files directory: %w", err) |
| } |
| defer root.Close() |
| - st, err := hostfiles.SyncDirAt(ctx, f.pub, root, skip) |
| + st, err := syncFilesAt(ctx, f.pub, root, skip) |
| return st, true, err |
| } |
diff --git a/internal/activator/hafiles_test.go b/internal/activator/hafiles_test.go| index e8e944439..2e7ed0996 100644 |
| --- a/internal/activator/hafiles_test.go |
| +++ b/internal/activator/hafiles_test.go |
| @@ -3,9 +3,12 @@ package activator |
| import ( |
| "context" |
| "os" |
| + "sync" |
| + "sync/atomic" |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/hostfiles" |
| ) |
| @@ -66,3 +69,126 @@ func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| go f2.Run(ctx2) |
| waitFor(t, "the snapshot of a.txt", func() bool { return load().Entries["a.txt"].Object != "" }) |
| } |
| + |
| +// A snapshot that was not complete records no digest: the next one runs |
| +// again even though no metadata changed, and publishes the file. |
| +func TestIncompleteSnapshotRunsAgainOverAnUnchangedTree(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com") |
| + writeFiles(t, b, rt, map[string]string{"a.txt": "app"}) |
| + f, err := b.openHostFiles(context.Background(), rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.platformEvery, f.snapshotEvery = time.Hour, 100*time.Millisecond |
| + var calls atomic.Int32 |
| + prev := syncFilesAt |
| + syncFilesAt = func(ctx context.Context, p *hostfiles.Publisher, dir *os.File, skip func(string, bool) bool) (hostfiles.SyncStats, error) { |
| + if calls.Add(1) == 1 { // a transient read failure: nothing staged, the file reported unreadable |
| + return hostfiles.SyncStats{Unreadable: []string{"a.txt"}}, nil |
| + } |
| + return prev(ctx, p, dir, skip) |
| + } |
| + t.Cleanup(func() { syncFilesAt = prev }) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + go f.Run(ctx) |
| + waitFor(t, "a.txt published by a later snapshot", func() bool { |
| + m, _, err := hostfiles.Load(context.Background(), b.FilesStore, b.filesPrefix(rt.Host)) |
| + return err == nil && m.Entries["a.txt"].Object != "" |
| + }) |
| + if calls.Load() < 2 { |
| + t.Fatalf("%d syncs", calls.Load()) |
| + } |
| +} |
| + |
| +// The platform cadence holds while an app snapshot runs: with a snapshot |
| +// blocked mid-read, a changed env file still publishes within the second, |
| +// and Run waits for the snapshot before it returns. |
| +func TestPlatformPublishesDuringASnapshot(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com") |
| + writeFiles(t, b, rt, map[string]string{"a.txt": "app"}) |
| + f, err := b.openHostFiles(context.Background(), rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.platformEvery, f.snapshotEvery = 100*time.Millisecond, 50*time.Millisecond |
| + blocked, unblock := make(chan struct{}), make(chan struct{}) |
| + var once sync.Once |
| + prev := syncFilesAt |
| + syncFilesAt = func(ctx context.Context, p *hostfiles.Publisher, dir *os.File, skip func(string, bool) bool) (hostfiles.SyncStats, error) { |
| + if skip != nil && !skip("a.txt", false) { // the snapshot's read, not the trio's |
| + once.Do(func() { close(blocked) }) |
| + <-unblock |
| + } |
| + return prev(ctx, p, dir, skip) |
| + } |
| + t.Cleanup(func() { syncFilesAt = prev }) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + ran := make(chan struct{}) |
| + go func() { defer close(ran); f.Run(ctx) }() |
| + select { |
| + case <-blocked: |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("no snapshot started") |
| + } |
| + if err := os.WriteFile(b.pathsFor(rt).envFile, []byte("CARLOS_INSTANCE_KEY=k2\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + deadline := time.Now().Add(2 * time.Second) |
| + for { |
| + m, _, err := hostfiles.Load(context.Background(), b.FilesStore, b.filesPrefix(rt.Host)) |
| + if err == nil { |
| + if _, ok := m.Platform[hostfiles.EnvItem]; ok { |
| + body, err := hostfiles.ReadPlatform(context.Background(), b.FilesStore, b.filesPrefix(rt.Host), m, hostfiles.EnvItem, nil) |
| + if err == nil && string(body) == "CARLOS_INSTANCE_KEY=k2\n" { |
| + break |
| + } |
| + } |
| + } |
| + if time.Now().After(deadline) { |
| + close(unblock) |
| + t.Fatal("the env did not publish while a snapshot ran") |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + cancel() |
| + select { |
| + case <-ran: |
| + t.Fatal("Run returned with its snapshot still running") |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + close(unblock) |
| + select { |
| + case <-ran: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("Run did not return once its snapshot finished") |
| + } |
| +} |
| + |
| +// A kept wake continues from the manifest its release record carries only |
| +// when that is the revision the marker names: a record whose bytes are not |
| +// (the tenant can write it) stages nothing, and the entry reads the |
| +// manifest instead. |
| +func TestKeptFilesNeedTheMarkersManifest(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com") |
| + publishManifest(t, b, rt, map[string]string{"a.txt": "1"}, "") |
| + pub, err := hostfiles.Open(context.Background(), b.FilesStore, b.filesPrefix(rt.Host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + base, gen := pub.Baseline(), pub.Gen() |
| + forged := append([]byte(nil), base.Body...) |
| + forged[len(forged)-2] = ' ' |
| + b.stageKeptFiles(rt, hafresh.LocalRecord{Files: &hafresh.FilesBaseline{Body: forged, ETag: base.ETag}}, gen) |
| + if _, ok := b.wakeFiles(rt.Host); ok { |
| + t.Fatal("a record whose manifest is not the marker's staged a publisher") |
| + } |
| + b.stageKeptFiles(rt, hafresh.LocalRecord{}, gen) |
| + if _, ok := b.wakeFiles(rt.Host); ok { |
| + t.Fatal("a record with no manifest staged one for a marker that names one") |
| + } |
| + b.stageKeptFiles(rt, hafresh.LocalRecord{Files: &hafresh.FilesBaseline{Body: base.Body, ETag: base.ETag}}, gen) |
| + if f, ok := b.wakeFiles(rt.Host); !ok || f.pub.Gen() != gen { |
| + t.Fatal("the marker's own manifest was not staged") |
| + } |
| +} |
diff --git a/internal/activator/harelease.go b/internal/activator/harelease.go| index e18a843fe..6650e8980 100644 |
| --- a/internal/activator/harelease.go |
| +++ b/internal/activator/harelease.go |
| @@ -26,10 +26,12 @@ import ( |
| // pending, with the lease held and renewing, and the sweep tries again. |
| var errHostSliceUnproven = errors.New("the host's slice is not proven empty") |
| -// The release's budgets beside finishStop's own: the final files publish, |
| -// and the marker's PUT. |
| +// The release's budgets, each its own and each started when its step |
| +// starts: the final files publish, the replica's final sync, and the |
| +// marker's PUT. |
| const ( |
| haFinalFilesBudget = 2 * time.Minute |
| + haFinalSyncBudget = 30 * time.Second |
| haMarkerBudget = 10 * time.Second |
| ) |
| @@ -38,7 +40,7 @@ const ( |
| type haReleaser interface { |
| hostSliceEmpty(rt registry.Route) (bool, error) |
| haReleaseBase(rt registry.Route) hafresh.Marker |
| - writeHARecord(rt registry.Route, m hafresh.Marker) error |
| + writeHARecord(rt registry.Route, m hafresh.Marker, files *hafresh.FilesBaseline) error |
| } |
| // hostSliceEmpty reads the host slice's cgroup.events |
| @@ -80,13 +82,15 @@ func (b *ExecBackend) haReleaseBase(rt registry.Route) hafresh.Marker { |
| } |
| // writeHARecord writes the host's local release record for m: the marker, |
| -// and the database, WAL and files tree as they are now (readLocalNow). A |
| +// the database, WAL and files tree as they are now (readLocalNow), and |
| +// files, the manifest the release committed last (a keep continues from |
| +// it without reading it, stageKeptFiles). A |
| // clean release first checkpoints the WAL into the database and truncates |
| // it (lease.TruncateWAL; every writer is proven stopped and the replica |
| // closed by now), so the record can show it empty, as a keep needs. A |
| // checkpoint that fails is logged and the record says the WAL is not |
| // empty: that copy is never kept. |
| -func (b *ExecBackend) writeHARecord(rt registry.Route, m hafresh.Marker) error { |
| +func (b *ExecBackend) writeHARecord(rt registry.Route, m hafresh.Marker, files *hafresh.FilesBaseline) error { |
| p := b.pathsFor(rt) |
| if m.Clean { |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| @@ -100,7 +104,7 @@ func (b *ExecBackend) writeHARecord(rt registry.Route, m hafresh.Marker) error { |
| if err != nil { |
| return err |
| } |
| - return writeReleaseRecord(p, rt.Host, hafresh.LocalRecord{Marker: m, DB: now.DB, WALEmpty: now.WALEmpty, TreeDigest: now.TreeDigest}) |
| + return writeReleaseRecord(p, rt.Host, hafresh.LocalRecord{Marker: m, DB: now.DB, WALEmpty: now.WALEmpty, TreeDigest: now.TreeDigest, Files: files}) |
| } |
| // haEntryRep is e's replica as an HA one, if it is. |
| @@ -147,18 +151,25 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error { |
| f := e.files |
| a.mu.Unlock() |
| gen, complete, ferr := "", false, errors.New("the entry has no files publisher") |
| + var files *hafresh.FilesBaseline |
| if f != nil { |
| // A budget of its own: a large tree's final read must not eat the |
| // final sync's. |
| fctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), haFinalFilesBudget) |
| gen, complete, ferr = f.Final(fctx) |
| cancel() |
| - } |
| - txid, finErr := hr.Finish(ctx) |
| + files = f.baseline() |
| + } |
| + // The final sync's budget starts now, never before the files publish: |
| + // a long one must not leave it a spent context, and the database's |
| + // last writes unsynced. |
| + sctx, scancel := context.WithTimeout(context.WithoutCancel(ctx), haFinalSyncBudget) |
| + txid, finErr := hr.Finish(sctx) |
| + scancel() |
| m := hb.haReleaseBase(rt) |
| m.TXID, m.FilesGen, m.At = txid, gen, time.Now().UTC() |
| m.Clean = complete && ferr == nil && finErr == nil |
| - rerr := hb.writeHARecord(rt, m) |
| + rerr := hb.writeHARecord(rt, m, files) |
| if rerr != nil { |
| // Without the record nothing could keep on this copy: the marker |
| // says so too. |
diff --git a/internal/activator/harelease_linux_test.go b/internal/activator/harelease_linux_test.go| new file mode 100644 |
| index 000000000..bc93ad315 |
| --- /dev/null |
| +++ b/internal/activator/harelease_linux_test.go |
| @@ -0,0 +1,23 @@ |
| +//go:build linux |
| + |
| +package activator |
| + |
| +import ( |
| + "path/filepath" |
| + "syscall" |
| + "testing" |
| +) |
| + |
| +// r2.8: a final publish that is not complete (here something that is not |
| +// a regular file in the tree) releases with an unclean marker. |
| +func TestReleaseUncleanWhenFinalPublishIncomplete(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "x"}) |
| + if err := syscall.Mkfifo(filepath.Join(filesDirOf(s.b, s.rt), "pipe"), 0o600); err != nil { |
| + t.Skipf("no FIFOs here: %v", err) |
| + } |
| + s.stopForTest(e) |
| + if v := s.lockView(t); !s.stoppedFor(e) || v.Lock.Release == nil || v.Lock.Release.Clean { |
| + t.Fatalf("want an unclean marker: %+v", v.Lock.Release) |
| + } |
| +} |
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go| index 06e407ead..4c40e67f5 100644 |
| --- a/internal/activator/harelease_test.go |
| +++ b/internal/activator/harelease_test.go |
| @@ -11,7 +11,6 @@ import ( |
| "strings" |
| "sync" |
| "sync/atomic" |
| - "syscall" |
| "testing" |
| "time" |
| @@ -21,6 +20,7 @@ import ( |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/lease/locktest" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // haUnit is the nested host as systemd and cgroupfs would show it: the |
| @@ -350,11 +350,11 @@ func (s *haSvc) failMarkerPuts(n int) { |
| } |
| } |
| -// failAfterReplicate makes the wake fail once its replica runs: the files |
| -// publisher's manifest read fails, so the publisher cannot open. |
| +// failAfterReplicate makes the wake fail once its replica runs: with no |
| +// files store, the files publisher cannot open (a first wake's restore |
| +// needs none, so the wake gets that far). |
| func (s *haSvc) failAfterReplicate() { |
| - key := hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host)) |
| - s.fx.FailNextMatching("GET", 403, func(k string, _ []byte) bool { return k == key }) |
| + s.b.FilesStore = nil |
| } |
| func isMarker(w lockWrite) bool { |
| @@ -610,20 +610,6 @@ func TestCleanReleaseRecordMatchesMarkerAndKeeps(t *testing.T) { |
| } |
| } |
| -// r2.8: a final publish that is not complete (here something that is not |
| -// a regular file in the tree) releases with an unclean marker. |
| -func TestReleaseUncleanWhenFinalPublishIncomplete(t *testing.T) { |
| - s, e := haServiceEntry(t, "shop.example.com") |
| - writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "x"}) |
| - if err := syscall.Mkfifo(filepath.Join(filesDirOf(s.b, s.rt), "pipe"), 0o600); err != nil { |
| - t.Skipf("no FIFOs here: %v", err) |
| - } |
| - s.stopForTest(e) |
| - if v := s.lockView(t); !s.stoppedFor(e) || v.Lock.Release == nil || v.Lock.Release.Clean { |
| - t.Fatalf("want an unclean marker: %+v", v.Lock.Release) |
| - } |
| -} |
| - |
| // The stream class captures every second for an HA host (the global |
| // cadence): the wake sets it on the lease before Replicate, and the |
| // replicator runs at it. Another class keeps litestream's default. |
| @@ -711,3 +697,112 @@ func TestSweepRetriesOwedMarkers(t *testing.T) { |
| s.a.sweepOnce() |
| waitFor(t, "the next sweep's retry", func() bool { return calls.Load() == 2 }) |
| } |
| + |
| +// slowStore delays every Put by delay (nanoseconds; 0: none), standing in |
| +// for a slow files publish. |
| +type slowStore struct { |
| + release.Store |
| + delay atomic.Int64 |
| +} |
| + |
| +func (s *slowStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + time.Sleep(time.Duration(s.delay.Load())) |
| + return s.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +// The final sync's budget starts after the files publish: a publish that |
| +// outlasts the caller's whole context still leaves the database's last |
| +// writes a full sync, so the release is clean and the replica holds them. |
| +func TestFinalSyncBudgetStartsAfterTheFilesPublish(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + slow := &slowStore{Store: s.b.FilesStore} |
| + s.b.FilesStore = slow |
| + s.rt.Replication = replicationDaily // only the final sync ships these rows |
| + if err := s.b.Registry.SetReplication(s.rt.Host, replicationDaily); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + db, err := sql.Open("sqlite", s.b.pathsFor(s.rt).dbPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 3; i++ { |
| + if _, err := db.Exec("insert into t values (?)", i); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + db.Close() |
| + writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "x"}) |
| + s.unit.set(func(u *haUnit) { u.slicePop = false }) |
| + slow.delay.Store(int64(400 * time.Millisecond)) |
| + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) |
| + defer cancel() |
| + if err := s.a.releaseHAClean(ctx, e); err != nil { |
| + t.Logf("release: %v", err) |
| + } |
| + if v := s.lockView(t); v.Lock.Release == nil || !v.Lock.Release.Clean { |
| + t.Fatalf("want a clean marker: %+v", v.Lock.Release) |
| + } |
| + got := filepath.Join(t.TempDir(), "restored.db") |
| + if ok, err := lease.Restore(context.Background(), got, s.fx.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), ""); err != nil || !ok { |
| + t.Fatalf("restore: %v, %v", ok, err) |
| + } |
| + rdb, err := sql.Open("sqlite", got) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rdb.Close() |
| + var n int |
| + if err := rdb.QueryRow("select count(*) from t").Scan(&n); err != nil || n != 3 { |
| + t.Fatalf("the replica holds %d rows (%v), want 3", n, err) |
| + } |
| +} |
| + |
| +// §18's budget, through whole wakes: a first wake is GET, LIST and PUT on |
| +// the lock and nothing of the files; a kept copy's wake is GET and PUT on |
| +// the lock and nothing else (its publisher continues from the manifest |
| +// its release record keeps); a restore reads the manifest once, the read |
| +// its publisher then continues from. |
| +func TestHAWakeRequestCounts(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + lock := s.lockKey() |
| + manifest := hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host)) |
| + wake := func() (*actEntry, []string) { |
| + t.Helper() |
| + n := len(s.fx.Requests()) |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return e, s.fx.Requests()[n:] |
| + } |
| + e, reqs := wake() |
| + if want := []string{"GET " + lock, "LIST " + s.b.Cfg.hibernatePrefix(s.rt.Host) + "/", "PUT " + lock}; strings.Join(reqs, ",") != strings.Join(want, ",") { |
| + t.Fatalf("a first wake made %v, want %v", reqs, want) |
| + } |
| + writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "app"}) |
| + s.stopForTest(e) |
| + e, reqs = wake() |
| + if want := []string{"GET " + lock, "PUT " + lock}; restoreCalls(s.b) != 0 || strings.Join(reqs, ",") != strings.Join(want, ",") { |
| + t.Fatalf("a kept wake made %v (%d restores), want %v", reqs, restoreCalls(s.b), want) |
| + } |
| + s.stopForTest(e) |
| + writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "changed after the release"}) // the keep proof fails |
| + e, reqs = wake() |
| + manifestReads := 0 |
| + for _, r := range reqs { |
| + if r == "GET "+manifest { |
| + manifestReads++ |
| + } |
| + } |
| + if restoreCalls(s.b) != 1 || manifestReads != 1 || reqs[0] != "GET "+lock || reqs[1] != "PUT "+lock { |
| + t.Fatalf("a restoring wake made %v (%d restores)", reqs, restoreCalls(s.b)) |
| + } |
| + s.stopForTest(e) // the restore's publisher continued from that read: no conflict |
| + if v := s.lockView(t); v.Lock.Release == nil || !v.Lock.Release.Clean { |
| + t.Fatalf("the restored wake's release: %+v", v.Lock.Release) |
| + } |
| +} |
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go| index 8ab07219e..5f52c048f 100644 |
| --- a/internal/activator/hawake.go |
| +++ b/internal/activator/hawake.go |
| @@ -155,6 +155,33 @@ type haWakes struct { |
| mu sync.Mutex |
| m map[string]haWake |
| classes map[string]string |
| + // fileSets is the files publisher an HA restore opened for its wake's |
| + // entry (stageWakeFiles), until the entry takes it (openHostFiles). |
| + fileSets map[string]*hostFiles |
| +} |
| + |
| +func (w *haWakes) setFiles(host string, f *hostFiles) { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if w.fileSets == nil { |
| + w.fileSets = map[string]*hostFiles{} |
| + } |
| + w.fileSets[host] = f |
| +} |
| + |
| +func (w *haWakes) files(host string) (*hostFiles, bool) { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + f, ok := w.fileSets[host] |
| + return f, ok |
| +} |
| + |
| +func (w *haWakes) takeFiles(host string) (*hostFiles, bool) { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + f, ok := w.fileSets[host] |
| + delete(w.fileSets, host) |
| + return f, ok |
| } |
| func (w *haWakes) set(host string, s haWake) { |
| @@ -178,6 +205,7 @@ func (w *haWakes) forget(host string) { |
| defer w.mu.Unlock() |
| delete(w.m, host) |
| delete(w.classes, host) |
| + delete(w.fileSets, host) |
| } |
| func (w *haWakes) setClass(host, class string) { |
| @@ -391,6 +419,8 @@ func (b *ExecBackend) restoreHA(ctx context.Context, rt registry.Route, v hafres |
| return false, fmt.Errorf("%s: set aside the local copy: %w", host, err) |
| } |
| log.Printf("activator: %s: restored (%s): first wake, the prefix proven empty, booting fresh", host, hafresh.KeepNoMarker) |
| + // The acquire proved the prefix empty, so there is no manifest. |
| + b.stageWakeFiles(rt, hostfiles.Baseline{}) |
| return true, nil |
| } |
| lifetime, err := b.haLifetime(ctx, rt) |
| @@ -406,6 +436,7 @@ func (b *ExecBackend) restoreHA(ctx context.Context, rt registry.Route, v hafres |
| } |
| if keep { |
| log.Printf("activator: %s: kept local", host) |
| + b.stageKeptFiles(rt, now.Record, v.Lock.Release.FilesGen) |
| return false, nil |
| } |
| if err := b.setAside(p, host); err != nil { |
| @@ -581,11 +612,13 @@ func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route) |
| return err |
| } |
| // One read of the manifest; none is an empty one, and an empty tree. |
| - rm, st, err := hostfiles.RestoreRoot(ctx, b.FilesStore, prefix, root, nil) |
| + rm, st, base, err := hostfiles.RestoreRootBaseline(ctx, b.FilesStore, prefix, root, nil) |
| root.Close() |
| if err != nil { |
| return err |
| } |
| + // The manifest just read is the one this wake's publisher continues. |
| + b.stageWakeFiles(rt, base) |
| if len(st.Skipped) > 0 { |
| log.Printf("activator: %s: %d file(s) the manifest holds as unpublished were not restored: %s", host, len(st.Skipped), strings.Join(st.Skipped, ", ")) |
| } |
diff --git a/internal/hafresh/keep.go b/internal/hafresh/keep.go| index d13cc0a8c..a75c0e5c0 100644 |
| --- a/internal/hafresh/keep.go |
| +++ b/internal/hafresh/keep.go |
| @@ -20,6 +20,19 @@ type LocalRecord struct { |
| DB FileID `json:"db"` |
| WALEmpty bool `json:"wal_empty"` |
| TreeDigest string `json:"tree_digest"` |
| + // Files is the files manifest the release committed last (the one |
| + // Marker.FilesGen names), so a wake that keeps this copy continues |
| + // publishing from it without reading it again. Nil when no manifest |
| + // was committed. It decides nothing here: the caller trusts it only |
| + // when its hash is the one FilesGen carries. |
| + Files *FilesBaseline `json:"files,omitempty"` |
| +} |
| + |
| +// FilesBaseline is a files manifest's exact bytes and the ETag the store |
| +// answered for them. |
| +type FilesBaseline struct { |
| + Body []byte `json:"body"` |
| + ETag string `json:"etag"` |
| } |
| // LocalNow is the local state as it is now, read at wake: the local record |
diff --git a/internal/hostfiles/hostfiles_test.go b/internal/hostfiles/hostfiles_test.go| index e4e61e9c4..b1926f380 100644 |
| --- a/internal/hostfiles/hostfiles_test.go |
| +++ b/internal/hostfiles/hostfiles_test.go |
| @@ -849,3 +849,61 @@ func TestGenNamesTheCommittedManifest(t *testing.T) { |
| t.Fatalf("reopened %q, want %q", g, want) |
| } |
| } |
| + |
| +// countingGets counts manifest reads. |
| +type countingGets struct { |
| + release.Store |
| + gets int |
| +} |
| + |
| +func (c *countingGets) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + c.gets++ |
| + return c.Store.Get(ctx, key) |
| +} |
| + |
| +// A baseline (the committed manifest's bytes and token, or none) opens a |
| +// publisher that continues without reading the manifest; a baseline of |
| +// none whose prefix gained a manifest meanwhile is superseded, as Open's |
| +// stale read would be. RestoreRootBaseline answers the bytes it read. |
| +func TestOpenBaselineContinuesWithoutARead(t *testing.T) { |
| + ctx := context.Background() |
| + s := &countingGets{Store: release.NewDirStore(t.TempDir())} |
| + p := open(t, s) |
| + stage(t, p, "a.txt", "1") |
| + commit(t, p) |
| + base := p.Baseline() |
| + if !base.Found || base.ETag == "" { |
| + t.Fatalf("baseline %+v", base) |
| + } |
| + gets := s.gets |
| + p2, err := OpenBaseline(s, pfx, base) |
| + if err != nil || s.gets != gets || p2.Gen() != p.Gen() { |
| + t.Fatalf("open: %v, %d reads, gen %q want %q", err, s.gets-gets, p2.Gen(), p.Gen()) |
| + } |
| + stage(t, p2, "b.txt", "2") |
| + commit(t, p2) |
| + |
| + empty := release.NewDirStore(t.TempDir()) |
| + p3, err := OpenBaseline(empty, pfx, Baseline{}) |
| + if err != nil || p3.Gen() != "0:" || p3.Baseline().Found { |
| + t.Fatalf("an absent baseline: %v, %q", err, p3.Gen()) |
| + } |
| + p4, _ := OpenBaseline(empty, pfx, Baseline{}) |
| + stage(t, p3, "a.txt", "1") |
| + commit(t, p3) |
| + stage(t, p4, "a.txt", "other") |
| + if _, err := p4.Commit(ctx); !errors.Is(err, ErrSuperseded) { |
| + t.Fatalf("a stale absent baseline committed: %v", err) |
| + } |
| + |
| + root, err := os.OpenRoot(t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer root.Close() |
| + _, _, rb, err := RestoreRootBaseline(ctx, s, pfx, root, nil) |
| + raw, etag, gerr := s.Get(ctx, ManifestKey(pfx)) |
| + if err != nil || gerr != nil || !rb.Found || string(rb.Body) != string(raw) || rb.ETag != etag { |
| + t.Fatalf("restore baseline %+v: %v %v", rb.Found, err, gerr) |
| + } |
| +} |
diff --git a/internal/hostfiles/publisher.go b/internal/hostfiles/publisher.go| index 192fa074d..1810a8b5a 100644 |
| --- a/internal/hostfiles/publisher.go |
| +++ b/internal/hostfiles/publisher.go |
| @@ -39,7 +39,9 @@ type Publisher struct { |
| inflight map[string]int64 |
| // committed is the sha256 of the manifest body last committed, or read |
| // at Open: the body behind man.Seq. "" while there is none. |
| - committed string |
| + // committedBody is that body itself, nil while there is none. |
| + committed string |
| + committedBody []byte |
| } |
| func Open(ctx context.Context, s release.Store, prefix string) (*Publisher, error) { |
| @@ -59,7 +61,7 @@ func Open(ctx context.Context, s release.Store, prefix string) (*Publisher, erro |
| } |
| p := &Publisher{s: s, prefix: prefix, man: m, etag: etag, next: m.Seq} |
| if found { |
| - p.committed = sum(raw) |
| + p.committed, p.committedBody = sum(raw), raw |
| } |
| return p, nil |
| } |
| @@ -109,7 +111,46 @@ func OpenAt(s release.Store, prefix string, body []byte, etag string) (*Publishe |
| if err := manifestWithinCap(m); err != nil { |
| return nil, fmt.Errorf("hostfiles: open %s: the manifest cannot be continued, an operator must replace it: %w", prefix, err) |
| } |
| - return &Publisher{s: s, prefix: prefix, man: m, etag: etag, next: m.Seq, committed: sum(body)}, nil |
| + return &Publisher{s: s, prefix: prefix, man: m, etag: etag, next: m.Seq, committed: sum(body), committedBody: append([]byte(nil), body...)}, nil |
| +} |
| + |
| +// Baseline is a manifest as a publisher continues from it: its exact |
| +// bytes and the token the store answered for them, or Found false for a |
| +// prefix known to hold no manifest. A caller that already holds one (it |
| +// read the manifest to restore from it, or kept it from its own last |
| +// commit) opens a publisher on it with OpenBaseline, with no read. |
| +type Baseline struct { |
| + Found bool |
| + Body []byte |
| + ETag string |
| +} |
| + |
| +// OpenBaseline is a publisher continuing from b with no read: OpenAt over |
| +// b's bytes and token, or, for a prefix known to hold no manifest, an |
| +// empty one whose first commit is a create (it fails ErrSuperseded if a |
| +// manifest appeared meanwhile, as Open's would). |
| +func OpenBaseline(s release.Store, prefix string, b Baseline) (*Publisher, error) { |
| + if b.Found { |
| + return OpenAt(s, prefix, b.Body, b.ETag) |
| + } |
| + if s == nil { |
| + return nil, errors.New("hostfiles: open: no store") |
| + } |
| + if err := checkPrefix(prefix); err != nil { |
| + return nil, err |
| + } |
| + return &Publisher{s: s, prefix: prefix, man: Manifest{V: ManifestVersion, Entries: map[string]Entry{}, Platform: map[string]Entry{}}}, nil |
| +} |
| + |
| +// Baseline is the manifest last committed (or opened on), as OpenBaseline |
| +// takes it: Found false while there is none. |
| +func (p *Publisher) Baseline() Baseline { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + if p.committedBody == nil { |
| + return Baseline{} |
| + } |
| + return Baseline{Found: true, Body: append([]byte(nil), p.committedBody...), ETag: p.etag} |
| } |
| func sum(body []byte) string { |
| @@ -256,7 +297,7 @@ func (p *Publisher) Commit(ctx context.Context) (int64, error) { |
| } else if seq, ok := p.inflight[sum(cur)]; ok { |
| // An earlier attempt landed and later stages changed the body. |
| // Adopt it, then write the current body once on top of it. |
| - p.man.Seq, p.etag, p.inflight, p.committed = seq, curEtag, nil, sum(cur) |
| + p.man.Seq, p.etag, p.inflight, p.committed, p.committedBody = seq, curEtag, nil, sum(cur), cur |
| etag, err = p.s.Put(ctx, ManifestKey(p.prefix), body, p.etag) |
| if errors.Is(err, release.ErrCASConflict) { |
| return 0, fmt.Errorf("%w: %s", ErrSuperseded, p.prefix) |
| @@ -275,7 +316,7 @@ func (p *Publisher) Commit(ctx context.Context) (int64, error) { |
| return 0, err |
| } |
| p.man.Seq, p.etag, p.dirty, p.inflight = out.Seq, etag, false, nil |
| - p.committed = sum(body) |
| + p.committed, p.committedBody = sum(body), body |
| return out.Seq, nil |
| } |
diff --git a/internal/hostfiles/restore.go b/internal/hostfiles/restore.go| index acf477529..f77e33205 100644 |
| --- a/internal/hostfiles/restore.go |
| +++ b/internal/hostfiles/restore.go |
| @@ -69,7 +69,7 @@ func Restore(ctx context.Context, s release.Store, prefix, dir string, origins [ |
| return nil, nil, fmt.Errorf("hostfiles: restore into %s: %w", dir, err) |
| } |
| return root, func() { root.Close() }, nil |
| - }) |
| + }, nil) |
| } |
| // RestoreRoot is Restore into a directory the caller has already opened as |
| @@ -79,16 +79,27 @@ func Restore(ctx context.Context, s release.Store, prefix, dir string, origins [ |
| // the root itself without either (instancefs.OpenRootBeneath) and restores |
| // here. Everything else is Restore's: the one implementation both share. |
| func RestoreRoot(ctx context.Context, s release.Store, prefix string, root *os.Root, origins []string) (Manifest, RestoreStats, error) { |
| + m, st, _, err := RestoreRootBaseline(ctx, s, prefix, root, origins) |
| + return m, st, err |
| +} |
| + |
| +// RestoreRootBaseline is RestoreRoot that also answers the manifest it |
| +// restored from as a Baseline (its exact bytes and token, or Found false |
| +// when there is none), so the caller can continue publishing from it |
| +// (OpenBaseline) without reading it again. |
| +func RestoreRootBaseline(ctx context.Context, s release.Store, prefix string, root *os.Root, origins []string) (Manifest, RestoreStats, Baseline, error) { |
| if root == nil { |
| - return Manifest{}, RestoreStats{}, errors.New("hostfiles: restore into a nil root") |
| + return Manifest{}, RestoreStats{}, Baseline{}, errors.New("hostfiles: restore into a nil root") |
| } |
| - return restore(ctx, s, prefix, origins, func() (*os.Root, func(), error) { return root, func() {}, nil }) |
| + var b Baseline |
| + m, st, err := restore(ctx, s, prefix, origins, func() (*os.Root, func(), error) { return root, func() {}, nil }, &b) |
| + return m, st, b, err |
| } |
| // restore is Restore and RestoreRoot. open is called only once the |
| // manifest is validated and names something to do, so a bad manifest |
| // touches no directory and an empty one needs none. |
| -func restore(ctx context.Context, s release.Store, prefix string, origins []string, open func() (*os.Root, func(), error)) (Manifest, RestoreStats, error) { |
| +func restore(ctx context.Context, s release.Store, prefix string, origins []string, open func() (*os.Root, func(), error), base *Baseline) (Manifest, RestoreStats, error) { |
| var st RestoreStats |
| if err := checkPrefix(prefix); err != nil { |
| return Manifest{}, st, err |
| @@ -97,13 +108,16 @@ func restore(ctx context.Context, s release.Store, prefix string, origins []stri |
| if err != nil { |
| return Manifest{}, st, err |
| } |
| - m, _, _, err := load(ctx, s, prefix) |
| + m, raw, etag, found, err := loadRaw(ctx, s, prefix) |
| if err != nil { |
| return Manifest{}, st, err |
| } |
| if err := checkManifest(m, origins); err != nil { |
| return Manifest{}, st, err |
| } |
| + if base != nil && found { |
| + *base = Baseline{Found: true, Body: raw, ETag: etag} |
| + } |
| var live, dead []string |
| for p, e := range m.Entries { |
| if e.Deleted { |