gunk-dev/the-valley

main.go

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