diff --git a/.dockerignore b/.dockerignore index 56d1085..a6f9cf8 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,6 +2,9 @@ .github .env .env.* +**/.env +**/.env.* +**/node_modules data bin dist diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5aae8be..4415e4b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,11 @@ jobs: go-version: ${{ matrix.go }} - run: make check build - run: python3 scripts/test_install.py + - name: Upgrade real v0.3.0 SQLite and PostgreSQL installations + if: matrix.go == '1.27.x' + run: | + docker build -f scripts/compatibility.Dockerfile -t ranjit-compatibility . + docker run --rm --network host -v "$PWD:/work:ro" -e RANJIT_TEST_POSTGRES_URL ranjit-compatibility /work/bin/ranjit - name: Exercise PostgreSQL and the Go backend example run: | go build -o bin/backend-example ./examples/backend @@ -56,6 +61,19 @@ jobs: if: matrix.go == '1.27.x' run: go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./... + quickstart: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - name: Start, verify, stop and restart the backend demo + run: | + trap 'scripts/quickstart.sh reset' EXIT + scripts/quickstart.sh + scripts/quickstart.sh stop + scripts/quickstart.sh + scripts/container_upgrade.sh ranjit-quickstart-ranjit + container: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d40ab0a..9353bdc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -29,7 +29,7 @@ jobs: --health-interval 5s --health-timeout 5s --health-retries 10 env: RANJIT_TEST_POSTGRES_URL: postgres://ranjit:test-only-password@localhost:5432/ranjit?sslmode=disable - timeout-minutes: 30 + timeout-minutes: 45 permissions: contents: write packages: write @@ -40,10 +40,24 @@ jobs: go-version: '1.27.x' - run: make check build - run: go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./... + - run: python3 scripts/test_install.py + - name: Validate upgrade compatibility and the backend quickstart + run: | + docker build -f scripts/compatibility.Dockerfile -t ranjit-compatibility . + docker run --rm --network host -v "$PWD:/work:ro" -e RANJIT_TEST_POSTGRES_URL ranjit-compatibility /work/bin/ranjit + trap 'scripts/quickstart.sh reset' EXIT + scripts/quickstart.sh + scripts/quickstart.sh stop + scripts/quickstart.sh + scripts/container_upgrade.sh ranjit-quickstart-ranjit - name: Build release archives env: RELEASE_VERSION: ${{ github.ref_name }} run: python3 scripts/release.py --version "$RELEASE_VERSION" + - name: Verify archives and install the candidate binary + env: + RELEASE_VERSION: ${{ github.ref_name }} + run: python3 scripts/verify_release.py --version "$RELEASE_VERSION" --artifacts dist - name: Build and smoke-test container env: RELEASE_VERSION: ${{ github.ref_name }} @@ -68,18 +82,18 @@ jobs: gzip -n "$artifact" done (cd dist && sha256sum *.docker.tar.gz >> checksums.txt) - sha256sum compose.quick.yaml >> dist/checksums.txt + sha256sum compose.quick.yaml install.sh >> dist/checksums.txt docker load --input "dist/ranjit_${RELEASE_VERSION}_linux_amd64.docker.tar.gz" docker compose -f compose.quick.yaml up -d --wait --wait-timeout 60 docker compose -f compose.quick.yaml exec -T ranjit /ranjit demo docker compose -f compose.quick.yaml exec -T ranjit /ranjit doctor docker compose -f compose.quick.yaml down --volumes - - name: Publish binaries + - name: Stage release downloads env: GH_TOKEN: ${{ github.token }} RELEASE_VERSION: ${{ github.ref_name }} run: | - gh release create "$RELEASE_VERSION" dist/* install.sh compose.quick.yaml --verify-tag --title "Ranjit $RELEASE_VERSION" --notes-file docs/release-notes.md + gh release create "$RELEASE_VERSION" dist/* install.sh compose.quick.yaml --draft --verify-tag --title "Ranjit $RELEASE_VERSION" --notes-file docs/release-notes.md - name: Publish container image env: REGISTRY_TOKEN: ${{ github.token }} @@ -87,4 +101,16 @@ jobs: RELEASE_VERSION: ${{ github.ref_name }} run: | printf '%s' "$REGISTRY_TOKEN" | docker login ghcr.io --username "$REGISTRY_USER" --password-stdin - docker buildx build --platform linux/amd64,linux/arm64 --build-arg VERSION="$RELEASE_VERSION" --tag "ghcr.io/getcortexlabs/ranjit:$RELEASE_VERSION" --tag ghcr.io/getcortexlabs/ranjit:latest --push . + docker buildx build --platform linux/amd64,linux/arm64 --build-arg VERSION="$RELEASE_VERSION" --tag "ghcr.io/getcortexlabs/ranjit:$RELEASE_VERSION" --push . + - name: Verify public images before announcing the release + env: + RELEASE_VERSION: ${{ github.ref_name }} + run: python3 scripts/verify_release.py --version "$RELEASE_VERSION" --images + - name: Publish and verify downloads and SDK + env: + GH_TOKEN: ${{ github.token }} + RELEASE_VERSION: ${{ github.ref_name }} + run: | + gh release edit "$RELEASE_VERSION" --draft=false + python3 scripts/verify_release.py --version "$RELEASE_VERSION" --published + docker buildx imagetools create --tag ghcr.io/getcortexlabs/ranjit:latest "ghcr.io/getcortexlabs/ranjit:$RELEASE_VERSION" diff --git a/README.md b/README.md index 8bdae1b..349bea6 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,16 @@ As integrações diretas usam as credenciais da aplicação criada pelo titular ## Usar no backend +Para experimentar a integração completa com Docker: + +```sh +git clone https://github.com/getcortexlabs/ranjit.git +cd ranjit +./scripts/quickstart.sh +``` + +O [quickstart](examples/quickstart/) sobe o serviço, um backend Go e o receptor de webhooks, gera as chaves e testa importação e sandbox. Os dados persistem entre reinícios. Docker é opcional para integrar seu aplicativo. + Para começar localmente, instale o binário abaixo, rode `ranjit serve` e obtenha a chave com `ranjit key`. No seu backend: ```sh @@ -37,7 +47,9 @@ O SDK é um cliente HTTP: o Ranjit roda como processo separado do seu backend. A O [exemplo de backend Go](examples/backend/) importa um CSV e consulta transações sem precisar de acesso bancário. O [guia de instalação em servidor e Orbit](docs/server.md) cobre PostgreSQL, segredos e a configuração do SDK. O painel e os comandos locais continuam disponíveis como ferramentas de apoio. -Para repetir uma criação sem duplicar conexões, use `client.ConnectWithKey`. Webhooks assinados avisam quando a sincronização conclui ou falha definitivamente. A chave da API pode ser trocada com um prazo para migrar os consumidores. O [guia de integração confiável](docs/backend-reliability.md) traz configuração, exemplos e recuperação de falhas. +Para repetir uma criação sem duplicar conexões, use `client.ConnectWithKey`. Webhooks assinados avisam sobre sincronizações e mudanças no estado das conexões. A chave da API pode ser trocada com um prazo para migrar os consumidores. O [guia de integração confiável](docs/backend-reliability.md) traz configuração, exemplos e recuperação de falhas. O [guia do SDK](docs/sdk.md) cobre paginação automática, retentativas de leitura e tratamento de erros. + +Para verificar a instalação pelo backend, basta configurar a mesma URL/chave e rodar `ranjit doctor --remote`. Use `--json` em automações. O comando consulta a API, o banco e os workers pelo serviço, sem precisar dos arquivos locais do Ranjit. ## Instalar diff --git a/client.go b/client.go index 5720d0a..bf37b98 100644 --- a/client.go +++ b/client.go @@ -15,12 +15,14 @@ import ( ) type Client struct { - baseURL string - apiKey string - HTTPClient *http.Client + ReadRetries RetryPolicy + baseURL string + apiKey string + HTTPClient *http.Client } type APIError struct { + Cause error StatusCode int Code string Message string @@ -220,31 +222,6 @@ func (c *Client) doWithKey(ctx context.Context, method, path string, input, outp return c.send(req, output) } -func (c *Client) send(req *http.Request, output any) error { - req.Header.Set("Authorization", "Bearer "+c.apiKey) - req.Header.Set("Accept", "application/json") - resp, err := c.HTTPClient.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - decoder := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)) - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - var problem struct { - Error struct { - Code string `json:"code"` - Message string `json:"message"` - } `json:"error"` - } - _ = decoder.Decode(&problem) - return &APIError{StatusCode: resp.StatusCode, Code: problem.Error.Code, Message: problem.Error.Message, RequestID: resp.Header.Get("X-Request-ID")} - } - if output == nil { - return nil - } - return decoder.Decode(output) -} - // ConnectWithKey retries a logical creation safely for 24 hours. Persist a random // key per operation in your backend and reuse it with the same request on retry. func (c *Client) ConnectWithKey(ctx context.Context, input ConnectRequest, key string) (ConnectResponse, error) { diff --git a/cmd/ranjit/cli.go b/cmd/ranjit/cli.go index a777cf9..aab839c 100644 --- a/cmd/ranjit/cli.go +++ b/cmd/ranjit/cli.go @@ -30,6 +30,7 @@ Conexão automática (exige acesso à API do banco): ranjit configure Assistente de configuração ranjit doctor Conferir configuração e certificados ranjit doctor --live Conferir também o acesso ao saldo + ranjit doctor --remote --json Diagnosticar instalação hospedada ranjit sync [perfil] Conectar e sincronizar agora ranjit serve API local e sincronização periódica diff --git a/cmd/ranjit/doctor.go b/cmd/ranjit/doctor.go index 5fe37f4..c3ee5d6 100644 --- a/cmd/ranjit/doctor.go +++ b/cmd/ranjit/doctor.go @@ -3,22 +3,43 @@ package main import ( "context" "errors" + "flag" "fmt" "github.com/getcortexlabs/ranjit/internal/app" "github.com/getcortexlabs/ranjit/internal/config" "github.com/getcortexlabs/ranjit/internal/provider" "github.com/getcortexlabs/ranjit/internal/store" + "os" "time" ) func (c cli) doctor(ctx context.Context, args []string) error { f := c.flags("doctor") + remote := f.Bool("remote", false, "diagnosticar serviço por HTTP usando RANJIT_URL e RANJIT_API_KEY") + address := f.String("url", os.Getenv("RANJIT_URL"), "origem HTTP(S) do serviço remoto") + asJSON := f.Bool("json", false, "relatório remoto em JSON") + timeout := f.Duration("timeout", 10*time.Second, "prazo total do diagnóstico remoto") live := f.Bool("live", false, "consultar saldo usando as credenciais configuradas") if err := f.Parse(args); err != nil { return err } if f.NArg() != 0 { - return errors.New("use ranjit doctor [--live]") + return errors.New("use ranjit doctor [--live] ou ranjit doctor --remote [--json]") + } + explicitURL := false + f.Visit(func(flag *flag.Flag) { + if flag.Name == "url" { + explicitURL = true + } + }) + if *remote || explicitURL { + if *live { + return errors.New("--live é uma consulta bancária local; não combine com --remote") + } + return c.remoteDoctor(ctx, *address, os.Getenv("RANJIT_API_KEY"), *timeout, *asJSON) + } + if *asJSON { + return errors.New("use ranjit doctor --remote --json para o relatório remoto") } cfg, err := config.Load() if err != nil { diff --git a/cmd/ranjit/doctor_remote.go b/cmd/ranjit/doctor_remote.go new file mode 100644 index 0000000..8032995 --- /dev/null +++ b/cmd/ranjit/doctor_remote.go @@ -0,0 +1,152 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/getcortexlabs/ranjit" +) + +type doctorCheck struct { + ID string `json:"id"` + Status string `json:"status"` + Message string `json:"message"` + Action string `json:"action,omitempty"` +} +type doctorReport struct { + SchemaVersion int `json:"schema_version"` + Status string `json:"status"` + ServerVersion string `json:"server_version,omitempty"` + Checks []doctorCheck `json:"checks"` +} + +func (c cli) remoteDoctor(ctx context.Context, address, key string, timeout time.Duration, asJSON bool) error { + report := doctorReport{SchemaVersion: 1, Status: "ok", Checks: []doctorCheck{}} + add := func(id, status, message, action string) { + report.Checks = append(report.Checks, doctorCheck{id, status, message, action}) + if status == "error" || status == "warning" && report.Status == "ok" { + report.Status = status + } + } + if timeout <= 0 || timeout > time.Minute { + return errors.New("--timeout deve ser maior que zero e no máximo 1m") + } + client, err := ranjit.NewClient(address, key) + if err != nil { + add("configuration", "error", "URL ou chave da API ausente/inválida.", "Configure RANJIT_URL como origem HTTP(S) e RANJIT_API_KEY como segredo do ambiente.") + return c.printDoctor(report, asJSON) + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + if err = client.Health(ctx); err != nil { + add("reachability", "error", "O serviço não respondeu ao healthcheck esperado.", "Confira URL, certificado TLS, proxy e conectividade.") + return c.printDoctor(report, asJSON) + } + add("reachability", "ok", "Serviço acessível.", "") + if _, err = client.Institutions(ctx); err != nil { + if errors.Is(err, ranjit.ErrUnauthorized) { + add("authentication", "error", "Chave da API recusada.", "Confira a chave e o prazo de uma eventual rotação.") + } else { + add("authentication", "error", "Não foi possível confirmar o acesso à API.", "Confira o proxy, a disponibilidade do serviço e a URL configurada.") + } + return c.printDoctor(report, asJSON) + } + add("authentication", "ok", "Chave aceita.", "") + if err = client.Ready(ctx); err != nil { + add("database", "error", "A prontidão do armazenamento não foi confirmada.", "Confira o banco e a conexão configurada no serviço.") + } else { + add("database", "ok", "Armazenamento pronto.", "") + } + diagnostics, err := client.Diagnostics(ctx) + if err != nil { + var api *ranjit.APIError + if errors.As(err, &api) && api.StatusCode == 404 { + add("diagnostics", "warning", "Esta instalação não disponibiliza diagnósticos.", "Confira a versão instalada.") + } else { + add("diagnostics", "error", "Não foi possível ler os diagnósticos.", "Confira disponibilidade, autenticação e versão do serviço.") + } + return c.printDoctor(report, asJSON) + } + if safeVersion(diagnostics.Version) { + report.ServerVersion = diagnostics.Version + add("version", "ok", "Versão do servidor identificada.", "") + } else { + add("version", "warning", "O servidor não informou uma versão reconhecida.", "Confira o binário ou a tag da imagem instalada.") + } + if diagnostics.Operations == nil { + add("workers", "warning", "Esta versão não informa a atividade dos workers.", "Atualize para uma versão com diagnósticos operacionais.") + } else { + if diagnostics.Operations.Database != "ready" { + add("operational_database", "error", "A leitura das filas falhou.", "Confira a disponibilidade e as permissões do banco.") + } + for _, name := range []string{"sync", "webhook"} { + worker, ok := diagnostics.Operations.Workers[name] + switch { + case !ok: + add("worker_"+name, "warning", "Atividade do worker não informada.", "Confira a versão do serviço.") + case worker.State == "disabled": + add("worker_"+name, "ok", "Worker desabilitado na configuração.", "") + case worker.State == "starting": + add("worker_"+name, "warning", "Worker iniciando.", "Repita o diagnóstico após a inicialização.") + case !worker.Healthy: + add("worker_"+name, "error", "Worker sem progresso saudável.", "Confira os logs e a disponibilidade do armazenamento.") + default: + add("worker_"+name, "ok", "Worker em atividade ou aguardando trabalho.", "") + } + } + if diagnostics.Operations.WebhookQueue.Counts["failed"] > 0 { + add("webhook_deliveries", "warning", "Há notificações com tentativas esgotadas.", "Confira o receptor e reenvie as entregas pela API.") + } + if diagnostics.Operations.SyncQueue.RecentFailed > 0 { + add("synchronizations", "warning", "Há sincronizações que falharam nas últimas 24 horas.", "Consulte os jobs e confira os perfis bancários afetados.") + } + } + if len(diagnostics.UnavailableProfiles) > 0 { + add("profiles", "warning", "Há perfis indisponíveis no servidor.", "Confira as credenciais e os certificados no ambiente do Ranjit.") + } + for _, cert := range diagnostics.Certificates { + if cert.Level != "ok" { + add("certificates", "warning", "Há certificados que precisam de atenção.", "Consulte os diagnósticos do servidor e renove os certificados necessários.") + break + } + } + return c.printDoctor(report, asJSON) +} + +func (c cli) printDoctor(report doctorReport, asJSON bool) error { + if asJSON { + if err := json.NewEncoder(c.out).Encode(report); err != nil { + return err + } + } else { + if report.ServerVersion != "" { + fmt.Fprintln(c.out, "Ranjit", report.ServerVersion) + } + for _, check := range report.Checks { + label := map[string]string{"ok": "OK", "warning": "AVISO", "error": "ERRO"}[check.Status] + fmt.Fprintf(c.out, "%s %s: %s\n", label, check.ID, check.Message) + if check.Action != "" { + fmt.Fprintln(c.out, " "+check.Action) + } + } + } + if report.Status == "error" { + return errors.New("diagnóstico remoto encontrou falhas") + } + return nil +} + +func safeVersion(v string) bool { + if v == "" || len(v) > 64 { + return false + } + for _, r := range v { + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '.' || r == '-' || r == '+') { + return false + } + } + return true +} diff --git a/cmd/ranjit/doctor_remote_test.go b/cmd/ranjit/doctor_remote_test.go new file mode 100644 index 0000000..0c61e7b --- /dev/null +++ b/cmd/ranjit/doctor_remote_test.go @@ -0,0 +1,84 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestRemoteDoctorDoesNotOpenLocalConfiguration(t *testing.T) { + for _, scenario := range []string{"healthy", "unauthorized", "database", "worker", "legacy", "missing"} { + t.Run(scenario, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/healthz": + w.Write([]byte(`{"status":"ok"}`)) + case "/readyz": + if scenario == "database" { + http.Error(w, "do-not-print-database-secret", 503) + } else { + w.Write([]byte(`{"status":"ready"}`)) + } + case "/v1/institutions": + if scenario == "unauthorized" { + http.Error(w, "do-not-print-key", 401) + } else { + w.Write([]byte(`{"data":[]}`)) + } + case "/v1/diagnostics": + if scenario == "missing" { + http.NotFound(w, r) + return + } + if scenario == "legacy" { + w.Write([]byte(`{"version":"v0.3.0"}`)) + return + } + healthy := scenario != "worker" + json.NewEncoder(w).Encode(map[string]any{"version": "v0.4.0", "operations": map[string]any{"database": "ready", "workers": map[string]any{"sync": map[string]any{"state": "idle", "healthy": healthy}, "webhook": map[string]any{"state": "disabled", "healthy": true}}}}) + } + })) + defer server.Close() + absent := filepath.Join(t.TempDir(), "must-not-create", "config.json") + t.Setenv("RANJIT_CONFIG", absent) + t.Setenv("RANJIT_URL", server.URL) + t.Setenv("RANJIT_API_KEY", "private-test-secret") + var out bytes.Buffer + err := (cli{out: &out}).doctor(t.Context(), []string{"--remote", "--json"}) + var report doctorReport + if e := json.Unmarshal(out.Bytes(), &report); e != nil { + t.Fatal(e, out.String()) + } + failed := scenario == "unauthorized" || scenario == "database" || scenario == "worker" + if (err != nil) != failed || report.SchemaVersion != 1 { + t.Fatal(report, err) + } + if strings.Contains(out.String(), "do-not-print") || strings.Contains(out.String(), "private-test-secret") { + t.Fatal("secret leaked") + } + if _, err := os.Stat(filepath.Dir(absent)); !os.IsNotExist(err) { + t.Fatal("remote doctor touched local config", err) + } + }) + } +} + +func TestRemoteDoctorTimeoutIsBoundedAndRedacted(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() })) + defer server.Close() + var out bytes.Buffer + err := (cli{out: &out}).remoteDoctor(t.Context(), server.URL, "private-test-secret", 20*time.Millisecond, true) + if err == nil || strings.Contains(out.String(), server.URL) || strings.Contains(out.String(), "private-test-secret") { + t.Fatal(err, out.String()) + } + var report doctorReport + if err = json.Unmarshal(out.Bytes(), &report); err != nil || report.Checks[0].ID != "reachability" { + t.Fatal(report, err) + } +} diff --git a/cmd/ranjit/inspect.go b/cmd/ranjit/inspect.go index 248b874..5947a29 100644 --- a/cmd/ranjit/inspect.go +++ b/cmd/ranjit/inspect.go @@ -38,6 +38,7 @@ func (c cli) inspect(ctx context.Context, command string, args []string) error { return err } defer db.Close() + db.EnableWebhooks(cfg.WebhookURL) if command == "revoke" { if err = db.Revoke(ctx, f.Arg(0), time.Now()); err != nil { return err diff --git a/cmd/ranjit/main.go b/cmd/ranjit/main.go index 6a7ff38..aa7bd3e 100644 --- a/cmd/ranjit/main.go +++ b/cmd/ranjit/main.go @@ -14,9 +14,11 @@ import ( "syscall" "time" + "github.com/getcortexlabs/ranjit" "github.com/getcortexlabs/ranjit/internal/app" "github.com/getcortexlabs/ranjit/internal/config" "github.com/getcortexlabs/ranjit/internal/httpapi" + "github.com/getcortexlabs/ranjit/internal/monitor" "github.com/getcortexlabs/ranjit/internal/service" "github.com/getcortexlabs/ranjit/internal/store" "github.com/getcortexlabs/ranjit/internal/webhook" @@ -122,9 +124,22 @@ func run(logger *slog.Logger) error { } db.EnableWebhooks(cfg.WebhookURL) svc := service.New(db, source, cfg.BaseURL) - server := &http.Server{Addr: cfg.Addr, Handler: httpapi.New(svc, cfg.APIKey, logger, httpapi.APIKeys(cfg.APIKeys), httpapi.Diagnostics(func() any { - return map[string]any{"version": version, "certificates": cfg.Certificates(time.Now()), "unavailable_profiles": unavailable} - })), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} + syncMonitor := monitor.NewWorker(true, 50*time.Second) + hookMonitor := monitor.NewWorker(cfg.WebhookURL != "", 25*time.Second) + diagnostics := func(ctx context.Context) ranjit.Diagnostics { + now := time.Now().UTC() + op := &ranjit.OperationsStatus{ObservedAt: now, Database: "ready", Workers: map[string]ranjit.WorkerStatus{"sync": syncMonitor.Snapshot(now), "webhook": hookMonitor.Snapshot(now)}} + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + var err error + op.SyncQueue, op.WebhookQueue, err = db.Queues(ctx, now) + if err != nil { + op.Database = "unavailable" + } + return ranjit.Diagnostics{Version: version, Certificates: cfg.Certificates(now), UnavailableProfiles: unavailable, Operations: op} + } + server := &http.Server{Addr: cfg.Addr, Handler: httpapi.New(svc, cfg.APIKey, logger, httpapi.APIKeys(cfg.APIKeys), httpapi.Operations(diagnostics)), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} + listener, err := net.Listen("tcp", cfg.Addr) if err != nil { return err @@ -132,12 +147,19 @@ func run(logger *slog.Logger) error { workerCtx, cancelWorker := context.WithCancel(context.Background()) defer cancelWorker() workerDone := make(chan struct{}) - go func() { defer close(workerDone); worker.New(db, source, cfg.SyncInterval, logger).Run(workerCtx) }() + go func() { + defer close(workerDone) + w := worker.New(db, source, cfg.SyncInterval, logger) + w.Monitor = syncMonitor + w.Run(workerCtx) + }() webhookDone := make(chan struct{}) go func() { defer close(webhookDone) if cfg.WebhookURL != "" { - webhook.New(db, cfg.WebhookURL, cfg.WebhookSecret, logger).Run(workerCtx) + w := webhook.New(db, cfg.WebhookURL, cfg.WebhookSecret, logger) + w.Monitor = hookMonitor + w.Run(workerCtx) } }() defer func() { cancelWorker(); <-webhookDone }() diff --git a/cmd/ranjit/maintenance.go b/cmd/ranjit/maintenance.go index a624feb..cd8689a 100644 --- a/cmd/ranjit/maintenance.go +++ b/cmd/ranjit/maintenance.go @@ -42,6 +42,7 @@ func (c cli) maintenance(ctx context.Context, command string, args []string) err return err } defer db.Close() + db.EnableWebhooks(cfg.WebhookURL) switch command { case "backup": if err = db.Backup(ctx, f.Arg(0)); err != nil { diff --git a/diagnostics.go b/diagnostics.go new file mode 100644 index 0000000..40777af --- /dev/null +++ b/diagnostics.go @@ -0,0 +1,71 @@ +package ranjit + +import ( + "context" + "net/http" + "time" +) + +type CertificateStatus struct { + Profile string `json:"profile"` + Level string `json:"level"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + DaysRemaining int `json:"days_remaining"` +} + +type Diagnostics struct { + Version string `json:"version"` + Certificates []CertificateStatus `json:"certificates"` + UnavailableProfiles []string `json:"unavailable_profiles"` + Operations *OperationsStatus `json:"operations,omitempty"` +} + +type OperationsStatus struct { + ObservedAt time.Time `json:"observed_at"` + Database string `json:"database"` + Workers map[string]WorkerStatus `json:"workers"` + SyncQueue QueueStatus `json:"sync_queue"` + WebhookQueue QueueStatus `json:"webhook_queue"` +} + +type WorkerStatus struct { + State string `json:"state"` + Healthy bool `json:"healthy"` + LastStartedAt *time.Time `json:"last_started_at,omitempty"` + LastFinishedAt *time.Time `json:"last_finished_at,omitempty"` + LastSuccessAt *time.Time `json:"last_success_at,omitempty"` + Steps uint64 `json:"steps"` + Errors uint64 `json:"errors"` +} + +// QueueStatus is a database snapshot. Recent outcomes cover the last 24 hours; +// worker step counters are process-local and reset on restart. +type QueueStatus struct { + Counts map[string]int64 `json:"counts"` + OldestDueAt *time.Time `json:"oldest_due_at,omitempty"` + LastSucceededAt *time.Time `json:"last_succeeded_at,omitempty"` + LastFailedAt *time.Time `json:"last_failed_at,omitempty"` + RecentSucceeded int64 `json:"recent_succeeded"` + RecentFailed int64 `json:"recent_failed"` +} + +func (c *Client) Diagnostics(ctx context.Context) (Diagnostics, error) { + var out Diagnostics + err := c.do(ctx, http.MethodGet, "/v1/diagnostics", nil, &out) + return out, err +} + +func (c *Client) Ready(ctx context.Context) error { return c.healthStatus(ctx, "/readyz", "ready") } +func (c *Client) Health(ctx context.Context) error { return c.healthStatus(ctx, "/healthz", "ok") } +func (c *Client) healthStatus(ctx context.Context, path, want string) error { + var result struct { + Status string `json:"status"` + } + if err := c.do(ctx, http.MethodGet, path, nil, &result); err != nil { + return err + } + if result.Status != want { + return ErrInvalidResponse + } + return nil +} diff --git a/docs/backend-reliability.md b/docs/backend-reliability.md index 5549ceb..ae7ce9f 100644 --- a/docs/backend-reliability.md +++ b/docs/backend-reliability.md @@ -19,7 +19,7 @@ No sandbox, o mesmo link é recuperável enquanto estiver pendente e dentro dos Sem o cabeçalho, `client.Connect` mantém o comportamento anterior: cada chamada cria uma conexão. O SDK não repete POSTs automaticamente. A idempotência descrita aqui se aplica apenas à criação de conexões; importações e solicitações de sincronização têm suas próprias regras de deduplicação. -## Receber o resultado da sincronização +## Receber notificações Configure no serviço: @@ -30,7 +30,20 @@ RANJIT_WEBHOOK_SECRET=seu-segredo-aleatorio-com-pelo-menos-32-caracteres Use um segredo novo e diferente da chave da API. Para configuração pessoal em `config.json`, os campos são `webhook_url` e `webhook_secret`. Reinicie o serviço ao alterar essas opções. HTTP só é aceito em loopback para desenvolvimento; a URL não aceita credenciais, query ou fragmento. Docker exige um endereço alcançável de dentro do container. -O Ranjit envia `sync.succeeded` após publicar o lote completo e `sync.failed` quando o job falha definitivamente. Tentativas intermediárias não geram eventos. Cancelamento, importação de arquivo e alteração de consentimento não geram notificações nesta versão. Habilitar webhooks não cria eventos retroativos. `ranjit sync` também grava os eventos quando configurado; `ranjit serve` precisa estar em execução para entregá-los. +O Ranjit envia `sync.succeeded` após publicar o lote completo e `sync.failed` quando o job falha definitivamente. Tentativas intermediárias, cancelamento de job e importação de arquivo não geram eventos de sincronização. Habilitar webhooks não cria eventos retroativos. Os comandos locais também gravam os eventos quando configurados; `ranjit serve` precisa estar em execução para entregá-los. + +Mudanças efetivas de conexão geram eventos na mesma transação do estado: + +| Evento | Quando ocorre | `data.status` | +| --- | --- | --- | +| `connection.activated` | Criação com acesso direto ou aprovação do sandbox | `active` | +| `connection.denied` | Recusa no sandbox | `denied` | +| `connection.paused` | Pausa de uma conexão direta | `paused` | +| `connection.expired` | Prazo local vencido, detectado pelo worker | `expired` | +| `connection.renewed` | Renovação do acesso direto | `active` | +| `connection.revoked` | Revogação | `revoked` | + +Esses eventos não têm `job_id`. Incluem `connection_id`, `customer_id` e `status`, exceto a revogação, que conserva apenas `connection_id` e `status`. Uma pausa ou revogação já aplicada não gera outro evento; repetir a criação com a mesma chave também não. Uma nova renovação que estende o prazo é outra mudança efetiva. ```json { @@ -55,7 +68,7 @@ O [receptor Go executável](../examples/webhook/) mostra assinatura, limite de c A fila fica no mesmo SQLite/PostgreSQL, gravada na mesma transação dos dados. O envio ocorre em um worker separado, com timeout de dez segundos. Redirecionamentos não são seguidos. Qualquer resposta fora de `2xx` ou erro de transporte agenda outra tentativa: até oito, com intervalos de 10, 20, 40, 80, 160, 320 e 640 segundos. Reinícios recuperam tentativas interrompidas após o lease de 30 segundos. Tentativas reclamadas depois de uma queda também contam no limite. -A entrega pode se repetir e não tem garantia de ordem entre eventos. ID e corpo permanecem iguais; cada tentativa recebe uma assinatura com horário novo. A fila conserva registros por sete dias desde a última alteração. Trocar a URL não redireciona eventos antigos para o novo destinatário; eles ficam associados à URL original até expirar. Desabilitar webhooks pausa as entregas. Revogar uma conexão apaga seus registros de entrega, mas não desfaz uma requisição já enviada. +A entrega pode se repetir e não tem garantia de ordem entre eventos. ID e corpo permanecem iguais; cada tentativa recebe uma assinatura com horário novo. Consulte o estado atual da conexão pela API antes de tomar uma decisão que dependa dele. A fila conserva registros por sete dias desde a última alteração. Trocar a URL não redireciona eventos antigos para o novo destinatário; eles ficam associados à URL original até expirar. Desabilitar webhooks pausa as entregas. Revogar uma conexão apaga as entregas anteriores e deixa somente o aviso mínimo de revogação; uma requisição já enviada não pode ser desfeita. Restaurar um backup limpa a fila e não emite eventos de restauração. ```go deliveries, err := client.WebhookDeliveries(ctx, "", 50) diff --git a/docs/openapi.json b/docs/openapi.json index 9242e9d..b3757a2 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1120,34 +1120,14 @@ "/v1/diagnostics": { "get": { "operationId": "diagnostics", - "summary": "Local server version and certificate alerts without credential details", + "summary": "Server version, certificate alerts, database queues and worker progress", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "version": { - "type": "string" - }, - "certificates": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CertificateStatus" - } - }, - "unavailable_profiles": { - "type": [ - "array", - "null" - ], - "items": { - "type": "string" - } - } - } + "$ref": "#/components/schemas/Diagnostics" } } } @@ -1225,6 +1205,31 @@ } } } + }, + "/metrics": { + "get": { + "operationId": "metrics", + "summary": "Authenticated Prometheus worker and queue metrics", + "description": "Requires the installation API key. Fixed worker, queue, state and outcome labels; no customer or connection IDs. Step counters reset on restart; queue outcomes are retained database gauges. Unavailable storage returns 503 instead of zero values.", + "responses": { + "200": { + "description": "Prometheus text exposition", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "503": { + "description": "Metrics unavailable because storage could not be read" + } + } + } } }, "components": { @@ -1905,9 +1910,7 @@ "WebhookData": { "type": "object", "required": [ - "job_id", - "connection_id", - "customer_id" + "connection_id" ], "properties": { "job_id": { @@ -1921,8 +1924,19 @@ }, "error_code": { "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "active", + "denied", + "paused", + "expired", + "revoked" + ] } - } + }, + "description": "Sync events require job_id and customer_id. Connection events require status and customer_id, except connection.revoked, which only carries connection_id and status. Delivery order is not guaranteed; query the current connection state." }, "WebhookEvent": { "type": "object", @@ -1940,7 +1954,13 @@ "type": "string", "enum": [ "sync.succeeded", - "sync.failed" + "sync.failed", + "connection.activated", + "connection.denied", + "connection.paused", + "connection.expired", + "connection.renewed", + "connection.revoked" ] }, "created_at": { @@ -2016,6 +2036,168 @@ "type": "string" } } + }, + "WorkerStatus": { + "type": "object", + "required": [ + "state", + "healthy", + "steps", + "errors" + ], + "properties": { + "state": { + "type": "string", + "enum": [ + "disabled", + "starting", + "running", + "idle", + "stalled", + "error", + "stopped" + ] + }, + "healthy": { + "type": "boolean" + }, + "steps": { + "type": "integer", + "minimum": 0 + }, + "errors": { + "type": "integer", + "minimum": 0 + }, + "last_started_at": { + "type": "string", + "format": "date-time" + }, + "last_finished_at": { + "type": "string", + "format": "date-time" + }, + "last_success_at": { + "type": "string", + "format": "date-time" + } + } + }, + "QueueStatus": { + "type": "object", + "required": [ + "counts", + "recent_succeeded", + "recent_failed" + ], + "properties": { + "counts": { + "type": "object", + "additionalProperties": { + "type": "integer", + "minimum": 0 + } + }, + "recent_succeeded": { + "type": "integer", + "minimum": 0 + }, + "recent_failed": { + "type": "integer", + "minimum": 0 + }, + "oldest_due_at": { + "type": "string", + "format": "date-time" + }, + "last_succeeded_at": { + "type": "string", + "format": "date-time" + }, + "last_failed_at": { + "type": "string", + "format": "date-time" + } + }, + "description": "Database snapshot. Recent outcomes cover 24 hours; retention can remove older records. Oldest due excludes scheduled work in the future." + }, + "OperationsStatus": { + "type": "object", + "required": [ + "observed_at", + "database", + "workers", + "sync_queue", + "webhook_queue" + ], + "properties": { + "observed_at": { + "type": "string", + "format": "date-time" + }, + "database": { + "type": "string", + "enum": [ + "ready", + "unavailable" + ] + }, + "workers": { + "type": "object", + "required": [ + "sync", + "webhook" + ], + "properties": { + "sync": { + "$ref": "#/components/schemas/WorkerStatus" + }, + "webhook": { + "$ref": "#/components/schemas/WorkerStatus" + } + } + }, + "sync_queue": { + "$ref": "#/components/schemas/QueueStatus" + }, + "webhook_queue": { + "$ref": "#/components/schemas/QueueStatus" + } + } + }, + "Diagnostics": { + "type": "object", + "properties": { + "version": { + "type": "string" + }, + "certificates": { + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/components/schemas/CertificateStatus" + } + }, + "unavailable_profiles": { + "type": [ + "array", + "null" + ], + "items": { + "type": "string" + } + }, + "operations": { + "$ref": "#/components/schemas/OperationsStatus" + } + }, + "required": [ + "version", + "certificates", + "unavailable_profiles" + ] } }, "responses": { diff --git a/docs/operations.md b/docs/operations.md index fbb6b85..c2c27e2 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -14,7 +14,7 @@ O servidor pode usar o sandbox local ou os conectores diretos Efí, Inter, Sicoo | `RANJIT_SYNC_INTERVAL` | `1h` | Intervalo do agendador; mínimo `1m` | | `RANJIT_DATABASE_URL` | — | PostgreSQL em vez de SQLite | | `RANJIT_PROFILES_JSON` | — | Perfis em JSON; `[]` habilita apenas arquivos | -| `RANJIT_WEBHOOK_URL` | — | Endpoint para resultados da sincronização | +| `RANJIT_WEBHOOK_URL` | — | Endpoint para sincronizações e eventos das conexões | | `RANJIT_WEBHOOK_SECRET` | — | Segredo de assinatura, mínimo 32 caracteres | | `RANJIT_API_KEY_PREVIOUS` | — | Chave anterior durante uma migração | | `RANJIT_API_KEY_PREVIOUS_EXPIRES_AT` | — | Expiração obrigatória da chave anterior em RFC3339 | @@ -37,6 +37,25 @@ Para restaurar: `ranjit service stop` (ou encerre `serve`/`ui`) e `ranjit restor Revogação e expiração de consentimento simulado removem as linhas dos dados financeiros. Em conexões diretas, expiração e pausa preservam o histórico, mas não apagam retroativamente backups ou garantem eliminação de bytes antigos no disco. A política de retenção também deve considerar os metadados das conexões e o histórico de jobs, que crescem nesta versão. +## Diagnóstico remoto e métricas + +Configure `RANJIT_URL` e `RANJIT_API_KEY` no ambiente do backend: + +```sh +ranjit doctor --remote +ranjit doctor --remote --json --timeout 10s +``` + +Esse modo não lê `config.json`, não abre banco local e não chama o banco financeiro. Verifica conectividade, chave, prontidão SQL, versão e progresso dos workers pela API. `--url` substitui a URL e também seleciona o modo remoto. O timeout vale para o diagnóstico inteiro, até um minuto. + +O JSON tem `schema_version: 1`, `status`, `server_version` quando disponível e `checks` com `id`, `status`, `message` e `action` opcional. Avisos retornam código de saída 0; falhas retornam 1. URL, segredos, certificados e respostas brutas não são impressos. Instalações antigas sem métricas geram um aviso de compatibilidade. + +`GET /v1/diagnostics` exige autenticação e inclui `operations`: disponibilidade do banco, contagens das filas, trabalho vencido mais antigo, resultados das últimas 24 horas e atividade dos workers. `idle` é saudável. `running` indica trabalho dentro do prazo; `stalled` indica ausência de progresso. A medição acompanha o início e o fim real de cada etapa. Um job bancário que falha não implica que o worker deixou de funcionar: confira também os resultados da fila. + +`GET /metrics` usa a mesma autenticação Bearer e retorna texto compatível com Prometheus. Configure `metrics_path: /metrics` e `authorization.credentials_file` no scraper. Não publique a chave em labels ou na URL. As séries `ranjit_worker_healthy`, `ranjit_worker_steps_total`, `ranjit_worker_errors_total`, `ranjit_queue_items`, `ranjit_queue_oldest_due_seconds`, `ranjit_queue_recent_outcomes` e `ranjit_queue_last_outcome_timestamp_seconds` usam apenas labels fixos de worker, fila, estado e resultado. Não expõem clientes, conexões, contas, perfis ou credenciais. + +Contadores de worker reiniciam com o processo. Resultados recentes são gauges do banco, não contadores cumulativos de eventos; as entregas também seguem a retenção de sete dias. Webhooks consideram somente o destino configurado. Sem banco disponível, `/metrics` retorna 503 em vez de informar filas vazias. Não há chamadas bancárias durante a coleta. + ## Saúde e encerramento `/healthz` verifica o processo. `/readyz` verifica também a conexão SQL, sem afirmar que o provedor ou o worker estão saudáveis. Os logs são JSON e incluem IDs de requisição ou de job e códigos de erro. Não incluem URL, query, headers, corpos ou mensagens brutas do provedor. Proxies precisam de configuração equivalente para não registrar os tokens dos links. diff --git a/docs/release-notes.md b/docs/release-notes.md index 3f5e233..f2cc2a1 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,12 +1,18 @@ -Integrações de backend com recuperação de pedidos, notificações assinadas e troca de chaves. +Integração de backend com instalação demonstrável, recuperação de pedidos, notificações assinadas e diagnóstico remoto. - `Idempotency-Key` e `client.ConnectWithKey`: pedidos repetidos recuperam a mesma conexão por 24 horas, inclusive depois de reiniciar. - Webhooks `sync.succeeded` e `sync.failed` com HMAC-SHA256, fila persistente, oito tentativas automáticas e reenvio pela API/SDK. - Rotação da chave com sobreposição: `ranjit key rotate --grace 24h` na configuração pessoal; chave anterior e expiração por ambiente em servidores. - Receptor Go com verificação de assinatura e caixa de entrada SQLite que deduplica eventos. +- Quickstart em um comando: Ranjit, backend Go e receptor com chaves separadas, dados persistentes e verificação de CSV e sandbox. +- Eventos de ativação, recusa, pausa, expiração, renovação e revogação na mesma transação do estado. Revogar limpa eventos anteriores e deixa um aviso mínimo. +- `ranjit doctor --remote --json` verifica API, autenticação, banco e workers sem configuração local. +- Métricas autenticadas em `/metrics` e diagnóstico das filas, com distinção entre worker ocioso e sem progresso. +- Iteradores no SDK Go para buscar páginas sob demanda; retentativas opcionais de GET com limite total, cancelamento e `Retry-After`. +- Testes de atualização a partir do binário e da imagem publicados da v0.3.0, incluindo SQLite/PostgreSQL, recuperação de jobs, backup, restauração e rollback. - Contrato HTTP, exemplos e documentação de instalação atualizados. -As novas tabelas são criadas automaticamente no SQLite ou PostgreSQL existente. Faça backup antes de atualizar; as migrações não têm downgrade automático. Webhooks são opcionais, sem eventos retroativos. Pedidos sem `Idempotency-Key` mantêm o comportamento anterior. +As novas tabelas e a migração dos eventos são aplicadas automaticamente no SQLite ou PostgreSQL existente. Faça backup antes de atualizar; as migrações não têm downgrade automático. Webhooks são opcionais, sem eventos retroativos. Pedidos sem `Idempotency-Key` mantêm o comportamento anterior. Retentativas do SDK continuam desabilitadas por padrão e nunca repetem mutações automaticamente. Os conectores bancários continuam experimentais. A validação com uma conta real depende de acesso habilitado à API do banco. A integração com dados simulados e importação de extratos funciona sem essas credenciais. diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 0000000..e2bef40 --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,37 @@ +# Publicar uma versão + +A v0.4.0 reúne as tarefas do [milestone](https://github.com/getcortexlabs/ranjit/milestone/1). PRs intermediários não geram versões. A publicação começa ao enviar a tag, depois do merge e dos checks do commit final. + +## Antes da tag + +- CI completo: Go 1.26/1.27, race detector, vet, SQLite/PostgreSQL, macOS/Windows, navegador, container e quickstart. +- `scripts/upgrade_smoke.py`: baixa o binário real da v0.3.0, verifica checksum, importa dados sintéticos e valida migração, recuperação de job pendente, reinício e rollback com o backup anterior. PostgreSQL usa um banco temporário próprio; o banco informado em `RANJIT_TEST_POSTGRES_URL` não é modificado. +- `scripts/container_upgrade.sh IMAGEM`: cria dados com a imagem publicada da v0.3.0 e compara as transações depois de executar a candidata e reiniciá-la. +- `install.sh`, `compose.quick.yaml`, SDK nos exemplos e notas de versão apontam para a mesma versão. +- Faça backup da instalação que será atualizada. Não existe migração reversa automática. + +O workflow repete os testes de compatibilidade e o quickstart antes de publicar. Compila seis arquivos, verifica seus checksums e instala o binário nativo em uma pasta vazia. Antes da publicação, somente o transporte HTTPS do instalador é substituído por arquivos locais; o arquivo e o executável testados são os da candidata. + +## Publicação e conferência + +1. Envie uma única tag `v0.4.0` no commit aprovado de `main`. +2. O workflow prepara uma release em rascunho, com binários, imagens para instalação offline, instalador, Compose e checksums. +3. Publica as imagens da versão e testa downloads anônimos em amd64 e arm64 usando configuração Docker vazia. +4. Publica a release e baixa os arquivos públicos para conferir os checksums, instalar o binário por HTTPS, testar o primeiro uso e resolver o SDK pelo módulo Go. +5. Somente depois dessas verificações atualiza `ghcr.io/getcortexlabs/ranjit:latest`. + +Se uma etapa falhar, confira o workflow e os artefatos antes de retomar. Não recrie a tag nem substitua artefatos de uma release que já foi anunciada. Uma falha antes da publicação mantém o rascunho; uma falha na verificação posterior exige investigar a distribuição antes de promover o catálogo. + +Para conferir uma publicação novamente: + +```sh +python3 scripts/verify_release.py --version v0.4.0 --published +``` + +Registre na release o resultado do workflow, o commit da tag e os testes de distribuição. A receita do Orbit deve apontar para `ghcr.io/getcortexlabs/ranjit:v0.4.0` somente após a imagem estar pública e as duas arquiteturas passarem. O catálogo não precisa das credenciais bancárias nem de uma assinatura paga. + +## Voltar à versão anterior + +Pare o serviço. Guarde a instalação com problema para análise e recupere o binário **e o backup feito pela versão anterior**, além da configuração correspondente. Não execute a v0.3.0 sobre o banco já migrado. No PostgreSQL, restaure o dump em um banco novo e altere a conexão do serviço; mantenha a instalação atual isolada até conferir os dados. + +`ranjit restore` na versão atual valida o SQLite, guarda uma cópia do banco substituído, cancela trabalhos antigos, limpa entregas de webhook e deixa conexões diretas pausadas. Não use esse comando como downgrade de schema. Retome conexões restauradas explicitamente, depois de conferir os perfis e as credenciais. diff --git a/docs/sdk.md b/docs/sdk.md new file mode 100644 index 0000000..1a257a5 --- /dev/null +++ b/docs/sdk.md @@ -0,0 +1,63 @@ +# SDK Go + +```sh +go get github.com/getcortexlabs/ranjit@v0.4.0 +``` + +Configure `RANJIT_URL` e `RANJIT_API_KEY` no ambiente do backend e crie um cliente com `ranjit.NewClientFromEnv()`. Também é possível usar `ranjit.NewClient(url, key)`. O SDK chama o serviço HTTP; não abre o banco nem executa os workers dentro do seu aplicativo. + +## Paginar + +Os métodos `Connections`, `Accounts`, `Transactions` e `SearchTransactions` retornam uma página e `NextCursor`. Para percorrer todas as páginas sem guardar tudo em memória: + +```go +for transaction, err := range client.IterSearchTransactions(ctx, ranjit.TransactionFilter{ + CustomerID: authenticatedUserID, + Limit: 100, +}) { + if err != nil { + return err + } + if err := saveTransaction(transaction); err != nil { + return err + } +} +``` + +Há também `IterConnections(ctx, customerID, limit)`, `IterAccounts(ctx, connectionID, limit)` e `IterTransactions(ctx, accountID, limit)`. Eles só buscam páginas durante a iteração. `break` interrompe sem buscar a próxima; cancelamento do contexto interrompe chamadas e esperas. Um cursor repetido pelo servidor retorna `ErrInvalidResponse` para evitar um laço infinito. Os filtros da consulta permanecem iguais entre páginas. + +A paginação não é uma fotografia imutável do banco: sincronizações concorrentes podem alterar o conjunto. Use os IDs estáveis ao gravar transações no seu aplicativo. + +## Repetir consultas após falhas temporárias + +Por padrão, cada chamada faz uma tentativa. Configure antes de compartilhar o cliente entre goroutines: + +```go +client.ReadRetries = ranjit.RetryPolicy{ + MaxAttempts: 3, + MaxElapsedTime: 10 * time.Second, + BaseDelay: 200 * time.Millisecond, + MaxDelay: 2 * time.Second, +} +``` + +A política vale apenas para GET. Repete erros transitórios de transporte e HTTP 408, 429, 500, 502, 503 e 504. O intervalo cresce com variação aleatória e respeita `Retry-After` em segundos ou data HTTP. Se a espera pedida pelo servidor não couber no prazo restante, retorna a última falha sem antecipar a chamada. O prazo do contexto, o orçamento total e `HTTPClient.Timeout` continuam valendo. São permitidas até dez tentativas e cinco minutos de orçamento total. + +POST e DELETE nunca são repetidos automaticamente. Para recuperar a criação de uma conexão após perder a resposta, reaproveite sua chave de operação com `ConnectWithKey`, conforme o [guia de idempotência](backend-reliability.md). + +## Tratar erros + +```go +if errors.Is(err, ranjit.ErrUnauthorized) { + // Atualize a chave configurada no backend. +} +var problem *ranjit.APIError +if errors.As(err, &problem) { + log.Printf("Ranjit status=%d code=%s request_id=%s", + problem.StatusCode, problem.Code, problem.RequestID) +} +``` + +`APIError` preserva status HTTP, código e ID da requisição. `errors.Is` reconhece também `ErrRateLimited`, `ErrNotFound`, `ErrConflict`, `ErrInvalid`, `ErrConsent`, os erros de provedor, idempotência e reenvio de webhook. Respostas maiores que 1 MiB retornam `ErrResponseTooLarge`; JSON inválido ou conteúdo extra retornam `ErrInvalidResponse`. Erros de transporte podem ser inspecionados com `errors.As` e `errors.Is`. + +`client.Health`, `client.Ready` e `client.Diagnostics` permitem consultar a saúde da instalação sem acesso ao banco. Não use disponibilidade do processo como confirmação de que a API bancária está acessível. diff --git a/docs/server.md b/docs/server.md index be06bb1..8b25cc7 100644 --- a/docs/server.md +++ b/docs/server.md @@ -2,8 +2,12 @@ O Ranjit é um serviço que sua aplicação chama por HTTP. O SDK Go cuida dessas chamadas. Você pode executar o binário junto do backend ou instalar o container na sua hospedagem. Docker é uma forma de instalação, não uma dependência do SDK. +O [guia do SDK](sdk.md) cobre paginação, retentativas e erros. `ranjit doctor --remote --json` verifica a instalação usando somente `RANJIT_URL` e `RANJIT_API_KEY`. Diagnósticos e métricas estão descritos em [operação](operations.md). + ## Desenvolvimento local +O [quickstart completo](../examples/quickstart/) sobe Ranjit, backend Go e receptor de webhooks com `./scripts/quickstart.sh`. Ele gera as chaves e verifica importação e sandbox. Para trabalhar sem Docker, siga com o binário abaixo. + Depois de instalar o binário: ```sh @@ -102,4 +106,4 @@ Antes de atualizar a imagem, faça um backup do banco. As migrações são aplic ## Webhooks e continuidade da integração -Você pode receber `sync.succeeded` e `sync.failed` no seu backend e trocar a chave da API com um prazo para atualizar os consumidores. Configure as variáveis pelo gerenciador de segredos da hospedagem e siga o [guia de integração confiável](backend-reliability.md). A fila de entrega usa o mesmo PostgreSQL/SQLite, sem Redis nem outro serviço. O receptor precisa estar acessível pelo Ranjit e salvar os eventos por ID antes de confirmar recebimento. +Você pode receber eventos de sincronização e de estado da conexão no seu backend e trocar a chave da API com um prazo para atualizar os consumidores. Configure as variáveis pelo gerenciador de segredos da hospedagem e siga o [guia de integração confiável](backend-reliability.md). A fila de entrega usa o mesmo PostgreSQL/SQLite, sem Redis nem outro serviço. O receptor precisa estar acessível pelo Ranjit e salvar os eventos por ID antes de confirmar recebimento. diff --git a/examples/backend/README.md b/examples/backend/README.md index c79cb5e..c0f1dcd 100644 --- a/examples/backend/README.md +++ b/examples/backend/README.md @@ -2,6 +2,8 @@ Exemplo de uma aplicação que usa o Ranjit como serviço. Importa um CSV e consulta transações para um cliente fixo, sem credenciais bancárias. +Para subir este backend, o serviço e o receptor de webhooks juntos, execute `./scripts/quickstart.sh` na raiz. O [quickstart](../quickstart/) gera os segredos e testa o fluxo. Para rodar sem Docker, siga abaixo. + 1. Instale o Ranjit e execute `ranjit serve`. 2. Em outro terminal, obtenha a chave com `ranjit key` e configure `RANJIT_API_KEY` no ambiente do exemplo. 3. Na raiz do repositório: @@ -29,3 +31,5 @@ Repita a consulta com `?cursor=NEXT_CURSOR` enquanto a resposta tiver `next_curs O token do exemplo é diferente da chave do Ranjit. O handler determina `customer_id` no servidor; campos enviados pelo cliente não substituem essa identidade. Em uma aplicação com vários usuários, substitua o cliente fixo pelo usuário autenticado da sua sessão e confira a propriedade dos IDs antes de consultar contas ou conexões. O exemplo escuta apenas em loopback e não implementa cadastro, login ou distribuição de tokens. Para hospedagem, o código do SDK continua igual: altere `RANJIT_URL` e configure a chave como segredo do backend. Consulte [instalação em servidor](../../docs/server.md). + +`APP_ADDR` altera o endereço de escuta; o padrão é `127.0.0.1:3000`. `GET /healthz` verifica a prontidão do serviço sem retornar dados financeiros. O exemplo configura até três tentativas para consultas GET, com dez segundos de orçamento; importações não são repetidas automaticamente. diff --git a/examples/backend/main.go b/examples/backend/main.go index 28af2ee..afc13d7 100644 --- a/examples/backend/main.go +++ b/examples/backend/main.go @@ -3,6 +3,7 @@ package main import ( + "context" "crypto/subtle" "encoding/json" "errors" @@ -19,12 +20,17 @@ func main() { if err != nil { log.Fatal(err) } + client.ReadRetries = ranjit.RetryPolicy{MaxAttempts: 3, MaxElapsedTime: 10 * time.Second} token := os.Getenv("APP_TOKEN") if len(token) < 32 || token == os.Getenv("RANJIT_API_KEY") { log.Fatal("APP_TOKEN must be a separate secret of at least 32 characters") } - server := &http.Server{Addr: "127.0.0.1:3000", Handler: routes(client, token), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: time.Minute} - log.Print("example backend listening on http://127.0.0.1:3000") + addr := os.Getenv("APP_ADDR") + if addr == "" { + addr = "127.0.0.1:3000" + } + server := &http.Server{Addr: addr, Handler: routes(client, token), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: time.Minute} + log.Print("example backend listening on ", addr) log.Fatal(server.ListenAndServe()) } @@ -45,6 +51,16 @@ func routes(client *ranjit.Client, token string) http.Handler { }) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") + if r.Method == http.MethodGet && r.URL.Path == "/healthz" { + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + if err := client.Ready(ctx); err != nil { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusNoContent) + return + } if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+token)) != 1 { http.Error(w, "unauthorized", http.StatusUnauthorized) return diff --git a/examples/quickstart/Dockerfile b/examples/quickstart/Dockerfile new file mode 100644 index 0000000..a3c20c4 --- /dev/null +++ b/examples/quickstart/Dockerfile @@ -0,0 +1,25 @@ +FROM golang:1.27.3-bookworm AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 go build -trimpath -o /quickstart ./examples/quickstart \ + && CGO_ENABLED=0 go build -trimpath -o /backend ./examples/backend \ + && CGO_ENABLED=0 go build -trimpath -o /receiver ./examples/webhook \ + && mkdir /data && chown 65532:65532 /data + +FROM scratch AS tools +COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt +COPY --from=build /quickstart /quickstart +COPY --from=build --chown=65532:65532 /data /data +USER 65532:65532 +ENTRYPOINT ["/quickstart"] + +FROM tools AS backend +COPY --from=build /backend /backend +ENTRYPOINT ["/backend"] + +FROM tools AS receiver +COPY --from=build /receiver /receiver +WORKDIR /data +ENTRYPOINT ["/receiver"] diff --git a/examples/quickstart/README.md b/examples/quickstart/README.md new file mode 100644 index 0000000..8b9d244 --- /dev/null +++ b/examples/quickstart/README.md @@ -0,0 +1,40 @@ +# Backend completo em um comando + +Na raiz do repositório, com Docker e Compose v2 instalados: + +```sh +./scripts/quickstart.sh +``` + +O comando compila e sobe o Ranjit, um backend Go e um receptor de webhooks. Cria três segredos diferentes em `examples/quickstart/.env`, com permissão `0600`, e verifica o fluxo inteiro: CSV pelo backend, autorização no sandbox, sincronização, paginação pelo SDK e recebimento das notificações assinadas. Não precisa de Go instalado nem de credenciais bancárias. A primeira execução demora mais por causa da compilação. + +| Serviço | Endereço | Autenticação | +| --- | --- | --- | +| Backend de exemplo | `http://localhost:3000` | `APP_TOKEN` | +| API do Ranjit | `http://localhost:8080` | `RANJIT_API_KEY` | +| Receptor | loopback do container, porta 8081 | Assinatura com `RANJIT_WEBHOOK_SECRET` | + +As duas portas publicadas escutam apenas no computador local. Os serviços compartilham a rede do container Ranjit para que o webhook de desenvolvimento use HTTP em loopback. Em produção, configure o endpoint HTTPS do seu backend e a rede da hospedagem conforme o [guia de servidor](../../docs/server.md). + +Para consultar o backend: + +```sh +set -a +. examples/quickstart/.env +set +a +curl -fsS http://localhost:3000/transactions \ + -H "Authorization: Bearer $APP_TOKEN" +``` + +O backend usa um cliente fixo, `example-customer`. Adapte a autenticação ao seu aplicativo e derive o cliente da sessão no servidor. A chave do Ranjit não deve chegar ao navegador. O receptor confirma a entrega somente depois de gravar o evento no SQLite, deduplicando pelo ID. + +```sh +./scripts/quickstart.sh verify # repete a verificação na instalação rodando +./scripts/quickstart.sh stop # encerra os containers e mantém os volumes +./scripts/quickstart.sh # recria os containers usando os mesmos dados +./scripts/quickstart.sh reset # apaga os dois volumes de demonstração +``` + +Os segredos são preservados ao parar, reiniciar ou resetar. Os volumes `ranjit-quickstart_data` e `ranjit-quickstart_inbox` guardam, respectivamente, os dados do Ranjit e os eventos recebidos. Repetir o exemplo não duplica o CSV nem uma conexão de sandbox ainda ativa. Se modificar ou revogar manualmente a conexão da demonstração, use `reset` antes de repetir o teste. + +Se as portas 3000 ou 8080 já estiverem ocupadas, encerre a outra instalação antes de iniciar. Para trabalhar sem Docker, use o [mesmo backend Go](../backend/) com o binário do Ranjit e o [receptor Go](../webhook/). diff --git a/examples/quickstart/compose.yaml b/examples/quickstart/compose.yaml new file mode 100644 index 0000000..5f6931d --- /dev/null +++ b/examples/quickstart/compose.yaml @@ -0,0 +1,73 @@ +name: ranjit-quickstart +services: + ranjit: + build: + context: ../.. + ports: + - "127.0.0.1:8080:8080" + - "127.0.0.1:3000:3000" + environment: + RANJIT_PROVIDER: sandbox + RANJIT_API_KEY: ${RANJIT_API_KEY:?Run scripts/quickstart.sh first} + RANJIT_BASE_URL: http://localhost:8080 + RANJIT_WEBHOOK_URL: http://127.0.0.1:8081/webhooks/ranjit + RANJIT_WEBHOOK_SECRET: ${RANJIT_WEBHOOK_SECRET:?Missing webhook secret} + volumes: + - data:/data + healthcheck: + test: [CMD, /ranjit, healthcheck] + interval: 2s + timeout: 3s + retries: 30 + backend: + build: + context: ../.. + dockerfile: examples/quickstart/Dockerfile + target: backend + # Sharing the demo's network keeps unsigned HTTP traffic on loopback. + network_mode: service:ranjit + depends_on: + ranjit: + condition: service_healthy + environment: + APP_ADDR: 0.0.0.0:3000 + APP_TOKEN: ${APP_TOKEN:?Missing backend token} + RANJIT_URL: http://127.0.0.1:8080 + RANJIT_API_KEY: ${RANJIT_API_KEY} + healthcheck: + test: [CMD, /quickstart, health, http://127.0.0.1:3000/healthz] + interval: 2s + timeout: 3s + retries: 30 + receiver: + build: + context: ../.. + dockerfile: examples/quickstart/Dockerfile + target: receiver + network_mode: service:ranjit + depends_on: + ranjit: + condition: service_healthy + environment: + RANJIT_WEBHOOK_SECRET: ${RANJIT_WEBHOOK_SECRET} + volumes: + - inbox:/data + healthcheck: + test: [CMD, /quickstart, health, http://127.0.0.1:8081/healthz] + interval: 2s + timeout: 3s + retries: 30 + verify: + image: ranjit-quickstart-tools + profiles: [tools] + network_mode: service:ranjit + environment: + APP_TOKEN: ${APP_TOKEN} + RANJIT_URL: http://127.0.0.1:8080 + RANJIT_API_KEY: ${RANJIT_API_KEY} + volumes: + - inbox:/inbox:ro + command: [verify] +volumes: + data: + inbox: diff --git a/examples/quickstart/main.go b/examples/quickstart/main.go new file mode 100644 index 0000000..1c227f3 --- /dev/null +++ b/examples/quickstart/main.go @@ -0,0 +1,209 @@ +// Local demo tooling. No bank credentials or financial data leave this stack. +package main + +import ( + "context" + "crypto/rand" + "database/sql" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" + + "github.com/getcortexlabs/ranjit" + _ "modernc.org/sqlite" +) + +var httpClient = &http.Client{Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(args []string) error { + if len(args) == 0 { + return errors.New("expected init, health or verify") + } + switch args[0] { + case "init": + file, err := os.OpenFile("/config/.env", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if errors.Is(err, os.ErrExist) { + return nil + } + if err != nil { + return err + } + _, err = fmt.Fprintf(file, "RANJIT_API_KEY=%s\nAPP_TOKEN=%s\nRANJIT_WEBHOOK_SECRET=%s\n", rand.Text()+rand.Text(), rand.Text()+rand.Text(), rand.Text()+rand.Text()) + return errors.Join(err, file.Close()) + case "health": + if len(args) != 2 { + return errors.New("health requires a URL") + } + resp, err := httpClient.Get(args[1]) + if err != nil { + return errors.New("service not reachable") + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("service returned %d", resp.StatusCode) + } + return nil + case "verify": + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + return verify(ctx) + default: + return errors.New("unknown command") + } +} + +func verify(ctx context.Context) error { + client, err := ranjit.NewClientFromEnv() + if err != nil { + return err + } + client.ReadRetries = ranjit.RetryPolicy{MaxAttempts: 3, MaxElapsedTime: 5 * time.Second} + // Stable external IDs make rerunning the demo safe, including after restart. + statement := "date,description,amount,id\n2026-11-01,Demo deposit,100.00,quickstart-deposit\n2026-11-02,Demo purchase,-12.50,quickstart-purchase\n" + var imported ranjit.ImportResult + if err := backend(ctx, "POST", "/statements", statement, &imported); err != nil { + return err + } + var page ranjit.Page[ranjit.Transaction] + if err := backend(ctx, "GET", "/transactions", "", &page); err != nil { + return err + } + if imported.Transactions != 2 || len(page.Data) != 2 { + return errors.New("CSV import did not produce the two expected transactions") + } + fmt.Println("CSV imported through the Go backend; repeated imports keep the same transactions.") + // Reuse the demo connection beyond the idempotency window, too. + var connection ranjit.Connection + for c, err := range client.IterConnections(ctx, "quickstart-sandbox", 20) { + if err != nil { + return err + } + if c.Status == "active" { + connection = c + break + } + } + if connection.ID == "" { + result, err := client.ConnectWithKey(ctx, ranjit.ConnectRequest{CustomerID: "quickstart-sandbox", InstitutionID: "sandbox-bank"}, "quickstart-sandbox-v1") + if err != nil { + return err + } + connection = result.Connection + if result.AuthorizationURL != "" { + u, err := url.Parse(result.AuthorizationURL) + if err != nil || u.Host != "localhost:8080" || u.Scheme != "http" || u.Path != "/sandbox/authorize" { + return errors.New("unexpected sandbox authorization URL") + } + form := url.Values{"token": {u.Query().Get("token")}, "decision": {"approve"}} + req, err := http.NewRequestWithContext(ctx, "POST", "http://127.0.0.1:8080/sandbox/authorize", strings.NewReader(form.Encode())) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := httpClient.Do(req) + if err != nil { + return errors.New("sandbox authorization unreachable") + } + resp.Body.Close() + if resp.StatusCode != 200 { + return fmt.Errorf("sandbox authorization returned %d", resp.StatusCode) + } + } + } + if err := wait(ctx, func() (bool, error) { + status, err := client.Status(ctx, connection.ID) + return status.Accounts == 2 && status.Transactions == 4, err + }); err != nil { + return err + } + count := 0 + for _, err := range client.IterSearchTransactions(ctx, ranjit.TransactionFilter{CustomerID: "quickstart-sandbox", Limit: 1}) { + if err != nil { + return err + } + count++ + } + if count != 4 { + return fmt.Errorf("sandbox pagination returned %d transactions, want 4", count) + } + fmt.Println("Sandbox authorized and synced; the SDK read all four transactions across pages.") + db, err := sql.Open("sqlite", "file:/inbox/webhook-inbox.db?mode=ro&_pragma=busy_timeout(5000)") + if err != nil { + return err + } + defer db.Close() + if err := wait(ctx, func() (bool, error) { + rows, err := db.QueryContext(ctx, `SELECT payload FROM webhook_inbox`) + if err != nil { + return false, err + } + defer rows.Close() + found := map[string]bool{} + for rows.Next() { + var raw string + var event ranjit.WebhookEvent + if err := rows.Scan(&raw); err != nil { + return false, err + } + if err := json.Unmarshal([]byte(raw), &event); err != nil { + return false, err + } + if event.Data.ConnectionID == connection.ID { + found[event.Type] = true + } + } + return found["connection.activated"] && found["sync.succeeded"], rows.Err() + }); err != nil { + return err + } + fmt.Println("Signed lifecycle and sync webhooks committed to the receiver inbox.") + fmt.Println("Ready: backend http://localhost:3000 · Ranjit http://localhost:8080") + return nil +} + +func backend(ctx context.Context, method, path, body string, out any) error { + req, err := http.NewRequestWithContext(ctx, method, "http://127.0.0.1:3000"+path, strings.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+os.Getenv("APP_TOKEN")) + req.Header.Set("Content-Type", "text/csv") + resp, err := httpClient.Do(req) + if err != nil { + return errors.New("demo backend unreachable") + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + return fmt.Errorf("demo backend returned %d", resp.StatusCode) + } + return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out) +} + +func wait(ctx context.Context, check func() (bool, error)) error { + ticker := time.NewTicker(250 * time.Millisecond) + defer ticker.Stop() + for { + ok, err := check() + if err != nil || ok { + return err + } + select { + case <-ctx.Done(): + return fmt.Errorf("demo verification timed out: %w", ctx.Err()) + case <-ticker.C: + } + } +} diff --git a/examples/webhook/README.md b/examples/webhook/README.md index 0c11cf6..b0e652a 100644 --- a/examples/webhook/README.md +++ b/examples/webhook/README.md @@ -15,7 +15,7 @@ set +a go run ./examples/webhook ``` -Em outro terminal, rode `make run`. Em um terceiro, `make example` cria uma conexão no sandbox. Abra o link exibido e aprove os dados fictícios. A primeira sincronização enviará `sync.succeeded` para o exemplo. Não é necessário habilitar um banco para esse teste. +Em outro terminal, rode `make run`. Em um terceiro, `make example` cria uma conexão no sandbox. Abra o link exibido e aprove os dados fictícios. O receptor receberá `connection.activated` e `sync.succeeded`. Não é necessário habilitar um banco para esse teste. Para subir os serviços e verificar o fluxo automaticamente, use o [quickstart](../quickstart/). O endpoint pode receber o mesmo ID várias vezes, inclusive depois de responder com sucesso se a resposta se perder. A assinatura muda a cada tentativa; o ID e o corpo do evento permanecem iguais. O exemplo só recebe eventos, não consulta nem altera dados financeiros. Use `client.Accounts` e `client.Transactions` ao consumir a caixa de entrada se sua aplicação precisar atualizar seu próprio histórico. diff --git a/examples/webhook/main.go b/examples/webhook/main.go index b59e6dc..7379de2 100644 --- a/examples/webhook/main.go +++ b/examples/webhook/main.go @@ -20,7 +20,11 @@ func main() { if len(secret) < 32 { log.Fatal("RANJIT_WEBHOOK_SECRET must contain at least 32 characters") } - db, err := openInbox("webhook-inbox.db") + path := os.Getenv("WEBHOOK_DATABASE") + if path == "" { + path = "webhook-inbox.db" + } + db, err := openInbox(path) if err != nil { log.Fatal(err) } @@ -49,6 +53,15 @@ func openInbox(path string) (*sql.DB, error) { func receiver(db *sql.DB, secret string) http.Handler { mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + if err := db.PingContext(ctx); err != nil { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusNoContent) + }) mux.HandleFunc("POST /webhooks/ranjit", func(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, 16<<10) defer r.Body.Close() diff --git a/install.sh b/install.sh index 9a2ee8f..a3581ca 100644 --- a/install.sh +++ b/install.sh @@ -2,7 +2,7 @@ # Install a released binary in the current user's directory. No sudo, Go or Docker. set -eu -version=${RANJIT_VERSION:-v0.3.0} +version=${RANJIT_VERSION:-v0.4.0} destination=${RANJIT_INSTALL_DIR:-"$HOME/.local/bin"} mode=binary case "${1:-}" in --docker) mode=docker ;; '') ;; *) echo 'Usage: sh install.sh [--docker]' >&2; exit 1 ;; esac diff --git a/internal/config/certificates.go b/internal/config/certificates.go index 605b277..47b52fc 100644 --- a/internal/config/certificates.go +++ b/internal/config/certificates.go @@ -6,16 +6,12 @@ import ( "math" "time" + "github.com/getcortexlabs/ranjit" "github.com/getcortexlabs/ranjit/internal/provider" ) // CertificateStatus deliberately omits certificate subjects, serials and paths. -type CertificateStatus struct { - Profile string `json:"profile"` - Level string `json:"level"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` - DaysRemaining int `json:"days_remaining"` -} +type CertificateStatus = ranjit.CertificateStatus func (c Config) Certificates(now time.Time) []CertificateStatus { profiles := c.Profiles diff --git a/internal/httpapi/backend_test.go b/internal/httpapi/backend_test.go index 6b5a204..595735c 100644 --- a/internal/httpapi/backend_test.go +++ b/internal/httpapi/backend_test.go @@ -91,11 +91,11 @@ func TestAPIKeysReloadAndExpireWithoutRestart(t *testing.T) { func TestWebhookDeliverySDKAndAuthentication(t *testing.T) { client, s, w, _ := setup(t) - s.Store.EnableWebhooks("https://backend.example/events") result := connect(t, client, "customer") if code, _ := decide(t, client, result, "approve", s.BaseURL); code != 200 { t.Fatal(code) } + s.Store.EnableWebhooks("https://backend.example/events") if err := w.Step(t.Context()); err != nil { t.Fatal(err) } diff --git a/internal/httpapi/metrics.go b/internal/httpapi/metrics.go new file mode 100644 index 0000000..20f8147 --- /dev/null +++ b/internal/httpapi/metrics.go @@ -0,0 +1,79 @@ +package httpapi + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/getcortexlabs/ranjit" +) + +func Operations(fn func(context.Context) ranjit.Diagnostics) Option { + return func(h *Server, mux *http.ServeMux) { + h.diagnostics = fn + mux.HandleFunc("GET /v1/diagnostics", func(w http.ResponseWriter, r *http.Request) { write(w, 200, fn(r.Context())) }) + } +} + +func (h *Server) metrics(w http.ResponseWriter, r *http.Request) { + data := h.diagnostics(r.Context()) + if data.Operations == nil || data.Operations.Database != "ready" { + http.Error(w, "metrics unavailable", http.StatusServiceUnavailable) + return + } + op := data.Operations + w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") + fmt.Fprintln(w, "# HELP ranjit_worker_healthy Worker is progressing or deliberately disabled.\n# TYPE ranjit_worker_healthy gauge") + for _, name := range []string{"sync", "webhook"} { + worker := op.Workers[name] + healthy := 0 + if worker.Healthy { + healthy = 1 + } + fmt.Fprintf(w, "ranjit_worker_healthy{worker=%q} %d\n", name, healthy) + } + fmt.Fprintln(w, "# HELP ranjit_worker_steps_total Completed worker steps since process start.\n# TYPE ranjit_worker_steps_total counter") + for _, name := range []string{"sync", "webhook"} { + fmt.Fprintf(w, "ranjit_worker_steps_total{worker=%q} %d\n", name, op.Workers[name].Steps) + } + fmt.Fprintln(w, "# HELP ranjit_worker_errors_total Failed worker steps since process start.\n# TYPE ranjit_worker_errors_total counter") + for _, name := range []string{"sync", "webhook"} { + fmt.Fprintf(w, "ranjit_worker_errors_total{worker=%q} %d\n", name, op.Workers[name].Errors) + } + fmt.Fprintln(w, "# HELP ranjit_queue_items Records currently in each queue state.\n# TYPE ranjit_queue_items gauge") + queues := []struct { + name string + stats ranjit.QueueStatus + }{{"sync", op.SyncQueue}, {"webhook", op.WebhookQueue}} + for _, q := range queues { + for _, state := range []string{"queued", "running", "succeeded", "delivered", "failed", "cancelled"} { + if count, ok := q.stats.Counts[state]; ok { + fmt.Fprintf(w, "ranjit_queue_items{queue=%q,state=%q} %d\n", q.name, state, count) + } + } + } + fmt.Fprintln(w, "# HELP ranjit_queue_oldest_due_seconds Age of the oldest due queued record.\n# TYPE ranjit_queue_oldest_due_seconds gauge") + for _, q := range queues { + age := 0.0 + if q.stats.OldestDueAt != nil { + age = max(0, op.ObservedAt.Sub(*q.stats.OldestDueAt).Seconds()) + } + fmt.Fprintf(w, "ranjit_queue_oldest_due_seconds{queue=%q} %g\n", q.name, age) + } + fmt.Fprintln(w, "# HELP ranjit_queue_recent_outcomes Outcomes recorded in the last 24 hours.\n# TYPE ranjit_queue_recent_outcomes gauge") + for _, q := range queues { + fmt.Fprintf(w, "ranjit_queue_recent_outcomes{queue=%q,outcome=\"succeeded\"} %d\nranjit_queue_recent_outcomes{queue=%q,outcome=\"failed\"} %d\n", q.name, q.stats.RecentSucceeded, q.name, q.stats.RecentFailed) + } + fmt.Fprintln(w, "# HELP ranjit_queue_last_outcome_timestamp_seconds Unix time of the latest recorded outcome, or zero.\n# TYPE ranjit_queue_last_outcome_timestamp_seconds gauge") + for _, q := range queues { + fmt.Fprintf(w, "ranjit_queue_last_outcome_timestamp_seconds{queue=%q,outcome=\"succeeded\"} %d\nranjit_queue_last_outcome_timestamp_seconds{queue=%q,outcome=\"failed\"} %d\n", q.name, unixOrZero(q.stats.LastSucceededAt), q.name, unixOrZero(q.stats.LastFailedAt)) + } +} + +func unixOrZero(t *time.Time) int64 { + if t == nil { + return 0 + } + return t.Unix() +} diff --git a/internal/httpapi/metrics_test.go b/internal/httpapi/metrics_test.go new file mode 100644 index 0000000..bec65e8 --- /dev/null +++ b/internal/httpapi/metrics_test.go @@ -0,0 +1,65 @@ +package httpapi_test + +import ( + "context" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/getcortexlabs/ranjit" + "github.com/getcortexlabs/ranjit/internal/httpapi" +) + +func TestOperationsAuthenticationAndBoundedMetrics(t *testing.T) { + client, service, _, _ := setup(t) + now := service.Now() + due := now.Add(-30 * time.Second) + op := &ranjit.OperationsStatus{Database: "ready", ObservedAt: now, + Workers: map[string]ranjit.WorkerStatus{"sync": {State: "idle", Healthy: true, Steps: 42}, "webhook": {State: "stalled"}}, + SyncQueue: ranjit.QueueStatus{Counts: map[string]int64{"queued": 2, "private-customer": 7}, OldestDueAt: &due, RecentFailed: 1}, + } + handler := httpapi.New(service, key, slog.New(slog.NewTextHandler(io.Discard, nil)), httpapi.Operations(func(context.Context) ranjit.Diagnostics { + return ranjit.Diagnostics{Version: "v0.4.0", Operations: op, UnavailableProfiles: []string{"private-profile"}} + })) + client.HTTPClient.Transport = handlerTransport{handler: handler} + for _, path := range []string{"/metrics", "/v1/diagnostics"} { + request := httptest.NewRequest("GET", path, nil) + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != http.StatusUnauthorized { + t.Fatal(path, response.Code) + } + } + diagnostics, err := client.Diagnostics(t.Context()) + if err != nil || diagnostics.Operations.SyncQueue.Counts["queued"] != 2 || diagnostics.Version != "v0.4.0" { + t.Fatal(diagnostics, err) + } + request := httptest.NewRequest("GET", "/metrics", nil) + request.Header.Set("Authorization", "Bearer "+key) + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + body := response.Body.String() + if response.Code != 200 || !strings.HasPrefix(response.Header().Get("Content-Type"), "text/plain; version=0.0.4") { + t.Fatal(response.Code, response.Header()) + } + for _, want := range []string{`ranjit_worker_healthy{worker="sync"} 1`, `ranjit_worker_healthy{worker="webhook"} 0`, `ranjit_worker_steps_total{worker="sync"} 42`, `ranjit_queue_oldest_due_seconds{queue="sync"} 30`} { + if !strings.Contains(body, want) { + t.Fatal("missing metric", want) + } + } + for _, secret := range []string{key, "private-customer", "private-profile"} { + if strings.Contains(body, secret) { + t.Fatal("unbounded or sensitive metric label") + } + } + op.Database = "unavailable" + response = httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != 503 || strings.Contains(response.Body.String(), "ranjit_queue_items") { + t.Fatal("unavailable database exported misleading metrics") + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 5415a46..ed67a4c 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -1,6 +1,7 @@ package httpapi import ( + "context" "crypto/sha256" "crypto/subtle" "encoding/json" @@ -20,10 +21,11 @@ import ( ) type Server struct { - sessions sessions - service *service.Service - keys func(time.Time) ([]string, error) - logger *slog.Logger + diagnostics func(context.Context) ranjit.Diagnostics + sessions sessions + service *service.Service + keys func(time.Time) ([]string, error) + logger *slog.Logger } // Option configures authentication or operational routes. @@ -80,6 +82,9 @@ func New(s *service.Service, apiKey string, logger *slog.Logger, options ...Opti api.HandleFunc("POST /v1/imports/columns", h.csvHeaders) api.HandleFunc("GET /v1/connections/{id}/status", h.status) mux.Handle("/v1/", h.authenticate(api)) + if h.diagnostics != nil { + mux.Handle("GET /metrics", h.authenticate(http.HandlerFunc(h.metrics))) + } mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { h.problem(w, ranjit.ErrNotFound) }) return h.middleware(mux) } diff --git a/internal/monitor/worker.go b/internal/monitor/worker.go new file mode 100644 index 0000000..f701eb9 --- /dev/null +++ b/internal/monitor/worker.go @@ -0,0 +1,84 @@ +package monitor + +import ( + "sync" + "time" + + "github.com/getcortexlabs/ranjit" +) + +// Worker records completed work, not a separate heartbeat that could keep +// reporting healthy while the real worker is stuck. +type Worker struct { + mu sync.Mutex + enabled bool + running bool + stopped bool + failed bool + budget time.Duration + started, finished, success time.Time + steps, errors uint64 +} + +func NewWorker(enabled bool, budget time.Duration) *Worker { + return &Worker{enabled: enabled, budget: budget} +} + +func (m *Worker) Begin(now time.Time) { + if m == nil { + return + } + m.mu.Lock() + defer m.mu.Unlock() + m.running, m.started = true, now.UTC() +} +func (m *Worker) End(now time.Time, err error) { + if m == nil { + return + } + m.mu.Lock() + defer m.mu.Unlock() + m.running, m.finished, m.failed = false, now.UTC(), err != nil + m.steps++ + if err != nil { + m.errors++ + } else { + m.success = now.UTC() + } +} +func (m *Worker) Stop() { + if m == nil { + return + } + m.mu.Lock() + defer m.mu.Unlock() + m.stopped = true +} + +func (m *Worker) Snapshot(now time.Time) ranjit.WorkerStatus { + m.mu.Lock() + defer m.mu.Unlock() + out := ranjit.WorkerStatus{State: "idle", Healthy: true, Steps: m.steps, Errors: m.errors, LastStartedAt: stamp(m.started), LastFinishedAt: stamp(m.finished), LastSuccessAt: stamp(m.success)} + switch { + case !m.enabled: + out.State = "disabled" + case m.stopped: + out.State, out.Healthy = "stopped", false + case m.started.IsZero(): + out.State, out.Healthy = "starting", false + case m.running && now.Sub(m.started) > m.budget || !m.running && now.Sub(m.finished) > 5*time.Second: + out.State, out.Healthy = "stalled", false + case m.failed: + out.State, out.Healthy = "error", false + case m.running: + out.State = "running" + } + return out +} + +func stamp(t time.Time) *time.Time { + if t.IsZero() { + return nil + } + return &t +} diff --git a/internal/monitor/worker_test.go b/internal/monitor/worker_test.go new file mode 100644 index 0000000..4b969b1 --- /dev/null +++ b/internal/monitor/worker_test.go @@ -0,0 +1,41 @@ +package monitor + +import ( + "errors" + "testing" + "time" +) + +func TestWorkerProgressAndFailure(t *testing.T) { + now := time.Now() + m := NewWorker(true, 30*time.Second) + if m.Snapshot(now).State != "starting" { + t.Fatal("unknown startup") + } + m.Begin(now) + if got := m.Snapshot(now.Add(20 * time.Second)); got.State != "running" || !got.Healthy { + t.Fatal(got) + } + if got := m.Snapshot(now.Add(31 * time.Second)); got.State != "stalled" || got.Healthy { + t.Fatal(got) + } + m.End(now.Add(32*time.Second), errors.New("storage failed")) + if got := m.Snapshot(now.Add(32 * time.Second)); got.State != "error" || got.Errors != 1 { + t.Fatal(got) + } + m.Begin(now.Add(33 * time.Second)) + m.End(now.Add(34*time.Second), nil) + if got := m.Snapshot(now.Add(35 * time.Second)); got.State != "idle" || !got.Healthy || got.Steps != 2 { + t.Fatal(got) + } + if got := m.Snapshot(now.Add(40 * time.Second)); got.State != "stalled" { + t.Fatal(got) + } + m.Stop() + if m.Snapshot(now).State != "stopped" { + t.Fatal("stopped worker healthy") + } + if got := NewWorker(false, time.Second).Snapshot(now); !got.Healthy || got.State != "disabled" { + t.Fatal(got) + } +} diff --git a/internal/store/backend_test.go b/internal/store/backend_test.go index 03c6d77..5b448f0 100644 --- a/internal/store/backend_test.go +++ b/internal/store/backend_test.go @@ -42,7 +42,7 @@ func TestBackendMigrationPreservesExistingGrantAndJob(t *testing.T) { if _, err := s.db.ExecContext(t.Context(), `DROP TABLE webhook_deliveries; DROP TABLE connection_requests;`); err != nil { t.Fatal(err) } - if _, err := s.db.ExecContext(t.Context(), `DELETE FROM schema_migrations WHERE name=?`, migration); err != nil { + if _, err := s.db.ExecContext(t.Context(), `DELETE FROM schema_migrations WHERE name>=?`, migration); err != nil { t.Fatal(err) } s.Close() @@ -147,11 +147,11 @@ func TestConnectionRequestRollsBackWithGrant(t *testing.T) { func TestWebhookDeliveryRestartFencingRetryAndTarget(t *testing.T) { backendStores(t, func(t *testing.T, s *Store, path string) { target := "https://backend.example/webhooks" - s.EnableWebhooks(target) c := directGrant() if err := s.CreateAuthorizedConnection(t.Context(), c); err != nil { t.Fatal(err) } + s.EnableWebhooks(target) j, err := s.Claim(t.Context(), testNow, time.Minute) if err != nil { t.Fatal(err) @@ -244,19 +244,19 @@ func TestWebhookDeliveryRestartFencingRetryAndTarget(t *testing.T) { t.Fatal(err) } page, err = s.WebhookDeliveries(t.Context(), "", 100) - if err != nil || len(page.Data) != 0 { - t.Fatal("revoked metadata retained", err) + if err != nil || len(page.Data) != 1 || page.Data[0].Event.Type != "connection.revoked" || page.Data[0].Event.Data.CustomerID != "" { + t.Fatal("revocation retained more than its minimal event", err) } }) } func TestWebhookFailureEventsAndOutboxRollback(t *testing.T) { backendStores(t, func(t *testing.T, s *Store, _ string) { - s.EnableWebhooks("https://backend.example/webhooks") c := directGrant() if err := s.CreateAuthorizedConnection(t.Context(), c); err != nil { t.Fatal(err) } + s.EnableWebhooks("https://backend.example/webhooks") j, err := s.Claim(t.Context(), testNow, time.Minute) if err != nil { t.Fatal(err) diff --git a/internal/store/connections.go b/internal/store/connections.go index f92ce33..64b30ab 100644 --- a/internal/store/connections.go +++ b/internal/store/connections.go @@ -40,6 +40,9 @@ func (s *Store) CreateAuthorizedConnection(ctx context.Context, c ranjit.Connect if _, err = enqueue(ctx, tx, c.ID, c.CreatedAt); err != nil { return err } + if err = s.queueConnectionEvent(ctx, tx, c, "connection.activated", c.CreatedAt); err != nil { + return err + } return tx.Commit() } @@ -109,6 +112,13 @@ func (s *Store) Decide(ctx context.Context, hash string, approve bool, now time. return c, err } } + eventType := "connection.denied" + if approve { + eventType = "connection.activated" + } + if err = s.queueConnectionEvent(ctx, tx, c, eventType, now); err != nil { + return c, err + } return c, tx.Commit() } @@ -119,6 +129,13 @@ func (s *Store) Revoke(ctx context.Context, id string, now time.Time) error { return err } defer tx.Rollback() + c, err := scanConnection(tx.QueryRowContext(ctx, `SELECT `+connectionColumns+` FROM connections WHERE id=?`, id)) + if err != nil { + return err + } + if c.Status == "revoked" { + return nil + } result, err := tx.ExecContext(ctx, `UPDATE connections SET status = 'revoked', token_hash = NULL WHERE id = ?`, id) if err = changed(result, err, ranjit.ErrNotFound); err != nil { return err @@ -133,6 +150,10 @@ func (s *Store) Revoke(ctx context.Context, id string, now time.Time) error { WHERE connection_id = ? AND status IN ('queued','running')`, now.UnixMilli(), id); err != nil { return err } + c.Status = "revoked" + if err = s.queueConnectionEvent(ctx, tx, c, "connection.revoked", now); err != nil { + return err + } return tx.Commit() } @@ -149,10 +170,31 @@ func (s *Store) Expire(ctx context.Context, now time.Time) error { if _, err = tx.ExecContext(ctx, `DELETE FROM webhook_deliveries WHERE updated_at 'file' AND status = 'active' AND consent_expires_at <= ?) OR (status = 'pending' AND authorization_expires_at <= ?)`, now.UnixMilli(), now.UnixMilli()); err != nil { + rows, err := tx.QueryContext(ctx, `UPDATE connections SET status='expired',token_hash=NULL + WHERE (provider<>'file' AND status='active' AND consent_expires_at<=?) OR (status='pending' AND authorization_expires_at<=?) RETURNING `+connectionColumns, now.UnixMilli(), now.UnixMilli()) + if err != nil { + return err + } + var expired []ranjit.Connection + for rows.Next() { + c, e := scanConnection(rows) + if e != nil { + rows.Close() + return e + } + expired = append(expired, c) + } + err = rows.Err() + rows.Close() + if err != nil { return err } + for _, c := range expired { + if err = s.queueConnectionEvent(ctx, tx, c, "connection.expired", now); err != nil { + return err + } + } + if _, err = tx.ExecContext(ctx, `DELETE FROM accounts WHERE connection_id IN (SELECT id FROM connections WHERE status = 'expired' AND provider = 'sandbox')`); err != nil { return err } @@ -197,13 +239,26 @@ func (s *Store) Pause(ctx context.Context, id string, now time.Time) error { return err } defer tx.Rollback() - result, err := tx.ExecContext(ctx, `UPDATE connections SET status='paused' WHERE id=? AND authorization_mode='api_credentials' AND status IN ('active','expired','paused')`, id) - if err = changed(result, err, ranjit.ErrConflict); err != nil { + c, err := scanConnection(tx.QueryRowContext(ctx, `SELECT `+connectionColumns+` FROM connections WHERE id=?`, id)) + if err != nil { + return err + } + if c.AuthorizationMode != "api_credentials" || (c.Status != "active" && c.Status != "expired" && c.Status != "paused") { + return ranjit.ErrConflict + } + if c.Status == "paused" { + return nil + } + if _, err = tx.ExecContext(ctx, `UPDATE connections SET status='paused' WHERE id=?`, id); err != nil { return err } if err = cancelJobs(ctx, tx, id, now); err != nil { return err } + c.Status = "paused" + if err = s.queueConnectionEvent(ctx, tx, c, "connection.paused", now); err != nil { + return err + } return tx.Commit() } @@ -218,15 +273,29 @@ func (s *Store) Renew(ctx context.Context, id, binding string, deadline, now tim return ranjit.Connection{}, err } defer tx.Rollback() - c, err := scanConnection(tx.QueryRowContext(ctx, `UPDATE connections SET status='active',consent_expires_at=? WHERE id=? AND credential_id=? AND authorization_mode='api_credentials' AND status IN ('active','paused','expired') RETURNING `+connectionColumns, deadline.UnixMilli(), id, binding)) + c, err := scanConnection(tx.QueryRowContext(ctx, `SELECT `+connectionColumns+` FROM connections WHERE id=?`, id)) if err != nil { return c, err } + if c.CredentialID != binding || c.AuthorizationMode != "api_credentials" || (c.Status != "active" && c.Status != "paused" && c.Status != "expired") { + return c, ranjit.ErrConflict + } + deadline = deadline.UTC().Truncate(time.Millisecond) + if c.Status == "active" && c.ConsentExpiresAt.Equal(deadline) { + return c, nil + } + if _, err = tx.ExecContext(ctx, `UPDATE connections SET status='active',consent_expires_at=? WHERE id=?`, deadline.UnixMilli(), id); err != nil { + return c, err + } if err = cancelJobs(ctx, tx, id, now); err != nil { return c, err } if _, err = enqueue(ctx, tx, id, now); err != nil { return c, err } + c.Status, c.ConsentExpiresAt = "active", deadline + if err = s.queueConnectionEvent(ctx, tx, c, "connection.renewed", now); err != nil { + return c, err + } return c, tx.Commit() } diff --git a/internal/store/diagnostics.go b/internal/store/diagnostics.go new file mode 100644 index 0000000..8079d38 --- /dev/null +++ b/internal/store/diagnostics.go @@ -0,0 +1,56 @@ +package store + +import ( + "context" + "database/sql" + "time" + + "github.com/getcortexlabs/ranjit" +) + +func (s *Store) Queues(ctx context.Context, now time.Time) (ranjit.QueueStatus, ranjit.QueueStatus, error) { + sync, err := s.queueStats(ctx, "jobs", "succeeded", "", nil, now) + if err != nil { + return sync, ranjit.QueueStatus{}, err + } + hooks, err := s.queueStats(ctx, "webhook_deliveries", "delivered", " WHERE target_hash=?", []any{s.webhookTarget}, now) + return sync, hooks, err +} + +func (s *Store) queueStats(ctx context.Context, table, success, filter string, args []any, now time.Time) (ranjit.QueueStatus, error) { + out := ranjit.QueueStatus{Counts: map[string]int64{"queued": 0, "running": 0, "failed": 0, success: 0}} + if table == "jobs" { + out.Counts["cancelled"] = 0 + } + // Identifiers and state names are internal constants, never request input. + query := `SELECT status,COUNT(*),MIN(CASE WHEN status='queued' AND available_at<=? THEN available_at END),MAX(updated_at),SUM(CASE WHEN updated_at>=? THEN 1 ELSE 0 END) FROM ` + table + filter + ` GROUP BY status` + params := append([]any{now.UnixMilli(), now.Add(-24 * time.Hour).UnixMilli()}, args...) + rows, err := s.db.QueryContext(ctx, query, params...) + if err != nil { + return out, err + } + defer rows.Close() + for rows.Next() { + var status string + var count, recent int64 + var due, last sql.NullInt64 + if err = rows.Scan(&status, &count, &due, &last, &recent); err != nil { + return out, err + } + out.Counts[status] = count + if due.Valid { + at := instant(due.Int64) + out.OldestDueAt = &at + } + if last.Valid { + at := instant(last.Int64) + switch status { + case success: + out.LastSucceededAt, out.RecentSucceeded = &at, recent + case "failed": + out.LastFailedAt, out.RecentFailed = &at, recent + } + } + } + return out, rows.Err() +} diff --git a/internal/store/diagnostics_test.go b/internal/store/diagnostics_test.go new file mode 100644 index 0000000..9755052 --- /dev/null +++ b/internal/store/diagnostics_test.go @@ -0,0 +1,51 @@ +package store + +import ( + "testing" + "time" +) + +func TestQueueDiagnosticsAcrossBackends(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, _ string) { + c := directGrant() + if err := s.CreateAuthorizedConnection(t.Context(), c); err != nil { + t.Fatal(err) + } + s.EnableWebhooks("https://backend.example/events") + sync, hooks, err := s.Queues(t.Context(), testNow.Add(time.Minute)) + if err != nil || sync.Counts["queued"] != 1 || sync.OldestDueAt == nil || !sync.OldestDueAt.Equal(testNow) || hooks.Counts["queued"] != 0 { + t.Fatal(sync, hooks, err) + } + j, err := s.Claim(t.Context(), testNow, time.Minute) + if err != nil { + t.Fatal(err) + } + if err = s.Fail(t.Context(), j, "provider_credentials", testNow); err != nil { + t.Fatal(err) + } + attempt, err := s.ClaimWebhook(t.Context(), testNow) + if err != nil { + t.Fatal(err) + } + if err = s.FinishWebhook(t.Context(), attempt, 204, testNow); err != nil { + t.Fatal(err) + } + sync, hooks, err = s.Queues(t.Context(), testNow) + if err != nil || sync.Counts["failed"] != 1 || sync.RecentFailed != 1 || sync.LastFailedAt == nil || hooks.Counts["delivered"] != 1 || hooks.RecentSucceeded != 1 { + t.Fatal(sync, hooks, err) + } + sync, hooks, err = s.Queues(t.Context(), testNow.Add(25*time.Hour)) + if err != nil || sync.RecentFailed != 0 || hooks.RecentSucceeded != 0 || sync.Counts["failed"] != 1 { + t.Fatal(sync, hooks, err) + } + s.EnableWebhooks("https://another.example/events") + _, hooks, err = s.Queues(t.Context(), testNow) + if err != nil || hooks.Counts["delivered"] != 0 { + t.Fatal("other target metadata exposed", hooks, err) + } + s.Close() + if _, _, err = s.Queues(t.Context(), testNow); err == nil { + t.Fatal("closed database reported healthy") + } + }) +} diff --git a/internal/store/idempotency.go b/internal/store/idempotency.go index 2952ae2..84210c9 100644 --- a/internal/store/idempotency.go +++ b/internal/store/idempotency.go @@ -65,6 +65,9 @@ func (s *Store) CreateConnectionOnce(ctx context.Context, c ranjit.Connection, t return c, deadline, err } if c.Status == "active" { + if err = s.queueConnectionEvent(ctx, tx, c, "connection.activated", c.CreatedAt); err != nil { + return c, deadline, err + } if _, err = enqueue(ctx, tx, c.ID, c.CreatedAt); err != nil { return c, deadline, err } diff --git a/internal/store/lifecycle_events_test.go b/internal/store/lifecycle_events_test.go new file mode 100644 index 0000000..1cd4548 --- /dev/null +++ b/internal/store/lifecycle_events_test.go @@ -0,0 +1,236 @@ +package store + +import ( + "errors" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/getcortexlabs/ranjit" + "github.com/getcortexlabs/ranjit/internal/provider/sandbox" +) + +func lifecycleTypes(t *testing.T, s *Store) map[string]int { + t.Helper() + page, err := s.WebhookDeliveries(t.Context(), "", 100) + if err != nil { + t.Fatal(err) + } + counts := map[string]int{} + for _, d := range page.Data { + counts[d.Event.Type]++ + if strings.HasPrefix(d.Event.Type, "connection.") && d.Event.Data.JobID != "" { + t.Fatal("lifecycle event has job") + } + } + return counts +} + +func TestLifecycleEventsAreAtomicAndNoopsDoNotDuplicate(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, path string) { + target := "https://backend.example/events" + s.EnableWebhooks(target) + c := directGrant() + c.ConsentExpiresAt = testNow.Add(10 * time.Minute) + for range 2 { + if _, _, err := s.CreateConnectionOnce(t.Context(), c, nil, time.Time{}, "key", "body"); err != nil { + t.Fatal(err) + } + } + var wg sync.WaitGroup + errs := make(chan error, 8) + for range 8 { + wg.Go(func() { errs <- s.Pause(t.Context(), c.ID, testNow) }) + } + wg.Wait() + for range 8 { + if err := <-errs; err != nil { + t.Fatal(err) + } + } + for range 2 { + if _, err := s.Renew(t.Context(), c.ID, c.CredentialID, testNow.Add(time.Hour), testNow); err != nil { + t.Fatal(err) + } + } + for range 2 { + if err := s.Expire(t.Context(), testNow.Add(2*time.Hour)); err != nil { + t.Fatal(err) + } + } + counts := lifecycleTypes(t, s) + for _, kind := range []string{"connection.activated", "connection.paused", "connection.renewed", "connection.expired"} { + if counts[kind] != 1 { + t.Fatal(kind, counts) + } + } + inFlight, err := s.ClaimWebhook(t.Context(), testNow.Add(2*time.Hour)) + if err != nil { + t.Fatal(err) + } + if err = s.Revoke(t.Context(), c.ID, testNow.Add(2*time.Hour)); err != nil { + t.Fatal(err) + } + if err = s.FinishWebhook(t.Context(), inFlight, 204, testNow.Add(2*time.Hour)); !errors.Is(err, ranjit.ErrLease) { + t.Fatal("revoked delivery acknowledged", err) + } + first, err := s.WebhookDeliveries(t.Context(), "", 100) + if err != nil || len(first.Data) != 1 { + t.Fatal(first, err) + } + event := first.Data[0].Event + if event.Type != "connection.revoked" || event.Data.CustomerID != "" || event.Data.JobID != "" || event.Data.Status != "revoked" { + t.Fatal(event) + } + if err = s.Revoke(t.Context(), c.ID, testNow.Add(2*time.Hour)); err != nil { + t.Fatal(err) + } + s.Close() + s, err = Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + s.EnableWebhooks(target) + next, err := s.WebhookDeliveries(t.Context(), "", 100) + if err != nil || len(next.Data) != 1 || next.Data[0].Event.ID != event.ID { + t.Fatal("revocation replay changed event", next, err) + } + if !s.db.postgres { + backup := filepath.Join(t.TempDir(), "backup.db") + if err = s.Backup(t.Context(), backup); err != nil { + t.Fatal(err) + } + restoredPath := filepath.Join(t.TempDir(), "restored.db") + if _, err = Restore(t.Context(), backup, restoredPath, false); err != nil { + t.Fatal(err) + } + restored, err := Open(t.Context(), restoredPath) + if err != nil { + t.Fatal(err) + } + defer restored.Close() + restored.EnableWebhooks(target) + if counts := lifecycleTypes(t, restored); len(counts) != 0 { + t.Fatal("restore emitted old events", counts) + } + } + }) +} + +func TestSandboxDecisionAndExpiryEvents(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, _ string) { + s.EnableWebhooks("https://backend.example/events") + for _, decision := range []string{"approve", "deny", "expire"} { + c := ranjit.Connection{ID: ranjit.NewID("con"), CustomerID: "customer", InstitutionID: "sandbox-bank", Provider: "sandbox", Status: "pending", CreatedAt: testNow, ConsentExpiresAt: testNow.Add(time.Hour)} + if _, _, err := s.CreateConnectionOnce(t.Context(), c, decision, testNow.Add(time.Minute), "", ""); err != nil { + t.Fatal(err) + } + if decision != "expire" { + if _, err := s.Decide(t.Context(), decision, decision == "approve", testNow); err != nil { + t.Fatal(err) + } + if _, err := s.Decide(t.Context(), decision, decision == "approve", testNow); !errors.Is(err, ranjit.ErrConsent) { + t.Fatal(err) + } + } + } + if err := s.Expire(t.Context(), testNow.Add(time.Minute)); err != nil { + t.Fatal(err) + } + counts := lifecycleTypes(t, s) + for _, kind := range []string{"connection.activated", "connection.denied", "connection.expired"} { + if counts[kind] != 1 { + t.Fatal(counts) + } + } + }) +} + +func TestLifecycleOutboxFailureRollsBackStateAndDeletion(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, _ string) { + c := directGrant() + c.ConsentExpiresAt = testNow.Add(time.Hour) + if err := s.CreateAuthorizedConnection(t.Context(), c); err != nil { + t.Fatal(err) + } + j := claim(t, s, c, testNow) + batch, err := (sandbox.Source{}).Fetch(t.Context(), ranjit.Connection{Provider: "sandbox", InstitutionID: "sandbox-bank"}) + if err != nil { + t.Fatal(err) + } + if err := s.Complete(t.Context(), j, batch, testNow); err != nil { + t.Fatal(err) + } + s.EnableWebhooks("https://backend.example/events") + ddl := `CREATE TRIGGER reject_lifecycle BEFORE INSERT ON webhook_deliveries BEGIN SELECT RAISE(ABORT,'test'); END` + if s.db.postgres { + ddl = `CREATE FUNCTION reject_lifecycle() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test'; END; $$; CREATE TRIGGER reject_lifecycle BEFORE INSERT ON webhook_deliveries FOR EACH ROW EXECUTE FUNCTION reject_lifecycle();` + } + if _, err := s.db.ExecContext(t.Context(), ddl); err != nil { + t.Fatal(err) + } + if err := s.Pause(t.Context(), c.ID, testNow); err == nil { + t.Fatal("pause accepted without event") + } + if _, err := s.Renew(t.Context(), c.ID, c.CredentialID, testNow.Add(2*time.Hour), testNow); err == nil { + t.Fatal("renew accepted without event") + } + if err := s.Expire(t.Context(), testNow.Add(2*time.Hour)); err == nil { + t.Fatal("expiry accepted without event") + } + if err := s.Revoke(t.Context(), c.ID, testNow); err == nil { + t.Fatal("revocation accepted without event") + } + got, err := s.Connection(t.Context(), c.ID, testNow) + if err != nil || got.Status != "active" || !got.ConsentExpiresAt.Equal(c.ConsentExpiresAt) { + t.Fatal(got, err) + } + page, err := s.Accounts(t.Context(), c.ID, "", 100, testNow) + if err != nil || len(page.Data) != 2 { + t.Fatal("financial data deleted after rollback", err) + } + }) +} + +func TestLifecycleMigrationPreservesSyncDeliveries(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, path string) { + c := directGrant() + if err := s.CreateAuthorizedConnection(t.Context(), c); err != nil { + t.Fatal(err) + } + if s.db.postgres { + if _, err := s.db.ExecContext(t.Context(), `ALTER TABLE webhook_deliveries ALTER COLUMN job_id SET NOT NULL; DELETE FROM schema_migrations WHERE name='003_connection_events.sql'`); err != nil { + t.Fatal(err) + } + } else { + ddl, _ := migrations.ReadFile("migrations/007_backend.sql") + old := string(ddl) + old = old[strings.Index(old, "CREATE TABLE webhook_deliveries"):] + if _, err := s.db.ExecContext(t.Context(), `DROP TABLE webhook_deliveries; DELETE FROM schema_migrations WHERE name='008_connection_events.sql';`+old); err != nil { + t.Fatal(err) + } + } + s.EnableWebhooks("https://backend.example/events") + j := claim(t, s, c, testNow) + if err := s.Fail(t.Context(), j, "provider_credentials", testNow); err != nil { + t.Fatal(err) + } + s.Close() + s, err := Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + s.EnableWebhooks("https://backend.example/events") + if err = s.Pause(t.Context(), c.ID, testNow); err != nil { + t.Fatal(err) + } + counts := lifecycleTypes(t, s) + if counts["sync.failed"] != 1 || counts["connection.paused"] != 1 { + t.Fatal(counts) + } + }) +} diff --git a/internal/store/migrations/008_connection_events.sql b/internal/store/migrations/008_connection_events.sql new file mode 100644 index 0000000..5f26dde --- /dev/null +++ b/internal/store/migrations/008_connection_events.sql @@ -0,0 +1,23 @@ +CREATE TABLE webhook_deliveries_next ( + id TEXT PRIMARY KEY, + job_id TEXT REFERENCES jobs(id) ON DELETE CASCADE, + connection_id TEXT NOT NULL REFERENCES connections(id) ON DELETE CASCADE, + target_hash TEXT NOT NULL, + event_type TEXT NOT NULL, + payload TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('queued', 'running', 'delivered', 'failed')), + attempts INTEGER NOT NULL DEFAULT 0, + http_status INTEGER NOT NULL DEFAULT 0, + error_code TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + available_at INTEGER NOT NULL, + lease_until INTEGER NOT NULL DEFAULT 0, + lease_token TEXT NOT NULL DEFAULT '', + UNIQUE(job_id, event_type) +); +INSERT INTO webhook_deliveries_next SELECT * FROM webhook_deliveries; +DROP TABLE webhook_deliveries; +ALTER TABLE webhook_deliveries_next RENAME TO webhook_deliveries; +CREATE INDEX webhook_deliveries_available ON webhook_deliveries(target_hash, status, available_at); +CREATE INDEX webhook_deliveries_expiry ON webhook_deliveries(updated_at); diff --git a/internal/store/postgres/003_connection_events.sql b/internal/store/postgres/003_connection_events.sql new file mode 100644 index 0000000..9389a37 --- /dev/null +++ b/internal/store/postgres/003_connection_events.sql @@ -0,0 +1 @@ +ALTER TABLE webhook_deliveries ALTER COLUMN job_id DROP NOT NULL; diff --git a/internal/store/webhooks.go b/internal/store/webhooks.go index c8b6da8..2af89c0 100644 --- a/internal/store/webhooks.go +++ b/internal/store/webhooks.go @@ -33,12 +33,28 @@ func (s *Store) queueWebhook(ctx context.Context, tx *transaction, j ranjit.Job, if err := tx.QueryRowContext(ctx, `SELECT customer_id FROM connections WHERE id=?`, j.ConnectionID).Scan(&event.Data.CustomerID); err != nil { return err } + return s.insertWebhook(ctx, tx, event, j.ID, now) +} + +func (s *Store) queueConnectionEvent(ctx context.Context, tx *transaction, c ranjit.Connection, eventType string, now time.Time) error { + if s.webhookTarget == "" { + return nil + } + data := ranjit.WebhookData{ConnectionID: c.ID, CustomerID: c.CustomerID, Status: c.Status} + if eventType == "connection.revoked" { + data.CustomerID = "" + } + event := ranjit.WebhookEvent{ID: ranjit.NewID("evt"), Type: eventType, CreatedAt: now.UTC(), Data: data} + return s.insertWebhook(ctx, tx, event, nil, now) +} + +func (s *Store) insertWebhook(ctx context.Context, tx *transaction, event ranjit.WebhookEvent, jobID any, now time.Time) error { data, err := json.Marshal(event) if err != nil { return err } _, err = tx.ExecContext(ctx, `INSERT INTO webhook_deliveries(id,job_id,connection_id,target_hash,event_type,payload,status,created_at,updated_at,available_at) - VALUES (?,?,?,?,?,?,'queued',?,?,?) ON CONFLICT(job_id,event_type) DO NOTHING`, event.ID, j.ID, j.ConnectionID, s.webhookTarget, eventType, string(data), now.UnixMilli(), now.UnixMilli(), now.UnixMilli()) + VALUES(?,?,?,?,?,?,'queued',?,?,?) ON CONFLICT(job_id,event_type) DO NOTHING`, event.ID, jobID, event.Data.ConnectionID, s.webhookTarget, event.Type, string(data), now.UnixMilli(), now.UnixMilli(), now.UnixMilli()) return err } diff --git a/internal/webhook/worker.go b/internal/webhook/worker.go index a9ec23b..1a6e26d 100644 --- a/internal/webhook/worker.go +++ b/internal/webhook/worker.go @@ -14,16 +14,18 @@ import ( "time" "github.com/getcortexlabs/ranjit" + "github.com/getcortexlabs/ranjit/internal/monitor" "github.com/getcortexlabs/ranjit/internal/store" ) type Worker struct { - Store *store.Store - URL string - Secret string - Client *http.Client - Now func() time.Time - Logger *slog.Logger + Monitor *monitor.Worker + Store *store.Store + URL string + Secret string + Client *http.Client + Now func() time.Time + Logger *slog.Logger } func New(db *store.Store, destination, secret string, logger *slog.Logger) *Worker { @@ -33,11 +35,17 @@ func New(db *store.Store, destination, secret string, logger *slog.Logger) *Work } func (w *Worker) Run(ctx context.Context) { + defer w.Monitor.Stop() defer w.Client.CloseIdleConnections() ticker := time.NewTicker(time.Second) defer ticker.Stop() for { - if err := w.Step(ctx); err != nil && ctx.Err() == nil { + w.Monitor.Begin(w.Now()) + stepCtx, cancel := context.WithTimeout(ctx, 20*time.Second) + err := w.Step(stepCtx) + cancel() + w.Monitor.End(w.Now(), err) + if err != nil && ctx.Err() == nil { w.Logger.Error("webhook delivery could not be recorded") } select { diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 7c166dc..f031c1b 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -7,11 +7,13 @@ import ( "time" "github.com/getcortexlabs/ranjit" + "github.com/getcortexlabs/ranjit/internal/monitor" "github.com/getcortexlabs/ranjit/internal/provider" "github.com/getcortexlabs/ranjit/internal/store" ) type Worker struct { + Monitor *monitor.Worker ConnectionIDs map[string]bool Store *store.Store Source provider.Source @@ -25,10 +27,16 @@ func New(db *store.Store, source provider.Source, interval time.Duration, logger } func (w *Worker) Run(ctx context.Context) { + defer w.Monitor.Stop() ticker := time.NewTicker(time.Second) defer ticker.Stop() for { - if err := w.Step(ctx); err != nil && ctx.Err() == nil { + w.Monitor.Begin(w.Now()) + stepCtx, cancel := context.WithTimeout(ctx, 45*time.Second) + err := w.Step(stepCtx) + cancel() + w.Monitor.End(w.Now(), err) + if err != nil && ctx.Err() == nil { w.Logger.Error("worker step failed") } select { diff --git a/iterator.go b/iterator.go new file mode 100644 index 0000000..55f4bc7 --- /dev/null +++ b/iterator.go @@ -0,0 +1,61 @@ +package ranjit + +import ( + "context" + "iter" +) + +func iterate[T any](ctx context.Context, startCursor string, fetch func(string) (Page[T], error)) iter.Seq2[T, error] { + return func(yield func(T, error) bool) { + cursor := startCursor + var zero T + seen := map[string]bool{cursor: true} + for { + if err := ctx.Err(); err != nil { + yield(zero, err) + return + } + page, err := fetch(cursor) + if err != nil { + yield(zero, err) + return + } + if page.NextCursor != "" && seen[page.NextCursor] { + yield(zero, ErrInvalidResponse) + return + } + for _, item := range page.Data { + if err = ctx.Err(); err != nil { + yield(zero, err) + return + } + if !yield(item, nil) { + return + } + } + if page.NextCursor == "" { + return + } + cursor = page.NextCursor + seen[cursor] = true + } + } +} + +// IterConnections fetches pages lazily. Breaking the loop stops further requests. +func (c *Client) IterConnections(ctx context.Context, customer string, limit int) iter.Seq2[Connection, error] { + return iterate(ctx, "", func(cursor string) (Page[Connection], error) { return c.Connections(ctx, customer, cursor, limit) }) +} +func (c *Client) IterAccounts(ctx context.Context, connectionID string, limit int) iter.Seq2[Account, error] { + return iterate(ctx, "", func(cursor string) (Page[Account], error) { return c.Accounts(ctx, connectionID, cursor, limit) }) +} +func (c *Client) IterTransactions(ctx context.Context, accountID string, limit int) iter.Seq2[Transaction, error] { + return iterate(ctx, "", func(cursor string) (Page[Transaction], error) { return c.Transactions(ctx, accountID, cursor, limit) }) +} +func (c *Client) IterSearchTransactions(ctx context.Context, filter TransactionFilter) iter.Seq2[Transaction, error] { + return iterate(ctx, filter.Cursor, func(cursor string) (Page[Transaction], error) { + pageFilter := filter + pageFilter.Cursor = cursor + return c.SearchTransactions(ctx, pageFilter) + }) +} diff --git a/iterator_test.go b/iterator_test.go new file mode 100644 index 0000000..feca82a --- /dev/null +++ b/iterator_test.go @@ -0,0 +1,110 @@ +package ranjit + +import ( + "context" + "errors" + "net/http" + "testing" +) + +func TestIteratorsFetchLazilyAndPreserveFilters(t *testing.T) { + c, _ := NewClient("http://localhost:8080", "key") + calls := 0 + c.HTTPClient.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + calls++ + q := r.URL.Query() + if q.Get("customer_id") != "customer" || q.Get("q") != "cafe" || q.Get("limit") != "1" { + t.Fatal("filters lost", q) + } + if q.Get("cursor") == "" { + return testResponse(r, 200, `{"data":[{"id":"first"}],"next_cursor":"second-page"}`), nil + } + if q.Get("cursor") != "second-page" { + t.Fatal("cursor lost") + } + return testResponse(r, 200, `{"data":[{"id":"second"}]}`), nil + }) + seq := c.IterSearchTransactions(t.Context(), TransactionFilter{CustomerID: "customer", Query: "cafe", Limit: 1}) + if calls != 0 { + t.Fatal("eager request") + } + for row, err := range seq { + if err != nil || row.ID != "first" { + t.Fatal(row, err) + } + break + } + if calls != 1 { + t.Fatal("fetched after break", calls) + } + calls = 0 + var ids []string + for row, err := range c.IterSearchTransactions(t.Context(), TransactionFilter{CustomerID: "customer", Query: "cafe", Limit: 1}) { + if err != nil { + t.Fatal(err) + } + ids = append(ids, row.ID) + } + if calls != 2 || len(ids) != 2 || ids[1] != "second" { + t.Fatal(ids, calls) + } +} + +func TestIteratorCancellationAndCursorCycles(t *testing.T) { + c, _ := NewClient("http://localhost:8080", "key") + calls := 0 + c.HTTPClient.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + calls++ + return testResponse(r, 200, `{"data":[{"id":"first"},{"id":"second"}],"next_cursor":"cycle"}`), nil + }) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + seen := 0 + for _, err := range c.IterAccounts(ctx, "con", 2) { + if err != nil { + if !errors.Is(err, context.Canceled) { + t.Fatal(err) + } + break + } + seen++ + cancel() + } + if seen != 1 || calls != 1 { + t.Fatal("cancellation ignored", seen, calls) + } + calls = 0 + var failure error + for _, err := range c.IterConnections(t.Context(), "customer", 2) { + if err != nil { + failure = err + break + } + } + if !errors.Is(failure, ErrInvalidResponse) || calls != 2 { + t.Fatal("cursor cycle accepted", failure, calls) + } +} + +func TestIteratorCanBeTraversedAgain(t *testing.T) { + c, _ := NewClient("http://localhost:8080", "key") + c.HTTPClient.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + if r.URL.Query().Get("cursor") == "" { + return testResponse(r, 200, `{"data":[{"id":"first"}],"next_cursor":"second"}`), nil + } + return testResponse(r, 200, `{"data":[{"id":"second"}]}`), nil + }) + sequence := c.IterSearchTransactions(t.Context(), TransactionFilter{CustomerID: "customer", Limit: 1}) + for i := 0; i < 2; i++ { + var ids []string + for item, err := range sequence { + if err != nil { + t.Fatal(err) + } + ids = append(ids, item.ID) + } + if len(ids) != 2 || ids[0] != "first" { + t.Fatal("iterator retained a previous traversal's cursor", ids) + } + } +} diff --git a/model.go b/model.go index 59d514e..e34bcf1 100644 --- a/model.go +++ b/model.go @@ -11,6 +11,10 @@ import ( ) var ( + ErrUnauthorized = errors.New("unauthorized") + ErrRateLimited = errors.New("rate limited") + ErrResponseTooLarge = errors.New("response exceeds 1 MiB") + ErrInvalidResponse = errors.New("invalid response") ErrWebhookState = errors.New("webhook is not failed or does not belong to the configured endpoint") ErrIdempotency = errors.New("idempotency key was already used with a different request") ErrNotFound = errors.New("not found") diff --git a/retry.go b/retry.go new file mode 100644 index 0000000..70cd148 --- /dev/null +++ b/retry.go @@ -0,0 +1,180 @@ +package ranjit + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "math/rand/v2" + "net" + "net/http" + "strconv" + "syscall" + "time" +) + +const maxResponseBytes = 1 << 20 + +// RetryPolicy applies only to GET requests. Configure it before sharing a Client. +// The zero value makes one attempt, preserving the default client behavior. +type RetryPolicy struct { + MaxAttempts int + MaxElapsedTime time.Duration + BaseDelay time.Duration + MaxDelay time.Duration +} + +func (p RetryPolicy) normalized() (RetryPolicy, error) { + if p.MaxAttempts == 0 { + p.MaxAttempts = 1 + } + if p.MaxAttempts < 1 || p.MaxAttempts > 10 || p.MaxElapsedTime < 0 || p.BaseDelay < 0 || p.MaxDelay < 0 { + return p, ErrInvalid + } + if p.MaxElapsedTime == 0 { + p.MaxElapsedTime = 30 * time.Second + } + if p.BaseDelay == 0 { + p.BaseDelay = 200 * time.Millisecond + } + if p.MaxDelay == 0 { + p.MaxDelay = 2 * time.Second + } + if p.MaxElapsedTime > 5*time.Minute || p.MaxDelay > time.Minute || p.BaseDelay > p.MaxDelay { + return p, ErrInvalid + } + return p, nil +} + +func (c *Client) send(req *http.Request, output any) error { + req.Header.Set("Authorization", "Bearer "+c.apiKey) + req.Header.Set("Accept", "application/json") + policy := RetryPolicy{MaxAttempts: 1} + if req.Method == http.MethodGet { + policy = c.ReadRetries + } + policy, err := policy.normalized() + if err != nil { + return err + } + if policy.MaxAttempts > 1 { + ctx, cancel := context.WithTimeout(req.Context(), policy.MaxElapsedTime) + defer cancel() + req = req.Clone(ctx) + } + for attempt := 1; ; attempt++ { + retryAfter, err := c.sendOnce(req, output) + if err == nil || attempt >= policy.MaxAttempts { + return err + } + if req.Context().Err() != nil { + return req.Context().Err() + } + if !canRetryRead(err) { + return err + } + delay := min(policy.BaseDelay*time.Duration(1< maxResponseBytes { + problem.Code, problem.Message, problem.Cause = "response_too_large", "response exceeds 1 MiB", ErrResponseTooLarge + return 0, problem + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + var envelope struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if json.Unmarshal(data, &envelope) == nil { + problem.Code, problem.Message = envelope.Error.Code, envelope.Error.Message + } + if problem.Message == "" { + problem.Message = http.StatusText(resp.StatusCode) + } + return retryAfter, problem + } + if output == nil { + return 0, nil + } + decoder := json.NewDecoder(bytes.NewReader(data)) + if err = decoder.Decode(output); err != nil || decoder.Decode(new(any)) != io.EOF { + problem.Code, problem.Message, problem.Cause = "invalid_response", "response is not a single JSON value", ErrInvalidResponse + return 0, problem + } + return 0, nil +} + +func parseRetryAfter(value string, now time.Time) time.Duration { + if seconds, err := strconv.ParseInt(value, 10, 64); err == nil { + if seconds <= 0 { + return 0 + } + // Values beyond the maximum read budget must not overflow into an early retry. + return time.Duration(min(seconds, 86400)) * time.Second + } + if date, err := http.ParseTime(value); err == nil { + return max(0, date.Sub(now)) + } + return 0 +} + +func canRetryRead(err error) bool { + if errors.Is(err, context.Canceled) || errors.Is(err, ErrResponseTooLarge) || errors.Is(err, ErrInvalidResponse) { + return false + } + var api *APIError + if errors.As(err, &api) { + switch api.StatusCode { + case 408, 429, 500, 502, 503, 504: + return true + } + return transientTransport(api.Cause) + } + return transientTransport(err) +} + +func transientTransport(err error) bool { + if err == nil { + return false + } + var network net.Error + return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.EPIPE) || errors.As(err, &network) && (network.Timeout() || network.Temporary()) +} + +func (e *APIError) Unwrap() error { return e.Cause } +func (e *APIError) Is(target error) bool { + if e.StatusCode == 401 && target == ErrUnauthorized || e.StatusCode == 429 && target == ErrRateLimited { + return true + } + codes := map[string]error{"not_found": ErrNotFound, "inactive_connection": ErrConflict, "invalid_request": ErrInvalid, "invalid_authorization": ErrConsent, "provider_credentials": ErrProviderCredentials, "provider_unavailable": ErrProviderUnavailable, "idempotency_conflict": ErrIdempotency, "webhook_not_retryable": ErrWebhookState} + return codes[e.Code] != nil && codes[e.Code] == target +} diff --git a/retry_test.go b/retry_test.go new file mode 100644 index 0000000..bb171c5 --- /dev/null +++ b/retry_test.go @@ -0,0 +1,103 @@ +package ranjit + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + "time" +) + +func testResponse(r *http.Request, status int, body string) *http.Response { + return &http.Response{StatusCode: status, Header: http.Header{"X-Request-Id": {"req-test"}}, Body: io.NopCloser(strings.NewReader(body)), Request: r} +} + +func TestReadRetriesAreBoundedAndNeverRepeatWrites(t *testing.T) { + c, _ := NewClient("http://localhost:8080", "key") + c.ReadRetries = RetryPolicy{MaxAttempts: 3, BaseDelay: time.Millisecond, MaxDelay: time.Millisecond, MaxElapsedTime: time.Second} + calls := 0 + c.HTTPClient.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + calls++ + if calls < 3 { + return testResponse(r, 503, `{"error":{"code":"unavailable","message":"try later"}}`), nil + } + return testResponse(r, 200, `{"data":[]}`), nil + }) + if _, err := c.Institutions(t.Context()); err != nil || calls != 3 { + t.Fatal(calls, err) + } + calls = 0 + if _, err := c.ConnectWithKey(t.Context(), ConnectRequest{CustomerID: "customer", InstitutionID: "sandbox-bank"}, "operation-key-1234"); err == nil || calls != 1 { + t.Fatal("write retried", calls, err) + } + calls = 0 + c.HTTPClient.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + calls++ + if calls == 1 { + return nil, io.EOF + } + return testResponse(r, 200, `{"data":[]}`), nil + }) + if _, err := c.Institutions(t.Context()); err != nil || calls != 2 { + t.Fatal("transport failure not recovered", calls, err) + } +} + +func TestRetryAfterBudgetCancellationAndPermanentErrors(t *testing.T) { + c, _ := NewClient("http://localhost:8080", "key") + c.ReadRetries = RetryPolicy{MaxAttempts: 3, MaxElapsedTime: 20 * time.Millisecond} + calls := 0 + c.HTTPClient.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + calls++ + resp := testResponse(r, 429, `{"error":{"code":"rate_limited","message":"later"}}`) + resp.Header.Set("Retry-After", "60") + return resp, nil + }) + _, err := c.Institutions(t.Context()) + var api *APIError + if !errors.Is(err, ErrRateLimited) || !errors.As(err, &api) || api.RequestID != "req-test" || calls != 1 { + t.Fatal(calls, err) + } + if got := parseRetryAfter(time.Now().Add(time.Hour).UTC().Format(http.TimeFormat), time.Now()); got < 59*time.Minute { + t.Fatal(got) + } + if got := parseRetryAfter("9223372036854775807", time.Now()); got < time.Hour { + t.Fatal("overflowed delay", got) + } + c.ReadRetries = RetryPolicy{MaxAttempts: 3, MaxElapsedTime: time.Second, BaseDelay: time.Second, MaxDelay: time.Second} + ctx, cancel := context.WithCancel(t.Context()) + calls = 0 + c.HTTPClient.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + calls++ + cancel() + return testResponse(r, 503, `{}`), nil + }) + if _, err = c.Institutions(ctx); !errors.Is(err, context.Canceled) || calls != 1 { + t.Fatal(calls, err) + } + calls = 0 + c.HTTPClient.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + calls++ + return testResponse(r, 401, `{"error":{"code":"unauthorized","message":"invalid key"}}`), nil + }) + if _, err = c.Institutions(t.Context()); !errors.Is(err, ErrUnauthorized) || calls != 1 { + t.Fatal(calls, err) + } +} + +func TestClientRejectsOversizedAndTrailingResponses(t *testing.T) { + c, _ := NewClient("http://localhost:8080", "key") + for _, tt := range []struct { + body string + want error + }{{`{"data":[]}` + strings.Repeat(" ", maxResponseBytes), ErrResponseTooLarge}, {`{"data":[]} {"extra":true}`, ErrInvalidResponse}} { + c.HTTPClient.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { return testResponse(r, 200, tt.body), nil }) + _, err := c.Institutions(t.Context()) + var api *APIError + if !errors.Is(err, tt.want) || !errors.As(err, &api) || api.StatusCode != 200 || api.RequestID != "req-test" { + t.Fatal(err) + } + } +} diff --git a/scripts/compatibility.Dockerfile b/scripts/compatibility.Dockerfile new file mode 100644 index 0000000..78aa2b1 --- /dev/null +++ b/scripts/compatibility.Dockerfile @@ -0,0 +1,7 @@ +# PostgreSQL tools match the CI server. The compatibility runner uses only the +# Python standard library and exercises released/candidate executables. +FROM postgres:17-bookworm +RUN apt-get update && apt-get install -y --no-install-recommends python3 ca-certificates \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /work +ENTRYPOINT ["python3", "scripts/upgrade_smoke.py"] diff --git a/scripts/container_upgrade.sh b/scripts/container_upgrade.sh new file mode 100755 index 0000000..b8845ea --- /dev/null +++ b/scripts/container_upgrade.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Actual released image -> candidate, using an isolated synthetic-data volume. +set -eu +candidate=${1:?Usage: scripts/container_upgrade.sh candidate-image} +volume="ranjit-upgrade-$$" +temporary=$(mktemp -d) +cleanup() { + docker volume rm "$volume" >/dev/null 2>&1 || true + rm -rf "$temporary" +} +trap cleanup EXIT HUP INT TERM +docker volume create "$volume" >/dev/null +docker run --rm -v "$volume:/data" ghcr.io/getcortexlabs/ranjit:v0.3.0 demo +docker run --rm -v "$volume:/data" ghcr.io/getcortexlabs/ranjit:v0.3.0 transactions --json > "$temporary/before.json" +docker run --rm -v "$volume:/data" ghcr.io/getcortexlabs/ranjit:v0.3.0 backup /data/before.db +docker run --rm -v "$volume:/data" "$candidate" doctor +docker run --rm -v "$volume:/data" "$candidate" transactions --json > "$temporary/after.json" +cmp "$temporary/before.json" "$temporary/after.json" +docker run --rm -v "$volume:/data" "$candidate" transactions --json > "$temporary/restarted.json" +cmp "$temporary/before.json" "$temporary/restarted.json" +printf '%s\n' 'Released container upgrade and restart preserved all transactions.' diff --git a/scripts/quickstart.sh b/scripts/quickstart.sh new file mode 100755 index 0000000..e7a3dbe --- /dev/null +++ b/scripts/quickstart.sh @@ -0,0 +1,22 @@ +#!/bin/sh +set -eu +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +config="$root/examples/quickstart" +compose() { + docker compose --env-file "$config/.env" -f "$config/compose.yaml" "$@" +} +case "${1:-start}" in + start) + docker build --target tools -f "$config/Dockerfile" -t ranjit-quickstart-tools "$root" + docker run --rm --user "$(id -u):$(id -g)" -v "$config:/config" ranjit-quickstart-tools init + compose up --build --force-recreate --wait --wait-timeout 120 ranjit backend receiver + compose run --rm --no-deps verify + ;; + verify) compose run --rm --no-deps verify ;; + stop) compose down ;; + reset) + # Explicitly requested demo reset. Keep the generated credentials. + compose down --volumes + ;; + *) printf '%s\n' 'Usage: scripts/quickstart.sh [start|verify|stop|reset]' >&2; exit 2 ;; +esac diff --git a/scripts/server_smoke.py b/scripts/server_smoke.py index 2b9fd79..5aad8c5 100644 --- a/scripts/server_smoke.py +++ b/scripts/server_smoke.py @@ -101,8 +101,11 @@ def do_POST(self): timestamp = timestamp.removeprefix("t=") want = hmac.new(webhook_secret.encode(), timestamp.encode() + b"." + body, hashlib.sha256).hexdigest() valid = hmac.compare_digest(digest, "v1=" + want) and abs(int(timestamp) - time.time()) < 300 - received.put((body, valid, signature)) - self.send_response(503 if received.qsize() == 1 else 204) + if json.loads(body)["type"] == "sync.succeeded": + received.put((body, valid, signature)) + self.send_response(503 if received.qsize() == 1 else 204) + else: + self.send_response(204) self.end_headers() def log_message(self, *_): @@ -132,7 +135,7 @@ def create_connection(): def wait_delivery(status): for _ in range(60): - deliveries = request(base + "/v1/webhooks/deliveries", service_key)["data"] + deliveries = [d for d in request(base + "/v1/webhooks/deliveries", service_key)["data"] if d["event"]["type"] == "sync.succeeded"] if deliveries and deliveries[0]["status"] == status and deliveries[0]["attempts"] > 0: return deliveries[0] time.sleep(0.5) diff --git a/scripts/upgrade_smoke.py b/scripts/upgrade_smoke.py new file mode 100644 index 0000000..d71061f --- /dev/null +++ b/scripts/upgrade_smoke.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Upgrade actual v0.3.0 data in disposable SQLite/PostgreSQL installations.""" +import argparse +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path +import platform +import secrets +import shutil +import socket +import sqlite3 +import subprocess +import tarfile +import tempfile +import time +import urllib.error +import urllib.parse +import urllib.request + +ROOT = Path(__file__).resolve().parent.parent +SAMPLE = b"id,date,description,amount\nupgrade-1,2026-11-01,Fixture,100.00\nupgrade-2,2026-11-02,Fixture debit,-12.50\n" +BASE_ENV = {k: v for k, v in os.environ.items() if not k.startswith("RANJIT_")} + + +def run(command, env, **kwargs): + result = subprocess.run(command, env=env, capture_output=True, **kwargs) + if result.returncode: + # Do not echo connection strings, keys, database output or raw server logs. + raise RuntimeError(f"{Path(str(command[0])).name} failed ({result.returncode})") + return result.stdout + + +def released_binary(directory): + system = "darwin" if platform.system() == "Darwin" else "linux" + arch = "arm64" if platform.machine() in ("arm64", "aarch64") else "amd64" + name = f"ranjit_v0.3.0_{system}_{arch}.tar.gz" + base = "https://github.com/getcortexlabs/ranjit/releases/download/v0.3.0/" + with urllib.request.urlopen(base + "checksums.txt", timeout=60) as response: + sums = {line.split()[1]: line.split()[0] for line in response.read().decode().splitlines()} + with urllib.request.urlopen(base + name, timeout=60) as response: + content = response.read() + assert hashlib.sha256(content).hexdigest() == sums[name], "v0.3.0 checksum mismatch" + archive = directory / name + archive.write_bytes(content) + old = directory / "ranjit-v0.3.0" + with tarfile.open(archive) as bundle: + old.write_bytes(bundle.extractfile("ranjit").read()) + old.chmod(0o755) + assert run([old, "version"], BASE_ENV).strip() == b"v0.3.0" + return old + + +def request(base, key, path, data=None, method=None, content_type="application/json"): + if isinstance(data, dict): + data = json.dumps(data).encode() + req = urllib.request.Request(base + path, data=data, method=method, + headers={"Authorization": "Bearer " + key, "Content-Type": content_type}) + with urllib.request.urlopen(req, timeout=5) as response: + payload = response.read() + return json.loads(payload) if payload else None + + +def wait(check): + for _ in range(150): + try: + result = check() + if result: + return result + except (urllib.error.URLError, TimeoutError, ConnectionResetError): + pass + time.sleep(0.1) + raise AssertionError("service did not reach expected state") + + +@contextmanager +def server(binary, env, base, key): + child = subprocess.Popen([binary, "serve"], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + wait(lambda: child.poll() is None and request(base, key, "/readyz")) + yield + finally: + child.terminate() + try: + child.wait(timeout=10) + except subprocess.TimeoutExpired: + child.kill() + child.wait() + + +def pg_env(dsn): + u = urllib.parse.urlsplit(dsn) + env = dict(BASE_ENV, PGHOST=u.hostname, PGPORT=str(u.port or 5432), PGUSER=urllib.parse.unquote(u.username or ""), + PGPASSWORD=urllib.parse.unquote(u.password or ""), PGDATABASE=u.path.lstrip("/")) + env["PGSSLMODE"] = urllib.parse.parse_qs(u.query).get("sslmode", ["prefer"])[0] + return env + + +def exercise(old, candidate, directory, postgres=None): + directory.mkdir() + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + base = f"http://127.0.0.1:{port}" + key = secrets.token_hex(32) + env = dict(BASE_ENV, RANJIT_API_KEY=key, RANJIT_ADDR=f"127.0.0.1:{port}", RANJIT_BASE_URL=base, + RANJIT_URL=base, RANJIT_PROVIDER="sandbox", XDG_CONFIG_HOME=str(directory)) + path, before_backup = directory / "ranjit.db", directory / "before.db" + config = directory / "config.json" + if postgres: + env["RANJIT_DATABASE_URL"] = postgres + sqlenv = pg_env(postgres) + else: + # A real v0.3 personal config is read unchanged by the candidate. + config.write_text(json.dumps(dict(version=1, database=str(path), api_key=key, + addr=f"127.0.0.1:{port}", base_url=base, sync_interval="1h", profiles=[dict(name="demo", provider="sandbox")]))) + config.chmod(0o600) + env["RANJIT_CONFIG"] = str(config) + del env["RANJIT_API_KEY"] + original_config = config.read_bytes() if config.exists() else None + + def sql(query): + if postgres: + return run(["psql", "-X", "-v", "ON_ERROR_STOP=1", "-At", "-c", query], sqlenv).decode().strip() + with sqlite3.connect(path) as db: + row = db.execute(query).fetchone() + return str(row[0]) if row else "" + + def records(): + return request(base, key, "/v1/transactions?customer_id=upgrade&limit=100")["data"] + + with server(old, env, base, key): + imported = request(base, key, "/v1/imports?customer_id=upgrade&account=fixture&format=csv", SAMPLE, content_type="text/csv") + connection = imported["connection_id"] + financial = records() + assert sorted(r["amount"]["amount_minor"] for r in financial) == [-1250, 10000] + institutions = request(base, key, "/v1/institutions")["data"] + pending = request(base, key, "/v1/connections", dict(customer_id="upgrade-sandbox", institution_id=institutions[0]["id"])) + # A pending job is staged while stopped to deterministically test recovery. + now = int(time.time() * 1000) + sid = pending["connection"]["id"] + sql(f"UPDATE connections SET status='active',token_hash=NULL WHERE id='{sid}'") + sql(f"INSERT INTO jobs(id,connection_id,status,attempts,error_code,created_at,updated_at,available_at,lease_until,lease_token,requests_completed) VALUES('job-upgrade','{sid}','queued',0,'',{now},{now},{now},0,'',0)") + # Synthetic direct grant: no bank is called and the credential binding is fake. + sql(f"INSERT INTO connections(id,customer_id,institution_id,provider,status,created_at,consent_expires_at,last_synced_at,token_hash,authorization_expires_at,authorization_mode,credential_id) VALUES('con-direct-fixture','upgrade-direct','efi','efi','active',{now},{now+86400000},NULL,NULL,0,'api_credentials','synthetic-binding')") + if postgres: + before_backup.write_bytes(run(["pg_dump", "--format=custom", "--no-owner", "--no-acl"], sqlenv)) + else: + run([old, "backup", str(before_backup)], env) + assert sql("SELECT count(*) FROM schema_migrations") in ("1", "6") + + for _ in range(2): + with server(candidate, env, base, key): + assert records() == financial + assert request(base, key, f"/v1/connections/{connection}")["status"] == "active" + wait(lambda: request(base, key, "/v1/jobs/job-upgrade")["status"] == "succeeded") + assert request(base, key, f"/v1/connections/{sid}/status")["transactions"] == 4 + report_env = dict(BASE_ENV, RANJIT_URL=base, RANJIT_API_KEY=key, RANJIT_CONFIG=str(directory / "must-not-exist.json")) + report = json.loads(run([candidate, "doctor", "--remote", "--json"], report_env)) + assert report["schema_version"] == 1 and report["status"] in ("ok", "warning") + assert not (directory / "must-not-exist.json").exists() + assert sql("SELECT count(*) FROM webhook_deliveries") == "0" + assert sql("SELECT count(*) FROM connection_requests") == "0" + if config.exists(): + assert config.read_bytes() == original_config + + if not postgres: + after_backup = directory / "after.db" + run([candidate, "backup", str(after_backup)], env) + # Seed one pending notification to prove restore never replays an outbox. + sql(f"INSERT INTO webhook_deliveries(id,job_id,connection_id,event_type,payload,target_hash,status,attempts,created_at,updated_at,available_at,lease_until,lease_token,error_code) VALUES('evt-fixture',NULL,'con-direct-fixture','connection.activated','{{}}','fixture','queued',0,{now},{now},{now},0,'','')") + run([candidate, "backup", str(directory / "outbox.db")], env) + run([candidate, "restore", "--replace", str(directory / "outbox.db")], env) + assert sql("SELECT status FROM connections WHERE id='con-direct-fixture'") == "paused" + assert sql("SELECT count(*) FROM webhook_deliveries") == "0" + assert sql("SELECT count(*) FROM jobs WHERE status IN ('queued','running')") == "0" + with server(candidate, env, base, key): + assert records() == financial + # Roll back using the old executable AND its compatible pre-upgrade copy. + for suffix in ("", "-wal", "-shm"): + Path(str(path) + suffix).unlink(missing_ok=True) + shutil.copy2(before_backup, path) + else: + # Roll back only this disposable database, never the caller's database. + sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public") + run(["pg_restore", "--no-owner", "--no-acl", "--dbname", sqlenv["PGDATABASE"], str(before_backup)], sqlenv) + with server(old, env, base, key): + assert records() == financial + print(f"{'PostgreSQL' if postgres else 'SQLite'}: actual v0.3.0 upgrade, records, jobs, restart and rollback passed", flush=True) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("candidate", type=Path) + args = parser.parse_args() + candidate = args.candidate.resolve() + with tempfile.TemporaryDirectory(prefix="ranjit-upgrade-") as temporary: + directory = Path(temporary) + old = released_binary(directory) + exercise(old, candidate, directory / "sqlite") + dsn = os.environ.get("RANJIT_TEST_POSTGRES_URL") + if dsn: + admin = pg_env(dsn) + name = "ranjit_upgrade_" + secrets.token_hex(6) + run(["createdb", name], admin) + u = urllib.parse.urlsplit(dsn) + isolated = urllib.parse.urlunsplit(u._replace(path="/" + name)) + try: + exercise(old, candidate, directory / "postgres", isolated) + finally: + run(["dropdb", "--if-exists", name], admin) + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_release.py b/scripts/verify_release.py new file mode 100644 index 0000000..6516bdd --- /dev/null +++ b/scripts/verify_release.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Verify archives locally, then published downloads, SDK and anonymous images.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import subprocess +import sys +import tarfile +import tempfile +import urllib.request +import zipfile + +TARGETS = ("linux_amd64", "linux_arm64", "darwin_amd64", "darwin_arm64", "windows_amd64", "windows_arm64") + + +def archives(directory, version, online=False): + sums = {} + for line in (directory / "checksums.txt").read_text().splitlines(): + digest, name = line.split() + if name in sums or Path(name).name != name or not re.fullmatch(r"[0-9a-f]{64}", digest): + raise ValueError("invalid checksum entry") + sums[name] = digest + for target in TARGETS: + windows = target.startswith("windows") + name = f"ranjit_{version}_{target}.{'zip' if windows else 'tar.gz'}" + path = directory / name + assert hashlib.sha256(path.read_bytes()).hexdigest() == sums[name], f"checksum mismatch: {name}" + if windows: + with zipfile.ZipFile(path) as bundle: + assert {"ranjit.exe", "LICENSE", "README.md"} <= set(bundle.namelist()) + else: + with tarfile.open(path) as bundle: + assert {"ranjit", "LICENSE", "README.md"} <= set(bundle.getnames()) + for name, digest in sums.items(): + assert hashlib.sha256((directory / name).read_bytes()).hexdigest() == digest, f"checksum mismatch: {name}" + system = "darwin" if platform.system() == "Darwin" else "linux" + arch = "arm64" if platform.machine() in ("arm64", "aarch64") else "amd64" + with tempfile.TemporaryDirectory(prefix="ranjit-release-check-") as temporary: + env = {k: v for k, v in os.environ.items() if not k.startswith("RANJIT_")} + destination = Path(temporary) / "bin with spaces" + env.update(RANJIT_INSTALL_DIR=str(destination), RANJIT_VERSION=version) + if not online: + # Before publication, only the HTTPS transport is substituted. The + # installer verifies and installs the actual candidate archive. + shim = Path(temporary) / "tools" + shim.mkdir() + curl = shim / "curl" + curl.write_text(f"#!{sys.executable}\n" + '''import os, pathlib, shutil, sys, urllib.parse +args = sys.argv[1:] +url = next(a for a in args if a.startswith("https://")) +name = pathlib.PurePosixPath(urllib.parse.urlsplit(url).path).name +shutil.copyfile(pathlib.Path(os.environ["RELEASE_FIXTURES"]) / name, args[args.index("-o") + 1]) +''') + curl.chmod(0o755) + env["PATH"] = str(shim) + os.pathsep + env["PATH"] + env["RELEASE_FIXTURES"] = str(directory.resolve()) + installer = directory / "install.sh" if online else Path(__file__).resolve().parent.parent / "install.sh" + subprocess.run(["sh", installer], env=env, check=True, stdout=subprocess.DEVNULL) + binary = destination / "ranjit" + assert subprocess.check_output([binary, "version"], text=True).strip() == version + env["RANJIT_CONFIG"] = str(Path(temporary) / "config.json") + subprocess.run([binary, "demo"], env=env, check=True, stdout=subprocess.DEVNULL) + rows = json.loads(subprocess.check_output([binary, "transactions", "--json"], env=env)) + assert len(rows) == 8, "first-use fixture missing (two sandbox institutions)" + print("Six archives: checksums and contents passed; native binary version and first use passed", flush=True) + + +def images(version): + # An empty Docker config prevents local/GitHub credentials masking visibility. + with tempfile.TemporaryDirectory(prefix="ranjit-anonymous-") as temporary: + for arch in ("amd64", "arm64"): + subprocess.run(["docker", "--config", temporary, "pull", "--platform", f"linux/{arch}", f"ghcr.io/getcortexlabs/ranjit:{version}"], check=True) + print("Anonymous pulls passed for linux/amd64 and linux/arm64", flush=True) + + +def published(version): + base = f"https://github.com/getcortexlabs/ranjit/releases/download/{version}/" + with tempfile.TemporaryDirectory(prefix="ranjit-published-") as temporary: + directory = Path(temporary) + with urllib.request.urlopen(base + "checksums.txt", timeout=60) as response: + checksums = response.read() + (directory / "checksums.txt").write_bytes(checksums) + for line in checksums.decode().splitlines(): + _, name = line.split() + if Path(name).name != name: + raise ValueError("invalid asset path") + with urllib.request.urlopen(base + name, timeout=120) as response, (directory / name).open("wb") as output: + while chunk := response.read(1 << 20): + output.write(chunk) + archives(directory, version, online=True) + env = dict(os.environ, GOPROXY="direct") + module = json.loads(subprocess.check_output(["go", "mod", "download", "-json", f"github.com/getcortexlabs/ranjit@{version}"], env=env)) + assert module["Version"] == version and module["Sum"], "published SDK unavailable" + images(version) + print("Public downloads, Go SDK tag and container distribution passed", flush=True) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--version", required=True) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--artifacts", type=Path) + group.add_argument("--images", action="store_true") + group.add_argument("--published", action="store_true") + args = parser.parse_args() + if not re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+", args.version): + parser.error("expected stable semantic version") + if args.artifacts: + archives(args.artifacts, args.version) + elif args.images: + images(args.version) + else: + published(args.version) + + +if __name__ == "__main__": + main() diff --git a/webhook.go b/webhook.go index 542dbd0..958af7e 100644 --- a/webhook.go +++ b/webhook.go @@ -22,9 +22,10 @@ type WebhookEvent struct { } type WebhookData struct { - JobID string `json:"job_id"` + Status string `json:"status,omitempty"` + JobID string `json:"job_id,omitempty"` ConnectionID string `json:"connection_id"` - CustomerID string `json:"customer_id"` + CustomerID string `json:"customer_id,omitempty"` ErrorCode string `json:"error_code,omitempty"` } @@ -65,7 +66,13 @@ func VerifyWebhook(body []byte, signature, secret string, now time.Time) (Webhoo if !hmac.Equal(digest, mac.Sum(nil)) { return event, invalid } - if err := json.Unmarshal(body, &event); err != nil || event.ID == "" || event.Type == "" || event.CreatedAt.IsZero() || event.Data.JobID == "" || event.Data.ConnectionID == "" || event.Data.CustomerID == "" { + if err := json.Unmarshal(body, &event); err != nil || event.ID == "" || event.Type == "" || event.CreatedAt.IsZero() || event.Data.ConnectionID == "" { + return WebhookEvent{}, invalid + } + if strings.HasPrefix(event.Type, "sync.") && (event.Data.JobID == "" || event.Data.CustomerID == "") { + return WebhookEvent{}, invalid + } + if strings.HasPrefix(event.Type, "connection.") && (event.Data.Status == "" || event.Type != "connection.revoked" && event.Data.CustomerID == "") { return WebhookEvent{}, invalid } return event, nil diff --git a/webhook_test.go b/webhook_test.go index 7f2aff3..6bb773a 100644 --- a/webhook_test.go +++ b/webhook_test.go @@ -49,3 +49,25 @@ func TestVerifyWebhookRejectsTamperingAndReplay(t *testing.T) { }) } } + +func TestVerifyLifecycleWebhooksWithoutJob(t *testing.T) { + now := time.Now().UTC() + secret := strings.Repeat("s", 40) + for _, kind := range []string{"activated", "denied", "paused", "expired", "renewed", "revoked"} { + t.Run(kind, func(t *testing.T) { + data := WebhookData{ConnectionID: "con-test", Status: "active", CustomerID: "customer"} + if kind == "revoked" { + data.Status, data.CustomerID = "revoked", "" + } + body, _ := json.Marshal(WebhookEvent{ID: "evt-test", Type: "connection." + kind, CreatedAt: now, Data: data}) + ts := strconv.FormatInt(now.Unix(), 10) + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(ts + ".")) + mac.Write(body) + event, err := VerifyWebhook(body, "t="+ts+",v1="+hex.EncodeToString(mac.Sum(nil)), secret, now) + if err != nil || event.Data.JobID != "" { + t.Fatal(event, err) + } + }) + } +}