events

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package events holds the use cases of the events context: ingest of the events SDKs post. The SDK edge in the delivery context authenticates the key and speaks HTTP, then hands the batch here.

Index

Constants

View Source
const (
	DefaultAliasLinksLimit     = 5_000_000
	DefaultFirstExposuresLimit = 10_000_000
)

The limits ingest applies when the configuration gives none.

View Source
const ClaimPurgeBatch = 10000

ClaimPurgeBatch is the most event IDs purged in one statement, so that a purge far behind never holds locks long enough to stall ingest.

View Source
const ConflictSampleSize = 100

ConflictSampleSize is how many conflicting units the conflicts of an experiment list: enough to see a pattern, few enough to read.

View Source
const DefaultEventsRetention = 30 * 24 * time.Hour

DefaultEventsRetention is how long raw events are kept when the configuration does not say: the window within which an event's time, shifted by the batch's clock skew, is accepted.

View Source
const RollupBatchSize = 20000

RollupBatchSize is the most raw rows a rollup applies in one unit of work, so that a stream far behind catches up in transactions short enough not to hold the horizon back themselves.

Variables

View Source
var ErrNotFound = errors.New("events: not found")

ErrNotFound is what a store answers for an entity it does not hold.

Functions

This section is empty.

Types

type AliasRollupStore

type AliasRollupStore interface {
	CursorStore

	// AliasesAfter returns the next aliases past from, at most limit, of
	// transactions that had all ended, and the cursor of the last; from
	// when there is none.
	AliasesAfter(ctx context.Context, from events.Cursor, limit int) ([]events.AliasRow, events.Cursor, error)
	AddEventCounts(ctx context.Context, counts map[events.EventDay]int64) error
	// contains filtered or unexported methods
}

AliasRollupStore is what the alias rollup reads and writes.

type BatchResult

type BatchResult struct {
	// Accepted counts the events stored, by type.
	Accepted map[events.EventType]int
	// Duplicates counts the events received before, in this batch or an
	// earlier one.
	Duplicates int
	// DroppedRows counts the summary rows naming a flag the project does
	// not have, or a variation the flag lacks.
	DroppedRows int
	// Rejected are the events refused, by index.
	Rejected []EventRejection
}

BatchResult is how a batch was judged.

func (BatchResult) AcceptedTotal

func (r BatchResult) AcceptedTotal() int

AcceptedTotal is how many events were stored, whatever their type.

func (BatchResult) DroppedRowsTold added in v0.5.0

func (r BatchResult) DroppedRowsTold(k delivery.SDKKeyKind) int

DroppedRowsTold is the count of dropped rows a key of kind k is told: the true count for a server key, 0 for a client key. Told to a client key, the count would say whether a flag key it guessed belongs to the project, an archived flag included. DroppedRows stays the true count for the metrics.

type CursorStore

type CursorStore interface {
	// LockStream holds stream for the unit of work, waiting for the
	// replica holding it, so one replica at a time moves it.
	LockStream(ctx context.Context, stream events.Stream) error
	// Cursor returns where stream has read to, the zero cursor before it
	// first moved.
	Cursor(ctx context.Context, stream events.Stream) (events.Cursor, error)
	// MoveCursor moves stream's cursor to to, as of at.
	MoveCursor(ctx context.Context, stream events.Stream, to events.Cursor, at time.Time) error
	// OldestUnread returns when the first row past stream's cursor was
	// received, whether or not the horizon still holds it back; ok is
	// false when every committed row was read.
	OldestUnread(ctx context.Context, stream events.Stream) (at time.Time, ok bool, err error)
}

CursorStore keeps where each rollup stream has read to.

type EvaluationQuery

type EvaluationQuery struct {
	Project     workspace.ProjectID
	Flag        string
	Environment string
	From, To    *time.Time
}

EvaluationQuery names a flag's evaluations in one environment over a range of UTC days, nil leaving an end to its default.

type EvaluationReader

type EvaluationReader interface {
	// FlagOf returns project's flag keyed key, archived or not, or
	// ErrNotFound.
	FlagOf(ctx context.Context, project workspace.ProjectID, key string) (flags.FlagID, error)
	// EnvironmentOf returns project's environment keyed key, or
	// ErrNotFound.
	EnvironmentOf(ctx context.Context, project workspace.ProjectID, key string) (workspace.EnvironmentID, error)
	// EvaluationCounts returns the flag's evaluations in environment per
	// day from first to last, both included, by day, source, variation and
	// reason.
	EvaluationCounts(ctx context.Context, flag flags.FlagID, environment workspace.EnvironmentID,
		first, last time.Time) ([]events.FlagEvaluationDay, error)
}

EvaluationReader reads what the summary rollup made of a flag's evaluations.

type EventBatch

type EventBatch struct {
	SDK delivery.SDKIdentity
	// SentAt is when the SDK says it sent the batch, by its own clock.
	SentAt time.Time
	Events []json.RawMessage
}

EventBatch is a batch of events as an SDK posts it, each event as sent.

type EventRejection

type EventRejection struct {
	// Index is the event's position in the batch.
	Index int
	// EventID is the event_id as sent, "" when it was not a string.
	EventID string
	events.Rejection
}

EventRejection is one event of a batch refused.

type EventStore

type EventStore interface {
	// DeclaredUnitTypes returns which of keys project declares as unit
	// types.
	DeclaredUnitTypes(ctx context.Context, project workspace.ProjectID, keys []string) (map[string]bool, error)
	// FlagVariations returns the variation keys of each flag of project
	// that keys name, archived ones included, by flag key; a key naming no
	// flag is absent.
	FlagVariations(ctx context.Context, project workspace.ProjectID, keys []string) (map[string][]string, error)
	// Experiments returns the experiments of project keyed by keys, of any
	// status, by key; a key naming none is absent. It holds each experiment
	// against deletion until the unit of work ends, so that the count of a
	// refusal written meanwhile finds its experiment.
	Experiments(ctx context.Context, project workspace.ProjectID, keys []string) (map[string]events.ExperimentFacts, error)
	// ClaimEvents records the IDs of events of typ of project as received
	// at at, and returns those not received before: the events to store.
	ClaimEvents(ctx context.Context, project workspace.ProjectID, typ events.EventType, ids []delivery.EventID,
		at time.Time) (map[delivery.EventID]bool, error)
	// AliasLinkCount returns how many alias links environment holds.
	AliasLinkCount(ctx context.Context, environment workspace.EnvironmentID) (int64, error)
	// LinkedPairs returns which of pairs are already linked in environment.
	LinkedPairs(ctx context.Context, environment workspace.EnvironmentID, pairs []events.AliasPair) (map[events.AliasPair]bool, error)
	// UnitsFirstExposed returns how many units of each of experiments the
	// rollup has counted a first exposure of in environment.
	UnitsFirstExposed(ctx context.Context, environment workspace.EnvironmentID, experiments []experiments.ExperimentID,
	) (map[experiments.ExperimentID]int64, error)
	// ExposedUnits returns which of units have a first exposure stored.
	ExposedUnits(ctx context.Context, units []events.UnitKey) (map[events.UnitKey]bool, error)
	SaveSummaries(ctx context.Context, rows []delivery.SummaryRecord) error
	SaveAliases(ctx context.Context, aliases []events.AliasRecord) error
	// LinkAliases links the pair of each alias in its environment, once per
	// pair, keeping the alias that occurred earliest.
	LinkAliases(ctx context.Context, aliases []events.AliasRecord) error
	SaveExposures(ctx context.Context, exposures []events.ExposureRecord) error
	// CountRejections adds counts to those of exposures refused in
	// environment, as of at.
	CountRejections(ctx context.Context, environment workspace.EnvironmentID, counts []events.RejectionCount, at time.Time) error
	// EnsureEventPartitions makes sure the raw event tables can take rows
	// received at at, outside any unit of work ctx carries.
	EnsureEventPartitions(ctx context.Context, at time.Time) error
}

EventStore stores the events SDKs post.

type ExperimentExposures

type ExperimentExposures struct {
	Variations []events.VariationExposures
	// ConflictTotal is how many exposures named another variation than
	// their unit's first exposure; ConflictUnits how many units had one.
	ConflictTotal, ConflictUnits int64
	// Rejections count the exposures refused, by reason.
	Rejections map[events.RejectionCode]int64
	// AsOf is when the exposure rollup last moved; nil before it first
	// did.
	AsOf *time.Time
}

ExperimentExposures are what an experiment's exposures in one environment came to.

type ExposureQuery

type ExposureQuery struct {
	Project     workspace.ProjectID
	Experiment  string
	Environment string
}

ExposureQuery names an experiment's exposures in one environment.

type ExposureReader

type ExposureReader interface {
	// ExperimentOf returns the identifier and weights of project's
	// experiment keyed key, of any status, or ErrNotFound.
	ExperimentOf(ctx context.Context, project workspace.ProjectID, key string) (experiments.ExperimentID, []experiments.Weight, error)
	// EnvironmentOf returns project's environment keyed key, or
	// ErrNotFound.
	EnvironmentOf(ctx context.Context, project workspace.ProjectID, key string) (workspace.EnvironmentID, error)
	// ExposureCounts returns the experiment's counts in environment summed
	// over every day, by variation.
	ExposureCounts(ctx context.Context, environment workspace.EnvironmentID, experiment experiments.ExperimentID) (map[string]events.ExposureDayCounts, error)
	// ExposureTimeline returns the experiment's counts in environment per
	// day and variation, from the day of from to the day of to, nil
	// leaving that end open.
	ExposureTimeline(ctx context.Context, environment workspace.EnvironmentID, experiment experiments.ExperimentID,
		from, to *time.Time) ([]events.ExposureTimelineDay, error)
	// ConflictTotals returns how many exposures conflicted with their
	// unit's first exposure, and in how many units.
	ConflictTotals(ctx context.Context, environment workspace.EnvironmentID, experiment experiments.ExperimentID) (total, units int64, err error)
	// Conflicts returns up to limit conflicting units, the most recent
	// conflict first.
	Conflicts(ctx context.Context, environment workspace.EnvironmentID, experiment experiments.ExperimentID, limit int) ([]events.Conflict, error)
	// RejectionCountsOf returns how many exposures of the experiment were
	// refused in environment, by reason.
	RejectionCountsOf(ctx context.Context, experiment experiments.ExperimentID, environment workspace.EnvironmentID) (map[events.RejectionCode]int64, error)
	// CursorMovedAt returns when stream's cursor last moved; ok is false
	// before it first did.
	CursorMovedAt(ctx context.Context, stream events.Stream) (at time.Time, ok bool, err error)
}

ExposureReader reads what the exposure rollup made of an experiment's exposures.

type ExposureRollupStore

type ExposureRollupStore interface {
	CursorStore
	// ExposuresAfter returns the next exposures past from, at most limit,
	// of transactions that had all ended, and the cursor of the last;
	// from when there is none.
	ExposuresAfter(ctx context.Context, from events.Cursor, limit int) ([]events.ExposureRow, events.Cursor, error)

	// FirstExposures returns the first exposures stored of units.
	FirstExposures(ctx context.Context, units []events.UnitKey) (map[events.UnitKey]events.FirstExposure, error)
	SaveFirstExposures(ctx context.Context, records map[events.UnitKey]events.FirstExposure) error
	AddExposureCounts(ctx context.Context, counts map[events.ExposureDay]events.ExposureDayCounts) error
	AddEventCounts(ctx context.Context, counts map[events.EventDay]int64) error
	LastEvaluatedStore
	// contains filtered or unexported methods
}

ExposureRollupStore is what the exposure rollup reads and writes.

type GetConflicts

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

GetConflicts reads a sample of an experiment's conflicting units in one environment.

func NewGetConflicts

func NewGetConflicts(snapshots Snapshotter, store ExposureReader) *GetConflicts

NewGetConflicts returns the handler.

func (*GetConflicts) Handle

Handle returns up to ConflictSampleSize conflicting units of q, the most recent conflict first.

type GetEventVolume

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

GetEventVolume reads the events a project received per day and the gaps retention left over the same days.

func NewGetEventVolume

func NewGetEventVolume(snapshots Snapshotter, store VolumeReader, c clock.Clock) *GetEventVolume

NewGetEventVolume returns the handler.

func (*GetEventVolume) Handle

Handle returns the volume q names; a range of days that cannot be read is an *events.RangeError. The gaps are the instance's: a stream reads every project's rows, so what a drop took is not told apart by project.

type GetExperimentExposures

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

GetExperimentExposures reads an experiment's exposures in one environment.

func NewGetExperimentExposures

func NewGetExperimentExposures(snapshots Snapshotter, store ExposureReader) *GetExperimentExposures

NewGetExperimentExposures returns the handler.

func (*GetExperimentExposures) Handle

Handle returns the exposures of q, or not_found for an experiment or an environment the project does not have. Everything is read in one snapshot, so the counts and the conflicts agree.

type GetExposureTimeline

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

GetExposureTimeline reads an experiment's exposure counts per day in one environment.

func NewGetExposureTimeline

func NewGetExposureTimeline(snapshots Snapshotter, store ExposureReader) *GetExposureTimeline

NewGetExposureTimeline returns the handler.

func (*GetExposureTimeline) Handle

Handle returns the counts of q per UTC day and variation, by day then variation key, from the day of from to the day of to, both included; nil leaves that end open.

type GetFlagEvaluations

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

GetFlagEvaluations reads a flag's evaluations per day in one environment.

func NewGetFlagEvaluations

func NewGetFlagEvaluations(snapshots Snapshotter, store EvaluationReader, c clock.Clock) *GetFlagEvaluations

NewGetFlagEvaluations returns the handler.

func (*GetFlagEvaluations) Handle

Handle returns the evaluations q names, or not_found for a flag or an environment the project does not have; a range of days that cannot be read is an *events.RangeError.

type IngestEvents

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

IngestEvents stores the events an SDK posts in a batch.

func NewIngestEvents

func NewIngestEvents(tx Transactor, store EventStore, c clock.Clock, retention time.Duration, limits Limits) *IngestEvents

NewIngestEvents returns the handler, accepting events within retention of the clock's time.

func (*IngestEvents) Handle

Handle judges each event of b on its own and stores those accepted in one unit of work, so that once it returns every accepted event is durable and the SDK may drop the batch. An event whose ID was received before, in this batch or for as long as event IDs are kept (see claimRetention), is a duplicate and stored once. A summary row naming a flag the project does not have is dropped: nobody could read it, and a client key is told none were. An exposure is checked against the experiment it names; a server key is told the check it failed, and a client key unknown_experiment for every refusal, so that it learns nothing of the project's experiments.

When the SDK's clock and the server's differ by more than a minute, every time in the batch is shifted by the difference before it is judged, so a device with a wrong clock keeps its events.

type LastEvaluatedStore

type LastEvaluatedStore interface {
	// MoveLastEvaluated moves each flag's last evaluation in each
	// environment to the time given, unless it holds a later one.
	MoveLastEvaluated(ctx context.Context, last map[events.FlagEnvironment]time.Time) error
}

LastEvaluatedStore keeps when SDKs last evaluated each flag.

type Limits added in v0.5.0

type Limits struct {
	// AliasLinks is the most alias links an environment keeps.
	AliasLinks int
	// FirstExposures is the most units whose first exposure an experiment
	// keeps in an environment.
	FirstExposures int
}

Limits bound what ingest keeps for good. A limit of 0 is the default.

type RetentionReport

type RetentionReport struct {
	// Dropped is how many partitions of each raw table were dropped.
	Dropped map[events.EventType]int
	// Gaps are the gaps the drops recorded.
	Gaps []events.Gap
}

RetentionReport is what a round of retention did.

type RetentionStore

type RetentionStore interface {
	CursorStore
	// CreateEventPartitions creates the partitions of every raw event
	// table for the UTC day of from and the ahead days after it, those
	// missing, outside any unit of work ctx carries.
	CreateEventPartitions(ctx context.Context, from time.Time, ahead int) error
	// LockRetention holds the retention of typ's raw table for the unit of
	// work, waiting for the replica holding it, so one replica at a time
	// drops its partitions.
	LockRetention(ctx context.Context, typ events.EventType) error
	// Partitions returns the UTC days of the partitions of typ's raw table.
	Partitions(ctx context.Context, typ events.EventType) ([]time.Time, error)
	// LockPartitions takes typ's raw table and the partitions of days
	// exclusively until the unit of work ends, giving up after a short
	// timeout rather than stalling ingest behind a transaction still
	// writing them.
	LockPartitions(ctx context.Context, typ events.EventType, days []time.Time) error
	// Lost returns what the partitions of days of typ's raw table hold past
	// from.
	Lost(ctx context.Context, typ events.EventType, days []time.Time, from events.Cursor) (events.Lost, error)
	// FirstStoredAfter returns the first row of typ's raw table past from
	// outside the partitions of days, nil when there is none.
	FirstStoredAfter(ctx context.Context, typ events.EventType, days []time.Time, from events.Cursor) (*events.Cursor, error)
	// Horizon returns the ID of the oldest transaction still running: every
	// row of a smaller one has committed or never will.
	Horizon(ctx context.Context) (uint64, error)
	SaveGap(ctx context.Context, gap events.Gap) error
	// DropPartitions drops the partitions of days of typ's raw table.
	DropPartitions(ctx context.Context, typ events.EventType, days []time.Time) error
	// PurgeClaims deletes at most limit event IDs of typ received before
	// before and returns how many it deleted.
	PurgeClaims(ctx context.Context, typ events.EventType, before time.Time, limit int) (int, error)
}

RetentionStore is what retention reads, drops and purges.

type RollUpAliases

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

RollUpAliases counts the stored aliases into daily event counts. Their links are written as they arrive; counting them as they arrive too would make every batch of a project's aliases wait on the one row of its day.

func NewRollUpAliases

func NewRollUpAliases(tx Transactor, store AliasRollupStore, c clock.Clock) *RollUpAliases

NewRollUpAliases returns the handler.

func (*RollUpAliases) Handle

func (h *RollUpAliases) Handle(ctx context.Context) (int, error)

Handle counts every alias committed below the horizon that the stream has not read yet, in batches, each in one unit of work with the move of the cursor past it. It returns how many aliases it read.

func (*RollUpAliases) Lag

Lag returns how long the oldest alias the rollup has not read yet has been waiting, 0 when it has read every committed one.

type RollUpExposures

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

RollUpExposures rolls the stored exposures up into first exposures, daily exposure counts and daily event counts.

func NewRollUpExposures

func NewRollUpExposures(tx Transactor, store ExposureRollupStore, c clock.Clock) *RollUpExposures

NewRollUpExposures returns the handler.

func (*RollUpExposures) Handle

func (h *RollUpExposures) Handle(ctx context.Context) (int, error)

Handle applies every exposure committed below the horizon that the stream has not read yet, in batches, each in one unit of work with the move of the cursor past it: a batch is applied once, never half. It returns how many rows it read.

func (*RollUpExposures) Lag

Lag returns how long the oldest exposure the rollup has not read yet has been waiting, 0 when it has read every committed one.

type RollUpSummaries

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

RollUpSummaries rolls the stored evaluation summaries up into evaluations per day, when each flag was last evaluated, and daily event counts.

func NewRollUpSummaries

func NewRollUpSummaries(tx Transactor, store SummaryRollupStore, c clock.Clock) *RollUpSummaries

NewRollUpSummaries returns the handler.

func (*RollUpSummaries) Handle

func (h *RollUpSummaries) Handle(ctx context.Context) (int, error)

Handle applies every summary row committed below the horizon that the stream has not read yet, in batches, each in one unit of work with the move of the cursor past it. It returns how many rows it read.

func (*RollUpSummaries) Lag

Lag returns how long the oldest summary row the rollup has not read yet has been waiting, 0 when it has read every committed one.

type RollupTargets

type RollupTargets struct {
	Projects     []workspace.ProjectID
	Environments []workspace.EnvironmentID
	Flags        []flags.FlagID
	Experiments  []experiments.ExperimentID
}

RollupTargets are what a batch of raw rows names and the rollup's aggregates reference.

type RunRetention

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

RunRetention keeps the raw event tables bounded: it creates their partitions ahead of time, drops the partitions past retention whole, and purges the event IDs a year (or the window and a day, if longer) old.

func NewRunRetention

func NewRunRetention(tx Transactor, store RetentionStore, sinks SinkRetention, c clock.Clock, ids *id.Source,
	retention time.Duration, ahead int,
) *RunRetention

NewRunRetention returns the handler, keeping raw events for retention and creating partitions ahead days after today. sinks records the rows a drop takes from the sinks' streams.

func (*RunRetention) Handle

func (h *RunRetention) Handle(ctx context.Context) (RetentionReport, error)

Handle runs one round. Each raw table is dropped in a unit of work of its own, so a table a long transaction still writes leaves the others to go; the round goes on past a table that failed and returns every error.

type SinkRetention added in v0.4.0

type SinkRetention interface {
	// LockStreams holds every sink stream reading typ's raw table until the
	// unit of work ends, those of disabled and stopped sinks included.
	LockStreams(ctx context.Context, typ events.EventType) error
	// RecordGaps records, for every sink stream reading typ, the rows the
	// drop of days takes that it had not delivered, moving its cursor past
	// them but never past horizon, and returns the gaps.
	RecordGaps(ctx context.Context, typ events.EventType, days []time.Time, horizon uint64, now time.Time) ([]events.Gap, error)
}

SinkRetention is the sinks' side of a drop, called inside the drop's unit of work: the sinks context implements it, the events context does not know what it records.

type Snapshotter

type Snapshotter interface {
	Snapshot(ctx context.Context, fn func(ctx context.Context) error) error
}

Snapshotter runs a query of several statements on one consistent view.

type SummaryRollupStore

type SummaryRollupStore interface {
	CursorStore

	LastEvaluatedStore
	// SummariesAfter returns the next summary rows past from, at most
	// limit, of transactions that had all ended, and the cursor of the
	// last; from when there is none.
	SummariesAfter(ctx context.Context, from events.Cursor, limit int) ([]events.SummaryRow, events.Cursor, error)
	// AddEvaluationCounts adds counts to the evaluations per day, each
	// saturating.
	AddEvaluationCounts(ctx context.Context, counts map[events.EvaluationDay]int64) error
	AddEventCounts(ctx context.Context, counts map[events.EventDay]int64) error
	// contains filtered or unexported methods
}

SummaryRollupStore is what the summary rollup reads and writes.

type Transactor

type Transactor interface {
	Within(ctx context.Context, fn func(ctx context.Context) error) error
}

Transactor runs a unit of work.

type VolumeQuery

type VolumeQuery struct {
	Project  workspace.ProjectID
	From, To *time.Time
}

VolumeQuery names a project's event volume over a range of UTC days, nil leaving an end to its default.

type VolumeReader

type VolumeReader interface {
	// EventCounts returns the events project received on each UTC day from
	// first to last, both included, by type.
	EventCounts(ctx context.Context, project workspace.ProjectID, first, last time.Time) (map[events.EventDay]int64, error)
	// Gaps returns the gaps whose rows were received from from to to, in
	// the order they were received.
	Gaps(ctx context.Context, from, to time.Time) ([]events.Gap, error)
}

VolumeReader reads what the rollups counted of the events received and the gaps retention left.

Jump to

Keyboard shortcuts

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