package thin import ( "context" "crypto/sha256" "database/sql" "encoding/hex" "errors" "io" "io/fs" "log/slog" "os" "path/filepath" "regexp" "sort" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/attach" "amadan.net/oficina/equipo/internal/wire" "golang.org/x/sys/unix" ) // Attachments reach the runner as attachment frames, chunk by chunk, // before the message frame that names them. Each chunk is written at its // offset into a private .part file beside the desk (never in it), its // index recorded with the frame id in one transaction, and only then // acked: a resent chunk is a no-op, a chunk lost in a crash is resent. // When every chunk is in, the size and SHA-256 are checked and the file // moves into the person's desk at attachments//, read-only. The // desk is the coordinator's read-only /workspace, so the model sees // /workspace/attachments// and can never write it. const ( fileSchema = `CREATE TABLE IF NOT EXISTS file_chunks (attachment_id TEXT NOT NULL, idx INTEGER NOT NULL, PRIMARY KEY (attachment_id, idx)); CREATE TABLE IF NOT EXISTS file_admits (attachment_id TEXT PRIMARY KEY, person TEXT NOT NULL, size INTEGER NOT NULL, state TEXT NOT NULL, at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS file_refused (attachment_id TEXT PRIMARY KEY, at TEXT NOT NULL);` // attachmentsDir is the desk's attachments directory. attachmentsDir = "attachments" // keepFiles is how long a delivered attachment stays on the runner. keepFiles = wire.RunnerKeepFiles // keepParts is how long an unfinished one waits for its chunks. keepParts = 2 * 24 * time.Hour // admitIncoming and admitDelivered are an admitted file's states: its // chunks arriving, or delivered and waiting for the message frame that // names it (which then protects it as a running turn's). admitIncoming = "incoming" admitDelivered = "delivered" ) var attachmentID = regexp.MustCompile(`^at_[a-z0-9]{8,60}$`) // fileStamp is a sortable time: fixed width, so text order is time order. const fileStamp = "2006-01-02T15:04:05.000000000Z" // Files receives attachment chunks for every person and keeps the // runner's disk bounded (Sweep). type Files struct { State *State SessionRoot string Logger *slog.Logger // Quota bounds what delivered attachments may hold; zero is DefaultQuota. Quota Quota mu sync.Mutex // fault fails a step of finishing a file, in tests of a crash there. fault func(step string) error } // Quota bounds attachments on the runner, per person and in all: those // delivered and those still arriving (by their declared size). A new file // is admitted only if it fits, after the oldest delivered files that // nothing protects make room; otherwise it is refused ("runner storage // full") and its turn fails in words. A file a running turn names, or one // admitted and not yet named by its message, is never removed. type Quota struct { PersonBytes, PersonFiles, TotalBytes, TotalFiles int64 } // DefaultQuota: fifty full messages a person, four people's worth in all. var DefaultQuota = Quota{PersonBytes: 500 << 20, PersonFiles: 1000, TotalBytes: 2 << 30, TotalFiles: 4000} func (f *Files) quota() Quota { if f.Quota == (Quota{}) { return DefaultQuota } return f.Quota } func (f *Files) step(name string) error { if f.fault != nil { return f.fault(name) } return nil } // valid reports a chunk the runner will write: a known kind and type, a // safe name, and a size, count and length that agree. func validChunk(c wire.AttachmentChunk) bool { if c.Person == "" || !attachmentID.MatchString(c.ID) || c.Size < 1 || c.Size > attach.MaxBytes { return false } if c.Kind != wire.AttachmentImage && c.Kind != wire.AttachmentFile || !attach.Allowed(c.MediaType) || attach.IsImage(c.MediaType) != (c.Kind == wire.AttachmentImage) { return false } if c.Name == "" || attach.SafeName(c.Name) != c.Name { return false } if raw, err := hex.DecodeString(c.SHA256); err != nil || len(raw) != sha256.Size { return false } if c.Count != attach.Chunks(c.Size) || c.Index < 0 || c.Index >= c.Count { return false } want := attach.ChunkBytes if c.Index == c.Count-1 { want = int(c.Size - int64(c.Index)*attach.ChunkBytes) } return len(c.Data) == want } // errMismatch is a whole file whose size or SHA-256 is wrong: its bytes // came wrong and cannot be put right here, so it is discarded. var errMismatch = errors.New("attachment size or sha256 does not match") // Accept applies one chunk exactly once. A chunk that is not valid is // dropped (logged, then acked): the turn that names it fails visibly. // Any filesystem failure returns an error, so the frame is not acked and // comes again, with every chunk written so far kept: finishing restarts // from where it stopped. func (f *Files) Accept(ctx context.Context, frameID string, c wire.AttachmentChunk) error { if !validChunk(c) { f.log("attachment chunk refused", errors.New(c.ID)) _, err := f.State.SeenResult(ctx, frameID) return err } f.mu.Lock() defer f.mu.Unlock() desk, err := OpenDesk(f.SessionRoot, c.Person) if err != nil { return err } final := filepath.Join(desk.Dir, attachmentsDir, c.ID, c.Name) incoming := filepath.Join(filepath.Dir(desk.Dir), "incoming") part, ready := filepath.Join(incoming, c.ID+".part"), filepath.Join(incoming, c.ID+".ready") if f.State.refused(ctx, c.ID) { // Refused for room: every chunk is acked unwritten. _, err := f.State.SeenResult(ctx, frameID) return err } if info, err := os.Lstat(final); err == nil && info.Mode().IsRegular() && info.Size() == c.Size { // Delivered already (an ack was lost, or the turn moved): tidy up // what a crash after delivery may have left, then ack. if err := f.forget(ctx, c.ID, part, ready); err != nil { return err } _, err := f.State.SeenResult(ctx, frameID) return err } admitted, err := f.admit(ctx, c.Person, c.ID, c.Size) if err != nil { return err } if !admitted { f.log("attachment refused: runner storage full", errors.New(c.ID)) _, err := f.State.SeenResult(ctx, frameID) return err } if _, err := os.Lstat(ready); err != nil { // Not yet whole: write this chunk. if err := os.MkdirAll(incoming, 0700); err != nil { return err } if err := writeAt(part, int64(c.Index)*attach.ChunkBytes, c.Data); err != nil { return err } } have := 0 err = f.State.tx(ctx, func(t *sql.Tx) error { if _, err := seen(t, frameID); err != nil { return err } if _, err := t.Exec("INSERT INTO file_chunks(attachment_id, idx) VALUES(?,?) ON CONFLICT DO NOTHING", c.ID, c.Index); err != nil { return err } return t.QueryRow("SELECT count(*) FROM file_chunks WHERE attachment_id=?", c.ID).Scan(&have) }) if err != nil || have < c.Count { return err } err = f.finish(part, ready, final, c.Size, c.SHA256) if errors.Is(err, errMismatch) { // Discarded: the turn that names it fails; a resend starts afresh. f.log("attachment discarded", err) os.Remove(part) if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_admits WHERE attachment_id=?", c.ID); err != nil { return err } return f.forget(ctx, c.ID, part, ready) } if err != nil { return err } if err := f.forget(ctx, c.ID, part, ready); err != nil { return err } _, err = f.State.db.ExecContext(ctx, "UPDATE file_admits SET state=? WHERE attachment_id=?", admitDelivered, c.ID) return err } // forget drops a finished or discarded file's chunk records and leftovers. func (f *Files) forget(ctx context.Context, id, part, ready string) error { if err := f.step("forget"); err != nil { return err } for _, p := range []string{part, ready} { if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) { return err } } _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id) return err } func writeAt(path string, off int64, data []byte) error { fd, err := unix.Open(path, unix.O_WRONLY|unix.O_CREAT|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600) if err != nil { return err } file := os.NewFile(uintptr(fd), path) defer file.Close() if _, err = file.WriteAt(data, off); err != nil { return err } return file.Sync() } // finish checks the assembled file and moves it into the desk, read-only, // through steps that each survive a crash: the checked file becomes // .ready by a rename (no more chunks are written once it exists), is // made read-only, and is renamed into the desk. Replay picks up at // whichever step was next. Only a wrong size or hash is errMismatch. func (f *Files) finish(part, ready, final string, size int64, sum string) error { if _, err := os.Lstat(ready); errors.Is(err, fs.ErrNotExist) { if err := f.step("verify"); err != nil { return err } if err := check(part, size, sum); err != nil { return err } if err := f.step("ready"); err != nil { return err } if err := os.Rename(part, ready); err != nil { return err } } else if err != nil { return err } else if err := check(ready, size, sum); err != nil { return err } if err := f.step("chmod"); err != nil { return err } if err := os.Chmod(ready, 0400); err != nil { return err } if err := f.step("mkdir"); err != nil { return err } if err := os.MkdirAll(filepath.Dir(final), 0700); err != nil { return err } if err := f.step("rename"); err != nil { return err } return os.Rename(ready, final) } // check reads a file whole: errMismatch when its size or hash is wrong, // any other error when it cannot be read. func check(path string, size int64, sum string) error { in, err := os.Open(path) if err != nil { return err } defer in.Close() h := sha256.New() n, err := io.Copy(h, in) if err != nil { return err } if n != size || hex.EncodeToString(h.Sum(nil)) != sum { return errMismatch } return nil } // Run sweeps every interval until ctx ends: the bounds below, for every // person, whether or not anything arrives. func (f *Files) Run(ctx context.Context, every time.Duration) { t := time.NewTicker(every) defer t.Stop() for { f.Sweep(ctx) select { case <-ctx.Done(): return case <-t.C: } } } // Sweep keeps the runner's attachments bounded and its records true: // unfinished files past keepParts go with their chunk records; chunk // records with no file go; delivered files past keepFiles go; then, over // the quota for a person or the runner, the oldest delivered files that // nothing protects go first. If what is protected cannot be read (a query // fails, a record does not decode, ctx ends), nothing is removed. func (f *Files) Sweep(ctx context.Context) { f.mu.Lock() defer f.mu.Unlock() if err := f.sweep(ctx); err != nil { f.log("attachment sweep", err) } } type heldDir struct { person, path, id string at time.Time bytes, files int64 } // usage is bytes and files. type usage [2]int64 // protected is every attachment that must stay: named by a running turn, // or admitted and not yet named by its message (within keepParts). Any // failure to read it is an error: nothing is then removed. func (f *Files) protected(ctx context.Context) (map[string]bool, error) { if err := ctx.Err(); err != nil { return nil, err } out, err := f.State.runningAttachments(ctx) if err != nil { return nil, err } rows, err := f.State.db.QueryContext(ctx, "SELECT attachment_id FROM file_admits WHERE at >= ?", time.Now().Add(-keepParts).UTC().Format(fileStamp)) if err != nil { return nil, err } defer rows.Close() for rows.Next() { var id string if err := rows.Scan(&id); err != nil { return nil, err } out[id] = true } return out, rows.Err() } // arriving is what admitted files still arriving hold, by person key and // in all (their declared size, one file each). func (f *Files) arriving(ctx context.Context) (map[string]usage, usage, error) { by := map[string]usage{} var total usage rows, err := f.State.db.QueryContext(ctx, "SELECT person, size FROM file_admits WHERE state=?", admitIncoming) if err != nil { return nil, total, err } defer rows.Close() for rows.Next() { var p string var n int64 if err := rows.Scan(&p, &n); err != nil { return nil, total, err } v := by[p] by[p] = usage{v[0] + n, v[1] + 1} total = usage{total[0] + n, total[1] + 1} } return by, total, rows.Err() } // delivered lists delivered attachments, oldest first. func (f *Files) delivered() []heldDir { var all []heldDir people, _ := os.ReadDir(f.SessionRoot) for _, p := range people { root := filepath.Join(f.SessionRoot, p.Name(), "desk", attachmentsDir) dirs, _ := os.ReadDir(root) for _, d := range dirs { info, err := d.Info() if err != nil || !d.IsDir() || !attachmentID.MatchString(d.Name()) { continue } h := heldDir{person: p.Name(), path: filepath.Join(root, d.Name()), id: d.Name(), at: info.ModTime()} files, _ := os.ReadDir(h.path) for _, x := range files { if xi, err := x.Info(); err == nil { h.bytes += xi.Size() h.files++ } } all = append(all, h) } } sort.Slice(all, func(i, j int) bool { return all[i].at.Before(all[j].at) }) return all } // makeRoom removes the oldest unprotected delivered files until every // person and the runner fit the quota with extra added for person ("" // for none). It reports whether they fit; it removes nothing a protected // file needs, and only files that help: a person over quota loses their // own oldest first, the runner's oldest after. func (f *Files) makeRoom(ctx context.Context, protect map[string]bool, person string, extra usage) (bool, error) { byArriving, arriving, err := f.arriving(ctx) if err != nil { return false, err } all := f.delivered() q := f.quota() by := map[string]usage{} for p, v := range byArriving { by[p] = v } total := arriving for _, h := range all { v := by[h.person] by[h.person] = usage{v[0] + h.bytes, v[1] + h.files} total = usage{total[0] + h.bytes, total[1] + h.files} } if person != "" { v := by[person] by[person] = usage{v[0] + extra[0], v[1] + extra[1]} total = usage{total[0] + extra[0], total[1] + extra[1]} } over := func(u usage, bytes, files int64) bool { return u[0] > bytes || u[1] > files } for _, h := range all { personOver := over(by[h.person], q.PersonBytes, q.PersonFiles) if !personOver && !over(total, q.TotalBytes, q.TotalFiles) { continue } if protect[h.id] { continue } if err := ctx.Err(); err != nil { return false, err } removeAll(h.path) v := by[h.person] by[h.person] = usage{v[0] - h.bytes, v[1] - h.files} total = usage{total[0] - h.bytes, total[1] - h.files} } for p, u := range by { if over(u, q.PersonBytes, q.PersonFiles) && (person == "" || p == person) { return false, nil } } return !over(total, q.TotalBytes, q.TotalFiles), nil } // admit takes a new attachment in if it fits once room is made, recording // it as arriving; one admitted already stays admitted. False refuses it // for good (file_refused): its chunks are acked unwritten. func (f *Files) admit(ctx context.Context, person, id string, size int64) (bool, error) { var n int if err := f.State.db.QueryRowContext(ctx, "SELECT count(*) FROM file_admits WHERE attachment_id=?", id).Scan(&n); err != nil || n > 0 { return n > 0, err } protect, err := f.protected(ctx) if err != nil { return false, err } key := filepath.Base(personDir(f.SessionRoot, person)) fits, err := f.makeRoom(ctx, protect, key, usage{size, 1}) if err != nil { return false, err } at := time.Now().UTC().Format(fileStamp) if !fits { _, err := f.State.db.ExecContext(ctx, "INSERT INTO file_refused(attachment_id, at) VALUES(?,?) ON CONFLICT DO NOTHING", id, at) return false, err } _, err = f.State.db.ExecContext(ctx, "INSERT INTO file_admits(attachment_id, person, size, state, at) VALUES(?,?,?,?,?)", id, key, size, admitIncoming, at) return err == nil, err } func (f *Files) sweep(ctx context.Context) error { if f.SessionRoot == "" { return nil } protect, err := f.protected(ctx) if err != nil { return err } stale := time.Now().Add(-keepParts) people, _ := os.ReadDir(f.SessionRoot) partial := map[string]bool{} for _, p := range people { if !p.IsDir() { continue } incoming := filepath.Join(f.SessionRoot, p.Name(), "incoming") entries, _ := os.ReadDir(incoming) for _, e := range entries { name := e.Name() id := strings.TrimSuffix(strings.TrimSuffix(name, ".part"), ".ready") info, err := e.Info() if err != nil || id == name { continue } if info.ModTime().Before(stale) && !protect[id] { os.Remove(filepath.Join(incoming, name)) if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id); err != nil { return err } continue } partial[id] = true } } for _, h := range f.delivered() { if h.at.Before(time.Now().Add(-keepFiles)) && !protect[h.id] { removeAll(h.path) } } // Chunk records whose file is gone (pruned, or never written). rows, err := f.State.db.QueryContext(ctx, "SELECT DISTINCT attachment_id FROM file_chunks") if err != nil { return err } var gone []string for rows.Next() { var id string if err := rows.Scan(&id); err != nil { rows.Close() return err } if !partial[id] { gone = append(gone, id) } } if err := rows.Err(); err != nil { rows.Close() return err } rows.Close() for _, id := range gone { if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id); err != nil { return err } } // Admissions and refusals past their time. cut := stale.UTC().Format(fileStamp) if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_admits WHERE at < ?", cut); err != nil { return err } if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_refused WHERE at < ?", time.Now().Add(-keepFiles).UTC().Format(fileStamp)); err != nil { return err } _, err = f.makeRoom(ctx, protect, "", usage{}) return err } // removeAll removes a tree whose files were made read-only. func removeAll(dir string) { _ = filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { if err == nil && d.IsDir() { os.Chmod(p, 0700) } return nil }) os.RemoveAll(dir) } func (f *Files) log(msg string, err error) { if f.Logger != nil && err != nil { f.Logger.Warn(msg, "err", sanitize(err)) } } // heldFile is one of a turn's attachments, checked on the desk. type heldFile struct { wire.AttachmentRef // Host is the file on the runner; Path is where the model sees it. Host, Path string } // errMissingFile fails a turn whose attachment is not on the desk whole. var errMissingFile = errors.New("attachment unavailable") // heldFiles finds each of a turn's attachments on the person's desk and // checks its size and SHA-256 again, just before the turn uses it. func heldFiles(desk *Desk, refs []wire.AttachmentRef) ([]heldFile, error) { out := make([]heldFile, 0, len(refs)) for _, r := range refs { if !attachmentID.MatchString(r.ID) || r.Name == "" || attach.SafeName(r.Name) != r.Name { return nil, errMissingFile } host := filepath.Join(desk.Dir, attachmentsDir, r.ID, r.Name) in, err := os.OpenFile(host, os.O_RDONLY|unix.O_NOFOLLOW, 0) if err != nil { return nil, errMissingFile } h := sha256.New() n, err := io.Copy(h, in) in.Close() if err != nil || n != r.Size || hex.EncodeToString(h.Sum(nil)) != r.SHA256 { return nil, errMissingFile } out = append(out, heldFile{AttachmentRef: r, Host: host, Path: "/workspace/" + attachmentsDir + "/" + r.ID + "/" + r.Name}) } return out, nil }