gunk-dev/the-valley

receive.go

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