From 36cd1d6005bef060c776775efe0f628a5a81b7b9 Mon Sep 17 00:00:00 2001 From: Alban Mouton Date: Tue, 10 Nov 2026 10:03:21 +0100 Subject: [PATCH] feat!: unified structured logger from lib-node 3 - @data-fair/lib-node ^3.0.0, @data-fair/lib-express ^2.0.0, pino-pretty in dev - console and internalError replaced by log from @data-fair/lib-node/log.js, error for internal failures only, upstream and owner-reported situations as warn - the worker runs each task in a log context (catalogId, taskType, importId / publicationId, owner fields from shared/log-fields.ts) - eslint no-console on api, worker and shared server code - logging conventions in AGENTS.md BREAKING CHANGE: logs are JSON lines on stdout in production, identified by their code field, log routes matching the old output must be adapted. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 22 ++ api/index.ts | 9 +- api/package.json | 4 +- api/src/misc/routers/datasets.ts | 7 +- api/src/server.ts | 3 +- eslint.config.mjs | 7 +- package-lock.json | 321 +++++++++++++++++- package.json | 3 +- shared/log-fields.ts | 29 ++ tests/features/shared/log-fields.unit.spec.ts | 22 ++ worker/index.ts | 11 +- worker/package.json | 2 +- worker/src/lib/import.ts | 6 +- worker/src/lib/internal-error.ts | 15 - worker/src/lib/publication.ts | 17 +- worker/src/worker.ts | 21 +- 16 files changed, 441 insertions(+), 58 deletions(-) create mode 100644 shared/log-fields.ts create mode 100644 tests/features/shared/log-fields.unit.spec.ts delete mode 100644 worker/src/lib/internal-error.ts diff --git a/AGENTS.md b/AGENTS.md index 9b6c095..6b8ee1c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -134,3 +134,25 @@ npm run check-types # TypeScript npm run build-types # generate type definitions from JSON schemas npm -w ui run build # build the Vue SPA ``` + +## Logging + +Server code (`api/`, `worker/`, `shared/`) logs through `import log from '@data-fair/lib-node/log.js'` +(pino: JSON on stdout in production, pretty in dev); the full API is in the "Logging" section of the +`@data-fair/lib-node` README. eslint `no-console` applies to `api/src/**`, `worker/src/**`, `shared/**` and the +two `index.ts`; `api/scripts/` keep `console`. + +- `log.info|warn|alert|error(msg, { code?, err?, ...fields })`: `code` is a **static string**, ids go in their + own fields, the error in `err`, never in the message. +- `error` is for internal failures only (counted in `df_logs`, alerting). Client errors, upstream failures + (a remote catalog, a plugin removed from the registry) and situations reported to the owner on the + task (lost permissions, missing publication site) are `warn`. +- The actor (ip, host, userId, accountKey...) is never passed by hand: `session.middleware()` opens the + request log context. The owner of a catalog, import or publication uses the `owner*` names + (`ownerLogFields` in `shared/log-fields.ts`). +- The worker runs each task in `withLogContext(taskLogFields(task, type))` (`catalogId`, `taskType`, + `importId` / `publicationId`, owner), so every line below it, plugin code included, carries the task. + The plugin is loaded before entering that context, its lines pass the fields explicitly. +- `debug` call sites are unchanged; their output is redirected into the logger. +- Task logs shown in the UI (`worker/src/lib/logs.ts`, the `log` given to plugins) are a separate thing, + stored on the import / publication document. diff --git a/api/index.ts b/api/index.ts index f005ffa..edad487 100644 --- a/api/index.ts +++ b/api/index.ts @@ -1,17 +1,18 @@ +import log from '@data-fair/lib-node/log.js' import { start, stop } from './src/server.ts' start().then(() => {}, err => { - console.error('Failure while starting service', err) + log.error('failure while starting the service', { code: 'start-process', err }) process.exit(1) }) process.on('SIGTERM', function onSigterm () { - console.info('Received SIGTERM signal, shutdown gracefully...') + log.info('received SIGTERM signal, shutting down gracefully...') stop().then(() => { - console.log('shutting down now') + log.info('shutting down now') process.exit() }, err => { - console.error('Failure while stopping service', err) + log.error('failure while stopping the service', { code: 'stop-process', err }) process.exit(1) }) }) diff --git a/api/package.json b/api/package.json index 45101fb..b309ba2 100644 --- a/api/package.json +++ b/api/package.json @@ -20,8 +20,8 @@ }, "dependencies": { "@data-fair/catalogs-shared": "*", - "@data-fair/lib-express": "^1.31.0", - "@data-fair/lib-node": "^2.16.1", + "@data-fair/lib-express": "^2.0.0", + "@data-fair/lib-node": "^3.0.0", "@data-fair/lib-node-registry": "^0.7.2", "@data-fair/lib-utils": "^1.10.1", "config": "^5.0.1", diff --git a/api/src/misc/routers/datasets.ts b/api/src/misc/routers/datasets.ts index 653a56e..e1baaf3 100644 --- a/api/src/misc/routers/datasets.ts +++ b/api/src/misc/routers/datasets.ts @@ -3,7 +3,7 @@ import Debug from 'debug' import { Router } from 'express' import { assertReqInternalSecret } from '@data-fair/lib-express' -import { internalError } from '@data-fair/lib-node/observer.js' +import log from '@data-fair/lib-node/log.js' import mongo from '#mongo' import config from '#config' @@ -16,8 +16,9 @@ router.post('/', async (req, res) => { assertReqInternalSecret(req, config.secretKeys.catalogs) debug('Incoming data fair webhook for datasets update/delete', req.body) - if (!req.body.update || !req.body.delete) { // Non blocking error - internalError('catalogs-data-fair-webhook', 'Missing datasets in request body') + // non blocking, a malformed call of the caller is not an internal failure + if (!req.body.update || !req.body.delete) { + log.warn('data-fair webhook without update or delete datasets lists', { code: 'catalogs-data-fair-webhook' }) } await mongo.publications.updateMany( diff --git a/api/src/server.ts b/api/src/server.ts index fa813cd..577deb9 100644 --- a/api/src/server.ts +++ b/api/src/server.ts @@ -6,6 +6,7 @@ import * as wsServer from '@data-fair/lib-express/ws-server.js' import { init as wsEmitterInit } from '@data-fair/lib-node/ws-emitter.js' import eventsQueue from '@data-fair/lib-node/events-queue.js' import { startObserver, stopObserver } from '@data-fair/lib-node/observer.js' +import log from '@data-fair/lib-node/log.js' import { createHttpTerminator } from 'http-terminator' import http from 'http' import config from '#config' @@ -58,7 +59,7 @@ export const start = async () => { server.listen(config.port) await new Promise(resolve => server.once('listening', resolve)) - console.log(`API server listening on port ${config.port}`) + log.info(`API server listening on port ${config.port}`) } export const stop = async () => { diff --git a/eslint.config.mjs b/eslint.config.mjs index 187ca83..b8c0ea1 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -4,5 +4,10 @@ import dfLibRecommended from '@data-fair/lib-utils/eslint/recommended.js' export default [ { ignores: ['ui/', '**/.type/', 'data/'] }, ...dfLibRecommended, - ...neostandard({ ts: true }) + ...neostandard({ ts: true }), + { + // server code logs through @data-fair/lib-node/log.js (its README, "Logging"), api/scripts/ keep console + files: ['api/src/**/*.ts', 'api/index.ts', 'worker/src/**/*.ts', 'worker/index.ts', 'shared/**/*.ts'], + rules: { 'no-console': 'error' } + } ] diff --git a/package-lock.json b/package-lock.json index 5ec9d04..4c7323e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,7 +23,7 @@ "@commitlint/config-conventional": "^21.2.3", "@data-fair/lib-agents-sim": "^0.11.0", "@data-fair/lib-dev": "^0.1.1", - "@data-fair/lib-node": "^2.16.1", + "@data-fair/lib-node": "^3.0.0", "@data-fair/lib-utils": "^1.14.0", "@json-layout/core": "~2.12.1", "@modelcontextprotocol/sdk": "^1.32.1", @@ -40,6 +40,7 @@ "husky": "^9.1.7", "neostandard": "^0.14.1", "nodemon": "^3.1.10", + "pino-pretty": "^13.2.0", "tough-cookie": "^5.0.0", "typescript": "^6.0.3" }, @@ -50,8 +51,8 @@ "api": { "dependencies": { "@data-fair/catalogs-shared": "*", - "@data-fair/lib-express": "^1.31.0", - "@data-fair/lib-node": "^2.16.1", + "@data-fair/lib-express": "^2.0.0", + "@data-fair/lib-node": "^3.0.0", "@data-fair/lib-node-registry": "^0.7.2", "@data-fair/lib-utils": "^1.10.1", "config": "^5.0.1", @@ -764,9 +765,9 @@ } }, "node_modules/@data-fair/lib-express": { - "version": "1.31.0", - "resolved": "https://registry.npmjs.org/@data-fair/lib-express/-/lib-express-1.31.0.tgz", - "integrity": "sha512-yeUZ0v9iYezjsqQK2CXbX4+jajXMiMgG7w50xISJmWJb+CRQKgz4+MlITzUdHJQVPsRrXKduQ0YjRSvuwV+E2A==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@data-fair/lib-express/-/lib-express-2.0.0.tgz", + "integrity": "sha512-Cgqvs5KaKWi7/XT0zSn0BgTcZVdeELeumzDDk9byYc9dAC/0Qx4FpwVopHi8kadgIvcL6IpSTerYPlFannD/zg==", "license": "MIT", "dependencies": { "@data-fair/lib-common-types": "^1.25.0", @@ -777,7 +778,7 @@ "serialize-javascript": "^7.0.0" }, "peerDependencies": { - "@data-fair/lib-node": "^2.16.0", + "@data-fair/lib-node": "^3.0.0", "express": "5", "ws": "8" }, @@ -806,9 +807,9 @@ } }, "node_modules/@data-fair/lib-node": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/@data-fair/lib-node/-/lib-node-2.16.1.tgz", - "integrity": "sha512-Xwl1s6JHXGMNBWWNg3vTdh5/bjrwReRxSf2AgMtdPxxnQLVrBmAuy6oqORldjJbyCtGRqT10fGRFP7IDUx6NyA==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@data-fair/lib-node/-/lib-node-3.0.0.tgz", + "integrity": "sha512-kVFuDxUqSwlEyvIXSyviZYa7wTJiXc1RHVTnIjnk+yZafCA09D3aWNWpKbKvOtwxbAGYh3sBi0jGy91cX4xVag==", "license": "MIT", "dependencies": { "@data-fair/lib-common-types": "^1.25.0", @@ -818,13 +819,16 @@ "axios": "^1.7.7", "cacheable-lookup": "^7.0.0", "cookie": "^0.7.2", + "debug": "^4.4.3", "ipaddr.js": "^2.5.0", "jsonwebtoken": "^9.0.2", "jwks-rsa": "^3.1.0", + "pino": "^10.4.0", "semver": "^7.6.3" }, "peerDependencies": { "mongodb": "6", + "pino-pretty": "13", "prom-client": "15", "tough-cookie": "5", "ws": "8" @@ -833,6 +837,9 @@ "mongodb": { "optional": true }, + "pino-pretty": { + "optional": true + }, "prom-client": { "optional": true }, @@ -889,6 +896,45 @@ } } }, + "node_modules/@data-fair/lib-types-builder/node_modules/@data-fair/lib-node": { + "version": "2.17.1", + "resolved": "https://registry.npmjs.org/@data-fair/lib-node/-/lib-node-2.17.1.tgz", + "integrity": "sha512-6+jadFjgh49BqXKUN6iTC2ynSnqAGF3d+piQCcDvHr77tpHcDEl1q5Dyp1xNijIymaX5ObdsiiCWg3QFkCC6DQ==", + "license": "MIT", + "dependencies": { + "@data-fair/lib-common-types": "^1.25.0", + "@data-fair/lib-utils": "^1.1.0", + "@data-fair/lib-validation": "^1.0.0", + "agentkeepalive": "^4.5.0", + "axios": "^1.7.7", + "cacheable-lookup": "^7.0.0", + "cookie": "^0.7.2", + "ipaddr.js": "^2.5.0", + "jsonwebtoken": "^9.0.2", + "jwks-rsa": "^3.1.0", + "semver": "^7.6.3" + }, + "peerDependencies": { + "mongodb": "6", + "prom-client": "15", + "tough-cookie": "5", + "ws": "8" + }, + "peerDependenciesMeta": { + "mongodb": { + "optional": true + }, + "prom-client": { + "optional": true + }, + "tough-cookie": { + "optional": true + }, + "ws": { + "optional": true + } + } + }, "node_modules/@data-fair/lib-utils": { "version": "1.14.0", "resolved": "https://registry.npmjs.org/@data-fair/lib-utils/-/lib-utils-1.14.0.tgz", @@ -2500,6 +2546,12 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, "node_modules/@playwright/test": { "version": "1.63.0", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz", @@ -3881,6 +3933,15 @@ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "license": "MIT" }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/axios": { "version": "1.20.0", "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", @@ -4260,6 +4321,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "devOptional": true, + "license": "MIT" + }, "node_modules/colorjs.io": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz", @@ -4506,6 +4574,16 @@ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, + "node_modules/dateformat": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz", + "integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/dayjs": { "version": "1.11.23", "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz", @@ -4664,6 +4742,16 @@ "node": ">= 0.8" } }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, "node_modules/enhanced-resolve": { "version": "5.26.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz", @@ -5348,6 +5436,13 @@ "integrity": "sha512-kuzL9zherLQoqDeQaS55AiiIg1kb4KYXaSusTtgZTPlvKP2gGCI82LNmBNh5RjDVUXIcmgx+/Mx7vPwRzBbhJA==", "license": "MIT" }, + "node_modules/fast-copy": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-4.3.1.tgz", + "integrity": "sha512-CRzQaTFOFUs6PuhsAq7lk9Zqr995soJBcFNZlfJS/5keTSl1awREV9dZW4xS2nX4pWbhIIR0xp4h+J8PQxCkvg==", + "devOptional": true, + "license": "MIT" + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -5409,6 +5504,13 @@ "node": ">=10.0" } }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "devOptional": true, + "license": "MIT" + }, "node_modules/fast-sha256": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", @@ -5824,6 +5926,13 @@ "node": ">= 0.4" } }, + "node_modules/help-me": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz", + "integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==", + "devOptional": true, + "license": "MIT" + }, "node_modules/hono": { "version": "4.13.13", "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz", @@ -6132,6 +6241,16 @@ "url": "https://github.com/sponsors/panva" } }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -7327,6 +7446,15 @@ "ufo": "^1.6.1" } }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/on-finished": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", @@ -7556,6 +7684,78 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pino": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.4.0.tgz", + "integrity": "sha512-bk1ZMTwG/Vymx+zPoa28MhNzucFvXJWp3csrSuxuHPSMeUettaCoQ5Jvg07mtC4JGNpcfTwz41oVCnNgBK9+vA==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^3.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^1.0.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^4.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", + "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-pretty": { + "version": "13.2.0", + "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-13.2.0.tgz", + "integrity": "sha512-jjghD1ML+Di/WxjJDz6j6Y4FT7hIXOlb8h27AyJ+ohtAXJXH4PS/xkv7si+RCCIW59HMgZsMKTDgzdr0RhuRrg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "colorette": "^2.0.7", + "dateformat": "^4.6.3", + "fast-copy": "^4.0.0", + "fast-safe-stringify": "^2.1.1", + "help-me": "^5.0.0", + "joycon": "^3.1.1", + "minimist": "^1.2.6", + "on-exit-leak-free": "^2.1.2", + "pino-abstract-transport": "^3.0.0", + "pump": "^3.0.3", + "secure-json-parse": "^4.1.0", + "sonic-boom": "^5.0.0", + "strip-json-comments": "^5.0.3" + }, + "bin": { + "pino-pretty": "bin.js" + } + }, + "node_modules/pino-pretty/node_modules/sonic-boom": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-5.0.2.tgz", + "integrity": "sha512-/JEruzo6yhNVhsLblTRchgTQHIt7SsdJP0YyrfWaNKjIOQDfrdZv9gwYraYCAsmKV39/LAdV31FLL5NCDpoL/A==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "license": "MIT" + }, "node_modules/pkce-challenge": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", @@ -7672,6 +7872,22 @@ "url": "https://github.com/prettier/prettier?sponsor=1" } }, + "node_modules/process-warning": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz", + "integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, "node_modules/prom-client": { "version": "15.1.3", "resolved": "https://registry.npmjs.org/prom-client/-/prom-client-15.1.3.tgz", @@ -7728,6 +7944,17 @@ "dev": true, "license": "MIT" }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -7807,6 +8034,12 @@ ], "license": "MIT" }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, "node_modules/range-parser": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", @@ -7861,6 +8094,12 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/real-require": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz", + "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==", + "license": "MIT" + }, "node_modules/reconnecting-websocket": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/reconnecting-websocket/-/reconnecting-websocket-4.4.0.tgz", @@ -8513,6 +8752,23 @@ "integrity": "sha512-6FtHJEvt+pVMIB9IBY+IcCJ6Z5f1iQnytgyfKMhDKgmzYG+TeH/wx1y3l27rshSbLiSanrR9ffZDrEsmjlQF2g==", "license": "MIT" }, + "node_modules/secure-json-parse": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.1.tgz", + "integrity": "sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw==", + "devOptional": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/semver": { "version": "7.8.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", @@ -8722,6 +8978,15 @@ "node": ">=10" } }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -8750,6 +9015,15 @@ "memory-pager": "^1.0.2" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/standardwebhooks": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", @@ -8815,6 +9089,19 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, + "node_modules/strip-json-comments": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz", + "integrity": "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/strip-literal": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-4.0.0.tgz", @@ -8907,6 +9194,18 @@ "b4a": "^1.6.4" } }, + "node_modules/thread-stream": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.1.tgz", + "integrity": "sha512-Stg6edJXC/6/xqGwSXwFokrUhChJ18amEjpKH89WrQQ0oVFDF+pUUcTpiwWhFUrE89Vf16FBOlwhaw+lescxMQ==", + "license": "MIT", + "dependencies": { + "real-require": "^1.0.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/timezones.json": { "version": "1.7.2", "resolved": "https://registry.npmjs.org/timezones.json/-/timezones.json-1.7.2.tgz", @@ -10320,7 +10619,7 @@ "worker": { "dependencies": { "@data-fair/catalogs-shared": "*", - "@data-fair/lib-node": "^2.16.1", + "@data-fair/lib-node": "^3.0.0", "@data-fair/lib-node-registry": "^0.7.2", "axios": "^1.20.0", "config": "^5.0.1", diff --git a/package.json b/package.json index 9028970..1479e22 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,7 @@ "@commitlint/config-conventional": "^21.2.3", "@data-fair/lib-agents-sim": "^0.11.0", "@data-fair/lib-dev": "^0.1.1", - "@data-fair/lib-node": "^2.16.1", + "@data-fair/lib-node": "^3.0.0", "@data-fair/lib-utils": "^1.14.0", "@json-layout/core": "~2.12.1", "@modelcontextprotocol/sdk": "^1.32.1", @@ -64,6 +64,7 @@ "husky": "^9.1.7", "neostandard": "^0.14.1", "nodemon": "^3.1.10", + "pino-pretty": "^13.2.0", "tough-cookie": "^5.0.0", "typescript": "^6.0.3" }, diff --git a/shared/log-fields.ts b/shared/log-fields.ts new file mode 100644 index 0000000..e5591d8 --- /dev/null +++ b/shared/log-fields.ts @@ -0,0 +1,29 @@ +// Log fields shared by the api and the worker (see the "Logging" section of AGENTS.md). +// The actor (accountKey, userId...) comes from the implicit log context opened by session.middleware(); +// the owner of a catalog, import or publication is a different notion and uses the owner* names, as in data-fair. +// Config-free on purpose: only plain values. + +export type OwnerLike = { type: string, id: string, name?: string, department?: string } + +export type OwnerLogFields = { ownerKey: string, ownerDep: string | undefined, ownerName: string | undefined } + +// the 3 keys are always present, possibly undefined: pino drops undefined values from the line +export const ownerLogFields = (owner: OwnerLike): OwnerLogFields => ({ + ownerKey: owner.type + '.' + owner.id, + ownerDep: owner.department || undefined, + ownerName: owner.name || undefined +}) + +export type TaskType = 'import' | 'publication' + +type TaskLike = { _id: string, catalog: { id: string }, owner: OwnerLike } + +export type TaskLogFields = OwnerLogFields & { catalogId: string, taskType: TaskType, importId?: string, publicationId?: string } + +/** fields of every line about an import or a publication, opened as log context by the worker for the whole task */ +export const taskLogFields = (task: TaskLike, type: TaskType): TaskLogFields => ({ + catalogId: task.catalog.id, + taskType: type, + [type === 'import' ? 'importId' : 'publicationId']: task._id, + ...ownerLogFields(task.owner) +}) diff --git a/tests/features/shared/log-fields.unit.spec.ts b/tests/features/shared/log-fields.unit.spec.ts new file mode 100644 index 0000000..07aec53 --- /dev/null +++ b/tests/features/shared/log-fields.unit.spec.ts @@ -0,0 +1,22 @@ +import { test, expect } from '@playwright/test' +import { ownerLogFields, taskLogFields } from '../../../shared/log-fields.ts' + +test.describe('log fields', () => { + test('ownerLogFields describes an organization department', () => { + expect(ownerLogFields({ type: 'organization', id: 'o1', name: 'Org 1', department: 'dep1' })) + .toEqual({ ownerKey: 'organization.o1', ownerDep: 'dep1', ownerName: 'Org 1' }) + }) + + test('ownerLogFields always returns the 3 keys', () => { + const fields = ownerLogFields({ type: 'user', id: 'u1', department: '' }) + expect(Object.keys(fields).sort()).toEqual(['ownerDep', 'ownerKey', 'ownerName']) + expect(fields).toEqual({ ownerKey: 'user.u1', ownerDep: undefined, ownerName: undefined }) + }) + + test('taskLogFields names the id after the task type', () => { + const task = { _id: 't1', catalog: { id: 'c1' }, owner: { type: 'user', id: 'u1', name: 'U' } } + expect(taskLogFields(task, 'import')).toEqual({ catalogId: 'c1', taskType: 'import', importId: 't1', ownerKey: 'user.u1', ownerDep: undefined, ownerName: 'U' }) + expect(taskLogFields(task, 'publication')).toMatchObject({ taskType: 'publication', publicationId: 't1' }) + expect(taskLogFields(task, 'publication')).not.toHaveProperty('importId') + }) +}) diff --git a/worker/index.ts b/worker/index.ts index 9932aeb..52f43cc 100644 --- a/worker/index.ts +++ b/worker/index.ts @@ -1,17 +1,18 @@ +import log from '@data-fair/lib-node/log.js' import { start, stop } from './src/worker.ts' -start().then(() => {}, err => { - console.error('Failure while starting worker', err) +start().then(() => log.info('worker loop is running'), err => { + log.error('failure while starting the worker', { code: 'start-process', err }) process.exit(1) }) process.on('SIGTERM', function onSigterm () { - console.info('Received SIGTERM signal, shutdown gracefully...') + log.info('received SIGTERM signal, shutting down gracefully...') stop().then(() => { - console.log('shutting down now') + log.info('shutting down now') process.exit() }, err => { - console.error('Failure while stopping worker', err) + log.error('failure while stopping the worker', { code: 'stop-process', err }) process.exit(1) }) }) diff --git a/worker/package.json b/worker/package.json index 21c1aba..0926a82 100644 --- a/worker/package.json +++ b/worker/package.json @@ -18,7 +18,7 @@ }, "dependencies": { "@data-fair/catalogs-shared": "*", - "@data-fair/lib-node": "^2.16.1", + "@data-fair/lib-node": "^3.0.0", "@data-fair/lib-node-registry": "^0.7.2", "axios": "^1.20.0", "config": "^5.0.1", diff --git a/worker/src/lib/import.ts b/worker/src/lib/import.ts index 7a927de..e67da65 100644 --- a/worker/src/lib/import.ts +++ b/worker/src/lib/import.ts @@ -6,8 +6,8 @@ import fs from 'fs-extra' import FormData from 'form-data' import tmp from 'tmp-promise' import { emit as wsEmit } from '@data-fair/lib-node/ws-emitter.js' -import { taskInternalError } from './internal-error.ts' import eventsQueue from '@data-fair/lib-node/events-queue.js' +import log from '@data-fair/lib-node/log.js' import { decipherSecrets } from '@data-fair/catalogs-shared/cipher.ts' // data-fair is a service of our own infrastructure (configured private URL, not user input) import { privateAxiosInstance as axios } from '@data-fair/lib-node/axios.js' @@ -33,7 +33,9 @@ const handleImportError = async (type: 'upload' | 'download', imp: Import, err: await errorLog(`Failed to ${type} resource file: ` + (err instanceof Error ? err.message : String(err)), err.name !== 'AxiosRequestError' ? err : undefined) await mongo.imports.updateOne({ _id: imp._id }, { $set: { status: 'error', finishedAt: new Date().toISOString() } }) await wsEmit(`import/${imp._id}`, { status: 'error', finishedAt: new Date().toISOString() }) - taskInternalError(imp, 'import', `worker-${type}-failed`, `Failed to ${type} resource file`, err) + // download: the remote catalog failed (upstream, warn); upload: data-fair, our own infrastructure (error) + if (type === 'download') log.warn('failed to download the resource file', { code: 'worker-download-failed', err }) + else log.error('failed to upload the resource file', { code: 'worker-upload-failed', err }) eventsQueue.pushEvent({ title: `L'import de la resource ${imp.remoteResource.title} à échoué`, topic: { key: `catalogs:import-error:${imp._id}` }, diff --git a/worker/src/lib/internal-error.ts b/worker/src/lib/internal-error.ts deleted file mode 100644 index 9a55a44..0000000 --- a/worker/src/lib/internal-error.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { Import, Publication } from '#api/types' -import { internalError } from '@data-fair/lib-node/observer.js' - -/** internalError prefixed with `[catalog:][:]`. Keep `code` low-cardinality: no ids (they go in the message). */ -export const taskInternalError = ( - task: Import | Publication, - type: 'import' | 'publication', - code: string, - description: string, - error?: any -) => { - const msg = `[catalog:${task.catalog.id}][${type}:${task._id}] ${description}` - if (error === undefined) internalError(code, msg) - else internalError(code, msg, error) -} diff --git a/worker/src/lib/publication.ts b/worker/src/lib/publication.ts index 68ca23c..f51972d 100644 --- a/worker/src/lib/publication.ts +++ b/worker/src/lib/publication.ts @@ -3,7 +3,7 @@ import type CatalogPlugin from '@data-fair/types-catalogs' import type { AxiosRequestConfig } from 'axios' import { emit as wsEmit } from '@data-fair/lib-node/ws-emitter.js' -import { taskInternalError } from './internal-error.ts' +import log from '@data-fair/lib-node/log.js' import eventsQueue from '@data-fair/lib-node/events-queue.js' import { decipherSecrets } from '@data-fair/catalogs-shared/cipher.ts' // data-fair is a service of our own infrastructure (configured private URL, not user input) @@ -72,18 +72,19 @@ export const process = async (catalog: Catalog, plugin: CatalogPlugin, pub: Publ itemId: pub._id } }) - return taskInternalError(pub, 'publication', 'worker-missing-permissions', errorMsg) + // the owner lost its permissions on the dataset, expected and reported to the owner + return log.warn(errorMsg, { code: 'worker-missing-permissions' }) } if (!dataFairDataset) { await mongo.publications.deleteOne({ _id: pub._id }) - return taskInternalError(pub, 'publication', 'worker-missing-dataset', 'found a publication without associated dataset, weird') + return log.error('found a publication without associated dataset, weird', { code: 'worker-missing-dataset' }) } // Check if the plugin has the capability to publish (and delete) datasets if (!plugin.metadata.capabilities.some(c => ['createFolderInRoot', 'createFolder', 'createResource', 'replaceFolder', 'replaceResource'].includes(c))) { await mongo.publications.deleteOne({ _id: pub._id }) - return taskInternalError(pub, 'publication', 'worker-missing-capabilities', 'found a publication without the capability to publish datasets, weird') + return log.error('found a publication without the capability to publish datasets, weird', { code: 'worker-missing-capabilities' }) } await publish(catalog, plugin, pub, dataFairDataset) @@ -96,7 +97,8 @@ const publish = async (catalog: Catalog, plugin: CatalogPlugin, pub: Publication const errorMsg = 'Publication site is required for this catalog' await mongo.publications.updateOne({ _id: pub._id }, { $set: { status: 'error', error: errorMsg } }) await wsEmit(`publication/${pub._id}`, { status: 'error', error: errorMsg }) - return taskInternalError(pub, 'publication', 'worker-missing-publication-site', errorMsg) + // a configuration error of the owner, reported on the publication + return log.warn(errorMsg, { code: 'worker-missing-publication-site' }) } // 4. Publish the dataset @@ -143,7 +145,7 @@ const publish = async (catalog: Catalog, plugin: CatalogPlugin, pub: Publication const deletePublication = async (catalog: Catalog, plugin: CatalogPlugin, pub: Publication) => { if (!pub.remoteFolder && !pub.remoteResource) { - taskInternalError(pub, 'publication', 'worker-missing-remote', 'try do delete a publication without remote folder or resource, weird') + log.error('try to delete a publication without remote folder or resource, weird', { code: 'worker-missing-remote' }) } else { try { await plugin.deletePublication({ @@ -154,7 +156,8 @@ const deletePublication = async (catalog: Catalog, plugin: CatalogPlugin, pub: P log: prepareLog(pub, 'publication') }) } catch (error: any) { - taskInternalError(pub, 'publication', 'worker-delete-publication-error', 'Error while deleting publication', error) + // the remote catalog failed, not us + log.warn('error while deleting the remote publication', { code: 'worker-delete-publication-error', err: error }) // Ignore errors during deletion, we will delete the publication anyway } } diff --git a/worker/src/worker.ts b/worker/src/worker.ts index fd1c210..4bf244c 100644 --- a/worker/src/worker.ts +++ b/worker/src/worker.ts @@ -1,4 +1,4 @@ -import type { Publication, Import } from '#api/types' +import type { Catalog, Publication, Import } from '#api/types' import type CatalogPlugin from '@data-fair/types-catalogs' import Debug from 'debug' @@ -13,7 +13,8 @@ import { importPluginModule } from '@data-fair/catalogs-shared/plugin-load.ts' import { getNextImportDate } from '@data-fair/catalogs-shared/cron.ts' import importTask from './lib/import.ts' import publicationTask from './lib/publication.ts' -import { taskInternalError } from './lib/internal-error.ts' +import log, { withLogContext } from '@data-fair/lib-node/log.js' +import { taskLogFields } from '@data-fair/catalogs-shared/log-fields.ts' import config, { registryCacheDir } from '#config' import mongo from '#mongo' import locks from '#locks' @@ -117,12 +118,15 @@ const mainLoop = async () => { */ async function iter (task: Task, type: typeof types[number]) { debug('Process', type, task._id) + // passed explicitly until the plugin is loaded: a plugin module evaluated inside a log context + // would attribute its long-lived timers and pools to this first task + const logFields = taskLogFields(task, type) const collection = type === 'import' ? mongo.imports : mongo.publications const catalog = await mongo.catalogs.findOne({ _id: task.catalog.id }) if (!catalog) { // A task without catalog should not exist, log an error and delete the task await collection.deleteOne({ _id: task._id }) - return taskInternalError(task, type, 'worker-missing-catalog', 'found a task without associated catalog, weird') + return log.error('found a task without associated catalog, weird', { code: 'worker-missing-catalog', ...logFields }) } debug(`From catalog ${catalog.title} (${catalog._id})`) @@ -155,10 +159,17 @@ async function iter (task: Task, type: typeof types[number]) { { $set: { status: 'error', logs: [{ type: 'error', msg, date: new Date().toISOString() }] } } ) await wsEmit(`${type}/${task._id}`, { status: 'error' }) - return taskInternalError(task, type, 'worker-plugin-load-failed', msg, e) + // a plugin removed from the registry or no longer shared with the owner is an expected situation + if (status === 404 || status === 403) return log.warn('the plugin of the catalog is not available', { code: 'worker-plugin-unavailable', plugin: catalog.plugin, ...logFields, err: e }) + return log.error('failed to load the plugin of the catalog', { code: 'worker-plugin-load-failed', plugin: catalog.plugin, ...logFields, err: e }) } debug(`Using plugin ${catalog.plugin}`) + await withLogContext(logFields, () => processTask(catalog, plugin, task, type)) +} + +async function processTask (catalog: Catalog, plugin: CatalogPlugin, task: Task, type: typeof types[number]) { + const collection = type === 'import' ? mongo.imports : mongo.publications try { if (type === 'import') { await importTask.process(catalog, plugin, task as Import) @@ -167,7 +178,7 @@ async function iter (task: Task, type: typeof types[number]) { } } catch (e: any) { // Normally we should not have errors here, they should be caught before - taskInternalError(task, type, 'worker-task-failed', 'Failed to process the task', e) + log.error('failed to process the task', { code: 'worker-task-failed', err: e }) await collection.updateOne({ _id: task._id }, { $set: { status: 'error' }, $push: {