@data-fair/lib-node 2.3.2 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/observer.js +31 -7
- package/package.json +2 -3
- package/upgrade-scripts.js +5 -5
- package/validation.d.ts +1 -8
- package/validation.js +1 -37
package/observer.js
CHANGED
|
@@ -36,8 +36,7 @@ const serveRegistry = async (res, registry) => {
|
|
|
36
36
|
res.end()
|
|
37
37
|
}
|
|
38
38
|
// live CPU performance inspection
|
|
39
|
-
const serveCPUProfile = async (res, duration
|
|
40
|
-
// @ts-ignore
|
|
39
|
+
const serveCPUProfile = async (res, duration) => {
|
|
41
40
|
const { Session } = await import('node:inspector/promises')
|
|
42
41
|
const session = new Session()
|
|
43
42
|
session.connect()
|
|
@@ -45,21 +44,44 @@ const serveCPUProfile = async (res, duration = 2000) => {
|
|
|
45
44
|
await session.post('Profiler.start')
|
|
46
45
|
await new Promise(resolve => setTimeout(resolve, duration))
|
|
47
46
|
const { profile } = await session.post('Profiler.stop')
|
|
47
|
+
await session.post('Profiler.disable')
|
|
48
48
|
session.disconnect()
|
|
49
49
|
res.setHeader('Content-Disposition', `attachment; filename="data-fair-${hostname()}-${new Date().toISOString()}.cpuprofile"`)
|
|
50
50
|
res.write(JSON.stringify(profile))
|
|
51
51
|
res.end()
|
|
52
52
|
}
|
|
53
|
+
// live heap allocation sampler
|
|
54
|
+
const serveHeapSnapshot = async (res, includeCollected, duration) => {
|
|
55
|
+
const { Session } = await import('node:inspector/promises')
|
|
56
|
+
const session = new Session()
|
|
57
|
+
session.connect()
|
|
58
|
+
await session.post('HeapProfiler.enable')
|
|
59
|
+
await session.post('HeapProfiler.startSampling', { includeObjectsCollectedByMajorGC: includeCollected, includeObjectsCollectedByMinorGC: true })
|
|
60
|
+
await new Promise(resolve => setTimeout(resolve, duration))
|
|
61
|
+
const { profile } = await session.post('HeapProfiler.stopSampling')
|
|
62
|
+
await session.post('HeapProfiler.disable')
|
|
63
|
+
session.disconnect()
|
|
64
|
+
res.setHeader('Content-Disposition', `attachment; filename="data-fair-${hostname()}-${new Date().toISOString()}.heapprofile"`)
|
|
65
|
+
res.write(JSON.stringify(profile))
|
|
66
|
+
res.end()
|
|
67
|
+
}
|
|
53
68
|
let server
|
|
54
69
|
export const startObserver = async (port = 9090) => {
|
|
55
70
|
server = createServer((req, res) => {
|
|
56
|
-
|
|
71
|
+
const url = new URL(req.url || '', `http://${req.headers.host}`)
|
|
72
|
+
if (req.method === 'GET' && url.pathname === '/metrics') {
|
|
57
73
|
serveRegistry(res, register).catch(err => httpErrorHandler(res, err))
|
|
58
|
-
} else if (req.method === 'GET' && (
|
|
74
|
+
} else if (req.method === 'GET' && (url.pathname === '/global-metrics' || url.pathname === '/service-metrics')) {
|
|
59
75
|
serveRegistry(res, servicePromRegistry).catch(err => httpErrorHandler(res, err))
|
|
60
|
-
} else if (req.method === 'GET' &&
|
|
61
|
-
|
|
62
|
-
serveCPUProfile(res).catch(err => httpErrorHandler(res, err))
|
|
76
|
+
} else if (req.method === 'GET' && url.pathname === '/cpu-profile') {
|
|
77
|
+
const duration = parseInt(url.searchParams.get('duration') || '2000')
|
|
78
|
+
serveCPUProfile(res, duration).catch(err => httpErrorHandler(res, err))
|
|
79
|
+
} else if (req.method === 'GET' && url.pathname === '/heap-profile') {
|
|
80
|
+
const duration = parseInt(url.searchParams.get('duration') || '2000')
|
|
81
|
+
serveHeapSnapshot(res, false, duration).catch(err => httpErrorHandler(res, err))
|
|
82
|
+
} else if (req.method === 'GET' && url.pathname === '/heap-profile-all') {
|
|
83
|
+
const duration = parseInt(url.searchParams.get('duration') || '2000')
|
|
84
|
+
serveHeapSnapshot(res, true, duration).catch(err => httpErrorHandler(res, err))
|
|
63
85
|
} else {
|
|
64
86
|
res.writeHead(404)
|
|
65
87
|
res.end()
|
|
@@ -71,6 +93,8 @@ export const startObserver = async (port = 9090) => {
|
|
|
71
93
|
GET /metrics -> get prometheus metrics for this instance
|
|
72
94
|
GET /service-metrics -> get prometheus metrics shared accross all instances
|
|
73
95
|
GET /cpu-profile -> generate and fetch a CPU profile
|
|
96
|
+
GET /heap-snapshot -> generate and fetch a sampled heap allocation snapshot
|
|
97
|
+
GET /heap-snapshot-all -> generate and fetch a sampled heap allocation snapshot including objects collected by GC
|
|
74
98
|
`)
|
|
75
99
|
}
|
|
76
100
|
export const stopObserver = async () => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@data-fair/lib-node",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.0",
|
|
4
4
|
"description": "Small nodejs related utility functions for the data-fair stack.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"files": [
|
|
@@ -15,10 +15,9 @@
|
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
17
|
"@data-fair/lib-common-types": "^1.5.0",
|
|
18
|
+
"@data-fair/lib-validation": "^1.0.0",
|
|
18
19
|
"@data-fair/lib-utils": "^1.1.0",
|
|
19
20
|
"agentkeepalive": "^4.5.0",
|
|
20
|
-
"ajv-formats": "^3.0.1",
|
|
21
|
-
"ajv-i18n": "^4.2.0",
|
|
22
21
|
"axios": "^1.7.7",
|
|
23
22
|
"cacheable-lookup": "^7.0.0",
|
|
24
23
|
"semver": "^7.6.3"
|
package/upgrade-scripts.js
CHANGED
|
@@ -34,9 +34,9 @@ async function runScripts (db, basePath, isFresh) {
|
|
|
34
34
|
debug('list scripts from ' + scriptsRoot)
|
|
35
35
|
let scripts = await listScripts(scriptsRoot)
|
|
36
36
|
if (previousPersion) {
|
|
37
|
-
debug(`
|
|
37
|
+
debug(`current service version from database : ${previousPersion}`)
|
|
38
38
|
} else {
|
|
39
|
-
debug('
|
|
39
|
+
debug('no service version found in database, this is the first time the upgrade system is run')
|
|
40
40
|
scripts = scripts.filter(scriptDef => scriptDef.version === 'init')
|
|
41
41
|
if (isFresh) {
|
|
42
42
|
if (await isFresh()) {
|
|
@@ -46,7 +46,7 @@ async function runScripts (db, basePath, isFresh) {
|
|
|
46
46
|
previousPersion = '0.0.0'
|
|
47
47
|
}
|
|
48
48
|
} else {
|
|
49
|
-
debug('
|
|
49
|
+
debug('no isFresh function, it could be a fresh install, do not run any script')
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
if (previousPersion) {
|
|
@@ -54,7 +54,7 @@ async function runScripts (db, basePath, isFresh) {
|
|
|
54
54
|
if (semver.gte(scriptDef.version, previousPersion)) {
|
|
55
55
|
for (const scriptName of scriptDef.names) {
|
|
56
56
|
const script = (await import(path.join(scriptsRoot, scriptDef.version, scriptName))).default
|
|
57
|
-
debug('
|
|
57
|
+
debug('apply script %s/%s : %s', scriptDef.version, scriptName, script.description)
|
|
58
58
|
await script.exec(db, Debug(`upgrade:${scriptDef.version}:${scriptName}`))
|
|
59
59
|
}
|
|
60
60
|
}
|
|
@@ -63,7 +63,7 @@ async function runScripts (db, basePath, isFresh) {
|
|
|
63
63
|
const coercedVersion = semver.coerce(pjson.version)
|
|
64
64
|
if (!coercedVersion) { throw new Error(`Invalid version number in package.json ${pjson.version}`) }
|
|
65
65
|
const newService = { id: pjson.name, version: coercedVersion.version }
|
|
66
|
-
debug(`
|
|
66
|
+
debug(`upgrade scripts are over, save current version number ${newService.version}`)
|
|
67
67
|
await services.updateOne({ id: pjson.name }, { $set: newService }, { upsert: true })
|
|
68
68
|
}
|
|
69
69
|
// Walk the scripts directories
|
package/validation.d.ts
CHANGED
|
@@ -1,8 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export declare const errorsText: (errors: ErrorObject[] | null | undefined, varName?: string) => string;
|
|
3
|
-
export type AssertValidOptions = {
|
|
4
|
-
lang?: string;
|
|
5
|
-
name?: string;
|
|
6
|
-
internal?: boolean;
|
|
7
|
-
};
|
|
8
|
-
export declare function assertValid<T>(validate: ValidateFunction, data: any, options?: AssertValidOptions): asserts data is T;
|
|
1
|
+
export * from '@data-fair/lib-validation';
|
package/validation.js
CHANGED
|
@@ -1,37 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import ajvEnModule from 'ajv-i18n/localize/en/index.js'
|
|
3
|
-
import { httpError } from '@data-fair/lib-utils/http-errors.js'
|
|
4
|
-
const ajvFr = ajvFrModule
|
|
5
|
-
const ajvEn = ajvEnModule
|
|
6
|
-
const localize = {
|
|
7
|
-
fr: ajvFr,
|
|
8
|
-
en: ajvEn
|
|
9
|
-
}
|
|
10
|
-
// cf https://github.com/ajv-validator/ajv/blob/b3e0cb17d0e095b5c883042b2306571be5ec86b7/lib/core.ts#L650
|
|
11
|
-
export const errorsText = (errors, varName = 'data') => {
|
|
12
|
-
if (!errors || errors.length === 0) { return 'No errors' }
|
|
13
|
-
return errors
|
|
14
|
-
.map((e) => {
|
|
15
|
-
let msg = `${varName}${e.instancePath} ${e.message}`.trim()
|
|
16
|
-
const paramKeys = Object.keys(e.params || {}).filter(key => {
|
|
17
|
-
if (key === 'error') { return false }
|
|
18
|
-
if (e.keyword === 'type' && key === 'type') { return false }
|
|
19
|
-
return true
|
|
20
|
-
})
|
|
21
|
-
const params = paramKeys
|
|
22
|
-
.map(key => paramKeys.length > 1 ? `${key}=${e.params[key]}` : e.params[key])
|
|
23
|
-
.join(', ')
|
|
24
|
-
if (params) { msg += ` (${params})` }
|
|
25
|
-
return msg
|
|
26
|
-
})
|
|
27
|
-
.reduce((text, msg) => text + ', ' + msg)
|
|
28
|
-
}
|
|
29
|
-
export function assertValid (validate, data, options = {}) {
|
|
30
|
-
const lang = options.lang ?? 'fr'
|
|
31
|
-
const name = options.name ?? 'data'
|
|
32
|
-
if (!validate(data)) {
|
|
33
|
-
(localize[lang] || localize.fr)(validate.errors)
|
|
34
|
-
const message = errorsText(validate.errors, name)
|
|
35
|
-
if (options.internal) { throw new Error(message) } else { throw httpError(400, message) }
|
|
36
|
-
}
|
|
37
|
-
}
|
|
1
|
+
export * from '@data-fair/lib-validation'
|