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