Files
mesh-catalog/modules/mesh-recovery/internal/recovery/restore.go
T
jschoubben 6c2d6605a5 mesh-recovery: its one whole test against the bus, and an act's end said once it is free
The whole test runs the process on its own account against a bus of its
own, every bound a setting of seconds, with a stand-in bus module for
snapshot-get, snapshot-restore and snapshot-restored: a hand take's log,
a restore waiting on the dump past its bound key, busy and the ask again,
the expiry on its bound key, a keeper's snapshot in three chunks, a
protected restore cancelled at its bound and its aside put back, one the
keeper answers neither, and a stop putting the aside back.

It found that an act said its ending event while it was still the running
one, so a caller told busy that asked again on hearing it was told busy
with the same act and heard nothing more: the act is now released and
written ended before its ending event, and the removal at a snapshot-kept
runs before its ended.

Builds: design 47 G §557, §554, §681, §562, §551, A-138, A-140, A-141, A-143

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-12 02:36:19 +01:00

371 lines
13 KiB
Go

package recovery
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
seat "git.novox.be/novox/mesh-contracts/go/seats/meshrecovery"
"git.novox.be/novox/mesh-sdk/go/keys"
)
const asideFile = "aside.json"
// The steps an aside's record says, in their order (§516): a restore that fails after `removed` puts the aside back.
const (
stepSetAside = "set aside"
stepRemoved = "removed"
stepRestored = "restored"
)
// asideRecord is the record in an aside's directory (§516); nothing of an aside is on the bus.
type asideRecord struct {
ID string `json:"id"`
Module string `json:"module"`
Kept string `json:"kept"`
Streams []string `json:"streams"`
Consumers []seat.Consumer `json:"consumers,omitempty"`
Digests []seat.Digest `json:"digests"`
Size int64 `json:"size"`
Step string `json:"step"`
}
func (r asideRecord) aside() seat.Aside {
return seat.Aside{ID: r.ID, Names: r.Streams, Size: r.Size}
}
func (e *Engine) asideRoot(module, kept string) (string, error) {
m, err := token(module)
if err != nil {
return "", err
}
k, err := token(kept)
if err != nil {
return "", err
}
return filepath.Join(e.Dir, "aside", m, k), nil
}
// endedRestored says the end of a restore, or of a restore-aside, under the act's id (§560).
func (e *Engine) endedRestored(a *Act, outcomeErr error, aside *seat.Aside, missing bool) error {
ev := seat.RestoredEvent{Act: a.ID, At: e.now(), Module: a.Module, Kept: a.Kept, Form: a.Form, Fingerprint: a.Fingerprint,
Snapshot: a.Snapshot, Outcome: seat.RestoredEventOutcomeDone, Aside: aside, Missing: missing}
outcomeErr = e.stoppedOr(outcomeErr)
if outcomeErr != nil {
ev.Outcome, ev.Error, ev.Why = seat.RestoredEventOutcomeFailed, outcomeErr.Error(), e.cancelledWhy(outcomeErr)
}
e.sayEnd(a.ID, seat.EventRestored, ev, a.Module, a.Kept)
return outcomeErr
}
func (e *Engine) cancelledWhy(err error) string {
e.mu.Lock()
defer e.mu.Unlock()
if err != nil && err.Error() == ErrCanceled {
return e.why
}
return ""
}
// restore is `restore-kept` and the hand verb `restore` with a point (or, past the dump, a keeper's snapshot by request) (§516, §554, §563, §567): it says restore-started,
// waits for the dump of the bus's item, finds the point (or has the backup holder bring it back), checks its digests
// against the bus, sets the live data aside whole and checked, removes it, restores the point under its names and
// sets each consumer to its recorded sequence; a step after the removal that fails puts the aside back.
func (e *Engine) restore(ctx context.Context, a *Act) error {
// Said means acknowledged: the dump's item events are read only once the bus took restore-started (§563).
if err := e.Seats.Say(seat.EventRestoreStarted, seat.RestoreStartedEvent{Act: a.ID, At: e.now(), Module: a.Module, Kept: a.Kept, Form: a.Form,
Fingerprint: a.Fingerprint, Snapshot: a.Snapshot}, a.Module, a.Kept); err != nil {
return e.endedRestored(a, fmt.Errorf("restore-started was not acknowledged by the bus, so nothing was read or set aside: %w", err), nil, false)
}
if e.Dump != nil {
waiting, done := e.waitsOn(a)
err := e.Dump.Wait(ctx, waiting)
done()
if err != nil {
if ctx.Err() != nil {
err = errors.New(ErrCanceled)
}
return e.endedRestored(a, err, nil, false)
}
}
if a.Request != "" {
return e.restoreRequest(ctx, a)
}
e.setStep(a, "finding the point", "")
pointPath := filepath.Join(e.Dir, "points", filepath.FromSlash(a.Snapshot))
if _, err := os.Stat(filepath.Join(pointPath, pointFile)); err != nil {
if !a.FromBackup {
return e.endedRestored(a, errors.New(ErrMissing), nil, true)
}
dir, err := e.Seats.Backup(ctx, Module)
if err != nil {
return e.endedRestored(a, errors.New(ErrMissing), nil, true)
}
defer os.RemoveAll(dir)
pointPath = filepath.Join(dir, filepath.FromSlash(a.Snapshot))
if _, err := os.Stat(filepath.Join(pointPath, pointFile)); err != nil {
return e.endedRestored(a, errors.New(ErrMissing), nil, true)
}
}
var p seat.Point
if err := readJSON(filepath.Join(pointPath, pointFile), &p); err != nil {
return e.endedRestored(a, fmt.Errorf("%s: %w", ErrDamaged, err), nil, false)
}
if err := e.checkDigests(pointPath, a.Snapshot, p); err != nil {
return e.endedRestored(a, err, nil, false)
}
names := make([]string, 0, len(p.Digests))
for _, d := range p.Digests {
names = append(names, d.Name)
}
rec, err := e.setAside(ctx, a, names, true)
if err != nil {
return e.endedRestored(a, err, nil, false)
}
// Past the removal, a failure puts the aside back (§516).
e.setStep(a, "restoring", "")
if err := e.putBack(ctx, pointPath, p.Digests, p.Consumers); err != nil {
if back := e.restoreFromAside(ctx, rec, true); back != nil {
err = fmt.Errorf("%w; and the aside is not put back: %v", err, back)
}
return e.endedRestored(a, err, asidePtr(rec), false)
}
rec.Step = stepRestored
_ = writeJSON(filepath.Join(e.asideDirOf(rec), asideFile), rec)
return e.endedRestored(a, nil, asidePtr(rec), false)
}
func asidePtr(r *asideRecord) *seat.Aside {
if r == nil {
return nil
}
x := r.aside()
return &x
}
func (e *Engine) asideDirOf(r *asideRecord) string {
root, _ := e.asideRoot(r.Module, r.Kept)
return filepath.Join(root, r.ID)
}
// checkDigests computes the digest of the bytes about to be restored and compares it with the key on the bus; the
// record in the directory is never the reference (§567).
func (e *Engine) checkDigests(pointPath, snapshot string, p seat.Point) error {
raw, ok, err := e.Digests.Get(keys.EscapeName(snapshot))
if err != nil {
return fmt.Errorf("the digests of %s cannot be read: %w", snapshot, err)
}
if !ok {
return fmt.Errorf("%s: %s has no digests on the bus", ErrDamaged, snapshot)
}
var want []seat.Digest
if err := unmarshal(raw, &want); err != nil {
return fmt.Errorf("%s: %s: %w", ErrDamaged, snapshot, err)
}
if len(want) != len(p.Digests) {
return fmt.Errorf("%s: %s holds %d object(s), the bus says %d", ErrDamaged, snapshot, len(p.Digests), len(want))
}
for _, w := range want {
got, _, err := digestOf(filepath.Join(pointPath, keys.EscapeName(w.Name)+".snap"))
if err != nil || got != w.Digest {
return fmt.Errorf("%s: %s, bus object %s", ErrDamaged, snapshot, w.Name)
}
}
return nil
}
// setAside takes a snapshot of each live object into aside/<module>/<kept>/<at>, reads it back to check it, and only then
// (when remove) removes the live objects, each step written first in the record (§516). Past the cap it refuses before
// any object is removed (§564).
func (e *Engine) setAside(ctx context.Context, a *Act, names []string, remove bool) (*asideRecord, error) {
e.setStep(a, "setting aside", "")
objs, err := e.Bus.Objects(ctx, names)
if err != nil {
return nil, err
}
var need int64
for _, o := range objs {
need += o.Bytes
}
if fill := e.filled(); fill+need > e.Settings.Cap {
return nil, fmt.Errorf("%s: the cap is %d bytes, the aside needs %d and the directory holds %d", ErrCap, e.Settings.Cap, need, fill)
}
root, err := e.asideRoot(a.Module, a.Kept)
if err != nil {
return nil, err
}
id := e.now().Format("20060102T150405Z")
for n := 2; ; n++ {
if _, err := os.Stat(filepath.Join(root, id)); err != nil {
break
}
id = fmt.Sprintf("%s-%d", e.now().Format("20060102T150405Z"), n)
}
dir := filepath.Join(root, id)
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
rec := &asideRecord{ID: id, Module: a.Module, Kept: a.Kept, Step: stepSetAside}
fail := func(err error) (*asideRecord, error) { _ = os.RemoveAll(dir); return nil, err }
for _, o := range objs {
if !o.Exists {
continue
}
sum, n, err := e.takeOne(ctx, o.Stream, filepath.Join(dir, keys.EscapeName(o.Stream)+".snap"))
if err != nil {
return fail(err)
}
if again, _, err := digestOf(filepath.Join(dir, keys.EscapeName(o.Stream)+".snap")); err != nil || again != sum {
return fail(fmt.Errorf("the aside of %s does not read back whole", o.Stream))
}
rec.Streams = append(rec.Streams, o.Stream)
rec.Digests = append(rec.Digests, seat.Digest{Name: o.Stream, Digest: sum})
rec.Consumers = append(rec.Consumers, o.Consumers...)
rec.Size += n
}
if err := writeJSON(filepath.Join(dir, asideFile), rec); err != nil {
return fail(err)
}
if !remove {
return rec, nil
}
rec.Step = stepRemoved
if err := writeJSON(filepath.Join(dir, asideFile), rec); err != nil {
return fail(err)
}
for _, s := range rec.Streams {
if err := e.Bus.Delete(ctx, s); err != nil {
if back := e.restoreFromAside(ctx, rec, false); back != nil {
return rec, fmt.Errorf("%w; and the aside is not put back: %v", err, back)
}
return rec, err
}
}
return rec, nil
}
// putBack restores each stream of a point under its own name and sets each consumer to its recorded sequence.
func (e *Engine) putBack(ctx context.Context, dir string, ds []seat.Digest, cs []seat.Consumer) error {
for _, d := range ds {
if err := e.Bus.Restore(ctx, filepath.Join(dir, keys.EscapeName(d.Name)+".snap")); err != nil {
return fmt.Errorf("stream %s: %w", d.Name, err)
}
}
return e.Bus.SetConsumers(ctx, cs)
}
// restoreFromAside puts an aside back under the live names: any partly restored stream is removed first. It is a failure
// path, so it runs whole also when the act's context ended, as at the process's stop (§562).
func (e *Engine) restoreFromAside(ctx context.Context, rec *asideRecord, clear bool) error {
ctx = context.WithoutCancel(ctx)
if clear {
for _, s := range rec.Streams {
if err := e.Bus.Delete(ctx, s); err != nil {
return err
}
}
}
if err := e.putBack(ctx, e.asideDirOf(rec), rec.Digests, rec.Consumers); err != nil {
return err
}
rec.Step = stepRestored
return writeJSON(filepath.Join(e.asideDirOf(rec), asideFile), rec)
}
func (e *Engine) readAside(module, kept, id string) (*asideRecord, error) {
root, err := e.asideRoot(module, kept)
if err != nil {
return nil, err
}
if id == "" || id == "." || id == ".." || strings.ContainsAny(id, "/") {
return nil, fmt.Errorf("%q is not an aside", id)
}
var rec asideRecord
if err := readJSON(filepath.Join(root, id, asideFile), &rec); err != nil {
return nil, fmt.Errorf("no aside %s of %s's %s", id, module, kept)
}
return &rec, nil
}
// aside is the hand verb `aside` (§516, §554, A-123): it sets the live kept data aside without restoring it, taking the bus
// names from the catalog entry of the fingerprint the node-engine's placement runs for the module, and removes the live
// objects once the aside is whole and checked (a move, not a removal: the data stays in the aside until it is discarded or
// put back by `restore-aside`); it ends with `set-aside`.
func (e *Engine) aside(ctx context.Context, a *Act) error {
fp, err := e.Seats.RunningFingerprint(ctx, a.Module)
if err != nil {
return err
}
a.Fingerprint = fp
names, err := e.Seats.Streams(ctx, a.Module, a.Kept, fp)
if err != nil {
return err
}
rec, err := e.setAside(ctx, a, names, true)
if err != nil {
return err
}
x := rec.aside()
e.sayEnd(a.ID, seat.EventSetAside, seat.SetAsideEvent{Act: a.ID, At: e.now(), ID: x.ID, Names: x.Names, Size: x.Size}, a.Module, a.Kept)
return nil
}
// restoreAside is `restore-aside` (§566): it puts an aside whose record ends at `removed` back under the live names it
// was taken from, refusing while a live object of those names exists, and ends with `restored`.
func (e *Engine) restoreAside(ctx context.Context, a *Act) error {
rec, err := e.readAside(a.Module, a.Kept, a.AsideID)
if err != nil {
return e.endedRestored(a, err, nil, false)
}
objs, err := e.Bus.Objects(ctx, rec.Streams)
if err != nil {
return e.endedRestored(a, err, nil, false)
}
for _, o := range objs {
if o.Exists {
return e.endedRestored(a, fmt.Errorf("the live stream %s exists; the aside %s is not put back over it", o.Stream, rec.ID), asidePtr(rec), false)
}
}
if err := e.restoreFromAside(ctx, rec, false); err != nil {
return e.endedRestored(a, err, asidePtr(rec), false)
}
return e.endedRestored(a, nil, asidePtr(rec), false)
}
// discardAside is `discard-aside` (§554): it removes that directory and nothing else, an id holding `.`, `..` or `/`
// refused; it ends with `aside-discarded`.
func (e *Engine) discardAside(a *Act) error {
rec, err := e.readAside(a.Module, a.Kept, a.AsideID)
if err != nil {
return err
}
if err := os.RemoveAll(e.asideDirOf(rec)); err != nil {
return err
}
x := rec.aside()
e.sayEnd(a.ID, seat.EventAsideDiscarded, seat.AsideDiscardedEvent{Act: a.ID, At: e.now(), ID: x.ID, Names: x.Names, Size: x.Size}, a.Module, a.Kept)
return nil
}
// Asides lists every aside in the directory (§517).
func (e *Engine) Asides() ([]seat.Aside, []asideRecord, error) {
var out []seat.Aside
var recs []asideRecord
_ = filepath.WalkDir(filepath.Join(e.Dir, "aside"), func(path string, d os.DirEntry, err error) error {
if err == nil && !d.IsDir() && d.Name() == asideFile {
var r asideRecord
if readJSON(path, &r) == nil {
out = append(out, r.aside())
recs = append(recs, r)
}
}
return nil
})
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out, recs, nil
}