asset

package
v1.23.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 24 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 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.

View Source
var ErrTimeSeriesAggregationMissingOrigin = fmt.Errorf(
	"Dash0TimeSeriesAggregation requires %s: the Dash0 API rejects a time series aggregation without an origin, and the origin is the key `apply` upserts by",
	OriginLabel,
)

ErrTimeSeriesAggregationMissingOrigin is returned when a time series aggregation document carries no dash0.com/origin label.

Origin is mandatory for this kind, so there is no create path to fall back to. Failing during validation stops a multi-document apply from writing half its documents first.

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"}

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 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 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 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 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 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 the dashboard upserts by another key, or "". It names the same dashboard: ImportDashboard falls back to it, and apply --since deletes at 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 ImportDashboard upserts by, or "".

func DashboardKeys added in v1.22.0

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

DashboardKeys lets the shared key rules resolve a dashboard's identifiers in the order apply upserts by: the dash0.com/origin label, then metadata.dash0Extensions.id, then the dash0.com/id label. The client's own GetID reads the dash0.com/id label first, which would put the server UUID ahead of the id the user chose. Read it before StripDashboardServerFields, which clears the dash0.com/id label.

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 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 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 ExtractAlias added in v1.22.0

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

ExtractAlias returns a second identifier that names the same asset as the one ExtractIdentifier returns, or "". Only dashboards have one: see DashboardAlias.

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: dash0.com/origin, then metadata.dash0Extensions.id, then dash0.com/id
  • CheckRule: top-level id
  • Dash0NotificationChannel, Dash0TimeSeriesAggregation: dash0.com/origin
  • Dash0Dataset: spec.slug, then dash0.com/id
  • SLO, Dash0SpamFilter, Dash0Team, Dash0Skill, Dash0GenerativeAiEvaluation, Dash0SignalToMetrics, Dash0Sampling: dash0.com/origin, then dash0.com/id
  • everything else (PersesDashboard, PrometheusRule, SyntheticCheck, View, Dash0AwsMetricScrapeConfig): dash0.com/id

Each kind reads only the field its Import helper actually upserts by. A fallback onto some other field would return an identifier no live asset can match, which --since would then "delete" to a 404 and report as already deleted -- returning "" instead routes the document to the NoIdentifier hard-fail. Only SLOs, teams, spam filters, Agent0 skills, evals, signal-to-metrics rules, and sampling rules genuinely accept either field.

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: eval ids are server-assigned, so an id-only document that took ImportGenerativeAiEvaluation's POST fallback left the live eval at an id the document never learned.

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 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 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 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 ParseCheckRules added in v1.15.4

func ParseCheckRules(data []byte) ([]*dash0api.PrometheusAlertRule, error)

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

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 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 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 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 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 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. SLO ids are server-assigned, so an id-only document that was first applied against an organization not holding that id took ImportSLO's POST fallback, and the live SLO is sitting at a fresh id the document never learned. Deleting by the id recorded in git history then either 404s (hard-failing without --force) or counts as already-deleted (with --force), leaving the real SLO orphaned either way. There is no local, API-free way to recover the live id from git history; origin is the only identifier the server never reassigns.

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 StripSamplingRuleServerFields, 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 document first applied to an organization without that id took ImportSamplingRule's POST fallback, and the live rule sits at an id the document never learned. Deleting by the id recorded in git history then 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 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. Rule ids are server-assigned, so an id-only document first applied to an organization without that id took ImportSignalToMetricsRule's POST fallback, and the live rule sits at an id the document never learned. Deleting by the id recorded in git history then 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 whose id was not found took ImportTeam's POST fallback, so the live team sits at a server-assigned id the document never learned.

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 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 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 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 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 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. 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 *dash0api.PrometheusAlertRule, dataset *string) (ImportPlan, error)

PlanCheckRule reads the stored check rule that ImportCheckRule would write. It returns any preflight error other than "not found".

func PlanCustomSkill added in v1.21.0

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

PlanCustomSkill reads the stored skill that ImportCustomSkill would write. dash0.com/origin upserts, while dash0.com/id only addresses an existing skill, so an unknown id is an error instead of a create.

func PlanDashboard added in v1.21.0

func PlanDashboard(ctx context.Context, apiClient dash0api.Client, dashboard *dash0api.DashboardDefinition, 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 reads the stored dataset that ImportDataset would write, keyed by its slug. Any preflight error other than "not found" is returned, because it decides between PUT and POST.

func PlanGenerativeAiEvaluation added in v1.21.0

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

PlanGenerativeAiEvaluation reads the stored eval that ImportGenerativeAiEvaluation would write. An empty Key means a POST: the document has no origin, and its id is unknown or missing.

func PlanNotificationChannel added in v1.21.0

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

PlanNotificationChannel reads the stored channel that ImportNotificationChannel would write, keyed by origin. It returns any preflight error other than "not found".

func PlanRecordingRule added in v1.21.0

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

PlanRecordingRule reads the stored recording rule that ImportRecordingRule would write, and carries its version onto rule. It returns any preflight error other than "not found".

func PlanSLO added in v1.21.0

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

PlanSLO picks the SLO's upsert key and reads the stored SLO that ImportSLO would write. Origin wins over id. On the id path a 404 leaves Key empty, so the write falls back to POST. Any other preflight error is returned: on the id path it decides the route, and on the origin path swallowing it would report a replace as a create.

func PlanSamplingRule added in v1.22.0

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

PlanSamplingRule reads the stored rule that ImportSamplingRule would write, and prepares rule as the request body. An empty Key means a POST: the document has no origin, and its id is unknown or missing.

Only a PUT to an 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. A POST must not carry one, because the server assigns ids.

Unlike signal-to-metrics rules, the GET honors the dataset: a rule stored in another dataset fails it with the cross-dataset 400, which is returned wrapped, so a preview fails the same way the write would.

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 reads the stored rule that ImportSignalToMetricsRule would write, and prepares rule as the request body. An empty Key means a POST: the document has no origin, and its id is unknown or missing.

Only a PUT to an 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. A POST must not carry one, because the server assigns ids.

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. Origin wins over id. It returns any preflight error other than "not found".

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. Origin wins over id. It returns any preflight error other than "not found".

func PlanSyntheticCheck added in v1.21.0

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

PlanSyntheticCheck reads the stored synthetic check that ImportSyntheticCheck would write. It returns any preflight error other than "not found".

func PlanTeam added in v1.21.0

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

PlanTeam picks the team's upsert key and reads the stored team that ImportTeam would write. Origin wins over id, unless the origin is not found and the id is, then the team is updated at the id. On the id path a 404 leaves Key empty, so the write falls back to POST. It returns any preflight error other than "not found".

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 PlanTimeSeriesAggregation added in v1.21.0

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

PlanTimeSeriesAggregation reads the stored aggregation that ImportTimeSeriesAggregation would write, keyed by its mandatory origin.

Any preflight error other than "not found" is returned, because whether the aggregation exists is then unknown. The PUT would fail the same way, so stopping here only avoids a write against unknown state and keeps Action honest. 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 reads the stored view that ImportView would write. It returns any preflight error other than "not found".

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. The server ignores all of it except dash0.com/origin, and the CLI does not claim ownership by sending an origin. The preflight GET supplies the diff, and fails with a 404 for an unknown integration before anything is written.

func ImportCheckRule added in v1.1.0

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

ImportCheckRule creates or updates a check rule via the standard CRUD APIs. When the input has a user-defined ID, UPDATE is always used — PUT has create-or-replace semantics, so this is idempotent regardless of whether the rule already exists. When the input has no ID, CREATE is used and the server assigns an ID. A PUT to the ID of 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.

The origin is the upsert key: PUT by origin creates the skill when the origin is new. Without an origin, the dash0.com/id label can only address an existing skill, so a preflight GET turns an unknown id into a not-found error instead of a skill created with the id as its origin. Without either, POST creates the skill and the server assigns its id.

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, dataset *string) (ImportResult, error)

ImportDashboard creates or updates a dashboard via the standard CRUD APIs. When the input has a user-defined ID, UPDATE is always used — PUT has create-or-replace semantics, so this is idempotent regardless of whether the dashboard already exists. When the input has no ID, CREATE is used and the server assigns an ID. A PUT to the ID of 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, keyed by its slug (the dash0.com/id label).

A preflight GET decides the route: on hit, PUT updates in place; on a genuine 404, POST creates. PUT is not used for the miss path because the server upserts on PUT for most tokens, so POST is the explicit create. A mistyped slug therefore creates a new dataset here; only `datasets update` refuses an unknown slug. A dataset deleted within the last 30 days answers 404, so the POST restores it. Any other preflight error surfaces instead of creating a duplicate.

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 upserts a generative AI evaluation.

The upsert keys follow ImportSLO:

  • With a dash0.com/origin label, the eval is PUT to that origin. PUT to an unknown origin creates the eval, so the preflight GET only decides "created" vs "updated" and supplies the diff; any error other than a 404 is surfaced.
  • With only a dash0.com/id label, a preflight GET decides the route: PUT on hit, POST on a 404 (the id belongs to another organization), and any other error is surfaced so a transient failure never creates a duplicate.
  • With neither, POST creates the eval.

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. The strip keeps dash0.com/origin, so the body of an origin PUT carries the same origin as the path.

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 via the standard CRUD APIs. When the input has a user-defined ID (via dash0.com/origin label), UPDATE is always used — PUT has create-or-replace semantics, so this is idempotent regardless of whether the channel already exists. When the input has no origin, CREATE is used and the server assigns an ID.

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 via the standard CRUD APIs. When the input has a user-defined ID, UPDATE is always used — PUT has create-or-replace semantics, so this is idempotent regardless of whether the rule already exists. When the input has no ID, CREATE is used and the server assigns an ID. A PUT to the ID of 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 upserts an SLO via the standard CRUD APIs.

Upsert key selection mirrors ImportTeam (origin-first, preflight-driven):

  • If the input has a user-defined origin (label `dash0.com/origin`), a preflight GetSLO runs against that origin. On hit, PUT is used to update in place. On a genuine 404, PUT is still used — the API treats an origin PUT as create-or-replace, so the SLO materializes at the requested origin. Any other preflight error is surfaced.
  • If the input has a user-defined ID (label `dash0.com/id`) but no origin, a preflight GetSLO gates the choice: on hit, PUT (idempotent update); on a genuine 404, POST (create fresh with a server-assigned id). The miss path matters for cross-environment apply: a YAML downloaded from one Dash0 org carries an id that does not exist in a different org's backend, and PUT-to-unknown-id returns 404. Falling back to POST lets that YAML apply at all, but is a one-way create, not an idempotent one: the server assigns an id the document does not carry, so the next apply preflights the same unknown id, 404s again, and POSTs a second SLO. Only dash0.com/origin makes a repeated apply converge. Any other preflight error (5xx, auth failure, network blip) is surfaced rather than silently POSTed, so a transient hiccup never spawns a duplicate.
  • Otherwise, POST is used and the server assigns both id and origin.

PUT is create-or-replace, so upserting on either key is idempotent across repeated applies. A PUT to a deleted SLO brings it back, which is reported as ActionRestored. Both labels are captured before StripSLOServerFields runs, because that helper clears dash0.com/origin and dash0.com/id.

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 upserts a sampling rule.

The upsert keys follow ImportSignalToMetricsRule:

  • With a dash0.com/origin label, the rule is PUT to that origin, which creates or replaces it, with any dash0.com/id cleared from the body. The preflight GET only decides whether the result is reported as created or updated.
  • With only a dash0.com/id label, a preflight GET gates the route. On a hit the rule is PUT to that id. On a 404 it is POSTed with the id cleared, because the server rejects an id in a POST body, and a PUT to an id that another organization owns fails: ids are unique across organizations. The POST fallback lets a document exported from another organization apply, but it is not idempotent: the next apply preflights the same unknown id and POSTs again. Any other preflight error is surfaced.
  • With neither label, the rule is POSTed and the server assigns both.

Both labels are read before StripSamplingRuleServerFields, which clears the origin and the dataset label. 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 upserts a signal-to-metrics rule.

The API's PUT /api/signal-to-metrics/{originOrId} creates a rule when nothing matches the path value, and records that value as the new rule's origin. Upsert key selection follows from that, and mirrors ImportSLO:

  • With a dash0.com/origin label, the rule is PUT to that origin, which creates or replaces it, with any dash0.com/id cleared from the body. A preflight GET only decides whether the result is reported as created, updated, or restored.
  • With only a dash0.com/id label, a preflight GET gates the route. On a hit the rule is PUT to that id. On a 404 it is POSTed with the id cleared, because the server assigns ids and rejects one in a POST body. A PUT here would create a rule whose origin is the foreign id. The POST fallback lets a document exported from another organization apply, but it is not idempotent: the next apply preflights the same unknown id and POSTs again. Any other preflight error is surfaced instead of risking a duplicate.
  • With neither label, the rule is POSTed and the server assigns both.

Both labels are read before StripSignalToMetricsServerFields, which clears the origin. 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 via the standard CRUD APIs.

Upsert key selection — important quirk of the spam filter API:

  • If the input has a user-defined origin (label `dash0.com/origin`), the origin is used as the upsert key. PUT to /spam-filters/{origin} creates the asset on first call and updates it on subsequent calls. This is the only reliable path to idempotent `apply`.
  • If the input has a user-defined ID (label `dash0.com/id`) but no origin, the ID is used as the upsert key. The server only honors this when a record already exists at that ID — a PUT to a brand-new ID generates a fresh server-side ID, so user-defined-id-only flows do not get true idempotency.
  • Otherwise, CREATE is used and the server assigns an ID.

dash0.com/id is captured before StripSpamFilterServerFields runs because that helper clears the id label along with the server source label.

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. The v1alpha2 type carries spec.context (scalar) instead of spec.contexts (array); the rest of the lifecycle — upsert-key selection (origin first, ID fallback), existence check via GetSpamFilter, create-vs-update routing — is identical. See ImportSpamFilter for the rationale.

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 via the standard CRUD APIs. When the input has a user-defined ID, UPDATE is always used — PUT has create-or-replace semantics, so this is idempotent regardless of whether the check already exists. When the input has no ID, CREATE is used and the server assigns an ID. A PUT to the ID of 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 upserts a team via the CRD Teams API.

Upsert key selection:

  • If the input has a user-defined origin (label `dash0.com/origin`), a preflight GetTeam runs against that origin. On hit, PUT is used to update in place. On miss, PUT is still used — the API treats origin PUT as create-or-replace, so the team materializes at the requested origin.
  • If the input has a user-defined ID (label `dash0.com/id`) but no origin, a preflight GetTeam gates the choice: on hit, PUT (idempotent update); on miss, POST (create fresh with a server-assigned id). The miss path matters for cross-environment apply: a YAML downloaded from one Dash0 org carries an id that does not exist in a different org's backend, and PUT-to-unknown-id returns 404. Falling back to POST keeps `apply` idempotent — the identifier in the file becomes advisory when it cannot be honored.
  • Otherwise, POST is used and the server assigns both id and origin.

dash0.com/id is captured before StripTeamServerFields runs because that helper clears the id label along with the server source label.

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 ImportTimeSeriesAggregation added in v1.18.0

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

ImportTimeSeriesAggregation upserts a time series aggregation by its dash0.com/origin label.

Unlike the other Import helpers, this never sends a POST. Origin is mandatory on create and POST rejects an origin that already exists, so PUT /{origin} is the only idempotent path.

Read the origin before StripTimeSeriesAggregationServerFields, which clears the label. Reading it after would yield "" on every apply.

The body's dash0.com/id is left alone. The server ignores it and uses the path's origin, so an exported document reapplies safely.

A PUT to the origin of 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 via the standard CRUD APIs. When the input has a user-defined ID, UPDATE is always used — PUT has create-or-replace semantics, so this is idempotent regardless of whether the view already exists. When the input has no ID, CREATE is used and the server assigns an ID. A PUT to the ID of a deleted view brings it back, which is reported as ActionRestored.

type ListFlags

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

ListFlags holds flags specific to list commands

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 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
}

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