| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io/fs" |
| 9 | "log" |
| 10 | "net/http" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "time" |
| 15 | |
| 16 | "the-valley/note" |
| 17 | "the-valley/web/export" |
| 18 | ) |
| 19 | |
| 20 | // receiver is the upload's three steps over the state directory, as |
| 21 | // package export defines them. |
| 22 | type receiver struct { |
| 23 | store *export.Store |
| 24 | verifiers []note.VerifierKey |
| 25 | instance string |
| 26 | destination string |
| 27 | token string |
| 28 | maxBody int64 |
| 29 | maxUpload int64 |
| 30 | log *log.Logger |
| 31 | |
| 32 | // slots holds one token for each authenticated request running. |
| 33 | slots chan struct{} |
| 34 | |
| 35 | mu sync.Mutex |
| 36 | // staged is the newest upload a manifest staged, or nil before the |
| 37 | // first since the receiver started. Store.Stage discards every older |
| 38 | // upload, so no other is worth a body or a commit. |
| 39 | staged *export.Staging |
| 40 | // receiving holds the path each body a request is staging goes to, |
| 41 | // which names the body's upload and its SHA-256. A second request for |
| 42 | // the same body of the same upload is answered 503 while the first |
| 43 | // runs, so staging holds one partial file of each body, as the |
| 44 | // store's storage cap counts it. A newer upload's request for the |
| 45 | // same body is not held up: staging the newer manifest stops the |
| 46 | // older upload's requests first. |
| 47 | receiving map[string]bool |
| 48 | } |
| 49 | |
| 50 | // errBusy is body's error when another request is staging the same body |
| 51 | // of the same upload. |
| 52 | var errBusy = errors.New("another request is staging this body") |
| 53 | |
| 54 | // The kinds of request the upload makes. |
| 55 | const ( |
| 56 | stepManifest = "manifest" |
| 57 | stepBody = "body" |
| 58 | stepCommit = "commit" |
| 59 | ) |
| 60 | |
| 61 | // ServeHTTP authenticates the request, then routes it, then takes a slot |
| 62 | // for it, in that order. A request without the token is refused with no |
| 63 | // slot taken and no byte of its body read. |
| 64 | func (rv *receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 65 | rc := http.NewResponseController(w) |
| 66 | rc.SetWriteDeadline(time.Now().Add(shortTimeout)) |
| 67 | if !export.Authorized(r, rv.token) { |
| 68 | // Closing the connection after the reply reads none of the body. |
| 69 | rc.SetReadDeadline(time.Now()) |
| 70 | w.Header().Set("Connection", "close") |
| 71 | w.Header().Set("WWW-Authenticate", `Bearer realm="valley-web-receive"`) |
| 72 | rv.fail(w, r, &export.Error{Code: export.CodeUnauthenticated, |
| 73 | Message: "the request does not carry the receiver's token in its Authorization header"}) |
| 74 | return |
| 75 | } |
| 76 | step, seq, sum, allow := route(r.URL.Path) |
| 77 | switch { |
| 78 | case step == "": |
| 79 | rc.SetReadDeadline(time.Now()) |
| 80 | w.Header().Set("Connection", "close") |
| 81 | reply(w, http.StatusNotFound, nil) |
| 82 | return |
| 83 | case r.Method != allow: |
| 84 | rc.SetReadDeadline(time.Now()) |
| 85 | w.Header().Set("Connection", "close") |
| 86 | w.Header().Set("Allow", allow) |
| 87 | reply(w, http.StatusMethodNotAllowed, nil) |
| 88 | return |
| 89 | } |
| 90 | select { |
| 91 | case rv.slots <- struct{}{}: |
| 92 | defer func() { <-rv.slots }() |
| 93 | default: |
| 94 | busy(w, rc) |
| 95 | return |
| 96 | } |
| 97 | |
| 98 | // The deadline bounds the connection's reads and writes, and ctx the |
| 99 | // store's work: waiting for its lock, and the git a commit runs. ctx |
| 100 | // is done, too, once the client goes away. |
| 101 | timeout := map[string]time.Duration{stepManifest: manifestTimeout, stepBody: bodyTimeout, stepCommit: commitTimeout}[step] |
| 102 | deadline := time.Now().Add(timeout) |
| 103 | rc.SetReadDeadline(deadline) |
| 104 | rc.SetWriteDeadline(deadline) |
| 105 | ctx, cancel := context.WithDeadline(r.Context(), deadline) |
| 106 | defer cancel() |
| 107 | switch step { |
| 108 | case stepManifest: |
| 109 | inv, err := rv.manifest(ctx, r) |
| 110 | if err != nil { |
| 111 | rv.fail(w, r, err) |
| 112 | return |
| 113 | } |
| 114 | reply(w, http.StatusOK, inv) |
| 115 | case stepBody: |
| 116 | err := rv.body(ctx, rc, r, seq, sum) |
| 117 | if errors.Is(err, errBusy) { |
| 118 | busy(w, rc) |
| 119 | return |
| 120 | } |
| 121 | if err != nil { |
| 122 | rv.fail(w, r, err) |
| 123 | return |
| 124 | } |
| 125 | reply(w, http.StatusNoContent, nil) |
| 126 | case stepCommit: |
| 127 | g, err := rv.commit(ctx, seq) |
| 128 | if err != nil { |
| 129 | rv.fail(w, r, err) |
| 130 | return |
| 131 | } |
| 132 | rv.log.Printf("activated sequence %d", g.Sequence) |
| 133 | reply(w, http.StatusOK, export.Committed{Schema: export.CommittedSchema, Sequence: g.Sequence}) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // route reads the step a path names, and the method that step takes. A |
| 138 | // body's path names its upload's sequence and its SHA-256, and a commit's |
| 139 | // the sequence. step is "" for a path the upload does not use. |
| 140 | func route(path string) (step string, seq int64, sum, method string) { |
| 141 | if path == export.ManifestPath { |
| 142 | return stepManifest, 0, "", http.MethodPost |
| 143 | } |
| 144 | rest, ok := strings.CutPrefix(path, "/web-export/v1/") |
| 145 | if !ok { |
| 146 | return "", 0, "", "" |
| 147 | } |
| 148 | parts := strings.Split(rest, "/") |
| 149 | if len(parts) != 2 { |
| 150 | return "", 0, "", "" |
| 151 | } |
| 152 | seq, err := strconv.ParseInt(parts[0], 10, 64) |
| 153 | if err != nil || seq <= 0 || strconv.FormatInt(seq, 10) != parts[0] { |
| 154 | return "", 0, "", "" |
| 155 | } |
| 156 | switch { |
| 157 | case parts[1] == "commit": |
| 158 | return stepCommit, seq, "", http.MethodPost |
| 159 | case isSHA256(parts[1]): |
| 160 | return stepBody, seq, parts[1], http.MethodPut |
| 161 | } |
| 162 | return "", 0, "", "" |
| 163 | } |
| 164 | |
| 165 | func isSHA256(s string) bool { |
| 166 | if len(s) != 64 { |
| 167 | return false |
| 168 | } |
| 169 | for i := 0; i < len(s); i++ { |
| 170 | if !('0' <= s[i] && s[i] <= '9' || 'a' <= s[i] && s[i] <= 'f') { |
| 171 | return false |
| 172 | } |
| 173 | } |
| 174 | return true |
| 175 | } |
| 176 | |
| 177 | // manifest is step 1: admit the manifest, hold its bodies to the caps, |
| 178 | // stage it, and reply with the inventory. Staging waits for the store's |
| 179 | // lock, which a commit holds throughout, until ctx is done. |
| 180 | func (rv *receiver) manifest(ctx context.Context, r *http.Request) (export.Inventory, error) { |
| 181 | hw, err := rv.store.HighWater() |
| 182 | if err != nil { |
| 183 | return export.Inventory{}, err |
| 184 | } |
| 185 | m, err := export.VerifyManifest(r.Body, export.Admission{Verifiers: rv.verifiers, |
| 186 | Instance: rv.instance, Destination: rv.destination, HighWater: hw, Now: time.Now()}) |
| 187 | if err != nil { |
| 188 | return export.Inventory{}, err |
| 189 | } |
| 190 | if err := m.CheckSizes(rv.maxBody, rv.maxUpload); err != nil { |
| 191 | return export.Inventory{}, err |
| 192 | } |
| 193 | st, err := rv.store.Stage(ctx, m) |
| 194 | if err != nil { |
| 195 | return export.Inventory{}, err |
| 196 | } |
| 197 | rv.mu.Lock() |
| 198 | if rv.staged == nil || rv.staged.Manifest.Sequence <= m.Sequence { |
| 199 | rv.staged = &st |
| 200 | } |
| 201 | rv.mu.Unlock() |
| 202 | return rv.store.Inventory(st) |
| 203 | } |
| 204 | |
| 205 | // upload is the staged upload with sequence: no-manifest when nothing |
| 206 | // newer than it is staged, and superseded when something newer is. |
| 207 | func (rv *receiver) upload(seq int64) (export.Staging, error) { |
| 208 | rv.mu.Lock() |
| 209 | defer rv.mu.Unlock() |
| 210 | switch { |
| 211 | case rv.staged == nil || rv.staged.Manifest.Sequence < seq: |
| 212 | return export.Staging{}, &export.Error{Code: export.CodeNoManifest, |
| 213 | Message: fmt.Sprintf("nothing is staged for sequence %d", seq)} |
| 214 | case rv.staged.Manifest.Sequence > seq: |
| 215 | return export.Staging{}, &export.Error{Code: export.CodeSuperseded, |
| 216 | Message: fmt.Sprintf("the upload with sequence %d supersedes this one, %d", rv.staged.Manifest.Sequence, seq)} |
| 217 | } |
| 218 | return *rv.staged, nil |
| 219 | } |
| 220 | |
| 221 | // body is step 2 for the body with SHA-256 sum. It stages the body until |
| 222 | // ctx is done, or until the store discards the upload's bodies (see |
| 223 | // export.Store.Writer), and then ends the read that waits on the client. |
| 224 | func (rv *receiver) body(ctx context.Context, rc *http.ResponseController, r *http.Request, seq int64, sum string) error { |
| 225 | st, err := rv.upload(seq) |
| 226 | if err != nil { |
| 227 | return err |
| 228 | } |
| 229 | var want *export.Body |
| 230 | for _, b := range st.Manifest.Bodies() { |
| 231 | if b.SHA256 == sum { |
| 232 | want = &b |
| 233 | break |
| 234 | } |
| 235 | } |
| 236 | if want == nil { |
| 237 | return &export.Error{Code: export.CodeNotDeclared, |
| 238 | Message: fmt.Sprintf("the manifest with sequence %d declares no body with SHA-256 %s", seq, sum)} |
| 239 | } |
| 240 | path := st.Body(*want) |
| 241 | rv.mu.Lock() |
| 242 | if rv.receiving[path] { |
| 243 | rv.mu.Unlock() |
| 244 | return errBusy |
| 245 | } |
| 246 | if rv.receiving == nil { |
| 247 | rv.receiving = map[string]bool{} |
| 248 | } |
| 249 | rv.receiving[path] = true |
| 250 | rv.mu.Unlock() |
| 251 | defer func() { |
| 252 | rv.mu.Lock() |
| 253 | delete(rv.receiving, path) |
| 254 | rv.mu.Unlock() |
| 255 | }() |
| 256 | wctx, done, err := rv.store.Writer(ctx, st) |
| 257 | if err != nil { |
| 258 | return err |
| 259 | } |
| 260 | defer done() |
| 261 | // A read deadline set once the handler has returned would end the |
| 262 | // connection's next request, so the handler waits for one being set. |
| 263 | interrupted := make(chan struct{}) |
| 264 | stop := context.AfterFunc(wctx, func() { |
| 265 | rc.SetReadDeadline(time.Now()) |
| 266 | close(interrupted) |
| 267 | }) |
| 268 | defer func() { |
| 269 | if !stop() { |
| 270 | <-interrupted |
| 271 | } |
| 272 | }() |
| 273 | _, err = export.StageBody(st.Bodies(), *want, rv.maxBody, r.WithContext(wctx)) |
| 274 | if errors.Is(err, fs.ErrNotExist) { |
| 275 | // The upload's staging directory is gone: a newer manifest |
| 276 | // discarded it, or a commit activated it. |
| 277 | if _, err := rv.upload(seq); err != nil { |
| 278 | return err |
| 279 | } |
| 280 | return &export.Error{Code: export.CodeNoManifest, |
| 281 | Message: fmt.Sprintf("nothing is staged for sequence %d any more", seq)} |
| 282 | } |
| 283 | return err |
| 284 | } |
| 285 | |
| 286 | // commit is step 3: activate the upload with sequence, until ctx is done. |
| 287 | func (rv *receiver) commit(ctx context.Context, seq int64) (export.Generation, error) { |
| 288 | st, err := rv.upload(seq) |
| 289 | if err != nil { |
| 290 | return export.Generation{}, err |
| 291 | } |
| 292 | return rv.store.Activate(ctx, st) |
| 293 | } |
| 294 | |
| 295 | // fail replies with the refusal err is, or with 500 and no refusal for any |
| 296 | // other error, which the publisher retries. Either is logged. |
| 297 | func (rv *receiver) fail(w http.ResponseWriter, r *http.Request, err error) { |
| 298 | var e *export.Error |
| 299 | if errors.As(err, &e) { |
| 300 | rv.log.Printf("%s %s from %s: refused: %v", r.Method, r.URL.Path, r.RemoteAddr, e) |
| 301 | reply(w, e.Code.Status(), e.Reply()) |
| 302 | return |
| 303 | } |
| 304 | rv.log.Printf("%s %s from %s: %v", r.Method, r.URL.Path, r.RemoteAddr, err) |
| 305 | reply(w, http.StatusInternalServerError, nil) |
| 306 | } |
| 307 | |
| 308 | // drain takes every request slot, so it waits until each request that |
| 309 | // holds one has finished, with the git it runs, or until ctx is done. It |
| 310 | // reports whether it took them all. A request that comes after takes no |
| 311 | // slot, and is answered 503. |
| 312 | func (rv *receiver) drain(ctx context.Context) bool { |
| 313 | for range cap(rv.slots) { |
| 314 | select { |
| 315 | case rv.slots <- struct{}{}: |
| 316 | case <-ctx.Done(): |
| 317 | return false |
| 318 | } |
| 319 | } |
| 320 | return true |
| 321 | } |
| 322 | |
| 323 | // busy answers 503 with Retry-After and no refusal, which the publisher |
| 324 | // retries after a pause, and closes the connection without reading the |
| 325 | // body. |
| 326 | func busy(w http.ResponseWriter, rc *http.ResponseController) { |
| 327 | rc.SetReadDeadline(time.Now()) |
| 328 | w.Header().Set("Connection", "close") |
| 329 | w.Header().Set("Retry-After", "5") |
| 330 | reply(w, http.StatusServiceUnavailable, nil) |
| 331 | } |
| 332 | |
| 333 | // reply writes the status, and doc as JSON when it is not nil. |
| 334 | func reply(w http.ResponseWriter, status int, doc any) { |
| 335 | w.Header().Set("Cache-Control", "no-store") |
| 336 | if doc == nil { |
| 337 | w.WriteHeader(status) |
| 338 | return |
| 339 | } |
| 340 | w.Header().Set("Content-Type", "application/json") |
| 341 | w.WriteHeader(status) |
| 342 | json.NewEncoder(w).Encode(doc) |
| 343 | } |