package runner import ( "context" "database/sql" "encoding/json" "errors" "net/http" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type EventPump struct { Journal *Journal Upload func(context.Context, Event) error Contain func(context.Context) error Secrets []string } func (p *EventPump) Append(ctx context.Context, e Event, ack func() error) error { if p.Journal == nil || p.Contain == nil { return runnerproto.ErrInvalid } if err := p.Journal.appendRedacted(ctx, e, p.Secrets); err != nil { return p.storageFailure(ctx, err) } if ack != nil { return ack() } return nil } func (p *EventPump) Flush(ctx context.Context, limit int) error { if p.Journal == nil || p.Upload == nil || p.Contain == nil { return runnerproto.ErrInvalid } pending, err := p.Journal.Pending(ctx, limit) if err != nil { return p.storageFailure(ctx, err) } for _, e := range pending { if err = p.Upload(ctx, e); err != nil { return err } if err = p.Journal.Ack(ctx, e.ID); err != nil { return p.storageFailure(ctx, err) } } return nil } func streamKey(a provider.Agent) string { return runnerproto.EventHash([]string{a.ServerID, a.AgentID, a.ProviderSessionID}) } func (j *Journal) BeginReplay(ctx context.Context, a provider.Agent) error { if a.ServerID == "" || a.AgentID == "" || a.ProviderSessionID == "" { return runnerproto.ErrInvalid } _, err := j.db.ExecContext(ctx, `INSERT INTO journal_streams VALUES(?,'',0,-1) ON CONFLICT(stream) DO UPDATE SET ready=-1`, streamKey(a)) if err != nil { return j.storageFailure(ctx, err) } return nil } func (j *Journal) Cursor(ctx context.Context, a provider.Agent) (provider.Cursor, error) { var c provider.Cursor err := j.db.QueryRowContext(ctx, "SELECT epoch,sequence FROM journal_streams WHERE stream=?", streamKey(a)).Scan(&c.Epoch, &c.Sequence) if errors.Is(err, sql.ErrNoRows) { return c, nil } return c, err } func (j *Journal) Ready(ctx context.Context, a provider.Agent) error { if err := j.AdmissionAllowed(ctx); err != nil { return err } var ready int if err := j.db.QueryRowContext(ctx, "SELECT ready FROM journal_streams WHERE stream=?", streamKey(a)).Scan(&ready); err != nil || ready != 1 { return provider.ErrNotReady } return nil } func (j *Journal) Recovered(ctx context.Context, a provider.Agent, c provider.Cursor) error { if c.Epoch == "" || c.Sequence < 0 || a.ServerID == "" || a.AgentID == "" || a.ProviderSessionID == "" { return runnerproto.ErrInvalid } if err := j.AdmissionAllowed(ctx); err != nil { return err } // Called only after Subscribe.Ready and durable draining of its refetch. tx, err := j.db.BeginTx(ctx, nil) if err != nil { return j.storageFailure(ctx, err) } defer tx.Rollback() var phase int if err = tx.QueryRowContext(ctx, "SELECT ready FROM journal_streams WHERE stream=?", streamKey(a)).Scan(&phase); err != nil || phase != -1 { return provider.ErrNotReady } var maximum sql.NullInt64 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 { return ErrJournal } if c.Sequence > 0 && (!maximum.Valid || c.Sequence > maximum.Int64) { return runnerproto.ErrInvalid } 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 { return ErrJournal } return tx.Commit() } func ReconnectDelay(attempt int) time.Duration { return runnerproto.ReconnectDelay(attempt) } func WaitReconnect(ctx context.Context, attempt int, deadline time.Time) error { return runnerproto.WaitReconnect(ctx, attempt, deadline) } func redactText(s string, secrets []string) string { return runnerproto.RedactText(s, secrets) } func RedactJSON(raw json.RawMessage, secrets []string) json.RawMessage { return runnerproto.RedactJSON(raw, secrets) } func DownloadLog(w http.ResponseWriter, data []byte, secrets []string) { runnerproto.DownloadLog(w, data, secrets) } func journalStreamEvent(ctx context.Context, tx *sql.Tx, e Event) error { key := streamKey(provider.Agent{ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID}) var epoch string var sequence int64 var ready int err := tx.QueryRowContext(ctx, "SELECT epoch,sequence,ready FROM journal_streams WHERE stream=?", key).Scan(&epoch, &sequence, &ready) if errors.Is(err, sql.ErrNoRows) { epoch = e.Epoch } else if err != nil { return err } switch e.Kind { case "timeline_replacement": epoch = e.Epoch sequence = 0 ready = 0 case "timeline_gap": ready = 0 default: if e.Sequence != nil { if epoch == "" { epoch = e.Epoch } if epoch != e.Epoch { ready = 0 } else if *e.Sequence > sequence { sequence = *e.Sequence } } } _, 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) return err } func (p *EventPump) storageFailure(ctx context.Context, err error) error { _ = p.Journal.storageFailure(ctx, err) cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) defer cancel() return errors.Join(err, p.Contain(cleanup)) } // Drain waits for every pending event to be acknowledged, including terminal // receipts beyond the first upload batch. A failed upload stays pending. func (p *EventPump) Drain(ctx context.Context) error { for { if err := p.Flush(ctx, 128); err != nil { return err } pending, err := p.Journal.Pending(ctx, 1) if err != nil { return p.storageFailure(ctx, err) } if len(pending) == 0 { return nil } } }