gunk-dev/the-valley

main.go

source215012f1aaa7main's published tip history
11.4 KiB
1// valley-web-publish publishes a valley host's public projects to a web
2// receiver. One run is one pass. It reads the valley through the CLI's JSON
3// commands, projects what it read onto the public export (package export),
4// signs a manifest for it, and uploads it by the protocol package export
5// defines. The receiver never connects to the host; its replies are all the
6// publisher hears from it.
7//
8// A pass, in order:
9//
10// 1. take the lock in the state directory, so two passes never overlap;
11// 2. read the export key from the state directory, or make one on the
12// first start, and say its verifier line whenever it changes;
13// 3. fetch main and refs/the-valley/projects of the instance repository
14// into the publisher's own bare repository, whose origin it is, refuse
15// a main that carries policy/valley, and read the instance's
16// policy/web;
17// 4. run valley plan --all --json and valley pending --all --json in that
18// repository, which discover the projects and the signers through the
19// instance repository's own publications, and hold both listings to
20// the project list it fetched;
21// 5. for each project the instance allows, fetch main into a mirror under
22// the cache and read the project's own policy/web there;
23// 6. run valley knot show --project P <id> --json for every knot of every
24// public project, fetch the instance repository again, and build the
25// export with export.Build, reading again when the inputs were read at
26// different graph tips or the instance repository moved;
27// 7. bundle each public project's main, and hold the bundles to
28// --max-bundles and the state and cache to --max-storage;
29// 8. upload it, unless the receiver acknowledged the same content digest
30// less than --recheck ago, or write it to --out instead.
31//
32// A project is public only when the instance's policy/web and its own both
33// say public (schema/web.cue). A declaration that is missing, or that the
34// schema refuses, means private. A project the instance allows that
35// cannot be read fails the pass, which then sends nothing: an export
36// without it would take it off the web.
37package main
38
39import (
40 "context"
41 "crypto/ed25519"
42 "errors"
43 "flag"
44 "fmt"
45 "io"
46 "math"
47 "net/http"
48 "os"
49 "path/filepath"
50 "strconv"
51 "strings"
52 "time"
53
54 "the-valley/webui/export"
55)
56
57const usage = `usage: valley-web-publish --instance-repo URL --instance NAME --destination NAME
58 (--receiver URL | --out DIR) [--principals FILE]
59 [--state DIR] [--schema FILE] [--recheck DURATION]
60 [--max-bundles SIZE] [--max-storage SIZE]
61
62One pass of the web publisher: read the valley's public projects, and
63upload them to the receiver at URL, or write them to DIR.
64
65 --instance-repo URL the instance repository: the origin of the
66 publisher's own bare repository, which the valley
67 CLI discovers projects and signers through; its
68 main holds policy/instance and no policy/valley
69 --instance NAME the instance the manifest names, and the export
70 key's signing name, NAME/web-export
71 --destination NAME the receiver the manifest is for
72 --receiver URL the receiver's base URL, http or https
73 --out DIR write the export to DIR, which must not exist or be
74 empty, instead of uploading it: manifest, export.json
75 and bundles/<project>.bundle
76 --principals FILE the display mapping: a JSON object from each
77 principal's name to the name an export shows; a
78 name it does not map is shown as contributor
79 --state DIR the key, its verifier line, the lock and the last
80 acknowledgement (default
81 ${XDG_STATE_HOME:-$HOME/.local/state}/valley/web-publish)
82 --schema FILE schema/web.cue (default $VALLEY_WEB_SCHEMA)
83 --recheck DURATION how long an acknowledgement is trusted: a pass whose
84 digest the receiver acknowledged less than this ago
85 sends nothing (default 1h)
86 --max-bundles SIZE the most the bundles of one export may hold
87 together; a pass past it sends nothing (default 1G)
88 --max-storage SIZE the most the state directory and the cache may hold
89 once the bundles are made; a pass past it sends
90 nothing (default 16G)
91
92A SIZE is a number of bytes, or a number with K, M, G or T for KiB, MiB,
93GiB or TiB.
94
95The cache is $XDG_CACHE_HOME (default $HOME/.cache): the valley CLI's
96clones under valley/, the publisher's repository and mirrors under
97valley-web-publish/.`
98
99func main() {
100 os.Exit(run(context.Background(), os.Args[1:], os.Stdout, os.Stderr))
101}
102
103func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
104 cfg, err := parseArgs(args)
105 if errors.Is(err, flag.ErrHelp) {
106 fmt.Fprintln(stdout, usage)
107 return 0
108 }
109 if err != nil {
110 fmt.Fprintf(stderr, "valley-web-publish: %v\n%s\n", err, usage)
111 return 2
112 }
113 p, err := newPublisher(cfg, stdout, stderr)
114 if err == nil {
115 err = p.pass(ctx)
116 }
117 if err != nil {
118 fmt.Fprintf(stderr, "valley-web-publish: %v\n", err)
119 return 1
120 }
121 return 0
122}
123
124// config is a pass's flags.
125type config struct {
126 instanceRepo string
127 instance string
128 destination string
129 receiver string
130 out string
131 principals string
132 state string
133 schema string
134 recheck time.Duration
135 maxBundles byteSize
136 maxStorage byteSize
137}
138
139func parseArgs(args []string) (config, error) {
140 c := config{maxBundles: 1 << 30, maxStorage: 16 << 30}
141 fs := flag.NewFlagSet("valley-web-publish", flag.ContinueOnError)
142 fs.SetOutput(io.Discard)
143 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
144 fs.StringVar(&c.instance, "instance", "", "")
145 fs.StringVar(&c.destination, "destination", "", "")
146 fs.StringVar(&c.receiver, "receiver", "", "")
147 fs.StringVar(&c.out, "out", "", "")
148 fs.StringVar(&c.principals, "principals", "", "")
149 fs.StringVar(&c.state, "state", "", "")
150 fs.StringVar(&c.schema, "schema", os.Getenv("VALLEY_WEB_SCHEMA"), "")
151 fs.DurationVar(&c.recheck, "recheck", time.Hour, "")
152 fs.Var(&c.maxBundles, "max-bundles", "")
153 fs.Var(&c.maxStorage, "max-storage", "")
154 if err := fs.Parse(args); err != nil {
155 return c, err
156 }
157 switch {
158 case fs.NArg() > 0:
159 return c, fmt.Errorf("unexpected argument %q", fs.Arg(0))
160 case c.instanceRepo == "":
161 return c, errors.New("--instance-repo is required")
162 case !export.ValidName(c.instance):
163 return c, fmt.Errorf("--instance %q is not a name: it is 1 to 64 letters, digits, dots, dashes and underscores, opening with a letter or a digit", c.instance)
164 case !export.ValidName(c.destination):
165 return c, fmt.Errorf("--destination %q is not a name: it is 1 to 64 letters, digits, dots, dashes and underscores, opening with a letter or a digit", c.destination)
166 case (c.receiver == "") == (c.out == ""):
167 return c, errors.New("give exactly one of --receiver and --out")
168 case c.schema == "":
169 return c, errors.New("no schema: give --schema, or set VALLEY_WEB_SCHEMA")
170 case c.recheck < 0:
171 return c, errors.New("--recheck is not negative")
172 }
173 if c.receiver != "" {
174 if err := checkReceiver(c.receiver); err != nil {
175 return c, err
176 }
177 }
178 if c.state == "" {
179 base := os.Getenv("XDG_STATE_HOME")
180 if base == "" {
181 home, err := os.UserHomeDir()
182 if err != nil {
183 return c, errors.New("no state directory: give --state, or set XDG_STATE_HOME or HOME")
184 }
185 base = filepath.Join(home, ".local", "state")
186 }
187 c.state = filepath.Join(base, "valley", "web-publish")
188 }
189 return c, nil
190}
191
192// byteSize is a size flag's value in bytes. It is set from a number, or a
193// number with K, M, G or T for 1024 to the first to fourth power, as
194// systemd reads a size.
195type byteSize int64
196
197func (b *byteSize) Set(v string) error {
198 number, unit := v, int64(1)
199 if n := len(v); n > 1 {
200 if i := strings.IndexByte("KMGT", v[n-1]); i >= 0 {
201 number, unit = v[:n-1], 1<<(10*(i+1))
202 }
203 }
204 x, err := strconv.ParseInt(number, 10, 64)
205 if err != nil || x <= 0 || x > math.MaxInt64/unit {
206 return fmt.Errorf("%q is not a size: a positive number of bytes, or one with K, M, G or T", v)
207 }
208 *b = byteSize(x * unit)
209 return nil
210}
211
212func (b *byteSize) String() string { return strconv.FormatInt(int64(*b), 10) }
213
214// publisher is one pass's configuration and what it reads and writes
215// through: its state and cache directories, its key, the receiver, and
216// the clock.
217type publisher struct {
218 cfg config
219 stdout, stderr io.Writer
220
221 // cache is the publisher's own cache, under $XDG_CACHE_HOME. origin is
222 // its bare repository, whose origin is the instance repository.
223 cache string
224 origin string
225
226 principals export.Principals
227 signer string
228 key ed25519.PrivateKey
229
230 client *http.Client
231 now func() time.Time
232 sleep func(context.Context, time.Duration) error
233}
234
235func newPublisher(cfg config, stdout, stderr io.Writer) (*publisher, error) {
236 base := os.Getenv("XDG_CACHE_HOME")
237 if base == "" {
238 home, err := os.UserHomeDir()
239 if err != nil {
240 return nil, errors.New("no cache directory: set XDG_CACHE_HOME or HOME")
241 }
242 base = filepath.Join(home, ".cache")
243 }
244 if !filepath.IsAbs(base) {
245 return nil, fmt.Errorf("XDG_CACHE_HOME is %q, which is not an absolute path", base)
246 }
247 principals, err := readPrincipals(cfg.principals)
248 if err != nil {
249 return nil, err
250 }
251 cache := filepath.Join(base, "valley-web-publish")
252 return &publisher{
253 cfg: cfg, stdout: stdout, stderr: stderr,
254 cache: cache, origin: filepath.Join(cache, "origin.git"),
255 principals: principals,
256 signer: cfg.instance + "/web-export",
257 client: newClient(),
258 now: time.Now,
259 sleep: sleepContext,
260 }, nil
261}
262
263// pass is one run of the publisher.
264func (p *publisher) pass(ctx context.Context) error {
265 if err := os.MkdirAll(p.cfg.state, 0o700); err != nil {
266 return err
267 }
268 unlock, err := lockFile(filepath.Join(p.cfg.state, "lock"))
269 if err != nil {
270 return err
271 }
272 defer unlock()
273 if p.key, err = p.loadKey(); err != nil {
274 return err
275 }
276 read, err := p.collect(ctx)
277 if err != nil {
278 return err
279 }
280 digest, err := read.export.Digest()
281 if err != nil {
282 return err
283 }
284 p.sayVisibility(read)
285 if p.cfg.out != "" {
286 return p.writeOut(ctx, read)
287 }
288 ack, err := p.readAcknowledged()
289 if err != nil {
290 return err
291 }
292 if ack.covers(p.cfg, digest, p.now(), p.cfg.recheck) {
293 p.say("the receiver acknowledged digest %s at %s, and nothing has changed since; nothing is sent", short(digest), ack.At)
294 return nil
295 }
296 return p.upload(ctx, read, digest, ack)
297}
298
299// sayVisibility says which projects this pass exports, and which it keeps
300// private.
301func (p *publisher) sayVisibility(r *reading) {
302 var public []string
303 for _, proj := range r.export.Projects {
304 public = append(public, proj.Name)
305 }
306 p.say("public: %s; private: %s", listNames(public), listNames(r.private))
307}
308
309func (p *publisher) say(format string, args ...any) {
310 fmt.Fprintf(p.stdout, "valley-web-publish: "+format+"\n", args...)
311}
312
313func (p *publisher) warn(format string, args ...any) {
314 fmt.Fprintf(p.stderr, "valley-web-publish: "+format+"\n", args...)
315}
316
317// short is the first twelve characters of a digest or an object ID, for
318// messages.
319func short(s string) string {
320 if len(s) > 12 {
321 return s[:12]
322 }
323 return s
324}
325
326func sleepContext(ctx context.Context, d time.Duration) error {
327 t := time.NewTimer(d)
328 defer t.Stop()
329 select {
330 case <-ctx.Done():
331 return ctx.Err()
332 case <-t.C:
333 return nil
334 }
335}