gunk-dev/the-valley

receive.go

source8e8db4f9b2eamain's published tip history
7.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}
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 // The deadline bounds the connection's reads and writes, and ctx the
90 // store's work: waiting for its lock, and the git a commit runs. ctx
91 // is done, too, once the client goes away.
92 timeout := map[string]time.Duration{stepManifest: manifestTimeout, stepBody: bodyTimeout, stepCommit: commitTimeout}[step]
93 deadline := time.Now().Add(timeout)
94 rc.SetReadDeadline(deadline)
95 rc.SetWriteDeadline(deadline)
96 ctx, cancel := context.WithDeadline(r.Context(), deadline)
97 defer cancel()
98 switch step {
99 case stepManifest:
100 inv, err := rv.manifest(ctx, r)
101 if err != nil {
102 rv.fail(w, r, err)
103 return
104 }
105 reply(w, http.StatusOK, inv)
106 case stepBody:
107 if err := rv.body(r, seq, sum); err != nil {
108 rv.fail(w, r, err)
109 return
110 }
111 reply(w, http.StatusNoContent, nil)
112 case stepCommit:
113 g, err := rv.commit(ctx, seq)
114 if err != nil {
115 rv.fail(w, r, err)
116 return
117 }
118 rv.log.Printf("activated sequence %d", g.Sequence)
119 reply(w, http.StatusOK, export.Committed{Schema: export.CommittedSchema, Sequence: g.Sequence})
120 }
121}
122
123// route reads the step a path names, and the method that step takes. A
124// body's path names its upload's sequence and its SHA-256, and a commit's
125// the sequence. step is "" for a path the upload does not use.
126func route(path string) (step string, seq int64, sum, method string) {
127 if path == export.ManifestPath {
128 return stepManifest, 0, "", http.MethodPost
129 }
130 rest, ok := strings.CutPrefix(path, "/web-export/v1/")
131 if !ok {
132 return "", 0, "", ""
133 }
134 parts := strings.Split(rest, "/")
135 if len(parts) != 2 {
136 return "", 0, "", ""
137 }
138 seq, err := strconv.ParseInt(parts[0], 10, 64)
139 if err != nil || seq <= 0 || strconv.FormatInt(seq, 10) != parts[0] {
140 return "", 0, "", ""
141 }
142 switch {
143 case parts[1] == "commit":
144 return stepCommit, seq, "", http.MethodPost
145 case isSHA256(parts[1]):
146 return stepBody, seq, parts[1], http.MethodPut
147 }
148 return "", 0, "", ""
149}
150
151func isSHA256(s string) bool {
152 if len(s) != 64 {
153 return false
154 }
155 for i := 0; i < len(s); i++ {
156 if !('0' <= s[i] && s[i] <= '9' || 'a' <= s[i] && s[i] <= 'f') {
157 return false
158 }
159 }
160 return true
161}
162
163// manifest is step 1: admit the manifest, hold its bodies to the caps,
164// stage it, and reply with the inventory. Staging waits for the store's
165// lock, which a commit holds throughout, until ctx is done.
166func (rv *receiver) manifest(ctx context.Context, r *http.Request) (export.Inventory, error) {
167 hw, err := rv.store.HighWater()
168 if err != nil {
169 return export.Inventory{}, err
170 }
171 m, err := export.VerifyManifest(r.Body, export.Admission{Verifiers: rv.verifiers,
172 Instance: rv.instance, Destination: rv.destination, HighWater: hw, Now: time.Now()})
173 if err != nil {
174 return export.Inventory{}, err
175 }
176 if err := m.CheckSizes(rv.maxBody, rv.maxUpload); err != nil {
177 return export.Inventory{}, err
178 }
179 st, err := rv.store.Stage(ctx, m)
180 if err != nil {
181 return export.Inventory{}, err
182 }
183 rv.mu.Lock()
184 if rv.staged == nil || rv.staged.Manifest.Sequence <= m.Sequence {
185 rv.staged = &st
186 }
187 rv.mu.Unlock()
188 return rv.store.Inventory(st)
189}
190
191// upload is the staged upload with sequence: no-manifest when nothing
192// newer than it is staged, and superseded when something newer is.
193func (rv *receiver) upload(seq int64) (export.Staging, error) {
194 rv.mu.Lock()
195 defer rv.mu.Unlock()
196 switch {
197 case rv.staged == nil || rv.staged.Manifest.Sequence < seq:
198 return export.Staging{}, &export.Error{Code: export.CodeNoManifest,
199 Message: fmt.Sprintf("nothing is staged for sequence %d", seq)}
200 case rv.staged.Manifest.Sequence > seq:
201 return export.Staging{}, &export.Error{Code: export.CodeSuperseded,
202 Message: fmt.Sprintf("the upload with sequence %d supersedes this one, %d", rv.staged.Manifest.Sequence, seq)}
203 }
204 return *rv.staged, nil
205}
206
207// body is step 2 for the body with SHA-256 sum.
208func (rv *receiver) body(r *http.Request, seq int64, sum string) error {
209 st, err := rv.upload(seq)
210 if err != nil {
211 return err
212 }
213 var want *export.Body
214 for _, b := range st.Manifest.Bodies() {
215 if b.SHA256 == sum {
216 want = &b
217 break
218 }
219 }
220 if want == nil {
221 return &export.Error{Code: export.CodeNotDeclared,
222 Message: fmt.Sprintf("the manifest with sequence %d declares no body with SHA-256 %s", seq, sum)}
223 }
224 _, err = export.StageBody(st.Bodies(), *want, rv.maxBody, r)
225 if errors.Is(err, fs.ErrNotExist) {
226 // The upload's staging directory is gone: a newer manifest
227 // discarded it, or a commit activated it.
228 if _, err := rv.upload(seq); err != nil {
229 return err
230 }
231 return &export.Error{Code: export.CodeNoManifest,
232 Message: fmt.Sprintf("nothing is staged for sequence %d any more", seq)}
233 }
234 return err
235}
236
237// commit is step 3: activate the upload with sequence, until ctx is done.
238func (rv *receiver) commit(ctx context.Context, seq int64) (export.Generation, error) {
239 st, err := rv.upload(seq)
240 if err != nil {
241 return export.Generation{}, err
242 }
243 return rv.store.Activate(ctx, st)
244}
245
246// fail replies with the refusal err is, or with 500 and no refusal for any
247// other error, which the publisher retries. Either is logged.
248func (rv *receiver) fail(w http.ResponseWriter, r *http.Request, err error) {
249 var e *export.Error
250 if errors.As(err, &e) {
251 rv.log.Printf("%s %s from %s: refused: %v", r.Method, r.URL.Path, r.RemoteAddr, e)
252 reply(w, e.Code.Status(), e.Reply())
253 return
254 }
255 rv.log.Printf("%s %s from %s: %v", r.Method, r.URL.Path, r.RemoteAddr, err)
256 reply(w, http.StatusInternalServerError, nil)
257}
258
259// reply writes the status, and doc as JSON when it is not nil.
260func reply(w http.ResponseWriter, status int, doc any) {
261 w.Header().Set("Cache-Control", "no-store")
262 if doc == nil {
263 w.WriteHeader(status)
264 return
265 }
266 w.Header().Set("Content-Type", "application/json")
267 w.WriteHeader(status)
268 json.NewEncoder(w).Encode(doc)
269}