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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions api/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import log from '@data-fair/lib-node/log.js'
import { start, stop } from './src/server.ts'
import { installUncaughtErrorsHandler } from '@data-fair/catalogs-shared/plugin-guard.ts'

installUncaughtErrorsHandler()

start().then(() => {}, err => {
log.error('failure while starting the service', { code: 'start-process', err })
Expand Down
1 change: 1 addition & 0 deletions api/src/catalogs/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export const prepareCatalog = async (catalog: Catalog) => {
secrets: decipherSecrets(catalog.secrets, config.cipherPassword)
})
} catch (error: any) {
if (error.status >= 500) throw error
throw httpError(400, `Invalid configuration: ${error.message || 'Unknown error'}`)
}

Expand Down
5 changes: 4 additions & 1 deletion api/src/plugins/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ import fs from 'fs-extra'
import { httpError } from '@data-fair/lib-express'
import { ensureArtefact } from '@data-fair/lib-node-registry'
import { importPluginModule } from '@data-fair/catalogs-shared/plugin-load.ts'
import { guardPlugin } from '@data-fair/catalogs-shared/plugin-guard.ts'
import config, { registryCacheDir } from '#config'

fs.ensureDirSync(registryCacheDir)

const pluginCallTimeout = 60 * 1000

/** Minimal account shape forwarded to the registry for access control. */
export type PluginAccount = { type: 'user' | 'organization', id: string, department?: string }

Expand Down Expand Up @@ -55,5 +58,5 @@ export const getPlugin = async (
// For compatibility with older plugins
if (plugin.listResources && !plugin.list) plugin.list = plugin.listResources

return { plugin, pkg }
return { plugin: guardPlugin(plugin, artefactId, { timeout: pluginCallTimeout }), pkg }
}
91 changes: 91 additions & 0 deletions shared/plugin-guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import type CatalogPlugin from '@data-fair/types-catalogs'
import { AsyncLocalStorage } from 'node:async_hooks'
import log from '@data-fair/lib-node/log.js'

type PluginCall = { plugin: string, method: string, settled: boolean, fail: (err: unknown) => void }

const pluginStorage = new AsyncLocalStorage<PluginCall>()
const pendingCalls = new Set<PluginCall>()

const maxPluginErrors = 10
const pluginErrorsWindow = 10 * 60 * 1000
const pluginErrorDates = new Map<string, number[]>()

const isThenable = (value: unknown): value is PromiseLike<unknown> =>
typeof (value as PromiseLike<unknown> | null)?.then === 'function'

const callPlugin = (plugin: string, method: string, timeout: number | undefined, run: () => unknown) => {
let fail: (err: unknown) => void = () => {}
const failed = new Promise<never>((_resolve, reject) => { fail = reject })
failed.catch(() => {})
const call: PluginCall = { plugin, method, settled: false, fail }
const settle = () => {
call.settled = true
pendingCalls.delete(call)
}

pendingCalls.add(call)
let result: unknown
try {
result = pluginStorage.run(call, run)
} catch (err) {
settle()
throw err
}
if (!isThenable(result)) {
settle()
return result
}

const timer = timeout
? setTimeout(() => {
log.warn('a plugin call timed out', { code: 'plugin-call-timeout', plugin, pluginMethod: method, timeout })
fail(Object.assign(new Error(`the plugin ${plugin} did not answer ${method} in ${timeout / 1000}s`), { status: 504, expose: true }))
}, timeout)
: undefined
return Promise.race([result, failed]).finally(() => {
clearTimeout(timer)
settle()
})
}

export const guardPlugin = (plugin: CatalogPlugin, pluginId: string, opts: { timeout?: number } = {}): CatalogPlugin => {
const guarded: Record<string, unknown> = { ...plugin }
for (const [key, value] of Object.entries(plugin) as [string, unknown][]) {
if (typeof value !== 'function') continue
guarded[key] = (...args: unknown[]) => callPlugin(pluginId, key, opts.timeout, () => (value as (...args: unknown[]) => unknown).apply(plugin, args))
}
return guarded as unknown as CatalogPlugin
}

export const outsidePlugin = <T>(fn: () => T): T => pluginStorage.exit(fn)

export const installUncaughtErrorsHandler = () => {
process.on('uncaughtException', (err, origin) => {
const call = pluginStorage.getStore()
if (!call) {
log.error('uncaught error, shutting down', { code: 'uncaught-error', origin, err })
process.exit(1)
}

const failedCalls = call.settled ? [...pendingCalls].filter(c => c.plugin === call.plugin) : [call]
log.error('uncaught error in a plugin', {
code: 'plugin-uncaught-error',
plugin: call.plugin,
pluginMethod: call.method,
afterCallSettled: call.settled,
failedCalls: failedCalls.length,
origin,
err
})
for (const failedCall of failedCalls) failedCall.fail(err)

const now = Date.now()
const dates = [...(pluginErrorDates.get(call.plugin) ?? []).filter(date => date > now - pluginErrorsWindow), now]
pluginErrorDates.set(call.plugin, dates)
if (dates.length >= maxPluginErrors) {
log.error('too many uncaught errors in a plugin, shutting down', { code: 'plugin-uncaught-errors-limit', plugin: call.plugin, count: dates.length })
process.exit(1)
}
})
}
104 changes: 104 additions & 0 deletions tests/features/shared/plugin-guard.unit.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { test, expect } from '@playwright/test'
import { spawnSync } from 'node:child_process'
import path from 'node:path'

const guardPath = path.resolve(import.meta.dirname, '../../../shared/plugin-guard.ts')

const runScript = (body: string) => {
const script = `
import { EventEmitter } from 'node:events'
import { guardPlugin, outsidePlugin, installUncaughtErrorsHandler } from ${JSON.stringify(guardPath)}
installUncaughtErrorsHandler()
const resetError = () => Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' })
const emitLater = () => setTimeout(() => new EventEmitter().emit('error', resetError()), 10)
let sharedConnection
const plugin = guardPlugin({
metadata: { title: 'test' },
async list () { emitLater(); return { count: 0, results: [] } },
async getResource () { Promise.reject(new Error('forgotten rejection')); return {} },
prepare () { emitLater(); return new Promise(() => {}) },
publishDataset () { return new Promise(() => {}) },
async openConnection () {
sharedConnection = new EventEmitter()
setTimeout(() => sharedConnection.emit('error', resetError()), 30)
},
useConnection () { return new Promise(() => {}) },
hostCallback (cb) { cb(); return new Promise(() => {}) },
assertConfigValid () { throw new Error('invalid config') }
}, 'test-plugin', { timeout: 100 })
${body}
setTimeout(() => { console.log('ALIVE'); process.exit(0) }, 200)
`
return spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', env: { ...process.env, NODE_ENV: 'production' } })
}

test.describe('plugin guard', () => {
test('an error event nobody listens to in a plugin call does not stop the process', () => {
const res = runScript('await plugin.list({})')
expect(res.stdout).toContain('ALIVE')
expect(res.stdout).toContain('"code":"plugin-uncaught-error"')
expect(res.stdout).toContain('"plugin":"test-plugin"')
expect(res.status).toBe(0)
})

test('an unhandled rejection in a plugin call does not stop the process', () => {
const res = runScript('await plugin.getResource({})')
expect(res.stdout).toContain('ALIVE')
expect(res.stdout).toContain('"origin":"unhandledRejection"')
expect(res.status).toBe(0)
})

test('a pending plugin call rejects with the uncaught error it raised', () => {
const res = runScript('await plugin.prepare({}).catch(err => console.log("REJECTED=" + err.code))')
expect(res.stdout).toContain('REJECTED=ECONNRESET')
expect(res.stdout).toContain('"pluginMethod":"prepare"')
expect(res.stdout).toContain('ALIVE')
})

test('a plugin call that never settles rejects after the timeout', () => {
const res = runScript('await plugin.publishDataset({}).catch(err => console.log("REJECTED=" + err.status + " " + err.message))')
expect(res.stdout).toContain('REJECTED=504 the plugin test-plugin did not answer publishDataset in 0.1s')
})

test('an error on a resource created by a settled call fails the pending calls of the same plugin', () => {
const res = runScript(`
await plugin.openConnection()
await plugin.useConnection().catch(err => console.log('REJECTED=' + err.code))`)
expect(res.stdout).toContain('REJECTED=ECONNRESET')
expect(res.stdout).toContain('"afterCallSettled":true')
expect(res.stdout).toContain('ALIVE')
})

test('an error from a host callback run outside of the plugin context still stops the process', () => {
const res = runScript('plugin.hostCallback(() => outsidePlugin(emitLater))')
expect(res.stdout).not.toContain('ALIVE')
expect(res.stdout).toContain('"code":"uncaught-error"')
expect(res.status).toBe(1)
})

test('10 uncaught errors of one plugin stop the process', () => {
const res = runScript('for (let i = 0; i < 9; i++) plugin.list({}); setTimeout(() => console.log("NINE_OK"), 50); setTimeout(() => plugin.list({}), 100)')
expect(res.stdout).toContain('NINE_OK')
expect(res.stdout).toContain('"plugin":"test-plugin","count":10')
expect(res.stdout).not.toContain('ALIVE')
expect(res.stdout).toContain('"code":"plugin-uncaught-errors-limit"')
expect(res.status).toBe(1)
})

test('a synchronous throw is returned unchanged', () => {
const res = runScript('try { plugin.assertConfigValid({}) } catch (err) { console.log("THROWN=" + err.message) }')
expect(res.stdout).toContain('THROWN=invalid config')
})

test('keeps the plugin metadata', () => {
const res = runScript('console.log("TITLE=" + plugin.metadata.title)')
expect(res.stdout).toContain('TITLE=test')
})

test('an uncaught error outside of a plugin call still stops the process', () => {
const res = runScript('emitLater()')
expect(res.stdout).not.toContain('ALIVE')
expect(res.stdout).toContain('"code":"uncaught-error"')
expect(res.status).toBe(1)
})
})
3 changes: 3 additions & 0 deletions worker/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import log from '@data-fair/lib-node/log.js'
import { start, stop } from './src/worker.ts'
import { installUncaughtErrorsHandler } from '@data-fair/catalogs-shared/plugin-guard.ts'

installUncaughtErrorsHandler()

start().then(() => log.info('worker loop is running'), err => {
log.error('failure while starting the worker', { code: 'start-process', err })
Expand Down
9 changes: 5 additions & 4 deletions worker/src/lib/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Import, Publication } from '#api/types'
import mongo from '#mongo'

import { emit as wsEmit } from '@data-fair/lib-node/ws-emitter.js'
import { outsidePlugin } from '@data-fair/catalogs-shared/plugin-guard.ts'

type TaskKey = 'import' | 'publication'
type Task = Import | Publication
Expand All @@ -14,23 +15,23 @@ type Task = Import | Publication
export default (task: Task, type: TaskKey): LogFunctions => {
const collection = type === 'import' ? mongo.imports : mongo.publications

const pushLog = async (log: Omit<Log, 'date'>) => {
const pushLog = (log: Omit<Log, 'date'>) => outsidePlugin(async () => {
const logWithDate = { ...log, date: new Date().toISOString() } as Log
await collection.updateOne({ _id: task._id }, { $push: { logs: logWithDate } })
await wsEmit(`${type}/${task._id}/logs`, logWithDate)
}
})

return {
info: async (msg, extra) => await pushLog({ type: 'info', msg, extra } as Omit<Log, 'date'>),
warning: async (msg, extra) => await pushLog({ type: 'warning', msg, extra } as Omit<Log, 'date'>),
error: async (msg, extra) => await pushLog({ type: 'error', msg, extra } as Omit<Log, 'date'>),
step: async (msg) => await pushLog({ type: 'step', msg } as Omit<Log, 'date'>),
task: async (key, msg, total) => await pushLog({ type: 'task', msg, key, progress: 0, total } as Omit<Log, 'date'>),
progress: async (taskKey, progress, total) => {
progress: (taskKey, progress, total) => outsidePlugin(async () => {
const progressDate = new Date().toISOString()
await collection.updateOne({ _id: task._id, logs: { $elemMatch: { type: 'task', key: taskKey } } },
{ $set: { 'logs.$.progress': progress, 'logs.$.total': total, 'logs.$.progressDate': progressDate } })
await wsEmit(`${type}/${task._id}/logs`, { type: 'task', key: taskKey, progressDate, progress, total })
}
})
}
}
2 changes: 2 additions & 0 deletions worker/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import eventsQueue from '@data-fair/lib-node/events-queue.js'
import upgradeScripts from '@data-fair/lib-node/upgrade-scripts.js'
import { ensureArtefact } from '@data-fair/lib-node-registry'
import { importPluginModule } from '@data-fair/catalogs-shared/plugin-load.ts'
import { guardPlugin } from '@data-fair/catalogs-shared/plugin-guard.ts'
import { getNextImportDate } from '@data-fair/catalogs-shared/cron.ts'
import importTask from './lib/import.ts'
import publicationTask from './lib/publication.ts'
Expand Down Expand Up @@ -150,6 +151,7 @@ async function iter (task: Task, type: typeof types[number]) {
const mod = await importPluginModule<{ default: CatalogPlugin }>(ensured.path)
plugin = mod.default
if (plugin.listResources && !plugin.list) plugin.list = plugin.listResources
plugin = guardPlugin(plugin, catalog.plugin)
} catch (e: any) {
const status = e.status ?? e.statusCode ?? e.response?.status
const msg = (status === 404 || status === 403)
Expand Down