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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,17 @@ GO_BUILD_TAGS := purego

export GOCACHE := $(CURDIR)/.cache/go-build
export GOLANGCI_LINT_CACHE := $(CURDIR)/.cache/golangci-lint
export POSTGRES_URI
export ARCHIVE_WRAPPER_CONFIG
export ARCHIVE_WRAPPER_CHAIN_HOME
export ARCHIVE_WRAPPER_GRPC_LISTEN_ADDRESS
export ARCHIVE_WRAPPER_GRPC_TRANSPORT_MODE
export ARCHIVE_WRAPPER_DB_PATH
export ARCHIVE_WRAPPER_CONTROL_SOCKET_PATH
export ARCHIVE_WRAPPER_LOG_PATH
CONFIG ?= config.yaml

.PHONY: ensure-cache proto fmt test lint build start proceed stop
.PHONY: ensure-cache proto fmt test lint build run stop

ensure-cache:
mkdir -p "$(GOCACHE)" "$(GOLANGCI_LINT_CACHE)"
Expand All @@ -27,13 +35,9 @@ lint: ensure-cache
build: ensure-cache
go build -tags=$(GO_BUILD_TAGS) -o archive-wrapper ./cmd/archive-wrapper

start: build
@test -n "$(CHAIN_HOME)" || (echo "usage: make start CHAIN_HOME=/path/to/pulsar [CONFIG=config.yaml]" && exit 1)
./archive-wrapper start --config $(CONFIG) --home $(CHAIN_HOME)

proceed: build
@test -n "$(CHAIN_HOME)" || (echo "usage: make proceed CHAIN_HOME=/path/to/pulsar [CONFIG=config.yaml]" && exit 1)
./archive-wrapper proceed --config $(CONFIG) --home $(CHAIN_HOME)
run: build
@test -n "$(CONFIG)" || (echo "CONFIG is required" && exit 1)
./archive-wrapper run --config "$(CONFIG)" $(if $(CHAIN_HOME),--home "$(CHAIN_HOME)",)

stop:
./archive-wrapper stop --config $(CONFIG) $(if $(SOCKET_PATH),--socket-path $(SOCKET_PATH),)
./archive-wrapper stop --config "$(CONFIG)" $(if $(CONTROL_SOCKET_PATH),--control-socket-path "$(CONTROL_SOCKET_PATH)",)
82 changes: 41 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,26 +36,32 @@ fields are:
| `db_path` | Local LevelDB directory. |
| `grpc_listen_address` | TCP address for the local query server. |
| `grpc_transport_mode` | `loopback` by default, or explicit `trusted-network`. |
| `chain_home` | Optional Pulsar home; start/proceed require it from config, CLI, or environment. |
| `control_socket_path` | Unix socket used by the `stop` command. |
| `chain_home` | Optional Pulsar home; `run` requires it from config, CLI, or environment. |
| `control_socket_path` | Unix socket used by the `run` and `stop` commands. |
| `deployment_metadata_key` | LevelDB key used to store deployment identity. |
| `deployment_metadata.schema_version` | Stored deployment metadata schema version. |
| `deployment_metadata.mina_network_id` | Mina network whose archive database is indexed. |

The first start binds the LevelDB database to its schema version, Mina network,
contract address, and genesis start height. `proceed` requires those values to
match before connecting to PostgreSQL. To change deployment identity, use a
new `db_path` and run `start`. The latest cursor is advanced only after a block
has been fetched successfully; action-bearing blocks are stored before the
cursor update. A missing best-chain block or a temporary PostgreSQL failure
leaves the cursor available for retry after restart or reconnection.
`run` binds a fresh LevelDB database to its schema version, Mina network,
contract address, and genesis start height. On restart, the same command
validates that identity and resumes from the persisted cursor. A database with
mismatched metadata, application state without metadata, malformed metadata or
cursor data, or a lock held by another process fails before PostgreSQL or gRPC
is opened. To change deployment identity, use a new `db_path`.

The latest cursor is advanced only after a block has been fetched successfully;
action-bearing blocks and their cursor are committed atomically. A missing
best-chain block or a temporary PostgreSQL failure leaves the cursor available
for retry after restart or reconnection.

## Build and run

Prefer the Makefile targets for day-to-day use.

Create a local `.env` file in the repository root first. The Makefile includes
it, and the executable also loads it at runtime.
For local Makefile usage, values may be placed in a repository-root `.env`
file. The Makefile includes this file; the executable itself never loads
`.env`. Container and direct binary deployments must inject environment
variables through their process environment.

Example:

Expand All @@ -75,19 +81,20 @@ Build the pure-Go binary with:
make build
```

Start the sidecar by providing the validator chain home:
Run the sidecar. `CHAIN_HOME` is optional when chain home is already supplied by
`chain_home` or `ARCHIVE_WRAPPER_CHAIN_HOME`:

```sh
make start
make run CHAIN_HOME=/path/to/validator
```

If you want a non-default wrapper config file, pass it explicitly:

```sh
make start CONFIG=/path/to/config.yaml
make run CONFIG=/path/to/config.yaml CHAIN_HOME=/path/to/validator
```

`start` reads `bridge.contract_address`, `bridge.confirmation_depth`,
`run` reads `bridge.contract_address`, `bridge.confirmation_depth`,
`bridge.start_block_height`, and `bridge.max_block_range` from
`/path/to/validator/config/genesis.json`, catches up to the archive tip minus
that depth, and then follows the PostgreSQL `blocks_inserted` notifications.
Expand All @@ -97,15 +104,9 @@ cursor. Payload contents, duplicate notifications, and coalesced notifications
do not determine the indexed range. Query and notification connection failures
are retried while the process is running.

To resume an existing LevelDB, use:

```sh
make proceed
```

`proceed` accepts an existing LevelDB even before its first cursor is written.
It resumes from the persisted cursor when present, or continues the initial
sync from the genesis start height when the cursor is still missing.
The same `make run` command is used for first boot and every restart. It accepts
an initialized LevelDB even before its first cursor is written, resumes from the
cursor when present, or continues initial sync from the genesis start height.

Stop the running process through its Unix control socket:

Expand All @@ -116,47 +117,46 @@ make stop
If you need a custom config or socket path while stopping:

```sh
make stop CONFIG=/path/to/config.yaml SOCKET_PATH=/tmp/archive-wrapper.sock
make stop CONFIG=/path/to/config.yaml CONTROL_SOCKET_PATH=/tmp/archive-wrapper.sock
```

The control socket accepts `PING` (responding with `PONG`) and `STOP`. The
process also shuts down gracefully on `SIGINT` or `SIGTERM`. The `stop`
command can use `--control-socket-path` directly (or the legacy
`--socket-path` alias). Otherwise it resolves the socket from
`ARCHIVE_WRAPPER_CONTROL_SOCKET_PATH` and then the selected config file.
command can use `--control-socket-path` directly. Otherwise it resolves the
socket from `ARCHIVE_WRAPPER_CONTROL_SOCKET_PATH` and then the selected config
file.
Shutdown first publishes `NOT_SERVING`, then cancels indexing and closes the
control listener. gRPC receives a 10-second graceful drain period before active
RPCs are forcibly stopped; PostgreSQL and LevelDB are closed afterward.

### Without Makefile

If you need to bypass the Makefile, the equivalent direct commands are:

```sh
./archive-wrapper start --config config.yaml --home /path/to/validator

./archive-wrapper proceed --config config.yaml --home /path/to/validator
./archive-wrapper run --config config.yaml --home /path/to/validator

./archive-wrapper stop --config config.yaml
```

For local development, you can also run the CLI without building first:

```sh
go run ./cmd/archive-wrapper start --config config.yaml --home /path/to/validator
go run ./cmd/archive-wrapper run --config config.yaml --home /path/to/validator
```

The executable loads `.env` when present. The supported environment variables
are:
The supported process environment variables are:

- `POSTGRES_URI` — archive PostgreSQL connection string; required for `start`
and `proceed`.
- `ARCHIVE_WRAPPER_CONFIG` — default config path for `start`, `proceed`, and
`stop`.
- `ARCHIVE_WRAPPER_CHAIN_HOME` — Pulsar chain home for `start` and `proceed`.
- `POSTGRES_URI` — archive PostgreSQL connection string; required for `run`.
- `ARCHIVE_WRAPPER_CONFIG` — default config path for `run` and `stop`.
- `ARCHIVE_WRAPPER_CHAIN_HOME` — Pulsar chain home for `run`.
- `ARCHIVE_WRAPPER_GRPC_LISTEN_ADDRESS` — effective gRPC listen address.
- `ARCHIVE_WRAPPER_GRPC_TRANSPORT_MODE` — effective gRPC transport mode.
- `ARCHIVE_WRAPPER_DB_PATH` — effective LevelDB path.
- `ARCHIVE_WRAPPER_CONTROL_SOCKET_PATH` — fallback socket path for `stop`.
- `ARCHIVE_WRAPPER_LOG_PATH` — append-only log path; defaults to
`archive-wrapper.log`.
- `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`.

## gRPC queries

Expand Down
10 changes: 6 additions & 4 deletions apperrors/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@ var (
ErrBlockHeightMustBeBiggerThanZero = errors.New("block height must be bigger than zero")
// ErrInvalidKey reports that a stored block record key does not match its action heights.
ErrInvalidKey = errors.New("invalid key")
// ErrDeploymentMetadataMissing reports indexed state that has no deployment identity.
ErrDeploymentMetadataMissing = errors.New("deployment metadata is missing")
// ErrDeploymentMetadataMismatch reports an attempt to reuse a DB for another deployment.
ErrDeploymentMetadataMismatch = errors.New("deployment metadata does not match")
// ErrDBLocked reports that another process owns the configured LevelDB.
ErrDBLocked = errors.New("database is locked")
// ErrDBCorrupt reports malformed or corrupted persisted wrapper state.
ErrDBCorrupt = errors.New("database state is corrupt")
// ErrDBStateIncomplete reports application data without deployment identity.
ErrDBStateIncomplete = errors.New("database state is incomplete")
)

var (
Expand Down Expand Up @@ -87,8 +91,6 @@ var (
ErrBlockHeightDBKeyRequired = errors.New("block_height_database_key is required")
// ErrDBPathRequired reports that db_path is missing from config.
ErrDBPathRequired = errors.New("db_path is required")
// ErrDBAlreadyExists reports that start was asked to use an existing LevelDB path.
ErrDBAlreadyExists = errors.New("db already exists")
// ErrControlSocketPathRequired reports that the control socket path is missing from config.
ErrControlSocketPathRequired = errors.New("control socket path is required")
// ErrDeploymentMetadataKeyRequired reports that the deployment metadata key is missing from config.
Expand Down
85 changes: 20 additions & 65 deletions cmd/archive-wrapper/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
Expand All @@ -11,7 +10,6 @@ import (

"github.com/node101-io/archive-wrapper/apperrors"
"github.com/node101-io/archive-wrapper/config"
"github.com/syndtr/goleveldb/leveldb"
)

// run validates command-specific inputs before handing control to the runtime.
Expand All @@ -23,11 +21,14 @@ func run(args []string, ctx context.Context, cancel context.CancelFunc, logger *
}

switch strings.ToLower(args[0]) {
case "start":
cmd := newRuntimeFlagSet("start")
case "run":
cmd := newRuntimeFlagSet("run")
if err := cmd.Parse(args[1:]); err != nil {
return err
}
if cmd.NArg() != 0 {
return fmt.Errorf("run does not accept positional arguments: %q", cmd.Args())
}
configPath, err := resolveConfigPath(cmd.FlagSet, *cmd.configPath)
if err != nil {
return err
Expand All @@ -37,75 +38,37 @@ func run(args []string, ctx context.Context, cancel context.CancelFunc, logger *
return err
}

cliLogger.Info("start command received", "config", configPath, "home", cfg.ChainHome)
if err := ensureDBPathDoesNotExist(cfg.DBPath); err != nil {
return err
}

bridgeParams, err := loadBridgeParamsFromHome(cfg.ChainHome)
params, err := loadBridgeParamsFromHome(cfg.ChainHome)
if err != nil {
return fmt.Errorf("load bridge params from genesis: %w", err)
}
return runStart(ctx, cfg, bridgeParams, cancel, logger)

case "proceed":
cmd := newRuntimeFlagSet("proceed")
if err := cmd.Parse(args[1:]); err != nil {
return err
}
configPath, err := resolveConfigPath(cmd.FlagSet, *cmd.configPath)
if err != nil {
return err
}
cfg, err := config.Resolve(configPath, cmd.overrides())
if err != nil {
return err
postgresURI := strings.TrimSpace(os.Getenv("POSTGRES_URI"))
if postgresURI == "" {
return apperrors.ErrPostgresURIRequired
}

if _, err := os.Stat(cfg.DBPath); err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("db does not exist: %s; run start first", cfg.DBPath)
}
return fmt.Errorf("stat db path: %w", err)
}

latestProcessedBlockHeight, err := loadLatestProcessedBlockHeight(
cfg.DBPath,
cfg.BlockHeightDatabaseKey,
logger,
)
if err != nil && !errors.Is(err, leveldb.ErrNotFound) {
return fmt.Errorf("load latest processed block height: %w", err)
}

cliLogger.Info("proceed command received", "config", configPath, "home", cfg.ChainHome)
if errors.Is(err, leveldb.ErrNotFound) {
cliLogger.Info("resuming before first cursor", "db_path", cfg.DBPath)
} else {
cliLogger.Info("resuming from persisted block height", "block_height", latestProcessedBlockHeight, "db_path", cfg.DBPath)
}

bridgeParams, err := loadBridgeParamsFromHome(cfg.ChainHome)
if err != nil {
return fmt.Errorf("load bridge params from genesis: %w", err)
}
return runStart(ctx, cfg, bridgeParams, cancel, logger)
cliLogger.Info("run command received", "config", configPath, "home", cfg.ChainHome)
return runRuntime(ctx, runtimeInputs{
Config: cfg,
BridgeParams: params,
PostgresURI: postgresURI,
}, cancel, logger)

case "stop":
cmd := flag.NewFlagSet("stop", flag.ContinueOnError)
configPath := cmd.String("config", "", "path to configuration file")
legacySocketPath := cmd.String("socket-path", "", "legacy path to control socket")
controlSocketPath := cmd.String("control-socket-path", "", "path to control socket")
if err := cmd.Parse(args[1:]); err != nil {
return err
}
if flagWasSet(cmd, "socket-path") && flagWasSet(cmd, "control-socket-path") {
return fmt.Errorf("--socket-path and --control-socket-path cannot be used together")
if cmd.NArg() != 0 {
return fmt.Errorf("stop does not accept positional arguments: %q", cmd.Args())
}

resolvedSocketPath, err := resolveStopSocketPath(
firstVisitedSocketPath(cmd, *legacySocketPath, *controlSocketPath),
flagWasSet(cmd, "socket-path") || flagWasSet(cmd, "control-socket-path"),
*controlSocketPath,
flagWasSet(cmd, "control-socket-path"),
*configPath,
flagWasSet(cmd, "config"),
)
Expand Down Expand Up @@ -159,8 +122,7 @@ func (f *runtimeFlagSet) overrides() config.Overrides {

func usage() string {
return `usage:
archive-wrapper start [--config <path>] [--home <path>] [runtime overrides]
archive-wrapper proceed [--config <path>] [--home <path>] [runtime overrides]
archive-wrapper run [--config <path>] [--home <path>] [runtime overrides]
archive-wrapper stop [--config <path>] [--control-socket-path <path>]
`
}
Expand Down Expand Up @@ -197,10 +159,3 @@ func resolveConfigPath(fs *flag.FlagSet, flagValue string) (string, error) {
}
return "", apperrors.ErrConfigPathRequired
}

func firstVisitedSocketPath(fs *flag.FlagSet, legacy, canonical string) string {
if flagWasSet(fs, "socket-path") {
return legacy
}
return canonical
}
Loading