gunk-dev/the-valley

receive.go

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