gunk-dev/the-valley

bus.go

source813c6679e1c2main's published tip history
5.4 KiB
1package main
2
3// Publishing outcomes. The mechanism is the post-receive hook's, exactly:
4// one `nats pub` per event, on valley.git.<repo>.<event>, with a payload
5// satisfying schema/events.cue. Failure to publish is logged and never
6// fatal — git is the source of truth and the bus is the replaceable
7// component, so a bus problem costs a log line and one `valley replay`.
8//
9// Nothing here consumes. Bus authentication (bd-d853d9c) gates automated
10// consumers, and the integrator level-triggers over the request refs
11// instead, so it needs no subscription.
12
13import (
14 "the-valley/integrator/verdict"
15
16 "encoding/json"
17 "fmt"
18 "os"
19 "os/exec"
20 "path/filepath"
21 "time"
22)
23
24func (in *integrator) publishLanded(ch verdict.Change, v verdict.Verdict, old, new string) {
25 transferred := []string{}
26 for _, cv := range v.Checks {
27 if cv.Transferred {
28 transferred = append(transferred, cv.Name)
29 }
30 }
31 in.publish("integration-succeeded", map[string]any{
32 "event": "integration-succeeded",
33 "repo": in.project,
34 "change": ch.ID,
35 "target": ch.Target,
36 "old": old,
37 "new": new,
38 "transferred": transferred,
39 })
40}
41
42func (in *integrator) publishStale(ch verdict.Change, v verdict.Verdict, tip string) {
43 checks := v.Invalidated
44 if checks == nil {
45 checks = []string{}
46 }
47 in.publish("request-stale", map[string]any{
48 "event": "request-stale",
49 "repo": in.project,
50 "change": ch.ID,
51 "target": ch.Target,
52 "tip": tip,
53 "reason": v.StaleReason,
54 "checks": checks,
55 })
56}
57
58// queueRefUpdate hands one ref move to the host, which publishes it the way
59// it publishes a push: to the project's push mirrors, and as a ref-updated
60// event. A push reaches both through the post-receive hook. The integrator
61// moves refs with update-ref, which runs no hook, so its landings reach
62// neither unless it says what it moved.
63//
64// The integrator does not publish the move itself. The mirror credentials
65// belong to the git user, and this process runs as its own user. A unit
66// running as the git user watches the queue and drains it with the same
67// pusher and publisher post-receive runs (nix/valley-host.nix).
68//
69// One file per move, holding the line post-receive reads: old, new, ref.
70// The file is written beside the queue and renamed into it, so the drain
71// never reads a partial one, and names sort in the order the moves were
72// made. Like the bus, this is best-effort: a move that cannot be queued is
73// reported and the landing stands, because git is the source of truth.
74func (in *integrator) queueRefUpdate(ref, old, new string) {
75 if in.publishQueue == "" {
76 return
77 }
78 if err := writeRefUpdate(in.publishQueue, ref, old, new); err != nil {
79 fmt.Fprintf(in.out, " publish %s not queued: %v\n", ref, err)
80 return
81 }
82 fmt.Fprintf(in.out, " publish %s queued\n", ref)
83}
84
85func writeRefUpdate(queue, ref, old, new string) error {
86 if info, err := os.Stat(queue); err != nil || !info.IsDir() {
87 return fmt.Errorf("%s is not a directory the host drains", queue)
88 }
89 tmp, err := os.CreateTemp(filepath.Dir(queue), ".valley-publish-*")
90 if err != nil {
91 return err
92 }
93 defer os.Remove(tmp.Name())
94 // The drain runs as the git user, which reads the file through the
95 // group, and CreateTemp makes it readable by its owner alone.
96 if err := tmp.Chmod(0o640); err != nil {
97 tmp.Close()
98 return err
99 }
100 if _, err := fmt.Fprintf(tmp, "%s %s %s\n", old, new, ref); err != nil {
101 tmp.Close()
102 return err
103 }
104 if err := tmp.Close(); err != nil {
105 return err
106 }
107 name := fmt.Sprintf("%020d-%s", time.Now().UnixNano(), new)
108 return os.Rename(tmp.Name(), filepath.Join(queue, name))
109}
110
111// publish writes one event. The payload is validated against the event
112// vocabulary before it is sent when a schema is configured: an event no
113// consumer could read is not a thing to publish, and the discipline that
114// keeps the vocabulary one schema'd event at a time is worth nothing if the
115// publisher can sidestep it.
116func (in *integrator) publish(kind string, payload map[string]any) {
117 body, err := json.Marshal(payload)
118 if err != nil {
119 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
120 return
121 }
122 if err := in.vetEvent(kind, body); err != nil {
123 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
124 return
125 }
126 fmt.Fprintf(in.out, " event %s %s\n", kind, body)
127 if in.bus == "" {
128 return
129 }
130 subject := fmt.Sprintf("valley.git.%s.%s", in.project, kind)
131 cmd := exec.Command(in.nats, "--server", in.bus, "pub", subject, string(body))
132 if out, err := cmd.CombinedOutput(); err != nil {
133 fmt.Fprintf(in.out, " bus publish of %s FAILED: %v: %s\n", subject, err, firstLine(string(out)))
134 return
135 }
136 fmt.Fprintf(in.out, " bus %s\n", subject)
137}
138
139// eventDefinition names the schema definition a payload is vetted against.
140var eventDefinition = map[string]string{
141 "integration-succeeded": "#IntegrationSucceeded",
142 "request-stale": "#RequestStale",
143}
144
145func (in *integrator) vetEvent(kind string, body []byte) error {
146 if in.eventSchema == "" {
147 return nil
148 }
149 def, ok := eventDefinition[kind]
150 if !ok {
151 return fmt.Errorf("%s is not in the event vocabulary", kind)
152 }
153 file, err := writeTemp("valley-integrator-event", body)
154 if err != nil {
155 return err
156 }
157 defer removeTemp(file)
158 cmd := exec.Command(in.cue, "vet", "-d", def, in.eventSchema, file)
159 if out, err := cmd.CombinedOutput(); err != nil {
160 return fmt.Errorf("the payload does not satisfy %s: %s", def, firstLine(string(out)))
161 }
162 return nil
163}