gunk-dev/the-valley

bus.go

sourcee838215cb25dmain's published tip history
7.2 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 vet and each publish is cut off after busDeadline, so a helper that
9// hangs costs at 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// busDeadline bounds one `nats pub`, and one `cue vet` of a payload. A
132// local server answers in milliseconds and a vet takes well under a second;
133// anything near this long is a helper that is not answering.
134const busDeadline = 10 * time.Second
135
136// publish writes one event. The payload is validated against the event
137// vocabulary before it is sent when a schema is configured: an event no
138// consumer could read is not a thing to publish, and the discipline that
139// keeps the vocabulary one schema'd event at a time is worth nothing if the
140// publisher can sidestep it. A vet that fails or times out skips the
141// publish, and like a failed publish it never affects the landing.
142func (in *integrator) publish(kind string, payload any) {
143 body, err := json.Marshal(payload)
144 if err != nil {
145 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
146 return
147 }
148 if err := in.vetEvent(kind, body); err != nil {
149 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
150 return
151 }
152 fmt.Fprintf(in.out, " event %s %s\n", kind, body)
153 if in.bus == "" {
154 return
155 }
156 subject := fmt.Sprintf("valley.git.%s.%s", in.project, kind)
157 ctx, cancel := context.WithTimeout(context.Background(), busDeadline)
158 defer cancel()
159 cmd := exec.CommandContext(ctx, in.nats, "--server", in.bus, "pub", subject, string(body))
160 // The deadline kills nats itself. WaitDelay stops the wait for its
161 // output too, should anything it started still hold the pipe.
162 cmd.WaitDelay = time.Second
163 if out, err := cmd.CombinedOutput(); err != nil {
164 if ctx.Err() != nil {
165 err = fmt.Errorf("no answer within %s", busDeadline)
166 }
167 fmt.Fprintf(in.out, " bus publish of %s FAILED: %v: %s\n", subject, err, firstLine(string(out)))
168 return
169 }
170 fmt.Fprintf(in.out, " bus %s\n", subject)
171}
172
173// eventDefinition names the schema definition a payload is vetted against.
174var eventDefinition = map[string]string{
175 "integration-succeeded": "#IntegrationSucceeded",
176 "ref-updated": "#RefUpdated",
177 "request-stale": "#RequestStale",
178}
179
180func (in *integrator) vetEvent(kind string, body []byte) error {
181 if in.eventSchema == "" {
182 return nil
183 }
184 def, ok := eventDefinition[kind]
185 if !ok {
186 return fmt.Errorf("%s is not in the event vocabulary", kind)
187 }
188 file, err := writeTemp("valley-integrator-event", body)
189 if err != nil {
190 return err
191 }
192 defer removeTemp(file)
193 ctx, cancel := context.WithTimeout(context.Background(), busDeadline)
194 defer cancel()
195 cmd := exec.CommandContext(ctx, in.cue, "vet", "-d", def, in.eventSchema, file)
196 cmd.WaitDelay = time.Second
197 if out, err := cmd.CombinedOutput(); err != nil {
198 if ctx.Err() != nil {
199 return fmt.Errorf("cue vet against %s gave no answer within %s", def, busDeadline)
200 }
201 return fmt.Errorf("the payload does not satisfy %s: %s", def, firstLine(string(out)))
202 }
203 return nil
204}