gunk-dev/the-valley

main.go

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