| new file mode 100644 |
| index 000000000..e5fc25c69 |
| --- /dev/null |
| +++ b/internal/registry/ha_journal.go |
| @@ -0,0 +1,314 @@ |
| +package registry |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| +) |
| + |
| +var ErrHAJournal = errors.New("ha_journal_invalid") |
| + |
| +type HATerminationInbox struct { |
| + Key, MessageID string |
| + Body []byte |
| + ReceivedAt, NextAttempt time.Time |
| + LastError string |
| +} |
| +type HADeparture struct { |
| + hadeparture.Departure |
| + ProofKey, ProofDigest, Phase, InventoryGeneration, LastError string |
| + NextAttempt, LastPage time.Time |
| +} |
| +type HABoxIdentity struct { |
| + Ref, IID, Account, Region, Digest string |
| + Raw []byte |
| + Observation hadeparture.BoxObservation |
| +} |
| +type HAIdentityWalk struct { |
| + Cursor string |
| + Keys []string |
| + Offset int |
| + Failed bool |
| + StartedAt time.Time |
| +} |
| + |
| +type haJournalRequest struct { |
| + Op, Key, ID, Code string |
| + Body []byte |
| + At, Next time.Time |
| + Limit int |
| + Page bool |
| + Departure HADeparture |
| + Identity HABoxIdentity |
| + Walk HAIdentityWalk |
| +} |
| +type haJournalResponse struct { |
| + Inbox []HATerminationInbox |
| + Departures []HADeparture |
| + Identity HABoxIdentity |
| + Walk HAIdentityWalk |
| + Found bool |
| +} |
| + |
| +func (r *Registry) migrateHAJournal() error { |
| + _, err := r.sql.Exec(` |
| + CREATE TABLE IF NOT EXISTS ha_termination_inbox(key TEXT PRIMARY KEY,message_id TEXT NOT NULL,body BLOB NOT NULL CHECK(length(body)<=65536),received INTEGER NOT NULL,next_attempt INTEGER NOT NULL,last_error TEXT NOT NULL DEFAULT ''); |
| + CREATE TABLE IF NOT EXISTS ha_departures(id TEXT PRIMARY KEY,body BLOB NOT NULL,phase TEXT NOT NULL DEFAULT 'pending',next_attempt INTEGER NOT NULL,last_page INTEGER NOT NULL DEFAULT 0,last_error TEXT NOT NULL DEFAULT ''); |
| + CREATE TABLE IF NOT EXISTS ha_box_identities(ref TEXT PRIMARY KEY,iid TEXT NOT NULL UNIQUE,body BLOB NOT NULL); |
| + CREATE TABLE IF NOT EXISTS ha_identity_walk(id INTEGER PRIMARY KEY CHECK(id=1),body BLOB NOT NULL); |
| + `) |
| + return err |
| +} |
| +func journalTime(t time.Time) int64 { |
| + if t.IsZero() { |
| + return 0 |
| + } |
| + return t.UnixNano() |
| +} |
| +func journalDate(n int64) time.Time { |
| + if n == 0 { |
| + return time.Time{} |
| + } |
| + return time.Unix(0, n).UTC() |
| +} |
| +func (r *Registry) RecordTermination(ctx context.Context, id string, body []byte, at time.Time) error { |
| + _, err := r.haJournal(ctx, haJournalRequest{Op: "record", ID: id, Body: body, At: at}) |
| + return err |
| +} |
| +func (r *Registry) TerminationInbox(ctx context.Context, at time.Time, limit int) ([]HATerminationInbox, error) { |
| + out, err := r.haJournal(ctx, haJournalRequest{Op: "inbox", At: at, Limit: limit}) |
| + return out.Inbox, err |
| +} |
| +func (r *Registry) RetryTermination(ctx context.Context, key string, next time.Time, code string) error { |
| + _, err := r.haJournal(ctx, haJournalRequest{Op: "retry_inbox", Key: key, Next: next, Code: code}) |
| + return err |
| +} |
| +func (r *Registry) RejectTermination(ctx context.Context, key string) error { |
| + _, err := r.haJournal(ctx, haJournalRequest{Op: "reject", Key: key}) |
| + return err |
| +} |
| +func (r *Registry) EnrollDeparture(ctx context.Context, d HADeparture, inbox string) error { |
| + _, err := r.haJournal(ctx, haJournalRequest{Op: "enroll", Departure: d, Key: inbox}) |
| + return err |
| +} |
| +func (r *Registry) PendingDepartures(ctx context.Context, at time.Time, limit int) ([]HADeparture, error) { |
| + out, err := r.haJournal(ctx, haJournalRequest{Op: "pending", At: at, Limit: limit}) |
| + return out.Departures, err |
| +} |
| +func (r *Registry) RetryDeparture(ctx context.Context, id string, at, next time.Time, code string, page bool) (bool, error) { |
| + out, err := r.haJournal(ctx, haJournalRequest{Op: "retry_departure", ID: id, At: at, Next: next, Code: code, Page: page}) |
| + return out.Found, err |
| +} |
| +func (r *Registry) SaveHAIdentity(ctx context.Context, b HABoxIdentity) error { |
| + _, err := r.haJournal(ctx, haJournalRequest{Op: "identity_save", Identity: b}) |
| + return err |
| +} |
| +func (r *Registry) HAIdentity(ctx context.Context, ref, iid string) (HABoxIdentity, bool, error) { |
| + out, err := r.haJournal(ctx, haJournalRequest{Op: "identity", ID: ref, Key: iid}) |
| + return out.Identity, out.Found, err |
| +} |
| +func (r *Registry) LoadHAIdentityWalk(ctx context.Context) (HAIdentityWalk, error) { |
| + out, err := r.haJournal(ctx, haJournalRequest{Op: "walk"}) |
| + return out.Walk, err |
| +} |
| +func (r *Registry) SaveHAIdentityWalk(ctx context.Context, w HAIdentityWalk) error { |
| + _, err := r.haJournal(ctx, haJournalRequest{Op: "walk_save", Walk: w}) |
| + return err |
| +} |
| +func (r *Registry) haJournal(ctx context.Context, q haJournalRequest) (out haJournalResponse, err error) { |
| + if r.remote != nil { |
| + resp, e := r.remote.call(ctx, remoteRequest{Method: "HAJournal", HAJournal: q}, nil) |
| + return resp.HAJournal, e |
| + } |
| + switch q.Op { |
| + case "record": |
| + if q.ID == "" || len(q.ID) > 1024 || len(q.Body) > hadeparture.MaxBodyBytes || q.At.IsZero() { |
| + return out, ErrHAJournal |
| + } |
| + key := fmt.Sprintf("%x", sha256.Sum256(append(append([]byte(q.ID), 0), q.Body...))) |
| + tx, e := r.beginClaimTransaction(ctx, true) |
| + if e != nil { |
| + return out, e |
| + } |
| + defer tx.Rollback() |
| + var exists int |
| + if e = tx.QueryRowContext(ctx, `SELECT count(*) FROM ha_termination_inbox WHERE key=?`, key).Scan(&exists); e != nil { |
| + return out, e |
| + } |
| + if exists != 0 { |
| + return out, nil |
| + } |
| + var count int |
| + if e = tx.QueryRowContext(ctx, `SELECT count(*) FROM ha_termination_inbox`).Scan(&count); e != nil { |
| + return out, e |
| + } |
| + if count >= hadeparture.MaxInboxRows { |
| + return out, ErrHAJournal |
| + } |
| + _, e = tx.ExecContext(ctx, `INSERT INTO ha_termination_inbox(key,message_id,body,received,next_attempt) VALUES(?,?,?,?,?)`, key, q.ID, q.Body, journalTime(q.At), journalTime(q.At)) |
| + if e != nil { |
| + return out, e |
| + } |
| + err = tx.Commit() |
| + case "inbox": |
| + if q.Limit < 1 || q.Limit > 32 { |
| + return out, ErrHAJournal |
| + } |
| + rows, e := r.sql.QueryContext(ctx, `SELECT key,message_id,body,received,next_attempt,last_error FROM ha_termination_inbox WHERE next_attempt<=? ORDER BY next_attempt,received,key LIMIT ?`, journalTime(q.At), q.Limit) |
| + if e != nil { |
| + return out, e |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var row HATerminationInbox |
| + var at, next int64 |
| + if e = rows.Scan(&row.Key, &row.MessageID, &row.Body, &at, &next, &row.LastError); e != nil { |
| + return out, e |
| + } |
| + row.ReceivedAt = journalDate(at) |
| + row.NextAttempt = journalDate(next) |
| + out.Inbox = append(out.Inbox, row) |
| + } |
| + err = rows.Err() |
| + case "reject": |
| + _, err = r.sql.ExecContext(ctx, `DELETE FROM ha_termination_inbox WHERE key=?`, q.Key) |
| + case "retry_inbox": |
| + _, err = r.sql.ExecContext(ctx, `UPDATE ha_termination_inbox SET next_attempt=?,last_error=? WHERE key=?`, journalTime(q.Next), q.Code, q.Key) |
| + case "enroll": |
| + d := q.Departure |
| + if d.ID == "" || d.ObservedAt.IsZero() || d.ProofKey == "" || d.ProofDigest == "" || d.Box.Ref == "" || d.Box.InstanceID == "" { |
| + return out, ErrHAJournal |
| + } |
| + d.Phase = "pending" |
| + d.LastPage = time.Time{} |
| + d.LastError = "" |
| + d.NextAttempt = d.ObservedAt |
| + body, e := json.Marshal(d) |
| + if e != nil { |
| + return out, e |
| + } |
| + tx, e := r.beginClaimTransaction(ctx, true) |
| + if e != nil { |
| + return out, e |
| + } |
| + defer tx.Rollback() |
| + // Replays preserve retry, phase and evidence provenance. |
| + if _, e = tx.ExecContext(ctx, `INSERT OR IGNORE INTO ha_departures(id,body,next_attempt) VALUES(?,?,?)`, d.ID, body, journalTime(d.NextAttempt)); e != nil { |
| + return out, e |
| + } |
| + if q.Key != "" { |
| + if _, e = tx.ExecContext(ctx, `DELETE FROM ha_termination_inbox WHERE key=?`, q.Key); e != nil { |
| + return out, e |
| + } |
| + } |
| + err = tx.Commit() |
| + case "pending": |
| + if q.Limit < 1 || q.Limit > 32 { |
| + return out, ErrHAJournal |
| + } |
| + rows, e := r.sql.QueryContext(ctx, `SELECT body,phase,next_attempt,last_page,last_error FROM ha_departures WHERE phase<>'complete' AND next_attempt<=? ORDER BY next_attempt,id LIMIT ?`, journalTime(q.At), q.Limit) |
| + if e != nil { |
| + return out, e |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var body []byte |
| + var d HADeparture |
| + var phase, code string |
| + var next, page int64 |
| + if e = rows.Scan(&body, &phase, &next, &page, &code); e != nil { |
| + return out, e |
| + } |
| + if e = json.Unmarshal(body, &d); e != nil { |
| + return out, e |
| + } |
| + d.Phase = phase |
| + d.LastError = code |
| + d.NextAttempt = journalDate(next) |
| + d.LastPage = journalDate(page) |
| + out.Departures = append(out.Departures, d) |
| + } |
| + err = rows.Err() |
| + case "retry_departure": |
| + tx, e := r.beginClaimTransaction(ctx, true) |
| + if e != nil { |
| + return out, e |
| + } |
| + defer tx.Rollback() |
| + if q.Page { |
| + res, e := tx.ExecContext(ctx, `UPDATE ha_departures SET last_page=? WHERE id=? AND phase<>'complete' AND (last_page=0 OR last_page<=?)`, journalTime(q.At), q.ID, journalTime(q.At.Add(-time.Hour))) |
| + if e != nil { |
| + return out, e |
| + } |
| + n, e := res.RowsAffected() |
| + if e != nil { |
| + return out, e |
| + } |
| + out.Found = n == 1 |
| + } |
| + if _, e = tx.ExecContext(ctx, `UPDATE ha_departures SET next_attempt=?,last_error=? WHERE id=? AND phase<>'complete'`, journalTime(q.Next), q.Code, q.ID); e != nil { |
| + return out, e |
| + } |
| + err = tx.Commit() |
| + case "identity_save": |
| + b := q.Identity |
| + if b.Ref == "" || b.IID == "" || b.Account == "" || b.Region == "" || len(b.Raw) > 64*1024 || len(b.Raw) == 0 || b.Digest != fmt.Sprintf("%x", sha256.Sum256(b.Raw)) { |
| + return out, ErrHAJournal |
| + } |
| + body, e := json.Marshal(b) |
| + if e != nil { |
| + return out, e |
| + } |
| + res, e := r.sql.ExecContext(ctx, `INSERT INTO ha_box_identities(ref,iid,body) VALUES(?,?,?) ON CONFLICT(ref) DO UPDATE SET body=excluded.body WHERE iid=excluded.iid AND json_extract(body,'$.Digest')=json_extract(excluded.body,'$.Digest')`, b.Ref, b.IID, body) |
| + if e != nil { |
| + return out, e |
| + } |
| + n, e := res.RowsAffected() |
| + if e != nil { |
| + return out, e |
| + } |
| + if n != 1 { |
| + return out, ErrHAJournal |
| + } |
| + case "identity": |
| + var body []byte |
| + err = r.sql.QueryRowContext(ctx, `SELECT body FROM ha_box_identities WHERE (?<>'' AND ref=?) OR (?<>'' AND iid=?)`, q.ID, q.ID, q.Key, q.Key).Scan(&body) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return out, nil |
| + } |
| + if err == nil { |
| + err = json.Unmarshal(body, &out.Identity) |
| + out.Found = err == nil |
| + } |
| + if out.Found && ((q.ID != "" && q.ID != out.Identity.Ref) || (q.Key != "" && q.Key != out.Identity.IID)) { |
| + return haJournalResponse{}, ErrHAJournal |
| + } |
| + case "walk_save": |
| + if len(q.Walk.Keys) > 1000 || q.Walk.Offset < 0 || q.Walk.Offset > len(q.Walk.Keys) { |
| + return out, ErrHAJournal |
| + } |
| + body, e := json.Marshal(q.Walk) |
| + if e != nil { |
| + return out, e |
| + } |
| + _, err = r.sql.ExecContext(ctx, `INSERT INTO ha_identity_walk(id,body) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET body=excluded.body`, body) |
| + case "walk": |
| + var body []byte |
| + err = r.sql.QueryRowContext(ctx, `SELECT body FROM ha_identity_walk WHERE id=1`).Scan(&body) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return out, nil |
| + } |
| + if err == nil { |
| + err = json.Unmarshal(body, &out.Walk) |
| + } |
| + default: |
| + return out, ErrHAJournal |
| + } |
| + return out, err |
| +} |