diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e7c9593 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +.git +.github +.cache +.env +.env.* +*.log +*.out +archive-wrapper +coverage* +tmp +v2/data +FLEXIBLE_DEPLOYMENT_REQUIREMENTS.md diff --git a/.github/workflows/container.yml b/.github/workflows/container.yml new file mode 100644 index 0000000..23c0987 --- /dev/null +++ b/.github/workflows/container.yml @@ -0,0 +1,183 @@ +name: Container + +on: + pull_request: + push: + branches: + - development + +permissions: + contents: read + +concurrency: + group: container-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + go: + name: Go validation + runs-on: ubuntu-24.04 + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + + - name: Run unit tests + env: + GOCACHE: /tmp/go-build-cache + run: go test -tags=purego ./... -count=1 + + - name: Run focused race tests + env: + GOCACHE: /tmp/go-build-cache + run: go test -race -tags=purego ./config ./cmd/archive-wrapper -count=1 + + - name: Run vet + env: + GOCACHE: /tmp/go-build-cache + run: go vet -tags=purego ./... + + - name: Run golangci-lint + uses: golangci/golangci-lint-action@v9 + with: + version: v2.11.4 + args: --build-tags=purego ./... + + - name: Verify module files + run: go mod tidy -diff + + container: + name: Container validation + needs: go + runs-on: ubuntu-24.04 + env: + IMAGE: archive-wrapper:${{ github.sha }} + BUILDER_IMAGE: archive-wrapper-builder:${{ github.sha }} + GOCACHE: /tmp/go-build-cache + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + + - name: Set up Docker Buildx + id: buildx + uses: docker/setup-buildx-action@v4 + + - name: Build multi-platform OCI image + run: | + make docker-build-multiarch \ + DOCKER_BUILDER="${{ steps.buildx.outputs.name }}" \ + IMAGE="$IMAGE" \ + OCI_OUTPUT="$RUNNER_TEMP/archive-wrapper.oci.tar" + sha256sum "$RUNNER_TEMP/archive-wrapper.oci.tar" + + - name: Verify reproducible artifacts + run: | + make reproducible-build + make reproducible-image DOCKER_BUILDER="${{ steps.buildx.outputs.name }}" + + - name: Build native test image + run: make docker-build IMAGE="$IMAGE" + + - name: Build builder stage for security scanning + run: | + docker buildx build --load --target builder --platform=linux/amd64 \ + -t "$BUILDER_IMAGE" . + + - name: Prepare security report directory + run: mkdir -p .cache/container-artifacts + + - name: Install govulncheck + env: + CGO_ENABLED: "0" + GOBIN: ${{ runner.temp }}/govulncheck-bin + run: | + mkdir -p "$GOBIN" + go install golang.org/x/vuln/cmd/govulncheck@v1.6.0 + + - name: Report reachable Go vulnerabilities + run: | + raw_report="$RUNNER_TEMP/govulncheck.sarif" + docker run --rm \ + --env GOTELEMETRY=off \ + --entrypoint /tools/govulncheck \ + --volume "$RUNNER_TEMP/govulncheck-bin:/tools:ro" \ + "$BUILDER_IMAGE" \ + -tags=purego -format sarif ./cmd/archive-wrapper \ + > "$raw_report" + jq -e ' + .runs |= map( + (.results // []) |= map(select(.level == "error")) + | . as $run + | .tool.driver.rules = [ + (.tool.driver.rules // [])[] + | select(.id as $id | any($run.results[]; .ruleId == $id)) + ] + ) + ' "$raw_report" > .cache/container-artifacts/govulncheck.sarif + + - name: Enforce builder OS vulnerability policy + uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 + with: + image-ref: ${{ env.BUILDER_IMAGE }} + format: table + exit-code: "1" + ignore-unfixed: true + vuln-type: os + severity: CRITICAL,HIGH + scanners: vuln + version: v0.73.0 + + - name: Enforce runtime OS vulnerability policy + uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 + with: + image-ref: ${{ env.IMAGE }} + format: table + exit-code: "1" + ignore-unfixed: true + vuln-type: os + severity: CRITICAL,HIGH + scanners: vuln + skip-setup-trivy: true + + - name: Run container smoke tests + env: + ARCHIVE_WRAPPER_SKIP_BUILD: "1" + ARCHIVE_WRAPPER_ARTIFACT_DIR: .cache/container-artifacts + run: make docker-test IMAGE="$IMAGE" + + - name: Upload OCI artifact + uses: actions/upload-artifact@v4 + with: + name: archive-wrapper-oci-${{ github.sha }} + path: ${{ runner.temp }}/archive-wrapper.oci.tar + if-no-files-found: error + retention-days: 7 + + - name: Upload vulnerability report + if: always() + uses: actions/upload-artifact@v4 + with: + name: go-vulnerabilities-${{ github.sha }} + path: .cache/container-artifacts/govulncheck.sarif + if-no-files-found: warn + retention-days: 7 + + - name: Upload failure diagnostics + if: failure() + uses: actions/upload-artifact@v4 + with: + name: container-failure-${{ github.sha }} + path: .cache/container-artifacts + if-no-files-found: ignore + retention-days: 7 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4fe985f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,53 @@ +# syntax=docker/dockerfile:1.10 + +ARG SOURCE_DATE_EPOCH=0 + +FROM --platform=$BUILDPLATFORM golang:1.26.5-alpine3.24@sha256:0178a641fbb4858c5f1b48e34bdaabe0350a330a1b1149aabd498d0699ff5fb2 AS builder + +ARG TARGETOS +ARG TARGETARCH +ARG VERSION=dev +ARG COMMIT_SHA=unknown +ARG BUILD_DATE=unknown + +WORKDIR /src + +COPY go.mod go.sum ./ +RUN --mount=type=cache,target=/go/pkg/mod \ + go mod download + +COPY . . +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/root/.cache/go-build \ + CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \ + go build -tags=purego -trimpath -buildvcs=false \ + -ldflags="-s -w -X 'main.version=$VERSION' -X 'main.commitSHA=$COMMIT_SHA' -X 'main.buildDate=$BUILD_DATE'" \ + -o /out/archive-wrapper ./cmd/archive-wrapper && \ + mkdir -p /out/rootfs/var/lib/archive-wrapper/data + +FROM gcr.io/distroless/static-debian12:nonroot@sha256:f5b485ea962d9bd1186b2f6b3a061191539b905b82ec395de78cbfae51f20e35 + +ARG VERSION=dev +ARG COMMIT_SHA=unknown +ARG BUILD_DATE=unknown + +LABEL org.opencontainers.image.title="archive-wrapper" \ + org.opencontainers.image.description="Mina archive sidecar for Pulsar validators" \ + org.opencontainers.image.source="https://github.com/node101-io/archive-wrapper" \ + org.opencontainers.image.version=$VERSION \ + org.opencontainers.image.revision=$COMMIT_SHA \ + org.opencontainers.image.created=$BUILD_DATE + +ENV ARCHIVE_WRAPPER_CONFIG=/etc/archive-wrapper/config.yaml \ + ARCHIVE_WRAPPER_CHAIN_HOME=/var/lib/pulsar + +COPY --from=builder --chown=65532:65532 /out/rootfs/var/lib/archive-wrapper /var/lib/archive-wrapper +COPY --from=builder --chown=65532:65532 /out/archive-wrapper /usr/local/bin/archive-wrapper + +USER 65532:65532 +EXPOSE 9095 +STOPSIGNAL SIGTERM +HEALTHCHECK --interval=10s --timeout=5s --start-period=30s --retries=6 \ + CMD ["/usr/local/bin/archive-wrapper", "healthcheck", "--timeout", "3s"] +ENTRYPOINT ["/usr/local/bin/archive-wrapper"] +CMD ["run"] diff --git a/Makefile b/Makefile index 7ccbd5b..9f95498 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,20 @@ GO_BUILD_TAGS := purego +VERSION ?= dev +COMMIT_SHA ?= $(shell git rev-parse HEAD 2>/dev/null || printf unknown) +SOURCE_DATE_EPOCH ?= $(shell git show -s --format=%ct HEAD 2>/dev/null || printf 0) +BUILD_DATE ?= $(shell date -u -d "@$(SOURCE_DATE_EPOCH)" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || printf unknown) +BUILD_LDFLAGS := -s -w -X 'main.version=$(VERSION)' -X 'main.commitSHA=$(COMMIT_SHA)' -X 'main.buildDate=$(BUILD_DATE)' + +IMAGE ?= archive-wrapper:$(COMMIT_SHA) +DOCKER_PLATFORM ?= linux/amd64 +DOCKER_PLATFORMS ?= linux/amd64,linux/arm64 +OCI_OUTPUT ?= $(CURDIR)/.cache/archive-wrapper.oci.tar +DOCKER_BUILDER ?= archive-wrapper-builder +DOCKER_BUILD_ARGS := \ + --build-arg VERSION=$(VERSION) \ + --build-arg COMMIT_SHA=$(COMMIT_SHA) \ + --build-arg BUILD_DATE=$(BUILD_DATE) \ + --build-arg SOURCE_DATE_EPOCH=$(SOURCE_DATE_EPOCH) -include .env @@ -12,13 +28,19 @@ export ARCHIVE_WRAPPER_GRPC_TRANSPORT_MODE export ARCHIVE_WRAPPER_DB_PATH export ARCHIVE_WRAPPER_CONTROL_SOCKET_PATH export ARCHIVE_WRAPPER_LOG_PATH +export ARCHIVE_WRAPPER_HEALTHCHECK_ADDRESS CONFIG ?= config.yaml -.PHONY: ensure-cache proto fmt test lint build run stop +.PHONY: ensure-cache ensure-docker-builder proto fmt test lint build run stop docker-build docker-build-multiarch docker-inspect docker-test reproducible-build reproducible-image ensure-cache: mkdir -p "$(GOCACHE)" "$(GOLANGCI_LINT_CACHE)" +ensure-docker-builder: + @docker buildx inspect $(DOCKER_BUILDER) >/dev/null 2>&1 || \ + docker buildx create --name $(DOCKER_BUILDER) --driver docker-container + @docker buildx inspect --bootstrap $(DOCKER_BUILDER) >/dev/null + proto: cd proto && buf generate --template buf.gen.gogo.yaml @@ -33,7 +55,34 @@ lint: ensure-cache golangci-lint run --build-tags=$(GO_BUILD_TAGS) ./... build: ensure-cache - go build -tags=$(GO_BUILD_TAGS) -o archive-wrapper ./cmd/archive-wrapper + go build -tags=$(GO_BUILD_TAGS) -trimpath -buildvcs=false \ + -ldflags="$(BUILD_LDFLAGS)" -o archive-wrapper ./cmd/archive-wrapper + +docker-build: ensure-cache + docker buildx build --load --platform=$(DOCKER_PLATFORM) \ + $(DOCKER_BUILD_ARGS) -t $(IMAGE) . + +docker-build-multiarch: ensure-cache ensure-docker-builder + docker buildx build --builder=$(DOCKER_BUILDER) --platform=$(DOCKER_PLATFORMS) \ + $(DOCKER_BUILD_ARGS) \ + --provenance=false \ + --output type=oci,dest=$(OCI_OUTPUT),rewrite-timestamp=true . + +docker-inspect: docker-build + docker image inspect $(IMAGE) --format '{{json .Config}}' + @docker run --rm --entrypoint /usr/local/bin/archive-wrapper $(IMAGE) version + +docker-test: + ARCHIVE_WRAPPER_IMAGE=$(IMAGE) ./scripts/test-container.sh + +reproducible-build: + VERSION=$(VERSION) COMMIT_SHA=$(COMMIT_SHA) SOURCE_DATE_EPOCH=$(SOURCE_DATE_EPOCH) \ + BUILD_DATE=$(BUILD_DATE) ./scripts/check-reproducible-build.sh + +reproducible-image: ensure-cache ensure-docker-builder + VERSION=$(VERSION) COMMIT_SHA=$(COMMIT_SHA) SOURCE_DATE_EPOCH=$(SOURCE_DATE_EPOCH) \ + BUILD_DATE=$(BUILD_DATE) DOCKER_BUILDER=$(DOCKER_BUILDER) \ + DOCKER_PLATFORMS=$(DOCKER_PLATFORMS) ./scripts/check-reproducible-image.sh run: build @test -n "$(CONFIG)" || (echo "CONFIG is required" && exit 1) diff --git a/README.md b/README.md index e3e1a54..26ade0b 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,13 @@ Build the pure-Go binary with: make build ``` +Build metadata is embedded from `VERSION`, `COMMIT_SHA`, and the current +commit timestamp. Inspect it without initializing logging or runtime resources: + +```sh +./archive-wrapper version +``` + Run the sidecar. `CHAIN_HOME` is optional when chain home is already supplied by `chain_home` or `ARCHIVE_WRAPPER_CHAIN_HOME`: @@ -157,6 +164,28 @@ The supported process environment variables are: - `ARCHIVE_WRAPPER_LOG_PATH` — optional append-only log path. Logs always go to `stderr`; when this value is non-empty they are also written to the selected file. Newly created log files use mode `0600`. +- `ARCHIVE_WRAPPER_HEALTHCHECK_ADDRESS` — optional explicit target for the + short-lived healthcheck command. It takes precedence over the effective gRPC + listen address. + +## Container image + +The repository builds a pinned, multi-stage, non-root image for `linux/amd64` +and `linux/arm64`. It contains only the statically linked wrapper binary and +distroless runtime files; config, genesis, database state, `.env` files, and +credentials must be mounted or injected at runtime. + +```sh +make docker-build +make docker-build-multiarch +make docker-inspect +make docker-test +``` + +The image defaults to `run`, handles `SIGTERM`, and includes an exec-form +healthcheck against `query.Query`. Detailed mount, ownership, read-only +filesystem, restart, and image update requirements are documented in +[`docs/container.md`](docs/container.md). ## gRPC queries @@ -185,12 +214,29 @@ PostgreSQL reconnection. They become `SERVING` only after a successful sync has created or recovered the local indexed-height cursor. A successful PostgreSQL Ping proves connectivity but does not make the query API ready. +If the current archive target is behind the persisted cursor, the wrapper +enters `WAITING_FOR_ARCHIVE` and remains `NOT_SERVING`. It never rewinds the +cursor or deletes indexed data. The supervisor retries until the archive target +catches up, then restores readiness without requiring a process restart. + +The native probe applies the same effective listener configuration as `run`. +Only `SERVING` exits successfully: + +```sh +./archive-wrapper healthcheck --config config.yaml --timeout 3s +./archive-wrapper healthcheck --address 127.0.0.1:9095 --timeout 3s +``` + +An explicit `--address` does not require a config file. When the configured +listener is `0.0.0.0` or `[::]`, the probe connects through the corresponding +loopback address inside the container. + The read-only `diagnostics.DiagnosticsService` remains available while the query API is starting or reconnecting. It reports the operational state, archive and target heights, indexed height, confirmed lag, and timestamps for the latest successful sync and operational error. Supported states are `STARTING`, `CONNECTING`, `SYNCING`, `WAITING_FOR_FINALITY`, `READY`, -`RECONNECTING`, `FAILED`, and `STOPPING`. +`RECONNECTING`, `WAITING_FOR_ARCHIVE`, `FAILED`, and `STOPPING`. For example, with the default listen address: @@ -204,8 +250,9 @@ grpcurl -plaintext \ 127.0.0.1:9095 diagnostics.DiagnosticsService/GetStatus ``` -Health status is advisory and does not reject query RPCs server-side. Clients -that require readiness gating must check or enable gRPC health checking. +Query RPCs are rejected with gRPC `Unavailable` whenever `query.Query` is +`NOT_SERVING`. Health and diagnostics remain available so operators can inspect +startup, reconnect, archive catch-up, failure, and shutdown states. ## Development checks diff --git a/apperrors/error.go b/apperrors/error.go index 5a30180..bbc7822 100644 --- a/apperrors/error.go +++ b/apperrors/error.go @@ -66,6 +66,8 @@ var ( ErrNilIndexer = errors.New("nil indexer") // ErrBlockHeightRegression reports an attempt to move the latest processed cursor backwards. ErrBlockHeightRegression = errors.New("block height cursor cannot move backwards") + // ErrArchiveTargetBehindCursor reports that the current archive source cannot verify the persisted cursor yet. + ErrArchiveTargetBehindCursor = errors.New("archive target is behind indexed cursor") // ErrInvalidBlockRange reports that the configured sync range parameters are invalid. ErrInvalidBlockRange = errors.New("invalid block range") // ErrNotificationConnectionLost reports a retryable PostgreSQL LISTEN/NOTIFY connection failure. diff --git a/cmd/archive-wrapper/buildinfo.go b/cmd/archive-wrapper/buildinfo.go new file mode 100644 index 0000000..66e9757 --- /dev/null +++ b/cmd/archive-wrapper/buildinfo.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "io" +) + +var ( + version = "dev" + commitSHA = "unknown" + buildDate = "unknown" +) + +func writeVersion(output io.Writer) error { + _, err := fmt.Fprintf( + output, + "archive-wrapper version=%s commit=%s build_date=%s\n", + version, + commitSHA, + buildDate, + ) + return err +} diff --git a/cmd/archive-wrapper/buildinfo_test.go b/cmd/archive-wrapper/buildinfo_test.go new file mode 100644 index 0000000..a207585 --- /dev/null +++ b/cmd/archive-wrapper/buildinfo_test.go @@ -0,0 +1,33 @@ +package main + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestWriteVersion(t *testing.T) { + originalVersion, originalCommit, originalDate := version, commitSHA, buildDate + t.Cleanup(func() { + version, commitSHA, buildDate = originalVersion, originalCommit, originalDate + }) + version, commitSHA, buildDate = "v1.2.3", "abc123", "2026-08-03T00:00:00Z" + + var output bytes.Buffer + require.NoError(t, writeVersion(&output)) + require.Equal( + t, + "archive-wrapper version=v1.2.3 commit=abc123 build_date=2026-08-03T00:00:00Z\n", + output.String(), + ) +} + +func TestRunMainWritesVersionToStdoutWithoutLogger(t *testing.T) { + var stdout, stderr bytes.Buffer + exitCode := runMain([]string{"version"}, &stdout, &stderr) + + require.Equal(t, exitCodeSuccess, exitCode) + require.Contains(t, stdout.String(), "archive-wrapper version=") + require.Empty(t, stderr.String()) +} diff --git a/cmd/archive-wrapper/cli.go b/cmd/archive-wrapper/cli.go index 26e454d..7893154 100644 --- a/cmd/archive-wrapper/cli.go +++ b/cmd/archive-wrapper/cli.go @@ -124,6 +124,8 @@ func usage() string { return `usage: archive-wrapper run [--config ] [--home ] [runtime overrides] archive-wrapper stop [--config ] [--control-socket-path ] + archive-wrapper healthcheck [--config ] [--address ] [--timeout ] + archive-wrapper version ` } diff --git a/cmd/archive-wrapper/healthcheck.go b/cmd/archive-wrapper/healthcheck.go new file mode 100644 index 0000000..93461e3 --- /dev/null +++ b/cmd/archive-wrapper/healthcheck.go @@ -0,0 +1,180 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "net" + "net/netip" + "strconv" + "strings" + "time" + + "github.com/node101-io/archive-wrapper/apperrors" + "github.com/node101-io/archive-wrapper/config" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + grpcHealthV1 "google.golang.org/grpc/health/grpc_health_v1" +) + +const defaultHealthcheckTimeout = 3 * time.Second + +func runHealthcheckCommand( + args []string, + lookupEnv func(string) (string, bool), +) error { + fs := flag.NewFlagSet("healthcheck", flag.ContinueOnError) + fs.SetOutput(io.Discard) + configPath := fs.String("config", "", "path to configuration file") + address := fs.String("address", "", "gRPC health target") + timeout := fs.Duration("timeout", defaultHealthcheckTimeout, "healthcheck timeout") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() != 0 { + return fmt.Errorf("healthcheck does not accept positional arguments: %q", fs.Args()) + } + if *timeout <= 0 { + return errors.New("healthcheck timeout must be greater than zero") + } + + resolvedAddress, err := resolveHealthcheckAddress( + *address, + flagWasSet(fs, "address"), + *configPath, + flagWasSet(fs, "config"), + lookupEnv, + ) + if err != nil { + return err + } + + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + return checkQueryHealth(ctx, resolvedAddress) +} + +func resolveHealthcheckAddress( + flagAddress string, + addressFlagSet bool, + flagConfigPath string, + configFlagSet bool, + lookupEnv func(string) (string, bool), +) (string, error) { + if lookupEnv == nil { + return "", errors.New("environment lookup is required") + } + + if addressFlagSet { + return healthDialAddress(flagAddress) + } + if address, ok := lookupEnv("ARCHIVE_WRAPPER_HEALTHCHECK_ADDRESS"); ok { + return healthDialAddress(address) + } + + configPath := strings.TrimSpace(flagConfigPath) + if configFlagSet { + if configPath == "" { + return "", apperrors.ErrConfigPathRequired + } + } else { + value, ok := lookupEnv("ARCHIVE_WRAPPER_CONFIG") + if !ok || strings.TrimSpace(value) == "" { + return "", apperrors.ErrConfigPathRequired + } + configPath = strings.TrimSpace(value) + } + + address, err := config.ResolveGRPCListenAddress(configPath) + if err != nil { + return "", err + } + return healthDialAddress(address) +} + +func healthDialAddress(address string) (string, error) { + if address != strings.TrimSpace(address) || address == "" { + return "", apperrors.ErrGRPCAddressRequired + } + + host, port, err := net.SplitHostPort(address) + if err != nil { + return "", fmt.Errorf("%w: %v", apperrors.ErrInvalidGRPCListenAddress, err) + } + ip, err := netip.ParseAddr(host) + if err != nil || ip.Zone() != "" { + return "", fmt.Errorf("%w: health target host must be an unscoped literal IP", apperrors.ErrInvalidGRPCListenAddress) + } + parsedPort, err := strconv.ParseUint(port, 10, 16) + if err != nil || parsedPort == 0 { + return "", fmt.Errorf("%w: port must be between 1 and 65535", apperrors.ErrInvalidGRPCListenAddress) + } + + switch { + case ip.Is4() && ip.IsUnspecified(): + ip = netip.MustParseAddr("127.0.0.1") + case ip.Is6() && ip.IsUnspecified(): + ip = netip.IPv6Loopback() + } + return net.JoinHostPort(ip.String(), port), nil +} + +func checkQueryHealth(ctx context.Context, address string) error { + connection, err := grpc.NewClient( + address, + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + if err != nil { + return errors.New("query health connection failed") + } + defer func() { _ = connection.Close() }() + + response, err := grpcHealthV1.NewHealthClient(connection).Check( + ctx, + &grpcHealthV1.HealthCheckRequest{Service: queryGRPCServiceName}, + ) + if err != nil { + return errors.New("query health check failed") + } + if response.Status != grpcHealthV1.HealthCheckResponse_SERVING { + return fmt.Errorf("query service is not serving: %s", response.Status) + } + return nil +} + +func runShortCommand( + args []string, + stdout io.Writer, + stderr io.Writer, + lookupEnv func(string) (string, bool), +) (bool, int) { + if len(args) == 0 { + return false, exitCodeSuccess + } + + switch strings.ToLower(args[0]) { + case "healthcheck": + if err := runHealthcheckCommand(args[1:], lookupEnv); err != nil { + _, _ = fmt.Fprintf(stderr, "healthcheck failed: %v\n", err) + return true, exitCodeFailure + } + return true, exitCodeSuccess + case "version": + if len(args) != 1 { + _, _ = fmt.Fprintln(stderr, "version does not accept arguments") + return true, exitCodeFailure + } + if stdout == nil { + _, _ = fmt.Fprintln(stderr, "stdout writer is required") + return true, exitCodeFailure + } + if err := writeVersion(stdout); err != nil { + return true, exitCodeFailure + } + return true, exitCodeSuccess + default: + return false, exitCodeSuccess + } +} diff --git a/cmd/archive-wrapper/healthcheck_test.go b/cmd/archive-wrapper/healthcheck_test.go new file mode 100644 index 0000000..b7cdaba --- /dev/null +++ b/cmd/archive-wrapper/healthcheck_test.go @@ -0,0 +1,175 @@ +package main + +import ( + "bytes" + "context" + "net" + "os" + "path/filepath" + "testing" + "time" + + "github.com/node101-io/archive-wrapper/apperrors" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + grpcHealth "google.golang.org/grpc/health" + grpcHealthV1 "google.golang.org/grpc/health/grpc_health_v1" +) + +func TestHealthDialAddress(t *testing.T) { + tests := []struct { + name string + address string + want string + wantErr bool + }{ + {name: "ipv4", address: "127.0.0.1:9095", want: "127.0.0.1:9095"}, + {name: "ipv4_wildcard", address: "0.0.0.0:9095", want: "127.0.0.1:9095"}, + {name: "ipv6", address: "[::1]:9095", want: "[::1]:9095"}, + {name: "ipv6_wildcard", address: "[::]:9095", want: "[::1]:9095"}, + {name: "hostname", address: "localhost:9095", wantErr: true}, + {name: "zero_port", address: "127.0.0.1:0", wantErr: true}, + {name: "empty", wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := healthDialAddress(tt.address) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + require.Equal(t, tt.want, got) + }) + } +} + +func TestResolveHealthcheckAddressPrecedence(t *testing.T) { + configPath := writeHealthcheckConfig(t, "127.0.0.1:9001") + lookup := mapLookup(map[string]string{ + "ARCHIVE_WRAPPER_CONFIG": configPath, + "ARCHIVE_WRAPPER_HEALTHCHECK_ADDRESS": "127.0.0.1:9002", + }) + + got, err := resolveHealthcheckAddress("127.0.0.1:9003", true, "", false, lookup) + require.NoError(t, err) + require.Equal(t, "127.0.0.1:9003", got) + + got, err = resolveHealthcheckAddress("", false, "", false, lookup) + require.NoError(t, err) + require.Equal(t, "127.0.0.1:9002", got) + + got, err = resolveHealthcheckAddress("", false, configPath, true, mapLookup(nil)) + require.NoError(t, err) + require.Equal(t, "127.0.0.1:9001", got) +} + +func TestResolveHealthcheckAddressUsesRuntimeEnvironment(t *testing.T) { + configPath := writeHealthcheckConfig(t, "127.0.0.1:9001") + t.Setenv("ARCHIVE_WRAPPER_GRPC_LISTEN_ADDRESS", "0.0.0.0:9004") + t.Setenv("ARCHIVE_WRAPPER_GRPC_TRANSPORT_MODE", "trusted-network") + + got, err := resolveHealthcheckAddress("", false, configPath, true, os.LookupEnv) + require.NoError(t, err) + require.Equal(t, "127.0.0.1:9004", got) +} + +func TestResolveHealthcheckAddressRejectsEmptyExplicitValues(t *testing.T) { + _, err := resolveHealthcheckAddress("", true, "unused", true, mapLookup(nil)) + require.ErrorIs(t, err, apperrors.ErrGRPCAddressRequired) + + _, err = resolveHealthcheckAddress("", false, "", true, mapLookup(nil)) + require.ErrorIs(t, err, apperrors.ErrConfigPathRequired) + + _, err = resolveHealthcheckAddress("", false, "", false, mapLookup(map[string]string{ + "ARCHIVE_WRAPPER_HEALTHCHECK_ADDRESS": "", + })) + require.ErrorIs(t, err, apperrors.ErrGRPCAddressRequired) +} + +func TestCheckQueryHealth(t *testing.T) { + tests := []struct { + name string + status grpcHealthV1.HealthCheckResponse_ServingStatus + wantErr bool + }{ + {name: "serving", status: grpcHealthV1.HealthCheckResponse_SERVING}, + {name: "not_serving", status: grpcHealthV1.HealthCheckResponse_NOT_SERVING, wantErr: true}, + {name: "unknown", status: grpcHealthV1.HealthCheckResponse_UNKNOWN, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + address, stop := serveTestHealth(t, tt.status) + defer stop() + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + err := checkQueryHealth(ctx, address) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + }) + } +} + +func TestCheckQueryHealthFailsForUnavailableTarget(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + require.Error(t, checkQueryHealth(ctx, "127.0.0.1:1")) +} + +func TestRunMainHealthcheckDoesNotInitializeRuntimeLogger(t *testing.T) { + logPath := filepath.Join(t.TempDir(), "healthcheck.log") + t.Setenv("ARCHIVE_WRAPPER_LOG_PATH", logPath) + var stderr bytes.Buffer + + exitCode := runMain( + []string{"healthcheck", "--address", "127.0.0.1:1", "--timeout", "10ms"}, + &bytes.Buffer{}, + &stderr, + ) + require.Equal(t, exitCodeFailure, exitCode) + _, err := os.Stat(logPath) + require.ErrorIs(t, err, os.ErrNotExist) +} + +func TestRunHealthcheckRejectsNonPositiveTimeout(t *testing.T) { + err := runHealthcheckCommand([]string{"--address", "127.0.0.1:9095", "--timeout", "0s"}, mapLookup(nil)) + require.ErrorContains(t, err, "greater than zero") +} + +func serveTestHealth( + t *testing.T, + status grpcHealthV1.HealthCheckResponse_ServingStatus, +) (string, func()) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + server := grpc.NewServer() + health := grpcHealth.NewServer() + health.SetServingStatus(queryGRPCServiceName, status) + grpcHealthV1.RegisterHealthServer(server, health) + go func() { _ = server.Serve(listener) }() + return listener.Addr().String(), server.Stop +} + +func writeHealthcheckConfig(t *testing.T, address string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "config.yaml") + contents := []byte(` +grpc_listen_address: "` + address + `" +grpc_transport_mode: "loopback" +`) + require.NoError(t, os.WriteFile(path, contents, 0o600)) + return path +} + +func mapLookup(values map[string]string) func(string) (string, bool) { + return func(key string) (string, bool) { + value, ok := values[key] + return value, ok + } +} diff --git a/cmd/archive-wrapper/indexer_supervisor.go b/cmd/archive-wrapper/indexer_supervisor.go index 4c0f255..f67d577 100644 --- a/cmd/archive-wrapper/indexer_supervisor.go +++ b/cmd/archive-wrapper/indexer_supervisor.go @@ -15,17 +15,19 @@ import ( "github.com/node101-io/archive-wrapper/indexer" ) -// These defaults bound each probe and pace retries after connection loss. -const notificationReconnectDelay = 2 * time.Second +// These defaults bound each probe and pace retryable Indexer failures. +const indexerRetryDelay = 2 * time.Second const postgresProbeTimeout = 5 * time.Second +const archiveSourceBehindSummary = "archive source is behind indexed cursor" + // postgresPinger keeps the reconnect loop independent from pgxpool in tests. type postgresPinger interface { Ping(context.Context) error } -// reconnectPolicy controls probe deadlines and delay between retryable failures. -type reconnectPolicy struct { +// supervisorPolicy controls probe deadlines and delay between retryable failures. +type supervisorPolicy struct { ProbeTimeout time.Duration RetryDelay time.Duration } @@ -49,7 +51,7 @@ func superviseIndexer( pinger postgresPinger, session indexerSession, readiness *readinessController, - policy reconnectPolicy, + policy supervisorPolicy, runtimeLogger *slog.Logger, ) error { @@ -75,17 +77,28 @@ func superviseIndexer( return err } - // Logic and data errors are fatal; only typed connection failures are retried. - if !errors.Is(err, apperrors.ErrNotificationConnectionLost) && - !errors.Is(err, apperrors.ErrQueryConnectionLost) { + switch { + case errors.Is(err, apperrors.ErrArchiveTargetBehindCursor): + readiness.WaitingForArchive(archiveSourceBehindSummary) + runtimeLogger.Warn( + "archive source is behind indexed cursor, waiting", + "retry_delay", + policy.RetryDelay, + "error", + err, + ) + + case errors.Is(err, apperrors.ErrNotificationConnectionLost), + errors.Is(err, apperrors.ErrQueryConnectionLost): + summary, _ := postgresErrorSummary(err) + readiness.Reconnecting(summary) + runtimeLogger.Warn("postgres connection lost, reconnecting", "duration", time.Since(attemptStartedAt), "retry_delay", policy.RetryDelay, "error", summary) + + default: readiness.Failed("indexer failed") return err } - summary, _ := postgresErrorSummary(err) - readiness.Reconnecting(summary) - runtimeLogger.Warn("postgres connection lost, reconnecting", "duration", time.Since(attemptStartedAt), "retry_delay", policy.RetryDelay, "error", summary) - select { case <-ctx.Done(): return ctx.Err() diff --git a/cmd/archive-wrapper/indexer_supervisor_test.go b/cmd/archive-wrapper/indexer_supervisor_test.go index dcdaf24..2feb9b4 100644 --- a/cmd/archive-wrapper/indexer_supervisor_test.go +++ b/cmd/archive-wrapper/indexer_supervisor_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "fmt" "io" "log/slog" "sync" @@ -16,6 +17,7 @@ import ( "github.com/node101-io/archive-wrapper/diagnostics" "github.com/node101-io/archive-wrapper/indexer" "github.com/stretchr/testify/require" + grpcHealthV1 "google.golang.org/grpc/health/grpc_health_v1" ) func TestSuperviseIndexerPingsBeforeSessionAndRecovers(t *testing.T) { @@ -39,7 +41,7 @@ func TestSuperviseIndexerPingsBeforeSessionAndRecovers(t *testing.T) { return nil } - err := superviseIndexer(context.Background(), pinger, session, controller, reconnectPolicy{ + err := superviseIndexer(context.Background(), pinger, session, controller, supervisorPolicy{ ProbeTimeout: time.Second, RetryDelay: time.Millisecond, }, logger) @@ -67,7 +69,7 @@ func TestSuperviseIndexerBoundsPingWithTimeout(t *testing.T) { err := superviseIndexer(context.Background(), pinger, func(context.Context) error { sessionCalls++ return nil - }, controller, reconnectPolicy{ + }, controller, supervisorPolicy{ ProbeTimeout: 10 * time.Millisecond, RetryDelay: time.Millisecond, }, logger) @@ -91,14 +93,14 @@ func TestSuperviseIndexerStopsRetryDelayOnCancellation(t *testing.T) { }), func(context.Context) error { sessionCalls.Add(1) return nil - }, controller, reconnectPolicy{ + }, controller, supervisorPolicy{ ProbeTimeout: time.Second, RetryDelay: time.Hour, }, logger) }() require.Eventually(t, func() bool { - return store.Snapshot().State == diagnostics.OperationalState_OPERATIONAL_STATE_RECONNECTING + return store.Snapshot().State == diagnostics.StateReconnecting }, time.Second, time.Millisecond) cancel() require.ErrorIs(t, <-done, context.Canceled) @@ -116,14 +118,14 @@ func TestSuperviseIndexerDoesNotRetryFatalError(t *testing.T) { }), func(context.Context) error { sessionCalls++ return fatalErr - }, controller, reconnectPolicy{ + }, controller, supervisorPolicy{ ProbeTimeout: time.Second, RetryDelay: time.Millisecond, }, logger) require.ErrorIs(t, err, fatalErr) require.Equal(t, 1, sessionCalls) - require.Equal(t, diagnostics.OperationalState_OPERATIONAL_STATE_FAILED, store.Snapshot().State) + require.Equal(t, diagnostics.StateFailed, store.Snapshot().State) require.Equal(t, "indexer failed", store.Snapshot().LastError) } @@ -140,7 +142,7 @@ func TestSuperviseIndexerRetriesTypedNotificationFailure(t *testing.T) { return apperrors.ErrNotificationConnectionLost } return nil - }, controller, reconnectPolicy{ + }, controller, supervisorPolicy{ ProbeTimeout: time.Second, RetryDelay: time.Millisecond, }, logger) @@ -150,6 +152,78 @@ func TestSuperviseIndexerRetriesTypedNotificationFailure(t *testing.T) { require.Equal(t, "postgres notification connection unavailable", store.Snapshot().LastError) } +func TestSuperviseIndexerWaitsForArchiveAndRecovers(t *testing.T) { + healthServer, store, controller := newTestReadinessController() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + readyProgress := indexer.SyncProgress{ + ArchiveHeight: 100, + TargetHeight: 68, + Initialized: true, + IndexedHeight: 68, + } + controller.OnSyncCompleted(readyProgress) + previousSuccessfulSync := *store.Snapshot().LastSuccessfulSyncAt + var sessionCalls atomic.Int32 + + err := superviseIndexer(context.Background(), pingerFunc(func(context.Context) error { + return nil + }), func(context.Context) error { + if sessionCalls.Add(1) == 1 { + controller.OnSyncStarted() + controller.OnSyncProgress(indexer.SyncProgress{ + ArchiveHeight: 99, + TargetHeight: 67, + Initialized: true, + IndexedHeight: 68, + }) + return fmt.Errorf("%w: cursor=68 target=67", apperrors.ErrArchiveTargetBehindCursor) + } + + recovered := readyProgress + recovered.ArchiveHeight = 100 + controller.OnSyncStarted() + controller.OnSyncCompleted(recovered) + return nil + }, controller, supervisorPolicy{ + ProbeTimeout: time.Second, + RetryDelay: 10 * time.Millisecond, + }, logger) + + require.NoError(t, err) + require.Equal(t, int32(2), sessionCalls.Load()) + require.Equal(t, diagnostics.StateReady, store.Snapshot().State) + require.True(t, store.Snapshot().Ready) + require.True(t, controller.queryGate.isReady()) + require.Equal(t, archiveSourceBehindSummary, store.Snapshot().LastError) + require.GreaterOrEqual(t, store.Snapshot().LastSuccessfulSyncAt.UnixNano(), previousSuccessfulSync.UnixNano()) + requireHealthStatus(t, healthServer, queryGRPCServiceName, grpcHealthV1.HealthCheckResponse_SERVING) +} + +func TestSuperviseIndexerSourceBehindRetryStopsOnCancellation(t *testing.T) { + _, store, controller := newTestReadinessController() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + + go func() { + done <- superviseIndexer(ctx, pingerFunc(func(context.Context) error { + return nil + }), func(context.Context) error { + return apperrors.ErrArchiveTargetBehindCursor + }, controller, supervisorPolicy{ + ProbeTimeout: time.Second, + RetryDelay: time.Hour, + }, logger) + }() + + require.Eventually(t, func() bool { + return store.Snapshot().State == diagnostics.StateWaitingForArchive + }, time.Second, time.Millisecond) + require.Equal(t, archiveSourceBehindSummary, store.Snapshot().LastError) + cancel() + require.ErrorIs(t, <-done, context.Canceled) +} + func TestSuperviseIndexerDoesNotLogPostgresConnectionDetails(t *testing.T) { _, _, controller := newTestReadinessController() var output bytes.Buffer @@ -165,7 +239,7 @@ func TestSuperviseIndexerDoesNotLogPostgresConnectionDetails(t *testing.T) { return nil }), func(context.Context) error { return nil - }, controller, reconnectPolicy{ + }, controller, supervisorPolicy{ ProbeTimeout: time.Second, RetryDelay: time.Millisecond, }, logger) diff --git a/cmd/archive-wrapper/logging_test.go b/cmd/archive-wrapper/logging_test.go index 4d4ad0d..b7ae425 100644 --- a/cmd/archive-wrapper/logging_test.go +++ b/cmd/archive-wrapper/logging_test.go @@ -4,6 +4,7 @@ import ( "bytes" "errors" "fmt" + "io" "log/slog" "os" "path/filepath" @@ -75,7 +76,7 @@ func TestRunMainReturnsFailureWithoutCreatingDefaultLogFile(t *testing.T) { )) var stderr bytes.Buffer - exitCode := runMain(nil, &stderr) + exitCode := runMain(nil, io.Discard, &stderr) require.Equal(t, exitCodeFailure, exitCode) require.Contains(t, stderr.String(), "destination=stderr") require.Contains(t, stderr.String(), "missing command") diff --git a/cmd/archive-wrapper/main.go b/cmd/archive-wrapper/main.go index 0c6a383..0bbde1c 100644 --- a/cmd/archive-wrapper/main.go +++ b/cmd/archive-wrapper/main.go @@ -17,10 +17,14 @@ const ( ) func main() { - os.Exit(runMain(os.Args[1:], os.Stderr)) + os.Exit(runMain(os.Args[1:], os.Stdout, os.Stderr)) } -func runMain(args []string, stderr io.Writer) (exitCode int) { +func runMain(args []string, stdout, stderr io.Writer) (exitCode int) { + if handled, code := runShortCommand(args, stdout, stderr, os.LookupEnv); handled { + return code + } + logger, cleanup, err := newRuntimeLogger(stderr, os.LookupEnv) if err != nil { if stderr != nil { @@ -28,6 +32,7 @@ func runMain(args []string, stderr io.Writer) (exitCode int) { } return exitCodeFailure } + logger = logger.With("version", version, "commit", commitSHA, "build_date", buildDate) slog.SetDefault(logger) exitCode = exitCodeSuccess defer func() { diff --git a/cmd/archive-wrapper/query_readiness_gate.go b/cmd/archive-wrapper/query_readiness_gate.go new file mode 100644 index 0000000..4a5b6a7 --- /dev/null +++ b/cmd/archive-wrapper/query_readiness_gate.go @@ -0,0 +1,39 @@ +package main + +import ( + "context" + "strings" + "sync/atomic" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// queryReadinessGate prevents business queries while the runtime is unavailable. +type queryReadinessGate struct { + ready atomic.Bool +} + +func (g *queryReadinessGate) setReady(ready bool) { + if g == nil { + return + } + g.ready.Store(ready) +} + +func (g *queryReadinessGate) isReady() bool { + return g != nil && g.ready.Load() +} + +func (g *queryReadinessGate) unaryServerInterceptor( + ctx context.Context, + req any, + info *grpc.UnaryServerInfo, + handler grpc.UnaryHandler, +) (any, error) { + if strings.HasPrefix(info.FullMethod, "/"+queryGRPCServiceName+"/") && !g.isReady() { + return nil, status.Error(codes.Unavailable, "query service is not ready") + } + return handler(ctx, req) +} diff --git a/cmd/archive-wrapper/query_readiness_gate_test.go b/cmd/archive-wrapper/query_readiness_gate_test.go new file mode 100644 index 0000000..cdb2eb0 --- /dev/null +++ b/cmd/archive-wrapper/query_readiness_gate_test.go @@ -0,0 +1,81 @@ +package main + +import ( + "context" + "sync" + "testing" + + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestQueryReadinessGateBlocksOnlyQueryService(t *testing.T) { + gate := &queryReadinessGate{} + handlerCalls := 0 + handler := func(context.Context, any) (any, error) { + handlerCalls++ + return "ok", nil + } + + _, err := gate.unaryServerInterceptor( + context.Background(), + nil, + &grpc.UnaryServerInfo{FullMethod: "/query.Query/GetMinaBlockHeight"}, + handler, + ) + require.Equal(t, codes.Unavailable, status.Code(err)) + require.Zero(t, handlerCalls) + + for _, method := range []string{ + "/grpc.health.v1.Health/Check", + "/diagnostics.DiagnosticsService/GetStatus", + "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", + } { + response, err := gate.unaryServerInterceptor( + context.Background(), + nil, + &grpc.UnaryServerInfo{FullMethod: method}, + handler, + ) + require.NoError(t, err) + require.Equal(t, "ok", response) + } + require.Equal(t, 3, handlerCalls) + + gate.setReady(true) + response, err := gate.unaryServerInterceptor( + context.Background(), + nil, + &grpc.UnaryServerInfo{FullMethod: "/query.Query/GetActionsInRange"}, + handler, + ) + require.NoError(t, err) + require.Equal(t, "ok", response) + require.Equal(t, 4, handlerCalls) +} + +func TestQueryReadinessGateSupportsConcurrentTransitions(t *testing.T) { + gate := &queryReadinessGate{} + var group sync.WaitGroup + + for i := 0; i < 100; i++ { + group.Add(2) + go func(ready bool) { + defer group.Done() + gate.setReady(ready) + }(i%2 == 0) + go func() { + defer group.Done() + _, _ = gate.unaryServerInterceptor( + context.Background(), + nil, + &grpc.UnaryServerInfo{FullMethod: "/query.Query/GetMinaBlockHeight"}, + func(context.Context, any) (any, error) { return nil, nil }, + ) + }() + } + + group.Wait() +} diff --git a/cmd/archive-wrapper/readiness.go b/cmd/archive-wrapper/readiness.go index a8c6398..c1bc99e 100644 --- a/cmd/archive-wrapper/readiness.go +++ b/cmd/archive-wrapper/readiness.go @@ -11,30 +11,40 @@ import ( // readinessController keeps gRPC health and diagnostics transitions consistent. type readinessController struct { - mu sync.Mutex - health *grpcHealth.Server - store *diagnostics.Store - terminal bool + mu sync.Mutex + health *grpcHealth.Server + store *diagnostics.Store + queryGate *queryReadinessGate + terminal bool } // newReadinessController binds both readiness views to one transition owner. -func newReadinessController(health *grpcHealth.Server, store *diagnostics.Store) *readinessController { - return &readinessController{health: health, store: store} +func newReadinessController( + health *grpcHealth.Server, + store *diagnostics.Store, + queryGate *queryReadinessGate, +) *readinessController { + return &readinessController{health: health, store: store, queryGate: queryGate} } // Connecting marks query traffic unavailable while PostgreSQL is being probed. func (c *readinessController) Connecting() { - c.transitionUnavailable(diagnostics.OperationalState_OPERATIONAL_STATE_CONNECTING, "") + c.transitionUnavailable(diagnostics.StateConnecting, "") } // Reconnecting records a safe connection summary and disables query readiness. func (c *readinessController) Reconnecting(summary string) { - c.transitionUnavailable(diagnostics.OperationalState_OPERATIONAL_STATE_RECONNECTING, summary) + c.transitionUnavailable(diagnostics.StateReconnecting, summary) +} + +// WaitingForArchive records source lag and disables query readiness. +func (c *readinessController) WaitingForArchive(summary string) { + c.transitionUnavailable(diagnostics.StateWaitingForArchive, summary) } // Failed records a non-serving runtime failure. func (c *readinessController) Failed(summary string) { - c.transitionUnavailable(diagnostics.OperationalState_OPERATIONAL_STATE_FAILED, summary) + c.transitionUnavailable(diagnostics.StateFailed, summary) } // Stopping is terminal so late Indexer callbacks cannot restore readiness. @@ -49,8 +59,9 @@ func (c *readinessController) Stopping() { return } c.terminal = true + c.queryGate.setReady(false) c.setQueryServingStatus(grpcHealthV1.HealthCheckResponse_NOT_SERVING) - c.store.SetState(diagnostics.OperationalState_OPERATIONAL_STATE_STOPPING, false) + c.store.SetState(diagnostics.StateStopping, false) } // OnSyncStarted preserves readiness only for an already initialized incremental sync. @@ -67,9 +78,10 @@ func (c *readinessController) OnSyncStarted() { snapshot := c.store.Snapshot() if !snapshot.Ready { + c.queryGate.setReady(false) c.setQueryServingStatus(grpcHealthV1.HealthCheckResponse_NOT_SERVING) } - c.store.SetState(diagnostics.OperationalState_OPERATIONAL_STATE_SYNCING, snapshot.Ready) + c.store.SetState(diagnostics.StateSyncing, snapshot.Ready) } // OnSyncProgress refreshes diagnostics without changing serving status. @@ -101,13 +113,15 @@ func (c *readinessController) OnSyncCompleted(progress indexer.SyncProgress) { c.setProgress(progress) c.store.RecordSuccessfulSync() if !progress.Initialized { + c.queryGate.setReady(false) c.setQueryServingStatus(grpcHealthV1.HealthCheckResponse_NOT_SERVING) - c.store.SetState(diagnostics.OperationalState_OPERATIONAL_STATE_WAITING_FOR_FINALITY, false) + c.store.SetState(diagnostics.StateWaitingForFinality, false) return } // Complete diagnostics first so a newly serving query never exposes stale status. - c.store.SetState(diagnostics.OperationalState_OPERATIONAL_STATE_READY, true) + c.store.SetState(diagnostics.StateReady, true) + c.queryGate.setReady(true) c.setQueryServingStatus(grpcHealthV1.HealthCheckResponse_SERVING) } @@ -123,6 +137,7 @@ func (c *readinessController) transitionUnavailable(state diagnostics.Operationa return } + c.queryGate.setReady(false) c.setQueryServingStatus(grpcHealthV1.HealthCheckResponse_NOT_SERVING) if summary != "" { c.store.RecordError(summary) diff --git a/cmd/archive-wrapper/readiness_test.go b/cmd/archive-wrapper/readiness_test.go index 236a5f8..4290f8b 100644 --- a/cmd/archive-wrapper/readiness_test.go +++ b/cmd/archive-wrapper/readiness_test.go @@ -29,15 +29,16 @@ func TestRegisterGRPCServicesStartsQueryUnavailableAndDiagnosticsServing(t *test func TestReadinessControllerTransitionsThroughSyncAndReconnect(t *testing.T) { healthServer, store, controller := newTestReadinessController() + require.False(t, controller.queryGate.isReady()) controller.Connecting() - require.Equal(t, diagnostics.OperationalState_OPERATIONAL_STATE_CONNECTING, store.Snapshot().State) + require.Equal(t, diagnostics.StateConnecting, store.Snapshot().State) requireHealthStatus(t, healthServer, queryGRPCServiceName, grpcHealthV1.HealthCheckResponse_NOT_SERVING) controller.OnSyncStarted() controller.OnSyncProgress(indexer.SyncProgress{ArchiveHeight: 42, TargetHeight: 10}) controller.OnSyncCompleted(indexer.SyncProgress{ArchiveHeight: 42, TargetHeight: 10}) - require.Equal(t, diagnostics.OperationalState_OPERATIONAL_STATE_WAITING_FOR_FINALITY, store.Snapshot().State) + require.Equal(t, diagnostics.StateWaitingForFinality, store.Snapshot().State) require.False(t, store.Snapshot().Ready) readyProgress := indexer.SyncProgress{ @@ -48,18 +49,30 @@ func TestReadinessControllerTransitionsThroughSyncAndReconnect(t *testing.T) { } controller.OnSyncStarted() controller.OnSyncCompleted(readyProgress) - require.Equal(t, diagnostics.OperationalState_OPERATIONAL_STATE_READY, store.Snapshot().State) + require.Equal(t, diagnostics.StateReady, store.Snapshot().State) require.True(t, store.Snapshot().Ready) + require.True(t, controller.queryGate.isReady()) requireHealthStatus(t, healthServer, queryGRPCServiceName, grpcHealthV1.HealthCheckResponse_SERVING) controller.OnSyncStarted() - require.Equal(t, diagnostics.OperationalState_OPERATIONAL_STATE_SYNCING, store.Snapshot().State) + require.Equal(t, diagnostics.StateSyncing, store.Snapshot().State) require.True(t, store.Snapshot().Ready) + require.True(t, controller.queryGate.isReady()) requireHealthStatus(t, healthServer, queryGRPCServiceName, grpcHealthV1.HealthCheckResponse_SERVING) + lastSuccessfulSyncAt := *store.Snapshot().LastSuccessfulSyncAt + controller.WaitingForArchive(archiveSourceBehindSummary) + require.Equal(t, diagnostics.StateWaitingForArchive, store.Snapshot().State) + require.False(t, store.Snapshot().Ready) + require.False(t, controller.queryGate.isReady()) + require.Equal(t, archiveSourceBehindSummary, store.Snapshot().LastError) + require.Equal(t, lastSuccessfulSyncAt, *store.Snapshot().LastSuccessfulSyncAt) + requireHealthStatus(t, healthServer, queryGRPCServiceName, grpcHealthV1.HealthCheckResponse_NOT_SERVING) + controller.Reconnecting("postgres notification connection unavailable") - require.Equal(t, diagnostics.OperationalState_OPERATIONAL_STATE_RECONNECTING, store.Snapshot().State) + require.Equal(t, diagnostics.StateReconnecting, store.Snapshot().State) require.False(t, store.Snapshot().Ready) + require.False(t, controller.queryGate.isReady()) require.Equal(t, "postgres notification connection unavailable", store.Snapshot().LastError) requireHealthStatus(t, healthServer, queryGRPCServiceName, grpcHealthV1.HealthCheckResponse_NOT_SERVING) } @@ -70,8 +83,9 @@ func TestReadinessControllerStoppingIsTerminal(t *testing.T) { controller.OnSyncCompleted(indexer.SyncProgress{Initialized: true, IndexedHeight: 10}) controller.Connecting() - require.Equal(t, diagnostics.OperationalState_OPERATIONAL_STATE_STOPPING, store.Snapshot().State) + require.Equal(t, diagnostics.StateStopping, store.Snapshot().State) require.False(t, store.Snapshot().Ready) + require.False(t, controller.queryGate.isReady()) requireHealthStatus(t, healthServer, queryGRPCServiceName, grpcHealthV1.HealthCheckResponse_NOT_SERVING) } @@ -81,7 +95,7 @@ func newTestReadinessController() (*grpcHealth.Server, *diagnostics.Store, *read healthServer.SetServingStatus(queryGRPCServiceName, grpcHealthV1.HealthCheckResponse_NOT_SERVING) healthServer.SetServingStatus(diagnosticsGRPCServiceName, grpcHealthV1.HealthCheckResponse_SERVING) store := diagnostics.NewStore() - return healthServer, store, newReadinessController(healthServer, store) + return healthServer, store, newReadinessController(healthServer, store, &queryReadinessGate{}) } func requireHealthStatus( diff --git a/cmd/archive-wrapper/runtime.go b/cmd/archive-wrapper/runtime.go index 196aba0..c9eaf2d 100644 --- a/cmd/archive-wrapper/runtime.go +++ b/cmd/archive-wrapper/runtime.go @@ -172,7 +172,8 @@ func runRuntime( } }() - grpcServer := grpc.NewServer() + queryGate := &queryReadinessGate{} + grpcServer := grpc.NewServer(grpc.UnaryInterceptor(queryGate.unaryServerInterceptor)) queryService, err := query.NewQuery( db, logger, @@ -185,7 +186,7 @@ func runRuntime( diagnosticsStore := diagnostics.NewStore() diagnosticsService := diagnostics.NewServer(diagnosticsStore) healthServer := registerGRPCServices(grpcServer, queryService, diagnosticsService) - readiness := newReadinessController(healthServer, diagnosticsStore) + readiness := newReadinessController(healthServer, diagnosticsStore, queryGate) // External cancellation wakes the coordinator; workers are canceled only // after readiness has been withdrawn. @@ -212,9 +213,9 @@ func runRuntime( runtimeLogger, ) } - err := superviseIndexer(runCtx, queryPool, session, readiness, reconnectPolicy{ + err := superviseIndexer(runCtx, queryPool, session, readiness, supervisorPolicy{ ProbeTimeout: postgresProbeTimeout, - RetryDelay: notificationReconnectDelay, + RetryDelay: indexerRetryDelay, }, runtimeLogger) workerResults <- runtimeWorkerResult{name: "indexer", err: err} }() diff --git a/config/config.go b/config/config.go index 5fb133e..1c62a26 100644 --- a/config/config.go +++ b/config/config.go @@ -68,6 +68,30 @@ func Resolve(configFile string, overrides Overrides) (Config, error) { return resolve(configFile, overrides, os.LookupEnv, true) } +// ResolveGRPCListenAddress resolves only the effective gRPC listener settings. +// Short-lived probes use this path without requiring chain or database inputs. +func ResolveGRPCListenAddress(configFile string) (string, error) { + if strings.TrimSpace(configFile) == "" { + return "", apperrors.ErrConfigPathRequired + } + + cfg, err := decode(configFile) + if err != nil { + return "", err + } + applyDefaults(&cfg) + applyEnvironment(&cfg, os.LookupEnv) + normalize(&cfg) + + if cfg.GRPCListenAddress == "" { + return "", apperrors.ErrGRPCAddressRequired + } + if err := validateGRPCListenAddress(cfg.GRPCListenAddress, cfg.EffectiveGRPCTransportMode()); err != nil { + return "", err + } + return cfg.GRPCListenAddress, nil +} + type lookupEnv func(string) (string, bool) func resolve(configFile string, overrides Overrides, lookup lookupEnv, requireChainHome bool) (Config, error) { diff --git a/config/config_test.go b/config/config_test.go index f841780..1d6b2f1 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -181,6 +181,32 @@ deployment_metadata: require.ErrorIs(t, err, apperrors.ErrChainHomeRequired) } +func TestResolveGRPCListenAddressDoesNotRequireChainHome(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(configPath, []byte(` +grpc_listen_address: "127.0.0.1:9090" +grpc_transport_mode: "loopback" +`), 0o600)) + + got, err := ResolveGRPCListenAddress(configPath) + require.NoError(t, err) + require.Equal(t, "127.0.0.1:9090", got) +} + +func TestResolveGRPCListenAddressAppliesRuntimeEnvironment(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(configPath, []byte(` +grpc_listen_address: "127.0.0.1:9090" +grpc_transport_mode: "loopback" +`), 0o600)) + t.Setenv("ARCHIVE_WRAPPER_GRPC_LISTEN_ADDRESS", "0.0.0.0:9095") + t.Setenv("ARCHIVE_WRAPPER_GRPC_TRANSPORT_MODE", "trusted-network") + + got, err := ResolveGRPCListenAddress(configPath) + require.NoError(t, err) + require.Equal(t, "0.0.0.0:9095", got) +} + func TestLoadRejectsNonLoopbackGRPCListenAddress(t *testing.T) { for _, address := range []string{ "0.0.0.0:9095", diff --git a/database/db.go b/database/db.go index 2ce4088..6396666 100644 --- a/database/db.go +++ b/database/db.go @@ -288,35 +288,6 @@ func (manager *DbManager) GetBlockHeight() (int64, error) { return height, nil } -func (manager *DbManager) getEarliestStoredRecordHeight() (int64, bool, error) { - iter := manager.db.NewIterator(nil, nil) - defer iter.Release() - - cursorKey := []byte(manager.blockHeightDatabaseKey) - - for iter.Next() { - key := iter.Key() - if len(key) != 8 { - continue - } - if string(key) == string(cursorKey) { - continue - } - - height, err := decodeBlockHeight(key) - if err != nil { - return 0, false, err - } - return height, true, nil - } - - if err := iter.Error(); err != nil { - return 0, false, fmt.Errorf("iterate stored block records: %w", err) - } - - return 0, false, nil -} - // Close closes the underlying LevelDB handle and marks the manager unusable. func (manager *DbManager) Close() error { diff --git a/database/db_test.go b/database/db_test.go index 5310222..d4daa82 100644 --- a/database/db_test.go +++ b/database/db_test.go @@ -261,6 +261,43 @@ func TestDbManagerInitializeOrValidateDeploymentAllowsInitializedDatabaseWithout require.False(t, hasCursor) } +func TestDbManagerInitializeOrValidateDeploymentValidatesCursorStartBoundary(t *testing.T) { + tests := []struct { + name string + cursor int64 + wantCorrupt bool + }{ + {name: "below start height", cursor: 9, wantCorrupt: true}, + {name: "at start height", cursor: 10}, + {name: "above start height", cursor: 11}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + manager, err := NewDbManager(t.TempDir(), blockHeightDatabaseKey, logger) + require.NoError(t, err) + defer func() { require.NoError(t, manager.Close()) }() + + metadata := testDeploymentMetadata() + state, err := manager.InitializeOrValidateDeployment("archive-wrapper:deployment", metadata) + require.NoError(t, err) + require.Equal(t, DeploymentStateFresh, state) + require.NoError(t, manager.InsertBlockHeight(tt.cursor)) + + state, err = manager.InitializeOrValidateDeployment("archive-wrapper:deployment", metadata) + if tt.wantCorrupt { + require.ErrorIs(t, err, apperrors.ErrDBCorrupt) + require.Equal(t, DeploymentStateUnspecified, state) + return + } + + require.NoError(t, err) + require.Equal(t, DeploymentStateInitialized, state) + }) + } +} + func TestDbManagerInitializeOrValidateDeploymentRejectsMalformedState(t *testing.T) { tests := []struct { name string diff --git a/database/metadata.go b/database/metadata.go index 72a2e93..740ad0b 100644 --- a/database/metadata.go +++ b/database/metadata.go @@ -75,7 +75,7 @@ func (manager *DbManager) InitializeOrValidateDeployment( expected, ) } - if err := manager.validatePersistedCursor(); err != nil { + if err := manager.validatePersistedCursor(expected.StartHeight); err != nil { return DeploymentStateUnspecified, err } return DeploymentStateInitialized, nil @@ -137,7 +137,7 @@ func validateDeploymentMetadata(metadata DeploymentMetadata) error { return nil } -func (manager *DbManager) validatePersistedCursor() error { +func (manager *DbManager) validatePersistedCursor(startHeight int64) error { record, err := manager.db.Get([]byte(manager.blockHeightDatabaseKey), nil) switch { case err == nil: @@ -152,6 +152,14 @@ func (manager *DbManager) validatePersistedCursor() error { height, ) } + if height < startHeight { + return fmt.Errorf( + "%w: block height cursor %d is below deployment start height %d", + apperrors.ErrDBCorrupt, + height, + startHeight, + ) + } return nil case errors.Is(err, leveldb.ErrNotFound): return nil diff --git a/diagnostics/diagnostics.pb.go b/diagnostics/diagnostics.pb.go index 721a9ee..e13d049 100644 --- a/diagnostics/diagnostics.pb.go +++ b/diagnostics/diagnostics.pb.go @@ -44,6 +44,7 @@ const ( OperationalState_OPERATIONAL_STATE_RECONNECTING OperationalState = 6 OperationalState_OPERATIONAL_STATE_FAILED OperationalState = 7 OperationalState_OPERATIONAL_STATE_STOPPING OperationalState = 8 + OperationalState_OPERATIONAL_STATE_WAITING_FOR_ARCHIVE OperationalState = 9 ) var OperationalState_name = map[int32]string{ @@ -56,6 +57,7 @@ var OperationalState_name = map[int32]string{ 6: "OPERATIONAL_STATE_RECONNECTING", 7: "OPERATIONAL_STATE_FAILED", 8: "OPERATIONAL_STATE_STOPPING", + 9: "OPERATIONAL_STATE_WAITING_FOR_ARCHIVE", } var OperationalState_value = map[string]int32{ @@ -68,6 +70,7 @@ var OperationalState_value = map[string]int32{ "OPERATIONAL_STATE_RECONNECTING": 6, "OPERATIONAL_STATE_FAILED": 7, "OPERATIONAL_STATE_STOPPING": 8, + "OPERATIONAL_STATE_WAITING_FOR_ARCHIVE": 9, } func (x OperationalState) String() string { @@ -208,50 +211,51 @@ func init() { func init() { proto.RegisterFile("diagnostics/diagnostics.proto", fileDescriptor_1418b64243aec797) } var fileDescriptor_1418b64243aec797 = []byte{ - // 677 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x94, 0xcf, 0x4e, 0xdb, 0x4c, - 0x14, 0xc5, 0x63, 0x92, 0xf0, 0xe7, 0x86, 0xa0, 0x7c, 0x23, 0x24, 0xfc, 0xa5, 0xc4, 0x49, 0xa9, - 0x5a, 0x45, 0x48, 0x24, 0x05, 0x76, 0x54, 0x5d, 0x98, 0xc4, 0xa1, 0xae, 0xa2, 0x24, 0xb2, 0x53, - 0x21, 0xba, 0x71, 0x07, 0x7b, 0x70, 0x46, 0x4a, 0x3c, 0xa9, 0x67, 0x42, 0x4b, 0x9f, 0xa0, 0x4b, - 0x1e, 0xa1, 0x7d, 0x94, 0xee, 0xd8, 0x95, 0x65, 0x57, 0x6d, 0x05, 0x2f, 0x52, 0xd9, 0x4e, 0x82, - 0x21, 0x20, 0xb1, 0x1b, 0x9f, 0xfb, 0x3b, 0xc7, 0xbe, 0x33, 0xbe, 0x03, 0x05, 0x87, 0x62, 0xd7, - 0x63, 0x5c, 0x50, 0x9b, 0x57, 0x63, 0xeb, 0xca, 0xd0, 0x67, 0x82, 0xa1, 0x4c, 0x4c, 0xca, 0xaf, - 0xba, 0xcc, 0x65, 0xa1, 0x5e, 0x0d, 0x56, 0x11, 0x92, 0x2f, 0xba, 0x8c, 0xb9, 0x7d, 0x52, 0x0d, - 0x9f, 0x8e, 0x47, 0x27, 0x55, 0x41, 0x07, 0x84, 0x0b, 0x3c, 0x18, 0x46, 0xc0, 0x86, 0x0c, 0xb9, - 0x03, 0x22, 0x4c, 0x81, 0xc5, 0x88, 0x1b, 0xe4, 0xe3, 0x88, 0x70, 0xb1, 0x97, 0xfa, 0xfa, 0xad, - 0x98, 0xd8, 0xf8, 0x9e, 0x84, 0xff, 0x62, 0x25, 0x3e, 0x64, 0x1e, 0x27, 0x68, 0x17, 0xd2, 0x5c, - 0x60, 0x41, 0x64, 0xa9, 0x24, 0x95, 0x57, 0x76, 0x0a, 0x95, 0xf8, 0x67, 0xb5, 0x87, 0xc4, 0xc7, - 0x82, 0x32, 0x0f, 0xf7, 0x03, 0x1b, 0x31, 0x22, 0x16, 0xad, 0x42, 0xda, 0x27, 0xd8, 0x39, 0x93, - 0xe7, 0x4a, 0x52, 0x79, 0xd1, 0x88, 0x1e, 0xd0, 0x1e, 0x2c, 0x50, 0xcf, 0x21, 0x9f, 0x89, 0x2f, - 0x27, 0x4b, 0x52, 0x39, 0xb3, 0x93, 0xbf, 0x15, 0xa6, 0x47, 0xb5, 0xe8, 0xfd, 0xfb, 0xa9, 0x8b, - 0xdf, 0xc5, 0x84, 0x31, 0x31, 0x20, 0x15, 0x32, 0x61, 0xb4, 0xc5, 0xa9, 0x67, 0x13, 0x39, 0x35, - 0xf6, 0x47, 0xdd, 0x56, 0x26, 0xdd, 0x56, 0xba, 0x93, 0x6e, 0xf7, 0x53, 0xe7, 0x7f, 0x8a, 0x92, - 0x01, 0xa1, 0xc9, 0x0c, 0x3c, 0xe8, 0x10, 0xd6, 0xfa, 0x98, 0x0b, 0x8b, 0x8f, 0x6c, 0x9b, 0x70, - 0x7e, 0x32, 0xea, 0x5b, 0xfc, 0xcc, 0xb3, 0x2d, 0x2c, 0xe4, 0xf4, 0x23, 0xe3, 0x56, 0x83, 0x00, - 0x73, 0xea, 0x37, 0xcf, 0x3c, 0x5b, 0x15, 0xa8, 0x0e, 0xd9, 0x30, 0x98, 0xf8, 0x3e, 0xf3, 0x83, - 0xb8, 0xf9, 0x47, 0xc6, 0x65, 0x02, 0x9b, 0x16, 0xb8, 0x54, 0x81, 0x0a, 0x00, 0x37, 0x29, 0xf2, - 0x42, 0x49, 0x2a, 0x2f, 0x19, 0x4b, 0x53, 0x60, 0x7c, 0x46, 0x3f, 0x25, 0xc8, 0xde, 0xda, 0x27, - 0x54, 0x82, 0x0c, 0xf5, 0xa8, 0xa0, 0xb8, 0x4f, 0xbf, 0x10, 0x27, 0x3c, 0xa5, 0x45, 0x23, 0x2e, - 0xa1, 0xe7, 0xb0, 0x12, 0xed, 0xa2, 0x63, 0xf5, 0x08, 0x75, 0x7b, 0x22, 0x3c, 0x95, 0xa4, 0x91, - 0x1d, 0xab, 0x6f, 0x42, 0x31, 0xc0, 0xb0, 0x6f, 0xf7, 0xe8, 0x29, 0x99, 0x60, 0xc9, 0x08, 0x1b, - 0xab, 0x63, 0xec, 0x19, 0x64, 0x05, 0xf6, 0x5d, 0x22, 0x26, 0x54, 0x2a, 0xa4, 0x96, 0x23, 0xf1, - 0x06, 0xb2, 0x99, 0x77, 0x42, 0xfd, 0x01, 0x71, 0xac, 0x3e, 0x76, 0xc3, 0x0d, 0x4e, 0x1a, 0xcb, - 0x53, 0xb1, 0x89, 0xdd, 0xa8, 0xa3, 0xcd, 0x1f, 0x73, 0x90, 0xbb, 0xfb, 0x1b, 0xa1, 0xa7, 0x50, - 0x68, 0x77, 0x34, 0x43, 0xed, 0xea, 0xed, 0x96, 0xda, 0xb4, 0xcc, 0xae, 0xda, 0xd5, 0xac, 0x77, - 0x2d, 0xb3, 0xa3, 0xd5, 0xf4, 0x86, 0xae, 0xd5, 0x73, 0x09, 0xa4, 0x40, 0x7e, 0x16, 0x31, 0xbb, - 0xaa, 0xd1, 0xd5, 0x5b, 0x07, 0x39, 0x09, 0x95, 0x60, 0x7d, 0xb6, 0x5e, 0x6b, 0xb7, 0x5a, 0x5a, - 0x2d, 0x24, 0xe6, 0x50, 0x01, 0xfe, 0xbf, 0x27, 0xe1, 0xa8, 0x55, 0x0b, 0xca, 0x49, 0xb4, 0x09, - 0x2f, 0x66, 0xcb, 0x87, 0xaa, 0x1e, 0xb8, 0xad, 0x46, 0xdb, 0xb0, 0x1a, 0x7a, 0x4b, 0x6d, 0xea, - 0xdd, 0xa3, 0x5c, 0x0a, 0x3d, 0x81, 0xb5, 0x59, 0xd6, 0xd0, 0xd4, 0xfa, 0x51, 0x2e, 0x8d, 0x36, - 0x40, 0xb9, 0xaf, 0x18, 0xfb, 0x96, 0x79, 0xb4, 0x0e, 0xf2, 0x2c, 0xd3, 0x50, 0xf5, 0xa6, 0x56, - 0xcf, 0x2d, 0x3c, 0xd4, 0x6b, 0xbb, 0xd3, 0x09, 0xdc, 0x8b, 0x3b, 0x1f, 0x00, 0xd5, 0x6f, 0x06, - 0xc9, 0x24, 0xfe, 0x29, 0xb5, 0x09, 0x7a, 0x0b, 0x4b, 0xd3, 0x71, 0x46, 0xb7, 0xe7, 0xf6, 0xee, - 0x0d, 0x90, 0x57, 0x1e, 0x2a, 0x47, 0xb7, 0xc0, 0xfe, 0xe1, 0xc5, 0x95, 0x22, 0x5d, 0x5e, 0x29, - 0xd2, 0xdf, 0x2b, 0x45, 0x3a, 0xbf, 0x56, 0x12, 0x97, 0xd7, 0x4a, 0xe2, 0xd7, 0xb5, 0x92, 0x78, - 0xff, 0xda, 0xa5, 0xa2, 0x37, 0x3a, 0xae, 0xd8, 0x6c, 0x50, 0xf5, 0x98, 0x43, 0xb6, 0x5f, 0x6e, - 0x6f, 0x51, 0x56, 0x1d, 0xff, 0x34, 0x5b, 0x9f, 0x7c, 0x3c, 0x1c, 0x12, 0x3f, 0x7e, 0x99, 0xbd, - 0x8a, 0xad, 0x8f, 0xe7, 0xc3, 0xe1, 0xd8, 0xfd, 0x17, 0x00, 0x00, 0xff, 0xff, 0x31, 0xde, 0xd9, - 0x00, 0xfa, 0x04, 0x00, 0x00, + // 689 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x94, 0x5f, 0x4f, 0xda, 0x50, + 0x18, 0xc6, 0xa9, 0x80, 0xca, 0x8b, 0x98, 0xee, 0xc4, 0xc4, 0x8e, 0x49, 0x61, 0x2e, 0x2e, 0xcc, + 0x44, 0x98, 0x7a, 0xe7, 0xb2, 0x8b, 0x0a, 0x45, 0xbb, 0x10, 0x20, 0x2d, 0x9b, 0x71, 0x37, 0xdd, + 0xb1, 0x1c, 0xcb, 0x49, 0xa0, 0x65, 0x3d, 0x07, 0x37, 0xf7, 0x09, 0x76, 0xe9, 0x47, 0xd8, 0xbe, + 0x8d, 0x77, 0xf3, 0x72, 0x57, 0xdb, 0xa2, 0xb7, 0xfb, 0x10, 0x4b, 0x5b, 0xc0, 0x2a, 0xba, 0x78, + 0x77, 0xfa, 0xbc, 0xbf, 0xe7, 0xe9, 0x79, 0xcf, 0x3f, 0xc8, 0x75, 0x28, 0xb6, 0x1d, 0x97, 0x71, + 0x6a, 0xb1, 0x72, 0x64, 0x5c, 0x1a, 0x78, 0x2e, 0x77, 0x51, 0x3a, 0x22, 0x65, 0x97, 0x6c, 0xd7, + 0x76, 0x03, 0xbd, 0xec, 0x8f, 0x42, 0x24, 0x9b, 0xb7, 0x5d, 0xd7, 0xee, 0x91, 0x72, 0xf0, 0x75, + 0x34, 0x3c, 0x2e, 0x73, 0xda, 0x27, 0x8c, 0xe3, 0xfe, 0x20, 0x04, 0x56, 0x25, 0x10, 0xf7, 0x08, + 0x37, 0x38, 0xe6, 0x43, 0xa6, 0x93, 0x8f, 0x43, 0xc2, 0xf8, 0x4e, 0xe2, 0xeb, 0xb7, 0x7c, 0x6c, + 0xf5, 0x7b, 0x1c, 0x1e, 0x45, 0x4a, 0x6c, 0xe0, 0x3a, 0x8c, 0xa0, 0x6d, 0x48, 0x32, 0x8e, 0x39, + 0x91, 0x84, 0x82, 0x50, 0x5c, 0xdc, 0xca, 0x95, 0xa2, 0xd3, 0x6a, 0x0e, 0x88, 0x87, 0x39, 0x75, + 0x1d, 0xdc, 0xf3, 0x6d, 0x44, 0x0f, 0x59, 0xb4, 0x04, 0x49, 0x8f, 0xe0, 0xce, 0xa9, 0x34, 0x53, + 0x10, 0x8a, 0xf3, 0x7a, 0xf8, 0x81, 0x76, 0x60, 0x8e, 0x3a, 0x1d, 0xf2, 0x99, 0x78, 0x52, 0xbc, + 0x20, 0x14, 0xd3, 0x5b, 0xd9, 0x1b, 0x61, 0x5a, 0x58, 0x0b, 0xff, 0xbf, 0x9b, 0x38, 0xff, 0x95, + 0x8f, 0xe9, 0x63, 0x03, 0x52, 0x20, 0x1d, 0x44, 0x9b, 0x8c, 0x3a, 0x16, 0x91, 0x12, 0x23, 0x7f, + 0xd8, 0x6d, 0x69, 0xdc, 0x6d, 0xa9, 0x3d, 0xee, 0x76, 0x37, 0x71, 0xf6, 0x3b, 0x2f, 0xe8, 0x10, + 0x98, 0x0c, 0xdf, 0x83, 0x0e, 0x60, 0xb9, 0x87, 0x19, 0x37, 0xd9, 0xd0, 0xb2, 0x08, 0x63, 0xc7, + 0xc3, 0x9e, 0xc9, 0x4e, 0x1d, 0xcb, 0xc4, 0x5c, 0x4a, 0x3e, 0x30, 0x6e, 0xc9, 0x0f, 0x30, 0x26, + 0x7e, 0xe3, 0xd4, 0xb1, 0x14, 0x8e, 0xaa, 0x90, 0x09, 0x82, 0x89, 0xe7, 0xb9, 0x9e, 0x1f, 0x37, + 0xfb, 0xc0, 0xb8, 0xb4, 0x6f, 0x53, 0x7d, 0x97, 0xc2, 0x51, 0x0e, 0xe0, 0x3a, 0x45, 0x9a, 0x2b, + 0x08, 0xc5, 0x94, 0x9e, 0x9a, 0x00, 0xa3, 0x3d, 0xfa, 0x21, 0x40, 0xe6, 0xc6, 0x3a, 0xa1, 0x02, + 0xa4, 0xa9, 0x43, 0x39, 0xc5, 0x3d, 0xfa, 0x85, 0x74, 0x82, 0x5d, 0x9a, 0xd7, 0xa3, 0x12, 0x5a, + 0x83, 0xc5, 0x70, 0x15, 0x3b, 0x66, 0x97, 0x50, 0xbb, 0xcb, 0x83, 0x5d, 0x89, 0xeb, 0x99, 0x91, + 0xba, 0x1f, 0x88, 0x3e, 0x86, 0x3d, 0xab, 0x4b, 0x4f, 0xc8, 0x18, 0x8b, 0x87, 0xd8, 0x48, 0x1d, + 0x61, 0xcf, 0x20, 0xc3, 0xb1, 0x67, 0x13, 0x3e, 0xa6, 0x12, 0x01, 0xb5, 0x10, 0x8a, 0xd7, 0x90, + 0xe5, 0x3a, 0xc7, 0xd4, 0xeb, 0x93, 0x8e, 0xd9, 0xc3, 0x76, 0xb0, 0xc0, 0x71, 0x7d, 0x61, 0x22, + 0xd6, 0xb1, 0x1d, 0x76, 0xb4, 0xfe, 0x77, 0x06, 0xc4, 0xdb, 0xc7, 0x08, 0x3d, 0x85, 0x5c, 0xb3, + 0xa5, 0xea, 0x4a, 0x5b, 0x6b, 0x36, 0x94, 0xba, 0x69, 0xb4, 0x95, 0xb6, 0x6a, 0xbe, 0x6d, 0x18, + 0x2d, 0xb5, 0xa2, 0xd5, 0x34, 0xb5, 0x2a, 0xc6, 0x90, 0x0c, 0xd9, 0x69, 0xc4, 0x68, 0x2b, 0x7a, + 0x5b, 0x6b, 0xec, 0x89, 0x02, 0x2a, 0xc0, 0xca, 0x74, 0xbd, 0xd2, 0x6c, 0x34, 0xd4, 0x4a, 0x40, + 0xcc, 0xa0, 0x1c, 0x3c, 0xbe, 0x23, 0xe1, 0xb0, 0x51, 0xf1, 0xcb, 0x71, 0xb4, 0x0e, 0xcf, 0xa7, + 0xcb, 0x07, 0x8a, 0xe6, 0xbb, 0xcd, 0x5a, 0x53, 0x37, 0x6b, 0x5a, 0x43, 0xa9, 0x6b, 0xed, 0x43, + 0x31, 0x81, 0x9e, 0xc0, 0xf2, 0x34, 0xab, 0xab, 0x4a, 0xf5, 0x50, 0x4c, 0xa2, 0x55, 0x90, 0xef, + 0x2a, 0x46, 0xe6, 0x32, 0x8b, 0x56, 0x40, 0x9a, 0x66, 0x6a, 0x8a, 0x56, 0x57, 0xab, 0xe2, 0xdc, + 0x7d, 0xbd, 0x36, 0x5b, 0x2d, 0xdf, 0x3d, 0x8f, 0x5e, 0xc0, 0xda, 0xff, 0xa7, 0xaa, 0xe8, 0x95, + 0x7d, 0xed, 0x9d, 0x2a, 0xa6, 0xb6, 0x3e, 0x00, 0xaa, 0x5e, 0xdf, 0x39, 0x83, 0x78, 0x27, 0xd4, + 0x22, 0xe8, 0x0d, 0xa4, 0x26, 0x37, 0x1f, 0xdd, 0xbc, 0xe2, 0xb7, 0x1f, 0x8b, 0xac, 0x7c, 0x5f, + 0x39, 0x7c, 0x30, 0x76, 0x0f, 0xce, 0x2f, 0x65, 0xe1, 0xe2, 0x52, 0x16, 0xfe, 0x5c, 0xca, 0xc2, + 0xd9, 0x95, 0x1c, 0xbb, 0xb8, 0x92, 0x63, 0x3f, 0xaf, 0xe4, 0xd8, 0xfb, 0xd7, 0x36, 0xe5, 0xdd, + 0xe1, 0x51, 0xc9, 0x72, 0xfb, 0x65, 0xc7, 0xed, 0x90, 0xcd, 0x97, 0x9b, 0x1b, 0xd4, 0x2d, 0x8f, + 0xce, 0xd7, 0xc6, 0x27, 0x0f, 0x0f, 0x06, 0xc4, 0x8b, 0xbe, 0x7b, 0xaf, 0x22, 0xe3, 0xa3, 0xd9, + 0xe0, 0x1e, 0x6d, 0xff, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x4d, 0x35, 0xb1, 0x9b, 0x25, 0x05, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/diagnostics/state.go b/diagnostics/state.go new file mode 100644 index 0000000..116b874 --- /dev/null +++ b/diagnostics/state.go @@ -0,0 +1,24 @@ +package diagnostics + +const ( + // StateUnspecified represents an unset operational state. + StateUnspecified OperationalState = OperationalState_OPERATIONAL_STATE_UNSPECIFIED + // StateStarting indicates that runtime initialization is in progress. + StateStarting OperationalState = OperationalState_OPERATIONAL_STATE_STARTING + // StateConnecting indicates that PostgreSQL connectivity is being probed. + StateConnecting OperationalState = OperationalState_OPERATIONAL_STATE_CONNECTING + // StateSyncing indicates that archive reconciliation is in progress. + StateSyncing OperationalState = OperationalState_OPERATIONAL_STATE_SYNCING + // StateWaitingForFinality indicates that no finalized cursor is available yet. + StateWaitingForFinality OperationalState = OperationalState_OPERATIONAL_STATE_WAITING_FOR_FINALITY + // StateReady indicates that business queries are available. + StateReady OperationalState = OperationalState_OPERATIONAL_STATE_READY + // StateReconnecting indicates recovery from a PostgreSQL connection failure. + StateReconnecting OperationalState = OperationalState_OPERATIONAL_STATE_RECONNECTING + // StateFailed indicates a terminal runtime failure. + StateFailed OperationalState = OperationalState_OPERATIONAL_STATE_FAILED + // StateStopping indicates terminal shutdown is in progress. + StateStopping OperationalState = OperationalState_OPERATIONAL_STATE_STOPPING + // StateWaitingForArchive indicates that the archive target is behind the persisted cursor. + StateWaitingForArchive OperationalState = OperationalState_OPERATIONAL_STATE_WAITING_FOR_ARCHIVE +) diff --git a/diagnostics/store.go b/diagnostics/store.go index f2483f1..a24ffc3 100644 --- a/diagnostics/store.go +++ b/diagnostics/store.go @@ -34,7 +34,7 @@ func newStore(now func() time.Time) *Store { return &Store{ now: now, snapshot: Snapshot{ - State: OperationalState_OPERATIONAL_STATE_STARTING, + State: StateStarting, StateSince: startedAt, }, } diff --git a/diagnostics/store_test.go b/diagnostics/store_test.go index 472c1ad..7aa67e6 100644 --- a/diagnostics/store_test.go +++ b/diagnostics/store_test.go @@ -16,22 +16,22 @@ func TestStoreTracksStateProgressAndHistory(t *testing.T) { store := newStore(func() time.Time { return now }) initial := store.Snapshot() - require.Equal(t, OperationalState_OPERATIONAL_STATE_STARTING, initial.State) + require.Equal(t, StateStarting, initial.State) require.False(t, initial.Ready) require.Equal(t, now, initial.StateSince) now = now.Add(time.Second) - store.SetState(OperationalState_OPERATIONAL_STATE_STARTING, false) + store.SetState(StateStarting, false) require.Equal(t, initial.StateSince, store.Snapshot().StateSince) now = now.Add(time.Second) - store.SetState(OperationalState_OPERATIONAL_STATE_SYNCING, false) + store.SetState(StateSyncing, false) store.SetProgress(true, 10, 45, 13) store.RecordSuccessfulSync() store.RecordError("postgres query connection unavailable") snapshot := store.Snapshot() - require.Equal(t, OperationalState_OPERATIONAL_STATE_SYNCING, snapshot.State) + require.Equal(t, StateSyncing, snapshot.State) require.Equal(t, now, snapshot.StateSince) require.Equal(t, IndexerStatus{ Initialized: true, @@ -97,7 +97,7 @@ func TestStoreSupportsConcurrentReadersAndWriters(t *testing.T) { go func(height int64) { defer group.Done() store.SetProgress(true, height, height+32, height) - store.SetState(OperationalState_OPERATIONAL_STATE_SYNCING, true) + store.SetState(StateSyncing, true) }(int64(i + 1)) go func() { defer group.Done() diff --git a/docs/container.md b/docs/container.md new file mode 100644 index 0000000..42a128a --- /dev/null +++ b/docs/container.md @@ -0,0 +1,168 @@ +# Archive Wrapper Container Contract + +## Artifact + +The `Dockerfile` produces a pure-Go archive-wrapper binary in a pinned Go +builder and copies it into a pinned distroless `static-debian12:nonroot` +runtime. The runtime image has no shell or package manager and runs as +UID/GID `65532:65532`. + +Supported image platforms are: + +```text +linux/amd64 +linux/arm64 +``` + +Build a native image or a multi-platform OCI archive with: + +```sh +make docker-build IMAGE=archive-wrapper:local +make docker-build-multiarch OCI_OUTPUT=/tmp/archive-wrapper.oci.tar +``` + +`VERSION`, `COMMIT_SHA`, `SOURCE_DATE_EPOCH`, and `BUILD_DATE` may be supplied +as Make variables. Defaults use the checked-out commit and its timestamp; +wall-clock build time is not embedded. OCI timestamps are rewritten to +`SOURCE_DATE_EPOCH`, and provenance attestations are disabled for byte-stable +local OCI exports. + +Verify binary and OCI reproducibility with: + +```sh +make reproducible-build +make reproducible-image +``` + +The pinned builder, runtime, and PostgreSQL test-fixture digests must be updated +through a reviewed dependency bump. Re-run both platform builds, artifact +reproducibility checks, and `make docker-test` after any digest change. + +## Vulnerability scanning + +Container CI scans the actual builder stage and final runtime image separately. +Fixable `HIGH` and `CRITICAL` operating-system package vulnerabilities fail the +build for either image. Findings without an available upstream patch do not +block changes that cannot yet consume a fix. + +Go dependency findings are analyzed from source with `govulncheck` inside the +pinned builder environment. The scan targets only the shipped +`./cmd/archive-wrapper` executable, uses the production `purego` build tag, and +stores reachable findings as a report-only SARIF artifact. Findings remain +visible without blocking pull requests; tool installation, configuration, or +analysis failures still fail CI. Import-only and module-only informational +entries are excluded from the artifact; reachable findings are never +suppressed automatically. + +## Runtime mounts + +The image contains no wrapper config, Pulsar genesis, PostgreSQL URI, `.env` +file, LevelDB state, or log file. A deployment must provide: + +| Container path | Access | Purpose | +| --- | --- | --- | +| `/etc/archive-wrapper/config.yaml` | read-only | Wrapper configuration. | +| `/var/lib/pulsar` | read-only | Pulsar home containing `config/genesis.json`. | +| `/var/lib/archive-wrapper` | read-write volume | Persistent wrapper state. | +| `/run/archive-wrapper` | read-write tmpfs | Ephemeral control socket. | + +The container can run with a read-only root filesystem. The recommended +configuration uses: + +```yaml +read_only: true +volumes: + - wrapper_data:/var/lib/archive-wrapper + - ./config.yaml:/etc/archive-wrapper/config.yaml:ro + - ./pulsar-home:/var/lib/pulsar:ro +tmpfs: + - /run/archive-wrapper:uid=65532,gid=65532,mode=0700 +``` + +Set these absolute paths in the mounted config: + +```yaml +db_path: /var/lib/archive-wrapper/data/leveldb +control_socket_path: /run/archive-wrapper/control.sock +grpc_listen_address: 0.0.0.0:9095 +grpc_transport_mode: trusted-network +``` + +The image pre-creates `/var/lib/archive-wrapper/data` with ownership +`65532:65532`. Docker copies that directory into a newly created named volume. +For a host bind mount, the operator must create the data directory and set its +ownership to `65532:65532` before starting the container. + +## Process lifecycle + +The image contract is: + +```text +ENTRYPOINT: /usr/local/bin/archive-wrapper +CMD: run +stop signal: SIGTERM +``` + +`POSTGRES_URI` must be injected through the process environment or a container +secret mechanism. The wrapper writes logs to stderr by default. Do not set +`ARCHIVE_WRAPPER_LOG_PATH` unless a writable file mount is intentionally +provided. + +The same image command is used for first boot and restart. A fresh volume is +initialized with deployment metadata, while an existing volume is validated +and resumed from its cursor. Reusing a volume for another network, contract, or +start height fails. A second process using the same LevelDB volume fails with a +database lock error. + +On `SIGTERM`, the wrapper withdraws query readiness, cancels indexing, closes +the control listener, drains gRPC for up to ten seconds, and closes PostgreSQL +and LevelDB. Container stop timeouts should therefore be greater than ten +seconds; fifteen seconds is the tested minimum. + +## Health and networking + +The image healthcheck runs: + +```sh +archive-wrapper healthcheck --timeout 3s +``` + +It reads the effective gRPC listener from +`ARCHIVE_WRAPPER_GRPC_LISTEN_ADDRESS` and the mounted config, then checks the +standard gRPC health record for `query.Query`. Wildcard bind addresses are +dialed through loopback inside the container. `SERVING` is reported only after +a successful reconciliation has produced or recovered a LevelDB cursor. + +PostgreSQL connectivity alone does not produce readiness. Initial catch-up, +finality waiting, PostgreSQL loss, and reconnect are correctly non-serving. +The wrapper process remains alive during retryable PostgreSQL outages so the +healthcheck can distinguish unready from crashed. + +An archive target below the persisted LevelDB cursor is also non-serving and is +reported as `WAITING_FOR_ARCHIVE`. The wrapper does not rewind or delete the +cursor; it retries until the archive source catches up. Business query RPCs are +rejected with gRPC `Unavailable` while non-serving, while health and diagnostics +remain accessible for recovery inspection. + +`trusted-network` permits plaintext gRPC on a controlled private container +network. It records an operator-selected trust boundary; it does not implement +firewalling, authentication, or encryption. TLS/mTLS and public-network +exposure are outside this deployment mode. + +## Validation + +Run the complete image contract locally with: + +```sh +make docker-test +``` + +The harness uses an isolated Compose project and pinned PostgreSQL fixture. It +checks fresh boot, catch-up, PostgreSQL loss and recovery, restart persistence, +graceful exit, LevelDB locking, non-root/read-only execution, secret redaction, +three concurrent clients, and three independent wrapper instances. It removes +only the containers and volumes created under its unique project name. + +Pulsar validator containers, shared/per-validator topology generation, and the +full Pulsar-wrapper end-to-end lifecycle are intentionally deferred to the +next deployment phase. diff --git a/indexer/indexer.go b/indexer/indexer.go index a510ab5..f7bb806 100644 --- a/indexer/indexer.go +++ b/indexer/indexer.go @@ -159,6 +159,15 @@ func (indexer *Indexer) syncTo( } indexer.observer.OnSyncProgress(progress) + if exists && cursor > target { + return fmt.Errorf( + "%w: cursor=%d target=%d", + apperrors.ErrArchiveTargetBehindCursor, + cursor, + target, + ) + } + if target <= cursor { indexer.logger.InfoContext(ctx, "sync already up to date", "cursor", cursor, "target", target) indexer.observer.OnSyncCompleted(progress) diff --git a/indexer/indexer_test.go b/indexer/indexer_test.go index 61a5506..4ad4bf2 100644 --- a/indexer/indexer_test.go +++ b/indexer/indexer_test.go @@ -256,6 +256,47 @@ func TestSyncToAfterCursorlessRestartDoesNotStoreEmptyBlock(t *testing.T) { require.Equal(t, int64(10), cursor) } +func TestSyncToRejectsArchiveTargetBehindPersistedCursorBeforeMutation(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + conn := &fakeNotificationConn{listenReady: true} + querier := &fakeQuerier{ + conn: conn, + blockIDsByHeight: map[int64]int64{}, + rowsByHeight: map[int64][]sqlcdb.ListActionRowsByBlockIDRow{}, + } + client, err := fetchmina.NewMinaClient(testContractAddress, querier, logger) + require.NoError(t, err) + db, err := database.NewDbManager(t.TempDir(), blockHeightDatabaseKey, logger) + require.NoError(t, err) + defer func() { require.NoError(t, db.Close()) }() + require.NoError(t, db.InsertBlockHeight(68)) + observer := &recordingSyncObserver{} + + idx, err := NewIndexer(conn, client, db, 10, 32, logger, WithSyncObserver(observer)) + require.NoError(t, err) + err = idx.syncTo(context.Background(), 99, 67) + + require.ErrorIs(t, err, apperrors.ErrArchiveTargetBehindCursor) + require.Equal(t, []string{"progress"}, observer.events) + require.Equal(t, []SyncProgress{{ + ArchiveHeight: 99, + TargetHeight: 67, + Initialized: true, + IndexedHeight: 68, + }}, observer.progress) + require.Empty(t, observer.completed) + require.Empty(t, querier.primedRanges) + require.Empty(t, querier.requestedActionHeights) + require.Empty(t, querier.pointLookupHeights) + + cursor, err := db.GetBlockHeight() + require.NoError(t, err) + require.Equal(t, int64(68), cursor) + hasRecord, err := db.Has(67) + require.NoError(t, err) + require.False(t, hasRecord) +} + func TestIndexAvailableBlocksDoesNotAdvanceCursorOnInvalidBlock(t *testing.T) { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) diff --git a/proto/diagnostics/diagnostics.proto b/proto/diagnostics/diagnostics.proto index 697414b..ad2242e 100644 --- a/proto/diagnostics/diagnostics.proto +++ b/proto/diagnostics/diagnostics.proto @@ -21,6 +21,7 @@ enum OperationalState { OPERATIONAL_STATE_RECONNECTING = 6; OPERATIONAL_STATE_FAILED = 7; OPERATIONAL_STATE_STOPPING = 8; + OPERATIONAL_STATE_WAITING_FOR_ARCHIVE = 9; } message GetStatusRequest { diff --git a/scripts/check-reproducible-build.sh b/scripts/check-reproducible-build.sh new file mode 100755 index 0000000..3af52f0 --- /dev/null +++ b/scripts/check-reproducible-build.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail + +root_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +tmp_dir=$(mktemp -d) +trap 'rm -rf "$tmp_dir"' EXIT + +version=${VERSION:-dev} +commit_sha=${COMMIT_SHA:-$(git -C "$root_dir" rev-parse HEAD)} +source_date_epoch=${SOURCE_DATE_EPOCH:-$(git -C "$root_dir" show -s --format=%ct HEAD)} +build_date=${BUILD_DATE:-$(date -u -d "@$source_date_epoch" +%Y-%m-%dT%H:%M:%SZ)} +ldflags="-s -w -X main.version=$version -X main.commitSHA=$commit_sha -X main.buildDate=$build_date" + +for output in first second; do + GOCACHE="${GOCACHE:-/tmp/go-build-cache}" \ + go build -tags=purego -trimpath -buildvcs=false \ + -ldflags="$ldflags" -o "$tmp_dir/$output" "$root_dir/cmd/archive-wrapper" +done + +first_sum=$(sha256sum "$tmp_dir/first" | cut -d' ' -f1) +second_sum=$(sha256sum "$tmp_dir/second" | cut -d' ' -f1) +[[ $first_sum == "$second_sum" ]] +echo "reproducible binary sha256=$first_sum" diff --git a/scripts/check-reproducible-image.sh b/scripts/check-reproducible-image.sh new file mode 100755 index 0000000..48073d1 --- /dev/null +++ b/scripts/check-reproducible-image.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail + +root_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +tmp_dir=$(mktemp -d) +trap 'rm -rf "$tmp_dir"' EXIT + +for output in first second; do + make -C "$root_dir" docker-build-multiarch \ + VERSION="${VERSION:-dev}" \ + COMMIT_SHA="${COMMIT_SHA:-unknown}" \ + SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-0}" \ + BUILD_DATE="${BUILD_DATE:-unknown}" \ + DOCKER_BUILDER="${DOCKER_BUILDER:-archive-wrapper-builder}" \ + DOCKER_PLATFORMS="${DOCKER_PLATFORMS:-linux/amd64,linux/arm64}" \ + OCI_OUTPUT="$tmp_dir/$output.oci.tar" +done + +first_sum=$(sha256sum "$tmp_dir/first.oci.tar" | cut -d' ' -f1) +second_sum=$(sha256sum "$tmp_dir/second.oci.tar" | cut -d' ' -f1) +[[ $first_sum == "$second_sum" ]] +echo "reproducible OCI sha256=$first_sum" diff --git a/scripts/test-container.sh b/scripts/test-container.sh new file mode 100755 index 0000000..2831408 --- /dev/null +++ b/scripts/test-container.sh @@ -0,0 +1,209 @@ +#!/usr/bin/env bash +set -euo pipefail + +root_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +compose_file="$root_dir/testdata/container/compose.yaml" +project="archive-wrapper-test-${CI_JOB_ID:-$$}-${RANDOM}" +image="${ARCHIVE_WRAPPER_IMAGE:-archive-wrapper:container-test}" +export ARCHIVE_WRAPPER_IMAGE="$image" +tmp_dir=$(mktemp -d) +inspect_container_id="" + +compose=(docker compose --project-name "$project" --file "$compose_file") + +cleanup() { + local status=$? + if (( status != 0 )); then + "${compose[@]}" ps >&2 || true + "${compose[@]}" logs --no-color >&2 || true + if [[ -n ${ARCHIVE_WRAPPER_ARTIFACT_DIR:-} ]]; then + mkdir -p "$ARCHIVE_WRAPPER_ARTIFACT_DIR" + "${compose[@]}" ps --all >"$ARCHIVE_WRAPPER_ARTIFACT_DIR/compose-ps.txt" 2>&1 || true + "${compose[@]}" logs --no-color >"$ARCHIVE_WRAPPER_ARTIFACT_DIR/compose.log" 2>&1 || true + docker image inspect "$image" >"$ARCHIVE_WRAPPER_ARTIFACT_DIR/image-inspect.json" 2>&1 || true + fi + fi + if [[ -n $inspect_container_id ]]; then + docker rm --force "$inspect_container_id" >/dev/null 2>&1 || true + fi + "${compose[@]}" --profile lock --profile isolation down --volumes --remove-orphans >/dev/null 2>&1 || true + rm -rf "$tmp_dir" + exit "$status" +} +trap cleanup EXIT + +wait_for_container_state() { + local service=$1 + local expected=$2 + local timeout=${3:-60} + local container_id + container_id=$("${compose[@]}" ps --all --quiet "$service") + for ((attempt = 0; attempt < timeout; attempt++)); do + if [[ $(docker inspect --format '{{.State.Status}}' "$container_id") == "$expected" ]]; then + return 0 + fi + sleep 1 + done + echo "$service did not reach state $expected" >&2 + return 1 +} + +wait_for_healthy() { + local service=$1 + local timeout=${2:-90} + local container_id + container_id=$("${compose[@]}" ps --all --quiet "$service") + for ((attempt = 0; attempt < timeout; attempt++)); do + if [[ $(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$container_id") == healthy ]]; then + return 0 + fi + sleep 1 + done + echo "$service did not become healthy" >&2 + return 1 +} + +wait_for_probe_failure() { + local service=$1 + local timeout=${2:-30} + for ((attempt = 0; attempt < timeout; attempt++)); do + if ! "${compose[@]}" exec -T "$service" /usr/local/bin/archive-wrapper healthcheck --timeout 1s >/dev/null 2>&1; then + return 0 + fi + sleep 1 + done + echo "$service health probe did not fail" >&2 + return 1 +} + +published_address() { + "${compose[@]}" port "$1" 9095 | head -n 1 | sed -E 's/^0\.0\.0\.0:/127.0.0.1:/; s/^\[::\]:/[::1]:/' +} + +inspect_image_contract() { + local image_user image_entrypoint image_command version_label revision_label created_label version_output + image_user=$(docker image inspect --format '{{.Config.User}}' "$image") + image_entrypoint=$(docker image inspect --format '{{json .Config.Entrypoint}}' "$image") + image_command=$(docker image inspect --format '{{json .Config.Cmd}}' "$image") + version_label=$(docker image inspect --format '{{index .Config.Labels "org.opencontainers.image.version"}}' "$image") + revision_label=$(docker image inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$image") + created_label=$(docker image inspect --format '{{index .Config.Labels "org.opencontainers.image.created"}}' "$image") + version_output=$(docker run --rm --entrypoint /usr/local/bin/archive-wrapper "$image" version) + + [[ $image_user == 65532:65532 ]] + [[ $image_entrypoint == '["/usr/local/bin/archive-wrapper"]' ]] + [[ $image_command == '["run"]' ]] + [[ $version_output == *"version=$version_label"* ]] + [[ $version_output == *"commit=$revision_label"* ]] + [[ $version_output == *"build_date=$created_label"* ]] + + if docker run --rm --entrypoint /bin/sh "$image" -c true >/dev/null 2>&1; then + echo "runtime image unexpectedly contains a shell" >&2 + return 1 + fi + + inspect_container_id=$(docker create "$image") + docker export "$inspect_container_id" >"$tmp_dir/rootfs.tar" + docker rm "$inspect_container_id" >/dev/null + inspect_container_id="" + tar -tf "$tmp_dir/rootfs.tar" >"$tmp_dir/rootfs-files" + if grep -qE '(^|/)(\.env|config\.yaml)$|^src/|^var/lib/archive-wrapper/data/leveldb/' "$tmp_dir/rootfs-files"; then + echo "runtime image contains source, config, secret, or runtime state" >&2 + return 1 + fi +} + +if [[ ${ARCHIVE_WRAPPER_SKIP_BUILD:-0} != 1 ]]; then + make -C "$root_dir" docker-build IMAGE="$image" +fi +inspect_image_contract + +# The wrapper must remain alive but non-serving until PostgreSQL is available. +"${compose[@]}" up --detach --no-deps wrapper1 +wait_for_container_state wrapper1 running +wait_for_probe_failure wrapper1 +wrapper_address=$(published_address wrapper1) +ARCHIVE_WRAPPER_TEST_ADDRESSES="$wrapper_address" \ + GOCACHE="${GOCACHE:-/tmp/go-build-cache}" \ + go test -tags=container ./tests/container -run '^TestUnavailableQueryIsRejected$' -count=1 + +"${compose[@]}" up --detach postgres +wait_for_healthy postgres +wait_for_healthy wrapper1 + +wrapper_address=$(published_address wrapper1) +ARCHIVE_WRAPPER_TEST_ADDRESSES="$wrapper_address" \ + GOCACHE="${GOCACHE:-/tmp/go-build-cache}" \ + go test -tags=container ./tests/container -run '^TestConcurrentClients$' -count=1 + +# A PostgreSQL outage withdraws readiness, and recovery does not require a wrapper restart. +"${compose[@]}" stop postgres +wait_for_probe_failure wrapper1 +wrapper_address=$(published_address wrapper1) +ARCHIVE_WRAPPER_TEST_ADDRESSES="$wrapper_address" \ + GOCACHE="${GOCACHE:-/tmp/go-build-cache}" \ + go test -tags=container ./tests/container -run '^TestUnavailableQueryIsRejected$' -count=1 +"${compose[@]}" start postgres +wait_for_healthy postgres +wait_for_healthy wrapper1 + +# Restart uses the same command and volume and must preserve the indexed cursor. +"${compose[@]}" stop --timeout 15 wrapper1 +wrapper_exit_code=$(docker inspect --format '{{.State.ExitCode}}' "$("${compose[@]}" ps --all --quiet wrapper1)") +[[ $wrapper_exit_code -eq 0 ]] +"${compose[@]}" start wrapper1 +wait_for_healthy wrapper1 +wrapper_address=$(published_address wrapper1) +ARCHIVE_WRAPPER_TEST_ADDRESSES="$wrapper_address" \ + GOCACHE="${GOCACHE:-/tmp/go-build-cache}" \ + go test -tags=container ./tests/container -run '^TestConcurrentClients$' -count=1 + +# A second owner of the same LevelDB volume must fail instead of serving stale state. +"${compose[@]}" --profile lock up --detach --no-deps wrapper-lock +wait_for_container_state wrapper-lock exited +lock_exit_code=$(docker inspect --format '{{.State.ExitCode}}' "$("${compose[@]}" ps -aq wrapper-lock)") +[[ $lock_exit_code -ne 0 ]] +"${compose[@]}" logs --no-color wrapper-lock | grep -q 'database is locked' + +wrapper_id=$("${compose[@]}" ps -q wrapper1) +[[ $(docker inspect --format '{{.Config.User}}' "$wrapper_id") == 65532:65532 ]] +[[ $(docker inspect --format '{{.HostConfig.ReadonlyRootfs}}' "$wrapper_id") == true ]] + +logs=$("${compose[@]}" logs --no-color wrapper1 wrapper-lock) +if grep -qE 'container-secret|postgres://archive:' <<<"$logs"; then + echo "container logs exposed PostgreSQL credentials" >&2 + exit 1 +fi + +data_volume="${project}_wrapper1_data" +docker run --rm --volume "$data_volume:/data:ro" \ + --entrypoint /bin/sh \ + postgres:17-bookworm@sha256:4f736ae292687621d4dbe0d499ffd024a36bd2ee7d8ca6f2ccd4c800f047b394 \ + -c 'test "$(stat -c %u:%g /data/data)" = 65532:65532 && test ! -e /data/archive-wrapper.log' + +# Independent wrapper state must remain isolated even when PostgreSQL is shared. +"${compose[@]}" --profile isolation up --detach --no-deps wrapper2 wrapper3 +wait_for_healthy wrapper2 +wait_for_healthy wrapper3 +wrapper1_address=$(published_address wrapper1) +wrapper2_address=$(published_address wrapper2) +wrapper3_address=$(published_address wrapper3) +ARCHIVE_WRAPPER_TEST_ADDRESSES="$wrapper1_address,$wrapper2_address,$wrapper3_address" \ + GOCACHE="${GOCACHE:-/tmp/go-build-cache}" \ + go test -tags=container ./tests/container -run '^TestWrapperIsolation$' -count=1 + +"${compose[@]}" stop --timeout 15 wrapper2 +wrapper2_exit_code=$(docker inspect --format '{{.State.ExitCode}}' "$("${compose[@]}" ps --all --quiet wrapper2)") +[[ $wrapper2_exit_code -eq 0 ]] +ARCHIVE_WRAPPER_TEST_ADDRESSES="$wrapper1_address,$wrapper3_address" \ + GOCACHE="${GOCACHE:-/tmp/go-build-cache}" \ + go test -tags=container ./tests/container -run '^TestWrapperIsolation$' -count=1 + +"${compose[@]}" start wrapper2 +wait_for_healthy wrapper2 +wrapper2_address=$(published_address wrapper2) +ARCHIVE_WRAPPER_TEST_ADDRESSES="$wrapper1_address,$wrapper2_address,$wrapper3_address" \ + GOCACHE="${GOCACHE:-/tmp/go-build-cache}" \ + go test -tags=container ./tests/container -run '^TestWrapperIsolation$' -count=1 + +echo "container lifecycle, shared-client, and wrapper-isolation smoke tests passed" diff --git a/testdata/container/chain-home/config/genesis.json b/testdata/container/chain-home/config/genesis.json new file mode 100644 index 0000000..248f9d6 --- /dev/null +++ b/testdata/container/chain-home/config/genesis.json @@ -0,0 +1,12 @@ +{ + "app_state": { + "bridge": { + "params": { + "confirmation_depth": "2", + "contract_address": "B62qjRDirGFRf5dvNcGzMs5oWzQ2VyNcygnoKM2MkxB9PFUp7Utdraf", + "start_block_height": "10", + "max_block_range": "100" + } + } + } +} diff --git a/testdata/container/compose.yaml b/testdata/container/compose.yaml new file mode 100644 index 0000000..6526b6d --- /dev/null +++ b/testdata/container/compose.yaml @@ -0,0 +1,74 @@ +services: + postgres: + image: postgres:17-bookworm@sha256:4f736ae292687621d4dbe0d499ffd024a36bd2ee7d8ca6f2ccd4c800f047b394 + environment: + POSTGRES_DB: archive + POSTGRES_USER: archive + POSTGRES_PASSWORD: container-secret + healthcheck: + test: ["CMD-SHELL", "pg_isready -U archive -d archive"] + interval: 2s + timeout: 2s + retries: 15 + volumes: + - ../../fetchmina/sql/schema.sql:/docker-entrypoint-initdb.d/01-schema.sql:ro + - ./seed.sql:/docker-entrypoint-initdb.d/02-seed.sql:ro + + wrapper1: + image: ${ARCHIVE_WRAPPER_IMAGE} + read_only: true + environment: &wrapper-environment + POSTGRES_URI: postgres://archive:container-secret@postgres:5432/archive?sslmode=disable + volumes: + - ./wrapper.yaml:/etc/archive-wrapper/config.yaml:ro + - ./chain-home:/var/lib/pulsar:ro + - wrapper1_data:/var/lib/archive-wrapper + tmpfs: + - /run/archive-wrapper:uid=65532,gid=65532,mode=0700 + ports: + - "9095" + + wrapper-lock: + profiles: ["lock"] + image: ${ARCHIVE_WRAPPER_IMAGE} + read_only: true + environment: *wrapper-environment + volumes: + - ./wrapper.yaml:/etc/archive-wrapper/config.yaml:ro + - ./chain-home:/var/lib/pulsar:ro + - wrapper1_data:/var/lib/archive-wrapper + tmpfs: + - /run/archive-wrapper:uid=65532,gid=65532,mode=0700 + + wrapper2: + profiles: ["isolation"] + image: ${ARCHIVE_WRAPPER_IMAGE} + read_only: true + environment: *wrapper-environment + volumes: + - ./wrapper.yaml:/etc/archive-wrapper/config.yaml:ro + - ./chain-home:/var/lib/pulsar:ro + - wrapper2_data:/var/lib/archive-wrapper + tmpfs: + - /run/archive-wrapper:uid=65532,gid=65532,mode=0700 + ports: + - "9095" + + wrapper3: + profiles: ["isolation"] + image: ${ARCHIVE_WRAPPER_IMAGE} + read_only: true + environment: *wrapper-environment + volumes: + - ./wrapper.yaml:/etc/archive-wrapper/config.yaml:ro + - ./chain-home:/var/lib/pulsar:ro + - wrapper3_data:/var/lib/archive-wrapper + tmpfs: + - /run/archive-wrapper:uid=65532,gid=65532,mode=0700 + ports: + - "9095" + +volumes: + wrapper1_data: + wrapper2_data: + wrapper3_data: diff --git a/testdata/container/seed.sql b/testdata/container/seed.sql new file mode 100644 index 0000000..84a5ea2 --- /dev/null +++ b/testdata/container/seed.sql @@ -0,0 +1,24 @@ +INSERT INTO blocks (id, height, chain_status, global_slot_since_genesis, parent_id, state_hash) VALUES + (10, 10, 'pending', 10, NULL, 'state-10'), + (11, 11, 'pending', 11, 10, 'state-11'), + (12, 12, 'pending', 12, 11, 'state-12'), + (13, 13, 'pending', 13, 12, 'state-13'), + (14, 14, 'pending', 14, 13, 'state-14'); + +INSERT INTO public_keys (id, value) VALUES + (1, 'B62qjRDirGFRf5dvNcGzMs5oWzQ2VyNcygnoKM2MkxB9PFUp7Utdraf'), + (2, 'B62qjTpSX2R4fyqJrC9pzvm5PSZb5GMaYBXh8di3TBn6pPC9XXYFC9k'); +INSERT INTO zkapp_fee_payer_body (id, public_key_id) VALUES (1, 2); +INSERT INTO account_identifiers (id, public_key_id) VALUES (1, 1); +INSERT INTO zkapp_field (id, field) VALUES + (1, '1'), + (2, 'ignored'), + (3, 'ignored'), + (4, '42'); +INSERT INTO zkapp_field_array (id, element_ids) VALUES (1, ARRAY[1, 2, 3, 4]::bigint[]); +INSERT INTO zkapp_events (id, element_ids) VALUES (1, ARRAY[1]::bigint[]); +INSERT INTO zkapp_account_update_body (id, account_identifier_id, actions_id) VALUES (1, 1, 1); +INSERT INTO zkapp_account_update (id, body_id) VALUES (1, 1); +INSERT INTO zkapp_commands (id, zkapp_fee_payer_body_id, zkapp_account_updates_ids, hash) +VALUES (1, 1, ARRAY[1]::bigint[], 'command-1'); +INSERT INTO blocks_zkapp_commands (block_id, zkapp_command_id, sequence_no) VALUES (11, 1, 0); diff --git a/testdata/container/wrapper.yaml b/testdata/container/wrapper.yaml new file mode 100644 index 0000000..f02b984 --- /dev/null +++ b/testdata/container/wrapper.yaml @@ -0,0 +1,9 @@ +block_height_database_key: "archive-wrapper" +db_path: "/var/lib/archive-wrapper/data/leveldb" +grpc_listen_address: "0.0.0.0:9095" +grpc_transport_mode: "trusted-network" +control_socket_path: "/run/archive-wrapper/control.sock" +deployment_metadata_key: "archive-wrapper:deployment" +deployment_metadata: + schema_version: 1 + mina_network_id: "container-testnet" diff --git a/tests/container/smoke_test.go b/tests/container/smoke_test.go new file mode 100644 index 0000000..8f7e048 --- /dev/null +++ b/tests/container/smoke_test.go @@ -0,0 +1,184 @@ +//go:build container + +package container_test + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/node101-io/archive-wrapper/actions" + "github.com/node101-io/archive-wrapper/query" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + grpcHealthV1 "google.golang.org/grpc/health/grpc_health_v1" + "google.golang.org/grpc/status" +) + +const queryServiceName = "query.Query" + +type wrapperResult struct { + height int64 + amount int64 + feePayer string +} + +func TestUnavailableQueryIsRejected(t *testing.T) { + address := testAddresses(t)[0] + connection, err := grpc.NewClient(address, grpc.WithTransportCredentials(insecure.NewCredentials())) + require.NoError(t, err) + defer connection.Close() + + require.Eventually(t, func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + + health, err := grpcHealthV1.NewHealthClient(connection).Check( + ctx, + &grpcHealthV1.HealthCheckRequest{Service: queryServiceName}, + ) + if err != nil || health.Status != grpcHealthV1.HealthCheckResponse_NOT_SERVING { + return false + } + + _, err = query.NewQueryClient(connection).GetMinaBlockHeight( + ctx, + &query.QueryGetMinaBlockHeightRequest{}, + ) + return status.Code(err) == codes.Unavailable + }, 10*time.Second, 100*time.Millisecond) +} + +func TestConcurrentClients(t *testing.T) { + addresses := testAddresses(t) + address := addresses[0] + + results := make(chan wrapperResult, 3) + workerErrors := make(chan error, 3) + start := make(chan struct{}) + var workers sync.WaitGroup + + for clientIndex := 0; clientIndex < 3; clientIndex++ { + clientIndex := clientIndex + workers.Add(1) + go func() { + defer workers.Done() + connection, err := grpc.NewClient(address, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + workerErrors <- err + return + } + defer connection.Close() + <-start + + if clientIndex == 0 { + canceledContext, cancel := context.WithCancel(context.Background()) + cancel() + _, _ = grpcHealthV1.NewHealthClient(connection).Check( + canceledContext, + &grpcHealthV1.HealthCheckRequest{Service: queryServiceName}, + ) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + result, err := queryWrapper(ctx, connection) + if err != nil { + workerErrors <- err + return + } + results <- result + }() + } + + close(start) + workers.Wait() + close(results) + close(workerErrors) + for err := range workerErrors { + require.NoError(t, err) + } + resultCount := 0 + for got := range results { + require.Equal(t, int64(12), got.height) + require.Equal(t, int64(42), got.amount) + require.NotEmpty(t, got.feePayer) + resultCount++ + } + require.Equal(t, 3, resultCount) +} + +func TestWrapperIsolation(t *testing.T) { + addresses := testAddresses(t) + require.NotEmpty(t, addresses) + + var expected wrapperResult + for index, address := range addresses { + connection, err := grpc.NewClient(address, grpc.WithTransportCredentials(insecure.NewCredentials())) + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + result, queryErr := queryWrapper(ctx, connection) + cancel() + require.NoError(t, connection.Close()) + require.NoError(t, queryErr) + if index == 0 { + expected = result + continue + } + require.Equal(t, expected, result) + } +} + +func queryWrapper(ctx context.Context, connection *grpc.ClientConn) (wrapperResult, error) { + health, err := grpcHealthV1.NewHealthClient(connection).Check( + ctx, + &grpcHealthV1.HealthCheckRequest{Service: queryServiceName}, + ) + if err != nil { + return wrapperResult{}, err + } + if health.Status != grpcHealthV1.HealthCheckResponse_SERVING { + return wrapperResult{}, fmt.Errorf("unexpected health status: %s", health.Status) + } + + queryClient := query.NewQueryClient(connection) + heightResponse, err := queryClient.GetMinaBlockHeight(ctx, &query.QueryGetMinaBlockHeightRequest{}) + if err != nil { + return wrapperResult{}, err + } + actionsResponse, err := queryClient.GetActionsInRange(ctx, &query.QueryGetActionsInRangeRequest{ + StartBlockHeight: 10, + EndBlockHeight: 12, + }) + if err != nil { + return wrapperResult{}, err + } + if len(actionsResponse.Actions) != 1 { + return wrapperResult{}, fmt.Errorf("unexpected action count: %d", len(actionsResponse.Actions)) + } + action := actionsResponse.Actions[0] + if action.BlockHeight != 11 || action.ActionType != actions.ActionType_DEPOSIT || len(action.FeePayer) == 0 { + return wrapperResult{}, errors.New("unexpected action payload") + } + + return wrapperResult{ + height: heightResponse.BlockHeight, + amount: action.Amount, + feePayer: string(action.FeePayer), + }, nil +} + +func testAddresses(t *testing.T) []string { + t.Helper() + raw := strings.TrimSpace(os.Getenv("ARCHIVE_WRAPPER_TEST_ADDRESSES")) + require.NotEmpty(t, raw, "ARCHIVE_WRAPPER_TEST_ADDRESSES is required") + return strings.Split(raw, ",") +}