package blossom // Long blob operations as separate steps. // // An upload hashes and writes up to maxBlob bytes, and a restore can stream a // backup of any size. Both used to run to completion inside one call, which on a // single-threaded scheduler means the whole relay waits. The job types here do // the same work a bounded number of bytes at a time, so the Blossom domain can // check its breaker between steps. import ( "archive/tar" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "hash" "io" "os" "path/filepath" "strings" "time" "git.smesh.lol/torly/pkg/nostr" ) // StepBytes is the default amount of work one Step call does. Four MiB keeps a // step in the low tens of milliseconds on the storage this runs on, which is the // granularity the Blossom domain can be interrupted at. const StepBytes = 4 << 20 // readChunk is the buffer a restore reads from the tar stream at a time. The step // budget, not this, bounds a step. const readChunk = 64 << 10 // IsUpload reports whether req is a BUD-02 upload, the one request shaped as a // long job rather than answered in one pass. func IsUpload(req *Request) bool { return req.Method == "PUT" && normalizePath(req.Path) == "/upload" } const ( putHashing uint8 = iota putOpening putWriting putCommitting putDone ) // PutJob is one upload being hashed, written and indexed a step at a time. type PutJob struct { s *Server req *Request body []byte typ string created int64 hex string pub string sum hash.Hash off int phase uint8 f *os.File tmp string path string desc Descriptor status int } // BeginPut starts a PUT if req is one, and reports whether the request was // handled. A nil job with handled true means the response is already final: the // upload is too large. func (s *Server) BeginPut(req *Request) (job *PutJob, resp *Response, handled bool) { if !IsUpload(req) { return nil, nil, false } if int64(len(req.Body)) > s.maxBlob { r := s.fail(413, "blob is too large") return nil, &r, true } ct := req.Header["content-type"] if ct == "" { ct = "application/octet-stream" } if len(ct) > 1024 { ct = ct[:1024] } return &PutJob{ s: s, req: req, body: req.Body, typ: ct, created: time.Now().Unix(), sum: sha256.New(), }, nil, true } // Step hashes or writes up to budget bytes and reports whether the job is done. func (j *PutJob) Step(budget int) (bool, error) { if j.phase == putDone { return true, nil } if budget <= 0 { budget = StepBytes } switch j.phase { case putHashing: n := len(j.body) - j.off if n > budget { n = budget } j.sum.Write(j.body[j.off : j.off+n]) j.off += n if j.off < len(j.body) { return false, nil } j.hex = hex.EncodeToString(j.sum.Sum(nil)) j.phase = putOpening return false, nil case putOpening: pub, err := j.s.authorize(j.req, "upload", j.hex) if err != nil { j.status = 401 return true, err } j.pub = nostr.Hex(pub[:]) j.path = j.s.blobPath(j.hex) j.s.mu.Lock() if existing := j.s.blobs[j.hex]; existing != nil { j.desc = j.s.descriptor(j.req, existing) j.s.mu.Unlock() j.phase = putDone return true, nil } if err := os.MkdirAll(filepath.Dir(j.path), 0o755); err != nil { j.s.mu.Unlock() return true, errors.New("could not create blob directory") } j.tmp = j.path + ".tmp" f, err := os.OpenFile(j.tmp, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { j.s.mu.Unlock() return true, errors.New("could not write blob") } j.f = f j.off = 0 j.phase = putWriting j.s.mu.Unlock() return false, nil case putWriting: n := len(j.body) - j.off if n > budget { n = budget } if _, err := j.f.Write(j.body[j.off : j.off+n]); err != nil { return true, errors.New("could not write blob") } j.off += n if j.off < len(j.body) { return false, nil } j.phase = putCommitting return false, nil default: // putCommitting if err := j.commit(); err != nil { return true, err } j.phase = putDone return true, nil } } func (j *PutJob) commit() error { if err := j.f.Close(); err != nil { os.Remove(j.tmp) return errors.New("could not write blob") } j.f = nil if err := os.Rename(j.tmp, j.path); err != nil { os.Remove(j.tmp) return errors.New("could not commit blob") } b := &Blob{Hash: j.hex, PubKey: j.pub, Size: int64(len(j.body)), Type: j.typ, Created: j.created} j.s.mu.Lock() j.s.putMem(b) err := j.s.appendRecord('p', b) j.desc = j.s.descriptor(j.req, b) j.s.mu.Unlock() if err != nil { return errors.New("could not update index") } return nil } // Response is the BUD-02 descriptor for a finished upload. func (j *PutJob) Response() Response { body, _ := json.Marshal(j.desc) return Response{ Status: 200, Header: [][2]string{{"Content-Type", "application/json"}}, Body: body, } } // ErrorResponse is the response for a failed upload. An authorization failure is // a 401 and everything else is a 500, which is what the synchronous path returned // before the job existed. func (j *PutJob) ErrorResponse(err error) Response { status := j.status if status == 0 { status = 500 } return j.s.fail(status, err.Error()) } // Cancel releases the temporary file of an abandoned upload. func (j *PutJob) Cancel() { if j.f != nil { j.f.Close() j.f = nil } if j.tmp != "" { os.Remove(j.tmp) j.tmp = "" } } // fail builds an error response without a request writer. func (s *Server) fail(status int, msg string) Response { w := &respWriter{} s.err(w, status, msg) return Response{Status: w.status, Header: w.header, Body: w.body} } const ( restoreManifest uint8 = iota restoreEntries restoreDone ) // RestoreJob imports one backup, one bounded read at a time. type RestoreJob struct { s *Server tr *tar.Reader entries map[string]BackupEntry stats BackupStats phase uint8 cur bool curHash string curEntry BackupEntry curSize int64 curSum hash.Hash f *os.File tmp string path string buf []byte err error } // BeginRestore starts a restore from r. The manifest is read by the first Step, // so a corrupt archive fails there rather than here. func (s *Server) BeginRestore(r io.Reader) (*RestoreJob, error) { if r == nil { return nil, errors.New("blossom restore: no input") } return &RestoreJob{s: s, tr: tar.NewReader(r), buf: make([]byte, readChunk)}, nil } // Step reads up to budget bytes of the archive and reports whether the restore is // finished. One blob file is written completely or not at all: the index record // is appended only after the entry's digest is checked. func (j *RestoreJob) Step(budget int) (bool, error) { if j.err != nil { return true, j.err } if budget <= 0 { budget = StepBytes } switch j.phase { case restoreManifest: if err := j.readManifest(); err != nil { j.err = err return true, err } j.phase = restoreEntries return false, nil case restoreDone: return true, nil } spent := 0 for spent < budget { if !j.cur { more, err := j.next() if err != nil { j.err = err return true, err } if !more { j.phase = restoreDone return true, nil } // next either opened an entry or skipped one and returned true; a // skipped entry leaves cur false and the loop moves on. if !j.cur { continue } } n := budget - spent if n > len(j.buf) { n = len(j.buf) } got, err := j.tr.Read(j.buf[:n]) if got > 0 { if _, werr := j.f.Write(j.buf[:got]); werr != nil { j.abandon() j.err = fmt.Errorf("blossom restore: %s: %w", j.curHash, werr) return true, j.err } j.curSum.Write(j.buf[:got]) j.curSize += int64(got) spent += got if j.s.maxBlob > 0 && j.curSize > j.s.maxBlob { j.abandon() j.err = fmt.Errorf("blossom restore: %s: blob exceeds configured maximum", j.curHash) return true, j.err } } if err == io.EOF { if cerr := j.commitEntry(); cerr != nil { j.err = cerr return true, cerr } continue } if err != nil { j.abandon() j.err = fmt.Errorf("blossom restore: %s: %w", j.curHash, err) return true, j.err } } return false, nil } // next advances to the next blob entry that needs writing, opening its file. It // returns false at the end of the archive. Entries that are malformed, absent // from the manifest or already present are accounted for and skipped. func (j *RestoreJob) next() (bool, error) { for { hdr, err := j.tr.Next() if err == io.EOF { return false, nil } if err != nil { return false, err } name := filepath.ToSlash(hdr.Name) if !strings.HasPrefix(name, backupBlobPrefix) { continue } hash := strings.TrimPrefix(name, backupBlobPrefix) if !nostr.IsHex64(hash) { j.stats.Skipped++ continue } entry, ok := j.entries[hash] if !ok { j.stats.Skipped++ continue } path := j.s.blobPath(hash) if _, err := os.Stat(path); err == nil { // Content-addressed: the bytes are already there. if err := j.s.addRestored(hash, entry); err != nil { return false, err } j.stats.Skipped++ continue } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return false, err } tmp := path + ".restore.tmp" f, err := os.OpenFile(tmp, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return false, err } j.cur = true j.curHash = hash j.curEntry = entry j.curSize = 0 j.curSum = sha256.New() j.f = f j.tmp = tmp j.path = path return true, nil } } // commitEntry finishes the current blob: digest check, sync, rename, then the // index record. Nothing is visible to the store before all of that. func (j *RestoreJob) commitEntry() error { got := hex.EncodeToString(j.curSum.Sum(nil)) if got != j.curHash { j.abandon() return fmt.Errorf("blossom restore: %s: sha256 mismatch: got %s", j.curHash, got) } if err := j.f.Sync(); err != nil { j.abandon() return err } if err := j.f.Close(); err != nil { j.abandon() return err } j.f = nil if err := os.Rename(j.tmp, j.path); err != nil { os.Remove(j.tmp) return err } j.tmp = "" entry := j.curEntry entry.Size = j.curSize if err := j.s.addRestored(j.curHash, entry); err != nil { return err } j.stats.Restored++ j.cur = false j.curHash = "" return nil } // abandon removes a partially written blob file. func (j *RestoreJob) abandon() { if j.f != nil { j.f.Close() j.f = nil } if j.tmp != "" { os.Remove(j.tmp) j.tmp = "" } j.cur = false } func (j *RestoreJob) readManifest() error { hdr, err := j.tr.Next() if err != nil { return fmt.Errorf("blossom restore: missing manifest: %w", err) } if filepath.Clean(hdr.Name) != backupManifest { return fmt.Errorf("blossom restore: first entry is %q, want %q", hdr.Name, backupManifest) } raw, err := io.ReadAll(io.LimitReader(j.tr, 32<<20)) if err != nil { return err } var manifest BackupManifest if err := json.Unmarshal(raw, &manifest); err != nil { return fmt.Errorf("blossom restore: manifest: %w", err) } if manifest.Version != backupVersion { return fmt.Errorf("blossom restore: unsupported version %d", manifest.Version) } j.entries = make(map[string]BackupEntry, len(manifest.Blobs)) for _, e := range manifest.Blobs { e.SHA256 = strings.ToLower(e.SHA256) if !nostr.IsHex64(e.SHA256) { continue } j.entries[e.SHA256] = e } return nil } // Stats is the tally so far. func (j *RestoreJob) Stats() BackupStats { return j.stats } // Cancel closes the open entry and removes its partial file. func (j *RestoreJob) Cancel() { j.abandon() }