gunk-dev/the-valley

upload.go

source4d6ef35777b0main's published tip history
22.0 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "io/fs"
11 "net"
12 "net/http"
13 "net/url"
14 "os"
15 "path/filepath"
16 "strings"
17 "time"
18
19 "the-valley/web/export"
20)
21
22// How an upload is retried. A pass makes at most uploadAttempts attempts.
23// It waits for its clock to pass a receiver's high-water mark only when
24// that is at most maxClockWait away; a mark further ahead is a clock fault
25// the operator has to see, and the next pass tries again.
26const (
27 uploadAttempts = 5
28 maxClockWait = 2 * export.MaxAhead
29 firstBackoff = 2 * time.Second
30)
31
32// How long each request may take. A body's time grows with its size, from
33// bodyTimeoutMin to bodyTimeoutMax, at bodyRateMin bytes a second. A
34// commit waits for the receiver to fetch and check every bundle it was
35// sent.
36const (
37 authorizationTimeout = time.Minute
38 manifestTimeout = 2 * time.Minute
39 bodyTimeoutMin = 2 * time.Minute
40 bodyTimeoutMax = 30 * time.Minute
41 bodyRateMin = 256 << 10
42 commitTimeout = 10 * time.Minute
43 maxReply = 1 << 20
44)
45
46// bodyTimeoutFor is how long a body of size bytes may take. The size is
47// held to the cap before it is multiplied, so none overflows the duration.
48func bodyTimeoutFor(size int64) time.Duration {
49 const atMax = int64((bodyTimeoutMax-bodyTimeoutMin)/time.Second) * bodyRateMin
50 switch {
51 case size <= 0:
52 return bodyTimeoutMin
53 case size >= atMax:
54 return bodyTimeoutMax
55 }
56 return bodyTimeoutMin + time.Duration(size)*time.Second/bodyRateMin
57}
58
59// bundles are each exported project's bundle of main, by project: the
60// file, and the body it makes. A bundle is made once for each source tip
61// and kept in the cache, so the body a manifest declares for a tip is the
62// same in every pass. The bundles the export does not declare are removed
63// first. Each bundle still to be made is then written only into the room
64// --max-bundles and --max-storage leave: its writing stops there, and the
65// pass then removes every bundle it wrote and sends nothing.
66func (p *publisher) bundles(ctx context.Context, r *reading) (map[string]string, map[string]export.Body, error) {
67 root := filepath.Join(p.cache, "bundles")
68 paths := map[string]string{}
69 for _, proj := range r.export.Projects {
70 paths[proj.Name] = filepath.Join(root, proj.Name, proj.SourceTip+".bundle")
71 }
72 pruneBundles(root, paths)
73 used, err := p.storageUsed()
74 if err != nil {
75 return nil, nil, err
76 }
77 var held int64 // what the export's bundles hold together
78 var missing []export.Project
79 for _, proj := range r.export.Projects {
80 info, err := os.Stat(paths[proj.Name])
81 switch {
82 case errors.Is(err, os.ErrNotExist):
83 missing = append(missing, proj)
84 case err != nil:
85 return nil, nil, err
86 default:
87 held += info.Size()
88 }
89 }
90 if held > int64(p.cfg.maxBundles) {
91 return nil, nil, fmt.Errorf("the bundles hold %d bytes together, more than --max-bundles %d, so the pass sends nothing", held, p.cfg.maxBundles)
92 }
93 if used > int64(p.cfg.maxStorage) {
94 return nil, nil, p.overStorage(used)
95 }
96 var made []string
97 for _, proj := range missing {
98 room, bound := int64(p.cfg.maxBundles)-held, fmt.Sprintf("--max-bundles %d", p.cfg.maxBundles)
99 if left := int64(p.cfg.maxStorage) - used; left < room {
100 room, bound = left, fmt.Sprintf("--max-storage %d", p.cfg.maxStorage)
101 }
102 size, err := makeBundle(ctx, r.mirrors[proj.Name], paths[proj.Name], proj.SourceTip, room)
103 if errors.Is(err, errOverBudget) {
104 err = fmt.Errorf("its bundle is larger than the %d bytes %s leaves for it, so the pass sends nothing and removes the bundles it wrote", room, bound)
105 }
106 if err != nil {
107 // Each bundle's directory goes with it, once it is empty.
108 for _, path := range append(made, paths[proj.Name]) {
109 os.Remove(path)
110 os.Remove(filepath.Dir(path))
111 }
112 return nil, nil, fmt.Errorf("%s: %w", proj.Name, err)
113 }
114 made = append(made, paths[proj.Name])
115 held += size
116 used += size
117 }
118 bodies := map[string]export.Body{}
119 for name, path := range paths {
120 if bodies[name], err = export.FileBody(name, path); err != nil {
121 return nil, nil, err
122 }
123 }
124 return paths, bodies, nil
125}
126
127// pruneBundles removes everything under root but the bundles keep names:
128// the bundles of a project's earlier tips, of projects the export does not
129// hold, and what a pass that was stopped left of one it was writing.
130func pruneBundles(root string, keep map[string]string) {
131 projects, _ := os.ReadDir(root)
132 for _, d := range projects {
133 dir := filepath.Join(root, d.Name())
134 if _, ok := keep[d.Name()]; !ok || !d.IsDir() {
135 os.RemoveAll(dir)
136 continue
137 }
138 files, _ := os.ReadDir(dir)
139 for _, f := range files {
140 if path := filepath.Join(dir, f.Name()); path != keep[d.Name()] {
141 os.RemoveAll(path)
142 }
143 }
144 }
145}
146
147// checkStorage holds the state directory and the caches to --max-storage.
148// A pass checks before it fetches anything, and again once it has read the
149// valley, whether it then sends anything or not.
150func (p *publisher) checkStorage() error {
151 used, err := p.storageUsed()
152 if err != nil {
153 return err
154 }
155 if used > int64(p.cfg.maxStorage) {
156 return p.overStorage(used)
157 }
158 return nil
159}
160
161func (p *publisher) overStorage(used int64) error {
162 return fmt.Errorf("the state directory and the cache hold %d bytes, more than --max-storage %d, so the pass sends nothing", used, p.cfg.maxStorage)
163}
164
165// storageUsed is the size of every regular file the publisher keeps: in
166// its state directory, its cache, and the valley CLI's cache beside it,
167// which holds the CLI's clones of every project.
168func (p *publisher) storageUsed() (int64, error) {
169 var total int64
170 for _, dir := range []string{p.cfg.state, p.cache, filepath.Join(filepath.Dir(p.cache), "valley")} {
171 err := filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error {
172 if err == nil && d.Type().IsRegular() {
173 var info fs.FileInfo
174 if info, err = d.Info(); err == nil {
175 total += info.Size()
176 }
177 }
178 if errors.Is(err, fs.ErrNotExist) {
179 return nil
180 }
181 return err
182 })
183 if err != nil {
184 return 0, err
185 }
186 }
187 return total, nil
188}
189
190// errOverBudget is makeBundle's error for a bundle larger than the room
191// it is given.
192var errOverBudget = errors.New("the bundle is larger than the room left for it")
193
194// makeBundle writes a full bundle of the mirror's main to path, and returns
195// its size. git writes the bundle to its stdout, and the publisher writes
196// it to a temporary name, which is renamed into place once git bundle
197// list-heads shows it carries main at tip. At most room bytes reach the
198// file: a write past them fails, which ends git at its next write, and
199// makeBundle removes the file and returns errOverBudget.
200func makeBundle(ctx context.Context, mirror, path, tip string, room int64) (int64, error) {
201 if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
202 return 0, err
203 }
204 tmp := path + ".new"
205 f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
206 if err != nil {
207 return 0, err
208 }
209 defer os.Remove(tmp)
210 w := &budgeted{w: f, room: room}
211 err = gitStream(ctx, mirror, nil, w, "bundle", "create", "--quiet", "-", export.MainRef)
212 if cerr := f.Close(); err == nil {
213 err = cerr
214 }
215 if w.over {
216 return 0, errOverBudget
217 }
218 if err != nil {
219 return 0, err
220 }
221 heads, err := git(ctx, mirror, "bundle", "list-heads", tmp)
222 if err != nil {
223 return 0, err
224 }
225 if got, want := strings.TrimSpace(string(heads)), tip+" "+export.MainRef; got != want {
226 return 0, fmt.Errorf("the bundle made of main carries %q, not %q", got, want)
227 }
228 return w.written, os.Rename(tmp, path)
229}
230
231// budgeted writes through to w until room bytes are written. A write that
232// would pass room writes nothing, fails, and sets over. It is no
233// io.ReaderFrom, so os/exec copies through Write.
234type budgeted struct {
235 w io.Writer
236 room, written int64
237 over bool
238}
239
240func (b *budgeted) Write(p []byte) (int, error) {
241 if int64(len(p)) > b.room-b.written {
242 b.over = true
243 return 0, errOverBudget
244 }
245 n, err := b.w.Write(p)
246 b.written += int64(n)
247 return n, err
248}
249
250// writeOut writes the export to --out, as a pass would send it: the
251// signed authorization, the signed manifest, export.json, and
252// bundles/<project>.bundle. The
253// directory is written beside its place and renamed into it whole, so a
254// reader never sees part of it.
255func (p *publisher) writeOut(ctx context.Context, r *reading) error {
256 dir := p.cfg.out
257 if entries, err := os.ReadDir(dir); err == nil && len(entries) > 0 {
258 return fmt.Errorf("--out %s is not empty", dir)
259 } else if err != nil && !errors.Is(err, os.ErrNotExist) {
260 return err
261 }
262 paths, bodies, err := p.bundles(ctx, r)
263 if err != nil {
264 return err
265 }
266 m, signed, err := p.sign(r, bodies, p.now().UnixNano())
267 if err != nil {
268 return err
269 }
270 parent := filepath.Dir(filepath.Clean(dir))
271 tmp, err := os.MkdirTemp(parent, "."+filepath.Base(dir)+".new-")
272 if err != nil {
273 return err
274 }
275 defer os.RemoveAll(tmp)
276 if err := os.WriteFile(filepath.Join(tmp, "manifest"), signed, 0o644); err != nil {
277 return err
278 }
279 if err := os.WriteFile(filepath.Join(tmp, authorizationFile), p.signedAuthorization, 0o644); err != nil {
280 return err
281 }
282 if err := os.WriteFile(filepath.Join(tmp, export.ExportFile), r.json, 0o644); err != nil {
283 return err
284 }
285 if err := os.Mkdir(filepath.Join(tmp, "bundles"), 0o755); err != nil {
286 return err
287 }
288 for name, path := range paths {
289 if err := copyFile(path, filepath.Join(tmp, "bundles", name+".bundle")); err != nil {
290 return err
291 }
292 }
293 if err := os.Chmod(tmp, 0o755); err != nil {
294 return err
295 }
296 if err := os.Rename(tmp, dir); err != nil {
297 return err
298 }
299 p.say("wrote the export to %s, as sequence %d", dir, m.Sequence)
300 return nil
301}
302
303func copyFile(from, to string) error {
304 in, err := os.Open(from)
305 if err != nil {
306 return err
307 }
308 defer in.Close()
309 out, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
310 if err != nil {
311 return err
312 }
313 if _, err := io.Copy(out, in); err != nil {
314 out.Close()
315 return err
316 }
317 return out.Close()
318}
319
320// sign makes and signs the manifest for the export, with the sequence
321// given.
322func (p *publisher) sign(r *reading, bodies map[string]export.Body, sequence int64) (*export.Manifest, []byte, error) {
323 m, err := export.NewManifest(p.cfg.instance, p.cfg.destination, sequence, r.export, r.json, bodies)
324 if err != nil {
325 return nil, nil, err
326 }
327 signed, err := m.Sign(p.signer, p.key)
328 if err != nil {
329 return nil, nil, err
330 }
331 return m, signed, nil
332}
333
334// upload sends the export to the receiver, by the protocol package export
335// defines, and records the receiver's acknowledgement. It retries:
336//
337// - a request that failed in transit, that the receiver answered with a
338// status and no refusal, or that it refused as unreadable, with the
339// same manifest, after a pause that doubles each time; the receiver
340// keeps the bodies already sent;
341// - incomplete, with the same manifest, whose inventory names what is
342// still needed;
343// - replayed, with a manifest signed once the clock has passed the
344// receiver's high-water mark, waiting for it when it is close;
345// - superseded and no-manifest, with a new manifest, after a pause.
346//
347// Before each retry the idle connections are closed, so it does not reuse
348// one that a failed request left dead or closing.
349//
350// Every other refusal ends the pass: it says the token, the manifest or a
351// body is wrong, or that the clocks disagree by more than the receiver's
352// window, and the operator has to see it. Out-of-window is the last of
353// those.
354func (p *publisher) upload(ctx context.Context, r *reading, digest string, ack acknowledged) error {
355 paths, bodies, err := p.bundles(ctx, r)
356 if err != nil {
357 return err
358 }
359 rc := receiver{base: strings.TrimSuffix(p.cfg.receiver, "/"), token: p.token, client: p.client}
360 highWater := ack.Sequence
361 var m *export.Manifest
362 var signed []byte
363 backoff := firstBackoff
364 for attempt := 1; ; attempt++ {
365 if m == nil {
366 seq, err := p.sequenceAfter(ctx, highWater)
367 if err != nil {
368 return err
369 }
370 if m, signed, err = p.sign(r, bodies, seq); err != nil {
371 return err
372 }
373 }
374 active, err := p.send(ctx, rc, m, signed, r.json, paths, digest)
375 if err == nil {
376 return p.recordAcknowledged(digest, active)
377 }
378 if ctx.Err() != nil {
379 return ctx.Err()
380 }
381 if attempt == uploadAttempts {
382 return fmt.Errorf("the upload failed %d times: %w", attempt, err)
383 }
384 pause := time.Duration(0)
385 var refusal *export.Error
386 switch {
387 case !errors.As(err, &refusal) || refusal.Code == export.CodeUnreadable:
388 pause, backoff = backoff, 2*backoff
389 case refusal.Code == export.CodeIncomplete:
390 case refusal.Code == export.CodeReplayed:
391 highWater = max(highWater, refusal.HighWater)
392 m = nil
393 case refusal.Code == export.CodeSuperseded || refusal.Code == export.CodeNoManifest:
394 pause, backoff = backoff, 2*backoff
395 m = nil
396 case refusal.Code == export.CodeOutOfWindow:
397 return fmt.Errorf("the receiver refused the manifest signed at %s: %s; check this host's clock and the receiver's", m.SignedAt().Format(time.RFC3339), refusal.Message)
398 default:
399 return fmt.Errorf("the receiver refused the upload: %w", err)
400 }
401 p.warn("%v; trying again", err)
402 if err := p.sleep(ctx, pause); err != nil {
403 return err
404 }
405 // After the pause, not before it: HTTP/2 ends a cancelled request's
406 // stream in the background, and until then its connection is not
407 // idle and would be kept for the retry.
408 rc.client.CloseIdleConnections()
409 }
410}
411
412// sequenceAfter is a sequence for a new manifest: the clock now, in Unix
413// nanoseconds, once it is past the greatest sequence the receiver is known
414// to have accepted. The clock is waited for when it is close behind, and
415// is otherwise a fault: publishing out of order is never done.
416func (p *publisher) sequenceAfter(ctx context.Context, highWater int64) (int64, error) {
417 seq := p.now().UnixNano()
418 if seq > highWater {
419 return seq, nil
420 }
421 behind := time.Duration(highWater-seq) + time.Millisecond
422 if behind > maxClockWait {
423 return 0, fmt.Errorf("the receiver has accepted sequence %d (signed at %s), and this host's clock is %s behind it; that exceeds the 2m wait limit, so the pass fails", highWater, time.Unix(0, highWater).UTC().Format(time.RFC3339), behind.Round(time.Second))
424 }
425 if err := p.sleep(ctx, behind); err != nil {
426 return 0, err
427 }
428 if seq = p.now().UnixNano(); seq <= highWater {
429 return 0, fmt.Errorf("this host's clock did not pass the receiver's sequence %d", highWater)
430 }
431 return seq, nil
432}
433
434// send is one attempt at the three steps. It returns the sequence the
435// receiver serves the export as: the active one when the inventory shows
436// it already serves this digest and needs no bundle, and otherwise the
437// manifest's, once committed.
438func (p *publisher) send(ctx context.Context, rc receiver, m *export.Manifest, signed, exportJSON []byte,
439 bundles map[string]string, digest string) (int64, error) {
440 inv, err := rc.postManifest(ctx, signed)
441 if err != nil {
442 return 0, err
443 }
444 if inv.Sequence != m.Sequence {
445 return 0, fmt.Errorf("the receiver's inventory is for sequence %d, not %d", inv.Sequence, m.Sequence)
446 }
447 needsBundle := false
448 for _, n := range inv.Needs {
449 needsBundle = needsBundle || n.Name != export.ExportFile
450 }
451 if inv.Active != nil && inv.Active.Digest == digest && !needsBundle {
452 p.say("the receiver serves this export already, as sequence %d; nothing is sent", inv.Active.Sequence)
453 return inv.Active.Sequence, nil
454 }
455 declared := map[string]export.Body{}
456 for _, b := range m.Bodies() {
457 declared[b.SHA256] = b
458 }
459 var sent []string
460 for _, n := range inv.Needs {
461 b, ok := declared[n.SHA256]
462 if !ok || b.Size != n.Size {
463 return 0, fmt.Errorf("the receiver needs a body, %s %s, that the manifest does not declare", n.Name, n.SHA256)
464 }
465 open := func() (io.ReadCloser, error) { return os.Open(bundles[b.Name]) }
466 if b.Name == export.ExportFile {
467 open = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(exportJSON)), nil }
468 }
469 if err := rc.putBody(ctx, m.Sequence, b, open); err != nil {
470 return 0, err
471 }
472 sent = append(sent, b.Name)
473 }
474 c, err := rc.commit(ctx, m.Sequence)
475 if err != nil {
476 return 0, err
477 }
478 if c.Sequence != m.Sequence {
479 return 0, fmt.Errorf("the receiver committed sequence %d, not %d", c.Sequence, m.Sequence)
480 }
481 if len(sent) == 0 {
482 sent = []string{"nothing"}
483 }
484 p.say("sent %s; the receiver activated sequence %d, digest %s", strings.Join(sent, ", "), c.Sequence, short(digest))
485 return c.Sequence, nil
486}
487
488// receiver is the receiver's upload endpoints under its base URL, and the
489// token every request to them carries.
490type receiver struct {
491 base string
492 token string
493 client *http.Client
494}
495
496// checkReceiver holds --receiver to an http or https URL with a host, and
497// no query or fragment the paths would be appended after.
498func checkReceiver(raw string) error {
499 u, err := url.Parse(raw)
500 if err != nil {
501 return fmt.Errorf("--receiver %q: %w", raw, err)
502 }
503 if (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
504 return fmt.Errorf("--receiver %q is not an http or https URL with a host, and no user, query or fragment", raw)
505 }
506 return nil
507}
508
509// newClient is the HTTP client uploads are made with. It follows no
510// redirect and uses no proxy: it connects to the receiver configured, and
511// neither a POST nor the token is ever sent elsewhere.
512//
513// The requests of one attempt share a connection. One left idle while a
514// pass reads the valley is closed before the receiver, or a proxy in front
515// of it, drops it. An HTTP/2 connection that receives nothing is pinged, so
516// a dead one fails its request within the two ping timeouts; over HTTP/1
517// only the request's own timeout does.
518func newClient() *http.Client {
519 return &http.Client{
520 CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
521 Transport: &http.Transport{
522 DialContext: (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
523 TLSHandshakeTimeout: 30 * time.Second,
524 ResponseHeaderTimeout: commitTimeout,
525 IdleConnTimeout: 15 * time.Second,
526 ForceAttemptHTTP2: true,
527 HTTP2: &http.HTTP2Config{SendPingTimeout: 30 * time.Second, PingTimeout: 15 * time.Second},
528 },
529 }
530}
531
532// postAuthorization posts a signed authorization.
533func (rc receiver) postAuthorization(ctx context.Context, signed []byte) (export.AuthorizationReply, error) {
534 var reply export.AuthorizationReply
535 err := rc.do(ctx, authorizationTimeout, http.MethodPost, export.AuthorizationPath, "text/plain; charset=utf-8",
536 func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(signed)), nil },
537 int64(len(signed)), http.StatusOK, export.AuthorizedSchema, &reply)
538 return reply, err
539}
540
541// statusError is a reply with a status other than the one wanted, and no
542// refusal in it.
543type statusError struct {
544 method, path, status string
545 code int
546}
547
548func (e statusError) Error() string {
549 return fmt.Sprintf("%s %s: the receiver replied %s", e.method, e.path, e.status)
550}
551
552// postManifest is step 1.
553func (rc receiver) postManifest(ctx context.Context, signed []byte) (export.Inventory, error) {
554 var inv export.Inventory
555 err := rc.do(ctx, manifestTimeout, http.MethodPost, export.ManifestPath, "text/plain; charset=utf-8",
556 func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(signed)), nil },
557 int64(len(signed)), http.StatusOK, export.InventorySchema, &inv)
558 return inv, err
559}
560
561// putBody is step 2, for one body: its bytes as they are, with their
562// declared size as the Content-Length and no Content-Encoding.
563func (rc receiver) putBody(ctx context.Context, sequence int64, b export.Body, open func() (io.ReadCloser, error)) error {
564 return rc.do(ctx, bodyTimeoutFor(b.Size), http.MethodPut, export.BodyPath(sequence, b.SHA256), "application/octet-stream",
565 open, b.Size, http.StatusNoContent, "", nil)
566}
567
568// commit is step 3.
569func (rc receiver) commit(ctx context.Context, sequence int64) (export.Committed, error) {
570 var c export.Committed
571 err := rc.do(ctx, commitTimeout, http.MethodPost, export.CommitPath(sequence), "",
572 nil, 0, http.StatusOK, export.CommittedSchema, &c)
573 return c, err
574}
575
576// do makes one request and reads its reply. A refusal the receiver replies
577// with is returned as an *export.Error; any other failure, in transit or
578// a status with no refusal in it, is an error of its own, which upload
579// retries.
580func (rc receiver) do(ctx context.Context, timeout time.Duration, method, path, contentType string,
581 open func() (io.ReadCloser, error), size int64, wantStatus int, schema string, into any) error {
582 ctx, cancel := context.WithTimeout(ctx, timeout)
583 defer cancel()
584 var body io.ReadCloser = http.NoBody
585 if open != nil {
586 var err error
587 if body, err = open(); err != nil {
588 return err
589 }
590 }
591 req, err := http.NewRequestWithContext(ctx, method, rc.base+path, body)
592 if err != nil {
593 body.Close()
594 return err
595 }
596 req.ContentLength = size
597 if size == 0 {
598 req.Body = http.NoBody
599 }
600 if contentType != "" {
601 req.Header.Set("Content-Type", contentType)
602 }
603 req.Header.Set("Authorization", export.BearerHeader(rc.token))
604 resp, err := rc.client.Do(req)
605 if err != nil {
606 return fmt.Errorf("%s %s: %w", method, path, err)
607 }
608 defer resp.Body.Close()
609 reply, err := io.ReadAll(io.LimitReader(resp.Body, maxReply+1))
610 if err != nil {
611 return fmt.Errorf("%s %s: reading the reply: %w", method, path, err)
612 }
613 if len(reply) > maxReply {
614 return fmt.Errorf("%s %s: the reply is longer than %d bytes", method, path, maxReply)
615 }
616 if resp.StatusCode != wantStatus {
617 var refusal export.ErrorReply
618 if json.Unmarshal(reply, &refusal) == nil && refusal.Schema == export.ErrorSchema && refusal.Code != "" {
619 return &export.Error{Code: refusal.Code, Message: refusal.Message, HighWater: refusal.HighWater, Needs: refusal.Needs}
620 }
621 return statusError{method: method, path: path, status: resp.Status, code: resp.StatusCode}
622 }
623 if into == nil {
624 return nil
625 }
626 var head struct {
627 Schema string `json:"schema"`
628 }
629 if err := json.Unmarshal(reply, &head); err != nil || head.Schema != schema {
630 return fmt.Errorf("%s %s: the reply is not %s", method, path, schema)
631 }
632 if err := json.Unmarshal(reply, into); err != nil {
633 return fmt.Errorf("%s %s: the reply is not %s: %w", method, path, schema, err)
634 }
635 return nil
636}