| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/attach" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | "amadan.net/oficina/equipo/internal/wire/wiretest" |
| 18 | "github.com/coder/websocket" |
| 19 | ) |
| 20 | |
| 21 | func chunkFrames(t *testing.T, person, id, name string, data []byte, first int) ([][]byte, wire.AttachmentRef) { |
| 22 | t.Helper() |
| 23 | sum := sha256.Sum256(data) |
| 24 | ref := wire.AttachmentRef{ID: id, Kind: wire.AttachmentFile, Name: name, MediaType: attach.Text, Size: int64(len(data)), SHA256: hex.EncodeToString(sum[:])} |
| 25 | count := attach.Chunks(ref.Size) |
| 26 | var out [][]byte |
| 27 | for i := 0; i < count; i++ { |
| 28 | end := min(len(data), (i+1)*attach.ChunkBytes) |
| 29 | f, _ := wire.NewFrame("c"+itoa(int64(first+i)), wire.FrameAttachment, wire.AttachmentChunk{Person: person, AttachmentRef: ref, Index: i, Count: count, Data: data[i*attach.ChunkBytes : end]}) |
| 30 | raw, _ := json.Marshal(f) |
| 31 | out = append(out, raw) |
| 32 | } |
| 33 | return out, ref |
| 34 | } |
| 35 | |
| 36 | // handshake answers a fresh connection: hello in, welcome out, sync in. |
| 37 | func handshake(t *testing.T, c *websocket.Conn) { |
| 38 | t.Helper() |
| 39 | read(t, c, wire.FrameHello) |
| 40 | write(t, c, wiretest.Fixture("frames/welcome.json")) |
| 41 | read(t, c, wire.FrameSync) |
| 42 | } |
| 43 | |
| 44 | func ackOf(t *testing.T, c *websocket.Conn) string { |
| 45 | t.Helper() |
| 46 | f, _ := read(t, c, wire.FrameAck) |
| 47 | var a wire.Ack |
| 48 | json.Unmarshal(f.Data, &a) |
| 49 | return a.ID |
| 50 | } |
| 51 | |
| 52 | // TestRunnerAttachmentExactlyOnce: chunks are written and acked one by |
| 53 | // one; the stream drops after two; on reconnect the instance resends what |
| 54 | // it has not seen acked (and, as a resend can, one it has); the file is |
| 55 | // assembled once, checked against its SHA-256, moved read-only into the |
| 56 | // desk, and the turn that names it runs once with it. |
| 57 | func TestRunnerAttachmentExactlyOnce(t *testing.T) { |
| 58 | inst := newFakeInstance(t) |
| 59 | coord := &stubCoordinator{} |
| 60 | link, state, _, _ := startLink(t, inst.url, coord) |
| 61 | c := <-inst.conns |
| 62 | handshake(t, c) |
| 63 | data := []byte(strings.Repeat("a line of the log\n", 20000)) // 360,000 bytes: 3 chunks |
| 64 | frames, ref := chunkFrames(t, "owner@example.com", "at_0001notes", "build.log", data, 10) |
| 65 | for _, raw := range frames[:2] { |
| 66 | write(t, c, raw) |
| 67 | ackOf(t, c) |
| 68 | } |
| 69 | c.Close(websocket.StatusGoingAway, "dropped") |
| 70 | |
| 71 | c = <-inst.conns |
| 72 | handshake(t, c) |
| 73 | for _, raw := range frames { |
| 74 | write(t, c, raw) |
| 75 | ackOf(t, c) |
| 76 | } |
| 77 | msg, _ := wire.NewFrame("c13", wire.FrameMessage, wire.MessageCommand{Person: "owner@example.com", TurnID: "t_0001", Attempt: 1, Text: "what broke?", PersonText: []string{"what broke?"}, Tail: []wire.TailMessage{}, Attachments: []wire.AttachmentRef{ref}}) |
| 78 | rawMsg, _ := json.Marshal(msg) |
| 79 | write(t, c, rawMsg) |
| 80 | if id := ackOf(t, c); id != "c13" { |
| 81 | t.Fatalf("ack %s", id) |
| 82 | } |
| 83 | read(t, c, wire.FrameReply) |
| 84 | // Resent again after the turn (an ack the instance lost): no-ops. |
| 85 | write(t, c, frames[2]) |
| 86 | ackOf(t, c) |
| 87 | write(t, c, rawMsg) |
| 88 | ackOf(t, c) |
| 89 | time.Sleep(100 * time.Millisecond) |
| 90 | coord.mu.Lock() |
| 91 | turns := append([]TurnInput(nil), coord.turns...) |
| 92 | coord.mu.Unlock() |
| 93 | if len(turns) != 1 || len(turns[0].Attachments) != 1 || turns[0].Attachments[0] != ref { |
| 94 | t.Fatalf("turns %+v", turns) |
| 95 | } |
| 96 | desk, err := OpenDesk(link.Files.SessionRoot, "owner@example.com") |
| 97 | if err != nil { |
| 98 | t.Fatal(err) |
| 99 | } |
| 100 | held, err := heldFiles(desk, turns[0].Attachments) |
| 101 | if err != nil || len(held) != 1 || held[0].Path != "/workspace/attachments/at_0001notes/build.log" { |
| 102 | t.Fatalf("held %+v %v", held, err) |
| 103 | } |
| 104 | info, err := os.Stat(held[0].Host) |
| 105 | if err != nil || info.Mode().Perm() != 0400 { |
| 106 | t.Fatalf("delivered file %v %v", info, err) |
| 107 | } |
| 108 | if parts, _ := filepath.Glob(filepath.Join(filepath.Dir(desk.Dir), "incoming", "*")); len(parts) != 0 { |
| 109 | t.Fatalf("leftover parts %v", parts) |
| 110 | } |
| 111 | var left int |
| 112 | state.db.QueryRow("SELECT count(*) FROM file_chunks").Scan(&left) |
| 113 | if left != 0 { |
| 114 | t.Fatalf("%d chunk rows left", left) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // TestAttachmentIntegrity: a file whose bytes do not match its SHA-256 is |
| 119 | // discarded, not delivered; a chunk that is not valid is refused; and a |
| 120 | // turn's files are checked again before it starts. |
| 121 | func TestAttachmentIntegrity(t *testing.T) { |
| 122 | ctx := context.Background() |
| 123 | state, err := OpenState(ctx, t.TempDir()) |
| 124 | if err != nil { |
| 125 | t.Fatal(err) |
| 126 | } |
| 127 | defer state.Close() |
| 128 | root := filepath.Join(t.TempDir(), "sessions") |
| 129 | os.MkdirAll(root, 0700) |
| 130 | files := &Files{State: state, SessionRoot: root} |
| 131 | data := []byte("the real notes\n") |
| 132 | sum := sha256.Sum256([]byte("other bytes entirely")) |
| 133 | ref := wire.AttachmentRef{ID: "at_0002forged", Kind: wire.AttachmentFile, Name: "notes.txt", MediaType: attach.Text, Size: int64(len(data)), SHA256: hex.EncodeToString(sum[:])} |
| 134 | if err := files.Accept(ctx, "c1", wire.AttachmentChunk{Person: "p@example.com", AttachmentRef: ref, Index: 0, Count: 1, Data: data}); err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | desk, _ := OpenDesk(root, "p@example.com") |
| 138 | if _, err := os.Stat(filepath.Join(desk.Dir, "attachments", ref.ID, ref.Name)); !os.IsNotExist(err) { |
| 139 | t.Fatal("a file that does not match its hash was delivered") |
| 140 | } |
| 141 | if _, err := heldFiles(desk, []wire.AttachmentRef{ref}); err != errMissingFile { |
| 142 | t.Fatalf("held a missing file: %v", err) |
| 143 | } |
| 144 | // Not valid: a path in the name, a short chunk, an unknown type. |
| 145 | good := sha256.Sum256(data) |
| 146 | ref.SHA256 = hex.EncodeToString(good[:]) |
| 147 | for i, bad := range []wire.AttachmentChunk{ |
| 148 | {Person: "p@example.com", AttachmentRef: wire.AttachmentRef{ID: ref.ID, Kind: ref.Kind, Name: "../escape.txt", MediaType: ref.MediaType, Size: ref.Size, SHA256: ref.SHA256}, Count: 1, Data: data}, |
| 149 | {Person: "p@example.com", AttachmentRef: ref, Count: 1, Data: data[:3]}, |
| 150 | {Person: "p@example.com", AttachmentRef: wire.AttachmentRef{ID: ref.ID, Kind: ref.Kind, Name: ref.Name, MediaType: "application/x-sh", Size: ref.Size, SHA256: ref.SHA256}, Count: 1, Data: data}, |
| 151 | {Person: "p@example.com", AttachmentRef: ref, Index: 1, Count: 2, Data: data}, |
| 152 | } { |
| 153 | if validChunk(bad) || files.Accept(ctx, "bad"+itoa(int64(i)), bad) != nil { |
| 154 | t.Fatalf("chunk %d was taken", i) |
| 155 | } |
| 156 | } |
| 157 | if entries, _ := os.ReadDir(filepath.Join(desk.Dir, "attachments")); len(entries) != 0 { |
| 158 | t.Fatal("a refused chunk left a file on the desk") |
| 159 | } |
| 160 | // Whole and matching: delivered; then changed on disk: refused again. |
| 161 | if err := files.Accept(ctx, "c2", wire.AttachmentChunk{Person: "p@example.com", AttachmentRef: ref, Index: 0, Count: 1, Data: data}); err != nil { |
| 162 | t.Fatal(err) |
| 163 | } |
| 164 | held, err := heldFiles(desk, []wire.AttachmentRef{ref}) |
| 165 | if err != nil { |
| 166 | t.Fatal(err) |
| 167 | } |
| 168 | os.Chmod(held[0].Host, 0600) |
| 169 | os.WriteFile(held[0].Host, []byte("the real notez\n"), 0600) |
| 170 | if _, err := heldFiles(desk, []wire.AttachmentRef{ref}); err != errMissingFile { |
| 171 | t.Fatal("a changed file was used") |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | func filesRig(t *testing.T) (*Files, context.Context) { |
| 176 | t.Helper() |
| 177 | ctx := context.Background() |
| 178 | state, err := OpenState(ctx, t.TempDir()) |
| 179 | if err != nil { |
| 180 | t.Fatal(err) |
| 181 | } |
| 182 | t.Cleanup(func() { state.Close() }) |
| 183 | root := filepath.Join(t.TempDir(), "sessions") |
| 184 | os.MkdirAll(root, 0700) |
| 185 | return &Files{State: state, SessionRoot: root}, ctx |
| 186 | } |
| 187 | |
| 188 | func chunksOf(person, id, name string, data []byte) ([]wire.AttachmentChunk, wire.AttachmentRef) { |
| 189 | sum := sha256.Sum256(data) |
| 190 | ref := wire.AttachmentRef{ID: id, Kind: wire.AttachmentFile, Name: name, MediaType: attach.Text, Size: int64(len(data)), SHA256: hex.EncodeToString(sum[:])} |
| 191 | n := attach.Chunks(ref.Size) |
| 192 | var out []wire.AttachmentChunk |
| 193 | for i := 0; i < n; i++ { |
| 194 | out = append(out, wire.AttachmentChunk{Person: person, AttachmentRef: ref, Index: i, Count: n, Data: data[i*attach.ChunkBytes : min(len(data), (i+1)*attach.ChunkBytes)]}) |
| 195 | } |
| 196 | return out, ref |
| 197 | } |
| 198 | |
| 199 | // Astra round 1: a filesystem failure while finishing deleted the chunks |
| 200 | // and let the frame be acked, so the file could never be rebuilt; a crash |
| 201 | // between chmod and rename left a part replay could not write. At each |
| 202 | // step of finishing, a failure returns an error (the frame is not acked) |
| 203 | // and keeps every chunk; replaying the frame delivers the file whole. |
| 204 | func TestAttachmentFinishCrashes(t *testing.T) { |
| 205 | data := []byte(strings.Repeat("crash at each step\n", 16000)) // 3 chunks |
| 206 | for _, step := range []string{"verify", "ready", "chmod", "mkdir", "rename", "forget"} { |
| 207 | t.Run(step, func(t *testing.T) { |
| 208 | t.Parallel() |
| 209 | f, ctx := filesRig(t) |
| 210 | chunks, ref := chunksOf("p@example.com", "at_crash"+step, "build.log", data) |
| 211 | for i, c := range chunks[:len(chunks)-1] { |
| 212 | if err := f.Accept(ctx, "c"+itoa(int64(i)), c); err != nil { |
| 213 | t.Fatal(err) |
| 214 | } |
| 215 | } |
| 216 | f.fault = func(s string) error { |
| 217 | if s == step { |
| 218 | return errors.New("disk said no at " + s) |
| 219 | } |
| 220 | return nil |
| 221 | } |
| 222 | last := chunks[len(chunks)-1] |
| 223 | if err := f.Accept(ctx, "c-last", last); err == nil { |
| 224 | t.Fatal("a failure while finishing was acked") |
| 225 | } |
| 226 | var rows int |
| 227 | f.State.db.QueryRow("SELECT count(*) FROM file_chunks WHERE attachment_id=?", ref.ID).Scan(&rows) |
| 228 | if step != "forget" && rows != len(chunks) { |
| 229 | t.Fatalf("%d of %d chunk records kept", rows, len(chunks)) |
| 230 | } |
| 231 | f.fault = nil |
| 232 | if err := f.Accept(ctx, "c-last", last); err != nil { |
| 233 | t.Fatalf("replay: %v", err) |
| 234 | } |
| 235 | desk, _ := OpenDesk(f.SessionRoot, "p@example.com") |
| 236 | held, err := heldFiles(desk, []wire.AttachmentRef{ref}) |
| 237 | if err != nil { |
| 238 | t.Fatalf("not delivered after replay: %v", err) |
| 239 | } |
| 240 | if info, _ := os.Stat(held[0].Host); info.Mode().Perm() != 0400 { |
| 241 | t.Fatalf("mode %v", info.Mode()) |
| 242 | } |
| 243 | left, _ := filepath.Glob(filepath.Join(filepath.Dir(desk.Dir), "incoming", "*")) |
| 244 | f.State.db.QueryRow("SELECT count(*) FROM file_chunks").Scan(&rows) |
| 245 | if len(left) != 0 || rows != 0 { |
| 246 | t.Fatalf("left %v and %d records", left, rows) |
| 247 | } |
| 248 | }) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | // Astra round 1: retention had no aggregate bound and ran only when a |
| 253 | // file arrived. Sweep removes stale parts with their records, records with |
| 254 | // no file, files past retention, and, over a person's or the runner's |
| 255 | // quota, the oldest delivered files first; never one a running turn names |
| 256 | // (b3, the newest, stays only because the quota is met without it). |
| 257 | func TestAttachmentSweep(t *testing.T) { |
| 258 | f, ctx := filesRig(t) |
| 259 | deliver := func(person, id string, age time.Duration) wire.AttachmentRef { |
| 260 | t.Helper() |
| 261 | chunks, ref := chunksOf(person, id, "n.txt", []byte(strings.Repeat("x", 100))) |
| 262 | if err := f.Accept(ctx, "f-"+id, chunks[0]); err != nil { |
| 263 | t.Fatal(err) |
| 264 | } |
| 265 | desk, _ := OpenDesk(f.SessionRoot, person) |
| 266 | at := time.Now().Add(-age) |
| 267 | if err := os.Chtimes(filepath.Join(desk.Dir, attachmentsDir, id), at, at); err != nil { |
| 268 | t.Fatal(err) |
| 269 | } |
| 270 | return ref |
| 271 | } |
| 272 | exists := func(person, id string) bool { |
| 273 | desk, _ := OpenDesk(f.SessionRoot, person) |
| 274 | _, err := os.Stat(filepath.Join(desk.Dir, attachmentsDir, id)) |
| 275 | return err == nil |
| 276 | } |
| 277 | const a, b = "a@example.com", "b@example.com" |
| 278 | // a1, the oldest, is named by a running turn; so is b1, past retention. |
| 279 | ref := func(id string) wire.AttachmentRef { |
| 280 | _, r := chunksOf("", id, "n.txt", []byte(strings.Repeat("x", 100))) |
| 281 | return r |
| 282 | } |
| 283 | if err := f.State.Accept(ctx, "m1", wire.MessageCommand{Person: a, TurnID: "t_1", Attempt: 1, Text: "x", PersonText: []string{"x"}, Tail: []wire.TailMessage{}, Attachments: []wire.AttachmentRef{ref("at_a1aaaaaaaa"), ref("at_b1bbbbbbbb")}}); err != nil { |
| 284 | t.Fatal(err) |
| 285 | } |
| 286 | deliver(a, "at_a1aaaaaaaa", 5*time.Hour) |
| 287 | deliver(a, "at_a2aaaaaaaa", 4*time.Hour) |
| 288 | deliver(a, "at_a3aaaaaaaa", 3*time.Hour) |
| 289 | deliver(a, "at_a4aaaaaaaa", 2*time.Hour) |
| 290 | deliver(b, "at_b1bbbbbbbb", 15*24*time.Hour) |
| 291 | deliver(b, "at_b2bbbbbbbb", 6*time.Hour) |
| 292 | deliver(b, "at_b3bbbbbbbb", 30*time.Minute) |
| 293 | // A stale part with its records, and records with no file at all. |
| 294 | desk, _ := OpenDesk(f.SessionRoot, b) |
| 295 | incoming := filepath.Join(filepath.Dir(desk.Dir), "incoming") |
| 296 | os.MkdirAll(incoming, 0700) |
| 297 | stale := filepath.Join(incoming, "at_stale0000.part") |
| 298 | os.WriteFile(stale, []byte("half"), 0600) |
| 299 | then := time.Now().Add(-3 * 24 * time.Hour) |
| 300 | os.Chtimes(stale, then, then) |
| 301 | fresh := filepath.Join(incoming, "at_fresh0000.part") |
| 302 | os.WriteFile(fresh, []byte("half"), 0600) |
| 303 | for _, id := range []string{"at_stale0000", "at_orphan000", "at_fresh0000"} { |
| 304 | f.State.db.Exec("INSERT INTO file_chunks(attachment_id, idx) VALUES(?,0)", id) |
| 305 | } |
| 306 | // Their messages came and went (the admissions are done); then the |
| 307 | // quota shrinks below what is held. |
| 308 | f.State.db.Exec("DELETE FROM file_admits") |
| 309 | f.Quota = Quota{PersonBytes: 250, PersonFiles: 100, TotalBytes: 1 << 30, TotalFiles: 4} |
| 310 | f.Sweep(ctx) |
| 311 | // Person a: 400 bytes over 250; a1 is protected, so a2 and a3 go. |
| 312 | for id, want := range map[string]bool{"at_a1aaaaaaaa": true, "at_a2aaaaaaaa": false, "at_a3aaaaaaaa": false, "at_a4aaaaaaaa": true} { |
| 313 | if exists(a, id) != want { |
| 314 | t.Fatalf("%s kept=%v, want %v", id, !want, want) |
| 315 | } |
| 316 | } |
| 317 | // The runner: at most 4 files; b1 is protected though past retention. |
| 318 | for id, want := range map[string]bool{"at_b1bbbbbbbb": true, "at_b2bbbbbbbb": false, "at_b3bbbbbbbb": true} { |
| 319 | if exists(b, id) != want { |
| 320 | t.Fatalf("%s kept=%v, want %v", id, !want, want) |
| 321 | } |
| 322 | } |
| 323 | if _, err := os.Stat(stale); !os.IsNotExist(err) { |
| 324 | t.Fatal("a stale part stayed") |
| 325 | } |
| 326 | var ids []string |
| 327 | rows, _ := f.State.db.Query("SELECT attachment_id FROM file_chunks ORDER BY 1") |
| 328 | for rows.Next() { |
| 329 | var id string |
| 330 | rows.Scan(&id) |
| 331 | ids = append(ids, id) |
| 332 | } |
| 333 | rows.Close() |
| 334 | if strings.Join(ids, ",") != "at_fresh0000" { |
| 335 | t.Fatalf("chunk records left %v, want only the fresh part's", ids) |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | // held is what delivered and arriving attachments hold on disk: bytes and |
| 340 | // files under every desk's attachments and every incoming directory. |
| 341 | func held(t *testing.T, root string) (int64, int) { |
| 342 | t.Helper() |
| 343 | var bytes int64 |
| 344 | files := 0 |
| 345 | for _, pattern := range []string{"*/desk/attachments/*/*", "*/incoming/*"} { |
| 346 | paths, _ := filepath.Glob(filepath.Join(root, pattern)) |
| 347 | for _, p := range paths { |
| 348 | if info, err := os.Stat(p); err == nil && info.Mode().IsRegular() { |
| 349 | bytes += info.Size() |
| 350 | files++ |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | return bytes, files |
| 355 | } |
| 356 | |
| 357 | // Astra round 2: the quota exempted every file delivered in the last hour |
| 358 | // and left partial files out, so a 1-file, 1-byte quota held three files. |
| 359 | // Admission counts arriving files by their declared size; room is made from |
| 360 | // the oldest unprotected delivered files; failing that the file is refused |
| 361 | // (runner_storage_full) and its chunks acked unwritten. Never a protected |
| 362 | // file removed. |
| 363 | func TestAttachmentQuotaAdmission(t *testing.T) { |
| 364 | ctx := context.Background() |
| 365 | t.Run("one file one byte", func(t *testing.T) { |
| 366 | t.Parallel() |
| 367 | f, _ := filesRig(t) |
| 368 | f.Quota = Quota{PersonBytes: 1, PersonFiles: 1, TotalBytes: 1, TotalFiles: 1} |
| 369 | for i, id := range []string{"at_q1aaaaaaaa", "at_q2aaaaaaaa", "at_q3aaaaaaaa"} { |
| 370 | chunks, ref := chunksOf("p@example.com", id, "n.txt", []byte("ten bytes!")) |
| 371 | if err := f.Accept(ctx, "q"+itoa(int64(i)), chunks[0]); err != nil { |
| 372 | t.Fatal(err) |
| 373 | } |
| 374 | if b, n := held(t, f.SessionRoot); b > 1 || n > 1 { |
| 375 | t.Fatalf("after %s the runner holds %d bytes in %d files", id, b, n) |
| 376 | } |
| 377 | if !f.State.anyRefused(ctx, []wire.AttachmentRef{ref}) { |
| 378 | t.Fatalf("%s was not refused", id) |
| 379 | } |
| 380 | } |
| 381 | }) |
| 382 | t.Run("room from the oldest unprotected, never the protected", func(t *testing.T) { |
| 383 | t.Parallel() |
| 384 | f, _ := filesRig(t) |
| 385 | f.Quota = Quota{PersonBytes: 100, PersonFiles: 1, TotalBytes: 100, TotalFiles: 1} |
| 386 | ten := []byte("ten bytes!") |
| 387 | c1, r1 := chunksOf("p@example.com", "at_r1aaaaaaaa", "a.txt", ten) |
| 388 | if err := f.Accept(ctx, "r1", c1[0]); err != nil { |
| 389 | t.Fatal(err) |
| 390 | } |
| 391 | // Its message names it: a running turn now protects it. |
| 392 | if err := f.State.Accept(ctx, "m1", wire.MessageCommand{Person: "p@example.com", TurnID: "t_1", Attempt: 1, Text: "x", PersonText: []string{"x"}, Tail: []wire.TailMessage{}, Attachments: []wire.AttachmentRef{r1}}); err != nil { |
| 393 | t.Fatal(err) |
| 394 | } |
| 395 | c2, r2 := chunksOf("p@example.com", "at_r2aaaaaaaa", "b.txt", ten) |
| 396 | if err := f.Accept(ctx, "r2", c2[0]); err != nil { |
| 397 | t.Fatal(err) |
| 398 | } |
| 399 | desk, _ := OpenDesk(f.SessionRoot, "p@example.com") |
| 400 | if _, err := heldFiles(desk, []wire.AttachmentRef{r1}); err != nil || !f.State.anyRefused(ctx, []wire.AttachmentRef{r2}) { |
| 401 | t.Fatalf("the protected file went or the new one was taken in: %v", err) |
| 402 | } |
| 403 | // The turn ends: r1 is no longer protected, and makes room for r3. |
| 404 | f.State.db.Exec("UPDATE runs SET state='done'") |
| 405 | c3, r3 := chunksOf("p@example.com", "at_r3aaaaaaaa", "c.txt", ten) |
| 406 | if err := f.Accept(ctx, "r3", c3[0]); err != nil { |
| 407 | t.Fatal(err) |
| 408 | } |
| 409 | if _, err := heldFiles(desk, []wire.AttachmentRef{r3}); err != nil { |
| 410 | t.Fatalf("r3 not delivered: %v", err) |
| 411 | } |
| 412 | if _, err := heldFiles(desk, []wire.AttachmentRef{r1}); err == nil { |
| 413 | t.Fatal("r1 kept beyond the quota") |
| 414 | } |
| 415 | // An arriving file counts: its first chunk holds the one file, so a |
| 416 | // file behind it is refused while it is still arriving. |
| 417 | f.State.db.Exec("DELETE FROM file_admits") |
| 418 | os.RemoveAll(filepath.Join(desk.Dir, attachmentsDir)) |
| 419 | big := []byte(strings.Repeat("y", attach.ChunkBytes+10)) |
| 420 | f.Quota = Quota{PersonBytes: 1 << 20, PersonFiles: 1, TotalBytes: 1 << 20, TotalFiles: 1} |
| 421 | c4, _ := chunksOf("p@example.com", "at_r4aaaaaaaa", "d.txt", big) |
| 422 | if err := f.Accept(ctx, "r4", c4[0]); err != nil { |
| 423 | t.Fatal(err) |
| 424 | } |
| 425 | c5, r5 := chunksOf("p@example.com", "at_r5aaaaaaaa", "e.txt", ten) |
| 426 | if err := f.Accept(ctx, "r5", c5[0]); err != nil { |
| 427 | t.Fatal(err) |
| 428 | } |
| 429 | if !f.State.anyRefused(ctx, []wire.AttachmentRef{r5}) { |
| 430 | t.Fatal("an arriving file did not count against the quota") |
| 431 | } |
| 432 | }) |
| 433 | } |
| 434 | |
| 435 | // Astra round 2: a failed protection lookup read as "nothing protected", |
| 436 | // so a cancelled sweep removed a running turn's file. A sweep whose |
| 437 | // lookup fails (cancelled, a query error, a record that does not decode) |
| 438 | // removes nothing. |
| 439 | func TestAttachmentSweepAbortsOnLookupFailure(t *testing.T) { |
| 440 | for _, tc := range []string{"cancelled", "query", "decode"} { |
| 441 | t.Run(tc, func(t *testing.T) { |
| 442 | t.Parallel() |
| 443 | f, ctx := filesRig(t) |
| 444 | var refs []wire.AttachmentRef |
| 445 | for _, id := range []string{"at_s1aaaaaaaa", "at_s2aaaaaaaa", "at_s3aaaaaaaa"} { |
| 446 | chunks, ref := chunksOf("p@example.com", id, "n.txt", []byte("ten bytes!")) |
| 447 | if err := f.Accept(ctx, "f-"+id, chunks[0]); err != nil { |
| 448 | t.Fatal(err) |
| 449 | } |
| 450 | refs = append(refs, ref) |
| 451 | } |
| 452 | if err := f.State.Accept(ctx, "m1", wire.MessageCommand{Person: "p@example.com", TurnID: "t_1", Attempt: 1, Text: "x", PersonText: []string{"x"}, Tail: []wire.TailMessage{}, Attachments: refs[:1]}); err != nil { |
| 453 | t.Fatal(err) |
| 454 | } |
| 455 | f.State.db.Exec("DELETE FROM file_admits") |
| 456 | f.Quota = Quota{PersonBytes: 1, PersonFiles: 1, TotalBytes: 1, TotalFiles: 1} |
| 457 | sweep := ctx |
| 458 | switch tc { |
| 459 | case "cancelled": |
| 460 | c, cancel := context.WithCancel(ctx) |
| 461 | cancel() |
| 462 | sweep = c |
| 463 | case "query": |
| 464 | f.State.fault = func(op string) error { |
| 465 | if op == "running_attachments" { |
| 466 | return errors.New("disk I/O error") |
| 467 | } |
| 468 | return nil |
| 469 | } |
| 470 | case "decode": |
| 471 | f.State.db.Exec("INSERT INTO runs(turn_id, person, attempt, state, text, tail, kind, person_text, attachments, created_at) VALUES('t_bad','p@example.com',1,?, 'x','[]','','[]','{not json',?)", runRunning, now()) |
| 472 | } |
| 473 | _, before := held(t, f.SessionRoot) |
| 474 | f.Sweep(sweep) |
| 475 | if _, after := held(t, f.SessionRoot); after != before { |
| 476 | t.Fatalf("a sweep whose lookup failed removed %d files", before-after) |
| 477 | } |
| 478 | // A healthy sweep removes the unprotected, keeps the protected. |
| 479 | f.State.fault = nil |
| 480 | f.State.db.Exec("DELETE FROM runs WHERE turn_id='t_bad'") |
| 481 | f.Sweep(ctx) |
| 482 | desk, _ := OpenDesk(f.SessionRoot, "p@example.com") |
| 483 | if _, err := heldFiles(desk, refs[:1]); err != nil { |
| 484 | t.Fatal("the protected file went") |
| 485 | } |
| 486 | if _, after := held(t, f.SessionRoot); after != 1 { |
| 487 | t.Fatalf("a healthy sweep left %d files", after) |
| 488 | } |
| 489 | }) |
| 490 | } |
| 491 | } |
| 492 | |