gunk-dev/the-valley

bus.go

sourcea74bc0625cc1main's published tip history
6.8 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// Each publish is cut off after busDeadline, so a bus that hangs costs at
9// most that long, and a landing publishes only after its own record is
10// complete (refs.go).
11//
12// Nothing here consumes. Bus authentication (bd-d853d9c) gates automated
13// consumers, and the integrator level-triggers over the request refs
14// instead, so it needs no subscription.
15
16import (
17 "the-valley/integrator/verdict"
18
19 "context"
20 "encoding/json"
21 "fmt"
22 "os"
23 "os/exec"
24 "path/filepath"
25 "time"
26)
27
28func (in *integrator) publishLanded(ch verdict.Change, v verdict.Verdict, old, new string) {
29 transferred := []string{}
30 for _, cv := range v.Checks {
31 if cv.Transferred {
32 transferred = append(transferred, cv.Name)
33 }
34 }
35 in.publish("integration-succeeded", map[string]any{
36 "event": "integration-succeeded",
37 "repo": in.project,
38 "change": ch.ID,
39 "target": ch.Target,
40 "old": old,
41 "new": new,
42 "transferred": transferred,
43 })
44}
45
46func (in *integrator) publishStale(ch verdict.Change, v verdict.Verdict, tip string) {
47 checks := v.Invalidated
48 if checks == nil {
49 checks = []string{}
50 }
51 in.publish("request-stale", map[string]any{
52 "event": "request-stale",
53 "repo": in.project,
54 "change": ch.ID,
55 "target": ch.Target,
56 "tip": tip,
57 "reason": v.StaleReason,
58 "checks": checks,
59 })
60}
61
62// publishRefUpdated publishes the ref-updated event for a landing's move.
63// A push gets the event from the post-receive hook. The integrator moves
64// refs with update-ref, which runs no hook, so it publishes the event
65// itself, once the landing is recorded, and never behind a mirror push.
66// The fields are the host publisher's, in its order (nix/valley-host.nix,
67// and `valley replay` in bin/valley); change one only with the others.
68func (in *integrator) publishRefUpdated(ref, old, new string) {
69 in.publish("ref-updated", struct {
70 Event string `json:"event"`
71 Repo string `json:"repo"`
72 Ref string `json:"ref"`
73 Old string `json:"old"`
74 New string `json:"new"`
75 }{"ref-updated", in.project, ref, old, new})
76}
77
78// queueRefUpdate hands one ref move to the host, which pushes it to the
79// project's mirrors the way it pushes a push's moves. A push queues its
80// moves from the post-receive hook. The integrator moves refs with
81// update-ref, which runs no hook, so its landings reach the mirrors only if
82// it says what it moved.
83//
84// The integrator does not push the mirrors itself. The mirror credentials
85// belong to the git user, and this process runs as its own user. A unit
86// running as the git user watches the queue and drains it, and it is the
87// only thing that pushes the mirrors (nix/valley-host.nix).
88//
89// One file per move, holding the line post-receive reads: old, new, ref.
90// The file is written beside the queue and renamed into it, so the drain
91// never reads a partial one, and names sort in the order the moves were
92// made. Like the bus, this is best-effort: a move that cannot be queued is
93// reported and the landing stands, because git is the source of truth.
94func (in *integrator) queueRefUpdate(ref, old, new string) {
95 if in.publishQueue == "" {
96 return
97 }
98 if err := writeRefUpdate(in.publishQueue, ref, old, new); err != nil {
99 fmt.Fprintf(in.out, " publish %s not queued: %v\n", ref, err)
100 return
101 }
102 fmt.Fprintf(in.out, " publish %s queued\n", ref)
103}
104
105func writeRefUpdate(queue, ref, old, new string) error {
106 if info, err := os.Stat(queue); err != nil || !info.IsDir() {
107 return fmt.Errorf("%s is not a directory the host drains", queue)
108 }
109 tmp, err := os.CreateTemp(filepath.Dir(queue), ".valley-publish-*")
110 if err != nil {
111 return err
112 }
113 defer os.Remove(tmp.Name())
114 // The drain runs as the git user, which reads the file through the
115 // group, and CreateTemp makes it readable by its owner alone.
116 if err := tmp.Chmod(0o640); err != nil {
117 tmp.Close()
118 return err
119 }
120 if _, err := fmt.Fprintf(tmp, "%s %s %s\n", old, new, ref); err != nil {
121 tmp.Close()
122 return err
123 }
124 if err := tmp.Close(); err != nil {
125 return err
126 }
127 name := fmt.Sprintf("%020d-%s", time.Now().UnixNano(), new)
128 return os.Rename(tmp.Name(), filepath.Join(queue, name))
129}
130
131// publish writes one event. The payload is validated against the event
132// vocabulary before it is sent when a schema is configured: an event no
133// consumer could read is not a thing to publish, and the discipline that
134// keeps the vocabulary one schema'd event at a time is worth nothing if the
135// publisher can sidestep it.
136// busDeadline bounds one `nats pub`. A local server answers in
137// milliseconds; anything near this long is a bus that is not answering.
138const busDeadline = 10 * time.Second
139
140func (in *integrator) publish(kind string, payload any) {
141 body, err := json.Marshal(payload)
142 if err != nil {
143 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
144 return
145 }
146 if err := in.vetEvent(kind, body); err != nil {
147 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
148 return
149 }
150 fmt.Fprintf(in.out, " event %s %s\n", kind, body)
151 if in.bus == "" {
152 return
153 }
154 subject := fmt.Sprintf("valley.git.%s.%s", in.project, kind)
155 ctx, cancel := context.WithTimeout(context.Background(), busDeadline)
156 defer cancel()
157 cmd := exec.CommandContext(ctx, in.nats, "--server", in.bus, "pub", subject, string(body))
158 // The deadline kills nats itself. WaitDelay stops the wait for its
159 // output too, should anything it started still hold the pipe.
160 cmd.WaitDelay = time.Second
161 if out, err := cmd.CombinedOutput(); err != nil {
162 if ctx.Err() != nil {
163 err = fmt.Errorf("no answer within %s", busDeadline)
164 }
165 fmt.Fprintf(in.out, " bus publish of %s FAILED: %v: %s\n", subject, err, firstLine(string(out)))
166 return
167 }
168 fmt.Fprintf(in.out, " bus %s\n", subject)
169}
170
171// eventDefinition names the schema definition a payload is vetted against.
172var eventDefinition = map[string]string{
173 "integration-succeeded": "#IntegrationSucceeded",
174 "ref-updated": "#RefUpdated",
175 "request-stale": "#RequestStale",
176}
177
178func (in *integrator) vetEvent(kind string, body []byte) error {
179 if in.eventSchema == "" {
180 return nil
181 }
182 def, ok := eventDefinition[kind]
183 if !ok {
184 return fmt.Errorf("%s is not in the event vocabulary", kind)
185 }
186 file, err := writeTemp("valley-integrator-event", body)
187 if err != nil {
188 return err
189 }
190 defer removeTemp(file)
191 cmd := exec.Command(in.cue, "vet", "-d", def, in.eventSchema, file)
192 if out, err := cmd.CombinedOutput(); err != nil {
193 return fmt.Errorf("the payload does not satisfy %s: %s", def, firstLine(string(out)))
194 }
195 return nil
196}