@nestjs/observe 0.3.26 → 0.3.28
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/README.md +38 -2
- package/dist/agent/observe-agent.shared-buffer.js +5 -0
- package/dist/agent/telemetry-wire-contract.js +3 -3
- package/dist/cli/link.js +24 -2
- package/dist/cli/package-manager.d.ts +6 -0
- package/dist/cli/package-manager.js +60 -3
- package/dist/cli/project-files.d.ts +25 -5
- package/dist/cli/project-files.js +98 -15
- package/dist/custom-metrics/summary.js +17 -10
- package/dist/instrument/create-instance-decorator.instrument.js +390 -38
- package/dist/instrument/raw-receiver.d.ts +6 -0
- package/dist/instrument/raw-receiver.js +32 -0
- package/dist/interfaces/observe-options.interface.d.ts +14 -5
- package/dist/otlp/otlp-span.mapper.d.ts +2 -0
- package/dist/otlp/otlp-span.mapper.js +19 -1
- package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
- package/dist/otlp/otlp-trace-exporter.service.js +232 -38
- package/dist/outgoing/http.integration.js +36 -11
- package/dist/outgoing/mongodb.integration.d.ts +3 -1
- package/dist/outgoing/mongodb.integration.js +93 -18
- package/dist/outgoing/mssql.integration.js +9 -4
- package/dist/outgoing/mysql2.integration.js +3 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
- package/dist/outgoing/pg.integration.js +5 -0
- package/dist/outgoing/sql-statement.util.js +36 -10
- package/dist/protocols/bull-observe-agent.service.js +21 -0
- package/dist/protocols/deferred-trace-completion.d.ts +8 -2
- package/dist/protocols/deferred-trace-completion.js +40 -3
- package/dist/protocols/graphql-observe-agent.service.d.ts +62 -2
- package/dist/protocols/graphql-observe-agent.service.js +188 -14
- package/dist/protocols/graphql-operation-parser.js +45 -14
- package/dist/protocols/http-observe-agent.service.d.ts +14 -7
- package/dist/protocols/http-observe-agent.service.js +57 -14
- package/dist/protocols/job-trace-runner.d.ts +7 -0
- package/dist/protocols/job-trace-runner.js +72 -8
- package/dist/protocols/rpc-observe-agent.service.d.ts +61 -0
- package/dist/protocols/rpc-observe-agent.service.js +146 -10
- package/dist/protocols/ws-observe-agent.service.js +1 -1
- package/dist/services/logger-patcher.service.js +13 -3
- package/dist/services/operation-trace.registry.d.ts +13 -0
- package/dist/services/operation-trace.registry.js +195 -65
- package/dist/services/stdout-forwarder.service.js +22 -2
- package/dist/services/tracer.service.d.ts +19 -14
- package/dist/services/tracer.service.js +57 -34
- package/dist/utils/capture-request.util.js +36 -8
- package/dist/utils/context-accessor.util.d.ts +16 -0
- package/dist/utils/context-accessor.util.js +28 -0
- package/dist/utils/default-trace-id-generator.util.js +5 -7
- package/dist/utils/error-stack.util.d.ts +13 -0
- package/dist/utils/error-stack.util.js +166 -0
- package/dist/utils/log-line.parser.d.ts +8 -0
- package/dist/utils/log-line.parser.js +13 -4
- package/dist/utils/log-redactor.js +184 -10
- package/dist/utils/redact-url-query.d.ts +16 -5
- package/dist/utils/redact-url-query.js +20 -7
- package/dist/utils/source-context.util.d.ts +6 -0
- package/dist/utils/source-context.util.js +68 -33
- package/dist/utils/source-map-resolver.util.js +25 -4
- package/dist/utils/store-copy.util.d.ts +10 -0
- package/dist/utils/store-copy.util.js +43 -0
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -446,6 +446,42 @@ Several of the places the agent hooks into hold one hook each: GraphQL's `Resolv
|
|
|
446
446
|
|
|
447
447
|
Set those after instead: on `app.getHttpAdapter()` before `listen()`, on `app.getTransportServer()`, or on the injected client from a provider.
|
|
448
448
|
|
|
449
|
+
### The request's async store
|
|
450
|
+
|
|
451
|
+
`ObserveModule` provides its `AsyncLocalStorage` to the whole application, under the `AsyncLocalStorage` class, so request context needs no other package: inject it anywhere. Each request, message, job or operation the agent handles runs with a `Map` of its own as the store, which holds what `setAttributes` returns and the trace id (under `traceIdKey`), and which you can read and write too. `TracerService.getAttribute()` and `setAttribute()` are the typed way in.
|
|
452
|
+
|
|
453
|
+
```ts
|
|
454
|
+
@Injectable()
|
|
455
|
+
export class CurrentTenant {
|
|
456
|
+
constructor(private readonly als: AsyncLocalStorage<Map<string, unknown>>) {}
|
|
457
|
+
|
|
458
|
+
get id() {
|
|
459
|
+
return this.als.getStore()?.get("tenantId") as string | undefined;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
The store is the agent's, so leave opening it to the agent: calling `run()` or `enterWith()` on it with a store of your own replaces the request's `Map`, and the agent loses the request. For a store of your own - Nest's async-local-storage recipe, say - provide it under a token of your own instead of the `AsyncLocalStorage` class, which would otherwise resolve to either one depending on the order of the imports. `enabled: false` does not change any of this: the store is provided either way.
|
|
465
|
+
|
|
466
|
+
### Guards and the handler they are handed
|
|
467
|
+
|
|
468
|
+
With `instrument: ObserveInstrument`, the controller and gateway methods Nest routes to are the agent's traced stand-ins for your methods, so `context.getHandler()` in a guard or interceptor returns the stand-in, not `MyController.prototype.method`. The stand-in carries the method's name and a copy of its metadata, taken when Nest registers the route. Reading that metadata through `Reflector`, as Nest's documentation does (`SetMetadata`, `Reflector.createDecorator()`), works the same with the agent as without it. Two things do not:
|
|
469
|
+
|
|
470
|
+
- **Looking a handler up by the function itself**: a `WeakMap` or `Map` keyed by the decorated method, or an `===` comparison with it. The stand-in is another function, so the lookup misses.
|
|
471
|
+
- **Metadata defined or changed after the route is registered**, in `onModuleInit` or at run time. The copy predates it.
|
|
472
|
+
|
|
473
|
+
A guard that treats such a miss as "no restriction" lets the request through. Keep what a guard reads on the method as metadata, defined by a decorator, and read it with `Reflector`. Where that is not possible, return `true` from `skipInstrumentation` for that controller or gateway, so it is left as it is.
|
|
474
|
+
|
|
475
|
+
### Scheduled jobs in a process with more than one application
|
|
476
|
+
|
|
477
|
+
`@nestjs/schedule` hands every `@Cron`, `@Interval` and `@Timeout` handler in the process through one shared method, and the agent patches it once: the first application in the process to construct its `ObserveModule` traces the scheduled handlers of every application there. This matters only when one process starts more than one application, or starts one again after `app.close()` - two applications side by side, a bootstrap that runs twice, a test file that does either. A later application's scheduled handlers then run under the first application's agent:
|
|
478
|
+
|
|
479
|
+
- Its `jobs` options (`ignore`, `tags`, `setAttributes`) are not used for them; the first application's are.
|
|
480
|
+
- With a `createObserveModule()` call of its own, the handlers run in the first agent's async context, while the `TracerService` injected into them reads the later application's. So `createSpan()` runs its callback untraced, `activeSpan()` hands back a span that records nothing, `setAttribute()` does nothing, `getAttribute()` returns `undefined` and `captureError()` records nothing. Their runs are not reported.
|
|
481
|
+
- Sharing one `createObserveModule()`, the `observe.ts` above, the handlers work, but their runs are reported through the first application's agent, under its `serviceId`, and not at all once that application has closed.
|
|
482
|
+
|
|
483
|
+
Keep scheduled jobs in one application per process, and construct that application first.
|
|
484
|
+
|
|
449
485
|
## Capturing failed and slow requests
|
|
450
486
|
|
|
451
487
|
The inputs behind a failing request are usually the fastest way to reproduce it. The agent keeps them only for the requests worth it - never for ordinary traffic:
|
|
@@ -589,7 +625,7 @@ What a backend receives, for each operation:
|
|
|
589
625
|
- **The same trace ids `traceparent` carries.** A request that arrived with a `traceparent` goes under the caller's span, a queue job or microservice message under the span that handed it on, and a call this service makes names its CLIENT span as the parent the callee sees - so services instrumented with OpenTelemetry, and other services running the agent, assemble into one trace in the backend.
|
|
590
626
|
- **Errors** as span status and an `exception` event, with the class, message and stack the dashboard shows - redacted the same way.
|
|
591
627
|
|
|
592
|
-
What is exported is what is recorded: after `tracesSampleRate`, `skipSpans` and `spanCollapse`, and on Free after what NestJS Observe holds back. A request whose caller sampled its trace out (`traceparent` flags `00`) is not exported, as an OpenTelemetry SDK sampling by its parent would leave it out. Spans wait in a queue of at most 10,000 while an export is retried (429, 502, 503 and 504, honouring `Retry-After`); past that, whole operations are dropped and counted. Exports run on the application's thread, outside its traces, and whatever is queued is exported when the application closes, within `shutdownFlushTimeout`. Traces only, for now: runtime metrics, custom metrics and logs are not exported.
|
|
628
|
+
What is exported is what is recorded: after `tracesSampleRate`, `skipSpans` and `spanCollapse`, and on Free after what NestJS Observe holds back. A request whose caller sampled its trace out (`traceparent` flags `00`) is not exported, as an OpenTelemetry SDK sampling by its parent would leave it out. Spans wait in a queue of at most 10,000, and at most 32 Mi characters of text, while an export is retried (429, 502, 503 and 504, honouring `Retry-After`); past that, whole operations are dropped and counted. An export carries at most 1,000 spans and 2 Mi characters, and a string attribute is cut to 16 KiB. Later batches go ahead of one the receiver turned away, and a batch it turns away three more times once one of them got through is dropped and counted too, so one it will never take does not hold up every trace after it. Exports run on the application's thread, outside its traces, and whatever is queued is exported when the application closes, within `shutdownFlushTimeout`. Traces only, for now: runtime metrics, custom metrics and logs are not exported.
|
|
593
629
|
|
|
594
630
|
## Configuration
|
|
595
631
|
|
|
@@ -619,7 +655,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
|
|
|
619
655
|
| `openTelemetry` | `false` | Continues and sends W3C `traceparent`, names a request after the W3C trace it is in, and follows an OpenTelemetry SDK running in the same process - see [Observe and OpenTelemetry](#observe-and-opentelemetry). Works only beside reporting to NestJS Observe, and stays on through collector outages. Off, the agent reads and sends `x-request-id` alone. |
|
|
620
656
|
| `http` | | `ignore`, `tags`, `setAttributes`, `getUserId`, `queryParamsObfuscateRegex`, `tracePreflights` and `capture` - see [Capturing failed and slow requests](#capturing-failed-and-slow-requests). |
|
|
621
657
|
| `rpc`, `grpc` | | `ignore`, `tags`, `setAttributes` and `getUserId` for microservice and gRPC handlers. |
|
|
622
|
-
| `graphql` | | The same four, once per GraphQL operation.
|
|
658
|
+
| `graphql` | | The same four, once per GraphQL operation. An operation `ignore` matches over HTTP takes the request's trace with it: nothing it reaches is recorded, nor anything else in a batched request it leads. |
|
|
623
659
|
| `ws` | | The same four, once per gateway message. |
|
|
624
660
|
| `jobs` | | `ignore`, `tags` and `setAttributes` for queue jobs and scheduled handlers. |
|
|
625
661
|
| `debug` | `false` | Logs the SDK's own diagnostics. |
|
|
@@ -837,6 +837,11 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
837
837
|
resetMainThreadBuffer() {
|
|
838
838
|
this._mainThreadBuffer = null;
|
|
839
839
|
this._metricsToEncode.clear();
|
|
840
|
+
// Of the batch just dropped, with the metrics in it. After a write that
|
|
841
|
+
// threw, they stayed, and the next batch written marked them delivered
|
|
842
|
+
// too: a counter's increase and a summary's window were lost unsent. A
|
|
843
|
+
// metric comes back at its next change, with its window still open.
|
|
844
|
+
this._awaitingFlushAck.clear();
|
|
840
845
|
this.withheldSnapshots = 0;
|
|
841
846
|
this.withheldJobs = 0;
|
|
842
847
|
}
|
|
@@ -48,9 +48,9 @@ const TRACE_NODE = {
|
|
|
48
48
|
t: { type: "object" },
|
|
49
49
|
d: { type: "number" },
|
|
50
50
|
// Boolean is the "an error occurred but was handled, details not captured"
|
|
51
|
-
// form - every failed non-root span,
|
|
52
|
-
// primitive,
|
|
53
|
-
// `TraceSpan.error`.
|
|
51
|
+
// form - every failed non-root span, a root span failing on a thrown
|
|
52
|
+
// primitive, and a failed root span past the trace's 20 recorded errors,
|
|
53
|
+
// reports `e: true` rather than an error object. See `TraceSpan.error`.
|
|
54
54
|
e: { type: "object", alsoAccepts: ["boolean"] },
|
|
55
55
|
c: { type: "string", required: true, maxLength: 255 },
|
|
56
56
|
m: { type: "string", required: true, maxLength: 255 },
|
package/dist/cli/link.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { writeAgentNotes } from "./agent-notes.js";
|
|
2
2
|
import { webAddress } from "./open-url.js";
|
|
3
3
|
import { addDependencyCommand, detectPackageManager, } from "./package-manager.js";
|
|
4
|
-
import { addEnvFileToStartScripts, ensureEnvIgnored, isEnvFileValue, isProjectFile, LINK_FILES, readPackageName, trackedEnvFile, writeEnvFile, } from "./project-files.js";
|
|
4
|
+
import { addEnvFileToStartScripts, ensureEnvIgnored, envFileIgnored, gitignoreProblem, isEnvFileValue, isProjectFile, LINK_FILES, readPackageName, trackedEnvFile, writeEnvFile, } from "./project-files.js";
|
|
5
5
|
import { findEntryFiles, inspectProject, QUICK_START_URL, SDK_PACKAGE, serviceIdFor, } from "./project-setup.js";
|
|
6
6
|
import { wireApplication } from "./wire-application.js";
|
|
7
7
|
/** Extra seconds `slow_down` adds to the interval, as RFC 8628 says. */
|
|
@@ -43,6 +43,11 @@ export async function link(options, deps) {
|
|
|
43
43
|
deps.log(`${tracked} is tracked by git, so the secret link writes into it would be in your next commit, whatever .gitignore says. Run git rm --cached ${tracked}, which keeps the file, and link again. Nothing was written.`);
|
|
44
44
|
return 1;
|
|
45
45
|
}
|
|
46
|
+
const gitignore = gitignoreProblem(options.cwd);
|
|
47
|
+
if (gitignore) {
|
|
48
|
+
deps.log(`${gitignore} Nothing was written.`);
|
|
49
|
+
return 1;
|
|
50
|
+
}
|
|
46
51
|
const manager = detectPackageManager(options.cwd);
|
|
47
52
|
let started;
|
|
48
53
|
try {
|
|
@@ -81,8 +86,25 @@ export async function link(options, deps) {
|
|
|
81
86
|
deps.log(credentials);
|
|
82
87
|
return 1;
|
|
83
88
|
}
|
|
89
|
+
// `.env` is kept out of git before the secret is in it: written first, a
|
|
90
|
+
// .gitignore that then could not be updated left the secret in a file
|
|
91
|
+
// the next `git add .` takes.
|
|
92
|
+
let ignoredNow;
|
|
93
|
+
try {
|
|
94
|
+
ignoredNow = ensureEnvIgnored(options.cwd);
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
deps.log(`Could not add .env to .gitignore (${describe(err)}), so the key pair was not written: it would not stay out of git. Fix .gitignore and link again.`);
|
|
98
|
+
return 1;
|
|
99
|
+
}
|
|
100
|
+
// Git has the last word on what it ignores: a rule elsewhere can take
|
|
101
|
+
// .env back, and a .env that links to another file is not what keeps
|
|
102
|
+
// that file out. Without a repository or git there is no one to ask.
|
|
103
|
+
if (envFileIgnored(options.cwd) === false) {
|
|
104
|
+
deps.log(`git does not ignore .env, or the file it leads to,${ignoredNow ? " even with the rule link added to .gitignore," : ""} so the key pair was not written: it would be in your next commit. git check-ignore -v .env shows the rule git goes by; link again once git ignores it.`);
|
|
105
|
+
return 1;
|
|
106
|
+
}
|
|
84
107
|
writeEnvFile(options.cwd, credentials.appKey, credentials.appSecret);
|
|
85
|
-
const ignoredNow = ensureEnvIgnored(options.cwd);
|
|
86
108
|
const scripts = addEnvFileToStartScripts(options.cwd);
|
|
87
109
|
deps.log("");
|
|
88
110
|
deps.log(`✔ Linked to ${credentials.applicationName} in ${credentials.projectName}. The key pair is in .env.`);
|
|
@@ -7,6 +7,12 @@ export type PackageManager = "npm" | "pnpm" | "yarn" | "bun";
|
|
|
7
7
|
* one, Corepack's `packageManager` field in package.json does, and npm is
|
|
8
8
|
* the answer when neither says anything. Running `npx` says nothing either
|
|
9
9
|
* way: it is how the command was started, not how the project installs.
|
|
10
|
+
*
|
|
11
|
+
* A project in no repository has no root to stop at, and a lockfile above
|
|
12
|
+
* it - a forgotten one in the home directory, say - belongs to something
|
|
13
|
+
* else: it made link install with a manager the project does not use, and
|
|
14
|
+
* outranked the project's own `packageManager` field. There, only `cwd` and
|
|
15
|
+
* the workspace it is a package of, if any, are looked in.
|
|
10
16
|
*/
|
|
11
17
|
export declare function detectPackageManager(cwd: string): PackageManager;
|
|
12
18
|
/** The command that adds `spec` to the project's dependencies. */
|
|
@@ -18,21 +18,78 @@ const MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]);
|
|
|
18
18
|
* one, Corepack's `packageManager` field in package.json does, and npm is
|
|
19
19
|
* the answer when neither says anything. Running `npx` says nothing either
|
|
20
20
|
* way: it is how the command was started, not how the project installs.
|
|
21
|
+
*
|
|
22
|
+
* A project in no repository has no root to stop at, and a lockfile above
|
|
23
|
+
* it - a forgotten one in the home directory, say - belongs to something
|
|
24
|
+
* else: it made link install with a manager the project does not use, and
|
|
25
|
+
* outranked the project's own `packageManager` field. There, only `cwd` and
|
|
26
|
+
* the workspace it is a package of, if any, are looked in.
|
|
21
27
|
*/
|
|
22
28
|
export function detectPackageManager(cwd) {
|
|
29
|
+
const root = repositoryRoot(cwd);
|
|
30
|
+
if (root === undefined) {
|
|
31
|
+
const workspace = workspaceRoot(cwd);
|
|
32
|
+
return (lockfileIn(cwd) ??
|
|
33
|
+
(workspace === undefined ? undefined : lockfileIn(workspace)) ??
|
|
34
|
+
declaredPackageManager(cwd) ??
|
|
35
|
+
(workspace === undefined
|
|
36
|
+
? undefined
|
|
37
|
+
: declaredPackageManager(workspace)) ??
|
|
38
|
+
"npm");
|
|
39
|
+
}
|
|
23
40
|
for (let dir = cwd;; dir = dirname(dir)) {
|
|
24
|
-
const found =
|
|
41
|
+
const found = lockfileIn(dir);
|
|
25
42
|
if (found) {
|
|
26
|
-
return found
|
|
43
|
+
return found;
|
|
27
44
|
}
|
|
28
45
|
// The repository's root is as far as the project goes: a lockfile
|
|
29
46
|
// above it belongs to something else.
|
|
30
|
-
if (
|
|
47
|
+
if (dir === root) {
|
|
31
48
|
break;
|
|
32
49
|
}
|
|
33
50
|
}
|
|
34
51
|
return declaredPackageManager(cwd) ?? "npm";
|
|
35
52
|
}
|
|
53
|
+
function lockfileIn(dir) {
|
|
54
|
+
return LOCKFILES.find(([file]) => existsSync(join(dir, file)))?.[1];
|
|
55
|
+
}
|
|
56
|
+
/** The nearest directory from `cwd` up that holds a `.git`. */
|
|
57
|
+
function repositoryRoot(cwd) {
|
|
58
|
+
for (let dir = cwd;; dir = dirname(dir)) {
|
|
59
|
+
if (existsSync(join(dir, ".git"))) {
|
|
60
|
+
return dir;
|
|
61
|
+
}
|
|
62
|
+
if (dirname(dir) === dir) {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The nearest directory above `cwd` that is a workspace's root - one with a
|
|
69
|
+
* `pnpm-workspace.yaml`, or a package.json that lists `workspaces` - where
|
|
70
|
+
* the lockfile of a package inside it is.
|
|
71
|
+
*/
|
|
72
|
+
function workspaceRoot(cwd) {
|
|
73
|
+
for (let dir = dirname(cwd);; dir = dirname(dir)) {
|
|
74
|
+
if (existsSync(join(dir, "pnpm-workspace.yaml")) || listsWorkspaces(dir)) {
|
|
75
|
+
return dir;
|
|
76
|
+
}
|
|
77
|
+
if (dirname(dir) === dir) {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** Whether `<dir>/package.json` lists `workspaces`, as npm, Yarn and Bun read them. */
|
|
83
|
+
function listsWorkspaces(dir) {
|
|
84
|
+
try {
|
|
85
|
+
const { workspaces } = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
86
|
+
return (Array.isArray(workspaces) ||
|
|
87
|
+
Array.isArray(workspaces?.packages));
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
36
93
|
/** `"pnpm@9.12.0"` in package.json's `packageManager` field, as `"pnpm"`. */
|
|
37
94
|
function declaredPackageManager(cwd) {
|
|
38
95
|
try {
|
|
@@ -47,13 +47,33 @@ export declare function writeEnvFile(cwd: string, appKey: string, appSecret: str
|
|
|
47
47
|
*
|
|
48
48
|
* An ignore rule does not apply to a file in the index, so the secret written
|
|
49
49
|
* into a tracked `.env` would be in the next `git commit -a` whatever
|
|
50
|
-
* `.gitignore` says. Git is asked
|
|
51
|
-
*
|
|
52
|
-
* a project's own `.git/config` could use to run a program turned off:
|
|
53
|
-
* `core.fsmonitor`, which `ls-files` would start, and the discovery of a bare
|
|
54
|
-
* repository that only sits in the checkout.
|
|
50
|
+
* `.gitignore` says. Git is asked as `askGit` asks it, with nothing of the
|
|
51
|
+
* project's that could run a program.
|
|
55
52
|
*/
|
|
56
53
|
export declare function trackedEnvFile(cwd: string): string | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* Whether git ignores the file the key pair is written into - `.env`, or
|
|
56
|
+
* what it links to: true or false as git answers, undefined when there is
|
|
57
|
+
* no repository or no git to ask.
|
|
58
|
+
*
|
|
59
|
+
* Asked of git itself, after `ensureEnvIgnored`, rather than read off
|
|
60
|
+
* `.gitignore`: git decides with every ignore file there is, and a rule
|
|
61
|
+
* `ensureEnvIgnored` saw does not ignore a file `.env` links to under
|
|
62
|
+
* another name. Asked the way `trackedEnvFile` asks.
|
|
63
|
+
*/
|
|
64
|
+
export declare function envFileIgnored(cwd: string): boolean | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Why `ensureEnvIgnored` could not add `.env` to `<cwd>/.gitignore`, or
|
|
67
|
+
* undefined when it can: the file is there, a regular file that can be read
|
|
68
|
+
* and written, or it is not and the directory can take it. Asked before a
|
|
69
|
+
* code is, so no pair is issued for a project it could not be kept out of
|
|
70
|
+
* git in.
|
|
71
|
+
*
|
|
72
|
+
* A link is refused even when it stays in the project: git reads no
|
|
73
|
+
* `.gitignore` that is a symbolic link (2.32 and later), so a rule written
|
|
74
|
+
* through it would keep nothing out of git, however it read.
|
|
75
|
+
*/
|
|
76
|
+
export declare function gitignoreProblem(cwd: string): string | undefined;
|
|
57
77
|
/**
|
|
58
78
|
* Makes sure `.env` is git-ignored, so the secret cannot be committed by
|
|
59
79
|
* accident. `nest new` already ignores it; a project from elsewhere may not.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
-
import { existsSync, lstatSync, readFileSync, realpathSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { accessSync, constants, existsSync, lstatSync, readFileSync, realpathSync, writeFileSync, } from "node:fs";
|
|
3
3
|
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
4
4
|
/** The files `link` writes in every project, whatever else it does. */
|
|
5
5
|
export const LINK_FILES = [".env", ".gitignore", "package.json"];
|
|
@@ -109,13 +109,53 @@ export function writeEnvFile(cwd, appKey, appSecret) {
|
|
|
109
109
|
*
|
|
110
110
|
* An ignore rule does not apply to a file in the index, so the secret written
|
|
111
111
|
* into a tracked `.env` would be in the next `git commit -a` whatever
|
|
112
|
-
* `.gitignore` says. Git is asked
|
|
113
|
-
*
|
|
114
|
-
* a project's own `.git/config` could use to run a program turned off:
|
|
115
|
-
* `core.fsmonitor`, which `ls-files` would start, and the discovery of a bare
|
|
116
|
-
* repository that only sits in the checkout.
|
|
112
|
+
* `.gitignore` says. Git is asked as `askGit` asks it, with nothing of the
|
|
113
|
+
* project's that could run a program.
|
|
117
114
|
*/
|
|
118
115
|
export function trackedEnvFile(cwd) {
|
|
116
|
+
const env = envFileOf(cwd);
|
|
117
|
+
if (!env) {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
const status = askGit(dirname(env.path), [
|
|
121
|
+
"--literal-pathspecs",
|
|
122
|
+
"ls-files",
|
|
123
|
+
"--error-unmatch",
|
|
124
|
+
"--",
|
|
125
|
+
basename(env.path),
|
|
126
|
+
]);
|
|
127
|
+
return status === 0 ? relative(env.root, env.path) || ".env" : undefined;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Whether git ignores the file the key pair is written into - `.env`, or
|
|
131
|
+
* what it links to: true or false as git answers, undefined when there is
|
|
132
|
+
* no repository or no git to ask.
|
|
133
|
+
*
|
|
134
|
+
* Asked of git itself, after `ensureEnvIgnored`, rather than read off
|
|
135
|
+
* `.gitignore`: git decides with every ignore file there is, and a rule
|
|
136
|
+
* `ensureEnvIgnored` saw does not ignore a file `.env` links to under
|
|
137
|
+
* another name. Asked the way `trackedEnvFile` asks.
|
|
138
|
+
*/
|
|
139
|
+
export function envFileIgnored(cwd) {
|
|
140
|
+
const env = envFileOf(cwd);
|
|
141
|
+
if (!env) {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
// `check-ignore` takes no `--literal-pathspecs`; a name after `./` is a
|
|
145
|
+
// name, whatever it starts with.
|
|
146
|
+
const status = askGit(dirname(env.path), [
|
|
147
|
+
"check-ignore",
|
|
148
|
+
"-q",
|
|
149
|
+
"--",
|
|
150
|
+
`./${basename(env.path)}`,
|
|
151
|
+
]);
|
|
152
|
+
return status === 0 ? true : status === 1 ? false : undefined;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* The project's real directory, and the real path of its `.env` - what it
|
|
156
|
+
* links to, or where it would be created.
|
|
157
|
+
*/
|
|
158
|
+
function envFileOf(cwd) {
|
|
119
159
|
let root;
|
|
120
160
|
try {
|
|
121
161
|
root = realpathSync(cwd);
|
|
@@ -130,20 +170,63 @@ export function trackedEnvFile(cwd) {
|
|
|
130
170
|
catch {
|
|
131
171
|
// Not there yet, though it may still be in the index.
|
|
132
172
|
}
|
|
133
|
-
|
|
173
|
+
return { root, path };
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Runs git with `args` in `dir` and returns its exit status, null when it
|
|
177
|
+
* could not run. Its arguments are fixed, it starts from Node's own
|
|
178
|
+
* directory and is pointed at the project with `-C`, and the two settings
|
|
179
|
+
* a project's own `.git/config` could use to run a program are turned off:
|
|
180
|
+
* `core.fsmonitor`, which reading the index starts, and the discovery of
|
|
181
|
+
* a bare repository that only sits in the checkout.
|
|
182
|
+
*/
|
|
183
|
+
function askGit(dir, args) {
|
|
184
|
+
return spawnSync("git", [
|
|
134
185
|
"-c",
|
|
135
186
|
"core.fsmonitor=false",
|
|
136
187
|
"-c",
|
|
137
188
|
"safe.bareRepository=explicit",
|
|
138
|
-
"--literal-pathspecs",
|
|
139
189
|
"-C",
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
190
|
+
dir,
|
|
191
|
+
...args,
|
|
192
|
+
], { cwd: dirname(process.execPath), stdio: "ignore", timeout: 10_000 }).status;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Why `ensureEnvIgnored` could not add `.env` to `<cwd>/.gitignore`, or
|
|
196
|
+
* undefined when it can: the file is there, a regular file that can be read
|
|
197
|
+
* and written, or it is not and the directory can take it. Asked before a
|
|
198
|
+
* code is, so no pair is issued for a project it could not be kept out of
|
|
199
|
+
* git in.
|
|
200
|
+
*
|
|
201
|
+
* A link is refused even when it stays in the project: git reads no
|
|
202
|
+
* `.gitignore` that is a symbolic link (2.32 and later), so a rule written
|
|
203
|
+
* through it would keep nothing out of git, however it read.
|
|
204
|
+
*/
|
|
205
|
+
export function gitignoreProblem(cwd) {
|
|
206
|
+
const path = join(cwd, ".gitignore");
|
|
207
|
+
const stats = lstatSync(path, { throwIfNoEntry: false });
|
|
208
|
+
if (stats === undefined) {
|
|
209
|
+
try {
|
|
210
|
+
accessSync(cwd, constants.W_OK);
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return `There is no .gitignore in ${cwd} and the directory cannot be written to, so link could not keep .env out of git.`;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (stats.isSymbolicLink()) {
|
|
218
|
+
return ".gitignore is a symbolic link, and git does not read one, so a rule in it would not keep .env out of git. Put the file itself in its place and link again.";
|
|
219
|
+
}
|
|
220
|
+
if (!stats.isFile()) {
|
|
221
|
+
return ".gitignore is not a file, so link could not keep .env out of git.";
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
accessSync(path, constants.R_OK | constants.W_OK);
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return ".gitignore cannot be read and written, so link could not keep .env out of git.";
|
|
229
|
+
}
|
|
147
230
|
}
|
|
148
231
|
/**
|
|
149
232
|
* Makes sure `.env` is git-ignored, so the secret cannot be committed by
|
|
@@ -10,6 +10,13 @@ const DEFAULT_LABEL = "default";
|
|
|
10
10
|
* separately and stay exact however many observations arrive.
|
|
11
11
|
*/
|
|
12
12
|
const DEFAULT_SAMPLE_SIZE = 2048;
|
|
13
|
+
/**
|
|
14
|
+
* A record keyed by label, with no prototype. A summary that declared no
|
|
15
|
+
* labels takes any, and on a plain object a label such as `constructor` or
|
|
16
|
+
* `toString` found an inherited member: its first observation was added to a
|
|
17
|
+
* function, and refused as a total past the largest number.
|
|
18
|
+
*/
|
|
19
|
+
const byLabel = () => Object.create(null);
|
|
13
20
|
/**
|
|
14
21
|
* A distribution of observations - request latency being the usual case.
|
|
15
22
|
*
|
|
@@ -68,13 +75,13 @@ export class Summary {
|
|
|
68
75
|
* Exact per-label aggregates for the current window. Tracked apart from the
|
|
69
76
|
* sample below so they describe every observation, not just the retained ones.
|
|
70
77
|
*/
|
|
71
|
-
_count =
|
|
72
|
-
_sum =
|
|
73
|
-
_max =
|
|
78
|
+
_count = byLabel();
|
|
79
|
+
_sum = byLabel();
|
|
80
|
+
_max = byLabel();
|
|
74
81
|
/**
|
|
75
82
|
* Bounded per-label sample the quantiles are read off.
|
|
76
83
|
*/
|
|
77
|
-
_samples =
|
|
84
|
+
_samples = byLabel();
|
|
78
85
|
/**
|
|
79
86
|
* The medians, doubling as the metric's headline reading.
|
|
80
87
|
*
|
|
@@ -198,10 +205,10 @@ export class Summary {
|
|
|
198
205
|
*/
|
|
199
206
|
markFlushed() {
|
|
200
207
|
this._windowLabels = 0;
|
|
201
|
-
this._count =
|
|
202
|
-
this._sum =
|
|
203
|
-
this._max =
|
|
204
|
-
this._samples =
|
|
208
|
+
this._count = byLabel();
|
|
209
|
+
this._sum = byLabel();
|
|
210
|
+
this._max = byLabel();
|
|
211
|
+
this._samples = byLabel();
|
|
205
212
|
}
|
|
206
213
|
/**
|
|
207
214
|
* Whether a summary that declared no labels may record under `label`: one
|
|
@@ -270,7 +277,7 @@ export class Summary {
|
|
|
270
277
|
* Nearest-rank quantile per label, read off a sorted copy of the sample.
|
|
271
278
|
*/
|
|
272
279
|
quantile(percentile) {
|
|
273
|
-
const quantiles =
|
|
280
|
+
const quantiles = byLabel();
|
|
274
281
|
for (const [key, samples] of Object.entries(this._samples)) {
|
|
275
282
|
if (!samples.length) {
|
|
276
283
|
continue;
|
|
@@ -279,6 +286,6 @@ export class Summary {
|
|
|
279
286
|
const rank = Math.ceil(percentile * sorted.length) - 1;
|
|
280
287
|
quantiles[key] = sorted[Math.min(Math.max(rank, 0), sorted.length - 1)];
|
|
281
288
|
}
|
|
282
|
-
return quantiles;
|
|
289
|
+
return { ...quantiles };
|
|
283
290
|
}
|
|
284
291
|
}
|