asset

package
v1.25.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// AwsMetricScrapeConfigKind is the kind of an AWS metric scrape config document.
	AwsMetricScrapeConfigKind = "Dash0AwsMetricScrapeConfig"
)
View Source
const CustomSkillKind = "Dash0Skill"

CustomSkillKind is the kind of an Agent0 custom skill document.

View Source
const CustomSkillManifestPath = "SKILL.md"

CustomSkillManifestPath is the file every custom skill must carry at its root.

View Source
const DatasetAPIVersion = "dash0.com/v1alpha1"

DatasetAPIVersion is the only dataset document format the API accepts.

View Source
const DatasetSoftDeleteNote = "Dashboards, check rules, synthetic checks and views are kept for 30 days; " +
	"creating the same slug within that time restores them. Telemetry is removed as its retention expires."

DatasetSoftDeleteNote says what a dataset delete keeps and removes. Every prompt, hint and help text about deleting a dataset uses it, so the wording cannot drift.

View Source
const GenerativeAiEvaluationDisplayName = "Eval"

GenerativeAiEvaluationDisplayName names a generative AI evaluation in user-facing output.

View Source
const InferredOriginPrefix = "dash0-cli_"

InferredOriginPrefix starts every origin the CLI infers, so Dash0 shows the asset as managed by the CLI.

View Source
const OriginLabel = `metadata.labels["dash0.com/origin"]`

OriginLabel is where the dash0.com/origin label lives in a document, for error messages that tell the user where to set it.

View Source
const SamplingRuleDeleteNote = "The delete is permanent: Dash0 drops the traces that only this rule kept, " +
	"and deleting the last enabled rule of a dataset turns sampling off."

SamplingRuleDeleteNote says what deleting a sampling rule does, for the confirmation prompt and the agent-mode refusal.

View Source
const SamplingRuleDisplayKind = "Sampling rule"

SamplingRuleDisplayKind is the display name of the Dash0Sampling kind, per the asset kind display-name table in docs/cli-naming-conventions.md.

View Source
const SignalToMetricsRuleDisplayKind = "Signal-to-metrics rule"

SignalToMetricsRuleDisplayKind is the display name of the Dash0SignalToMetrics kind, per the asset kind display-name table in docs/cli-naming-conventions.md.

Variables

View Source
var ErrAwsMetricScrapeConfigMissingID = errors.New(
	`Dash0AwsMetricScrapeConfig requires metadata.labels["dash0.com/id"]: it is the id of the AWS integration whose scrape config the document replaces`,
)

ErrAwsMetricScrapeConfigMissingID is returned when an `apply` document does not name the AWS integration whose config it replaces.

View Source
var ErrDatasetSlugRequired = errors.New(`dataset definition requires a slug in spec.slug or metadata.labels["dash0.com/id"]`)

ErrDatasetSlugRequired is returned when a dataset definition carries neither spec.slug nor a dash0.com/id label. The slug is the dataset's only identifier: it is the path id and cannot be assigned by the server.

View Source
var ErrNoYAMLFilesFound = errors.New("no .yaml or .yml files found")

ErrNoYAMLFilesFound is wrapped into DiscoverFiles' "no .yaml or .yml files found" error so callers can distinguish "the directory is legitimately empty" from any other failure via errors.Is, without matching on message text. runApply uses this to tolerate an empty directory specifically when --since is set: every asset that used to live there may simply have been deleted, which is a valid all-deletions run, not a usage error.

SpamFilterSupportedAPIVersions lists the spam filter apiVersion values the CLI understands. Exported so callers can render the supported list in their own error messages.

View Source
var ValidKinds = []string{"dashboard", "ephemeraldashboard", "checkrule", "syntheticcheck", "slo", "view", "prometheusrule", "persesdashboard", "spamfilter", "notificationchannel", "team", "timeseriesaggregation", "dataset", "skill", "awsmetricscrapeconfig", "generativeaievaluation", "signaltometrics", "sampling", "telemetrytransformationrule"}

ValidKinds lists every normalized kind apply accepts. Tests check that ParseDocumentHeader, applyDocument, and diff's planDocument each handle every one, so a kind missing from any of them fails a test.

Functions

func AwsMetricScrapeConfigIsSet added in v1.20.0

func AwsMetricScrapeConfigIsSet(cfg *dash0api.AwsMetricScrapeConfigDefinition) bool

AwsMetricScrapeConfigIsSet reports whether the integration has a stored config. The server omits the annotations of one never written or cleared.

func CarryRecordingRuleVersion added in v1.11.0

func CarryRecordingRuleVersion(src, dst *dash0api.RecordingRule)

CarryRecordingRuleVersion copies the version label from src to dst so that update requests include the optimistic-locking version the API currently requires.

func CheckAlertNameCollisions added in v1.17.0

func CheckAlertNameCollisions(names []PrometheusAlertName) error

CheckAlertNameCollisions validates that no two alerting rules in the same PrometheusRule CRD would derive the identical check-rule id. DeriveAlertCheckRuleID folds each alert's composed name through slugify, which collapses punctuation differences (e.g. "High CPU" and "High_CPU" both fold to "high-cpu") -- if that happens, both alerts would upsert to the identical derived id, silently overwriting each other exactly like the collision this derivation exists to prevent in the first place.

Called both from composePrometheusRuleNames (so apply's actual dispatch and check-rules create/update, which both go through ParseCheckRules, refuse the CRD) and from apply's own pre-flight validatePrometheusRule (so a multi-document apply run fails before any document is applied, not only once this specific CRD's turn comes up mid-run).

func CheckAwsMetricScrapeConfigOrigin added in v1.25.0

func CheckAwsMetricScrapeConfigOrigin(cfg *dash0api.AwsMetricScrapeConfigDefinition, integrationID string, before *dash0api.AwsMetricScrapeConfigDefinition) error

CheckAwsMetricScrapeConfigOrigin fails when the stored config has an origin other than the document's, because the CLI never changes a stored origin.

func CheckDashboardKind added in v1.23.0

func CheckDashboardKind(id string, stored, proposed *dash0api.DashboardDefinition) error

CheckDashboardKind returns a DashboardKindMismatchError when proposed would change the stored dashboard at id between ephemeral and permanent. A deleted dashboard can come back as either kind.

func CheckInferredOriginCollisions added in v1.25.0

func CheckInferredOriginCollisions(documents []Document, dataset *string) []string

CheckInferredOriginCollisions fails documents without an id that would write the same origin: two that get the same inferred origin, or one whose explicit origin is another's inferred origin, because the second would replace the first. A document with an id writes by the inferred origin only when the id is not found, which only the run knows; InferredOriginWrites checks that.

func CheckRouteUpdate added in v1.25.0

func CheckRouteUpdate(args []string, k UpdateKey, identity Identity) error

CheckRouteUpdate fails when RouteUpdate has no key to read, so a command can report a bad file or argument before it builds an API client.

func CheckRuleDeletedAt added in v1.19.0

func CheckRuleDeletedAt(rule *dash0api.PrometheusAlertRule) *time.Time

CheckRuleDeletedAt returns when the check rule was deleted, or nil when it is not deleted.

func CheckRuleIDsOccupiedByCRD added in v1.17.0

func CheckRuleIDsOccupiedByCRD(identifier string, alerts []PrometheusAlertName) []string

CheckRuleIDsOccupiedByCRD returns the check-rule ids a CRD's alerts live at: the CRD's literal identifier for zero or one alert, each alert's derived id for two or more. ids[i] is alerts[i]'s address, which --since's diff needs.

func CheckRuleStoredOrigin added in v1.25.0

func CheckRuleStoredOrigin(rule *dash0api.PrometheusAlertRule) string

CheckRuleStoredOrigin returns the origin of a stored check rule. Dash0 creates a check rule with its origin as its id, and returns no origin label.

func CheckSignalToMetricsRuleDataset added in v1.21.0

func CheckSignalToMetricsRuleDataset(existing *dash0api.SignalToMetricsDefinition, dataset *string, originOrID string) error

CheckSignalToMetricsRuleDataset returns a SignalToMetricsRuleDatasetMismatchError when the stored rule belongs to another dataset than dataset, where nil means "default".

The API's GET by origin or ID ignores the dataset parameter, so it returns a rule from any dataset. A write through another dataset then fails with a 400, and a preview that compared against that rule would report no changes for a write that cannot succeed. A rule without a dataset label is not checked.

func CheckStoredOrigin added in v1.25.0

func CheckStoredOrigin(key string, identity Identity, stored any) error

CheckStoredOrigin fails when key is the file's id and the asset stored there has an origin other than the file's, as apply does.

func ClearCheckRuleDeletedAt added in v1.19.0

func ClearCheckRuleDeletedAt(rule *dash0api.PrometheusAlertRule)

ClearCheckRuleDeletedAt removes the deletion timestamp from a check rule, for example from a file exported with `check-rules get -o yaml` while the rule was deleted.

func ClearDashboardDeletedAt added in v1.19.0

func ClearDashboardDeletedAt(dashboard *dash0api.DashboardDefinition)

ClearDashboardDeletedAt removes the deletion timestamp from a dashboard, for example from a file exported with `dashboards get -o yaml` while the dashboard was deleted.

func ClearRecordingRuleDeletedAt added in v1.19.0

func ClearRecordingRuleDeletedAt(rule *dash0api.RecordingRule)

ClearRecordingRuleDeletedAt removes the deletion timestamp from a recording rule, for example from a file exported with `recording-rules get -o yaml` while the rule was deleted.

func ClearUpdateOrigin added in v1.25.0

func ClearUpdateOrigin(document any)

ClearUpdateOrigin removes dash0.com/origin from the body of an update, as apply does, so an update never tries to change a stored origin.

SLOs, sampling rules, signal-to-metrics rules, and time series aggregations never send the origin in the body, on a create either: the origin is the URL path.

func CustomSkillDeletedAt added in v1.20.0

func CustomSkillDeletedAt(skill *dash0api.SkillDefinition) *time.Time

CustomSkillDeletedAt returns when the skill was soft-deleted, or nil if it was not.

func CustomSkillKey added in v1.20.0

func CustomSkillKey(skill *dash0api.SkillDefinition) string

CustomSkillKey returns the identifier a custom skill is addressed by: its origin, or its id when it has no origin.

func CustomSkillName added in v1.20.0

func CustomSkillName(skill *dash0api.SkillDefinition) string

CustomSkillName returns the name of a custom skill: the name in the SKILL.md frontmatter, which is where the server reads it from, otherwise metadata.name. The frontmatter wins because an exported document keeps the old metadata.name after the frontmatter renames the skill. It returns "" when neither is available.

func DashboardAlias added in v1.22.0

func DashboardAlias(dashboard *dash0api.DashboardDefinition) string

DashboardAlias returns the dash0.com/id label when DashboardKey is another key, or "". It names the same dashboard, so preview reads it when the key is not found.

func DashboardDeletedAt added in v1.19.0

func DashboardDeletedAt(dashboard *dash0api.DashboardDefinition) *time.Time

DashboardDeletedAt returns when the dashboard was deleted, or nil when it is not deleted.

func DashboardDisplayKind added in v1.23.0

func DashboardDisplayKind(dashboard *dash0api.DashboardDefinition) string

DashboardDisplayKind returns "Ephemeral dashboard" for an EphemeralDashboard and "Dashboard" for any other dashboard.

func DashboardKey added in v1.22.0

func DashboardKey(dashboard *dash0api.DashboardDefinition) string

DashboardKey returns the identifier the document header and preview name a dashboard by, or "".

func DashboardKeys added in v1.22.0

func DashboardKeys(dashboard *dash0api.DashboardDefinition) dash0api.AssetMetadata

DashboardKeys resolves a dashboard's identifiers for the update argument check and preview, in this order: the dash0.com/origin label, then metadata.dash0Extensions.id, then the dash0.com/id label. apply, create, update -f, and apply --since route by DashboardIdentity instead. Read it before StripDashboardServerFields, which clears the dash0.com/id label.

func DatasetName added in v1.25.0

func DatasetName(dataset *string) string

DatasetName returns the dataset an asset lives in. Without --dataset the API uses "default", so both name the same asset and must infer the same origin.

func DatasetOrigin added in v1.19.0

func DatasetOrigin(dataset *dash0api.DatasetDefinition) string

DatasetOrigin returns the dash0.com/origin label of a dataset, or "" when it has none.

func DeriveAlertCheckRuleID added in v1.17.0

func DeriveAlertCheckRuleID(sharedID, composedName string) string

DeriveAlertCheckRuleID derives a per-alert check-rule identifier for a PrometheusRule CRD with more than one alerting rule, from the CRD's own shared id and the alert's composed name. See composePrometheusRuleNames' doc comment for the full rationale.

Exported so --since's whole-CRD deletion dispatch (internal/apply/since.go) can compute the exact same derived id per alert when the whole CRD is removed: the check rules that actually exist server-side for a multi-alert CRD live at these derived ids, never at the literal shared id, so deleting the CRD must target each of them individually rather than the shared id alone.

func DescribeSamplingRuleConditions added in v1.22.0

func DescribeSamplingRuleConditions(rule *dash0api.SamplingDefinition) string

DescribeSamplingRuleConditions renders a rule's condition tree on one line for table and summary output, or "" when it cannot be decoded.

func DetectSpamFilterAPIVersion added in v1.12.2

func DetectSpamFilterAPIVersion(data []byte) (string, error)

DetectSpamFilterAPIVersion peeks at the apiVersion field on a YAML or JSON spam filter document so the caller can route to the matching client method. A missing value defaults to v1alpha1, matching the API client's decodeSpamFilterObject behavior. An unsupported value is rejected with the list of supported versions so the user knows what to fix.

func DiscoverFiles added in v1.21.0

func DiscoverFiles(dirPath string) ([]string, error)

DiscoverFiles recursively finds all .yaml/.yml files under dirPath, skipping hidden entries (names starting with '.'). Returns paths relative to dirPath, sorted lexicographically.

func DocumentCreateOrigin added in v1.25.0

func DocumentCreateOrigin(doc Document, dataset *string) string

DocumentCreateOrigin returns the origin apply creates the document by, or "" for the kinds documentIdentity leaves out.

func ExplainCustomSkillError added in v1.20.0

func ExplainCustomSkillError(err error, name string) error

ExplainCustomSkillError adds the cause and the fix to the API errors a custom skill write commonly hits: a name another skill already uses, and a defaultEnabled the caller may not set. It returns nil for any other error, so the caller falls back to client.HandleAPIError.

The advice goes behind "\nHint:" so agent mode lifts it into the JSON error's hint field.

func ExplainGenerativeAiEvaluationError added in v1.21.0

func ExplainGenerativeAiEvaluationError(err error, name string) error

ExplainGenerativeAiEvaluationError adds the cause and the fix to the 400 for a metadata.name that another eval in the dataset already uses, and to the two 400s a write to an existing eval hits when the document changes a field that is fixed at create: metadata.name and spec.judge.output.kind. It returns nil for any other error, so the caller falls back to client.HandleAPIError.

The advice goes behind "\nHint:" so agent mode lifts it into the JSON error's hint field.

func ExtractDeleteFallbacks added in v1.25.0

func ExtractDeleteFallbacks(data []byte) (alias, inferredOriginName string, err error)

ExtractDeleteFallbacks returns the other keys --since may have to delete a routed document at. alias is the origin of a document that also has an id: apply writes at the id when it exists, else at the origin, so --since deletes in that order. inferredOriginName is the metadata.name of a document without an origin: apply writes it at its inferred origin when it has no id or the id is not found, so --since must delete it there. Both are "" for datasets and AWS metric scrape configs, which --since deletes at their id.

func ExtractIdentifier added in v1.17.0

func ExtractIdentifier(data []byte) (string, error)

ExtractIdentifier returns the user-defined identifier a document is upserted by, or "" when the document carries none. The field location varies by kind, per the "Asset identifiers and idempotent upsert" table in the command reference:

  • Dashboard, EphemeralDashboard, PersesDashboard: dash0.com/id, then dash0.com/origin, then metadata.dash0Extensions.id (see DashboardIdentity)
  • CheckRule: top-level id, then labels["dash0.com/origin"]
  • every other routed kind: dash0.com/id, then dash0.com/origin
  • Dash0Dataset: spec.slug, then dash0.com/id
  • Dash0AwsMetricScrapeConfig: dash0.com/id

The kinds RouteDocument routes read the id first, as apply does, so --since deletes where apply wrote. For the other kinds, a fallback onto another field would return an identifier no live asset matches, so they return "". --since then keys a routed document by its inferred origin (ExtractInferredKeys), and fails for the rest.

func FindNonHiddenYAMLFiles added in v1.17.0

func FindNonHiddenYAMLFiles(root string, files *[]string, sawNestedDir *bool) fs.WalkDirFunc

FindNonHiddenYAMLFiles returns a fs.WalkDirFunc for passing directly to filepath.WalkDir(root, ...): it appends every non-hidden .yaml/.yml file visited to *files and skips hidden files and directories (any path component starting with "."), via fs.SkipDir for directories. This is the one walk callback shared by apply's directory-scan and --since's disk-side scan, so both agree on what counts as an asset-definition file without hand-rolling the same callback twice; the filepath.WalkDir call itself stays at each call site for readability.

root itself is exempt from the hidden-name check even if it starts with "." — an -f target the user named explicitly (e.g. -f .dash0-assets/) is a deliberate choice, not something to skip. Only path components *inside* root are checked. ListYAMLFilesAtRef (internal/git/plumbing.go) mirrors this same exemption for --since's git-ref-side scan, so a dot-prefixed -f target means the same thing on both sides of the diff.

sawNestedDir, if non-nil, is set to true the first time the walk visits a non-hidden subdirectory of root — letting a caller tailor a "nothing found" message (e.g. "in <dir> and nested directories" vs a flat "in <dir>"). Pass nil when the caller doesn't need this.

func FormatNameAndID added in v1.21.0

func FormatNameAndID(name, id string) string

FormatNameAndID returns a display string with name and optional ID.

func FormatValidationError added in v1.21.0

func FormatValidationError(issues ...string) error

FormatValidationError formats one or more validation issues into a consistent "validation failed with N error/errors:" message.

func GenerativeAiEvaluationDeletedAt added in v1.21.0

func GenerativeAiEvaluationDeletedAt(evaluation *dash0api.GenerativeAiEvaluationDefinition) *time.Time

GenerativeAiEvaluationDeletedAt returns when the eval was deleted, or nil when it is not deleted.

func GenerativeAiEvaluationUsesOrigin added in v1.21.0

func GenerativeAiEvaluationUsesOrigin(data []byte) (bool, error)

GenerativeAiEvaluationUsesOrigin reports whether an eval document carries a non-empty dash0.com/origin label. --since uses it the same way as SLOUsesOrigin: an id-only eval that an earlier CLI version created by POST sits at a server-assigned id the document never learned.

func GetRoutedAsset added in v1.25.0

func GetRoutedAsset(ctx context.Context, apiClient dash0api.Client, kind, key string, dataset *string) (deleted bool, err error)

GetRoutedAsset reads the asset of a routed kind at key, and reports whether it is soft-deleted. --since reads before it deletes, because several delete endpoints answer an unknown key with 2xx, and the API keeps a deleted asset.

func GetSamplingRuleOrigin added in v1.22.0

func GetSamplingRuleOrigin(rule *dash0api.SamplingDefinition) string

GetSamplingRuleOrigin extracts the dash0.com/origin label. The API client ships accessors for the id, name, and dataset labels, but not this one.

func GetSignalToMetricsRuleOrigin added in v1.21.0

func GetSignalToMetricsRuleOrigin(rule *dash0api.SignalToMetricsDefinition) string

GetSignalToMetricsRuleOrigin extracts the dash0.com/origin label. The API client ships accessors for the id, name, and dataset labels, but not this one.

func GetTelemetryTransformationRuleOrigin added in v1.25.0

func GetTelemetryTransformationRuleOrigin(rule *dash0api.TelemetryTransformationRuleDefinition) string

func GetTimeSeriesAggregationOrigin added in v1.18.0

func GetTimeSeriesAggregationOrigin(aggregation *dash0api.TimeSeriesAggregationDefinition) string

GetTimeSeriesAggregationOrigin extracts the dash0.com/origin label. The API client ships accessors for the id, name, and dataset labels, but not this one.

func IDOnlyDeleteWarning added in v1.23.0

func IDOnlyDeleteWarning(kind, display string) string

IDOnlyDeleteWarning returns the warning `apply --since` prints before it deletes an asset that IdentifiedByIDOnly reported. display is the asset's name and id.

func IdentifiedByIDOnly added in v1.23.0

func IdentifiedByIDOnly(kind string, data []byte) (bool, error)

IdentifiedByIDOnly reports whether a document of a kind that needs the id-only delete warning carries no dash0.com/origin label. It is false for every other kind.

func InferKindOrigin added in v1.25.0

func InferKindOrigin(kind, name string, dataset *string) string

InferKindOrigin returns the origin apply infers for a document of kind named name. Teams, notification channels, and Agent0 skills are organization-level, so theirs has no dataset.

func InferOrigin added in v1.25.0

func InferOrigin(kind, name, dataset string) string

InferOrigin returns the origin of a document without one. It depends only on the kind, metadata.name, and dataset, so the same document gets the same origin from every checkout, and a different one in every dataset.

func InferredOriginKind added in v1.25.0

func InferredOriginKind(kind string) string

InferredOriginKind returns the normalized kind an inferred origin hashes, so documents of two kinds that write the same origin compare equal.

func IsEphemeralDashboard added in v1.23.0

func IsEphemeralDashboard(dashboard *dash0api.DashboardDefinition) bool

IsEphemeralDashboard reports whether dashboard is an EphemeralDashboard.

func IsHiddenPath added in v1.17.0

func IsHiddenPath(path string) bool

IsHiddenPath reports whether any slash-separated component of path starts with "." — used to skip hidden files and directories consistently across a directory walk (a single entry name), a git ls-tree listing (a full repo-relative path), and any other path-filtering scan.

func IsRoutedKind added in v1.25.0

func IsRoutedKind(kind string) bool

IsRoutedKind reports whether RouteDocument serves kind.

func IsSamplingRuleWrongDataset added in v1.22.0

func IsSamplingRuleWrongDataset(err error) bool

IsSamplingRuleWrongDataset reports whether err is the API's cross-dataset collision: HTTP 400 saying a rule with this origin or ID exists but belongs to a different dataset.

Origins and IDs are unique per organization while each rule belongs to one dataset. GET, PUT, and DELETE through another dataset therefore fail with this 400. It is not a 404: the rule exists, so delete --force must not report it as already gone.

func IsSignalToMetricsRuleWrongDataset added in v1.21.0

func IsSignalToMetricsRuleWrongDataset(err error) bool

IsSignalToMetricsRuleWrongDataset reports whether err is the API's cross-dataset origin collision: HTTP 400 saying a rule with this origin exists but belongs to a different dataset.

Origins are unique per organization while each rule belongs to one dataset, as for time series aggregations. Writing or deleting by an origin from another dataset therefore fails with this 400. It is not a 404: the rule exists, so delete --force must not report it as already gone.

It also reports a SignalToMetricsRuleDatasetMismatchError, the same collision found by the CLI before the write.

func IsTimeSeriesAggregationWrongDataset added in v1.18.0

func IsTimeSeriesAggregationWrongDataset(err error) bool

IsTimeSeriesAggregationWrongDataset reports whether err is the API's cross-dataset origin collision: HTTP 400 with a message saying the origin exists but belongs to a different dataset.

Origins are unique per organization, while each aggregation belongs to one dataset. Only aggregations and signal-to-metrics rules combine the two, so the resulting 400 is easy to mistake for a malformed document. It must not be treated as a 404 either: the aggregation exists, so swallowing it under --force would report success while it is still live.

func IsValidKind added in v1.17.0

func IsValidKind(kind string) bool

IsValidKind reports whether kind (in any casing/hyphenation NormalizeKind accepts) is one of the Dash0 asset kinds apply/create/--since know how to handle. Used to distinguish a genuine Dash0 document from unrelated YAML (e.g. a stray Kubernetes ConfigMap) that happens to sit in a scanned scope.

func IsYAMLFile added in v1.17.0

func IsYAMLFile(path string) bool

IsYAMLFile reports whether path has a .yaml or .yml extension (case-insensitive) — the file types apply's directory scan and --since's git-ref/disk scans consider.

func KindDisplayName added in v1.1.0

func KindDisplayName(kind string) string

KindDisplayName returns the human-readable name for an asset kind. Multi-word kinds like "CheckRule" become "Check rule" and "SyntheticCheck" becomes "Synthetic check".

func NormalizeKind added in v1.17.0

func NormalizeKind(kind string) string

NormalizeKind lowercases kind, strips "-"/"_", and trims a leading "dash0" prefix, so callers can compare kind strings regardless of how they were cased or hyphenated in the source document (e.g. "Dash0Team" and "team" both normalize to "team").

func ParseAwsMetricScrapeConfig added in v1.20.0

func ParseAwsMetricScrapeConfig(raw []byte) (*dash0api.AwsMetricScrapeConfigDefinition, []string, error)

ParseAwsMetricScrapeConfig decodes and validates a Dash0AwsMetricScrapeConfig document before any API call. It returns warnings for metadata the API ignores on write.

spec.namespaces is required: the client sends a missing list as [], which stops all scraping, so a typo must not get that far. Unknown fields under spec are rejected for the same reason.

func ParseDashboard added in v1.25.0

func ParseDashboard(raw []byte) (dashboard *dash0api.DashboardDefinition, inferredName string, err error)

ParseDashboard parses a Dashboard, EphemeralDashboard, or PersesDashboard document, and returns the metadata.name to infer its origin from. The PersesDashboard conversion replaces metadata.name with the title, and a new title must not move the dashboard to a new inferred origin.

func ParseDocumentHeader added in v1.21.0

func ParseDocumentHeader(data []byte) (kind, name, id string, err error)

ParseDocumentHeader extracts the kind, human-readable name, and ID from raw YAML bytes. It unmarshals into typed structs and delegates to the Extract* functions in internal/asset/ so that apply and the per-asset CRUD commands use the same extraction logic.

func ParseGenerativeAiEvaluation added in v1.21.0

func ParseGenerativeAiEvaluation(data []byte) (*dash0api.GenerativeAiEvaluationDefinition, error)

ParseGenerativeAiEvaluation decodes an eval document and checks what every eval entry point needs before an API call: the fields the API rejects when empty, the required gen_ai.operation.name is_set filter, and a sample rate between 0 and 1. The check runs before the first write, so a multi-document apply never writes some documents and then fails on a problem that the CLI can find by itself. spec.display.name and spec.judge.systemPrompt may be empty, and the model and output kind are not checked against a list, so a value the API adds later still passes.

spec.enabled and spec.sample.rate must be present. The client types hold them as a plain bool and float32, so a document without them would be sent as enabled: false and rate: 0, an eval that never samples a trace.

func ParsePrometheusRuleCRD added in v1.21.0

func ParsePrometheusRuleCRD(data []byte) (*dash0api.RecordingRule, error)

ParsePrometheusRuleCRD parses raw bytes as a PrometheusRule CRD (the typed dash0api.RecordingRule, an alias for the generated PrometheusRule type that captures both Alert and Record per rule).

func ParseSamplingRule added in v1.22.0

func ParseSamplingRule(data []byte) (*dash0api.SamplingDefinition, error)

ParseSamplingRule decodes a sampling rule document and checks what the API would accept but what could never work, before any API call. apply runs it for every document before the first write, so a multi-document apply never writes some rules and then fails on a problem the CLI can find by itself.

  • spec.enabled must be present. The client type holds it as a plain bool, so a document without it would silently create a disabled rule.
  • spec.conditions must be present, because the API requires it.
  • The condition tree may hold at most 32 ottl and error conditions. Dash0 refuses to load a rule above that limit, and the rule stops matching.
  • A rule whose conditions are all probabilistic cannot set spec.rateLimit. The API rejects it, so in apply it would fail after the documents before it were written.

func ParseTelemetryTransformationRule added in v1.25.0

func ParseTelemetryTransformationRule(raw []byte) (*dash0api.TelemetryTransformationRuleDefinition, error)

func Pluralize added in v1.21.0

func Pluralize(count int, singular string) string

Pluralize returns "1 thing" or "N things" depending on count. This logic is currently naive and assumes all plurals are formed by adding "s". This happens to work for all our asset kinds, errors, documents and other situations we use this logic.

func PreferredKey added in v1.22.0

func PreferredKey(definition dash0api.AssetMetadata) string

PreferredKey returns the identifier a document is upserted by: its origin when the kind upserts by origin and the document has one, else its id when the kind upserts by id, else "". Read it before a Strip*ServerFields call, which can clear both labels.

func PrepareTelemetryTransformationRule added in v1.25.0

func PrepareTelemetryTransformationRule(rule, stored *dash0api.TelemetryTransformationRuleDefinition, dataset *string)

PrepareTelemetryTransformationRule turns rule into the body of a PUT for create and apply. The path carries the id or origin, so the body carries neither. An update sends the stored updated-at, so an exported file can be applied again after the server moved the token forward.

func PrepareTelemetryTransformationRuleUpdate added in v1.25.0

func PrepareTelemetryTransformationRuleUpdate(rule, stored *dash0api.TelemetryTransformationRuleDefinition, dataset *string)

PrepareTelemetryTransformationRuleUpdate prepares the body for update -f. It keeps an explicit updated-at, so a rule changed since its export fails with superseded_version instead of being overwritten.

func PreviewUpdate added in v1.20.0

func PreviewUpdate[T any](stored, update any) (*T, error)

PreviewUpdate returns stored as it would look after a partial update: the update's values win, and anything the update leaves out keeps its stored value. It serves kinds whose PUT keeps omitted spec fields, so a dry-run diff does not show omissions as removals.

func PrintChanges added in v1.19.0

func PrintChanges(w io.Writer, displayKind string, before, after any) error

PrintChanges writes the unified diff between the before and after states of an asset to w, and writes nothing when they are the same.

func PrintDiff added in v1.7.0

func PrintDiff(w io.Writer, displayKind, name string, before, after any) error

PrintDiff computes a unified diff between the before and after states of an asset and writes it to w. If there are no changes, a "no changes" message is printed instead.

func PrintUpdateOutcome added in v1.19.0

func PrintUpdateOutcome(w io.Writer, outcome UpdateOutcome) error

PrintUpdateOutcome writes the outcome of an update to w. For a deleted asset it prints `restored`, or `would be restored` on a dry run, followed by a diff of any other changes. For any other asset it prints a diff. After a real update it returns a StillDeletedError when the API response still marks the asset as deleted.

func PrometheusAlertInferredName added in v1.25.0

func PrometheusAlertInferredName(crdName, checkRuleName string) string

PrometheusAlertInferredName is what an alert of a PrometheusRule hashes into its inferred origin, with kind "prometheusrule". The NUL keeps CRD "a" with alert "b - c" apart from CRD "a\x00b" with alert "c".

func PrometheusRuleHasAlerts added in v1.12.2

func PrometheusRuleHasAlerts(crd *dash0api.RecordingRule) bool

PrometheusRuleHasAlerts reports whether any rule in the CRD is an alerting rule (has `alert:` set). Used by apply to decide whether to dispatch to the check-rule import path.

func PrometheusRuleHasRecordingRule added in v1.17.0

func PrometheusRuleHasRecordingRule(data []byte) (bool, error)

PrometheusRuleHasRecordingRule reports whether a PrometheusRule CRD document has at least one recording rule (a `record:` entry). Returns false for a document that isn't a PrometheusRule CRD at all.

--since uses this as a coarse presence/absence signal to detect a CRD that survives (its own identifier is still present in both snapshots) but whose recording-rule role disappeared entirely -- e.g. its last `record:` entry was removed while an `alert:` entry keeps the CRD's identifier alive. Unlike alerting rules, which become one check rule per alert (and so can be tracked and deleted individually by name), Dash0 models a CRD's recording rules as a single server-side resource, so there is no per-record identity to track -- only whether the role exists at all.

func ReadDefinition

func ReadDefinition(path string, target interface{}, stdin io.Reader) error

ReadDefinition reads a YAML or JSON definition from a file or stdin. If path is "-" or empty, it reads from stdin (assumes YAML format). Otherwise, it reads from the file at the given path.

func ReadDefinitionFile

func ReadDefinitionFile(path string, target interface{}) error

ReadDefinitionFile reads a YAML or JSON file and unmarshals into the target. It auto-detects the format based on file extension, falling back to YAML first.

func ReadRawInput added in v1.1.0

func ReadRawInput(path string, stdin io.Reader) ([]byte, error)

ReadRawInput reads raw bytes from a file or stdin without unmarshalling. If path is "-" or empty, it reads from stdin.

func RecordingOnlyPrometheusRule added in v1.12.2

func RecordingOnlyPrometheusRule(crd *dash0api.RecordingRule) *dash0api.RecordingRule

RecordingOnlyPrometheusRule returns a copy of the input PrometheusRule CRD stripped of alerting rules so it can be sent to the recording-rules API. Returns nil if the input contains no recording rules. Empty groups (after filtering) are dropped.

func RecordingRuleDeletedAt added in v1.19.0

func RecordingRuleDeletedAt(rule *dash0api.RecordingRule) *time.Time

RecordingRuleDeletedAt returns when the recording rule was deleted, or nil when it is not deleted. The PrometheusRule type keeps annotations as plain strings, so the timestamp is parsed here.

func RegisterCommonFlags

func RegisterCommonFlags(cmd *cobra.Command, flags *CommonFlags)

RegisterCommonFlags adds common flags to a command

func RegisterDeleteFlags

func RegisterDeleteFlags(cmd *cobra.Command, flags *DeleteFlags)

RegisterDeleteFlags adds delete-specific flags to a command

func RegisterFileInputFlags

func RegisterFileInputFlags(cmd *cobra.Command, flags *FileInputFlags)

RegisterFileInputFlags adds file input flags to a command and marks -f as required

func RegisterGetFlags

func RegisterGetFlags(cmd *cobra.Command, flags *GetFlags)

RegisterGetFlags adds get-specific flags to a command

func RegisterListFlags

func RegisterListFlags(cmd *cobra.Command, flags *ListFlags)

RegisterListFlags adds list-specific flags to a command

func RequireNotDeleted added in v1.19.0

func RequireNotDeleted(displayKind, name, id string, deletedAt *time.Time) error

RequireNotDeleted returns a StillDeletedError when the API response for a create or update still marks the asset as deleted.

func ResolveUpdateKey added in v1.18.0

func ResolveUpdateKey(args []string, k UpdateKey) (string, error)

ResolveUpdateKey returns the originOrId to update. Without an argument it is the key apply upserts by, with no fallback. An argument must match the file, because a PUT onto an asset the file does not name cannot be undone.

func RouteUpdate added in v1.25.0

func RouteUpdate[T any](ctx context.Context, args []string, k UpdateKey, identity Identity, get func(context.Context, string) (T, error)) (string, T, error)

RouteUpdate returns the key and the stored asset that `update -f` writes for a kind RouteDocument routes. Without an argument it reads the file's id first, then its origin, as apply reads those labels. update never creates and never tries the inferred origin, so a missing asset is get's not-found error.

func RoutedKeys added in v1.25.0

func RoutedKeys(upsert dash0api.AssetMetadata) dash0api.AssetMetadata

RoutedKeys lets the shared key rules read the origin of a routed kind whose client type reports that it upserts by id only.

func RoutingAssetsWarning added in v1.16.4

func RoutingAssetsWarning(channel *dash0api.NotificationChannelDefinition) string

RoutingAssetsWarning returns a user-facing warning when the notification channel definition carries a non-empty spec.routing.assets, and an empty string otherwise. The Dash0 API treats spec.routing.assets as an API-managed back-reference (populated when a check rule or synthetic check binds to the channel) and silently ignores any value supplied on write — without a warning, users believe they attached the channel when nothing happened. The wording matches the Terraform provider's warnIfRoutingAssetsSet so both IaC clients speak the same language.

func SLODeletedAt added in v1.19.0

func SLODeletedAt(slo *dash0api.SloDefinition) *time.Time

SLODeletedAt returns when the SLO was deleted, or nil when it is not deleted.

func SLOUsesOrigin added in v1.18.0

func SLOUsesOrigin(data []byte) (bool, error)

SLOUsesOrigin reports whether an SLO document carries a non-empty dash0.com/origin label.

--since uses this to warn when an SLO is about to be deleted by dash0.com/id alone: an id-only SLO that an earlier CLI version created by POST sits at a server-assigned id the document never learned, and the delete misses it.

func SamplingRuleKey added in v1.22.0

func SamplingRuleKey(rule *dash0api.SamplingDefinition) string

SamplingRuleKey returns the identifier ImportSamplingRule upserts by: the dash0.com/origin label, else the dash0.com/id label, else "".

func SamplingRuleKeys added in v1.22.0

func SamplingRuleKeys(rule *dash0api.SamplingDefinition) dash0api.AssetMetadata

SamplingRuleKeys lets the shared key rules resolve a sampling rule's identifiers: the client gives SamplingDefinition no UpsertKeys. Sampling rules upsert by origin, with the id as the fallback. Read it before ClearUpdateOrigin, which clears the origin.

func SamplingRuleUsesOrigin added in v1.22.0

func SamplingRuleUsesOrigin(data []byte) (bool, error)

SamplingRuleUsesOrigin reports whether a sampling rule document carries a non-empty dash0.com/origin label.

--since uses this to warn when a rule is about to be deleted by dash0.com/id alone: an id-only rule that an earlier CLI version created by POST sits at a server-assigned id the document never learned, and the delete misses it.

func SamplingTurnOnWarning added in v1.22.0

func SamplingTurnOnWarning(ctx context.Context, apiClient dash0api.Client, rule, existing *dash0api.SamplingDefinition, dataset *string) string

SamplingTurnOnWarning returns a warning when writing rule would turn sampling on for the dataset: the rule ends up enabled, it was not enabled before, and no other rule in the dataset is enabled. Sampling is off for a dataset until it has an enabled rule; from then on, Dash0 drops every trace that no enabled rule keeps, and dropped traces cannot be recovered.

func SamplingTurnOnWarningInNewDataset added in v1.22.0

func SamplingTurnOnWarningInNewDataset(rule *dash0api.SamplingDefinition, dataset *string) string

SamplingTurnOnWarningInNewDataset returns the turn-on warning for an enabled rule in a dataset that the same run creates. That dataset has no rules yet, so the rule turns sampling on, and its rules cannot be listed before it exists.

func SetCustomSkillOrigin added in v1.25.0

func SetCustomSkillOrigin(skill *dash0api.SkillDefinition, origin string)

func SetGenerativeAiEvaluationOrigin added in v1.25.0

func SetGenerativeAiEvaluationOrigin(evaluation *dash0api.GenerativeAiEvaluationDefinition, origin string)

func SetRecordingRuleOrigin added in v1.25.0

func SetRecordingRuleOrigin(rule *dash0api.RecordingRule, origin string)

SetRecordingRuleOrigin sets the dash0.com/origin label, and removes it when origin is empty.

func SetSyntheticCheckOrigin added in v1.25.0

func SetSyntheticCheckOrigin(check *dash0api.SyntheticCheckDefinition, origin string)

func SetViewOrigin added in v1.25.0

func SetViewOrigin(view *dash0api.ViewDefinition, origin string)

func SignalToMetricsRuleDeletedAt added in v1.21.0

func SignalToMetricsRuleDeletedAt(rule *dash0api.SignalToMetricsDefinition) *time.Time

SignalToMetricsRuleDeletedAt returns when the rule was deleted, or nil when it is not deleted.

func SignalToMetricsRuleKey added in v1.21.0

func SignalToMetricsRuleKey(rule *dash0api.SignalToMetricsDefinition) string

SignalToMetricsRuleKey returns the identifier ImportSignalToMetricsRule upserts by: the dash0.com/origin label, else the dash0.com/id label, else "".

func SignalToMetricsRuleUsesOrigin added in v1.21.0

func SignalToMetricsRuleUsesOrigin(data []byte) (bool, error)

SignalToMetricsRuleUsesOrigin reports whether a signal-to-metrics rule document carries a non-empty dash0.com/origin label.

--since uses this to warn when a rule is about to be deleted by dash0.com/id alone: an id-only rule that an earlier CLI version created by POST sits at a server-assigned id the document never learned, and the delete misses it.

func SortCustomSkillPermissions added in v1.20.0

func SortCustomSkillPermissions(skill *dash0api.SkillDefinition)

SortCustomSkillPermissions is the custom skill equivalent of SortViewPermissions.

func SortDatasetPermissions added in v1.19.0

func SortDatasetPermissions(dataset *dash0api.DatasetDefinition)

SortDatasetPermissions is the Dataset equivalent of SortViewPermissions.

func SortSyntheticCheckPermissions added in v1.16.4

func SortSyntheticCheckPermissions(check *dash0api.SyntheticCheckDefinition)

SortSyntheticCheckPermissions is the SyntheticCheck equivalent of SortViewPermissions.

func SortViewPermissions added in v1.16.4

func SortViewPermissions(view *dash0api.ViewDefinition)

SortViewPermissions sorts a view's spec.permissions lexicographically. The server does not guarantee a stable order for this field (see issue #231), so the CLI normalizes it before display or diffing to avoid spurious reordering noise across repeated get/apply cycles.

func SpamFilterUsesOrigin added in v1.17.0

func SpamFilterUsesOrigin(data []byte) (bool, error)

SpamFilterUsesOrigin reports whether a spam filter document (v1alpha1 or v1alpha2 — both share the same metadata/labels shape) carries a non-empty dash0.com/origin label.

--since uses this to warn when a spam filter is about to be deleted by dash0.com/id alone: per ImportSpamFilter's upsert-key selection, an ID-only spam filter's id is reassigned server-side on its first PUT to a brand-new id, so the id recorded in the git history --since diffs against may no longer match the live asset's actual id by the time the document is deleted — deleting by that stale id either 404s (hard-failing without --force) or is silently treated as already-deleted (with --force), leaving the real live filter orphaned either way. There is no local, API-free way to recover the live id from git history alone; the origin label is the only identifier that never gets reassigned.

func SpamFilterV1Alpha2ID added in v1.21.0

func SpamFilterV1Alpha2ID(filter *dash0api.SpamFilterV1Alpha2) string

SpamFilterV1Alpha2ID extracts the dash0.com/id label from a v1alpha2 filter. Kept here rather than re-exporting from the api client because the API client only exposes labelled accessors for v1alpha1.

func SyntheticCheckDeletedAt added in v1.19.0

func SyntheticCheckDeletedAt(check *dash0api.SyntheticCheckDefinition) *time.Time

SyntheticCheckDeletedAt returns when the synthetic check was deleted, or nil when it is not deleted.

func TeamUsesOrigin added in v1.22.0

func TeamUsesOrigin(data []byte) (bool, error)

TeamUsesOrigin reports whether a team document carries a non-empty dash0.com/origin label. --since uses it the same way as SLOUsesOrigin: an id-only team applied before the router was created by POST, so the live team can sit at a server-assigned id the document never learned.

func TelemetryTransformationRuleDeletedAt added in v1.25.0

func TelemetryTransformationRuleDeletedAt(rule *dash0api.TelemetryTransformationRuleDefinition) *time.Time

TelemetryTransformationRuleDeletedAt returns when the stored rule was deleted, or nil.

func TimeSeriesAggregationDeletedAt added in v1.19.0

func TimeSeriesAggregationDeletedAt(aggregation *dash0api.TimeSeriesAggregationDefinition) *time.Time

TimeSeriesAggregationDeletedAt returns when the aggregation was deleted, or nil when it is not deleted.

func ToEphemeralDashboard added in v1.23.0

func ToEphemeralDashboard(dashboard *dash0api.DashboardDefinition, ttl string)

ToEphemeralDashboard turns dashboard into an EphemeralDashboard that the API deletes once ttl has passed since its latest write.

func UnifiedDiff added in v1.21.0

func UnifiedDiff(displayKind string, before, after any) (string, error)

UnifiedDiff returns the unified diff between before and after, or "" when they are semantically the same. dash0 diff uses it to compare each update once and print the same text later with WriteDiff.

func UpdateOrigin added in v1.25.0

func UpdateOrigin(storedOrigin, key string) string

UpdateOrigin returns the origin that an update of a view, synthetic check, or recording rule at key sends. An update at the stored origin sends it back, because without it Dash0 leaves the origin out of a later read by id. An update at the id sends none, because the API rejects a body origin there.

func ValidateCustomSkill added in v1.20.0

func ValidateCustomSkill(skill *dash0api.SkillDefinition) error

ValidateCustomSkill checks what every custom skill entry point needs before an API call: the Dash0Skill kind and a SKILL.md file at the skill root.

func ValidateDashboard added in v1.22.0

func ValidateDashboard(dashboard *dash0api.DashboardDefinition) error

ValidateDashboard rejects a dashboard whose dash0.com/origin label and metadata.dash0Extensions.id differ: the API refuses the create, and an update would address only one of the two.

func ValidateDataset added in v1.19.0

func ValidateDataset(dataset *dash0api.DatasetDefinition) error

ValidateDataset checks what every dataset entry point needs before an API call: a slug and a known apiVersion.

func ValidateDatasetAPIVersion added in v1.19.0

func ValidateDatasetAPIVersion(dataset *dash0api.DatasetDefinition) error

ValidateDatasetAPIVersion rejects a dataset definition whose apiVersion is missing or unknown, so a typo fails before any API call instead of as a server 400.

func ValidateDocuments added in v1.21.0

func ValidateDocuments(documents []Document) (validationErrors, validationWarnings []string)

ValidateDocuments checks all documents up front, collecting all errors so a multi-doc apply is never partially triggered by a problem detectable before the first API call. Non-fatal warnings are collected separately — callers only print them when validation succeeds, since a warning about a document that never gets applied would be noise next to a hard error.

func ValidateEphemeralDashboard added in v1.23.0

func ValidateEphemeralDashboard(dashboard *dash0api.DashboardDefinition) error

ValidateEphemeralDashboard rejects an EphemeralDashboard without spec.ttl before any write. The API owns the duration format and its limits.

func ValidatePrometheusRule added in v1.21.0

func ValidatePrometheusRule(data []byte) error

ValidatePrometheusRule rejects a PrometheusRule CRD that contains no alerting and no recording rules, so the failure surfaces in the validation phase rather than after the first request.

func ViewDeletedAt added in v1.19.0

func ViewDeletedAt(view *dash0api.ViewDefinition) *time.Time

ViewDeletedAt returns when the view was deleted, or nil when it is not deleted.

func WarnNothingAtInferredOrigin added in v1.25.0

func WarnNothingAtInferredOrigin(w io.Writer, origin string)

WarnNothingAtInferredOrigin reports a --since deletion that is skipped, because nothing is stored at the inferred origin.

func WithInferredOriginWrites added in v1.25.0

func WithInferredOriginWrites(ctx context.Context, writes InferredOriginWrites, location string) context.Context

WithInferredOriginWrites makes RouteDocument claim the inferred origin the document at location writes, before the write.

func WrapSamplingRuleWrongDataset added in v1.22.0

func WrapSamplingRuleWrongDataset(err error, originOrID string) error

WrapSamplingRuleWrongDataset turns the cross-dataset 400 into an error that names the cause and the fix, with the advice behind "\nHint:" so agent mode lifts it into the JSON error's hint field.

func WrapSignalToMetricsRuleWrongDataset added in v1.21.0

func WrapSignalToMetricsRuleWrongDataset(err error, originOrID string) error

WrapSignalToMetricsRuleWrongDataset turns the cross-dataset 400 into an error that names the cause and the fix, with the advice behind "\nHint:" so agent mode lifts it into the JSON error's hint field.

func WrapTimeSeriesAggregationWrongDataset added in v1.18.0

func WrapTimeSeriesAggregationWrongDataset(err error, origin string) error

WrapTimeSeriesAggregationWrongDataset turns the API's cross-dataset 400 into an error that names the cause and the fix. The API states the fact but not what to do about it, and the fix is counterintuitive: origins are organization-wide, so one document cannot serve two datasets.

The advice goes behind "\nHint:" so agent mode lifts it into the JSON error's hint field, as every other actionable error here does (see agentmode.PrintJSONError).

func WriteDefinitionFile

func WriteDefinitionFile(path string, data interface{}) error

WriteDefinitionFile writes data to a YAML or JSON file. It auto-detects the format based on file extension, defaulting to YAML.

func WriteDiff added in v1.21.0

func WriteDiff(w io.Writer, text string) error

WriteDiff writes text from UnifiedDiff to w, colorized unless color is off.

func WriteToStdout

func WriteToStdout(format string, data interface{}) error

WriteToStdout writes data to stdout in the specified format. Format can be "yaml", "yml", or "json".

Types

type CheckRule added in v1.25.0

type CheckRule struct {
	*dash0api.PrometheusAlertRule
	// Origin is the document's origin. The rule's labels are its alerts'
	// Prometheus labels, so the origin never travels in them.
	Origin       string
	InferredKind string
	InferredName string
}

CheckRule is a check rule ready for import, with the kind and name its inferred origin comes from.

func ParseCheckRules added in v1.15.4

func ParseCheckRules(data []byte) ([]CheckRule, error)

ParseCheckRules parses a CheckRule or PrometheusRule CRD document into one or more check rules ready for import.

A CheckRule infers its origin from its name. An alert of a PrometheusRule infers it from the CRD's metadata.name and the alert's composed name, so two alerts never share one, and carries the CRD's dash0.com/origin, derived per alert like the id when the CRD has two or more alerts.

For PrometheusRule CRDs the check-rule name is composed as "<group name> - <alert name>", matching the Dash0 Kubernetes operator and the Terraform provider. A plain CheckRule document keeps its name verbatim.

The underlying SDK conversion (ParseAsPrometheusAlertRules) names each check rule after the alert only and discards the group name, so the group-name prefix is reapplied here from the raw CRD.

func (CheckRule) Identity added in v1.25.0

func (rule CheckRule) Identity(dataset *string) Identity

Identity returns what RouteDocument routes the check rule by.

func (CheckRule) UpdateKeys added in v1.25.0

func (rule CheckRule) UpdateKeys() dash0api.AssetMetadata

UpdateKeys is what `check-rules update -f` resolves its key from: the rule's origin lives in Origin, not in its labels.

type CommonFlags

type CommonFlags struct {
	ApiUrl    string
	AuthToken string
	Dataset   string
	Output    string
}

CommonFlags holds common flag values used across all asset commands

type DashboardKindMismatchError added in v1.23.0

type DashboardKindMismatchError struct {
	ID       string
	Stored   string
	Proposed string
}

DashboardKindMismatchError reports a write that would change a dashboard between ephemeral and permanent, which the API rejects.

func (*DashboardKindMismatchError) Error added in v1.23.0

type DatasetSlugChangeError added in v1.25.0

type DatasetSlugChangeError struct {
	Origin   string
	Stored   string
	Document string
}

DatasetSlugChangeError reports a document whose origin belongs to a dataset with another slug.

func (*DatasetSlugChangeError) Error added in v1.25.0

func (e *DatasetSlugChangeError) Error() string

type DeleteFlags

type DeleteFlags struct {
	CommonFlags
	Force bool
}

DeleteFlags holds flags specific to delete commands

type Document added in v1.21.0

type Document struct {
	Kind     string
	Name     string // human-readable name extracted from the document
	ID       string // asset ID extracted from the document (location varies by kind)
	Raw      []byte
	FilePath string // relative path when loaded from a directory, empty for stdin/single-file
	DocIndex int    // 1-based index within the file
	DocCount int    // total number of documents in the file
}

Document represents a parsed YAML document with its kind, extracted name/identifier, and raw content. Shared between apply (which creates/updates/deletes from it) and diff (which only reads and previews), so both commands discover and parse -f's input identically.

func ParseMultiDocumentYAML added in v1.21.0

func ParseMultiDocumentYAML(data []byte) ([]Document, error)

ParseMultiDocumentYAML splits data on YAML document boundaries and parses each into an Document. Factored out of ReadMultiDocumentYAML so callers that already have file content in memory (e.g. --since's git-history name lookups, which read a blob via ReadFileAtRef rather than a path on disk) can reuse the same parsing without a round trip through the filesystem.

func ReadDirectory added in v1.21.0

func ReadDirectory(dirPath string) ([]Document, error)

ReadDirectory reads all YAML files from a directory recursively.

func ReadInput added in v1.21.0

func ReadInput(file string, sinceFlagSet bool) (documents []Document, fromDirectory, targetVanished bool, err error)

ReadInput reads -f the way apply and diff do: stdin ("-"), a single file, or a directory (recursively). With --since, a target that was removed or holds no YAML file anymore is an all-deletions run, not an error, so it returns no documents. targetVanished reports that the target no longer exists, so fromDirectory is a guess the caller corrects from git history.

func ReadMultiDocumentYAML added in v1.21.0

func ReadMultiDocumentYAML(filePath string, stdin io.Reader) ([]Document, error)

ReadMultiDocumentYAML splits a YAML stream into individual documents. This is the only place that requires gopkg.in/yaml.v3 directly — sigs.k8s.io/yaml doesn't provide a streaming decoder for multi-document YAML.

func (Document) Location added in v1.21.0

func (d Document) Location() string

Location returns a human-readable string describing where this document came from.

type FileInputFlags

type FileInputFlags struct {
	CommonFlags
	File   string
	DryRun bool
}

FileInputFlags holds flags for file-based input operations (create, update, apply)

type GetFlags

type GetFlags struct {
	CommonFlags
}

GetFlags holds flags specific to get commands

type IDOriginConflictError added in v1.25.0

type IDOriginConflictError struct {
	ID     string
	Origin string
}

IDOriginConflictError reports a check rule whose id and origin differ. The rule is created at the id, and Dash0 returns no origin label for it, so every later apply would fail the stored-origin check.

func (*IDOriginConflictError) Error added in v1.25.0

func (e *IDOriginConflictError) Error() string

type Identity added in v1.25.0

type Identity struct {
	// ID is the document's id, or "".
	ID string
	// Origin is the document's dash0.com/origin, or "".
	Origin string
	// Inferred is the origin a document without one is created by.
	Inferred string
	// CreatesAtID is set for kinds that keep the id in the file, as check
	// rules: an id that is not found is created at that id.
	CreatesAtID bool
	// IDRequired is set for kinds that cannot be written without their id,
	// as datasets and AWS metric scrape configs.
	IDRequired bool
}

Identity is what a document names its asset by.

func AwsMetricScrapeConfigIdentity added in v1.25.0

func AwsMetricScrapeConfigIdentity(cfg *dash0api.AwsMetricScrapeConfigDefinition, integrationID string) Identity

AwsMetricScrapeConfigIdentity returns what an AWS metric scrape config is routed by. The integration id is the id, and the inferred origin hashes it in place of metadata.name, which is the integration's name and read-only.

func CustomSkillIdentity added in v1.25.0

func CustomSkillIdentity(skill *dash0api.SkillDefinition) Identity

CustomSkillIdentity returns what RouteDocument routes a skill by. The inferred origin comes from the skill's name, which is the SKILL.md frontmatter name and unique per organization, not from metadata.name. Skills are organization-level, so it has no dataset.

func DashboardIdentity added in v1.25.0

func DashboardIdentity(dashboard *dash0api.DashboardDefinition, inferredName string, dataset *string) Identity

DashboardIdentity returns what RouteDocument routes a dashboard by. The id is the dash0.com/id label; metadata.dash0Extensions.id names the origin, which ValidateDashboard keeps equal to the dash0.com/origin label. The inferred origin comes from inferredName (see ParseDashboard).

func DatasetIdentity added in v1.25.0

func DatasetIdentity(dataset *dash0api.DatasetDefinition) Identity

DatasetIdentity returns what RouteDocument routes a dataset by. The slug is the id, and the inferred origin hashes it in place of metadata.name, because the slug is required and names the dataset for good.

func GenerativeAiEvaluationIdentity added in v1.25.0

func GenerativeAiEvaluationIdentity(evaluation *dash0api.GenerativeAiEvaluationDefinition, dataset *string) Identity

GenerativeAiEvaluationIdentity returns what RouteDocument routes an eval by.

func NotificationChannelIdentity added in v1.25.0

func NotificationChannelIdentity(channel *dash0api.NotificationChannelDefinition) Identity

NotificationChannelIdentity returns what RouteDocument routes a notification channel by. Channels are organization-level, so the inferred origin has no dataset.

func RecordingRuleIdentity added in v1.25.0

func RecordingRuleIdentity(rule *dash0api.RecordingRule, dataset *string) Identity

RecordingRuleIdentity returns what RouteDocument routes the recording rules of a PrometheusRule CRD by. They are one asset, so the origin is inferred from the CRD's metadata.name alone.

func SLOIdentity added in v1.25.0

func SLOIdentity(slo *dash0api.SloDefinition, dataset *string) Identity

SLOIdentity returns what RouteDocument routes an SLO by.

func SamplingRuleIdentity added in v1.25.0

func SamplingRuleIdentity(rule *dash0api.SamplingDefinition, dataset *string) Identity

SamplingRuleIdentity returns what RouteDocument routes a sampling rule by. The client gives SamplingDefinition no GetOrigin, so the labels are read here.

func SignalToMetricsRuleIdentity added in v1.25.0

func SignalToMetricsRuleIdentity(rule *dash0api.SignalToMetricsDefinition, dataset *string) Identity

SignalToMetricsRuleIdentity returns what RouteDocument routes a signal-to-metrics rule by.

func SpamFilterIdentity added in v1.25.0

func SpamFilterIdentity(filter interface {
	routedAsset
	GetName() string
}, dataset *string) Identity

SpamFilterIdentity returns what RouteDocument routes a spam filter of either apiVersion by.

func SyntheticCheckIdentity added in v1.25.0

func SyntheticCheckIdentity(check *dash0api.SyntheticCheckDefinition, dataset *string) Identity

SyntheticCheckIdentity returns what RouteDocument routes a synthetic check by.

func TeamIdentity added in v1.25.0

func TeamIdentity(team *dash0api.TeamDefinitionV1Alpha1) Identity

TeamIdentity returns what RouteDocument routes a team by. Teams are organization-level, so the inferred origin has no dataset.

func TelemetryTransformationRuleIdentity added in v1.25.0

func TelemetryTransformationRuleIdentity(rule *dash0api.TelemetryTransformationRuleDefinition, dataset *string) Identity

TelemetryTransformationRuleIdentity returns what RouteDocument routes a rule by.

func TimeSeriesAggregationIdentity added in v1.25.0

func TimeSeriesAggregationIdentity(aggregation *dash0api.TimeSeriesAggregationDefinition, dataset *string) Identity

TimeSeriesAggregationIdentity returns what RouteDocument routes a time series aggregation by.

func ViewIdentity added in v1.25.0

func ViewIdentity(view *dash0api.ViewDefinition, dataset *string) Identity

ViewIdentity returns what RouteDocument routes a view by.

func (Identity) CreateOrigin added in v1.25.0

func (i Identity) CreateOrigin() string

CreateOrigin is the origin the asset is created by.

type ImportAction added in v1.1.0

type ImportAction string

ImportAction indicates whether an asset was created, updated, or restored.

const (
	ActionCreated  ImportAction = "created"
	ActionUpdated  ImportAction = "updated"
	ActionRestored ImportAction = "restored"
)

type ImportPlan added in v1.21.0

type ImportPlan struct {
	// Key is the id or origin the write targets. An empty Key means a create
	// with a server-assigned id.
	Key    string
	Action ImportAction
	// Before is the stored asset, or nil when nothing is stored yet.
	Before any
	// Proposed is the asset as it would be stored after the write.
	Proposed any
	// Warnings are non-fatal notes about the planned write. Callers print
	// them to stderr; see ImportResult.Warnings.
	Warnings []string
}

ImportPlan is what an import would do, decided from the stored asset before any write. apply writes it; diff only prints it.

func PlanAwsMetricScrapeConfig added in v1.21.0

func PlanAwsMetricScrapeConfig(
	ctx context.Context,
	apiClient dash0api.Client,
	cfg *dash0api.AwsMetricScrapeConfigDefinition,
	integrationID string,
) (ImportPlan, error)

PlanAwsMetricScrapeConfig reads the stored config that ImportAwsMetricScrapeConfig would replace. It does not use RouteDocument: the integration id is the only key, and an unknown integration fails, because the CLI cannot create one. An integration that never had a config, or had it cleared, makes the write a create.

func PlanCheckRule added in v1.21.0

func PlanCheckRule(ctx context.Context, apiClient dash0api.Client, rule CheckRule, dataset *string) (ImportPlan, error)

PlanCheckRule routes the check rule with RouteDocument and reads the stored rule that ImportCheckRule would write. It returns any preflight error other than "not found"; Key is empty when the id read failed, because the write has no target.

func PlanCustomSkill added in v1.21.0

func PlanCustomSkill(ctx context.Context, apiClient dash0api.Client, skill *dash0api.SkillDefinition) (ImportPlan, error)

PlanCustomSkill routes the skill with RouteDocument and reads the stored skill that ImportCustomSkill would write. Any preflight error other than "not found" is returned and stops the write. Only a PUT to the id keeps the id in the body.

func PlanDashboard added in v1.21.0

func PlanDashboard(ctx context.Context, apiClient dash0api.Client, dashboard *dash0api.DashboardDefinition, inferredName string, dataset *string) (ImportPlan, error)

PlanDashboard reads the stored dashboard that ImportDashboard would write. It returns any preflight error other than "not found".

func PlanDataset added in v1.21.0

func PlanDataset(ctx context.Context, apiClient dash0api.Client, dataset *dash0api.DatasetDefinition) (ImportPlan, error)

PlanDataset routes the dataset with RouteDocument and reads the stored dataset that ImportDataset would write. Key is empty when the document is invalid or the slug read failed, because the write has no target.

func PlanGenerativeAiEvaluation added in v1.21.0

func PlanGenerativeAiEvaluation(ctx context.Context, apiClient dash0api.Client, evaluation *dash0api.GenerativeAiEvaluationDefinition, dataset *string) (ImportPlan, error)

PlanGenerativeAiEvaluation routes the eval with RouteDocument and reads the stored eval that ImportGenerativeAiEvaluation would write. Any preflight error other than "not found" is returned and stops the write.

func PlanNotificationChannel added in v1.21.0

func PlanNotificationChannel(ctx context.Context, apiClient dash0api.Client, channel *dash0api.NotificationChannelDefinition) (ImportPlan, error)

PlanNotificationChannel routes the channel with RouteDocument and reads the stored channel that ImportNotificationChannel would write. It returns any preflight error other than "not found"; an empty Key means the write has no target.

func PlanRecordingRule added in v1.21.0

func PlanRecordingRule(ctx context.Context, apiClient dash0api.Client, rule *dash0api.RecordingRule, dataset *string) (ImportPlan, error)

PlanRecordingRule routes the recording rule with RouteDocument, reads the stored rule that ImportRecordingRule would write, and carries its version onto rule. It returns any preflight error other than "not found"; Key is empty when the id read failed, because the write has no target.

func PlanSLO added in v1.21.0

func PlanSLO(ctx context.Context, apiClient dash0api.Client, slo *dash0api.SloDefinition, dataset *string) (ImportPlan, error)

PlanSLO routes the SLO with RouteDocument and reads the stored SLO that ImportSLO would write. Any preflight error other than "not found" is returned and stops the write.

func PlanSamplingRule added in v1.22.0

func PlanSamplingRule(ctx context.Context, apiClient dash0api.Client, rule *dash0api.SamplingDefinition, dataset *string) (ImportPlan, error)

PlanSamplingRule routes the rule with RouteDocument, reads the stored rule that ImportSamplingRule would write, and prepares rule as the request body. Any preflight error other than "not found" is returned and stops the write.

Unlike signal-to-metrics rules, the GET honors the dataset: a rule stored in another dataset fails it with the cross-dataset 400. That 400 is not "not found", so it is returned wrapped, and a preview fails the same way the write would. Only a PUT to the id keeps the id in the body.

When the write would turn sampling on for the dataset, the plan carries a warning: once a dataset has an enabled rule, Dash0 drops every trace that no enabled rule keeps.

func PlanSignalToMetricsRule added in v1.21.0

func PlanSignalToMetricsRule(ctx context.Context, apiClient dash0api.Client, rule *dash0api.SignalToMetricsDefinition, dataset *string) (ImportPlan, error)

PlanSignalToMetricsRule routes the rule with RouteDocument, reads the stored rule that ImportSignalToMetricsRule would write, and prepares rule as the request body. Any preflight error other than "not found" is returned and stops the write.

The GET ignores the dataset, so a stored rule from another dataset fails here with a SignalToMetricsRuleDatasetMismatchError instead of being compared against. Only a PUT to the id keeps the id in the body: a PUT to an origin selects the rule by the path, so an id in the body can only disagree with it, for example the id of the same rule in another organization.

func PlanSpamFilter added in v1.21.0

func PlanSpamFilter(ctx context.Context, apiClient dash0api.Client, filter *dash0api.SpamFilter, dataset *string) (ImportPlan, error)

PlanSpamFilter reads the stored v1alpha1 spam filter that ImportSpamFilter would write. It returns any preflight error other than "not found"; an empty Key means the write has no target.

func PlanSpamFilterV1Alpha2 added in v1.21.0

func PlanSpamFilterV1Alpha2(ctx context.Context, apiClient dash0api.Client, filter *dash0api.SpamFilterV1Alpha2, dataset *string) (ImportPlan, error)

PlanSpamFilterV1Alpha2 reads the stored spam filter that ImportSpamFilterV1Alpha2 would write. See PlanSpamFilter.

func PlanSyntheticCheck added in v1.21.0

func PlanSyntheticCheck(ctx context.Context, apiClient dash0api.Client, check *dash0api.SyntheticCheckDefinition, dataset *string) (ImportPlan, error)

PlanSyntheticCheck routes the synthetic check with RouteDocument and reads the stored check that ImportSyntheticCheck would write. It returns any preflight error other than "not found"; Key is empty when the id read failed, because the write has no target.

func PlanTeam added in v1.21.0

func PlanTeam(ctx context.Context, apiClient dash0api.Client, team *dash0api.TeamDefinitionV1Alpha1) (ImportPlan, error)

PlanTeam routes the team with RouteDocument and reads the stored team that ImportTeam would write. It returns any preflight error other than "not found"; an empty Key means the write has no target.

The server stores member ids, so spec.members on Before holds ids. Callers resolve them to emails and decide whether a failed lookup matters.

func PlanTelemetryTransformationRule added in v1.25.0

func PlanTelemetryTransformationRule(ctx context.Context, apiClient dash0api.Client, rule *dash0api.TelemetryTransformationRuleDefinition, dataset *string) (ImportPlan, error)

PlanTelemetryTransformationRule routes the rule with RouteDocument, reads the stored rule that ImportTelemetryTransformationRule would write, and prepares rule as the request body. The GET hides deleted rules and rules in other datasets, so both route as a create: the PUT revives a deleted rule, and fails with a conflict for an origin in another dataset.

func PlanTimeSeriesAggregation added in v1.21.0

func PlanTimeSeriesAggregation(ctx context.Context, apiClient dash0api.Client, aggregation *dash0api.TimeSeriesAggregationDefinition, dataset *string) (ImportPlan, error)

PlanTimeSeriesAggregation routes the aggregation with RouteDocument and reads the stored aggregation that ImportTimeSeriesAggregation would write.

Any preflight error other than "not found" is returned, because the PUT would fail the same way. A 403 is the common case, since every endpoint for this kind needs the admin role.

func PlanView added in v1.21.0

func PlanView(ctx context.Context, apiClient dash0api.Client, view *dash0api.ViewDefinition, dataset *string) (ImportPlan, error)

PlanView routes the view with RouteDocument and reads the stored view that ImportView would write. It returns any preflight error other than "not found"; Key is empty when the id read failed, because the write has no target.

type ImportResult added in v1.1.0

type ImportResult struct {
	Name   string
	ID     string
	Action ImportAction
	Before any // asset state before update or restore (nil for creates)
	After  any // asset state after update/create
	// Warnings are non-fatal notes about the write, such as a sampling rule
	// that turns sampling on for its dataset. Callers print them to stderr.
	Warnings []string
}

ImportResult holds the outcome of importing an asset.

func ImportAwsMetricScrapeConfig added in v1.20.0

func ImportAwsMetricScrapeConfig(
	ctx context.Context,
	apiClient dash0api.Client,
	cfg *dash0api.AwsMetricScrapeConfigDefinition,
	integrationID string,
) (ImportResult, error)

ImportAwsMetricScrapeConfig replaces the scrape config of an AWS integration.

The metadata is not sent, because the server ignores all of it except dash0.com/origin. The origin is sent only by the first write, the create, because the server stores it then and ignores it afterwards.

func ImportCheckRule added in v1.1.0

func ImportCheckRule(ctx context.Context, apiClient dash0api.Client, rule CheckRule, dataset *string) (ImportResult, error)

ImportCheckRule creates or updates a check rule through RouteDocument. A PUT to a deleted check rule brings it back, which is reported as ActionRestored.

func ImportCustomSkill added in v1.20.0

func ImportCustomSkill(ctx context.Context, apiClient dash0api.Client, skill *dash0api.SkillDefinition) (ImportResult, error)

ImportCustomSkill creates or updates an Agent0 custom skill through RouteDocument. The body carries the origin only on create.

The origin and id are read before StripCustomSkillServerFields, which removes spec.source and the per-user dash0.com/enabled annotation that a write must never send.

func ImportDashboard added in v1.1.0

func ImportDashboard(ctx context.Context, apiClient dash0api.Client, dashboard *dash0api.DashboardDefinition, inferredName string, dataset *string) (ImportResult, error)

ImportDashboard creates or updates a dashboard through RouteDocument, and infers its origin from inferredName (see ParseDashboard). A PUT to a deleted dashboard brings it back, which is reported as ActionRestored.

func ImportDataset added in v1.19.0

func ImportDataset(ctx context.Context, apiClient dash0api.Client, dataset *dash0api.DatasetDefinition) (ImportResult, error)

ImportDataset creates or updates a dataset by the routing rule, with the slug as its id. A PUT creates a dataset that does not exist, and restores one deleted within the last 30 days, so a dataset is never created by POST.

func ImportGenerativeAiEvaluation added in v1.21.0

func ImportGenerativeAiEvaluation(ctx context.Context, apiClient dash0api.Client, evaluation *dash0api.GenerativeAiEvaluationDefinition, dataset *string) (ImportResult, error)

ImportGenerativeAiEvaluation creates or updates a generative AI evaluation through RouteDocument. The body carries the origin only on create.

The identifiers are read before StripGenerativeAiEvaluationServerFields, which removes dash0.com/id (the server rejects a create that sets it) and dash0.com/version. Without the version, the PUT overwrites unconditionally.

func ImportNotificationChannel added in v1.9.0

func ImportNotificationChannel(ctx context.Context, apiClient dash0api.Client, channel *dash0api.NotificationChannelDefinition) (ImportResult, error)

ImportNotificationChannel creates or updates a notification channel through RouteDocument.

func ImportRecordingRule added in v1.11.0

func ImportRecordingRule(ctx context.Context, apiClient dash0api.Client, rule *dash0api.RecordingRule, dataset *string) (ImportResult, error)

ImportRecordingRule creates or updates a recording rule through RouteDocument. A PUT to a deleted recording rule brings it back, which is reported as ActionRestored.

func ImportSLO added in v1.18.0

func ImportSLO(ctx context.Context, apiClient dash0api.Client, slo *dash0api.SloDefinition, dataset *string) (ImportResult, error)

ImportSLO creates or updates an SLO through RouteDocument. The path carries the origin, so the body never does. A PUT to a deleted SLO brings it back, which is reported as ActionRestored.

func ImportSamplingRule added in v1.22.0

func ImportSamplingRule(ctx context.Context, apiClient dash0api.Client, rule *dash0api.SamplingDefinition, dataset *string) (ImportResult, error)

ImportSamplingRule creates or updates a sampling rule through RouteDocument. The path carries the origin, so the body never does.

The labels are read before StripSamplingRuleServerFields, which clears the dataset label, and ClearUpdateOrigin, which clears the origin. The dataset label must not be sent: on writes it currently wins over the dataset query parameter, so an exported rule would otherwise land in the dataset it was exported from.

The API deletes sampling rules for good, so a write never restores one.

func ImportSignalToMetricsRule added in v1.21.0

func ImportSignalToMetricsRule(ctx context.Context, apiClient dash0api.Client, rule *dash0api.SignalToMetricsDefinition, dataset *string) (ImportResult, error)

ImportSignalToMetricsRule creates or updates a signal-to-metrics rule through RouteDocument. The path carries the origin, so the body never does. A PUT to a deleted rule brings it back, which is reported as ActionRestored.

func ImportSpamFilter added in v1.12.0

func ImportSpamFilter(ctx context.Context, apiClient dash0api.Client, filter *dash0api.SpamFilter, dataset *string) (ImportResult, error)

ImportSpamFilter creates or updates a v1alpha1 spam filter through RouteDocument. An id that is not found is never PUT, because the server would assign a fresh id and a repeated apply would create another filter.

func ImportSpamFilterV1Alpha2 added in v1.12.2

func ImportSpamFilterV1Alpha2(ctx context.Context, apiClient dash0api.Client, filter *dash0api.SpamFilterV1Alpha2, dataset *string) (ImportResult, error)

ImportSpamFilterV1Alpha2 mirrors ImportSpamFilter for the v1alpha2 schema, which carries spec.context (scalar) instead of spec.contexts (array).

func ImportSyntheticCheck added in v1.1.0

func ImportSyntheticCheck(ctx context.Context, apiClient dash0api.Client, check *dash0api.SyntheticCheckDefinition, dataset *string) (ImportResult, error)

ImportSyntheticCheck creates or updates a synthetic check through RouteDocument. A PUT to a deleted synthetic check brings it back, which is reported as ActionRestored.

func ImportTeam added in v1.16.0

func ImportTeam(ctx context.Context, apiClient dash0api.Client, team *dash0api.TeamDefinitionV1Alpha1) (ImportResult, error)

ImportTeam creates or updates a team through RouteDocument.

Before returning, spec.members on both the before and after states is translated from internal IDs (what the server echoes) to email addresses, so the apply diff renderer prints legible membership changes.

func ImportTelemetryTransformationRule added in v1.25.0

func ImportTelemetryTransformationRule(ctx context.Context, apiClient dash0api.Client, rule *dash0api.TelemetryTransformationRuleDefinition, dataset *string) (ImportResult, error)

ImportTelemetryTransformationRule creates or updates a rule through RouteDocument, always by PUT.

func ImportTimeSeriesAggregation added in v1.18.0

func ImportTimeSeriesAggregation(
	ctx context.Context,
	apiClient dash0api.Client,
	aggregation *dash0api.TimeSeriesAggregationDefinition,
	dataset *string,
) (ImportResult, error)

ImportTimeSeriesAggregation creates or updates a time series aggregation through RouteDocument. The path carries the origin, so the body never does. A PUT to a deleted aggregation brings it back, which is reported as ActionRestored.

func ImportView added in v1.1.0

func ImportView(ctx context.Context, apiClient dash0api.Client, view *dash0api.ViewDefinition, dataset *string) (ImportResult, error)

ImportView creates or updates a view through RouteDocument. A PUT to a deleted view brings it back, which is reported as ActionRestored.

type InferredKey added in v1.25.0

type InferredKey struct {
	// Kind is the normalized kind of the asset: "checkrule" and
	// "recordingrule" for the assets of a PrometheusRule.
	Kind   string
	Origin string
	// Name is the display name of an asset of a PrometheusRule, else "".
	Name string
}

InferredKey is an asset that apply writes at its inferred origin, because its document has no origin.

func ExtractInferredKeys added in v1.25.0

func ExtractInferredKeys(data []byte, dataset *string) ([]InferredKey, bool, error)

ExtractInferredKeys returns the assets that a document without an origin writes at their inferred origins, the same ones apply computes for the dataset. A document with an id writes there only when the id is not found. It returns false for a document with an origin, and for datasets and AWS metric scrape configs, whose id is required.

type InferredOriginWrites added in v1.25.0

type InferredOriginWrites map[string]string

InferredOriginWrites maps each inferred origin a run writes to the document that writes it, so a second document writing there fails instead of replacing the first.

func (InferredOriginWrites) Claim added in v1.25.0

func (w InferredOriginWrites) Claim(identity Identity, key, location string) error

Claim records that the document at location writes key. It fails when another document of the run already writes key as its inferred origin.

func (InferredOriginWrites) ClaimDocument added in v1.25.0

func (w InferredOriginWrites) ClaimDocument(doc Document, dataset *string, key string) error

ClaimDocument is Claim for a document whose write targets key, for callers that plan documents without routing them in run order.

type ListFlags

type ListFlags struct {
	CommonFlags
	Limit      int
	All        bool
	SkipHeader bool
}

ListFlags holds flags specific to list commands

type OriginMismatchError added in v1.25.0

type OriginMismatchError struct {
	ID         string
	Stored     string
	Document   string
	IDRequired bool
}

OriginMismatchError reports a document whose id names an asset that Dash0 stores with another origin. The CLI never changes a stored origin.

func (*OriginMismatchError) Error added in v1.25.0

func (e *OriginMismatchError) Error() string

type PrometheusAlertName added in v1.17.0

type PrometheusAlertName struct {
	GroupName string
	AlertName string
}

PrometheusAlertName identifies a single alerting rule inside a PrometheusRule CRD by the group it lives in and its own alert name.

Dash0 has no per-alert server-side id — a CRD's alerting rules share the CRD's own identifier — so this pair is the only stable handle on one alert within a CRD. --since uses it to resolve a removed alert by its composed check-rule name.

func ExtractPrometheusAlertNames added in v1.17.0

func ExtractPrometheusAlertNames(data []byte) ([]PrometheusAlertName, error)

ExtractPrometheusAlertNames parses a PrometheusRule CRD document and returns the (group name, alert name) pair for every alerting rule, in document order. Recording rules are skipped.

Unlike a struct-typed unmarshal (sigs.k8s.io/yaml decoding into a *string field, as PrometheusRuleEndpoints and the rest of this file otherwise use), this reads each name's literal scalar value directly off the raw YAML node tree. sigs.k8s.io/yaml's YAML->JSON->struct path resolves an unquoted YAML 1.1/1.2 boolean literal (Y, N, yes, no, on, off, true, false, and case variants) to a real JSON boolean, then silently coerces that boolean into the destination string field as "true"/"false" instead of erroring — so an alert genuinely named e.g. "Y" would otherwise be corrupted to "true" everywhere its name is used (the composed check-rule name here, and --since's alert-tracking diff in internal/git, which calls this function via internal/git/snapshot.go instead of dash0-api-client-go/yaml's identically-named, differently-implemented ExtractPrometheusAlertNames for exactly this reason).

func (PrometheusAlertName) CheckRuleName added in v1.17.0

func (p PrometheusAlertName) CheckRuleName() string

CheckRuleName composes the check-rule name Dash0 gives an alerting rule converted from a PrometheusRule CRD: "<group name> - <alert name>", matching the Dash0 Kubernetes operator and the Terraform provider.

type Route added in v1.25.0

type Route[T any] struct {
	// Key is the id or origin the PUT targets.
	Key string
	// Create is true when nothing is stored at Key, so the write sends the
	// origin. An update never sends it, so a stored origin stays as created.
	Create bool
	// Stored is the stored asset; the zero value when Create is true.
	Stored T
}

Route is where a write goes.

func RouteDocument added in v1.25.0

func RouteDocument[T any](ctx context.Context, identity Identity, get func(context.Context, string) (T, error), storedOrigin func(T) string) (Route[T], error)

RouteDocument is the one routing rule for every kind: id first, then origin, never POST, so a repeated apply cannot create a second asset. A failed id read leaves Key empty, because the write has no target; a failed origin read keeps Key, because the origin is the target either way.

type SignalToMetricsRuleDatasetMismatchError added in v1.21.0

type SignalToMetricsRuleDatasetMismatchError struct {
	OriginOrID string
	Stored     string
	Target     string
}

SignalToMetricsRuleDatasetMismatchError reports a stored rule that belongs to another dataset than the one a write targets.

func (*SignalToMetricsRuleDatasetMismatchError) Error added in v1.21.0

type StillDeletedError added in v1.19.0

type StillDeletedError struct {
	DisplayKind string
	Name        string
	ID          string
}

StillDeletedError reports an asset that the API saved but still marks as deleted.

func (*StillDeletedError) Error added in v1.19.0

func (e *StillDeletedError) Error() string

type UpdateKey added in v1.18.0

type UpdateKey struct {
	// Noun names the asset in error messages, lowercase and unabbreviated:
	// "dashboard", "spam filter", "time series aggregation".
	Noun string

	// Upsert is the document. Read it before a Strip*ServerFields call, which
	// can clear both labels.
	Upsert dash0api.AssetMetadata

	// OriginLabel is where the document sets its origin, when that is not
	// metadata.labels, as for check rules.
	OriginLabel string
}

UpdateKey is what every `update -f <file>` chooses its key from. One shared rule keeps update and apply addressing the same asset for every kind.

type UpdateOutcome added in v1.19.0

type UpdateOutcome struct {
	DisplayKind     string
	Name            string
	ID              string
	Before          any
	After           any
	BeforeDeletedAt *time.Time
	AfterDeletedAt  *time.Time
	DryRun          bool
}

UpdateOutcome is an asset before and after an `update` command, or before and after the update that `update --dry-run` previews.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL