@watchtowerobservability/checks 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/README.md +32 -2
- package/dist/cli.d.ts +26 -0
- package/dist/cli.js +202 -0
- package/dist/index.d.ts +145 -0
- package/dist/index.js +153 -0
- package/dist/tracetest.d.ts +55 -0
- package/dist/tracetest.js +54 -0
- package/package.json +41 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,33 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @watchtowerobservability/checks
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Watchtower monitors as TypeScript. A config file default-exports a project; `wt-checks` turns it
|
|
4
|
+
into `watchtower.dev/v1` manifests and syncs them through the API with `wtctl` (same engine as
|
|
5
|
+
`wtctl apply` and the Terraform provider).
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// checks.config.ts
|
|
9
|
+
import { browser, defineProject, http, secret, step, totp } from "@watchtowerobservability/checks";
|
|
10
|
+
|
|
11
|
+
export default defineProject({
|
|
12
|
+
env: "env_123",
|
|
13
|
+
defaults: { interval: "1m", locations: ["eu-west", "us-east"] },
|
|
14
|
+
secrets: [secret("LOGIN_MFA", { fromEnv: "LOGIN_MFA_SEED" })],
|
|
15
|
+
checks: [
|
|
16
|
+
http("api-health", { url: "https://api.example.com/health", assertions: ["[STATUS] == 200"] }),
|
|
17
|
+
browser("login", {
|
|
18
|
+
steps: [step.goto("https://app.example.com/login"), step.fill("#otp", totp("LOGIN_MFA")), step.click("button[type=submit]")],
|
|
19
|
+
}),
|
|
20
|
+
],
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
npx wt-checks test --project prj_1 # synth + wtctl diff: what deploy would change
|
|
26
|
+
npx wt-checks deploy --project prj_1 # synth + wtctl apply (add --prune to delete removed checks)
|
|
27
|
+
npx wt-checks watch --project prj_1 # apply now and on every save (hot reload)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
`WT_API` and `WT_API_KEY` (or `--api`, `--key`) reach your Watchtower; `WTCTL` picks the `wtctl`
|
|
31
|
+
binary. Secret values never live in code: `secret(name, { fromEnv })` reads an environment variable
|
|
32
|
+
at apply time, and checks reference it with `secretRef(name)` or `totp(name)`. Node 22.18 or newer
|
|
33
|
+
loads the `.ts` config directly.
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { type Manifest, type ProjectDef } from "./index.ts";
|
|
3
|
+
export declare const USAGE = "usage: wt-checks <synth|test|deploy|watch> [--config checks.config.ts] [--out .watchtower/checks]\n [--project <id>] [--api <url>] [--key <key>] [--prune] (passed to wtctl; WTCTL picks the binary)\n synth write one manifest per check and secret to --out\n test synth, then show what deploy would change (wtctl diff); nothing is changed\n deploy synth, then apply the manifests (wtctl apply)\n watch synth and apply now, then again on every change to the config or the files it imports";
|
|
4
|
+
export interface Opts {
|
|
5
|
+
cmd: "synth" | "test" | "deploy" | "watch";
|
|
6
|
+
config: string;
|
|
7
|
+
out: string;
|
|
8
|
+
pass: string[];
|
|
9
|
+
}
|
|
10
|
+
export declare function parseArgs(argv: string[]): Opts;
|
|
11
|
+
export declare function loadProject(file: string): Promise<ProjectDef>;
|
|
12
|
+
/**
|
|
13
|
+
* Writes the manifests to dir: changed files only (atomically, so a watcher never reads half a
|
|
14
|
+
* file), then removes manifests no longer defined. New files land before stale ones go, so an
|
|
15
|
+
* apply with --prune never sees a partial set.
|
|
16
|
+
*/
|
|
17
|
+
export declare function writeManifests(dir: string, manifests: Manifest[]): {
|
|
18
|
+
written: number;
|
|
19
|
+
removed: number;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Calls onChange (debounced) when a source file below root changes. Paths below an ignored
|
|
23
|
+
* directory, node_modules and .git do not count. Returns the stop function.
|
|
24
|
+
*/
|
|
25
|
+
export declare function watchSources(root: string, ignore: string[], onChange: () => void, debounceMs?: number): () => void;
|
|
26
|
+
export declare function main(argv: string[], log?: (s: string) => void): Promise<number>;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
3
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
4
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
5
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
return path;
|
|
9
|
+
};
|
|
10
|
+
// wt-checks: synthesize a checks config into manifests and sync them with wtctl
|
|
11
|
+
// (`apply`, `diff`, and `checks watch` for hot reload).
|
|
12
|
+
import { spawn } from "node:child_process";
|
|
13
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, watch, writeFileSync } from "node:fs";
|
|
14
|
+
import { dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
15
|
+
import { pathToFileURL } from "node:url";
|
|
16
|
+
import { synth } from "./index.js";
|
|
17
|
+
export const USAGE = `usage: wt-checks <synth|test|deploy|watch> [--config checks.config.ts] [--out .watchtower/checks]
|
|
18
|
+
[--project <id>] [--api <url>] [--key <key>] [--prune] (passed to wtctl; WTCTL picks the binary)
|
|
19
|
+
synth write one manifest per check and secret to --out
|
|
20
|
+
test synth, then show what deploy would change (wtctl diff); nothing is changed
|
|
21
|
+
deploy synth, then apply the manifests (wtctl apply)
|
|
22
|
+
watch synth and apply now, then again on every change to the config or the files it imports`;
|
|
23
|
+
/** The file that marks a directory as ours; only such a directory has stale manifests removed. */
|
|
24
|
+
const MARK = ".wt-checks";
|
|
25
|
+
const SOURCES = new Set([".ts", ".mts", ".cts", ".js", ".mjs", ".cjs", ".json"]);
|
|
26
|
+
export function parseArgs(argv) {
|
|
27
|
+
const [cmd = "", ...rest] = argv;
|
|
28
|
+
let config = "checks.config.ts";
|
|
29
|
+
let out = join(".watchtower", "checks");
|
|
30
|
+
const pass = [];
|
|
31
|
+
for (let i = 0; i < rest.length; i++) {
|
|
32
|
+
const a = rest[i];
|
|
33
|
+
const value = () => {
|
|
34
|
+
const v = rest[++i];
|
|
35
|
+
if (v === undefined || v.startsWith("--"))
|
|
36
|
+
throw new Error(`${a} needs a value\n${USAGE}`);
|
|
37
|
+
return v;
|
|
38
|
+
};
|
|
39
|
+
if (a === "--config" || a === "-c")
|
|
40
|
+
config = value();
|
|
41
|
+
else if (a === "--out" || a === "-o")
|
|
42
|
+
out = value();
|
|
43
|
+
else
|
|
44
|
+
pass.push(a);
|
|
45
|
+
}
|
|
46
|
+
if (cmd !== "synth" && cmd !== "test" && cmd !== "deploy" && cmd !== "watch")
|
|
47
|
+
throw new Error(USAGE);
|
|
48
|
+
return { cmd, config: resolve(config), out: resolve(out), pass };
|
|
49
|
+
}
|
|
50
|
+
export async function loadProject(file) {
|
|
51
|
+
const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(file).href)));
|
|
52
|
+
const def = mod.default;
|
|
53
|
+
if (!def || !Array.isArray(def.checks)) {
|
|
54
|
+
throw new Error(`${file} must default-export defineProject({ checks: [...] })`);
|
|
55
|
+
}
|
|
56
|
+
return def;
|
|
57
|
+
}
|
|
58
|
+
const fileName = (m) => `${m.kind}-${m.metadata.name}.json`;
|
|
59
|
+
/**
|
|
60
|
+
* Writes the manifests to dir: changed files only (atomically, so a watcher never reads half a
|
|
61
|
+
* file), then removes manifests no longer defined. New files land before stale ones go, so an
|
|
62
|
+
* apply with --prune never sees a partial set.
|
|
63
|
+
*/
|
|
64
|
+
export function writeManifests(dir, manifests) {
|
|
65
|
+
if (existsSync(dir) && !existsSync(join(dir, MARK)) && readdirSync(dir).length > 0) {
|
|
66
|
+
throw new Error(`${dir} is not empty and not a wt-checks output directory; pick another --out`);
|
|
67
|
+
}
|
|
68
|
+
mkdirSync(dir, { recursive: true });
|
|
69
|
+
writeFileSync(join(dir, MARK), "generated by wt-checks; *.json here is rewritten on every synth\n");
|
|
70
|
+
const keep = new Set();
|
|
71
|
+
let written = 0;
|
|
72
|
+
for (const m of manifests) {
|
|
73
|
+
const name = fileName(m);
|
|
74
|
+
keep.add(name);
|
|
75
|
+
const path = join(dir, name);
|
|
76
|
+
const body = JSON.stringify(m, null, 2) + "\n";
|
|
77
|
+
if (existsSync(path) && readFileSync(path, "utf8") === body)
|
|
78
|
+
continue;
|
|
79
|
+
writeFileSync(path + ".tmp", body);
|
|
80
|
+
renameSync(path + ".tmp", path);
|
|
81
|
+
written++;
|
|
82
|
+
}
|
|
83
|
+
let removed = 0;
|
|
84
|
+
for (const f of readdirSync(dir)) {
|
|
85
|
+
if (f.endsWith(".json") && !keep.has(f)) {
|
|
86
|
+
rmSync(join(dir, f));
|
|
87
|
+
removed++;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { written, removed };
|
|
91
|
+
}
|
|
92
|
+
async function synthTo(o, log) {
|
|
93
|
+
const ms = synth(await loadProject(o.config));
|
|
94
|
+
const r = writeManifests(o.out, ms);
|
|
95
|
+
log(`${ms.length} manifest(s) in ${relative(process.cwd(), o.out) || "."}: ${r.written} written, ${r.removed} removed`);
|
|
96
|
+
}
|
|
97
|
+
function wtctl(args) {
|
|
98
|
+
const bin = process.env.WTCTL || "wtctl";
|
|
99
|
+
const js = /\.[cm]?js$/.test(bin) || /\.ts$/.test(bin);
|
|
100
|
+
return spawn(js ? process.execPath : bin, js ? [bin, ...args] : args, { stdio: "inherit" });
|
|
101
|
+
}
|
|
102
|
+
function exitOf(child) {
|
|
103
|
+
return new Promise((done) => {
|
|
104
|
+
child.on("error", (e) => {
|
|
105
|
+
process.stderr.write(`wt-checks: cannot run wtctl (${e.message}); install it or set WTCTL\n`);
|
|
106
|
+
done(2);
|
|
107
|
+
});
|
|
108
|
+
child.on("exit", (code) => done(code ?? 1));
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Calls onChange (debounced) when a source file below root changes. Paths below an ignored
|
|
113
|
+
* directory, node_modules and .git do not count. Returns the stop function.
|
|
114
|
+
*/
|
|
115
|
+
export function watchSources(root, ignore, onChange, debounceMs = 300) {
|
|
116
|
+
let timer;
|
|
117
|
+
const w = watch(root, { recursive: true }, (_event, name) => {
|
|
118
|
+
if (!name)
|
|
119
|
+
return;
|
|
120
|
+
const abs = resolve(root, name.toString());
|
|
121
|
+
const parts = relative(root, abs).split(sep);
|
|
122
|
+
if (parts.includes("node_modules") || parts.includes(".git"))
|
|
123
|
+
return;
|
|
124
|
+
if (ignore.some((d) => abs === d || abs.startsWith(d + sep)))
|
|
125
|
+
return;
|
|
126
|
+
if (!SOURCES.has(extname(abs)))
|
|
127
|
+
return;
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
timer = setTimeout(onChange, debounceMs);
|
|
130
|
+
});
|
|
131
|
+
return () => {
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
w.close();
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/** Re-synthesizes in a fresh process, so edits to files the config imports are seen too. */
|
|
137
|
+
function resynth(o) {
|
|
138
|
+
const script = process.argv[1];
|
|
139
|
+
const child = spawn(process.execPath, [...process.execArgv, script, "synth", "--config", o.config, "--out", o.out], {
|
|
140
|
+
stdio: "inherit",
|
|
141
|
+
});
|
|
142
|
+
return exitOf(child);
|
|
143
|
+
}
|
|
144
|
+
async function watchMode(o, log) {
|
|
145
|
+
try {
|
|
146
|
+
await synthTo(o, log);
|
|
147
|
+
}
|
|
148
|
+
catch (e) {
|
|
149
|
+
log(`synth failed, waiting for the next change: ${e.message}`);
|
|
150
|
+
}
|
|
151
|
+
// wtctl applies now and after every manifest change; we keep the manifests current
|
|
152
|
+
const child = wtctl(["checks", "watch", "-f", o.out, ...o.pass]);
|
|
153
|
+
let running = false;
|
|
154
|
+
let again = false;
|
|
155
|
+
const run = async () => {
|
|
156
|
+
if (running) {
|
|
157
|
+
again = true;
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
running = true;
|
|
161
|
+
do {
|
|
162
|
+
again = false;
|
|
163
|
+
log("change detected, synthesizing");
|
|
164
|
+
if ((await resynth(o)) !== 0)
|
|
165
|
+
log("synth failed, waiting for the next change");
|
|
166
|
+
} while (again);
|
|
167
|
+
running = false;
|
|
168
|
+
};
|
|
169
|
+
const stop = watchSources(dirname(o.config), [o.out], () => void run());
|
|
170
|
+
const quit = () => child.kill("SIGINT");
|
|
171
|
+
process.once("SIGINT", quit);
|
|
172
|
+
process.once("SIGTERM", quit);
|
|
173
|
+
const code = await exitOf(child);
|
|
174
|
+
stop();
|
|
175
|
+
return code;
|
|
176
|
+
}
|
|
177
|
+
export async function main(argv, log = (s) => process.stderr.write(s + "\n")) {
|
|
178
|
+
let o;
|
|
179
|
+
try {
|
|
180
|
+
o = parseArgs(argv);
|
|
181
|
+
}
|
|
182
|
+
catch (e) {
|
|
183
|
+
log(e.message);
|
|
184
|
+
return 2;
|
|
185
|
+
}
|
|
186
|
+
if (o.cmd === "watch")
|
|
187
|
+
return watchMode(o, log);
|
|
188
|
+
try {
|
|
189
|
+
await synthTo(o, log);
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
log(`synth failed: ${e.message}`);
|
|
193
|
+
return 1;
|
|
194
|
+
}
|
|
195
|
+
if (o.cmd === "synth")
|
|
196
|
+
return 0;
|
|
197
|
+
return exitOf(wtctl([o.cmd === "deploy" ? "apply" : "diff", "-f", o.out, ...o.pass]));
|
|
198
|
+
}
|
|
199
|
+
const self = process.argv[1] ? resolve(process.argv[1]) : "";
|
|
200
|
+
if (self && (import.meta.url === pathToFileURL(self).href || self.endsWith(`${sep}wt-checks`))) {
|
|
201
|
+
main(process.argv.slice(2)).then((code) => process.exit(code));
|
|
202
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
export declare const API_VERSION = "watchtower.dev/v1";
|
|
2
|
+
export type ManifestKind = "Monitor" | "CheckSecret";
|
|
3
|
+
export interface Manifest {
|
|
4
|
+
apiVersion: typeof API_VERSION;
|
|
5
|
+
kind: ManifestKind;
|
|
6
|
+
metadata: {
|
|
7
|
+
name: string;
|
|
8
|
+
labels?: Record<string, string>;
|
|
9
|
+
};
|
|
10
|
+
spec: Record<string, unknown>;
|
|
11
|
+
}
|
|
12
|
+
/** A duration: seconds as a number, or "500ms", "30s", "5m", "1h". */
|
|
13
|
+
export type Duration = number | string;
|
|
14
|
+
export interface Retry {
|
|
15
|
+
mode?: "none" | "fixed" | "linear" | "exponential";
|
|
16
|
+
max?: number;
|
|
17
|
+
delayMs?: number;
|
|
18
|
+
}
|
|
19
|
+
/** What every check may set; a project's `defaults` fill what a check leaves out. */
|
|
20
|
+
export interface CheckProps {
|
|
21
|
+
env?: string;
|
|
22
|
+
service?: string;
|
|
23
|
+
interval?: Duration;
|
|
24
|
+
timeout?: Duration;
|
|
25
|
+
locations?: string[];
|
|
26
|
+
assertions?: string[];
|
|
27
|
+
retry?: Retry;
|
|
28
|
+
/** Locations that must fail before the check is down. */
|
|
29
|
+
minFail?: number;
|
|
30
|
+
/** A passing check slower than this is degraded, not down. */
|
|
31
|
+
degraded?: Duration;
|
|
32
|
+
alert?: boolean;
|
|
33
|
+
enabled?: boolean;
|
|
34
|
+
labels?: Record<string, string>;
|
|
35
|
+
/** Further MonitorSpec fields, sent as they are (snake_case, e.g. escalation settings). */
|
|
36
|
+
extra?: Record<string, unknown>;
|
|
37
|
+
}
|
|
38
|
+
export interface Check {
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly kind: string;
|
|
41
|
+
readonly config: Record<string, unknown>;
|
|
42
|
+
readonly props: CheckProps;
|
|
43
|
+
}
|
|
44
|
+
export interface SecretDef {
|
|
45
|
+
readonly name: string;
|
|
46
|
+
/** The environment variable that holds the value when the manifests are applied. */
|
|
47
|
+
readonly fromEnv: string;
|
|
48
|
+
}
|
|
49
|
+
/** `{{secret.NAME}}`: a vault value, substituted when the check runs. */
|
|
50
|
+
export declare function secretRef(name: string): string;
|
|
51
|
+
/** `{{totp.NAME}}`: the current one-time code of the TOTP seed stored as vault secret NAME. */
|
|
52
|
+
export declare function totp(name: string): string;
|
|
53
|
+
/** A vault secret whose value comes from an environment variable at apply time (never from code). */
|
|
54
|
+
export declare function secret(name: string, opts: {
|
|
55
|
+
fromEnv: string;
|
|
56
|
+
}): SecretDef;
|
|
57
|
+
/** Any check kind with its driver config (see docs/product/uptime/check-types.md). */
|
|
58
|
+
export declare function check(name: string, kind: string, config: Record<string, unknown>, props?: CheckProps): Check;
|
|
59
|
+
export interface HttpConfig {
|
|
60
|
+
url: string;
|
|
61
|
+
method?: string;
|
|
62
|
+
headers?: Record<string, string>;
|
|
63
|
+
body?: string;
|
|
64
|
+
maxRedirects?: number;
|
|
65
|
+
tlsVerify?: boolean;
|
|
66
|
+
auth?: {
|
|
67
|
+
type: "basic";
|
|
68
|
+
username: string;
|
|
69
|
+
passwordRef: string;
|
|
70
|
+
} | {
|
|
71
|
+
type: "bearer";
|
|
72
|
+
tokenRef: string;
|
|
73
|
+
} | {
|
|
74
|
+
type: "negotiate";
|
|
75
|
+
username: string;
|
|
76
|
+
realm: string;
|
|
77
|
+
kdc: string;
|
|
78
|
+
passwordRef: string;
|
|
79
|
+
spn?: string;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
export declare function http(name: string, cfg: HttpConfig & CheckProps): Check;
|
|
83
|
+
export interface BrowserStep {
|
|
84
|
+
action: string;
|
|
85
|
+
[field: string]: unknown;
|
|
86
|
+
}
|
|
87
|
+
/** The browser step script; `step.fill("#otp", totp("MFA"))` types a fresh code. */
|
|
88
|
+
export declare const step: {
|
|
89
|
+
goto: (url: string) => BrowserStep;
|
|
90
|
+
click: (selector: string) => BrowserStep;
|
|
91
|
+
fill: (selector: string, value: string) => BrowserStep;
|
|
92
|
+
press: (key: string, selector?: string) => BrowserStep;
|
|
93
|
+
waitFor: (selector: string) => BrowserStep;
|
|
94
|
+
assertText: (selector: string, text: string) => BrowserStep;
|
|
95
|
+
assertVisible: (selector: string) => BrowserStep;
|
|
96
|
+
evaluate: (script: string, value?: string) => BrowserStep;
|
|
97
|
+
};
|
|
98
|
+
export interface Passkey {
|
|
99
|
+
rpId: string;
|
|
100
|
+
credentialId: string;
|
|
101
|
+
privateKeyRef: string;
|
|
102
|
+
userHandle?: string;
|
|
103
|
+
signCount?: number;
|
|
104
|
+
discoverable?: boolean;
|
|
105
|
+
}
|
|
106
|
+
export interface BrowserConfig {
|
|
107
|
+
steps: BrowserStep[];
|
|
108
|
+
emulation?: Record<string, unknown>;
|
|
109
|
+
capture?: Array<"har" | "trace" | "video">;
|
|
110
|
+
passkeys?: Passkey[];
|
|
111
|
+
}
|
|
112
|
+
export declare function browser(name: string, cfg: BrowserConfig & CheckProps): Check;
|
|
113
|
+
export interface MultiStepStep {
|
|
114
|
+
name: string;
|
|
115
|
+
request: HttpConfig;
|
|
116
|
+
extract?: Record<string, string>;
|
|
117
|
+
assertions?: string[];
|
|
118
|
+
}
|
|
119
|
+
export declare function multiStep(name: string, cfg: {
|
|
120
|
+
steps: MultiStepStep[];
|
|
121
|
+
} & CheckProps): Check;
|
|
122
|
+
export declare function tcp(name: string, cfg: {
|
|
123
|
+
host: string;
|
|
124
|
+
port: number;
|
|
125
|
+
} & CheckProps): Check;
|
|
126
|
+
export declare function dns(name: string, cfg: {
|
|
127
|
+
host: string;
|
|
128
|
+
recordType?: string;
|
|
129
|
+
server?: string;
|
|
130
|
+
} & CheckProps): Check;
|
|
131
|
+
/** Seconds of a Duration (fractions kept for "ms"). */
|
|
132
|
+
export declare function seconds(d: Duration): number;
|
|
133
|
+
export interface ProjectDef {
|
|
134
|
+
/** The environment id every check runs in unless it sets `env`. */
|
|
135
|
+
env?: string;
|
|
136
|
+
defaults?: CheckProps;
|
|
137
|
+
checks: Check[];
|
|
138
|
+
secrets?: SecretDef[];
|
|
139
|
+
}
|
|
140
|
+
/** The default export of a checks config file. */
|
|
141
|
+
export declare function defineProject(def: ProjectDef): ProjectDef;
|
|
142
|
+
/** The manifests of a project, secrets first (monitors reference them). Throws on a bad project. */
|
|
143
|
+
export declare function synth(def: ProjectDef): Manifest[];
|
|
144
|
+
export { cypressTraceparent, newTraceparent, playwrightTraceparent, runTraceTest } from "./tracetest.ts";
|
|
145
|
+
export type { CypressLike, PlaywrightContextLike, RunTraceTestOptions, Traceparent, TraceTestRun } from "./tracetest.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Checks as code: monitors written as TypeScript constructs, synthesized into the
|
|
2
|
+
// `watchtower.dev/v1` manifests that `wtctl apply` and `wtctl checks watch` sync through the API.
|
|
3
|
+
export const API_VERSION = "watchtower.dev/v1";
|
|
4
|
+
const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,199}$/i;
|
|
5
|
+
const SECRET_RE = /^[A-Za-z][A-Za-z0-9_]*$/;
|
|
6
|
+
/** `{{secret.NAME}}`: a vault value, substituted when the check runs. */
|
|
7
|
+
export function secretRef(name) {
|
|
8
|
+
if (!SECRET_RE.test(name))
|
|
9
|
+
throw new Error(`secret name ${JSON.stringify(name)} is not valid`);
|
|
10
|
+
return `{{secret.${name}}}`;
|
|
11
|
+
}
|
|
12
|
+
/** `{{totp.NAME}}`: the current one-time code of the TOTP seed stored as vault secret NAME. */
|
|
13
|
+
export function totp(name) {
|
|
14
|
+
if (!SECRET_RE.test(name))
|
|
15
|
+
throw new Error(`secret name ${JSON.stringify(name)} is not valid`);
|
|
16
|
+
return `{{totp.${name}}}`;
|
|
17
|
+
}
|
|
18
|
+
/** A vault secret whose value comes from an environment variable at apply time (never from code). */
|
|
19
|
+
export function secret(name, opts) {
|
|
20
|
+
if (!SECRET_RE.test(name))
|
|
21
|
+
throw new Error(`secret name ${JSON.stringify(name)} is not valid`);
|
|
22
|
+
if (!SECRET_RE.test(opts.fromEnv))
|
|
23
|
+
throw new Error(`fromEnv ${JSON.stringify(opts.fromEnv)} is not an env var name`);
|
|
24
|
+
return { name, fromEnv: opts.fromEnv };
|
|
25
|
+
}
|
|
26
|
+
/** Any check kind with its driver config (see docs/product/uptime/check-types.md). */
|
|
27
|
+
export function check(name, kind, config, props = {}) {
|
|
28
|
+
if (!NAME_RE.test(name))
|
|
29
|
+
throw new Error(`check name ${JSON.stringify(name)}: letters, digits, . _ - (at most 200)`);
|
|
30
|
+
if (!/^[a-z0-9_]+$/.test(kind))
|
|
31
|
+
throw new Error(`check ${name}: kind ${JSON.stringify(kind)} is not valid`);
|
|
32
|
+
return { name, kind, config, props };
|
|
33
|
+
}
|
|
34
|
+
function snake(o) {
|
|
35
|
+
const out = {};
|
|
36
|
+
for (const [k, v] of Object.entries(o)) {
|
|
37
|
+
if (v === undefined)
|
|
38
|
+
continue;
|
|
39
|
+
const key = k.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());
|
|
40
|
+
out[key] = v !== null && typeof v === "object" && !Array.isArray(v) && key !== "headers" ? snake(v) : v;
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
export function http(name, cfg) {
|
|
45
|
+
const { url, method, headers, body, maxRedirects, tlsVerify, auth, ...props } = cfg;
|
|
46
|
+
return check(name, "http", snake({ url, method, headers, body, maxRedirects, tlsVerify, auth }), props);
|
|
47
|
+
}
|
|
48
|
+
/** The browser step script; `step.fill("#otp", totp("MFA"))` types a fresh code. */
|
|
49
|
+
export const step = {
|
|
50
|
+
goto: (url) => ({ action: "goto", url }),
|
|
51
|
+
click: (selector) => ({ action: "click", selector }),
|
|
52
|
+
fill: (selector, value) => ({ action: "fill", selector, value }),
|
|
53
|
+
press: (key, selector) => ({ action: "press", value: key, ...(selector ? { selector } : {}) }),
|
|
54
|
+
waitFor: (selector) => ({ action: "wait_for", selector }),
|
|
55
|
+
assertText: (selector, text) => ({ action: "assert_text", selector, text }),
|
|
56
|
+
assertVisible: (selector) => ({ action: "assert_visible", selector }),
|
|
57
|
+
evaluate: (script, value) => ({ action: "evaluate", script, ...(value ? { value } : {}) }),
|
|
58
|
+
};
|
|
59
|
+
export function browser(name, cfg) {
|
|
60
|
+
const { steps, emulation, capture, passkeys, ...props } = cfg;
|
|
61
|
+
if (steps.length === 0)
|
|
62
|
+
throw new Error(`browser check ${name} needs steps`);
|
|
63
|
+
const config = { steps };
|
|
64
|
+
if (emulation)
|
|
65
|
+
config.emulation = emulation;
|
|
66
|
+
if (capture)
|
|
67
|
+
config.capture = capture;
|
|
68
|
+
if (passkeys)
|
|
69
|
+
config.passkeys = passkeys.map((p) => snake({ ...p }));
|
|
70
|
+
return check(name, "browser", config, props);
|
|
71
|
+
}
|
|
72
|
+
export function multiStep(name, cfg) {
|
|
73
|
+
const { steps, ...props } = cfg;
|
|
74
|
+
const out = steps.map((s) => {
|
|
75
|
+
const { url, method, headers, body, maxRedirects, tlsVerify, auth } = s.request;
|
|
76
|
+
return { name: s.name, request: snake({ url, method, headers, body, maxRedirects, tlsVerify, auth }), extract: s.extract, assertions: s.assertions };
|
|
77
|
+
});
|
|
78
|
+
return check(name, "multistep", { steps: out }, props);
|
|
79
|
+
}
|
|
80
|
+
export function tcp(name, cfg) {
|
|
81
|
+
const { host, port, ...props } = cfg;
|
|
82
|
+
return check(name, "tcp", { host, port }, props);
|
|
83
|
+
}
|
|
84
|
+
export function dns(name, cfg) {
|
|
85
|
+
const { host, recordType, server, ...props } = cfg;
|
|
86
|
+
return check(name, "dns", snake({ host, recordType, server }), props);
|
|
87
|
+
}
|
|
88
|
+
/** Seconds of a Duration (fractions kept for "ms"). */
|
|
89
|
+
export function seconds(d) {
|
|
90
|
+
if (typeof d === "number")
|
|
91
|
+
return d;
|
|
92
|
+
const m = /^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(d.trim());
|
|
93
|
+
if (!m)
|
|
94
|
+
throw new Error(`duration ${JSON.stringify(d)}: use a number of seconds or 500ms, 30s, 5m, 1h`);
|
|
95
|
+
const n = Number(m[1]);
|
|
96
|
+
if (m[2] === "ms")
|
|
97
|
+
return n / 1000;
|
|
98
|
+
return n * { s: 1, m: 60, h: 3600 }[m[2]];
|
|
99
|
+
}
|
|
100
|
+
/** The default export of a checks config file. */
|
|
101
|
+
export function defineProject(def) {
|
|
102
|
+
return def;
|
|
103
|
+
}
|
|
104
|
+
function monitor(c, def) {
|
|
105
|
+
const p = { ...def.defaults, ...c.props, labels: { ...def.defaults?.labels, ...c.props.labels } };
|
|
106
|
+
const env = p.env ?? def.env;
|
|
107
|
+
if (!env)
|
|
108
|
+
throw new Error(`check ${c.name}: set env on the project or the check`);
|
|
109
|
+
const spec = { env_id: env, name: c.name, kind: c.kind, config: c.config };
|
|
110
|
+
if (p.service)
|
|
111
|
+
spec.service = p.service;
|
|
112
|
+
if (p.assertions)
|
|
113
|
+
spec.assertions = p.assertions;
|
|
114
|
+
if (p.interval !== undefined)
|
|
115
|
+
spec.interval_s = Math.round(seconds(p.interval));
|
|
116
|
+
if (p.timeout !== undefined)
|
|
117
|
+
spec.timeout_ms = Math.round(seconds(p.timeout) * 1000);
|
|
118
|
+
if (p.locations)
|
|
119
|
+
spec.locations = p.locations;
|
|
120
|
+
if (p.retry)
|
|
121
|
+
spec.retry = snake({ ...p.retry });
|
|
122
|
+
if (p.minFail !== undefined)
|
|
123
|
+
spec.quorum = { min_fail: p.minFail };
|
|
124
|
+
if (p.degraded !== undefined)
|
|
125
|
+
spec.degraded_ms = Math.round(seconds(p.degraded) * 1000);
|
|
126
|
+
if (p.alert !== undefined)
|
|
127
|
+
spec.alert = p.alert;
|
|
128
|
+
if (p.enabled !== undefined)
|
|
129
|
+
spec.enabled = p.enabled;
|
|
130
|
+
Object.assign(spec, p.extra);
|
|
131
|
+
const labels = p.labels && Object.keys(p.labels).length > 0 ? p.labels : undefined;
|
|
132
|
+
return { apiVersion: API_VERSION, kind: "Monitor", metadata: labels ? { name: c.name, labels } : { name: c.name }, spec };
|
|
133
|
+
}
|
|
134
|
+
/** The manifests of a project, secrets first (monitors reference them). Throws on a bad project. */
|
|
135
|
+
export function synth(def) {
|
|
136
|
+
const seen = new Set();
|
|
137
|
+
const once = (id) => {
|
|
138
|
+
if (seen.has(id))
|
|
139
|
+
throw new Error(`${id} is defined twice`);
|
|
140
|
+
seen.add(id);
|
|
141
|
+
};
|
|
142
|
+
const out = [];
|
|
143
|
+
for (const s of def.secrets ?? []) {
|
|
144
|
+
once(`CheckSecret/${s.name}`);
|
|
145
|
+
out.push({ apiVersion: API_VERSION, kind: "CheckSecret", metadata: { name: s.name }, spec: { value: `\${${s.fromEnv}}` } });
|
|
146
|
+
}
|
|
147
|
+
for (const c of def.checks) {
|
|
148
|
+
once(`Monitor/${c.name}`);
|
|
149
|
+
out.push(monitor(c, def));
|
|
150
|
+
}
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
export { cypressTraceparent, newTraceparent, playwrightTraceparent, runTraceTest } from "./tracetest.js";
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export interface Traceparent {
|
|
2
|
+
/** 32 lowercase hex characters. */
|
|
3
|
+
traceId: string;
|
|
4
|
+
/** The W3C `traceparent` header value (sampled). */
|
|
5
|
+
header: string;
|
|
6
|
+
}
|
|
7
|
+
/** A fresh sampled W3C traceparent. */
|
|
8
|
+
export declare function newTraceparent(): Traceparent;
|
|
9
|
+
/** What we need of a Playwright `BrowserContext` (or `APIRequestContext` options holder). */
|
|
10
|
+
export interface PlaywrightContextLike {
|
|
11
|
+
setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
/** Every request of the context carries the traceparent; returns it for `runTraceTest`. */
|
|
14
|
+
export declare function playwrightTraceparent(context: PlaywrightContextLike, tp?: Traceparent): Promise<Traceparent>;
|
|
15
|
+
/** What we need of Cypress' `cy`. */
|
|
16
|
+
export interface CypressLike {
|
|
17
|
+
intercept(matcher: {
|
|
18
|
+
url: string | RegExp;
|
|
19
|
+
}, handler: (req: {
|
|
20
|
+
headers: Record<string, string | string[]>;
|
|
21
|
+
}) => void): unknown;
|
|
22
|
+
}
|
|
23
|
+
/** Requests matching `url` (default: all) carry the traceparent. */
|
|
24
|
+
export declare function cypressTraceparent(cy: CypressLike, url?: string | RegExp, tp?: Traceparent): Traceparent;
|
|
25
|
+
export interface TraceTestRun {
|
|
26
|
+
id: string;
|
|
27
|
+
state: "pending" | "running" | "passed" | "failed" | "error";
|
|
28
|
+
trace_id: string | null;
|
|
29
|
+
result: {
|
|
30
|
+
error?: string;
|
|
31
|
+
assertions?: {
|
|
32
|
+
on: string;
|
|
33
|
+
name: string;
|
|
34
|
+
ok: boolean;
|
|
35
|
+
detail?: string;
|
|
36
|
+
}[];
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export interface RunTraceTestOptions {
|
|
40
|
+
/** API base, e.g. https://watchtower.example.com (default $WT_API). */
|
|
41
|
+
api?: string;
|
|
42
|
+
/** Key with manage_monitors (default $WT_TOKEN). */
|
|
43
|
+
token?: string;
|
|
44
|
+
project: string;
|
|
45
|
+
testId: string;
|
|
46
|
+
traceId: string;
|
|
47
|
+
ciRef?: string;
|
|
48
|
+
variables?: Record<string, string>;
|
|
49
|
+
/** How long to wait for the verdict (default 120 s). */
|
|
50
|
+
timeoutMs?: number;
|
|
51
|
+
pollMs?: number;
|
|
52
|
+
fetch?: typeof fetch;
|
|
53
|
+
}
|
|
54
|
+
/** Queues the run, waits for its verdict and throws unless it passed (so the test fails). */
|
|
55
|
+
export declare function runTraceTest(o: RunTraceTestOptions): Promise<TraceTestRun>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Trace tests triggered by your own test runner (PLT-006): a Playwright or Cypress run sends a
|
|
2
|
+
// traceparent we made, then asks Watchtower to judge the trace it produced with a trace test whose
|
|
3
|
+
// trigger is `{"runner": {"kind": "playwright" | "cypress" | "k6" | "ci"}}`.
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
/** A fresh sampled W3C traceparent. */
|
|
6
|
+
export function newTraceparent() {
|
|
7
|
+
const traceId = randomBytes(16).toString("hex");
|
|
8
|
+
return { traceId, header: `00-${traceId}-${randomBytes(8).toString("hex")}-01` };
|
|
9
|
+
}
|
|
10
|
+
/** Every request of the context carries the traceparent; returns it for `runTraceTest`. */
|
|
11
|
+
export async function playwrightTraceparent(context, tp = newTraceparent()) {
|
|
12
|
+
await context.setExtraHTTPHeaders({ traceparent: tp.header });
|
|
13
|
+
return tp;
|
|
14
|
+
}
|
|
15
|
+
/** Requests matching `url` (default: all) carry the traceparent. */
|
|
16
|
+
export function cypressTraceparent(cy, url = /.*/, tp = newTraceparent()) {
|
|
17
|
+
cy.intercept({ url }, (req) => { req.headers["traceparent"] = tp.header; });
|
|
18
|
+
return tp;
|
|
19
|
+
}
|
|
20
|
+
const DONE = new Set(["passed", "failed", "error"]);
|
|
21
|
+
/** Queues the run, waits for its verdict and throws unless it passed (so the test fails). */
|
|
22
|
+
export async function runTraceTest(o) {
|
|
23
|
+
const api = (o.api ?? process.env["WT_API"] ?? "").replace(/\/+$/, "");
|
|
24
|
+
const token = o.token ?? process.env["WT_TOKEN"] ?? "";
|
|
25
|
+
if (!api || !token)
|
|
26
|
+
throw new Error("runTraceTest needs api and token (or WT_API and WT_TOKEN)");
|
|
27
|
+
const f = o.fetch ?? fetch;
|
|
28
|
+
const base = `${api}/v1/projects/${encodeURIComponent(o.project)}`;
|
|
29
|
+
const call = async (method, path, body) => {
|
|
30
|
+
const res = await f(base + path, {
|
|
31
|
+
method,
|
|
32
|
+
headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) },
|
|
33
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
34
|
+
});
|
|
35
|
+
if (!res.ok)
|
|
36
|
+
throw new Error(`${method} ${path}: HTTP ${res.status} ${await res.text()}`);
|
|
37
|
+
return (await res.json());
|
|
38
|
+
};
|
|
39
|
+
let run = await call("POST", `/trace-tests/${encodeURIComponent(o.testId)}/runner-runs`, {
|
|
40
|
+
trace_id: o.traceId, ...(o.ciRef ? { ci_ref: o.ciRef } : {}), ...(o.variables ? { variables: o.variables } : {}),
|
|
41
|
+
});
|
|
42
|
+
const end = Date.now() + (o.timeoutMs ?? 120_000);
|
|
43
|
+
while (!DONE.has(run.state)) {
|
|
44
|
+
if (Date.now() > end)
|
|
45
|
+
throw new Error(`trace test run ${run.id} is still ${run.state}`);
|
|
46
|
+
await new Promise((r) => setTimeout(r, o.pollMs ?? 2000));
|
|
47
|
+
run = await call("GET", `/trace-test-runs/${encodeURIComponent(run.id)}`);
|
|
48
|
+
}
|
|
49
|
+
if (run.state !== "passed") {
|
|
50
|
+
const bad = (run.result.assertions ?? []).filter((a) => !a.ok).map((a) => `${a.name}: ${a.detail ?? "failed"}`);
|
|
51
|
+
throw new Error(`trace test ${run.state}: ${[run.result.error, ...bad].filter(Boolean).join("; ")}`);
|
|
52
|
+
}
|
|
53
|
+
return run;
|
|
54
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@watchtowerobservability/checks",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Checks as code: Watchtower monitors as TypeScript constructs, synced through the API with test, deploy and a hot-reloading watch mode",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"bin": {
|
|
17
|
+
"wt-checks": "dist/cli.js"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=22.18"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsc -p tsconfig.json",
|
|
27
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
28
|
+
"test": "node --test test/*.test.ts",
|
|
29
|
+
"prepack": "npm run build"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "22.15.0",
|
|
33
|
+
"typescript": "5.7.2"
|
|
34
|
+
},
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/watchtowerobservability/watchtower-checks.git"
|
|
38
|
+
},
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public",
|
|
41
|
+
"registry": "https://registry.npmjs.org/"
|
|
42
|
+
}
|
|
43
|
+
}
|