diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 000000000..d1316afa3 --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,65 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json +# TODO: delete this file after PR #1601 (pluggable database) is merged. +reviews: + # Files removed with SQLite, Typesense, the Elasticsearch query translator and the Aquarius + # routes. They no longer exist, so they need no review. + path_filters: + - '!src/@types/DDO/IDdoStateQuery.ts' + - '!src/@types/DDO/IMetadataQuery.ts' + - '!src/@types/DDO/SearchQuery.ts' + - '!src/components/database/ElasticSearchDdoStateQuery.ts' + - '!src/components/database/ElasticSearchMetadataQuery.ts' + - '!src/components/httpRoutes/aquarius.ts' + - '!schemas/**' + - '!scripts/inspect-job-metrics.mjs' + - '!typesense-compose.yml' + - '!src/@types/Typesense.ts' + - '!src/components/database/SQLLite*.ts' + - '!src/components/database/sqlite*.ts' + - '!src/components/database/Typesense*.ts' + - '!src/components/database/typesense*.ts' + - '!src/test/data/ddoSchema.ts' + - '!src/test/data/nonceSchema.ts' + - '!src/test/integration/nonce.test.ts' + - '!src/test/integration/typesense.test.ts' + - '!src/test/unit/sqliteClient.test.ts' + # More than 100 files: CodeRabbit skips the review. Docs, the lock file, agent files and + # tests that change only to fit the new database (new test files are still reviewed). + - '!docs/**' + - '!package-lock.json' + - '!AGENTS.md' + - '!CLAUDE.md' + - '!README.md' + - '!.github/copilot-instructions.md' + - '!src/test/.env.test' + - '!src/test/config.json' + - '!src/test/integration/compute.test.ts' + - '!src/test/integration/configDatabase.test.ts' + - '!src/test/integration/database.test.ts' + - '!src/test/integration/elasticsearch.test.ts' + - '!src/test/integration/imageCleanup.test.ts' + - '!src/test/integration/indexer.test.ts' + - '!src/test/integration/logs.test.ts' + - '!src/test/integration/maintenanceMode.test.ts' + - '!src/test/integration/persistentStorage.test.ts' + - '!src/test/unit/auth/token.test.ts' + - '!src/test/unit/compute.test.ts' + - '!src/test/unit/config.test.ts' + - '!src/test/unit/database/getJobsFilters.test.ts' + - '!src/test/unit/escrowFilters.test.ts' + - '!src/test/unit/fileInfoHandler.test.ts' + - '!src/test/unit/indexer/validation.test.ts' + - '!src/test/unit/maintenanceCoverage.test.ts' + - '!src/test/unit/maintenanceMode.test.ts' + - '!src/test/unit/nodeMetricsHandlers.test.ts' + - '!src/test/unit/oceanP2P.test.ts' + - '!src/test/unit/p2p/provideLimiter.test.ts' + - '!src/test/unit/p2p/republishStoredDdos.test.ts' + - '!src/test/unit/persistentStorageSharing.test.ts' + - '!src/test/unit/safeUrl.test.ts' + - '!src/test/unit/service/serviceDiskUsage.test.ts' + - '!src/test/unit/service/serviceJobsDatabase.test.ts' + - '!src/test/unit/service/serviceRestartRace.test.ts' + - '!src/test/utils/hooks.ts' + - '!src/test/utils/utils.ts' + - '!src/test/performance/util.js' diff --git a/.dockerignore b/.dockerignore index 2cc11f57e..4f295508d 100644 --- a/.dockerignore +++ b/.dockerignore @@ -15,4 +15,3 @@ src/test coverage docker-compose.yml elasticsearch-compose.yml -typesense-compose.yml diff --git a/.env.example b/.env.example index dda7eb784..17947224f 100644 --- a/.env.example +++ b/.env.example @@ -3,15 +3,18 @@ #check env.md file for examples and descriptions on each variable #----------------- REQUIRED -------------------------- -#This is the only required/mandatory variable -#Node will simply not run without this variable +#The node does not run without these two variables +#DB_TYPE: sqlite, postgresql or elasticsearch (the last two also need DB_URL, DB_USERNAME and DB_PASSWORD) #All the other variables can remain blank (because they have defaults) or simply commented export PRIVATE_KEY=REPLACE_ME +export DB_TYPE=sqlite #----------------------------------------------------- ## core export RPCS= export DB_URL= +export DB_USERNAME= +export DB_PASSWORD= export IPFS_GATEWAY=https://ipfs.io/ export ARWEAVE_GATEWAY=https://arweave.net/ export LOAD_INITIAL_DDOS= @@ -44,6 +47,24 @@ export HTTP_API_PORT= export VALIDATE_UNSIGNED_DDO= export JWT_SECRET= export NODE_OWNER_INFO= +## Scoped auth tokens (see docs/env.md). Left COMMENTED OUT with their defaults on purpose: a bare +## `export KEY=` reaches the schema as '' — which coerces to 0 (silently overriding a numeric +## default) or fails the enum (TOKEN_REVOCATION_FALLBACK) / min(1) (MAX_TOKEN_LIFETIME) check and +## breaks config load. Uncomment a line only to OVERRIDE the default shown. +# Hard cap on auth-token lifetime, in SECONDS. Default 86400 (24h). No never-expiring tokens. +# export MAX_TOKEN_LIFETIME=86400 +# Unreachable-issuer policy for foreign tokens: closed | cache | open. Default cache. +# export TOKEN_REVOCATION_FALLBACK=cache +# Soft-fail grace (seconds), consulted only in cache mode. 0 = fail-closed. Default 300. +# export TOKEN_SOFTFAIL_GRACE=300 +# Seconds a positive revocation verdict suppresses re-dialing. 0 = every request. Default 60. +# export TOKEN_REVALIDATE_INTERVAL=60 +# Honor FOREIGN (other-issuer) tokens at all (lever B). Default false. +# export ALLOW_CROSS_NODE_TOKENS=false +# JSON array of issuer peerIds to federate with; REQUIRED non-empty if cross-node is on. Default []. +# export TRUSTED_TOKEN_ISSUERS=["16Uiu2HAm..."] +# OJ-03 status challenge-signing rate limit (req/min/caller, separate bucket). 0 = disabled. Default 10. +# export STATUS_CHALLENGE_RATE_LIMIT=10 export UNSAFE_URLS= export ALLOWED_PRIVATE_URL_RANGES= diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index b294aa687..96e7e408b 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -39,11 +39,7 @@ export class FileInfoHandler extends CommandHandler { ### Database Abstraction Layer -Multiple database backends via `DatabaseFactory` pattern: - -- **Elasticsearch**: DDO metadata, indexer state, orders (async) -- **Typesense**: Search-optimized metadata queries -- **SQLite**: Nonce tracking, config storage, c2d Database (local) +Stores are built by `DatabaseFactory` from `DB_TYPE`: required: `sqlite` (no other setting), `postgresql` or `elasticsearch` (both need `DB_URL`, `DB_USERNAME`, `DB_PASSWORD`). SQLite and PostgreSQL share the stores in `src/components/database/sql/`; Elasticsearch uses the `Elastic*` files. The stores hold DDO metadata, indexer state, orders and the node state (nonces, config, auth tokens, buckets, node metrics, C2D jobs, service jobs, image records, service locks). Access via singleton `Database` class: `db.ddo`, `db.indexer`, `db.order`, `db.c2d`, `db.nonce`, etc. @@ -64,7 +60,7 @@ Central coordinator managing all components. Initialize with configuration and o ### Building & Testing - **Build**: `npm run build` → compiles TypeScript to `./dist/` -- **Tests**: `npm run test` runs unit + integration (requires Docker Compose for Typesense) +- **Tests**: `npm run test` runs unit + integration (integration tests need Barge; PostgreSQL or Elasticsearch only when `DB_TYPE` selects one) - **Dev**: Use `npm run build:tsc` in watch mode, or Node's `--experimental-specifier-resolution=node` for ESM imports ### Configuration @@ -72,7 +68,7 @@ Central coordinator managing all components. Initialize with configuration and o Environment-driven via `.env` or `CONFIG_PATH=/path/to/config.json`: - **PRIVATE_KEY** (required): Node identity for P2P + crypto operations -- **DB_URL**: Elasticsearch/Typesense connection +- **DB_TYPE** / **DB_URL**: database selection (required, no default) and server URL - **RPCS**: JSON mapping network IDs to RPC endpoints - **OPERATOR_SERVICE_URL**: C2D cluster URLs (array of strings) - See [docs/env.md](docs/env.md) for 40+ environment variables @@ -108,7 +104,7 @@ validateCommandParameters(command, ['required', 'fields']) // throws ValidatePar ### DDO/Asset Schema Validation -DDOs validated against SHACL schemas in [schemas/](schemas/) (v1, v3, v5, v7). Indexer enforces validation; check `ValidateDDOHandler` for signature verification. +DDOs validated against SHACL schemas from `@oceanprotocol/ddo-js` (`validateDDO` in `src/utils/asset.ts`). Indexer enforces validation; check `ValidateDDOHandler` for signature verification. ### Error Response Format diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d8b510467..135132bdb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -77,6 +77,49 @@ jobs: test_unit: runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - db: sqlite + - db: postgresql + db_url: 'postgresql://localhost:5432/ocean' + db_username: 'ocean' + db_password: 'changeme' + - db: elasticsearch + db_url: 'http://localhost:9200' + db_username: 'elastic' + db_password: 'changeme' + # a service with an empty image does not start: each leg starts its database only + services: + postgresql: + image: ${{ matrix.db == 'postgresql' && 'postgres:17' || '' }} + env: + POSTGRES_USER: ocean + POSTGRES_PASSWORD: changeme + POSTGRES_DB: ocean + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U ocean" + --health-interval 5s + --health-timeout 5s + --health-retries 20 + elasticsearch: + image: ${{ matrix.db == 'elasticsearch' && 'elasticsearch:8.5.1' || '' }} + env: + discovery.type: single-node + ELASTIC_PASSWORD: changeme + xpack.security.enabled: 'true' + xpack.security.http.ssl.enabled: 'false' + ES_JAVA_OPTS: -Xms512m -Xmx512m + ports: + - 9200:9200 + options: >- + --health-cmd "curl -sf -u elastic:changeme 'http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=5s'" + --health-interval 10s + --health-timeout 5s + --health-retries 20 steps: - uses: actions/checkout@v7 with: @@ -102,19 +145,51 @@ jobs: IPFS_GATEWAY: http://172.15.0.16:8080/ ARWEAVE_GATEWAY: https://arweave.net/ RPCS: '{ "1": {"rpc": "https://rpc.eth.gateway.fm", "chainId": 1, "network": "mainet", "chunkSize": 100}, "137": {"rpc": "https://polygon.meowrpc.com", "chainId": 137, "network": "polygon", "chunkSize": 100 }, "80001": {"rpc": "https://rpc-mumbai.maticvigil.com","chainId": 80001, "network": "polygon-mumbai", "chunkSize": 100 } }' - DB_URL: 'http://localhost:8108/?apiKey=xyz' - DB_TYPE: 'typesense' - DB_USERNAME: 'elastic' - DB_PASSWORD: 'changeme' + DB_TYPE: ${{ matrix.db }} + DB_URL: ${{ matrix.db_url }} + DB_USERNAME: ${{ matrix.db_username }} + DB_PASSWORD: ${{ matrix.db_password }} + # sniffing returns the container-internal address, unreachable from the runner + ELASTICSEARCH_SNIFF_ON_START: 'false' + ELASTICSEARCH_SNIFF_INTERVAL: 'false' + ELASTICSEARCH_SNIFF_ON_CONNECTION_FAULT: 'false' FEE_TOKENS: '{ "1": "0x967da4048cD07aB37855c090aAF366e4ce1b9F48", "137": "0x282d8efCe846A88B159800bd4130ad77443Fa1A1", "80001": "0xd8992Ed72C445c35Cb4A2be468568Ed1079357c8", "56": "0xDCe07662CA8EbC241316a15B611c89711414Dd1a" }' FEE_AMOUNT: '{ "amount": 1, "unit": "MB" }' - uses: actions/upload-artifact@v7 with: - name: coverage + name: coverage-unit-${{ matrix.db }} path: coverage/ test_integration: runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - db: sqlite + - db: postgresql + db_url: 'postgresql://localhost:5432/ocean' + db_username: 'ocean' + db_password: 'changeme' + # the Elasticsearch of Barge + - db: elasticsearch + db_url: 'http://localhost:9200' + db_username: 'elastic' + db_password: 'changeme' + services: + postgresql: + image: ${{ matrix.db == 'postgresql' && 'postgres:17' || '' }} + env: + POSTGRES_USER: ocean + POSTGRES_PASSWORD: changeme + POSTGRES_DB: ocean + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U ocean" + --health-interval 5s + --health-timeout 5s + --health-retries 20 steps: - uses: actions/checkout@v7 with: @@ -148,7 +223,7 @@ jobs: - name: Run Barge working-directory: ${{ github.workspace }}/barge run: | - bash -x start_ocean.sh --no-node --with-typesense 2>&1 > start_ocean.log & + bash -x start_ocean.sh --no-node 2>&1 > start_ocean.log & - run: npm ci - run: npm run build - run: docker image ls @@ -163,7 +238,7 @@ jobs: [ -f "$HOME/.ocean/ocean-contracts/artifacts/ready" ] && break done - name: docker logs - run: docker logs ocean-ocean-contracts-1 && docker logs ocean-typesense-1 + run: docker logs ocean-ocean-contracts-1 if: ${{ failure() }} - name: Build Docker registry auths id: docker_auths @@ -191,19 +266,21 @@ jobs: IPFS_GATEWAY: http://172.15.0.16:8080/ ARWEAVE_GATEWAY: https://arweave.net/ RPCS: '{ "8996": {"rpc": "http://127.0.0.1:8545", "chainId": 8996, "network": "development", "chunkSize": 100}}' - DB_URL: 'http://localhost:9200' - DB_TYPE: 'elasticsearch' + DB_TYPE: ${{ matrix.db }} + DB_URL: ${{ matrix.db_url }} + DB_USERNAME: ${{ matrix.db_username }} + DB_PASSWORD: ${{ matrix.db_password }} FEE_TOKENS: '{ "1": "0x967da4048cD07aB37855c090aAF366e4ce1b9F48", "137": "0x282d8efCe846A88B159800bd4130ad77443Fa1A1", "80001": "0xd8992Ed72C445c35Cb4A2be468568Ed1079357c8", "56": "0xDCe07662CA8EbC241316a15B611c89711414Dd1a" }' FEE_AMOUNT: '{ "amount": 1, "unit": "MB" }' ASSET_PURGATORY_URL: 'https://raw.githubusercontent.com/oceanprotocol/list-purgatory/main/list-assets.json' ACCOUNT_PURGATORY_URL: 'https://raw.githubusercontent.com/oceanprotocol/list-purgatory/main/list-accounts.json' DOCKER_REGISTRY_AUTHS: ${{ steps.docker_auths.outputs.value }} - name: docker logs - run: docker logs ocean-ocean-contracts-1 && docker logs ocean-typesense-1 + run: docker logs ocean-ocean-contracts-1 if: ${{ failure() }} - uses: actions/upload-artifact@v7 with: - name: coverage + name: coverage-integration-${{ matrix.db }} path: coverage/ test_system: @@ -250,7 +327,7 @@ jobs: - name: Run Barge working-directory: ${{ github.workspace }}/barge run: | - bash -x start_ocean.sh --no-node --with-typesense 2>&1 > start_ocean.log & + bash -x start_ocean.sh --no-node 2>&1 > start_ocean.log & - run: docker image ls - name: Delete default runner images run: | @@ -260,12 +337,15 @@ jobs: with: persist-credentials: false repository: 'oceanprotocol/ocean-cli' + # the CLI without Aquarius (/api/query, /api/ddo); back to rc_3.0.0 when it is merged + ref: 'feat/node-neutral-query' path: 'ocean-cli' - name: Checkout Ocean-js uses: actions/checkout@v7 with: persist-credentials: false repository: 'oceanprotocol/ocean.js' + ref: 'rc_11.0.0' path: 'ocean.js' - name: Build ocean-js working-directory: ${{ github.workspace }}/ocean.js @@ -301,7 +381,7 @@ jobs: done - name: docker logs - run: docker logs ocean-contracts-1 && docker logs ocean-typesense-1 + run: docker logs ocean-contracts-1 if: ${{ failure() }} - name: Build Docker registry auths @@ -324,6 +404,7 @@ jobs: run: | npm run start > ocean-node.log 2>&1 & env: + DB_TYPE: sqlite PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }} IPFS_GATEWAY: http://172.15.0.16:8080/ ARWEAVE_GATEWAY: https://arweave.net/ @@ -331,16 +412,12 @@ jobs: HTTP_API_PORT: 8001 RPCS: '{ "8996": {"rpc": "http://127.0.0.1:8545", "chainId": 8996, "network": "development", "chunkSize": 100} }' INDEXER_NETWORKS: '[8996]' - DB_URL: 'http://localhost:9200' FEE_TOKENS: '{ "1": "0x967da4048cD07aB37855c090aAF366e4ce1b9F48", "137": "0x282d8efCe846A88B159800bd4130ad77443Fa1A1", "80001": "0xd8992Ed72C445c35Cb4A2be468568Ed1079357c8", "56": "0xDCe07662CA8EbC241316a15B611c89711414Dd1a" }' FEE_AMOUNT: '{ "amount": 1, "unit": "MB" }' AUTHORIZED_DECRYPTERS: '["0xe2DD09d719Da89e5a3D0F2549c7E24566e947260"]' P2P_ENABLE_UPNP: 'false' P2P_ENABLE_AUTONAT: 'false' ALLOWED_ADMINS: '["0xe2DD09d719Da89e5a3D0F2549c7E24566e947260"]' - DB_TYPE: 'elasticsearch' - DB_USERNAME: 'elastic' - DB_PASSWORD: 'changeme' MAX_REQ_PER_MINUTE: 320 MAX_CONNECTIONS_PER_MINUTE: 320 DOCKER_COMPUTE_ENVIRONMENTS: '[{"socketPath":"/var/run/docker.sock","environments":[{"storageExpiry":604800,"maxJobDuration":3600,"minJobDuration":60,"resources":[{"id":"cpu","total":4,"max":4,"min":1,"type":"cpu"},{"id":"ram","total":10,"max":10,"min":1,"type":"ram"},{"id":"disk","total":10,"max":10,"min":0,"type":"disk"}],"fees":{"8996":[{"prices":[{"id":"cpu","price":1}]}]},"free":{"maxJobDuration":60,"maxJobs":3,"resources":[{"id":"cpu","max":1},{"id":"ram","max":1},{"id":"disk","max":1}]}}]}]' @@ -376,6 +453,5 @@ jobs: fi echo "=== Docker Logs ===" docker logs ocean-contracts-1 || echo "No ocean-contracts-1 container" - docker logs ocean-typesense-1 || echo "No ocean-typesense-1 container" echo "=== System Processes ===" ps aux | grep -E "(node|ocean)" || echo "No node/ocean processes found" diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index a9f9c3b0a..d72bb9818 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -13,6 +13,8 @@ on: - 'deps/node_v24' - 'feature/user_input_subsidy' - 'feature/subsidy_provider' + - 'rc_*' + - 'feat/elasticsearch-only-db-1551' env: DOCKERHUB_IMAGE: ${{ 'oceanprotocol/ocean-node' }} diff --git a/.gitignore b/.gitignore index 8da551d01..155fa0e2a 100644 --- a/.gitignore +++ b/.gitignore @@ -133,9 +133,6 @@ out .yarn/install-state.gz .pnp.* -# Typesense -typesense-data - # IDEA .idea diff --git a/AGENTS.md b/AGENTS.md index 11d37232a..11dfced4d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,16 +23,16 @@ libp2p P2P interface, both of which dispatch to the same set of command handlers test command. If the pinned version is already installed directly (no nvm available), verifying the active runtime against `.nvmrc` instead is sufficient — e.g. `test "v$(cat .nvmrc)" = "$(node -v)"`; do not abort the build just because `nvm` is - absent. The wrong Node version fails with errors like `Unexpected token 'with'`, - missing `GLIBC_2.38`, or — since the SQLite layer uses the built-in `node:sqlite` - module — `ERR_UNKNOWN_BUILTIN_MODULE: node:sqlite` on Node < 22.13. This is enforced by + absent. The wrong Node version fails with errors like `Unexpected token 'with'` or + missing `GLIBC_2.38`. This is enforced by `.cursor/rules/tests-nvm.mdc` and this `AGENTS.md`. - **There is no `postinstall` step.** `npm install` is plain. (Historically a `postinstall` ran `scripts/fix-libp2p-http-utils.js` to default a missing URL port to 443/80 in `@libp2p/http-utils`; upstream shipped that fix in `2.0.3`, so both the hook and the script were removed.) -- **Docker + docker-compose** are needed for the metadata database (Typesense or - Elasticsearch) and for C2D (Compute-to-Data) via the local Docker socket. +- **Docker + docker-compose** are needed for C2D (Compute-to-Data) via the local Docker + socket, and for PostgreSQL or Elasticsearch when `DB_TYPE` selects one of them. SQLite + needs no container. - TypeScript config: **TypeScript 6**, ESM (`module: esnext`, `target: ES2022`, `moduleResolution: node`), `experimentalDecorators` + `emitDecoratorMetadata` enabled, `rootDir: ./src`, `outDir: ./dist`. Most local imports use the `.js` extension @@ -45,12 +45,13 @@ libp2p P2P interface, both of which dispatch to the same set of command handlers ~123 errors), and `typescript-eslint` has to support TS 7 — its peer range is `>=4.8.4 <6.1.0`, so it pins us below 7 today. -### Mandatory config: `PRIVATE_KEY` + a config file +### Mandatory config: `PRIVATE_KEY`, `DB_TYPE` and a config file -`PRIVATE_KEY` (with the `0x` prefix, 66 chars) is the **only** required environment -variable — it seeds the node identity (libp2p peerId), the EVM signer, and encryption keys. +`PRIVATE_KEY` (with the `0x` prefix, 66 chars) and `DB_TYPE` are the required environment +variables — `PRIVATE_KEY` seeds the node identity (libp2p peerId), the EVM signer, and +encryption keys; `DB_TYPE` selects the database. A JSON config file must also exist (see §3); every other setting has a default or comes -from that file / env overrides. Generate a key with: +from that file / env overrides. `DB_TYPE=sqlite` needs no other setting. Generate a key with: ```bash node dist/helpers/scripts/generatePK.js # prints a key/address to stdout @@ -139,8 +140,9 @@ the compiled output. In tests, do **not** mutate `process.env` directly — use **Integration tests require a running local chain + services (Barge).** Clone `oceanprotocol/barge`, `git checkout feature/nodes`, then `./start_ocean.sh -with-c2d` -(see `docs/testing.md` and `docs/database.md` for the exact flags per DB type). The default -`config.json` points the DB at Typesense on `http://localhost:8108`. +(see `docs/testing.md` and `docs/database.md` for the exact flags). The tests run on the +database that `DB_TYPE` selects (the test hooks set `sqlite` when it is not set); suites that +use the Elasticsearch client directly are wrapped in `describeOnElasticsearch`. Other useful scripts: `npm run client` (2-node download flow demo), `npm run check-nonce` (nonce tracking; needs DB), and k6 perf tests `test:smoke` / `test:load` / `test:stress` / @@ -159,8 +161,9 @@ the files in `logs/` instead (see `docs/Logs.md`). ### Databases for local dev ```bash -docker-compose -f typesense-compose.yml up -d # Typesense (default in config.json) -docker-compose -f elasticsearch-compose.yml up -d # Elasticsearch alternative +# DB_TYPE=sqlite needs nothing. For the other two: +docker-compose -f postgresql-compose.yml up -d # DB_TYPE=postgresql +docker-compose -f elasticsearch-compose.yml up -d # DB_TYPE=elasticsearch ``` --- @@ -182,28 +185,15 @@ via `src/utils/config/index.ts` and `src/utils/index.ts`). Key facts: still resolve a home directory. If it is missing, startup fails with `Config file not found at path: ...`, even when every setting is given via env. The repo - ships a ready `config.json` (Typesense DB, chain `8996`/development, HTTP port `8001`, - single Docker C2D env). + ships a ready `config.json` (chain `8996`/development, HTTP port `8001`, single Docker C2D + env). - **`INTERFACES`** env var (JSON array like `["HTTP","P2P"]`) toggles `hasHttp` / `hasP2P`. - Omitted = both enabled. `DB_URL`/`DB_TYPE` presence drives `hasIndexer` — without a valid - metadata DB config the Indexer and the metadata-backed features (DDOs, orders, access - lists, escrow events, DB logs) are disabled, but the SQLite core still runs: nonce, auth - tokens, C2D jobs, node config (and best-effort node metrics). So nonce and auth services - keep working. This graceful-degrade path only applies when the config itself is - schema-valid: `dbConfig.dbType` is `z.string().nullable()` (`schemas.ts`), so a non-string - value (number/bool/object) fails zod validation in `buildMergedConfig()` and aborts the - **whole node** at startup — it does not disable just the metadata DB. Because the field is - `.nullable()` and **not** `.optional()`, `dbType` must be **present**: `null` is valid and - selects the no-metadata-DB mode above, but **omitting the key** from a supplied `dbConfig` - (e.g. a config file with `DB_URL` unset) is undefined and also fails zod and aborts the - whole node. Use `dbType: null`, not an absent key, for the no-DB mode. - - **Paid/free compute still needs the metadata DB to resolve a published dataset.** SQLite - preserves C2D **job storage**, but `FindDdoHandler.findAndFormatDdo` (`ddoHandler.ts`) - falls back to the P2P `FIND_DDO` lookup when no local DDO DB exists, and that network - response is a **summary** (`{id,lastUpdateTx,lastUpdateTime,provider}`), not the full - DDO. Parsing it for `services`/`indexedMetadata` throws and returns `null`, so - `initialize`/`startCompute` cannot resolve the asset. "C2D keeps working" means the job - runtime, not compute against a published DID without a metadata DB. + Omitted = both enabled. `DB_TYPE` is required and selects the database: `sqlite`, `postgresql` + or `elasticsearch`; with no `DB_TYPE` config validation fails and the node does not start + (no default, no guess from `DB_URL`). The last two require `DB_URL`, `DB_USERNAME` and + `DB_PASSWORD` (or `dbConfig` in the file); the URL is not checked, the driver connects to + it as given. An empty `DB_*` value counts as not set. Node state does not move between + databases. There is no DEGRADED / no-DB mode. - The full catalog of env vars is defined as `ENVIRONMENT_VARIABLES` in `src/utils/constants.ts` and documented in `docs/env.md` (long file — the authoritative reference). `.env.example` lists them grouped as core / p2p / compute. @@ -211,7 +201,7 @@ via `src/utils/config/index.ts` and `src/utils/index.ts`). Key facts: logging (config is read from many places; there's a known TODO to centralize access on the `OceanNode` class). -Selected env vars worth knowing: `RPCS` (per-chain RPC map, JSON), `DB_URL`/`DB_TYPE`, +Selected env vars worth knowing: `RPCS` (per-chain RPC map, JSON), `DB_URL`, `ALLOWED_ADMINS`(+`_LIST`) (gate admin commands), `AUTHORIZED_DECRYPTERS`/`_PUBLISHERS`/ `ALLOWED_VALIDATORS` (+ their access-list variants), `MAX_REQ_PER_MINUTE` (rate limit), `RATE_DENY_LIST`, `HTTP_API_PORT`, `JWT_SECRET`, `OPERATOR_SERVICE_URL` (external C2D @@ -329,13 +319,14 @@ Handler source is grouped under `src/components/core/`: the `Escrow` component; `serviceResourceMatching.ts` maps requested cpu/ram/disk/gpu against environment pools (dual-gate: per-env ceiling + engine-wide pool; GPUs tracked globally). See `docs/compute.md`. -- **database/** — `Database.init()` factory (`index.ts`, `DatabaseFactory.ts`). The metadata - DB backend is pluggable: **Typesense or Elasticsearch** (chosen by `DB_TYPE`) for DDOs, - indexer state, logs, orders, ddoState, access lists, escrow events — behind the - `Abstract*Database` interfaces in `BaseDatabase.ts`. **SQLite** is always used for the - nonce DB, config DB, C2D job DB, and auth-token DB (works even with no metadata DB - configured) — via Node's built-in `node:sqlite` module (no native addon), wrapped by - `SqliteClient` in `src/components/database/sqliteClient.ts`. See `docs/database.md`. +- **database/** — `Database.init()` gets the stores from `DatabaseFactory.createStores`, the + only place that selects the backend from `dbConfig.dbType`. The stores hold the index data + (DDOs, indexer state, logs, orders, ddoState, access lists, escrow events — behind the + `Abstract*Database` classes in `BaseDatabase.ts`) and the node state (nonces, config, auth + tokens, buckets, node metrics, C2D jobs, service jobs, image records, service locks). + Backends: **SQLite** and **PostgreSQL** share the stores in `database/sql/` + (`SqlClient`); **Elasticsearch** uses the `Elastic*` files (mappings in + `ElasticSchemas.ts`). Node metrics are kept per `INSTANCE_ID`. See `docs/database.md`. - **KeyManager/** — provider-abstraction over the node key (`docs/KeyManager.md`). Currently `RawPrivateKeyProvider` (from `PRIVATE_KEY`); derives the libp2p peerId/keys and the EVM address, and caches the ethers signer. Designed to add KMS providers (GCP/AWS) later. @@ -360,9 +351,8 @@ Handler source is grouped under `src/components/core/`: `constants.ts`, `crypt.ts` (hashing/signing), `blockchain.ts`, `logging/` (winston: console, per-module rotating files in `logs/` by default when `LOG_DB` is off, optional DB transport), `cronjobs/`, `validators.ts`, `credentials.ts`, `accessList.ts`, `asset.ts`, `attestation.ts`. -- Runtime data dirs: `databases/` (SQLite files + libp2p LevelDB store), `c2d_storage/` (C2D - job working data), `logs/`, `schemas/` (SHACL DDO validation schemas — shipped into the - Docker image). Service-on-demand templates are not shipped: the node reads +- Runtime data dirs: `databases/` (only `p2p-store`, the libp2p LevelDB store), + `c2d_storage/` (C2D job working data), `logs/`. Service-on-demand templates are not shipped: the node reads them from the folder given by `serviceTemplatesPath` / `SERVICE_TEMPLATES_PATH`, which the operator mounts in at run time. - `tsoa.json` configures OpenAPI spec generation from `src/components/httpRoutes/**`; the @@ -374,7 +364,7 @@ Handler source is grouped under `src/components/core/`: Multi-stage `Dockerfile` (builder + runner), both stages on `node:26.12.1-trixie-slim` pinned by digest. The runner ships only -`dist/`, `node_modules`, `schemas/`, `hfpatch/` (the `sitecustomize.py` the node copies +`dist/`, `node_modules`, `hfpatch/` (the `sitecustomize.py` the node copies into services — see `docs/services.md`) and `config.json` (`.dockerignore` excludes all of `docs/`) — no service templates. It exposes P2P ports `9000-9003,9005` and HTTP `8000`. `docker-entrypoint.sh` handles Docker socket group membership at runtime so C2D diff --git a/CLAUDE.md b/CLAUDE.md index 1ccc31187..cf73f5d97 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,22 +12,22 @@ of which dispatch to the same set of command handlers. ## 1. Environment & tooling prerequisites -- **Node.js 26 is required** (`.nvmrc` pins 26.12.1`— the current Node 26 LTS — -matching the Dockerfile and CI;`package.json` `engines`requires`>=24`, so Node 22 is -no longer a supported runtime). The Dockerfile additionally pins each base -image by digest, so bumping the version means updating the `sha256:`alongside the tag — -resolve it with`docker buildx imagetools inspect node:-trixie`, not from the tag -alone. Always run `nvm use`(or`source ~/.nvm/nvm.sh && nvm use`) before -any `npm`, build, or test command. The wrong Node version fails with errors like -`Unexpected token 'with'`, missing `GLIBC_2.38`, or — since the SQLite layer uses the -built-in `node:sqlite`module —`ERR_UNKNOWN_BUILTIN_MODULE: node:sqlite`on Node < 22.13. -This is enforced by`.cursor/rules/tests-nvm.mdc`and the in-repo`CLAUDE.md`. +- **Node.js 26 is required** (`.nvmrc` pins `26.12.1`, the current Node 26 LTS, matching + the Dockerfile and CI; `package.json` `engines` requires `>=24`, so Node 22 is no longer a + supported runtime). The Dockerfile also pins each base image by digest, so a version bump + updates the `sha256:` with the tag: resolve it with + `docker buildx imagetools inspect node:-trixie`, not from the tag alone. Always + run `nvm use` (or `source ~/.nvm/nvm.sh && nvm use`) before any `npm`, build or test + command. The wrong Node version fails with errors like `Unexpected token 'with'` or a + missing `GLIBC_2.38`. This is enforced by `.cursor/rules/tests-nvm.mdc` and the in-repo + `CLAUDE.md`. - **There is no `postinstall` step.** `npm install` is plain. (Historically a `postinstall` ran `scripts/fix-libp2p-http-utils.js` to default a missing URL port to 443/80 in `@libp2p/http-utils`; upstream shipped that fix in `2.0.3`, so both the hook and the script were removed.) -- **Docker + docker-compose** are needed for the metadata database (Typesense or - Elasticsearch) and for C2D (Compute-to-Data) via the local Docker socket. +- **Docker + docker-compose** are needed for C2D (Compute-to-Data) via the local Docker + socket, and for PostgreSQL or Elasticsearch when `DB_TYPE` selects one of them. SQLite + needs no container. - TypeScript config: **TypeScript 6**, ESM (`module: esnext`, `target: ES2022`, `moduleResolution: node`), `experimentalDecorators` + `emitDecoratorMetadata` enabled, `rootDir: ./src`, `outDir: ./dist`. Most local imports use the `.js` extension @@ -40,11 +40,12 @@ This is enforced by`.cursor/rules/tests-nvm.mdc`and the in-repo`CLAUDE.md`. ~123 errors), and `typescript-eslint` has to support TS 7 — its peer range is `>=4.8.4 <6.1.0`, so it pins us below 7 today. -### Only-mandatory config: `PRIVATE_KEY` +### Mandatory config: `PRIVATE_KEY` and `DB_TYPE` -`PRIVATE_KEY` (with the `0x` prefix) is the **only** required environment variable — it -seeds the node identity (libp2p peerId), the EVM signer, and encryption keys. Everything -else has defaults. Generate one with: +`PRIVATE_KEY` (with the `0x` prefix) and `DB_TYPE` are the required environment variables. +`PRIVATE_KEY` seeds the node identity (libp2p peerId), the EVM signer, and encryption keys; +`DB_TYPE` selects the database (`sqlite` needs no other setting). Everything else has +defaults. Generate one with: ```bash node dist/helpers/scripts/generatePK.js # prints a key/address to stdout @@ -133,8 +134,12 @@ the compiled output. In tests, do **not** mutate `process.env` directly — use **Integration tests require a running local chain + services (Barge).** Clone `oceanprotocol/barge`, `git checkout feature/nodes`, then `./start_ocean.sh -with-c2d` -(see `docs/testing.md` and `docs/database.md` for the exact flags per DB type). The default -`config.json` points the DB at Typesense on `http://localhost:8108`. +(see `docs/testing.md` and `docs/database.md` for the exact flags). The tests run on the +database that `DB_TYPE` selects (the test hooks set `sqlite` when it is not set; note that +`src/test/.env.test` can set `DB_URL`); suites that use the +Elasticsearch client directly are wrapped in `describeOnElasticsearch` and run only with +`DB_TYPE=elasticsearch`. The SQL store suites (`src/test/unit/database/`) also run on +PostgreSQL with `DB_TYPE=postgresql`. Other useful scripts: `npm run client` (2-node download flow demo), `npm run check-nonce` (nonce tracking; needs DB), `npm run logs` (calls the signed `/logs` API; currently broken, see `docs/Logs.md`), and k6 perf tests @@ -144,8 +149,9 @@ a running node). ### Databases for local dev ```bash -docker-compose -f typesense-compose.yml up -d # Typesense (default in config.json) -docker-compose -f elasticsearch-compose.yml up -d # Elasticsearch alternative +# DB_TYPE=sqlite needs nothing. For the other two: +docker-compose -f postgresql-compose.yml up -d # DB_TYPE=postgresql +docker-compose -f elasticsearch-compose.yml up -d # DB_TYPE=elasticsearch ``` --- @@ -157,10 +163,14 @@ via `src/utils/config/index.ts` and `src/utils/index.ts`). Key facts: - **Two config sources.** Either environment variables, or a JSON file. `getConfigFilePath()` resolves the file from `CONFIG_PATH` env var, else `./config.json` in cwd. The repo ships a - ready `config.json` (Typesense DB, chain `8996`/development, single Docker C2D env). + ready `config.json` (chain `8996`/development, single Docker C2D env). - **`INTERFACES`** env var (JSON array like `["HTTP","P2P"]`) toggles `hasHttp` / `hasP2P`. - Omitted = both enabled. `DB_URL`/`DB_TYPE` presence drives `hasIndexer` — without a valid - DB config the Indexer is disabled and only the SQLite nonce DB is available. + Omitted = both enabled. `DB_TYPE` is required and selects the database: `sqlite`, `postgresql` + or `elasticsearch`; with no `DB_TYPE` config validation fails and the node does not start + (no default, no guess from `DB_URL`). The last two require `DB_URL`, `DB_USERNAME` and + `DB_PASSWORD` (or `dbConfig` in the file); the URL is not checked, the driver connects to + it as given. An empty `DB_*` value counts as not set. Node state does not move between + databases. There is no DEGRADED / no-DB mode. - The full catalog of env vars is defined as `ENVIRONMENT_VARIABLES` in `src/utils/constants.ts` and documented in `docs/env.md` (long file — the authoritative reference). `.env.example` lists them grouped as core / p2p / compute. @@ -168,7 +178,7 @@ via `src/utils/config/index.ts` and `src/utils/index.ts`). Key facts: logging (config is read from many places; there's a known TODO to centralize access on the `OceanNode` class). -Selected env vars worth knowing: `RPCS` (per-chain RPC map, JSON), `DB_URL`/`DB_TYPE`, +Selected env vars worth knowing: `RPCS` (per-chain RPC map, JSON), `DB_URL`, `ALLOWED_ADMINS`(+`_LIST`) (gate admin commands), `AUTHORIZED_DECRYPTERS`/`_PUBLISHERS`/ `ALLOWED_VALIDATORS` (+ their access-list variants), `MAX_REQ_PER_MINUTE` (rate limit), `RATE_DENY_LIST`, `HTTP_API_PORT`, `JWT_SECRET`, `OPERATOR_SERVICE_URL` (external C2D @@ -220,7 +230,7 @@ Multiple front doors, one shared `handler.handle(task)` primitive: - **P2P inbound** (`src/components/P2P/handleProtocolCommands.ts`): a libp2p protocol handler reads a length-prefixed command frame off the stream, applies connection/request rate limits, and dispatches through the same `CoreHandlersRegistry`. -- **RESTful routes** (`src/components/httpRoutes/*`, e.g. `provider.ts`, `aquarius.ts`, +- **RESTful routes** (`src/components/httpRoutes/*`, e.g. `provider.ts`, `ddo.ts`, `compute.ts`, `auth.ts`, `escrow.ts`, `accessList.ts`, `persistentStorage.ts`) are ergonomic wrappers that build the equivalent `Command` and invoke the corresponding handler. Route mounting lives in `src/components/httpRoutes/index.ts` @@ -289,13 +299,25 @@ Handler source is grouped under `src/components/core/`: the `Escrow` component; `serviceResourceMatching.ts` maps requested cpu/ram/disk/gpu against environment pools (dual-gate: per-env ceiling + engine-wide pool; GPUs tracked globally). See `docs/compute.md`. -- **database/** — `Database.init()` factory (`index.ts`, `DatabaseFactory.ts`). The metadata - DB backend is pluggable: **Typesense or Elasticsearch** (chosen by `DB_TYPE`) for DDOs, - indexer state, logs, orders, ddoState, access lists, escrow events — behind the - `Abstract*Database` interfaces in `BaseDatabase.ts`. **SQLite** is always used for the - nonce DB, config DB, C2D job DB, and auth-token DB (works even with no metadata DB - configured) — via Node's built-in `node:sqlite` module (no native addon), wrapped by - `SqliteClient` in `src/components/database/sqliteClient.ts`. See `docs/database.md`. +- **database/** — `Database.init()` gets the 13 stores (`DatabaseStores`) from + `DatabaseFactory.createStores`, the only place that selects the backend from + `dbConfig.dbType`. No file outside this folder imports a backend. The stores hold the + index data (DDOs, indexer state, logs, orders, ddoState, access lists, escrow events — + behind the `Abstract*Database` classes in `BaseDatabase.ts`) and the node state (nonces, + config, auth tokens, buckets, node metrics, C2D jobs, service jobs, image records, service + locks — behind the provider interfaces). Backends: + - **SQLite** and **PostgreSQL**: one set of stores in `database/sql/`, written + against the `SqlClient` interface (`SqliteClient` on `node:sqlite`, `PostgresClient` on + `pg`). The rules for SQL that runs on both are at the top of `sql/SqlClient.ts`. + `SqlDocuments` keeps JSON documents with a field table and runs typed conditions + (`Condition` in `BaseDatabase.ts`) as fixed SQL. `SqliteStores.ts` keeps the file + names of the older releases and upgrades their tables. + - **Elasticsearch**: the `Elastic*` files (index mappings in `ElasticSchemas.ts`). + - The DDO search (`query` command, `POST /api/query`) is typed: + `assetQuery.ts` checks the request (zod) and turns the filters into conditions; SQL + and Elasticsearch (`esConditions.ts`) each run them with fixed queries. There is no + Elasticsearch query syntax on any database. + - Node metrics are kept per `INSTANCE_ID`. See `docs/database.md`. - **KeyManager/** — provider-abstraction over the node key (`docs/KeyManager.md`). Currently `RawPrivateKeyProvider` (from `PRIVATE_KEY`); derives the libp2p peerId/keys and the EVM address, and caches the ethers signer. Designed to add KMS providers (GCP/AWS) later. @@ -316,9 +338,9 @@ Handler source is grouped under `src/components/core/`: `constants.ts`, `crypt.ts` (hashing/signing), `blockchain.ts`, `logging/` (winston: console, per-module rotating files in `logs/` by default when `LOG_DB` is off, optional DB transport), `cronjobs/`, `validators.ts`, `credentials.ts`, `accessList.ts`, `asset.ts`, `attestation.ts`. -- Runtime data dirs: `databases/` (SQLite files + libp2p LevelDB store), `c2d_storage/` (C2D - job working data), `logs/`, `schemas/` (SHACL DDO validation schemas — shipped into the - Docker image). Service-on-demand templates are not shipped: the node reads +- Runtime data dirs: `databases/` (`p2p-store`, the libp2p LevelDB store, and the SQLite + files of the node with the default database), + `c2d_storage/` (C2D job working data), `logs/`. Service-on-demand templates are not shipped: the node reads them from the folder given by `serviceTemplatesPath` / `SERVICE_TEMPLATES_PATH`, which the operator mounts in at run time. - `tsoa.json` configures OpenAPI spec generation from `src/components/httpRoutes/**`; the @@ -329,7 +351,7 @@ Handler source is grouped under `src/components/core/`: ## 5. Docker & deployment Multi-stage `Dockerfile` (builder + slim runner) on `node:24`. The runner ships only -`dist/`, `node_modules`, `schemas/`, `hfpatch/` (the `sitecustomize.py` the node copies +`dist/`, `node_modules`, `hfpatch/` (the `sitecustomize.py` the node copies into services — see `docs/services.md`) and `config.json` (`.dockerignore` excludes all of `docs/`) — no service templates. It exposes P2P ports `9000-9003,9005` and HTTP `8000`. `docker-entrypoint.sh` handles Docker socket group membership at runtime so C2D diff --git a/Dockerfile b/Dockerfile index 257539e36..b0e7a7444 100644 --- a/Dockerfile +++ b/Dockerfile @@ -40,17 +40,17 @@ WORKDIR /usr/src/app COPY --chown=node:node --from=builder /usr/src/app/dist ./dist COPY --chown=node:node --from=builder /usr/src/app/node_modules ./node_modules -COPY --chown=node:node --from=builder /usr/src/app/schemas ./schemas # sitecustomize.py the node copies into service containers (src/components/c2d/serviceHfMirror.ts) COPY --chown=node:node --from=builder /usr/src/app/hfpatch ./hfpatch COPY --chown=node:node --from=builder /usr/src/app/package.json ./ COPY --chown=node:node --from=builder /usr/src/app/config.json ./ -# `databases` holds everything the node must not lose across a restart: the SQLite files -# (nonce, config, C2D jobs, auth tokens) and `databases/p2p-store`, the LevelDatastore that -# backs libp2p. kad-dht's reprovider refreshes this node's provider records from that -# datastore, so if it starts empty the node stops answering for content it still holds, and the -# records expire out of the network without anything noticing. The directory is created and +# `databases` holds what the node must not lose across a restart on this host: +# `databases/p2p-store`, the LevelDatastore that backs libp2p, and the SQLite files of the +# node when it uses the default database. kad-dht's reprovider refreshes this node's +# provider records from that datastore, so if it starts empty the node stops answering for +# content it still holds, and the records expire out of the network without anything +# noticing. The directory is created and # handed to the unprivileged `node` user here, and VOLUME declares the mount point so a named # volume or bind mount can be attached; docker-entrypoint.sh re-applies ownership at runtime # for the bind-mount case, where the host directory arrives owned by whoever created it. diff --git a/README.md b/README.md index 750a0c3b3..c4eca8564 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ directory (indexed at the bottom) for the detailed references. Ocean Node has **two front doors and one dispatcher**: -- **HTTP** — `POST /directCommand` (plus ergonomic REST routes under `provider`, `aquarius`, +- **HTTP** — `POST /directCommand` (plus ergonomic REST routes under `provider`, `ddo`, `query`, `compute`, `auth`, `escrow`, …) normalizes each request into a `Command`. - **P2P** — a libp2p protocol handler reads length-prefixed command frames off the stream. @@ -51,10 +51,10 @@ See [Architecture](docs/Arhitecture.md) for the layered model and Mermaid diagra - **OS**: latest LTS Ubuntu or latest macOS recommended; other OSes (including Windows) should also work. -A **persistent `databases/` volume is REQUIRED**, not optional. It holds the SQLite files -(nonce, config, C2D jobs, auth tokens) and `databases/p2p-store`, the libp2p datastore that -backs this node's DHT provider records. Starting it empty silently drops content the node -still serves. The Dockerfile declares `VOLUME ["/usr/src/app/databases"]` for this reason — +A **persistent `databases/` volume is REQUIRED**, not optional. It holds +`databases/p2p-store`, the libp2p datastore that backs this node's DHT provider records, and, +with `DB_TYPE=sqlite`, all the data of the node. Starting it empty silently drops +content the node still serves. The Dockerfile declares `VOLUME ["/usr/src/app/databases"]` for this reason — see "Persistent node data" in [Docker deployment](docs/dockerDeployment.md). ## Quick start (operators) @@ -90,24 +90,21 @@ PM2 is a process manager that makes it easy to run and monitor Node.js apps. ```bash npm install -g pm2 -# 1. Start a metadata database (Typesense is the default in config.json) -docker-compose -f typesense-compose.yml up -d - -# 2. Install deps and build — `npm run start` runs dist/index.js, so a prior build is required +# 1. Install deps and build — `npm run start` runs dist/index.js, so a prior build is required npm install npm run build -# 3. Set up env vars. The node does NOT auto-load .env at runtime (dotenv is only used in +# 2. Set up env vars. The node does NOT auto-load .env at runtime (dotenv is only used in # tests), so the vars must be in the shell environment before `pm2 start`. # Interactive helper, then load the generated .env into this shell: npm run setupEnv source .env -# …or set them manually (PRIVATE_KEY is the only mandatory one; keep the 0x prefix): +# …or set them manually (only PRIVATE_KEY is mandatory; keep the 0x prefix): # export PRIVATE_KEY="0x<64-hex-characters>" # or generate one: node dist/helpers/scripts/generatePK.js # if you use a JSON config file instead, point CONFIG_PATH at its absolute path: # export CONFIG_PATH="/absolute/path/to/config.json" -# 4. Start under PM2 +# 3. Start under PM2 pm2 start npm --name "ocean-node" -- run start ``` @@ -121,18 +118,12 @@ own stdout copy in `~/.pm2/logs` with no size cap unless `pm2-logrotate` is inst - **Node.js**: use the version pinned in [`.nvmrc`](.nvmrc) (run `nvm use`). The effective supported runtime is **Node 24+** (`package.json` `engines`), and the `.nvmrc`/Dockerfile - pin the exact tested version (currently 26.12.1). Note that on anything below **22.13** the - node fails to even start, because the SQLite layer uses the built-in `node:sqlite` module - (`ERR_UNKNOWN_BUILTIN_MODULE: node:sqlite`) — but 22.x is not a supported runtime, use 24+. -- **Docker + Docker Compose** (for the metadata database and C2D). + pin the exact tested version (currently 26.12.1). +- **Docker + Docker Compose** (for C2D, and for PostgreSQL or Elasticsearch if you select one + of them; SQLite needs no container). ```bash -# 1. Start a metadata database (Typesense is the default in config.json) -docker-compose -f typesense-compose.yml up -d -# …or Elasticsearch: -# docker-compose -f elasticsearch-compose.yml up -d - -# 2. Install and build +# 1. Install and build nvm use npm install npm run build @@ -151,16 +142,17 @@ prior `npm run build` is required. ## Configuration -- **`PRIVATE_KEY`** (exactly 66 characters: `0x` + 64 hex) is the **only mandatory** - variable. It seeds the node identity (libp2p peerId), the EVM signer and the encryption - keys; everything else has defaults. Generate one with - `node dist/helpers/scripts/generatePK.js`. +- **`PRIVATE_KEY`** (exactly 66 characters: `0x` + 64 hex) and **`DB_TYPE`** are the + **mandatory** variables. `PRIVATE_KEY` seeds the node identity (libp2p peerId), the EVM + signer and the encryption keys; `DB_TYPE` selects the database (`sqlite` needs no other + setting). Everything else has defaults. + Generate a key with `node dist/helpers/scripts/generatePK.js`. - **Config sources**: a JSON config file plus environment-variable overrides. The file is resolved from `CONFIG_PATH`, else `./config.json` in the working directory, and must exist — - the repo ships a ready-to-run [`config.json`](config.json) (Typesense DB, chain + the repo ships a ready-to-run [`config.json`](config.json) (chain `8996`/development, a single Docker C2D environment). Environment variables are merged on top of the file and take precedence. - - ⚠️ **Blank env vars override the file.** Only *unset* variables fall through to + - ⚠️ **Blank env vars override the file.** Only _unset_ variables fall through to `config.json`; an **empty** value (e.g. `export HTTP_API_PORT=`) is treated as set and overrides the file's value. `npm run setupEnv` creates `.env` by copying [`.env.example`](.env.example), which has many blank `export VAR=` lines, so after @@ -170,8 +162,8 @@ prior `npm run build` is required. omitted means both. - [`docs/env.md`](docs/env.md) is the authoritative reference. Key groups worth knowing: - `RPCS` — per-chain RPC endpoint map (JSON). - - `DB_URL` / `DB_TYPE` — metadata DB connection and backend; presence drives whether the - indexer runs. + - `DB_TYPE` — the database, required: `sqlite`, `postgresql` or `elasticsearch`. + `DB_URL` / `DB_USERNAME` / `DB_PASSWORD` — the connection, for the last two. - `ALLOWED_ADMINS`, `AUTHORIZED_DECRYPTERS`, `AUTHORIZED_PUBLISHERS`, `ALLOWED_VALIDATORS` (and their access-list variants) — admin / decrypter / validator allow-lists. - `MAX_REQ_PER_MINUTE`, `RATE_DENY_LIST` — rate limiting. @@ -182,29 +174,71 @@ prior `npm run build` is required. ## Databases -The metadata backend is pluggable: **Typesense** or **Elasticsearch**, chosen via `DB_TYPE`. -Both ship with a compose file ([`typesense-compose.yml`](typesense-compose.yml), -[`elasticsearch-compose.yml`](elasticsearch-compose.yml)) and hold DDOs, indexer state, logs, -orders, access lists and escrow events. - -> **Default differs by config source.** The shipped [`config.json`](config.json) defaults to -> **Typesense**, but when you supply the DB through **environment variables** (`DB_URL`, e.g. -> via `npm run setupEnv`) the builder sets `dbConfig.dbType` to `DB_TYPE || 'elasticsearch'`. -> So if you enable the DB via env vars and want Typesense, you must set `DB_TYPE=typesense` -> explicitly — otherwise the node tries to talk to your Typesense endpoint as Elasticsearch. - -**SQLite is always on**, independent of the metadata DB: it backs the nonce, config, C2D-job -and auth-token stores via Node's built-in `node:sqlite` module (no native addon). A valid -`dbConfig` in `config.json` is **retained** when `DB_URL` is unset or empty (env `DB_TYPE` -alone does not build or override it), so the file's DB config still drives the indexer; it is -disabled outright only when **neither** the file nor the environment provides a valid DB -config (the SQLite stores keep working regardless). A valid `dbConfig` is **necessary but not -sufficient**, though: if the metadata DB is unreachable when the node starts (connection -fails after the init retries), the node logs *DEGRADED mode*, disables the indexer, and keeps -only the SQLite-backed C2D / nonce / auth stores — so also make sure the configured -Typesense/Elasticsearch endpoint is actually up and reachable. A config value of the wrong type instead fails -`OceanNodeConfigSchema` (zod) validation and stops startup before any DB is initialized. See -[Database guide](docs/database.md). +The node keeps all its data in one database, selected with `DB_TYPE`: + +- **`sqlite`**: no database container and no other setting. The files are in the + `databases/` folder. One folder is for one node instance. +- **`postgresql`** or **`elasticsearch`**: for several node instances on one database. Set + `DB_URL`, `DB_USERNAME` and `DB_PASSWORD` (or `dbConfig` in `config.json`); without them the + configuration fails validation and the node does not start. The repo has a compose file for + each: [`postgresql-compose.yml`](postgresql-compose.yml) and + [`elasticsearch-compose.yml`](elasticsearch-compose.yml). + +With no `DB_TYPE` the node does not start: it does not get the type from `DB_URL`. See +"Upgrade" in the [Database guide](docs/database.md). + +### Move the node state to PostgreSQL or Elasticsearch + +Version 5.1.0 and older keep the node state (nonces, compute jobs, auth tokens, buckets, +metrics history) in the SQLite files of `databases/`, and the DDO index in Typesense or +Elasticsearch. A node of this release with `DB_TYPE=sqlite` keeps all of it in these files. +To move the state of such a node, run this in the folder of its `docker-compose.yml`: + +```bash +curl -fsSL https://raw.githubusercontent.com/oceanprotocol/ocean-node/main/scripts/ocean-node-migrate-db.sh | bash +# TODO: remove once merged. Until then, the script is only on this branch: +curl -fsSL https://raw.githubusercontent.com/oceanprotocol/ocean-node/feat/db-migration/scripts/ocean-node-migrate-db.sh | bash +``` + +The script: + +1. Asks for the database: `p` (PostgreSQL), `e` (Elasticsearch) or `s` (SQLite). The new + database takes the place of the old one (Typesense, or Elasticsearch when you select + another one; on a SQLite node it is added) in `docker-compose.yml` (or `.yaml`), and in the + `dbConfig` of `config.json` when the compose file mounts it. With `s` the old database + goes: the state is in SQLite already, so the node uses the same files and upgrades their + tables when it starts. The old files stay in `.old`; the volume of the old database stays. + When the volume of the new database exists already, it asks to remove it. When you keep + Elasticsearch, the script protects it: an Elasticsearch with `xpack.security.enabled: false` + gets security and a new password for the user `elastic`, and restarts when the node stops. + Without that line Elasticsearch 8 has security, so the compose file needs + `ELASTIC_PASSWORD`. The node gets the same user and password. The changes that it shows + hide the passwords and the private key: they are in the files. When the compose file sets + PostgreSQL already (after a quickstart run), the script does not ask and does not change + the files: it only copies. Docker compose reads only `docker-compose.yml` (`-f`). The + script stops when `COMPOSE_FILE` or `COMPOSE_ENV_FILES` is set, or the folder has a + `compose.yaml` or an override file, because docker compose reads them without `-f`. +2. Shows what it will copy and asks you to confirm. The node still runs. +3. Stops the node, keeps a copy of the state files in the folder `backup-