gunk-dev/the-valley

bus.go

source34d12a6791c4main's published tip history
8.5 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 "errors"
22 "fmt"
23 "io/fs"
24 "os"
25 "os/exec"
26 "path/filepath"
27 "time"
28)
29
30func (in *integrator) publishLanded(ch verdict.Change, v verdict.Verdict, old, new string) {
31 transferred := []string{}
32 for _, cv := range v.Checks {
33 if cv.Transferred {
34 transferred = append(transferred, cv.Name)
35 }
36 }
37 in.publish("integration-succeeded", map[string]any{
38 "event": "integration-succeeded",
39 "repo": in.project,
40 "change": ch.ID,
41 "target": ch.Target,
42 "old": old,
43 "new": new,
44 "transferred": transferred,
45 })
46}
47
48func (in *integrator) publishStale(ch verdict.Change, v verdict.Verdict, tip string) {
49 checks := v.Invalidated
50 if checks == nil {
51 checks = []string{}
52 }
53 in.publish("request-stale", map[string]any{
54 "event": "request-stale",
55 "repo": in.project,
56 "change": ch.ID,
57 "target": ch.Target,
58 "tip": tip,
59 "reason": v.StaleReason,
60 "checks": checks,
61 })
62}
63
64// publishRefUpdated publishes the ref-updated event for a landing's move.
65// A push gets the event from the post-receive hook. The integrator moves
66// refs with update-ref, which runs no hook, so it publishes the event
67// itself, once the landing is recorded, and never behind a mirror push.
68// The fields are the host publisher's, in its order (nix/valley-host.nix,
69// and `valley replay` in bin/valley); change one only with the others.
70func (in *integrator) publishRefUpdated(ref, old, new string) {
71 in.publish("ref-updated", struct {
72 Event string `json:"event"`
73 Repo string `json:"repo"`
74 Ref string `json:"ref"`
75 Old string `json:"old"`
76 New string `json:"new"`
77 }{"ref-updated", in.project, ref, old, new})
78}
79
80// markDue tells the host's check worker that a landing moved a ref it
81// reads, so it starts a pass without waiting for its timer. The landing
82// does not wait for anything the worker does, and a mark that fails is
83// reported and the landing stands: the worker's recovery scan reads the
84// same refs later (status/worker.go).
85func (in *integrator) markDue() {
86 if in.wake == "" {
87 return
88 }
89 if err := markDue(in.wake); err != nil {
90 fmt.Fprintf(in.out, " wake the check worker was not marked due: %v\n", err)
91 return
92 }
93 fmt.Fprintf(in.out, " wake the check worker is due\n")
94}
95
96// markDue creates the empty file due in the wake directory dir, which
97// the host made. One mark stands for any number of moves: a file that
98// is already there is a mark already made, so it is success, and the
99// directory never holds more than the one file from every writer. The
100// file carries nothing and nothing reads it; the worker renames it when
101// it starts a pass (status/wake.go). An empty dir marks nothing.
102func markDue(dir string) error {
103 if dir == "" {
104 return nil
105 }
106 f, err := os.OpenFile(filepath.Join(dir, "due"), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o440)
107 if errors.Is(err, fs.ErrExist) {
108 return nil
109 }
110 if err != nil {
111 return err
112 }
113 return f.Close()
114}
115
116// queueRefUpdate hands one ref move to the host, which pushes it to the
117// project's mirrors the way it pushes a push's moves. A push queues its
118// moves from the post-receive hook. The integrator moves refs with
119// update-ref, which runs no hook, so its landings reach the mirrors only if
120// it says what it moved.
121//
122// The integrator does not push the mirrors itself. The mirror credentials
123// belong to the git user, and this process runs as its own user. A unit
124// running as the git user watches the queue and drains it, and it is the
125// only thing that pushes the mirrors (nix/valley-host.nix).
126//
127// One file per move, holding the line post-receive reads: old, new, ref.
128// The file is written beside the queue and renamed into it, so the drain
129// never reads a partial one, and names sort in the order the moves were
130// made. Like the bus, this is best-effort: a move that cannot be queued is
131// reported and the landing stands, because git is the source of truth.
132func (in *integrator) queueRefUpdate(ref, old, new string) {
133 if in.publishQueue == "" {
134 return
135 }
136 if err := writeRefUpdate(in.publishQueue, ref, old, new); err != nil {
137 fmt.Fprintf(in.out, " publish %s not queued: %v\n", ref, err)
138 return
139 }
140 fmt.Fprintf(in.out, " publish %s queued\n", ref)
141}
142
143func writeRefUpdate(queue, ref, old, new string) error {
144 if info, err := os.Stat(queue); err != nil || !info.IsDir() {
145 return fmt.Errorf("%s is not a directory the host drains", queue)
146 }
147 tmp, err := os.CreateTemp(filepath.Dir(queue), ".valley-publish-*")
148 if err != nil {
149 return err
150 }
151 defer os.Remove(tmp.Name())
152 // The drain runs as the git user, which reads the file through the
153 // group, and CreateTemp makes it readable by its owner alone.
154 if err := tmp.Chmod(0o640); err != nil {
155 tmp.Close()
156 return err
157 }
158 if _, err := fmt.Fprintf(tmp, "%s %s %s\n", old, new, ref); err != nil {
159 tmp.Close()
160 return err
161 }
162 if err := tmp.Close(); err != nil {
163 return err
164 }
165 name := fmt.Sprintf("%020d-%s", time.Now().UnixNano(), new)
166 return os.Rename(tmp.Name(), filepath.Join(queue, name))
167}
168
169// busDeadline bounds one `nats pub`, and one `cue vet` of a payload. A
170// local server answers in milliseconds and a vet takes well under a second;
171// anything near this long is a helper that is not answering.
172const busDeadline = 10 * time.Second
173
174// publish writes one event. The payload is validated against the event
175// vocabulary before it is sent when a schema is configured: an event no
176// consumer could read is not a thing to publish, and the discipline that
177// keeps the vocabulary one schema'd event at a time is worth nothing if the
178// publisher can sidestep it. A vet that fails or times out skips the
179// publish, and like a failed publish it never affects the landing.
180func (in *integrator) publish(kind string, payload any) {
181 body, err := json.Marshal(payload)
182 if err != nil {
183 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
184 return
185 }
186 if err := in.vetEvent(kind, body); err != nil {
187 fmt.Fprintf(in.out, " bus %s not published: %v\n", kind, err)
188 return
189 }
190 fmt.Fprintf(in.out, " event %s %s\n", kind, body)
191 if in.bus == "" {
192 return
193 }
194 subject := fmt.Sprintf("valley.git.%s.%s", in.project, kind)
195 ctx, cancel := context.WithTimeout(context.Background(), busDeadline)
196 defer cancel()
197 cmd := exec.CommandContext(ctx, in.nats, "--server", in.bus, "pub", subject, string(body))
198 // The deadline kills nats itself. WaitDelay stops the wait for its
199 // output too, should anything it started still hold the pipe.
200 cmd.WaitDelay = time.Second
201 if out, err := cmd.CombinedOutput(); err != nil {
202 if ctx.Err() != nil {
203 err = fmt.Errorf("no answer within %s", busDeadline)
204 }
205 fmt.Fprintf(in.out, " bus publish of %s FAILED: %v: %s\n", subject, err, firstLine(string(out)))
206 return
207 }
208 fmt.Fprintf(in.out, " bus %s\n", subject)
209}
210
211// eventDefinition names the schema definition a payload is vetted against.
212var eventDefinition = map[string]string{
213 "integration-succeeded": "#IntegrationSucceeded",
214 "ref-updated": "#RefUpdated",
215 "request-stale": "#RequestStale",
216}
217
218func (in *integrator) vetEvent(kind string, body []byte) error {
219 if in.eventSchema == "" {
220 return nil
221 }
222 def, ok := eventDefinition[kind]
223 if !ok {
224 return fmt.Errorf("%s is not in the event vocabulary", kind)
225 }
226 file, err := writeTemp("valley-integrator-event", body)
227 if err != nil {
228 return err
229 }
230 defer removeTemp(file)
231 ctx, cancel := context.WithTimeout(context.Background(), busDeadline)
232 defer cancel()
233 cmd := exec.CommandContext(ctx, in.cue, "vet", "-d", def, in.eventSchema, file)
234 cmd.WaitDelay = time.Second
235 if out, err := cmd.CombinedOutput(); err != nil {
236 if ctx.Err() != nil {
237 return fmt.Errorf("cue vet against %s gave no answer within %s", def, busDeadline)
238 }
239 return fmt.Errorf("the payload does not satisfy %s: %s", def, firstLine(string(out)))
240 }
241 return nil
242}