Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
.github
.env
.env.*
**/.env
**/.env.*
**/node_modules
data
bin
dist
Expand Down
18 changes: 18 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
36 changes: 31 additions & 5 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 }}
Expand All @@ -68,23 +82,35 @@ 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 }}
REGISTRY_USER: ${{ github.actor }}
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"
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
33 changes: 5 additions & 28 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions cmd/ranjit/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
23 changes: 22 additions & 1 deletion cmd/ranjit/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
152 changes: 152 additions & 0 deletions cmd/ranjit/doctor_remote.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading