gunk-dev/the-valley

bus.go

source2623f99ec0a3main's published tip history
6.1 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// publishRefUpdated publishes the ref-updated event for a landing's move.
59// A push gets the event from the post-receive hook. The integrator moves
60// refs with update-ref, which runs no hook, so it publishes the event
61// itself, at once, and never behind a mirror push. The fields are the host
62// publisher's, in its order (nix/valley-host.nix, and `valley replay` in
63// bin/valley); change one only with the others.
64func (in *integrator) publishRefUpdated(ref, old, new string) {
65 in.publish("ref-updated", struct {
66 Event string `json:"event"`
67 Repo string `json:"repo"`
68 Ref string `json:"ref"`
69 Old string `json:"old"`
70 New string `json:"new"`
71 }{"ref-updated", in.project, ref, old, new})
72}
73
74// queueRefUpdate hands one ref move to the host, which pushes it to the
75// project's mirrors the way it pushes a push's moves. A push queues its
76// moves from the post-receive hook. The integrator moves refs with
77// update-ref, which runs no hook, so its landings reach the mirrors only if
78// it says what it moved.
79//
80// The integrator does not push the mirrors itself. The mirror credentials
81// belong to the git user, and this process runs as its own user. A unit
82// running as the git user watches the queue and drains it, and it is the
83// only thing that pushes the mirrors (nix/valley-host.nix).
84//
85// One file per move, holding the line post-receive reads: old, new, ref.
86// The file is written beside the queue and renamed into it, so the drain
87// never reads a partial one, and names sort in the order the moves were
88// made. Like the bus, this is best-effort: a move that cannot be queued is
89// reported and the landing stands, because git is the source of truth.
90func (in *integrator) queueRefUpdate(ref, old, new string) {
91 if in.publishQueue == "" {
92 return
93 }
94 if err := writeRefUpdate(in.publishQueue, ref, old, new); err != nil {
95 fmt.Fprintf(in.out, " publish %s not queued: %v\n", ref, err)
96 return
97 }
98 fmt.Fprintf(in.out, " publish %s queued\n", ref)
99}
100
101func writeRefUpdate(queue, ref, old, new string) error {
102 if info, err := os.Stat(queue); err != nil || !info.IsDir() {
103 return fmt.Errorf("%s is not a directory the host drains", queue)
104 }
105 tmp, err := os.CreateTemp(filepath.Dir(queue), ".valley-publish-*")
106 if err != nil {
107 return err
108 }
109 defer os.Remove(tmp.Name())
110 // The drain runs as the git user, which reads the file through the
111 // group, and CreateTemp makes it readable by its owner alone.
112 if err := tmp.Chmod(0o640); err != nil {
113 tmp.Close()
114 return err
115 }
116 if _, err := fmt.Fprintf(tmp, "%s %s %s\n", old, new, ref); err != nil {
117 tmp.Close()
118 return err
119 }
120 if err := tmp.Close(); err != nil {
121 return err
122 }
123 name := fmt.Sprintf("%020d-%s", time.Now().UnixNano(), new)
124 return os.Rename(tmp.Name(), filepath.Join(queue, name))
125}
126
127// publish writes one event. The payload is validated against the event
128// vocabulary before it is sent when a schema is configured: an event no
129// consumer could read is not a thing to publish, and the discipline that
130// keeps the vocabulary one schema'd event at a time is worth nothing if the
131// publisher can sidestep it.
132func (in *integrator) publish(kind string, payload any) {
133 body, err := json.Marshal(payload)
134 if err != nil {
135 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
136 return
137 }
138 if err := in.vetEvent(kind, body); err != nil {
139 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
140 return
141 }
142 fmt.Fprintf(in.out, " event %s %s\n", kind, body)
143 if in.bus == "" {
144 return
145 }
146 subject := fmt.Sprintf("valley.git.%s.%s", in.project, kind)
147 cmd := exec.Command(in.nats, "--server", in.bus, "pub", subject, string(body))
148 if out, err := cmd.CombinedOutput(); err != nil {
149 fmt.Fprintf(in.out, " bus publish of %s FAILED: %v: %s\n", subject, err, firstLine(string(out)))
150 return
151 }
152 fmt.Fprintf(in.out, " bus %s\n", subject)
153}
154
155// eventDefinition names the schema definition a payload is vetted against.
156var eventDefinition = map[string]string{
157 "integration-succeeded": "#IntegrationSucceeded",
158 "ref-updated": "#RefUpdated",
159 "request-stale": "#RequestStale",
160}
161
162func (in *integrator) vetEvent(kind string, body []byte) error {
163 if in.eventSchema == "" {
164 return nil
165 }
166 def, ok := eventDefinition[kind]
167 if !ok {
168 return fmt.Errorf("%s is not in the event vocabulary", kind)
169 }
170 file, err := writeTemp("valley-integrator-event", body)
171 if err != nil {
172 return err
173 }
174 defer removeTemp(file)
175 cmd := exec.Command(in.cue, "vet", "-d", def, in.eventSchema, file)
176 if out, err := cmd.CombinedOutput(); err != nil {
177 return fmt.Errorf("the payload does not satisfy %s: %s", def, firstLine(string(out)))
178 }
179 return nil
180}