jobs.go raw
1 package blossom
2
3 // Long blob operations as separate steps.
4 //
5 // An upload hashes and writes up to maxBlob bytes, and a restore can stream a
6 // backup of any size. Both used to run to completion inside one call, which on a
7 // single-threaded scheduler means the whole relay waits. The job types here do
8 // the same work a bounded number of bytes at a time, so the Blossom domain can
9 // check its breaker between steps.
10
11 import (
12 "archive/tar"
13 "crypto/sha256"
14 "encoding/hex"
15 "encoding/json"
16 "errors"
17 "fmt"
18 "hash"
19 "io"
20 "os"
21 "path/filepath"
22 "strings"
23 "time"
24
25 "git.smesh.lol/torly/pkg/nostr"
26 )
27
28 // StepBytes is the default amount of work one Step call does. Four MiB keeps a
29 // step in the low tens of milliseconds on the storage this runs on, which is the
30 // granularity the Blossom domain can be interrupted at.
31 const StepBytes = 4 << 20
32
33 // readChunk is the buffer a restore reads from the tar stream at a time. The step
34 // budget, not this, bounds a step.
35 const readChunk = 64 << 10
36
37 // IsUpload reports whether req is a BUD-02 upload, the one request shaped as a
38 // long job rather than answered in one pass.
39 func IsUpload(req *Request) bool {
40 return req.Method == "PUT" && normalizePath(req.Path) == "/upload"
41 }
42
43 const (
44 putHashing uint8 = iota
45 putOpening
46 putWriting
47 putCommitting
48 putDone
49 )
50
51 // PutJob is one upload being hashed, written and indexed a step at a time.
52 type PutJob struct {
53 s *Server
54 req *Request
55 body []byte
56
57 typ string
58 created int64
59 hex string
60 pub string
61 sum hash.Hash
62
63 off int
64 phase uint8
65
66 f *os.File
67 tmp string
68 path string
69 desc Descriptor
70 status int
71 }
72
73 // BeginPut starts a PUT if req is one, and reports whether the request was
74 // handled. A nil job with handled true means the response is already final: the
75 // upload is too large.
76 func (s *Server) BeginPut(req *Request) (job *PutJob, resp *Response, handled bool) {
77 if !IsUpload(req) {
78 return nil, nil, false
79 }
80 if int64(len(req.Body)) > s.maxBlob {
81 r := s.fail(413, "blob is too large")
82 return nil, &r, true
83 }
84 ct := req.Header["content-type"]
85 if ct == "" {
86 ct = "application/octet-stream"
87 }
88 if len(ct) > 1024 {
89 ct = ct[:1024]
90 }
91 return &PutJob{
92 s: s,
93 req: req,
94 body: req.Body,
95 typ: ct,
96 created: time.Now().Unix(),
97 sum: sha256.New(),
98 }, nil, true
99 }
100
101 // Step hashes or writes up to budget bytes and reports whether the job is done.
102 func (j *PutJob) Step(budget int) (bool, error) {
103 if j.phase == putDone {
104 return true, nil
105 }
106 if budget <= 0 {
107 budget = StepBytes
108 }
109 switch j.phase {
110 case putHashing:
111 n := len(j.body) - j.off
112 if n > budget {
113 n = budget
114 }
115 j.sum.Write(j.body[j.off : j.off+n])
116 j.off += n
117 if j.off < len(j.body) {
118 return false, nil
119 }
120 j.hex = hex.EncodeToString(j.sum.Sum(nil))
121 j.phase = putOpening
122 return false, nil
123
124 case putOpening:
125 pub, err := j.s.authorize(j.req, "upload", j.hex)
126 if err != nil {
127 j.status = 401
128 return true, err
129 }
130 j.pub = nostr.Hex(pub[:])
131 j.path = j.s.blobPath(j.hex)
132
133 j.s.mu.Lock()
134 if existing := j.s.blobs[j.hex]; existing != nil {
135 j.desc = j.s.descriptor(j.req, existing)
136 j.s.mu.Unlock()
137 j.phase = putDone
138 return true, nil
139 }
140 if err := os.MkdirAll(filepath.Dir(j.path), 0o755); err != nil {
141 j.s.mu.Unlock()
142 return true, errors.New("could not create blob directory")
143 }
144 j.tmp = j.path + ".tmp"
145 f, err := os.OpenFile(j.tmp, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
146 if err != nil {
147 j.s.mu.Unlock()
148 return true, errors.New("could not write blob")
149 }
150 j.f = f
151 j.off = 0
152 j.phase = putWriting
153 j.s.mu.Unlock()
154 return false, nil
155
156 case putWriting:
157 n := len(j.body) - j.off
158 if n > budget {
159 n = budget
160 }
161 if _, err := j.f.Write(j.body[j.off : j.off+n]); err != nil {
162 return true, errors.New("could not write blob")
163 }
164 j.off += n
165 if j.off < len(j.body) {
166 return false, nil
167 }
168 j.phase = putCommitting
169 return false, nil
170
171 default: // putCommitting
172 if err := j.commit(); err != nil {
173 return true, err
174 }
175 j.phase = putDone
176 return true, nil
177 }
178 }
179
180 func (j *PutJob) commit() error {
181 if err := j.f.Close(); err != nil {
182 os.Remove(j.tmp)
183 return errors.New("could not write blob")
184 }
185 j.f = nil
186 if err := os.Rename(j.tmp, j.path); err != nil {
187 os.Remove(j.tmp)
188 return errors.New("could not commit blob")
189 }
190 b := &Blob{Hash: j.hex, PubKey: j.pub, Size: int64(len(j.body)), Type: j.typ, Created: j.created}
191
192 j.s.mu.Lock()
193 j.s.putMem(b)
194 err := j.s.appendRecord('p', b)
195 j.desc = j.s.descriptor(j.req, b)
196 j.s.mu.Unlock()
197
198 if err != nil {
199 return errors.New("could not update index")
200 }
201 return nil
202 }
203
204 // Response is the BUD-02 descriptor for a finished upload.
205 func (j *PutJob) Response() Response {
206 body, _ := json.Marshal(j.desc)
207 return Response{
208 Status: 200,
209 Header: [][2]string{{"Content-Type", "application/json"}},
210 Body: body,
211 }
212 }
213
214 // ErrorResponse is the response for a failed upload. An authorization failure is
215 // a 401 and everything else is a 500, which is what the synchronous path returned
216 // before the job existed.
217 func (j *PutJob) ErrorResponse(err error) Response {
218 status := j.status
219 if status == 0 {
220 status = 500
221 }
222 return j.s.fail(status, err.Error())
223 }
224
225 // Cancel releases the temporary file of an abandoned upload.
226 func (j *PutJob) Cancel() {
227 if j.f != nil {
228 j.f.Close()
229 j.f = nil
230 }
231 if j.tmp != "" {
232 os.Remove(j.tmp)
233 j.tmp = ""
234 }
235 }
236
237 // fail builds an error response without a request writer.
238 func (s *Server) fail(status int, msg string) Response {
239 w := &respWriter{}
240 s.err(w, status, msg)
241 return Response{Status: w.status, Header: w.header, Body: w.body}
242 }
243
244 const (
245 restoreManifest uint8 = iota
246 restoreEntries
247 restoreDone
248 )
249
250 // RestoreJob imports one backup, one bounded read at a time.
251 type RestoreJob struct {
252 s *Server
253 tr *tar.Reader
254
255 entries map[string]BackupEntry
256 stats BackupStats
257
258 phase uint8
259
260 cur bool
261 curHash string
262 curEntry BackupEntry
263 curSize int64
264 curSum hash.Hash
265 f *os.File
266 tmp string
267 path string
268 buf []byte
269 err error
270 }
271
272 // BeginRestore starts a restore from r. The manifest is read by the first Step,
273 // so a corrupt archive fails there rather than here.
274 func (s *Server) BeginRestore(r io.Reader) (*RestoreJob, error) {
275 if r == nil {
276 return nil, errors.New("blossom restore: no input")
277 }
278 return &RestoreJob{s: s, tr: tar.NewReader(r), buf: make([]byte, readChunk)}, nil
279 }
280
281 // Step reads up to budget bytes of the archive and reports whether the restore is
282 // finished. One blob file is written completely or not at all: the index record
283 // is appended only after the entry's digest is checked.
284 func (j *RestoreJob) Step(budget int) (bool, error) {
285 if j.err != nil {
286 return true, j.err
287 }
288 if budget <= 0 {
289 budget = StepBytes
290 }
291 switch j.phase {
292 case restoreManifest:
293 if err := j.readManifest(); err != nil {
294 j.err = err
295 return true, err
296 }
297 j.phase = restoreEntries
298 return false, nil
299 case restoreDone:
300 return true, nil
301 }
302
303 spent := 0
304 for spent < budget {
305 if !j.cur {
306 more, err := j.next()
307 if err != nil {
308 j.err = err
309 return true, err
310 }
311 if !more {
312 j.phase = restoreDone
313 return true, nil
314 }
315 // next either opened an entry or skipped one and returned true; a
316 // skipped entry leaves cur false and the loop moves on.
317 if !j.cur {
318 continue
319 }
320 }
321 n := budget - spent
322 if n > len(j.buf) {
323 n = len(j.buf)
324 }
325 got, err := j.tr.Read(j.buf[:n])
326 if got > 0 {
327 if _, werr := j.f.Write(j.buf[:got]); werr != nil {
328 j.abandon()
329 j.err = fmt.Errorf("blossom restore: %s: %w", j.curHash, werr)
330 return true, j.err
331 }
332 j.curSum.Write(j.buf[:got])
333 j.curSize += int64(got)
334 spent += got
335 if j.s.maxBlob > 0 && j.curSize > j.s.maxBlob {
336 j.abandon()
337 j.err = fmt.Errorf("blossom restore: %s: blob exceeds configured maximum", j.curHash)
338 return true, j.err
339 }
340 }
341 if err == io.EOF {
342 if cerr := j.commitEntry(); cerr != nil {
343 j.err = cerr
344 return true, cerr
345 }
346 continue
347 }
348 if err != nil {
349 j.abandon()
350 j.err = fmt.Errorf("blossom restore: %s: %w", j.curHash, err)
351 return true, j.err
352 }
353 }
354 return false, nil
355 }
356
357 // next advances to the next blob entry that needs writing, opening its file. It
358 // returns false at the end of the archive. Entries that are malformed, absent
359 // from the manifest or already present are accounted for and skipped.
360 func (j *RestoreJob) next() (bool, error) {
361 for {
362 hdr, err := j.tr.Next()
363 if err == io.EOF {
364 return false, nil
365 }
366 if err != nil {
367 return false, err
368 }
369 name := filepath.ToSlash(hdr.Name)
370 if !strings.HasPrefix(name, backupBlobPrefix) {
371 continue
372 }
373 hash := strings.TrimPrefix(name, backupBlobPrefix)
374 if !nostr.IsHex64(hash) {
375 j.stats.Skipped++
376 continue
377 }
378 entry, ok := j.entries[hash]
379 if !ok {
380 j.stats.Skipped++
381 continue
382 }
383 path := j.s.blobPath(hash)
384 if _, err := os.Stat(path); err == nil {
385 // Content-addressed: the bytes are already there.
386 if err := j.s.addRestored(hash, entry); err != nil {
387 return false, err
388 }
389 j.stats.Skipped++
390 continue
391 }
392 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
393 return false, err
394 }
395 tmp := path + ".restore.tmp"
396 f, err := os.OpenFile(tmp, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
397 if err != nil {
398 return false, err
399 }
400 j.cur = true
401 j.curHash = hash
402 j.curEntry = entry
403 j.curSize = 0
404 j.curSum = sha256.New()
405 j.f = f
406 j.tmp = tmp
407 j.path = path
408 return true, nil
409 }
410 }
411
412 // commitEntry finishes the current blob: digest check, sync, rename, then the
413 // index record. Nothing is visible to the store before all of that.
414 func (j *RestoreJob) commitEntry() error {
415 got := hex.EncodeToString(j.curSum.Sum(nil))
416 if got != j.curHash {
417 j.abandon()
418 return fmt.Errorf("blossom restore: %s: sha256 mismatch: got %s", j.curHash, got)
419 }
420 if err := j.f.Sync(); err != nil {
421 j.abandon()
422 return err
423 }
424 if err := j.f.Close(); err != nil {
425 j.abandon()
426 return err
427 }
428 j.f = nil
429 if err := os.Rename(j.tmp, j.path); err != nil {
430 os.Remove(j.tmp)
431 return err
432 }
433 j.tmp = ""
434 entry := j.curEntry
435 entry.Size = j.curSize
436 if err := j.s.addRestored(j.curHash, entry); err != nil {
437 return err
438 }
439 j.stats.Restored++
440 j.cur = false
441 j.curHash = ""
442 return nil
443 }
444
445 // abandon removes a partially written blob file.
446 func (j *RestoreJob) abandon() {
447 if j.f != nil {
448 j.f.Close()
449 j.f = nil
450 }
451 if j.tmp != "" {
452 os.Remove(j.tmp)
453 j.tmp = ""
454 }
455 j.cur = false
456 }
457
458 func (j *RestoreJob) readManifest() error {
459 hdr, err := j.tr.Next()
460 if err != nil {
461 return fmt.Errorf("blossom restore: missing manifest: %w", err)
462 }
463 if filepath.Clean(hdr.Name) != backupManifest {
464 return fmt.Errorf("blossom restore: first entry is %q, want %q", hdr.Name, backupManifest)
465 }
466 raw, err := io.ReadAll(io.LimitReader(j.tr, 32<<20))
467 if err != nil {
468 return err
469 }
470 var manifest BackupManifest
471 if err := json.Unmarshal(raw, &manifest); err != nil {
472 return fmt.Errorf("blossom restore: manifest: %w", err)
473 }
474 if manifest.Version != backupVersion {
475 return fmt.Errorf("blossom restore: unsupported version %d", manifest.Version)
476 }
477 j.entries = make(map[string]BackupEntry, len(manifest.Blobs))
478 for _, e := range manifest.Blobs {
479 e.SHA256 = strings.ToLower(e.SHA256)
480 if !nostr.IsHex64(e.SHA256) {
481 continue
482 }
483 j.entries[e.SHA256] = e
484 }
485 return nil
486 }
487
488 // Stats is the tally so far.
489 func (j *RestoreJob) Stats() BackupStats { return j.stats }
490
491 // Cancel closes the open entry and removes its partial file.
492 func (j *RestoreJob) Cancel() { j.abandon() }
493