oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1package mapa
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io"
11 "net/http"
12 "net/url"
13 "time"
14
15 "amadan.net/rastrillo/rastrillo/blobs"
16)
17
18// bucket is CARLOS's bucket as Mapa writes to it: blobs.S3 for reading
19// and deleting, and a Put of Mapa's own over a presigned URL, so that a
20// refusal is read from the response's status (Fable L8). blobs.S3's own
21// Put reports a status only as text.
22type bucket struct {
23 *blobs.S3
24 client *http.Client
25}
26
27// errPutDenied is the bucket refusing a Put: past the plan's grace,
28// CARLOS denies PutObject (images §3.4).
29var errPutDenied = errors.New("mapa: the bucket refused the object")
30
31// presignFor is how long a Put's presigned URL lives: only for the Put
32// (Fable N5).
33const presignFor = 60 * time.Second
34
35func (store bucket) Put(ctx context.Context, data io.Reader,
36 kind string) (blobs.Ref, error) {
37 raw, err := heldBytes(data)
38 if err != nil {
39 return blobs.Ref{}, err
40 }
41 sum := sha256.Sum256(raw)
42 ref := blobs.Ref{Hash: hex.EncodeToString(sum[:]),
43 Size: int64(len(raw)), ContentType: kind}
44 address, err := store.PresignPut(ref.Hash, presignFor)
45 if err != nil {
46 return blobs.Ref{}, err
47 }
48 request, err := http.NewRequestWithContext(ctx, http.MethodPut,
49 address, bytes.NewReader(raw))
50 if err != nil {
51 return blobs.Ref{}, err
52 }
53 request.Header.Set("Content-Type", kind)
54 response, err := store.client.Do(request)
55 if err != nil {
56 // *url.Error's text holds the presigned address, signature and
57 // all, and this error is logged: only its cause goes on (Fable
58 // N5).
59 var failed *url.Error
60 if errors.As(err, &failed) {
61 err = failed.Err
62 }
63 return blobs.Ref{}, fmt.Errorf("mapa: putting an image: %w", err)
64 }
65 defer response.Body.Close()
66 _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
67 switch {
68 case response.StatusCode == http.StatusForbidden:
69 return blobs.Ref{}, errPutDenied
70 case response.StatusCode/100 != 2:
71 return blobs.Ref{}, fmt.Errorf("mapa: putting an image: %s",
72 response.Status)
73 }
74 return ref, nil
75}
76
77// heldBytes is data's bytes, without a copy when it holds them already
78// (Fable N7: the sealed image is 10 MiB).
79func heldBytes(data io.Reader) ([]byte, error) {
80 if held, ok := data.(interface{ Bytes() []byte }); ok {
81 return held.Bytes(), nil
82 }
83 return io.ReadAll(data)
84}
85