diff --git a/.env.example b/.env.example index bea5746..d80d2eb 100644 --- a/.env.example +++ b/.env.example @@ -1,12 +1,13 @@ # BitReport error reporting — Docker Compose (copy to `.env` in this directory). # `docker compose` reads `.env` automatically for variable substitution in docker-compose.yml. -# --- PostgreSQL (service: postgres) --- -ER_POSTGRES_USER=postgres -ER_POSTGRES_PASSWORD=postgres -ER_POSTGRES_DB=error_reporting -# Host port mapped to Postgres (container always listens on 5432) -ER_PUBLISH_PG_PORT=5434 +# --- MariaDB (service: mariadb) --- +ER_MYSQL_ROOT_PASSWORD=devrootchange +ER_MYSQL_USER=er_app +ER_MYSQL_PASSWORD=er_app_secret +ER_MYSQL_DATABASE=error_reporting +# Host port mapped to MariaDB (container listens on 3306) +ER_PUBLISH_MYSQL_PORT=3306 # --- Ingest API (service: ingest-api) --- ER_PUBLISH_INGEST_PORT=3041 @@ -22,3 +23,6 @@ ER_COLLECTOR_PROJECT_ALPHA_TOKEN=er_tst_a_secret_one # HTTP_FETCH_TIMEOUT_MS=15000 # MAX_BACKOFF_EXPONENT=8 # COLLECTOR_DEFAULT_INGEST_TOKEN= + +# Node apps (ingest-api, collector-worker, api/) expect: +# DATABASE_URL=mysql://USER:PASSWORD@HOST:PORT/DATABASE diff --git a/README.md b/README.md index 2373451..3547186 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # errors.bitreport.pt -BitReport **central error reporting** platform: ingest API, collector worker, admin UI (incidents), PostgreSQL migrations, and optional **admin portal** (auth/RBAC) from BIT-183. +BitReport **central error reporting** platform: ingest API, collector worker, admin UI (incidents), MariaDB migrations, and optional **admin portal** (auth/RBAC) from BIT-183. **Remote:** `https://git.bitreport.pt/BitReport.pt/errors.bitreport.pt.git` **Tracking:** Paperclip **BIT-247** (migration from `OTT/error-reporting/`). @@ -17,7 +17,7 @@ BitReport **central error reporting** platform: ingest API, collector worker, ad | `docker-compose.yml`, `.env.example` | Local / Proxmox Docker stack | | `api/` | Fastify admin API — sessions, RBAC (BIT-183) | | `web/` | Next.js admin login/UI for `api/` | -| `db/migrations/` | Admin-user schema (node-pg-migrate); distinct from `database/error_reporting/` | +| `db/migrations/` | Admin-user schema (SQL); applied with error_reporting migrations via `scripts/docker-migrate.sh` | | `docs/` | Permission matrix, deployment runbooks | ## Docker Compose (ingest stack) @@ -41,3 +41,10 @@ curl -sf "http://127.0.0.1:${ER_PUBLISH_INGEST_PORT:-3041}/health" cd ingest-api && npm ci && npm test cd ../api && npm ci && npm test ``` + +Integration tests for ingest (`ingest-api/src/integration.twoProjects.test.ts`) require a migrated MariaDB and: + +```bash +export ERROR_REPORTING_TEST_DATABASE_URL='mysql://USER:PASS@127.0.0.1:3306/error_reporting' +cd ingest-api && npm test +``` diff --git a/api/package-lock.json b/api/package-lock.json index 29a17ef..7b96f84 100644 --- a/api/package-lock.json +++ b/api/package-lock.json @@ -14,14 +14,15 @@ "@fastify/rate-limit": "^9.1.0", "@fastify/swagger": "^8.14.0", "@fastify/swagger-ui": "^3.0.0", + "bcrypt": "^5.1.1", "fastify": "^4.27.0", - "pg": "^8.11.5", + "mysql2": "^3.11.5", "pino": "^9.1.0", "zod": "^3.23.8" }, "devDependencies": { + "@types/bcrypt": "^5.0.2", "@types/node": "^20.14.0", - "@types/pg": "^8.11.6", "tsx": "^4.15.6", "typescript": "^5.4.5", "vitest": "^1.6.0" @@ -656,6 +657,26 @@ "node": ">=8" } }, + "node_modules/@mapbox/node-pre-gyp": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", + "integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==", + "license": "BSD-3-Clause", + "dependencies": { + "detect-libc": "^2.0.0", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.7", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, "node_modules/@pinojs/redact": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", @@ -1029,6 +1050,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/bcrypt": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@types/bcrypt/-/bcrypt-5.0.2.tgz", + "integrity": "sha512-6atioO8Y75fNcbmj0G7UjI9lXN2pQ/IGJ2FWT4a/btd0Lk9lQalHLKhkgKVZ3r+spnmWUKfbMi1GEe9wyHQfNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/estree": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", @@ -1040,24 +1071,11 @@ "version": "20.19.37", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz", "integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==", - "dev": true, "license": "MIT", "dependencies": { "undici-types": "~6.21.0" } }, - "node_modules/@types/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "pg-protocol": "*", - "pg-types": "^2.2.0" - } - }, "node_modules/@vitest/expect": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.6.1.tgz", @@ -1132,6 +1150,12 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "license": "ISC" + }, "node_modules/abstract-logging": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz", @@ -1164,6 +1188,18 @@ "node": ">=0.4.0" } }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/ajv": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", @@ -1238,6 +1274,26 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/aproba": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.1.0.tgz", + "integrity": "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew==", + "license": "ISC" + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", + "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/asn1.js": { "version": "5.4.1", "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", @@ -1279,12 +1335,35 @@ "fastq": "^1.17.1" } }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "license": "MIT" }, + "node_modules/bcrypt": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz", + "integrity": "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.11", + "node-addon-api": "^5.0.0" + }, + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/bn.js": { "version": "4.12.3", "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.3.tgz", @@ -1342,6 +1421,15 @@ "node": "*" } }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -1360,6 +1448,21 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "license": "MIT" }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "license": "ISC", + "bin": { + "color-support": "bin.js" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, "node_modules/confbox": { "version": "0.1.8", "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", @@ -1367,6 +1470,12 @@ "dev": true, "license": "MIT" }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", + "license": "ISC" + }, "node_modules/content-disposition": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", @@ -1441,6 +1550,21 @@ "node": ">=6" } }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "license": "MIT" + }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -1450,6 +1574,15 @@ "node": ">= 0.8" } }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, "node_modules/diff-sequences": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", @@ -1763,6 +1896,36 @@ "node": ">= 0.6" } }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "license": "ISC" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1778,6 +1941,83 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/gauge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", + "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/gauge/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/gauge/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/gauge/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/gauge/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/gauge/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, "node_modules/get-func-name": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", @@ -1835,6 +2075,12 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", + "license": "ISC" + }, "node_modules/helmet": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/helmet/-/helmet-7.2.0.tgz", @@ -1860,6 +2106,19 @@ "node": ">= 0.8" } }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/human-signals": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", @@ -1870,6 +2129,33 @@ "node": ">=16.17.0" } }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -1894,6 +2180,12 @@ "node": ">=8" } }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "license": "MIT" + }, "node_modules/is-stream": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", @@ -1995,6 +2287,12 @@ "url": "https://github.com/sponsors/antfu" } }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/loupe": { "version": "2.3.7", "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", @@ -2011,6 +2309,21 @@ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", "license": "ISC" }, + "node_modules/lru.min": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz", + "integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -2021,6 +2334,30 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", @@ -2083,6 +2420,43 @@ "node": ">=16 || 14 >=14.17" } }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "license": "MIT", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/mlly": { "version": "1.8.2", "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", @@ -2118,6 +2492,40 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/mysql2": { + "version": "3.20.0", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.20.0.tgz", + "integrity": "sha512-eCLUs7BNbgA6nf/MZXsaBO1SfGs0LtLVrJD3WeWq+jPLDWkSufTD+aGMwykfUVPdZnblaUK1a8G/P63cl9FkKg==", + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.2", + "denque": "^2.1.0", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.2", + "long": "^5.3.2", + "lru.min": "^1.1.4", + "named-placeholders": "^1.1.6", + "sql-escaper": "^1.3.3" + }, + "engines": { + "node": ">= 8.0" + }, + "peerDependencies": { + "@types/node": ">= 8" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "license": "MIT", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/nanoid": { "version": "3.3.11", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", @@ -2137,6 +2545,47 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/node-addon-api": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz", + "integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==", + "license": "MIT" + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "license": "ISC", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/npm-run-path": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", @@ -2166,6 +2615,28 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/npmlog": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", + "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/obliterator": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz", @@ -2181,6 +2652,15 @@ "node": ">=14.0.0" } }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, "node_modules/onetime": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", @@ -2225,6 +2705,15 @@ "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", "license": "BlueOak-1.0.0" }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -2267,95 +2756,6 @@ "node": "*" } }, - "node_modules/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", - "license": "MIT", - "dependencies": { - "pg-connection-string": "^2.12.0", - "pg-pool": "^3.13.0", - "pg-protocol": "^1.13.0", - "pg-types": "2.2.0", - "pgpass": "1.0.5" - }, - "engines": { - "node": ">= 16.0.0" - }, - "optionalDependencies": { - "pg-cloudflare": "^1.3.0" - }, - "peerDependencies": { - "pg-native": ">=3.0.1" - }, - "peerDependenciesMeta": { - "pg-native": { - "optional": true - } - } - }, - "node_modules/pg-cloudflare": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz", - "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==", - "license": "MIT", - "optional": true - }, - "node_modules/pg-connection-string": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz", - "integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==", - "license": "MIT" - }, - "node_modules/pg-int8": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", - "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", - "license": "ISC", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/pg-pool": { - "version": "3.13.0", - "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz", - "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==", - "license": "MIT", - "peerDependencies": { - "pg": ">=8.0" - } - }, - "node_modules/pg-protocol": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz", - "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==", - "license": "MIT" - }, - "node_modules/pg-types": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", - "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", - "license": "MIT", - "dependencies": { - "pg-int8": "1.0.1", - "postgres-array": "~2.0.0", - "postgres-bytea": "~1.0.0", - "postgres-date": "~1.0.4", - "postgres-interval": "^1.1.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/pgpass": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", - "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", - "license": "MIT", - "dependencies": { - "split2": "^4.1.0" - } - }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -2464,45 +2864,6 @@ "node": "^10 || ^12 || >=14" } }, - "node_modules/postgres-array": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", - "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/postgres-bytea": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", - "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-date": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", - "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-interval": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", - "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", - "license": "MIT", - "dependencies": { - "xtend": "^4.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/pretty-format": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", @@ -2559,6 +2920,20 @@ "dev": true, "license": "MIT" }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/real-require": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", @@ -2612,6 +2987,65 @@ "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", "license": "MIT" }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/rimraf/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/rollup": { "version": "4.60.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.0.tgz", @@ -2719,6 +3153,12 @@ "node": ">=10" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/set-cookie-parser": { "version": "2.7.2", "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", @@ -2799,6 +3239,21 @@ "node": ">= 10.x" } }, + "node_modules/sql-escaper": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.3.3.tgz", + "integrity": "sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=2.0.0", + "node": ">=12.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -2835,6 +3290,15 @@ "reusify": "^1.0.0" } }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/string-width": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", @@ -2957,6 +3421,33 @@ "url": "https://github.com/sponsors/antfu" } }, + "node_modules/tar": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", + "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "deprecated": "Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/tar/node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "license": "ISC", + "engines": { + "node": ">=8" + } + }, "node_modules/thread-stream": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz", @@ -3011,6 +3502,12 @@ "node": ">=0.6" } }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, "node_modules/tsx": { "version": "4.21.0", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz", @@ -3066,7 +3563,6 @@ "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, "license": "MIT" }, "node_modules/uri-js": { @@ -3078,6 +3574,12 @@ "punycode": "^2.1.0" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, "node_modules/vite": { "version": "5.4.21", "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", @@ -3657,6 +4159,22 @@ } } }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -3689,6 +4207,56 @@ "node": ">=8" } }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "license": "ISC", + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/wide-align/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wide-align/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wide-align/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wide-align/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/wrap-ansi": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", @@ -3792,6 +4360,12 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", @@ -3801,6 +4375,12 @@ "node": ">=0.4" } }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, "node_modules/yaml": { "version": "2.8.3", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz", diff --git a/api/package.json b/api/package.json index 8c21148..fe5c2ef 100644 --- a/api/package.json +++ b/api/package.json @@ -10,8 +10,7 @@ "typecheck": "tsc --noEmit", "test": "vitest run", "test:watch": "vitest", - "db:migrate": "node-pg-migrate -d $DATABASE_URL up", - "db:migrate:down": "node-pg-migrate -d $DATABASE_URL down" + "db:migrate": "bash ../scripts/run-mysql-migrations.sh" }, "dependencies": { "@fastify/cookie": "^9.3.1", @@ -20,14 +19,15 @@ "@fastify/rate-limit": "^9.1.0", "@fastify/swagger": "^8.14.0", "@fastify/swagger-ui": "^3.0.0", + "bcrypt": "^5.1.1", "fastify": "^4.27.0", - "pg": "^8.11.5", + "mysql2": "^3.11.5", "pino": "^9.1.0", "zod": "^3.23.8" }, "devDependencies": { + "@types/bcrypt": "^5.0.2", "@types/node": "^20.14.0", - "@types/pg": "^8.11.6", "tsx": "^4.15.6", "typescript": "^5.4.5", "vitest": "^1.6.0" diff --git a/api/src/plugins/audit.ts b/api/src/plugins/audit.ts index 315abbd..2cc86bd 100644 --- a/api/src/plugins/audit.ts +++ b/api/src/plugins/audit.ts @@ -6,42 +6,12 @@ * is preferable to data corruption. Critical operations must log AFTER the * primary operation succeeds. * - * Schema (created in migration 003_audit_logs): - * - * CREATE TABLE audit_logs ( - * id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - * action VARCHAR(128) NOT NULL, -- e.g. 'projects.delete' - * actor_id UUID, -- NULL for anonymous (failed login) - * actor_ip INET, - * target TEXT, -- email, project ID, token ID, etc. - * metadata JSONB NOT NULL DEFAULT '{}', - * created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - * ); - * CREATE INDEX ON audit_logs (actor_id, created_at DESC); - * CREATE INDEX ON audit_logs (action, created_at DESC); - * - * Critical actions that MUST emit audit events (see ROLE_PERMISSIONS for context): - * auth.login — successful login - * auth.login_failed — failed login attempt (includes reason) - * auth.logout — explicit logout - * users.create — new admin user created - * users.update — admin user role/email changed - * users.delete — admin user deleted - * projects.create — new project registered - * projects.update — project settings changed - * projects.delete — project deleted (destructive) - * ingest_tokens.create — new ingest token issued - * ingest_tokens.revoke — ingest token revoked - * sources.create — new active collector source added - * sources.delete — source removed - * errors.triage — error state changed (status transition + note) - * errors.delete — error record deleted - * settings.update — system settings changed + * Schema: db/migrations/003_audit_logs.sql (MariaDB). */ import fp from 'fastify-plugin'; import type { FastifyInstance } from 'fastify'; -import type { Pool } from 'pg'; +import type { Pool } from 'mysql2/promise'; export interface AuditEvent { action: string; @@ -52,7 +22,7 @@ export interface AuditEvent { } /** - * Write an audit log entry. Accepts a pg Pool or PoolClient so it can + * Write an audit log entry. Accepts a mysql2 Pool or PoolConnection so it can * participate in an ongoing transaction if needed. */ export async function auditLog( @@ -60,9 +30,9 @@ export async function auditLog( event: AuditEvent, ): Promise { try { - await db.query( + await db.execute( `INSERT INTO audit_logs (action, actor_id, actor_ip, target, metadata) - VALUES ($1, $2, $3::inet, $4, $5::jsonb)`, + VALUES (?, ?, ?, ?, ?)`, [ event.action, event.actor_id ?? null, @@ -72,8 +42,6 @@ export async function auditLog( ], ); } catch (err) { - // Audit failure must never break the main operation. - // Log the failure so ops can investigate. console.error('[audit] Failed to write audit event', { action: event.action, error: String(err), diff --git a/api/src/plugins/db.ts b/api/src/plugins/db.ts index f7c0606..e11b432 100644 --- a/api/src/plugins/db.ts +++ b/api/src/plugins/db.ts @@ -1,10 +1,10 @@ /** - * PostgreSQL connection pool plugin. - * Decorates app with app.db (pg.Pool). - * Env vars: DATABASE_URL (preferred) or DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD. + * MariaDB / MySQL connection pool plugin. + * Decorates app with app.db (mysql2 Pool). + * Env: DATABASE_URL (mysql://user:pass@host:port/db) or discrete DB_* vars. */ import fp from 'fastify-plugin'; -import { Pool } from 'pg'; +import mysql, { type Pool } from 'mysql2/promise'; import type { FastifyInstance } from 'fastify'; declare module 'fastify' { @@ -14,18 +14,21 @@ declare module 'fastify' { } export default fp(async function dbPlugin(app: FastifyInstance) { - const pool = new Pool({ - connectionString: process.env.DATABASE_URL, - max: parseInt(process.env.DB_POOL_MAX ?? '10', 10), - idleTimeoutMillis: 30_000, - connectionTimeoutMillis: 5_000, + const _url = process.env.DATABASE_URL; + if (typeof _url !== 'string' || _url.trim() === '') { + throw new Error('DATABASE_URL is required'); + } + const pool = mysql.createPool({ + uri: _url.trim(), + connectionLimit: parseInt(process.env.DB_POOL_MAX ?? '10', 10), + waitForConnections: true, + enableKeepAlive: true, }); - // Verify connection on startup - const client = await pool.connect(); + const client = await pool.getConnection(); try { await client.query('SELECT 1'); - app.log.info('PostgreSQL connected'); + app.log.info('MariaDB connected'); } finally { client.release(); } @@ -34,6 +37,6 @@ export default fp(async function dbPlugin(app: FastifyInstance) { app.addHook('onClose', async () => { await pool.end(); - app.log.info('PostgreSQL pool closed'); + app.log.info('MariaDB pool closed'); }); }, { name: 'db' }); diff --git a/api/src/routes/admin/auth.ts b/api/src/routes/admin/auth.ts index 5e1944c..5c0928f 100644 --- a/api/src/routes/admin/auth.ts +++ b/api/src/routes/admin/auth.ts @@ -8,6 +8,7 @@ */ import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; +import type { RowDataPacket } from 'mysql2'; import bcrypt from 'bcrypt'; import { setAccessCookie, @@ -24,14 +25,8 @@ interface LoginBody { password: string; } -interface RefreshCookies { - '__Host-refresh'?: string; -} - -const BCRYPT_ROUNDS = 12; - export default async function adminAuthRoutes(app: FastifyInstance): Promise { - const db = app.db; // postgres pool — registered separately + const db = app.db; /** * POST /admin/auth/login @@ -55,28 +50,29 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise, reply: FastifyReply) => { const { email, password } = request.body; - // Lookup user — always run bcrypt even if not found (prevent timing oracle) - const result = await db.query<{ - id: string; - email: string; - role: string; - password_hash: string; - is_active: boolean; - }>( + const [rows] = await db.execute( `SELECT id, email, role, password_hash, is_active FROM admin_users - WHERE email = $1 + WHERE LOWER(email) = LOWER(?) LIMIT 1`, - [email.toLowerCase()], + [email], ); - const user = result.rows[0]; + const user = rows[0] as + | { + id: string; + email: string; + role: string; + password_hash: string; + is_active: number | boolean; + } + | undefined; - // Use a dummy hash when user not found to prevent timing attacks const hash_to_check = user?.password_hash ?? '$2b$12$invalidhashfortimingprotection000000000000000'; const password_ok = await bcrypt.compare(password, hash_to_check); - if (!user || !password_ok || !user.is_active) { + const _active = user ? Boolean(user.is_active) : false; + if (!user || !password_ok || !_active) { await auditLog(db, { action: 'auth.login_failed', actor_id: null, @@ -87,16 +83,15 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise( + app.post( '/admin/auth/refresh', - async (request: FastifyRequest<{ Cookies: RefreshCookies }>, reply: FastifyReply) => { + async (request: FastifyRequest, reply: FastifyReply) => { const refresh_token = request.cookies['__Host-refresh']; if (!refresh_token) { return reply.code(401).send({ error: 'No refresh token' }); @@ -131,58 +126,55 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise( + const [rows] = await db.execute( `SELECT id, user_id, expires_at, revoked_at FROM admin_refresh_tokens - WHERE token_hash = $1 + WHERE token_hash = ? LIMIT 1`, [refresh_hash], ); - const token_row = result.rows[0]; + const token_row = rows[0] as + | { + id: string; + user_id: string; + expires_at: Date; + revoked_at: Date | null; + } + | undefined; if (!token_row || token_row.revoked_at || token_row.expires_at < new Date()) { clearAuthCookies(reply); return reply.code(401).send({ error: 'Refresh token invalid or expired' }); } - // Revoke old refresh token (rotation — detect replay attacks) - await db.query( - `UPDATE admin_refresh_tokens SET revoked_at = NOW() WHERE id = $1`, + await db.execute( + `UPDATE admin_refresh_tokens SET revoked_at = NOW(6) WHERE id = ?`, [token_row.id], ); - // Fetch user - const user_result = await db.query<{ - id: string; - email: string; - role: string; - is_active: boolean; - }>( - `SELECT id, email, role, is_active FROM admin_users WHERE id = $1`, + const [userRows] = await db.execute( + `SELECT id, email, role, is_active FROM admin_users WHERE id = ?`, [token_row.user_id], ); - const user = user_result.rows[0]; - if (!user || !user.is_active) { + const user = userRows[0] as + | { id: string; email: string; role: string; is_active: number | boolean } + | undefined; + const _uActive = user ? Boolean(user.is_active) : false; + if (!user || !_uActive) { clearAuthCookies(reply); return reply.code(401).send({ error: 'User no longer active' }); } - // Issue new token pair - const payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as any }; + const payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as JwtPayload['role'] }; const new_access_token = app.jwt.sign(payload, { expiresIn: '15m' }); const new_refresh_token = generateRefreshToken(); const new_refresh_hash = hashRefreshToken(new_refresh_token); - await db.query( + await db.execute( `INSERT INTO admin_refresh_tokens (user_id, token_hash, expires_at) - VALUES ($1, $2, NOW() + INTERVAL '7 days')`, + VALUES (?, ?, DATE_ADD(NOW(6), INTERVAL 7 DAY))`, [user.id, new_refresh_hash], ); @@ -202,10 +194,10 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise { const refresh_token = request.cookies['__Host-refresh']; if (refresh_token) { - const refresh_hash = hashRefreshToken(refresh_token); - await db.query( - `UPDATE admin_refresh_tokens SET revoked_at = NOW() WHERE token_hash = $1`, - [refresh_hash], + const rh = hashRefreshToken(refresh_token); + await db.execute( + `UPDATE admin_refresh_tokens SET revoked_at = NOW(6) WHERE token_hash = ?`, + [rh], ); } diff --git a/collector-worker/package-lock.json b/collector-worker/package-lock.json index 138d01a..2c23969 100644 --- a/collector-worker/package-lock.json +++ b/collector-worker/package-lock.json @@ -9,11 +9,10 @@ "version": "0.1.0", "dependencies": { "dotenv": "^16.4.5", - "pg": "^8.13.1" + "mysql2": "^3.11.5" }, "devDependencies": { "@types/node": "^22.9.0", - "@types/pg": "^8.11.10", "tsx": "^4.19.2", "typescript": "^5.6.3", "vitest": "^2.1.0" @@ -832,24 +831,11 @@ "version": "22.19.15", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz", "integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==", - "dev": true, "license": "MIT", "dependencies": { "undici-types": "~6.21.0" } }, - "node_modules/@types/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "pg-protocol": "*", - "pg-types": "^2.2.0" - } - }, "node_modules/@vitest/expect": { "version": "2.1.9", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz", @@ -973,6 +959,15 @@ "node": ">=12" } }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/cac": { "version": "6.7.14", "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", @@ -1038,6 +1033,15 @@ "node": ">=6" } }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, "node_modules/dotenv": { "version": "16.6.1", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", @@ -1134,6 +1138,15 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, "node_modules/get-tsconfig": { "version": "4.13.6", "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz", @@ -1147,6 +1160,34 @@ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" } }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "license": "MIT" + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/loupe": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", @@ -1154,6 +1195,21 @@ "dev": true, "license": "MIT" }, + "node_modules/lru.min": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz", + "integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -1171,6 +1227,40 @@ "dev": true, "license": "MIT" }, + "node_modules/mysql2": { + "version": "3.20.0", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.20.0.tgz", + "integrity": "sha512-eCLUs7BNbgA6nf/MZXsaBO1SfGs0LtLVrJD3WeWq+jPLDWkSufTD+aGMwykfUVPdZnblaUK1a8G/P63cl9FkKg==", + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.2", + "denque": "^2.1.0", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.2", + "long": "^5.3.2", + "lru.min": "^1.1.4", + "named-placeholders": "^1.1.6", + "sql-escaper": "^1.3.3" + }, + "engines": { + "node": ">= 8.0" + }, + "peerDependencies": { + "@types/node": ">= 8" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "license": "MIT", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/nanoid": { "version": "3.3.11", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", @@ -1207,95 +1297,6 @@ "node": ">= 14.16" } }, - "node_modules/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", - "license": "MIT", - "dependencies": { - "pg-connection-string": "^2.12.0", - "pg-pool": "^3.13.0", - "pg-protocol": "^1.13.0", - "pg-types": "2.2.0", - "pgpass": "1.0.5" - }, - "engines": { - "node": ">= 16.0.0" - }, - "optionalDependencies": { - "pg-cloudflare": "^1.3.0" - }, - "peerDependencies": { - "pg-native": ">=3.0.1" - }, - "peerDependenciesMeta": { - "pg-native": { - "optional": true - } - } - }, - "node_modules/pg-cloudflare": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz", - "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==", - "license": "MIT", - "optional": true - }, - "node_modules/pg-connection-string": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz", - "integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==", - "license": "MIT" - }, - "node_modules/pg-int8": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", - "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", - "license": "ISC", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/pg-pool": { - "version": "3.13.0", - "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz", - "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==", - "license": "MIT", - "peerDependencies": { - "pg": ">=8.0" - } - }, - "node_modules/pg-protocol": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz", - "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==", - "license": "MIT" - }, - "node_modules/pg-types": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", - "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", - "license": "MIT", - "dependencies": { - "pg-int8": "1.0.1", - "postgres-array": "~2.0.0", - "postgres-bytea": "~1.0.0", - "postgres-date": "~1.0.4", - "postgres-interval": "^1.1.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/pgpass": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", - "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", - "license": "MIT", - "dependencies": { - "split2": "^4.1.0" - } - }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -1332,45 +1333,6 @@ "node": "^10 || ^12 || >=14" } }, - "node_modules/postgres-array": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", - "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/postgres-bytea": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", - "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-date": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", - "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-interval": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", - "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", - "license": "MIT", - "dependencies": { - "xtend": "^4.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/resolve-pkg-maps": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", @@ -1426,6 +1388,12 @@ "fsevents": "~2.3.2" } }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -1443,13 +1411,19 @@ "node": ">=0.10.0" } }, - "node_modules/split2": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", - "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", - "license": "ISC", + "node_modules/sql-escaper": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.3.3.tgz", + "integrity": "sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw==", + "license": "MIT", "engines": { - "node": ">= 10.x" + "bun": ">=1.0.0", + "deno": ">=2.0.0", + "node": ">=12.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" } }, "node_modules/stackback": { @@ -1548,7 +1522,6 @@ "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, "license": "MIT" }, "node_modules/vite": { @@ -2146,15 +2119,6 @@ "engines": { "node": ">=8" } - }, - "node_modules/xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "license": "MIT", - "engines": { - "node": ">=0.4" - } } } } diff --git a/collector-worker/package.json b/collector-worker/package.json index 8b524f4..f73925c 100644 --- a/collector-worker/package.json +++ b/collector-worker/package.json @@ -13,11 +13,10 @@ }, "dependencies": { "dotenv": "^16.4.5", - "pg": "^8.13.1" + "mysql2": "^3.11.5" }, "devDependencies": { "@types/node": "^22.9.0", - "@types/pg": "^8.11.10", "tsx": "^4.19.2", "typescript": "^5.6.3", "vitest": "^2.1.0" diff --git a/collector-worker/src/db/collectorRunWriter.ts b/collector-worker/src/db/collectorRunWriter.ts index 3719a48..c8048fc 100644 --- a/collector-worker/src/db/collectorRunWriter.ts +++ b/collector-worker/src/db/collectorRunWriter.ts @@ -1,29 +1,32 @@ -import type { Pool, PoolClient } from "pg"; +import type { Pool, PoolConnection } from "mysql2/promise"; +import type { ResultSetHeader } from "mysql2"; export async function insertRunStarted( - client: PoolClient, + client: PoolConnection, input: { collectorSourceId: string; projectId: string }, ): Promise { - const _ins = await client.query<{ id: string }>( + const [res] = await client.execute( `INSERT INTO er_collector_runs ( collector_source_id, project_id, triggered_by, started_at, status - ) VALUES ($1::bigint, $2::bigint, 'scheduler', NOW(), 'running') - RETURNING id::text`, + ) VALUES (?, ?, 'scheduler', NOW(6), 'running')`, [input.collectorSourceId, input.projectId], ); - const _id = _ins.rows[0]?.id; - if (!_id) { + const _id = res.insertId; + if (typeof _id !== "number" && typeof _id !== "bigint") { throw new Error("collector_run_insert_failed"); } - return _id; + if (Number(_id) <= 0) { + throw new Error("collector_run_insert_failed"); + } + return String(_id); } export async function finishRun( - client: PoolClient, + client: PoolConnection, input: { runId: string; status: "success" | "failed" | "partial"; @@ -34,35 +37,35 @@ export async function finishRun( errorSummary: string | null; }, ): Promise { - await client.query( + await client.execute( `UPDATE er_collector_runs - SET finished_at = NOW(), - status = $2, - fetched_count = $3, - accepted_count = $4, - deduplicated_count = $5, - failed_count = $6, - error_summary = $7 - WHERE id = $1::bigint`, + SET finished_at = NOW(6), + status = ?, + fetched_count = ?, + accepted_count = ?, + deduplicated_count = ?, + failed_count = ?, + error_summary = ? + WHERE id = ?`, [ - input.runId, input.status, input.fetchedCount, input.acceptedCount, input.deduplicatedCount, input.failedCount, input.errorSummary, + input.runId, ], ); } export async function markSourceSuccess(pool: Pool, sourceId: string): Promise { - await pool.query( + await pool.execute( `UPDATE er_collector_sources - SET last_success_at = NOW(), + SET last_success_at = NOW(6), last_error_message = NULL, - updated_at = NOW() - WHERE id = $1::bigint`, + updated_at = NOW(6) + WHERE id = ?`, [sourceId], ); } @@ -71,12 +74,12 @@ export async function markSourceFailure( pool: Pool, input: { sourceId: string; message: string }, ): Promise { - await pool.query( + await pool.execute( `UPDATE er_collector_sources - SET last_error_at = NOW(), - last_error_message = $2, - updated_at = NOW() - WHERE id = $1::bigint`, - [input.sourceId, input.message.slice(0, 4000)], + SET last_error_at = NOW(6), + last_error_message = ?, + updated_at = NOW(6) + WHERE id = ?`, + [input.message.slice(0, 4000), input.sourceId], ); } diff --git a/collector-worker/src/db/loadActiveSources.ts b/collector-worker/src/db/loadActiveSources.ts index 8809a5d..b147e3d 100644 --- a/collector-worker/src/db/loadActiveSources.ts +++ b/collector-worker/src/db/loadActiveSources.ts @@ -1,33 +1,29 @@ -import type { Pool } from "pg"; +import type { Pool } from "mysql2/promise"; +import type { RowDataPacket } from "mysql2"; import type { CollectorSourceRow } from "../types/ingest.js"; export async function loadActiveSources(pool: Pool): Promise { - const _res = await pool.query<{ - id: string; - project_id: string; - name: string; - source_type: string; - endpoint_uri: string; - auth_secret_ref: string | null; - poll_interval_seconds: string; - }>( - `SELECT id::text, - project_id::text, + const [rows] = await pool.execute( + `SELECT CAST(id AS CHAR) AS id, + CAST(project_id AS CHAR) AS project_id, name, source_type, endpoint_uri, auth_secret_ref, - poll_interval_seconds::text + CAST(poll_interval_seconds AS CHAR) AS poll_interval_seconds FROM er_collector_sources WHERE is_active = TRUE`, ); - return _res.rows.map((row) => ({ - id: row.id, - project_id: row.project_id, - name: row.name, - source_type: row.source_type, - endpoint_uri: row.endpoint_uri, - auth_secret_ref: row.auth_secret_ref, - poll_interval_seconds: Number.parseInt(row.poll_interval_seconds, 10), + return rows.map((row) => ({ + id: String((row as { id: string }).id), + project_id: String((row as { project_id: string }).project_id), + name: String((row as { name: string }).name), + source_type: String((row as { source_type: string }).source_type), + endpoint_uri: String((row as { endpoint_uri: string }).endpoint_uri), + auth_secret_ref: (row as { auth_secret_ref: string | null }).auth_secret_ref, + poll_interval_seconds: Number.parseInt( + String((row as { poll_interval_seconds: string }).poll_interval_seconds), + 10, + ), })); } diff --git a/collector-worker/src/main.ts b/collector-worker/src/main.ts index 48b1a2e..4790ba6 100644 --- a/collector-worker/src/main.ts +++ b/collector-worker/src/main.ts @@ -1,4 +1,4 @@ -import pg from "pg"; +import mysql from "mysql2/promise"; import { loadEnv } from "./config/loadEnv.js"; import { loadActiveSources } from "./db/loadActiveSources.js"; import { logError, logInfo } from "./log/structuredLog.js"; @@ -6,10 +6,11 @@ import { runHttpSourceOnce } from "./scheduler/runHttpSourceOnce.js"; import type { SourceRuntimeState } from "./scheduler/sourceState.js"; const _env = loadEnv(); -const _pool = new pg.Pool({ - connectionString: _env.DATABASE_URL, - max: 8, - idleTimeoutMillis: 30_000, +const _pool = mysql.createPool({ + uri: _env.DATABASE_URL, + connectionLimit: 8, + waitForConnections: true, + enableKeepAlive: true, }); const _stateBySourceId = new Map(); diff --git a/collector-worker/src/scheduler/runHttpSourceOnce.ts b/collector-worker/src/scheduler/runHttpSourceOnce.ts index 74b6aa7..7027d6e 100644 --- a/collector-worker/src/scheduler/runHttpSourceOnce.ts +++ b/collector-worker/src/scheduler/runHttpSourceOnce.ts @@ -1,4 +1,4 @@ -import type { Pool } from "pg"; +import type { Pool } from "mysql2/promise"; import { resolveIngestToken } from "../auth/resolveSecret.js"; import type { CollectorEnv } from "../config/loadEnv.js"; import { @@ -21,17 +21,17 @@ export async function runHttpSourceOnce(input: { }): Promise { const { pool, env, source, state } = input; const _baseMs = Math.max(source.poll_interval_seconds, 15) * 1000; - const _client = await pool.connect(); + const _client = await pool.getConnection(); let _runId = ""; try { - await _client.query("BEGIN"); + await _client.beginTransaction(); _runId = await insertRunStarted(_client, { collectorSourceId: source.id, projectId: source.project_id, }); - await _client.query("COMMIT"); + await _client.commit(); } catch (_err) { - await _client.query("ROLLBACK"); + await _client.rollback(); _client.release(); const _msg = _err instanceof Error ? _err.message : "run_start_failed"; logError({ @@ -106,7 +106,7 @@ export async function runHttpSourceOnce(input: { } if (_fetched.events.length === 0) { - const _c2 = await pool.connect(); + const _c2 = await pool.getConnection(); try { await finishRun(_c2, { runId: _runId, @@ -167,7 +167,7 @@ export async function runHttpSourceOnce(input: { return; } - const _c3 = await pool.connect(); + const _c3 = await pool.getConnection(); try { await finishRun(_c3, { runId: _runId, @@ -201,7 +201,7 @@ async function _finishFailedRun( runId: string, input: { fetched: number; accepted: number; failed: number; error: string }, ): Promise { - const _c = await pool.connect(); + const _c = await pool.getConnection(); try { await finishRun(_c, { runId, diff --git a/database/error_reporting/README.md b/database/error_reporting/README.md index 8a76a05..08a0010 100644 --- a/database/error_reporting/README.md +++ b/database/error_reporting/README.md @@ -3,7 +3,7 @@ This folder contains the relational data model for the Error Reporting platform epic (`BIT-154`), implemented for task `BIT-178`. Status and dependency: -- Stack baseline is defined by `docs/architecture/ADR-002-error-reporting-platform-phase1.md` (Fastify + PostgreSQL + Redis queue for phase 1). +- Runtime target is **MariaDB 10.11+** (or MySQL 8+) with **InnoDB**; Compose and LXC apply the same SQL. - Schema changes must continue through versioned SQL migrations only (`up` + `down`), never ad hoc DDL. ## Migration layout @@ -15,13 +15,22 @@ Migrations are versioned and reversible (`up` + `down`), timestamped, and idempo 3. `20260322044500_add_ingest_idempotency.*` 4. `20260322045000_create_collectors_retention_and_audit.*` +Admin portal tables (`admin_users`, refresh tokens, audit) live under `db/migrations/` at repo root and are applied in the same database by `scripts/docker-migrate.sh` / `deploy/lxc/run-migrate.sh`. + ## Apply manually (example) +From the repository root, with `mariadb` client and a `mysql://` (or discrete `ER_MYSQL_*`) connection: + ```bash -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql +./scripts/run-mysql-migrations.sh +``` + +Or run individual files: + +```bash +mariadb -h 127.0.0.1 -u er_app -p"$ER_MYSQL_PASSWORD" error_reporting \ + < database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql +# ... remaining migrations + db/migrations/*.sql + seed as in scripts/docker-migrate.sh ``` Rollback in reverse order with the matching `*.down.sql` files. diff --git a/database/error_reporting/migrations/20260322043000_create_error_reporting_core.down.sql b/database/error_reporting/migrations/20260322043000_create_error_reporting_core.down.sql index 6bdb358..73206c1 100644 --- a/database/error_reporting/migrations/20260322043000_create_error_reporting_core.down.sql +++ b/database/error_reporting/migrations/20260322043000_create_error_reporting_core.down.sql @@ -1,12 +1,7 @@ BEGIN; -DROP INDEX IF EXISTS er_incidents_project_severity_seen_idx; -DROP INDEX IF EXISTS er_incidents_project_state_seen_idx; DROP TABLE IF EXISTS er_incidents; - -DROP INDEX IF EXISTS er_ingest_keys_project_status_idx; DROP TABLE IF EXISTS er_ingest_keys; - DROP TABLE IF EXISTS er_projects; COMMIT; diff --git a/database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql b/database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql index afb75df..4ace5a6 100644 --- a/database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql +++ b/database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql @@ -1,29 +1,29 @@ BEGIN; CREATE TABLE IF NOT EXISTS er_projects ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, slug VARCHAR(64) NOT NULL, name VARCHAR(160) NOT NULL, description TEXT NULL, is_active BOOLEAN NOT NULL DEFAULT TRUE, timezone_name VARCHAR(64) NOT NULL DEFAULT 'UTC', - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), CONSTRAINT er_projects_slug_uniq UNIQUE (slug), CONSTRAINT er_projects_slug_not_blank_chk CHECK (slug <> '') ); CREATE TABLE IF NOT EXISTS er_ingest_keys ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, project_id BIGINT NOT NULL, label VARCHAR(128) NOT NULL, token_prefix CHAR(8) NOT NULL, token_hash CHAR(64) NOT NULL, status VARCHAR(16) NOT NULL DEFAULT 'active', - last_used_at TIMESTAMP WITHOUT TIME ZONE NULL, - expires_at TIMESTAMP WITHOUT TIME ZONE NULL, - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - revoked_at TIMESTAMP WITHOUT TIME ZONE NULL, + last_used_at DATETIME(6) NULL, + expires_at DATETIME(6) NULL, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + revoked_at DATETIME(6) NULL, CONSTRAINT er_ingest_keys_project_fk FOREIGN KEY (project_id) REFERENCES er_projects (id) ON UPDATE CASCADE @@ -38,20 +38,20 @@ CREATE INDEX IF NOT EXISTS er_ingest_keys_project_status_idx ON er_ingest_keys (project_id, status); CREATE TABLE IF NOT EXISTS er_incidents ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, project_id BIGINT NOT NULL, fingerprint VARCHAR(128) NOT NULL, title VARCHAR(300) NOT NULL, severity VARCHAR(16) NOT NULL, current_state VARCHAR(16) NOT NULL DEFAULT 'open', - first_seen_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, - last_seen_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, + first_seen_at DATETIME(6) NOT NULL, + last_seen_at DATETIME(6) NOT NULL, occurrences_count BIGINT NOT NULL DEFAULT 1, - regression_count INTEGER NOT NULL DEFAULT 0, + regression_count INT NOT NULL DEFAULT 0, last_ingest_key_id BIGINT NULL, metadata_json TEXT NULL, - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), CONSTRAINT er_incidents_project_fk FOREIGN KEY (project_id) REFERENCES er_projects (id) ON UPDATE CASCADE diff --git a/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.down.sql b/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.down.sql index e8831fe..c47536b 100644 --- a/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.down.sql +++ b/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.down.sql @@ -1,18 +1,7 @@ BEGIN; -DROP INDEX IF EXISTS er_incident_attachments_project_kind_time_idx; -DROP INDEX IF EXISTS er_incident_attachments_occurrence_idx; -DROP INDEX IF EXISTS er_incident_attachments_incident_time_idx; DROP TABLE IF EXISTS er_incident_attachments; - -DROP INDEX IF EXISTS er_incident_state_history_project_state_time_idx; -DROP INDEX IF EXISTS er_incident_state_history_incident_time_idx; DROP TABLE IF EXISTS er_incident_state_history; - -DROP INDEX IF EXISTS er_incident_occurrences_request_id_idx; -DROP INDEX IF EXISTS er_incident_occurrences_project_env_time_idx; -DROP INDEX IF EXISTS er_incident_occurrences_project_time_idx; -DROP INDEX IF EXISTS er_incident_occurrences_incident_time_idx; DROP TABLE IF EXISTS er_incident_occurrences; COMMIT; diff --git a/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql b/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql index 28edf2b..bd43bc8 100644 --- a/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql +++ b/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql @@ -1,11 +1,11 @@ BEGIN; CREATE TABLE IF NOT EXISTS er_incident_occurrences ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, incident_id BIGINT NOT NULL, project_id BIGINT NOT NULL, ingest_key_id BIGINT NULL, - occurred_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, + occurred_at DATETIME(6) NOT NULL, level_raw VARCHAR(32) NOT NULL DEFAULT 'error', severity VARCHAR(16) NOT NULL DEFAULT 'medium', schema_version SMALLINT NOT NULL DEFAULT 1, @@ -19,7 +19,7 @@ CREATE TABLE IF NOT EXISTS er_incident_occurrences ( stack_trace TEXT NULL, context_json TEXT NULL, payload_json TEXT NULL, - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), CONSTRAINT er_incident_occurrences_incident_fk FOREIGN KEY (incident_id) REFERENCES er_incidents (id) ON UPDATE CASCADE @@ -52,7 +52,7 @@ CREATE INDEX IF NOT EXISTS er_incident_occurrences_request_id_idx ON er_incident_occurrences (request_id); CREATE TABLE IF NOT EXISTS er_incident_state_history ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, incident_id BIGINT NOT NULL, project_id BIGINT NOT NULL, from_state VARCHAR(16) NULL, @@ -60,7 +60,7 @@ CREATE TABLE IF NOT EXISTS er_incident_state_history ( changed_by_type VARCHAR(16) NOT NULL, changed_by_ref VARCHAR(128) NOT NULL, change_note TEXT NULL, - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), CONSTRAINT er_incident_state_history_incident_fk FOREIGN KEY (incident_id) REFERENCES er_incidents (id) ON UPDATE CASCADE @@ -87,7 +87,7 @@ CREATE INDEX IF NOT EXISTS er_incident_state_history_project_state_time_idx ON er_incident_state_history (project_id, to_state, created_at DESC); CREATE TABLE IF NOT EXISTS er_incident_attachments ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, occurrence_id BIGINT NOT NULL, incident_id BIGINT NOT NULL, project_id BIGINT NOT NULL, @@ -97,7 +97,7 @@ CREATE TABLE IF NOT EXISTS er_incident_attachments ( size_bytes BIGINT NOT NULL DEFAULT 0, checksum_sha256 CHAR(64) NULL, metadata_json TEXT NULL, - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), CONSTRAINT er_incident_attachments_occurrence_fk FOREIGN KEY (occurrence_id) REFERENCES er_incident_occurrences (id) ON UPDATE CASCADE diff --git a/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.down.sql b/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.down.sql index c87bb17..95cb002 100644 --- a/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.down.sql +++ b/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.down.sql @@ -1,7 +1,5 @@ BEGIN; -DROP INDEX IF EXISTS er_ingest_idempotency_created_idx; -DROP INDEX IF EXISTS er_ingest_idempotency_project_created_idx; DROP TABLE IF EXISTS er_ingest_idempotency; COMMIT; diff --git a/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql b/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql index 93a4135..96f48dd 100644 --- a/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql +++ b/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql @@ -1,7 +1,7 @@ BEGIN; CREATE TABLE IF NOT EXISTS er_ingest_idempotency ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, ingest_key_id BIGINT NOT NULL, project_id BIGINT NOT NULL, idempotency_key VARCHAR(128) NOT NULL, @@ -10,7 +10,7 @@ CREATE TABLE IF NOT EXISTS er_ingest_idempotency ( occurrence_id BIGINT NULL, http_status SMALLINT NOT NULL DEFAULT 200, response_json TEXT NOT NULL, - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), CONSTRAINT er_ingest_idempotency_ingest_key_fk FOREIGN KEY (ingest_key_id) REFERENCES er_ingest_keys (id) ON UPDATE CASCADE diff --git a/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.down.sql b/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.down.sql index 90b35e2..2b7926b 100644 --- a/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.down.sql +++ b/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.down.sql @@ -1,18 +1,8 @@ BEGIN; -DROP INDEX IF EXISTS er_audit_logs_request_id_idx; -DROP INDEX IF EXISTS er_audit_logs_project_entity_created_idx; -DROP INDEX IF EXISTS er_audit_logs_project_created_idx; DROP TABLE IF EXISTS er_audit_logs; - DROP TABLE IF EXISTS er_retention_policies; - -DROP INDEX IF EXISTS er_collector_runs_project_status_started_idx; -DROP INDEX IF EXISTS er_collector_runs_project_started_idx; -DROP INDEX IF EXISTS er_collector_runs_source_started_idx; DROP TABLE IF EXISTS er_collector_runs; - -DROP INDEX IF EXISTS er_collector_sources_project_active_idx; DROP TABLE IF EXISTS er_collector_sources; COMMIT; diff --git a/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql b/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql index bf114a8..6256510 100644 --- a/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql +++ b/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql @@ -1,19 +1,19 @@ BEGIN; CREATE TABLE IF NOT EXISTS er_collector_sources ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, project_id BIGINT NOT NULL, name VARCHAR(128) NOT NULL, source_type VARCHAR(16) NOT NULL, endpoint_uri VARCHAR(1024) NOT NULL, auth_secret_ref VARCHAR(255) NULL, - poll_interval_seconds INTEGER NOT NULL DEFAULT 60, + poll_interval_seconds INT NOT NULL DEFAULT 60, is_active BOOLEAN NOT NULL DEFAULT TRUE, - last_success_at TIMESTAMP WITHOUT TIME ZONE NULL, - last_error_at TIMESTAMP WITHOUT TIME ZONE NULL, + last_success_at DATETIME(6) NULL, + last_error_at DATETIME(6) NULL, last_error_message TEXT NULL, - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), CONSTRAINT er_collector_sources_project_fk FOREIGN KEY (project_id) REFERENCES er_projects (id) ON UPDATE CASCADE @@ -29,19 +29,19 @@ CREATE INDEX IF NOT EXISTS er_collector_sources_project_active_idx ON er_collector_sources (project_id, is_active); CREATE TABLE IF NOT EXISTS er_collector_runs ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, collector_source_id BIGINT NOT NULL, project_id BIGINT NOT NULL, triggered_by VARCHAR(16) NOT NULL, - started_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, - finished_at TIMESTAMP WITHOUT TIME ZONE NULL, + started_at DATETIME(6) NOT NULL, + finished_at DATETIME(6) NULL, status VARCHAR(16) NOT NULL, - fetched_count INTEGER NOT NULL DEFAULT 0, - accepted_count INTEGER NOT NULL DEFAULT 0, - deduplicated_count INTEGER NOT NULL DEFAULT 0, - failed_count INTEGER NOT NULL DEFAULT 0, + fetched_count INT NOT NULL DEFAULT 0, + accepted_count INT NOT NULL DEFAULT 0, + deduplicated_count INT NOT NULL DEFAULT 0, + failed_count INT NOT NULL DEFAULT 0, error_summary TEXT NULL, - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), CONSTRAINT er_collector_runs_source_fk FOREIGN KEY (collector_source_id) REFERENCES er_collector_sources (id) ON UPDATE CASCADE @@ -72,18 +72,18 @@ CREATE INDEX IF NOT EXISTS er_collector_runs_project_status_started_idx ON er_collector_runs (project_id, status, started_at DESC); CREATE TABLE IF NOT EXISTS er_retention_policies ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, project_id BIGINT NOT NULL, - keep_open_days INTEGER NOT NULL DEFAULT 90, - keep_resolved_days INTEGER NOT NULL DEFAULT 30, - keep_ignored_days INTEGER NOT NULL DEFAULT 7, - keep_attachments_days INTEGER NOT NULL DEFAULT 30, - keep_audit_days INTEGER NOT NULL DEFAULT 365, + keep_open_days INT NOT NULL DEFAULT 90, + keep_resolved_days INT NOT NULL DEFAULT 30, + keep_ignored_days INT NOT NULL DEFAULT 7, + keep_attachments_days INT NOT NULL DEFAULT 30, + keep_audit_days INT NOT NULL DEFAULT 365, delete_mode VARCHAR(16) NOT NULL DEFAULT 'soft', updated_by_type VARCHAR(16) NOT NULL DEFAULT 'system', updated_by_ref VARCHAR(128) NOT NULL DEFAULT 'bootstrap', - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), CONSTRAINT er_retention_policies_project_fk FOREIGN KEY (project_id) REFERENCES er_projects (id) ON UPDATE CASCADE @@ -99,7 +99,7 @@ CREATE TABLE IF NOT EXISTS er_retention_policies ( ); CREATE TABLE IF NOT EXISTS er_audit_logs ( - id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, project_id BIGINT NOT NULL, actor_type VARCHAR(16) NOT NULL, actor_ref VARCHAR(128) NOT NULL, @@ -110,7 +110,7 @@ CREATE TABLE IF NOT EXISTS er_audit_logs ( after_json TEXT NULL, request_id VARCHAR(128) NULL, ip_address VARCHAR(64) NULL, - created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), CONSTRAINT er_audit_logs_project_fk FOREIGN KEY (project_id) REFERENCES er_projects (id) ON UPDATE CASCADE diff --git a/database/error_reporting/seed/dev_collector_http_fixture.sql b/database/error_reporting/seed/dev_collector_http_fixture.sql index f942a19..5c800dc 100644 --- a/database/error_reporting/seed/dev_collector_http_fixture.sql +++ b/database/error_reporting/seed/dev_collector_http_fixture.sql @@ -21,6 +21,6 @@ SELECT TRUE FROM er_projects p WHERE p.slug = 'project-alpha' -ON CONFLICT (project_id, name) DO NOTHING; +ON DUPLICATE KEY UPDATE endpoint_uri = VALUES(endpoint_uri); COMMIT; diff --git a/database/error_reporting/seed/dev_two_projects.sql b/database/error_reporting/seed/dev_two_projects.sql index c700a00..82fc807 100644 --- a/database/error_reporting/seed/dev_two_projects.sql +++ b/database/error_reporting/seed/dev_two_projects.sql @@ -9,16 +9,16 @@ INSERT INTO er_projects (slug, name, description, is_active) VALUES ('project-alpha', 'Project Alpha', 'Seed project A for passive ingest tests', TRUE), ('project-beta', 'Project Beta', 'Seed project B for passive ingest tests', TRUE) -ON CONFLICT (slug) DO NOTHING; +ON DUPLICATE KEY UPDATE slug = VALUES(slug); INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status) SELECT p.id, 'default', 'tok_pr_a', '6b28a152af86ee5d2a30216c5c25e938c1b9bec58685a735b590c8cbaa005189', 'active' FROM er_projects p WHERE p.slug = 'project-alpha' -ON CONFLICT (project_id, label) DO NOTHING; +ON DUPLICATE KEY UPDATE label = label; INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status) SELECT p.id, 'default', 'tok_pr_b', '63ca0b7048280893a98adb9e2a7333e431eb217d90b9470312b2f169ca736012', 'active' FROM er_projects p WHERE p.slug = 'project-beta' -ON CONFLICT (project_id, label) DO NOTHING; +ON DUPLICATE KEY UPDATE label = label; COMMIT; diff --git a/db/migrations/001_admin_users.sql b/db/migrations/001_admin_users.sql index 1ef9488..a89739b 100644 --- a/db/migrations/001_admin_users.sql +++ b/db/migrations/001_admin_users.sql @@ -1,35 +1,19 @@ --- Migration 001: admin_users table +-- Migration 001: admin_users table (MariaDB / MySQL 8+) -- Stores admin panel users with role-based access control. -- Passwords are hashed with bcrypt (cost 12) — never store plaintext. -- -- Roles: superadmin | admin | viewer (see api/src/types/auth.ts) CREATE TABLE IF NOT EXISTS admin_users ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + id CHAR(36) NOT NULL DEFAULT (UUID()) PRIMARY KEY, email VARCHAR(320) NOT NULL, - password_hash VARCHAR(60) NOT NULL, -- bcrypt output is always 60 chars + password_hash VARCHAR(60) NOT NULL, role VARCHAR(20) NOT NULL DEFAULT 'viewer' CHECK (role IN ('superadmin', 'admin', 'viewer')), is_active BOOLEAN NOT NULL DEFAULT TRUE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) ); CREATE UNIQUE INDEX IF NOT EXISTS admin_users_email_idx - ON admin_users (LOWER(email)); - --- Auto-update updated_at on row change -CREATE OR REPLACE FUNCTION set_updated_at() -RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - NEW.updated_at = NOW(); - RETURN NEW; -END; -$$; - -CREATE TRIGGER admin_users_updated_at - BEFORE UPDATE ON admin_users - FOR EACH ROW EXECUTE FUNCTION set_updated_at(); - -COMMENT ON TABLE admin_users IS 'Admin panel users (RBAC). Phase 1: global roles, no per-project scoping.'; -COMMENT ON COLUMN admin_users.role IS 'superadmin = full access; admin = project mgmt; viewer = read-only'; + ON admin_users ((LOWER(email))); diff --git a/db/migrations/002_admin_refresh_tokens.sql b/db/migrations/002_admin_refresh_tokens.sql index 8fdd134..f5e09c8 100644 --- a/db/migrations/002_admin_refresh_tokens.sql +++ b/db/migrations/002_admin_refresh_tokens.sql @@ -1,15 +1,14 @@ --- Migration 002: admin_refresh_tokens table --- Stores hashed refresh tokens for admin session rotation. --- Only the SHA-256 hash is stored; the plaintext token is sent to the client --- in an HTTP-only cookie and never persisted. +-- Migration 002: admin_refresh_tokens table (MariaDB / MySQL) CREATE TABLE IF NOT EXISTS admin_refresh_tokens ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE, - token_hash VARCHAR(64) NOT NULL, -- SHA-256 hex (64 chars) - expires_at TIMESTAMPTZ NOT NULL, - revoked_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + id CHAR(36) NOT NULL DEFAULT (UUID()) PRIMARY KEY, + user_id CHAR(36) NOT NULL, + token_hash VARCHAR(64) NOT NULL, + expires_at DATETIME(6) NOT NULL, + revoked_at DATETIME(6) NULL, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + CONSTRAINT admin_refresh_tokens_user_fk FOREIGN KEY (user_id) + REFERENCES admin_users (id) ON DELETE CASCADE ); CREATE UNIQUE INDEX IF NOT EXISTS admin_refresh_tokens_hash_idx @@ -17,8 +16,3 @@ CREATE UNIQUE INDEX IF NOT EXISTS admin_refresh_tokens_hash_idx CREATE INDEX IF NOT EXISTS admin_refresh_tokens_user_idx ON admin_refresh_tokens (user_id, created_at DESC); - --- Periodic cleanup: delete expired/revoked tokens older than 30 days. --- Run via cron or pg_cron: DELETE FROM admin_refresh_tokens WHERE expires_at < NOW() - INTERVAL '30 days'; - -COMMENT ON TABLE admin_refresh_tokens IS 'Hashed refresh tokens for admin JWT rotation. Plaintext never stored.'; diff --git a/db/migrations/003_audit_logs.sql b/db/migrations/003_audit_logs.sql index 1a2e0ed..06b224f 100644 --- a/db/migrations/003_audit_logs.sql +++ b/db/migrations/003_audit_logs.sql @@ -1,39 +1,21 @@ --- Migration 003: audit_logs table +-- Migration 003: audit_logs table (MariaDB / MySQL) -- Append-only audit trail for critical admin operations. --- No UPDATE or DELETE on this table — immutability is the point. --- Partitioning by month recommended when volume grows (phase 2). CREATE TABLE IF NOT EXISTS audit_logs ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - action VARCHAR(128) NOT NULL, -- e.g. 'auth.login', 'projects.delete' - actor_id UUID, -- NULL for unauthenticated events (login failures) - actor_ip INET, - target TEXT NOT NULL DEFAULT '', -- email, project ID, token ID, etc. - metadata JSONB NOT NULL DEFAULT '{}', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + id CHAR(36) NOT NULL DEFAULT (UUID()) PRIMARY KEY, + action VARCHAR(128) NOT NULL, + actor_id CHAR(36) NULL, + actor_ip VARCHAR(45) NULL, + target TEXT NOT NULL DEFAULT '', + metadata JSON NOT NULL DEFAULT (JSON_OBJECT()), + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ); --- Query patterns: --- 1. All actions by a user, recent first CREATE INDEX IF NOT EXISTS audit_logs_actor_time_idx - ON audit_logs (actor_id, created_at DESC) - WHERE actor_id IS NOT NULL; + ON audit_logs (actor_id, created_at DESC); --- 2. All events of a specific type, recent first CREATE INDEX IF NOT EXISTS audit_logs_action_time_idx ON audit_logs (action, created_at DESC); --- 3. Recent activity feed (dashboard) CREATE INDEX IF NOT EXISTS audit_logs_time_idx ON audit_logs (created_at DESC); - --- Revoke DELETE and UPDATE on this table to enforce immutability. --- (Run as superuser after migration) --- REVOKE DELETE, UPDATE, TRUNCATE ON audit_logs FROM PUBLIC; --- REVOKE DELETE, UPDATE, TRUNCATE ON audit_logs FROM app_user; - -COMMENT ON TABLE audit_logs IS 'Append-only audit trail. Critical: no DELETEs or UPDATEs allowed.'; -COMMENT ON COLUMN audit_logs.action IS 'Dot-notation: domain.verb (e.g. auth.login, projects.delete)'; -COMMENT ON COLUMN audit_logs.actor_id IS 'NULL for pre-auth events (failed logins)'; -COMMENT ON COLUMN audit_logs.target IS 'Human-readable target: email, ID, or description'; -COMMENT ON COLUMN audit_logs.metadata IS 'Structured context: role, reason, old/new values (no secrets)'; diff --git a/db/migrations/004_seed_superadmin.sql b/db/migrations/004_seed_superadmin.sql index a220754..1912824 100644 --- a/db/migrations/004_seed_superadmin.sql +++ b/db/migrations/004_seed_superadmin.sql @@ -1,20 +1,7 @@ -- Migration 004: seed initial superadmin (dev/test only) --- DO NOT run in production with hardcoded credentials. --- In production: use the admin CLI (api/src/scripts/create-admin.ts) to create the first user. --- -- Default dev credentials: admin@bitreport.pt / changeme --- Password hash below is bcrypt(cost=12) of 'changeme' — CHANGE IMMEDIATELY. -DO $$ -BEGIN - IF NOT EXISTS (SELECT 1 FROM admin_users WHERE role = 'superadmin') THEN - INSERT INTO admin_users (email, password_hash, role) - VALUES ( - 'admin@bitreport.pt', - '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewYpfQN4ZSIMM.Ey', -- 'changeme' - 'superadmin' - ); - RAISE NOTICE 'Seeded default superadmin. CHANGE THE PASSWORD IMMEDIATELY.'; - END IF; -END; -$$; +INSERT INTO admin_users (email, password_hash, role) +SELECT 'admin@bitreport.pt', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewYpfQN4ZSIMM.Ey', 'superadmin' +FROM DUAL +WHERE NOT EXISTS (SELECT 1 FROM admin_users WHERE role = 'superadmin' LIMIT 1); diff --git a/deploy/lxc/README.md b/deploy/lxc/README.md index 334586d..500ec03 100644 --- a/deploy/lxc/README.md +++ b/deploy/lxc/README.md @@ -1,13 +1,13 @@ # Native LXC deploy (no Docker) -Scripts and unit files for running **ingest-api**, **admin-ui**, and **collector-worker** on Debian/Ubuntu LXC with **PostgreSQL** on the same CT or another host. +Scripts and unit files for running **ingest-api**, **admin-ui**, and **collector-worker** on Debian/Ubuntu LXC with **MariaDB** (or MySQL 8+) on the same CT or another host. Authoritative runbook: [`docs/deployment/bitreport-error-reporting-lxc-proxmox.md`](../../docs/deployment/bitreport-error-reporting-lxc-proxmox.md). | Path | Purpose | |------|---------| | `env.example` | Template for `/etc/error-reporting/env` | -| `run-migrate.sh` | Apply migrations + seed (after Postgres is up) | +| `run-migrate.sh` | Apply migrations + seed (after MariaDB is up) | | `verify.sh` | `curl` ingest `/health` and optional checks | | `systemd/*.service` | Unit files (adjust `WorkingDirectory` if not `/opt/errors.bitreport.pt`) | | `nginx/*.conf.example` | TLS reverse proxy sketch | diff --git a/deploy/lxc/env.example b/deploy/lxc/env.example index fbb6001..25353c3 100644 --- a/deploy/lxc/env.example +++ b/deploy/lxc/env.example @@ -6,9 +6,9 @@ ER_REPO_ROOT=/opt/errors.bitreport.pt # Legacy variable name (still read by run-migrate.sh if ER_REPO_ROOT is unset): # OTT_ROOT=/opt/errors.bitreport.pt -# --- PostgreSQL (single LXC: localhost; split DB LXC: set host accordingly) --- -# URL-encode special characters in user/password per PostgreSQL libpq rules. -DATABASE_URL=postgres://postgres:CHANGE_ME@127.0.0.1:5432/error_reporting +# --- MariaDB / MySQL (single LXC: localhost; split DB LXC: set host in URL) --- +# Percent-encode special characters in user/password (RFC 3986) when building the URL. +DATABASE_URL=mysql://er_app:CHANGE_ME@127.0.0.1:3306/error_reporting # --- ingest-api --- PORT=3041 @@ -23,8 +23,8 @@ SOURCE_REFRESH_MS=15000 HTTP_FETCH_TIMEOUT_MS=15000 MAX_BACKOFF_EXPONENT=8 -# --- admin-ui (Next.js server-side API calls) --- -ERROR_REPORTING_ADMIN_API_BASE=http://127.0.0.1:3041 +# --- admin-ui (Next.js server-side API calls) — target the Fastify `api/` service (default PORT 3200) --- +ERROR_REPORTING_ADMIN_API_BASE=http://127.0.0.1:3200 # ERROR_REPORTING_UI_DEMO=1 # --- Demo / staging only: token must match seed SQL for project-alpha HTTP fixture --- diff --git a/deploy/lxc/run-migrate.sh b/deploy/lxc/run-migrate.sh index 0237b8a..055b928 100755 --- a/deploy/lxc/run-migrate.sh +++ b/deploy/lxc/run-migrate.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash -# Apply error_reporting SQL migrations and seeds (same order as docker-migrate.sh). -# Prerequisites: psql (postgresql-client), empty or already-migrated DB, DATABASE_URL + ER_REPO_ROOT (or legacy OTT_ROOT). +# Apply error_reporting + admin SQL migrations and error_reporting seeds (same order as scripts/docker-migrate.sh). +# Prerequisites: mariadb client, empty or already-migrated DB, ER_REPO_ROOT, and either DATABASE_URL (mysql://...) +# or ER_MYSQL_HOST / ER_MYSQL_USER / ER_MYSQL_PASSWORD / ER_MYSQL_DATABASE. set -euo pipefail _ENV_FILE="/etc/error-reporting/env" @@ -13,25 +14,52 @@ fi _REPO_ROOT="${ER_REPO_ROOT:-${OTT_ROOT:-}}" : "${_REPO_ROOT:?Set ER_REPO_ROOT to this repository root (contains database/error_reporting/). Legacy OTT_ROOT is accepted.}" -: "${DATABASE_URL:?Set DATABASE_URL (postgres://...) for psql}" -_MIG="${_REPO_ROOT}/database/error_reporting/migrations" -_SEED="${_REPO_ROOT}/database/error_reporting/seed" +_MIG_ER="${_REPO_ROOT}/database/error_reporting/migrations" +_SEED_ER="${_REPO_ROOT}/database/error_reporting/seed" +_MIG_ADMIN="${_REPO_ROOT}/db/migrations" -if [[ ! -d "${_MIG}" ]]; then - echo "run-migrate: migrations directory not found: ${_MIG}" >&2 +if [[ ! -d "${_MIG_ER}" ]]; then + echo "run-migrate: migrations directory not found: ${_MIG_ER}" >&2 exit 1 fi +if [[ -n "${DATABASE_URL:-}" ]] && [[ "${DATABASE_URL}" == mysql://* || "${DATABASE_URL}" == mariadb://* ]]; then + _PARSED="$(python3 -c " +import os +from urllib.parse import urlparse, unquote +u = urlparse(os.environ['DATABASE_URL']) +if u.scheme not in ('mysql', 'mariadb', 'mysqli'): + raise SystemExit('DATABASE_URL must be mysql:// or mariadb://') +host = u.hostname or '127.0.0.1' +port = u.port or 3306 +user = unquote(u.username or '') +password = unquote(u.password or '') +db = (u.path or '/').lstrip('/').split('?')[0] +print(host, port, user, password, db) +")" + read -r ER_MYSQL_HOST ER_MYSQL_PORT ER_MYSQL_USER ER_MYSQL_PASSWORD ER_MYSQL_DATABASE <<< "${_PARSED}" +fi + +: "${ER_MYSQL_HOST:?Set ER_MYSQL_HOST or mysql:// DATABASE_URL}" +: "${ER_MYSQL_USER:?Set ER_MYSQL_USER or DATABASE_URL}" +: "${ER_MYSQL_PASSWORD:?Set ER_MYSQL_PASSWORD or DATABASE_URL}" +: "${ER_MYSQL_DATABASE:?Set ER_MYSQL_DATABASE or DATABASE_URL}" +: "${ER_MYSQL_PORT:=3306}" + _run_sql() { - psql "${DATABASE_URL}" -v ON_ERROR_STOP=1 -f "$1" + mariadb -h "${ER_MYSQL_HOST}" -P "${ER_MYSQL_PORT}" -u "${ER_MYSQL_USER}" -p"${ER_MYSQL_PASSWORD}" "${ER_MYSQL_DATABASE}" < "$1" } -_run_sql "${_MIG}/20260322043000_create_error_reporting_core.up.sql" -_run_sql "${_MIG}/20260322044000_create_error_occurrences_and_states.up.sql" -_run_sql "${_MIG}/20260322044500_add_ingest_idempotency.up.sql" -_run_sql "${_MIG}/20260322045000_create_collectors_retention_and_audit.up.sql" -_run_sql "${_SEED}/dev_two_projects.sql" -_run_sql "${_SEED}/dev_collector_http_fixture.sql" +_run_sql "${_MIG_ER}/20260322043000_create_error_reporting_core.up.sql" +_run_sql "${_MIG_ER}/20260322044000_create_error_occurrences_and_states.up.sql" +_run_sql "${_MIG_ER}/20260322044500_add_ingest_idempotency.up.sql" +_run_sql "${_MIG_ER}/20260322045000_create_collectors_retention_and_audit.up.sql" +_run_sql "${_MIG_ADMIN}/001_admin_users.sql" +_run_sql "${_MIG_ADMIN}/002_admin_refresh_tokens.sql" +_run_sql "${_MIG_ADMIN}/003_audit_logs.sql" +_run_sql "${_MIG_ADMIN}/004_seed_superadmin.sql" +_run_sql "${_SEED_ER}/dev_two_projects.sql" +_run_sql "${_SEED_ER}/dev_collector_http_fixture.sql" echo "run-migrate: complete" diff --git a/deploy/lxc/verify.sh b/deploy/lxc/verify.sh index 7c9a5c1..c0c9468 100755 --- a/deploy/lxc/verify.sh +++ b/deploy/lxc/verify.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Smoke checks after install: Postgres reachability (optional) + ingest /health. +# Smoke checks after install: MariaDB reachability (optional) + ingest /health. set -euo pipefail _ENV_FILE="/etc/error-reporting/env" @@ -19,12 +19,25 @@ if ! curl -sf "${_INGEST_URL}" >/dev/null; then fi echo "verify: ingest OK" -if command -v pg_isready >/dev/null 2>&1 && [[ -n "${DATABASE_URL:-}" ]]; then - # pg_isready does not accept URI; probe TCP only when URL is simple localhost. - if [[ "${DATABASE_URL}" == *"@127.0.0.1:"* ]] || [[ "${DATABASE_URL}" == *"@localhost:"* ]]; then - echo "verify: pg_isready (best-effort, discrete vars may be needed on some hosts)" - _pgport="${PGPORT:-5432}" - pg_isready -h 127.0.0.1 -p "${_pgport}" || true +if command -v mariadb-admin >/dev/null 2>&1 && [[ -n "${DATABASE_URL:-}" ]]; then + if [[ "${DATABASE_URL}" == mysql://* || "${DATABASE_URL}" == mariadb://* ]]; then + _PARSED="$(python3 -c " +import os +from urllib.parse import urlparse, unquote +u = urlparse(os.environ['DATABASE_URL']) +if u.scheme not in ('mysql', 'mariadb', 'mysqli'): + raise SystemExit(0) +host = u.hostname or '127.0.0.1' +port = u.port or 3306 +user = unquote(u.username or '') +password = unquote(u.password or '') +print(host, port, user, password) +" 2>/dev/null)" || true + if [[ -n "${_PARSED}" ]]; then + read -r _h _p _u _pw <<< "${_PARSED}" + echo "verify: mariadb-admin ping (best-effort)" + mariadb-admin ping -h "${_h}" -P "${_p}" -u "${_u}" -p"${_pw}" --silent || true + fi fi fi diff --git a/docker-compose.yml b/docker-compose.yml index 0f774c5..bcb709e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,4 @@ -# BitReport error reporting — reproducible stack: Postgres, migrate (one-shot), ingest API, collector worker. +# BitReport error reporting — reproducible stack: MariaDB, migrate (one-shot), ingest API, collector worker. # Prerequisites: Docker Engine + Compose v2. # # Quick start: @@ -10,39 +10,42 @@ # Docs: docs/deployment/bitreport-error-reporting-compose-proxmox.md services: - postgres: - image: postgres:16-alpine + mariadb: + image: mariadb:11 environment: - POSTGRES_USER: ${ER_POSTGRES_USER:-postgres} - POSTGRES_PASSWORD: ${ER_POSTGRES_PASSWORD:-postgres} - POSTGRES_DB: ${ER_POSTGRES_DB:-error_reporting} + MARIADB_ROOT_PASSWORD: ${ER_MYSQL_ROOT_PASSWORD:-devrootchange} + MARIADB_DATABASE: ${ER_MYSQL_DATABASE:-error_reporting} + MARIADB_USER: ${ER_MYSQL_USER:-er_app} + MARIADB_PASSWORD: ${ER_MYSQL_PASSWORD:-er_app_secret} ports: - - "${ER_PUBLISH_PG_PORT:-5434}:5432" + - "${ER_PUBLISH_MYSQL_PORT:-3306}:3306" healthcheck: test: [ "CMD-SHELL", - "pg_isready -U ${ER_POSTGRES_USER:-postgres} -d ${ER_POSTGRES_DB:-error_reporting}", + "mariadb-admin ping -h 127.0.0.1 -u \"$$MARIADB_USER\" -p\"$$MARIADB_PASSWORD\" --silent", ] - interval: 3s - timeout: 3s - retries: 15 + interval: 5s + timeout: 5s + retries: 24 + start_period: 20s migrate: - image: postgres:16-alpine + image: mariadb:11 depends_on: - postgres: + mariadb: condition: service_healthy environment: - PGHOST: postgres - PGUSER: ${ER_POSTGRES_USER:-postgres} - PGPASSWORD: ${ER_POSTGRES_PASSWORD:-postgres} - PGDATABASE: ${ER_POSTGRES_DB:-error_reporting} + MARIADB_HOST: mariadb + MARIADB_USER: ${ER_MYSQL_USER:-er_app} + MARIADB_PASSWORD: ${ER_MYSQL_PASSWORD:-er_app_secret} + MARIADB_DATABASE: ${ER_MYSQL_DATABASE:-error_reporting} volumes: - - ./database/error_reporting/migrations:/migrations:ro - - ./database/error_reporting/seed:/seed:ro + - ./database/error_reporting/migrations:/migrations/error_reporting:ro + - ./database/error_reporting/seed:/seed/error_reporting:ro + - ./db/migrations:/migrations/admin:ro - ./scripts/docker-migrate.sh:/docker-migrate.sh:ro - entrypoint: ["/bin/sh", "/docker-migrate.sh"] + entrypoint: ["/bin/bash", "/docker-migrate.sh"] fixture-poll: image: nginx:alpine @@ -56,10 +59,10 @@ services: depends_on: migrate: condition: service_completed_successfully - postgres: + mariadb: condition: service_healthy environment: - DATABASE_URL: postgres://${ER_POSTGRES_USER:-postgres}:${ER_POSTGRES_PASSWORD:-postgres}@postgres:5432/${ER_POSTGRES_DB:-error_reporting} + DATABASE_URL: mysql://${ER_MYSQL_USER:-er_app}:${ER_MYSQL_PASSWORD:-er_app_secret}@mariadb:3306/${ER_MYSQL_DATABASE:-error_reporting} PORT: "3041" NODE_ENV: production INGEST_RATE_LIMIT_MAX: ${INGEST_RATE_LIMIT_MAX:-300} @@ -89,7 +92,7 @@ services: fixture-poll: condition: service_started environment: - DATABASE_URL: postgres://${ER_POSTGRES_USER:-postgres}:${ER_POSTGRES_PASSWORD:-postgres}@postgres:5432/${ER_POSTGRES_DB:-error_reporting} + DATABASE_URL: mysql://${ER_MYSQL_USER:-er_app}:${ER_MYSQL_PASSWORD:-er_app_secret}@mariadb:3306/${ER_MYSQL_DATABASE:-error_reporting} INGEST_BASE_URL: http://ingest-api:3041 TICK_INTERVAL_MS: ${TICK_INTERVAL_MS:-3000} SOURCE_REFRESH_MS: ${SOURCE_REFRESH_MS:-15000} diff --git a/docs/deployment/bitreport-error-reporting-compose-proxmox.md b/docs/deployment/bitreport-error-reporting-compose-proxmox.md index b43244f..b0fdb89 100644 --- a/docs/deployment/bitreport-error-reporting-compose-proxmox.md +++ b/docs/deployment/bitreport-error-reporting-compose-proxmox.md @@ -2,12 +2,12 @@ **Deploy sem Docker (LXC nativo, systemd):** ver [`bitreport-error-reporting-lxc-proxmox.md`](./bitreport-error-reporting-lxc-proxmox.md) e [`deploy/lxc/`](../deploy/lxc/). -Stack versionada em [`docker-compose.yml`](../docker-compose.yml) na raiz deste repositório: **PostgreSQL**, **migrate** (one-shot), **ingest-api** (app), **collector-worker** (worker), mais **fixture-poll** para o cenário de demo com fonte HTTP local. +Stack versionada em [`docker-compose.yml`](../docker-compose.yml) na raiz deste repositório: **MariaDB 11**, **migrate** (one-shot), **ingest-api** (app), **collector-worker** (worker), mais **fixture-poll** para o cenário de demo com fonte HTTP local. ## Pré-requisitos - Docker Engine 24+ e Docker Compose v2 (plugin `docker compose`), ou Podman Compose compatível. -- Portas livres no host (por omissão): **5434** → Postgres, **3041** → ingest API. Ajustáveis em `.env` (`ER_PUBLISH_*`). +- Portas livres no host (por omissão): **3306** → MariaDB, **3041** → ingest API. Ajustáveis em `.env` (`ER_PUBLISH_*`). ## Arranque reproduzível (qualquer ambiente) @@ -26,7 +26,7 @@ curl -sf "http://127.0.0.1:${ER_PUBLISH_INGEST_PORT:-3041}/health" **Logs úteis:** `docker compose logs -f ingest-api collector-worker` -**Recriar BD do zero** (apaga volumes se existirem; em ambiente novo basta remover o container/volume do Postgres): +**Recriar BD do zero** (apaga volumes se existirem; em ambiente novo basta remover o container/volume do MariaDB): ```bash docker compose down -v @@ -37,10 +37,11 @@ docker compose up --build | Variável | Onde | Descrição | |----------|------|-----------| -| `ER_POSTGRES_USER` | postgres, migrate, apps | Utilizador da BD | -| `ER_POSTGRES_PASSWORD` | idem | Palavra-passe (evitar `@`, `:`, `/` na URL ou usar encoding na `DATABASE_URL` manual) | -| `ER_POSTGRES_DB` | idem | Nome da base | -| `ER_PUBLISH_PG_PORT` | postgres | Porta no host → 5432 no container | +| `ER_MYSQL_ROOT_PASSWORD` | mariadb (init) | Palavra-passe do `root` no primeiro arranque | +| `ER_MYSQL_USER` | mariadb, migrate, apps | Utilizador da aplicação | +| `ER_MYSQL_PASSWORD` | idem | Palavra-passe (percent-encode na `DATABASE_URL` se tiver `@`, `:`, `/`, etc.) | +| `ER_MYSQL_DATABASE` | idem | Nome da base | +| `ER_PUBLISH_MYSQL_PORT` | mariadb | Porta no host → 3306 no container | | `ER_PUBLISH_INGEST_PORT` | ingest-api | Porta no host → API | | `ER_COLLECTOR_PROJECT_ALPHA_TOKEN` | collector-worker | Token do projeto de demo (alinhado com seed SQL) | | `INGEST_RATE_LIMIT_MAX` | ingest-api | Máx. pedidos por janela (opcional) | @@ -48,15 +49,15 @@ docker compose up --build | `TICK_INTERVAL_MS`, `SOURCE_REFRESH_MS`, `HTTP_FETCH_TIMEOUT_MS`, `MAX_BACKOFF_EXPONENT` | collector-worker | Intervalos e limites (opcional) | | `COLLECTOR_DEFAULT_INGEST_TOKEN` | collector-worker | Fallback para referências `env:VAR` vazias (opcional) | -A `DATABASE_URL` usada nos containers é construída pelo Compose a partir de `ER_POSTGRES_*`. Palavras-passe com caracteres especiais na URL PostgreSQL devem ser [percent-encoded](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING). +A `DATABASE_URL` usada nos containers é construída pelo Compose no formato `mysql://USER:PASSWORD@mariadb:3306/DATABASE`. Palavras-passe com caracteres especiais devem ser [percent-encoded](https://datatracker.ietf.org/doc/html/rfc3986#section-2.1). ## Proxmox (LXC ou VM) 1. **LXC com Docker:** ativar *nesting* no container (`features: nesting=1`) e instalar Docker como no Debian/Ubuntu oficial. Alternativa: VM com Docker — menos atrito com o kernel e cgroups. -2. **Recursos:** Postgres + Node para ingest + worker; para testes, 2 GB RAM e 2 vCPU costumam chegar; subir conforme carga. -3. **Armazenamento:** volume Docker ou bind mount em disco local rápido para `postgres` se quiseres persistência estável. -4. **Firewall (Proxmox / host):** em produção, **não** expor `ER_PUBLISH_PG_PORT` à Internet. Expor só o reverse proxy (80/443) ou VPN. -5. **Backups:** incluir volumes ou dumps (`pg_dump`) da base `ER_POSTGRES_DB`. +2. **Recursos:** MariaDB + Node para ingest + worker; para testes, 2 GB RAM e 2 vCPU costumam chegar; subir conforme carga. +3. **Armazenamento:** volume Docker ou bind mount em disco local rápido para `mariadb` se quiseres persistência estável. +4. **Firewall (Proxmox / host):** em produção, **não** expor `ER_PUBLISH_MYSQL_PORT` à Internet. Expor só o reverse proxy (80/443) ou VPN. +5. **Backups:** incluir volumes ou dumps lógicos (`mariadb-dump` / `mysqldump`) da base `ER_MYSQL_DATABASE`. ## Domínio externo, reverse proxy e TLS @@ -88,8 +89,8 @@ Ajustar `INGEST_RATE_LIMIT_*` se o tráfego passar por um único IP de proxy (po ## Produção — checklist rápido -- [ ] `ER_POSTGRES_PASSWORD` e tokens de projeto fortes e únicos. -- [ ] Postgres não publicado na Internet. +- [ ] `ER_MYSQL_PASSWORD`, `ER_MYSQL_ROOT_PASSWORD` e tokens de projeto fortes e únicos. +- [ ] MariaDB não publicado na Internet. - [ ] TLS terminado no proxy; redirecionamento HTTP → HTTPS. - [ ] `restart: unless-stopped` já no worker; política de restart para `ingest-api` alinhada com o vosso orchestrator. - [ ] Logs centralizados e alertas para falhas de healthcheck. diff --git a/docs/deployment/bitreport-error-reporting-lxc-proxmox.md b/docs/deployment/bitreport-error-reporting-lxc-proxmox.md index c675bdd..bdff28c 100644 --- a/docs/deployment/bitreport-error-reporting-lxc-proxmox.md +++ b/docs/deployment/bitreport-error-reporting-lxc-proxmox.md @@ -1,6 +1,6 @@ # Error reporting — LXC Proxmox (sem Docker) -Deploy nativo da stack na **raiz do repositório `errors.bitreport.pt`** num contentor **LXC** (Debian 12 ou Ubuntu 24.04 LTS, alinhado com o resto da infra BitReport): **PostgreSQL**, **Node.js 20+**, **systemd** para **ingest-api**, **admin-ui**, **collector-worker**, env em **`/etc/error-reporting/env`**, proxy TLS opcional com **nginx**. +Deploy nativo da stack na **raiz do repositório `errors.bitreport.pt`** num contentor **LXC** (Debian 12 ou Ubuntu 24.04 LTS, alinhado com o resto da infra BitReport): **MariaDB 10.11+** (ou MySQL 8+), **Node.js 20+**, **systemd** para **ingest-api**, **admin-ui**, **collector-worker**, env em **`/etc/error-reporting/env`**, proxy TLS opcional com **nginx**. Comparação com Compose: variáveis e ordem de migrações espelham [`bitreport-error-reporting-compose-proxmox.md`](./bitreport-error-reporting-compose-proxmox.md) e [`docker-compose.yml`](../docker-compose.yml). @@ -12,18 +12,18 @@ A versão actual da plataforma (**ingest-api**, **collector-worker**, **admin-ui | Opção | Quando usar | |-------|-------------| -| **Tudo num CT** | Staging, MVP, baixo tráfego: PostgreSQL + apps no mesmo LXC. | -| **PostgreSQL noutro CT** | Produção alinhada com padrão “DB dedicado”: definir `DATABASE_URL` com hostname interno do CT da base. | +| **Tudo num CT** | Staging, MVP, baixo tráfego: MariaDB + apps no mesmo LXC. | +| **MariaDB noutro CT** | Produção alinhada com padrão “DB dedicado”: definir `DATABASE_URL` com hostname interno do CT da base. | -**Recursos de partida:** 2 GB RAM, 2 vCPU (subir com carga). Disco rápido para PostgreSQL (`/var/lib/postgresql`). +**Recursos de partida:** 2 GB RAM, 2 vCPU (subir com carga). Disco rápido para dados InnoDB (`/var/lib/mysql`). -**Rede:** não expor a porta PostgreSQL à Internet; apenas 80/443 (proxy) ou VPN. +**Rede:** não expor a porta MariaDB (3306) à Internet; apenas 80/443 (proxy) ou VPN. ## 1. Proxmox — criar o LXC 1. Template **Debian 12** ou **Ubuntu 24.04** (mesma linha que os outros serviços). 2. Sem necessidade de **nesting** (não há Docker). -3. Activar backup do CT e incluir volumes de dados PostgreSQL nos backups ou `pg_dump` agendado. +3. Activar backup do CT e incluir volumes de dados MariaDB nos backups ou cópias lógicas (`mariadb-dump`) agendadas. ## 2. Pacotes base e Node.js 20 @@ -31,7 +31,7 @@ No CT (como root): ```bash apt-get update -apt-get install -y curl ca-certificates git postgresql postgresql-client nginx +apt-get install -y curl ca-certificates git mariadb-server mariadb-client nginx python3 # Node.js 20 LTS (exemplo NodeSource — confirmar URL actual em https://github.com/nodesource/distributions) curl -fsSL https://deb.nodesource.com/setup_20.x | bash - @@ -40,21 +40,24 @@ apt-get install -y nodejs node -v # v20.x ``` -## 3. PostgreSQL +## 3. MariaDB Criar utilizador e base (ajustar palavras-passe): ```bash -sudo -u postgres psql -v ON_ERROR_STOP=1 <<'SQL' -CREATE USER er_app WITH PASSWORD 'CHANGE_ME_STRONG'; -CREATE DATABASE error_reporting OWNER er_app; -GRANT ALL PRIVILEGES ON DATABASE error_reporting TO er_app; -SQL +mariadb -u root -p -e " +CREATE DATABASE IF NOT EXISTS error_reporting CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +CREATE USER IF NOT EXISTS 'er_app'@'localhost' IDENTIFIED BY 'CHANGE_ME_STRONG'; +GRANT ALL PRIVILEGES ON error_reporting.* TO 'er_app'@'localhost'; +FLUSH PRIVILEGES; +" ``` Construir `DATABASE_URL` (codificar caracteres especiais na password se necessário): -`postgres://er_app:CHANGE_ME_STRONG@127.0.0.1:5432/error_reporting` +`mysql://er_app:CHANGE_ME_STRONG@127.0.0.1:3306/error_reporting` + +Alternativa: definir `ER_MYSQL_HOST`, `ER_MYSQL_PORT`, `ER_MYSQL_USER`, `ER_MYSQL_PASSWORD`, `ER_MYSQL_DATABASE` e deixar `deploy/lxc/run-migrate.sh` derivar a ligação a partir de `DATABASE_URL` em formato `mysql://` (ver script). ## 4. Código no CT @@ -74,7 +77,7 @@ useradd --system --home /opt/errors.bitreport.pt --shell /usr/sbin/nologin error chown -R error-reporting:error-reporting /opt/errors.bitreport.pt ``` -O utilizador precisa de leitura em `database/error_reporting/` apenas para **correr migrações** (normalmente como root ou postgres com script); em runtime as apps só precisam de `ingest-api`, `admin-ui`, `collector-worker`. +O utilizador precisa de leitura em `database/error_reporting/` e `db/migrations/` apenas para **correr migrações** (normalmente como root com script); em runtime as apps só precisam de `ingest-api`, `admin-ui`, `collector-worker`. ## 6. Ficheiro de ambiente @@ -86,7 +89,7 @@ chown root:error-reporting /etc/error-reporting/env nano /etc/error-reporting/env # DATABASE_URL, ER_REPO_ROOT, tokens ``` -Editar pelo menos: `ER_REPO_ROOT`, `DATABASE_URL`, `INGEST_BASE_URL` (normalmente `http://127.0.0.1:3041`), `ERROR_REPORTING_ADMIN_API_BASE` (URL que o **Next.js** usa no servidor para falar com a API — em CT único, `http://127.0.0.1:3041`). +Editar pelo menos: `ER_REPO_ROOT`, `DATABASE_URL` (`mysql://...`), `INGEST_BASE_URL` (normalmente `http://127.0.0.1:3041`), `ERROR_REPORTING_ADMIN_API_BASE` (URL que o **Next.js** usa no servidor para falar com a API — em CT único, `http://127.0.0.1:3200` ou a porta onde corre o `api/`). ## 7. Dependências Node e build @@ -94,6 +97,7 @@ Editar pelo menos: `ER_REPO_ROOT`, `DATABASE_URL`, `INGEST_BASE_URL` (normalment cd /opt/errors.bitreport.pt/ingest-api && npm ci && npm run build cd /opt/errors.bitreport.pt/admin-ui && npm ci && npm run build cd /opt/errors.bitreport.pt/collector-worker && npm ci && npm run build +cd /opt/errors.bitreport.pt/api && npm ci && npm run build chown -R error-reporting:error-reporting /opt/errors.bitreport.pt ``` @@ -157,7 +161,7 @@ Colocar **nginx** (no host Proxmox, CT de proxy, ou o mesmo CT se política o pe ## 13. Checklist rápido (produção) - [ ] Palavras-passe e tokens fortes; `chmod 640` em `/etc/error-reporting/env`. -- [ ] PostgreSQL só na rede interna / localhost. +- [ ] MariaDB só na rede interna / localhost. - [ ] TLS no proxy; redireccionamento HTTP → HTTPS. - [ ] Logs (`journalctl`) e alertas para falhas de arranque. - [ ] Backups testados (BD + env cifrado na vault, não no Git). diff --git a/ingest-api/package-lock.json b/ingest-api/package-lock.json index f47318c..484e8de 100644 --- a/ingest-api/package-lock.json +++ b/ingest-api/package-lock.json @@ -13,11 +13,10 @@ "@fastify/swagger-ui": "^3.1.0", "dotenv": "^16.4.5", "fastify": "^4.28.1", - "pg": "^8.13.1" + "mysql2": "^3.11.5" }, "devDependencies": { "@types/node": "^22.9.0", - "@types/pg": "^8.11.10", "tsx": "^4.19.2", "typescript": "^5.6.3", "vitest": "^2.1.0" @@ -986,24 +985,11 @@ "version": "22.19.15", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz", "integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==", - "dev": true, "license": "MIT", "dependencies": { "undici-types": "~6.21.0" } }, - "node_modules/@types/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "pg-protocol": "*", - "pg-types": "^2.2.0" - } - }, "node_modules/@vitest/expect": { "version": "2.1.9", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz", @@ -1225,6 +1211,15 @@ "fastq": "^1.17.1" } }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1357,6 +1352,15 @@ "node": ">=6" } }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -1633,6 +1637,15 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, "node_modules/get-tsconfig": { "version": "4.13.6", "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz", @@ -1683,6 +1696,22 @@ "node": ">= 0.8" } }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -1707,6 +1736,12 @@ "node": ">=8" } }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "license": "MIT" + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -1771,6 +1806,12 @@ "set-cookie-parser": "^2.4.1" } }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/loupe": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", @@ -1784,6 +1825,21 @@ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", "license": "ISC" }, + "node_modules/lru.min": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz", + "integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -1836,6 +1892,40 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/mysql2": { + "version": "3.20.0", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.20.0.tgz", + "integrity": "sha512-eCLUs7BNbgA6nf/MZXsaBO1SfGs0LtLVrJD3WeWq+jPLDWkSufTD+aGMwykfUVPdZnblaUK1a8G/P63cl9FkKg==", + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.2", + "denque": "^2.1.0", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.2", + "long": "^5.3.2", + "lru.min": "^1.1.4", + "named-placeholders": "^1.1.6", + "sql-escaper": "^1.3.3" + }, + "engines": { + "node": ">= 8.0" + }, + "peerDependencies": { + "@types/node": ">= 8" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "license": "MIT", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/nanoid": { "version": "3.3.11", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", @@ -1918,95 +2008,6 @@ "node": ">= 14.16" } }, - "node_modules/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", - "license": "MIT", - "dependencies": { - "pg-connection-string": "^2.12.0", - "pg-pool": "^3.13.0", - "pg-protocol": "^1.13.0", - "pg-types": "2.2.0", - "pgpass": "1.0.5" - }, - "engines": { - "node": ">= 16.0.0" - }, - "optionalDependencies": { - "pg-cloudflare": "^1.3.0" - }, - "peerDependencies": { - "pg-native": ">=3.0.1" - }, - "peerDependenciesMeta": { - "pg-native": { - "optional": true - } - } - }, - "node_modules/pg-cloudflare": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz", - "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==", - "license": "MIT", - "optional": true - }, - "node_modules/pg-connection-string": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz", - "integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==", - "license": "MIT" - }, - "node_modules/pg-int8": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", - "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", - "license": "ISC", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/pg-pool": { - "version": "3.13.0", - "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz", - "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==", - "license": "MIT", - "peerDependencies": { - "pg": ">=8.0" - } - }, - "node_modules/pg-protocol": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz", - "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==", - "license": "MIT" - }, - "node_modules/pg-types": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", - "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", - "license": "MIT", - "dependencies": { - "pg-int8": "1.0.1", - "postgres-array": "~2.0.0", - "postgres-bytea": "~1.0.0", - "postgres-date": "~1.0.4", - "postgres-interval": "^1.1.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/pgpass": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", - "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", - "license": "MIT", - "dependencies": { - "split2": "^4.1.0" - } - }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -2096,45 +2097,6 @@ "node": "^10 || ^12 || >=14" } }, - "node_modules/postgres-array": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", - "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/postgres-bytea": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", - "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-date": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", - "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-interval": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", - "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", - "license": "MIT", - "dependencies": { - "xtend": "^4.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/process-warning": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz", @@ -2305,6 +2267,12 @@ "node": ">=10" } }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, "node_modules/secure-json-parse": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz", @@ -2403,6 +2371,21 @@ "node": ">= 10.x" } }, + "node_modules/sql-escaper": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.3.3.tgz", + "integrity": "sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=2.0.0", + "node": ">=12.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -2631,7 +2614,6 @@ "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, "license": "MIT" }, "node_modules/uri-js": { @@ -3345,15 +3327,6 @@ "node": ">=8" } }, - "node_modules/xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "license": "MIT", - "engines": { - "node": ">=0.4" - } - }, "node_modules/yaml": { "version": "2.8.3", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz", diff --git a/ingest-api/package.json b/ingest-api/package.json index 3c650dc..df40f9f 100644 --- a/ingest-api/package.json +++ b/ingest-api/package.json @@ -18,11 +18,10 @@ "@fastify/swagger-ui": "^3.1.0", "dotenv": "^16.4.5", "fastify": "^4.28.1", - "pg": "^8.13.1" + "mysql2": "^3.11.5" }, "devDependencies": { "@types/node": "^22.9.0", - "@types/pg": "^8.11.10", "tsx": "^4.19.2", "typescript": "^5.6.3", "vitest": "^2.1.0" diff --git a/ingest-api/src/buildApp.ts b/ingest-api/src/buildApp.ts index 0f6e14e..21cba36 100644 --- a/ingest-api/src/buildApp.ts +++ b/ingest-api/src/buildApp.ts @@ -4,7 +4,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import swagger from "@fastify/swagger"; import swaggerUi from "@fastify/swagger-ui"; import rateLimit from "@fastify/rate-limit"; -import type { Pool } from "pg"; +import type { Pool } from "mysql2/promise"; import type { IngestEnv } from "./config/env.js"; import { sha256Hex } from "./lib/hash.js"; import { attachIngestAuth } from "./services/ingestAuth.js"; diff --git a/ingest-api/src/integration.twoProjects.test.ts b/ingest-api/src/integration.twoProjects.test.ts index 399966d..a20b682 100644 --- a/ingest-api/src/integration.twoProjects.test.ts +++ b/ingest-api/src/integration.twoProjects.test.ts @@ -1,5 +1,6 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import pg from "pg"; +import mysql from "mysql2/promise"; +import type { RowDataPacket } from "mysql2"; import { buildApp } from "./buildApp.js"; import type { IngestEnv } from "./config/env.js"; import { sha256Hex } from "./lib/hash.js"; @@ -7,7 +8,7 @@ import { sha256Hex } from "./lib/hash.js"; const _testUrl = process.env.ERROR_REPORTING_TEST_DATABASE_URL; describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => { - let _pool: pg.Pool; + let _pool: mysql.Pool; let _app: Awaited>; const _tokenA = "er_tst_a_secret_one"; const _tokenB = "er_tst_b_secret_two"; @@ -15,31 +16,38 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => { let _projectIdB = ""; beforeAll(async () => { - _pool = new pg.Pool({ connectionString: _testUrl, max: 4 }); - await _pool.query(` - TRUNCATE TABLE - er_ingest_idempotency, - er_occurrence_events, - er_incidents, - er_ingest_keys, - er_projects - RESTART IDENTITY CASCADE - `); - const _p = await _pool.query<{ id: string }>( - `INSERT INTO er_projects (slug, name) VALUES ('pa', 'Project A'), ('pb', 'Project B') - RETURNING id::text`, + _pool = mysql.createPool({ uri: _testUrl!, connectionLimit: 4, waitForConnections: true }); + const _c = await _pool.getConnection(); + try { + await _c.query("SET FOREIGN_KEY_CHECKS = 0"); + await _c.query(`TRUNCATE TABLE er_ingest_idempotency`); + await _c.query(`TRUNCATE TABLE er_incident_occurrences`); + await _c.query(`TRUNCATE TABLE er_incidents`); + await _c.query(`TRUNCATE TABLE er_ingest_keys`); + await _c.query(`TRUNCATE TABLE er_projects`); + await _c.query("SET FOREIGN_KEY_CHECKS = 1"); + } finally { + _c.release(); + } + await _pool.execute(`INSERT INTO er_projects (slug, name) VALUES ('pa', 'Project A')`); + await _pool.execute(`INSERT INTO er_projects (slug, name) VALUES ('pb', 'Project B')`); + const [rows] = await _pool.execute( + `SELECT CAST(id AS CHAR) AS id, slug FROM er_projects WHERE slug IN ('pa', 'pb') ORDER BY slug`, ); - const _rows = _p.rows; - if (_rows.length < 2) { + if (rows.length < 2) { throw new Error("seed projects failed"); } - _projectIdA = _rows[0]?.id ?? ""; - _projectIdB = _rows[1]?.id ?? ""; - await _pool.query( + _projectIdA = String((rows[0] as { id: string }).id); + _projectIdB = String((rows[1] as { id: string }).id); + await _pool.execute( `INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status) - VALUES ($1::bigint, 'default', 'tok_pr_a', $2, 'active'), - ($3::bigint, 'default', 'tok_pr_b', $4, 'active')`, - [_projectIdA, sha256Hex(_tokenA), _projectIdB, sha256Hex(_tokenB)], + VALUES (?, 'default', 'tok_pr_a', ?, 'active')`, + [_projectIdA, sha256Hex(_tokenA)], + ); + await _pool.execute( + `INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status) + VALUES (?, 'default', 'tok_pr_b', ?, 'active')`, + [_projectIdB, sha256Hex(_tokenB)], ); const _env: IngestEnv = { PORT: 0, @@ -104,16 +112,16 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => { expect(_bodyB.results[0]?.fingerprint).toBe("fp-b-1"); expect(_bodyB.results[0]?.incident_id).not.toBe(_bodyA.results[0]?.incident_id); - const _check = await _pool.query<{ c: string }>( - `SELECT COUNT(*)::text AS c FROM er_incidents WHERE project_id = $1::bigint`, + const [checkA] = await _pool.execute( + `SELECT COUNT(*) AS c FROM er_incidents WHERE project_id = ?`, [_projectIdA], ); - expect(_check.rows[0]?.c).toBe("1"); - const _checkB = await _pool.query<{ c: string }>( - `SELECT COUNT(*)::text AS c FROM er_incidents WHERE project_id = $1::bigint`, + expect(Number((checkA[0] as { c: number }).c)).toBe(1); + const [checkB] = await _pool.execute( + `SELECT COUNT(*) AS c FROM er_incidents WHERE project_id = ?`, [_projectIdB], ); - expect(_checkB.rows[0]?.c).toBe("1"); + expect(Number((checkB[0] as { c: number }).c)).toBe(1); }); it("replays identical idempotent requests", async () => { @@ -147,8 +155,10 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => { }); expect(_second.statusCode).toBe(200); expect(_second.body).toBe(_first.body); - const _occ = await _pool.query(`SELECT COUNT(*)::int AS c FROM er_occurrence_events`); - expect(_occ.rows[0]?.c).toBe(3); + const [occ] = await _pool.execute( + `SELECT COUNT(*) AS c FROM er_incident_occurrences`, + ); + expect(Number((occ[0] as { c: number }).c)).toBe(3); }); it("returns 409 when idempotency key is reused with a different body", async () => { diff --git a/ingest-api/src/server.ts b/ingest-api/src/server.ts index b7824c4..f1d7e1e 100644 --- a/ingest-api/src/server.ts +++ b/ingest-api/src/server.ts @@ -1,12 +1,13 @@ -import pg from "pg"; +import mysql from "mysql2/promise"; import { loadEnv } from "./config/env.js"; import { buildApp } from "./buildApp.js"; const _env = loadEnv(); -const _pool = new pg.Pool({ - connectionString: _env.DATABASE_URL, - max: 16, - idleTimeoutMillis: 30_000, +const _pool = mysql.createPool({ + uri: _env.DATABASE_URL, + connectionLimit: 16, + waitForConnections: true, + enableKeepAlive: true, }); const _app = await buildApp({ env: _env, pool: _pool }); diff --git a/ingest-api/src/services/ingestAuth.ts b/ingest-api/src/services/ingestAuth.ts index 406ae12..8365b66 100644 --- a/ingest-api/src/services/ingestAuth.ts +++ b/ingest-api/src/services/ingestAuth.ts @@ -1,4 +1,5 @@ -import type { Pool } from "pg"; +import type { Pool } from "mysql2/promise"; +import type { RowDataPacket } from "mysql2"; import type { FastifyReply, FastifyRequest } from "fastify"; import { sha256Hex } from "../lib/hash.js"; @@ -35,26 +36,23 @@ export async function attachIngestAuth( return; } const _hash = sha256Hex(_token); - const _result = await pool.query<{ - id: string; - project_id: string; - }>( - `SELECT id::text, project_id::text + const [rows] = await pool.execute( + `SELECT CAST(id AS CHAR) AS id, CAST(project_id AS CHAR) AS project_id FROM er_ingest_keys - WHERE token_hash = $1 + WHERE token_hash = ? AND status = 'active' AND revoked_at IS NULL - AND (expires_at IS NULL OR expires_at > NOW())`, + AND (expires_at IS NULL OR expires_at > NOW(6))`, [_hash], ); - if (_result.rowCount === 0) { + if (rows.length === 0) { await reply.status(401).send({ error: "unauthorized", message: "Invalid or inactive ingest key.", }); return; } - const _row = _result.rows[0]; + const _row = rows[0] as { id: string; project_id: string }; if (!_row) { await reply.status(401).send({ error: "unauthorized", diff --git a/ingest-api/src/services/processIngestBatch.ts b/ingest-api/src/services/processIngestBatch.ts index 15e9f23..b0bfeca 100644 --- a/ingest-api/src/services/processIngestBatch.ts +++ b/ingest-api/src/services/processIngestBatch.ts @@ -1,4 +1,5 @@ -import type { Pool, PoolClient } from "pg"; +import type { Pool, PoolConnection } from "mysql2/promise"; +import type { ResultSetHeader, RowDataPacket } from "mysql2"; import { stableJsonHash } from "../lib/hash.js"; import { computeFingerprint, @@ -23,6 +24,23 @@ export type IngestResultItem = { fingerprint: string; }; +function _parseStoredJson(raw: unknown): unknown { + if (raw === null || raw === undefined) { + return raw; + } + if (typeof raw === "object") { + return raw; + } + if (typeof raw === "string") { + try { + return JSON.parse(raw) as unknown; + } catch { + return raw; + } + } + return raw; +} + export async function processIngestBatch(input: { pool: Pool; ingestKeyId: string; @@ -31,25 +49,25 @@ export async function processIngestBatch(input: { idempotencyKey: string | null; bodyHash: string; }): Promise<{ status: 200 | 409; body: unknown }> { - const _client = await input.pool.connect(); + const _client = await input.pool.getConnection(); try { - await _client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); + await _client.query("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED"); + await _client.beginTransaction(); if (input.idempotencyKey !== null) { - const _existing = await _client.query<{ - body_hash: string; - response_json: unknown; - http_status: number; - }>( + const [rows] = await _client.execute( `SELECT body_hash, response_json, http_status FROM er_ingest_idempotency - WHERE ingest_key_id = $1::bigint - AND idempotency_key = $2`, + WHERE ingest_key_id = ? + AND idempotency_key = ? + LIMIT 1`, [input.ingestKeyId, input.idempotencyKey], ); - const _row0 = _existing.rows[0]; + const _row0 = rows[0] as + | { body_hash: string; response_json: unknown; http_status: number } + | undefined; if (_row0) { if (_row0.body_hash !== input.bodyHash) { - await _client.query("ROLLBACK"); + await _client.rollback(); return { status: 409, body: { @@ -59,8 +77,8 @@ export async function processIngestBatch(input: { }, }; } - await _client.query("COMMIT"); - return { status: 200, body: _row0.response_json }; + await _client.commit(); + return { status: 200, body: _parseStoredJson(_row0.response_json) }; } } @@ -79,12 +97,13 @@ export async function processIngestBatch(input: { if (input.idempotencyKey !== null) { const _firstIncidentId = _results[0]?.incident_id; if (typeof _firstIncidentId === "string") { - await _client.query( + await _client.execute( `INSERT INTO er_ingest_idempotency ( - ingest_key_id, idempotency_key, body_hash, incident_id, http_status, response_json - ) VALUES ($1::bigint, $2, $3, $4::bigint, 200, $5::jsonb)`, + ingest_key_id, project_id, idempotency_key, body_hash, incident_id, http_status, response_json + ) VALUES (?, ?, ?, ?, ?, 200, ?)`, [ input.ingestKeyId, + input.projectId, input.idempotencyKey, input.bodyHash, _firstIncidentId, @@ -94,15 +113,14 @@ export async function processIngestBatch(input: { } } - await _client.query( - `UPDATE er_ingest_keys SET last_used_at = NOW() WHERE id = $1::bigint`, - [input.ingestKeyId], - ); + await _client.execute(`UPDATE er_ingest_keys SET last_used_at = NOW(6) WHERE id = ?`, [ + input.ingestKeyId, + ]); - await _client.query("COMMIT"); + await _client.commit(); return { status: 200, body: _responseBody }; } catch (_err) { - await _client.query("ROLLBACK"); + await _client.rollback(); throw _err; } finally { _client.release(); @@ -110,7 +128,7 @@ export async function processIngestBatch(input: { } async function _ingestOneEvent( - client: PoolClient, + client: PoolConnection, input: { ingestKeyId: string; projectId: string; event: IngestEventInput }, ): Promise { const _ev = input.event; @@ -131,34 +149,33 @@ async function _ingestOneEvent( const _stack = typeof _ev.stacktrace === "string" ? _ev.stacktrace : null; const _context = _ev.context && typeof _ev.context === "object" ? _ev.context : null; - const _incident = await client.query<{ id: string }>( + await client.execute( `INSERT INTO er_incidents ( project_id, fingerprint, title, severity, first_seen_at, last_seen_at, occurrences_count, last_ingest_key_id - ) VALUES ( - $1::bigint, $2, $3, $4, $5::timestamp, $5::timestamp, 1, $6::bigint - ) - ON CONFLICT (project_id, fingerprint) DO UPDATE SET - last_seen_at = EXCLUDED.last_seen_at, + ) VALUES (?, ?, ?, ?, ?, ?, 1, ?) + ON DUPLICATE KEY UPDATE + last_seen_at = VALUES(last_seen_at), occurrences_count = er_incidents.occurrences_count + 1, - last_ingest_key_id = EXCLUDED.last_ingest_key_id, - updated_at = CURRENT_TIMESTAMP - RETURNING id::text`, - [input.projectId, _fingerprint, _title, _severity, _occurred, input.ingestKeyId], + last_ingest_key_id = VALUES(last_ingest_key_id), + updated_at = CURRENT_TIMESTAMP(6)`, + [input.projectId, _fingerprint, _title, _severity, _occurred, _occurred, input.ingestKeyId], ); - const _incidentRow = _incident.rows[0]; + + const [incRows] = await client.execute( + `SELECT CAST(id AS CHAR) AS id FROM er_incidents WHERE project_id = ? AND fingerprint = ? LIMIT 1`, + [input.projectId, _fingerprint], + ); + const _incidentRow = incRows[0] as { id: string } | undefined; if (!_incidentRow) { throw new Error("incident_upsert_failed"); } - const _occ = await client.query<{ id: string }>( - `INSERT INTO er_occurrence_events ( + const [occHeader] = await client.execute( + `INSERT INTO er_incident_occurrences ( project_id, incident_id, ingest_key_id, occurred_at, level_raw, severity, - message, stacktrace, context_json, schema_version - ) VALUES ( - $1::bigint, $2::bigint, $3::bigint, $4::timestamptz, $5, $6, $7, $8, $9::jsonb, $10 - ) - RETURNING id::text`, + message, stack_trace, context_json, schema_version, environment + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'production')`, [ input.projectId, _incidentRow.id, @@ -172,14 +189,17 @@ async function _ingestOneEvent( _ev.schema_version, ], ); - const _occRow = _occ.rows[0]; - if (!_occRow) { + const _occId = occHeader.insertId; + if (typeof _occId !== "bigint" && typeof _occId !== "number") { + throw new Error("occurrence_insert_failed"); + } + if (Number(_occId) <= 0) { throw new Error("occurrence_insert_failed"); } return { incident_id: _incidentRow.id, - occurrence_id: _occRow.id, + occurrence_id: String(_occId), fingerprint: _fingerprint, }; } diff --git a/scripts/docker-migrate.sh b/scripts/docker-migrate.sh index a600142..30b517a 100755 --- a/scripts/docker-migrate.sh +++ b/scripts/docker-migrate.sh @@ -1,23 +1,32 @@ -#!/bin/sh -set -eu +#!/usr/bin/env bash +# Apply error_reporting + admin SQL migrations and error_reporting seeds (Compose one-shot). +set -euo pipefail -: "${PGHOST:=postgres}" -: "${PGUSER:=postgres}" -: "${PGDATABASE:=error_reporting}" +: "${MARIADB_HOST:=mariadb}" +: "${MARIADB_USER:?MARIADB_USER required}" +: "${MARIADB_PASSWORD:?MARIADB_PASSWORD required}" +: "${MARIADB_DATABASE:?MARIADB_DATABASE required}" -until pg_isready -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE"; do +echo "docker-migrate: waiting for ${MARIADB_HOST}..." +until mariadb-admin ping -h "${MARIADB_HOST}" -u "${MARIADB_USER}" -p"${MARIADB_PASSWORD}" --silent; do sleep 1 done -_run_sql() { - psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -v ON_ERROR_STOP=1 -f "$1" +_run_sql_file() { + _path="$1" + echo "docker-migrate: applying ${_path}" + mariadb -h "${MARIADB_HOST}" -u "${MARIADB_USER}" -p"${MARIADB_PASSWORD}" "${MARIADB_DATABASE}" < "${_path}" } -_run_sql "/migrations/20260322043000_create_error_reporting_core.up.sql" -_run_sql "/migrations/20260322044000_create_error_occurrences_and_states.up.sql" -_run_sql "/migrations/20260322044500_add_ingest_idempotency.up.sql" -_run_sql "/migrations/20260322045000_create_collectors_retention_and_audit.up.sql" -_run_sql "/seed/dev_two_projects.sql" -_run_sql "/seed/dev_collector_http_fixture.sql" +_run_sql_file "/migrations/error_reporting/20260322043000_create_error_reporting_core.up.sql" +_run_sql_file "/migrations/error_reporting/20260322044000_create_error_occurrences_and_states.up.sql" +_run_sql_file "/migrations/error_reporting/20260322044500_add_ingest_idempotency.up.sql" +_run_sql_file "/migrations/error_reporting/20260322045000_create_collectors_retention_and_audit.up.sql" +_run_sql_file "/migrations/admin/001_admin_users.sql" +_run_sql_file "/migrations/admin/002_admin_refresh_tokens.sql" +_run_sql_file "/migrations/admin/003_audit_logs.sql" +_run_sql_file "/migrations/admin/004_seed_superadmin.sql" +_run_sql_file "/seed/error_reporting/dev_two_projects.sql" +_run_sql_file "/seed/error_reporting/dev_collector_http_fixture.sql" echo "docker-migrate: complete" diff --git a/scripts/run-mysql-migrations.sh b/scripts/run-mysql-migrations.sh new file mode 100755 index 0000000..ed83b0c --- /dev/null +++ b/scripts/run-mysql-migrations.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Run SQL migrations from repo root (same files as docker-migrate.sh). Requires mariadb client. +# Usage from errors.bitreport.pt root: +# ER_MYSQL_HOST=127.0.0.1 ER_MYSQL_USER=... ER_MYSQL_PASSWORD=... ER_MYSQL_DATABASE=... ./scripts/run-mysql-migrations.sh +# Or set DATABASE_URL=mysql://user:pass@host:port/db +set -euo pipefail + +_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "${_ROOT}" + +if [[ -n "${DATABASE_URL:-}" ]] && [[ "${DATABASE_URL}" == mysql://* || "${DATABASE_URL}" == mariadb://* ]]; then + _PARSED="$(python3 -c " +import os +from urllib.parse import urlparse, unquote +u = urlparse(os.environ['DATABASE_URL']) +if u.scheme not in ('mysql', 'mariadb', 'mysqli'): + raise SystemExit('DATABASE_URL must be mysql:// or mariadb://') +host = u.hostname or '127.0.0.1' +port = u.port or 3306 +user = unquote(u.username or '') +password = unquote(u.password or '') +db = (u.path or '/').lstrip('/').split('?')[0] +print(host, port, user, password, db) +")" + read -r ER_MYSQL_HOST ER_MYSQL_PORT ER_MYSQL_USER ER_MYSQL_PASSWORD ER_MYSQL_DATABASE <<< "${_PARSED}" +fi + +: "${ER_MYSQL_HOST:?ER_MYSQL_HOST or mysql DATABASE_URL required}" +: "${ER_MYSQL_USER:?ER_MYSQL_USER required}" +: "${ER_MYSQL_PASSWORD:?ER_MYSQL_PASSWORD required}" +: "${ER_MYSQL_DATABASE:?ER_MYSQL_DATABASE required}" +: "${ER_MYSQL_PORT:=3306}" + +_run() { + echo "run-mysql-migrations: $1" + mariadb -h "${ER_MYSQL_HOST}" -P "${ER_MYSQL_PORT}" -u "${ER_MYSQL_USER}" -p"${ER_MYSQL_PASSWORD}" "${ER_MYSQL_DATABASE}" < "$1" +} + +_run "${_ROOT}/database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql" +_run "${_ROOT}/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql" +_run "${_ROOT}/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql" +_run "${_ROOT}/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql" +_run "${_ROOT}/db/migrations/001_admin_users.sql" +_run "${_ROOT}/db/migrations/002_admin_refresh_tokens.sql" +_run "${_ROOT}/db/migrations/003_audit_logs.sql" +_run "${_ROOT}/db/migrations/004_seed_superadmin.sql" +_run "${_ROOT}/database/error_reporting/seed/dev_two_projects.sql" +_run "${_ROOT}/database/error_reporting/seed/dev_collector_http_fixture.sql" + +echo "run-mysql-migrations: complete"