gunk-dev/the-valley

receive.go

source601b054bc28emain's published tip history
14.7 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "io/fs"
11 "log"
12 "net/http"
13 "strconv"
14 "strings"
15 "sync"
16 "sync/atomic"
17 "time"
18
19 "the-valley/note"
20 "the-valley/web/export"
21)
22
23// receiver is the upload's three steps over the state directory, as
24// package export defines them.
25type receiver struct {
26 store *export.Store
27 verifiers []note.VerifierKey
28 instance string
29 destination string
30 token string
31 maxBody int64
32 maxUpload int64
33 log *log.Logger
34
35 // slots holds one token for each authenticated upload request
36 // running, and authSlots one for each authorization request, so a
37 // saturated upload never holds up an authorization.
38 slots chan struct{}
39 authSlots chan struct{}
40 // pruning is set while a prune runs after an authorization, so one
41 // prune at a time waits for the readers of the active generation.
42 pruning atomic.Bool
43 // pruneDelay is the first pause before prune tries again while a
44 // reader holds the generation. A test shortens it.
45 pruneDelay time.Duration
46
47 mu sync.Mutex
48 // staged is the newest upload a manifest staged, or nil before the
49 // first since the receiver started. Store.Stage discards every older
50 // upload, so no other is worth a body or a commit.
51 staged *export.Staging
52 // receiving holds the path each body a request is staging goes to,
53 // which names the body's upload and its SHA-256. A second request for
54 // the same body of the same upload is answered 503 while the first
55 // runs, so staging holds one partial file of each body, as the
56 // store's storage cap counts it. A newer upload's request for the
57 // same body is not held up: staging the newer manifest stops the
58 // older upload's requests first.
59 receiving map[string]bool
60}
61
62// errBusy is body's error when another request is staging the same body
63// of the same upload.
64var errBusy = errors.New("another request is staging this body")
65
66// The kinds of request the publisher makes.
67const (
68 stepAuthorization = "authorization"
69 stepManifest = "manifest"
70 stepBody = "body"
71 stepCommit = "commit"
72 // stepLegacy is a path of the first version of the upload, which is
73 // refused as unsupported-version.
74 stepLegacy = "legacy"
75)
76
77// ServeHTTP authenticates the request, then routes it, then takes a slot
78// for it, in that order. A request without the token is refused with no
79// slot taken and no byte of its body read.
80func (rv *receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
81 rc := http.NewResponseController(w)
82 rc.SetWriteDeadline(time.Now().Add(shortTimeout))
83 if !export.CarriesToken(r, rv.token) {
84 // Closing the connection after the reply reads none of the body.
85 rc.SetReadDeadline(time.Now())
86 w.Header().Set("Connection", "close")
87 w.Header().Set("WWW-Authenticate", `Bearer realm="valley-web-receive"`)
88 rv.fail(w, r, &export.Error{Code: export.CodeUnauthenticated,
89 Message: "Authorization header must carry the receiver's bearer token"})
90 return
91 }
92 step, seq, sum, allow := route(r.URL.Path)
93 switch {
94 case step == "":
95 rc.SetReadDeadline(time.Now())
96 w.Header().Set("Connection", "close")
97 reply(w, http.StatusNotFound, nil)
98 return
99 case step == stepLegacy:
100 rc.SetReadDeadline(time.Now())
101 w.Header().Set("Connection", "close")
102 rv.fail(w, r, &export.Error{Code: export.CodeUnsupportedVersion,
103 Message: "this receiver takes signed authorizations and the-valley/web-export/v2 manifests under " + export.PathPrefix + "; upgrade valley-web-publish on the valley host"})
104 return
105 case r.Method != allow:
106 rc.SetReadDeadline(time.Now())
107 w.Header().Set("Connection", "close")
108 w.Header().Set("Allow", allow)
109 reply(w, http.StatusMethodNotAllowed, nil)
110 return
111 }
112 slots := rv.slots
113 if step == stepAuthorization {
114 slots = rv.authSlots
115 }
116 select {
117 case slots <- struct{}{}:
118 defer func() { <-slots }()
119 default:
120 busy(w, rc)
121 return
122 }
123
124 // The deadline bounds the connection's reads and writes, and ctx the
125 // store's work: waiting for its lock, and the git a commit runs. ctx
126 // is done, too, once the client goes away.
127 timeout := map[string]time.Duration{stepAuthorization: authorizationTimeout, stepManifest: manifestTimeout, stepBody: bodyTimeout, stepCommit: commitTimeout}[step]
128 deadline := time.Now().Add(timeout)
129 rc.SetReadDeadline(deadline)
130 rc.SetWriteDeadline(deadline)
131 ctx, cancel := context.WithDeadline(r.Context(), deadline)
132 defer cancel()
133 switch step {
134 case stepAuthorization:
135 got, err := rv.authorization(ctx, r)
136 if err != nil {
137 rv.fail(w, r, err)
138 return
139 }
140 rv.log.Printf("stored authorization %d", got.Sequence)
141 reply(w, http.StatusOK, got)
142 case stepManifest:
143 inv, err := rv.manifest(ctx, r)
144 if err != nil {
145 rv.fail(w, r, err)
146 return
147 }
148 reply(w, http.StatusOK, inv)
149 case stepBody:
150 err := rv.body(ctx, rc, r, seq, sum)
151 if errors.Is(err, errBusy) {
152 busy(w, rc)
153 return
154 }
155 if err != nil {
156 rv.fail(w, r, err)
157 return
158 }
159 reply(w, http.StatusNoContent, nil)
160 case stepCommit:
161 g, err := rv.commit(ctx, seq)
162 if err != nil {
163 rv.fail(w, r, err)
164 return
165 }
166 rv.log.Printf("activated sequence %d", g.Sequence)
167 reply(w, http.StatusOK, export.Committed{Schema: export.CommittedSchema, Sequence: g.Sequence})
168 }
169}
170
171// route reads the step a path names, and the method that step takes. A
172// body's path names its upload's sequence and its SHA-256, and a commit's
173// the sequence. step is "" for a path the upload does not use.
174func route(path string) (step string, seq int64, sum, method string) {
175 switch {
176 case path == export.AuthorizationPath:
177 return stepAuthorization, 0, "", http.MethodPost
178 case path == export.ManifestPath:
179 return stepManifest, 0, "", http.MethodPost
180 case strings.HasPrefix(path, export.LegacyPrefix):
181 return stepLegacy, 0, "", ""
182 }
183 rest, ok := strings.CutPrefix(path, export.PathPrefix)
184 if !ok {
185 return "", 0, "", ""
186 }
187 parts := strings.Split(rest, "/")
188 if len(parts) != 2 {
189 return "", 0, "", ""
190 }
191 seq, err := strconv.ParseInt(parts[0], 10, 64)
192 if err != nil || seq <= 0 || strconv.FormatInt(seq, 10) != parts[0] {
193 return "", 0, "", ""
194 }
195 switch {
196 case parts[1] == "commit":
197 return stepCommit, seq, "", http.MethodPost
198 case isSHA256(parts[1]):
199 return stepBody, seq, parts[1], http.MethodPut
200 }
201 return "", 0, "", ""
202}
203
204func isSHA256(s string) bool {
205 if len(s) != 64 {
206 return false
207 }
208 for i := 0; i < len(s); i++ {
209 if !('0' <= s[i] && s[i] <= '9' || 'a' <= s[i] && s[i] <= 'f') {
210 return false
211 }
212 }
213 return true
214}
215
216// authorization admits a signed authorization by its signature, its type,
217// its instance and destination, and its sequence, and stores it durably,
218// without the store's activation lock. The reply is sent once it is
219// stored. It then deletes, in the background, the repositories the
220// authorization withdrew, once no reader holds them; neither the reply nor
221// the next authorization waits for that.
222func (rv *receiver) authorization(ctx context.Context, r *http.Request) (export.AuthorizationReply, error) {
223 hw, err := rv.store.AuthorizationHighWater()
224 if err != nil {
225 return export.AuthorizationReply{}, err
226 }
227 signed, err := io.ReadAll(io.LimitReader(r.Body, export.MaxAuthorization+1))
228 if err != nil {
229 return export.AuthorizationReply{}, &export.Error{Code: export.CodeUnreadable, Message: fmt.Sprintf("the authorization could not be read: %v", err)}
230 }
231 a, err := export.VerifyAuthorization(bytes.NewReader(signed), export.AuthorizationAdmission{Verifiers: rv.verifiers,
232 Instance: rv.instance, Destination: rv.destination, HighWater: hw})
233 if err != nil {
234 return export.AuthorizationReply{}, err
235 }
236 if err := rv.store.Authorize(ctx, a, signed); err != nil {
237 return export.AuthorizationReply{}, err
238 }
239 rv.prune()
240 got := export.AuthorizationReply{Schema: export.AuthorizedSchema, Sequence: a.Sequence}
241 // What the receiver serves only advises the publisher, so a failure
242 // to read it does not undo the reply: the publisher then uploads.
243 active, _, err := rv.store.Holdings()
244 if err == nil {
245 got.Missing, err = rv.store.Missing()
246 }
247 if err != nil {
248 rv.log.Printf("reading what the store serves: %v", err)
249 return got, nil
250 }
251 got.Active = active
252 return got, nil
253}
254
255// prune deletes the repositories the stored authorization withdrew, in a
256// goroutine of its own, unless one is running already: that one reads the
257// authorization again each time it tries. While a reader holds the active
258// generation it tries again, after a pause that doubles up to five
259// seconds, for at most pruneTimeout. A prune that does not finish is
260// logged, and the next authorization, activation or start of the receiver
261// tries again.
262func (rv *receiver) prune() {
263 if !rv.pruning.CompareAndSwap(false, true) {
264 return
265 }
266 go func() {
267 defer rv.pruning.Store(false)
268 ctx, cancel := context.WithTimeout(context.Background(), pruneTimeout)
269 defer cancel()
270 pause := rv.pruneDelay
271 for {
272 err := rv.store.Prune(ctx)
273 if err == nil {
274 return
275 }
276 if !errors.Is(err, export.ErrHeld) {
277 rv.log.Printf("deleting withdrawn repositories: %v", err)
278 return
279 }
280 select {
281 case <-time.After(pause):
282 pause = min(2*pause, 5*time.Second)
283 case <-ctx.Done():
284 rv.log.Printf("deleting withdrawn repositories: readers held the active generation for %v; will retry on the next authorization or activation", pruneTimeout)
285 return
286 }
287 }
288 }()
289}
290
291// manifest is step 1: admit the manifest, hold its bodies to the caps,
292// stage it, and reply with the inventory. Staging waits for the store's
293// lock, which a commit holds throughout, until ctx is done.
294func (rv *receiver) manifest(ctx context.Context, r *http.Request) (export.Inventory, error) {
295 hw, err := rv.store.HighWater()
296 if err != nil {
297 return export.Inventory{}, err
298 }
299 m, err := export.VerifyManifest(r.Body, export.Admission{Verifiers: rv.verifiers,
300 Instance: rv.instance, Destination: rv.destination, HighWater: hw, Now: time.Now()})
301 if err != nil {
302 return export.Inventory{}, err
303 }
304 if err := m.CheckSizes(rv.maxBody, rv.maxUpload); err != nil {
305 return export.Inventory{}, err
306 }
307 st, err := rv.store.Stage(ctx, m)
308 if err != nil {
309 return export.Inventory{}, err
310 }
311 rv.mu.Lock()
312 if rv.staged == nil || rv.staged.Manifest.Sequence <= m.Sequence {
313 rv.staged = &st
314 }
315 rv.mu.Unlock()
316 return rv.store.Inventory(st)
317}
318
319// upload is the staged upload with sequence: no-manifest when nothing
320// newer than it is staged, and superseded when something newer is.
321func (rv *receiver) upload(seq int64) (export.Staging, error) {
322 rv.mu.Lock()
323 defer rv.mu.Unlock()
324 switch {
325 case rv.staged == nil || rv.staged.Manifest.Sequence < seq:
326 return export.Staging{}, &export.Error{Code: export.CodeNoManifest,
327 Message: fmt.Sprintf("no manifest is staged for sequence %d", seq)}
328 case rv.staged.Manifest.Sequence > seq:
329 return export.Staging{}, &export.Error{Code: export.CodeSuperseded,
330 Message: fmt.Sprintf("staged upload %d supersedes sequence %d", rv.staged.Manifest.Sequence, seq)}
331 }
332 return *rv.staged, nil
333}
334
335// body is step 2 for the body with SHA-256 sum. It stages the body until
336// ctx is done, or until the store discards the upload's bodies (see
337// export.Store.Writer), and then ends the read that waits on the client.
338func (rv *receiver) body(ctx context.Context, rc *http.ResponseController, r *http.Request, seq int64, sum string) error {
339 st, err := rv.upload(seq)
340 if err != nil {
341 return err
342 }
343 var want *export.Body
344 for _, b := range st.Manifest.Bodies() {
345 if b.SHA256 == sum {
346 want = &b
347 break
348 }
349 }
350 if want == nil {
351 return &export.Error{Code: export.CodeNotDeclared,
352 Message: fmt.Sprintf("manifest for sequence %d declares no body with SHA-256 %s", seq, sum)}
353 }
354 path := st.Body(*want)
355 rv.mu.Lock()
356 if rv.receiving[path] {
357 rv.mu.Unlock()
358 return errBusy
359 }
360 if rv.receiving == nil {
361 rv.receiving = map[string]bool{}
362 }
363 rv.receiving[path] = true
364 rv.mu.Unlock()
365 defer func() {
366 rv.mu.Lock()
367 delete(rv.receiving, path)
368 rv.mu.Unlock()
369 }()
370 wctx, done, err := rv.store.Writer(ctx, st)
371 if err != nil {
372 return err
373 }
374 defer done()
375 // A read deadline set once the handler has returned would end the
376 // connection's next request, so the handler waits for one being set.
377 interrupted := make(chan struct{})
378 stop := context.AfterFunc(wctx, func() {
379 rc.SetReadDeadline(time.Now())
380 close(interrupted)
381 })
382 defer func() {
383 if !stop() {
384 <-interrupted
385 }
386 }()
387 _, err = export.StageBody(st.Bodies(), *want, rv.maxBody, r.WithContext(wctx))
388 if errors.Is(err, fs.ErrNotExist) {
389 // The upload's staging directory is gone: a newer manifest
390 // discarded it, or a commit activated it.
391 if _, err := rv.upload(seq); err != nil {
392 return err
393 }
394 return &export.Error{Code: export.CodeNoManifest,
395 Message: fmt.Sprintf("staging for sequence %d was cleared before the body finished", seq)}
396 }
397 return err
398}
399
400// commit is step 3: activate the upload with sequence, until ctx is done.
401func (rv *receiver) commit(ctx context.Context, seq int64) (export.Generation, error) {
402 st, err := rv.upload(seq)
403 if err != nil {
404 return export.Generation{}, err
405 }
406 g, err := rv.store.Activate(ctx, st)
407 if err == nil {
408 // Activate prunes what it can; a reader may have held the old
409 // generation, which the new one replaced, or the new one.
410 rv.prune()
411 }
412 return g, err
413}
414
415// fail replies with the refusal err is, or with 500 and no refusal for any
416// other error, which the publisher retries. Either is logged.
417func (rv *receiver) fail(w http.ResponseWriter, r *http.Request, err error) {
418 var e *export.Error
419 if errors.As(err, &e) {
420 rv.log.Printf("%s %s from %s: refused: %v", r.Method, r.URL.Path, r.RemoteAddr, e)
421 reply(w, e.Code.Status(), e.Reply())
422 return
423 }
424 rv.log.Printf("%s %s from %s: %v", r.Method, r.URL.Path, r.RemoteAddr, err)
425 reply(w, http.StatusInternalServerError, nil)
426}
427
428// drain takes every request slot, so it waits until each request that
429// holds one has finished, with the git it runs, or until ctx is done. It
430// reports whether it took them all. A request that comes after takes no
431// slot, and is answered 503.
432func (rv *receiver) drain(ctx context.Context) bool {
433 for _, slots := range []chan struct{}{rv.slots, rv.authSlots} {
434 for range cap(slots) {
435 select {
436 case slots <- struct{}{}:
437 case <-ctx.Done():
438 return false
439 }
440 }
441 }
442 return true
443}
444
445// busy answers 503 with Retry-After and no refusal, which the publisher
446// retries after a pause, and closes the connection without reading the
447// body.
448func busy(w http.ResponseWriter, rc *http.ResponseController) {
449 rc.SetReadDeadline(time.Now())
450 w.Header().Set("Connection", "close")
451 w.Header().Set("Retry-After", "5")
452 reply(w, http.StatusServiceUnavailable, nil)
453}
454
455// reply writes the status, and doc as JSON when it is not nil.
456func reply(w http.ResponseWriter, status int, doc any) {
457 w.Header().Set("Cache-Control", "no-store")
458 if doc == nil {
459 w.WriteHeader(status)
460 return
461 }
462 w.Header().Set("Content-Type", "application/json")
463 w.WriteHeader(status)
464 json.NewEncoder(w).Encode(doc)
465}