@elisra-devops/docgen-data-provider 1.140.0 → 1.141.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.
Files changed (44) hide show
  1. package/.github/workflows/ci.yml +2 -0
  2. package/bin/helpers/tfs.js +21 -14
  3. package/bin/helpers/tfs.js.map +1 -1
  4. package/bin/modules/JfrogDataProvider.js +1 -1
  5. package/bin/modules/JfrogDataProvider.js.map +1 -1
  6. package/bin/modules/PipelinesDataProvider.js +1 -1
  7. package/bin/modules/PipelinesDataProvider.js.map +1 -1
  8. package/bin/modules/ResultDataProvider.js +21 -15
  9. package/bin/modules/ResultDataProvider.js.map +1 -1
  10. package/bin/modules/TicketsDataProvider.js +13 -10
  11. package/bin/modules/TicketsDataProvider.js.map +1 -1
  12. package/bin/tests/modules/JfrogDataProvider.test.js +3 -1
  13. package/bin/tests/modules/JfrogDataProvider.test.js.map +1 -1
  14. package/bin/tests/modules/ResultDataProvider.test.js +6 -2
  15. package/bin/tests/modules/ResultDataProvider.test.js.map +1 -1
  16. package/bin/tests/utils/logger.test.d.ts +1 -0
  17. package/bin/tests/utils/logger.test.js +238 -0
  18. package/bin/tests/utils/logger.test.js.map +1 -0
  19. package/bin/tests/utils/runContext.test.d.ts +1 -0
  20. package/bin/tests/utils/runContext.test.js +51 -0
  21. package/bin/tests/utils/runContext.test.js.map +1 -0
  22. package/bin/utils/logSink.d.ts +25 -0
  23. package/bin/utils/logSink.js +16 -0
  24. package/bin/utils/logSink.js.map +1 -0
  25. package/bin/utils/logger.d.ts +6 -0
  26. package/bin/utils/logger.js +219 -27
  27. package/bin/utils/logger.js.map +1 -1
  28. package/bin/utils/runContext.d.ts +8 -0
  29. package/bin/utils/runContext.js +12 -0
  30. package/bin/utils/runContext.js.map +1 -0
  31. package/eslint.config.mjs +40 -0
  32. package/package.json +8 -3
  33. package/src/helpers/tfs.ts +19 -15
  34. package/src/modules/JfrogDataProvider.ts +1 -1
  35. package/src/modules/PipelinesDataProvider.ts +1 -1
  36. package/src/modules/ResultDataProvider.ts +20 -15
  37. package/src/modules/TicketsDataProvider.ts +15 -14
  38. package/src/tests/modules/JfrogDataProvider.test.ts +3 -1
  39. package/src/tests/modules/ResultDataProvider.test.ts +6 -2
  40. package/src/tests/utils/logger.test.ts +270 -0
  41. package/src/tests/utils/runContext.test.ts +48 -0
  42. package/src/utils/logSink.ts +44 -0
  43. package/src/utils/logger.ts +229 -29
  44. package/src/utils/runContext.ts +25 -0
@@ -0,0 +1,48 @@
1
+ import * as winston from 'winston';
2
+ import Transport = require('winston-transport');
3
+ import { withRunContext } from '../../utils/logger';
4
+ import { runContextStore } from '../../utils/runContext';
5
+
6
+ class CaptureTransport extends Transport {
7
+ lines: Record<string, unknown>[] = [];
8
+ log(info: Record<string, unknown>, callback: () => void) {
9
+ this.lines.push(JSON.parse((info as any)[Symbol.for('message')] ?? JSON.stringify(info)));
10
+ callback();
11
+ }
12
+ }
13
+ function makeTestLogger() {
14
+ const capture = new CaptureTransport();
15
+ const logger = winston.createLogger({
16
+ level: 'silly',
17
+ format: winston.format.combine(withRunContext(), winston.format.json()),
18
+ transports: [capture],
19
+ });
20
+ return { logger, capture };
21
+ }
22
+
23
+ describe('withRunContext', () => {
24
+ test('is a no-op when the store was never populated', () => {
25
+ const { logger, capture } = makeTestLogger();
26
+ logger.info('outside any run');
27
+ expect(capture.lines[0].runId).toBeUndefined();
28
+ });
29
+
30
+ test('stamps runId onto every log emitted inside store.run(...)', () => {
31
+ const { logger, capture } = makeTestLogger();
32
+ runContextStore.run({ runId: 'run-123' }, () => {
33
+ logger.info('inside the run');
34
+ });
35
+ logger.info('outside again');
36
+ expect(capture.lines[0].runId).toBe('run-123');
37
+ expect(capture.lines[1].runId).toBeUndefined();
38
+ });
39
+
40
+ test('async work started inside the run keeps the runId across the await boundary', async () => {
41
+ const { logger, capture } = makeTestLogger();
42
+ await runContextStore.run({ runId: 'run-async' }, async () => {
43
+ await new Promise((resolve) => setTimeout(resolve, 0));
44
+ logger.info('after await');
45
+ });
46
+ expect(capture.lines[0].runId).toBe('run-async');
47
+ });
48
+ });
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ // The one queryable-error-store event shape, emitted by DiagnosticsTransport (logger.ts).
4
+ // This package never installs a sink itself — it only reads whatever the host process
5
+ // (docgen-content-control's index.ts) installed. err is intentionally narrow —
6
+ // {message, code, stack} — per the settled Phase 6 schema decision: no generic
7
+ // extra-fields bucket.
8
+ export interface DiagnosticEvent {
9
+ ts: string;
10
+ level: string;
11
+ service: string;
12
+ version: string;
13
+ runId?: string;
14
+ docType?: string;
15
+ step?: string;
16
+ contentControlType?: string;
17
+ contentControlTitle?: string;
18
+ project?: string;
19
+ userId?: string;
20
+ message: string;
21
+ err?: { message: string; code?: string; stack?: string };
22
+ // Phase 6b — set on a debug/info event captured under retain-on-failure. Deleted by
23
+ // api-gate at the run's one success point; left alone (and thus permanent, subject to the
24
+ // normal TTL) if the run fails.
25
+ retainPending?: boolean;
26
+ }
27
+
28
+ export interface LogSink {
29
+ push(event: DiagnosticEvent): void;
30
+ }
31
+
32
+ // Symbol.for so this package's copy converges on the same installed sink as
33
+ // docgen-content-control's (the host process this package runs inside) and
34
+ // docgen-dg-skins-package's, the same reasoning as runContext.ts's AsyncLocalStorage. A
35
+ // never-populated sink is a harmless no-op — this package only reads it, never installs one.
36
+ const KEY = Symbol.for('elisradevops.docgen.logSink');
37
+
38
+ export function getLogSink(): LogSink | undefined {
39
+ return (globalThis as Record<symbol, unknown>)[KEY] as LogSink | undefined;
40
+ }
41
+
42
+ export function installLogSink(sink: LogSink): void {
43
+ (globalThis as Record<symbol, unknown>)[KEY] = sink;
44
+ }
@@ -1,37 +1,237 @@
1
1
  'use strict';
2
2
  import * as winston from 'winston';
3
- import BrowserConsole from 'winston-transport-browserconsole';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ import * as Transport from 'winston-transport';
6
+ import { runContextStore } from './runContext';
7
+ import { getLogSink, DiagnosticEvent } from './logSink';
4
8
  let logger: winston.Logger;
5
9
 
6
- const logFormat = winston.format.printf((info) => `${info.timestamp} - ${info.level}: ${info.message}`);
7
- // if (typeof window === "undefined") {
8
- // let logsPath = process.env.logs_path || "./logs/";
9
-
10
- // logger = winston.createLogger({
11
- // format: winston.format.timestamp(),
12
- // level: "silly",
13
- // transports: [
14
- // new winston.transports.File({
15
- // filename: `${logsPath}azure-rest-api-errors.log`,
16
- // level: "error",
17
- // format: logFormat,
18
- // }),
19
- // new winston.transports.File({
20
- // filename: `${logsPath}azure-rest-api-all.log`,
21
- // format: logFormat,
22
- // }),
23
- // new winston.transports.Console({ format: logFormat, level: "debug" }),
24
- // ],
25
- // });
26
- // } else {
10
+ // Merges the ambient runId (set by content-control's request middleware, once Phase 3 lands
11
+ // there) into every log record. A never-populated store is a harmless no-op — this package
12
+ // only reads it, never sets it.
13
+ export const withRunContext = winston.format((info) => {
14
+ const store = runContextStore.getStore();
15
+ if (store?.runId) (info as Record<string, unknown>).runId = store.runId;
16
+ // Phase 7b — same ambient, per-run treatment as runId.
17
+ if (store?.docType) (info as Record<string, unknown>).docType = store.docType;
18
+ // Phase 7c — same read-only treatment; populated by content-control's attachRunContext.
19
+ if (store?.project) (info as Record<string, unknown>).project = store.project;
20
+ return info;
21
+ });
22
+
23
+ // Defense-in-depth: scrubs known-sensitive keys out of any object attached to a log call
24
+ // (meta, splat, an Error's own enumerable props — e.g. AxiosError.toJSON()'s
25
+ // config.auth.password / config.headers.Authorization, which is exactly how a PAT was
26
+ // leaking via `logger.error(JSON.stringify(error))` on ADO REST failures). Does not
27
+ // redact secrets interpolated into a message string — that's the corresponding call-site
28
+ // fixes' job; this is a backstop for structured fields.
29
+ // "accesskey" (not just "minioaccesskey") so this also catches an *AccessKeyId-style field —
30
+ // a real gap found in api-gate's copy during the Phase 5 manifest work: only the *SecretKey
31
+ // sibling was covered before, via "secret". Applied here too to keep the four copies in sync.
32
+ const SENSITIVE_KEY = /token|pat|password|secret|authorization|accesskey|minioaccesskey|miniosecretkey/i;
33
+
34
+ // A per-key try/catch on the *read*, not just around the whole loop: a getter that throws
35
+ // (e.g. `{ get boom() { throw ... } }`) would otherwise abort redaction for every remaining
36
+ // key in the same object, or — worse — survive redaction untouched and re-throw later, inside
37
+ // winston's json() formatter, which is not wrapped in anything. redactValue always returns a
38
+ // freshly built plain object/array, never the original reference, so once a value has passed
39
+ // through here nothing downstream can re-trigger a throwing accessor on it.
40
+ function safeRead(obj: Record<string, unknown>, key: string): { ok: true; value: unknown } | { ok: false } {
41
+ try {
42
+ return { ok: true, value: obj[key] };
43
+ } catch {
44
+ return { ok: false };
45
+ }
46
+ }
47
+ function redactValue(value: unknown, depth = 0, seen = new WeakSet<object>()): unknown {
48
+ if (depth > 6 || value === null || typeof value !== 'object') return value;
49
+ if (seen.has(value as object)) return '[Circular]';
50
+ seen.add(value as object);
51
+ if (Array.isArray(value)) return value.map((v) => redactValue(v, depth + 1, seen));
52
+ const out: Record<string, unknown> = {};
53
+ for (const key of Object.keys(value as Record<string, unknown>)) {
54
+ const read = safeRead(value as Record<string, unknown>, key);
55
+ if (!read.ok) {
56
+ out[key] = '[Unreadable property]';
57
+ continue;
58
+ }
59
+ out[key] = SENSITIVE_KEY.test(key) ? '[REDACTED]' : redactValue(read.value, depth + 1, seen);
60
+ }
61
+ return out;
62
+ }
63
+ export const redact = winston.format((info) => {
64
+ const target = info as Record<string, unknown>;
65
+ for (const key of Object.keys(target)) {
66
+ // level/timestamp are always plain strings winston sets itself — never touched. message is
67
+ // NOT exempt: when logger.error(x) is called with a single non-string/non-Error argument,
68
+ // winston nests the whole thing under info.message (this is exactly the shape hit by a raw
69
+ // object argument), so message can carry a throwing getter or a sensitive key just as much
70
+ // as any other field — redactValue already no-ops on a plain string, so including it here
71
+ // costs nothing for the common case and closes that gap for the uncommon one.
72
+ if (key === 'level' || key === 'timestamp') continue;
73
+ const read = safeRead(target, key);
74
+ const value = !read.ok
75
+ ? '[Unreadable property]'
76
+ : // A top-level primitive (e.g. token: "abc") has no children for redactValue to walk into —
77
+ // the key itself has to be checked here too, not just inside the recursive object walk.
78
+ SENSITIVE_KEY.test(key)
79
+ ? '[REDACTED]'
80
+ : redactValue(read.value);
81
+ try {
82
+ target[key] = value;
83
+ } catch {
84
+ // The original property could be a getter-only accessor with no setter, which throws on
85
+ // plain assignment in strict mode — redefine it outright rather than skip it.
86
+ Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
87
+ }
88
+ }
89
+ return info;
90
+ });
91
+
92
+ // Resolves the package's own version for defaultMeta. Node-only (this package is currently
93
+ // only ever consumed by docgen-content-control at runtime — the browser transport below is
94
+ // unused/commented out), so fs/path are safe here.
95
+ function readOwnVersion(): string {
96
+ const candidates = [
97
+ path.resolve(__dirname, '../package.json'),
98
+ path.resolve(__dirname, '../../package.json'),
99
+ path.resolve(process.cwd(), 'package.json'),
100
+ ];
101
+ for (const candidate of candidates) {
102
+ try {
103
+ if (!fs.existsSync(candidate)) continue;
104
+ return JSON.parse(fs.readFileSync(candidate, 'utf8')).version || 'unknown';
105
+ } catch {
106
+ // try next candidate
107
+ }
108
+ }
109
+ return 'unknown';
110
+ }
111
+
112
+ // A template literal's implicit ToString throws on a Symbol value (unlike String(), which
113
+ // calls Symbol.prototype.toString() explicitly) — logger.error(Symbol('x')) would otherwise
114
+ // crash inside this formatter itself, the one place in the pipeline with no try/catch around
115
+ // it. Symbol.toString() itself never throws, so this needs no further guarding.
116
+ const safeMessageString = (value: unknown): string =>
117
+ typeof value === 'symbol' ? value.toString() : String(value);
118
+
119
+ const textFormat = winston.format.printf((info) => `${info.timestamp} - ${info.level}: ${safeMessageString(info.message)}`);
120
+
121
+ // Bounded so one oversized message/stack can't produce an unbounded LogEvent document.
122
+ const MAX_MESSAGE_LEN = 2000;
123
+ const MAX_STACK_LEN = 4000;
124
+ function clamp(value: unknown, max: number): string | undefined {
125
+ if (typeof value !== 'string') return undefined;
126
+ return value.length > max ? value.slice(0, max) : value;
127
+ }
128
+
129
+ // Ships warn/error records to whatever LogSink the host process (docgen-content-control's
130
+ // index.ts) has installed — this package never installs one itself, only reads it. This is
131
+ // the dominant source of real ADO error records (tfs.ts's executeWithRetry is the single
132
+ // static axios instance handling all Azure DevOps traffic), so without this transport most
133
+ // real generation failures either never reach the store or get misattributed to
134
+ // dg-content-control. Reads info *after* the rest of the format chain has already run —
135
+ // redact() has already scrubbed it by the time this transport sees it. Never throws, never
136
+ // blocks the call path, and never logs through `logger` itself (that would recurse back
137
+ // into this same transport) — failures go to console.error only.
138
+ const DIAGNOSTICS_CAPTURE_ENABLED = (process.env.DIAGNOSTICS_CAPTURE_ENABLED || 'true').toLowerCase() !== 'false';
139
+ // Exported for tests, the same treatment as redact()/withRunContext() — so a test pipeline
140
+ // can exercise this transport without going through the real singleton logger's env-gated
141
+ // json()/textFormat branch.
142
+ export class DiagnosticsTransport extends Transport {
143
+ log(info: Record<string, unknown>, callback: () => void): void {
144
+ setImmediate(() => this.emit('logged', info));
145
+ try {
146
+ const level = info.level;
147
+ const isWarnOrError = level === 'warn' || level === 'error';
148
+ // Phase 6b — the logger's own level gate is now 'debug' (see createLogger below), so a
149
+ // debug/info call reaches this transport regardless of mode; this is the one place that
150
+ // decides whether it's actually persisted, keyed off the per-run capture mode rather
151
+ // than a process-wide setting — concurrent runs in 'normal' mode are unaffected by a
152
+ // sibling run's 'verbose'/'retain-on-failure' opt-in.
153
+ const captureMode = runContextStore.getStore()?.captureMode;
154
+ const isCapturedDebugOrInfo =
155
+ (level === 'debug' || level === 'info') && (captureMode === 'verbose' || captureMode === 'retain-on-failure');
156
+ if (DIAGNOSTICS_CAPTURE_ENABLED && (isWarnOrError || isCapturedDebugOrInfo)) {
157
+ // winston.errors({stack:true}) merges an Error's own enumerable properties (stack,
158
+ // and anything else the call site set, e.g. `err.code`) directly onto `info` — there
159
+ // is no separate nested info.err. `info.stack`'s presence is the only reliable signal
160
+ // that this record came from `logger.error('...', err)`/`logger.error(err)` rather
161
+ // than a plain string message. When present, info.message is already the
162
+ // stable-message-plus-error-message string winston produced, so err.message reuses it.
163
+ const hasErr = typeof info.stack === 'string';
164
+ const message = clamp(info.message, MAX_MESSAGE_LEN) ?? '';
165
+ const event: DiagnosticEvent = {
166
+ ts: typeof info.timestamp === 'string' ? info.timestamp : new Date().toISOString(),
167
+ level: String(info.level),
168
+ service: String(info.service ?? '@elisra-devops/docgen-data-provider'),
169
+ version: String(info.version ?? 'unknown'),
170
+ runId: typeof info.runId === 'string' ? info.runId : undefined,
171
+ docType: typeof info.docType === 'string' ? info.docType : undefined,
172
+ step: typeof info.step === 'string' ? info.step : undefined,
173
+ contentControlType: typeof info.contentControlType === 'string' ? info.contentControlType : undefined,
174
+ contentControlTitle: typeof info.contentControlTitle === 'string' ? info.contentControlTitle : undefined,
175
+ project: typeof info.project === 'string' ? info.project : undefined,
176
+ userId: typeof info.userId === 'string' ? info.userId : undefined,
177
+ message,
178
+ err: hasErr
179
+ ? {
180
+ message,
181
+ code: typeof info.code === 'string' ? info.code : undefined,
182
+ stack: clamp(info.stack, MAX_STACK_LEN),
183
+ }
184
+ : undefined,
185
+ retainPending: !isWarnOrError && captureMode === 'retain-on-failure' ? true : undefined,
186
+ };
187
+ getLogSink()?.push(event);
188
+ }
189
+ } catch (e) {
190
+ // eslint-disable-next-line no-console
191
+ console.error('DiagnosticsTransport failed to push event', e);
192
+ }
193
+ callback();
194
+ }
195
+ }
196
+
197
+ // LOG_FORMAT=json is the eventual default (structured stdout a collector can parse), but
198
+ // stays opt-in for one release so switching is a config change, not an image rebuild, if
199
+ // anyone reading raw console output needs to roll back.
200
+ const useJson = (process.env.LOG_FORMAT || 'text').toLowerCase() === 'json';
201
+
202
+ // Phase 6b — the Logger's own level gate must be 'debug' (winston's most permissive) so a
203
+ // debug/info call always reaches every transport's log(); a static per-logger level can't
204
+ // depend on the ALS store's per-run capture mode, so DiagnosticsTransport has to be the one
205
+ // deciding what's actually persisted. The Console transport below gets its own explicit
206
+ // level so stdout's default behavior (info/warn/error unless LOG_LEVEL=debug) is unchanged —
207
+ // this only spends the format-chain cost on debug() calls that previously short-circuited
208
+ // for free; info/warn/error volume (Phase 4's focus) is unaffected either way.
209
+ const CONSOLE_LOG_LEVEL = process.env.LOG_LEVEL || 'info';
210
+
27
211
  logger = winston.createLogger({
28
- format: winston.format.timestamp(),
29
- level: 'silly',
30
- transports: [
31
- new winston.transports.Console({ format: logFormat, level: 'debug' }),
32
- // new BrowserConsole({ format: logFormat, level: 'debug' }),
33
- ],
212
+ level: 'debug',
213
+ defaultMeta: { service: '@elisra-devops/docgen-data-provider', version: readOwnVersion() },
214
+ format: useJson
215
+ ? winston.format.combine(
216
+ winston.format.errors({ stack: true }),
217
+ winston.format.timestamp(),
218
+ withRunContext(),
219
+ redact(),
220
+ winston.format.splat(),
221
+ winston.format.json()
222
+ )
223
+ : winston.format.combine(
224
+ winston.format.errors({ stack: true }),
225
+ winston.format.timestamp(),
226
+ withRunContext(),
227
+ redact(),
228
+ winston.format.splat(),
229
+ textFormat
230
+ ),
231
+ // Stdout only — no File transports, consistent with the other DocGen services (no mounted
232
+ // log volume anywhere in this deployment, so a File transport is invisible to `kubectl logs`
233
+ // and can throw at import time under a read-only root filesystem).
234
+ transports: [new winston.transports.Console({ level: CONSOLE_LOG_LEVEL }), new DiagnosticsTransport()],
34
235
  });
35
- // }
36
236
 
37
237
  export default logger;
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+ import { AsyncLocalStorage } from 'async_hooks';
3
+
4
+ export interface RunContext {
5
+ runId: string;
6
+ // Phase 6b — this package never sets it, only reads it: content-control (the host process
7
+ // this package runs in-process inside) populates it via its own attachRunContext, and this
8
+ // package's DiagnosticsTransport reads the same in-process ALS store.
9
+ captureMode?: 'verbose' | 'retain-on-failure';
10
+ // Phase 7b — same read-only treatment as captureMode above.
11
+ docType?: string;
12
+ // Phase 7c — same read-only treatment; set by content-control's attachRunContext via
13
+ // x-docgen-project, visible here through the shared in-process ALS store.
14
+ project?: string;
15
+ }
16
+
17
+ // Symbol.for uses the global symbol registry, so every duplicated copy of this file across
18
+ // the DocGen packages — hoisted or nested at any depth by npm — converges on the same
19
+ // AsyncLocalStorage instance. Keying by module identity instead would silently split into
20
+ // two stores and runId would go missing with no visible error.
21
+ const KEY = Symbol.for('elisradevops.docgen.runContext');
22
+
23
+ export const runContextStore: AsyncLocalStorage<RunContext> =
24
+ ((globalThis as Record<symbol, unknown>)[KEY] as AsyncLocalStorage<RunContext> | undefined) ??
25
+ ((globalThis as Record<symbol, unknown>)[KEY] = new AsyncLocalStorage<RunContext>());