telemetry

package
v0.0.1-rc.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 31 Imported by: 1 module, 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

Overview

Package telemetry ingests high-volume observed activity, stores it in a raw sink, and maintains bounded graph rollups from it.

Pipeline position

OTLP/HTTP or provider-native receiver
  -> MappingRegistry (plugin-owned mappers, trusted plugin/source)
  -> Pipeline.Ingest (bounded queue, all or none, rejects when full)
  -> Sink.WriteBatch (JSONL or ClickHouse, retried until it succeeds)
  -> CommitFunc (RollupPublisher.Commit: Rollup.ObserveResolved,
     Rollup.Advance, publish rollup contributions through the
     host's RollupTarget)

Raw Event values never enter the graph. The graph receives only bounded Rollup output: per-minute telemetry series, NetworkPeerClass resources for unresolved peers, ProcessClass resources for process executions, and lease relationships whose predicate each kind declares in EventKinds (communicates-with for network kinds, executes for process executions).

Invariants

  • Every event has a stable event ID that survives producer retries and keeps its original observation timestamp, so the raw store can collapse duplicates.
  • Plugin and source provenance come from mapper registration, never from payload fields.
  • A batch reaches the commit callback only after the sink acknowledged it, so the graph never reflects telemetry that is not durably stored.
  • Nothing is dropped while the process runs: a request the queue cannot take whole is rejected for the producer to retry, a failing sink stalls the pipeline (and is logged with counts only), and a failing commit is retried with the batch kept, stopping the pipeline only when it persists.
  • Receivers acknowledge a request once its events are queued, before the sink write. Acknowledged events still in the queue are lost if the process crashes, or at shutdown if the drain deadline in Pipeline.Run expires first.
  • Properties and evidence IDs are bounded per event, and rollup series are bounded by retention and a series cap, so graph cardinality does not grow with traffic volume.
  • Properties and evidence may be sensitive. This package does not log them; keep it that way.

See https://agent-shield.dev/docs/architecture/telemetry/.

Index

Constants

View Source
const (
	DestinationIPClassPublic  = "public"
	DestinationIPClassPrivate = "private"
	DestinationIPClassSpecial = "special"
	DestinationIPClassUnknown = "unknown"
)

Destination IP classes exposed to detector rules as destination_ip_class.

View Source
const (
	EventKindNetworkFlow    = "network-flow"
	EventKindGatewayRequest = "gateway-request"
	EventKindActiveProbe    = "active-probe"
	EventKindProcessExec    = "process-exec"
)

Event kinds emitted by in-tree telemetry mappers.

View Source
const (
	RollupContributionName = "rollups"
	RollupCollection       = "telemetry/rollups"
)

Every (plugin, source) pair that produced rollups owns one contribution named RollupContributionName and marks RollupCollection ready after each publication.

Variables

View Source
var (
	ErrNoTelemetryMapper        = errors.New("no telemetry mapper matched the record")
	ErrAmbiguousTelemetryMapper = errors.New("multiple telemetry mappers matched the record")
)

Mapping registry errors. Both reject the record rather than guessing an owner.

View Source
var (
	ErrPipelineOverloaded = errors.New("telemetry queue cannot accept the request now")
	ErrPipelineClosed     = errors.New("telemetry pipeline is not accepting events")
	ErrRequestTooLarge    = errors.New("telemetry request exceeds queue capacity")
)

Ingest admission errors. Receivers map ErrPipelineOverloaded to a retryable "slow down" response (HTTP 429), ErrPipelineClosed to 503, and ErrRequestTooLarge to a non-retryable rejection.

View Source
var ErrSkipRecord = errors.New("telemetry record is not projected by its mapper")

ErrSkipRecord is returned by a Mapper's Map for a well-formed record it deliberately does not project, such as a provider alert type the mapper does not handle. The registry then returns no events and no error, so the record is neither ingested nor counted as rejected.

Functions

func ClassifyDestinationIP

func ClassifyDestinationIP(raw string) (string, error)

ClassifyDestinationIP classifies an IP address string. An unparsable value returns DestinationIPClassUnknown with an error.

func IngestWaiting

func IngestWaiting(ctx context.Context, ingestor EventIngestor, events ...Event) error

IngestWaiting submits events like Ingest but waits while the queue is full instead of returning ErrPipelineOverloaded. It is for in-process producers that read a stream and have no client to push back on; HTTP receivers return 429 instead. It returns when the events are accepted, on any other error, or when ctx ends.

func IsCommunication

func IsCommunication(kind string) bool

IsCommunication reports whether kind records subject-to-object communication.

func LeasePredicate

func LeasePredicate(kind string) graph.Predicate

LeasePredicate returns the leased relationship predicate for rollups of kind. Unregistered kinds retain the historical communicates-with lease.

func TooManyRequests

func TooManyRequests(writer http.ResponseWriter, message string)

TooManyRequests writes a 429 with a Retry-After hint. Receivers sharing an EventIngestor use it for ErrPipelineOverloaded and their own admission limits.

Types

type ClickHouseConfig

type ClickHouseConfig struct {
	Endpoint string
	Database string
	Table    string
	Username string
	Password string
	Client   *http.Client
}

ClickHouseConfig configures a ClickHouseSink. Password is sent as HTTP basic auth; use HTTPS when the endpoint is not local.

type ClickHouseSink

type ClickHouseSink struct {
	// contains filtered or unexported fields
}

ClickHouseSink inserts batches over the ClickHouse HTTP interface as gzip JSONEachRow. The target table is expected to be the ReplacingMergeTree from deploy/clickhouse/schema.sql, whose ordering key includes the observation date, plugin_id, source_id, and event_id, so events resent in later batches collapse on merge. Each insert carries a deterministic insert_deduplication_token, so a retried batch is not inserted, or counted by the minute rollup view, twice.

func NewClickHouseSink

func NewClickHouseSink(config ClickHouseConfig) (*ClickHouseSink, error)

NewClickHouseSink validates config. A nil Client gets a 30-second timeout.

func (*ClickHouseSink) WriteBatch

func (sink *ClickHouseSink) WriteBatch(ctx context.Context, events []Event) error

WriteBatch inserts events in one request. A non-2xx response returns an error including up to 4 KiB of the ClickHouse response body; that body is left out when the error is logged through log/slog.

type CommitFunc

type CommitFunc func(context.Context, []Event) error

CommitFunc projects a sink-acknowledged batch into graph state. It is called with a nil batch on lifecycle ticks so time-based rollup changes, such as lease expiry, are published while traffic is quiet.

An error means the batch was accepted but its projection is not yet published. Run retries by calling CommitFunc again with a nil batch, so a CommitFunc must keep a batch it failed to publish and publish it on the next call. Each call runs under PipelineConfig.CommitTimeout.

type DestinationIPClassDescription

type DestinationIPClassDescription struct {
	Class       string
	Description string
}

DestinationIPClassDescription pairs a destination IP class with its meaning.

func DestinationIPClasses

func DestinationIPClasses() []DestinationIPClassDescription

DestinationIPClasses is the closed vocabulary of destination_ip_class, in a fixed order. Detector validation and the rule-authoring schema read it, so a class added here becomes visible to rules and models.

type Event

type Event struct {
	EventID          string              `json:"eventId"`
	PluginID         string              `json:"pluginId,omitempty"`
	ObservedAt       time.Time           `json:"observedAt"`
	Kind             string              `json:"kind"`
	Subject          graph.IdentityClaim `json:"subject"`
	Object           graph.IdentityClaim `json:"object"`
	Operation        string              `json:"operation,omitempty"`
	Outcome          string              `json:"outcome,omitempty"`
	Coverage         string              `json:"coverage,omitempty"`
	Count            uint64              `json:"count,omitempty"`
	Properties       map[string]string   `json:"properties,omitempty"`
	RollupProperties map[string]string   `json:"-"`
	SourceID         string              `json:"sourceId"`
	EvidenceIDs      []string            `json:"evidenceIds,omitempty"`
}

Event is one normalized telemetry observation from Subject to Object.

EventID must be stable across producer retries, and ObservedAt must be the original observation time rather than receipt time; the ClickHouse raw table deduplicates on both. Count is the number of source observations the event represents; zero is normalized to one. Properties are stored raw. RollupProperties selects the subset of Properties that become rollup series dimensions; leave out high-cardinality values such as ephemeral ports. It is not serialized to the sink.

func ResolveGraphEndpoints

func ResolveGraphEndpoints(events []Event, snapshot graph.Snapshot) []Event

ResolveGraphEndpoints rewrites NetworkDestination endpoints of sink-committed events before rollup. A destination exposed by exactly one current resource (through an exposes relationship) resolves to that resource; a destination that is itself a materialized resource is kept; anything else collapses to a direction-aware NetworkPeerClass in the same realm. Ambiguous bindings are not guessed. Non-destination endpoints are returned unchanged. The exact address stays only in the raw sink, which keeps rollup identity bounded.

Resolution uses the current graph, so it reflects bindings at processing time, not at the event's observation time. It collapses unresolved destinations at once; RollupPublisher instead uses Rollup.ObserveResolved, which holds them for a grace period while inventory catches up.

type EventIngestor

type EventIngestor interface {
	Ingest(context.Context, ...Event) error
}

EventIngestor accepts normalized events. Pipeline implements it. Ingest must not drop events: it either accepts the whole request or returns an error, such as ErrPipelineOverloaded, and accepts none of it.

type EventKindDescription

type EventKindDescription struct {
	Kind               string
	Description        string
	Operation          string
	Outcome            string
	DestinationIPClass bool
	// Lease is the predicate of the leased relationship that rollups of this kind
	// project between subject and object; empty projects none. communicates-with
	// also exposes the object's network role to detection.
	Lease graph.Predicate
}

EventKindDescription documents an event kind's operation and outcome vocabulary. It feeds generated detector-rule documentation.

func EventKinds

func EventKinds() []EventKindDescription

EventKinds returns descriptions of every in-tree event kind.

type JSONLSink

type JSONLSink struct {
	// contains filtered or unexported fields
}

JSONLSink appends events as JSON lines to a local file, fsyncing each batch. It is meant for development: it does not deduplicate retried events and has no rotation. The file is created with mode 0600 because events may contain sensitive properties.

func OpenJSONLSink

func OpenJSONLSink(path string) (*JSONLSink, error)

OpenJSONLSink opens or creates path for appending, creating parent directories as needed.

func (*JSONLSink) Close

func (sink *JSONLSink) Close() error

Close closes the file. Later writes fail.

func (*JSONLSink) WriteBatch

func (sink *JSONLSink) WriteBatch(ctx context.Context, events []Event) error

WriteBatch appends events and syncs the file before returning.

type LogRecord

type LogRecord struct {
	Timestamp          time.Time
	ObservedTimestamp  time.Time
	SeverityNumber     int32
	SeverityText       string
	Body               any
	Attributes         map[string]any
	ResourceAttributes map[string]any
	ScopeName          string
	ScopeVersion       string
	TraceID            string
	SpanID             string
}

LogRecord is a provider-neutral view of one OTLP log record. Attribute values keep their OTLP types; see OTLPReceiver for the conversion.

func (LogRecord) Attribute

func (record LogRecord) Attribute(name string) (any, bool)

Attribute returns a log record attribute.

func (LogRecord) ResourceAttribute

func (record LogRecord) ResourceAttribute(name string) (any, bool)

ResourceAttribute returns an attribute of the record's OTLP resource.

type Mapper

type Mapper interface {
	Match(LogRecord) bool
	Map(context.Context, LogRecord) ([]Event, error)
}

Mapper translates log records from one telemetry source into events. Match must be cheap and side-effect free because it runs for every record against every registered mapper. Map should derive a stable event ID from the record (a producer-supplied ID or a digest of identifying content) so retries map to the same ID.

type MapperFuncs

type MapperFuncs struct {
	MatchFunc func(LogRecord) bool
	MapFunc   func(context.Context, LogRecord) ([]Event, error)
}

MapperFuncs adapts a pair of functions to Mapper. A nil MatchFunc never matches.

func (MapperFuncs) Map

func (mapper MapperFuncs) Map(ctx context.Context, record LogRecord) ([]Event, error)

Map calls MapFunc.

func (MapperFuncs) Match

func (mapper MapperFuncs) Match(record LogRecord) bool

Match calls MatchFunc.

type Mapping

type Mapping struct {
	PluginID string
	SourceID string
	Mapper   Mapper
}

Mapping binds a mapper to the trusted plugin and source that own its events.

type MappingError

type MappingError struct {
	PluginID string
	SourceID string
	Err      error
}

MappingError reports a record that matched one mapping but could not be mapped.

func (*MappingError) Error

func (err *MappingError) Error() string

Error implements error.

func (*MappingError) Unwrap

func (err *MappingError) Unwrap() error

Unwrap returns the mapper's error.

type MappingRegistry

type MappingRegistry struct {
	// contains filtered or unexported fields
}

MappingRegistry routes each log record to exactly one Mapping.

func NewMappingRegistry

func NewMappingRegistry(mappings ...Mapping) (*MappingRegistry, error)

NewMappingRegistry validates and copies mappings.

func (*MappingRegistry) Map

func (registry *MappingRegistry) Map(ctx context.Context, record LogRecord) ([]Event, error)

Map routes record to its single matching mapper and returns normalized events stamped with that mapping's plugin and source IDs. Events without an ObservedAt inherit the record timestamp, falling back to its observed timestamp. Any failure rejects the whole record. A record the mapper skips with ErrSkipRecord yields no events and no error.

type OTLPReceiver

type OTLPReceiver struct {
	// contains filtered or unexported fields
}

OTLPReceiver is an OTLP/HTTP logs endpoint (the handler for /v1/logs).

Request handling:

  1. Accept only POST with Content-Type application/x-protobuf or application/json, and Content-Encoding identity or gzip; other methods get 405, other media types 415, and other encodings 400. Beyond MaxConcurrentRequests in flight, a request gets 429 with Retry-After before its body is read.
  2. Read at most MaxRequestBytes of body and of decompressed payload; larger or undecodable requests get 400.
  3. Convert each log record to a provider-neutral LogRecord. OTLP values keep their types (string, bool, int64, float64, []byte, []any, map[string]any); resource attributes are shared by the records under them; trace and span IDs become lowercase hex.
  4. Route each record through the MappingRegistry. Exactly one mapper must match. The mapper, not this receiver, extracts the stable event ID and the original event timestamp from the record, so a collector retry of the same record produces the same event. When the mapper leaves ObservedAt unset, the record's time_unix_nano is used, then its observed_time_unix_nano; a record with neither is rejected. Plugin and source IDs are overwritten from mapper registration, so payloads cannot spoof provenance. A mapper may skip a record it deliberately does not project (ErrSkipRecord); a skipped record is neither ingested nor rejected.
  5. Records that match no mapper, match several, or fail mapping or validation are counted in OTLP partial_success.rejected_log_records and the rest of the request proceeds. The rejection message carries only a count, never record content. The receiver also logs one bounded warning per distinct rejection reason in the request, with the owning plugin and source, or the producer's service.name when no mapper matched.
  6. Ingest the accepted events, all or none. When the pipeline queue cannot take them all, the receiver returns 429 with Retry-After; when the pipeline is shutting down or the request was cancelled, 503. OTLP exporters retry both, and nothing from the request was queued. A request with more events than the whole queue gets 413.
  7. Respond 200 with an ExportLogsServiceResponse in the request's encoding. A 200 means the events are queued, not yet written to the sink; see the package documentation for when queued events can be lost.

The receiver has no authentication. Bind it to loopback or put it behind an authenticated proxy, and restrict which producers can set the attributes mappers match on. Record bodies and attributes may hold secrets; the receiver never logs them. Rejection logs carry only mapper error text, which mappers must keep free of payload values.

func NewOTLPReceiver

func NewOTLPReceiver(config OTLPReceiverConfig, registry *MappingRegistry, ingestor EventIngestor) (*OTLPReceiver, error)

NewOTLPReceiver returns a receiver that maps records through registry and passes events to ingestor.

func (*OTLPReceiver) ServeHTTP

func (receiver *OTLPReceiver) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP handles one OTLP logs export; see OTLPReceiver.

type OTLPReceiverConfig

type OTLPReceiverConfig struct {
	// MaxRequestBytes limits the request body and the decompressed payload
	// separately. Default 16 MiB.
	MaxRequestBytes int64
	// MaxConcurrentRequests limits requests handled at once; more get 429.
	// Default 8.
	MaxConcurrentRequests int
	// Logger receives rejected-record summaries; nil uses slog.Default().
	Logger *slog.Logger
}

OTLPReceiverConfig configures an OTLPReceiver. Zero fields take defaults.

type OwnedInput

type OwnedInput struct {
	PluginID string
	SourceID string
	Input    graph.Input
}

OwnedInput is the rollup graph input owned by one telemetry provider's plugin and source.

type Pipeline

type Pipeline struct {
	// contains filtered or unexported fields
}

Pipeline batches events from many producers into one sink and then one commit callback. Ingest is safe for concurrent use; Run must be called exactly once and owns all batching, so the sink and CommitFunc are never called concurrently.

func NewPipeline

func NewPipeline(config PipelineConfig, sink Sink, commit CommitFunc) (*Pipeline, error)

NewPipeline returns a pipeline writing to sink. commit may be nil when no graph projection is wanted.

func (*Pipeline) Ingest

func (pipeline *Pipeline) Ingest(ctx context.Context, events ...Event) error

Ingest validates events and enqueues them all or none. It never blocks on a full queue and never drops an event: when the queue cannot take the whole request it returns ErrPipelineOverloaded and enqueues nothing, which is the pipeline's explicit backpressure. Producers retry the whole request later, and stable event IDs keep that retry idempotent in the raw store. A request larger than the whole queue returns ErrRequestTooLarge. Once Run starts draining or has returned, Ingest returns ErrPipelineClosed, so no event is accepted that nothing will drain.

func (*Pipeline) Run

func (pipeline *Pipeline) Run(ctx context.Context) (err error)

Run drains the queue until ctx ends or a commit fails persistently.

Each flush writes the batch to the sink, retrying with exponential backoff until it succeeds or ctx ends, and only then passes it to CommitFunc. A batch is therefore never projected before it is durable, and a failing sink stalls the pipeline (and, once the queue is full, rejects producers) instead of dropping data. A failed CommitFunc is retried with the same backoff, each attempt under CommitTimeout; Run returns the error only after CommitRetryLimit of consecutive failures.

On cancellation Run stops admission and drains everything still queued in MaxBatch-sized flushes under a fresh 10-second deadline, since ctx is already done. Events still queued when that deadline expires are lost with the process. Admission also stops when Run returns for any reason. A panic inside Run is returned as an error with its stack.

type PipelineConfig

type PipelineConfig struct {
	// QueueCapacity bounds queued, not-yet-flushed events. Default 100,000.
	QueueCapacity int
	// MaxBatch flushes as soon as a batch reaches this size. Default 5,000.
	MaxBatch int
	// FlushInterval flushes a partial batch. Default 250ms.
	FlushInterval time.Duration
	// LifecycleInterval, when positive, calls CommitFunc on a timer even with
	// no traffic. Zero disables lifecycle ticks.
	LifecycleInterval time.Duration
	// RetryMinimum and RetryMaximum bound the exponential sink and commit
	// retry delay. Defaults 100ms and 10s.
	RetryMinimum time.Duration
	RetryMaximum time.Duration
	// CommitTimeout bounds one CommitFunc attempt, so a hung query cannot
	// stall the pipeline forever. Default 30s.
	CommitTimeout time.Duration
	// CommitRetryLimit is how long consecutive CommitFunc failures are
	// retried before Run gives up and returns the error. Default 5 minutes.
	CommitRetryLimit time.Duration
	// Logger receives sink and commit failure and recovery messages. Default
	// slog.Default().
	Logger *slog.Logger
}

PipelineConfig tunes a Pipeline. Zero values select the defaults noted.

type Rollup

type Rollup struct {
	// contains filtered or unexported fields
}

Rollup is the in-memory bounded projection of sink-committed telemetry into graph input. It owns three kinds of state:

  • series: per-window counts keyed by plugin, source, endpoints, kind, operation, outcome, coverage, and rollup properties;
  • edges: one communicates-with lease per (plugin, source, subject, object), derived from series;
  • classes: NetworkPeerClass resources referenced by live series.

Graph cardinality is bounded by Retention, MaxSeries, and the per-series evidence cap, not by traffic volume. Counts are not deduplicated by event ID, so a producer retry that re-enqueues events can inflate them; the raw sink is authoritative. Rollup is safe for concurrent use.

func NewRollup

func NewRollup(config RollupConfig) *Rollup

NewRollup returns an empty rollup with defaults applied.

func (*Rollup) Advance

func (rollup *Rollup) Advance(now time.Time) bool

Advance applies time-based changes at now: expiring series and leases, refreshing leases in their horizon, and dropping unused peer classes. It reports whether graph input changed, so a quiet lifecycle tick publishes only when something expired or was refreshed.

func (*Rollup) Input

func (rollup *Rollup) Input() graph.Input

Input returns the whole rollup as one graph input. Series without provider ownership are attributed to pluginID and sourceID. Output is sorted, so it is deterministic for a given state.

func (*Rollup) Inputs

func (rollup *Rollup) Inputs() []OwnedInput

Inputs returns the rollup split by owning provider plugin and source, sorted by owner, so each provider's rollups are published and retracted as that provider's own contribution.

func (*Rollup) ObserveBatch

func (rollup *Rollup) ObserveBatch(events []Event) (skipped int)

ObserveBatch folds a sink-committed batch into the rollup. Call it only after the sink acknowledged the batch. Endpoints should already be resolved with ResolveGraphEndpoints. Series whose endpoints are not yet materialized are kept: the host filters them out at publication and they appear once inventory catches up, within Retention. That retained, bounded series set is the retry path for unresolved endpoints.

Events dated more than MaxClockSkew past the rollup clock are not rolled up and are counted in the result; they remain in the raw sink. Expiry runs from the newest event time, capped at the rollup clock.

func (*Rollup) ObserveResolved

func (rollup *Rollup) ObserveResolved(events []Event, snapshot graph.Snapshot, now time.Time) (changed bool, skipped int)

ObserveResolved resolves endpoints against snapshot and folds events into the rollup at now; it is what RollupPublisher uses. Unlike ResolveGraphEndpoints, a network destination without a unique binding keeps its exact address for UnresolvedGrace (within the held-series bound). Every call first re-resolves the held series: one whose address gained a binding moves to the bound resource, and one past its grace collapses to its peer class. It reports whether that re-resolution changed any series, and how many events were skipped as future-dated.

func (*Rollup) Restore

func (rollup *Rollup) Restore(snapshot graph.Snapshot) error

Restore rebuilds rollup state from the canonical graph after a restart, before new events are accepted. Restoring the published edge leases with their exact expiry matters: without them, the first post-restart publication would omit still-live edges and retract them. Leases without a surviving telemetry series get a LeaseOnly placeholder series.

Historical rollups owned by the old telemetry/runtime host fallback are discarded rather than restored under a synthetic provider identity.

type RollupConfig

type RollupConfig struct {
	// Window is the series bucket width. Default 1 minute.
	Window time.Duration
	// Retention drops series whose last observation is older than this
	// relative to the newest event or lifecycle tick, and is the lease length
	// of communicates-with edges. Default 24h.
	Retention time.Duration
	// EdgeRefreshBefore is the refresh horizon: a published edge lease is
	// renewed only once it is within this long of expiring. Default and
	// fallback for out-of-range values: Retention/4.
	EdgeRefreshBefore time.Duration
	// MaxSeries caps retained series; the oldest is evicted on overflow.
	// Default 100,000.
	MaxSeries int
	// MaxClockSkew is how far past the rollup clock an event may be dated.
	// Later events stay in the raw sink but are not rolled up, so one
	// future-dated record cannot expire every series. Default 5 minutes.
	MaxClockSkew time.Duration
	// UnresolvedGrace is how long a network destination with no unique
	// exposes binding keeps its exact address in the rollup, waiting for
	// inventory, before it collapses to a peer class. Default 5 minutes.
	UnresolvedGrace time.Duration
	// Now is the rollup clock. Default time.Now.
	Now func() time.Time
}

RollupConfig bounds a Rollup. Zero values select the defaults noted.

type RollupPublisher

type RollupPublisher struct {
	// contains filtered or unexported fields
}

RollupPublisher projects sink-committed telemetry into per-provider rollup contributions. Its Commit method is the pipeline's CommitFunc.

Each (plugin, source) that has ever produced rollups in this process is republished on every commit that changed something, with generations advancing from the durable generation read on first use. A pair whose series have all expired is published with empty input so its stale assertions retract. Publication is in (plugin, source) order.

A RollupPublisher is not safe for concurrent use; Pipeline never calls its CommitFunc concurrently.

func NewRollupPublisher

func NewRollupPublisher(config RollupPublisherConfig) (*RollupPublisher, error)

NewRollupPublisher validates config.

func (*RollupPublisher) Commit

func (publisher *RollupPublisher) Commit(ctx context.Context, events []Event) error

Commit observes events, advances rollup lifecycle, and republishes every owner's rollup contribution. It publishes nothing when events is empty and nothing expired, resolved, or is still unpublished.

Commit follows the CommitFunc retry contract: after an error, the batch is kept (observed, or queued if the graph could not be loaded) and the next call, even with nil events, publishes it. Republishing replaces each owner's whole contribution, so a retry is idempotent. After a failed publication the owner's durable generation is re-read, because the failed write may have committed.

type RollupPublisherConfig

type RollupPublisherConfig struct {
	Rollup *Rollup
	// Snapshot returns the current graph. It resolves event endpoints and
	// decides which rollup assertions are published.
	Snapshot func(context.Context) (graph.Snapshot, error)
	Target   RollupTarget
	// PublishInterval bounds graph publication frequency independently of raw
	// sink flushing. Zero publishes on every commit.
	PublishInterval time.Duration
	// Now is the clock for observation, expiry, and the unresolved-address
	// grace. Defaults to time.Now.
	Now func() time.Time
	// Logger receives counts of future-dated events left out of the rollup.
	// Default slog.Default().
	Logger *slog.Logger
}

RollupPublisherConfig configures a RollupPublisher.

type RollupTarget

type RollupTarget interface {
	// ContributionGeneration returns the highest durable contribution
	// generation for (plugin, source).
	ContributionGeneration(ctx context.Context, pluginID, sourceID string) (uint64, error)
	// PublishRollup replaces the (plugin, source) rollup contribution with
	// input at generation and marks RollupCollection ready at generation.
	PublishRollup(ctx context.Context, pluginID, sourceID string, generation uint64, input graph.Input, observedAt time.Time) error
}

RollupTarget persists rollup contributions. The host implements it over the discovery runtime, which this package cannot import.

type Sink

type Sink interface {
	WriteBatch(context.Context, []Event) error
}

Sink durably stores raw events. WriteBatch must be all-or-nothing from the caller's view: on error the pipeline retries the whole batch, so a sink must tolerate rewriting events it partially stored. It is never called concurrently by Pipeline.

Jump to

Keyboard shortcuts

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