gunk-dev/the-valley

main.go

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