oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "crypto/sha256"
6 "database/sql"
7 "encoding/hex"
8 "errors"
9 "io"
10 "io/fs"
11 "log/slog"
12 "os"
13 "path/filepath"
14 "regexp"
15 "sort"
16 "strings"
17 "sync"
18 "time"
19
20 "amadan.net/oficina/equipo/internal/attach"
21 "amadan.net/oficina/equipo/internal/wire"
22 "golang.org/x/sys/unix"
23)
24
25// Attachments reach the runner as attachment frames, chunk by chunk,
26// before the message frame that names them. Each chunk is written at its
27// offset into a private .part file beside the desk (never in it), its
28// index recorded with the frame id in one transaction, and only then
29// acked: a resent chunk is a no-op, a chunk lost in a crash is resent.
30// When every chunk is in, the size and SHA-256 are checked and the file
31// moves into the person's desk at attachments/<id>/<name>, read-only. The
32// desk is the coordinator's read-only /workspace, so the model sees
33// /workspace/attachments/<id>/<name> and can never write it.
34
35const (
36 fileSchema = `CREATE TABLE IF NOT EXISTS file_chunks (attachment_id TEXT NOT NULL, idx INTEGER NOT NULL, PRIMARY KEY (attachment_id, idx));
37CREATE 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);
38CREATE TABLE IF NOT EXISTS file_refused (attachment_id TEXT PRIMARY KEY, at TEXT NOT NULL);`
39 // attachmentsDir is the desk's attachments directory.
40 attachmentsDir = "attachments"
41 // keepFiles is how long a delivered attachment stays on the runner.
42 keepFiles = wire.RunnerKeepFiles
43 // keepParts is how long an unfinished one waits for its chunks.
44 keepParts = 2 * 24 * time.Hour
45 // admitIncoming and admitDelivered are an admitted file's states: its
46 // chunks arriving, or delivered and waiting for the message frame that
47 // names it (which then protects it as a running turn's).
48 admitIncoming = "incoming"
49 admitDelivered = "delivered"
50)
51
52var attachmentID = regexp.MustCompile(`^at_[a-z0-9]{8,60}$`)
53
54// fileStamp is a sortable time: fixed width, so text order is time order.
55const fileStamp = "2006-01-02T15:04:05.000000000Z"
56
57// Files receives attachment chunks for every person and keeps the
58// runner's disk bounded (Sweep).
59type Files struct {
60 State *State
61 SessionRoot string
62 Logger *slog.Logger
63 // Quota bounds what delivered attachments may hold; zero is DefaultQuota.
64 Quota Quota
65
66 mu sync.Mutex
67 // fault fails a step of finishing a file, in tests of a crash there.
68 fault func(step string) error
69}
70
71// Quota bounds attachments on the runner, per person and in all: those
72// delivered and those still arriving (by their declared size). A new file
73// is admitted only if it fits, after the oldest delivered files that
74// nothing protects make room; otherwise it is refused ("runner storage
75// full") and its turn fails in words. A file a running turn names, or one
76// admitted and not yet named by its message, is never removed.
77type Quota struct {
78 PersonBytes, PersonFiles, TotalBytes, TotalFiles int64
79}
80
81// DefaultQuota: fifty full messages a person, four people's worth in all.
82var DefaultQuota = Quota{PersonBytes: 500 << 20, PersonFiles: 1000, TotalBytes: 2 << 30, TotalFiles: 4000}
83
84func (f *Files) quota() Quota {
85 if f.Quota == (Quota{}) {
86 return DefaultQuota
87 }
88 return f.Quota
89}
90
91func (f *Files) step(name string) error {
92 if f.fault != nil {
93 return f.fault(name)
94 }
95 return nil
96}
97
98// valid reports a chunk the runner will write: a known kind and type, a
99// safe name, and a size, count and length that agree.
100func validChunk(c wire.AttachmentChunk) bool {
101 if c.Person == "" || !attachmentID.MatchString(c.ID) || c.Size < 1 || c.Size > attach.MaxBytes {
102 return false
103 }
104 if c.Kind != wire.AttachmentImage && c.Kind != wire.AttachmentFile || !attach.Allowed(c.MediaType) || attach.IsImage(c.MediaType) != (c.Kind == wire.AttachmentImage) {
105 return false
106 }
107 if c.Name == "" || attach.SafeName(c.Name) != c.Name {
108 return false
109 }
110 if raw, err := hex.DecodeString(c.SHA256); err != nil || len(raw) != sha256.Size {
111 return false
112 }
113 if c.Count != attach.Chunks(c.Size) || c.Index < 0 || c.Index >= c.Count {
114 return false
115 }
116 want := attach.ChunkBytes
117 if c.Index == c.Count-1 {
118 want = int(c.Size - int64(c.Index)*attach.ChunkBytes)
119 }
120 return len(c.Data) == want
121}
122
123// errMismatch is a whole file whose size or SHA-256 is wrong: its bytes
124// came wrong and cannot be put right here, so it is discarded.
125var errMismatch = errors.New("attachment size or sha256 does not match")
126
127// Accept applies one chunk exactly once. A chunk that is not valid is
128// dropped (logged, then acked): the turn that names it fails visibly.
129// Any filesystem failure returns an error, so the frame is not acked and
130// comes again, with every chunk written so far kept: finishing restarts
131// from where it stopped.
132func (f *Files) Accept(ctx context.Context, frameID string, c wire.AttachmentChunk) error {
133 if !validChunk(c) {
134 f.log("attachment chunk refused", errors.New(c.ID))
135 _, err := f.State.SeenResult(ctx, frameID)
136 return err
137 }
138 f.mu.Lock()
139 defer f.mu.Unlock()
140 desk, err := OpenDesk(f.SessionRoot, c.Person)
141 if err != nil {
142 return err
143 }
144 final := filepath.Join(desk.Dir, attachmentsDir, c.ID, c.Name)
145 incoming := filepath.Join(filepath.Dir(desk.Dir), "incoming")
146 part, ready := filepath.Join(incoming, c.ID+".part"), filepath.Join(incoming, c.ID+".ready")
147 if f.State.refused(ctx, c.ID) {
148 // Refused for room: every chunk is acked unwritten.
149 _, err := f.State.SeenResult(ctx, frameID)
150 return err
151 }
152 if info, err := os.Lstat(final); err == nil && info.Mode().IsRegular() && info.Size() == c.Size {
153 // Delivered already (an ack was lost, or the turn moved): tidy up
154 // what a crash after delivery may have left, then ack.
155 if err := f.forget(ctx, c.ID, part, ready); err != nil {
156 return err
157 }
158 _, err := f.State.SeenResult(ctx, frameID)
159 return err
160 }
161 admitted, err := f.admit(ctx, c.Person, c.ID, c.Size)
162 if err != nil {
163 return err
164 }
165 if !admitted {
166 f.log("attachment refused: runner storage full", errors.New(c.ID))
167 _, err := f.State.SeenResult(ctx, frameID)
168 return err
169 }
170 if _, err := os.Lstat(ready); err != nil {
171 // Not yet whole: write this chunk.
172 if err := os.MkdirAll(incoming, 0700); err != nil {
173 return err
174 }
175 if err := writeAt(part, int64(c.Index)*attach.ChunkBytes, c.Data); err != nil {
176 return err
177 }
178 }
179 have := 0
180 err = f.State.tx(ctx, func(t *sql.Tx) error {
181 if _, err := seen(t, frameID); err != nil {
182 return err
183 }
184 if _, err := t.Exec("INSERT INTO file_chunks(attachment_id, idx) VALUES(?,?) ON CONFLICT DO NOTHING", c.ID, c.Index); err != nil {
185 return err
186 }
187 return t.QueryRow("SELECT count(*) FROM file_chunks WHERE attachment_id=?", c.ID).Scan(&have)
188 })
189 if err != nil || have < c.Count {
190 return err
191 }
192 err = f.finish(part, ready, final, c.Size, c.SHA256)
193 if errors.Is(err, errMismatch) {
194 // Discarded: the turn that names it fails; a resend starts afresh.
195 f.log("attachment discarded", err)
196 os.Remove(part)
197 if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_admits WHERE attachment_id=?", c.ID); err != nil {
198 return err
199 }
200 return f.forget(ctx, c.ID, part, ready)
201 }
202 if err != nil {
203 return err
204 }
205 if err := f.forget(ctx, c.ID, part, ready); err != nil {
206 return err
207 }
208 _, err = f.State.db.ExecContext(ctx, "UPDATE file_admits SET state=? WHERE attachment_id=?", admitDelivered, c.ID)
209 return err
210}
211
212// forget drops a finished or discarded file's chunk records and leftovers.
213func (f *Files) forget(ctx context.Context, id, part, ready string) error {
214 if err := f.step("forget"); err != nil {
215 return err
216 }
217 for _, p := range []string{part, ready} {
218 if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) {
219 return err
220 }
221 }
222 _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id)
223 return err
224}
225
226func writeAt(path string, off int64, data []byte) error {
227 fd, err := unix.Open(path, unix.O_WRONLY|unix.O_CREAT|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600)
228 if err != nil {
229 return err
230 }
231 file := os.NewFile(uintptr(fd), path)
232 defer file.Close()
233 if _, err = file.WriteAt(data, off); err != nil {
234 return err
235 }
236 return file.Sync()
237}
238
239// finish checks the assembled file and moves it into the desk, read-only,
240// through steps that each survive a crash: the checked file becomes
241// <id>.ready by a rename (no more chunks are written once it exists), is
242// made read-only, and is renamed into the desk. Replay picks up at
243// whichever step was next. Only a wrong size or hash is errMismatch.
244func (f *Files) finish(part, ready, final string, size int64, sum string) error {
245 if _, err := os.Lstat(ready); errors.Is(err, fs.ErrNotExist) {
246 if err := f.step("verify"); err != nil {
247 return err
248 }
249 if err := check(part, size, sum); err != nil {
250 return err
251 }
252 if err := f.step("ready"); err != nil {
253 return err
254 }
255 if err := os.Rename(part, ready); err != nil {
256 return err
257 }
258 } else if err != nil {
259 return err
260 } else if err := check(ready, size, sum); err != nil {
261 return err
262 }
263 if err := f.step("chmod"); err != nil {
264 return err
265 }
266 if err := os.Chmod(ready, 0400); err != nil {
267 return err
268 }
269 if err := f.step("mkdir"); err != nil {
270 return err
271 }
272 if err := os.MkdirAll(filepath.Dir(final), 0700); err != nil {
273 return err
274 }
275 if err := f.step("rename"); err != nil {
276 return err
277 }
278 return os.Rename(ready, final)
279}
280
281// check reads a file whole: errMismatch when its size or hash is wrong,
282// any other error when it cannot be read.
283func check(path string, size int64, sum string) error {
284 in, err := os.Open(path)
285 if err != nil {
286 return err
287 }
288 defer in.Close()
289 h := sha256.New()
290 n, err := io.Copy(h, in)
291 if err != nil {
292 return err
293 }
294 if n != size || hex.EncodeToString(h.Sum(nil)) != sum {
295 return errMismatch
296 }
297 return nil
298}
299
300// Run sweeps every interval until ctx ends: the bounds below, for every
301// person, whether or not anything arrives.
302func (f *Files) Run(ctx context.Context, every time.Duration) {
303 t := time.NewTicker(every)
304 defer t.Stop()
305 for {
306 f.Sweep(ctx)
307 select {
308 case <-ctx.Done():
309 return
310 case <-t.C:
311 }
312 }
313}
314
315// Sweep keeps the runner's attachments bounded and its records true:
316// unfinished files past keepParts go with their chunk records; chunk
317// records with no file go; delivered files past keepFiles go; then, over
318// the quota for a person or the runner, the oldest delivered files that
319// nothing protects go first. If what is protected cannot be read (a query
320// fails, a record does not decode, ctx ends), nothing is removed.
321func (f *Files) Sweep(ctx context.Context) {
322 f.mu.Lock()
323 defer f.mu.Unlock()
324 if err := f.sweep(ctx); err != nil {
325 f.log("attachment sweep", err)
326 }
327}
328
329type heldDir struct {
330 person, path, id string
331 at time.Time
332 bytes, files int64
333}
334
335// usage is bytes and files.
336type usage [2]int64
337
338// protected is every attachment that must stay: named by a running turn,
339// or admitted and not yet named by its message (within keepParts). Any
340// failure to read it is an error: nothing is then removed.
341func (f *Files) protected(ctx context.Context) (map[string]bool, error) {
342 if err := ctx.Err(); err != nil {
343 return nil, err
344 }
345 out, err := f.State.runningAttachments(ctx)
346 if err != nil {
347 return nil, err
348 }
349 rows, err := f.State.db.QueryContext(ctx, "SELECT attachment_id FROM file_admits WHERE at >= ?", time.Now().Add(-keepParts).UTC().Format(fileStamp))
350 if err != nil {
351 return nil, err
352 }
353 defer rows.Close()
354 for rows.Next() {
355 var id string
356 if err := rows.Scan(&id); err != nil {
357 return nil, err
358 }
359 out[id] = true
360 }
361 return out, rows.Err()
362}
363
364// arriving is what admitted files still arriving hold, by person key and
365// in all (their declared size, one file each).
366func (f *Files) arriving(ctx context.Context) (map[string]usage, usage, error) {
367 by := map[string]usage{}
368 var total usage
369 rows, err := f.State.db.QueryContext(ctx, "SELECT person, size FROM file_admits WHERE state=?", admitIncoming)
370 if err != nil {
371 return nil, total, err
372 }
373 defer rows.Close()
374 for rows.Next() {
375 var p string
376 var n int64
377 if err := rows.Scan(&p, &n); err != nil {
378 return nil, total, err
379 }
380 v := by[p]
381 by[p] = usage{v[0] + n, v[1] + 1}
382 total = usage{total[0] + n, total[1] + 1}
383 }
384 return by, total, rows.Err()
385}
386
387// delivered lists delivered attachments, oldest first.
388func (f *Files) delivered() []heldDir {
389 var all []heldDir
390 people, _ := os.ReadDir(f.SessionRoot)
391 for _, p := range people {
392 root := filepath.Join(f.SessionRoot, p.Name(), "desk", attachmentsDir)
393 dirs, _ := os.ReadDir(root)
394 for _, d := range dirs {
395 info, err := d.Info()
396 if err != nil || !d.IsDir() || !attachmentID.MatchString(d.Name()) {
397 continue
398 }
399 h := heldDir{person: p.Name(), path: filepath.Join(root, d.Name()), id: d.Name(), at: info.ModTime()}
400 files, _ := os.ReadDir(h.path)
401 for _, x := range files {
402 if xi, err := x.Info(); err == nil {
403 h.bytes += xi.Size()
404 h.files++
405 }
406 }
407 all = append(all, h)
408 }
409 }
410 sort.Slice(all, func(i, j int) bool { return all[i].at.Before(all[j].at) })
411 return all
412}
413
414// makeRoom removes the oldest unprotected delivered files until every
415// person and the runner fit the quota with extra added for person (""
416// for none). It reports whether they fit; it removes nothing a protected
417// file needs, and only files that help: a person over quota loses their
418// own oldest first, the runner's oldest after.
419func (f *Files) makeRoom(ctx context.Context, protect map[string]bool, person string, extra usage) (bool, error) {
420 byArriving, arriving, err := f.arriving(ctx)
421 if err != nil {
422 return false, err
423 }
424 all := f.delivered()
425 q := f.quota()
426 by := map[string]usage{}
427 for p, v := range byArriving {
428 by[p] = v
429 }
430 total := arriving
431 for _, h := range all {
432 v := by[h.person]
433 by[h.person] = usage{v[0] + h.bytes, v[1] + h.files}
434 total = usage{total[0] + h.bytes, total[1] + h.files}
435 }
436 if person != "" {
437 v := by[person]
438 by[person] = usage{v[0] + extra[0], v[1] + extra[1]}
439 total = usage{total[0] + extra[0], total[1] + extra[1]}
440 }
441 over := func(u usage, bytes, files int64) bool { return u[0] > bytes || u[1] > files }
442 for _, h := range all {
443 personOver := over(by[h.person], q.PersonBytes, q.PersonFiles)
444 if !personOver && !over(total, q.TotalBytes, q.TotalFiles) {
445 continue
446 }
447 if protect[h.id] {
448 continue
449 }
450 if err := ctx.Err(); err != nil {
451 return false, err
452 }
453 removeAll(h.path)
454 v := by[h.person]
455 by[h.person] = usage{v[0] - h.bytes, v[1] - h.files}
456 total = usage{total[0] - h.bytes, total[1] - h.files}
457 }
458 for p, u := range by {
459 if over(u, q.PersonBytes, q.PersonFiles) && (person == "" || p == person) {
460 return false, nil
461 }
462 }
463 return !over(total, q.TotalBytes, q.TotalFiles), nil
464}
465
466// admit takes a new attachment in if it fits once room is made, recording
467// it as arriving; one admitted already stays admitted. False refuses it
468// for good (file_refused): its chunks are acked unwritten.
469func (f *Files) admit(ctx context.Context, person, id string, size int64) (bool, error) {
470 var n int
471 if err := f.State.db.QueryRowContext(ctx, "SELECT count(*) FROM file_admits WHERE attachment_id=?", id).Scan(&n); err != nil || n > 0 {
472 return n > 0, err
473 }
474 protect, err := f.protected(ctx)
475 if err != nil {
476 return false, err
477 }
478 key := filepath.Base(personDir(f.SessionRoot, person))
479 fits, err := f.makeRoom(ctx, protect, key, usage{size, 1})
480 if err != nil {
481 return false, err
482 }
483 at := time.Now().UTC().Format(fileStamp)
484 if !fits {
485 _, err := f.State.db.ExecContext(ctx, "INSERT INTO file_refused(attachment_id, at) VALUES(?,?) ON CONFLICT DO NOTHING", id, at)
486 return false, err
487 }
488 _, err = f.State.db.ExecContext(ctx, "INSERT INTO file_admits(attachment_id, person, size, state, at) VALUES(?,?,?,?,?)", id, key, size, admitIncoming, at)
489 return err == nil, err
490}
491
492func (f *Files) sweep(ctx context.Context) error {
493 if f.SessionRoot == "" {
494 return nil
495 }
496 protect, err := f.protected(ctx)
497 if err != nil {
498 return err
499 }
500 stale := time.Now().Add(-keepParts)
501 people, _ := os.ReadDir(f.SessionRoot)
502 partial := map[string]bool{}
503 for _, p := range people {
504 if !p.IsDir() {
505 continue
506 }
507 incoming := filepath.Join(f.SessionRoot, p.Name(), "incoming")
508 entries, _ := os.ReadDir(incoming)
509 for _, e := range entries {
510 name := e.Name()
511 id := strings.TrimSuffix(strings.TrimSuffix(name, ".part"), ".ready")
512 info, err := e.Info()
513 if err != nil || id == name {
514 continue
515 }
516 if info.ModTime().Before(stale) && !protect[id] {
517 os.Remove(filepath.Join(incoming, name))
518 if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id); err != nil {
519 return err
520 }
521 continue
522 }
523 partial[id] = true
524 }
525 }
526 for _, h := range f.delivered() {
527 if h.at.Before(time.Now().Add(-keepFiles)) && !protect[h.id] {
528 removeAll(h.path)
529 }
530 }
531 // Chunk records whose file is gone (pruned, or never written).
532 rows, err := f.State.db.QueryContext(ctx, "SELECT DISTINCT attachment_id FROM file_chunks")
533 if err != nil {
534 return err
535 }
536 var gone []string
537 for rows.Next() {
538 var id string
539 if err := rows.Scan(&id); err != nil {
540 rows.Close()
541 return err
542 }
543 if !partial[id] {
544 gone = append(gone, id)
545 }
546 }
547 if err := rows.Err(); err != nil {
548 rows.Close()
549 return err
550 }
551 rows.Close()
552 for _, id := range gone {
553 if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id); err != nil {
554 return err
555 }
556 }
557 // Admissions and refusals past their time.
558 cut := stale.UTC().Format(fileStamp)
559 if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_admits WHERE at < ?", cut); err != nil {
560 return err
561 }
562 if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_refused WHERE at < ?", time.Now().Add(-keepFiles).UTC().Format(fileStamp)); err != nil {
563 return err
564 }
565 _, err = f.makeRoom(ctx, protect, "", usage{})
566 return err
567}
568
569// removeAll removes a tree whose files were made read-only.
570func removeAll(dir string) {
571 _ = filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
572 if err == nil && d.IsDir() {
573 os.Chmod(p, 0700)
574 }
575 return nil
576 })
577 os.RemoveAll(dir)
578}
579
580func (f *Files) log(msg string, err error) {
581 if f.Logger != nil && err != nil {
582 f.Logger.Warn(msg, "err", sanitize(err))
583 }
584}
585
586// heldFile is one of a turn's attachments, checked on the desk.
587type heldFile struct {
588 wire.AttachmentRef
589 // Host is the file on the runner; Path is where the model sees it.
590 Host, Path string
591}
592
593// errMissingFile fails a turn whose attachment is not on the desk whole.
594var errMissingFile = errors.New("attachment unavailable")
595
596// heldFiles finds each of a turn's attachments on the person's desk and
597// checks its size and SHA-256 again, just before the turn uses it.
598func heldFiles(desk *Desk, refs []wire.AttachmentRef) ([]heldFile, error) {
599 out := make([]heldFile, 0, len(refs))
600 for _, r := range refs {
601 if !attachmentID.MatchString(r.ID) || r.Name == "" || attach.SafeName(r.Name) != r.Name {
602 return nil, errMissingFile
603 }
604 host := filepath.Join(desk.Dir, attachmentsDir, r.ID, r.Name)
605 in, err := os.OpenFile(host, os.O_RDONLY|unix.O_NOFOLLOW, 0)
606 if err != nil {
607 return nil, errMissingFile
608 }
609 h := sha256.New()
610 n, err := io.Copy(h, in)
611 in.Close()
612 if err != nil || n != r.Size || hex.EncodeToString(h.Sum(nil)) != r.SHA256 {
613 return nil, errMissingFile
614 }
615 out = append(out, heldFile{AttachmentRef: r, Host: host, Path: "/workspace/" + attachmentsDir + "/" + r.ID + "/" + r.Name})
616 }
617 return out, nil
618}
619