diff --git a/CHANGELOG.md b/CHANGELOG.md index 036197d..5f8fa93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,12 +20,48 @@ this file collects what users and scripts need to know. - Shell completion offers the allowed values of `-o`, `auth token --audience`, `langsync init --seed` and `backup datasources update --region`. +- PulseCheck: `norcube pulsecheck` covers every operation of the + PulseCheck API an organization member has. + - `pulsecheck status` shows open incidents, monitors by status and every + monitor that needs attention; `--fail-on critical` (or `warning`) + fails a CI job while such an incident is open. + - `monitors list | get | create | update | delete | pause | resume`, + with typed flags per type (`--type http | keyword | ssl | domain`) or + the API's JSON body with `--from-file`; secret header values only from + a file or stdin (`--secret-headers-file`). Monitors are named by id or + exact name. + - `monitors run ` runs a check now; with `--wait` a critical or + inconclusive result (or a warning with `--fail-on warning`) exits 1 + with `job_failed`, for deploy pipelines. + - `monitors bulk pause | resume | delete` by ids, a file, or the list + filters, in batches of 100. + - `monitors results list`, `status-changes list` (alias `history`), + `stats get`, `availability get`, `certificate get`, `alerts get | set`. + - `incidents list` (every API filter), `get` (timeline and alerts), + `acknowledge` (alias `ack`), `summary`. + - `channels list | get | create | update | delete | test | verify` and + `channels deliveries list`. A webhook's signing secret is written to + `--secret-file` and never printed; Slack and Discord URLs are read + from a file or stdin; `verify` asks for the code on a terminal or + reads it with `--code-file`. + - Completion for monitor, channel and incident ids; `nrc api pulsecheck` + and `auth token --audience pulsecheck`; CI tokens with the + `pulsecheck.read`, `pulsecheck.check`, `pulsecheck.write` and + `pulsecheck.channels` scopes (alert channels need the last one; + `pulsecheck.write` doesn't include it). +- Errors of services that answer RFC 9457 problems (PulseCheck) show the + problem's detail and invalid fields, and `-o json` errors carry its + `reason`, field `errors` and `data` in `details`. ### Changes for scripts - The `norcube commands` document is a contract: within `schemaVersion` 1 fields, values and commands are only ever added. A breaking change bumps `schemaVersion`. +- New error code `unhealthy` (exit 1): `pulsecheck status --fail-on` + found what it was told to fail on; `details` holds the report. +- `--endpoint-url`, `NORCUBE_PULSECHECK_URL` and the `endpoints` table of + a profile accept the new service key `pulsecheck`. ## 0.21.4 (2026-10-30) diff --git a/README.md b/README.md index d9acfd1..2e3b7d8 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ What it's best at: proving you're never locked in to Norcube Backup. `norcube ba Scripted demo with sanitized names: whoami, Backup health, scripting with `-o json --query`, any endpoint with `norcube api`, and your CLI sessions. The tape and stub live in [`demo/`](demo/). -> **Status**: pre-1.0. Norcube Backup (data sources, backups on demand and downloads, restores, restore tests and their settings, health, policies), LangSync (namespaces, terms, translations, languages, prompts, glossary, API keys, CSV import, audit log, project sync), DomainRadar (domain checks, bulk checks, saved domains, brand monitoring, name generation), Billing (status, subscriptions, usage, invoices, spending caps), organizations, profiles, and `norcube api` for everything else. See the [changelog](CHANGELOG.md). +> **Status**: pre-1.0. Norcube Backup (data sources, backups on demand and downloads, restores, restore tests and their settings, health, policies), LangSync (namespaces, terms, translations, languages, prompts, glossary, API keys, CSV import, audit log, project sync), DomainRadar (domain checks, bulk checks, saved domains, brand monitoring, name generation), PulseCheck (uptime, SSL and domain expiry monitors, check history, incidents, alert channels, a CI status gate), Billing (status, subscriptions, usage, invoices, spending caps), organizations, profiles, and `norcube api` for everything else. See the [changelog](CHANGELOG.md). ## Install @@ -169,6 +169,7 @@ norcube backup jobs list # every backup job in the organization norcube backup health # which backups actually restore norcube langsync namespaces list # LangSync namespaces norcube domainradar check acme.dev # is a domain free? +norcube pulsecheck status # open incidents and monitors that need attention norcube billing usage estimate # this month's charges so far norcube doctor # something not working? start here ``` diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3324ba7..3e76f58 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -39,7 +39,7 @@ maps them to stable codes and exit codes. | `internal/clierr` | Error codes, exit codes and the JSON error shape. | | `internal/completion` | Dynamic shell completion with a one-second budget and a one-minute cache. | | `internal/orgs` | Organization slug resolution and its cache. | -| `internal/api/` | Generated clients. Never edit `*.gen.go`; run `make codegen`. | +| `internal/api/` | Generated clients. Never edit `*.gen.go`; run `make codegen`. `internal/api/apierror` turns any error response (the `{type, msg}` shape and RFC 9457 problems) into a `clierr.Error`. | `internal/cli/commands.go` is `nrc commands`: it walks the cobra tree and prints the machine-readable command tree (schema in @@ -126,7 +126,7 @@ secrets and the one-time setup. help text and an effect, nothing writes to stdout outside the result path, and no two sibling commands share a name or alias. `commands_test.go` pins the `nrc commands` schema (golden - `commands-billing.*`) and checks that it lists every visible command, - sorted, offline. + `commands-billing.*`; `commands-pulsecheck.json` pins a whole product + group) and checks that it lists every visible command, sorted, offline. - `go test -race ./...`, `go vet` and golangci-lint (pinned in CI) must pass. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index d24149b..c087dd3 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -37,7 +37,7 @@ stale; either way, fix one of them in the same change. One open-source (Apache 2.0) binary that drives every Norcube product from a terminal, a script or a CI job: Norcube Backup, LangSync, -DomainRadar, Billing and the platform itself (sign-in, organizations, +DomainRadar, PulseCheck, Billing and the platform itself (sign-in, organizations, CLI sessions, CI tokens). It is a client of the products' public HTTP APIs and nothing else: it holds no business logic the API does not have, and every typed client in it is generated from the backend's Swagger @@ -113,6 +113,9 @@ meaning across the tree: | `pause` / `resume` | Stop and restart a schedule without deleting it | `backup datasources pause`, `backup policies resume` | | `download` / `export` | Write server data to a file or stdout | `backup jobs download`, `billing invoices download`, `domainradar bulk export` | | `sync` / `pull` / `init` | LangSync project files | `langsync sync` | +| `acknowledge` | Mark something as being handled without changing it otherwise | `pulsecheck incidents acknowledge` (alias `ack`) | +| `verify` | Confirm a contact with a code sent to it | `pulsecheck channels verify` | +| `summary` | Counts over a whole resource, not a list | `pulsecheck incidents summary` | | `cancel`, `watch`, `results`, `status`, `check`, `generate`, `import`, `set`, `revoke`, `use` | As named | `domainradar bulk watch`, `langsync terms import status` | `rm` is an alias of `remove` only, never of `delete`. @@ -196,7 +199,7 @@ exit codes may not. | Exit | Codes | Meaning | | --- | --- | --- | | 0 | | Success | -| 1 | `error`, `server_error`, `job_failed` | General failure; a waited-for job ended unsuccessfully (`details` holds the job) | +| 1 | `error`, `server_error`, `job_failed`, `unhealthy` | General failure; a waited-for job ended unsuccessfully (`details` holds the job); a `--fail-on` state was found (`pulsecheck status`, `details` holds the report) | | 2 | `usage_error`, `validation_failed`, `org_not_found` | Fix the command line or input; also any prompt without a terminal | | 3 | `not_found` | The API answered 404 | | 4 | `login_required` | Not signed in, session expired or revoked, CI token expired, revoked or unknown | @@ -368,7 +371,8 @@ is declared where the command is defined, with the annotations of P13. **Enforced.** `TestEveryCommandHasAnExample`, `TestHelpTextIsComplete` and `TestEveryCommandDeclaresAnEffect` in [`contract_test.go`](../internal/cli/contract_test.go); the schema golden -`commands-billing.*` and the tree tests in +`commands-billing.*` (and `commands-pulsecheck.json` for a whole product +group) and the tree tests in [`commands_test.go`](../internal/cli/commands_test.go) (every visible command listed, hidden ones only with `--all`, sorted output, offline); the [`docs-reference`](../.github/workflows/docs-reference.yaml) workflow @@ -573,8 +577,8 @@ generated package). Each entry gives: | `spec`, `package` | `make codegen` input and output | Today the registry holds Auth, the web app, Backup (`snapdb`), LangSync, -DomainRadar, Billing and PromptHub (callable with `nrc api`, no command -group yet). +DomainRadar, Billing, PulseCheck and PromptHub (callable with `nrc api`, +no command group yet). Not yet derived from the registry, and therefore also edited by hand when a service is added: the per-service fields and `switch` statements of @@ -709,7 +713,7 @@ or the field is left out. The stability rule is in P9. --- -## 4. Feature inventory (v0.21.4) +## 4. Feature inventory (v0.21.4, plus Unreleased) What exists, per command group. The [command reference](https://docs.norcube.com/platform/cli-reference) has every @@ -722,14 +726,19 @@ flag; [CHANGELOG.md](../CHANGELOG.md) says when each arrived. | `langsync` | `init`, `sync`, `pull`; `namespaces list | create | update | delete`; `terms list | add | update | delete | import`, `terms import status`; `translations get | set | suggest | translate-missing`; `languages list | add | remove | create | delete`; `prompts list | get | create | update | delete`; `glossary get`, `glossary items list | get | create | translate | delete`, `glossary languages attach`; `api-keys list | create | revoke`; `audit list` | | `domainradar` | `check`; `bulk create | list | get | results | watch | export | cancel | delete`; `saved list | add | remove`; `watchers list | get | create | update | delete`; `hits list | get`; `names generate | list | get | results | check | delete` | | `billing` | `status`; `subscriptions list`; `usage estimate | metrics`; `invoices list | download`; `budget get | set` | +| `pulsecheck` | `status` (`--fail-on`); `monitors list | get | create | update | delete | pause | resume | run` (`--wait`), `monitors bulk pause | resume | delete`, `monitors results list`, `monitors status-changes list`, `monitors stats get`, `monitors availability get`, `monitors certificate get`, `monitors alerts get | set`; `incidents list | get | acknowledge | summary`; `channels list | get | create | update | delete | test | verify`, `channels deliveries list` | | PromptHub | No command group; `nrc api prompthub ...` | -| CMS, PulseCheck | None (CMS has no public API; PulseCheck is not in the registry yet, section 6.1) | +| CMS | None (CMS has no public API) | CI token scopes, as defined by Norcube Auth and listed by `nrc auth ci-token scopes`: `backup.read`, `backup.write` (run backups now), `backup.verify` (restore tests), `domainradar.check`, `langsync.read`, `langsync.sync`, `langsync.write`, `billing.read`, -`cms.read`, `cms.write`. +`cms.read`, `cms.write`, `pulsecheck.read`, `pulsecheck.check` (run a +monitor's check now), `pulsecheck.write` (manage monitors, alert routing, +acknowledge incidents), `pulsecheck.channels` (manage alert channels, test +sends and verification codes; not included in `pulsecheck.write`, because +channels hold credentials and sends cost money). Installation channels: Homebrew cask (with `nrc`), `.deb` / `.rpm` / `.apk`, `install.sh`, release archives (darwin and linux amd64/arm64, @@ -774,6 +783,7 @@ changelog, and the owner's decisions in the planning sessions of | 2026-10-29 | The CLI becomes a first-party OAuth client of Norcube Auth (PKCE, scoped logins, Connected apps, revocation) | Owner: "i want the proper way". Rejected: scopes on today's CLI sessions, which keeps the refresh token passing through dashboard JavaScript and three token models | owner | | 2026-10-30 | Pin the Go toolchain, check `go mod tidy`, run govulncheck in CI with documented acceptances | Releases had been built with a Go patch with reachable stdlib advisories | 3b2e964 (v0.21.4) | | 2026-10-30 | Engineering reviews are written down as reports and fixed in separate, deliberate changes, not by automatic fix agents | Owner's instruction | owner | +| 2026-11-04 | PulseCheck in the CLI. Monitors and channels are named by id or exact name (a name matching several is a usage error, never a guess); sub-resources of a monitor are nested resources with standard verbs (`monitors results list`, `monitors stats get`) rather than new verbs; `monitors run --wait` makes the synchronous check's verdict the exit code (`job_failed` on critical or inconclusive, `--fail-on warning`); `pulsecheck status --fail-on` exits 1 with the new code `unhealthy` and prints the report either way (default `none`); bulk actions are their own subgroup (`monitors bulk ...`) so one command's output shape never depends on how many ids it got; a webhook's signing secret is written to `--secret-file` and never printed, Slack and Discord URLs and secret headers come from files or stdin; `output.Object.Text` keeps `-o text` columns fixed for objects whose fields depend on the resource; RFC 9457 problems (`code`, `reason`, `errors`) are parsed by the shared error formatter. No `pc` alias: no product has an abbreviation, and P13 asks for one name. Alert channels get their own scope (`pulsecheck.channels`), granted explicitly and not implied by `pulsecheck.write` (owner: "everything should be well scoped") | Owner's brief: every PulseCheck operation, robust, scriptable. Rejected: `--wait` polling a check that is already synchronous; printing the webhook secret once like a CI token (the owner asked that webhook secrets never be printed); `monitors pause a b c` switching to the bulk endpoint and its shape with two or more ids | owner | | 2026-11-04 | `nrc commands`: the whole command tree as one versioned, offline document; what the tree cannot reveal is declared with annotations (`effect`, flag enums, service), never inferred from verbs | Agents should not crawl dozens of `--help` pages. Prior art: `kubectl api-resources` / `explain` (verbs per resource, offline schema), `aws ... --generate-cli-skeleton` (machine-readable input), cobra's doc generation (`tools/gendocs` already walks the tree). Global flags listed once rather than on every command, to keep the document small; a verb-based guess of the effect was rejected because domain verbs like `check`, `suggest` or `init` don't say whether they change anything | owner | --- @@ -845,21 +855,17 @@ it with the same guarantees as every other product. The steps, in order: add the product there. 14. **Changelog** under `## Unreleased`, then release (section 6.6). -**Worked example: PulseCheck (state on 2026-11-03).** +**Worked example: PulseCheck (state on 2026-11-04).** | Step | State | | --- | --- | -| 1 Audience | `pulsecheck` exists in Norcube Auth (in the sign-in audience list; the dashboard token endpoint mints it on staging, not yet in production) | -| 2 Scopes | None. Norcube Auth's comment: "PulseCheck ... has no OAuth scopes yet: only a full sign-in reaches it"; PulseCheck refuses every scoped token | -| 3 Enforcement | Refuses scoped tokens outright; needs a route-to-scope table once scopes exist | -| 4 Contract | Swagger with `@Id` annotations exists in the service | -| 5 to 10 CLI | Not started: no registry entry, client, commands or tests | -| 11 MCP | No tools | -| 12 to 14 | No CLI docs, no website mention, no changelog entry | - -The smallest useful first step is step 5 alone (registry entry plus -production endpoint), which makes `nrc api pulsecheck ...` work for -signed-in people; CI use waits for steps 2 and 3. +| 1 Audience | `pulsecheck` exists in Norcube Auth (sign-in audience list, CI token exchange) | +| 2 Scopes | `pulsecheck.read`, `pulsecheck.check`, `pulsecheck.write`, `pulsecheck.channels` in the CI token catalog (and so the CLI sign-in catalog), with IAM actions; channel changes and sends only with `pulsecheck.channels`, which `pulsecheck.write` doesn't include; not on the MCP consent screen until the MCP redesign | +| 3 Enforcement | Default-closed route table (`internal/routers/app/scopes.go`) after the token middleware, coverage and matrix tests, and IAM refusing a scoped request the table never checked | +| 4 Contract | Every operation has a verb-noun `@Id`, `@Security Bearer`, 401/403 problems and `x-norcube-scopes`; the status route is tagged `Status` and excluded here | +| 5 to 10 CLI | Registry entry, hand-kept tables, client, `nrc pulsecheck` commands, completion, command and golden tests | +| 11 MCP | No tools yet | +| 12 to 14 | Changelog entry; the product's CLI guide page and the website mention are still to write | ### 6.2 Adding a command @@ -1054,8 +1060,8 @@ observable contract and will be announced in the changelog. - **First-party OAuth sign-in** (P12): in development; scoped logins (`nrc login --scopes`), Connected apps, RFC 7009 revocation; the current exchange endpoint retires two releases after it ships. -- **PulseCheck** (section 6.1 table): scopes and enforcement in the - backend, then the registry entry, client and commands. +- **PulseCheck**: a docs guide page (`/pulsecheck/cli`), the website + demo, MCP tools (section 6.1 table). - **Coverage still missing in the CLI:** organization members and IAM (`org members ...`), Backup destinations beyond `list`, notifications and audit, resumable downloads, PromptHub commands. diff --git a/go.mod b/go.mod index aeb2810..101e56f 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/creativeprojects/go-selfupdate v1.5.2 github.com/getkin/kin-openapi v0.138.0 github.com/gofrs/flock v0.13.0 + github.com/google/uuid v1.6.0 github.com/jmespath-community/go-jmespath v1.1.1 github.com/oapi-codegen/runtime v1.4.0 github.com/pelletier/go-toml/v2 v2.3.1 @@ -49,7 +50,6 @@ require ( github.com/godbus/dbus/v5 v5.2.2 // indirect github.com/google/go-github/v74 v74.0.0 // indirect github.com/google/go-querystring v1.1.0 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-retryablehttp v0.7.8 // indirect github.com/hashicorp/go-version v1.8.0 // indirect diff --git a/internal/api/apierror/apierror.go b/internal/api/apierror/apierror.go index a372a1a..bd4fc88 100644 --- a/internal/api/apierror/apierror.go +++ b/internal/api/apierror/apierror.go @@ -14,6 +14,7 @@ import ( "encoding/json" "fmt" "net/http" + "strings" "github.com/norcubeplatform/cli/internal/clierr" ) @@ -54,7 +55,22 @@ func Format(service string, resp *http.Response, body []byte, typed ...*Typed) e } } - // Every Norcube service answers errors as {"type": ..., "msg": ...}, + // Newer services (PulseCheck) answer RFC 9457 problems: "code" is the + // stable code, "reason" a finer cause, "detail" the sentence. + if p, ok := parseProblem(body); ok { + e.Message, e.Type = p.message(), p.Code + mapped := p.Code + if strings.EqualFold(p.Reason, "INSUFFICIENT_SCOPE") { + mapped = p.Reason + } + e.Code = clierr.CodeForStatus(e.HTTPStatus, mapped) + if d := p.details(); d != nil { + e.Details = d + } + return e + } + + // The other Norcube services answer errors as {"type": ..., "msg": ...}, // also on statuses the generated client has no typed field for. var generic struct { Type string `json:"type"` @@ -85,3 +101,74 @@ func requestID(h http.Header) string { } return "" } + +// problem is an RFC 9457 problem document as Norcube services send it +// (application/problem+json). +type problem struct { + Code string `json:"code"` + Detail string `json:"detail"` + Title string `json:"title"` + Reason string `json:"reason"` + Data map[string]string `json:"data"` + Errors []violation `json:"errors"` +} + +// violation is one invalid field of a VALIDATION_FAILED problem. +type violation struct { + Pointer string `json:"pointer"` + Rule string `json:"rule"` + Detail string `json:"detail"` + Params map[string]any `json:"params,omitempty"` +} + +// maxViolations bounds how many field errors the message lists; details +// keep all of them. +const maxViolations = 5 + +func parseProblem(body []byte) (problem, bool) { + var p problem + if json.Unmarshal(body, &p) != nil || p.Code == "" || (p.Detail == "" && p.Title == "") { + return problem{}, false + } + return p, true +} + +// message is the detail, followed by the invalid fields ("/http/url: +// must be a public address"). +func (p problem) message() string { + msg := p.Detail + if msg == "" { + msg = p.Title + } + if len(p.Errors) == 0 { + return msg + } + parts := make([]string, 0, maxViolations+1) + for i, v := range p.Errors { + if i == maxViolations { + parts = append(parts, fmt.Sprintf("and %d more", len(p.Errors)-maxViolations)) + break + } + parts = append(parts, strings.TrimSpace(v.Pointer+": "+v.Detail)) + } + return msg + " (" + strings.Join(parts, "; ") + ")" +} + +// details are the problem's machine-readable parts for the JSON error: +// the reason, the field errors and the data, when there are any. +func (p problem) details() map[string]any { + d := map[string]any{} + if p.Reason != "" { + d["reason"] = p.Reason + } + if len(p.Errors) > 0 { + d["errors"] = p.Errors + } + if len(p.Data) > 0 { + d["data"] = p.Data + } + if len(d) == 0 { + return nil + } + return d +} diff --git a/internal/api/apierror/apierror_test.go b/internal/api/apierror/apierror_test.go index d736e87..de486c0 100644 --- a/internal/api/apierror/apierror_test.go +++ b/internal/api/apierror/apierror_test.go @@ -1,10 +1,13 @@ package apierror import ( + "errors" "net/http" "net/url" "strings" "testing" + + "github.com/norcubeplatform/cli/internal/clierr" ) func respFor(method, rawurl string, status int) *http.Response { @@ -51,3 +54,40 @@ func TestFormatEmptyBodyAndNilResponse(t *testing.T) { t.Fatalf("nil response mishandled: %q", got) } } + +func TestFormatProblem(t *testing.T) { + body := []byte(`{"type":"https://docs.norcube.com/errors/validation-failed","title":"Validation failed","status":400, + "detail":"The request has invalid fields.","code":"VALIDATION_FAILED", + "errors":[{"pointer":"/http/timeoutMs","rule":"range","params":{"min":1000,"max":30000},"detail":"must be between 1000 and 30000"}]}`) + err := Format("pulsecheck", respFor("POST", "https://api.test/monitors", 400), body) + var ce *clierr.Error + if !errors.As(err, &ce) { + t.Fatalf("not a clierr.Error: %T", err) + } + if ce.Code != clierr.CodeValidation || ce.Type != "VALIDATION_FAILED" { + t.Errorf("code %q type %q", ce.Code, ce.Type) + } + if want := "The request has invalid fields. (/http/timeoutMs: must be between 1000 and 30000)"; ce.Message != want { + t.Errorf("message %q", ce.Message) + } + if d, ok := ce.Details.(map[string]any); !ok || d["errors"] == nil { + t.Errorf("details %#v", ce.Details) + } +} + +func TestFormatProblemScopeAndForbidden(t *testing.T) { + scope := []byte(`{"title":"Forbidden","status":403,"detail":"This token can't change monitors.","code":"FORBIDDEN","reason":"INSUFFICIENT_SCOPE"}`) + err := Format("pulsecheck", respFor("DELETE", "https://api.test/monitors/m", 403), scope) + var ce *clierr.Error + if !errors.As(err, &ce) || ce.Code != clierr.CodeInsufficientScope || ce.ExitCode() != clierr.ExitAccess { + t.Fatalf("scope refusal: %+v", err) + } + plain := []byte(`{"title":"Forbidden","status":403,"detail":"You don't have access to this in PulseCheck.","code":"FORBIDDEN"}`) + err = Format("pulsecheck", respFor("GET", "https://api.test/monitors", 403), plain) + if !errors.As(err, &ce) || ce.Code != clierr.CodePermissionDenied || ce.Details != nil { + t.Fatalf("permission refusal: %+v", ce) + } + if !strings.Contains(err.Error(), "(FORBIDDEN, 403)") { + t.Errorf("text %q", err.Error()) + } +} diff --git a/internal/api/pulsecheck/oapi-codegen.yaml b/internal/api/pulsecheck/oapi-codegen.yaml new file mode 100644 index 0000000..660b3d8 --- /dev/null +++ b/internal/api/pulsecheck/oapi-codegen.yaml @@ -0,0 +1,11 @@ +package: pulsecheck +generate: + models: true + client: true +output: internal/api/pulsecheck/pulsecheck.gen.go +output-options: + skip-prune: true + # The service status route is not for organization members; leave it out + # of the client. + exclude-tags: + - Status diff --git a/internal/api/pulsecheck/pulsecheck.gen.go b/internal/api/pulsecheck/pulsecheck.gen.go new file mode 100644 index 0000000..c0ac4d7 --- /dev/null +++ b/internal/api/pulsecheck/pulsecheck.gen.go @@ -0,0 +1,7791 @@ +// Package pulsecheck provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.7.0 DO NOT EDIT. +package pulsecheck + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/oapi-codegen/runtime" + openapi_types "github.com/oapi-codegen/runtime/types" +) + +// Defines values for ConstantsErrorCode. +const ( + ErrorCodeAlreadyExists ConstantsErrorCode = "ALREADY_EXISTS" + ErrorCodeConflict ConstantsErrorCode = "CONFLICT" + ErrorCodeForbidden ConstantsErrorCode = "FORBIDDEN" + ErrorCodeInternal ConstantsErrorCode = "INTERNAL_ERROR" + ErrorCodeInvalidPayload ConstantsErrorCode = "INVALID_PAYLOAD" + ErrorCodeLimitReached ConstantsErrorCode = "LIMIT_REACHED" + ErrorCodeManagedResource ConstantsErrorCode = "MANAGED_RESOURCE" + ErrorCodeMethodNotAllowed ConstantsErrorCode = "METHOD_NOT_ALLOWED" + ErrorCodeNotFound ConstantsErrorCode = "NOT_FOUND" + ErrorCodeOrgBlocked ConstantsErrorCode = "ORG_BLOCKED" + ErrorCodePayloadTooLarge ConstantsErrorCode = "PAYLOAD_TOO_LARGE" + ErrorCodeTooManyRequests ConstantsErrorCode = "TOO_MANY_REQUESTS" + ErrorCodeUnauthorized ConstantsErrorCode = "UNAUTHORIZED" + ErrorCodeUnavailable ConstantsErrorCode = "UNAVAILABLE" + ErrorCodeValidationFailed ConstantsErrorCode = "VALIDATION_FAILED" +) + +// Valid indicates whether the value is a known member of the ConstantsErrorCode enum. +func (e ConstantsErrorCode) Valid() bool { + switch e { + case ErrorCodeAlreadyExists: + return true + case ErrorCodeConflict: + return true + case ErrorCodeForbidden: + return true + case ErrorCodeInternal: + return true + case ErrorCodeInvalidPayload: + return true + case ErrorCodeLimitReached: + return true + case ErrorCodeManagedResource: + return true + case ErrorCodeMethodNotAllowed: + return true + case ErrorCodeNotFound: + return true + case ErrorCodeOrgBlocked: + return true + case ErrorCodePayloadTooLarge: + return true + case ErrorCodeTooManyRequests: + return true + case ErrorCodeUnauthorized: + return true + case ErrorCodeUnavailable: + return true + case ErrorCodeValidationFailed: + return true + default: + return false + } +} + +// Defines values for ConstantsErrorReason. +const ( + ErrorReasonAlertChannelLimit ConstantsErrorReason = "ALERT_CHANNEL_LIMIT" + ErrorReasonAlreadyVerified ConstantsErrorReason = "ALREADY_VERIFIED" + ErrorReasonCallerOutsideNamespace ConstantsErrorReason = "CALLER_OUTSIDE_NAMESPACE" + ErrorReasonChannelTypeUnavailable ConstantsErrorReason = "CHANNEL_TYPE_UNAVAILABLE" + ErrorReasonCodeExpired ConstantsErrorReason = "CODE_EXPIRED" + ErrorReasonCodeRecentlySent ConstantsErrorReason = "CODE_RECENTLY_SENT" + ErrorReasonContactUnverified ConstantsErrorReason = "CONTACT_UNVERIFIED" + ErrorReasonDeliveryRejected ConstantsErrorReason = "DELIVERY_REJECTED" + ErrorReasonInsufficientScope ConstantsErrorReason = "INSUFFICIENT_SCOPE" + ErrorReasonMissingOrganizationID ConstantsErrorReason = "MISSING_ORGANIZATION_ID" + ErrorReasonMonitorLimit ConstantsErrorReason = "MONITOR_LIMIT" + ErrorReasonNothingToVerify ConstantsErrorReason = "NOTHING_TO_VERIFY" + ErrorReasonTooManyAttempts ConstantsErrorReason = "TOO_MANY_ATTEMPTS" + ErrorReasonUnverifiedChannelLimit ConstantsErrorReason = "UNVERIFIED_CHANNEL_LIMIT" +) + +// Valid indicates whether the value is a known member of the ConstantsErrorReason enum. +func (e ConstantsErrorReason) Valid() bool { + switch e { + case ErrorReasonAlertChannelLimit: + return true + case ErrorReasonAlreadyVerified: + return true + case ErrorReasonCallerOutsideNamespace: + return true + case ErrorReasonChannelTypeUnavailable: + return true + case ErrorReasonCodeExpired: + return true + case ErrorReasonCodeRecentlySent: + return true + case ErrorReasonContactUnverified: + return true + case ErrorReasonDeliveryRejected: + return true + case ErrorReasonInsufficientScope: + return true + case ErrorReasonMissingOrganizationID: + return true + case ErrorReasonMonitorLimit: + return true + case ErrorReasonNothingToVerify: + return true + case ErrorReasonTooManyAttempts: + return true + case ErrorReasonUnverifiedChannelLimit: + return true + default: + return false + } +} + +// Defines values for DtoAlertChannelKind. +const ( + DtoAlertChannelKindDiscord DtoAlertChannelKind = "discord" + DtoAlertChannelKindEmail DtoAlertChannelKind = "email" + DtoAlertChannelKindSlack DtoAlertChannelKind = "slack" + DtoAlertChannelKindSms DtoAlertChannelKind = "sms" + DtoAlertChannelKindVoice DtoAlertChannelKind = "voice" + DtoAlertChannelKindWebhook DtoAlertChannelKind = "webhook" +) + +// Valid indicates whether the value is a known member of the DtoAlertChannelKind enum. +func (e DtoAlertChannelKind) Valid() bool { + switch e { + case DtoAlertChannelKindDiscord: + return true + case DtoAlertChannelKindEmail: + return true + case DtoAlertChannelKindSlack: + return true + case DtoAlertChannelKindSms: + return true + case DtoAlertChannelKindVoice: + return true + case DtoAlertChannelKindWebhook: + return true + default: + return false + } +} + +// Defines values for DtoAlertChannelCreateKind. +const ( + DtoAlertChannelCreateKindDiscord DtoAlertChannelCreateKind = "discord" + DtoAlertChannelCreateKindEmail DtoAlertChannelCreateKind = "email" + DtoAlertChannelCreateKindSlack DtoAlertChannelCreateKind = "slack" + DtoAlertChannelCreateKindSms DtoAlertChannelCreateKind = "sms" + DtoAlertChannelCreateKindWebhook DtoAlertChannelCreateKind = "webhook" +) + +// Valid indicates whether the value is a known member of the DtoAlertChannelCreateKind enum. +func (e DtoAlertChannelCreateKind) Valid() bool { + switch e { + case DtoAlertChannelCreateKindDiscord: + return true + case DtoAlertChannelCreateKindEmail: + return true + case DtoAlertChannelCreateKindSlack: + return true + case DtoAlertChannelCreateKindSms: + return true + case DtoAlertChannelCreateKindWebhook: + return true + default: + return false + } +} + +// Defines values for DtoAlertChannelWithSecretKind. +const ( + Discord DtoAlertChannelWithSecretKind = "discord" + Email DtoAlertChannelWithSecretKind = "email" + Slack DtoAlertChannelWithSecretKind = "slack" + Sms DtoAlertChannelWithSecretKind = "sms" + Voice DtoAlertChannelWithSecretKind = "voice" + Webhook DtoAlertChannelWithSecretKind = "webhook" +) + +// Valid indicates whether the value is a known member of the DtoAlertChannelWithSecretKind enum. +func (e DtoAlertChannelWithSecretKind) Valid() bool { + switch e { + case Discord: + return true + case Email: + return true + case Slack: + return true + case Sms: + return true + case Voice: + return true + case Webhook: + return true + default: + return false + } +} + +// Defines values for DtoChannelDeliveryEvent. +const ( + DtoChannelDeliveryEventDown DtoChannelDeliveryEvent = "down" + DtoChannelDeliveryEventExpired DtoChannelDeliveryEvent = "expired" + DtoChannelDeliveryEventExpiring DtoChannelDeliveryEvent = "expiring" + DtoChannelDeliveryEventRecovered DtoChannelDeliveryEvent = "recovered" + DtoChannelDeliveryEventReminder DtoChannelDeliveryEvent = "reminder" + DtoChannelDeliveryEventWarning DtoChannelDeliveryEvent = "warning" +) + +// Valid indicates whether the value is a known member of the DtoChannelDeliveryEvent enum. +func (e DtoChannelDeliveryEvent) Valid() bool { + switch e { + case DtoChannelDeliveryEventDown: + return true + case DtoChannelDeliveryEventExpired: + return true + case DtoChannelDeliveryEventExpiring: + return true + case DtoChannelDeliveryEventRecovered: + return true + case DtoChannelDeliveryEventReminder: + return true + case DtoChannelDeliveryEventWarning: + return true + default: + return false + } +} + +// Defines values for DtoChannelDeliveryStatus. +const ( + DtoChannelDeliveryStatusDead DtoChannelDeliveryStatus = "dead" + DtoChannelDeliveryStatusPending DtoChannelDeliveryStatus = "pending" + DtoChannelDeliveryStatusSent DtoChannelDeliveryStatus = "sent" +) + +// Valid indicates whether the value is a known member of the DtoChannelDeliveryStatus enum. +func (e DtoChannelDeliveryStatus) Valid() bool { + switch e { + case DtoChannelDeliveryStatusDead: + return true + case DtoChannelDeliveryStatusPending: + return true + case DtoChannelDeliveryStatusSent: + return true + default: + return false + } +} + +// Defines values for DtoCheckResultSeverity. +const ( + DtoCheckResultSeverityCritical DtoCheckResultSeverity = "critical" + DtoCheckResultSeverityInconclusive DtoCheckResultSeverity = "inconclusive" + DtoCheckResultSeverityOk DtoCheckResultSeverity = "ok" + DtoCheckResultSeverityWarning DtoCheckResultSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the DtoCheckResultSeverity enum. +func (e DtoCheckResultSeverity) Valid() bool { + switch e { + case DtoCheckResultSeverityCritical: + return true + case DtoCheckResultSeverityInconclusive: + return true + case DtoCheckResultSeverityOk: + return true + case DtoCheckResultSeverityWarning: + return true + default: + return false + } +} + +// Defines values for DtoDomainRegistrationDnssec. +const ( + Signed DtoDomainRegistrationDnssec = "signed" + Unsigned DtoDomainRegistrationDnssec = "unsigned" +) + +// Valid indicates whether the value is a known member of the DtoDomainRegistrationDnssec enum. +func (e DtoDomainRegistrationDnssec) Valid() bool { + switch e { + case Signed: + return true + case Unsigned: + return true + default: + return false + } +} + +// Defines values for DtoDomainRegistrationSource. +const ( + Dns DtoDomainRegistrationSource = "dns" + Rdap DtoDomainRegistrationSource = "rdap" + Whois DtoDomainRegistrationSource = "whois" +) + +// Valid indicates whether the value is a known member of the DtoDomainRegistrationSource enum. +func (e DtoDomainRegistrationSource) Valid() bool { + switch e { + case Dns: + return true + case Rdap: + return true + case Whois: + return true + default: + return false + } +} + +// Defines values for DtoHTTPSettingsInputKeywordMode. +const ( + Absent DtoHTTPSettingsInputKeywordMode = "absent" + Present DtoHTTPSettingsInputKeywordMode = "present" +) + +// Valid indicates whether the value is a known member of the DtoHTTPSettingsInputKeywordMode enum. +func (e DtoHTTPSettingsInputKeywordMode) Valid() bool { + switch e { + case Absent: + return true + case Present: + return true + default: + return false + } +} + +// Defines values for DtoHTTPSettingsInputMethod. +const ( + DELETE DtoHTTPSettingsInputMethod = "DELETE" + GET DtoHTTPSettingsInputMethod = "GET" + HEAD DtoHTTPSettingsInputMethod = "HEAD" + OPTIONS DtoHTTPSettingsInputMethod = "OPTIONS" + PATCH DtoHTTPSettingsInputMethod = "PATCH" + POST DtoHTTPSettingsInputMethod = "POST" + PUT DtoHTTPSettingsInputMethod = "PUT" +) + +// Valid indicates whether the value is a known member of the DtoHTTPSettingsInputMethod enum. +func (e DtoHTTPSettingsInputMethod) Valid() bool { + switch e { + case DELETE: + return true + case GET: + return true + case HEAD: + return true + case OPTIONS: + return true + case PATCH: + return true + case POST: + return true + case PUT: + return true + default: + return false + } +} + +// Defines values for DtoHistoryBeatSeverity. +const ( + DtoHistoryBeatSeverityCritical DtoHistoryBeatSeverity = "critical" + DtoHistoryBeatSeverityInconclusive DtoHistoryBeatSeverity = "inconclusive" + DtoHistoryBeatSeverityOk DtoHistoryBeatSeverity = "ok" + DtoHistoryBeatSeverityWarning DtoHistoryBeatSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the DtoHistoryBeatSeverity enum. +func (e DtoHistoryBeatSeverity) Valid() bool { + switch e { + case DtoHistoryBeatSeverityCritical: + return true + case DtoHistoryBeatSeverityInconclusive: + return true + case DtoHistoryBeatSeverityOk: + return true + case DtoHistoryBeatSeverityWarning: + return true + default: + return false + } +} + +// Defines values for DtoIncidentAspect. +const ( + DtoIncidentAspectAvailability DtoIncidentAspect = "availability" + DtoIncidentAspectCertificate DtoIncidentAspect = "certificate" + DtoIncidentAspectDomain DtoIncidentAspect = "domain" +) + +// Valid indicates whether the value is a known member of the DtoIncidentAspect enum. +func (e DtoIncidentAspect) Valid() bool { + switch e { + case DtoIncidentAspectAvailability: + return true + case DtoIncidentAspectCertificate: + return true + case DtoIncidentAspectDomain: + return true + default: + return false + } +} + +// Defines values for DtoIncidentMonitorType. +const ( + DtoIncidentMonitorTypeDomain DtoIncidentMonitorType = "domain" + DtoIncidentMonitorTypeHttp DtoIncidentMonitorType = "http" + DtoIncidentMonitorTypeSsl DtoIncidentMonitorType = "ssl" +) + +// Valid indicates whether the value is a known member of the DtoIncidentMonitorType enum. +func (e DtoIncidentMonitorType) Valid() bool { + switch e { + case DtoIncidentMonitorTypeDomain: + return true + case DtoIncidentMonitorTypeHttp: + return true + case DtoIncidentMonitorTypeSsl: + return true + default: + return false + } +} + +// Defines values for DtoIncidentMonitorVariant. +const ( + DtoIncidentMonitorVariantDomain DtoIncidentMonitorVariant = "domain" + DtoIncidentMonitorVariantHttp DtoIncidentMonitorVariant = "http" + DtoIncidentMonitorVariantKeyword DtoIncidentMonitorVariant = "keyword" + DtoIncidentMonitorVariantSsl DtoIncidentMonitorVariant = "ssl" +) + +// Valid indicates whether the value is a known member of the DtoIncidentMonitorVariant enum. +func (e DtoIncidentMonitorVariant) Valid() bool { + switch e { + case DtoIncidentMonitorVariantDomain: + return true + case DtoIncidentMonitorVariantHttp: + return true + case DtoIncidentMonitorVariantKeyword: + return true + case DtoIncidentMonitorVariantSsl: + return true + default: + return false + } +} + +// Defines values for DtoIncidentPeakSeverity. +const ( + DtoIncidentPeakSeverityCritical DtoIncidentPeakSeverity = "critical" + DtoIncidentPeakSeverityWarning DtoIncidentPeakSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the DtoIncidentPeakSeverity enum. +func (e DtoIncidentPeakSeverity) Valid() bool { + switch e { + case DtoIncidentPeakSeverityCritical: + return true + case DtoIncidentPeakSeverityWarning: + return true + default: + return false + } +} + +// Defines values for DtoIncidentSeverity. +const ( + DtoIncidentSeverityCritical DtoIncidentSeverity = "critical" + DtoIncidentSeverityWarning DtoIncidentSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the DtoIncidentSeverity enum. +func (e DtoIncidentSeverity) Valid() bool { + switch e { + case DtoIncidentSeverityCritical: + return true + case DtoIncidentSeverityWarning: + return true + default: + return false + } +} + +// Defines values for DtoIncidentStatus. +const ( + DtoIncidentStatusOpen DtoIncidentStatus = "open" + DtoIncidentStatusResolved DtoIncidentStatus = "resolved" +) + +// Valid indicates whether the value is a known member of the DtoIncidentStatus enum. +func (e DtoIncidentStatus) Valid() bool { + switch e { + case DtoIncidentStatusOpen: + return true + case DtoIncidentStatusResolved: + return true + default: + return false + } +} + +// Defines values for DtoIncidentDeliveryEvent. +const ( + DtoIncidentDeliveryEventDown DtoIncidentDeliveryEvent = "down" + DtoIncidentDeliveryEventExpired DtoIncidentDeliveryEvent = "expired" + DtoIncidentDeliveryEventExpiring DtoIncidentDeliveryEvent = "expiring" + DtoIncidentDeliveryEventRecovered DtoIncidentDeliveryEvent = "recovered" + DtoIncidentDeliveryEventReminder DtoIncidentDeliveryEvent = "reminder" + DtoIncidentDeliveryEventWarning DtoIncidentDeliveryEvent = "warning" +) + +// Valid indicates whether the value is a known member of the DtoIncidentDeliveryEvent enum. +func (e DtoIncidentDeliveryEvent) Valid() bool { + switch e { + case DtoIncidentDeliveryEventDown: + return true + case DtoIncidentDeliveryEventExpired: + return true + case DtoIncidentDeliveryEventExpiring: + return true + case DtoIncidentDeliveryEventRecovered: + return true + case DtoIncidentDeliveryEventReminder: + return true + case DtoIncidentDeliveryEventWarning: + return true + default: + return false + } +} + +// Defines values for DtoIncidentDeliveryStatus. +const ( + DtoIncidentDeliveryStatusDead DtoIncidentDeliveryStatus = "dead" + DtoIncidentDeliveryStatusPending DtoIncidentDeliveryStatus = "pending" + DtoIncidentDeliveryStatusSent DtoIncidentDeliveryStatus = "sent" +) + +// Valid indicates whether the value is a known member of the DtoIncidentDeliveryStatus enum. +func (e DtoIncidentDeliveryStatus) Valid() bool { + switch e { + case DtoIncidentDeliveryStatusDead: + return true + case DtoIncidentDeliveryStatusPending: + return true + case DtoIncidentDeliveryStatusSent: + return true + default: + return false + } +} + +// Defines values for DtoIncidentDetailAspect. +const ( + DtoIncidentDetailAspectAvailability DtoIncidentDetailAspect = "availability" + DtoIncidentDetailAspectCertificate DtoIncidentDetailAspect = "certificate" + DtoIncidentDetailAspectDomain DtoIncidentDetailAspect = "domain" +) + +// Valid indicates whether the value is a known member of the DtoIncidentDetailAspect enum. +func (e DtoIncidentDetailAspect) Valid() bool { + switch e { + case DtoIncidentDetailAspectAvailability: + return true + case DtoIncidentDetailAspectCertificate: + return true + case DtoIncidentDetailAspectDomain: + return true + default: + return false + } +} + +// Defines values for DtoIncidentDetailMonitorType. +const ( + DtoIncidentDetailMonitorTypeDomain DtoIncidentDetailMonitorType = "domain" + DtoIncidentDetailMonitorTypeHttp DtoIncidentDetailMonitorType = "http" + DtoIncidentDetailMonitorTypeSsl DtoIncidentDetailMonitorType = "ssl" +) + +// Valid indicates whether the value is a known member of the DtoIncidentDetailMonitorType enum. +func (e DtoIncidentDetailMonitorType) Valid() bool { + switch e { + case DtoIncidentDetailMonitorTypeDomain: + return true + case DtoIncidentDetailMonitorTypeHttp: + return true + case DtoIncidentDetailMonitorTypeSsl: + return true + default: + return false + } +} + +// Defines values for DtoIncidentDetailMonitorVariant. +const ( + DtoIncidentDetailMonitorVariantDomain DtoIncidentDetailMonitorVariant = "domain" + DtoIncidentDetailMonitorVariantHttp DtoIncidentDetailMonitorVariant = "http" + DtoIncidentDetailMonitorVariantKeyword DtoIncidentDetailMonitorVariant = "keyword" + DtoIncidentDetailMonitorVariantSsl DtoIncidentDetailMonitorVariant = "ssl" +) + +// Valid indicates whether the value is a known member of the DtoIncidentDetailMonitorVariant enum. +func (e DtoIncidentDetailMonitorVariant) Valid() bool { + switch e { + case DtoIncidentDetailMonitorVariantDomain: + return true + case DtoIncidentDetailMonitorVariantHttp: + return true + case DtoIncidentDetailMonitorVariantKeyword: + return true + case DtoIncidentDetailMonitorVariantSsl: + return true + default: + return false + } +} + +// Defines values for DtoIncidentDetailPeakSeverity. +const ( + DtoIncidentDetailPeakSeverityCritical DtoIncidentDetailPeakSeverity = "critical" + DtoIncidentDetailPeakSeverityWarning DtoIncidentDetailPeakSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the DtoIncidentDetailPeakSeverity enum. +func (e DtoIncidentDetailPeakSeverity) Valid() bool { + switch e { + case DtoIncidentDetailPeakSeverityCritical: + return true + case DtoIncidentDetailPeakSeverityWarning: + return true + default: + return false + } +} + +// Defines values for DtoIncidentDetailSeverity. +const ( + DtoIncidentDetailSeverityCritical DtoIncidentDetailSeverity = "critical" + DtoIncidentDetailSeverityWarning DtoIncidentDetailSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the DtoIncidentDetailSeverity enum. +func (e DtoIncidentDetailSeverity) Valid() bool { + switch e { + case DtoIncidentDetailSeverityCritical: + return true + case DtoIncidentDetailSeverityWarning: + return true + default: + return false + } +} + +// Defines values for DtoIncidentDetailStatus. +const ( + DtoIncidentDetailStatusOpen DtoIncidentDetailStatus = "open" + DtoIncidentDetailStatusResolved DtoIncidentDetailStatus = "resolved" +) + +// Valid indicates whether the value is a known member of the DtoIncidentDetailStatus enum. +func (e DtoIncidentDetailStatus) Valid() bool { + switch e { + case DtoIncidentDetailStatusOpen: + return true + case DtoIncidentDetailStatusResolved: + return true + default: + return false + } +} + +// Defines values for DtoIncidentEventType. +const ( + DtoIncidentEventTypeAcknowledged DtoIncidentEventType = "acknowledged" + DtoIncidentEventTypeDeescalated DtoIncidentEventType = "deescalated" + DtoIncidentEventTypeDeliveryFailed DtoIncidentEventType = "delivery_failed" + DtoIncidentEventTypeEscalated DtoIncidentEventType = "escalated" + DtoIncidentEventTypeOpened DtoIncidentEventType = "opened" + DtoIncidentEventTypeReminder DtoIncidentEventType = "reminder" + DtoIncidentEventTypeResolved DtoIncidentEventType = "resolved" + DtoIncidentEventTypeThreshold DtoIncidentEventType = "threshold" +) + +// Valid indicates whether the value is a known member of the DtoIncidentEventType enum. +func (e DtoIncidentEventType) Valid() bool { + switch e { + case DtoIncidentEventTypeAcknowledged: + return true + case DtoIncidentEventTypeDeescalated: + return true + case DtoIncidentEventTypeDeliveryFailed: + return true + case DtoIncidentEventTypeEscalated: + return true + case DtoIncidentEventTypeOpened: + return true + case DtoIncidentEventTypeReminder: + return true + case DtoIncidentEventTypeResolved: + return true + case DtoIncidentEventTypeThreshold: + return true + default: + return false + } +} + +// Defines values for DtoLastCheckSeverity. +const ( + DtoLastCheckSeverityCritical DtoLastCheckSeverity = "critical" + DtoLastCheckSeverityInconclusive DtoLastCheckSeverity = "inconclusive" + DtoLastCheckSeverityOk DtoLastCheckSeverity = "ok" + DtoLastCheckSeverityWarning DtoLastCheckSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the DtoLastCheckSeverity enum. +func (e DtoLastCheckSeverity) Valid() bool { + switch e { + case DtoLastCheckSeverityCritical: + return true + case DtoLastCheckSeverityInconclusive: + return true + case DtoLastCheckSeverityOk: + return true + case DtoLastCheckSeverityWarning: + return true + default: + return false + } +} + +// Defines values for DtoMonitorOverallStatus. +const ( + DtoMonitorOverallStatusCritical DtoMonitorOverallStatus = "critical" + DtoMonitorOverallStatusOk DtoMonitorOverallStatus = "ok" + DtoMonitorOverallStatusPaused DtoMonitorOverallStatus = "paused" + DtoMonitorOverallStatusPending DtoMonitorOverallStatus = "pending" + DtoMonitorOverallStatusWarning DtoMonitorOverallStatus = "warning" +) + +// Valid indicates whether the value is a known member of the DtoMonitorOverallStatus enum. +func (e DtoMonitorOverallStatus) Valid() bool { + switch e { + case DtoMonitorOverallStatusCritical: + return true + case DtoMonitorOverallStatusOk: + return true + case DtoMonitorOverallStatusPaused: + return true + case DtoMonitorOverallStatusPending: + return true + case DtoMonitorOverallStatusWarning: + return true + default: + return false + } +} + +// Defines values for DtoMonitorStatus. +const ( + DtoMonitorStatusCritical DtoMonitorStatus = "critical" + DtoMonitorStatusOk DtoMonitorStatus = "ok" + DtoMonitorStatusPaused DtoMonitorStatus = "paused" + DtoMonitorStatusPending DtoMonitorStatus = "pending" + DtoMonitorStatusWarning DtoMonitorStatus = "warning" +) + +// Valid indicates whether the value is a known member of the DtoMonitorStatus enum. +func (e DtoMonitorStatus) Valid() bool { + switch e { + case DtoMonitorStatusCritical: + return true + case DtoMonitorStatusOk: + return true + case DtoMonitorStatusPaused: + return true + case DtoMonitorStatusPending: + return true + case DtoMonitorStatusWarning: + return true + default: + return false + } +} + +// Defines values for DtoMonitorType. +const ( + DtoMonitorTypeDomain DtoMonitorType = "domain" + DtoMonitorTypeHttp DtoMonitorType = "http" + DtoMonitorTypeSsl DtoMonitorType = "ssl" +) + +// Valid indicates whether the value is a known member of the DtoMonitorType enum. +func (e DtoMonitorType) Valid() bool { + switch e { + case DtoMonitorTypeDomain: + return true + case DtoMonitorTypeHttp: + return true + case DtoMonitorTypeSsl: + return true + default: + return false + } +} + +// Defines values for DtoMonitorVariant. +const ( + DtoMonitorVariantDomain DtoMonitorVariant = "domain" + DtoMonitorVariantHttp DtoMonitorVariant = "http" + DtoMonitorVariantKeyword DtoMonitorVariant = "keyword" + DtoMonitorVariantSsl DtoMonitorVariant = "ssl" +) + +// Valid indicates whether the value is a known member of the DtoMonitorVariant enum. +func (e DtoMonitorVariant) Valid() bool { + switch e { + case DtoMonitorVariantDomain: + return true + case DtoMonitorVariantHttp: + return true + case DtoMonitorVariantKeyword: + return true + case DtoMonitorVariantSsl: + return true + default: + return false + } +} + +// Defines values for DtoMonitorAlertRouteEvents. +const ( + DtoMonitorAlertRouteEventsDown DtoMonitorAlertRouteEvents = "down" + DtoMonitorAlertRouteEventsExpired DtoMonitorAlertRouteEvents = "expired" + DtoMonitorAlertRouteEventsExpiring DtoMonitorAlertRouteEvents = "expiring" + DtoMonitorAlertRouteEventsRecovered DtoMonitorAlertRouteEvents = "recovered" + DtoMonitorAlertRouteEventsWarning DtoMonitorAlertRouteEvents = "warning" +) + +// Valid indicates whether the value is a known member of the DtoMonitorAlertRouteEvents enum. +func (e DtoMonitorAlertRouteEvents) Valid() bool { + switch e { + case DtoMonitorAlertRouteEventsDown: + return true + case DtoMonitorAlertRouteEventsExpired: + return true + case DtoMonitorAlertRouteEventsExpiring: + return true + case DtoMonitorAlertRouteEventsRecovered: + return true + case DtoMonitorAlertRouteEventsWarning: + return true + default: + return false + } +} + +// Defines values for DtoMonitorAlertsApplicableEvents. +const ( + DtoMonitorAlertsApplicableEventsDown DtoMonitorAlertsApplicableEvents = "down" + DtoMonitorAlertsApplicableEventsExpired DtoMonitorAlertsApplicableEvents = "expired" + DtoMonitorAlertsApplicableEventsExpiring DtoMonitorAlertsApplicableEvents = "expiring" + DtoMonitorAlertsApplicableEventsRecovered DtoMonitorAlertsApplicableEvents = "recovered" + DtoMonitorAlertsApplicableEventsWarning DtoMonitorAlertsApplicableEvents = "warning" +) + +// Valid indicates whether the value is a known member of the DtoMonitorAlertsApplicableEvents enum. +func (e DtoMonitorAlertsApplicableEvents) Valid() bool { + switch e { + case DtoMonitorAlertsApplicableEventsDown: + return true + case DtoMonitorAlertsApplicableEventsExpired: + return true + case DtoMonitorAlertsApplicableEventsExpiring: + return true + case DtoMonitorAlertsApplicableEventsRecovered: + return true + case DtoMonitorAlertsApplicableEventsWarning: + return true + default: + return false + } +} + +// Defines values for DtoMonitorAspectAspect. +const ( + DtoMonitorAspectAspectCertificate DtoMonitorAspectAspect = "certificate" + DtoMonitorAspectAspectDomain DtoMonitorAspectAspect = "domain" +) + +// Valid indicates whether the value is a known member of the DtoMonitorAspectAspect enum. +func (e DtoMonitorAspectAspect) Valid() bool { + switch e { + case DtoMonitorAspectAspectCertificate: + return true + case DtoMonitorAspectAspectDomain: + return true + default: + return false + } +} + +// Defines values for DtoMonitorAspectStatus. +const ( + DtoMonitorAspectStatusCritical DtoMonitorAspectStatus = "critical" + DtoMonitorAspectStatusOk DtoMonitorAspectStatus = "ok" + DtoMonitorAspectStatusPending DtoMonitorAspectStatus = "pending" + DtoMonitorAspectStatusWarning DtoMonitorAspectStatus = "warning" +) + +// Valid indicates whether the value is a known member of the DtoMonitorAspectStatus enum. +func (e DtoMonitorAspectStatus) Valid() bool { + switch e { + case DtoMonitorAspectStatusCritical: + return true + case DtoMonitorAspectStatusOk: + return true + case DtoMonitorAspectStatusPending: + return true + case DtoMonitorAspectStatusWarning: + return true + default: + return false + } +} + +// Defines values for DtoMonitorBulkRequestAction. +const ( + DtoMonitorBulkRequestActionDelete DtoMonitorBulkRequestAction = "delete" + DtoMonitorBulkRequestActionPause DtoMonitorBulkRequestAction = "pause" + DtoMonitorBulkRequestActionResume DtoMonitorBulkRequestAction = "resume" +) + +// Valid indicates whether the value is a known member of the DtoMonitorBulkRequestAction enum. +func (e DtoMonitorBulkRequestAction) Valid() bool { + switch e { + case DtoMonitorBulkRequestActionDelete: + return true + case DtoMonitorBulkRequestActionPause: + return true + case DtoMonitorBulkRequestActionResume: + return true + default: + return false + } +} + +// Defines values for DtoMonitorBulkResultAction. +const ( + DtoMonitorBulkResultActionDelete DtoMonitorBulkResultAction = "delete" + DtoMonitorBulkResultActionPause DtoMonitorBulkResultAction = "pause" + DtoMonitorBulkResultActionResume DtoMonitorBulkResultAction = "resume" +) + +// Valid indicates whether the value is a known member of the DtoMonitorBulkResultAction enum. +func (e DtoMonitorBulkResultAction) Valid() bool { + switch e { + case DtoMonitorBulkResultActionDelete: + return true + case DtoMonitorBulkResultActionPause: + return true + case DtoMonitorBulkResultActionResume: + return true + default: + return false + } +} + +// Defines values for DtoMonitorCertificateSeverity. +const ( + DtoMonitorCertificateSeverityCritical DtoMonitorCertificateSeverity = "critical" + DtoMonitorCertificateSeverityInconclusive DtoMonitorCertificateSeverity = "inconclusive" + DtoMonitorCertificateSeverityOk DtoMonitorCertificateSeverity = "ok" + DtoMonitorCertificateSeverityWarning DtoMonitorCertificateSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the DtoMonitorCertificateSeverity enum. +func (e DtoMonitorCertificateSeverity) Valid() bool { + switch e { + case DtoMonitorCertificateSeverityCritical: + return true + case DtoMonitorCertificateSeverityInconclusive: + return true + case DtoMonitorCertificateSeverityOk: + return true + case DtoMonitorCertificateSeverityWarning: + return true + default: + return false + } +} + +// Defines values for DtoMonitorCreateType. +const ( + DtoMonitorCreateTypeDomain DtoMonitorCreateType = "domain" + DtoMonitorCreateTypeHttp DtoMonitorCreateType = "http" + DtoMonitorCreateTypeSsl DtoMonitorCreateType = "ssl" +) + +// Valid indicates whether the value is a known member of the DtoMonitorCreateType enum. +func (e DtoMonitorCreateType) Valid() bool { + switch e { + case DtoMonitorCreateTypeDomain: + return true + case DtoMonitorCreateTypeHttp: + return true + case DtoMonitorCreateTypeSsl: + return true + default: + return false + } +} + +// Defines values for DtoMonitorEventAspect. +const ( + DtoMonitorEventAspectAvailability DtoMonitorEventAspect = "availability" + DtoMonitorEventAspectCertificate DtoMonitorEventAspect = "certificate" + DtoMonitorEventAspectDomain DtoMonitorEventAspect = "domain" +) + +// Valid indicates whether the value is a known member of the DtoMonitorEventAspect enum. +func (e DtoMonitorEventAspect) Valid() bool { + switch e { + case DtoMonitorEventAspectAvailability: + return true + case DtoMonitorEventAspectCertificate: + return true + case DtoMonitorEventAspectDomain: + return true + default: + return false + } +} + +// Defines values for DtoMonitorEventType. +const ( + CertificateRenewed DtoMonitorEventType = "certificate_renewed" +) + +// Valid indicates whether the value is a known member of the DtoMonitorEventType enum. +func (e DtoMonitorEventType) Valid() bool { + switch e { + case CertificateRenewed: + return true + default: + return false + } +} + +// Defines values for DtoMonitorStatsGranularity. +const ( + Day DtoMonitorStatsGranularity = "day" + Hour DtoMonitorStatsGranularity = "hour" +) + +// Valid indicates whether the value is a known member of the DtoMonitorStatsGranularity enum. +func (e DtoMonitorStatsGranularity) Valid() bool { + switch e { + case Day: + return true + case Hour: + return true + default: + return false + } +} + +// Defines values for DtoStatusChangeFrom. +const ( + DtoStatusChangeFromCritical DtoStatusChangeFrom = "critical" + DtoStatusChangeFromOk DtoStatusChangeFrom = "ok" + DtoStatusChangeFromPending DtoStatusChangeFrom = "pending" + DtoStatusChangeFromWarning DtoStatusChangeFrom = "warning" +) + +// Valid indicates whether the value is a known member of the DtoStatusChangeFrom enum. +func (e DtoStatusChangeFrom) Valid() bool { + switch e { + case DtoStatusChangeFromCritical: + return true + case DtoStatusChangeFromOk: + return true + case DtoStatusChangeFromPending: + return true + case DtoStatusChangeFromWarning: + return true + default: + return false + } +} + +// Defines values for DtoStatusChangeTo. +const ( + DtoStatusChangeToCritical DtoStatusChangeTo = "critical" + DtoStatusChangeToOk DtoStatusChangeTo = "ok" + DtoStatusChangeToWarning DtoStatusChangeTo = "warning" +) + +// Valid indicates whether the value is a known member of the DtoStatusChangeTo enum. +func (e DtoStatusChangeTo) Valid() bool { + switch e { + case DtoStatusChangeToCritical: + return true + case DtoStatusChangeToOk: + return true + case DtoStatusChangeToWarning: + return true + default: + return false + } +} + +// Defines values for ValidationRule. +const ( + RuleDependsOn ValidationRule = "dependsOn" + RuleDuplicate ValidationRule = "duplicate" + RuleExclusive ValidationRule = "exclusive" + RuleFormat ValidationRule = "format" + RuleImmutable ValidationRule = "immutable" + RuleMax ValidationRule = "max" + RuleMaxItems ValidationRule = "maxItems" + RuleMaxLength ValidationRule = "maxLength" + RuleMin ValidationRule = "min" + RuleMismatch ValidationRule = "mismatch" + RuleNotAllowed ValidationRule = "notAllowed" + RuleOneOf ValidationRule = "oneOf" + RulePublic ValidationRule = "public" + RuleRange ValidationRule = "range" + RuleReference ValidationRule = "reference" + RuleRequired ValidationRule = "required" + RuleType ValidationRule = "type" + RuleUnique ValidationRule = "unique" + RuleUnknown ValidationRule = "unknown" + RuleUnsupported ValidationRule = "unsupported" + RuleUnverified ValidationRule = "unverified" +) + +// Valid indicates whether the value is a known member of the ValidationRule enum. +func (e ValidationRule) Valid() bool { + switch e { + case RuleDependsOn: + return true + case RuleDuplicate: + return true + case RuleExclusive: + return true + case RuleFormat: + return true + case RuleImmutable: + return true + case RuleMax: + return true + case RuleMaxItems: + return true + case RuleMaxLength: + return true + case RuleMin: + return true + case RuleMismatch: + return true + case RuleNotAllowed: + return true + case RuleOneOf: + return true + case RulePublic: + return true + case RuleRange: + return true + case RuleReference: + return true + case RuleRequired: + return true + case RuleType: + return true + case RuleUnique: + return true + case RuleUnknown: + return true + case RuleUnsupported: + return true + case RuleUnverified: + return true + default: + return false + } +} + +// Defines values for ValidationUnit. +const ( + UnitBytes ValidationUnit = "bytes" + UnitCharacters ValidationUnit = "characters" +) + +// Valid indicates whether the value is a known member of the ValidationUnit enum. +func (e ValidationUnit) Valid() bool { + switch e { + case UnitBytes: + return true + case UnitCharacters: + return true + default: + return false + } +} + +// Defines values for ListAlertChannelDeliveriesParamsStatus. +const ( + ListAlertChannelDeliveriesParamsStatusDead ListAlertChannelDeliveriesParamsStatus = "dead" + ListAlertChannelDeliveriesParamsStatusPending ListAlertChannelDeliveriesParamsStatus = "pending" + ListAlertChannelDeliveriesParamsStatusSent ListAlertChannelDeliveriesParamsStatus = "sent" +) + +// Valid indicates whether the value is a known member of the ListAlertChannelDeliveriesParamsStatus enum. +func (e ListAlertChannelDeliveriesParamsStatus) Valid() bool { + switch e { + case ListAlertChannelDeliveriesParamsStatusDead: + return true + case ListAlertChannelDeliveriesParamsStatusPending: + return true + case ListAlertChannelDeliveriesParamsStatusSent: + return true + default: + return false + } +} + +// Defines values for ListIncidentsParamsAcknowledged. +const ( + False ListIncidentsParamsAcknowledged = "false" + True ListIncidentsParamsAcknowledged = "true" +) + +// Valid indicates whether the value is a known member of the ListIncidentsParamsAcknowledged enum. +func (e ListIncidentsParamsAcknowledged) Valid() bool { + switch e { + case False: + return true + case True: + return true + default: + return false + } +} + +// Defines values for ListIncidentsParamsAspect. +const ( + ListIncidentsParamsAspectAvailability ListIncidentsParamsAspect = "availability" + ListIncidentsParamsAspectCertificate ListIncidentsParamsAspect = "certificate" + ListIncidentsParamsAspectDomain ListIncidentsParamsAspect = "domain" +) + +// Valid indicates whether the value is a known member of the ListIncidentsParamsAspect enum. +func (e ListIncidentsParamsAspect) Valid() bool { + switch e { + case ListIncidentsParamsAspectAvailability: + return true + case ListIncidentsParamsAspectCertificate: + return true + case ListIncidentsParamsAspectDomain: + return true + default: + return false + } +} + +// Defines values for ListIncidentsParamsSeverity. +const ( + ListIncidentsParamsSeverityCritical ListIncidentsParamsSeverity = "critical" + ListIncidentsParamsSeverityWarning ListIncidentsParamsSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the ListIncidentsParamsSeverity enum. +func (e ListIncidentsParamsSeverity) Valid() bool { + switch e { + case ListIncidentsParamsSeverityCritical: + return true + case ListIncidentsParamsSeverityWarning: + return true + default: + return false + } +} + +// Defines values for ListIncidentsParamsStatus. +const ( + ListIncidentsParamsStatusOpen ListIncidentsParamsStatus = "open" + ListIncidentsParamsStatusResolved ListIncidentsParamsStatus = "resolved" +) + +// Valid indicates whether the value is a known member of the ListIncidentsParamsStatus enum. +func (e ListIncidentsParamsStatus) Valid() bool { + switch e { + case ListIncidentsParamsStatusOpen: + return true + case ListIncidentsParamsStatusResolved: + return true + default: + return false + } +} + +// Defines values for ListMonitorsParamsInclude. +const ( + History ListMonitorsParamsInclude = "history" +) + +// Valid indicates whether the value is a known member of the ListMonitorsParamsInclude enum. +func (e ListMonitorsParamsInclude) Valid() bool { + switch e { + case History: + return true + default: + return false + } +} + +// Defines values for ListMonitorsParamsSort. +const ( + Created ListMonitorsParamsSort = "created" + LastChecked ListMonitorsParamsSort = "lastChecked" + Name ListMonitorsParamsSort = "name" + Status ListMonitorsParamsSort = "status" + Uptime ListMonitorsParamsSort = "uptime" +) + +// Valid indicates whether the value is a known member of the ListMonitorsParamsSort enum. +func (e ListMonitorsParamsSort) Valid() bool { + switch e { + case Created: + return true + case LastChecked: + return true + case Name: + return true + case Status: + return true + case Uptime: + return true + default: + return false + } +} + +// Defines values for ListMonitorsParamsStatus. +const ( + ListMonitorsParamsStatusCritical ListMonitorsParamsStatus = "critical" + ListMonitorsParamsStatusOk ListMonitorsParamsStatus = "ok" + ListMonitorsParamsStatusPaused ListMonitorsParamsStatus = "paused" + ListMonitorsParamsStatusPending ListMonitorsParamsStatus = "pending" + ListMonitorsParamsStatusWarning ListMonitorsParamsStatus = "warning" +) + +// Valid indicates whether the value is a known member of the ListMonitorsParamsStatus enum. +func (e ListMonitorsParamsStatus) Valid() bool { + switch e { + case ListMonitorsParamsStatusCritical: + return true + case ListMonitorsParamsStatusOk: + return true + case ListMonitorsParamsStatusPaused: + return true + case ListMonitorsParamsStatusPending: + return true + case ListMonitorsParamsStatusWarning: + return true + default: + return false + } +} + +// Defines values for ListMonitorsParamsType. +const ( + Domain ListMonitorsParamsType = "domain" + Http ListMonitorsParamsType = "http" + Ssl ListMonitorsParamsType = "ssl" +) + +// Valid indicates whether the value is a known member of the ListMonitorsParamsType enum. +func (e ListMonitorsParamsType) Valid() bool { + switch e { + case Domain: + return true + case Http: + return true + case Ssl: + return true + default: + return false + } +} + +// Defines values for GetMonitorStatsParamsRange. +const ( + N24h GetMonitorStatsParamsRange = "24h" + N30d GetMonitorStatsParamsRange = "30d" + N7d GetMonitorStatsParamsRange = "7d" + N90d GetMonitorStatsParamsRange = "90d" +) + +// Valid indicates whether the value is a known member of the GetMonitorStatsParamsRange enum. +func (e GetMonitorStatsParamsRange) Valid() bool { + switch e { + case N24h: + return true + case N30d: + return true + case N7d: + return true + case N90d: + return true + default: + return false + } +} + +// ConstantsErrorCode defines model for constants.ErrorCode. +type ConstantsErrorCode string + +// ConstantsErrorReason defines model for constants.ErrorReason. +type ConstantsErrorReason string + +// DtoAlertChannel defines model for dto.AlertChannel. +type DtoAlertChannel struct { + CreatedAt string `json:"createdAt"` + Enabled bool `json:"enabled"` + Id openapi_types.UUID `json:"id"` + IsDefault bool `json:"isDefault"` + + // Kind Kind is how the channel delivers. voice is a voice-call channel made + // before calls were withdrawn: it stays disabled and gets no alerts; + // it can be renamed or deleted. + Kind DtoAlertChannelKind `json:"kind"` + Name string `json:"name"` + Settings DtoAlertChannelSettings `json:"settings"` + UpdatedAt string `json:"updatedAt"` + + // Verified Verified is false for an SMS or email-address channel until + // its contact confirmed a code; such a channel gets no alerts. + Verified bool `json:"verified"` +} + +// DtoAlertChannelKind Kind is how the channel delivers. voice is a voice-call channel made +// before calls were withdrawn: it stays disabled and gets no alerts; +// it can be renamed or deleted. +type DtoAlertChannelKind string + +// DtoAlertChannelCreate defines model for dto.AlertChannelCreate. +type DtoAlertChannelCreate struct { + // IsDefault IsDefault channels get the alerts of monitors without their own + // alert settings. + IsDefault *bool `json:"isDefault,omitempty"` + Kind DtoAlertChannelCreateKind `json:"kind"` + Name string `json:"name"` + Settings DtoAlertChannelSettingsInput `json:"settings"` +} + +// DtoAlertChannelCreateKind defines model for DtoAlertChannelCreate.Kind. +type DtoAlertChannelCreateKind string + +// DtoAlertChannelSettings defines model for dto.AlertChannelSettings. +type DtoAlertChannelSettings struct { + Address *string `json:"address,omitempty"` + Hint *string `json:"hint,omitempty"` + Members *bool `json:"members,omitempty"` + Phone *string `json:"phone,omitempty"` + Url *string `json:"url,omitempty"` +} + +// DtoAlertChannelSettingsInput defines model for dto.AlertChannelSettingsInput. +type DtoAlertChannelSettingsInput struct { + Address *string `json:"address,omitempty"` + Members *bool `json:"members,omitempty"` + Phone *string `json:"phone,omitempty"` + SigningSecret *string `json:"signingSecret,omitempty"` + Url *string `json:"url,omitempty"` +} + +// DtoAlertChannelTestResult defines model for dto.AlertChannelTestResult. +type DtoAlertChannelTestResult struct { + ProviderRef string `json:"providerRef"` +} + +// DtoAlertChannelUpdate defines model for dto.AlertChannelUpdate. +type DtoAlertChannelUpdate struct { + Enabled *bool `json:"enabled,omitempty"` + IsDefault *bool `json:"isDefault,omitempty"` + Name *string `json:"name,omitempty"` + RotateSecret *bool `json:"rotateSecret,omitempty"` + Settings *DtoAlertChannelSettingsInput `json:"settings,omitempty"` +} + +// DtoAlertChannelVerifyConfirm defines model for dto.AlertChannelVerifyConfirm. +type DtoAlertChannelVerifyConfirm struct { + Code string `json:"code"` +} + +// DtoAlertChannelWithSecret defines model for dto.AlertChannelWithSecret. +type DtoAlertChannelWithSecret struct { + CreatedAt string `json:"createdAt"` + Enabled bool `json:"enabled"` + Id openapi_types.UUID `json:"id"` + IsDefault bool `json:"isDefault"` + + // Kind Kind is how the channel delivers. voice is a voice-call channel made + // before calls were withdrawn: it stays disabled and gets no alerts; + // it can be renamed or deleted. + Kind DtoAlertChannelWithSecretKind `json:"kind"` + Name string `json:"name"` + Settings DtoAlertChannelSettings `json:"settings"` + SigningSecret *string `json:"signingSecret,omitempty"` + UpdatedAt string `json:"updatedAt"` + + // Verified Verified is false for an SMS or email-address channel until + // its contact confirmed a code; such a channel gets no alerts. + Verified bool `json:"verified"` +} + +// DtoAlertChannelWithSecretKind Kind is how the channel delivers. voice is a voice-call channel made +// before calls were withdrawn: it stays disabled and gets no alerts; +// it can be renamed or deleted. +type DtoAlertChannelWithSecretKind string + +// DtoAvailability defines model for dto.Availability. +type DtoAvailability struct { + Checks int `json:"checks"` + Critical int `json:"critical"` + Days []DtoDayAvailability `json:"days"` + DowntimeMinutes int `json:"downtimeMinutes"` + From string `json:"from"` + Inconclusive int `json:"inconclusive"` + Ok int `json:"ok"` + To string `json:"to"` + + // UptimePercent UptimePercent is (ok + warning) / (ok + warning + critical); absent + // without conclusive checks, and for SSL and domain monitors (no + // uptime: their downtime is always 0). + UptimePercent *float32 `json:"uptimePercent,omitempty"` + Warning int `json:"warning"` +} + +// DtoCertificate defines model for dto.Certificate. +type DtoCertificate struct { + // Chain Chain is what the server presented, leaf first; absent on results + // recorded before chains were kept. + Chain *[]DtoChainCertificate `json:"chain,omitempty"` + ChainValid bool `json:"chainValid"` + DaysRemaining int `json:"daysRemaining"` + + // DnsNames DNSNames are the subject alternative names (SANs). + DnsNames *[]string `json:"dnsNames,omitempty"` + + // FingerprintSha256 FingerprintSHA256 is the SHA-256 of the certificate (DER), hex. + FingerprintSha256 *string `json:"fingerprintSha256,omitempty"` + HostnameValid bool `json:"hostnameValid"` + Issuer string `json:"issuer"` + IssuerOrg *string `json:"issuerOrg,omitempty"` + NotAfter string `json:"notAfter"` + NotBefore string `json:"notBefore"` + SerialNumber *string `json:"serialNumber,omitempty"` + + // SignatureAlgorithm SignatureAlgorithm as Go names it ("SHA256-RSA", "ECDSA-SHA384"). + SignatureAlgorithm *string `json:"signatureAlgorithm,omitempty"` + Subject string `json:"subject"` + + // VerifiedChainLength VerifiedChainLength counts the certificates from the leaf to a + // trusted root, root included; absent when the chain doesn't verify. + VerifiedChainLength *int `json:"verifiedChainLength,omitempty"` +} + +// DtoCertificateRenewal defines model for dto.CertificateRenewal. +type DtoCertificateRenewal struct { + Current DtoRenewedCertificate `json:"current"` + Previous DtoRenewedCertificate `json:"previous"` +} + +// DtoChainCertificate defines model for dto.ChainCertificate. +type DtoChainCertificate struct { + IsCA bool `json:"isCA"` + Issuer string `json:"issuer"` + NotAfter string `json:"notAfter"` + NotBefore string `json:"notBefore"` + Subject string `json:"subject"` +} + +// DtoChannelDelivery defines model for dto.ChannelDelivery. +type DtoChannelDelivery struct { + Attempts int `json:"attempts"` + CreatedAt string `json:"createdAt"` + Event DtoChannelDeliveryEvent `json:"event"` + Id openapi_types.UUID `json:"id"` + + // IncidentId IncidentID is absent for an alert outside an incident. + IncidentId *openapi_types.UUID `json:"incidentId,omitempty"` + LastError *string `json:"lastError,omitempty"` + MonitorId openapi_types.UUID `json:"monitorId"` + MonitorName string `json:"monitorName"` + + // NextAttemptAt NextAttemptAt is set while pending. + NextAttemptAt *string `json:"nextAttemptAt,omitempty"` + SentAt *string `json:"sentAt,omitempty"` + + // Status Status: pending (queued or waiting to retry), sent, dead (gave up). + Status DtoChannelDeliveryStatus `json:"status"` +} + +// DtoChannelDeliveryEvent defines model for DtoChannelDelivery.Event. +type DtoChannelDeliveryEvent string + +// DtoChannelDeliveryStatus Status: pending (queued or waiting to retry), sent, dead (gave up). +type DtoChannelDeliveryStatus string + +// DtoCheckRegion defines model for dto.CheckRegion. +type DtoCheckRegion struct { + // Code Code is the AWS region code, as results' region carries it. + Code string `json:"code"` + + // Name Name is the city people know the region by. + Name string `json:"name"` +} + +// DtoCheckResult defines model for dto.CheckResult. +type DtoCheckResult struct { + Certificate *DtoCertificate `json:"certificate,omitempty"` + CheckedAt string `json:"checkedAt"` + Condition string `json:"condition"` + Domain *DtoDomainRegistration `json:"domain,omitempty"` + ErrorMessage *string `json:"errorMessage,omitempty"` + Id int `json:"id"` + Redirects *[]string `json:"redirects,omitempty"` + Region string `json:"region"` + Severity DtoCheckResultSeverity `json:"severity"` + StatusCode *int `json:"statusCode,omitempty"` + Timings DtoCheckTimings `json:"timings"` +} + +// DtoCheckResultSeverity defines model for DtoCheckResult.Severity. +type DtoCheckResultSeverity string + +// DtoCheckTimings defines model for dto.CheckTimings. +type DtoCheckTimings struct { + ConnectMs *int `json:"connectMs,omitempty"` + DnsMs *int `json:"dnsMs,omitempty"` + RedirectMs *int `json:"redirectMs,omitempty"` + TlsMs *int `json:"tlsMs,omitempty"` + TotalMs int `json:"totalMs"` + TtfbMs *int `json:"ttfbMs,omitempty"` +} + +// DtoConditionFacts defines model for dto.ConditionFacts. +type DtoConditionFacts struct { + DaysRemaining *int `json:"daysRemaining,omitempty"` + ExpiresAt *string `json:"expiresAt,omitempty"` + + // ResponseTimeMs ResponseTimeMs and SlowThresholdMs: a slow response's time and the + // threshold it went over (slow_response only). + ResponseTimeMs *int `json:"responseTimeMs,omitempty"` + SlowThresholdMs *int `json:"slowThresholdMs,omitempty"` + StatusCode *int `json:"statusCode,omitempty"` + + // ThresholdDays ThresholdDays is the smallest expiry threshold the expiry is within. + ThresholdDays *int `json:"thresholdDays,omitempty"` +} + +// DtoDayAvailability defines model for dto.DayAvailability. +type DtoDayAvailability struct { + Checks int `json:"checks"` + Critical int `json:"critical"` + + // Date Date is the UTC day, YYYY-MM-DD. + Date string `json:"date"` + + // DowntimeMinutes DowntimeMinutes estimates the time spent down: the share of + // critical checks among the conclusive ones times the minutes the + // day's checks cover. A warning is not downtime. + DowntimeMinutes int `json:"downtimeMinutes"` + Inconclusive int `json:"inconclusive"` + + // NoData NoData: no checks that day (draw it gray, never as up). + NoData bool `json:"noData"` + Ok int `json:"ok"` + UptimePercent *float32 `json:"uptimePercent,omitempty"` + Warning int `json:"warning"` +} + +// DtoDomainRegistration defines model for dto.DomainRegistration. +type DtoDomainRegistration struct { + // CheckedAt CheckedAt is when the registry was asked (lookups are cached up to + // an hour). + CheckedAt string `json:"checkedAt"` + + // DaysRemaining DaysRemaining is 0 on the expiry day, negative after it. + DaysRemaining *int `json:"daysRemaining,omitempty"` + + // Dnssec DNSSEC: signed when the registry holds DS records for the domain; + // absent when the registry doesn't say. + Dnssec *DtoDomainRegistrationDnssec `json:"dnssec,omitempty"` + Domain string `json:"domain"` + + // ExpiresAt ExpiresAt is the expiry date at 00:00 UTC; absent when the registry + // publishes none. + ExpiresAt *string `json:"expiresAt,omitempty"` + + // Nameservers Nameservers are the delegation's nameservers, lower case, in the + // registry's order; [] when unknown (results recorded before they were + // kept, registries that publish none). + Nameservers []string `json:"nameservers"` + Registered bool `json:"registered"` + + // RegisteredAt RegisteredAt is the registration (creation) date at 00:00 UTC, and + // UpdatedAt the registry's last change of it; absent when the registry + // doesn't publish them (and for dns answers). + RegisteredAt *string `json:"registeredAt,omitempty"` + Registrar *string `json:"registrar,omitempty"` + Source DtoDomainRegistrationSource `json:"source"` + + // StatusCodes StatusCodes are the EPP status codes (RFC 5731), e.g. ok, + // clientTransferProhibited, serverHold, pendingDelete, + // redemptionPeriod; [] when unknown (dns answers). + StatusCodes []string `json:"statusCodes"` + UpdatedAt *string `json:"updatedAt,omitempty"` +} + +// DtoDomainRegistrationDnssec DNSSEC: signed when the registry holds DS records for the domain; +// absent when the registry doesn't say. +type DtoDomainRegistrationDnssec string + +// DtoDomainRegistrationSource defines model for DtoDomainRegistration.Source. +type DtoDomainRegistrationSource string + +// DtoDomainSettings defines model for dto.DomainSettings. +type DtoDomainSettings struct { + Domain string `json:"domain"` + ExpiryThresholdsDays []int `json:"expiryThresholdsDays"` +} + +// DtoDomainSettingsInput defines model for dto.DomainSettingsInput. +type DtoDomainSettingsInput struct { + Domain string `json:"domain"` + ExpiryThresholdsDays []int `json:"expiryThresholdsDays"` +} + +// DtoExpiryWatch defines model for dto.ExpiryWatch. +type DtoExpiryWatch struct { + ThresholdsDays []int `json:"thresholdsDays"` +} + +// DtoExpiryWatchInput defines model for dto.ExpiryWatchInput. +type DtoExpiryWatchInput struct { + // ThresholdsDays ThresholdsDays are the expiry warnings, in days before expiry. + ThresholdsDays []int `json:"thresholdsDays"` +} + +// DtoHTTPHeader defines model for dto.HTTPHeader. +type DtoHTTPHeader struct { + Name string `json:"name"` + Secret bool `json:"secret"` + Value *string `json:"value,omitempty"` +} + +// DtoHTTPHeaderInput defines model for dto.HTTPHeaderInput. +type DtoHTTPHeaderInput struct { + Name string `json:"name"` + Secret *bool `json:"secret,omitempty"` + Value *string `json:"value,omitempty"` +} + +// DtoHTTPSettings defines model for dto.HTTPSettings. +type DtoHTTPSettings struct { + // CertificateExpiry CertificateExpiry and DomainExpiry are the watches that are on; + // absent when off. + CertificateExpiry *DtoExpiryWatch `json:"certificateExpiry,omitempty"` + DomainExpiry *DtoExpiryWatch `json:"domainExpiry,omitempty"` + ExpectedStatus []string `json:"expectedStatus"` + FollowRedirects bool `json:"followRedirects"` + Headers []DtoHTTPHeader `json:"headers"` + Keyword *string `json:"keyword,omitempty"` + KeywordCaseSensitive bool `json:"keywordCaseSensitive"` + KeywordMode *string `json:"keywordMode,omitempty"` + MaxRedirects int `json:"maxRedirects"` + Method string `json:"method"` + RequestBody *string `json:"requestBody,omitempty"` + RequestBodyContentType *string `json:"requestBodyContentType,omitempty"` + SlowThresholdMs *int `json:"slowThresholdMs,omitempty"` + TimeoutMs int `json:"timeoutMs"` + Url string `json:"url"` + VerifyTls bool `json:"verifyTls"` +} + +// DtoHTTPSettingsInput defines model for dto.HTTPSettingsInput. +type DtoHTTPSettingsInput struct { + // CertificateExpiry CertificateExpiry watches the expiry of the certificate the URL + // presents (https:// URLs only), judged with every check; omit it to + // leave the watch off. + CertificateExpiry *DtoExpiryWatchInput `json:"certificateExpiry,omitempty"` + + // DomainExpiry DomainExpiry watches the registration of the URL's registrable + // domain (shop.example.com watches example.com), looked up twice a + // day; omit it to leave the watch off. Not for IP addresses. + DomainExpiry *DtoExpiryWatchInput `json:"domainExpiry,omitempty"` + ExpectedStatus []string `json:"expectedStatus"` + FollowRedirects bool `json:"followRedirects"` + Headers *[]DtoHTTPHeaderInput `json:"headers,omitempty"` + + // Keyword Keyword is looked for in the first 256 KiB of the response body. + Keyword *string `json:"keyword,omitempty"` + KeywordCaseSensitive *bool `json:"keywordCaseSensitive,omitempty"` + KeywordMode *DtoHTTPSettingsInputKeywordMode `json:"keywordMode,omitempty"` + MaxRedirects int `json:"maxRedirects"` + Method DtoHTTPSettingsInputMethod `json:"method"` + RequestBody *string `json:"requestBody,omitempty"` + RequestBodyContentType *string `json:"requestBodyContentType,omitempty"` + SlowThresholdMs *int `json:"slowThresholdMs,omitempty"` + TimeoutMs int `json:"timeoutMs"` + Url string `json:"url"` + VerifyTls bool `json:"verifyTls"` +} + +// DtoHTTPSettingsInputKeywordMode defines model for DtoHTTPSettingsInput.KeywordMode. +type DtoHTTPSettingsInputKeywordMode string + +// DtoHTTPSettingsInputMethod defines model for DtoHTTPSettingsInput.Method. +type DtoHTTPSettingsInputMethod string + +// DtoHistoryBeat defines model for dto.HistoryBeat. +type DtoHistoryBeat struct { + CheckedAt string `json:"checkedAt"` + Condition string `json:"condition"` + ResponseTimeMs int `json:"responseTimeMs"` + ResultId int `json:"resultId"` + Severity DtoHistoryBeatSeverity `json:"severity"` + StatusCode *int `json:"statusCode,omitempty"` +} + +// DtoHistoryBeatSeverity defines model for DtoHistoryBeat.Severity. +type DtoHistoryBeatSeverity string + +// DtoIncident defines model for dto.Incident. +type DtoIncident struct { + AcknowledgedAt *string `json:"acknowledgedAt,omitempty"` + AcknowledgedBy *openapi_types.UUID `json:"acknowledgedBy,omitempty"` + + // Aspect Aspect is what the incident is about. + Aspect DtoIncidentAspect `json:"aspect"` + + // Condition Condition is what the latest check that changed the incident found; + // summary is its message, facts its facts. + Condition string `json:"condition"` + + // DurationSeconds DurationSeconds is how long it lasted (or has lasted so far). + DurationSeconds int `json:"durationSeconds"` + Facts DtoConditionFacts `json:"facts"` + Id openapi_types.UUID `json:"id"` + MonitorId openapi_types.UUID `json:"monitorId"` + MonitorName string `json:"monitorName"` + MonitorTarget string `json:"monitorTarget"` + MonitorType DtoIncidentMonitorType `json:"monitorType"` + + // MonitorVariant MonitorVariant names what the monitor does, as on monitor rows + // (keyword for an HTTP monitor with a keyword). + MonitorVariant DtoIncidentMonitorVariant `json:"monitorVariant"` + OpenedAt string `json:"openedAt"` + PeakSeverity DtoIncidentPeakSeverity `json:"peakSeverity"` + ResolvedAt *string `json:"resolvedAt,omitempty"` + + // Severity Severity is the current one; peakSeverity the worst it reached (a + // de-escalated incident stays open at warning). + Severity DtoIncidentSeverity `json:"severity"` + Status DtoIncidentStatus `json:"status"` + Summary string `json:"summary"` + + // Title Title names the problem in the monitor type's words (an expiry's + // days counted now, or when it ended). + Title string `json:"title"` +} + +// DtoIncidentAspect Aspect is what the incident is about. +type DtoIncidentAspect string + +// DtoIncidentMonitorType defines model for DtoIncident.MonitorType. +type DtoIncidentMonitorType string + +// DtoIncidentMonitorVariant MonitorVariant names what the monitor does, as on monitor rows +// (keyword for an HTTP monitor with a keyword). +type DtoIncidentMonitorVariant string + +// DtoIncidentPeakSeverity defines model for DtoIncident.PeakSeverity. +type DtoIncidentPeakSeverity string + +// DtoIncidentSeverity Severity is the current one; peakSeverity the worst it reached (a +// de-escalated incident stays open at warning). +type DtoIncidentSeverity string + +// DtoIncidentStatus defines model for DtoIncident.Status. +type DtoIncidentStatus string + +// DtoIncidentDelivery defines model for dto.IncidentDelivery. +type DtoIncidentDelivery struct { + // AlertId AlertID is the alert this delivery sends: an alert goes to every + // channel of its route, one delivery each. + AlertId openapi_types.UUID `json:"alertId"` + Attempts int `json:"attempts"` + ChannelId *openapi_types.UUID `json:"channelId,omitempty"` + ChannelKind *string `json:"channelKind,omitempty"` + ChannelName *string `json:"channelName,omitempty"` + Event DtoIncidentDeliveryEvent `json:"event"` + LastError *string `json:"lastError,omitempty"` + + // NextAttemptAt NextAttemptAt is when a pending delivery is tried again. + NextAttemptAt *string `json:"nextAttemptAt,omitempty"` + + // QueuedAt QueuedAt is when the alert was queued: the time of the timeline + // entry that sent it (opened, escalated, threshold, reminder). + QueuedAt string `json:"queuedAt"` + SentAt *string `json:"sentAt,omitempty"` + Status DtoIncidentDeliveryStatus `json:"status"` +} + +// DtoIncidentDeliveryEvent defines model for DtoIncidentDelivery.Event. +type DtoIncidentDeliveryEvent string + +// DtoIncidentDeliveryStatus defines model for DtoIncidentDelivery.Status. +type DtoIncidentDeliveryStatus string + +// DtoIncidentDetail defines model for dto.IncidentDetail. +type DtoIncidentDetail struct { + AcknowledgedAt *string `json:"acknowledgedAt,omitempty"` + AcknowledgedBy *openapi_types.UUID `json:"acknowledgedBy,omitempty"` + + // AcknowledgedByName AcknowledgedByName names who acknowledged it (their name, else + // email); absent when nobody did or Norcube Auth couldn't say. + AcknowledgedByName *string `json:"acknowledgedByName,omitempty"` + Alerts []DtoIncidentDelivery `json:"alerts"` + + // Aspect Aspect is what the incident is about. + Aspect DtoIncidentDetailAspect `json:"aspect"` + + // Condition Condition is what the latest check that changed the incident found; + // summary is its message, facts its facts. + Condition string `json:"condition"` + + // DurationSeconds DurationSeconds is how long it lasted (or has lasted so far). + DurationSeconds int `json:"durationSeconds"` + Facts DtoConditionFacts `json:"facts"` + Id openapi_types.UUID `json:"id"` + MonitorId openapi_types.UUID `json:"monitorId"` + MonitorName string `json:"monitorName"` + MonitorTarget string `json:"monitorTarget"` + MonitorType DtoIncidentDetailMonitorType `json:"monitorType"` + + // MonitorVariant MonitorVariant names what the monitor does, as on monitor rows + // (keyword for an HTTP monitor with a keyword). + MonitorVariant DtoIncidentDetailMonitorVariant `json:"monitorVariant"` + OpenedAt string `json:"openedAt"` + PeakSeverity DtoIncidentDetailPeakSeverity `json:"peakSeverity"` + ResolvedAt *string `json:"resolvedAt,omitempty"` + + // Severity Severity is the current one; peakSeverity the worst it reached (a + // de-escalated incident stays open at warning). + Severity DtoIncidentDetailSeverity `json:"severity"` + Status DtoIncidentDetailStatus `json:"status"` + Summary string `json:"summary"` + Timeline []DtoIncidentEvent `json:"timeline"` + + // Title Title names the problem in the monitor type's words (an expiry's + // days counted now, or when it ended). + Title string `json:"title"` +} + +// DtoIncidentDetailAspect Aspect is what the incident is about. +type DtoIncidentDetailAspect string + +// DtoIncidentDetailMonitorType defines model for DtoIncidentDetail.MonitorType. +type DtoIncidentDetailMonitorType string + +// DtoIncidentDetailMonitorVariant MonitorVariant names what the monitor does, as on monitor rows +// (keyword for an HTTP monitor with a keyword). +type DtoIncidentDetailMonitorVariant string + +// DtoIncidentDetailPeakSeverity defines model for DtoIncidentDetail.PeakSeverity. +type DtoIncidentDetailPeakSeverity string + +// DtoIncidentDetailSeverity Severity is the current one; peakSeverity the worst it reached (a +// de-escalated incident stays open at warning). +type DtoIncidentDetailSeverity string + +// DtoIncidentDetailStatus defines model for DtoIncidentDetail.Status. +type DtoIncidentDetailStatus string + +// DtoIncidentEvent defines model for dto.IncidentEvent. +type DtoIncidentEvent struct { + At string `json:"at"` + Detail *map[string]interface{} `json:"detail,omitempty"` + Type DtoIncidentEventType `json:"type"` +} + +// DtoIncidentEventType defines model for DtoIncidentEvent.Type. +type DtoIncidentEventType string + +// DtoIncidentOpenCounts defines model for dto.IncidentOpenCounts. +type DtoIncidentOpenCounts struct { + Critical int `json:"critical"` + Total int `json:"total"` + Unacknowledged int `json:"unacknowledged"` + Warning int `json:"warning"` +} + +// DtoIncidentSummary defines model for dto.IncidentSummary. +type DtoIncidentSummary struct { + // MttrLast30dSeconds MttrLast30dSeconds is the mean time to resolve of those incidents; + // absent when none was resolved. + MttrLast30dSeconds *int `json:"mttrLast30dSeconds,omitempty"` + Open DtoIncidentOpenCounts `json:"open"` + + // ResolvedLast30d ResolvedLast30d counts incidents resolved in the last 30 days, the + // ones mttrLast30dSeconds averages. + ResolvedLast30d int `json:"resolvedLast30d"` + + // ResolvedLast7d ResolvedLast7d counts incidents resolved in the last 7 days. + ResolvedLast7d int `json:"resolvedLast7d"` +} + +// DtoLastCheck defines model for dto.LastCheck. +type DtoLastCheck struct { + At string `json:"at"` + Condition string `json:"condition"` + Severity DtoLastCheckSeverity `json:"severity"` + TotalMs *int `json:"totalMs,omitempty"` +} + +// DtoLastCheckSeverity defines model for DtoLastCheck.Severity. +type DtoLastCheckSeverity string + +// DtoMonitor defines model for dto.Monitor. +type DtoMonitor struct { + // Aspects Aspects are the monitor's watched aspects (an HTTP monitor's + // certificate and domain watches that are on), on list rows too; [] + // without watches. + Aspects []DtoMonitorAspect `json:"aspects"` + + // Condition Condition explains status; absent while pending. + Condition *DtoMonitorCondition `json:"condition,omitempty"` + CreatedAt string `json:"createdAt"` + CreatedBy openapi_types.UUID `json:"createdBy"` + Description string `json:"description"` + Domain *DtoDomainSettings `json:"domain,omitempty"` + + // History History is set on list rows with include=history: the newest + // results (at most 60), newest first; [] for a monitor never checked. + History *[]DtoHistoryBeat `json:"history,omitempty"` + Http *DtoHTTPSettings `json:"http,omitempty"` + Id openapi_types.UUID `json:"id"` + IntervalSeconds int `json:"intervalSeconds"` + + // Last24h Last24h is set on list rows of monitors that track uptime (HTTP): + // the last 24 full hours plus the current one. SSL and domain monitors + // show days left (condition.facts) instead. + Last24h *DtoWindowSummary `json:"last24h,omitempty"` + LastCheck *DtoLastCheck `json:"lastCheck,omitempty"` + Name string `json:"name"` + NextCheckAt *string `json:"nextCheckAt,omitempty"` + + // OverallStatus OverallStatus is the worst of status and the statuses of the + // monitor's watched aspects (critical, warning, pending, ok), paused + // while disabled. The list status filter and sort use it. + OverallStatus DtoMonitorOverallStatus `json:"overallStatus"` + + // ParentResource ParentResource is set when the monitor belongs to a resource of + // another Norcube service ("domainradar:saved_domain:example.com"). It + // can't be deleted here, and its domain can't change. + ParentResource *string `json:"parentResource,omitempty"` + + // Regions Regions are where the monitor is checked from, on list rows too. + // Today every monitor is checked from the one region the service runs + // in; with probes in more regions (planned) a monitor may list + // several. Each result says which region checked it (region). + Regions []DtoCheckRegion `json:"regions"` + Ssl *DtoSSLSettings `json:"ssl,omitempty"` + + // Status Status is the primary aspect's: the severity of the last conclusive + // check, pending before one, paused while disabled. An inconclusive + // check (a failed registry lookup) never changes it. + Status DtoMonitorStatus `json:"status"` + StatusSince string `json:"statusSince"` + Target string `json:"target"` + Type DtoMonitorType `json:"type"` + UpdatedAt string `json:"updatedAt"` + + // Variant Variant is what the monitor does in one word, on list rows too + // (which carry no settings): keyword for an HTTP monitor that looks for + // a keyword in the body, otherwise the type. + Variant DtoMonitorVariant `json:"variant"` +} + +// DtoMonitorOverallStatus OverallStatus is the worst of status and the statuses of the +// monitor's watched aspects (critical, warning, pending, ok), paused +// while disabled. The list status filter and sort use it. +type DtoMonitorOverallStatus string + +// DtoMonitorStatus Status is the primary aspect's: the severity of the last conclusive +// check, pending before one, paused while disabled. An inconclusive +// check (a failed registry lookup) never changes it. +type DtoMonitorStatus string + +// DtoMonitorType defines model for DtoMonitor.Type. +type DtoMonitorType string + +// DtoMonitorVariant Variant is what the monitor does in one word, on list rows too +// (which carry no settings): keyword for an HTTP monitor that looks for +// a keyword in the body, otherwise the type. +type DtoMonitorVariant string + +// DtoMonitorAlertRoute defines model for dto.MonitorAlertRoute. +type DtoMonitorAlertRoute struct { + ChannelId openapi_types.UUID `json:"channelId"` + Events []DtoMonitorAlertRouteEvents `json:"events"` +} + +// DtoMonitorAlertRouteEvents defines model for DtoMonitorAlertRoute.Events. +type DtoMonitorAlertRouteEvents string + +// DtoMonitorAlerts defines model for dto.MonitorAlerts. +type DtoMonitorAlerts struct { + // ApplicableEvents ApplicableEvents are the events monitors of this type can send + // (offer only these in a routing form). + ApplicableEvents []DtoMonitorAlertsApplicableEvents `json:"applicableEvents"` + ConfirmFailures int `json:"confirmFailures"` + ConfirmSuccesses int `json:"confirmSuccesses"` + ReminderMinutes int `json:"reminderMinutes"` + Routes []DtoMonitorAlertRoute `json:"routes"` + UseDefaults bool `json:"useDefaults"` +} + +// DtoMonitorAlertsApplicableEvents defines model for DtoMonitorAlerts.ApplicableEvents. +type DtoMonitorAlertsApplicableEvents string + +// DtoMonitorAlertsUpdate defines model for dto.MonitorAlertsUpdate. +type DtoMonitorAlertsUpdate struct { + ConfirmFailures *int `json:"confirmFailures,omitempty"` + ConfirmSuccesses *int `json:"confirmSuccesses,omitempty"` + ReminderMinutes *int `json:"reminderMinutes,omitempty"` + Routes *[]DtoMonitorAlertRoute `json:"routes,omitempty"` + UseDefaults *bool `json:"useDefaults,omitempty"` +} + +// DtoMonitorAspect defines model for dto.MonitorAspect. +type DtoMonitorAspect struct { + // AlertedThresholds AlertedThresholds are the expiry thresholds already alerted for the + // current expiry, oldest first; [] before the first (or once renewed). + AlertedThresholds []DtoThresholdAlert `json:"alertedThresholds"` + Aspect DtoMonitorAspectAspect `json:"aspect"` + + // CheckedAt CheckedAt is the last observation, conclusive or not; absent before + // the first. + CheckedAt *string `json:"checkedAt,omitempty"` + + // Condition Condition explains status ("ok", "cert_expiring", "domain_expired", + // ...); absent while pending. + Condition *string `json:"condition,omitempty"` + + // DaysRemaining DaysRemaining is counted when read from expiresAt, negative once + // expired. + DaysRemaining *int `json:"daysRemaining,omitempty"` + ExpiresAt *string `json:"expiresAt,omitempty"` + Message *string `json:"message,omitempty"` + Status DtoMonitorAspectStatus `json:"status"` + + // Subject Subject is what the aspect is about: the URL's host for the + // certificate, its registrable domain for the domain. + Subject string `json:"subject"` + ThresholdsDays []int `json:"thresholdsDays"` +} + +// DtoMonitorAspectAspect defines model for DtoMonitorAspect.Aspect. +type DtoMonitorAspectAspect string + +// DtoMonitorAspectStatus defines model for DtoMonitorAspect.Status. +type DtoMonitorAspectStatus string + +// DtoMonitorBulkItem defines model for dto.MonitorBulkItem. +type DtoMonitorBulkItem struct { + Code *string `json:"code,omitempty"` + Detail *string `json:"detail,omitempty"` + MonitorId openapi_types.UUID `json:"monitorId"` + Ok bool `json:"ok"` +} + +// DtoMonitorBulkRequest defines model for dto.MonitorBulkRequest. +type DtoMonitorBulkRequest struct { + Action DtoMonitorBulkRequestAction `json:"action"` + MonitorIds []string `json:"monitorIds"` +} + +// DtoMonitorBulkRequestAction defines model for DtoMonitorBulkRequest.Action. +type DtoMonitorBulkRequestAction string + +// DtoMonitorBulkResult defines model for dto.MonitorBulkResult. +type DtoMonitorBulkResult struct { + Action DtoMonitorBulkResultAction `json:"action"` + Failed int `json:"failed"` + Items []DtoMonitorBulkItem `json:"items"` + Succeeded int `json:"succeeded"` +} + +// DtoMonitorBulkResultAction defines model for DtoMonitorBulkResult.Action. +type DtoMonitorBulkResultAction string + +// DtoMonitorCertificate defines model for dto.MonitorCertificate. +type DtoMonitorCertificate struct { + // AlertWindowStart AlertWindowStart is when the largest threshold is crossed (notAfter + // minus it): shade from here to notAfter. + AlertWindowStart *string `json:"alertWindowStart,omitempty"` + Certificate DtoCertificate `json:"certificate"` + CheckedAt string `json:"checkedAt"` + Condition string `json:"condition"` + + // DaysRemaining DaysRemaining counts from now (certificate.daysRemaining from the + // check). + DaysRemaining int `json:"daysRemaining"` + ErrorMessage *string `json:"errorMessage,omitempty"` + NextThresholdAt *string `json:"nextThresholdAt,omitempty"` + + // NextThresholdDays NextThresholdDays / NextThresholdAt: the next threshold to cross + // and when; absent once past the smallest. + NextThresholdDays *int `json:"nextThresholdDays,omitempty"` + ResultId int `json:"resultId"` + Severity DtoMonitorCertificateSeverity `json:"severity"` + + // ThresholdsDays ThresholdsDays are the SSL monitor's expiry thresholds, largest + // first; empty for an HTTP monitor (no expiry alerts). + ThresholdsDays []int `json:"thresholdsDays"` +} + +// DtoMonitorCertificateSeverity defines model for DtoMonitorCertificate.Severity. +type DtoMonitorCertificateSeverity string + +// DtoMonitorCondition defines model for dto.MonitorCondition. +type DtoMonitorCondition struct { + // AlertedThresholds AlertedThresholds are the expiry thresholds already alerted for the + // current expiry (SSL and domain monitors), oldest first; [] otherwise. + // An HTTP monitor's watched certificate and domain have theirs on + // aspects. + AlertedThresholds []DtoThresholdAlert `json:"alertedThresholds"` + + // Code Code is the condition ("ok", "slow_response", "cert_expiring", ...), + // worded per monitor type by the dashboard. + Code string `json:"code"` + + // ConclusiveAt ConclusiveAt is when a check last confirmed it; older than + // lastCheck.at when the newest checks couldn't tell. + ConclusiveAt *string `json:"conclusiveAt,omitempty"` + Facts DtoConditionFacts `json:"facts"` + Message *string `json:"message,omitempty"` + + // Since Since is when the status began (statusSince). + Since string `json:"since"` +} + +// DtoMonitorCreate defines model for dto.MonitorCreate. +type DtoMonitorCreate struct { + Description *string `json:"description,omitempty"` + Domain *DtoDomainSettingsInput `json:"domain,omitempty"` + Http *DtoHTTPSettingsInput `json:"http,omitempty"` + + // IntervalSeconds The org's plan can require more than the 30-second floor (60 s by + // default), and domain monitors run at most hourly (3600); the error + // message names the minimum. + IntervalSeconds int `json:"intervalSeconds"` + Name string `json:"name"` + Ssl *DtoSSLSettingsInput `json:"ssl,omitempty"` + Type DtoMonitorCreateType `json:"type"` +} + +// DtoMonitorCreateType defines model for DtoMonitorCreate.Type. +type DtoMonitorCreateType string + +// DtoMonitorEvent defines model for dto.MonitorEvent. +type DtoMonitorEvent struct { + Aspect DtoMonitorEventAspect `json:"aspect"` + At string `json:"at"` + + // CheckResultId CheckResultID is the check that saw it. + CheckResultId int `json:"checkResultId"` + Id int `json:"id"` + + // Renewal Renewal is set on certificate_renewed. + Renewal *DtoCertificateRenewal `json:"renewal,omitempty"` + + // Type Type: certificate_renewed, a check saw a certificate other than the + // newest one so far, expiring later (SSL monitors and HTTP monitors + // that watch their certificate; an older certificate, say from a node + // behind on renewals, is not one). + Type DtoMonitorEventType `json:"type"` +} + +// DtoMonitorEventAspect defines model for DtoMonitorEvent.Aspect. +type DtoMonitorEventAspect string + +// DtoMonitorEventType Type: certificate_renewed, a check saw a certificate other than the +// newest one so far, expiring later (SSL monitors and HTTP monitors +// that watch their certificate; an older certificate, say from a node +// behind on renewals, is not one). +type DtoMonitorEventType string + +// DtoMonitorStats defines model for dto.MonitorStats. +type DtoMonitorStats struct { + AvgMs *int `json:"avgMs,omitempty"` + Checks int `json:"checks"` + Critical int `json:"critical"` + From string `json:"from"` + Granularity DtoMonitorStatsGranularity `json:"granularity"` + Inconclusive int `json:"inconclusive"` + MaxMs *int `json:"maxMs,omitempty"` + Ok int `json:"ok"` + Series []DtoStatsBucket `json:"series"` + To string `json:"to"` + + // UptimePercent UptimePercent is (ok + warning) / (ok + warning + critical); absent + // without conclusive checks and for SSL and domain monitors. + UptimePercent *float32 `json:"uptimePercent,omitempty"` + Warning int `json:"warning"` +} + +// DtoMonitorStatsGranularity defines model for DtoMonitorStats.Granularity. +type DtoMonitorStatsGranularity string + +// DtoMonitorUpdate defines model for dto.MonitorUpdate. +type DtoMonitorUpdate struct { + Description *string `json:"description,omitempty"` + Domain *DtoDomainSettingsInput `json:"domain,omitempty"` + Http *DtoHTTPSettingsInput `json:"http,omitempty"` + IntervalSeconds *int `json:"intervalSeconds,omitempty"` + Name *string `json:"name,omitempty"` + Ssl *DtoSSLSettingsInput `json:"ssl,omitempty"` +} + +// DtoRenewedCertificate defines model for dto.RenewedCertificate. +type DtoRenewedCertificate struct { + FingerprintSha256 *string `json:"fingerprintSha256,omitempty"` + Issuer string `json:"issuer"` + NotAfter string `json:"notAfter"` + NotBefore string `json:"notBefore"` + SerialNumber string `json:"serialNumber"` + Subject string `json:"subject"` +} + +// DtoSSLSettings defines model for dto.SSLSettings. +type DtoSSLSettings struct { + ExpiryThresholdsDays []int `json:"expiryThresholdsDays"` + Host string `json:"host"` + Port int `json:"port"` + ServerName *string `json:"serverName,omitempty"` +} + +// DtoSSLSettingsInput defines model for dto.SSLSettingsInput. +type DtoSSLSettingsInput struct { + ExpiryThresholdsDays []int `json:"expiryThresholdsDays"` + Host string `json:"host"` + Port int `json:"port"` + ServerName *string `json:"serverName,omitempty"` +} + +// DtoStatsBucket defines model for dto.StatsBucket. +type DtoStatsBucket struct { + AvgMs int `json:"avgMs"` + Checks int `json:"checks"` + Critical int `json:"critical"` + Inconclusive int `json:"inconclusive"` + MaxMs int `json:"maxMs"` + Ok int `json:"ok"` + P50Ms int `json:"p50Ms"` + P95Ms int `json:"p95Ms"` + Region string `json:"region"` + Start string `json:"start"` + Warning int `json:"warning"` +} + +// DtoStatusChange defines model for dto.StatusChange. +type DtoStatusChange struct { + ChangedAt string `json:"changedAt"` + + // CheckResultId CheckResultID is the result that made the change (raw results are + // kept about 30 days, changes a year). + CheckResultId int `json:"checkResultId"` + + // Condition Condition is what the check that made the change found. + Condition string `json:"condition"` + + // DurationSeconds DurationSeconds is how long the status lasted (until now for the + // newest change). + DurationSeconds int `json:"durationSeconds"` + + // EndedAt EndedAt is when the next change happened; absent for the newest + // change (the current status, unless the monitor is paused). + EndedAt *string `json:"endedAt,omitempty"` + + // Events Events are what else happened while this status lasted (from + // changedAt to endedAt), newest first: certificate renewals. [] when + // nothing did. + Events []DtoMonitorEvent `json:"events"` + From DtoStatusChangeFrom `json:"from"` + Id int `json:"id"` + Message *string `json:"message,omitempty"` + StatusCode *int `json:"statusCode,omitempty"` + To DtoStatusChangeTo `json:"to"` +} + +// DtoStatusChangeFrom defines model for DtoStatusChange.From. +type DtoStatusChangeFrom string + +// DtoStatusChangeTo defines model for DtoStatusChange.To. +type DtoStatusChangeTo string + +// DtoThresholdAlert defines model for dto.ThresholdAlert. +type DtoThresholdAlert struct { + AlertedAt string `json:"alertedAt"` + Days int `json:"days"` +} + +// DtoWindowSummary defines model for dto.WindowSummary. +type DtoWindowSummary struct { + AvgMs *int `json:"avgMs,omitempty"` + Checks int `json:"checks"` + Critical int `json:"critical"` + From string `json:"from"` + Inconclusive int `json:"inconclusive"` + Ok int `json:"ok"` + + // P50Ms P50Ms and P95Ms approximate the window's median and 95th percentile + // response time (the checks-weighted mean of the hourly percentiles). + P50Ms *int `json:"p50Ms,omitempty"` + P95Ms *int `json:"p95Ms,omitempty"` + + // UptimePercent UptimePercent is (ok + warning) / (ok + warning + critical): a + // warning still answered, an inconclusive check counts neither way. + // WarningPercent is the warnings' share of the conclusive checks. + UptimePercent *float32 `json:"uptimePercent,omitempty"` + Warning int `json:"warning"` + WarningPercent *float32 `json:"warningPercent,omitempty"` +} + +// ResponseAPIResponsePaginationCursors defines model for response.APIResponsePaginationCursors. +type ResponseAPIResponsePaginationCursors struct { + Next *string `json:"next,omitempty"` + Prev *string `json:"prev,omitempty"` +} + +// ResponseAPIResponsePaginationMeta defines model for response.APIResponsePaginationMeta. +type ResponseAPIResponsePaginationMeta struct { + Timestamp *string `json:"timestamp,omitempty"` +} + +// ResponseAPIResponseWithPagination defines model for response.APIResponseWithPagination. +type ResponseAPIResponseWithPagination struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List interface{} `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` +} + +// ResponseProblem defines model for response.Problem. +type ResponseProblem struct { + Code ConstantsErrorCode `json:"code"` + + // Data Data holds stable facts about the error ("limit"), the same ones gRPC + // sends as ErrorInfo metadata. + Data *map[string]string `json:"data,omitempty"` + + // Detail Detail is an English sentence for people. + Detail string `json:"detail"` + + // Errors Errors lists the field problems of a VALIDATION_FAILED problem. + Errors *[]ValidationViolation `json:"errors,omitempty"` + + // Instance Instance identifies this occurrence: the request id the server + // generated, also sent as X-Request-ID and logged as request_id. + Instance string `json:"instance"` + + // Reason Reason is a finer stable cause within Code, when there is one. + Reason *ConstantsErrorReason `json:"reason,omitempty"` + Status int `json:"status"` + Timestamp string `json:"timestamp"` + Title string `json:"title"` + + // Type Type identifies the problem type (one per code); it may be + // dereferenced for documentation. + Type string `json:"type"` +} + +// ValidationParams defines model for validation.Params. +type ValidationParams struct { + // Allowed Allowed: oneOf. + Allowed *[]string `json:"allowed,omitempty"` + + // Expected Expected: type, mismatch. + Expected *string `json:"expected,omitempty"` + + // Field Field is the pointer of the other field: min and max compared with a + // field, exclusive, dependsOn. + Field *string `json:"field,omitempty"` + + // Max Max: range, max, maxLength, maxItems. + Max *int `json:"max,omitempty"` + + // Min Min: range, min. + Min *int `json:"min,omitempty"` + + // Unit Unit: maxLength. + Unit *ValidationUnit `json:"unit,omitempty"` + + // Value Value: unsupported. + Value *string `json:"value,omitempty"` +} + +// ValidationRule defines model for validation.Rule. +type ValidationRule string + +// ValidationUnit defines model for validation.Unit. +type ValidationUnit string + +// ValidationViolation defines model for validation.Violation. +type ValidationViolation struct { + Detail string `json:"detail"` + Params *ValidationParams `json:"params,omitempty"` + Pointer string `json:"pointer"` + Rule ValidationRule `json:"rule"` +} + +// ListAlertChannelsParams defines parameters for ListAlertChannels. +type ListAlertChannelsParams struct { + Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"` + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + +// ListAlertChannelDeliveriesParams defines parameters for ListAlertChannelDeliveries. +type ListAlertChannelDeliveriesParams struct { + Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"` + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + Status *ListAlertChannelDeliveriesParamsStatus `form:"status,omitempty" json:"status,omitempty"` +} + +// ListAlertChannelDeliveriesParamsStatus defines parameters for ListAlertChannelDeliveries. +type ListAlertChannelDeliveriesParamsStatus string + +// ListIncidentsParams defines parameters for ListIncidents. +type ListIncidentsParams struct { + // Acknowledged Acknowledged: true for incidents someone acknowledged, false for + // the others. + Acknowledged *ListIncidentsParamsAcknowledged `form:"acknowledged,omitempty" json:"acknowledged,omitempty"` + + // Aspect Aspect is what the incident is about. + Aspect *ListIncidentsParamsAspect `form:"aspect,omitempty" json:"aspect,omitempty"` + Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"` + + // From From and To bound when the incident started: from inclusive, to + // exclusive (RFC 3339). + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + MonitorId *openapi_types.UUID `form:"monitorId,omitempty" json:"monitorId,omitempty"` + + // Q Q is part of the monitor's name or target, any case. + Q *string `form:"q,omitempty" json:"q,omitempty"` + + // Severity Severity matches an open incident's current severity and a resolved + // one's peak severity (how bad it got). + Severity *ListIncidentsParamsSeverity `form:"severity,omitempty" json:"severity,omitempty"` + Status *ListIncidentsParamsStatus `form:"status,omitempty" json:"status,omitempty"` + To *time.Time `form:"to,omitempty" json:"to,omitempty"` +} + +// ListIncidentsParamsAcknowledged defines parameters for ListIncidents. +type ListIncidentsParamsAcknowledged string + +// ListIncidentsParamsAspect defines parameters for ListIncidents. +type ListIncidentsParamsAspect string + +// ListIncidentsParamsSeverity defines parameters for ListIncidents. +type ListIncidentsParamsSeverity string + +// ListIncidentsParamsStatus defines parameters for ListIncidents. +type ListIncidentsParamsStatus string + +// ListMonitorsParams defines parameters for ListMonitors. +type ListMonitorsParams struct { + Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"` + + // Include Include is a comma-separated list of optional row parts: history + // adds each row's last 60 check results. + Include *ListMonitorsParamsInclude `form:"include,omitempty" json:"include,omitempty"` + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + Q *string `form:"q,omitempty" json:"q,omitempty"` + + // Sort Sort: status (default, by overall status: critical, warning, + // pending, ok, paused, then name), name (A to Z), lastChecked (most recent first), uptime + // (lowest over last24h first; no data, and SSL and domain monitors, + // last), created (newest first). + // A cursor only continues the sort it came from. + Sort *ListMonitorsParamsSort `form:"sort,omitempty" json:"sort,omitempty"` + + // Status Status matches the overall status (the worst of the monitor's status + // and its watched aspects'). + Status *ListMonitorsParamsStatus `form:"status,omitempty" json:"status,omitempty"` + Type *ListMonitorsParamsType `form:"type,omitempty" json:"type,omitempty"` +} + +// ListMonitorsParamsInclude defines parameters for ListMonitors. +type ListMonitorsParamsInclude string + +// ListMonitorsParamsSort defines parameters for ListMonitors. +type ListMonitorsParamsSort string + +// ListMonitorsParamsStatus defines parameters for ListMonitors. +type ListMonitorsParamsStatus string + +// ListMonitorsParamsType defines parameters for ListMonitors. +type ListMonitorsParamsType string + +// GetMonitorAvailabilityParams defines parameters for GetMonitorAvailability. +type GetMonitorAvailabilityParams struct { + // Days Days is how many UTC days, ending today, the bar covers (default 90). + Days *int `form:"days,omitempty" json:"days,omitempty"` +} + +// ListMonitorResultsParams defines parameters for ListMonitorResults. +type ListMonitorResultsParams struct { + Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"` + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + To *time.Time `form:"to,omitempty" json:"to,omitempty"` +} + +// GetMonitorStatsParams defines parameters for GetMonitorStats. +type GetMonitorStatsParams struct { + Range GetMonitorStatsParamsRange `form:"range" json:"range"` +} + +// GetMonitorStatsParamsRange defines parameters for GetMonitorStats. +type GetMonitorStatsParamsRange string + +// ListMonitorStatusChangesParams defines parameters for ListMonitorStatusChanges. +type ListMonitorStatusChangesParams struct { + Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"` + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + +// CreateAlertChannelJSONRequestBody defines body for CreateAlertChannel for application/json ContentType. +type CreateAlertChannelJSONRequestBody = DtoAlertChannelCreate + +// UpdateAlertChannelJSONRequestBody defines body for UpdateAlertChannel for application/json ContentType. +type UpdateAlertChannelJSONRequestBody = DtoAlertChannelUpdate + +// ConfirmAlertChannelVerificationJSONRequestBody defines body for ConfirmAlertChannelVerification for application/json ContentType. +type ConfirmAlertChannelVerificationJSONRequestBody = DtoAlertChannelVerifyConfirm + +// CreateMonitorJSONRequestBody defines body for CreateMonitor for application/json ContentType. +type CreateMonitorJSONRequestBody = DtoMonitorCreate + +// ApplyMonitorBulkActionJSONRequestBody defines body for ApplyMonitorBulkAction for application/json ContentType. +type ApplyMonitorBulkActionJSONRequestBody = DtoMonitorBulkRequest + +// UpdateMonitorJSONRequestBody defines body for UpdateMonitor for application/json ContentType. +type UpdateMonitorJSONRequestBody = DtoMonitorUpdate + +// SetMonitorAlertsJSONRequestBody defines body for SetMonitorAlerts for application/json ContentType. +type SetMonitorAlertsJSONRequestBody = DtoMonitorAlertsUpdate + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // ListAlertChannels request + ListAlertChannels(ctx context.Context, params *ListAlertChannelsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateAlertChannelWithBody request with any body + CreateAlertChannelWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateAlertChannel(ctx context.Context, body CreateAlertChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteAlertChannel request + DeleteAlertChannel(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetAlertChannel request + GetAlertChannel(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateAlertChannelWithBody request with any body + UpdateAlertChannelWithBody(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateAlertChannel(ctx context.Context, id openapi_types.UUID, body UpdateAlertChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListAlertChannelDeliveries request + ListAlertChannelDeliveries(ctx context.Context, id openapi_types.UUID, params *ListAlertChannelDeliveriesParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // TestAlertChannel request + TestAlertChannel(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SendAlertChannelVerification request + SendAlertChannelVerification(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ConfirmAlertChannelVerificationWithBody request with any body + ConfirmAlertChannelVerificationWithBody(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ConfirmAlertChannelVerification(ctx context.Context, id openapi_types.UUID, body ConfirmAlertChannelVerificationJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListIncidents request + ListIncidents(ctx context.Context, params *ListIncidentsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetIncidentSummary request + GetIncidentSummary(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetIncident request + GetIncident(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // AcknowledgeIncident request + AcknowledgeIncident(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListMonitors request + ListMonitors(ctx context.Context, params *ListMonitorsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateMonitorWithBody request with any body + CreateMonitorWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateMonitor(ctx context.Context, body CreateMonitorJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ApplyMonitorBulkActionWithBody request with any body + ApplyMonitorBulkActionWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ApplyMonitorBulkAction(ctx context.Context, body ApplyMonitorBulkActionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteMonitor request + DeleteMonitor(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetMonitor request + GetMonitor(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateMonitorWithBody request with any body + UpdateMonitorWithBody(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateMonitor(ctx context.Context, id openapi_types.UUID, body UpdateMonitorJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetMonitorAlerts request + GetMonitorAlerts(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SetMonitorAlertsWithBody request with any body + SetMonitorAlertsWithBody(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + SetMonitorAlerts(ctx context.Context, id openapi_types.UUID, body SetMonitorAlertsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetMonitorAvailability request + GetMonitorAvailability(ctx context.Context, id openapi_types.UUID, params *GetMonitorAvailabilityParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetMonitorCertificate request + GetMonitorCertificate(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RunMonitorCheck request + RunMonitorCheck(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PauseMonitor request + PauseMonitor(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListMonitorResults request + ListMonitorResults(ctx context.Context, id openapi_types.UUID, params *ListMonitorResultsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ResumeMonitor request + ResumeMonitor(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetMonitorStats request + GetMonitorStats(ctx context.Context, id openapi_types.UUID, params *GetMonitorStatsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListMonitorStatusChanges request + ListMonitorStatusChanges(ctx context.Context, id openapi_types.UUID, params *ListMonitorStatusChangesParams, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) ListAlertChannels(ctx context.Context, params *ListAlertChannelsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListAlertChannelsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateAlertChannelWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateAlertChannelRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateAlertChannel(ctx context.Context, body CreateAlertChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateAlertChannelRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteAlertChannel(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteAlertChannelRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetAlertChannel(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetAlertChannelRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateAlertChannelWithBody(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateAlertChannelRequestWithBody(c.Server, id, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateAlertChannel(ctx context.Context, id openapi_types.UUID, body UpdateAlertChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateAlertChannelRequest(c.Server, id, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListAlertChannelDeliveries(ctx context.Context, id openapi_types.UUID, params *ListAlertChannelDeliveriesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListAlertChannelDeliveriesRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) TestAlertChannel(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewTestAlertChannelRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) SendAlertChannelVerification(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSendAlertChannelVerificationRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ConfirmAlertChannelVerificationWithBody(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewConfirmAlertChannelVerificationRequestWithBody(c.Server, id, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ConfirmAlertChannelVerification(ctx context.Context, id openapi_types.UUID, body ConfirmAlertChannelVerificationJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewConfirmAlertChannelVerificationRequest(c.Server, id, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListIncidents(ctx context.Context, params *ListIncidentsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListIncidentsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetIncidentSummary(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetIncidentSummaryRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetIncident(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetIncidentRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AcknowledgeIncident(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAcknowledgeIncidentRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListMonitors(ctx context.Context, params *ListMonitorsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListMonitorsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateMonitorWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateMonitorRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateMonitor(ctx context.Context, body CreateMonitorJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateMonitorRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ApplyMonitorBulkActionWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewApplyMonitorBulkActionRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ApplyMonitorBulkAction(ctx context.Context, body ApplyMonitorBulkActionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewApplyMonitorBulkActionRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteMonitor(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteMonitorRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetMonitor(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetMonitorRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateMonitorWithBody(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateMonitorRequestWithBody(c.Server, id, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateMonitor(ctx context.Context, id openapi_types.UUID, body UpdateMonitorJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateMonitorRequest(c.Server, id, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetMonitorAlerts(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetMonitorAlertsRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) SetMonitorAlertsWithBody(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSetMonitorAlertsRequestWithBody(c.Server, id, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) SetMonitorAlerts(ctx context.Context, id openapi_types.UUID, body SetMonitorAlertsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSetMonitorAlertsRequest(c.Server, id, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetMonitorAvailability(ctx context.Context, id openapi_types.UUID, params *GetMonitorAvailabilityParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetMonitorAvailabilityRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetMonitorCertificate(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetMonitorCertificateRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RunMonitorCheck(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRunMonitorCheckRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PauseMonitor(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPauseMonitorRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListMonitorResults(ctx context.Context, id openapi_types.UUID, params *ListMonitorResultsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListMonitorResultsRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ResumeMonitor(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewResumeMonitorRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetMonitorStats(ctx context.Context, id openapi_types.UUID, params *GetMonitorStatsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetMonitorStatsRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListMonitorStatusChanges(ctx context.Context, id openapi_types.UUID, params *ListMonitorStatusChangesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListMonitorStatusChangesRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewListAlertChannelsRequest generates requests for ListAlertChannels +func NewListAlertChannelsRequest(server string, params *ListAlertChannelsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/alert-channels") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Cursor != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "cursor", *params.Cursor, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateAlertChannelRequest calls the generic CreateAlertChannel builder with application/json body +func NewCreateAlertChannelRequest(server string, body CreateAlertChannelJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateAlertChannelRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateAlertChannelRequestWithBody generates requests for CreateAlertChannel with any type of body +func NewCreateAlertChannelRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/alert-channels") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteAlertChannelRequest generates requests for DeleteAlertChannel +func NewDeleteAlertChannelRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/alert-channels/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetAlertChannelRequest generates requests for GetAlertChannel +func NewGetAlertChannelRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/alert-channels/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateAlertChannelRequest calls the generic UpdateAlertChannel builder with application/json body +func NewUpdateAlertChannelRequest(server string, id openapi_types.UUID, body UpdateAlertChannelJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateAlertChannelRequestWithBody(server, id, "application/json", bodyReader) +} + +// NewUpdateAlertChannelRequestWithBody generates requests for UpdateAlertChannel with any type of body +func NewUpdateAlertChannelRequestWithBody(server string, id openapi_types.UUID, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/alert-channels/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPatch, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListAlertChannelDeliveriesRequest generates requests for ListAlertChannelDeliveries +func NewListAlertChannelDeliveriesRequest(server string, id openapi_types.UUID, params *ListAlertChannelDeliveriesParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/alert-channels/%s/deliveries", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Cursor != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "cursor", *params.Cursor, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Status != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "status", *params.Status, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewTestAlertChannelRequest generates requests for TestAlertChannel +func NewTestAlertChannelRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/alert-channels/%s/test", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewSendAlertChannelVerificationRequest generates requests for SendAlertChannelVerification +func NewSendAlertChannelVerificationRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/alert-channels/%s/verify", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewConfirmAlertChannelVerificationRequest calls the generic ConfirmAlertChannelVerification builder with application/json body +func NewConfirmAlertChannelVerificationRequest(server string, id openapi_types.UUID, body ConfirmAlertChannelVerificationJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewConfirmAlertChannelVerificationRequestWithBody(server, id, "application/json", bodyReader) +} + +// NewConfirmAlertChannelVerificationRequestWithBody generates requests for ConfirmAlertChannelVerification with any type of body +func NewConfirmAlertChannelVerificationRequestWithBody(server string, id openapi_types.UUID, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/alert-channels/%s/verify/confirm", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListIncidentsRequest generates requests for ListIncidents +func NewListIncidentsRequest(server string, params *ListIncidentsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/incidents") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Acknowledged != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "acknowledged", *params.Acknowledged, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Aspect != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "aspect", *params.Aspect, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Cursor != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "cursor", *params.Cursor, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.MonitorId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "monitorId", *params.MonitorId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "uuid"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Q != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "q", *params.Q, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Severity != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "severity", *params.Severity, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Status != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "status", *params.Status, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetIncidentSummaryRequest generates requests for GetIncidentSummary +func NewGetIncidentSummaryRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/incidents/summary") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetIncidentRequest generates requests for GetIncident +func NewGetIncidentRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/incidents/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewAcknowledgeIncidentRequest generates requests for AcknowledgeIncident +func NewAcknowledgeIncidentRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/incidents/%s/acknowledge", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListMonitorsRequest generates requests for ListMonitors +func NewListMonitorsRequest(server string, params *ListMonitorsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Cursor != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "cursor", *params.Cursor, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Include != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "include", *params.Include, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Q != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "q", *params.Q, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Sort != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "sort", *params.Sort, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Status != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "status", *params.Status, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Type != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "type", *params.Type, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateMonitorRequest calls the generic CreateMonitor builder with application/json body +func NewCreateMonitorRequest(server string, body CreateMonitorJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateMonitorRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateMonitorRequestWithBody generates requests for CreateMonitor with any type of body +func NewCreateMonitorRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewApplyMonitorBulkActionRequest calls the generic ApplyMonitorBulkAction builder with application/json body +func NewApplyMonitorBulkActionRequest(server string, body ApplyMonitorBulkActionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewApplyMonitorBulkActionRequestWithBody(server, "application/json", bodyReader) +} + +// NewApplyMonitorBulkActionRequestWithBody generates requests for ApplyMonitorBulkAction with any type of body +func NewApplyMonitorBulkActionRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/bulk") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteMonitorRequest generates requests for DeleteMonitor +func NewDeleteMonitorRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetMonitorRequest generates requests for GetMonitor +func NewGetMonitorRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateMonitorRequest calls the generic UpdateMonitor builder with application/json body +func NewUpdateMonitorRequest(server string, id openapi_types.UUID, body UpdateMonitorJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateMonitorRequestWithBody(server, id, "application/json", bodyReader) +} + +// NewUpdateMonitorRequestWithBody generates requests for UpdateMonitor with any type of body +func NewUpdateMonitorRequestWithBody(server string, id openapi_types.UUID, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPatch, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetMonitorAlertsRequest generates requests for GetMonitorAlerts +func NewGetMonitorAlertsRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/alerts", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewSetMonitorAlertsRequest calls the generic SetMonitorAlerts builder with application/json body +func NewSetMonitorAlertsRequest(server string, id openapi_types.UUID, body SetMonitorAlertsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewSetMonitorAlertsRequestWithBody(server, id, "application/json", bodyReader) +} + +// NewSetMonitorAlertsRequestWithBody generates requests for SetMonitorAlerts with any type of body +func NewSetMonitorAlertsRequestWithBody(server string, id openapi_types.UUID, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/alerts", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetMonitorAvailabilityRequest generates requests for GetMonitorAvailability +func NewGetMonitorAvailabilityRequest(server string, id openapi_types.UUID, params *GetMonitorAvailabilityParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/availability", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Days != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "days", *params.Days, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetMonitorCertificateRequest generates requests for GetMonitorCertificate +func NewGetMonitorCertificateRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/certificate", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRunMonitorCheckRequest generates requests for RunMonitorCheck +func NewRunMonitorCheckRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/check", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewPauseMonitorRequest generates requests for PauseMonitor +func NewPauseMonitorRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/pause", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListMonitorResultsRequest generates requests for ListMonitorResults +func NewListMonitorResultsRequest(server string, id openapi_types.UUID, params *ListMonitorResultsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/results", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Cursor != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "cursor", *params.Cursor, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewResumeMonitorRequest generates requests for ResumeMonitor +func NewResumeMonitorRequest(server string, id openapi_types.UUID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/resume", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetMonitorStatsRequest generates requests for GetMonitorStats +func NewGetMonitorStatsRequest(server string, id openapi_types.UUID, params *GetMonitorStatsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/stats", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "range", params.Range, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListMonitorStatusChangesRequest generates requests for ListMonitorStatusChanges +func NewListMonitorStatusChangesRequest(server string, id openapi_types.UUID, params *ListMonitorStatusChangesParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: "uuid"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/monitors/%s/status-changes", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Cursor != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "cursor", *params.Cursor, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // ListAlertChannelsWithResponse request + ListAlertChannelsWithResponse(ctx context.Context, params *ListAlertChannelsParams, reqEditors ...RequestEditorFn) (*ListAlertChannelsResponse, error) + + // CreateAlertChannelWithBodyWithResponse request with any body + CreateAlertChannelWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateAlertChannelResponse, error) + + CreateAlertChannelWithResponse(ctx context.Context, body CreateAlertChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateAlertChannelResponse, error) + + // DeleteAlertChannelWithResponse request + DeleteAlertChannelWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*DeleteAlertChannelResponse, error) + + // GetAlertChannelWithResponse request + GetAlertChannelWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetAlertChannelResponse, error) + + // UpdateAlertChannelWithBodyWithResponse request with any body + UpdateAlertChannelWithBodyWithResponse(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateAlertChannelResponse, error) + + UpdateAlertChannelWithResponse(ctx context.Context, id openapi_types.UUID, body UpdateAlertChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateAlertChannelResponse, error) + + // ListAlertChannelDeliveriesWithResponse request + ListAlertChannelDeliveriesWithResponse(ctx context.Context, id openapi_types.UUID, params *ListAlertChannelDeliveriesParams, reqEditors ...RequestEditorFn) (*ListAlertChannelDeliveriesResponse, error) + + // TestAlertChannelWithResponse request + TestAlertChannelWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*TestAlertChannelResponse, error) + + // SendAlertChannelVerificationWithResponse request + SendAlertChannelVerificationWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*SendAlertChannelVerificationResponse, error) + + // ConfirmAlertChannelVerificationWithBodyWithResponse request with any body + ConfirmAlertChannelVerificationWithBodyWithResponse(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ConfirmAlertChannelVerificationResponse, error) + + ConfirmAlertChannelVerificationWithResponse(ctx context.Context, id openapi_types.UUID, body ConfirmAlertChannelVerificationJSONRequestBody, reqEditors ...RequestEditorFn) (*ConfirmAlertChannelVerificationResponse, error) + + // ListIncidentsWithResponse request + ListIncidentsWithResponse(ctx context.Context, params *ListIncidentsParams, reqEditors ...RequestEditorFn) (*ListIncidentsResponse, error) + + // GetIncidentSummaryWithResponse request + GetIncidentSummaryWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetIncidentSummaryResponse, error) + + // GetIncidentWithResponse request + GetIncidentWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetIncidentResponse, error) + + // AcknowledgeIncidentWithResponse request + AcknowledgeIncidentWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*AcknowledgeIncidentResponse, error) + + // ListMonitorsWithResponse request + ListMonitorsWithResponse(ctx context.Context, params *ListMonitorsParams, reqEditors ...RequestEditorFn) (*ListMonitorsResponse, error) + + // CreateMonitorWithBodyWithResponse request with any body + CreateMonitorWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateMonitorResponse, error) + + CreateMonitorWithResponse(ctx context.Context, body CreateMonitorJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateMonitorResponse, error) + + // ApplyMonitorBulkActionWithBodyWithResponse request with any body + ApplyMonitorBulkActionWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ApplyMonitorBulkActionResponse, error) + + ApplyMonitorBulkActionWithResponse(ctx context.Context, body ApplyMonitorBulkActionJSONRequestBody, reqEditors ...RequestEditorFn) (*ApplyMonitorBulkActionResponse, error) + + // DeleteMonitorWithResponse request + DeleteMonitorWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*DeleteMonitorResponse, error) + + // GetMonitorWithResponse request + GetMonitorWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetMonitorResponse, error) + + // UpdateMonitorWithBodyWithResponse request with any body + UpdateMonitorWithBodyWithResponse(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateMonitorResponse, error) + + UpdateMonitorWithResponse(ctx context.Context, id openapi_types.UUID, body UpdateMonitorJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateMonitorResponse, error) + + // GetMonitorAlertsWithResponse request + GetMonitorAlertsWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetMonitorAlertsResponse, error) + + // SetMonitorAlertsWithBodyWithResponse request with any body + SetMonitorAlertsWithBodyWithResponse(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SetMonitorAlertsResponse, error) + + SetMonitorAlertsWithResponse(ctx context.Context, id openapi_types.UUID, body SetMonitorAlertsJSONRequestBody, reqEditors ...RequestEditorFn) (*SetMonitorAlertsResponse, error) + + // GetMonitorAvailabilityWithResponse request + GetMonitorAvailabilityWithResponse(ctx context.Context, id openapi_types.UUID, params *GetMonitorAvailabilityParams, reqEditors ...RequestEditorFn) (*GetMonitorAvailabilityResponse, error) + + // GetMonitorCertificateWithResponse request + GetMonitorCertificateWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetMonitorCertificateResponse, error) + + // RunMonitorCheckWithResponse request + RunMonitorCheckWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*RunMonitorCheckResponse, error) + + // PauseMonitorWithResponse request + PauseMonitorWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*PauseMonitorResponse, error) + + // ListMonitorResultsWithResponse request + ListMonitorResultsWithResponse(ctx context.Context, id openapi_types.UUID, params *ListMonitorResultsParams, reqEditors ...RequestEditorFn) (*ListMonitorResultsResponse, error) + + // ResumeMonitorWithResponse request + ResumeMonitorWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*ResumeMonitorResponse, error) + + // GetMonitorStatsWithResponse request + GetMonitorStatsWithResponse(ctx context.Context, id openapi_types.UUID, params *GetMonitorStatsParams, reqEditors ...RequestEditorFn) (*GetMonitorStatsResponse, error) + + // ListMonitorStatusChangesWithResponse request + ListMonitorStatusChangesWithResponse(ctx context.Context, id openapi_types.UUID, params *ListMonitorStatusChangesParams, reqEditors ...RequestEditorFn) (*ListMonitorStatusChangesResponse, error) +} + +type ListAlertChannelsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoAlertChannel `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r ListAlertChannelsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListAlertChannelsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListAlertChannelsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type CreateAlertChannelResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *DtoAlertChannelWithSecret + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r CreateAlertChannelResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateAlertChannelResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateAlertChannelResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type DeleteAlertChannelResponse struct { + Body []byte + HTTPResponse *http.Response + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r DeleteAlertChannelResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteAlertChannelResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r DeleteAlertChannelResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetAlertChannelResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoAlertChannel + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r GetAlertChannelResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetAlertChannelResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetAlertChannelResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type UpdateAlertChannelResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoAlertChannelWithSecret + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r UpdateAlertChannelResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateAlertChannelResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r UpdateAlertChannelResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ListAlertChannelDeliveriesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoChannelDelivery `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r ListAlertChannelDeliveriesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListAlertChannelDeliveriesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListAlertChannelDeliveriesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type TestAlertChannelResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoAlertChannelTestResult + JSON401 *ResponseProblem + JSON402 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem + JSON409 *ResponseProblem + JSON429 *ResponseProblem + JSON503 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r TestAlertChannelResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r TestAlertChannelResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r TestAlertChannelResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type SendAlertChannelVerificationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON401 *ResponseProblem + JSON402 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem + JSON409 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r SendAlertChannelVerificationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SendAlertChannelVerificationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SendAlertChannelVerificationResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ConfirmAlertChannelVerificationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoAlertChannel + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem + JSON409 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r ConfirmAlertChannelVerificationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ConfirmAlertChannelVerificationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ConfirmAlertChannelVerificationResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ListIncidentsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoIncident `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r ListIncidentsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListIncidentsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListIncidentsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetIncidentSummaryResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoIncidentSummary + JSON401 *ResponseProblem + JSON403 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r GetIncidentSummaryResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetIncidentSummaryResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetIncidentSummaryResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetIncidentResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoIncidentDetail + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r GetIncidentResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetIncidentResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetIncidentResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type AcknowledgeIncidentResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoIncidentDetail + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r AcknowledgeIncidentResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r AcknowledgeIncidentResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r AcknowledgeIncidentResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ListMonitorsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoMonitor `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r ListMonitorsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListMonitorsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListMonitorsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type CreateMonitorResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *DtoMonitor + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON402 *ResponseProblem + JSON403 *ResponseProblem + JSON503 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r CreateMonitorResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateMonitorResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateMonitorResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ApplyMonitorBulkActionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMonitorBulkResult + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON429 *ResponseProblem + JSON503 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r ApplyMonitorBulkActionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ApplyMonitorBulkActionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ApplyMonitorBulkActionResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type DeleteMonitorResponse struct { + Body []byte + HTTPResponse *http.Response + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem + JSON409 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r DeleteMonitorResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteMonitorResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r DeleteMonitorResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetMonitorResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMonitor + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r GetMonitorResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetMonitorResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetMonitorResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type UpdateMonitorResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMonitor + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem + JSON503 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r UpdateMonitorResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateMonitorResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r UpdateMonitorResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetMonitorAlertsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMonitorAlerts + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r GetMonitorAlertsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetMonitorAlertsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetMonitorAlertsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type SetMonitorAlertsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMonitorAlerts + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r SetMonitorAlertsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SetMonitorAlertsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SetMonitorAlertsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetMonitorAvailabilityResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoAvailability + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r GetMonitorAvailabilityResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetMonitorAvailabilityResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetMonitorAvailabilityResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetMonitorCertificateResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMonitorCertificate + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r GetMonitorCertificateResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetMonitorCertificateResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetMonitorCertificateResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type RunMonitorCheckResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoCheckResult + JSON401 *ResponseProblem + JSON402 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem + JSON429 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r RunMonitorCheckResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RunMonitorCheckResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r RunMonitorCheckResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type PauseMonitorResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMonitor + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r PauseMonitorResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PauseMonitorResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r PauseMonitorResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ListMonitorResultsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoCheckResult `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r ListMonitorResultsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListMonitorResultsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListMonitorResultsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ResumeMonitorResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMonitor + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r ResumeMonitorResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ResumeMonitorResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ResumeMonitorResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetMonitorStatsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMonitorStats + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r GetMonitorStatsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetMonitorStatsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetMonitorStatsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ListMonitorStatusChangesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoStatusChange `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + JSON400 *ResponseProblem + JSON401 *ResponseProblem + JSON403 *ResponseProblem + JSON404 *ResponseProblem +} + +// Status returns HTTPResponse.Status +func (r ListMonitorStatusChangesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListMonitorStatusChangesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListMonitorStatusChangesResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +// ListAlertChannelsWithResponse request returning *ListAlertChannelsResponse +func (c *ClientWithResponses) ListAlertChannelsWithResponse(ctx context.Context, params *ListAlertChannelsParams, reqEditors ...RequestEditorFn) (*ListAlertChannelsResponse, error) { + rsp, err := c.ListAlertChannels(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListAlertChannelsResponse(rsp) +} + +// CreateAlertChannelWithBodyWithResponse request with arbitrary body returning *CreateAlertChannelResponse +func (c *ClientWithResponses) CreateAlertChannelWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateAlertChannelResponse, error) { + rsp, err := c.CreateAlertChannelWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateAlertChannelResponse(rsp) +} + +func (c *ClientWithResponses) CreateAlertChannelWithResponse(ctx context.Context, body CreateAlertChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateAlertChannelResponse, error) { + rsp, err := c.CreateAlertChannel(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateAlertChannelResponse(rsp) +} + +// DeleteAlertChannelWithResponse request returning *DeleteAlertChannelResponse +func (c *ClientWithResponses) DeleteAlertChannelWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*DeleteAlertChannelResponse, error) { + rsp, err := c.DeleteAlertChannel(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteAlertChannelResponse(rsp) +} + +// GetAlertChannelWithResponse request returning *GetAlertChannelResponse +func (c *ClientWithResponses) GetAlertChannelWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetAlertChannelResponse, error) { + rsp, err := c.GetAlertChannel(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetAlertChannelResponse(rsp) +} + +// UpdateAlertChannelWithBodyWithResponse request with arbitrary body returning *UpdateAlertChannelResponse +func (c *ClientWithResponses) UpdateAlertChannelWithBodyWithResponse(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateAlertChannelResponse, error) { + rsp, err := c.UpdateAlertChannelWithBody(ctx, id, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateAlertChannelResponse(rsp) +} + +func (c *ClientWithResponses) UpdateAlertChannelWithResponse(ctx context.Context, id openapi_types.UUID, body UpdateAlertChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateAlertChannelResponse, error) { + rsp, err := c.UpdateAlertChannel(ctx, id, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateAlertChannelResponse(rsp) +} + +// ListAlertChannelDeliveriesWithResponse request returning *ListAlertChannelDeliveriesResponse +func (c *ClientWithResponses) ListAlertChannelDeliveriesWithResponse(ctx context.Context, id openapi_types.UUID, params *ListAlertChannelDeliveriesParams, reqEditors ...RequestEditorFn) (*ListAlertChannelDeliveriesResponse, error) { + rsp, err := c.ListAlertChannelDeliveries(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListAlertChannelDeliveriesResponse(rsp) +} + +// TestAlertChannelWithResponse request returning *TestAlertChannelResponse +func (c *ClientWithResponses) TestAlertChannelWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*TestAlertChannelResponse, error) { + rsp, err := c.TestAlertChannel(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseTestAlertChannelResponse(rsp) +} + +// SendAlertChannelVerificationWithResponse request returning *SendAlertChannelVerificationResponse +func (c *ClientWithResponses) SendAlertChannelVerificationWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*SendAlertChannelVerificationResponse, error) { + rsp, err := c.SendAlertChannelVerification(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseSendAlertChannelVerificationResponse(rsp) +} + +// ConfirmAlertChannelVerificationWithBodyWithResponse request with arbitrary body returning *ConfirmAlertChannelVerificationResponse +func (c *ClientWithResponses) ConfirmAlertChannelVerificationWithBodyWithResponse(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ConfirmAlertChannelVerificationResponse, error) { + rsp, err := c.ConfirmAlertChannelVerificationWithBody(ctx, id, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseConfirmAlertChannelVerificationResponse(rsp) +} + +func (c *ClientWithResponses) ConfirmAlertChannelVerificationWithResponse(ctx context.Context, id openapi_types.UUID, body ConfirmAlertChannelVerificationJSONRequestBody, reqEditors ...RequestEditorFn) (*ConfirmAlertChannelVerificationResponse, error) { + rsp, err := c.ConfirmAlertChannelVerification(ctx, id, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseConfirmAlertChannelVerificationResponse(rsp) +} + +// ListIncidentsWithResponse request returning *ListIncidentsResponse +func (c *ClientWithResponses) ListIncidentsWithResponse(ctx context.Context, params *ListIncidentsParams, reqEditors ...RequestEditorFn) (*ListIncidentsResponse, error) { + rsp, err := c.ListIncidents(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListIncidentsResponse(rsp) +} + +// GetIncidentSummaryWithResponse request returning *GetIncidentSummaryResponse +func (c *ClientWithResponses) GetIncidentSummaryWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetIncidentSummaryResponse, error) { + rsp, err := c.GetIncidentSummary(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetIncidentSummaryResponse(rsp) +} + +// GetIncidentWithResponse request returning *GetIncidentResponse +func (c *ClientWithResponses) GetIncidentWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetIncidentResponse, error) { + rsp, err := c.GetIncident(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetIncidentResponse(rsp) +} + +// AcknowledgeIncidentWithResponse request returning *AcknowledgeIncidentResponse +func (c *ClientWithResponses) AcknowledgeIncidentWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*AcknowledgeIncidentResponse, error) { + rsp, err := c.AcknowledgeIncident(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseAcknowledgeIncidentResponse(rsp) +} + +// ListMonitorsWithResponse request returning *ListMonitorsResponse +func (c *ClientWithResponses) ListMonitorsWithResponse(ctx context.Context, params *ListMonitorsParams, reqEditors ...RequestEditorFn) (*ListMonitorsResponse, error) { + rsp, err := c.ListMonitors(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListMonitorsResponse(rsp) +} + +// CreateMonitorWithBodyWithResponse request with arbitrary body returning *CreateMonitorResponse +func (c *ClientWithResponses) CreateMonitorWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateMonitorResponse, error) { + rsp, err := c.CreateMonitorWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateMonitorResponse(rsp) +} + +func (c *ClientWithResponses) CreateMonitorWithResponse(ctx context.Context, body CreateMonitorJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateMonitorResponse, error) { + rsp, err := c.CreateMonitor(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateMonitorResponse(rsp) +} + +// ApplyMonitorBulkActionWithBodyWithResponse request with arbitrary body returning *ApplyMonitorBulkActionResponse +func (c *ClientWithResponses) ApplyMonitorBulkActionWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ApplyMonitorBulkActionResponse, error) { + rsp, err := c.ApplyMonitorBulkActionWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseApplyMonitorBulkActionResponse(rsp) +} + +func (c *ClientWithResponses) ApplyMonitorBulkActionWithResponse(ctx context.Context, body ApplyMonitorBulkActionJSONRequestBody, reqEditors ...RequestEditorFn) (*ApplyMonitorBulkActionResponse, error) { + rsp, err := c.ApplyMonitorBulkAction(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseApplyMonitorBulkActionResponse(rsp) +} + +// DeleteMonitorWithResponse request returning *DeleteMonitorResponse +func (c *ClientWithResponses) DeleteMonitorWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*DeleteMonitorResponse, error) { + rsp, err := c.DeleteMonitor(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteMonitorResponse(rsp) +} + +// GetMonitorWithResponse request returning *GetMonitorResponse +func (c *ClientWithResponses) GetMonitorWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetMonitorResponse, error) { + rsp, err := c.GetMonitor(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetMonitorResponse(rsp) +} + +// UpdateMonitorWithBodyWithResponse request with arbitrary body returning *UpdateMonitorResponse +func (c *ClientWithResponses) UpdateMonitorWithBodyWithResponse(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateMonitorResponse, error) { + rsp, err := c.UpdateMonitorWithBody(ctx, id, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateMonitorResponse(rsp) +} + +func (c *ClientWithResponses) UpdateMonitorWithResponse(ctx context.Context, id openapi_types.UUID, body UpdateMonitorJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateMonitorResponse, error) { + rsp, err := c.UpdateMonitor(ctx, id, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateMonitorResponse(rsp) +} + +// GetMonitorAlertsWithResponse request returning *GetMonitorAlertsResponse +func (c *ClientWithResponses) GetMonitorAlertsWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetMonitorAlertsResponse, error) { + rsp, err := c.GetMonitorAlerts(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetMonitorAlertsResponse(rsp) +} + +// SetMonitorAlertsWithBodyWithResponse request with arbitrary body returning *SetMonitorAlertsResponse +func (c *ClientWithResponses) SetMonitorAlertsWithBodyWithResponse(ctx context.Context, id openapi_types.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SetMonitorAlertsResponse, error) { + rsp, err := c.SetMonitorAlertsWithBody(ctx, id, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSetMonitorAlertsResponse(rsp) +} + +func (c *ClientWithResponses) SetMonitorAlertsWithResponse(ctx context.Context, id openapi_types.UUID, body SetMonitorAlertsJSONRequestBody, reqEditors ...RequestEditorFn) (*SetMonitorAlertsResponse, error) { + rsp, err := c.SetMonitorAlerts(ctx, id, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSetMonitorAlertsResponse(rsp) +} + +// GetMonitorAvailabilityWithResponse request returning *GetMonitorAvailabilityResponse +func (c *ClientWithResponses) GetMonitorAvailabilityWithResponse(ctx context.Context, id openapi_types.UUID, params *GetMonitorAvailabilityParams, reqEditors ...RequestEditorFn) (*GetMonitorAvailabilityResponse, error) { + rsp, err := c.GetMonitorAvailability(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetMonitorAvailabilityResponse(rsp) +} + +// GetMonitorCertificateWithResponse request returning *GetMonitorCertificateResponse +func (c *ClientWithResponses) GetMonitorCertificateWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetMonitorCertificateResponse, error) { + rsp, err := c.GetMonitorCertificate(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetMonitorCertificateResponse(rsp) +} + +// RunMonitorCheckWithResponse request returning *RunMonitorCheckResponse +func (c *ClientWithResponses) RunMonitorCheckWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*RunMonitorCheckResponse, error) { + rsp, err := c.RunMonitorCheck(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseRunMonitorCheckResponse(rsp) +} + +// PauseMonitorWithResponse request returning *PauseMonitorResponse +func (c *ClientWithResponses) PauseMonitorWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*PauseMonitorResponse, error) { + rsp, err := c.PauseMonitor(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParsePauseMonitorResponse(rsp) +} + +// ListMonitorResultsWithResponse request returning *ListMonitorResultsResponse +func (c *ClientWithResponses) ListMonitorResultsWithResponse(ctx context.Context, id openapi_types.UUID, params *ListMonitorResultsParams, reqEditors ...RequestEditorFn) (*ListMonitorResultsResponse, error) { + rsp, err := c.ListMonitorResults(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListMonitorResultsResponse(rsp) +} + +// ResumeMonitorWithResponse request returning *ResumeMonitorResponse +func (c *ClientWithResponses) ResumeMonitorWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*ResumeMonitorResponse, error) { + rsp, err := c.ResumeMonitor(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseResumeMonitorResponse(rsp) +} + +// GetMonitorStatsWithResponse request returning *GetMonitorStatsResponse +func (c *ClientWithResponses) GetMonitorStatsWithResponse(ctx context.Context, id openapi_types.UUID, params *GetMonitorStatsParams, reqEditors ...RequestEditorFn) (*GetMonitorStatsResponse, error) { + rsp, err := c.GetMonitorStats(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetMonitorStatsResponse(rsp) +} + +// ListMonitorStatusChangesWithResponse request returning *ListMonitorStatusChangesResponse +func (c *ClientWithResponses) ListMonitorStatusChangesWithResponse(ctx context.Context, id openapi_types.UUID, params *ListMonitorStatusChangesParams, reqEditors ...RequestEditorFn) (*ListMonitorStatusChangesResponse, error) { + rsp, err := c.ListMonitorStatusChanges(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListMonitorStatusChangesResponse(rsp) +} + +// ParseListAlertChannelsResponse parses an HTTP response from a ListAlertChannelsWithResponse call +func ParseListAlertChannelsResponse(rsp *http.Response) (*ListAlertChannelsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListAlertChannelsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoAlertChannel `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + } + + return response, nil +} + +// ParseCreateAlertChannelResponse parses an HTTP response from a CreateAlertChannelWithResponse call +func ParseCreateAlertChannelResponse(rsp *http.Response) (*CreateAlertChannelResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateAlertChannelResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest DtoAlertChannelWithSecret + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + } + + return response, nil +} + +// ParseDeleteAlertChannelResponse parses an HTTP response from a DeleteAlertChannelWithResponse call +func ParseDeleteAlertChannelResponse(rsp *http.Response) (*DeleteAlertChannelResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteAlertChannelResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetAlertChannelResponse parses an HTTP response from a GetAlertChannelWithResponse call +func ParseGetAlertChannelResponse(rsp *http.Response) (*GetAlertChannelResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetAlertChannelResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoAlertChannel + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseUpdateAlertChannelResponse parses an HTTP response from a UpdateAlertChannelWithResponse call +func ParseUpdateAlertChannelResponse(rsp *http.Response) (*UpdateAlertChannelResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateAlertChannelResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoAlertChannelWithSecret + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseListAlertChannelDeliveriesResponse parses an HTTP response from a ListAlertChannelDeliveriesWithResponse call +func ParseListAlertChannelDeliveriesResponse(rsp *http.Response) (*ListAlertChannelDeliveriesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListAlertChannelDeliveriesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoChannelDelivery `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseTestAlertChannelResponse parses an HTTP response from a TestAlertChannelWithResponse call +func ParseTestAlertChannelResponse(rsp *http.Response) (*TestAlertChannelResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &TestAlertChannelResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoAlertChannelTestResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + return response, nil +} + +// ParseSendAlertChannelVerificationResponse parses an HTTP response from a SendAlertChannelVerificationWithResponse call +func ParseSendAlertChannelVerificationResponse(rsp *http.Response) (*SendAlertChannelVerificationResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SendAlertChannelVerificationResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + } + + return response, nil +} + +// ParseConfirmAlertChannelVerificationResponse parses an HTTP response from a ConfirmAlertChannelVerificationWithResponse call +func ParseConfirmAlertChannelVerificationResponse(rsp *http.Response) (*ConfirmAlertChannelVerificationResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ConfirmAlertChannelVerificationResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoAlertChannel + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + } + + return response, nil +} + +// ParseListIncidentsResponse parses an HTTP response from a ListIncidentsWithResponse call +func ParseListIncidentsResponse(rsp *http.Response) (*ListIncidentsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListIncidentsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoIncident `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + } + + return response, nil +} + +// ParseGetIncidentSummaryResponse parses an HTTP response from a GetIncidentSummaryWithResponse call +func ParseGetIncidentSummaryResponse(rsp *http.Response) (*GetIncidentSummaryResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetIncidentSummaryResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoIncidentSummary + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + } + + return response, nil +} + +// ParseGetIncidentResponse parses an HTTP response from a GetIncidentWithResponse call +func ParseGetIncidentResponse(rsp *http.Response) (*GetIncidentResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetIncidentResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoIncidentDetail + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseAcknowledgeIncidentResponse parses an HTTP response from a AcknowledgeIncidentWithResponse call +func ParseAcknowledgeIncidentResponse(rsp *http.Response) (*AcknowledgeIncidentResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &AcknowledgeIncidentResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoIncidentDetail + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseListMonitorsResponse parses an HTTP response from a ListMonitorsWithResponse call +func ParseListMonitorsResponse(rsp *http.Response) (*ListMonitorsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListMonitorsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoMonitor `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + } + + return response, nil +} + +// ParseCreateMonitorResponse parses an HTTP response from a CreateMonitorWithResponse call +func ParseCreateMonitorResponse(rsp *http.Response) (*CreateMonitorResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateMonitorResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest DtoMonitor + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + return response, nil +} + +// ParseApplyMonitorBulkActionResponse parses an HTTP response from a ApplyMonitorBulkActionWithResponse call +func ParseApplyMonitorBulkActionResponse(rsp *http.Response) (*ApplyMonitorBulkActionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ApplyMonitorBulkActionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMonitorBulkResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + return response, nil +} + +// ParseDeleteMonitorResponse parses an HTTP response from a DeleteMonitorWithResponse call +func ParseDeleteMonitorResponse(rsp *http.Response) (*DeleteMonitorResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteMonitorResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + } + + return response, nil +} + +// ParseGetMonitorResponse parses an HTTP response from a GetMonitorWithResponse call +func ParseGetMonitorResponse(rsp *http.Response) (*GetMonitorResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetMonitorResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMonitor + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseUpdateMonitorResponse parses an HTTP response from a UpdateMonitorWithResponse call +func ParseUpdateMonitorResponse(rsp *http.Response) (*UpdateMonitorResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateMonitorResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMonitor + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + return response, nil +} + +// ParseGetMonitorAlertsResponse parses an HTTP response from a GetMonitorAlertsWithResponse call +func ParseGetMonitorAlertsResponse(rsp *http.Response) (*GetMonitorAlertsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetMonitorAlertsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMonitorAlerts + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseSetMonitorAlertsResponse parses an HTTP response from a SetMonitorAlertsWithResponse call +func ParseSetMonitorAlertsResponse(rsp *http.Response) (*SetMonitorAlertsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SetMonitorAlertsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMonitorAlerts + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetMonitorAvailabilityResponse parses an HTTP response from a GetMonitorAvailabilityWithResponse call +func ParseGetMonitorAvailabilityResponse(rsp *http.Response) (*GetMonitorAvailabilityResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetMonitorAvailabilityResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoAvailability + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetMonitorCertificateResponse parses an HTTP response from a GetMonitorCertificateWithResponse call +func ParseGetMonitorCertificateResponse(rsp *http.Response) (*GetMonitorCertificateResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetMonitorCertificateResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMonitorCertificate + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseRunMonitorCheckResponse parses an HTTP response from a RunMonitorCheckWithResponse call +func ParseRunMonitorCheckResponse(rsp *http.Response) (*RunMonitorCheckResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &RunMonitorCheckResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoCheckResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 402: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON402 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + + } + + return response, nil +} + +// ParsePauseMonitorResponse parses an HTTP response from a PauseMonitorWithResponse call +func ParsePauseMonitorResponse(rsp *http.Response) (*PauseMonitorResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PauseMonitorResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMonitor + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseListMonitorResultsResponse parses an HTTP response from a ListMonitorResultsWithResponse call +func ParseListMonitorResultsResponse(rsp *http.Response) (*ListMonitorResultsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListMonitorResultsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoCheckResult `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseResumeMonitorResponse parses an HTTP response from a ResumeMonitorWithResponse call +func ParseResumeMonitorResponse(rsp *http.Response) (*ResumeMonitorResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ResumeMonitorResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMonitor + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetMonitorStatsResponse parses an HTTP response from a GetMonitorStatsWithResponse call +func ParseGetMonitorStatsResponse(rsp *http.Response) (*GetMonitorStatsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetMonitorStatsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMonitorStats + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseListMonitorStatusChangesResponse parses an HTTP response from a ListMonitorStatusChangesWithResponse call +func ParseListMonitorStatusChangesResponse(rsp *http.Response) (*ListMonitorStatusChangesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListMonitorStatusChangesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + Cursors ResponseAPIResponsePaginationCursors `json:"cursors"` + List []DtoStatusChange `json:"list"` + Meta ResponseAPIResponsePaginationMeta `json:"meta"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseProblem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} diff --git a/internal/auth/tokens.go b/internal/auth/tokens.go index 6d72768..8d58327 100644 --- a/internal/auth/tokens.go +++ b/internal/auth/tokens.go @@ -33,6 +33,7 @@ const ( AudienceDomainradar = "domainradar" AudiencePrompthub = "prompthub" AudienceCMS = "cms-api" + AudiencePulsecheck = "pulsecheck" ) // TokenSource returns a valid Bearer access token for a (audience, organization) diff --git a/internal/cli/authcmd.go b/internal/cli/authcmd.go index c8132ae..eaff0db 100644 --- a/internal/cli/authcmd.go +++ b/internal/cli/authcmd.go @@ -245,7 +245,7 @@ func checkSessions(ctx context.Context, flags *clictx.Flags, rows []authStatus) } // ciAudiences are the services a CI token can be exchanged for. -var ciAudiences = []string{auth.AudienceLangsync, auth.AudienceSnapDB, auth.AudienceDomainradar, auth.AudienceBilling, auth.AudienceCMS} +var ciAudiences = []string{auth.AudienceLangsync, auth.AudienceSnapDB, auth.AudienceDomainradar, auth.AudienceBilling, auth.AudienceCMS, auth.AudiencePulsecheck} // checkCIToken exchanges the CI token for every service it may reach, in // parallel, and fills s with the token's organization, name, expiry and @@ -334,6 +334,7 @@ var audiences = map[string]string{ "langsync": auth.AudienceLangsync, "domainradar": auth.AudienceDomainradar, "prompthub": auth.AudiencePrompthub, + "pulsecheck": auth.AudiencePulsecheck, } func audienceNames() []string { @@ -418,7 +419,7 @@ type tokenResult struct { // token, which only works in its own organization. func printCIAccessToken(cmd *cobra.Command, flags *clictx.Flags, ci *auth.CIExchanger, name, aud string) error { if aud == auth.AudienceAuth || aud == auth.AudiencePrompthub { - return clierr.Usage(fmt.Errorf("a CI token can't be exchanged for %s; pick one of langsync, backup, domainradar, billing", name)) + return clierr.Usage(fmt.Errorf("a CI token can't be exchanged for %s; pick one of langsync, backup, domainradar, billing, pulsecheck", name)) } g, err := ci.Grant(cmd.Context(), aud) if err != nil { diff --git a/internal/cli/commands_test.go b/internal/cli/commands_test.go index a3d3b29..b5708d9 100644 --- a/internal/cli/commands_test.go +++ b/internal/cli/commands_test.go @@ -29,7 +29,7 @@ func commandsEnv(t *testing.T) { p := f.Profile(config.DefaultProfileName) p.Environment = config.EnvCustom p.Endpoints = map[string]string{} - for _, key := range []string{config.ServiceAuth, config.ServiceSnapDB, config.ServiceLangsync, config.ServiceDomainradar, config.ServiceBilling} { + for _, key := range []string{config.ServiceAuth, config.ServiceSnapDB, config.ServiceLangsync, config.ServiceDomainradar, config.ServiceBilling, config.ServicePulsecheck} { p.Endpoints[key] = srv.URL } }) diff --git a/internal/cli/golden_test.go b/internal/cli/golden_test.go index 630ae26..cd794c2 100644 --- a/internal/cli/golden_test.go +++ b/internal/cli/golden_test.go @@ -143,7 +143,7 @@ func goldenEnv(t *testing.T) string { p.Environment = config.EnvCustom p.Endpoints = map[string]string{ config.ServiceAuth: srv.URL, config.ServiceSnapDB: srv.URL, config.ServiceLangsync: srv.URL, - config.ServiceDomainradar: srv.URL, config.ServiceBilling: srv.URL, + config.ServiceDomainradar: srv.URL, config.ServiceBilling: srv.URL, config.ServicePulsecheck: srv.URL, } p.User = config.User{ID: "user-1", Name: "Dev Eloper", Email: "dev@example.com"} p.SetActiveOrg(config.Organization{ID: homeOrgID, Slug: "home", Name: "Home"}) @@ -151,6 +151,7 @@ func goldenEnv(t *testing.T) string { t.Setenv("NORCUBE_LANGSYNC_URL", "") t.Setenv("NORCUBE_DOMAINRADAR_URL", "") t.Setenv("NORCUBE_BILLING_URL", "") + t.Setenv("NORCUBE_PULSECHECK_URL", "") if err := auth.SaveRefreshToken(config.DefaultProfileName, srv.URL, "refresh-0"); err != nil { t.Fatal(err) } diff --git a/internal/cli/pulsecheck/bulk.go b/internal/cli/pulsecheck/bulk.go new file mode 100644 index 0000000..1d178c4 --- /dev/null +++ b/internal/cli/pulsecheck/bulk.go @@ -0,0 +1,194 @@ +package pulsecheck + +import ( + "context" + "fmt" + "strings" + + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/output" +) + +// bulkMax is how many monitors one bulk request takes; longer lists are +// sent in batches. +const bulkMax = 100 + +func newMonitorBulkCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "bulk", + Short: "Pause, resume or delete many monitors at once", + Long: `Applies one action to many monitors: the ones you name (ids or exact +names, as arguments or one per line with --file), or every monitor the +list filters match (--type, --status, --search). Each monitor is handled as +its own request would be, so one refusal doesn't stop the others; the +result lists every monitor with ok or its problem code. The command exits +1 when any monitor failed.`, + } + for _, a := range []struct{ action, short, example string }{ + {"pause", "Pause many monitors", ` # Maintenance window: pause everything behind api.example.com + norcube pulsecheck monitors bulk pause --search api.example.com --yes`}, + {"resume", "Resume many monitors", ` norcube pulsecheck monitors bulk resume --status paused --search api.example.com --yes`}, + {"delete", "Delete many monitors and their history", ` norcube pulsecheck monitors bulk delete 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f "Old landing page" + norcube pulsecheck monitors bulk delete --file old-monitors.txt --yes`}, + } { + cmd.AddCommand(newBulkActionCmd(d, a.action, a.short, a.example)) + } + return cmd +} + +func newBulkActionCmd(d deps, action, short, example string) *cobra.Command { + var ( + yes bool + file string + typ, status, search string + ) + cmd := &cobra.Command{ + Use: action + " [...]", + Annotations: cmdutil.Writes(), + Short: short, + Example: example, + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + byFilter := typ != "" || status != "" || search != "" + if byFilter && (len(args) > 0 || file != "") { + return nil, clierr.Usage(fmt.Errorf("name monitors or select them with --type, --status and --search, not both")) + } + if typ != "" { + if err := oneOf("--type", typ, monitorTypes); err != nil { + return nil, err + } + } + if status != "" { + if err := oneOf("--status", status, monitorStatuses); err != nil { + return nil, err + } + } + var refs []string + if !byFilter { + var err error + refs, err = cmdutil.ReadItems(cmdutil.ItemSource{Args: args, File: file, Stdin: cmd.InOrStdin(), What: "monitors"}) + if err != nil { + return nil, err + } + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + ids, err := bulkTargets(cmd.Context(), c, refs, typ, status, search) + if err != nil { + return nil, err + } + if len(ids) == 0 { + return nil, &clierr.Error{Code: clierr.CodeNotFound, Message: "no monitor matches the filters"} + } + if ok, err := cmdutil.Confirm(fmt.Sprintf("%s %d monitor(s)?", capitalize(action), len(ids)), yes); err != nil || !ok { + return nil, cmdutil.Cancelled(cmd, err) + } + result := pulsecheck.DtoMonitorBulkResult{Action: pulsecheck.DtoMonitorBulkResultAction(action), Items: []pulsecheck.DtoMonitorBulkItem{}} + for start := 0; start < len(ids); start += bulkMax { + batch := ids[start:min(start+bulkMax, len(ids))] + res, err := c.API.ApplyMonitorBulkActionWithResponse(cmd.Context(), pulsecheck.DtoMonitorBulkRequest{ + Action: pulsecheck.DtoMonitorBulkRequestAction(action), MonitorIds: batch, + }) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + result.Items = append(result.Items, res.JSON200.Items...) + result.Succeeded += res.JSON200.Succeeded + result.Failed += res.JSON200.Failed + } + table := output.Table[pulsecheck.DtoMonitorBulkItem]{ + Headers: []string{"MONITOR", "RESULT", "DETAIL"}, + Style: output.Style{StatusColumn: 1}, + Rows: func(it pulsecheck.DtoMonitorBulkItem) []string { + r := "ok" + if !it.Ok { + r = cmdutil.DerefOr(it.Code, "failed") + } + return []string{it.MonitorId.String(), r, strOr(it.Detail)} + }, + Items: result.Items, + } + if result.Failed > 0 { + if err := cmdutil.Print(cmd, table); err != nil { + return nil, err + } + return nil, &clierr.Error{Code: clierr.CodeError, Details: result, + Message: fmt.Sprintf("%s: %d of %d monitors failed", action, result.Failed, len(ids))} + } + if cmdutil.Human(cmd) { + fmt.Fprintf(cmdutil.Stderr(cmd), "%sd %d monitor(s).\n", capitalize(strings.TrimSuffix(action, "e")), result.Succeeded) + } + return table, nil + }), + } + cmd.Flags().BoolVar(&yes, "yes", false, "Don't ask for confirmation") + cmd.Flags().StringVarP(&file, "file", "f", "", "Read monitors (ids or names) from this file, one per line (- for standard input)") + cmd.Flags().StringVar(&typ, "type", "", "Select every monitor of this type: http, ssl or domain") + cmd.Flags().StringVar(&status, "status", "", "Select every monitor with this overall status") + cmd.Flags().StringVar(&search, "search", "", "Select every monitor whose name or target contains this text") + cmdutil.FlagEnum(cmd, "type", monitorTypes...) + cmdutil.FlagEnum(cmd, "status", monitorStatuses...) + return cmd +} + +// bulkTargets resolves the named monitors, or lists the ones the filters +// match (every page), into ids without duplicates. +func bulkTargets(ctx context.Context, c *pcContext, refs []string, typ, status, search string) ([]string, error) { + seen := map[string]bool{} + var ids []string + add := func(id string) { + if !seen[id] { + seen[id] = true + ids = append(ids, id) + } + } + if refs != nil { + for _, r := range refs { + id, err := monitorRef(ctx, c, r) + if err != nil { + return nil, err + } + add(id.String()) + } + return ids, nil + } + limit := maxPageSize + p := pulsecheck.ListMonitorsParams{Limit: &limit} + if typ != "" { + t := pulsecheck.ListMonitorsParamsType(typ) + p.Type = &t + } + if status != "" { + s := pulsecheck.ListMonitorsParamsStatus(status) + p.Status = &s + } + if search != "" { + p.Q = &search + } + for len(ids) < maxItems { + res, err := c.API.ListMonitorsWithResponse(ctx, &p) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + for _, m := range res.JSON200.List { + add(m.Id.String()) + } + next := nextCursor(res.JSON200.Cursors) + if next == "" { + break + } + p.Cursor = &next + } + return ids, nil +} diff --git a/internal/cli/pulsecheck/channels.go b/internal/cli/pulsecheck/channels.go new file mode 100644 index 0000000..6d3e172 --- /dev/null +++ b/internal/cli/pulsecheck/channels.go @@ -0,0 +1,669 @@ +package pulsecheck + +import ( + "context" + "errors" + "fmt" + "net/http" + "regexp" + "strings" + + "github.com/charmbracelet/huh" + "github.com/google/uuid" + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/output" + "github.com/norcubeplatform/cli/internal/term" +) + +// channelKinds are the kinds a channel can be created with (voice-call +// channels made before calls were withdrawn can only be renamed or +// deleted). +var channelKinds = []string{"email", "webhook", "slack", "discord", "sms"} + +var deliveryStatuses = []string{"pending", "sent", "dead"} + +func newChannelsCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "channels", + Aliases: []string{"channel", "alert-channels"}, + Short: "Manage alert channels: email, webhooks, Slack, Discord and SMS", + Long: `Alert channels are where incidents alert. Default channels get the +alerts of every monitor that follows the organization's defaults; a +monitor's own routes ("monitors alerts set") name channels directly. + +Credentials stay secret: Slack and Discord URLs are read from a file or +standard input and shown only as a hint, and a webhook's signing secret is +written to a file you name, never printed. Email-address and SMS channels +get no alerts until their contact confirms a code ("channels verify"). +A CI token changes channels only with the pulsecheck.channels scope +(pulsecheck.write doesn't include it); any PulseCheck scope reads them.`, + } + cmd.AddCommand( + newChannelListCmd(d), newChannelGetCmd(d), newChannelCreateCmd(d), newChannelUpdateCmd(d), + newChannelDeleteCmd(d), newChannelTestCmd(d), newChannelVerifyCmd(d), newDeliveriesCmd(d), + ) + return cmd +} + +func newChannelListCmd(d deps) *cobra.Command { + var pf cmdutil.PageFlags + cmd := &cobra.Command{ + Use: "list", + Annotations: cmdutil.Reads(), + Short: "List alert channels", + Example: ` norcube pulsecheck channels list`, + Args: cobra.NoArgs, + RunE: cmdutil.Run(func(cmd *cobra.Command, _ []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + page, err := cmdutil.Paginate(cmd.Context(), pf, func(ctx context.Context, cursor string, size int) ([]pulsecheck.DtoAlertChannel, string, error) { + p := pulsecheck.ListAlertChannelsParams{Limit: &size} + if cursor != "" { + p.Cursor = &cursor + } + res, err := c.API.ListAlertChannelsWithResponse(ctx, &p) + if err != nil { + return nil, "", err + } + if res.JSON200 == nil { + return nil, "", apiError(res.HTTPResponse, res.Body) + } + return res.JSON200.List, nextCursor(res.JSON200.Cursors), nil + }) + if err != nil { + return nil, err + } + return nil, page.Print(cmd, channelTable(page.Items)) + }), + } + cmdutil.AddPageFlags(cmd, &pf, defaultPageSize, maxItems) + return cmd +} + +func newChannelGetCmd(d deps) *cobra.Command { + return &cobra.Command{ + Use: "get ", + Annotations: cmdutil.Reads(), + Short: "Show an alert channel", + Example: ` norcube pulsecheck channels get "On-call webhook"`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + ch, err := getChannel(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + return channelObject(ch), nil + }), + } +} + +func getChannel(ctx context.Context, c *pcContext, ref string) (pulsecheck.DtoAlertChannel, error) { + id, err := channelRef(ctx, c, ref) + if err != nil { + return pulsecheck.DtoAlertChannel{}, err + } + res, err := c.API.GetAlertChannelWithResponse(ctx, id) + if err != nil { + return pulsecheck.DtoAlertChannel{}, err + } + if res.JSON200 == nil { + return pulsecheck.DtoAlertChannel{}, apiError(res.HTTPResponse, res.Body) + } + return *res.JSON200, nil +} + +// channelFlags are the settings create and update share. +type channelFlags struct { + address, url, urlFile, phone string + signingSecretFile, secretOut string + members, isDefault bool +} + +func addChannelFlags(cmd *cobra.Command, f *channelFlags) { + fl := cmd.Flags() + fl.StringVar(&f.address, "address", "", "email: the address to alert (it gets a code to confirm)") + fl.BoolVar(&f.members, "members", false, "email: alert the organization's members instead of one address") + fl.StringVar(&f.url, "url", "", "webhook: the URL PulseCheck posts signed alerts to") + fl.StringVar(&f.urlFile, "url-file", "", "slack, discord: read the incoming-webhook URL (a credential) from this file (- for standard input)") + fl.StringVar(&f.phone, "phone", "", "sms: a mobile number in international format, e.g. +420601123456 (it gets a code to confirm)") + fl.StringVar(&f.signingSecretFile, "signing-secret-file", "", "webhook: use your own signing secret (whsec_…) read from this file (- for standard input)") + fl.StringVar(&f.secretOut, "secret-file", "", "webhook: write the generated signing secret to this new file (mode 0600); it is never printed") + fl.BoolVar(&f.isDefault, "default", false, "Make it a default channel: monitors that follow the organization's defaults alert here") + cmd.MarkFlagsMutuallyExclusive("address", "members") + cmd.MarkFlagsMutuallyExclusive("signing-secret-file", "secret-file") +} + +// settingsFor builds a kind's settings from the flags, refusing flags of +// other kinds and credentials in arguments. +func settingsFor(cmd *cobra.Command, kind string, f channelFlags) (*pulsecheck.DtoAlertChannelSettingsInput, error) { + set := cmd.Flags().Changed + allowed := map[string][]string{ + "email": {"address", "members"}, + "webhook": {"url", "signing-secret-file", "secret-file"}, + "slack": {"url-file"}, + "discord": {"url-file"}, + "sms": {"phone"}, + }[kind] + for _, n := range []string{"address", "members", "url", "url-file", "phone", "signing-secret-file", "secret-file"} { + if set(n) && !strings.Contains(" "+strings.Join(allowed, " ")+" ", " "+n+" ") { + if n == "url" && (kind == "slack" || kind == "discord") { + return nil, clierr.Usage(fmt.Errorf("a %s webhook URL is a credential: pass it with --url-file (- reads standard input), not as an argument", kind)) + } + return nil, clierr.Usage(fmt.Errorf("--%s doesn't apply to %s channels", n, kind)) + } + } + in := &pulsecheck.DtoAlertChannelSettingsInput{} + any := false + switch kind { + case "email": + if f.address != "" { + in.Address, any = &f.address, true + } + if f.members { + in.Members, any = &f.members, true + } + case "webhook": + if f.url != "" { + in.Url, any = &f.url, true + } + if f.signingSecretFile != "" { + s, err := cmdutil.ReadText(cmd.InOrStdin(), "", f.signingSecretFile, "the signing secret") + if err != nil { + return nil, err + } + s = strings.TrimSpace(s) + in.SigningSecret, any = &s, true + } + case "slack", "discord": + if f.urlFile != "" { + u, err := cmdutil.ReadText(cmd.InOrStdin(), "", f.urlFile, "the webhook URL") + if err != nil { + return nil, err + } + u = strings.TrimSpace(u) + in.Url, any = &u, true + } + case "sms": + if f.phone != "" { + in.Phone, any = &f.phone, true + } + } + if !any { + return nil, nil + } + return in, nil +} + +func newChannelCreateCmd(d deps) *cobra.Command { + var ( + f channelFlags + kind string + ) + cmd := &cobra.Command{ + Use: "create ", + Annotations: cmdutil.Writes(), + Short: "Create an alert channel", + Long: `Creates a channel of one kind: + + email --address (confirmed with a code sent there) or --members + webhook --url; signed with a secret PulseCheck generates (saved with + --secret-file, never printed) or yours (--signing-secret-file) + slack --url-file: the incoming-webhook URL, from a file or stdin + discord --url-file: the webhook URL, from a file or stdin + sms --phone (confirmed with a code texted there) + +Email-address and SMS channels get no alerts until verified: run +"channels verify " (on a terminal it asks for the code).`, + Example: ` norcube pulsecheck channels create "Ops" --kind email --address ops@example.com --default + norcube pulsecheck channels create "On-call webhook" --kind webhook --url https://example.com/hooks/pulsecheck --secret-file webhook-secret.txt + pbpaste | norcube pulsecheck channels create "#alerts" --kind slack --url-file - + norcube pulsecheck channels create "On-call phone" --kind sms --phone +420601123456`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + if kind == "" { + return nil, clierr.Usage(fmt.Errorf("--kind is required: one of %s", strings.Join(channelKinds, ", "))) + } + if err := oneOf("--kind", kind, channelKinds); err != nil { + return nil, err + } + if f.secretOut == "-" { + return nil, clierr.Usage(fmt.Errorf("--secret-file needs a file name: the signing secret is never printed")) + } + settings, err := settingsFor(cmd, kind, f) + if err != nil { + return nil, err + } + if settings == nil { + need := map[string]string{"email": "--address or --members", "webhook": "--url", "slack": "--url-file", "discord": "--url-file", "sms": "--phone"}[kind] + return nil, clierr.Usage(fmt.Errorf("%s channels need %s", kind, need)) + } + body := pulsecheck.DtoAlertChannelCreate{Kind: pulsecheck.DtoAlertChannelCreateKind(kind), Name: strings.TrimSpace(args[0]), Settings: *settings} + if cmd.Flags().Changed("default") { + body.IsDefault = &f.isDefault + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + res, err := c.API.CreateAlertChannelWithResponse(cmd.Context(), body) + if err != nil { + return nil, err + } + if res.JSON201 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + created := *res.JSON201 + if err := keepSecret(cmd, created, f.secretOut); err != nil { + return nil, err + } + ch := withoutSecret(created) + msg := fmt.Sprintf("Created %s channel %s (%s).", ch.Kind, ch.Name, ch.Id) + if !ch.Verified && (kind == "sms" || (kind == "email" && !f.members)) { + msg += " Confirm it with: norcube pulsecheck channels verify " + ch.Id.String() + } + return output.Done{Message: msg, Value: ch, Fields: []output.Field{{Value: ch.Id.String()}, {Value: ch.Name}}}, nil + }), + } + cmd.Flags().StringVar(&kind, "kind", "", "Channel kind: email, webhook, slack, discord or sms") + cmdutil.FlagEnum(cmd, "kind", channelKinds...) + addChannelFlags(cmd, &f) + return cmd +} + +// keepSecret writes a signing secret the API returned this once to the +// file named by --secret-file, or says on stderr that it was not kept. +// It never reaches stdout. +func keepSecret(cmd *cobra.Command, ch pulsecheck.DtoAlertChannelWithSecret, dest string) error { + secret := cmdutil.Deref(ch.SigningSecret) + if secret == "" { + return nil + } + if dest == "" { + fmt.Fprintf(cmdutil.Stderr(cmd), "The webhook's signing secret was not kept (pass --secret-file to save it). Get a new one with: norcube pulsecheck channels update %s --rotate-secret --secret-file \n", ch.Id) + return nil + } + if _, err := cmdutil.SaveStream(cmd, strings.NewReader(secret+"\n"), dest, 0o600); err != nil { + return fmt.Errorf("the channel was saved, but its signing secret could not be written to %s: %w (rotate it with --rotate-secret --secret-file)", dest, err) + } + fmt.Fprintf(cmdutil.Stderr(cmd), "Wrote the webhook's signing secret to %s.\n", dest) + return nil +} + +func newChannelUpdateCmd(d deps) *cobra.Command { + var ( + f channelFlags + name string + enable, disable bool + rotate bool + ) + cmd := &cobra.Command{ + Use: "update ", + Annotations: cmdutil.Writes(), + Short: "Rename, enable, disable or reconfigure an alert channel", + Long: `Changes only what you pass. New settings replace the kind's settings as a +whole (a Slack or Discord URL must be given again); a new address or phone +number needs verifying again. --rotate-secret gives a webhook a new +signing secret, written to --secret-file.`, + Example: ` norcube pulsecheck channels update "Ops" --default=false + norcube pulsecheck channels update "On-call webhook" --rotate-secret --secret-file new-secret.txt + norcube pulsecheck channels update "On-call phone" --phone +420601999888`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + if f.secretOut == "-" { + return nil, clierr.Usage(fmt.Errorf("--secret-file needs a file name: the signing secret is never printed")) + } + if rotate && f.signingSecretFile != "" { + return nil, clierr.Usage(fmt.Errorf("--rotate-secret and --signing-secret-file can't be combined")) + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + ch, err := getChannel(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + kind := string(ch.Kind) + if rotate && kind != "webhook" { + return nil, clierr.Usage(fmt.Errorf("--rotate-secret is for webhook channels")) + } + settings, err := settingsFor(cmd, kind, f) + if err != nil { + return nil, err + } + body := pulsecheck.DtoAlertChannelUpdate{Settings: settings} + changed := settings != nil + if cmd.Flags().Changed("name") { + n := strings.TrimSpace(name) + body.Name, changed = &n, true + } + if cmd.Flags().Changed("default") { + body.IsDefault, changed = &f.isDefault, true + } + if enable || disable { + v := enable + body.Enabled, changed = &v, true + } + if rotate { + body.RotateSecret, changed = &rotate, true + } + if !changed { + return nil, clierr.Usage(fmt.Errorf("nothing to change: pass --name, --default, --enable, --disable, --rotate-secret or new settings")) + } + res, err := c.API.UpdateAlertChannelWithResponse(cmd.Context(), ch.Id, body) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + if err := keepSecret(cmd, *res.JSON200, f.secretOut); err != nil { + return nil, err + } + u := withoutSecret(*res.JSON200) + return output.Done{ + Message: fmt.Sprintf("Updated channel %s (%s).", u.Name, u.Id), + Value: u, + Fields: []output.Field{{Value: u.Id.String()}, {Value: u.Name}}, + }, nil + }), + } + cmd.Flags().StringVar(&name, "name", "", "New name") + cmd.Flags().BoolVar(&enable, "enable", false, "Send alerts through the channel again") + cmd.Flags().BoolVar(&disable, "disable", false, "Stop sending alerts through the channel, keeping it") + cmd.Flags().BoolVar(&rotate, "rotate-secret", false, "webhook: generate a new signing secret (use with --secret-file)") + cmd.MarkFlagsMutuallyExclusive("enable", "disable") + addChannelFlags(cmd, &f) + return cmd +} + +func newChannelDeleteCmd(d deps) *cobra.Command { + var yes bool + cmd := &cobra.Command{ + Use: "delete ", + Annotations: cmdutil.Writes(), + Short: "Delete an alert channel", + Long: "Deletes the channel and removes it from every monitor's alert routes; alerts still queued for it are dropped.", + Example: ` norcube pulsecheck channels delete "Old webhook" + norcube pulsecheck channels delete 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f --yes`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := channelRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + if ok, err := cmdutil.Confirm(fmt.Sprintf("Delete alert channel %s? Monitors routed to it stop alerting there", args[0]), yes); err != nil || !ok { + return nil, cmdutil.Cancelled(cmd, err) + } + res, err := c.API.DeleteAlertChannelWithResponse(cmd.Context(), id) + if err != nil { + return nil, err + } + if res.StatusCode() != http.StatusNoContent { + return nil, apiError(res.HTTPResponse, res.Body) + } + return output.Done{ + Message: fmt.Sprintf("Deleted channel %s.", args[0]), + Value: deleted{ID: id.String(), Deleted: true}, + Fields: []output.Field{{Value: id.String()}}, + }, nil + }), + } + cmd.Flags().BoolVar(&yes, "yes", false, "Don't ask for confirmation") + return cmd +} + +func newChannelTestCmd(d deps) *cobra.Command { + var yes bool + cmd := &cobra.Command{ + Use: "test ", + Annotations: cmdutil.Writes(), + Short: "Send a test alert through a channel now", + Long: `Sends a test alert right away and prints the provider's reference. Rate +limited (20 per user and 60 per organization an hour); an SMS counts +toward the daily SMS limit, so SMS channels ask first (--yes skips it).`, + Example: ` norcube pulsecheck channels test "On-call webhook"`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + ch, err := getChannel(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + if ch.Kind == "sms" { + if ok, err := cmdutil.Confirm(fmt.Sprintf("Text a test alert to %s? It counts toward the daily SMS limit", destination(ch)), yes); err != nil || !ok { + return nil, cmdutil.Cancelled(cmd, err) + } + } + res, err := c.API.TestAlertChannelWithResponse(cmd.Context(), ch.Id) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + return output.Done{ + Message: fmt.Sprintf("Sent a test alert through %s (provider reference %s).", ch.Name, res.JSON200.ProviderRef), + Value: *res.JSON200, + Fields: []output.Field{{Value: res.JSON200.ProviderRef}}, + }, nil + }), + } + cmd.Flags().BoolVar(&yes, "yes", false, "Don't ask before texting an SMS channel") + return cmd +} + +var verificationCode = regexp.MustCompile(`^[0-9]{6}$`) + +// verifyResult is what `channels verify` prints as JSON. +type verifyResult struct { + ID string `json:"id" yaml:"id"` + CodeSent bool `json:"codeSent" yaml:"codeSent"` + Verified bool `json:"verified" yaml:"verified"` +} + +func newChannelVerifyCmd(d deps) *cobra.Command { + var ( + codeFile string + resend bool + ) + cmd := &cobra.Command{ + Use: "verify ", + Annotations: cmdutil.Writes(), + Short: "Confirm an SMS or email-address channel with the code sent to it", + Long: `Email-address and SMS channels get no alerts until their contact +confirms a 6-digit code (valid 10 minutes, 5 attempts). + +On a terminal, verify sends a code and asks for it. In a script, run it +once to send the code, then again with --code-file (- reads standard +input) to confirm. The code is never taken as an argument nor printed. +A new code can be sent after a minute (--resend), at most 5 a day.`, + Example: ` norcube pulsecheck channels verify "On-call phone" + norcube pulsecheck channels verify 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f --resend + echo 123456 | norcube pulsecheck channels verify 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f --code-file -`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + if resend && codeFile != "" { + return nil, clierr.Usage(fmt.Errorf("--resend and --code-file can't be combined")) + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := channelRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + stderr := cmdutil.Stderr(cmd) + var code string + sent := false + if codeFile == "" { + if err := sendCode(cmd.Context(), c, id); err != nil { + return nil, err + } + sent = true + if !term.StdinIsTerminal() { + fmt.Fprintf(stderr, "Sent a code. Confirm it with: norcube pulsecheck channels verify %s --code-file -\n", id) + return output.Done{Message: "Code sent.", Value: verifyResult{ID: id.String(), CodeSent: true}, + Fields: []output.Field{{Value: id.String()}, {Value: "sent"}}}, nil + } + code, err = askCode() + if err != nil { + if errors.Is(err, cmdutil.ErrCancelled) { + return nil, cmdutil.Cancelled(cmd, nil) + } + return nil, err + } + } else { + code, err = cmdutil.ReadText(cmd.InOrStdin(), "", codeFile, "the code") + if err != nil { + return nil, err + } + } + code = strings.TrimSpace(code) + if !verificationCode.MatchString(code) { + return nil, clierr.Usage(fmt.Errorf("the code is the 6 digits sent to the channel")) + } + res, err := c.API.ConfirmAlertChannelVerificationWithResponse(cmd.Context(), id, pulsecheck.DtoAlertChannelVerifyConfirm{Code: code}) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + ch := *res.JSON200 + return output.Done{ + Message: fmt.Sprintf("Verified channel %s (%s): it gets alerts now.", ch.Name, ch.Id), + Value: verifyResult{ID: ch.Id.String(), CodeSent: sent, Verified: ch.Verified}, + Fields: []output.Field{{Value: ch.Id.String()}, {Value: "verified"}}, + }, nil + }), + } + cmd.Flags().StringVar(&codeFile, "code-file", "", "Confirm with the code read from this file (- for standard input) instead of sending one") + cmd.Flags().BoolVar(&resend, "resend", false, "Send a new code (the same as running verify again)") + return cmd +} + +func sendCode(ctx context.Context, c *pcContext, id uuid.UUID) error { + res, err := c.API.SendAlertChannelVerificationWithResponse(ctx, id) + if err != nil { + return err + } + if res.StatusCode() != http.StatusNoContent { + return apiError(res.HTTPResponse, res.Body) + } + return nil +} + +// askCode reads the code on a terminal without echoing it. +func askCode() (string, error) { + var code string + err := huh.NewInput(). + Title("Code"). + Description("The 6-digit code sent to the channel (valid 10 minutes)."). + EchoMode(huh.EchoModePassword). + Validate(func(s string) error { + if !verificationCode.MatchString(strings.TrimSpace(s)) { + return fmt.Errorf("enter the 6 digits") + } + return nil + }). + Value(&code). + Run() + if errors.Is(err, huh.ErrUserAborted) { + return "", cmdutil.ErrCancelled + } + return code, err +} + +// ---------- deliveries ---------- + +func newDeliveriesCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "deliveries", + Short: "The alerts a channel was given to send", + } + var ( + pf cmdutil.PageFlags + status string + ) + list := &cobra.Command{ + Use: "list ", + Annotations: cmdutil.Reads(), + Short: "List a channel's deliveries, newest first", + Long: `Lists every alert given to the channel (kept 90 days): the event, monitor +and incident, whether it was sent, is pending (queued or waiting to retry) +or dead (given up), the attempts and the last error, with URLs, addresses +and phone numbers removed. --status dead lists the failures nobody saw.`, + Example: ` norcube pulsecheck channels deliveries list "On-call webhook" --status dead`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + params := pulsecheck.ListAlertChannelDeliveriesParams{} + if status != "" { + if err := oneOf("--status", status, deliveryStatuses); err != nil { + return nil, err + } + s := pulsecheck.ListAlertChannelDeliveriesParamsStatus(status) + params.Status = &s + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := channelRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + page, err := cmdutil.Paginate(cmd.Context(), pf, func(ctx context.Context, cursor string, size int) ([]pulsecheck.DtoChannelDelivery, string, error) { + p := params + p.Limit = &size + if cursor != "" { + p.Cursor = &cursor + } + res, err := c.API.ListAlertChannelDeliveriesWithResponse(ctx, id, &p) + if err != nil { + return nil, "", err + } + if res.JSON200 == nil { + return nil, "", apiError(res.HTTPResponse, res.Body) + } + return res.JSON200.List, nextCursor(res.JSON200.Cursors), nil + }) + if err != nil { + return nil, err + } + return nil, page.Print(cmd, output.Table[pulsecheck.DtoChannelDelivery]{ + Headers: []string{"CREATED", "EVENT", "MONITOR", "STATUS", "ATTEMPTS", "SENT", "LAST ERROR"}, + MaxWidths: []int{0, 0, 28, 0, 0, 0, 60}, + Style: output.Style{StatusColumn: 3}, + Rows: func(x pulsecheck.DtoChannelDelivery) []string { + return []string{output.WhenString(x.CreatedAt), string(x.Event), x.MonitorName, string(x.Status), + fmt.Sprint(x.Attempts), output.WhenString(cmdutil.Deref(x.SentAt)), strOr(x.LastError)} + }, + Items: page.Items, + }) + }), + } + list.Flags().StringVar(&status, "status", "", "Only pending, sent or dead deliveries") + cmdutil.FlagEnum(list, "status", deliveryStatuses...) + cmdutil.AddPageFlags(list, &pf, defaultPageSize, maxItems) + cmd.AddCommand(list) + return cmd +} diff --git a/internal/cli/pulsecheck/cmd.go b/internal/cli/pulsecheck/cmd.go new file mode 100644 index 0000000..dbec8a5 --- /dev/null +++ b/internal/cli/pulsecheck/cmd.go @@ -0,0 +1,102 @@ +// Package pulsecheck implements the `norcube pulsecheck ...` command tree: +// uptime, SSL certificate and domain expiry monitors, their check history, +// incidents and alert channels, and an organization-wide status for +// scripts and CI. +package pulsecheck + +import ( + "net/http" + "time" + + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cli/internal/api/apierror" + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/config" + "github.com/norcubeplatform/cli/internal/service" +) + +// pcContext is the PulseCheck API client plus the profile, organization +// and output format of the invocation. +type pcContext = service.Client[*pulsecheck.ClientWithResponses] + +// deps are what the commands need from outside: how to build the API +// client and what time it is. Production code uses defaultDeps; tests +// pass fakes, so no command reaches for a global. +type deps struct { + // client builds the PulseCheck client for the invocation. + client func(cmd *cobra.Command) (*pcContext, error) + // now is the current time (--since ages, timeline durations). + now func() time.Time +} + +func defaultDeps() deps { + return deps{ + client: func(cmd *cobra.Command) (*pcContext, error) { + return service.New(cmd, config.ServicePulsecheck, newAPI) + }, + now: time.Now, + } +} + +func newAPI(baseURL string, httpc *http.Client, edit service.RequestEditor) (*pulsecheck.ClientWithResponses, error) { + return pulsecheck.NewClientWithResponses(baseURL, + pulsecheck.WithHTTPClient(httpc), + pulsecheck.WithRequestEditorFn(edit)) +} + +// NewCmd returns the `pulsecheck` parent command with all subcommands. +func NewCmd() *cobra.Command { return newCmd(defaultDeps()) } + +func newCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "pulsecheck", + Short: "Monitor uptime, SSL certificates and domain expiry, and manage incidents and alerts", + Long: `PulseCheck checks your sites, certificates and domains on a schedule +from Norcube's servers. A monitor is an HTTP check (optionally with a +keyword), an SSL certificate check or a domain expiry check. Problems +confirmed by consecutive checks open incidents, which alert through your +alert channels (email, webhook, Slack, Discord, SMS). + +Monitors and channels are named by their id or, where a command says so, +by their exact name. Checks count towards your PulseCheck usage, on a +schedule and when you run one now. + +In CI, "pulsecheck status --fail-on critical" fails the job while a +critical incident is open, and "pulsecheck monitors run --wait" +fails it when the check finds the monitor down. CI tokens need a +PulseCheck scope: pulsecheck.read (everything that reads), +pulsecheck.check (run checks), pulsecheck.write (manage monitors and +incidents) or pulsecheck.channels (manage alert channels, which +pulsecheck.write doesn't include).`, + } + cmd.AddCommand( + newStatusCmd(d), + newMonitorsCmd(d), + newIncidentsCmd(d), + newChannelsCmd(d), + ) + registerCompletions(cmd, d) + return cmd +} + +// apiError renders a non-2xx PulseCheck response (an RFC 9457 problem) +// through the shared formatter: its code and exit code follow the status, +// and a 403 for a scope the token lacks exits 5. +func apiError(resp *http.Response, body []byte) error { + return apierror.Format("pulsecheck", resp, body) +} + +// nextCursor reads the next-page cursor of a PulseCheck list. +func nextCursor(c pulsecheck.ResponseAPIResponsePaginationCursors) string { + return cmdutil.Deref(c.Next) +} + +// Page sizes and caps for --all-pages. The API returns at most 100 items +// per page. +const ( + defaultPageSize = 50 + maxPageSize = 100 + maxItems = 10000 +) diff --git a/internal/cli/pulsecheck/completion.go b/internal/cli/pulsecheck/completion.go new file mode 100644 index 0000000..54e7822 --- /dev/null +++ b/internal/cli/pulsecheck/completion.go @@ -0,0 +1,124 @@ +package pulsecheck + +import ( + "fmt" + + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/completion" +) + +// Completion lookup keys (they also separate the cache entries). Each +// lookup is one request of at most 100 items, within completion's +// one-second budget, cached a minute per profile and organization. +const ( + completeMonitors = "pulsecheck-monitors" + completeChannels = "pulsecheck-channels" + completeIncidents = "pulsecheck-incidents" +) + +// registerCompletions offers monitor ids (named, with their status), +// channel ids and open incident ids to the commands and flags that take +// them. +func registerCompletions(root *cobra.Command, d deps) { + monitors := monitorCandidates(d) + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + if c.Flags().Lookup("monitor") != nil { + _ = c.RegisterFlagCompletionFunc("monitor", completion.Flag(completeMonitors, monitors)) + } + switch first := firstArg(c.Use); first { + case "": + c.ValidArgsFunction = completion.Func(completeMonitors, 1, monitors) + case "[...]": + c.ValidArgsFunction = completion.Func(completeMonitors, 1<<10, monitors) + case "": + c.ValidArgsFunction = completion.Func(completeChannels, 1, channelCandidates(d)) + case "": + c.ValidArgsFunction = completion.Func(completeIncidents, 1, incidentCandidates(d)) + } + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) +} + +// firstArg is the first argument placeholder of a Use line. +func firstArg(use string) string { + for i := 0; i < len(use); i++ { + if use[i] == ' ' { + return use[i+1:] + } + } + return "" +} + +func monitorCandidates(d deps) completion.Fetcher { + return func(cmd *cobra.Command) ([]cobra.Completion, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + limit := maxPageSize + res, err := c.API.ListMonitorsWithResponse(cmd.Context(), &pulsecheck.ListMonitorsParams{Limit: &limit}) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, fmt.Errorf("status %d", res.StatusCode()) + } + out := make([]cobra.Completion, 0, len(res.JSON200.List)) + for _, m := range res.JSON200.List { + out = append(out, fmt.Sprintf("%s\t%s (%s, %s)", m.Id, m.Name, m.Variant, monitorWord(m))) + } + return out, nil + } +} + +func channelCandidates(d deps) completion.Fetcher { + return func(cmd *cobra.Command) ([]cobra.Completion, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + limit := maxPageSize + res, err := c.API.ListAlertChannelsWithResponse(cmd.Context(), &pulsecheck.ListAlertChannelsParams{Limit: &limit}) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, fmt.Errorf("status %d", res.StatusCode()) + } + out := make([]cobra.Completion, 0, len(res.JSON200.List)) + for _, ch := range res.JSON200.List { + out = append(out, fmt.Sprintf("%s\t%s (%s)", ch.Id, ch.Name, ch.Kind)) + } + return out, nil + } +} + +// incidentCandidates offers the newest incidents, open ones first (the +// API's order). +func incidentCandidates(d deps) completion.Fetcher { + return func(cmd *cobra.Command) ([]cobra.Completion, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + limit := maxPageSize + res, err := c.API.ListIncidentsWithResponse(cmd.Context(), &pulsecheck.ListIncidentsParams{Limit: &limit}) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, fmt.Errorf("status %d", res.StatusCode()) + } + out := make([]cobra.Completion, 0, len(res.JSON200.List)) + for _, i := range res.JSON200.List { + out = append(out, fmt.Sprintf("%s\t%s, %s: %s", i.Id, i.Status, i.MonitorName, i.Title)) + } + return out, nil + } +} diff --git a/internal/cli/pulsecheck/format.go b/internal/cli/pulsecheck/format.go new file mode 100644 index 0000000..f3c2679 --- /dev/null +++ b/internal/cli/pulsecheck/format.go @@ -0,0 +1,478 @@ +package pulsecheck + +import ( + "fmt" + "strconv" + "strings" + "time" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/output" +) + +// Status words are PulseCheck's own vocabulary (the service README's +// status model): an HTTP monitor is Up or Down, a certificate Valid, +// Expiring or Expired, a domain Registered or Expiring. JSON keeps the +// API's codes (status, condition); only tables and text show words. +var conditionWords = map[string]map[string]string{ + "http": { + "ok": "Up", "slow_response": "Slow", "config_error": "Can't check", "internal": "Unknown", + }, + "ssl": { + "ok": "Valid", "cert_expiring": "Expiring", "cert_expired": "Expired", + "cert_invalid": "Invalid", "cert_hostname": "Invalid", "cert_not_yet_valid": "Invalid", + "timeout": "Unreachable", "dns": "Unreachable", "connect": "Unreachable", "tls": "Unreachable", + "blocked_destination": "Unreachable", "internal": "Unknown", + }, + "domain": { + "ok": "Registered", "domain_expiring": "Expiring", "domain_expiry_unknown": "Expiry unknown", + "domain_expired": "Expired", "domain_not_registered": "Not registered", + "domain_lookup_failed": "Unknown", "internal": "Unknown", + }, +} + +// statusWord names a monitor's status in its type's words. HTTP problems +// other than the ones listed are Down. +func statusWord(monitorType, status, condition string) string { + switch status { + case "paused": + return "Paused" + case "pending": + return "Pending" + } + if w, ok := conditionWords[monitorType][condition]; ok { + return w + } + switch status { + case "ok": + return conditionWords[monitorType]["ok"] + case "critical": + if monitorType == "http" { + return "Down" + } + return "Critical" + case "warning": + return "Warning" + } + return capitalize(status) +} + +// aspectWord names a watched aspect's status (an HTTP monitor's +// certificate or domain watch) in that aspect's words. +func aspectWord(aspect, status, condition string) string { + kind := map[string]string{"certificate": "ssl", "domain": "domain"}[aspect] + if status == "pending" { + return "Pending" + } + if w, ok := conditionWords[kind][condition]; ok { + return w + } + return capitalize(status) +} + +// severityWord names a check result's severity for a monitor type. +func resultWord(monitorType, severity, condition string) string { + if severity == "inconclusive" { + return "Unknown" + } + return statusWord(monitorType, severity, condition) +} + +// stamp renders an API time inside a longer cell (a timeline line), in +// local time to the minute; whole-cell times use output.WhenString. +func stamp(s string) string { + t, err := time.Parse(time.RFC3339Nano, s) + if err != nil { + return s + } + return t.Local().Format("2006-01-02 15:04") +} + +// plural is "1 check", "2 checks". +func plural(n int, word string) string { + if n == 1 { + return fmt.Sprintf("%d %s", n, word) + } + return fmt.Sprintf("%d %ss", n, word) +} + +func capitalize(s string) string { + if s == "" { + return "" + } + return strings.ToUpper(s[:1]) + s[1:] +} + +// percent renders an uptime share ("99.95%"); no data is the placeholder, +// never 100%. +func percent(p *float32) string { + if p == nil { + return "—" + } + return strconv.FormatFloat(float64(*p), 'f', -1, 32) + "%" +} + +func ms(p *int) string { + if p == nil { + return "—" + } + return fmt.Sprintf("%d ms", *p) +} + +func intOr(p *int) string { + if p == nil { + return "—" + } + return strconv.Itoa(*p) +} + +func strOr(p *string) string { + if p == nil || *p == "" { + return "—" + } + return *p +} + +// orNone joins lines for one multi-line field. +func orNone(lines []string) string { + if len(lines) == 0 { + return "none" + } + return strings.Join(lines, "\n") +} + +func yesNo(b bool) string { + if b { + return "yes" + } + return "no" +} + +// duration renders seconds as "3d 4h", "2h 5m", "4m 10s". +func duration(seconds int) string { + d := time.Duration(seconds) * time.Second + switch { + case d >= 24*time.Hour: + return fmt.Sprintf("%dd %dh", int(d.Hours())/24, int(d.Hours())%24) + case d >= time.Hour: + return fmt.Sprintf("%dh %dm", int(d.Hours()), int(d.Minutes())%60) + case d >= time.Minute: + return fmt.Sprintf("%dm %ds", int(d.Minutes()), int(d.Seconds())%60) + } + return fmt.Sprintf("%ds", int(d.Seconds())) +} + +// interval renders a check interval ("1m", "12h"). +func interval(seconds int) string { + d := time.Duration(seconds) * time.Second + switch { + case d%time.Hour == 0: + return fmt.Sprintf("%dh", int(d.Hours())) + case d%time.Minute == 0: + return fmt.Sprintf("%dm", int(d.Minutes())) + } + return fmt.Sprintf("%ds", seconds) +} + +func joinInts(v []int) string { + out := make([]string, len(v)) + for i, n := range v { + out[i] = strconv.Itoa(n) + } + return strings.Join(out, ", ") +} + +// ---------- monitors ---------- + +var monitorHeaders = []string{"ID", "NAME", "TYPE", "STATUS", "TARGET", "UPTIME 24H", "LAST CHECK"} + +func monitorWord(m pulsecheck.DtoMonitor) string { + cond := "" + if m.Condition != nil { + cond = m.Condition.Code + } + return statusWord(string(m.Type), string(m.Status), cond) +} + +func monitorRow(m pulsecheck.DtoMonitor) []string { + uptime, last := "—", "—" + if m.Last24h != nil { + uptime = percent(m.Last24h.UptimePercent) + } + if m.LastCheck != nil { + last = output.WhenString(m.LastCheck.At) + } + return []string{m.Id.String(), m.Name, string(m.Variant), monitorWord(m), m.Target, uptime, last} +} + +func monitorTable(items []pulsecheck.DtoMonitor) output.Table[pulsecheck.DtoMonitor] { + return output.Table[pulsecheck.DtoMonitor]{ + Headers: monitorHeaders, + MaxWidths: []int{0, 32, 0, 0, 48, 0, 0}, + Style: output.Style{StatusColumn: 3}, + Rows: monitorRow, + Items: items, + } +} + +func monitorObject(m pulsecheck.DtoMonitor) output.Object { + f := []output.Field{ + {Name: "ID", Value: m.Id.String()}, + {Name: "Name", Value: m.Name}, + {Name: "Type", Value: string(m.Variant)}, + {Name: "Target", Value: m.Target}, + {Name: "Status", Value: monitorWord(m)}, + {Name: "Since", Value: output.WhenString(m.StatusSince)}, + } + if m.Condition != nil && m.Condition.Message != nil { + f = append(f, output.Field{Name: "Reason", Value: *m.Condition.Message}) + } + if m.Condition != nil && m.Condition.Facts.DaysRemaining != nil { + f = append(f, output.Field{Name: "Days left", Value: strconv.Itoa(*m.Condition.Facts.DaysRemaining)}) + } + for _, a := range m.Aspects { + v := aspectWord(string(a.Aspect), string(a.Status), cmdutil.Deref(a.Condition)) + if a.DaysRemaining != nil { + v += fmt.Sprintf(" (%d days left)", *a.DaysRemaining) + } + f = append(f, output.Field{Name: capitalize(string(a.Aspect)) + " of " + a.Subject, Value: v}) + } + f = append(f, output.Field{Name: "Interval", Value: interval(m.IntervalSeconds)}) + if m.Last24h != nil { + f = append(f, output.Field{Name: "Uptime 24h", Value: percent(m.Last24h.UptimePercent)}, + output.Field{Name: "Response p95", Value: ms(m.Last24h.P95Ms)}) + } + last, next := "—", output.WhenString(cmdutil.Deref(m.NextCheckAt)) + if m.LastCheck != nil { + last = output.WhenString(m.LastCheck.At) + } + regions := make([]string, len(m.Regions)) + for i, r := range m.Regions { + regions[i] = r.Name + } + f = append(f, + output.Field{Name: "Last check", Value: last}, + output.Field{Name: "Next check", Value: next}, + output.Field{Name: "Regions", Value: strings.Join(regions, ", ")}, + ) + f = append(f, settingsFields(m)...) + if m.ParentResource != nil { + f = append(f, output.Field{Name: "Managed by", Value: *m.ParentResource}) + } + if m.Description != "" { + f = append(f, output.Field{Name: "Description", Value: m.Description}) + } + f = append(f, output.Field{Name: "Created", Value: output.WhenString(m.CreatedAt)}) + // -o text prints the list's columns: the fields above depend on the type. + return output.Object{Value: m, Fields: f, Text: monitorRow(m)} +} + +// settingsFields are a monitor's check settings for its detail view. +// Secret header values never reach the CLI (the API withholds them). +func settingsFields(m pulsecheck.DtoMonitor) []output.Field { + var f []output.Field + switch { + case m.Http != nil: + h := m.Http + f = append(f, + output.Field{Name: "Request", Value: h.Method + " " + h.Url}, + output.Field{Name: "Expected status", Value: strings.Join(h.ExpectedStatus, ", ")}, + output.Field{Name: "Timeout", Value: fmt.Sprintf("%d ms", h.TimeoutMs)}, + ) + if h.SlowThresholdMs != nil { + f = append(f, output.Field{Name: "Slow above", Value: ms(h.SlowThresholdMs)}) + } + if h.Keyword != nil { + mode := cmdutil.DerefOr(h.KeywordMode, "present") + f = append(f, output.Field{Name: "Keyword", Value: fmt.Sprintf("%q must be %s", *h.Keyword, mode)}) + } + for _, hd := range h.Headers { + v := cmdutil.Deref(hd.Value) + if hd.Secret { + v = "(secret)" + } + f = append(f, output.Field{Name: "Header " + hd.Name, Value: v}) + } + redirects := "not followed" + if h.FollowRedirects { + redirects = fmt.Sprintf("followed, at most %d", h.MaxRedirects) + } + f = append(f, output.Field{Name: "Redirects", Value: redirects}, + output.Field{Name: "Verify TLS", Value: yesNo(h.VerifyTls)}) + case m.Ssl != nil: + f = append(f, output.Field{Name: "Host", Value: fmt.Sprintf("%s:%d", m.Ssl.Host, m.Ssl.Port)}) + if m.Ssl.ServerName != nil { + f = append(f, output.Field{Name: "Server name", Value: *m.Ssl.ServerName}) + } + f = append(f, output.Field{Name: "Alert at days", Value: joinInts(m.Ssl.ExpiryThresholdsDays)}) + case m.Domain != nil: + f = append(f, output.Field{Name: "Domain", Value: m.Domain.Domain}, + output.Field{Name: "Alert at days", Value: joinInts(m.Domain.ExpiryThresholdsDays)}) + } + return f +} + +// ---------- check results ---------- + +var resultHeaders = []string{"ID", "CHECKED", "RESULT", "CONDITION", "STATUS CODE", "TIME", "REGION"} + +func resultRow(monitorType string) func(r pulsecheck.DtoCheckResult) []string { + return func(r pulsecheck.DtoCheckResult) []string { + return []string{ + strconv.Itoa(r.Id), + output.WhenStringSeconds(r.CheckedAt), + resultWord(monitorType, string(r.Severity), r.Condition), + r.Condition, + intOr(r.StatusCode), + fmt.Sprintf("%d ms", r.Timings.TotalMs), + r.Region, + } + } +} + +func resultObject(monitorType string, r pulsecheck.DtoCheckResult) output.Object { + row := resultRow(monitorType)(r) + f := []output.Field{ + {Name: "Result", Value: row[2]}, + {Name: "Condition", Value: r.Condition}, + {Name: "Checked", Value: row[1]}, + {Name: "Status code", Value: row[4]}, + {Name: "Total time", Value: row[5]}, + {Name: "Region", Value: r.Region}, + } + if r.ErrorMessage != nil { + f = append(f, output.Field{Name: "Message", Value: *r.ErrorMessage}) + } + if c := r.Certificate; c != nil { + f = append(f, output.Field{Name: "Certificate", Value: fmt.Sprintf("%s, expires %s (%d days)", c.Subject, output.WhenString(c.NotAfter), c.DaysRemaining)}) + } + if dr := r.Domain; dr != nil { + f = append(f, output.Field{Name: "Domain expires", Value: output.WhenString(cmdutil.Deref(dr.ExpiresAt))}, + output.Field{Name: "Registrar", Value: strOr(dr.Registrar)}) + } + f = append(f, output.Field{Name: "Result ID", Value: row[0]}) + return output.Object{Value: r, Fields: f, Text: row} +} + +// ---------- incidents ---------- + +var incidentHeaders = []string{"ID", "STATUS", "SEVERITY", "MONITOR", "TITLE", "OPENED", "DURATION", "ACK"} + +func incidentRow(i pulsecheck.DtoIncident) []string { + ack := "no" + if i.AcknowledgedAt != nil { + ack = "yes" + } + return []string{ + i.Id.String(), string(i.Status), string(i.Severity), i.MonitorName, i.Title, + output.WhenString(i.OpenedAt), duration(i.DurationSeconds), ack, + } +} + +func incidentTable(items []pulsecheck.DtoIncident) output.Table[pulsecheck.DtoIncident] { + return output.Table[pulsecheck.DtoIncident]{ + Headers: incidentHeaders, + MaxWidths: []int{0, 0, 0, 28, 48, 0, 0, 0}, + Style: output.Style{StatusColumn: 2}, + Rows: incidentRow, + Items: items, + } +} + +func incidentObject(i pulsecheck.DtoIncidentDetail) output.Object { + ack := "no" + if i.AcknowledgedAt != nil { + ack = output.WhenString(*i.AcknowledgedAt) + if i.AcknowledgedByName != nil { + ack += " by " + *i.AcknowledgedByName + } + } + f := []output.Field{ + {Name: "ID", Value: i.Id.String()}, + {Name: "Title", Value: i.Title}, + {Name: "Status", Value: string(i.Status)}, + {Name: "Severity", Value: fmt.Sprintf("%s (peak %s)", i.Severity, i.PeakSeverity)}, + {Name: "Monitor", Value: fmt.Sprintf("%s (%s, %s)", i.MonitorName, i.MonitorVariant, i.MonitorTarget)}, + {Name: "Aspect", Value: string(i.Aspect)}, + {Name: "Summary", Value: i.Summary}, + {Name: "Opened", Value: output.WhenString(i.OpenedAt)}, + {Name: "Resolved", Value: output.WhenString(cmdutil.Deref(i.ResolvedAt))}, + {Name: "Duration", Value: duration(i.DurationSeconds)}, + {Name: "Acknowledged", Value: ack}, + } + timeline := make([]string, 0, len(i.Timeline)) + for _, e := range i.Timeline { + timeline = append(timeline, stamp(e.At)+" "+string(e.Type)) + } + alerts := make([]string, 0, len(i.Alerts)) + for _, a := range i.Alerts { + to := cmdutil.DerefOr(a.ChannelName, "member emails") + alerts = append(alerts, fmt.Sprintf("%s %s to %s: %s (%s)", stamp(a.QueuedAt), a.Event, to, a.Status, plural(a.Attempts, "attempt"))) + } + f = append(f, output.Field{Name: "Timeline", Value: orNone(timeline)}, output.Field{Name: "Alerts", Value: orNone(alerts)}) + row := incidentRow(pulsecheck.DtoIncident{ + Id: i.Id, Status: pulsecheck.DtoIncidentStatus(i.Status), Severity: pulsecheck.DtoIncidentSeverity(i.Severity), + MonitorName: i.MonitorName, Title: i.Title, OpenedAt: i.OpenedAt, DurationSeconds: i.DurationSeconds, AcknowledgedAt: i.AcknowledgedAt, + }) + return output.Object{Value: i, Fields: f, Text: row} +} + +// ---------- alert channels ---------- + +var channelHeaders = []string{"ID", "NAME", "KIND", "DESTINATION", "DEFAULT", "ENABLED", "VERIFIED"} + +// destination is where a channel delivers, as the API shows it (never a +// credential: Slack and Discord URLs are hints). +func destination(c pulsecheck.DtoAlertChannel) string { + s := c.Settings + switch { + case cmdutil.Deref(s.Members): + return "organization members" + case s.Address != nil: + return *s.Address + case s.Phone != nil: + return *s.Phone + case s.Hint != nil: + return *s.Hint + case s.Url != nil: + return *s.Url + } + return "—" +} + +func channelRow(c pulsecheck.DtoAlertChannel) []string { + return []string{c.Id.String(), c.Name, string(c.Kind), destination(c), yesNo(c.IsDefault), yesNo(c.Enabled), yesNo(c.Verified)} +} + +func channelTable(items []pulsecheck.DtoAlertChannel) output.Table[pulsecheck.DtoAlertChannel] { + return output.Table[pulsecheck.DtoAlertChannel]{ + Headers: channelHeaders, + MaxWidths: []int{0, 28, 0, 40, 0, 0, 0}, + Style: output.NoStyle, + Rows: channelRow, + Items: items, + } +} + +func channelObject(c pulsecheck.DtoAlertChannel) output.Object { + row := channelRow(c) + f := make([]output.Field, 0, len(row)+2) + names := []string{"ID", "Name", "Kind", "Destination", "Default", "Enabled", "Verified"} + for i, n := range names { + f = append(f, output.Field{Name: n, Value: row[i]}) + } + f = append(f, output.Field{Name: "Created", Value: output.WhenString(c.CreatedAt)}, + output.Field{Name: "Updated", Value: output.WhenString(c.UpdatedAt)}) + return output.Object{Value: c, Fields: f} +} + +// withoutSecret drops the one-time signing secret from a channel the API +// returned with one, so it never reaches stdout. +func withoutSecret(c pulsecheck.DtoAlertChannelWithSecret) pulsecheck.DtoAlertChannel { + return pulsecheck.DtoAlertChannel{ + CreatedAt: c.CreatedAt, Enabled: c.Enabled, Id: c.Id, IsDefault: c.IsDefault, + Kind: pulsecheck.DtoAlertChannelKind(c.Kind), Name: c.Name, Settings: c.Settings, + UpdatedAt: c.UpdatedAt, Verified: c.Verified, + } +} diff --git a/internal/cli/pulsecheck/incidents.go b/internal/cli/pulsecheck/incidents.go new file mode 100644 index 0000000..a1badcc --- /dev/null +++ b/internal/cli/pulsecheck/incidents.go @@ -0,0 +1,258 @@ +package pulsecheck + +import ( + "context" + "fmt" + "strconv" + + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/output" +) + +var ( + incidentStatuses = []string{"open", "resolved"} + incidentSeverities = []string{"warning", "critical"} + incidentAspects = []string{"availability", "certificate", "domain"} +) + +func newIncidentsCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "incidents", + Aliases: []string{"incident"}, + Short: "List, inspect and acknowledge incidents", + Long: `An incident is a confirmed problem with one aspect of a monitor: its +availability, its certificate or its domain. It opens after the monitor's +confirmations (or at once for an expiry), alerts the monitor's channels, +reminds until acknowledged, and resolves when the checks are good again.`, + } + cmd.AddCommand(newIncidentListCmd(d), newIncidentGetCmd(d), newIncidentAckCmd(d), newIncidentSummaryCmd(d)) + return cmd +} + +func newIncidentListCmd(d deps) *cobra.Command { + var ( + pf cmdutil.PageFlags + status, severity, aspect, monitor string + search, since, until string + acked, unacked bool + ) + cmd := &cobra.Command{ + Use: "list", + Annotations: cmdutil.Reads(), + Short: "List incidents, open ones first", + Long: `Lists incidents: open critical ones first, then open warnings, then +resolved ones, newest first within each. Every filter given must match. +--severity reads an open incident's current severity and a resolved one's +peak, so "--severity critical" finds every incident that ever paged. +--since and --until select by when the incident started.`, + Example: ` norcube pulsecheck incidents list --status open + norcube pulsecheck incidents list --status open --unacknowledged --severity critical + norcube pulsecheck incidents list --monitor "Shop" --since 30d -o json`, + Args: cobra.NoArgs, + RunE: cmdutil.Run(func(cmd *cobra.Command, _ []string) (any, error) { + params := pulsecheck.ListIncidentsParams{} + if status != "" { + if err := oneOf("--status", status, incidentStatuses); err != nil { + return nil, err + } + v := pulsecheck.ListIncidentsParamsStatus(status) + params.Status = &v + } + if severity != "" { + if err := oneOf("--severity", severity, incidentSeverities); err != nil { + return nil, err + } + v := pulsecheck.ListIncidentsParamsSeverity(severity) + params.Severity = &v + } + if aspect != "" { + if err := oneOf("--aspect", aspect, incidentAspects); err != nil { + return nil, err + } + v := pulsecheck.ListIncidentsParamsAspect(aspect) + params.Aspect = &v + } + if acked || unacked { + v := pulsecheck.ListIncidentsParamsAcknowledged(strconv.FormatBool(acked)) + params.Acknowledged = &v + } + if search != "" { + params.Q = &search + } + if err := timeRange(since, until, d.now(), ¶ms.From, ¶ms.To); err != nil { + return nil, err + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + if monitor != "" { + id, err := monitorRef(cmd.Context(), c, monitor) + if err != nil { + return nil, err + } + params.MonitorId = &id + } + page, err := cmdutil.Paginate(cmd.Context(), pf, func(ctx context.Context, cursor string, size int) ([]pulsecheck.DtoIncident, string, error) { + p := params + p.Limit = &size + if cursor != "" { + p.Cursor = &cursor + } + res, err := c.API.ListIncidentsWithResponse(ctx, &p) + if err != nil { + return nil, "", err + } + if res.JSON200 == nil { + return nil, "", apiError(res.HTTPResponse, res.Body) + } + return res.JSON200.List, nextCursor(res.JSON200.Cursors), nil + }) + if err != nil { + return nil, err + } + return nil, page.Print(cmd, incidentTable(page.Items)) + }), + } + cmd.Flags().StringVar(&status, "status", "", "Only open or resolved incidents") + cmd.Flags().StringVar(&severity, "severity", "", "Only warning or critical incidents (current severity while open, peak once resolved)") + cmd.Flags().StringVar(&aspect, "aspect", "", "Only incidents about availability, the certificate or the domain") + cmd.Flags().StringVar(&monitor, "monitor", "", "Only incidents of this monitor (id or exact name)") + cmd.Flags().StringVar(&search, "search", "", "Only incidents whose monitor's name or target contains this text") + cmd.Flags().BoolVar(&acked, "acknowledged", false, "Only acknowledged incidents") + cmd.Flags().BoolVar(&unacked, "unacknowledged", false, "Only incidents nobody acknowledged yet") + addTimeFlags(cmd, &since, &until, "incidents that started") + cmd.MarkFlagsMutuallyExclusive("acknowledged", "unacknowledged") + cmdutil.FlagEnum(cmd, "status", incidentStatuses...) + cmdutil.FlagEnum(cmd, "severity", incidentSeverities...) + cmdutil.FlagEnum(cmd, "aspect", incidentAspects...) + cmdutil.AddPageFlags(cmd, &pf, defaultPageSize, maxItems) + return cmd +} + +func newIncidentGetCmd(d deps) *cobra.Command { + return &cobra.Command{ + Use: "get ", + Annotations: cmdutil.Reads(), + Short: "Show an incident with its timeline and the alerts sent", + Long: `Shows the incident, its timeline (opened, escalated, reminders, +acknowledged, resolved) and every alert sent for it with its delivery +status, so a failing channel shows here.`, + Example: ` norcube pulsecheck incidents get 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 + norcube pulsecheck incidents get 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 -o json --query timeline`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + id, err := idArg("incident", args[0]) + if err != nil { + return nil, err + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + res, err := c.API.GetIncidentWithResponse(cmd.Context(), id) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + return incidentObject(*res.JSON200), nil + }), + } +} + +func newIncidentAckCmd(d deps) *cobra.Command { + return &cobra.Command{ + Use: "acknowledge ", + Aliases: []string{"ack"}, + Annotations: cmdutil.Writes(), + Short: "Acknowledge an incident: someone is on it, stop the reminders", + Long: "Marks an open incident as being handled; its reminders stop. Idempotent: a resolved or already acknowledged incident is returned unchanged.", + Example: ` norcube pulsecheck incidents acknowledge 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + id, err := idArg("incident", args[0]) + if err != nil { + return nil, err + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + res, err := c.API.AcknowledgeIncidentWithResponse(cmd.Context(), id) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + i := *res.JSON200 + return output.Done{ + Message: fmt.Sprintf("Acknowledged incident %s (%s).", i.Id, i.Title), + Value: i, + Fields: []output.Field{{Value: i.Id.String()}, {Value: string(i.Status)}}, + }, nil + }), + } +} + +func newIncidentSummaryCmd(d deps) *cobra.Command { + return &cobra.Command{ + Use: "summary", + Annotations: cmdutil.Reads(), + Short: "Count open incidents by severity, and resolved ones with the time to resolve", + Long: `The organization's incidents at a glance: open ones by current severity +and those nobody acknowledged, incidents resolved in the last 7 and 30 +days, and the mean time from opened to resolved over the last 30 days. +For a pass or fail answer in CI use "pulsecheck status --fail-on".`, + Example: ` norcube pulsecheck incidents summary + norcube pulsecheck incidents summary -o json --query open.critical`, + Args: cobra.NoArgs, + RunE: cmdutil.Run(func(cmd *cobra.Command, _ []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + s, err := incidentSummary(cmd.Context(), c) + if err != nil { + return nil, err + } + return summaryObject(s), nil + }), + } +} + +func incidentSummary(ctx context.Context, c *pcContext) (pulsecheck.DtoIncidentSummary, error) { + res, err := c.API.GetIncidentSummaryWithResponse(ctx) + if err != nil { + return pulsecheck.DtoIncidentSummary{}, err + } + if res.JSON200 == nil { + return pulsecheck.DtoIncidentSummary{}, apiError(res.HTTPResponse, res.Body) + } + return *res.JSON200, nil +} + +func summaryFields(s pulsecheck.DtoIncidentSummary) []output.Field { + mttr := "—" + if s.MttrLast30dSeconds != nil { + mttr = duration(*s.MttrLast30dSeconds) + } + return []output.Field{ + {Name: "Open", Value: strconv.Itoa(s.Open.Total)}, + {Name: "Critical", Value: strconv.Itoa(s.Open.Critical)}, + {Name: "Warning", Value: strconv.Itoa(s.Open.Warning)}, + {Name: "Unacknowledged", Value: strconv.Itoa(s.Open.Unacknowledged)}, + {Name: "Resolved 7d", Value: strconv.Itoa(s.ResolvedLast7d)}, + {Name: "Resolved 30d", Value: strconv.Itoa(s.ResolvedLast30d)}, + {Name: "Mean time to resolve 30d", Value: mttr}, + } +} + +func summaryObject(s pulsecheck.DtoIncidentSummary) output.Object { + return output.Object{Value: s, Fields: summaryFields(s)} +} diff --git a/internal/cli/pulsecheck/monitor_data.go b/internal/cli/pulsecheck/monitor_data.go new file mode 100644 index 0000000..d0027bb --- /dev/null +++ b/internal/cli/pulsecheck/monitor_data.go @@ -0,0 +1,599 @@ +package pulsecheck + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/output" +) + +// ---------- results ---------- + +func newResultsCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "results", + Aliases: []string{"checks"}, + Short: "A monitor's check results", + } + cmd.AddCommand(newResultsListCmd(d)) + return cmd +} + +func newResultsListCmd(d deps) *cobra.Command { + var ( + pf cmdutil.PageFlags + since, until string + ) + cmd := &cobra.Command{ + Use: "list ", + Annotations: cmdutil.Reads(), + Short: "List a monitor's check results, newest first", + Long: `Lists the monitor's checks in [--since, --until), newest first; by default +the last 24 hours. Raw results are kept at least 30 days. JSON has every +detail of a result: timings, the certificate seen, the domain's +registration.`, + Example: ` norcube pulsecheck monitors results list "Shop" + norcube pulsecheck monitors results list "Shop" --since 7d --all-pages -o json --query "[?severity=='critical'].checkedAt"`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + params := pulsecheck.ListMonitorResultsParams{} + if err := timeRange(since, until, d.now(), ¶ms.From, ¶ms.To); err != nil { + return nil, err + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + m, err := getMonitor(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + page, err := cmdutil.Paginate(cmd.Context(), pf, func(ctx context.Context, cursor string, size int) ([]pulsecheck.DtoCheckResult, string, error) { + p := params + p.Limit = &size + if cursor != "" { + p.Cursor = &cursor + } + res, err := c.API.ListMonitorResultsWithResponse(ctx, m.Id, &p) + if err != nil { + return nil, "", err + } + if res.JSON200 == nil { + return nil, "", apiError(res.HTTPResponse, res.Body) + } + return res.JSON200.List, nextCursor(res.JSON200.Cursors), nil + }) + if err != nil { + return nil, err + } + return nil, page.Print(cmd, output.Table[pulsecheck.DtoCheckResult]{ + Headers: resultHeaders, + Style: output.Style{StatusColumn: 2}, + Rows: resultRow(string(m.Type)), + Items: page.Items, + }) + }), + } + addTimeFlags(cmd, &since, &until, "results") + cmdutil.AddPageFlags(cmd, &pf, defaultPageSize, maxItems) + return cmd +} + +func addTimeFlags(cmd *cobra.Command, since, until *string, what string) { + cmd.Flags().StringVar(since, "since", "", "Only "+what+" at or after this time: an RFC 3339 timestamp, a date or an age such as 24h or 7d") + cmd.Flags().StringVar(until, "until", "", "Only "+what+" before this time (timestamp, date or age)") +} + +// timeRange parses --since and --until into optional query parameters. +func timeRange(since, until string, now time.Time, from, to **time.Time) error { + if since != "" { + t, err := cmdutil.ParseTimeArg("since", since, now) + if err != nil { + return err + } + *from = &t + } + if until != "" { + t, err := cmdutil.ParseTimeArg("until", until, now) + if err != nil { + return err + } + *to = &t + } + if *from != nil && *to != nil && !(*from).Before(**to) { + return clierr.Usage(fmt.Errorf("--since must be before --until")) + } + return nil +} + +// ---------- status changes ---------- + +func newStatusChangesCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "status-changes", + Aliases: []string{"history"}, + Short: "When a monitor went up, down, or expiring, and for how long", + } + cmd.AddCommand(newStatusChangesListCmd(d)) + return cmd +} + +func newStatusChangesListCmd(d deps) *cobra.Command { + var pf cmdutil.PageFlags + cmd := &cobra.Command{ + Use: "list ", + Annotations: cmdutil.Reads(), + Short: "List every status change of a monitor, newest first", + Long: `Lists each time a check moved the monitor to another status: from, to, +when, how long it lasted (the newest one is still going) and what the +check said. Kept a year. Pausing is not a status change. JSON adds the +events in each span (a renewed certificate).`, + Example: ` norcube pulsecheck monitors status-changes list "Shop" + norcube pulsecheck monitors history list "Shop" -o json`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + m, err := getMonitor(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + page, err := cmdutil.Paginate(cmd.Context(), pf, func(ctx context.Context, cursor string, size int) ([]pulsecheck.DtoStatusChange, string, error) { + p := pulsecheck.ListMonitorStatusChangesParams{Limit: &size} + if cursor != "" { + p.Cursor = &cursor + } + res, err := c.API.ListMonitorStatusChangesWithResponse(ctx, m.Id, &p) + if err != nil { + return nil, "", err + } + if res.JSON200 == nil { + return nil, "", apiError(res.HTTPResponse, res.Body) + } + return res.JSON200.List, nextCursor(res.JSON200.Cursors), nil + }) + if err != nil { + return nil, err + } + typ := string(m.Type) + return nil, page.Print(cmd, output.Table[pulsecheck.DtoStatusChange]{ + Headers: []string{"CHANGED", "FROM", "TO", "FOR", "CONDITION", "MESSAGE"}, + MaxWidths: []int{0, 0, 0, 0, 0, 60}, + Style: output.Style{StatusColumn: 2}, + Rows: func(s pulsecheck.DtoStatusChange) []string { + return []string{ + output.WhenStringSeconds(s.ChangedAt), + statusWord(typ, string(s.From), ""), + statusWord(typ, string(s.To), s.Condition), + duration(s.DurationSeconds), + s.Condition, + strOr(s.Message), + } + }, + Items: page.Items, + }) + }), + } + cmdutil.AddPageFlags(cmd, &pf, defaultPageSize, maxItems) + return cmd +} + +// ---------- stats ---------- + +var statsRanges = []string{"24h", "7d", "30d", "90d"} + +func newStatsCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "stats", + Short: "A monitor's uptime and response times", + } + var rng string + get := &cobra.Command{ + Use: "get ", + Annotations: cmdutil.Reads(), + Short: "Show uptime, response times and check counts over a range", + Long: `Shows uptime ((ok + warning) / conclusive checks, HTTP monitors only), +average and maximum response time and check counts for the range ending +now. JSON adds the series: hourly buckets up to 7d, daily beyond. +Refreshed every few minutes.`, + Example: ` norcube pulsecheck monitors stats get "Shop" + norcube pulsecheck monitors stats get "Shop" --range 30d -o json --query uptimePercent`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + if err := oneOf("--range", rng, statsRanges); err != nil { + return nil, err + } + params := pulsecheck.GetMonitorStatsParams{Range: pulsecheck.GetMonitorStatsParamsRange(rng)} + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := monitorRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + res, err := c.API.GetMonitorStatsWithResponse(cmd.Context(), id, ¶ms) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + s := *res.JSON200 + return output.Object{Value: s, Fields: []output.Field{ + {Name: "From", Value: output.WhenString(s.From)}, + {Name: "To", Value: output.WhenString(s.To)}, + {Name: "Uptime", Value: percent(s.UptimePercent)}, + {Name: "Average", Value: ms(s.AvgMs)}, + {Name: "Slowest", Value: ms(s.MaxMs)}, + {Name: "Checks", Value: strconv.Itoa(s.Checks)}, + {Name: "OK", Value: strconv.Itoa(s.Ok)}, + {Name: "Warning", Value: strconv.Itoa(s.Warning)}, + {Name: "Critical", Value: strconv.Itoa(s.Critical)}, + {Name: "Inconclusive", Value: strconv.Itoa(s.Inconclusive)}, + }}, nil + }), + } + get.Flags().StringVar(&rng, "range", "24h", "Range ending now: 24h, 7d, 30d or 90d") + cmdutil.FlagEnum(get, "range", statsRanges...) + cmd.AddCommand(get) + return cmd +} + +// ---------- availability ---------- + +func newAvailabilityCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "availability", + Short: "A monitor's uptime and downtime per day", + } + var days int + get := &cobra.Command{ + Use: "get ", + Annotations: cmdutil.Reads(), + Short: "Show uptime and estimated downtime per UTC day", + Long: `One row per UTC day ending today, oldest first: check counts, uptime and +an estimate of the minutes spent down (HTTP monitors). A day without +checks has no uptime, never 100%.`, + Example: ` norcube pulsecheck monitors availability get "Shop" --days 30`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + params := pulsecheck.GetMonitorAvailabilityParams{} + if cmd.Flags().Changed("days") { + if days < 1 || days > 90 { + return nil, clierr.Usage(fmt.Errorf("--days must be between 1 and 90")) + } + params.Days = &days + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := monitorRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + res, err := c.API.GetMonitorAvailabilityWithResponse(cmd.Context(), id, ¶ms) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + return availabilityView(*res.JSON200), nil + }), + } + get.Flags().IntVar(&days, "days", 0, "Days ending today, 1 to 90 (default 90)") + cmd.AddCommand(get) + return cmd +} + +// availabilityView shows a table of days; JSON and YAML keep the whole +// answer (the range's totals too). +func availabilityView(a pulsecheck.DtoAvailability) output.View[pulsecheck.DtoDayAvailability] { + return output.View[pulsecheck.DtoDayAvailability]{Value: a, Table: output.Table[pulsecheck.DtoDayAvailability]{ + Headers: []string{"DAY", "UPTIME", "DOWNTIME", "CHECKS", "OK", "WARNING", "CRITICAL"}, + Style: output.NoStyle, + Rows: func(day pulsecheck.DtoDayAvailability) []string { + up := percent(day.UptimePercent) + if day.NoData { + up = "no data" + } + return []string{day.Date, up, fmt.Sprintf("%d min", day.DowntimeMinutes), strconv.Itoa(day.Checks), + strconv.Itoa(day.Ok), strconv.Itoa(day.Warning), strconv.Itoa(day.Critical)} + }, + Items: a.Days, + }} +} + +// ---------- certificate ---------- + +func newCertificateCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "certificate", + Aliases: []string{"cert"}, + Short: "The newest TLS certificate an SSL or HTTPS monitor saw", + } + cmd.AddCommand(&cobra.Command{ + Use: "get ", + Annotations: cmdutil.Reads(), + Short: "Show the monitor's newest certificate and when it expires", + Long: `Shows the newest certificate the monitor's checks saw: subject, issuer, +names, validity, whether the chain and hostname verify, and days left. SSL +monitors add the expiry thresholds and the next one to be crossed. Exits 3 +when no check has seen a certificate (plain HTTP and domain monitors).`, + Example: ` norcube pulsecheck monitors certificate get "API cert" + norcube pulsecheck monitors cert get "Shop" -o json --query certificate.notAfter`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := monitorRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + res, err := c.API.GetMonitorCertificateWithResponse(cmd.Context(), id) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + mc := *res.JSON200 + crt := mc.Certificate + f := []output.Field{ + {Name: "Subject", Value: crt.Subject}, + {Name: "Issuer", Value: crt.Issuer}, + {Name: "Names", Value: strings.Join(cmdutil.Deref(crt.DnsNames), ", ")}, + {Name: "Valid from", Value: output.WhenString(crt.NotBefore)}, + {Name: "Expires", Value: output.WhenString(crt.NotAfter)}, + {Name: "Days left", Value: strconv.Itoa(mc.DaysRemaining)}, + {Name: "Chain valid", Value: yesNo(crt.ChainValid)}, + {Name: "Hostname valid", Value: yesNo(crt.HostnameValid)}, + {Name: "Status", Value: resultWord("ssl", string(mc.Severity), mc.Condition)}, + {Name: "Serial", Value: strOr(crt.SerialNumber)}, + {Name: "SHA-256", Value: strOr(crt.FingerprintSha256)}, + {Name: "Seen", Value: output.WhenString(mc.CheckedAt)}, + } + alertDays := "—" + if len(mc.ThresholdsDays) > 0 { + alertDays = joinInts(mc.ThresholdsDays) + } + // Always present (SSL monitors only fill them), so -o text keeps + // its columns. + f = append(f, + output.Field{Name: "Alert at days", Value: alertDays}, + output.Field{Name: "Next alert", Value: output.WhenString(cmdutil.Deref(mc.NextThresholdAt))}, + output.Field{Name: "Next alert at days", Value: intOr(mc.NextThresholdDays)}, + ) + return output.Object{Value: mc, Fields: f}, nil + }), + }) + return cmd +} + +// ---------- alert settings ---------- + +var alertEvents = []string{"down", "warning", "expiring", "expired", "recovered"} + +func newAlertsCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "alerts", + Short: "Where and when a monitor alerts", + Long: `A monitor either follows the organization's defaults (its default +channels, or the members by email when none is default) or has its own +routes: which events go to which channels, how many failed checks open an +incident, how many good ones resolve it, and how often to remind.`, + } + cmd.AddCommand(newAlertsGetCmd(d), newAlertsSetCmd(d)) + return cmd +} + +func alertsObject(a pulsecheck.DtoMonitorAlerts) output.Object { + routes := "organization defaults" + if !a.UseDefaults { + parts := make([]string, 0, len(a.Routes)) + for _, r := range a.Routes { + ev := make([]string, len(r.Events)) + for i, e := range r.Events { + ev[i] = string(e) + } + parts = append(parts, r.ChannelId.String()+": "+strings.Join(ev, ",")) + } + routes = strings.Join(parts, "\n") + if len(parts) == 0 { + routes = "none (muted)" + } + } + reminder := "off" + if a.ReminderMinutes > 0 { + reminder = interval(a.ReminderMinutes * 60) + } + ev := make([]string, len(a.ApplicableEvents)) + for i, e := range a.ApplicableEvents { + ev[i] = string(e) + } + return output.Object{Value: a, Fields: []output.Field{ + {Name: "Routes", Value: routes}, + {Name: "Open after", Value: plural(a.ConfirmFailures, "failed check")}, + {Name: "Resolve after", Value: plural(a.ConfirmSuccesses, "good check")}, + {Name: "Remind every", Value: reminder}, + {Name: "Events", Value: strings.Join(ev, ", ")}, + }} +} + +func newAlertsGetCmd(d deps) *cobra.Command { + return &cobra.Command{ + Use: "get ", + Annotations: cmdutil.Reads(), + Short: "Show how a monitor alerts", + Example: ` norcube pulsecheck monitors alerts get "Shop"`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := monitorRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + res, err := c.API.GetMonitorAlertsWithResponse(cmd.Context(), id) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + return alertsObject(*res.JSON200), nil + }), + } +} + +func newAlertsSetCmd(d deps) *cobra.Command { + var ( + defaults, mute bool + routes []string + failures, successes int + reminder time.Duration + fromFile string + ) + cmd := &cobra.Command{ + Use: "set ", + Annotations: cmdutil.Writes(), + Short: "Set where and when a monitor alerts", + Long: `Replaces the monitor's alerting. --defaults returns it to the +organization's defaults. Otherwise give its routes, each a channel (id or +exact name) and the events it gets (down, warning, expiring, expired, +recovered), or --mute for no alerts; settings you leave out keep their +current values. Channels themselves are managed with "pulsecheck channels".`, + Example: ` norcube pulsecheck monitors alerts set "Shop" --route "On-call webhook=down,recovered" --route ops-email=down + norcube pulsecheck monitors alerts set "Shop" --confirm-failures 3 --reminder 30m + norcube pulsecheck monitors alerts set "Shop" --mute + norcube pulsecheck monitors alerts set "Shop" --defaults`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + set := cmd.Flags().Changed + custom := set("route") || mute || set("confirm-failures") || set("confirm-successes") || set("reminder") + switch { + case fromFile != "" && (defaults || custom): + return nil, clierr.Usage(fmt.Errorf("--from-file can't be combined with other flags")) + case defaults && custom: + return nil, clierr.Usage(fmt.Errorf("--defaults can't be combined with routes or settings")) + case mute && set("route"): + return nil, clierr.Usage(fmt.Errorf("--mute and --route can't be combined")) + case fromFile == "" && !defaults && !custom: + return nil, clierr.Usage(fmt.Errorf("nothing to set: pass --route, --mute, --defaults, a setting or --from-file")) + } + if set("reminder") && (reminder < 0 || reminder%time.Minute != 0) { + return nil, clierr.Usage(fmt.Errorf("--reminder takes whole minutes, e.g. 30m or 2h (0 for none)")) + } + type route struct { + channel string + events []pulsecheck.DtoMonitorAlertRouteEvents + } + var parsed []route + for _, r := range routes { + ch, evs, ok := strings.Cut(r, "=") + if !ok || strings.TrimSpace(ch) == "" || strings.TrimSpace(evs) == "" { + return nil, clierr.Usage(fmt.Errorf(`--route %q: write it as =[,...]`, r)) + } + var events []pulsecheck.DtoMonitorAlertRouteEvents + for _, e := range strings.Split(evs, ",") { + e = strings.TrimSpace(e) + if err := oneOf("--route event", e, alertEvents); err != nil { + return nil, err + } + events = append(events, pulsecheck.DtoMonitorAlertRouteEvents(e)) + } + parsed = append(parsed, route{strings.TrimSpace(ch), events}) + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := monitorRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + var body pulsecheck.DtoMonitorAlertsUpdate + switch { + case fromFile != "": + if err := readJSON(cmd, fromFile, "the alert settings", &body); err != nil { + return nil, err + } + case defaults: + t := true + body.UseDefaults = &t + default: + // Every field is required when not following the defaults: + // start from the current settings. + cur, err := c.API.GetMonitorAlertsWithResponse(cmd.Context(), id) + if err != nil { + return nil, err + } + if cur.JSON200 == nil { + return nil, apiError(cur.HTTPResponse, cur.Body) + } + a := *cur.JSON200 + f, s, rm := a.ConfirmFailures, a.ConfirmSuccesses, a.ReminderMinutes + if set("confirm-failures") { + f = failures + } + if set("confirm-successes") { + s = successes + } + if set("reminder") { + rm = int(reminder / time.Minute) + } + rs := a.Routes + if a.UseDefaults { + rs = []pulsecheck.DtoMonitorAlertRoute{} + } + if set("route") { + rs = make([]pulsecheck.DtoMonitorAlertRoute, 0, len(parsed)) + for _, r := range parsed { + chID, err := channelRef(cmd.Context(), c, r.channel) + if err != nil { + return nil, err + } + rs = append(rs, pulsecheck.DtoMonitorAlertRoute{ChannelId: chID, Events: r.events}) + } + } + if mute { + rs = []pulsecheck.DtoMonitorAlertRoute{} + } + fls := false + body = pulsecheck.DtoMonitorAlertsUpdate{UseDefaults: &fls, ConfirmFailures: &f, ConfirmSuccesses: &s, ReminderMinutes: &rm, Routes: &rs} + } + res, err := c.API.SetMonitorAlertsWithResponse(cmd.Context(), id, body) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + return alertsObject(*res.JSON200), nil + }), + } + cmd.Flags().BoolVar(&defaults, "defaults", false, "Follow the organization's default channels again") + cmd.Flags().StringArrayVar(&routes, "route", nil, `A route "=," (channel id or exact name; events down, warning, expiring, expired, recovered); repeatable, replaces the routes`) + cmd.Flags().BoolVar(&mute, "mute", false, "Send no alerts for this monitor") + cmd.Flags().IntVar(&failures, "confirm-failures", 0, "Failed checks in a row before an incident opens, 1 to 10") + cmd.Flags().IntVar(&successes, "confirm-successes", 0, "Good checks in a row before it resolves, 1 to 10") + cmd.Flags().DurationVar(&reminder, "reminder", 0, "Remind about an unacknowledged critical incident this often, e.g. 1h (0 for no reminders)") + cmd.Flags().StringVar(&fromFile, "from-file", "", "Read the API's alert settings body as JSON from this file (- for standard input)") + return cmd +} diff --git a/internal/cli/pulsecheck/monitor_write.go b/internal/cli/pulsecheck/monitor_write.go new file mode 100644 index 0000000..14f55bf --- /dev/null +++ b/internal/cli/pulsecheck/monitor_write.go @@ -0,0 +1,623 @@ +package pulsecheck + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net" + "net/url" + "slices" + "strings" + "time" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/output" +) + +// What `monitors create --type` accepts: the API's types plus keyword, an +// HTTP monitor that looks for a keyword (the API's "variant"). +var createTypes = []string{"http", "keyword", "ssl", "domain"} + +var ( + httpMethods = []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"} + keywordModes = []string{"present", "absent"} +) + +// Defaults for settings the API requires on create; the dashboard's create +// form starts from the same. +const ( + defaultHTTPInterval = time.Minute + defaultSSLInterval = time.Hour + defaultDomainInterval = 12 * time.Hour + defaultTimeout = 10 * time.Second + defaultMaxRedirects = 5 +) + +var defaultExpiryDays = []int{30, 14, 7} + +// Flags by monitor type, so a flag of another type is a usage error. +var ( + httpFlagNames = []string{"url", "method", "expect", "timeout", "slow", "no-follow-redirects", "max-redirects", + "insecure", "keyword", "keyword-mode", "keyword-case-sensitive", "no-keyword", "header", "secret-headers-file", + "clear-headers", "body-file", "body-content-type", "cert-expiry-days", "no-cert-watch", "domain-expiry-days", "no-domain-watch"} + sslFlagNames = []string{"host", "port", "server-name", "alert-days"} + domainFlagNames = []string{"domain", "alert-days"} +) + +// monitorFlags are the settings create and update share. +type monitorFlags struct { + name, description string + interval time.Duration + fromFile string + + // HTTP + url, method, keyword, keywordMode string + expect, headers []string + timeout, slow time.Duration + noFollow, insecure, caseSensitive bool + noKeyword, clearHeaders bool + maxRedirects int + secretHeadersFile, bodyFile, bodyType string + certDays, domainDays []int + noCertWatch, noDomainWatch bool + host, serverName, domain string + port int + alertDays []int +} + +func addMonitorFlags(cmd *cobra.Command, f *monitorFlags, update bool) { + fl := cmd.Flags() + if update { + fl.StringVar(&f.name, "name", "", "New name") + } + fl.StringVar(&f.description, "description", "", "A note on what the monitor is for") + fl.DurationVar(&f.interval, "interval", 0, "How often to check, e.g. 30s, 5m, 1h (default 1m for HTTP, 1h for SSL, 12h for domains; your plan sets the minimum)") + fl.StringVar(&f.fromFile, "from-file", "", "Read the request body as JSON from this file (- for standard input), in the API's shape; no other setting flags then") + + fl.StringVar(&f.url, "url", "", "HTTP: the URL to request") + fl.StringVar(&f.method, "method", "", "HTTP: request method (default GET)") + fl.StringSliceVar(&f.expect, "expect", nil, "HTTP: accepted status codes or ranges, e.g. 2xx, 301, 400-404 (repeat or comma-separate; default 2xx)") + fl.DurationVar(&f.timeout, "timeout", 0, "HTTP: give up on a request after this long, 1s to 30s (default 10s)") + fl.DurationVar(&f.slow, "slow", 0, "HTTP: warn when a response takes longer than this") + fl.BoolVar(&f.noFollow, "no-follow-redirects", false, "HTTP: judge the first response instead of following redirects") + fl.IntVar(&f.maxRedirects, "max-redirects", 0, "HTTP: redirects to follow at most (default 5)") + fl.BoolVar(&f.insecure, "insecure", false, "HTTP: don't verify the TLS certificate (it is still reported)") + fl.StringVar(&f.keyword, "keyword", "", "HTTP: text to look for in the response body (the first 256 KiB)") + fl.StringVar(&f.keywordMode, "keyword-mode", "", "HTTP: whether the keyword must be present (default) or absent") + fl.BoolVar(&f.caseSensitive, "keyword-case-sensitive", false, "HTTP: match the keyword's case") + fl.StringArrayVar(&f.headers, "header", nil, `HTTP: a request header "Name: value" (repeatable; replaces the plain headers on update)`) + fl.StringVar(&f.secretHeadersFile, "secret-headers-file", "", `HTTP: read secret headers ("Name: value" per line) from this file (- for standard input); stored encrypted, never shown again`) + fl.StringVar(&f.bodyFile, "body-file", "", "HTTP: send the request body read from this file (- for standard input)") + fl.StringVar(&f.bodyType, "body-content-type", "", "HTTP: Content-Type of --body-file") + fl.IntSliceVar(&f.certDays, "cert-expiry-days", nil, "HTTP: also watch the certificate, alerting this many days before it expires (https URLs; default on with 30,14,7)") + fl.BoolVar(&f.noCertWatch, "no-cert-watch", false, "HTTP: don't watch the certificate") + fl.IntSliceVar(&f.domainDays, "domain-expiry-days", nil, "HTTP: also watch the domain's registration, alerting this many days before it expires (default on with 30,14,7 for host names)") + fl.BoolVar(&f.noDomainWatch, "no-domain-watch", false, "HTTP: don't watch the domain's registration") + + fl.StringVar(&f.host, "host", "", "SSL: host whose certificate to check") + fl.IntVar(&f.port, "port", 0, "SSL: port (default 443)") + fl.StringVar(&f.serverName, "server-name", "", "SSL: SNI name to send, when it differs from --host") + fl.StringVar(&f.domain, "domain", "", "Domain: the registered domain, e.g. example.com (not www.example.com)") + fl.IntSliceVar(&f.alertDays, "alert-days", nil, "SSL and domain: alert this many days before expiry, up to 5 values (default 30,14,7)") + + if update { + fl.BoolVar(&f.noKeyword, "no-keyword", false, "HTTP: stop looking for a keyword") + fl.BoolVar(&f.clearHeaders, "clear-headers", false, "HTTP: remove every request header, secret ones too") + cmd.MarkFlagsMutuallyExclusive("keyword", "no-keyword") + cmd.MarkFlagsMutuallyExclusive("header", "clear-headers") + cmd.MarkFlagsMutuallyExclusive("secret-headers-file", "clear-headers") + } + cmd.MarkFlagsMutuallyExclusive("cert-expiry-days", "no-cert-watch") + cmd.MarkFlagsMutuallyExclusive("domain-expiry-days", "no-domain-watch") + cmdutil.FlagEnum(cmd, "method", httpMethods...) + cmdutil.FlagEnum(cmd, "keyword-mode", keywordModes...) +} + +// changedSettings lists the setting flags given on the command line. +func changedSettings(cmd *cobra.Command) []string { + var out []string + cmd.Flags().Visit(func(f *pflag.Flag) { + if slices.Contains(httpFlagNames, f.Name) || slices.Contains(sslFlagNames, f.Name) || slices.Contains(domainFlagNames, f.Name) { + out = append(out, f.Name) + } + }) + return out +} + +// checkFlagsFit refuses setting flags of another monitor type. +func checkFlagsFit(changed []string, monitorType string) error { + own := map[string][]string{"http": httpFlagNames, "ssl": sslFlagNames, "domain": domainFlagNames}[monitorType] + for _, n := range changed { + if !slices.Contains(own, n) { + return clierr.Usage(fmt.Errorf("--%s doesn't apply to %s monitors", n, monitorType)) + } + } + return nil +} + +func newMonitorCreateCmd(d deps) *cobra.Command { + var ( + f monitorFlags + typ string + ) + cmd := &cobra.Command{ + Use: "create ", + Annotations: cmdutil.Writes(), + Short: "Create a monitor; its first check runs right away", + Long: `Creates an enabled monitor of one type: + + http requests --url and expects --expect (default 2xx) within --timeout; + for https URLs it also watches the certificate and the domain's + registration unless --no-cert-watch / --no-domain-watch + keyword an HTTP monitor that also looks for --keyword in the body + (--keyword-mode absent: alerts when it appears) + ssl checks the certificate of --host:--port and alerts --alert-days + before it expires + domain checks the registration of --domain and alerts --alert-days + before it expires + +Settings not given start from the dashboard's defaults. For anything the +flags don't cover, pass the API's JSON body with --from-file (see "nrc api +pulsecheck POST /monitors"). Secret header values come from a file or +standard input only (--secret-headers-file), never from arguments. The +first check runs at once and is billed like a scheduled one.`, + Example: ` norcube pulsecheck monitors create "Shop" --type http --url https://shop.example.com/health + norcube pulsecheck monitors create "Login page" --type keyword --url https://example.com/login --keyword "Sign in" + norcube pulsecheck monitors create "API cert" --type ssl --host api.example.com --alert-days 30,7 + norcube pulsecheck monitors create "example.com" --type domain --domain example.com --interval 24h + printf 'Authorization: Bearer %s\n' "$TOKEN" | norcube pulsecheck monitors create "Admin API" --type http --url https://example.com/admin/health --secret-headers-file - + norcube pulsecheck monitors create --from-file monitor.json`, + Args: cobra.MaximumNArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + body, err := createBody(cmd, f, typ, args) + if err != nil { + return nil, err + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + res, err := c.API.CreateMonitorWithResponse(cmd.Context(), body) + if err != nil { + return nil, err + } + if res.JSON201 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + m := *res.JSON201 + return output.Done{ + Message: fmt.Sprintf("Created monitor %s (%s); its first check is running.", m.Name, m.Id), + Value: m, + Fields: []output.Field{{Value: m.Id.String()}, {Value: m.Name}}, + }, nil + }), + } + cmd.Flags().StringVar(&typ, "type", "", "Monitor type: http, keyword, ssl or domain") + cmdutil.FlagEnum(cmd, "type", createTypes...) + addMonitorFlags(cmd, &f, false) + return cmd +} + +// createBody builds and validates POST /monitors before any request. +func createBody(cmd *cobra.Command, f monitorFlags, typ string, args []string) (pulsecheck.DtoMonitorCreate, error) { + var body pulsecheck.DtoMonitorCreate + changed := changedSettings(cmd) + if f.fromFile != "" { + if typ != "" || len(changed) > 0 || cmd.Flags().Changed("interval") || cmd.Flags().Changed("description") { + return body, clierr.Usage(fmt.Errorf("--from-file can't be combined with --type or setting flags; put them in the file")) + } + if err := readJSON(cmd, f.fromFile, "the monitor", &body); err != nil { + return body, err + } + if len(args) == 1 { + body.Name = args[0] + } + return body, nil + } + if len(args) == 0 { + return body, clierr.Usage(fmt.Errorf("name the monitor: norcube pulsecheck monitors create --type ")) + } + if typ == "" { + return body, clierr.Usage(fmt.Errorf("--type is required: one of %s", strings.Join(createTypes, ", "))) + } + if err := oneOf("--type", typ, createTypes); err != nil { + return body, err + } + apiType := typ + if typ == "keyword" { + apiType = "http" + if f.keyword == "" { + return body, clierr.Usage(fmt.Errorf("--type keyword needs --keyword")) + } + } + if err := checkFlagsFit(changed, apiType); err != nil { + return body, err + } + body.Name = strings.TrimSpace(args[0]) + body.Type = pulsecheck.DtoMonitorCreateType(apiType) + if f.description != "" { + body.Description = &f.description + } + iv := map[string]time.Duration{"http": defaultHTTPInterval, "ssl": defaultSSLInterval, "domain": defaultDomainInterval}[apiType] + if cmd.Flags().Changed("interval") { + iv = f.interval + } + secs, err := intervalSeconds(iv) + if err != nil { + return body, err + } + body.IntervalSeconds = secs + set := cmd.Flags().Changed + switch apiType { + case "http": + if f.url == "" { + return body, clierr.Usage(fmt.Errorf("--url is required for %s monitors", typ)) + } + h, err := httpSettings(cmd, f, nil, set) + if err != nil { + return body, err + } + body.Http = h + case "ssl": + if f.host == "" { + return body, clierr.Usage(fmt.Errorf("--host is required for ssl monitors")) + } + body.Ssl = sslSettings(f, nil, set) + case "domain": + if f.domain == "" { + return body, clierr.Usage(fmt.Errorf("--domain is required for domain monitors")) + } + body.Domain = domainSettings(f, nil, set) + } + return body, nil +} + +func newMonitorUpdateCmd(d deps) *cobra.Command { + var f monitorFlags + cmd := &cobra.Command{ + Use: "update ", + Annotations: cmdutil.Writes(), + Short: "Change a monitor's name, interval or check settings", + Long: `Changes only what you pass. Check settings start from the monitor's +current ones, so "--timeout 5s" keeps everything else; secret headers keep +their stored values unless --secret-headers-file replaces them (and only +while the URL keeps its origin). The type can't change. --from-file sends +the API's PATCH body as it is (a settings object there replaces the +settings as a whole).`, + Example: ` norcube pulsecheck monitors update "Shop" --interval 30s --slow 1500ms + norcube pulsecheck monitors update "Shop" --name "Shop (EU)" --expect 2xx,301 + norcube pulsecheck monitors update "API cert" --alert-days 21,7 + norcube pulsecheck monitors update 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f --from-file patch.json`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + changed := changedSettings(cmd) + others := cmd.Flags().Changed("name") || cmd.Flags().Changed("description") || cmd.Flags().Changed("interval") + var body pulsecheck.DtoMonitorUpdate + if f.fromFile != "" { + if len(changed) > 0 || others { + return nil, clierr.Usage(fmt.Errorf("--from-file can't be combined with setting flags; put them in the file")) + } + if err := readJSON(cmd, f.fromFile, "the changes", &body); err != nil { + return nil, err + } + } else if len(changed) == 0 && !others { + return nil, clierr.Usage(fmt.Errorf("nothing to change: pass a setting flag (see --help) or --from-file")) + } + if cmd.Flags().Changed("interval") { + secs, err := intervalSeconds(f.interval) + if err != nil { + return nil, err + } + body.IntervalSeconds = &secs + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + m, err := getMonitor(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + if err := checkFlagsFit(changed, string(m.Type)); err != nil { + return nil, err + } + if cmd.Flags().Changed("name") { + n := strings.TrimSpace(f.name) + body.Name = &n + } + if cmd.Flags().Changed("description") { + body.Description = &f.description + } + if len(changed) > 0 { + set := cmd.Flags().Changed + switch string(m.Type) { + case "http": + h, err := httpSettings(cmd, f, m.Http, set) + if err != nil { + return nil, err + } + body.Http = h + case "ssl": + body.Ssl = sslSettings(f, m.Ssl, set) + case "domain": + body.Domain = domainSettings(f, m.Domain, set) + } + } + res, err := c.API.UpdateMonitorWithResponse(cmd.Context(), m.Id, body) + if err != nil { + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + u := *res.JSON200 + return output.Done{ + Message: fmt.Sprintf("Updated monitor %s (%s).", u.Name, u.Id), + Value: u, + Fields: []output.Field{{Value: u.Id.String()}, {Value: u.Name}}, + }, nil + }), + } + addMonitorFlags(cmd, &f, true) + return cmd +} + +func intervalSeconds(d time.Duration) (int, error) { + if d < time.Second || d%time.Second != 0 { + return 0, clierr.Usage(fmt.Errorf("--interval %s: use whole seconds, e.g. 30s, 5m or 1h", d)) + } + return int(d / time.Second), nil +} + +// httpSettings builds the HTTP settings object: from base (the monitor's +// current settings) or the defaults, with the flags given applied. +func httpSettings(cmd *cobra.Command, f monitorFlags, base *pulsecheck.DtoHTTPSettings, set func(string) bool) (*pulsecheck.DtoHTTPSettingsInput, error) { + in := &pulsecheck.DtoHTTPSettingsInput{ + Method: "GET", ExpectedStatus: []string{"2xx"}, TimeoutMs: int(defaultTimeout / time.Millisecond), + FollowRedirects: true, MaxRedirects: defaultMaxRedirects, VerifyTls: true, + } + if base != nil { + in.Url, in.Method, in.ExpectedStatus = base.Url, pulsecheck.DtoHTTPSettingsInputMethod(base.Method), base.ExpectedStatus + in.TimeoutMs, in.SlowThresholdMs = base.TimeoutMs, base.SlowThresholdMs + in.FollowRedirects, in.MaxRedirects, in.VerifyTls = base.FollowRedirects, base.MaxRedirects, base.VerifyTls + in.Keyword, in.RequestBody, in.RequestBodyContentType = base.Keyword, base.RequestBody, base.RequestBodyContentType + if base.Keyword != nil { + cs := base.KeywordCaseSensitive + in.KeywordCaseSensitive = &cs + if base.KeywordMode != nil { + km := pulsecheck.DtoHTTPSettingsInputKeywordMode(*base.KeywordMode) + in.KeywordMode = &km + } + } + headers := make([]pulsecheck.DtoHTTPHeaderInput, 0, len(base.Headers)) + for _, h := range base.Headers { + secret := h.Secret + // A secret header without a value keeps its stored one. + headers = append(headers, pulsecheck.DtoHTTPHeaderInput{Name: h.Name, Secret: &secret, Value: h.Value}) + } + in.Headers = &headers + if base.CertificateExpiry != nil { + in.CertificateExpiry = &pulsecheck.DtoExpiryWatchInput{ThresholdsDays: base.CertificateExpiry.ThresholdsDays} + } + if base.DomainExpiry != nil { + in.DomainExpiry = &pulsecheck.DtoExpiryWatchInput{ThresholdsDays: base.DomainExpiry.ThresholdsDays} + } + } + if set("url") { + in.Url = f.url + } + if set("method") { + m := strings.ToUpper(f.method) + if err := oneOf("--method", m, httpMethods); err != nil { + return nil, err + } + in.Method = pulsecheck.DtoHTTPSettingsInputMethod(m) + } + if set("expect") { + in.ExpectedStatus = f.expect + } + if set("timeout") { + in.TimeoutMs = int(f.timeout / time.Millisecond) + } + if set("slow") { + v := int(f.slow / time.Millisecond) + in.SlowThresholdMs = &v + } + if set("no-follow-redirects") { + in.FollowRedirects = !f.noFollow + } + if set("max-redirects") { + in.MaxRedirects = f.maxRedirects + } + if set("insecure") { + in.VerifyTls = !f.insecure + } + if set("keyword") { + in.Keyword = &f.keyword + } + if set("no-keyword") && f.noKeyword { + in.Keyword, in.KeywordMode, in.KeywordCaseSensitive = nil, nil, nil + } + if set("keyword-mode") { + if err := oneOf("--keyword-mode", f.keywordMode, keywordModes); err != nil { + return nil, err + } + km := pulsecheck.DtoHTTPSettingsInputKeywordMode(f.keywordMode) + in.KeywordMode = &km + } + if set("keyword-case-sensitive") { + in.KeywordCaseSensitive = &f.caseSensitive + } + if (set("keyword-mode") || set("keyword-case-sensitive")) && in.Keyword == nil { + return nil, clierr.Usage(fmt.Errorf("--keyword-mode and --keyword-case-sensitive need a keyword (--keyword)")) + } + if err := applyHeaders(cmd, f, in, set); err != nil { + return nil, err + } + if set("body-file") { + b, err := cmdutil.ReadText(cmd.InOrStdin(), "", f.bodyFile, "the request body") + if err != nil { + return nil, err + } + in.RequestBody = &b + } + if set("body-content-type") { + in.RequestBodyContentType = &f.bodyType + } + if base == nil { + // New monitors watch an https URL's certificate and a host name's + // domain, like the dashboard's create form. + if u, err := url.Parse(in.Url); err == nil && u.Scheme == "https" { + if !f.noCertWatch { + in.CertificateExpiry = &pulsecheck.DtoExpiryWatchInput{ThresholdsDays: defaultExpiryDays} + } + if !f.noDomainWatch && net.ParseIP(u.Hostname()) == nil && strings.Contains(u.Hostname(), ".") { + in.DomainExpiry = &pulsecheck.DtoExpiryWatchInput{ThresholdsDays: defaultExpiryDays} + } + } + } + if set("cert-expiry-days") { + in.CertificateExpiry = &pulsecheck.DtoExpiryWatchInput{ThresholdsDays: f.certDays} + } + if f.noCertWatch { + in.CertificateExpiry = nil + } + if set("domain-expiry-days") { + in.DomainExpiry = &pulsecheck.DtoExpiryWatchInput{ThresholdsDays: f.domainDays} + } + if f.noDomainWatch { + in.DomainExpiry = nil + } + return in, nil +} + +// applyHeaders sets the request headers: --header replaces the plain ones, +// --secret-headers-file the secret ones, --clear-headers removes all. +func applyHeaders(cmd *cobra.Command, f monitorFlags, in *pulsecheck.DtoHTTPSettingsInput, set func(string) bool) error { + current := []pulsecheck.DtoHTTPHeaderInput{} + if in.Headers != nil { + current = *in.Headers + } + if f.clearHeaders { + current = nil + } + split := func(secret bool) (keep []pulsecheck.DtoHTTPHeaderInput) { + for _, h := range current { + if cmdutil.Deref(h.Secret) != secret { + keep = append(keep, h) + } + } + return keep + } + if set("header") { + plain := make([]pulsecheck.DtoHTTPHeaderInput, 0, len(f.headers)) + for _, raw := range f.headers { + h, err := parseHeader(raw, "--header") + if err != nil { + return err + } + plain = append(plain, h) + } + current = append(split(false), plain...) + } + if set("secret-headers-file") { + text, err := cmdutil.ReadText(cmd.InOrStdin(), "", f.secretHeadersFile, "the secret headers") + if err != nil { + return err + } + var secrets []pulsecheck.DtoHTTPHeaderInput + for _, line := range strings.Split(text, "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + h, err := parseHeader(line, "--secret-headers-file") + if err != nil { + return err + } + t := true + h.Secret = &t + secrets = append(secrets, h) + } + current = append(split(true), secrets...) + } + in.Headers = ¤t + return nil +} + +// parseHeader reads "Name: value". The error never repeats the value: it +// may be a secret. +func parseHeader(raw, flag string) (pulsecheck.DtoHTTPHeaderInput, error) { + name, value, ok := strings.Cut(raw, ":") + name, value = strings.TrimSpace(name), strings.TrimSpace(value) + if !ok || name == "" || strings.ContainsAny(name, " \t") { + return pulsecheck.DtoHTTPHeaderInput{}, clierr.Usage(fmt.Errorf(`%s: write each header as "Name: value"`, flag)) + } + return pulsecheck.DtoHTTPHeaderInput{Name: name, Value: &value}, nil +} + +func sslSettings(f monitorFlags, base *pulsecheck.DtoSSLSettings, set func(string) bool) *pulsecheck.DtoSSLSettingsInput { + in := &pulsecheck.DtoSSLSettingsInput{Port: 443, ExpiryThresholdsDays: defaultExpiryDays} + if base != nil { + in.Host, in.Port, in.ServerName, in.ExpiryThresholdsDays = base.Host, base.Port, base.ServerName, base.ExpiryThresholdsDays + } + if set("host") { + in.Host = f.host + } + if set("port") { + in.Port = f.port + } + if set("server-name") { + in.ServerName = &f.serverName + } + if set("alert-days") { + in.ExpiryThresholdsDays = f.alertDays + } + return in +} + +func domainSettings(f monitorFlags, base *pulsecheck.DtoDomainSettings, set func(string) bool) *pulsecheck.DtoDomainSettingsInput { + in := &pulsecheck.DtoDomainSettingsInput{ExpiryThresholdsDays: defaultExpiryDays} + if base != nil { + in.Domain, in.ExpiryThresholdsDays = base.Domain, base.ExpiryThresholdsDays + } + if set("domain") { + in.Domain = f.domain + } + if set("alert-days") { + in.ExpiryThresholdsDays = f.alertDays + } + return in +} + +// readJSON decodes a JSON request body from a file or standard input, +// refusing members the API doesn't have (as the API does) before any +// request. +func readJSON(cmd *cobra.Command, path, what string, v any) error { + text, err := cmdutil.ReadText(cmd.InOrStdin(), "", path, what) + if err != nil { + return err + } + dec := json.NewDecoder(bytes.NewReader([]byte(text))) + dec.DisallowUnknownFields() + if err := dec.Decode(v); err != nil { + return clierr.Usage(fmt.Errorf("%s in %s is not valid: %w", what, inputName(path), err)) + } + if dec.Decode(new(json.RawMessage)) != io.EOF { + return clierr.Usage(fmt.Errorf("%s in %s has more than one JSON value", what, inputName(path))) + } + return nil +} + +func inputName(path string) string { + if path == "-" { + return "standard input" + } + return path +} diff --git a/internal/cli/pulsecheck/monitors.go b/internal/cli/pulsecheck/monitors.go new file mode 100644 index 0000000..5f5fe54 --- /dev/null +++ b/internal/cli/pulsecheck/monitors.go @@ -0,0 +1,402 @@ +package pulsecheck + +import ( + "context" + "errors" + "fmt" + "net/http" + "time" + + "github.com/google/uuid" + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/output" +) + +func newMonitorsCmd(d deps) *cobra.Command { + cmd := &cobra.Command{ + Use: "monitors", + Aliases: []string{"monitor"}, + Short: "Create, inspect and manage monitors and their check history", + Long: `A monitor checks one thing on a schedule: an HTTP endpoint (optionally +for a keyword), an SSL certificate, or a domain's registration. Commands +that take a accept its id or its exact name.`, + } + cmd.AddCommand( + newMonitorListCmd(d), + newMonitorGetCmd(d), + newMonitorCreateCmd(d), + newMonitorUpdateCmd(d), + newMonitorDeleteCmd(d), + newMonitorPauseCmd(d), + newMonitorResumeCmd(d), + newMonitorRunCmd(d), + newMonitorBulkCmd(d), + newResultsCmd(d), + newStatusChangesCmd(d), + newStatsCmd(d), + newAvailabilityCmd(d), + newCertificateCmd(d), + newAlertsCmd(d), + ) + return cmd +} + +// Values of the list filters, as the API accepts them. +var ( + monitorTypes = []string{"http", "ssl", "domain"} + monitorStatuses = []string{"pending", "ok", "warning", "critical", "paused"} + monitorSorts = []string{"status", "name", "lastChecked", "uptime", "created"} +) + +func newMonitorListCmd(d deps) *cobra.Command { + var ( + pf cmdutil.PageFlags + typ, status, search, order string + history bool + ) + cmd := &cobra.Command{ + Use: "list", + Annotations: cmdutil.Reads(), + Short: "List monitors with their current status", + Long: `Lists the organization's monitors, by default the ones that need +attention first (critical, warning, pending, ok, paused, then by name). +--status filters by the overall status: the worse of the monitor's own +status and the certificate and domain it watches.`, + Example: ` norcube pulsecheck monitors list + norcube pulsecheck monitors list --status critical --type http + norcube pulsecheck monitors list --search shop --sort uptime --all-pages -o json`, + Args: cobra.NoArgs, + RunE: cmdutil.Run(func(cmd *cobra.Command, _ []string) (any, error) { + params := pulsecheck.ListMonitorsParams{} + if typ != "" { + if err := oneOf("--type", typ, monitorTypes); err != nil { + return nil, err + } + t := pulsecheck.ListMonitorsParamsType(typ) + params.Type = &t + } + if status != "" { + if err := oneOf("--status", status, monitorStatuses); err != nil { + return nil, err + } + s := pulsecheck.ListMonitorsParamsStatus(status) + params.Status = &s + } + if order != "" { + if err := oneOf("--sort", order, monitorSorts); err != nil { + return nil, err + } + s := pulsecheck.ListMonitorsParamsSort(order) + params.Sort = &s + } + if search != "" { + params.Q = &search + } + if history { + h := pulsecheck.ListMonitorsParamsInclude("history") + params.Include = &h + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + page, err := cmdutil.Paginate(cmd.Context(), pf, func(ctx context.Context, cursor string, size int) ([]pulsecheck.DtoMonitor, string, error) { + p := params + p.Limit = &size + if cursor != "" { + p.Cursor = &cursor + } + res, err := c.API.ListMonitorsWithResponse(ctx, &p) + if err != nil { + return nil, "", err + } + if res.JSON200 == nil { + return nil, "", apiError(res.HTTPResponse, res.Body) + } + return res.JSON200.List, nextCursor(res.JSON200.Cursors), nil + }) + if err != nil { + return nil, err + } + return nil, page.Print(cmd, monitorTable(page.Items)) + }), + } + cmd.Flags().StringVar(&typ, "type", "", "Only monitors of this type: http, ssl or domain") + cmd.Flags().StringVar(&status, "status", "", "Only monitors with this overall status: pending, ok, warning, critical or paused") + cmd.Flags().StringVar(&search, "search", "", "Only monitors whose name or target contains this text") + cmd.Flags().StringVar(&order, "sort", "", "Order: status (default), name, lastChecked, uptime (lowest first) or created (newest first)") + cmd.Flags().BoolVar(&history, "history", false, "Include each monitor's newest 60 results (JSON and YAML only)") + cmdutil.FlagEnum(cmd, "type", monitorTypes...) + cmdutil.FlagEnum(cmd, "status", monitorStatuses...) + cmdutil.FlagEnum(cmd, "sort", monitorSorts...) + cmdutil.AddPageFlags(cmd, &pf, defaultPageSize, maxItems) + return cmd +} + +func newMonitorGetCmd(d deps) *cobra.Command { + return &cobra.Command{ + Use: "get ", + Annotations: cmdutil.Reads(), + Short: "Show a monitor's settings and current status", + Long: "Shows the monitor, its check settings (secret header values are never returned), its status with the reason, and the certificate and domain it watches.", + Example: ` norcube pulsecheck monitors get "Shop API" + norcube pulsecheck monitors get 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f -o json`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + m, err := getMonitor(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + return monitorObject(m), nil + }), + } +} + +// getMonitor resolves ref and fetches the monitor. +func getMonitor(ctx context.Context, c *pcContext, ref string) (pulsecheck.DtoMonitor, error) { + id, err := monitorRef(ctx, c, ref) + if err != nil { + return pulsecheck.DtoMonitor{}, err + } + res, err := c.API.GetMonitorWithResponse(ctx, id) + if err != nil { + return pulsecheck.DtoMonitor{}, err + } + if res.JSON200 == nil { + return pulsecheck.DtoMonitor{}, apiError(res.HTTPResponse, res.Body) + } + return *res.JSON200, nil +} + +func newMonitorDeleteCmd(d deps) *cobra.Command { + var yes bool + cmd := &cobra.Command{ + Use: "delete ", + Annotations: cmdutil.Writes(), + Short: "Delete a monitor and its whole check history", + Long: `Deletes the monitor with its results, status history and incidents. +To stop checks but keep the history, use "monitors pause". A monitor that +belongs to another Norcube product (a DomainRadar saved domain's expiry +alerts) can't be deleted here (exit 8): remove it in that product.`, + Example: ` norcube pulsecheck monitors delete "Old landing page" + norcube pulsecheck monitors delete 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f --yes`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := monitorRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + if ok, err := cmdutil.Confirm(fmt.Sprintf("Delete monitor %s and its whole check history? This can't be undone", args[0]), yes); err != nil || !ok { + return nil, cmdutil.Cancelled(cmd, err) + } + res, err := c.API.DeleteMonitorWithResponse(cmd.Context(), id) + if err != nil { + return nil, err + } + if res.StatusCode() != http.StatusNoContent { + return nil, apiError(res.HTTPResponse, res.Body) + } + return output.Done{ + Message: fmt.Sprintf("Deleted monitor %s.", args[0]), + Value: deleted{ID: id.String(), Deleted: true}, + Fields: []output.Field{{Value: id.String()}}, + }, nil + }), + } + cmd.Flags().BoolVar(&yes, "yes", false, "Don't ask for confirmation") + return cmd +} + +// deleted is what delete commands print as JSON. +type deleted struct { + ID string `json:"id" yaml:"id"` + Deleted bool `json:"deleted" yaml:"deleted"` +} + +// monitorAction is pause or resume of one monitor. +type monitorAction struct { + use, short, long, example, done string + call func(ctx context.Context, c *pcContext, id uuid.UUID) (*pulsecheck.DtoMonitor, *http.Response, []byte, error) +} + +func newMonitorPauseCmd(d deps) *cobra.Command { + return newMonitorActionCmd(d, monitorAction{ + use: "pause ", + short: "Stop a monitor's scheduled checks", + long: `Stops scheduled checks; the history stays. Pausing closes the monitor's +open incident without alerting. Idempotent.`, + example: ` norcube pulsecheck monitors pause "Shop API"`, + done: "Paused", + call: func(ctx context.Context, c *pcContext, id uuid.UUID) (*pulsecheck.DtoMonitor, *http.Response, []byte, error) { + res, err := c.API.PauseMonitorWithResponse(ctx, id) + if err != nil { + return nil, nil, nil, err + } + return res.JSON200, res.HTTPResponse, res.Body, nil + }, + }) +} + +func newMonitorResumeCmd(d deps) *cobra.Command { + return newMonitorActionCmd(d, monitorAction{ + use: "resume ", + short: "Restart a paused monitor's scheduled checks", + long: `Restarts scheduled checks; the next one runs right away unless the last +one is less than an interval old. Idempotent.`, + example: ` norcube pulsecheck monitors resume "Shop API"`, + done: "Resumed", + call: func(ctx context.Context, c *pcContext, id uuid.UUID) (*pulsecheck.DtoMonitor, *http.Response, []byte, error) { + res, err := c.API.ResumeMonitorWithResponse(ctx, id) + if err != nil { + return nil, nil, nil, err + } + return res.JSON200, res.HTTPResponse, res.Body, nil + }, + }) +} + +func newMonitorActionCmd(d deps, a monitorAction) *cobra.Command { + return &cobra.Command{ + Use: a.use, + Annotations: cmdutil.Writes(), + Short: a.short, + Long: a.long, + Example: a.example, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + c, err := d.client(cmd) + if err != nil { + return nil, err + } + id, err := monitorRef(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + m, resp, body, err := a.call(cmd.Context(), c, id) + if err != nil { + return nil, err + } + if m == nil { + return nil, apiError(resp, body) + } + return output.Done{ + Message: fmt.Sprintf("%s monitor %s (%s).", a.done, m.Name, m.Id), + Value: *m, + Fields: []output.Field{{Value: m.Id.String()}, {Value: string(m.Status)}}, + }, nil + }), + } +} + +// Failure thresholds of `monitors run --wait`. +var failOnValues = []string{"critical", "warning"} + +const runWaitTimeout = 2 * time.Minute + +func newMonitorRunCmd(d deps) *cobra.Command { + var ( + wf cmdutil.WaitFlags + failOn string + ) + cmd := &cobra.Command{ + Use: "run ", + Annotations: cmdutil.Writes(), + Short: "Run a monitor's check now and show the result", + Long: `Runs the monitor's check right away (paused monitors too) and prints the +stored result. The check is billed like a scheduled one and rate limited +(200 per user and 600 per organization an hour). + +The check runs while the command waits, so the result is always final. +--wait makes the result the command's outcome, for deploy pipelines: it +exits 1 with code job_failed (the result in "details") when the check +found the monitor critical or couldn't reach a verdict (inconclusive), or +with --fail-on warning also when it found a warning, and prints nothing +on stdout then; it exits 7 when no result arrives within --wait-timeout. Without --wait the command exits 0 +whatever the check found.`, + Example: ` norcube pulsecheck monitors run "Shop API" + # Fail a deploy when the site is down after it + norcube pulsecheck monitors run "Shop API" --wait + norcube pulsecheck monitors run 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f --wait --fail-on warning -o json`, + Args: cobra.ExactArgs(1), + RunE: cmdutil.Run(func(cmd *cobra.Command, args []string) (any, error) { + if failOn != "" { + if !wf.Wait { + return nil, clierr.Usage(fmt.Errorf("--fail-on needs --wait")) + } + if err := oneOf("--fail-on", failOn, failOnValues); err != nil { + return nil, err + } + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + m, err := getMonitor(cmd.Context(), c, args[0]) + if err != nil { + return nil, err + } + ctx := cmd.Context() + if wf.Wait && wf.Timeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, wf.Timeout) + defer cancel() + } + res, err := c.API.RunMonitorCheckWithResponse(ctx, m.Id) + if err != nil { + if wf.Wait && errors.Is(err, context.DeadlineExceeded) && ctx.Err() != nil { + return nil, cmdutil.ErrWaitTimeout + } + return nil, err + } + if res.JSON200 == nil { + return nil, apiError(res.HTTPResponse, res.Body) + } + r := *res.JSON200 + if wf.Wait && checkFailed(string(r.Severity), failOn) { + // Like every failed --wait: nothing on stdout, the result + // in the error's details. + return nil, cmdutil.JobFailed(fmt.Sprintf("the check of %s found it %s (%s)", m.Name, + resultWord(string(m.Type), string(r.Severity), r.Condition), r.Condition), r) + } + return resultObject(string(m.Type), r), nil + }), + } + cmdutil.AddWaitFlags(cmd, &wf, "check", runWaitTimeout) + cmd.Flags().StringVar(&failOn, "fail-on", "", "With --wait, the severity that fails the command: critical (default) or warning (inconclusive always fails)") + cmdutil.FlagEnum(cmd, "fail-on", failOnValues...) + return cmd +} + +// checkFailed reports whether a check result's severity fails a --wait: +// critical and inconclusive always, warning with --fail-on warning. +func checkFailed(severity, failOn string) bool { + switch severity { + case "critical", "inconclusive": + return true + case "warning": + return failOn == "warning" + } + return false +} + +// oneOf validates an enum flag before any request. +func oneOf(flag, v string, allowed []string) error { + for _, a := range allowed { + if v == a { + return nil + } + } + return clierr.Usage(fmt.Errorf("%s %q: one of %v", flag, v, allowed)) +} diff --git a/internal/cli/pulsecheck/resolve.go b/internal/cli/pulsecheck/resolve.go new file mode 100644 index 0000000..72cca4a --- /dev/null +++ b/internal/cli/pulsecheck/resolve.go @@ -0,0 +1,111 @@ +package pulsecheck + +import ( + "context" + "fmt" + "strings" + + "github.com/google/uuid" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/clierr" +) + +// monitorRef resolves a monitor named on the command line: its id, or its +// exact name (case-insensitive). A name that matches no monitor is a 404 +// (exit 3); one that matches several is a usage error naming their ids. +func monitorRef(ctx context.Context, c *pcContext, ref string) (uuid.UUID, error) { + ref = strings.TrimSpace(ref) + if id, err := uuid.Parse(ref); err == nil { + return id, nil + } + if ref == "" { + return uuid.Nil, clierr.Usage(fmt.Errorf("no monitor given")) + } + q := ref + limit := maxPageSize + var matches []pulsecheck.DtoMonitor + params := &pulsecheck.ListMonitorsParams{Q: &q, Limit: &limit} + for { + res, err := c.API.ListMonitorsWithResponse(ctx, params) + if err != nil { + return uuid.Nil, err + } + if res.JSON200 == nil { + return uuid.Nil, apiError(res.HTTPResponse, res.Body) + } + for _, m := range res.JSON200.List { + if strings.EqualFold(m.Name, ref) { + matches = append(matches, m) + } + } + next := nextCursor(res.JSON200.Cursors) + if next == "" || len(matches) > 1 { + break + } + params.Cursor = &next + } + switch len(matches) { + case 0: + return uuid.Nil, &clierr.Error{Code: clierr.CodeNotFound, Message: fmt.Sprintf("no monitor named %q", ref), + Hint: "List them with `norcube pulsecheck monitors list --search " + ref + "`."} + case 1: + return matches[0].Id, nil + } + ids := make([]string, len(matches)) + for i, m := range matches { + ids[i] = m.Id.String() + } + return uuid.Nil, clierr.Usage(fmt.Errorf("%d monitors are named %q: name one by id (%s)", len(matches), ref, strings.Join(ids, ", "))) +} + +// idArg parses an id argument (incidents, channels) before any request. +func idArg(what, v string) (uuid.UUID, error) { + id, err := uuid.Parse(strings.TrimSpace(v)) + if err != nil { + return uuid.Nil, clierr.Usage(fmt.Errorf("%q is not a %s id (a UUID such as 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f)", v, what)) + } + return id, nil +} + +// channelRef resolves an alert channel by id or exact name +// (case-insensitive), the same way monitorRef does. +func channelRef(ctx context.Context, c *pcContext, ref string) (uuid.UUID, error) { + ref = strings.TrimSpace(ref) + if id, err := uuid.Parse(ref); err == nil { + return id, nil + } + if ref == "" { + return uuid.Nil, clierr.Usage(fmt.Errorf("no alert channel given")) + } + limit := maxPageSize + params := &pulsecheck.ListAlertChannelsParams{Limit: &limit} + var ids []string + for { + res, err := c.API.ListAlertChannelsWithResponse(ctx, params) + if err != nil { + return uuid.Nil, err + } + if res.JSON200 == nil { + return uuid.Nil, apiError(res.HTTPResponse, res.Body) + } + for _, ch := range res.JSON200.List { + if strings.EqualFold(ch.Name, ref) { + ids = append(ids, ch.Id.String()) + } + } + next := nextCursor(res.JSON200.Cursors) + if next == "" { + break + } + params.Cursor = &next + } + switch len(ids) { + case 0: + return uuid.Nil, &clierr.Error{Code: clierr.CodeNotFound, Message: fmt.Sprintf("no alert channel named %q", ref), + Hint: "List them with `norcube pulsecheck channels list`."} + case 1: + return uuid.MustParse(ids[0]), nil + } + return uuid.Nil, clierr.Usage(fmt.Errorf("%d alert channels are named %q: name one by id (%s)", len(ids), ref, strings.Join(ids, ", "))) +} diff --git a/internal/cli/pulsecheck/status.go b/internal/cli/pulsecheck/status.go new file mode 100644 index 0000000..551566d --- /dev/null +++ b/internal/cli/pulsecheck/status.go @@ -0,0 +1,193 @@ +package pulsecheck + +import ( + "context" + "fmt" + "strings" + + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cli/internal/api/pulsecheck" + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/output" +) + +// What `status --fail-on` accepts, from the strictest to none. +var statusFailOn = []string{"warning", "critical", "none"} + +// statusReport is what `pulsecheck status` prints as JSON. +type statusReport struct { + // Status is the organization's verdict from its open incidents: + // critical, warning or ok. + Status string `json:"status" yaml:"status"` + Incidents pulsecheck.DtoIncidentSummary `json:"incidents" yaml:"incidents"` + Monitors monitorCounts `json:"monitors" yaml:"monitors"` + // Problems are the monitors whose overall status is critical or + // warning, worst first. + Problems []problemMonitor `json:"problems" yaml:"problems"` +} + +// monitorCounts counts monitors by overall status. +type monitorCounts struct { + Total int `json:"total" yaml:"total"` + OK int `json:"ok" yaml:"ok"` + Warning int `json:"warning" yaml:"warning"` + Critical int `json:"critical" yaml:"critical"` + Pending int `json:"pending" yaml:"pending"` + Paused int `json:"paused" yaml:"paused"` +} + +// problemMonitor is a monitor that needs attention, in the API's field +// names. +type problemMonitor struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Type string `json:"type" yaml:"type"` + Variant string `json:"variant" yaml:"variant"` + Target string `json:"target" yaml:"target"` + Status string `json:"status" yaml:"status"` + OverallStatus string `json:"overallStatus" yaml:"overallStatus"` + Condition string `json:"condition,omitempty" yaml:"condition,omitempty"` + Message string `json:"message,omitempty" yaml:"message,omitempty"` +} + +func newStatusCmd(d deps) *cobra.Command { + var failOn string + cmd := &cobra.Command{ + Use: "status", + Annotations: cmdutil.Reads(), + Short: "Show the organization's monitoring status, or fail a CI job on open incidents", + Long: `Shows the open incidents by severity, the monitors by status, and every +monitor that is critical or warning. The verdict ("status" in JSON) comes +from open incidents, which are problems the checks confirmed: critical +while a critical incident is open, warning while only warnings are, else +ok. + +--fail-on turns the verdict into the exit code: with --fail-on critical +the command exits 1 (code unhealthy, the report in the error's details) +while a critical incident is open, with --fail-on warning while any +incident is open. The report is printed either way. The default, none, +always exits 0.`, + Example: ` norcube pulsecheck status + # Gate a deploy on PulseCheck + norcube pulsecheck status --fail-on critical + norcube pulsecheck status -o json --query problems[].name`, + Args: cobra.NoArgs, + RunE: cmdutil.Run(func(cmd *cobra.Command, _ []string) (any, error) { + if err := oneOf("--fail-on", failOn, statusFailOn); err != nil { + return nil, err + } + c, err := d.client(cmd) + if err != nil { + return nil, err + } + report, err := buildStatus(cmd.Context(), c) + if err != nil { + return nil, err + } + view := statusObject(report) + fail := (failOn == "critical" && report.Status == "critical") || + (failOn == "warning" && report.Status != "ok") + if !fail { + return view, nil + } + if err := cmdutil.Print(cmd, view); err != nil { + return nil, err + } + return nil, &clierr.Error{ + Code: clierr.CodeUnhealthy, + Message: fmt.Sprintf("PulseCheck is %s: %d critical and %d warning incident(s) open", report.Status, report.Incidents.Open.Critical, report.Incidents.Open.Warning), + Hint: "See them with `norcube pulsecheck incidents list --status open`.", + Details: report, + } + }), + } + cmd.Flags().StringVar(&failOn, "fail-on", "none", "Exit 1 while incidents of this severity or worse are open: critical, warning or none") + cmdutil.FlagEnum(cmd, "fail-on", statusFailOn...) + return cmd +} + +func buildStatus(ctx context.Context, c *pcContext) (statusReport, error) { + summary, err := incidentSummary(ctx, c) + if err != nil { + return statusReport{}, err + } + r := statusReport{Status: "ok", Incidents: summary, Problems: []problemMonitor{}} + switch { + case summary.Open.Critical > 0: + r.Status = "critical" + case summary.Open.Total > 0: + r.Status = "warning" + } + // Sorted by status (the API's default): critical and warning first. + limit := maxPageSize + p := pulsecheck.ListMonitorsParams{Limit: &limit} + for r.Monitors.Total < maxItems { + res, err := c.API.ListMonitorsWithResponse(ctx, &p) + if err != nil { + return statusReport{}, err + } + if res.JSON200 == nil { + return statusReport{}, apiError(res.HTTPResponse, res.Body) + } + for _, m := range res.JSON200.List { + r.Monitors.Total++ + switch m.OverallStatus { + case "ok": + r.Monitors.OK++ + case "warning": + r.Monitors.Warning++ + case "critical": + r.Monitors.Critical++ + case "pending": + r.Monitors.Pending++ + case "paused": + r.Monitors.Paused++ + } + if m.OverallStatus == "critical" || m.OverallStatus == "warning" { + pm := problemMonitor{ID: m.Id.String(), Name: m.Name, Type: string(m.Type), Variant: string(m.Variant), + Target: m.Target, Status: string(m.Status), OverallStatus: string(m.OverallStatus)} + if m.Condition != nil { + pm.Condition, pm.Message = m.Condition.Code, cmdutil.Deref(m.Condition.Message) + } + r.Problems = append(r.Problems, pm) + } + } + next := nextCursor(res.JSON200.Cursors) + if next == "" { + break + } + p.Cursor = &next + } + return r, nil +} + +func statusObject(r statusReport) output.Object { + f := []output.Field{{Name: "Status", Value: r.Status}} + f = append(f, summaryFields(r.Incidents)[:4]...) + f = append(f, output.Field{Name: "Monitors", Value: fmt.Sprintf("%d (%d ok, %d warning, %d critical, %d pending, %d paused)", + r.Monitors.Total, r.Monitors.OK, r.Monitors.Warning, r.Monitors.Critical, r.Monitors.Pending, r.Monitors.Paused)}) + // One field for every problem monitor, a line each, so -o text keeps + // fixed columns. + lines := make([]string, 0, len(r.Problems)) + for _, p := range r.Problems { + word := statusWord(p.Type, p.Status, p.Condition) + if p.Status != p.OverallStatus { + // The monitor itself is fine; a certificate or domain it + // watches isn't. + word = capitalize(p.OverallStatus) + } + line := word + ": " + p.Name + " (" + p.Target + ")" + if p.Message != "" { + line += ", " + p.Message + } + lines = append(lines, line) + } + problems := "none" + if len(lines) > 0 { + problems = strings.Join(lines, "\n") + } + f = append(f, output.Field{Name: "Problems", Value: problems}) + return output.Object{Value: r, Fields: f} +} diff --git a/internal/cli/pulsecheck_test.go b/internal/cli/pulsecheck_test.go new file mode 100644 index 0000000..545bac8 --- /dev/null +++ b/internal/cli/pulsecheck_test.go @@ -0,0 +1,700 @@ +package cli + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/norcubeplatform/cli/internal/clierr" +) + +// PulseCheck fixtures: three monitors (an HTTP one that is down with an +// open critical incident, an SSL one expiring soon, a domain one that is +// fine), two alert channels, one incident. +const ( + pcShop = "7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f" + pcCert = "2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809" + pcDomain = "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d" + pcHook = "0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f" + pcPhone = "5e6f7a8b-9c0d-4e1f-8a2b-3c4d5e6f7a8b" + pcInc = "3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10" + pcUser = "11111111-2222-4333-8444-555555555555" +) + +var ( + pcShopJSON = `{"id":"` + pcShop + `","name":"Shop","description":"","type":"http","variant":"keyword","target":"https://shop.example.com/health", + "intervalSeconds":60,"status":"critical","overallStatus":"critical","statusSince":"2026-11-03T08:00:00Z", + "condition":{"code":"unexpected_status","message":"HTTP 503","since":"2026-11-03T08:00:00Z","facts":{"statusCode":503},"alertedThresholds":[]}, + "lastCheck":{"at":"2026-11-03T08:10:00Z","severity":"critical","condition":"unexpected_status","totalMs":180}, + "nextCheckAt":"2026-11-03T08:11:00Z", + "last24h":{"from":"2026-11-02T08:00:00Z","checks":1440,"ok":1420,"warning":0,"critical":20,"inconclusive":0,"uptimePercent":98.61,"warningPercent":0,"avgMs":120,"p50Ms":110,"p95Ms":240}, + "aspects":[{"aspect":"certificate","subject":"shop.example.com","status":"ok","condition":"ok","daysRemaining":64,"thresholdsDays":[30,14,7],"alertedThresholds":[]}], + "regions":[{"code":"eu-central-1","name":"Frankfurt"}], + "http":{"url":"https://shop.example.com/health","method":"GET","expectedStatus":["2xx"],"timeoutMs":10000,"slowThresholdMs":1500, + "followRedirects":true,"maxRedirects":5,"verifyTls":true,"keyword":"ok","keywordMode":"present","keywordCaseSensitive":false, + "headers":[{"name":"Authorization","secret":true},{"name":"X-Env","secret":false,"value":"prod"}], + "certificateExpiry":{"thresholdsDays":[30,14,7]}}, + "createdAt":"2026-10-01T09:00:00Z","createdBy":"` + pcUser + `","updatedAt":"2026-10-01T09:00:00Z"}` + pcCertJSON = `{"id":"` + pcCert + `","name":"API cert","description":"","type":"ssl","variant":"ssl","target":"api.example.com:443", + "intervalSeconds":3600,"status":"warning","overallStatus":"warning","statusSince":"2026-11-01T00:00:00Z", + "condition":{"code":"cert_expiring","message":"Certificate expires in 12 days","since":"2026-11-01T00:00:00Z","facts":{"daysRemaining":12,"thresholdDays":14,"expiresAt":"2026-11-15T12:00:00Z"},"alertedThresholds":[{"days":14,"alertedAt":"2026-11-01T00:00:00Z"}]}, + "lastCheck":{"at":"2026-11-03T08:00:00Z","severity":"warning","condition":"cert_expiring","totalMs":95}, + "aspects":[],"regions":[{"code":"eu-central-1","name":"Frankfurt"}], + "ssl":{"host":"api.example.com","port":443,"expiryThresholdsDays":[30,14,7]}, + "createdAt":"2026-10-02T09:00:00Z","createdBy":"` + pcUser + `","updatedAt":"2026-10-02T09:00:00Z"}` + pcDomainJSON = `{"id":"` + pcDomain + `","name":"example.com","description":"Company domain","type":"domain","variant":"domain","target":"example.com", + "intervalSeconds":43200,"status":"ok","overallStatus":"ok","statusSince":"2026-10-03T09:00:00Z", + "condition":{"code":"ok","message":"Registered until 2027-08-01","since":"2026-10-03T09:00:00Z","facts":{"daysRemaining":271},"alertedThresholds":[]}, + "lastCheck":{"at":"2026-11-03T06:00:00Z","severity":"ok","condition":"ok","totalMs":420}, + "aspects":[],"regions":[{"code":"eu-central-1","name":"Frankfurt"}], + "domain":{"domain":"example.com","expiryThresholdsDays":[60,30]}, + "createdAt":"2026-10-03T09:00:00Z","createdBy":"` + pcUser + `","updatedAt":"2026-10-03T09:00:00Z"}` + pcIncidentJSON = `"id":"` + pcInc + `","monitorId":"` + pcShop + `","monitorName":"Shop","monitorType":"http","monitorVariant":"keyword", + "monitorTarget":"https://shop.example.com/health","aspect":"availability","title":"Shop is down","status":"open","severity":"critical", + "peakSeverity":"critical","condition":"unexpected_status","summary":"HTTP 503","facts":{"statusCode":503}, + "openedAt":"2026-11-03T08:01:00Z","durationSeconds":540` + pcHookJSON = `{"id":"` + pcHook + `","kind":"webhook","name":"On-call webhook","isDefault":true,"enabled":true,"verified":true, + "settings":{"url":"https://hooks.example.com/pulsecheck"},"createdAt":"2026-10-01T09:00:00Z","updatedAt":"2026-10-01T09:00:00Z"}` + pcPhoneJSON = `{"id":"` + pcPhone + `","kind":"sms","name":"On-call phone","isDefault":false,"enabled":true,"verified":false, + "settings":{"phone":"+420601123456"},"createdAt":"2026-10-05T09:00:00Z","updatedAt":"2026-10-05T09:00:00Z"}` +) + +func pcList(items ...string) string { + return `{"list":[` + strings.Join(items, ",") + `],"cursors":{},"meta":{}}` +} + +func init() { + for k, v := range map[string]string{ + "GET /monitors": pcList(pcShopJSON, pcCertJSON, pcDomainJSON), + "GET /monitors/" + pcShop: pcShopJSON, + "GET /monitors/" + pcCert: pcCertJSON, + "GET /monitors/" + pcDomain: pcDomainJSON, + "GET /monitors/" + pcShop + "/results": pcList( + `{"id":9002,"checkedAt":"2026-11-03T08:10:00Z","severity":"critical","condition":"unexpected_status","statusCode":503,"errorMessage":"HTTP 503","region":"eu-central-1","timings":{"dnsMs":4,"connectMs":12,"tlsMs":30,"ttfbMs":170,"totalMs":180}}`, + `{"id":9001,"checkedAt":"2026-11-03T07:59:00Z","severity":"ok","condition":"ok","statusCode":200,"region":"eu-central-1","timings":{"dnsMs":3,"connectMs":11,"tlsMs":28,"ttfbMs":100,"totalMs":110}}`), + "GET /monitors/" + pcShop + "/status-changes": pcList( + `{"id":2,"from":"ok","to":"critical","changedAt":"2026-11-03T08:00:00Z","durationSeconds":600,"condition":"unexpected_status","statusCode":503,"message":"HTTP 503","checkResultId":9000,"events":[]}`, + `{"id":1,"from":"pending","to":"ok","changedAt":"2026-10-01T09:01:00Z","endedAt":"2026-11-03T08:00:00Z","durationSeconds":2847540,"condition":"ok","checkResultId":1,"events":[]}`), + "GET /monitors/" + pcShop + "/stats": `{"from":"2026-11-02T08:00:00Z","to":"2026-11-03T08:10:00Z","granularity":"hour","checks":1440,"ok":1420,"warning":0,"critical":20,"inconclusive":0,"uptimePercent":98.61,"avgMs":120,"maxMs":980,"series":[]}`, + "GET /monitors/" + pcShop + "/availability": `{"from":"2026-11-01","to":"2026-11-03","checks":4300,"ok":4260,"warning":0,"critical":40,"inconclusive":0,"uptimePercent":99.07,"downtimeMinutes":40,"days":[ + {"date":"2026-11-01","checks":1440,"ok":1440,"warning":0,"critical":0,"inconclusive":0,"uptimePercent":100,"downtimeMinutes":0,"noData":false}, + {"date":"2026-11-02","checks":1440,"ok":1420,"warning":0,"critical":20,"inconclusive":0,"uptimePercent":98.61,"downtimeMinutes":20,"noData":false}, + {"date":"2026-11-03","checks":0,"ok":0,"warning":0,"critical":0,"inconclusive":0,"downtimeMinutes":0,"noData":true}]}`, + "GET /monitors/" + pcCert + "/certificate": `{"resultId":77,"checkedAt":"2026-11-03T08:00:00Z","severity":"warning","condition":"cert_expiring","daysRemaining":12, + "thresholdsDays":[30,14,7],"nextThresholdAt":"2026-11-08T12:00:00Z","nextThresholdDays":7, + "certificate":{"subject":"CN=api.example.com","issuer":"CN=Example CA","dnsNames":["api.example.com"],"notBefore":"2026-08-17T12:00:00Z","notAfter":"2026-11-15T12:00:00Z", + "daysRemaining":12,"chainValid":true,"hostnameValid":true,"serialNumber":"04ab","fingerprintSha256":"aa:bb"}}`, + "GET /monitors/" + pcShop + "/alerts": `{"useDefaults":false,"confirmFailures":2,"confirmSuccesses":1,"reminderMinutes":60, + "routes":[{"channelId":"` + pcHook + `","events":["down","recovered"]}],"applicableEvents":["down","warning","expiring","expired","recovered"]}`, + "GET /incidents": pcList(`{` + pcIncidentJSON + `}`), + "GET /incidents/" + pcInc: `{` + pcIncidentJSON + `,"timeline":[{"type":"opened","at":"2026-11-03T08:01:00Z"}], + "alerts":[{"alertId":"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee","queuedAt":"2026-11-03T08:01:00Z","event":"down","channelId":"` + pcHook + `","channelName":"On-call webhook","channelKind":"webhook","status":"sent","attempts":1,"sentAt":"2026-11-03T08:01:02Z"}]}`, + "GET /incidents/summary": `{"open":{"total":1,"critical":1,"warning":0,"unacknowledged":1},"resolvedLast7d":4,"resolvedLast30d":12,"mttrLast30dSeconds":1260}`, + "GET /alert-channels": pcList(pcHookJSON, pcPhoneJSON), + "GET /alert-channels/" + pcHook: pcHookJSON, + "GET /alert-channels/" + pcPhone: pcPhoneJSON, + "GET /alert-channels/" + pcHook + "/deliveries": pcList( + `{"id":"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff","event":"down","monitorId":"` + pcShop + `","monitorName":"Shop","incidentId":"` + pcInc + `","status":"sent","attempts":1,"createdAt":"2026-11-03T08:01:00Z","sentAt":"2026-11-03T08:01:02Z"}`), + } { + goldenData[k] = v + } +} + +func TestGoldenPulseCheck(t *testing.T) { + commands := []struct { + name string + args []string + }{ + {"pulsecheck-status", []string{"pulsecheck", "status"}}, + {"pulsecheck-monitors-list", []string{"pulsecheck", "monitors", "list"}}, + {"pulsecheck-monitors-get", []string{"pulsecheck", "monitors", "get", pcShop}}, + {"pulsecheck-monitors-get-ssl", []string{"pulsecheck", "monitors", "get", pcCert}}, + {"pulsecheck-results-list", []string{"pulsecheck", "monitors", "results", "list", pcShop}}, + {"pulsecheck-status-changes-list", []string{"pulsecheck", "monitors", "status-changes", "list", pcShop}}, + {"pulsecheck-stats-get", []string{"pulsecheck", "monitors", "stats", "get", pcShop}}, + {"pulsecheck-availability-get", []string{"pulsecheck", "monitors", "availability", "get", pcShop}}, + {"pulsecheck-certificate-get", []string{"pulsecheck", "monitors", "certificate", "get", pcCert}}, + {"pulsecheck-alerts-get", []string{"pulsecheck", "monitors", "alerts", "get", pcShop}}, + {"pulsecheck-incidents-list", []string{"pulsecheck", "incidents", "list"}}, + {"pulsecheck-incidents-get", []string{"pulsecheck", "incidents", "get", pcInc}}, + {"pulsecheck-incidents-summary", []string{"pulsecheck", "incidents", "summary"}}, + {"pulsecheck-channels-list", []string{"pulsecheck", "channels", "list"}}, + {"pulsecheck-channels-get", []string{"pulsecheck", "channels", "get", pcHook}}, + {"pulsecheck-deliveries-list", []string{"pulsecheck", "channels", "deliveries", "list", pcHook}}, + } + for _, c := range commands { + for format, ext := range goldenFormats { + t.Run(c.name+"/"+format, func(t *testing.T) { + url := goldenEnv(t) + out, stderr, err := run(t, append(c.args, "-o", format, "--no-pager")...) + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + checkGolden(t, c.name+"."+ext, out, url) + }) + } + } +} + +// The machine-readable tree of the whole PulseCheck group is pinned: it +// is what scripts and agents read to discover the commands. +func TestGoldenCommandsPulseCheck(t *testing.T) { + commandsEnv(t) + out, stderr, err := run(t, "commands", "pulsecheck", "-o", "json") + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + checkGolden(t, "commands-pulsecheck.json", out, "http://unused") +} + +// recorder captures the requests a test's handlers saw. +type recorder struct { + mu sync.Mutex + reqs []recorded +} + +type recorded struct { + method, path, query string + body map[string]any +} + +func (r *recorder) handler(status int, body string) http.HandlerFunc { + return func(w http.ResponseWriter, req *http.Request) { + raw, _ := io.ReadAll(req.Body) + var m map[string]any + _ = json.Unmarshal(raw, &m) + r.mu.Lock() + r.reqs = append(r.reqs, recorded{req.Method, req.URL.Path, req.URL.RawQuery, m}) + r.mu.Unlock() + if status >= 400 { + w.Header().Set("Content-Type", "application/problem+json") + } + w.WriteHeader(status) + fmt.Fprint(w, body) + } +} + +func (r *recorder) only(t *testing.T) recorded { + t.Helper() + r.mu.Lock() + defer r.mu.Unlock() + if len(r.reqs) != 1 { + t.Fatalf("%d requests, want 1: %+v", len(r.reqs), r.reqs) + } + return r.reqs[0] +} + +func (r *recorder) count() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.reqs) +} + +func exitOf(err error) int { return Describe(err).ExitCode() } + +func TestPulseCheckMonitorCreate(t *testing.T) { + goldenEnv(t) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{"POST /monitors": rec.handler(201, pcShopJSON)}) + + out, stderr, err := runIn(t, "Authorization: Bearer s3cret\n", "pulsecheck", "monitors", "create", "Shop", "--type", "keyword", + "--url", "https://shop.example.com/health", "--keyword", "ok", "--header", "X-Env: prod", + "--secret-headers-file", "-", "--slow", "1500ms", "-o", "json") + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if !strings.Contains(out, `"id": "`+pcShop+`"`) { + t.Errorf("stdout: %s", out) + } + b := rec.only(t).body + h, _ := b["http"].(map[string]any) + if b["type"] != "http" || b["name"] != "Shop" || b["intervalSeconds"] != float64(60) || h == nil { + t.Fatalf("body %v", b) + } + if h["method"] != "GET" || h["timeoutMs"] != float64(10000) || h["followRedirects"] != true || h["verifyTls"] != true || + h["keyword"] != "ok" || h["slowThresholdMs"] != float64(1500) { + t.Errorf("http settings %v", h) + } + if h["certificateExpiry"] == nil || h["domainExpiry"] == nil { + t.Errorf("an https URL watches its certificate and domain by default: %v", h) + } + headers, _ := h["headers"].([]any) + if len(headers) != 2 || fmt.Sprint(headers[1]) != "map[name:Authorization secret:true value:Bearer s3cret]" { + t.Errorf("headers %v", headers) + } + if strings.Contains(stderr, "s3cret") || strings.Contains(out, "s3cret") { + t.Error("a secret header value reached the output") + } + + // SSL and domain monitors, and a body from a file. + rec = recorder{} + goldenHandlers(t, map[string]http.HandlerFunc{"POST /monitors": rec.handler(201, pcCertJSON)}) + if _, stderr, err := run(t, "pulsecheck", "monitors", "create", "API cert", "--type", "ssl", "--host", "api.example.com", "--alert-days", "21,7"); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if s := fmt.Sprint(rec.only(t).body["ssl"]); s != "map[expiryThresholdsDays:[21 7] host:api.example.com port:443]" { + t.Errorf("ssl %s", s) + } + rec = recorder{} + goldenHandlers(t, map[string]http.HandlerFunc{"POST /monitors": rec.handler(201, pcDomainJSON)}) + if _, stderr, err := runIn(t, `{"type":"domain","name":"x","intervalSeconds":86400,"domain":{"domain":"example.com","expiryThresholdsDays":[30]}}`, + "pulsecheck", "monitors", "create", "example.com", "--from-file", "-"); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if b := rec.only(t).body; b["name"] != "example.com" || b["intervalSeconds"] != float64(86400) { + t.Errorf("from-file body %v", b) + } +} + +func TestPulseCheckUsageErrorsBeforeAnyRequest(t *testing.T) { + goldenEnv(t) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{ + "POST /monitors": rec.handler(201, pcShopJSON), + "POST /alert-channels": rec.handler(201, pcHookJSON), + }) + cases := [][]string{ + {"pulsecheck", "monitors", "create", "x"}, + {"pulsecheck", "monitors", "create", "x", "--type", "tcp"}, + {"pulsecheck", "monitors", "create", "x", "--type", "keyword", "--url", "https://e.com"}, + {"pulsecheck", "monitors", "create", "x", "--type", "ssl", "--url", "https://e.com", "--host", "e.com"}, + {"pulsecheck", "monitors", "create", "x", "--type", "http"}, + {"pulsecheck", "monitors", "create", "x", "--type", "http", "--url", "https://e.com", "--interval", "1500ms"}, + {"pulsecheck", "monitors", "create", "x", "--type", "http", "--url", "https://e.com", "--header", "no colon"}, + {"pulsecheck", "monitors", "create", "--from-file", "-", "--type", "http"}, + {"pulsecheck", "monitors", "list", "--status", "down"}, + {"pulsecheck", "monitors", "run", pcShop, "--fail-on", "warning"}, + {"pulsecheck", "monitors", "update", pcShop}, + {"pulsecheck", "monitors", "results", "list", pcShop, "--since", "yesterday"}, + {"pulsecheck", "monitors", "alerts", "set", pcShop}, + {"pulsecheck", "monitors", "alerts", "set", pcShop, "--defaults", "--mute"}, + {"pulsecheck", "monitors", "alerts", "set", pcShop, "--route", "hook"}, + {"pulsecheck", "monitors", "alerts", "set", pcShop, "--route", "hook=paged"}, + {"pulsecheck", "monitors", "bulk", "pause"}, + {"pulsecheck", "monitors", "bulk", "pause", pcShop, "--status", "critical"}, + {"pulsecheck", "incidents", "get", "not-a-uuid"}, + {"pulsecheck", "incidents", "list", "--acknowledged", "--unacknowledged"}, + {"pulsecheck", "channels", "create", "x"}, + {"pulsecheck", "channels", "create", "x", "--kind", "slack", "--url", "https://hooks.slack.com/services/T/B/x"}, + {"pulsecheck", "channels", "create", "x", "--kind", "sms", "--address", "a@example.com"}, + {"pulsecheck", "channels", "create", "x", "--kind", "webhook", "--url", "https://e.com/h", "--secret-file", "-"}, + {"pulsecheck", "status", "--fail-on", "sometimes"}, + } + for _, args := range cases { + _, _, err := run(t, args...) + if err == nil || exitOf(err) != clierr.ExitUsage { + t.Errorf("%v: got %v (exit %d), want a usage error", args, err, exitOf(err)) + } + } + if n := rec.count(); n != 0 { + t.Fatalf("%d requests sent for invalid input", n) + } +} + +// update starts from the monitor's settings: a changed flag keeps every +// other setting, and a secret header keeps its stored value (no value +// sent). +func TestPulseCheckMonitorUpdateMergesSettings(t *testing.T) { + goldenEnv(t) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{"PATCH /monitors/" + pcShop: rec.handler(200, pcShopJSON)}) + if _, stderr, err := run(t, "pulsecheck", "monitors", "update", pcShop, "--timeout", "5s", "--name", "Shop EU"); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + b := rec.only(t).body + h, _ := b["http"].(map[string]any) + if b["name"] != "Shop EU" || h["timeoutMs"] != float64(5000) || h["keyword"] != "ok" || h["slowThresholdMs"] != float64(1500) { + t.Fatalf("body %v", b) + } + if hs := fmt.Sprint(h["headers"]); hs != "[map[name:Authorization secret:true] map[name:X-Env secret:false value:prod]]" { + t.Errorf("headers %s", hs) + } + if _, _, err := run(t, "pulsecheck", "monitors", "update", pcShop, "--host", "x.example.com"); exitOf(err) != clierr.ExitUsage { + t.Errorf("ssl flag on an http monitor: %v", err) + } +} + +// Monitors are named by id or exact name: one match is used, none is a +// 404 (exit 3), several are a usage error. +func TestPulseCheckMonitorNames(t *testing.T) { + goldenEnv(t) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{"POST /monitors/" + pcShop + "/pause": rec.handler(200, pcShopJSON)}) + out, stderr, err := run(t, "pulsecheck", "monitors", "pause", "shop") + if err != nil || !strings.Contains(out, "Paused monitor Shop") { + t.Fatalf("%v %q %s", err, out, stderr) + } + if _, _, err := run(t, "pulsecheck", "monitors", "pause", "nope"); exitOf(err) != clierr.ExitNotFound { + t.Errorf("unknown name: %v", err) + } + twice := strings.Replace(pcCertJSON, `"name":"API cert"`, `"name":"Shop"`, 1) + goldenHandlers(t, map[string]http.HandlerFunc{"GET /monitors": rec.handler(200, pcList(pcShopJSON, twice))}) + if _, _, err := run(t, "pulsecheck", "monitors", "get", "Shop"); exitOf(err) != clierr.ExitUsage || !strings.Contains(err.Error(), pcCert) { + t.Errorf("ambiguous name: %v", err) + } +} + +func TestPulseCheckMonitorDeleteConfirms(t *testing.T) { + goldenEnv(t) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{"DELETE /monitors/" + pcShop: rec.handler(204, "")}) + if _, _, err := run(t, "pulsecheck", "monitors", "delete", pcShop); exitOf(err) != clierr.ExitUsage || !strings.Contains(err.Error(), "--yes") { + t.Fatalf("without a terminal: %v", err) + } + if rec.count() != 0 { + t.Fatal("deleted without confirmation") + } + out, _, err := run(t, "pulsecheck", "monitors", "delete", pcShop, "--yes", "-o", "json") + if err != nil || !strings.Contains(out, `"deleted": true`) { + t.Fatalf("%v %s", err, out) + } + // A linked monitor: 409 MANAGED_RESOURCE exits 8. + goldenHandlers(t, map[string]http.HandlerFunc{"DELETE /monitors/" + pcShop: rec.handler(409, + `{"type":"https://docs.norcube.com/errors/managed-resource","title":"Managed by another service","status":409,"detail":"This monitor belongs to a DomainRadar saved domain.","code":"MANAGED_RESOURCE"}`)}) + if _, _, err := run(t, "pulsecheck", "monitors", "delete", pcShop, "--yes"); exitOf(err) != clierr.ExitConflict { + t.Errorf("managed monitor: %v", err) + } +} + +// run --wait turns the check's verdict into the exit code: a critical +// result is job_failed (exit 1) with the result in details and nothing +// on stdout; an ok one exits 0 and prints the result. +func TestPulseCheckMonitorRunWait(t *testing.T) { + goldenEnv(t) + down := `{"id":9003,"checkedAt":"2026-11-03T08:12:00Z","severity":"critical","condition":"unexpected_status","statusCode":503,"region":"eu-central-1","timings":{"totalMs":150}}` + slow := strings.NewReplacer(`"critical"`, `"warning"`, "unexpected_status", "slow_response").Replace(down) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{"POST /monitors/" + pcShop + "/check": rec.handler(200, down)}) + + out, _, err := run(t, "pulsecheck", "monitors", "run", pcShop, "-o", "json") + if err != nil || !strings.Contains(out, `"severity": "critical"`) { + t.Fatalf("without --wait: %v %s", err, out) + } + out, _, err = run(t, "pulsecheck", "monitors", "run", "Shop", "--wait", "-o", "json") + e := Describe(err) + if e.Code != clierr.CodeJobFailed || e.ExitCode() != clierr.ExitError || out != "" || e.Details == nil { + t.Fatalf("critical with --wait: %+v stdout %q", e, out) + } + goldenHandlers(t, map[string]http.HandlerFunc{"POST /monitors/" + pcShop + "/check": rec.handler(200, slow)}) + if _, _, err := run(t, "pulsecheck", "monitors", "run", pcShop, "--wait"); err != nil { + t.Errorf("a warning passes by default: %v", err) + } + if _, _, err := run(t, "pulsecheck", "monitors", "run", pcShop, "--wait", "--fail-on", "warning"); Describe(err).Code != clierr.CodeJobFailed { + t.Errorf("--fail-on warning: %v", err) + } +} + +func TestPulseCheckBulk(t *testing.T) { + goldenEnv(t) + var rec recorder + ok := `{"action":"pause","succeeded":2,"failed":0,"items":[{"monitorId":"` + pcShop + `","ok":true},{"monitorId":"` + pcCert + `","ok":true}]}` + goldenHandlers(t, map[string]http.HandlerFunc{ + "GET /monitors": rec.handler(200, pcList(pcShopJSON, pcCertJSON)), + "POST /monitors/bulk": rec.handler(200, ok), + }) + if _, _, err := run(t, "pulsecheck", "monitors", "bulk", "pause", "--search", "example.com"); exitOf(err) != clierr.ExitUsage { + t.Fatalf("bulk without --yes: %v", err) + } + rec = recorder{} + goldenHandlers(t, map[string]http.HandlerFunc{ + "GET /monitors": rec.handler(200, pcList(pcShopJSON, pcCertJSON)), + "POST /monitors/bulk": rec.handler(200, ok), + }) + out, stderr, err := run(t, "pulsecheck", "monitors", "bulk", "pause", "--search", "example.com", "--status", "critical", "--yes", "-o", "json") + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if len(rec.reqs) != 2 || !strings.Contains(rec.reqs[0].query, "q=example.com") || !strings.Contains(rec.reqs[0].query, "status=critical") { + t.Fatalf("requests %+v", rec.reqs) + } + if fmt.Sprint(rec.reqs[1].body) != "map[action:pause monitorIds:["+pcShop+" "+pcCert+"]]" || !strings.Contains(out, `"ok": true`) { + t.Errorf("bulk body %v, out %s", rec.reqs[1].body, out) + } + partial := `{"action":"delete","succeeded":1,"failed":1,"items":[{"monitorId":"` + pcShop + `","ok":true},{"monitorId":"` + pcCert + `","ok":false,"code":"MANAGED_RESOURCE","detail":"Linked."}]}` + goldenHandlers(t, map[string]http.HandlerFunc{"POST /monitors/bulk": rec.handler(200, partial)}) + out, _, err = run(t, "pulsecheck", "monitors", "bulk", "delete", pcShop, pcCert, "--yes", "-o", "text") + if exitOf(err) != clierr.ExitError || !strings.Contains(out, "MANAGED_RESOURCE") { + t.Errorf("partial failure: %v %q", err, out) + } +} + +func TestPulseCheckIncidents(t *testing.T) { + goldenEnv(t) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{"GET /incidents": rec.handler(200, pcList())}) + if _, stderr, err := run(t, "pulsecheck", "incidents", "list", "--status", "open", "--severity", "critical", "--aspect", "availability", + "--unacknowledged", "--monitor", pcShop, "--search", "shop", "--since", "2026-11-01T00:00:00Z", "-o", "json"); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + q := rec.only(t).query + for _, want := range []string{"status=open", "severity=critical", "aspect=availability", "acknowledged=false", "monitorId=" + pcShop, "q=shop", "from=2026-11-01T00%3A00%3A00Z", "limit=50"} { + if !strings.Contains(q, want) { + t.Errorf("query %q lacks %s", q, want) + } + } + acked := strings.Replace(goldenData["GET /incidents/"+pcInc], `"durationSeconds":540`, `"durationSeconds":540,"acknowledgedAt":"2026-11-03T08:05:00Z","acknowledgedBy":"`+pcUser+`","acknowledgedByName":"Dev Eloper"`, 1) + goldenHandlers(t, map[string]http.HandlerFunc{"POST /incidents/" + pcInc + "/acknowledge": rec.handler(200, acked)}) + out, _, err := run(t, "pulsecheck", "incidents", "ack", pcInc) + if err != nil || !strings.Contains(out, "Acknowledged incident") { + t.Fatalf("%v %q", err, out) + } +} + +func TestPulseCheckAlertsSet(t *testing.T) { + goldenEnv(t) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{"PUT /monitors/" + pcShop + "/alerts": rec.handler(200, goldenData["GET /monitors/"+pcShop+"/alerts"])}) + if _, stderr, err := run(t, "pulsecheck", "monitors", "alerts", "set", pcShop, "--route", "on-call webhook=down,recovered", "--reminder", "30m"); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + b := rec.only(t).body + if fmt.Sprint(b["routes"]) != "[map[channelId:"+pcHook+" events:[down recovered]]]" || b["reminderMinutes"] != float64(30) || + b["confirmFailures"] != float64(2) || b["useDefaults"] != false { + t.Errorf("body %v", b) + } + rec = recorder{} + goldenHandlers(t, map[string]http.HandlerFunc{"PUT /monitors/" + pcShop + "/alerts": rec.handler(200, goldenData["GET /monitors/"+pcShop+"/alerts"])}) + if _, _, err := run(t, "pulsecheck", "monitors", "alerts", "set", pcShop, "--defaults"); err != nil || fmt.Sprint(rec.only(t).body) != "map[useDefaults:true]" { + t.Errorf("--defaults: %v %v", err, rec.reqs) + } + rec = recorder{} + goldenHandlers(t, map[string]http.HandlerFunc{"PUT /monitors/" + pcShop + "/alerts": rec.handler(200, goldenData["GET /monitors/"+pcShop+"/alerts"])}) + if _, _, err := run(t, "pulsecheck", "monitors", "alerts", "set", pcShop, "--mute"); err != nil || fmt.Sprint(rec.only(t).body["routes"]) != "[]" { + t.Errorf("--mute: %v %v", err, rec.reqs) + } +} + +// A webhook's signing secret goes to the file named, never to stdout or +// stderr; Slack URLs come from a file or stdin. +func TestPulseCheckChannelCreateKeepsSecretsOffStdout(t *testing.T) { + goldenEnv(t) + const secret = "whsec_c2VjcmV0LXNpZ25pbmcta2V5" // #nosec G101 -- a test fixture, not a credential + withSecret := strings.Replace(pcHookJSON, `"isDefault":true`, `"isDefault":true,"signingSecret":"`+secret+`"`, 1) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{"POST /alert-channels": rec.handler(201, withSecret)}) + file := filepath.Join(t.TempDir(), "secret.txt") + for _, format := range []string{"table", "json", "yaml", "text"} { + _ = os.Remove(file) + out, stderr, err := run(t, "pulsecheck", "channels", "create", "On-call webhook", "--kind", "webhook", + "--url", "https://hooks.example.com/pulsecheck", "--secret-file", file, "-o", format) + if err != nil { + t.Fatalf("%s: %v\n%s", format, err, stderr) + } + if strings.Contains(out, secret) || strings.Contains(stderr, secret) || strings.Contains(out, "signingSecret") { + t.Fatalf("%s: the secret reached the output:\n%s\n%s", format, out, stderr) + } + } + got, err := os.ReadFile(file) // #nosec G304 -- test file + if err != nil || strings.TrimSpace(string(got)) != secret { + t.Fatalf("secret file: %v %q", err, got) + } + if info, _ := os.Stat(file); info.Mode().Perm()&0o077 != 0 { + t.Errorf("secret file mode %v", info.Mode().Perm()) + } + // Without --secret-file the secret is dropped, with a note. + _, stderr, err := run(t, "pulsecheck", "channels", "create", "Hook", "--kind", "webhook", "--url", "https://hooks.example.com/x") + if err != nil || !strings.Contains(stderr, "--rotate-secret") || strings.Contains(stderr, secret) { + t.Errorf("no --secret-file: %v %q", err, stderr) + } + + rec = recorder{} + slack := `{"id":"` + pcHook + `","kind":"slack","name":"#alerts","isDefault":false,"enabled":true,"verified":true,"settings":{"hint":"hooks.slack.com/…x9z"},"createdAt":"2026-11-03T08:00:00Z","updatedAt":"2026-11-03T08:00:00Z"}` + goldenHandlers(t, map[string]http.HandlerFunc{"POST /alert-channels": rec.handler(201, slack)}) + out, stderr, err := runIn(t, "https://hooks.slack.com/services/T0/B0/x9z\n", "pulsecheck", "channels", "create", "#alerts", "--kind", "slack", "--url-file", "-") + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if b := rec.only(t).body; fmt.Sprint(b["settings"]) != "map[url:https://hooks.slack.com/services/T0/B0/x9z]" || strings.Contains(out, "services/T0") { + t.Errorf("slack body %v out %q", b, out) + } +} + +func TestPulseCheckChannelVerify(t *testing.T) { + goldenEnv(t) + var rec recorder + verified := strings.Replace(pcPhoneJSON, `"verified":false`, `"verified":true`, 1) + goldenHandlers(t, map[string]http.HandlerFunc{ + "POST /alert-channels/" + pcPhone + "/verify": rec.handler(204, ""), + "POST /alert-channels/" + pcPhone + "/verify/confirm": rec.handler(200, verified), + }) + // No terminal: the code is sent, and the command says how to confirm. + out, stderr, err := run(t, "pulsecheck", "channels", "verify", "On-call phone", "-o", "json") + if err != nil || !strings.Contains(out, `"codeSent": true`) || !strings.Contains(stderr, "--code-file -") { + t.Fatalf("send: %v %q %q", err, out, stderr) + } + out, _, err = runIn(t, "123456\n", "pulsecheck", "channels", "verify", pcPhone, "--code-file", "-", "-o", "json") + if err != nil || !strings.Contains(out, `"verified": true`) || strings.Contains(out, "123456") { + t.Fatalf("confirm: %v %q", err, out) + } + if rec.reqs[1].path != "/alert-channels/"+pcPhone+"/verify/confirm" || rec.reqs[1].body["code"] != "123456" { + t.Errorf("requests %+v", rec.reqs) + } + if _, _, err := runIn(t, "12ab\n", "pulsecheck", "channels", "verify", pcPhone, "--code-file", "-"); exitOf(err) != clierr.ExitUsage { + t.Errorf("bad code: %v", err) + } + // An expired code: 409 CONFLICT, reason CODE_EXPIRED, exits 8 with the reason in details. + goldenHandlers(t, map[string]http.HandlerFunc{"POST /alert-channels/" + pcPhone + "/verify/confirm": rec.handler(409, + `{"title":"Conflict","status":409,"detail":"The code has expired. Send a new one.","code":"CONFLICT","reason":"CODE_EXPIRED"}`)}) + _, _, err = runIn(t, "123456", "pulsecheck", "channels", "verify", pcPhone, "--code-file", "-") + if e := Describe(err); e.ExitCode() != clierr.ExitConflict || fmt.Sprint(e.Details) != "map[reason:CODE_EXPIRED]" { + t.Errorf("expired: %+v", e) + } +} + +func TestPulseCheckChannelTestAndDelete(t *testing.T) { + goldenEnv(t) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{ + "POST /alert-channels/" + pcPhone + "/test": rec.handler(200, `{"providerRef":"bg-123"}`), + "POST /alert-channels/" + pcHook + "/test": rec.handler(200, `{"providerRef":"wh-1"}`), + "DELETE /alert-channels/" + pcHook: rec.handler(204, ""), + }) + if _, _, err := run(t, "pulsecheck", "channels", "test", pcPhone); exitOf(err) != clierr.ExitUsage { + t.Fatalf("an SMS test needs --yes without a terminal: %v", err) + } + if out, _, err := run(t, "pulsecheck", "channels", "test", pcPhone, "--yes", "-o", "text"); err != nil || strings.TrimSpace(out) != "bg-123" { + t.Fatalf("sms test: %v %q", err, out) + } + if _, _, err := run(t, "pulsecheck", "channels", "test", "on-call webhook"); err != nil { + t.Fatalf("webhook test: %v", err) + } + if _, _, err := run(t, "pulsecheck", "channels", "delete", pcHook, "--yes"); err != nil || rec.count() != 3 { + t.Fatalf("delete: %v %d", err, rec.count()) + } +} + +func TestPulseCheckStatusFailOn(t *testing.T) { + goldenEnv(t) + out, _, err := run(t, "pulsecheck", "status", "--fail-on", "critical", "-o", "json") + e := Describe(err) + if e.Code != clierr.CodeUnhealthy || e.ExitCode() != clierr.ExitError || !strings.Contains(out, `"status": "critical"`) { + t.Fatalf("critical incident open: %+v %q", e, out) + } + if _, _, err := run(t, "pulsecheck", "status"); err != nil { + t.Errorf("default --fail-on none: %v", err) + } + var rec recorder + quiet := `{"open":{"total":0,"critical":0,"warning":0,"unacknowledged":0},"resolvedLast7d":0,"resolvedLast30d":0}` + goldenHandlers(t, map[string]http.HandlerFunc{"GET /incidents/summary": rec.handler(200, quiet)}) + if _, _, err := run(t, "pulsecheck", "status", "--fail-on", "warning"); err != nil { + t.Errorf("nothing open: %v", err) + } +} + +// PulseCheck's RFC 9457 problems map to the CLI's codes: a scope a token +// lacks exits 5 (insufficient_scope), invalid fields exit 2 with the +// field errors in the message and details. +func TestPulseCheckProblems(t *testing.T) { + goldenEnv(t) + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{ + "POST /monitors/" + pcShop + "/pause": rec.handler(403, + `{"title":"Forbidden","status":403,"detail":"This token can't change monitors or incidents: it needs the pulsecheck.write scope.","code":"FORBIDDEN","reason":"INSUFFICIENT_SCOPE"}`), + "POST /monitors": rec.handler(400, + `{"title":"Validation failed","status":400,"detail":"The request has invalid fields.","code":"VALIDATION_FAILED","errors":[{"pointer":"/http/url","rule":"public","detail":"must be a public address"}]}`), + }) + _, _, err := run(t, "pulsecheck", "monitors", "pause", pcShop) + if e := Describe(err); e.Code != clierr.CodeInsufficientScope || e.ExitCode() != clierr.ExitAccess || !strings.Contains(e.Message, "pulsecheck.write") { + t.Errorf("scope: %+v", e) + } + // A token without pulsecheck.channels (pulsecheck.write doesn't include it). + goldenHandlers(t, map[string]http.HandlerFunc{"POST /alert-channels": rec.handler(403, + `{"title":"Forbidden","status":403,"detail":"This token can't change alert channels or send test alerts: it needs the pulsecheck.channels scope.","code":"FORBIDDEN","reason":"INSUFFICIENT_SCOPE"}`)}) + _, _, err = run(t, "pulsecheck", "channels", "create", "Ops", "--kind", "email", "--address", "ops@example.com") + if e := Describe(err); e.Code != clierr.CodeInsufficientScope || e.ExitCode() != clierr.ExitAccess || !strings.Contains(e.Message, "pulsecheck.channels") { + t.Errorf("channels scope: %+v", e) + } + _, _, err = run(t, "pulsecheck", "monitors", "create", "x", "--type", "http", "--url", "https://10.0.0.1/") + e := Describe(err) + var ce *clierr.Error + if e.Code != clierr.CodeValidation || e.ExitCode() != clierr.ExitUsage || !strings.Contains(e.Message, "/http/url: must be a public address") || !errors.As(err, &ce) { + t.Errorf("validation: %+v", e) + } +} + +// Monitor, channel and incident ids complete from the API, on arguments +// and on --monitor. +func TestPulseCheckCompletion(t *testing.T) { + goldenEnv(t) + clearCompletionCache(t) + cases := []struct { + args []string + want string + }{ + {[]string{"pulsecheck", "monitors", "get", ""}, pcShop + "," + pcCert + "," + pcDomain}, + {[]string{"pulsecheck", "monitors", "results", "list", "7d"}, pcShop}, + {[]string{"pulsecheck", "monitors", "bulk", "pause", pcShop, "2b"}, pcCert}, + {[]string{"pulsecheck", "incidents", "list", "--monitor", "9a"}, pcDomain}, + {[]string{"pulsecheck", "channels", "verify", "5e"}, pcPhone}, + {[]string{"pulsecheck", "incidents", "ack", ""}, pcInc}, + {[]string{"pulsecheck", "monitors", "list", "--status", ""}, "pending,ok,warning,critical,paused"}, + } + for _, c := range cases { + got, _ := complete(t, c.args...) + if strings.Join(got, ",") != c.want { + t.Errorf("%v: %v, want %s", c.args, got, c.want) + } + } +} + +// The remaining commands send what their flags say. +func TestPulseCheckRequests(t *testing.T) { + goldenEnv(t) + secretFile := filepath.Join(t.TempDir(), "rotated.txt") + rotated := strings.Replace(pcHookJSON, `"isDefault":true`, `"isDefault":false,"signingSecret":"whsec_bmV3LXNlY3JldA"`, 1) + cases := []struct { + name string + args []string + route string + status int + answer string + wantQuery string + wantBody string + }{ + {"resume", []string{"monitors", "resume", "API cert"}, "POST /monitors/" + pcCert + "/resume", 200, pcCertJSON, "", ""}, + {"results range", []string{"monitors", "results", "list", pcShop, "--since", "2026-11-01T00:00:00Z", "--until", "2026-11-02T00:00:00Z", "--limit", "10"}, + "GET /monitors/" + pcShop + "/results", 200, pcList(), "from=2026-11-01T00%3A00%3A00Z&limit=10&to=2026-11-02T00%3A00%3A00Z", ""}, + {"stats range", []string{"monitors", "stats", "get", pcShop, "--range", "30d"}, "GET /monitors/" + pcShop + "/stats", 200, + goldenData["GET /monitors/"+pcShop+"/stats"], "range=30d", ""}, + {"availability days", []string{"monitors", "availability", "get", pcShop, "--days", "7"}, "GET /monitors/" + pcShop + "/availability", 200, + goldenData["GET /monitors/"+pcShop+"/availability"], "days=7", ""}, + {"list filters", []string{"monitors", "list", "--type", "ssl", "--status", "warning", "--sort", "uptime", "--search", "api", "--history"}, + "GET /monitors", 200, pcList(pcCertJSON), "include=history&limit=50&q=api&sort=uptime&status=warning&type=ssl", ""}, + {"deliveries status", []string{"channels", "deliveries", "list", pcHook, "--status", "dead"}, "GET /alert-channels/" + pcHook + "/deliveries", 200, + pcList(), "limit=50&status=dead", ""}, + {"channel update", []string{"channels", "update", pcHook, "--name", "Pager", "--default=false", "--disable", "--rotate-secret", "--secret-file", secretFile}, + "PATCH /alert-channels/" + pcHook, 200, rotated, "", "map[enabled:false isDefault:false name:Pager rotateSecret:true]"}, + {"sms create", []string{"channels", "create", "Phone", "--kind", "sms", "--phone", "+420601123456"}, "POST /alert-channels", 201, pcPhoneJSON, "", + "map[kind:sms name:Phone settings:map[phone:+420601123456]]"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + var rec recorder + goldenHandlers(t, map[string]http.HandlerFunc{c.route: rec.handler(c.status, c.answer)}) + out, stderr, err := run(t, append(append([]string{"pulsecheck"}, c.args...), "-o", "json")...) + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + r := rec.only(t) + if c.wantQuery != "" && r.query != c.wantQuery { + t.Errorf("query %q, want %q", r.query, c.wantQuery) + } + if c.wantBody != "" && fmt.Sprint(r.body) != c.wantBody { + t.Errorf("body %v, want %s", r.body, c.wantBody) + } + if strings.Contains(out+stderr, "whsec_") { + t.Errorf("a signing secret reached the output") + } + }) + } + if got, _ := os.ReadFile(secretFile); strings.TrimSpace(string(got)) != "whsec_bmV3LXNlY3JldA" { // #nosec G304 -- test file + t.Errorf("rotated secret file %q", got) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index e24a935..63e5a53 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -14,6 +14,7 @@ import ( "github.com/norcubeplatform/cli/internal/cli/billing" "github.com/norcubeplatform/cli/internal/cli/domainradar" "github.com/norcubeplatform/cli/internal/cli/langsync" + "github.com/norcubeplatform/cli/internal/cli/pulsecheck" "github.com/norcubeplatform/cli/internal/clictx" "github.com/norcubeplatform/cli/internal/clierr" "github.com/norcubeplatform/cli/internal/cmdutil" @@ -104,6 +105,7 @@ func NewRootCmd() *cobra.Command { langsync.NewCmd(), domainradar.NewCmd(), billing.NewCmd(), + pulsecheck.NewCmd(), ) markUsageErrors(cmd) completion.Bind(flags) diff --git a/internal/cli/testdata/golden/commands-billing.json b/internal/cli/testdata/golden/commands-billing.json index d2f99e3..eb3bf97 100644 --- a/internal/cli/testdata/golden/commands-billing.json +++ b/internal/cli/testdata/golden/commands-billing.json @@ -42,7 +42,7 @@ { "name": "endpoint-url", "type": "stringArray", - "description": "Override a service endpoint, service=url (repeatable; services: auth, web_app, snapdb, langsync, domainradar, billing, prompthub)", + "description": "Override a service endpoint, service=url (repeatable; services: auth, web_app, snapdb, langsync, domainradar, billing, pulsecheck, prompthub)", "required": false, "repeatable": true }, diff --git a/internal/cli/testdata/golden/commands-billing.yaml b/internal/cli/testdata/golden/commands-billing.yaml index ba10ef2..b49b5bc 100644 --- a/internal/cli/testdata/golden/commands-billing.yaml +++ b/internal/cli/testdata/golden/commands-billing.yaml @@ -390,7 +390,7 @@ globalFlags: repeatable: false required: false type: bool - - description: 'Override a service endpoint, service=url (repeatable; services: auth, web_app, snapdb, langsync, domainradar, billing, prompthub)' + - description: 'Override a service endpoint, service=url (repeatable; services: auth, web_app, snapdb, langsync, domainradar, billing, pulsecheck, prompthub)' name: endpoint-url repeatable: true required: false diff --git a/internal/cli/testdata/golden/commands-pulsecheck.json b/internal/cli/testdata/golden/commands-pulsecheck.json new file mode 100644 index 0000000..527b1f0 --- /dev/null +++ b/internal/cli/testdata/golden/commands-pulsecheck.json @@ -0,0 +1,2699 @@ +{ + "schemaVersion": 1, + "cliVersion": "dev", + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "globalFlags": [ + { + "name": "auth-url", + "type": "string", + "description": "Override the auth service base URL, same as --endpoint-url auth=URL (env: NORCUBE_AUTH_URL)", + "required": false, + "repeatable": false + }, + { + "name": "cli-connect-timeout", + "type": "int", + "default": "10", + "description": "Seconds to wait for a connection, 0 for no limit (env: NORCUBE_CONNECT_TIMEOUT)", + "required": false, + "repeatable": false + }, + { + "name": "cli-read-timeout", + "type": "int", + "default": "60", + "description": "Seconds to wait for each API response, 0 for no limit (env: NORCUBE_READ_TIMEOUT)", + "required": false, + "repeatable": false + }, + { + "name": "debug", + "type": "bool", + "default": "false", + "description": "Print every HTTP request and response to stderr, with credentials redacted (env: NORCUBE_DEBUG=1)", + "required": false, + "repeatable": false + }, + { + "name": "endpoint-url", + "type": "stringArray", + "description": "Override a service endpoint, service=url (repeatable; services: auth, web_app, snapdb, langsync, domainradar, billing, pulsecheck, prompthub)", + "required": false, + "repeatable": true + }, + { + "name": "max-attempts", + "type": "int", + "default": "3", + "description": "Attempts for a request that hit throttling or a transient failure, 1 disables retries (env: NORCUBE_MAX_ATTEMPTS)", + "required": false, + "repeatable": false + }, + { + "name": "no-color", + "type": "bool", + "default": "false", + "description": "Disable color and styling (env: NO_COLOR, CLICOLOR=0)", + "required": false, + "repeatable": false + }, + { + "name": "no-pager", + "type": "bool", + "default": "false", + "description": "Disable automatic paging of long table output (env: $PAGER controls the pager, default: less)", + "required": false, + "repeatable": false + }, + { + "name": "org", + "type": "string", + "description": "Run this command against a specific organization, id or slug (env: NORCUBE_ORG)", + "required": false, + "repeatable": false + }, + { + "name": "output", + "shorthand": "o", + "type": "string", + "default": "table", + "description": "Output format: table | json | yaml | text (env: NORCUBE_OUTPUT)", + "required": false, + "repeatable": false, + "enum": [ + "table", + "json", + "yaml", + "text" + ] + }, + { + "name": "profile", + "type": "string", + "description": "Use a named profile from the config file (env: NORCUBE_PROFILE)", + "required": false, + "repeatable": false + }, + { + "name": "query", + "type": "string", + "description": "JMESPath expression applied to the result before it is printed, e.g. \"[?status=='failed'].jobId\"", + "required": false, + "repeatable": false + }, + { + "name": "token-file", + "type": "string", + "description": "Read an access token from this file instead of the profile's credentials (env: NORCUBE_TOKEN holds one directly)", + "required": false, + "repeatable": false + }, + { + "name": "web-app", + "type": "string", + "description": "Override the web app base URL used for browser login (env: NORCUBE_WEB_APP)", + "required": false, + "repeatable": false + } + ], + "commands": [ + { + "command": "norcube pulsecheck", + "path": [ + "pulsecheck" + ], + "name": "pulsecheck", + "short": "Monitor uptime, SSL certificates and domain expiry, and manage incidents and alerts", + "long": "PulseCheck checks your sites, certificates and domains on a schedule\nfrom Norcube's servers. A monitor is an HTTP check (optionally with a\nkeyword), an SSL certificate check or a domain expiry check. Problems\nconfirmed by consecutive checks open incidents, which alert through your\nalert channels (email, webhook, Slack, Discord, SMS).\n\nMonitors and channels are named by their id or, where a command says so,\nby their exact name. Checks count towards your PulseCheck usage, on a\nschedule and when you run one now.\n\nIn CI, \"pulsecheck status --fail-on critical\" fails the job while a\ncritical incident is open, and \"pulsecheck monitors run \u003cmonitor\u003e --wait\"\nfails it when the check finds the monitor down. CI tokens need a\nPulseCheck scope: pulsecheck.read (everything that reads),\npulsecheck.check (run checks), pulsecheck.write (manage monitors and\nincidents) or pulsecheck.channels (manage alert channels, which\npulsecheck.write doesn't include).", + "usage": "norcube pulsecheck \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck channels", + "path": [ + "pulsecheck", + "channels" + ], + "name": "channels", + "aliases": [ + "channel", + "alert-channels" + ], + "short": "Manage alert channels: email, webhooks, Slack, Discord and SMS", + "long": "Alert channels are where incidents alert. Default channels get the\nalerts of every monitor that follows the organization's defaults; a\nmonitor's own routes (\"monitors alerts set\") name channels directly.\n\nCredentials stay secret: Slack and Discord URLs are read from a file or\nstandard input and shown only as a hint, and a webhook's signing secret is\nwritten to a file you name, never printed. Email-address and SMS channels\nget no alerts until their contact confirms a code (\"channels verify\").\nA CI token changes channels only with the pulsecheck.channels scope\n(pulsecheck.write doesn't include it); any PulseCheck scope reads them.", + "usage": "norcube pulsecheck channels \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck channels create", + "path": [ + "pulsecheck", + "channels", + "create" + ], + "name": "create", + "short": "Create an alert channel", + "long": "Creates a channel of one kind:\n\n email --address (confirmed with a code sent there) or --members\n webhook --url; signed with a secret PulseCheck generates (saved with\n --secret-file, never printed) or yours (--signing-secret-file)\n slack --url-file: the incoming-webhook URL, from a file or stdin\n discord --url-file: the webhook URL, from a file or stdin\n sms --phone (confirmed with a code texted there)\n\nEmail-address and SMS channels get no alerts until verified: run\n\"channels verify \u003cchannel\u003e\" (on a terminal it asks for the code).", + "usage": "norcube pulsecheck channels create \u003cname\u003e [flags]", + "args": "\u003cname\u003e", + "example": "norcube pulsecheck channels create \"Ops\" --kind email --address ops@example.com --default\nnorcube pulsecheck channels create \"On-call webhook\" --kind webhook --url https://example.com/hooks/pulsecheck --secret-file webhook-secret.txt\npbpaste | norcube pulsecheck channels create \"#alerts\" --kind slack --url-file -\nnorcube pulsecheck channels create \"On-call phone\" --kind sms --phone +420601123456", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "address", + "type": "string", + "description": "email: the address to alert (it gets a code to confirm)", + "required": false, + "repeatable": false + }, + { + "name": "default", + "type": "bool", + "default": "false", + "description": "Make it a default channel: monitors that follow the organization's defaults alert here", + "required": false, + "repeatable": false + }, + { + "name": "kind", + "type": "string", + "description": "Channel kind: email, webhook, slack, discord or sms", + "required": false, + "repeatable": false, + "enum": [ + "email", + "webhook", + "slack", + "discord", + "sms" + ] + }, + { + "name": "members", + "type": "bool", + "default": "false", + "description": "email: alert the organization's members instead of one address", + "required": false, + "repeatable": false + }, + { + "name": "phone", + "type": "string", + "description": "sms: a mobile number in international format, e.g. +420601123456 (it gets a code to confirm)", + "required": false, + "repeatable": false + }, + { + "name": "secret-file", + "type": "string", + "description": "webhook: write the generated signing secret to this new file (mode 0600); it is never printed", + "required": false, + "repeatable": false + }, + { + "name": "signing-secret-file", + "type": "string", + "description": "webhook: use your own signing secret (whsec_…) read from this file (- for standard input)", + "required": false, + "repeatable": false + }, + { + "name": "url", + "type": "string", + "description": "webhook: the URL PulseCheck posts signed alerts to", + "required": false, + "repeatable": false + }, + { + "name": "url-file", + "type": "string", + "description": "slack, discord: read the incoming-webhook URL (a credential) from this file (- for standard input)", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck channels delete", + "path": [ + "pulsecheck", + "channels", + "delete" + ], + "name": "delete", + "short": "Delete an alert channel", + "long": "Deletes the channel and removes it from every monitor's alert routes; alerts still queued for it are dropped.", + "usage": "norcube pulsecheck channels delete \u003cchannel\u003e [flags]", + "args": "\u003cchannel\u003e", + "example": "norcube pulsecheck channels delete \"Old webhook\"\nnorcube pulsecheck channels delete 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f --yes", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": true, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "yes", + "type": "bool", + "default": "false", + "description": "Don't ask for confirmation", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck channels deliveries", + "path": [ + "pulsecheck", + "channels", + "deliveries" + ], + "name": "deliveries", + "short": "The alerts a channel was given to send", + "usage": "norcube pulsecheck channels deliveries \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck channels deliveries list", + "path": [ + "pulsecheck", + "channels", + "deliveries", + "list" + ], + "name": "list", + "short": "List a channel's deliveries, newest first", + "long": "Lists every alert given to the channel (kept 90 days): the event, monitor\nand incident, whether it was sent, is pending (queued or waiting to retry)\nor dead (given up), the attempts and the last error, with URLs, addresses\nand phone numbers removed. --status dead lists the failures nobody saw.", + "usage": "norcube pulsecheck channels deliveries list \u003cchannel\u003e [flags]", + "args": "\u003cchannel\u003e", + "example": "norcube pulsecheck channels deliveries list \"On-call webhook\" --status dead", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": true, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "all-pages", + "type": "bool", + "default": "false", + "description": "Follow cursors until every page is fetched (capped by --max-items)", + "required": false, + "repeatable": false + }, + { + "name": "cursor", + "type": "string", + "description": "Continue from the cursor a previous page printed", + "required": false, + "repeatable": false + }, + { + "name": "limit", + "type": "int", + "default": "0", + "description": "Same as --page-size", + "required": false, + "repeatable": false + }, + { + "name": "max-items", + "type": "int", + "default": "0", + "description": "Cap for --all-pages (0 = 10000)", + "required": false, + "repeatable": false + }, + { + "name": "page-size", + "type": "int", + "default": "0", + "description": "Items per request (0 = 50)", + "required": false, + "repeatable": false + }, + { + "name": "status", + "type": "string", + "description": "Only pending, sent or dead deliveries", + "required": false, + "repeatable": false, + "enum": [ + "pending", + "sent", + "dead" + ] + } + ] + }, + { + "command": "norcube pulsecheck channels get", + "path": [ + "pulsecheck", + "channels", + "get" + ], + "name": "get", + "short": "Show an alert channel", + "usage": "norcube pulsecheck channels get \u003cchannel\u003e", + "args": "\u003cchannel\u003e", + "example": "norcube pulsecheck channels get \"On-call webhook\"", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [] + }, + { + "command": "norcube pulsecheck channels list", + "path": [ + "pulsecheck", + "channels", + "list" + ], + "name": "list", + "short": "List alert channels", + "usage": "norcube pulsecheck channels list [flags]", + "example": "norcube pulsecheck channels list", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": true, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "all-pages", + "type": "bool", + "default": "false", + "description": "Follow cursors until every page is fetched (capped by --max-items)", + "required": false, + "repeatable": false + }, + { + "name": "cursor", + "type": "string", + "description": "Continue from the cursor a previous page printed", + "required": false, + "repeatable": false + }, + { + "name": "limit", + "type": "int", + "default": "0", + "description": "Same as --page-size", + "required": false, + "repeatable": false + }, + { + "name": "max-items", + "type": "int", + "default": "0", + "description": "Cap for --all-pages (0 = 10000)", + "required": false, + "repeatable": false + }, + { + "name": "page-size", + "type": "int", + "default": "0", + "description": "Items per request (0 = 50)", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck channels test", + "path": [ + "pulsecheck", + "channels", + "test" + ], + "name": "test", + "short": "Send a test alert through a channel now", + "long": "Sends a test alert right away and prints the provider's reference. Rate\nlimited (20 per user and 60 per organization an hour); an SMS counts\ntoward the daily SMS limit, so SMS channels ask first (--yes skips it).", + "usage": "norcube pulsecheck channels test \u003cchannel\u003e [flags]", + "args": "\u003cchannel\u003e", + "example": "norcube pulsecheck channels test \"On-call webhook\"", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": true, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "yes", + "type": "bool", + "default": "false", + "description": "Don't ask before texting an SMS channel", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck channels update", + "path": [ + "pulsecheck", + "channels", + "update" + ], + "name": "update", + "short": "Rename, enable, disable or reconfigure an alert channel", + "long": "Changes only what you pass. New settings replace the kind's settings as a\nwhole (a Slack or Discord URL must be given again); a new address or phone\nnumber needs verifying again. --rotate-secret gives a webhook a new\nsigning secret, written to --secret-file.", + "usage": "norcube pulsecheck channels update \u003cchannel\u003e [flags]", + "args": "\u003cchannel\u003e", + "example": "norcube pulsecheck channels update \"Ops\" --default=false\nnorcube pulsecheck channels update \"On-call webhook\" --rotate-secret --secret-file new-secret.txt\nnorcube pulsecheck channels update \"On-call phone\" --phone +420601999888", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "address", + "type": "string", + "description": "email: the address to alert (it gets a code to confirm)", + "required": false, + "repeatable": false + }, + { + "name": "default", + "type": "bool", + "default": "false", + "description": "Make it a default channel: monitors that follow the organization's defaults alert here", + "required": false, + "repeatable": false + }, + { + "name": "disable", + "type": "bool", + "default": "false", + "description": "Stop sending alerts through the channel, keeping it", + "required": false, + "repeatable": false + }, + { + "name": "enable", + "type": "bool", + "default": "false", + "description": "Send alerts through the channel again", + "required": false, + "repeatable": false + }, + { + "name": "members", + "type": "bool", + "default": "false", + "description": "email: alert the organization's members instead of one address", + "required": false, + "repeatable": false + }, + { + "name": "name", + "type": "string", + "description": "New name", + "required": false, + "repeatable": false + }, + { + "name": "phone", + "type": "string", + "description": "sms: a mobile number in international format, e.g. +420601123456 (it gets a code to confirm)", + "required": false, + "repeatable": false + }, + { + "name": "rotate-secret", + "type": "bool", + "default": "false", + "description": "webhook: generate a new signing secret (use with --secret-file)", + "required": false, + "repeatable": false + }, + { + "name": "secret-file", + "type": "string", + "description": "webhook: write the generated signing secret to this new file (mode 0600); it is never printed", + "required": false, + "repeatable": false + }, + { + "name": "signing-secret-file", + "type": "string", + "description": "webhook: use your own signing secret (whsec_…) read from this file (- for standard input)", + "required": false, + "repeatable": false + }, + { + "name": "url", + "type": "string", + "description": "webhook: the URL PulseCheck posts signed alerts to", + "required": false, + "repeatable": false + }, + { + "name": "url-file", + "type": "string", + "description": "slack, discord: read the incoming-webhook URL (a credential) from this file (- for standard input)", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck channels verify", + "path": [ + "pulsecheck", + "channels", + "verify" + ], + "name": "verify", + "short": "Confirm an SMS or email-address channel with the code sent to it", + "long": "Email-address and SMS channels get no alerts until their contact\nconfirms a 6-digit code (valid 10 minutes, 5 attempts).\n\nOn a terminal, verify sends a code and asks for it. In a script, run it\nonce to send the code, then again with --code-file (- reads standard\ninput) to confirm. The code is never taken as an argument nor printed.\nA new code can be sent after a minute (--resend), at most 5 a day.", + "usage": "norcube pulsecheck channels verify \u003cchannel\u003e [flags]", + "args": "\u003cchannel\u003e", + "example": "norcube pulsecheck channels verify \"On-call phone\"\nnorcube pulsecheck channels verify 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f --resend\necho 123456 | norcube pulsecheck channels verify 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f --code-file -", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "code-file", + "type": "string", + "description": "Confirm with the code read from this file (- for standard input) instead of sending one", + "required": false, + "repeatable": false + }, + { + "name": "resend", + "type": "bool", + "default": "false", + "description": "Send a new code (the same as running verify again)", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck incidents", + "path": [ + "pulsecheck", + "incidents" + ], + "name": "incidents", + "aliases": [ + "incident" + ], + "short": "List, inspect and acknowledge incidents", + "long": "An incident is a confirmed problem with one aspect of a monitor: its\navailability, its certificate or its domain. It opens after the monitor's\nconfirmations (or at once for an expiry), alerts the monitor's channels,\nreminds until acknowledged, and resolves when the checks are good again.", + "usage": "norcube pulsecheck incidents \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck incidents acknowledge", + "path": [ + "pulsecheck", + "incidents", + "acknowledge" + ], + "name": "acknowledge", + "aliases": [ + "ack" + ], + "short": "Acknowledge an incident: someone is on it, stop the reminders", + "long": "Marks an open incident as being handled; its reminders stop. Idempotent: a resolved or already acknowledged incident is returned unchanged.", + "usage": "norcube pulsecheck incidents acknowledge \u003cincident\u003e", + "args": "\u003cincident\u003e", + "example": "norcube pulsecheck incidents acknowledge 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [] + }, + { + "command": "norcube pulsecheck incidents get", + "path": [ + "pulsecheck", + "incidents", + "get" + ], + "name": "get", + "short": "Show an incident with its timeline and the alerts sent", + "long": "Shows the incident, its timeline (opened, escalated, reminders,\nacknowledged, resolved) and every alert sent for it with its delivery\nstatus, so a failing channel shows here.", + "usage": "norcube pulsecheck incidents get \u003cincident\u003e", + "args": "\u003cincident\u003e", + "example": "norcube pulsecheck incidents get 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10\nnorcube pulsecheck incidents get 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 -o json --query timeline", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [] + }, + { + "command": "norcube pulsecheck incidents list", + "path": [ + "pulsecheck", + "incidents", + "list" + ], + "name": "list", + "short": "List incidents, open ones first", + "long": "Lists incidents: open critical ones first, then open warnings, then\nresolved ones, newest first within each. Every filter given must match.\n--severity reads an open incident's current severity and a resolved one's\npeak, so \"--severity critical\" finds every incident that ever paged.\n--since and --until select by when the incident started.", + "usage": "norcube pulsecheck incidents list [flags]", + "example": "norcube pulsecheck incidents list --status open\nnorcube pulsecheck incidents list --status open --unacknowledged --severity critical\nnorcube pulsecheck incidents list --monitor \"Shop\" --since 30d -o json", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": true, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "acknowledged", + "type": "bool", + "default": "false", + "description": "Only acknowledged incidents", + "required": false, + "repeatable": false + }, + { + "name": "all-pages", + "type": "bool", + "default": "false", + "description": "Follow cursors until every page is fetched (capped by --max-items)", + "required": false, + "repeatable": false + }, + { + "name": "aspect", + "type": "string", + "description": "Only incidents about availability, the certificate or the domain", + "required": false, + "repeatable": false, + "enum": [ + "availability", + "certificate", + "domain" + ] + }, + { + "name": "cursor", + "type": "string", + "description": "Continue from the cursor a previous page printed", + "required": false, + "repeatable": false + }, + { + "name": "limit", + "type": "int", + "default": "0", + "description": "Same as --page-size", + "required": false, + "repeatable": false + }, + { + "name": "max-items", + "type": "int", + "default": "0", + "description": "Cap for --all-pages (0 = 10000)", + "required": false, + "repeatable": false + }, + { + "name": "monitor", + "type": "string", + "description": "Only incidents of this monitor (id or exact name)", + "required": false, + "repeatable": false + }, + { + "name": "page-size", + "type": "int", + "default": "0", + "description": "Items per request (0 = 50)", + "required": false, + "repeatable": false + }, + { + "name": "search", + "type": "string", + "description": "Only incidents whose monitor's name or target contains this text", + "required": false, + "repeatable": false + }, + { + "name": "severity", + "type": "string", + "description": "Only warning or critical incidents (current severity while open, peak once resolved)", + "required": false, + "repeatable": false, + "enum": [ + "warning", + "critical" + ] + }, + { + "name": "since", + "type": "string", + "description": "Only incidents that started at or after this time: an RFC 3339 timestamp, a date or an age such as 24h or 7d", + "required": false, + "repeatable": false + }, + { + "name": "status", + "type": "string", + "description": "Only open or resolved incidents", + "required": false, + "repeatable": false, + "enum": [ + "open", + "resolved" + ] + }, + { + "name": "unacknowledged", + "type": "bool", + "default": "false", + "description": "Only incidents nobody acknowledged yet", + "required": false, + "repeatable": false + }, + { + "name": "until", + "type": "string", + "description": "Only incidents that started before this time (timestamp, date or age)", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck incidents summary", + "path": [ + "pulsecheck", + "incidents", + "summary" + ], + "name": "summary", + "short": "Count open incidents by severity, and resolved ones with the time to resolve", + "long": "The organization's incidents at a glance: open ones by current severity\nand those nobody acknowledged, incidents resolved in the last 7 and 30\ndays, and the mean time from opened to resolved over the last 30 days.\nFor a pass or fail answer in CI use \"pulsecheck status --fail-on\".", + "usage": "norcube pulsecheck incidents summary", + "example": "norcube pulsecheck incidents summary\nnorcube pulsecheck incidents summary -o json --query open.critical", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [] + }, + { + "command": "norcube pulsecheck monitors", + "path": [ + "pulsecheck", + "monitors" + ], + "name": "monitors", + "aliases": [ + "monitor" + ], + "short": "Create, inspect and manage monitors and their check history", + "long": "A monitor checks one thing on a schedule: an HTTP endpoint (optionally\nfor a keyword), an SSL certificate, or a domain's registration. Commands\nthat take a \u003cmonitor\u003e accept its id or its exact name.", + "usage": "norcube pulsecheck monitors \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck monitors alerts", + "path": [ + "pulsecheck", + "monitors", + "alerts" + ], + "name": "alerts", + "short": "Where and when a monitor alerts", + "long": "A monitor either follows the organization's defaults (its default\nchannels, or the members by email when none is default) or has its own\nroutes: which events go to which channels, how many failed checks open an\nincident, how many good ones resolve it, and how often to remind.", + "usage": "norcube pulsecheck monitors alerts \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck monitors alerts get", + "path": [ + "pulsecheck", + "monitors", + "alerts", + "get" + ], + "name": "get", + "short": "Show how a monitor alerts", + "usage": "norcube pulsecheck monitors alerts get \u003cmonitor\u003e", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors alerts get \"Shop\"", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [] + }, + { + "command": "norcube pulsecheck monitors alerts set", + "path": [ + "pulsecheck", + "monitors", + "alerts", + "set" + ], + "name": "set", + "short": "Set where and when a monitor alerts", + "long": "Replaces the monitor's alerting. --defaults returns it to the\norganization's defaults. Otherwise give its routes, each a channel (id or\nexact name) and the events it gets (down, warning, expiring, expired,\nrecovered), or --mute for no alerts; settings you leave out keep their\ncurrent values. Channels themselves are managed with \"pulsecheck channels\".", + "usage": "norcube pulsecheck monitors alerts set \u003cmonitor\u003e [flags]", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors alerts set \"Shop\" --route \"On-call webhook=down,recovered\" --route ops-email=down\nnorcube pulsecheck monitors alerts set \"Shop\" --confirm-failures 3 --reminder 30m\nnorcube pulsecheck monitors alerts set \"Shop\" --mute\nnorcube pulsecheck monitors alerts set \"Shop\" --defaults", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "confirm-failures", + "type": "int", + "default": "0", + "description": "Failed checks in a row before an incident opens, 1 to 10", + "required": false, + "repeatable": false + }, + { + "name": "confirm-successes", + "type": "int", + "default": "0", + "description": "Good checks in a row before it resolves, 1 to 10", + "required": false, + "repeatable": false + }, + { + "name": "defaults", + "type": "bool", + "default": "false", + "description": "Follow the organization's default channels again", + "required": false, + "repeatable": false + }, + { + "name": "from-file", + "type": "string", + "description": "Read the API's alert settings body as JSON from this file (- for standard input)", + "required": false, + "repeatable": false + }, + { + "name": "mute", + "type": "bool", + "default": "false", + "description": "Send no alerts for this monitor", + "required": false, + "repeatable": false + }, + { + "name": "reminder", + "type": "duration", + "default": "0s", + "description": "Remind about an unacknowledged critical incident this often, e.g. 1h (0 for no reminders)", + "required": false, + "repeatable": false + }, + { + "name": "route", + "type": "stringArray", + "description": "A route \"\u003cchannel\u003e=\u003cevent\u003e,\u003cevent\u003e\" (channel id or exact name; events down, warning, expiring, expired, recovered); repeatable, replaces the routes", + "required": false, + "repeatable": true + } + ] + }, + { + "command": "norcube pulsecheck monitors availability", + "path": [ + "pulsecheck", + "monitors", + "availability" + ], + "name": "availability", + "short": "A monitor's uptime and downtime per day", + "usage": "norcube pulsecheck monitors availability \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck monitors availability get", + "path": [ + "pulsecheck", + "monitors", + "availability", + "get" + ], + "name": "get", + "short": "Show uptime and estimated downtime per UTC day", + "long": "One row per UTC day ending today, oldest first: check counts, uptime and\nan estimate of the minutes spent down (HTTP monitors). A day without\nchecks has no uptime, never 100%.", + "usage": "norcube pulsecheck monitors availability get \u003cmonitor\u003e [flags]", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors availability get \"Shop\" --days 30", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "days", + "type": "int", + "default": "0", + "description": "Days ending today, 1 to 90 (default 90)", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck monitors bulk", + "path": [ + "pulsecheck", + "monitors", + "bulk" + ], + "name": "bulk", + "short": "Pause, resume or delete many monitors at once", + "long": "Applies one action to many monitors: the ones you name (ids or exact\nnames, as arguments or one per line with --file), or every monitor the\nlist filters match (--type, --status, --search). Each monitor is handled as\nits own request would be, so one refusal doesn't stop the others; the\nresult lists every monitor with ok or its problem code. The command exits\n1 when any monitor failed.", + "usage": "norcube pulsecheck monitors bulk \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck monitors bulk delete", + "path": [ + "pulsecheck", + "monitors", + "bulk", + "delete" + ], + "name": "delete", + "short": "Delete many monitors and their history", + "usage": "norcube pulsecheck monitors bulk delete [\u003cmonitor\u003e...] [flags]", + "args": "[\u003cmonitor\u003e...]", + "example": "norcube pulsecheck monitors bulk delete 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f \"Old landing page\"\nnorcube pulsecheck monitors bulk delete --file old-monitors.txt --yes", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": true, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "file", + "shorthand": "f", + "type": "string", + "description": "Read monitors (ids or names) from this file, one per line (- for standard input)", + "required": false, + "repeatable": false + }, + { + "name": "search", + "type": "string", + "description": "Select every monitor whose name or target contains this text", + "required": false, + "repeatable": false + }, + { + "name": "status", + "type": "string", + "description": "Select every monitor with this overall status", + "required": false, + "repeatable": false, + "enum": [ + "pending", + "ok", + "warning", + "critical", + "paused" + ] + }, + { + "name": "type", + "type": "string", + "description": "Select every monitor of this type: http, ssl or domain", + "required": false, + "repeatable": false, + "enum": [ + "http", + "ssl", + "domain" + ] + }, + { + "name": "yes", + "type": "bool", + "default": "false", + "description": "Don't ask for confirmation", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck monitors bulk pause", + "path": [ + "pulsecheck", + "monitors", + "bulk", + "pause" + ], + "name": "pause", + "short": "Pause many monitors", + "usage": "norcube pulsecheck monitors bulk pause [\u003cmonitor\u003e...] [flags]", + "args": "[\u003cmonitor\u003e...]", + "example": "# Maintenance window: pause everything behind api.example.com\nnorcube pulsecheck monitors bulk pause --search api.example.com --yes", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": true, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "file", + "shorthand": "f", + "type": "string", + "description": "Read monitors (ids or names) from this file, one per line (- for standard input)", + "required": false, + "repeatable": false + }, + { + "name": "search", + "type": "string", + "description": "Select every monitor whose name or target contains this text", + "required": false, + "repeatable": false + }, + { + "name": "status", + "type": "string", + "description": "Select every monitor with this overall status", + "required": false, + "repeatable": false, + "enum": [ + "pending", + "ok", + "warning", + "critical", + "paused" + ] + }, + { + "name": "type", + "type": "string", + "description": "Select every monitor of this type: http, ssl or domain", + "required": false, + "repeatable": false, + "enum": [ + "http", + "ssl", + "domain" + ] + }, + { + "name": "yes", + "type": "bool", + "default": "false", + "description": "Don't ask for confirmation", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck monitors bulk resume", + "path": [ + "pulsecheck", + "monitors", + "bulk", + "resume" + ], + "name": "resume", + "short": "Resume many monitors", + "usage": "norcube pulsecheck monitors bulk resume [\u003cmonitor\u003e...] [flags]", + "args": "[\u003cmonitor\u003e...]", + "example": "norcube pulsecheck monitors bulk resume --status paused --search api.example.com --yes", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": true, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "file", + "shorthand": "f", + "type": "string", + "description": "Read monitors (ids or names) from this file, one per line (- for standard input)", + "required": false, + "repeatable": false + }, + { + "name": "search", + "type": "string", + "description": "Select every monitor whose name or target contains this text", + "required": false, + "repeatable": false + }, + { + "name": "status", + "type": "string", + "description": "Select every monitor with this overall status", + "required": false, + "repeatable": false, + "enum": [ + "pending", + "ok", + "warning", + "critical", + "paused" + ] + }, + { + "name": "type", + "type": "string", + "description": "Select every monitor of this type: http, ssl or domain", + "required": false, + "repeatable": false, + "enum": [ + "http", + "ssl", + "domain" + ] + }, + { + "name": "yes", + "type": "bool", + "default": "false", + "description": "Don't ask for confirmation", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck monitors certificate", + "path": [ + "pulsecheck", + "monitors", + "certificate" + ], + "name": "certificate", + "aliases": [ + "cert" + ], + "short": "The newest TLS certificate an SSL or HTTPS monitor saw", + "usage": "norcube pulsecheck monitors certificate \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck monitors certificate get", + "path": [ + "pulsecheck", + "monitors", + "certificate", + "get" + ], + "name": "get", + "short": "Show the monitor's newest certificate and when it expires", + "long": "Shows the newest certificate the monitor's checks saw: subject, issuer,\nnames, validity, whether the chain and hostname verify, and days left. SSL\nmonitors add the expiry thresholds and the next one to be crossed. Exits 3\nwhen no check has seen a certificate (plain HTTP and domain monitors).", + "usage": "norcube pulsecheck monitors certificate get \u003cmonitor\u003e", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors certificate get \"API cert\"\nnorcube pulsecheck monitors cert get \"Shop\" -o json --query certificate.notAfter", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [] + }, + { + "command": "norcube pulsecheck monitors create", + "path": [ + "pulsecheck", + "monitors", + "create" + ], + "name": "create", + "short": "Create a monitor; its first check runs right away", + "long": "Creates an enabled monitor of one type:\n\n http requests --url and expects --expect (default 2xx) within --timeout;\n for https URLs it also watches the certificate and the domain's\n registration unless --no-cert-watch / --no-domain-watch\n keyword an HTTP monitor that also looks for --keyword in the body\n (--keyword-mode absent: alerts when it appears)\n ssl checks the certificate of --host:--port and alerts --alert-days\n before it expires\n domain checks the registration of --domain and alerts --alert-days\n before it expires\n\nSettings not given start from the dashboard's defaults. For anything the\nflags don't cover, pass the API's JSON body with --from-file (see \"nrc api\npulsecheck POST /monitors\"). Secret header values come from a file or\nstandard input only (--secret-headers-file), never from arguments. The\nfirst check runs at once and is billed like a scheduled one.", + "usage": "norcube pulsecheck monitors create \u003cname\u003e [flags]", + "args": "\u003cname\u003e", + "example": "norcube pulsecheck monitors create \"Shop\" --type http --url https://shop.example.com/health\nnorcube pulsecheck monitors create \"Login page\" --type keyword --url https://example.com/login --keyword \"Sign in\"\nnorcube pulsecheck monitors create \"API cert\" --type ssl --host api.example.com --alert-days 30,7\nnorcube pulsecheck monitors create \"example.com\" --type domain --domain example.com --interval 24h\nprintf 'Authorization: Bearer %s\\n' \"$TOKEN\" | norcube pulsecheck monitors create \"Admin API\" --type http --url https://example.com/admin/health --secret-headers-file -\nnorcube pulsecheck monitors create --from-file monitor.json", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "alert-days", + "type": "intSlice", + "description": "SSL and domain: alert this many days before expiry, up to 5 values (default 30,14,7)", + "required": false, + "repeatable": true + }, + { + "name": "body-content-type", + "type": "string", + "description": "HTTP: Content-Type of --body-file", + "required": false, + "repeatable": false + }, + { + "name": "body-file", + "type": "string", + "description": "HTTP: send the request body read from this file (- for standard input)", + "required": false, + "repeatable": false + }, + { + "name": "cert-expiry-days", + "type": "intSlice", + "description": "HTTP: also watch the certificate, alerting this many days before it expires (https URLs; default on with 30,14,7)", + "required": false, + "repeatable": true + }, + { + "name": "description", + "type": "string", + "description": "A note on what the monitor is for", + "required": false, + "repeatable": false + }, + { + "name": "domain", + "type": "string", + "description": "Domain: the registered domain, e.g. example.com (not www.example.com)", + "required": false, + "repeatable": false + }, + { + "name": "domain-expiry-days", + "type": "intSlice", + "description": "HTTP: also watch the domain's registration, alerting this many days before it expires (default on with 30,14,7 for host names)", + "required": false, + "repeatable": true + }, + { + "name": "expect", + "type": "stringSlice", + "description": "HTTP: accepted status codes or ranges, e.g. 2xx, 301, 400-404 (repeat or comma-separate; default 2xx)", + "required": false, + "repeatable": true + }, + { + "name": "from-file", + "type": "string", + "description": "Read the request body as JSON from this file (- for standard input), in the API's shape; no other setting flags then", + "required": false, + "repeatable": false + }, + { + "name": "header", + "type": "stringArray", + "description": "HTTP: a request header \"Name: value\" (repeatable; replaces the plain headers on update)", + "required": false, + "repeatable": true + }, + { + "name": "host", + "type": "string", + "description": "SSL: host whose certificate to check", + "required": false, + "repeatable": false + }, + { + "name": "insecure", + "type": "bool", + "default": "false", + "description": "HTTP: don't verify the TLS certificate (it is still reported)", + "required": false, + "repeatable": false + }, + { + "name": "interval", + "type": "duration", + "default": "0s", + "description": "How often to check, e.g. 30s, 5m, 1h (default 1m for HTTP, 1h for SSL, 12h for domains; your plan sets the minimum)", + "required": false, + "repeatable": false + }, + { + "name": "keyword", + "type": "string", + "description": "HTTP: text to look for in the response body (the first 256 KiB)", + "required": false, + "repeatable": false + }, + { + "name": "keyword-case-sensitive", + "type": "bool", + "default": "false", + "description": "HTTP: match the keyword's case", + "required": false, + "repeatable": false + }, + { + "name": "keyword-mode", + "type": "string", + "description": "HTTP: whether the keyword must be present (default) or absent", + "required": false, + "repeatable": false, + "enum": [ + "present", + "absent" + ] + }, + { + "name": "max-redirects", + "type": "int", + "default": "0", + "description": "HTTP: redirects to follow at most (default 5)", + "required": false, + "repeatable": false + }, + { + "name": "method", + "type": "string", + "description": "HTTP: request method (default GET)", + "required": false, + "repeatable": false, + "enum": [ + "GET", + "HEAD", + "POST", + "PUT", + "PATCH", + "DELETE", + "OPTIONS" + ] + }, + { + "name": "no-cert-watch", + "type": "bool", + "default": "false", + "description": "HTTP: don't watch the certificate", + "required": false, + "repeatable": false + }, + { + "name": "no-domain-watch", + "type": "bool", + "default": "false", + "description": "HTTP: don't watch the domain's registration", + "required": false, + "repeatable": false + }, + { + "name": "no-follow-redirects", + "type": "bool", + "default": "false", + "description": "HTTP: judge the first response instead of following redirects", + "required": false, + "repeatable": false + }, + { + "name": "port", + "type": "int", + "default": "0", + "description": "SSL: port (default 443)", + "required": false, + "repeatable": false + }, + { + "name": "secret-headers-file", + "type": "string", + "description": "HTTP: read secret headers (\"Name: value\" per line) from this file (- for standard input); stored encrypted, never shown again", + "required": false, + "repeatable": false + }, + { + "name": "server-name", + "type": "string", + "description": "SSL: SNI name to send, when it differs from --host", + "required": false, + "repeatable": false + }, + { + "name": "slow", + "type": "duration", + "default": "0s", + "description": "HTTP: warn when a response takes longer than this", + "required": false, + "repeatable": false + }, + { + "name": "timeout", + "type": "duration", + "default": "0s", + "description": "HTTP: give up on a request after this long, 1s to 30s (default 10s)", + "required": false, + "repeatable": false + }, + { + "name": "type", + "type": "string", + "description": "Monitor type: http, keyword, ssl or domain", + "required": false, + "repeatable": false, + "enum": [ + "http", + "keyword", + "ssl", + "domain" + ] + }, + { + "name": "url", + "type": "string", + "description": "HTTP: the URL to request", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck monitors delete", + "path": [ + "pulsecheck", + "monitors", + "delete" + ], + "name": "delete", + "short": "Delete a monitor and its whole check history", + "long": "Deletes the monitor with its results, status history and incidents.\nTo stop checks but keep the history, use \"monitors pause\". A monitor that\nbelongs to another Norcube product (a DomainRadar saved domain's expiry\nalerts) can't be deleted here (exit 8): remove it in that product.", + "usage": "norcube pulsecheck monitors delete \u003cmonitor\u003e [flags]", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors delete \"Old landing page\"\nnorcube pulsecheck monitors delete 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f --yes", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": true, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "yes", + "type": "bool", + "default": "false", + "description": "Don't ask for confirmation", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck monitors get", + "path": [ + "pulsecheck", + "monitors", + "get" + ], + "name": "get", + "short": "Show a monitor's settings and current status", + "long": "Shows the monitor, its check settings (secret header values are never returned), its status with the reason, and the certificate and domain it watches.", + "usage": "norcube pulsecheck monitors get \u003cmonitor\u003e", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors get \"Shop API\"\nnorcube pulsecheck monitors get 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f -o json", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [] + }, + { + "command": "norcube pulsecheck monitors list", + "path": [ + "pulsecheck", + "monitors", + "list" + ], + "name": "list", + "short": "List monitors with their current status", + "long": "Lists the organization's monitors, by default the ones that need\nattention first (critical, warning, pending, ok, paused, then by name).\n--status filters by the overall status: the worse of the monitor's own\nstatus and the certificate and domain it watches.", + "usage": "norcube pulsecheck monitors list [flags]", + "example": "norcube pulsecheck monitors list\nnorcube pulsecheck monitors list --status critical --type http\nnorcube pulsecheck monitors list --search shop --sort uptime --all-pages -o json", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": true, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "all-pages", + "type": "bool", + "default": "false", + "description": "Follow cursors until every page is fetched (capped by --max-items)", + "required": false, + "repeatable": false + }, + { + "name": "cursor", + "type": "string", + "description": "Continue from the cursor a previous page printed", + "required": false, + "repeatable": false + }, + { + "name": "history", + "type": "bool", + "default": "false", + "description": "Include each monitor's newest 60 results (JSON and YAML only)", + "required": false, + "repeatable": false + }, + { + "name": "limit", + "type": "int", + "default": "0", + "description": "Same as --page-size", + "required": false, + "repeatable": false + }, + { + "name": "max-items", + "type": "int", + "default": "0", + "description": "Cap for --all-pages (0 = 10000)", + "required": false, + "repeatable": false + }, + { + "name": "page-size", + "type": "int", + "default": "0", + "description": "Items per request (0 = 50)", + "required": false, + "repeatable": false + }, + { + "name": "search", + "type": "string", + "description": "Only monitors whose name or target contains this text", + "required": false, + "repeatable": false + }, + { + "name": "sort", + "type": "string", + "description": "Order: status (default), name, lastChecked, uptime (lowest first) or created (newest first)", + "required": false, + "repeatable": false, + "enum": [ + "status", + "name", + "lastChecked", + "uptime", + "created" + ] + }, + { + "name": "status", + "type": "string", + "description": "Only monitors with this overall status: pending, ok, warning, critical or paused", + "required": false, + "repeatable": false, + "enum": [ + "pending", + "ok", + "warning", + "critical", + "paused" + ] + }, + { + "name": "type", + "type": "string", + "description": "Only monitors of this type: http, ssl or domain", + "required": false, + "repeatable": false, + "enum": [ + "http", + "ssl", + "domain" + ] + } + ] + }, + { + "command": "norcube pulsecheck monitors pause", + "path": [ + "pulsecheck", + "monitors", + "pause" + ], + "name": "pause", + "short": "Stop a monitor's scheduled checks", + "long": "Stops scheduled checks; the history stays. Pausing closes the monitor's\nopen incident without alerting. Idempotent.", + "usage": "norcube pulsecheck monitors pause \u003cmonitor\u003e", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors pause \"Shop API\"", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [] + }, + { + "command": "norcube pulsecheck monitors results", + "path": [ + "pulsecheck", + "monitors", + "results" + ], + "name": "results", + "aliases": [ + "checks" + ], + "short": "A monitor's check results", + "usage": "norcube pulsecheck monitors results \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck monitors results list", + "path": [ + "pulsecheck", + "monitors", + "results", + "list" + ], + "name": "list", + "short": "List a monitor's check results, newest first", + "long": "Lists the monitor's checks in [--since, --until), newest first; by default\nthe last 24 hours. Raw results are kept at least 30 days. JSON has every\ndetail of a result: timings, the certificate seen, the domain's\nregistration.", + "usage": "norcube pulsecheck monitors results list \u003cmonitor\u003e [flags]", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors results list \"Shop\"\nnorcube pulsecheck monitors results list \"Shop\" --since 7d --all-pages -o json --query \"[?severity=='critical'].checkedAt\"", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": true, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "all-pages", + "type": "bool", + "default": "false", + "description": "Follow cursors until every page is fetched (capped by --max-items)", + "required": false, + "repeatable": false + }, + { + "name": "cursor", + "type": "string", + "description": "Continue from the cursor a previous page printed", + "required": false, + "repeatable": false + }, + { + "name": "limit", + "type": "int", + "default": "0", + "description": "Same as --page-size", + "required": false, + "repeatable": false + }, + { + "name": "max-items", + "type": "int", + "default": "0", + "description": "Cap for --all-pages (0 = 10000)", + "required": false, + "repeatable": false + }, + { + "name": "page-size", + "type": "int", + "default": "0", + "description": "Items per request (0 = 50)", + "required": false, + "repeatable": false + }, + { + "name": "since", + "type": "string", + "description": "Only results at or after this time: an RFC 3339 timestamp, a date or an age such as 24h or 7d", + "required": false, + "repeatable": false + }, + { + "name": "until", + "type": "string", + "description": "Only results before this time (timestamp, date or age)", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck monitors resume", + "path": [ + "pulsecheck", + "monitors", + "resume" + ], + "name": "resume", + "short": "Restart a paused monitor's scheduled checks", + "long": "Restarts scheduled checks; the next one runs right away unless the last\none is less than an interval old. Idempotent.", + "usage": "norcube pulsecheck monitors resume \u003cmonitor\u003e", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors resume \"Shop API\"", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [] + }, + { + "command": "norcube pulsecheck monitors run", + "path": [ + "pulsecheck", + "monitors", + "run" + ], + "name": "run", + "short": "Run a monitor's check now and show the result", + "long": "Runs the monitor's check right away (paused monitors too) and prints the\nstored result. The check is billed like a scheduled one and rate limited\n(200 per user and 600 per organization an hour).\n\nThe check runs while the command waits, so the result is always final.\n--wait makes the result the command's outcome, for deploy pipelines: it\nexits 1 with code job_failed (the result in \"details\") when the check\nfound the monitor critical or couldn't reach a verdict (inconclusive), or\nwith --fail-on warning also when it found a warning, and prints nothing\non stdout then; it exits 7 when no result arrives within --wait-timeout. Without --wait the command exits 0\nwhatever the check found.", + "usage": "norcube pulsecheck monitors run \u003cmonitor\u003e [flags]", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors run \"Shop API\"\n# Fail a deploy when the site is down after it\nnorcube pulsecheck monitors run \"Shop API\" --wait\nnorcube pulsecheck monitors run 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f --wait --fail-on warning -o json", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": true, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "fail-on", + "type": "string", + "description": "With --wait, the severity that fails the command: critical (default) or warning (inconclusive always fails)", + "required": false, + "repeatable": false, + "enum": [ + "critical", + "warning" + ] + }, + { + "name": "wait", + "type": "bool", + "default": "false", + "description": "Wait until the check finishes (Ctrl-C stops waiting, not the check)", + "required": false, + "repeatable": false + }, + { + "name": "wait-timeout", + "type": "duration", + "default": "2m0s", + "description": "Give up waiting after this long (the job keeps running on the server)", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck monitors stats", + "path": [ + "pulsecheck", + "monitors", + "stats" + ], + "name": "stats", + "short": "A monitor's uptime and response times", + "usage": "norcube pulsecheck monitors stats \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck monitors stats get", + "path": [ + "pulsecheck", + "monitors", + "stats", + "get" + ], + "name": "get", + "short": "Show uptime, response times and check counts over a range", + "long": "Shows uptime ((ok + warning) / conclusive checks, HTTP monitors only),\naverage and maximum response time and check counts for the range ending\nnow. JSON adds the series: hourly buckets up to 7d, daily beyond.\nRefreshed every few minutes.", + "usage": "norcube pulsecheck monitors stats get \u003cmonitor\u003e [flags]", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors stats get \"Shop\"\nnorcube pulsecheck monitors stats get \"Shop\" --range 30d -o json --query uptimePercent", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "range", + "type": "string", + "default": "24h", + "description": "Range ending now: 24h, 7d, 30d or 90d", + "required": false, + "repeatable": false, + "enum": [ + "24h", + "7d", + "30d", + "90d" + ] + } + ] + }, + { + "command": "norcube pulsecheck monitors status-changes", + "path": [ + "pulsecheck", + "monitors", + "status-changes" + ], + "name": "status-changes", + "aliases": [ + "history" + ], + "short": "When a monitor went up, down, or expiring, and for how long", + "usage": "norcube pulsecheck monitors status-changes \u003ccommand\u003e", + "group": true, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "confirm": false, + "wait": false, + "paginated": false, + "flags": [] + }, + { + "command": "norcube pulsecheck monitors status-changes list", + "path": [ + "pulsecheck", + "monitors", + "status-changes", + "list" + ], + "name": "list", + "short": "List every status change of a monitor, newest first", + "long": "Lists each time a check moved the monitor to another status: from, to,\nwhen, how long it lasted (the newest one is still going) and what the\ncheck said. Kept a year. Pausing is not a status change. JSON adds the\nevents in each span (a renewed certificate).", + "usage": "norcube pulsecheck monitors status-changes list \u003cmonitor\u003e [flags]", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors status-changes list \"Shop\"\nnorcube pulsecheck monitors history list \"Shop\" -o json", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": true, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "all-pages", + "type": "bool", + "default": "false", + "description": "Follow cursors until every page is fetched (capped by --max-items)", + "required": false, + "repeatable": false + }, + { + "name": "cursor", + "type": "string", + "description": "Continue from the cursor a previous page printed", + "required": false, + "repeatable": false + }, + { + "name": "limit", + "type": "int", + "default": "0", + "description": "Same as --page-size", + "required": false, + "repeatable": false + }, + { + "name": "max-items", + "type": "int", + "default": "0", + "description": "Cap for --all-pages (0 = 10000)", + "required": false, + "repeatable": false + }, + { + "name": "page-size", + "type": "int", + "default": "0", + "description": "Items per request (0 = 50)", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck monitors update", + "path": [ + "pulsecheck", + "monitors", + "update" + ], + "name": "update", + "short": "Change a monitor's name, interval or check settings", + "long": "Changes only what you pass. Check settings start from the monitor's\ncurrent ones, so \"--timeout 5s\" keeps everything else; secret headers keep\ntheir stored values unless --secret-headers-file replaces them (and only\nwhile the URL keeps its origin). The type can't change. --from-file sends\nthe API's PATCH body as it is (a settings object there replaces the\nsettings as a whole).", + "usage": "norcube pulsecheck monitors update \u003cmonitor\u003e [flags]", + "args": "\u003cmonitor\u003e", + "example": "norcube pulsecheck monitors update \"Shop\" --interval 30s --slow 1500ms\nnorcube pulsecheck monitors update \"Shop\" --name \"Shop (EU)\" --expect 2xx,301\nnorcube pulsecheck monitors update \"API cert\" --alert-days 21,7\nnorcube pulsecheck monitors update 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f --from-file patch.json", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "write", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "alert-days", + "type": "intSlice", + "description": "SSL and domain: alert this many days before expiry, up to 5 values (default 30,14,7)", + "required": false, + "repeatable": true + }, + { + "name": "body-content-type", + "type": "string", + "description": "HTTP: Content-Type of --body-file", + "required": false, + "repeatable": false + }, + { + "name": "body-file", + "type": "string", + "description": "HTTP: send the request body read from this file (- for standard input)", + "required": false, + "repeatable": false + }, + { + "name": "cert-expiry-days", + "type": "intSlice", + "description": "HTTP: also watch the certificate, alerting this many days before it expires (https URLs; default on with 30,14,7)", + "required": false, + "repeatable": true + }, + { + "name": "clear-headers", + "type": "bool", + "default": "false", + "description": "HTTP: remove every request header, secret ones too", + "required": false, + "repeatable": false + }, + { + "name": "description", + "type": "string", + "description": "A note on what the monitor is for", + "required": false, + "repeatable": false + }, + { + "name": "domain", + "type": "string", + "description": "Domain: the registered domain, e.g. example.com (not www.example.com)", + "required": false, + "repeatable": false + }, + { + "name": "domain-expiry-days", + "type": "intSlice", + "description": "HTTP: also watch the domain's registration, alerting this many days before it expires (default on with 30,14,7 for host names)", + "required": false, + "repeatable": true + }, + { + "name": "expect", + "type": "stringSlice", + "description": "HTTP: accepted status codes or ranges, e.g. 2xx, 301, 400-404 (repeat or comma-separate; default 2xx)", + "required": false, + "repeatable": true + }, + { + "name": "from-file", + "type": "string", + "description": "Read the request body as JSON from this file (- for standard input), in the API's shape; no other setting flags then", + "required": false, + "repeatable": false + }, + { + "name": "header", + "type": "stringArray", + "description": "HTTP: a request header \"Name: value\" (repeatable; replaces the plain headers on update)", + "required": false, + "repeatable": true + }, + { + "name": "host", + "type": "string", + "description": "SSL: host whose certificate to check", + "required": false, + "repeatable": false + }, + { + "name": "insecure", + "type": "bool", + "default": "false", + "description": "HTTP: don't verify the TLS certificate (it is still reported)", + "required": false, + "repeatable": false + }, + { + "name": "interval", + "type": "duration", + "default": "0s", + "description": "How often to check, e.g. 30s, 5m, 1h (default 1m for HTTP, 1h for SSL, 12h for domains; your plan sets the minimum)", + "required": false, + "repeatable": false + }, + { + "name": "keyword", + "type": "string", + "description": "HTTP: text to look for in the response body (the first 256 KiB)", + "required": false, + "repeatable": false + }, + { + "name": "keyword-case-sensitive", + "type": "bool", + "default": "false", + "description": "HTTP: match the keyword's case", + "required": false, + "repeatable": false + }, + { + "name": "keyword-mode", + "type": "string", + "description": "HTTP: whether the keyword must be present (default) or absent", + "required": false, + "repeatable": false, + "enum": [ + "present", + "absent" + ] + }, + { + "name": "max-redirects", + "type": "int", + "default": "0", + "description": "HTTP: redirects to follow at most (default 5)", + "required": false, + "repeatable": false + }, + { + "name": "method", + "type": "string", + "description": "HTTP: request method (default GET)", + "required": false, + "repeatable": false, + "enum": [ + "GET", + "HEAD", + "POST", + "PUT", + "PATCH", + "DELETE", + "OPTIONS" + ] + }, + { + "name": "name", + "type": "string", + "description": "New name", + "required": false, + "repeatable": false + }, + { + "name": "no-cert-watch", + "type": "bool", + "default": "false", + "description": "HTTP: don't watch the certificate", + "required": false, + "repeatable": false + }, + { + "name": "no-domain-watch", + "type": "bool", + "default": "false", + "description": "HTTP: don't watch the domain's registration", + "required": false, + "repeatable": false + }, + { + "name": "no-follow-redirects", + "type": "bool", + "default": "false", + "description": "HTTP: judge the first response instead of following redirects", + "required": false, + "repeatable": false + }, + { + "name": "no-keyword", + "type": "bool", + "default": "false", + "description": "HTTP: stop looking for a keyword", + "required": false, + "repeatable": false + }, + { + "name": "port", + "type": "int", + "default": "0", + "description": "SSL: port (default 443)", + "required": false, + "repeatable": false + }, + { + "name": "secret-headers-file", + "type": "string", + "description": "HTTP: read secret headers (\"Name: value\" per line) from this file (- for standard input); stored encrypted, never shown again", + "required": false, + "repeatable": false + }, + { + "name": "server-name", + "type": "string", + "description": "SSL: SNI name to send, when it differs from --host", + "required": false, + "repeatable": false + }, + { + "name": "slow", + "type": "duration", + "default": "0s", + "description": "HTTP: warn when a response takes longer than this", + "required": false, + "repeatable": false + }, + { + "name": "timeout", + "type": "duration", + "default": "0s", + "description": "HTTP: give up on a request after this long, 1s to 30s (default 10s)", + "required": false, + "repeatable": false + }, + { + "name": "url", + "type": "string", + "description": "HTTP: the URL to request", + "required": false, + "repeatable": false + } + ] + }, + { + "command": "norcube pulsecheck status", + "path": [ + "pulsecheck", + "status" + ], + "name": "status", + "short": "Show the organization's monitoring status, or fail a CI job on open incidents", + "long": "Shows the open incidents by severity, the monitors by status, and every\nmonitor that is critical or warning. The verdict (\"status\" in JSON) comes\nfrom open incidents, which are problems the checks confirmed: critical\nwhile a critical incident is open, warning while only warnings are, else\nok.\n\n--fail-on turns the verdict into the exit code: with --fail-on critical\nthe command exits 1 (code unhealthy, the report in the error's details)\nwhile a critical incident is open, with --fail-on warning while any\nincident is open. The report is printed either way. The default, none,\nalways exits 0.", + "usage": "norcube pulsecheck status [flags]", + "example": "norcube pulsecheck status\n# Gate a deploy on PulseCheck\nnorcube pulsecheck status --fail-on critical\nnorcube pulsecheck status -o json --query problems[].name", + "group": false, + "service": { + "key": "pulsecheck", + "name": "Norcube PulseCheck", + "audience": "pulsecheck" + }, + "effect": "read", + "confirm": false, + "wait": false, + "paginated": false, + "outputFormats": [ + "table", + "json", + "yaml", + "text" + ], + "flags": [ + { + "name": "fail-on", + "type": "string", + "default": "none", + "description": "Exit 1 while incidents of this severity or worse are open: critical, warning or none", + "required": false, + "repeatable": false, + "enum": [ + "warning", + "critical", + "none" + ] + } + ] + } + ] +} diff --git a/internal/cli/testdata/golden/pulsecheck-alerts-get.json b/internal/cli/testdata/golden/pulsecheck-alerts-get.json new file mode 100644 index 0000000..48546eb --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-alerts-get.json @@ -0,0 +1,22 @@ +{ + "applicableEvents": [ + "down", + "warning", + "expiring", + "expired", + "recovered" + ], + "confirmFailures": 2, + "confirmSuccesses": 1, + "reminderMinutes": 60, + "routes": [ + { + "channelId": "0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f", + "events": [ + "down", + "recovered" + ] + } + ], + "useDefaults": false +} diff --git a/internal/cli/testdata/golden/pulsecheck-alerts-get.tsv b/internal/cli/testdata/golden/pulsecheck-alerts-get.tsv new file mode 100644 index 0000000..1b91152 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-alerts-get.tsv @@ -0,0 +1 @@ +0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f: down,recovered 2 failed checks 1 good check 1h down, warning, expiring, expired, recovered diff --git a/internal/cli/testdata/golden/pulsecheck-alerts-get.txt b/internal/cli/testdata/golden/pulsecheck-alerts-get.txt new file mode 100644 index 0000000..419e2af --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-alerts-get.txt @@ -0,0 +1,5 @@ +Routes: 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f: down,recovered +Open after: 2 failed checks +Resolve after: 1 good check +Remind every: 1h +Events: down, warning, expiring, expired, recovered diff --git a/internal/cli/testdata/golden/pulsecheck-alerts-get.yaml b/internal/cli/testdata/golden/pulsecheck-alerts-get.yaml new file mode 100644 index 0000000..aa1f0eb --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-alerts-get.yaml @@ -0,0 +1,15 @@ +applicableEvents: + - down + - warning + - expiring + - expired + - recovered +confirmFailures: 2 +confirmSuccesses: 1 +reminderMinutes: 60 +routes: + - channelId: 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f + events: + - down + - recovered +useDefaults: false diff --git a/internal/cli/testdata/golden/pulsecheck-availability-get.json b/internal/cli/testdata/golden/pulsecheck-availability-get.json new file mode 100644 index 0000000..475e750 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-availability-get.json @@ -0,0 +1,45 @@ +{ + "checks": 4300, + "critical": 40, + "days": [ + { + "checks": 1440, + "critical": 0, + "date": "2026-11-01", + "downtimeMinutes": 0, + "inconclusive": 0, + "noData": false, + "ok": 1440, + "uptimePercent": 100, + "warning": 0 + }, + { + "checks": 1440, + "critical": 20, + "date": "2026-11-02", + "downtimeMinutes": 20, + "inconclusive": 0, + "noData": false, + "ok": 1420, + "uptimePercent": 98.61, + "warning": 0 + }, + { + "checks": 0, + "critical": 0, + "date": "2026-11-03", + "downtimeMinutes": 0, + "inconclusive": 0, + "noData": true, + "ok": 0, + "warning": 0 + } + ], + "downtimeMinutes": 40, + "from": "2026-11-01", + "inconclusive": 0, + "ok": 4260, + "to": "2026-11-03", + "uptimePercent": 99.07, + "warning": 0 +} diff --git a/internal/cli/testdata/golden/pulsecheck-availability-get.tsv b/internal/cli/testdata/golden/pulsecheck-availability-get.tsv new file mode 100644 index 0000000..9c7afe2 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-availability-get.tsv @@ -0,0 +1,3 @@ +2026-11-01 100% 0 min 1440 1440 0 0 +2026-11-02 98.61% 20 min 1440 1420 0 20 +2026-11-03 no data 0 min 0 0 0 0 diff --git a/internal/cli/testdata/golden/pulsecheck-availability-get.txt b/internal/cli/testdata/golden/pulsecheck-availability-get.txt new file mode 100644 index 0000000..053af19 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-availability-get.txt @@ -0,0 +1,4 @@ +DAY UPTIME DOWNTIME CHECKS OK WARNING CRITICAL +2026-11-01 100% 0 min 1440 1440 0 0 +2026-11-02 98.61% 20 min 1440 1420 0 20 +2026-11-03 no data 0 min 0 0 0 0 diff --git a/internal/cli/testdata/golden/pulsecheck-availability-get.yaml b/internal/cli/testdata/golden/pulsecheck-availability-get.yaml new file mode 100644 index 0000000..e298568 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-availability-get.yaml @@ -0,0 +1,36 @@ +checks: 4300 +critical: 40 +days: + - checks: 1440 + critical: 0 + date: "2026-11-01" + downtimeMinutes: 0 + inconclusive: 0 + noData: false + ok: 1440 + uptimePercent: 100 + warning: 0 + - checks: 1440 + critical: 20 + date: "2026-11-02" + downtimeMinutes: 20 + inconclusive: 0 + noData: false + ok: 1420 + uptimePercent: 98.61 + warning: 0 + - checks: 0 + critical: 0 + date: "2026-11-03" + downtimeMinutes: 0 + inconclusive: 0 + noData: true + ok: 0 + warning: 0 +downtimeMinutes: 40 +from: "2026-11-01" +inconclusive: 0 +ok: 4260 +to: "2026-11-03" +uptimePercent: 99.07 +warning: 0 diff --git a/internal/cli/testdata/golden/pulsecheck-certificate-get.json b/internal/cli/testdata/golden/pulsecheck-certificate-get.json new file mode 100644 index 0000000..ecbd782 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-certificate-get.json @@ -0,0 +1,28 @@ +{ + "certificate": { + "chainValid": true, + "daysRemaining": 12, + "dnsNames": [ + "api.example.com" + ], + "fingerprintSha256": "aa:bb", + "hostnameValid": true, + "issuer": "CN=Example CA", + "notAfter": "2026-11-15T12:00:00Z", + "notBefore": "2026-08-17T12:00:00Z", + "serialNumber": "04ab", + "subject": "CN=api.example.com" + }, + "checkedAt": "2026-11-03T08:00:00Z", + "condition": "cert_expiring", + "daysRemaining": 12, + "nextThresholdAt": "2026-11-08T12:00:00Z", + "nextThresholdDays": 7, + "resultId": 77, + "severity": "warning", + "thresholdsDays": [ + 30, + 14, + 7 + ] +} diff --git a/internal/cli/testdata/golden/pulsecheck-certificate-get.tsv b/internal/cli/testdata/golden/pulsecheck-certificate-get.tsv new file mode 100644 index 0000000..158d6ab --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-certificate-get.tsv @@ -0,0 +1 @@ +CN=api.example.com CN=Example CA api.example.com 2026-08-17T12:00:00Z 2026-11-15T12:00:00Z 12 yes yes Expiring 04ab aa:bb 2026-11-03T08:00:00Z 30, 14, 7 2026-11-08T12:00:00Z 7 diff --git a/internal/cli/testdata/golden/pulsecheck-certificate-get.txt b/internal/cli/testdata/golden/pulsecheck-certificate-get.txt new file mode 100644 index 0000000..1235548 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-certificate-get.txt @@ -0,0 +1,15 @@ +Subject: CN=api.example.com +Issuer: CN=Example CA +Names: api.example.com +Valid from: 2026-08-17 14:00 +Expires: 2026-11-15 14:00 +Days left: 12 +Chain valid: yes +Hostname valid: yes +Status: Expiring +Serial: 04ab +SHA-256: aa:bb +Seen: 2026-11-03 10:00 +Alert at days: 30, 14, 7 +Next alert: 2026-11-08 14:00 +Next alert at days: 7 diff --git a/internal/cli/testdata/golden/pulsecheck-certificate-get.yaml b/internal/cli/testdata/golden/pulsecheck-certificate-get.yaml new file mode 100644 index 0000000..5065c34 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-certificate-get.yaml @@ -0,0 +1,23 @@ +certificate: + chainValid: true + daysRemaining: 12 + dnsNames: + - api.example.com + fingerprintSha256: aa:bb + hostnameValid: true + issuer: CN=Example CA + notAfter: "2026-11-15T12:00:00Z" + notBefore: "2026-08-17T12:00:00Z" + serialNumber: 04ab + subject: CN=api.example.com +checkedAt: "2026-11-03T08:00:00Z" +condition: cert_expiring +daysRemaining: 12 +nextThresholdAt: "2026-11-08T12:00:00Z" +nextThresholdDays: 7 +resultId: 77 +severity: warning +thresholdsDays: + - 30 + - 14 + - 7 diff --git a/internal/cli/testdata/golden/pulsecheck-channels-get.json b/internal/cli/testdata/golden/pulsecheck-channels-get.json new file mode 100644 index 0000000..fbbfcbb --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-channels-get.json @@ -0,0 +1,13 @@ +{ + "createdAt": "2026-10-01T09:00:00Z", + "enabled": true, + "id": "0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f", + "isDefault": true, + "kind": "webhook", + "name": "On-call webhook", + "settings": { + "url": "https://hooks.example.com/pulsecheck" + }, + "updatedAt": "2026-10-01T09:00:00Z", + "verified": true +} diff --git a/internal/cli/testdata/golden/pulsecheck-channels-get.tsv b/internal/cli/testdata/golden/pulsecheck-channels-get.tsv new file mode 100644 index 0000000..eb55b7a --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-channels-get.tsv @@ -0,0 +1 @@ +0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f On-call webhook webhook https://hooks.example.com/pulsecheck yes yes yes 2026-10-01T09:00:00Z 2026-10-01T09:00:00Z diff --git a/internal/cli/testdata/golden/pulsecheck-channels-get.txt b/internal/cli/testdata/golden/pulsecheck-channels-get.txt new file mode 100644 index 0000000..7825cb8 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-channels-get.txt @@ -0,0 +1,9 @@ +ID: 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f +Name: On-call webhook +Kind: webhook +Destination: https://hooks.example.com/pulsecheck +Default: yes +Enabled: yes +Verified: yes +Created: 2026-10-01 11:00 +Updated: 2026-10-01 11:00 diff --git a/internal/cli/testdata/golden/pulsecheck-channels-get.yaml b/internal/cli/testdata/golden/pulsecheck-channels-get.yaml new file mode 100644 index 0000000..f89c1e1 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-channels-get.yaml @@ -0,0 +1,10 @@ +createdAt: "2026-10-01T09:00:00Z" +enabled: true +id: 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f +isDefault: true +kind: webhook +name: On-call webhook +settings: + url: https://hooks.example.com/pulsecheck +updatedAt: "2026-10-01T09:00:00Z" +verified: true diff --git a/internal/cli/testdata/golden/pulsecheck-channels-list.json b/internal/cli/testdata/golden/pulsecheck-channels-list.json new file mode 100644 index 0000000..5107631 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-channels-list.json @@ -0,0 +1,28 @@ +[ + { + "createdAt": "2026-10-01T09:00:00Z", + "enabled": true, + "id": "0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f", + "isDefault": true, + "kind": "webhook", + "name": "On-call webhook", + "settings": { + "url": "https://hooks.example.com/pulsecheck" + }, + "updatedAt": "2026-10-01T09:00:00Z", + "verified": true + }, + { + "createdAt": "2026-10-05T09:00:00Z", + "enabled": true, + "id": "5e6f7a8b-9c0d-4e1f-8a2b-3c4d5e6f7a8b", + "isDefault": false, + "kind": "sms", + "name": "On-call phone", + "settings": { + "phone": "+420601123456" + }, + "updatedAt": "2026-10-05T09:00:00Z", + "verified": false + } +] diff --git a/internal/cli/testdata/golden/pulsecheck-channels-list.tsv b/internal/cli/testdata/golden/pulsecheck-channels-list.tsv new file mode 100644 index 0000000..f180bf6 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-channels-list.tsv @@ -0,0 +1,2 @@ +0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f On-call webhook webhook https://hooks.example.com/pulsecheck yes yes yes +5e6f7a8b-9c0d-4e1f-8a2b-3c4d5e6f7a8b On-call phone sms +420601123456 no yes no diff --git a/internal/cli/testdata/golden/pulsecheck-channels-list.txt b/internal/cli/testdata/golden/pulsecheck-channels-list.txt new file mode 100644 index 0000000..b2fcd40 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-channels-list.txt @@ -0,0 +1,3 @@ +ID NAME KIND DESTINATION DEFAULT ENABLED VERIFIED +0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f On-call webhook webhook https://hooks.example.com/pulsecheck yes yes yes +5e6f7a8b-9c0d-4e1f-8a2b-3c4d5e6f7a8b On-call phone sms +420601123456 no yes no diff --git a/internal/cli/testdata/golden/pulsecheck-channels-list.yaml b/internal/cli/testdata/golden/pulsecheck-channels-list.yaml new file mode 100644 index 0000000..0cae600 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-channels-list.yaml @@ -0,0 +1,20 @@ +- createdAt: "2026-10-01T09:00:00Z" + enabled: true + id: 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f + isDefault: true + kind: webhook + name: On-call webhook + settings: + url: https://hooks.example.com/pulsecheck + updatedAt: "2026-10-01T09:00:00Z" + verified: true +- createdAt: "2026-10-05T09:00:00Z" + enabled: true + id: 5e6f7a8b-9c0d-4e1f-8a2b-3c4d5e6f7a8b + isDefault: false + kind: sms + name: On-call phone + settings: + phone: "+420601123456" + updatedAt: "2026-10-05T09:00:00Z" + verified: false diff --git a/internal/cli/testdata/golden/pulsecheck-deliveries-list.json b/internal/cli/testdata/golden/pulsecheck-deliveries-list.json new file mode 100644 index 0000000..2c52bde --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-deliveries-list.json @@ -0,0 +1,13 @@ +[ + { + "attempts": 1, + "createdAt": "2026-11-03T08:01:00Z", + "event": "down", + "id": "bbbbbbbb-cccc-4ddd-8eee-ffffffffffff", + "incidentId": "3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10", + "monitorId": "7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f", + "monitorName": "Shop", + "sentAt": "2026-11-03T08:01:02Z", + "status": "sent" + } +] diff --git a/internal/cli/testdata/golden/pulsecheck-deliveries-list.tsv b/internal/cli/testdata/golden/pulsecheck-deliveries-list.tsv new file mode 100644 index 0000000..64862b7 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-deliveries-list.tsv @@ -0,0 +1 @@ +2026-11-03T08:01:00Z down Shop sent 1 2026-11-03T08:01:02Z diff --git a/internal/cli/testdata/golden/pulsecheck-deliveries-list.txt b/internal/cli/testdata/golden/pulsecheck-deliveries-list.txt new file mode 100644 index 0000000..5b3f95c --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-deliveries-list.txt @@ -0,0 +1,2 @@ +CREATED EVENT MONITOR STATUS ATTEMPTS SENT LAST ERROR +2026-11-03 10:01 down Shop sent 1 2026-11-03 10:01 — diff --git a/internal/cli/testdata/golden/pulsecheck-deliveries-list.yaml b/internal/cli/testdata/golden/pulsecheck-deliveries-list.yaml new file mode 100644 index 0000000..35c5a9d --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-deliveries-list.yaml @@ -0,0 +1,9 @@ +- attempts: 1 + createdAt: "2026-11-03T08:01:00Z" + event: down + id: bbbbbbbb-cccc-4ddd-8eee-ffffffffffff + incidentId: 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 + monitorId: 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f + monitorName: Shop + sentAt: "2026-11-03T08:01:02Z" + status: sent diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-get.json b/internal/cli/testdata/golden/pulsecheck-incidents-get.json new file mode 100644 index 0000000..3ce88ed --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-get.json @@ -0,0 +1,39 @@ +{ + "alerts": [ + { + "alertId": "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", + "attempts": 1, + "channelId": "0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f", + "channelKind": "webhook", + "channelName": "On-call webhook", + "event": "down", + "queuedAt": "2026-11-03T08:01:00Z", + "sentAt": "2026-11-03T08:01:02Z", + "status": "sent" + } + ], + "aspect": "availability", + "condition": "unexpected_status", + "durationSeconds": 540, + "facts": { + "statusCode": 503 + }, + "id": "3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10", + "monitorId": "7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f", + "monitorName": "Shop", + "monitorTarget": "https://shop.example.com/health", + "monitorType": "http", + "monitorVariant": "keyword", + "openedAt": "2026-11-03T08:01:00Z", + "peakSeverity": "critical", + "severity": "critical", + "status": "open", + "summary": "HTTP 503", + "timeline": [ + { + "at": "2026-11-03T08:01:00Z", + "type": "opened" + } + ], + "title": "Shop is down" +} diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-get.tsv b/internal/cli/testdata/golden/pulsecheck-incidents-get.tsv new file mode 100644 index 0000000..fb76da1 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-get.tsv @@ -0,0 +1 @@ +3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 open critical Shop Shop is down 2026-11-03T08:01:00Z 9m 0s no diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-get.txt b/internal/cli/testdata/golden/pulsecheck-incidents-get.txt new file mode 100644 index 0000000..ca8a8ad --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-get.txt @@ -0,0 +1,13 @@ +ID: 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 +Title: Shop is down +Status: open +Severity: critical (peak critical) +Monitor: Shop (keyword, https://shop.example.com/health) +Aspect: availability +Summary: HTTP 503 +Opened: 2026-11-03 10:01 +Resolved: — +Duration: 9m 0s +Acknowledged: no +Timeline: 2026-11-03 10:01 opened +Alerts: 2026-11-03 10:01 down to On-call webhook: sent (1 attempt) diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-get.yaml b/internal/cli/testdata/golden/pulsecheck-incidents-get.yaml new file mode 100644 index 0000000..2cbabbb --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-get.yaml @@ -0,0 +1,30 @@ +alerts: + - alertId: aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee + attempts: 1 + channelId: 0c2d4f6a-8b1e-4c3d-9e5f-7a6b5c4d3e2f + channelKind: webhook + channelName: On-call webhook + event: down + queuedAt: "2026-11-03T08:01:00Z" + sentAt: "2026-11-03T08:01:02Z" + status: sent +aspect: availability +condition: unexpected_status +durationSeconds: 540 +facts: + statusCode: 503 +id: 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 +monitorId: 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f +monitorName: Shop +monitorTarget: https://shop.example.com/health +monitorType: http +monitorVariant: keyword +openedAt: "2026-11-03T08:01:00Z" +peakSeverity: critical +severity: critical +status: open +summary: HTTP 503 +timeline: + - at: "2026-11-03T08:01:00Z" + type: opened +title: Shop is down diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-list.json b/internal/cli/testdata/golden/pulsecheck-incidents-list.json new file mode 100644 index 0000000..b03ee09 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-list.json @@ -0,0 +1,22 @@ +[ + { + "aspect": "availability", + "condition": "unexpected_status", + "durationSeconds": 540, + "facts": { + "statusCode": 503 + }, + "id": "3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10", + "monitorId": "7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f", + "monitorName": "Shop", + "monitorTarget": "https://shop.example.com/health", + "monitorType": "http", + "monitorVariant": "keyword", + "openedAt": "2026-11-03T08:01:00Z", + "peakSeverity": "critical", + "severity": "critical", + "status": "open", + "summary": "HTTP 503", + "title": "Shop is down" + } +] diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-list.tsv b/internal/cli/testdata/golden/pulsecheck-incidents-list.tsv new file mode 100644 index 0000000..fb76da1 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-list.tsv @@ -0,0 +1 @@ +3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 open critical Shop Shop is down 2026-11-03T08:01:00Z 9m 0s no diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-list.txt b/internal/cli/testdata/golden/pulsecheck-incidents-list.txt new file mode 100644 index 0000000..3a6208b --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-list.txt @@ -0,0 +1,2 @@ +ID STATUS SEVERITY MONITOR TITLE OPENED DURATION ACK +3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 open critical Shop Shop is down 2026-11-03 10:01 9m 0s no diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-list.yaml b/internal/cli/testdata/golden/pulsecheck-incidents-list.yaml new file mode 100644 index 0000000..503ef3c --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-list.yaml @@ -0,0 +1,17 @@ +- aspect: availability + condition: unexpected_status + durationSeconds: 540 + facts: + statusCode: 503 + id: 3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10 + monitorId: 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f + monitorName: Shop + monitorTarget: https://shop.example.com/health + monitorType: http + monitorVariant: keyword + openedAt: "2026-11-03T08:01:00Z" + peakSeverity: critical + severity: critical + status: open + summary: HTTP 503 + title: Shop is down diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-summary.json b/internal/cli/testdata/golden/pulsecheck-incidents-summary.json new file mode 100644 index 0000000..b5d715c --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-summary.json @@ -0,0 +1,11 @@ +{ + "mttrLast30dSeconds": 1260, + "open": { + "critical": 1, + "total": 1, + "unacknowledged": 1, + "warning": 0 + }, + "resolvedLast30d": 12, + "resolvedLast7d": 4 +} diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-summary.tsv b/internal/cli/testdata/golden/pulsecheck-incidents-summary.tsv new file mode 100644 index 0000000..fdf3fe7 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-summary.tsv @@ -0,0 +1 @@ +1 1 0 1 4 12 21m 0s diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-summary.txt b/internal/cli/testdata/golden/pulsecheck-incidents-summary.txt new file mode 100644 index 0000000..fcf5d98 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-summary.txt @@ -0,0 +1,7 @@ +Open: 1 +Critical: 1 +Warning: 0 +Unacknowledged: 1 +Resolved 7d: 4 +Resolved 30d: 12 +Mean time to resolve 30d: 21m 0s diff --git a/internal/cli/testdata/golden/pulsecheck-incidents-summary.yaml b/internal/cli/testdata/golden/pulsecheck-incidents-summary.yaml new file mode 100644 index 0000000..a5ae963 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-incidents-summary.yaml @@ -0,0 +1,8 @@ +mttrLast30dSeconds: 1260 +open: + critical: 1 + total: 1 + unacknowledged: 1 + warning: 0 +resolvedLast7d: 4 +resolvedLast30d: 12 diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.json b/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.json new file mode 100644 index 0000000..77edfae --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.json @@ -0,0 +1,53 @@ +{ + "aspects": [], + "condition": { + "alertedThresholds": [ + { + "alertedAt": "2026-11-01T00:00:00Z", + "days": 14 + } + ], + "code": "cert_expiring", + "facts": { + "daysRemaining": 12, + "expiresAt": "2026-11-15T12:00:00Z", + "thresholdDays": 14 + }, + "message": "Certificate expires in 12 days", + "since": "2026-11-01T00:00:00Z" + }, + "createdAt": "2026-10-02T09:00:00Z", + "createdBy": "11111111-2222-4333-8444-555555555555", + "description": "", + "id": "2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809", + "intervalSeconds": 3600, + "lastCheck": { + "at": "2026-11-03T08:00:00Z", + "condition": "cert_expiring", + "severity": "warning", + "totalMs": 95 + }, + "name": "API cert", + "overallStatus": "warning", + "regions": [ + { + "code": "eu-central-1", + "name": "Frankfurt" + } + ], + "ssl": { + "expiryThresholdsDays": [ + 30, + 14, + 7 + ], + "host": "api.example.com", + "port": 443 + }, + "status": "warning", + "statusSince": "2026-11-01T00:00:00Z", + "target": "api.example.com:443", + "type": "ssl", + "updatedAt": "2026-10-02T09:00:00Z", + "variant": "ssl" +} diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.tsv b/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.tsv new file mode 100644 index 0000000..eff1aa7 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.tsv @@ -0,0 +1 @@ +2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809 API cert ssl Expiring api.example.com:443 2026-11-03T08:00:00Z diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.txt b/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.txt new file mode 100644 index 0000000..7bd4da5 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.txt @@ -0,0 +1,15 @@ +ID: 2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809 +Name: API cert +Type: ssl +Target: api.example.com:443 +Status: Expiring +Since: 2026-11-01 02:00 +Reason: Certificate expires in 12 days +Days left: 12 +Interval: 1h +Last check: 2026-11-03 10:00 +Next check: — +Regions: Frankfurt +Host: api.example.com:443 +Alert at days: 30, 14, 7 +Created: 2026-10-02 11:00 diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.yaml b/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.yaml new file mode 100644 index 0000000..98574ff --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-get-ssl.yaml @@ -0,0 +1,40 @@ +aspects: [] +condition: + alertedThresholds: + - alertedAt: "2026-11-01T00:00:00Z" + days: 14 + code: cert_expiring + facts: + daysRemaining: 12 + expiresAt: "2026-11-15T12:00:00Z" + thresholdDays: 14 + message: Certificate expires in 12 days + since: "2026-11-01T00:00:00Z" +createdAt: "2026-10-02T09:00:00Z" +createdBy: 11111111-2222-4333-8444-555555555555 +description: "" +id: 2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809 +intervalSeconds: 3600 +lastCheck: + at: "2026-11-03T08:00:00Z" + condition: cert_expiring + severity: warning + totalMs: 95 +name: API cert +overallStatus: warning +regions: + - code: eu-central-1 + name: Frankfurt +ssl: + expiryThresholdsDays: + - 30 + - 14 + - 7 + host: api.example.com + port: 443 +status: warning +statusSince: "2026-11-01T00:00:00Z" +target: api.example.com:443 +type: ssl +updatedAt: "2026-10-02T09:00:00Z" +variant: ssl diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-get.json b/internal/cli/testdata/golden/pulsecheck-monitors-get.json new file mode 100644 index 0000000..a8f3122 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-get.json @@ -0,0 +1,98 @@ +{ + "aspects": [ + { + "alertedThresholds": [], + "aspect": "certificate", + "condition": "ok", + "daysRemaining": 64, + "status": "ok", + "subject": "shop.example.com", + "thresholdsDays": [ + 30, + 14, + 7 + ] + } + ], + "condition": { + "alertedThresholds": [], + "code": "unexpected_status", + "facts": { + "statusCode": 503 + }, + "message": "HTTP 503", + "since": "2026-11-03T08:00:00Z" + }, + "createdAt": "2026-10-01T09:00:00Z", + "createdBy": "11111111-2222-4333-8444-555555555555", + "description": "", + "http": { + "certificateExpiry": { + "thresholdsDays": [ + 30, + 14, + 7 + ] + }, + "expectedStatus": [ + "2xx" + ], + "followRedirects": true, + "headers": [ + { + "name": "Authorization", + "secret": true + }, + { + "name": "X-Env", + "secret": false, + "value": "prod" + } + ], + "keyword": "ok", + "keywordCaseSensitive": false, + "keywordMode": "present", + "maxRedirects": 5, + "method": "GET", + "slowThresholdMs": 1500, + "timeoutMs": 10000, + "url": "https://shop.example.com/health", + "verifyTls": true + }, + "id": "7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f", + "intervalSeconds": 60, + "last24h": { + "avgMs": 120, + "checks": 1440, + "critical": 20, + "from": "2026-11-02T08:00:00Z", + "inconclusive": 0, + "ok": 1420, + "p50Ms": 110, + "p95Ms": 240, + "uptimePercent": 98.61, + "warning": 0, + "warningPercent": 0 + }, + "lastCheck": { + "at": "2026-11-03T08:10:00Z", + "condition": "unexpected_status", + "severity": "critical", + "totalMs": 180 + }, + "name": "Shop", + "nextCheckAt": "2026-11-03T08:11:00Z", + "overallStatus": "critical", + "regions": [ + { + "code": "eu-central-1", + "name": "Frankfurt" + } + ], + "status": "critical", + "statusSince": "2026-11-03T08:00:00Z", + "target": "https://shop.example.com/health", + "type": "http", + "updatedAt": "2026-10-01T09:00:00Z", + "variant": "keyword" +} diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-get.tsv b/internal/cli/testdata/golden/pulsecheck-monitors-get.tsv new file mode 100644 index 0000000..eb9e7af --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-get.tsv @@ -0,0 +1 @@ +7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f Shop keyword Down https://shop.example.com/health 98.61% 2026-11-03T08:10:00Z diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-get.txt b/internal/cli/testdata/golden/pulsecheck-monitors-get.txt new file mode 100644 index 0000000..d029ca4 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-get.txt @@ -0,0 +1,24 @@ +ID: 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f +Name: Shop +Type: keyword +Target: https://shop.example.com/health +Status: Down +Since: 2026-11-03 10:00 +Reason: HTTP 503 +Certificate of shop.example.com: Valid (64 days left) +Interval: 1m +Uptime 24h: 98.61% +Response p95: 240 ms +Last check: 2026-11-03 10:10 +Next check: 2026-11-03 10:11 +Regions: Frankfurt +Request: GET https://shop.example.com/health +Expected status: 2xx +Timeout: 10000 ms +Slow above: 1500 ms +Keyword: "ok" must be present +Header Authorization: (secret) +Header X-Env: prod +Redirects: followed, at most 5 +Verify TLS: yes +Created: 2026-10-01 11:00 diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-get.yaml b/internal/cli/testdata/golden/pulsecheck-monitors-get.yaml new file mode 100644 index 0000000..4023714 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-get.yaml @@ -0,0 +1,76 @@ +aspects: + - alertedThresholds: [] + aspect: certificate + condition: ok + daysRemaining: 64 + status: ok + subject: shop.example.com + thresholdsDays: + - 30 + - 14 + - 7 +condition: + alertedThresholds: [] + code: unexpected_status + facts: + statusCode: 503 + message: HTTP 503 + since: "2026-11-03T08:00:00Z" +createdAt: "2026-10-01T09:00:00Z" +createdBy: 11111111-2222-4333-8444-555555555555 +description: "" +http: + certificateExpiry: + thresholdsDays: + - 30 + - 14 + - 7 + expectedStatus: + - 2xx + followRedirects: true + headers: + - name: Authorization + secret: true + - name: X-Env + secret: false + value: prod + keyword: ok + keywordCaseSensitive: false + keywordMode: present + maxRedirects: 5 + method: GET + slowThresholdMs: 1500 + timeoutMs: 10000 + url: https://shop.example.com/health + verifyTls: true +id: 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f +intervalSeconds: 60 +last24h: + avgMs: 120 + checks: 1440 + critical: 20 + from: "2026-11-02T08:00:00Z" + inconclusive: 0 + ok: 1420 + p50Ms: 110 + p95Ms: 240 + uptimePercent: 98.61 + warning: 0 + warningPercent: 0 +lastCheck: + at: "2026-11-03T08:10:00Z" + condition: unexpected_status + severity: critical + totalMs: 180 +name: Shop +nextCheckAt: "2026-11-03T08:11:00Z" +overallStatus: critical +regions: + - code: eu-central-1 + name: Frankfurt +status: critical +statusSince: "2026-11-03T08:00:00Z" +target: https://shop.example.com/health +type: http +updatedAt: "2026-10-01T09:00:00Z" +variant: keyword diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-list.json b/internal/cli/testdata/golden/pulsecheck-monitors-list.json new file mode 100644 index 0000000..828f81d --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-list.json @@ -0,0 +1,197 @@ +[ + { + "aspects": [ + { + "alertedThresholds": [], + "aspect": "certificate", + "condition": "ok", + "daysRemaining": 64, + "status": "ok", + "subject": "shop.example.com", + "thresholdsDays": [ + 30, + 14, + 7 + ] + } + ], + "condition": { + "alertedThresholds": [], + "code": "unexpected_status", + "facts": { + "statusCode": 503 + }, + "message": "HTTP 503", + "since": "2026-11-03T08:00:00Z" + }, + "createdAt": "2026-10-01T09:00:00Z", + "createdBy": "11111111-2222-4333-8444-555555555555", + "description": "", + "http": { + "certificateExpiry": { + "thresholdsDays": [ + 30, + 14, + 7 + ] + }, + "expectedStatus": [ + "2xx" + ], + "followRedirects": true, + "headers": [ + { + "name": "Authorization", + "secret": true + }, + { + "name": "X-Env", + "secret": false, + "value": "prod" + } + ], + "keyword": "ok", + "keywordCaseSensitive": false, + "keywordMode": "present", + "maxRedirects": 5, + "method": "GET", + "slowThresholdMs": 1500, + "timeoutMs": 10000, + "url": "https://shop.example.com/health", + "verifyTls": true + }, + "id": "7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f", + "intervalSeconds": 60, + "last24h": { + "avgMs": 120, + "checks": 1440, + "critical": 20, + "from": "2026-11-02T08:00:00Z", + "inconclusive": 0, + "ok": 1420, + "p50Ms": 110, + "p95Ms": 240, + "uptimePercent": 98.61, + "warning": 0, + "warningPercent": 0 + }, + "lastCheck": { + "at": "2026-11-03T08:10:00Z", + "condition": "unexpected_status", + "severity": "critical", + "totalMs": 180 + }, + "name": "Shop", + "nextCheckAt": "2026-11-03T08:11:00Z", + "overallStatus": "critical", + "regions": [ + { + "code": "eu-central-1", + "name": "Frankfurt" + } + ], + "status": "critical", + "statusSince": "2026-11-03T08:00:00Z", + "target": "https://shop.example.com/health", + "type": "http", + "updatedAt": "2026-10-01T09:00:00Z", + "variant": "keyword" + }, + { + "aspects": [], + "condition": { + "alertedThresholds": [ + { + "alertedAt": "2026-11-01T00:00:00Z", + "days": 14 + } + ], + "code": "cert_expiring", + "facts": { + "daysRemaining": 12, + "expiresAt": "2026-11-15T12:00:00Z", + "thresholdDays": 14 + }, + "message": "Certificate expires in 12 days", + "since": "2026-11-01T00:00:00Z" + }, + "createdAt": "2026-10-02T09:00:00Z", + "createdBy": "11111111-2222-4333-8444-555555555555", + "description": "", + "id": "2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809", + "intervalSeconds": 3600, + "lastCheck": { + "at": "2026-11-03T08:00:00Z", + "condition": "cert_expiring", + "severity": "warning", + "totalMs": 95 + }, + "name": "API cert", + "overallStatus": "warning", + "regions": [ + { + "code": "eu-central-1", + "name": "Frankfurt" + } + ], + "ssl": { + "expiryThresholdsDays": [ + 30, + 14, + 7 + ], + "host": "api.example.com", + "port": 443 + }, + "status": "warning", + "statusSince": "2026-11-01T00:00:00Z", + "target": "api.example.com:443", + "type": "ssl", + "updatedAt": "2026-10-02T09:00:00Z", + "variant": "ssl" + }, + { + "aspects": [], + "condition": { + "alertedThresholds": [], + "code": "ok", + "facts": { + "daysRemaining": 271 + }, + "message": "Registered until 2027-08-01", + "since": "2026-10-03T09:00:00Z" + }, + "createdAt": "2026-10-03T09:00:00Z", + "createdBy": "11111111-2222-4333-8444-555555555555", + "description": "Company domain", + "domain": { + "domain": "example.com", + "expiryThresholdsDays": [ + 60, + 30 + ] + }, + "id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d", + "intervalSeconds": 43200, + "lastCheck": { + "at": "2026-11-03T06:00:00Z", + "condition": "ok", + "severity": "ok", + "totalMs": 420 + }, + "name": "example.com", + "overallStatus": "ok", + "regions": [ + { + "code": "eu-central-1", + "name": "Frankfurt" + } + ], + "status": "ok", + "statusSince": "2026-10-03T09:00:00Z", + "target": "example.com", + "type": "domain", + "updatedAt": "2026-10-03T09:00:00Z", + "variant": "domain" + } +] diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-list.tsv b/internal/cli/testdata/golden/pulsecheck-monitors-list.tsv new file mode 100644 index 0000000..12c14aa --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-list.tsv @@ -0,0 +1,3 @@ +7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f Shop keyword Down https://shop.example.com/health 98.61% 2026-11-03T08:10:00Z +2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809 API cert ssl Expiring api.example.com:443 2026-11-03T08:00:00Z +9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d example.com domain Registered example.com 2026-11-03T06:00:00Z diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-list.txt b/internal/cli/testdata/golden/pulsecheck-monitors-list.txt new file mode 100644 index 0000000..5d484dc --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-list.txt @@ -0,0 +1,4 @@ +ID NAME TYPE STATUS TARGET UPTIME 24H LAST CHECK +7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f Shop keyword Down https://shop.example.com/health 98.61% 2026-11-03 10:10 +2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809 API cert ssl Expiring api.example.com:443 — 2026-11-03 10:00 +9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d example.com domain Registered example.com — 2026-11-03 08:00 diff --git a/internal/cli/testdata/golden/pulsecheck-monitors-list.yaml b/internal/cli/testdata/golden/pulsecheck-monitors-list.yaml new file mode 100644 index 0000000..1f6b96f --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-monitors-list.yaml @@ -0,0 +1,150 @@ +- aspects: + - alertedThresholds: [] + aspect: certificate + condition: ok + daysRemaining: 64 + status: ok + subject: shop.example.com + thresholdsDays: + - 30 + - 14 + - 7 + condition: + alertedThresholds: [] + code: unexpected_status + facts: + statusCode: 503 + message: HTTP 503 + since: "2026-11-03T08:00:00Z" + createdAt: "2026-10-01T09:00:00Z" + createdBy: 11111111-2222-4333-8444-555555555555 + description: "" + http: + certificateExpiry: + thresholdsDays: + - 30 + - 14 + - 7 + expectedStatus: + - 2xx + followRedirects: true + headers: + - name: Authorization + secret: true + - name: X-Env + secret: false + value: prod + keyword: ok + keywordCaseSensitive: false + keywordMode: present + maxRedirects: 5 + method: GET + slowThresholdMs: 1500 + timeoutMs: 10000 + url: https://shop.example.com/health + verifyTls: true + id: 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f + intervalSeconds: 60 + last24h: + avgMs: 120 + checks: 1440 + critical: 20 + from: "2026-11-02T08:00:00Z" + inconclusive: 0 + ok: 1420 + p50Ms: 110 + p95Ms: 240 + uptimePercent: 98.61 + warning: 0 + warningPercent: 0 + lastCheck: + at: "2026-11-03T08:10:00Z" + condition: unexpected_status + severity: critical + totalMs: 180 + name: Shop + nextCheckAt: "2026-11-03T08:11:00Z" + overallStatus: critical + regions: + - code: eu-central-1 + name: Frankfurt + status: critical + statusSince: "2026-11-03T08:00:00Z" + target: https://shop.example.com/health + type: http + updatedAt: "2026-10-01T09:00:00Z" + variant: keyword +- aspects: [] + condition: + alertedThresholds: + - alertedAt: "2026-11-01T00:00:00Z" + days: 14 + code: cert_expiring + facts: + daysRemaining: 12 + expiresAt: "2026-11-15T12:00:00Z" + thresholdDays: 14 + message: Certificate expires in 12 days + since: "2026-11-01T00:00:00Z" + createdAt: "2026-10-02T09:00:00Z" + createdBy: 11111111-2222-4333-8444-555555555555 + description: "" + id: 2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809 + intervalSeconds: 3600 + lastCheck: + at: "2026-11-03T08:00:00Z" + condition: cert_expiring + severity: warning + totalMs: 95 + name: API cert + overallStatus: warning + regions: + - code: eu-central-1 + name: Frankfurt + ssl: + expiryThresholdsDays: + - 30 + - 14 + - 7 + host: api.example.com + port: 443 + status: warning + statusSince: "2026-11-01T00:00:00Z" + target: api.example.com:443 + type: ssl + updatedAt: "2026-10-02T09:00:00Z" + variant: ssl +- aspects: [] + condition: + alertedThresholds: [] + code: ok + facts: + daysRemaining: 271 + message: Registered until 2027-08-01 + since: "2026-10-03T09:00:00Z" + createdAt: "2026-10-03T09:00:00Z" + createdBy: 11111111-2222-4333-8444-555555555555 + description: Company domain + domain: + domain: example.com + expiryThresholdsDays: + - 60 + - 30 + id: 9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d + intervalSeconds: 43200 + lastCheck: + at: "2026-11-03T06:00:00Z" + condition: ok + severity: ok + totalMs: 420 + name: example.com + overallStatus: ok + regions: + - code: eu-central-1 + name: Frankfurt + status: ok + statusSince: "2026-10-03T09:00:00Z" + target: example.com + type: domain + updatedAt: "2026-10-03T09:00:00Z" + variant: domain diff --git a/internal/cli/testdata/golden/pulsecheck-results-list.json b/internal/cli/testdata/golden/pulsecheck-results-list.json new file mode 100644 index 0000000..9bd9eaa --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-results-list.json @@ -0,0 +1,33 @@ +[ + { + "checkedAt": "2026-11-03T08:10:00Z", + "condition": "unexpected_status", + "errorMessage": "HTTP 503", + "id": 9002, + "region": "eu-central-1", + "severity": "critical", + "statusCode": 503, + "timings": { + "connectMs": 12, + "dnsMs": 4, + "tlsMs": 30, + "totalMs": 180, + "ttfbMs": 170 + } + }, + { + "checkedAt": "2026-11-03T07:59:00Z", + "condition": "ok", + "id": 9001, + "region": "eu-central-1", + "severity": "ok", + "statusCode": 200, + "timings": { + "connectMs": 11, + "dnsMs": 3, + "tlsMs": 28, + "totalMs": 110, + "ttfbMs": 100 + } + } +] diff --git a/internal/cli/testdata/golden/pulsecheck-results-list.tsv b/internal/cli/testdata/golden/pulsecheck-results-list.tsv new file mode 100644 index 0000000..a929221 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-results-list.tsv @@ -0,0 +1,2 @@ +9002 2026-11-03T08:10:00Z Down unexpected_status 503 180 ms eu-central-1 +9001 2026-11-03T07:59:00Z Up ok 200 110 ms eu-central-1 diff --git a/internal/cli/testdata/golden/pulsecheck-results-list.txt b/internal/cli/testdata/golden/pulsecheck-results-list.txt new file mode 100644 index 0000000..2cbeb75 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-results-list.txt @@ -0,0 +1,3 @@ +ID CHECKED RESULT CONDITION STATUS CODE TIME REGION +9002 2026-11-03 10:10:00 Down unexpected_status 503 180 ms eu-central-1 +9001 2026-11-03 09:59:00 Up ok 200 110 ms eu-central-1 diff --git a/internal/cli/testdata/golden/pulsecheck-results-list.yaml b/internal/cli/testdata/golden/pulsecheck-results-list.yaml new file mode 100644 index 0000000..193492e --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-results-list.yaml @@ -0,0 +1,25 @@ +- checkedAt: "2026-11-03T08:10:00Z" + condition: unexpected_status + errorMessage: HTTP 503 + id: 9002 + region: eu-central-1 + severity: critical + statusCode: 503 + timings: + connectMs: 12 + dnsMs: 4 + tlsMs: 30 + totalMs: 180 + ttfbMs: 170 +- checkedAt: "2026-11-03T07:59:00Z" + condition: ok + id: 9001 + region: eu-central-1 + severity: ok + statusCode: 200 + timings: + connectMs: 11 + dnsMs: 3 + tlsMs: 28 + totalMs: 110 + ttfbMs: 100 diff --git a/internal/cli/testdata/golden/pulsecheck-stats-get.json b/internal/cli/testdata/golden/pulsecheck-stats-get.json new file mode 100644 index 0000000..a5ff537 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-stats-get.json @@ -0,0 +1,14 @@ +{ + "avgMs": 120, + "checks": 1440, + "critical": 20, + "from": "2026-11-02T08:00:00Z", + "granularity": "hour", + "inconclusive": 0, + "maxMs": 980, + "ok": 1420, + "series": [], + "to": "2026-11-03T08:10:00Z", + "uptimePercent": 98.61, + "warning": 0 +} diff --git a/internal/cli/testdata/golden/pulsecheck-stats-get.tsv b/internal/cli/testdata/golden/pulsecheck-stats-get.tsv new file mode 100644 index 0000000..d7ca0ea --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-stats-get.tsv @@ -0,0 +1 @@ +2026-11-02T08:00:00Z 2026-11-03T08:10:00Z 98.61% 120 ms 980 ms 1440 1420 0 20 0 diff --git a/internal/cli/testdata/golden/pulsecheck-stats-get.txt b/internal/cli/testdata/golden/pulsecheck-stats-get.txt new file mode 100644 index 0000000..426918c --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-stats-get.txt @@ -0,0 +1,10 @@ +From: 2026-11-02 10:00 +To: 2026-11-03 10:10 +Uptime: 98.61% +Average: 120 ms +Slowest: 980 ms +Checks: 1440 +OK: 1420 +Warning: 0 +Critical: 20 +Inconclusive: 0 diff --git a/internal/cli/testdata/golden/pulsecheck-stats-get.yaml b/internal/cli/testdata/golden/pulsecheck-stats-get.yaml new file mode 100644 index 0000000..52efeea --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-stats-get.yaml @@ -0,0 +1,12 @@ +avgMs: 120 +checks: 1440 +critical: 20 +from: "2026-11-02T08:00:00Z" +granularity: hour +inconclusive: 0 +maxMs: 980 +ok: 1420 +series: [] +to: "2026-11-03T08:10:00Z" +uptimePercent: 98.61 +warning: 0 diff --git a/internal/cli/testdata/golden/pulsecheck-status-changes-list.json b/internal/cli/testdata/golden/pulsecheck-status-changes-list.json new file mode 100644 index 0000000..aeea162 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-status-changes-list.json @@ -0,0 +1,25 @@ +[ + { + "changedAt": "2026-11-03T08:00:00Z", + "checkResultId": 9000, + "condition": "unexpected_status", + "durationSeconds": 600, + "events": [], + "from": "ok", + "id": 2, + "message": "HTTP 503", + "statusCode": 503, + "to": "critical" + }, + { + "changedAt": "2026-10-01T09:01:00Z", + "checkResultId": 1, + "condition": "ok", + "durationSeconds": 2847540, + "endedAt": "2026-11-03T08:00:00Z", + "events": [], + "from": "pending", + "id": 1, + "to": "ok" + } +] diff --git a/internal/cli/testdata/golden/pulsecheck-status-changes-list.tsv b/internal/cli/testdata/golden/pulsecheck-status-changes-list.tsv new file mode 100644 index 0000000..2507db5 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-status-changes-list.tsv @@ -0,0 +1,2 @@ +2026-11-03T08:00:00Z Up Down 10m 0s unexpected_status HTTP 503 +2026-10-01T09:01:00Z Pending Up 32d 22h ok diff --git a/internal/cli/testdata/golden/pulsecheck-status-changes-list.txt b/internal/cli/testdata/golden/pulsecheck-status-changes-list.txt new file mode 100644 index 0000000..e60719a --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-status-changes-list.txt @@ -0,0 +1,3 @@ +CHANGED FROM TO FOR CONDITION MESSAGE +2026-11-03 10:00:00 Up Down 10m 0s unexpected_status HTTP 503 +2026-10-01 11:01:00 Pending Up 32d 22h ok — diff --git a/internal/cli/testdata/golden/pulsecheck-status-changes-list.yaml b/internal/cli/testdata/golden/pulsecheck-status-changes-list.yaml new file mode 100644 index 0000000..441625e --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-status-changes-list.yaml @@ -0,0 +1,19 @@ +- changedAt: "2026-11-03T08:00:00Z" + checkResultId: 9000 + condition: unexpected_status + durationSeconds: 600 + events: [] + from: ok + id: 2 + message: HTTP 503 + statusCode: 503 + to: critical +- changedAt: "2026-10-01T09:01:00Z" + checkResultId: 1 + condition: ok + durationSeconds: 2847540 + endedAt: "2026-11-03T08:00:00Z" + events: [] + from: pending + id: 1 + to: ok diff --git a/internal/cli/testdata/golden/pulsecheck-status.json b/internal/cli/testdata/golden/pulsecheck-status.json new file mode 100644 index 0000000..d681155 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-status.json @@ -0,0 +1,46 @@ +{ + "status": "critical", + "incidents": { + "mttrLast30dSeconds": 1260, + "open": { + "critical": 1, + "total": 1, + "unacknowledged": 1, + "warning": 0 + }, + "resolvedLast30d": 12, + "resolvedLast7d": 4 + }, + "monitors": { + "total": 3, + "ok": 1, + "warning": 1, + "critical": 1, + "pending": 0, + "paused": 0 + }, + "problems": [ + { + "id": "7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f", + "name": "Shop", + "type": "http", + "variant": "keyword", + "target": "https://shop.example.com/health", + "status": "critical", + "overallStatus": "critical", + "condition": "unexpected_status", + "message": "HTTP 503" + }, + { + "id": "2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809", + "name": "API cert", + "type": "ssl", + "variant": "ssl", + "target": "api.example.com:443", + "status": "warning", + "overallStatus": "warning", + "condition": "cert_expiring", + "message": "Certificate expires in 12 days" + } + ] +} diff --git a/internal/cli/testdata/golden/pulsecheck-status.tsv b/internal/cli/testdata/golden/pulsecheck-status.tsv new file mode 100644 index 0000000..d5db8b4 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-status.tsv @@ -0,0 +1 @@ +critical 1 1 0 1 3 (1 ok, 1 warning, 1 critical, 0 pending, 0 paused) Down: Shop (https://shop.example.com/health), HTTP 503 Expiring: API cert (api.example.com:443), Certificate expires in 12 days diff --git a/internal/cli/testdata/golden/pulsecheck-status.txt b/internal/cli/testdata/golden/pulsecheck-status.txt new file mode 100644 index 0000000..79b505c --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-status.txt @@ -0,0 +1,8 @@ +Status: critical +Open: 1 +Critical: 1 +Warning: 0 +Unacknowledged: 1 +Monitors: 3 (1 ok, 1 warning, 1 critical, 0 pending, 0 paused) +Problems: Down: Shop (https://shop.example.com/health), HTTP 503 + Expiring: API cert (api.example.com:443), Certificate expires in 12 days diff --git a/internal/cli/testdata/golden/pulsecheck-status.yaml b/internal/cli/testdata/golden/pulsecheck-status.yaml new file mode 100644 index 0000000..0f6a762 --- /dev/null +++ b/internal/cli/testdata/golden/pulsecheck-status.yaml @@ -0,0 +1,36 @@ +incidents: + mttrLast30dSeconds: 1260 + open: + critical: 1 + total: 1 + unacknowledged: 1 + warning: 0 + resolvedLast7d: 4 + resolvedLast30d: 12 +monitors: + critical: 1 + ok: 1 + paused: 0 + pending: 0 + total: 3 + warning: 1 +problems: + - condition: unexpected_status + id: 7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f + message: HTTP 503 + name: Shop + overallStatus: critical + status: critical + target: https://shop.example.com/health + type: http + variant: keyword + - condition: cert_expiring + id: 2b3c4d5e-6f70-4a81-92a3-b4c5d6e7f809 + message: Certificate expires in 12 days + name: API cert + overallStatus: warning + status: warning + target: api.example.com:443 + type: ssl + variant: ssl +status: critical diff --git a/internal/clierr/clierr_test.go b/internal/clierr/clierr_test.go index e527d00..ce12672 100644 --- a/internal/clierr/clierr_test.go +++ b/internal/clierr/clierr_test.go @@ -28,3 +28,12 @@ func TestIsUsage(t *testing.T) { t.Error("Usage(nil) must stay nil") } } + +// Codes that report an outcome rather than a failure of the CLI exit 1. +func TestOutcomeCodesExitOne(t *testing.T) { + for _, c := range []string{CodeJobFailed, CodeUnhealthy} { + if got := ExitFor(c); got != ExitError { + t.Errorf("%s exits %d, want %d", c, got, ExitError) + } + } +} diff --git a/internal/clierr/error.go b/internal/clierr/error.go index 859ffc0..13bbbb0 100644 --- a/internal/clierr/error.go +++ b/internal/clierr/error.go @@ -25,6 +25,10 @@ const ( // CodeJobFailed: a command waited (--wait) for a server-side job that // ended unsuccessfully. Exit code 1. CodeJobFailed = "job_failed" + // CodeUnhealthy: a command asked to fail on a state it reports + // (`pulsecheck status --fail-on`) found it, e.g. an open critical + // incident. Exit code 1; details hold what it found. + CodeUnhealthy = "unhealthy" ) // Error is a failure described for both people and scripts. Printed as diff --git a/internal/config/config.go b/internal/config/config.go index 46d6027..65ece50 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -148,6 +148,7 @@ type Config struct { Langsync string Domainradar string Billing string + Pulsecheck string Prompthub string User User @@ -169,6 +170,8 @@ func (c *Config) Endpoint(service string) string { return c.Domainradar case ServiceBilling: return c.Billing + case ServicePulsecheck: + return c.Pulsecheck case ServicePrompthub: return c.Prompthub } @@ -190,6 +193,8 @@ func (c *Config) SetEndpoint(service, url string) { c.Domainradar = url case ServiceBilling: c.Billing = url + case ServicePulsecheck: + c.Pulsecheck = url case ServicePrompthub: c.Prompthub = url } diff --git a/internal/config/environments.go b/internal/config/environments.go index e85edbc..3cd32b7 100644 --- a/internal/config/environments.go +++ b/internal/config/environments.go @@ -14,6 +14,7 @@ const ( ServiceLangsync = "langsync" ServiceDomainradar = "domainradar" ServiceBilling = "billing" + ServicePulsecheck = "pulsecheck" ServicePrompthub = "prompthub" ) diff --git a/internal/output/style.go b/internal/output/style.go index 1c875bf..34243c3 100644 --- a/internal/output/style.go +++ b/internal/output/style.go @@ -65,13 +65,15 @@ func (s styling) styleStatus(v string) string { return v } switch strings.ToLower(strings.TrimSpace(v)) { - case "success", "ok", "succeeded", "passed", "active", "ready", "completed", "done", "available": + case "success", "ok", "succeeded", "passed", "active", "ready", "completed", "done", "available", + "up", "valid", "registered": return successStyle.Render(v) - case "failed", "error", "errored", "denied", "rejected": + case "failed", "error", "errored", "denied", "rejected", + "down", "critical", "expired", "invalid", "unreachable", "can't check", "not registered", "dead": return failureStyle.Render(v) case "running", "pending", "queued", "in_progress", "starting", "scheduled", "processing", "generating": return runningStyle.Render(v) - case "partial", "warning", "deprecated": + case "partial", "warning", "deprecated", "expiring", "slow", "expiry unknown": return infoStyle.Render(v) case "inactive", "disabled", "off", "paused", "stopped", "cancelled": return dimStyle.Render(v) diff --git a/internal/output/text.go b/internal/output/text.go index 218a226..3b868a0 100644 --- a/internal/output/text.go +++ b/internal/output/text.go @@ -22,10 +22,14 @@ const placeholder = "—" // Object is a single resource. JSON and YAML encode Value; a table shows // Fields as aligned name/value lines; text prints the field values on one -// tab-separated line, in Fields order. +// tab-separated line, in Fields order, or Text when it is set. type Object struct { Value any Fields []Field + // Text, when set, is the record -o text prints instead of the field + // values: for objects whose fields depend on the resource (a monitor's + // settings by type), so the text columns stay fixed. + Text []string } // Field is one line of an Object's table view. @@ -58,6 +62,13 @@ func (o Object) writeTable(w io.Writer) error { } func (o Object) writeText(w io.Writer) error { + if o.Text != nil { + cells := make([]string, len(o.Text)) + for i, c := range o.Text { + cells[i] = textCell(c) + } + return writeLine(w, cells) + } cells := make([]string, len(o.Fields)) for i, f := range o.Fields { cells[i] = textCell(f.Value) diff --git a/internal/output/text_test.go b/internal/output/text_test.go index 52861a2..08fc418 100644 --- a/internal/output/text_test.go +++ b/internal/output/text_test.go @@ -117,3 +117,23 @@ func TestObjectAlignsMultiLineValues(t *testing.T) { t.Fatalf("%q, %v", b.String(), err) } } + +// An object's Text replaces its field values in -o text; the table still +// shows the fields. +func TestObjectTextRecord(t *testing.T) { + o := Object{Value: map[string]int{"a": 1}, Fields: []Field{{Name: "A", Value: "1"}, {Name: "Extra", Value: "x"}}, + Text: []string{"1", WhenString("2026-10-28T09:00:00Z")}} + var text, table strings.Builder + if err := Print(&text, FormatText, o); err != nil { + t.Fatal(err) + } + if got := text.String(); got != "1\t2026-10-28T09:00:00Z\n" { + t.Errorf("text %q", got) + } + if err := Print(&table, FormatTable, o); err != nil { + t.Fatal(err) + } + if !strings.Contains(table.String(), "Extra:") { + t.Errorf("table %q", table.String()) + } +} diff --git a/internal/registry/services.yaml b/internal/registry/services.yaml index 082fdf9..a35105b 100644 --- a/internal/registry/services.yaml +++ b/internal/registry/services.yaml @@ -62,6 +62,16 @@ services: file: backend_swagger.json package: billing + - key: pulsecheck + name: Norcube PulseCheck + command: pulsecheck + audience: pulsecheck + endpoint: https://pulsecheck.api.norcube.com/app/v1 + spec: + app: pulsecheck + file: app_swagger.json + package: pulsecheck + - key: prompthub name: PromptHub command: prompthub diff --git a/specs/pulsecheck.openapi.json b/specs/pulsecheck.openapi.json new file mode 100644 index 0000000..9c0e2c2 --- /dev/null +++ b/specs/pulsecheck.openapi.json @@ -0,0 +1,5377 @@ +{ + "components": { + "schemas": { + "constants.ErrorCode": { + "enum": [ + "INTERNAL_ERROR", + "VALIDATION_FAILED", + "INVALID_PAYLOAD", + "UNAUTHORIZED", + "FORBIDDEN", + "NOT_FOUND", + "METHOD_NOT_ALLOWED", + "ALREADY_EXISTS", + "CONFLICT", + "MANAGED_RESOURCE", + "LIMIT_REACHED", + "ORG_BLOCKED", + "PAYLOAD_TOO_LARGE", + "TOO_MANY_REQUESTS", + "UNAVAILABLE" + ], + "type": "string", + "x-enum-varnames": [ + "ErrorCodeInternal", + "ErrorCodeValidationFailed", + "ErrorCodeInvalidPayload", + "ErrorCodeUnauthorized", + "ErrorCodeForbidden", + "ErrorCodeNotFound", + "ErrorCodeMethodNotAllowed", + "ErrorCodeAlreadyExists", + "ErrorCodeConflict", + "ErrorCodeManagedResource", + "ErrorCodeLimitReached", + "ErrorCodeOrgBlocked", + "ErrorCodePayloadTooLarge", + "ErrorCodeTooManyRequests", + "ErrorCodeUnavailable" + ] + }, + "constants.ErrorReason": { + "enum": [ + "MONITOR_LIMIT", + "ALERT_CHANNEL_LIMIT", + "UNVERIFIED_CHANNEL_LIMIT", + "MISSING_ORGANIZATION_ID", + "INSUFFICIENT_SCOPE", + "CALLER_OUTSIDE_NAMESPACE", + "NOTHING_TO_VERIFY", + "ALREADY_VERIFIED", + "CODE_RECENTLY_SENT", + "CODE_EXPIRED", + "TOO_MANY_ATTEMPTS", + "CONTACT_UNVERIFIED", + "DELIVERY_REJECTED", + "CHANNEL_TYPE_UNAVAILABLE" + ], + "type": "string", + "x-enum-varnames": [ + "ErrorReasonMonitorLimit", + "ErrorReasonAlertChannelLimit", + "ErrorReasonUnverifiedChannelLimit", + "ErrorReasonMissingOrganizationID", + "ErrorReasonInsufficientScope", + "ErrorReasonCallerOutsideNamespace", + "ErrorReasonNothingToVerify", + "ErrorReasonAlreadyVerified", + "ErrorReasonCodeRecentlySent", + "ErrorReasonCodeExpired", + "ErrorReasonTooManyAttempts", + "ErrorReasonContactUnverified", + "ErrorReasonDeliveryRejected", + "ErrorReasonChannelTypeUnavailable" + ] + }, + "dto.AlertChannel": { + "properties": { + "createdAt": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "id": { + "format": "uuid", + "type": "string" + }, + "isDefault": { + "type": "boolean" + }, + "kind": { + "description": "Kind is how the channel delivers. voice is a voice-call channel made\nbefore calls were withdrawn: it stays disabled and gets no alerts;\nit can be renamed or deleted.", + "enum": [ + "email", + "webhook", + "slack", + "discord", + "sms", + "voice" + ], + "type": "string" + }, + "name": { + "type": "string" + }, + "settings": { + "$ref": "#/components/schemas/dto.AlertChannelSettings" + }, + "updatedAt": { + "type": "string" + }, + "verified": { + "description": "Verified is false for an SMS or email-address channel until\nits contact confirmed a code; such a channel gets no alerts.", + "type": "boolean" + } + }, + "required": [ + "createdAt", + "enabled", + "id", + "isDefault", + "kind", + "name", + "settings", + "updatedAt", + "verified" + ], + "type": "object" + }, + "dto.AlertChannelCreate": { + "properties": { + "isDefault": { + "description": "IsDefault channels get the alerts of monitors without their own\nalert settings.", + "example": true, + "type": "boolean" + }, + "kind": { + "enum": [ + "email", + "webhook", + "slack", + "discord", + "sms" + ], + "example": "webhook", + "type": "string" + }, + "name": { + "example": "On-call webhook", + "type": "string" + }, + "settings": { + "$ref": "#/components/schemas/dto.AlertChannelSettingsInput" + } + }, + "required": [ + "kind", + "name", + "settings" + ], + "type": "object" + }, + "dto.AlertChannelSettings": { + "properties": { + "address": { + "type": "string" + }, + "hint": { + "example": "hooks.slack.com/…a1b2", + "type": "string" + }, + "members": { + "type": "boolean" + }, + "phone": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "type": "object" + }, + "dto.AlertChannelSettingsInput": { + "properties": { + "address": { + "example": "ops@example.com", + "type": "string" + }, + "members": { + "type": "boolean" + }, + "phone": { + "example": "+420601123456", + "type": "string" + }, + "signingSecret": { + "type": "string" + }, + "url": { + "example": "https://example.com/hooks/pulsecheck", + "type": "string" + } + }, + "type": "object" + }, + "dto.AlertChannelTestResult": { + "properties": { + "providerRef": { + "type": "string" + } + }, + "required": [ + "providerRef" + ], + "type": "object" + }, + "dto.AlertChannelUpdate": { + "properties": { + "enabled": { + "type": "boolean" + }, + "isDefault": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "rotateSecret": { + "type": "boolean" + }, + "settings": { + "$ref": "#/components/schemas/dto.AlertChannelSettingsInput" + } + }, + "type": "object" + }, + "dto.AlertChannelVerifyConfirm": { + "properties": { + "code": { + "example": "123456", + "type": "string" + } + }, + "required": [ + "code" + ], + "type": "object" + }, + "dto.AlertChannelWithSecret": { + "properties": { + "createdAt": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "id": { + "format": "uuid", + "type": "string" + }, + "isDefault": { + "type": "boolean" + }, + "kind": { + "description": "Kind is how the channel delivers. voice is a voice-call channel made\nbefore calls were withdrawn: it stays disabled and gets no alerts;\nit can be renamed or deleted.", + "enum": [ + "email", + "webhook", + "slack", + "discord", + "sms", + "voice" + ], + "type": "string" + }, + "name": { + "type": "string" + }, + "settings": { + "$ref": "#/components/schemas/dto.AlertChannelSettings" + }, + "signingSecret": { + "example": "whsec_…", + "type": "string" + }, + "updatedAt": { + "type": "string" + }, + "verified": { + "description": "Verified is false for an SMS or email-address channel until\nits contact confirmed a code; such a channel gets no alerts.", + "type": "boolean" + } + }, + "required": [ + "createdAt", + "enabled", + "id", + "isDefault", + "kind", + "name", + "settings", + "updatedAt", + "verified" + ], + "type": "object" + }, + "dto.Availability": { + "properties": { + "checks": { + "type": "integer" + }, + "critical": { + "type": "integer" + }, + "days": { + "items": { + "$ref": "#/components/schemas/dto.DayAvailability" + }, + "type": "array" + }, + "downtimeMinutes": { + "type": "integer" + }, + "from": { + "type": "string" + }, + "inconclusive": { + "type": "integer" + }, + "ok": { + "type": "integer" + }, + "to": { + "type": "string" + }, + "uptimePercent": { + "description": "UptimePercent is (ok + warning) / (ok + warning + critical); absent\nwithout conclusive checks, and for SSL and domain monitors (no\nuptime: their downtime is always 0).", + "example": 99.98, + "type": "number" + }, + "warning": { + "type": "integer" + } + }, + "required": [ + "checks", + "critical", + "days", + "downtimeMinutes", + "from", + "inconclusive", + "ok", + "to", + "warning" + ], + "type": "object" + }, + "dto.Certificate": { + "properties": { + "chain": { + "description": "Chain is what the server presented, leaf first; absent on results\nrecorded before chains were kept.", + "items": { + "$ref": "#/components/schemas/dto.ChainCertificate" + }, + "type": "array" + }, + "chainValid": { + "type": "boolean" + }, + "daysRemaining": { + "type": "integer" + }, + "dnsNames": { + "description": "DNSNames are the subject alternative names (SANs).", + "items": { + "type": "string" + }, + "type": "array" + }, + "fingerprintSha256": { + "description": "FingerprintSHA256 is the SHA-256 of the certificate (DER), hex.", + "example": "5f1c…", + "type": "string" + }, + "hostnameValid": { + "type": "boolean" + }, + "issuer": { + "type": "string" + }, + "issuerOrg": { + "type": "string" + }, + "notAfter": { + "type": "string" + }, + "notBefore": { + "type": "string" + }, + "serialNumber": { + "example": "3a1f…", + "type": "string" + }, + "signatureAlgorithm": { + "description": "SignatureAlgorithm as Go names it (\"SHA256-RSA\", \"ECDSA-SHA384\").", + "example": "ECDSA-SHA384", + "type": "string" + }, + "subject": { + "type": "string" + }, + "verifiedChainLength": { + "description": "VerifiedChainLength counts the certificates from the leaf to a\ntrusted root, root included; absent when the chain doesn't verify.", + "example": 3, + "type": "integer" + } + }, + "required": [ + "chainValid", + "daysRemaining", + "hostnameValid", + "issuer", + "notAfter", + "notBefore", + "subject" + ], + "type": "object" + }, + "dto.CertificateRenewal": { + "properties": { + "current": { + "$ref": "#/components/schemas/dto.RenewedCertificate" + }, + "previous": { + "$ref": "#/components/schemas/dto.RenewedCertificate" + } + }, + "required": [ + "current", + "previous" + ], + "type": "object" + }, + "dto.ChainCertificate": { + "properties": { + "isCA": { + "type": "boolean" + }, + "issuer": { + "type": "string" + }, + "notAfter": { + "type": "string" + }, + "notBefore": { + "type": "string" + }, + "subject": { + "type": "string" + } + }, + "required": [ + "isCA", + "issuer", + "notAfter", + "notBefore", + "subject" + ], + "type": "object" + }, + "dto.ChannelDelivery": { + "properties": { + "attempts": { + "type": "integer" + }, + "createdAt": { + "type": "string" + }, + "event": { + "enum": [ + "down", + "warning", + "expiring", + "expired", + "recovered", + "reminder" + ], + "type": "string" + }, + "id": { + "format": "uuid", + "type": "string" + }, + "incidentId": { + "description": "IncidentID is absent for an alert outside an incident.", + "format": "uuid", + "type": "string" + }, + "lastError": { + "example": "endpoint answered 410", + "type": "string" + }, + "monitorId": { + "format": "uuid", + "type": "string" + }, + "monitorName": { + "type": "string" + }, + "nextAttemptAt": { + "description": "NextAttemptAt is set while pending.", + "type": "string" + }, + "sentAt": { + "type": "string" + }, + "status": { + "description": "Status: pending (queued or waiting to retry), sent, dead (gave up).", + "enum": [ + "pending", + "sent", + "dead" + ], + "type": "string" + } + }, + "required": [ + "attempts", + "createdAt", + "event", + "id", + "monitorId", + "monitorName", + "status" + ], + "type": "object" + }, + "dto.CheckRegion": { + "properties": { + "code": { + "description": "Code is the AWS region code, as results' region carries it.", + "example": "eu-central-1", + "type": "string" + }, + "name": { + "description": "Name is the city people know the region by.", + "example": "Frankfurt", + "type": "string" + } + }, + "required": [ + "code", + "name" + ], + "type": "object" + }, + "dto.CheckResult": { + "properties": { + "certificate": { + "$ref": "#/components/schemas/dto.Certificate" + }, + "checkedAt": { + "type": "string" + }, + "condition": { + "example": "ok", + "type": "string" + }, + "domain": { + "$ref": "#/components/schemas/dto.DomainRegistration" + }, + "errorMessage": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "redirects": { + "items": { + "type": "string" + }, + "type": "array" + }, + "region": { + "example": "eu-central-1", + "type": "string" + }, + "severity": { + "enum": [ + "ok", + "warning", + "critical", + "inconclusive" + ], + "type": "string" + }, + "statusCode": { + "type": "integer" + }, + "timings": { + "$ref": "#/components/schemas/dto.CheckTimings" + } + }, + "required": [ + "checkedAt", + "condition", + "id", + "region", + "severity", + "timings" + ], + "type": "object" + }, + "dto.CheckTimings": { + "properties": { + "connectMs": { + "nullable": true, + "type": "integer" + }, + "dnsMs": { + "nullable": true, + "type": "integer" + }, + "redirectMs": { + "nullable": true, + "type": "integer" + }, + "tlsMs": { + "nullable": true, + "type": "integer" + }, + "totalMs": { + "type": "integer" + }, + "ttfbMs": { + "nullable": true, + "type": "integer" + } + }, + "required": [ + "totalMs" + ], + "type": "object" + }, + "dto.ConditionFacts": { + "properties": { + "daysRemaining": { + "example": 5, + "type": "integer" + }, + "expiresAt": { + "type": "string" + }, + "responseTimeMs": { + "description": "ResponseTimeMs and SlowThresholdMs: a slow response's time and the\nthreshold it went over (slow_response only).", + "example": 1503, + "type": "integer" + }, + "slowThresholdMs": { + "example": 500, + "type": "integer" + }, + "statusCode": { + "example": 503, + "type": "integer" + }, + "thresholdDays": { + "description": "ThresholdDays is the smallest expiry threshold the expiry is within.", + "example": 7, + "type": "integer" + } + }, + "type": "object" + }, + "dto.DayAvailability": { + "properties": { + "checks": { + "type": "integer" + }, + "critical": { + "type": "integer" + }, + "date": { + "description": "Date is the UTC day, YYYY-MM-DD.", + "example": "2026-10-29", + "type": "string" + }, + "downtimeMinutes": { + "description": "DowntimeMinutes estimates the time spent down: the share of\ncritical checks among the conclusive ones times the minutes the\nday's checks cover. A warning is not downtime.", + "type": "integer" + }, + "inconclusive": { + "type": "integer" + }, + "noData": { + "description": "NoData: no checks that day (draw it gray, never as up).", + "type": "boolean" + }, + "ok": { + "type": "integer" + }, + "uptimePercent": { + "example": 100, + "type": "number" + }, + "warning": { + "type": "integer" + } + }, + "required": [ + "checks", + "critical", + "date", + "downtimeMinutes", + "inconclusive", + "noData", + "ok", + "warning" + ], + "type": "object" + }, + "dto.DomainRegistration": { + "properties": { + "checkedAt": { + "description": "CheckedAt is when the registry was asked (lookups are cached up to\nan hour).", + "type": "string" + }, + "daysRemaining": { + "description": "DaysRemaining is 0 on the expiry day, negative after it.", + "type": "integer" + }, + "dnssec": { + "description": "DNSSEC: signed when the registry holds DS records for the domain;\nabsent when the registry doesn't say.", + "enum": [ + "signed", + "unsigned" + ], + "example": "signed", + "type": "string" + }, + "domain": { + "type": "string" + }, + "expiresAt": { + "description": "ExpiresAt is the expiry date at 00:00 UTC; absent when the registry\npublishes none.", + "type": "string" + }, + "nameservers": { + "description": "Nameservers are the delegation's nameservers, lower case, in the\nregistry's order; [] when unknown (results recorded before they were\nkept, registries that publish none).", + "example": [ + "a.iana-servers.net", + "b.iana-servers.net" + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "registered": { + "type": "boolean" + }, + "registeredAt": { + "description": "RegisteredAt is the registration (creation) date at 00:00 UTC, and\nUpdatedAt the registry's last change of it; absent when the registry\ndoesn't publish them (and for dns answers).", + "type": "string" + }, + "registrar": { + "type": "string" + }, + "source": { + "enum": [ + "rdap", + "whois", + "dns" + ], + "type": "string" + }, + "statusCodes": { + "description": "StatusCodes are the EPP status codes (RFC 5731), e.g. ok,\nclientTransferProhibited, serverHold, pendingDelete,\nredemptionPeriod; [] when unknown (dns answers).", + "example": [ + "clientDeleteProhibited", + "clientTransferProhibited" + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "updatedAt": { + "type": "string" + } + }, + "required": [ + "checkedAt", + "domain", + "nameservers", + "registered", + "source", + "statusCodes" + ], + "type": "object" + }, + "dto.DomainSettings": { + "properties": { + "domain": { + "type": "string" + }, + "expiryThresholdsDays": { + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "domain", + "expiryThresholdsDays" + ], + "type": "object" + }, + "dto.DomainSettingsInput": { + "properties": { + "domain": { + "example": "example.com", + "type": "string" + }, + "expiryThresholdsDays": { + "example": [ + 30, + 14, + 7 + ], + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "domain", + "expiryThresholdsDays" + ], + "type": "object" + }, + "dto.ExpiryWatch": { + "properties": { + "thresholdsDays": { + "example": [ + 30, + 14, + 7 + ], + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "thresholdsDays" + ], + "type": "object" + }, + "dto.ExpiryWatchInput": { + "properties": { + "thresholdsDays": { + "description": "ThresholdsDays are the expiry warnings, in days before expiry.", + "example": [ + 30, + 14, + 7 + ], + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "thresholdsDays" + ], + "type": "object" + }, + "dto.HTTPHeader": { + "properties": { + "name": { + "type": "string" + }, + "secret": { + "type": "boolean" + }, + "value": { + "type": "string" + } + }, + "required": [ + "name", + "secret" + ], + "type": "object" + }, + "dto.HTTPHeaderInput": { + "properties": { + "name": { + "example": "Authorization", + "type": "string" + }, + "secret": { + "example": true, + "type": "boolean" + }, + "value": { + "example": "Bearer …", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "dto.HTTPSettings": { + "properties": { + "certificateExpiry": { + "allOf": [ + { + "$ref": "#/components/schemas/dto.ExpiryWatch" + } + ], + "description": "CertificateExpiry and DomainExpiry are the watches that are on;\nabsent when off." + }, + "domainExpiry": { + "$ref": "#/components/schemas/dto.ExpiryWatch" + }, + "expectedStatus": { + "items": { + "type": "string" + }, + "type": "array" + }, + "followRedirects": { + "type": "boolean" + }, + "headers": { + "items": { + "$ref": "#/components/schemas/dto.HTTPHeader" + }, + "type": "array" + }, + "keyword": { + "type": "string" + }, + "keywordCaseSensitive": { + "type": "boolean" + }, + "keywordMode": { + "type": "string" + }, + "maxRedirects": { + "type": "integer" + }, + "method": { + "type": "string" + }, + "requestBody": { + "type": "string" + }, + "requestBodyContentType": { + "type": "string" + }, + "slowThresholdMs": { + "type": "integer" + }, + "timeoutMs": { + "type": "integer" + }, + "url": { + "type": "string" + }, + "verifyTls": { + "type": "boolean" + } + }, + "required": [ + "expectedStatus", + "followRedirects", + "headers", + "keywordCaseSensitive", + "maxRedirects", + "method", + "timeoutMs", + "url", + "verifyTls" + ], + "type": "object" + }, + "dto.HTTPSettingsInput": { + "properties": { + "certificateExpiry": { + "allOf": [ + { + "$ref": "#/components/schemas/dto.ExpiryWatchInput" + } + ], + "description": "CertificateExpiry watches the expiry of the certificate the URL\npresents (https:// URLs only), judged with every check; omit it to\nleave the watch off." + }, + "domainExpiry": { + "allOf": [ + { + "$ref": "#/components/schemas/dto.ExpiryWatchInput" + } + ], + "description": "DomainExpiry watches the registration of the URL's registrable\ndomain (shop.example.com watches example.com), looked up twice a\nday; omit it to leave the watch off. Not for IP addresses." + }, + "expectedStatus": { + "example": [ + "2xx", + "301" + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "followRedirects": { + "example": true, + "type": "boolean" + }, + "headers": { + "items": { + "$ref": "#/components/schemas/dto.HTTPHeaderInput" + }, + "type": "array" + }, + "keyword": { + "description": "Keyword is looked for in the first 256 KiB of the response body.", + "example": "All systems operational", + "type": "string" + }, + "keywordCaseSensitive": { + "type": "boolean" + }, + "keywordMode": { + "enum": [ + "present", + "absent" + ], + "type": "string" + }, + "maxRedirects": { + "example": 5, + "maximum": 10, + "minimum": 0, + "type": "integer" + }, + "method": { + "enum": [ + "GET", + "HEAD", + "POST", + "PUT", + "PATCH", + "DELETE", + "OPTIONS" + ], + "example": "GET", + "type": "string" + }, + "requestBody": { + "type": "string" + }, + "requestBodyContentType": { + "example": "application/json", + "type": "string" + }, + "slowThresholdMs": { + "example": 2000, + "type": "integer" + }, + "timeoutMs": { + "example": 10000, + "maximum": 30000, + "minimum": 1000, + "type": "integer" + }, + "url": { + "example": "https://example.com/health", + "type": "string" + }, + "verifyTls": { + "example": true, + "type": "boolean" + } + }, + "required": [ + "expectedStatus", + "followRedirects", + "maxRedirects", + "method", + "timeoutMs", + "url", + "verifyTls" + ], + "type": "object" + }, + "dto.HistoryBeat": { + "properties": { + "checkedAt": { + "type": "string" + }, + "condition": { + "example": "unexpected_status", + "type": "string" + }, + "responseTimeMs": { + "type": "integer" + }, + "resultId": { + "type": "integer" + }, + "severity": { + "enum": [ + "ok", + "warning", + "critical", + "inconclusive" + ], + "type": "string" + }, + "statusCode": { + "example": 503, + "type": "integer" + } + }, + "required": [ + "checkedAt", + "condition", + "responseTimeMs", + "resultId", + "severity" + ], + "type": "object" + }, + "dto.Incident": { + "properties": { + "acknowledgedAt": { + "type": "string" + }, + "acknowledgedBy": { + "format": "uuid", + "type": "string" + }, + "aspect": { + "description": "Aspect is what the incident is about.", + "enum": [ + "availability", + "certificate", + "domain" + ], + "type": "string" + }, + "condition": { + "description": "Condition is what the latest check that changed the incident found;\nsummary is its message, facts its facts.", + "example": "unexpected_status", + "type": "string" + }, + "durationSeconds": { + "description": "DurationSeconds is how long it lasted (or has lasted so far).", + "type": "integer" + }, + "facts": { + "$ref": "#/components/schemas/dto.ConditionFacts" + }, + "id": { + "format": "uuid", + "type": "string" + }, + "monitorId": { + "format": "uuid", + "type": "string" + }, + "monitorName": { + "type": "string" + }, + "monitorTarget": { + "example": "https://example.com/health", + "type": "string" + }, + "monitorType": { + "enum": [ + "http", + "ssl", + "domain" + ], + "type": "string" + }, + "monitorVariant": { + "description": "MonitorVariant names what the monitor does, as on monitor rows\n(keyword for an HTTP monitor with a keyword).", + "enum": [ + "http", + "keyword", + "ssl", + "domain" + ], + "type": "string" + }, + "openedAt": { + "type": "string" + }, + "peakSeverity": { + "enum": [ + "warning", + "critical" + ], + "type": "string" + }, + "resolvedAt": { + "type": "string" + }, + "severity": { + "description": "Severity is the current one; peakSeverity the worst it reached (a\nde-escalated incident stays open at warning).", + "enum": [ + "warning", + "critical" + ], + "type": "string" + }, + "status": { + "enum": [ + "open", + "resolved" + ], + "type": "string" + }, + "summary": { + "type": "string" + }, + "title": { + "description": "Title names the problem in the monitor type's words (an expiry's\ndays counted now, or when it ended).", + "example": "Certificate of example.com expires in 5 days", + "type": "string" + } + }, + "required": [ + "aspect", + "condition", + "durationSeconds", + "facts", + "id", + "monitorId", + "monitorName", + "monitorTarget", + "monitorType", + "monitorVariant", + "openedAt", + "peakSeverity", + "severity", + "status", + "summary", + "title" + ], + "type": "object" + }, + "dto.IncidentDelivery": { + "properties": { + "alertId": { + "description": "AlertID is the alert this delivery sends: an alert goes to every\nchannel of its route, one delivery each.", + "format": "uuid", + "type": "string" + }, + "attempts": { + "type": "integer" + }, + "channelId": { + "format": "uuid", + "type": "string" + }, + "channelKind": { + "type": "string" + }, + "channelName": { + "type": "string" + }, + "event": { + "enum": [ + "down", + "warning", + "expiring", + "expired", + "recovered", + "reminder" + ], + "type": "string" + }, + "lastError": { + "type": "string" + }, + "nextAttemptAt": { + "description": "NextAttemptAt is when a pending delivery is tried again.", + "type": "string" + }, + "queuedAt": { + "description": "QueuedAt is when the alert was queued: the time of the timeline\nentry that sent it (opened, escalated, threshold, reminder).", + "type": "string" + }, + "sentAt": { + "type": "string" + }, + "status": { + "enum": [ + "pending", + "sent", + "dead" + ], + "type": "string" + } + }, + "required": [ + "alertId", + "attempts", + "event", + "queuedAt", + "status" + ], + "type": "object" + }, + "dto.IncidentDetail": { + "properties": { + "acknowledgedAt": { + "type": "string" + }, + "acknowledgedBy": { + "format": "uuid", + "type": "string" + }, + "acknowledgedByName": { + "description": "AcknowledgedByName names who acknowledged it (their name, else\nemail); absent when nobody did or Norcube Auth couldn't say.", + "example": "Dev Owner", + "type": "string" + }, + "alerts": { + "items": { + "$ref": "#/components/schemas/dto.IncidentDelivery" + }, + "type": "array" + }, + "aspect": { + "description": "Aspect is what the incident is about.", + "enum": [ + "availability", + "certificate", + "domain" + ], + "type": "string" + }, + "condition": { + "description": "Condition is what the latest check that changed the incident found;\nsummary is its message, facts its facts.", + "example": "unexpected_status", + "type": "string" + }, + "durationSeconds": { + "description": "DurationSeconds is how long it lasted (or has lasted so far).", + "type": "integer" + }, + "facts": { + "$ref": "#/components/schemas/dto.ConditionFacts" + }, + "id": { + "format": "uuid", + "type": "string" + }, + "monitorId": { + "format": "uuid", + "type": "string" + }, + "monitorName": { + "type": "string" + }, + "monitorTarget": { + "example": "https://example.com/health", + "type": "string" + }, + "monitorType": { + "enum": [ + "http", + "ssl", + "domain" + ], + "type": "string" + }, + "monitorVariant": { + "description": "MonitorVariant names what the monitor does, as on monitor rows\n(keyword for an HTTP monitor with a keyword).", + "enum": [ + "http", + "keyword", + "ssl", + "domain" + ], + "type": "string" + }, + "openedAt": { + "type": "string" + }, + "peakSeverity": { + "enum": [ + "warning", + "critical" + ], + "type": "string" + }, + "resolvedAt": { + "type": "string" + }, + "severity": { + "description": "Severity is the current one; peakSeverity the worst it reached (a\nde-escalated incident stays open at warning).", + "enum": [ + "warning", + "critical" + ], + "type": "string" + }, + "status": { + "enum": [ + "open", + "resolved" + ], + "type": "string" + }, + "summary": { + "type": "string" + }, + "timeline": { + "items": { + "$ref": "#/components/schemas/dto.IncidentEvent" + }, + "type": "array" + }, + "title": { + "description": "Title names the problem in the monitor type's words (an expiry's\ndays counted now, or when it ended).", + "example": "Certificate of example.com expires in 5 days", + "type": "string" + } + }, + "required": [ + "alerts", + "aspect", + "condition", + "durationSeconds", + "facts", + "id", + "monitorId", + "monitorName", + "monitorTarget", + "monitorType", + "monitorVariant", + "openedAt", + "peakSeverity", + "severity", + "status", + "summary", + "timeline", + "title" + ], + "type": "object" + }, + "dto.IncidentEvent": { + "properties": { + "at": { + "type": "string" + }, + "detail": { + "additionalProperties": {}, + "type": "object" + }, + "type": { + "enum": [ + "opened", + "escalated", + "deescalated", + "threshold", + "reminder", + "acknowledged", + "resolved", + "delivery_failed" + ], + "type": "string" + } + }, + "required": [ + "at", + "type" + ], + "type": "object" + }, + "dto.IncidentOpenCounts": { + "properties": { + "critical": { + "example": 1, + "type": "integer" + }, + "total": { + "example": 3, + "type": "integer" + }, + "unacknowledged": { + "example": 2, + "type": "integer" + }, + "warning": { + "example": 2, + "type": "integer" + } + }, + "required": [ + "critical", + "total", + "unacknowledged", + "warning" + ], + "type": "object" + }, + "dto.IncidentSummary": { + "properties": { + "mttrLast30dSeconds": { + "description": "MttrLast30dSeconds is the mean time to resolve of those incidents;\nabsent when none was resolved.", + "example": 1260, + "type": "integer" + }, + "open": { + "$ref": "#/components/schemas/dto.IncidentOpenCounts" + }, + "resolvedLast30d": { + "description": "ResolvedLast30d counts incidents resolved in the last 30 days, the\nones mttrLast30dSeconds averages.", + "example": 12, + "type": "integer" + }, + "resolvedLast7d": { + "description": "ResolvedLast7d counts incidents resolved in the last 7 days.", + "example": 4, + "type": "integer" + } + }, + "required": [ + "open", + "resolvedLast30d", + "resolvedLast7d" + ], + "type": "object" + }, + "dto.LastCheck": { + "properties": { + "at": { + "type": "string" + }, + "condition": { + "example": "ok", + "type": "string" + }, + "severity": { + "enum": [ + "ok", + "warning", + "critical", + "inconclusive" + ], + "type": "string" + }, + "totalMs": { + "type": "integer" + } + }, + "required": [ + "at", + "condition", + "severity" + ], + "type": "object" + }, + "dto.Monitor": { + "properties": { + "aspects": { + "description": "Aspects are the monitor's watched aspects (an HTTP monitor's\ncertificate and domain watches that are on), on list rows too; []\nwithout watches.", + "items": { + "$ref": "#/components/schemas/dto.MonitorAspect" + }, + "type": "array" + }, + "condition": { + "allOf": [ + { + "$ref": "#/components/schemas/dto.MonitorCondition" + } + ], + "description": "Condition explains status; absent while pending." + }, + "createdAt": { + "type": "string" + }, + "createdBy": { + "format": "uuid", + "type": "string" + }, + "description": { + "type": "string" + }, + "domain": { + "$ref": "#/components/schemas/dto.DomainSettings" + }, + "history": { + "description": "History is set on list rows with include=history: the newest\nresults (at most 60), newest first; [] for a monitor never checked.", + "items": { + "$ref": "#/components/schemas/dto.HistoryBeat" + }, + "type": "array" + }, + "http": { + "$ref": "#/components/schemas/dto.HTTPSettings" + }, + "id": { + "format": "uuid", + "type": "string" + }, + "intervalSeconds": { + "type": "integer" + }, + "last24h": { + "allOf": [ + { + "$ref": "#/components/schemas/dto.WindowSummary" + } + ], + "description": "Last24h is set on list rows of monitors that track uptime (HTTP):\nthe last 24 full hours plus the current one. SSL and domain monitors\nshow days left (condition.facts) instead." + }, + "lastCheck": { + "$ref": "#/components/schemas/dto.LastCheck" + }, + "name": { + "type": "string" + }, + "nextCheckAt": { + "type": "string" + }, + "overallStatus": { + "description": "OverallStatus is the worst of status and the statuses of the\nmonitor's watched aspects (critical, warning, pending, ok), paused\nwhile disabled. The list status filter and sort use it.", + "enum": [ + "pending", + "ok", + "warning", + "critical", + "paused" + ], + "type": "string" + }, + "parentResource": { + "description": "ParentResource is set when the monitor belongs to a resource of\nanother Norcube service (\"domainradar:saved_domain:example.com\"). It\ncan't be deleted here, and its domain can't change.", + "example": "domainradar:saved_domain:example.com", + "type": "string" + }, + "regions": { + "description": "Regions are where the monitor is checked from, on list rows too.\nToday every monitor is checked from the one region the service runs\nin; with probes in more regions (planned) a monitor may list\nseveral. Each result says which region checked it (region).", + "items": { + "$ref": "#/components/schemas/dto.CheckRegion" + }, + "type": "array" + }, + "ssl": { + "$ref": "#/components/schemas/dto.SSLSettings" + }, + "status": { + "description": "Status is the primary aspect's: the severity of the last conclusive\ncheck, pending before one, paused while disabled. An inconclusive\ncheck (a failed registry lookup) never changes it.", + "enum": [ + "pending", + "ok", + "warning", + "critical", + "paused" + ], + "type": "string" + }, + "statusSince": { + "type": "string" + }, + "target": { + "example": "https://example.com/health", + "type": "string" + }, + "type": { + "enum": [ + "http", + "ssl", + "domain" + ], + "type": "string" + }, + "updatedAt": { + "type": "string" + }, + "variant": { + "description": "Variant is what the monitor does in one word, on list rows too\n(which carry no settings): keyword for an HTTP monitor that looks for\na keyword in the body, otherwise the type.", + "enum": [ + "http", + "keyword", + "ssl", + "domain" + ], + "example": "keyword", + "type": "string" + } + }, + "required": [ + "aspects", + "createdAt", + "createdBy", + "description", + "id", + "intervalSeconds", + "name", + "overallStatus", + "regions", + "status", + "statusSince", + "target", + "type", + "updatedAt", + "variant" + ], + "type": "object" + }, + "dto.MonitorAlertRoute": { + "properties": { + "channelId": { + "format": "uuid", + "type": "string" + }, + "events": { + "example": [ + "down", + "recovered" + ], + "items": { + "enum": [ + "down", + "warning", + "expiring", + "expired", + "recovered" + ], + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "channelId", + "events" + ], + "type": "object" + }, + "dto.MonitorAlerts": { + "properties": { + "applicableEvents": { + "description": "ApplicableEvents are the events monitors of this type can send\n(offer only these in a routing form).", + "example": [ + "down", + "warning", + "recovered" + ], + "items": { + "enum": [ + "down", + "warning", + "expiring", + "expired", + "recovered" + ], + "type": "string" + }, + "type": "array" + }, + "confirmFailures": { + "type": "integer" + }, + "confirmSuccesses": { + "type": "integer" + }, + "reminderMinutes": { + "type": "integer" + }, + "routes": { + "items": { + "$ref": "#/components/schemas/dto.MonitorAlertRoute" + }, + "type": "array" + }, + "useDefaults": { + "type": "boolean" + } + }, + "required": [ + "applicableEvents", + "confirmFailures", + "confirmSuccesses", + "reminderMinutes", + "routes", + "useDefaults" + ], + "type": "object" + }, + "dto.MonitorAlertsUpdate": { + "properties": { + "confirmFailures": { + "example": 2, + "maximum": 10, + "minimum": 1, + "type": "integer" + }, + "confirmSuccesses": { + "example": 1, + "maximum": 10, + "minimum": 1, + "type": "integer" + }, + "reminderMinutes": { + "example": 60, + "type": "integer" + }, + "routes": { + "items": { + "$ref": "#/components/schemas/dto.MonitorAlertRoute" + }, + "type": "array" + }, + "useDefaults": { + "type": "boolean" + } + }, + "type": "object" + }, + "dto.MonitorAspect": { + "properties": { + "alertedThresholds": { + "description": "AlertedThresholds are the expiry thresholds already alerted for the\ncurrent expiry, oldest first; [] before the first (or once renewed).", + "items": { + "$ref": "#/components/schemas/dto.ThresholdAlert" + }, + "type": "array" + }, + "aspect": { + "enum": [ + "certificate", + "domain" + ], + "type": "string" + }, + "checkedAt": { + "description": "CheckedAt is the last observation, conclusive or not; absent before\nthe first.", + "type": "string" + }, + "condition": { + "description": "Condition explains status (\"ok\", \"cert_expiring\", \"domain_expired\",\n...); absent while pending.", + "example": "cert_expiring", + "type": "string" + }, + "daysRemaining": { + "description": "DaysRemaining is counted when read from expiresAt, negative once\nexpired.", + "example": 12, + "type": "integer" + }, + "expiresAt": { + "type": "string" + }, + "message": { + "example": "certificate expires in 12 days (2026-11-12), within the 14-day threshold", + "type": "string" + }, + "status": { + "enum": [ + "pending", + "ok", + "warning", + "critical" + ], + "type": "string" + }, + "subject": { + "description": "Subject is what the aspect is about: the URL's host for the\ncertificate, its registrable domain for the domain.", + "example": "example.com", + "type": "string" + }, + "thresholdsDays": { + "example": [ + 30, + 14, + 7 + ], + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "alertedThresholds", + "aspect", + "status", + "subject", + "thresholdsDays" + ], + "type": "object" + }, + "dto.MonitorBulkItem": { + "properties": { + "code": { + "example": "MANAGED_RESOURCE", + "type": "string" + }, + "detail": { + "type": "string" + }, + "monitorId": { + "format": "uuid", + "type": "string" + }, + "ok": { + "type": "boolean" + } + }, + "required": [ + "monitorId", + "ok" + ], + "type": "object" + }, + "dto.MonitorBulkRequest": { + "properties": { + "action": { + "enum": [ + "pause", + "resume", + "delete" + ], + "example": "pause", + "type": "string" + }, + "monitorIds": { + "example": [ + "7d1c2f7e-6a1f-4f5e-9b8a-1f7c2b3d4e5f" + ], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "action", + "monitorIds" + ], + "type": "object" + }, + "dto.MonitorBulkResult": { + "properties": { + "action": { + "enum": [ + "pause", + "resume", + "delete" + ], + "type": "string" + }, + "failed": { + "type": "integer" + }, + "items": { + "items": { + "$ref": "#/components/schemas/dto.MonitorBulkItem" + }, + "type": "array" + }, + "succeeded": { + "type": "integer" + } + }, + "required": [ + "action", + "failed", + "items", + "succeeded" + ], + "type": "object" + }, + "dto.MonitorCertificate": { + "properties": { + "alertWindowStart": { + "description": "AlertWindowStart is when the largest threshold is crossed (notAfter\nminus it): shade from here to notAfter.", + "type": "string" + }, + "certificate": { + "$ref": "#/components/schemas/dto.Certificate" + }, + "checkedAt": { + "type": "string" + }, + "condition": { + "example": "cert_expiring", + "type": "string" + }, + "daysRemaining": { + "description": "DaysRemaining counts from now (certificate.daysRemaining from the\ncheck).", + "example": 41, + "type": "integer" + }, + "errorMessage": { + "type": "string" + }, + "nextThresholdAt": { + "type": "string" + }, + "nextThresholdDays": { + "description": "NextThresholdDays / NextThresholdAt: the next threshold to cross\nand when; absent once past the smallest.", + "example": 30, + "type": "integer" + }, + "resultId": { + "type": "integer" + }, + "severity": { + "enum": [ + "ok", + "warning", + "critical", + "inconclusive" + ], + "type": "string" + }, + "thresholdsDays": { + "description": "ThresholdsDays are the SSL monitor's expiry thresholds, largest\nfirst; empty for an HTTP monitor (no expiry alerts).", + "example": [ + 30, + 14, + 7 + ], + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "certificate", + "checkedAt", + "condition", + "daysRemaining", + "resultId", + "severity", + "thresholdsDays" + ], + "type": "object" + }, + "dto.MonitorCondition": { + "properties": { + "alertedThresholds": { + "description": "AlertedThresholds are the expiry thresholds already alerted for the\ncurrent expiry (SSL and domain monitors), oldest first; [] otherwise.\nAn HTTP monitor's watched certificate and domain have theirs on\naspects.", + "items": { + "$ref": "#/components/schemas/dto.ThresholdAlert" + }, + "type": "array" + }, + "code": { + "description": "Code is the condition (\"ok\", \"slow_response\", \"cert_expiring\", ...),\nworded per monitor type by the dashboard.", + "example": "cert_expiring", + "type": "string" + }, + "conclusiveAt": { + "description": "ConclusiveAt is when a check last confirmed it; older than\nlastCheck.at when the newest checks couldn't tell.", + "type": "string" + }, + "facts": { + "$ref": "#/components/schemas/dto.ConditionFacts" + }, + "message": { + "example": "certificate expires in 5 days (2026-11-05), within the 7-day threshold", + "type": "string" + }, + "since": { + "description": "Since is when the status began (statusSince).", + "type": "string" + } + }, + "required": [ + "alertedThresholds", + "code", + "facts", + "since" + ], + "type": "object" + }, + "dto.MonitorCreate": { + "properties": { + "description": { + "example": "Homepage, checked from Frankfurt", + "type": "string" + }, + "domain": { + "$ref": "#/components/schemas/dto.DomainSettingsInput" + }, + "http": { + "$ref": "#/components/schemas/dto.HTTPSettingsInput" + }, + "intervalSeconds": { + "description": "The org's plan can require more than the 30-second floor (60 s by\ndefault), and domain monitors run at most hourly (3600); the error\nmessage names the minimum.", + "example": 60, + "maximum": 86400, + "minimum": 30, + "type": "integer" + }, + "name": { + "example": "Marketing site", + "type": "string" + }, + "ssl": { + "$ref": "#/components/schemas/dto.SSLSettingsInput" + }, + "type": { + "enum": [ + "http", + "ssl", + "domain" + ], + "example": "http", + "type": "string" + } + }, + "required": [ + "intervalSeconds", + "name", + "type" + ], + "type": "object" + }, + "dto.MonitorEvent": { + "properties": { + "aspect": { + "enum": [ + "availability", + "certificate", + "domain" + ], + "example": "certificate", + "type": "string" + }, + "at": { + "type": "string" + }, + "checkResultId": { + "description": "CheckResultID is the check that saw it.", + "type": "integer" + }, + "id": { + "type": "integer" + }, + "renewal": { + "allOf": [ + { + "$ref": "#/components/schemas/dto.CertificateRenewal" + } + ], + "description": "Renewal is set on certificate_renewed." + }, + "type": { + "description": "Type: certificate_renewed, a check saw a certificate other than the\nnewest one so far, expiring later (SSL monitors and HTTP monitors\nthat watch their certificate; an older certificate, say from a node\nbehind on renewals, is not one).", + "enum": [ + "certificate_renewed" + ], + "type": "string" + } + }, + "required": [ + "aspect", + "at", + "checkResultId", + "id", + "type" + ], + "type": "object" + }, + "dto.MonitorStats": { + "properties": { + "avgMs": { + "type": "integer" + }, + "checks": { + "type": "integer" + }, + "critical": { + "type": "integer" + }, + "from": { + "type": "string" + }, + "granularity": { + "enum": [ + "hour", + "day" + ], + "type": "string" + }, + "inconclusive": { + "type": "integer" + }, + "maxMs": { + "type": "integer" + }, + "ok": { + "type": "integer" + }, + "series": { + "items": { + "$ref": "#/components/schemas/dto.StatsBucket" + }, + "type": "array" + }, + "to": { + "type": "string" + }, + "uptimePercent": { + "description": "UptimePercent is (ok + warning) / (ok + warning + critical); absent\nwithout conclusive checks and for SSL and domain monitors.", + "example": 99.95, + "type": "number" + }, + "warning": { + "type": "integer" + } + }, + "required": [ + "checks", + "critical", + "from", + "granularity", + "inconclusive", + "ok", + "series", + "to", + "warning" + ], + "type": "object" + }, + "dto.MonitorUpdate": { + "properties": { + "description": { + "type": "string" + }, + "domain": { + "$ref": "#/components/schemas/dto.DomainSettingsInput" + }, + "http": { + "$ref": "#/components/schemas/dto.HTTPSettingsInput" + }, + "intervalSeconds": { + "maximum": 86400, + "minimum": 30, + "type": "integer" + }, + "name": { + "type": "string" + }, + "ssl": { + "$ref": "#/components/schemas/dto.SSLSettingsInput" + } + }, + "type": "object" + }, + "dto.RenewedCertificate": { + "properties": { + "fingerprintSha256": { + "type": "string" + }, + "issuer": { + "type": "string" + }, + "notAfter": { + "type": "string" + }, + "notBefore": { + "type": "string" + }, + "serialNumber": { + "type": "string" + }, + "subject": { + "type": "string" + } + }, + "required": [ + "issuer", + "notAfter", + "notBefore", + "serialNumber", + "subject" + ], + "type": "object" + }, + "dto.SSLSettings": { + "properties": { + "expiryThresholdsDays": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "host": { + "type": "string" + }, + "port": { + "type": "integer" + }, + "serverName": { + "type": "string" + } + }, + "required": [ + "expiryThresholdsDays", + "host", + "port" + ], + "type": "object" + }, + "dto.SSLSettingsInput": { + "properties": { + "expiryThresholdsDays": { + "example": [ + 30, + 14, + 7 + ], + "items": { + "type": "integer" + }, + "type": "array" + }, + "host": { + "example": "example.com", + "type": "string" + }, + "port": { + "example": 443, + "maximum": 65535, + "minimum": 1, + "type": "integer" + }, + "serverName": { + "example": "example.com", + "type": "string" + } + }, + "required": [ + "expiryThresholdsDays", + "host", + "port" + ], + "type": "object" + }, + "dto.StatsBucket": { + "properties": { + "avgMs": { + "type": "integer" + }, + "checks": { + "type": "integer" + }, + "critical": { + "type": "integer" + }, + "inconclusive": { + "type": "integer" + }, + "maxMs": { + "type": "integer" + }, + "ok": { + "type": "integer" + }, + "p50Ms": { + "type": "integer" + }, + "p95Ms": { + "type": "integer" + }, + "region": { + "type": "string" + }, + "start": { + "type": "string" + }, + "warning": { + "type": "integer" + } + }, + "required": [ + "avgMs", + "checks", + "critical", + "inconclusive", + "maxMs", + "ok", + "p50Ms", + "p95Ms", + "region", + "start", + "warning" + ], + "type": "object" + }, + "dto.StatusChange": { + "properties": { + "changedAt": { + "type": "string" + }, + "checkResultId": { + "description": "CheckResultID is the result that made the change (raw results are\nkept about 30 days, changes a year).", + "type": "integer" + }, + "condition": { + "description": "Condition is what the check that made the change found.", + "example": "unexpected_status", + "type": "string" + }, + "durationSeconds": { + "description": "DurationSeconds is how long the status lasted (until now for the\nnewest change).", + "type": "integer" + }, + "endedAt": { + "description": "EndedAt is when the next change happened; absent for the newest\nchange (the current status, unless the monitor is paused).", + "type": "string" + }, + "events": { + "description": "Events are what else happened while this status lasted (from\nchangedAt to endedAt), newest first: certificate renewals. [] when\nnothing did.", + "items": { + "$ref": "#/components/schemas/dto.MonitorEvent" + }, + "type": "array" + }, + "from": { + "enum": [ + "pending", + "ok", + "warning", + "critical" + ], + "type": "string" + }, + "id": { + "type": "integer" + }, + "message": { + "example": "status 503 is not accepted (2xx)", + "type": "string" + }, + "statusCode": { + "example": 503, + "type": "integer" + }, + "to": { + "enum": [ + "ok", + "warning", + "critical" + ], + "type": "string" + } + }, + "required": [ + "changedAt", + "checkResultId", + "condition", + "durationSeconds", + "events", + "from", + "id", + "to" + ], + "type": "object" + }, + "dto.ThresholdAlert": { + "properties": { + "alertedAt": { + "type": "string" + }, + "days": { + "example": 14, + "type": "integer" + } + }, + "required": [ + "alertedAt", + "days" + ], + "type": "object" + }, + "dto.WindowSummary": { + "properties": { + "avgMs": { + "example": 182, + "type": "integer" + }, + "checks": { + "type": "integer" + }, + "critical": { + "type": "integer" + }, + "from": { + "type": "string" + }, + "inconclusive": { + "type": "integer" + }, + "ok": { + "type": "integer" + }, + "p50Ms": { + "description": "P50Ms and P95Ms approximate the window's median and 95th percentile\nresponse time (the checks-weighted mean of the hourly percentiles).", + "example": 150, + "type": "integer" + }, + "p95Ms": { + "example": 420, + "type": "integer" + }, + "uptimePercent": { + "description": "UptimePercent is (ok + warning) / (ok + warning + critical): a\nwarning still answered, an inconclusive check counts neither way.\nWarningPercent is the warnings' share of the conclusive checks.", + "example": 99.93, + "type": "number" + }, + "warning": { + "type": "integer" + }, + "warningPercent": { + "example": 0.4, + "type": "number" + } + }, + "required": [ + "checks", + "critical", + "from", + "inconclusive", + "ok", + "warning" + ], + "type": "object" + }, + "response.APIResponsePaginationCursors": { + "properties": { + "next": { + "example": "eyJpZCI6InUuLi4ifQ==", + "type": "string" + }, + "prev": { + "example": "eyJpZCI6InUuLi4ifQ==", + "type": "string" + } + }, + "type": "object" + }, + "response.APIResponsePaginationMeta": { + "properties": { + "timestamp": { + "example": "2025-01-08T17:29:30.663Z", + "type": "string" + } + }, + "type": "object" + }, + "response.APIResponseWithPagination": { + "properties": { + "cursors": { + "$ref": "#/components/schemas/response.APIResponsePaginationCursors" + }, + "list": {}, + "meta": { + "$ref": "#/components/schemas/response.APIResponsePaginationMeta" + } + }, + "required": [ + "cursors", + "list", + "meta" + ], + "type": "object" + }, + "response.Problem": { + "properties": { + "code": { + "allOf": [ + { + "$ref": "#/components/schemas/constants.ErrorCode" + } + ], + "example": "VALIDATION_FAILED" + }, + "data": { + "additionalProperties": { + "type": "string" + }, + "description": "Data holds stable facts about the error (\"limit\"), the same ones gRPC\nsends as ErrorInfo metadata.", + "type": "object" + }, + "detail": { + "description": "Detail is an English sentence for people.", + "example": "The request has invalid fields.", + "type": "string" + }, + "errors": { + "description": "Errors lists the field problems of a VALIDATION_FAILED problem.", + "items": { + "$ref": "#/components/schemas/validation.Violation" + }, + "type": "array" + }, + "instance": { + "description": "Instance identifies this occurrence: the request id the server\ngenerated, also sent as X-Request-ID and logged as request_id.", + "example": "urn:uuid:3f2c8a8e-6c1d-4a59-9a43-2b1f0f6f9d10", + "format": "uri", + "type": "string" + }, + "reason": { + "allOf": [ + { + "$ref": "#/components/schemas/constants.ErrorReason" + } + ], + "description": "Reason is a finer stable cause within Code, when there is one." + }, + "status": { + "example": 400, + "type": "integer" + }, + "timestamp": { + "type": "string" + }, + "title": { + "example": "Validation failed", + "type": "string" + }, + "type": { + "description": "Type identifies the problem type (one per code); it may be\ndereferenced for documentation.", + "example": "https://docs.norcube.com/errors/validation-failed", + "format": "uri", + "type": "string" + } + }, + "required": [ + "code", + "detail", + "instance", + "status", + "timestamp", + "title", + "type" + ], + "type": "object" + }, + "validation.Params": { + "properties": { + "allowed": { + "description": "Allowed: oneOf.", + "items": { + "type": "string" + }, + "type": "array" + }, + "expected": { + "description": "Expected: type, mismatch.", + "type": "string" + }, + "field": { + "description": "Field is the pointer of the other field: min and max compared with a\nfield, exclusive, dependsOn.", + "example": "/http/requestBody", + "type": "string" + }, + "max": { + "description": "Max: range, max, maxLength, maxItems.", + "example": 30000, + "type": "integer" + }, + "min": { + "description": "Min: range, min.", + "example": 1000, + "type": "integer" + }, + "unit": { + "allOf": [ + { + "$ref": "#/components/schemas/validation.Unit" + } + ], + "description": "Unit: maxLength." + }, + "value": { + "description": "Value: unsupported.", + "type": "string" + } + }, + "type": "object" + }, + "validation.Rule": { + "enum": [ + "required", + "min", + "max", + "range", + "maxLength", + "maxItems", + "oneOf", + "format", + "public", + "unique", + "exclusive", + "dependsOn", + "notAllowed", + "immutable", + "unknown", + "duplicate", + "type", + "reference", + "unverified", + "unsupported", + "mismatch" + ], + "type": "string", + "x-enum-varnames": [ + "RuleRequired", + "RuleMin", + "RuleMax", + "RuleRange", + "RuleMaxLength", + "RuleMaxItems", + "RuleOneOf", + "RuleFormat", + "RulePublic", + "RuleUnique", + "RuleExclusive", + "RuleDependsOn", + "RuleNotAllowed", + "RuleImmutable", + "RuleUnknown", + "RuleDuplicate", + "RuleType", + "RuleReference", + "RuleUnverified", + "RuleUnsupported", + "RuleMismatch" + ] + }, + "validation.Unit": { + "enum": [ + "characters", + "bytes" + ], + "type": "string", + "x-enum-varnames": [ + "UnitCharacters", + "UnitBytes" + ] + }, + "validation.Violation": { + "properties": { + "detail": { + "example": "must be between 1000 and 30000", + "type": "string" + }, + "params": { + "$ref": "#/components/schemas/validation.Params" + }, + "pointer": { + "example": "/http/timeoutMs", + "type": "string" + }, + "rule": { + "allOf": [ + { + "$ref": "#/components/schemas/validation.Rule" + } + ], + "example": "range" + } + }, + "required": [ + "detail", + "pointer", + "rule" + ], + "type": "object" + } + } + }, + "info": { + "contact": { + "email": "jan@jetlio.com", + "name": "Jan Å vábík" + }, + "description": "Uptime, SSL certificate and domain expiry monitoring.", + "title": "Norcube PulseCheck API", + "version": "" + }, + "openapi": "3.0.3", + "paths": { + "/alert-channels": { + "get": { + "description": "The organization's alert channels, newest first. Credentials are never returned.", + "operationId": "listAlertChannels", + "parameters": [ + { + "in": "query", + "name": "cursor", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "limit", + "schema": { + "maximum": 100, + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIResponseWithPagination" + }, + { + "properties": { + "list": { + "items": { + "$ref": "#/components/schemas/dto.AlertChannel" + }, + "type": "array" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + } + }, + "summary": "List alert channels", + "tags": [ + "Alert channels" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + }, + "post": { + "description": "Creates a channel. A webhook's signing secret (Standard Webhooks, whsec_…) is returned this once; SMS channels get no alerts until their number is verified. Voice-call channels can't be created, nor SMS channels where no SMS provider is configured: 400 with reason CHANNEL_TYPE_UNAVAILABLE.", + "operationId": "createAlertChannel", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.AlertChannelCreate" + } + } + }, + "description": "Channel", + "required": true, + "x-originalParamName": "payload" + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.AlertChannelWithSecret" + } + } + }, + "description": "Created" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Invalid fields (VALIDATION_FAILED), reason CHANNEL_TYPE_UNAVAILABLE when the kind isn't offered" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Forbidden, or channel limit reached (LIMIT_REACHED), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + } + }, + "summary": "Create an alert channel", + "tags": [ + "Alert channels" + ], + "x-norcube-scopes": [ + "pulsecheck.channels" + ] + } + }, + "/alert-channels/{id}": { + "delete": { + "description": "Deletes the channel and removes it from every monitor's alert settings. Pending alerts to it are dropped.", + "operationId": "deleteAlertChannel", + "parameters": [ + { + "description": "Channel ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Delete an alert channel", + "tags": [ + "Alert channels" + ], + "x-norcube-scopes": [ + "pulsecheck.channels" + ] + }, + "get": { + "description": "One alert channel: kind, name, whether it is a default channel, enabled and verified, and its settings without credentials (a Slack or Discord URL as a hint, a webhook's signing secret never).", + "operationId": "getAlertChannel", + "parameters": [ + { + "description": "Channel ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.AlertChannel" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Get an alert channel", + "tags": [ + "Alert channels" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + }, + "patch": { + "description": "Changes the given fields. signingSecret is returned when a webhook's secret was rotated or replaced. A voice channel can be renamed but not enabled or given settings (400, reason CHANNEL_TYPE_UNAVAILABLE).", + "operationId": "updateAlertChannel", + "parameters": [ + { + "description": "Channel ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.AlertChannelUpdate" + } + } + }, + "description": "Changes", + "required": true, + "x-originalParamName": "payload" + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.AlertChannelWithSecret" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Update an alert channel", + "tags": [ + "Alert channels" + ], + "x-norcube-scopes": [ + "pulsecheck.channels" + ] + } + }, + "/alert-channels/{id}/deliveries": { + "get": { + "description": "Every alert given to this channel, newest first (kept 90 days): the event and monitor (and incident), status (pending: queued or waiting to retry; sent; dead: given up), attempts, the next attempt while pending, and the last error with URLs, email addresses, phone numbers and token-like strings removed. status=dead lists the failures nobody saw.", + "operationId": "listAlertChannelDeliveries", + "parameters": [ + { + "description": "Alert channel ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "in": "query", + "name": "cursor", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "limit", + "schema": { + "maximum": 100, + "minimum": 1, + "type": "integer" + } + }, + { + "in": "query", + "name": "status", + "schema": { + "enum": [ + "pending", + "sent", + "dead" + ], + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIResponseWithPagination" + }, + { + "properties": { + "list": { + "items": { + "$ref": "#/components/schemas/dto.ChannelDelivery" + }, + "type": "array" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "List a channel's deliveries", + "tags": [ + "Alert channels" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + } + }, + "/alert-channels/{id}/test": { + "post": { + "description": "Sends a test alert right away and returns the provider's reference. Rate limited; an SMS counts toward the daily SMS limit. Refused while the organization is blocked for unpaid invoices.", + "operationId": "testAlertChannel", + "parameters": [ + { + "description": "Channel ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.AlertChannelTestResult" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Organization blocked for unpaid invoices" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "The provider refused it, the contact isn't verified, or a voice channel (CHANNEL_TYPE_UNAVAILABLE)" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Too Many Requests" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "The provider didn't answer; retry" + } + }, + "summary": "Send a test alert", + "tags": [ + "Alert channels" + ], + "x-norcube-scopes": [ + "pulsecheck.channels" + ] + } + }, + "/alert-channels/{id}/verify": { + "post": { + "description": "Texts (or, for an email-address channel, emails) a 6-digit code valid for 10 minutes. At most once a minute; an SMS counts toward the daily SMS limit.", + "operationId": "sendAlertChannelVerification", + "parameters": [ + { + "description": "Channel ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "ORG_BLOCKED: unpaid invoices" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Nothing to verify, already verified, a code was just sent, or a voice channel (CHANNEL_TYPE_UNAVAILABLE)" + } + }, + "summary": "Send a verification code", + "tags": [ + "Alert channels" + ], + "x-norcube-scopes": [ + "pulsecheck.channels" + ] + } + }, + "/alert-channels/{id}/verify/confirm": { + "post": { + "description": "Verifies the channel's number with the code sent. Five wrong codes (or an expired one) need a new code.", + "operationId": "confirmAlertChannelVerification", + "parameters": [ + { + "description": "Channel ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.AlertChannelVerifyConfirm" + } + } + }, + "description": "Code", + "required": true, + "x-originalParamName": "payload" + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.AlertChannel" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Wrong code" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Expired, or too many attempts" + } + }, + "summary": "Confirm a verification code", + "tags": [ + "Alert channels" + ], + "x-norcube-scopes": [ + "pulsecheck.channels" + ] + } + }, + "/incidents": { + "get": { + "description": "The organization's incidents: open ones first (critical, then warning), then resolved ones, newest first within each. Filter by status (open, resolved), monitor, severity (an open incident's current severity, a resolved one's peak), aspect, acknowledged, q (part of the monitor's name or target, any case, at most 100 characters) and when it started (from inclusive, to exclusive). Every filter given must match. Rows carry the monitor's name, type, variant and target. An invalid filter is a VALIDATION_FAILED problem with the parameter's pointer (\"/severity\").", + "operationId": "listIncidents", + "parameters": [ + { + "description": "Acknowledged: true for incidents someone acknowledged, false for\nthe others.", + "in": "query", + "name": "acknowledged", + "schema": { + "enum": [ + "true", + "false" + ], + "type": "string" + } + }, + { + "description": "Aspect is what the incident is about.", + "in": "query", + "name": "aspect", + "schema": { + "enum": [ + "availability", + "certificate", + "domain" + ], + "type": "string" + } + }, + { + "in": "query", + "name": "cursor", + "schema": { + "type": "string" + } + }, + { + "description": "From and To bound when the incident started: from inclusive, to\nexclusive (RFC 3339).", + "in": "query", + "name": "from", + "schema": { + "format": "date-time", + "type": "string" + } + }, + { + "in": "query", + "name": "limit", + "schema": { + "maximum": 100, + "minimum": 1, + "type": "integer" + } + }, + { + "in": "query", + "name": "monitorId", + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "description": "Q is part of the monitor's name or target, any case.", + "in": "query", + "name": "q", + "schema": { + "maxLength": 100, + "type": "string" + } + }, + { + "description": "Severity matches an open incident's current severity and a resolved\none's peak severity (how bad it got).", + "in": "query", + "name": "severity", + "schema": { + "enum": [ + "warning", + "critical" + ], + "type": "string" + } + }, + { + "in": "query", + "name": "status", + "schema": { + "enum": [ + "open", + "resolved" + ], + "type": "string" + } + }, + { + "in": "query", + "name": "to", + "schema": { + "format": "date-time", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIResponseWithPagination" + }, + { + "properties": { + "list": { + "items": { + "$ref": "#/components/schemas/dto.Incident" + }, + "type": "array" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + } + }, + "summary": "List incidents", + "tags": [ + "Incidents" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + } + }, + "/incidents/summary": { + "get": { + "description": "The organization's incidents at a glance, for a page header: open incidents by current severity and those nobody acknowledged, incidents resolved in the last 7 days, and the mean time to resolve (opened to resolved) of incidents resolved in the last 30 days. Takes no filters: it describes the organization, not a list view.", + "operationId": "getIncidentSummary", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.IncidentSummary" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + } + }, + "summary": "Summarize incidents", + "tags": [ + "Incidents" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + } + }, + "/incidents/{id}": { + "get": { + "description": "An incident with its timeline and every alert sent for it (with delivery status, so a failing channel shows here).", + "operationId": "getIncident", + "parameters": [ + { + "description": "Incident ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.IncidentDetail" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Get an incident", + "tags": [ + "Incidents" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + } + }, + "/incidents/{id}/acknowledge": { + "post": { + "description": "Marks an open incident as being handled: its reminders stop. Idempotent; a resolved incident is returned unchanged.", + "operationId": "acknowledgeIncident", + "parameters": [ + { + "description": "Incident ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.IncidentDetail" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Acknowledge an incident", + "tags": [ + "Incidents" + ], + "x-norcube-scopes": [ + "pulsecheck.write" + ] + } + }, + "/monitors": { + "get": { + "description": "The organization's monitors with their current status, by default ordered by status severity (critical, warning, pending, ok, paused) then name; `sort` picks another order, and a cursor only continues the sort it came from. `status` is the severity of the last conclusive check (an inconclusive one, such as a failed registry lookup, never moves it) and `condition` its reason with facts (days left for SSL and domain monitors). Rows of HTTP monitors have `last24h` (checks by severity, uptime and warning share, approximate p50/p95 over the last 24 full hours plus the current one; no data is absent, not 100%). `include=history` adds each row's newest 60 results (`history`, newest first) for a heartbeat strip. Rows carry no settings; `variant` names what each monitor does (`keyword` for an HTTP monitor that looks for a keyword).", + "operationId": "listMonitors", + "parameters": [ + { + "in": "query", + "name": "cursor", + "schema": { + "type": "string" + } + }, + { + "description": "Include is a comma-separated list of optional row parts: history\nadds each row's last 60 check results.", + "in": "query", + "name": "include", + "schema": { + "enum": [ + "history" + ], + "type": "string" + } + }, + { + "in": "query", + "name": "limit", + "schema": { + "maximum": 100, + "minimum": 1, + "type": "integer" + } + }, + { + "in": "query", + "name": "q", + "schema": { + "type": "string" + } + }, + { + "description": "Sort: status (default, by overall status: critical, warning,\npending, ok, paused, then name), name (A to Z), lastChecked (most recent first), uptime\n(lowest over last24h first; no data, and SSL and domain monitors,\nlast), created (newest first).\nA cursor only continues the sort it came from.", + "in": "query", + "name": "sort", + "schema": { + "enum": [ + "status", + "name", + "lastChecked", + "uptime", + "created" + ], + "type": "string" + } + }, + { + "description": "Status matches the overall status (the worst of the monitor's status\nand its watched aspects').", + "in": "query", + "name": "status", + "schema": { + "enum": [ + "pending", + "ok", + "warning", + "critical", + "paused" + ], + "type": "string" + } + }, + { + "in": "query", + "name": "type", + "schema": { + "enum": [ + "http", + "ssl", + "domain" + ], + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIResponseWithPagination" + }, + { + "properties": { + "list": { + "items": { + "$ref": "#/components/schemas/dto.Monitor" + }, + "type": "array" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + } + }, + "summary": "List monitors", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + }, + "post": { + "description": "Creates an enabled monitor; its first check runs right away. Every check setting is required.", + "operationId": "createMonitor", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MonitorCreate" + } + } + }, + "description": "Monitor", + "required": true, + "x-originalParamName": "payload" + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.Monitor" + } + } + }, + "description": "Created" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Organization blocked for unpaid invoices" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Forbidden, or monitor limit reached (LIMIT_REACHED), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Service Unavailable" + } + }, + "summary": "Create a monitor", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.write" + ] + } + }, + "/monitors/bulk": { + "post": { + "description": "Applies one action to up to 100 monitors, each exactly as its own request would (pause closes its open incident, resume checks soon, delete refuses a linked monitor with MANAGED_RESOURCE) after an IAM check on that monitor (UpdateMonitor for pause/resume, DeleteMonitor for delete). Not atomic: the answer has one item per id, in request order, ok or the problem code that monitor's own request would have had (NOT_FOUND, FORBIDDEN, MANAGED_RESOURCE, UNAVAILABLE, INTERNAL_ERROR). The request itself fails only when invalid (an unknown action, no ids, more than 100, a malformed or repeated id) or when permissions can't be checked (503). Shares the on-demand check budget (one unit per request).", + "operationId": "applyMonitorBulkAction", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MonitorBulkRequest" + } + } + }, + "description": "Action and monitors", + "required": true, + "x-originalParamName": "payload" + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MonitorBulkResult" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Too Many Requests" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Service Unavailable" + } + }, + "summary": "Pause, resume or delete many monitors", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.write" + ] + } + }, + "/monitors/{id}": { + "delete": { + "description": "Deletes the monitor and its whole check history. A monitor that belongs to a resource of another service (parentResource set) is refused with 409 MANAGED_RESOURCE: remove it there.", + "operationId": "deleteMonitor", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Managed by another service (MANAGED_RESOURCE)" + } + }, + "summary": "Delete a monitor", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.write" + ] + }, + "get": { + "description": "A monitor with its settings and current status. Secret header values are never returned.", + "operationId": "getMonitor", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.Monitor" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Get a monitor", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + }, + "patch": { + "description": "Changes the given fields. A settings object replaces the settings as a whole; omit a secret header's value to keep the stored one. The type can't change, nor the domain of a monitor that belongs to another service's resource.", + "operationId": "updateMonitor", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MonitorUpdate" + } + } + }, + "description": "Changes", + "required": true, + "x-originalParamName": "payload" + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.Monitor" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Service Unavailable" + } + }, + "summary": "Update a monitor", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.write" + ] + } + }, + "/monitors/{id}/alerts": { + "get": { + "description": "How the monitor alerts. useDefaults: alerts go to the organization's default channels (or, with none, its members by email) on down, expiring, expired and recovered, with the default confirmations shown. applicableEvents lists the events monitors of this type can send.", + "operationId": "getMonitorAlerts", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MonitorAlerts" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Get a monitor's alert settings", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + }, + "put": { + "description": "Replaces how the monitor alerts: confirmations (failures before an incident opens, successes before it resolves), reminder interval (0: none) and which events go to which channels. An empty routes list sends no alerts. useDefaults: true returns to the organization defaults.", + "operationId": "setMonitorAlerts", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MonitorAlertsUpdate" + } + } + }, + "description": "Alert settings", + "required": true, + "x-originalParamName": "payload" + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MonitorAlerts" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Set a monitor's alert settings", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.write" + ] + } + }, + "/monitors/{id}/availability": { + "get": { + "description": "One entry per UTC day, oldest first, for the `days` days ending today (default and maximum 90): check counts by severity, uptime % ((ok + warning) / conclusive checks) and an estimate of the minutes spent down (HTTP monitors; absent and 0 for SSL and domain monitors), and noData for a day without checks (draw it gray: it is never 100%). Today is refreshed every few minutes.", + "operationId": "getMonitorAvailability", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "description": "Days is how many UTC days, ending today, the bar covers (default 90).", + "in": "query", + "name": "days", + "schema": { + "maximum": 90, + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.Availability" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Get daily availability", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + } + }, + "/monitors/{id}/certificate": { + "get": { + "description": "The newest certificate an SSL or HTTPS monitor saw: subject, issuer, SANs, validity, serial, the presented chain and whether it verifies, days left counted from now, and (SSL monitors) the expiry thresholds with the alert window and the next threshold to be crossed. 404 when no check has seen a certificate (plain HTTP and domain monitors never do).", + "operationId": "getMonitorCertificate", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MonitorCertificate" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Get the latest certificate", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + } + }, + "/monitors/{id}/check": { + "post": { + "description": "Runs the monitor's check immediately (paused monitors too) and returns the stored result. Billed like a scheduled check; rate limited.", + "operationId": "runMonitorCheck", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.CheckResult" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Organization blocked for unpaid invoices" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Too Many Requests" + } + }, + "summary": "Run a check now", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.check", + "pulsecheck.write" + ] + } + }, + "/monitors/{id}/pause": { + "post": { + "description": "Stops scheduled checks. Idempotent.", + "operationId": "pauseMonitor", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.Monitor" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Pause a monitor", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.write" + ] + } + }, + "/monitors/{id}/results": { + "get": { + "description": "The monitor's check history in [from, to), newest first. Defaults to the last 24 hours. Raw results are kept at least 30 days (whole months are dropped once entirely past retention).", + "operationId": "listMonitorResults", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "in": "query", + "name": "cursor", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "from", + "schema": { + "format": "date-time", + "type": "string" + } + }, + { + "in": "query", + "name": "limit", + "schema": { + "maximum": 200, + "minimum": 1, + "type": "integer" + } + }, + { + "in": "query", + "name": "to", + "schema": { + "format": "date-time", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIResponseWithPagination" + }, + { + "properties": { + "list": { + "items": { + "$ref": "#/components/schemas/dto.CheckResult" + }, + "type": "array" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "List check results", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + } + }, + "/monitors/{id}/resume": { + "post": { + "description": "Restarts scheduled checks; the next one runs right away. Idempotent.", + "operationId": "resumeMonitor", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.Monitor" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Resume a monitor", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.write" + ] + } + }, + "/monitors/{id}/stats": { + "get": { + "description": "Uptime %, latency and a bucketed series for the range ending now (hourly up to 7d, daily beyond). Uptime is (ok + warning) / (ok + warning + critical), HTTP monitors only. Refreshed every few minutes.", + "operationId": "getMonitorStats", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "in": "query", + "name": "range", + "required": true, + "schema": { + "enum": [ + "24h", + "7d", + "30d", + "90d" + ], + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MonitorStats" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "Get uptime stats", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + } + }, + "/monitors/{id}/status-changes": { + "get": { + "description": "Every time a check moved the monitor to another status, newest first: from, to, when, how long it lasted (endedAt absent and the duration running until now for the newest), and what the check said (condition, statusCode, message). Inconclusive checks never change the status. Each change carries `events`: what else happened while its status lasted, newest first (`certificate_renewed` with the previous and the new certificate, for SSL monitors and HTTP monitors that watch their certificate; no alert is sent for it). Kept a year. Pausing is not a status change (see the audit log).", + "operationId": "listMonitorStatusChanges", + "parameters": [ + { + "description": "Monitor ID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + }, + { + "in": "query", + "name": "cursor", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "limit", + "schema": { + "maximum": 100, + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIResponseWithPagination" + }, + { + "properties": { + "list": { + "items": { + "$ref": "#/components/schemas/dto.StatusChange" + }, + "type": "array" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Missing, invalid or expired token (UNAUTHORIZED)" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "No permission for this (FORBIDDEN), or the token's scopes don't allow this (reason INSUFFICIENT_SCOPE)" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.Problem" + } + } + }, + "description": "Not Found" + } + }, + "summary": "List status changes", + "tags": [ + "Monitors" + ], + "x-norcube-scopes": [ + "pulsecheck.read", + "pulsecheck.check", + "pulsecheck.write", + "pulsecheck.channels" + ] + } + } + } +} \ No newline at end of file