| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "net/http" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 12 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 13 | ) |
| 14 | |
| 15 | type EventPump struct { |
| 16 | Journal *Journal |
| 17 | Upload func(context.Context, Event) error |
| 18 | Contain func(context.Context) error |
| 19 | Secrets []string |
| 20 | } |
| 21 | |
| 22 | func (p *EventPump) Append(ctx context.Context, e Event, ack func() error) error { |
| 23 | if p.Journal == nil || p.Contain == nil { |
| 24 | return runnerproto.ErrInvalid |
| 25 | } |
| 26 | if err := p.Journal.appendRedacted(ctx, e, p.Secrets); err != nil { |
| 27 | return p.storageFailure(ctx, err) |
| 28 | } |
| 29 | if ack != nil { |
| 30 | return ack() |
| 31 | } |
| 32 | return nil |
| 33 | } |
| 34 | func (p *EventPump) Flush(ctx context.Context, limit int) error { |
| 35 | if p.Journal == nil || p.Upload == nil || p.Contain == nil { |
| 36 | return runnerproto.ErrInvalid |
| 37 | } |
| 38 | pending, err := p.Journal.Pending(ctx, limit) |
| 39 | if err != nil { |
| 40 | return p.storageFailure(ctx, err) |
| 41 | } |
| 42 | for _, e := range pending { |
| 43 | if err = p.Upload(ctx, e); err != nil { |
| 44 | return err |
| 45 | } |
| 46 | if err = p.Journal.Ack(ctx, e.ID); err != nil { |
| 47 | return p.storageFailure(ctx, err) |
| 48 | } |
| 49 | } |
| 50 | return nil |
| 51 | } |
| 52 | func streamKey(a provider.Agent) string { |
| 53 | return runnerproto.EventHash([]string{a.ServerID, a.AgentID, a.ProviderSessionID}) |
| 54 | } |
| 55 | func (j *Journal) BeginReplay(ctx context.Context, a provider.Agent) error { |
| 56 | if a.ServerID == "" || a.AgentID == "" || a.ProviderSessionID == "" { |
| 57 | return runnerproto.ErrInvalid |
| 58 | } |
| 59 | _, err := j.db.ExecContext(ctx, `INSERT INTO journal_streams VALUES(?,'',0,-1) ON CONFLICT(stream) DO UPDATE SET ready=-1`, streamKey(a)) |
| 60 | if err != nil { |
| 61 | return j.storageFailure(ctx, err) |
| 62 | } |
| 63 | return nil |
| 64 | } |
| 65 | func (j *Journal) Cursor(ctx context.Context, a provider.Agent) (provider.Cursor, error) { |
| 66 | var c provider.Cursor |
| 67 | err := j.db.QueryRowContext(ctx, "SELECT epoch,sequence FROM journal_streams WHERE stream=?", streamKey(a)).Scan(&c.Epoch, &c.Sequence) |
| 68 | if errors.Is(err, sql.ErrNoRows) { |
| 69 | return c, nil |
| 70 | } |
| 71 | return c, err |
| 72 | } |
| 73 | func (j *Journal) Ready(ctx context.Context, a provider.Agent) error { |
| 74 | if err := j.AdmissionAllowed(ctx); err != nil { |
| 75 | return err |
| 76 | } |
| 77 | var ready int |
| 78 | if err := j.db.QueryRowContext(ctx, "SELECT ready FROM journal_streams WHERE stream=?", streamKey(a)).Scan(&ready); err != nil || ready != 1 { |
| 79 | return provider.ErrNotReady |
| 80 | } |
| 81 | return nil |
| 82 | } |
| 83 | func (j *Journal) Recovered(ctx context.Context, a provider.Agent, c provider.Cursor) error { |
| 84 | if c.Epoch == "" || c.Sequence < 0 || a.ServerID == "" || a.AgentID == "" || a.ProviderSessionID == "" { |
| 85 | return runnerproto.ErrInvalid |
| 86 | } |
| 87 | if err := j.AdmissionAllowed(ctx); err != nil { |
| 88 | return err |
| 89 | } |
| 90 | // Called only after Subscribe.Ready and durable draining of its refetch. |
| 91 | tx, err := j.db.BeginTx(ctx, nil) |
| 92 | if err != nil { |
| 93 | return j.storageFailure(ctx, err) |
| 94 | } |
| 95 | defer tx.Rollback() |
| 96 | var phase int |
| 97 | if err = tx.QueryRowContext(ctx, "SELECT ready FROM journal_streams WHERE stream=?", streamKey(a)).Scan(&phase); err != nil || phase != -1 { |
| 98 | return provider.ErrNotReady |
| 99 | } |
| 100 | var maximum sql.NullInt64 |
| 101 | if err = tx.QueryRowContext(ctx, `SELECT MAX(json_extract(body,'$.sequence')) FROM journal_events WHERE json_extract(body,'$.server_id')=? AND json_extract(body,'$.agent_id')=? AND json_extract(body,'$.session_id')=? AND json_extract(body,'$.epoch')=?`, a.ServerID, a.AgentID, a.ProviderSessionID, c.Epoch).Scan(&maximum); err != nil { |
| 102 | return ErrJournal |
| 103 | } |
| 104 | if c.Sequence > 0 && (!maximum.Valid || c.Sequence > maximum.Int64) { |
| 105 | return runnerproto.ErrInvalid |
| 106 | } |
| 107 | if _, err = tx.ExecContext(ctx, `INSERT INTO journal_streams VALUES(?,?,?,1) ON CONFLICT(stream) DO UPDATE SET epoch=excluded.epoch,sequence=excluded.sequence,ready=1`, streamKey(a), c.Epoch, c.Sequence); err != nil { |
| 108 | return ErrJournal |
| 109 | } |
| 110 | return tx.Commit() |
| 111 | } |
| 112 | func ReconnectDelay(attempt int) time.Duration { return runnerproto.ReconnectDelay(attempt) } |
| 113 | func WaitReconnect(ctx context.Context, attempt int, deadline time.Time) error { |
| 114 | return runnerproto.WaitReconnect(ctx, attempt, deadline) |
| 115 | } |
| 116 | func redactText(s string, secrets []string) string { return runnerproto.RedactText(s, secrets) } |
| 117 | func RedactJSON(raw json.RawMessage, secrets []string) json.RawMessage { |
| 118 | return runnerproto.RedactJSON(raw, secrets) |
| 119 | } |
| 120 | func DownloadLog(w http.ResponseWriter, data []byte, secrets []string) { |
| 121 | runnerproto.DownloadLog(w, data, secrets) |
| 122 | } |
| 123 | |
| 124 | func journalStreamEvent(ctx context.Context, tx *sql.Tx, e Event) error { |
| 125 | key := streamKey(provider.Agent{ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID}) |
| 126 | var epoch string |
| 127 | var sequence int64 |
| 128 | var ready int |
| 129 | err := tx.QueryRowContext(ctx, "SELECT epoch,sequence,ready FROM journal_streams WHERE stream=?", key).Scan(&epoch, &sequence, &ready) |
| 130 | if errors.Is(err, sql.ErrNoRows) { |
| 131 | epoch = e.Epoch |
| 132 | } else if err != nil { |
| 133 | return err |
| 134 | } |
| 135 | switch e.Kind { |
| 136 | case "timeline_replacement": |
| 137 | epoch = e.Epoch |
| 138 | sequence = 0 |
| 139 | ready = 0 |
| 140 | case "timeline_gap": |
| 141 | ready = 0 |
| 142 | default: |
| 143 | if e.Sequence != nil { |
| 144 | if epoch == "" { |
| 145 | epoch = e.Epoch |
| 146 | } |
| 147 | if epoch != e.Epoch { |
| 148 | ready = 0 |
| 149 | } else if *e.Sequence > sequence { |
| 150 | sequence = *e.Sequence |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | _, err = tx.ExecContext(ctx, `INSERT INTO journal_streams VALUES(?,?,?,?) ON CONFLICT(stream) DO UPDATE SET epoch=excluded.epoch,sequence=excluded.sequence,ready=excluded.ready`, key, epoch, sequence, ready) |
| 155 | return err |
| 156 | } |
| 157 | |
| 158 | func (p *EventPump) storageFailure(ctx context.Context, err error) error { |
| 159 | _ = p.Journal.storageFailure(ctx, err) |
| 160 | cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) |
| 161 | defer cancel() |
| 162 | return errors.Join(err, p.Contain(cleanup)) |
| 163 | } |
| 164 | |
| 165 | // Drain waits for every pending event to be acknowledged, including terminal |
| 166 | // receipts beyond the first upload batch. A failed upload stays pending. |
| 167 | func (p *EventPump) Drain(ctx context.Context) error { |
| 168 | for { |
| 169 | if err := p.Flush(ctx, 128); err != nil { |
| 170 | return err |
| 171 | } |
| 172 | pending, err := p.Journal.Pending(ctx, 1) |
| 173 | if err != nil { |
| 174 | return p.storageFailure(ctx, err) |
| 175 | } |
| 176 | if len(pending) == 0 { |
| 177 | return nil |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | |