runstream

package
v0.8.6 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	ApplyAction string = "apply"
	PlanAction  string = "plan"
)
View Source
const (
	// AutoMergeMetadataKvBucket stores aggregate state for each VCS change and commit.
	AutoMergeMetadataKvBucket = "AUTO_MERGE_METADATA"
)
View Source
const (
	// RunCompletionKvBucket records the runs already counted in
	// tfbuddy_tfc_runs_finished.
	RunCompletionKvBucket = "RUN_COMPLETIONS"
)
View Source
const RunEventsStreamName = "RUN_EVENTS"
View Source
const RunMetadataKvBucket = "RUN_METADATA"
View Source
const RunPollingKvName = "POLLING_TASKS"
View Source
const RunPollingStreamNameV0 = "RUN_POLLING"
View Source
const TaskPollingDelayDefault = 10 * time.Second
View Source
const TaskPollingDelayMinimum = 1 * time.Second
View Source
const (
	// WorkspaceDispatchKvBucket records which workspaces each trigger has
	// already dispatched.
	WorkspaceDispatchKvBucket = "WORKSPACE_DISPATCHES"
)

Variables

View Source
var ErrAutoMergeStateNotFound = errors.New("auto-merge state not found")
View Source
var FailedResponse = []byte("failed")
View Source
var SuccessDoneResponse = []byte("done")
View Source
var SuccessResponse = []byte("success")

Functions

func AutoMergeWorkspaceKey added in v0.7.0

func AutoMergeWorkspaceKey(organization, workspace string) string

func RecordRunCreated added in v0.8.6

func RecordRunCreated(provider, runType string)

RecordRunCreated counts a TFC run TFBuddy created. runType is the trigger's action, plan or apply.

Types

type AutoMergeRef added in v0.7.0

type AutoMergeRef struct {
	// VcsProvider, Project, MergeRequest, and CommitSHA locate aggregate state.
	VcsProvider  string
	Project      string
	MergeRequest int
	CommitSHA    string
	// Organization and Workspace select one workspace within the aggregate.
	Organization string
	Workspace    string
	// RunID identifies the TFC apply reporting an event.
	RunID string
	// Generation identifies the apply command that dispatched RunID.
	Generation string
	// Sequence rejects events from an older apply command.
	Sequence int64
}

AutoMergeRef identifies one workspace apply within an MR commit.

func AutoMergeRefForRun added in v0.7.0

func AutoMergeRefForRun(run RunMetadata) AutoMergeRef

type AutoMergeResult added in v0.7.0

type AutoMergeResult string
const (
	AutoMergeResultAutoMerged     AutoMergeResult = "auto_merged"
	AutoMergeResultManuallyMerged AutoMergeResult = "manually_merged"
	AutoMergeResultClosedUnmerged AutoMergeResult = "closed_unmerged"
)

type AutoMergeState added in v0.7.0

type AutoMergeState struct {
	// VcsProvider and Project identify the repository containing the change.
	VcsProvider string `json:"vcs_provider"`
	Project     string `json:"project"`
	// MergeRequest and CommitSHA pin this state to one immutable change revision.
	MergeRequest int    `json:"merge_request"`
	CommitSHA    string `json:"commit_sha"`
	// Eligible is true only when every affected workspace opted into auto-merge.
	Eligible bool `json:"eligible"`
	// Workspaces tracks the current apply state of every affected workspace.
	Workspaces map[string]*AutoMergeWorkspaceState `json:"workspaces"`
	// MergeClaimed atomically grants one worker permission to request the merge.
	MergeClaimed bool `json:"merge_claimed"`
	// MergeRequested records that the VCS accepted TFBuddy's merge request.
	MergeRequested bool `json:"merge_requested"`
	// Finalized prevents duplicate terminal VCS webhooks from recording a result twice.
	Finalized bool `json:"finalized"`
}

AutoMergeState coordinates all workspaces affected by one MR commit.

func NewAutoMergeState added in v0.7.0

func NewAutoMergeState(vcsProvider, project string, mr int, commitSHA string, eligible bool, workspaces []string) *AutoMergeState

type AutoMergeWorkspaceState added in v0.7.0

type AutoMergeWorkspaceState struct {
	// Generation identifies the apply command that dispatched this workspace run.
	Generation string `json:"generation,omitempty"`
	// Sequence orders apply commands so older deliveries cannot replace newer state.
	Sequence int64 `json:"sequence,omitempty"`
	// RunID identifies the current non-targeted TFC apply for this generation.
	RunID string `json:"run_id,omitempty"`
	// Applied records whether RunID completed successfully.
	Applied bool `json:"applied"`
}

AutoMergeWorkspaceState tracks the newest apply run for one workspace. Applied is only true when that exact run completed successfully without targets.

type RunEvent

type RunEvent interface {
	GetRunID() string
	GetContext() context.Context
	SetContext(context.Context)
	SetCarrier(map[string]string)
	GetNewStatus() string
	GetMetadata() RunMetadata
	SetMetadata(RunMetadata)
}

type RunMetadata

type RunMetadata interface {
	GetAction() string
	GetMRInternalID() int
	GetRootNoteID() int64
	GetMRProjectNameWithNamespace() string
	GetDiscussionID() string
	GetRunID() string
	GetWorkspace() string
	GetCommitSHA() string
	GetOrganization() string
	GetVcsProvider() string
	GetAutoMerge() bool
	GetAutoMergeGeneration() string
	GetAutoMergeSequence() int64
}

type RunPollingTask

type RunPollingTask interface {
	Schedule(ctx context.Context) error
	Reschedule(ctx context.Context) error
	Completed() error
	GetRunID() string
	GetContext() context.Context
	SetCarrier(map[string]string)
	GetLastStatus() string
	SetLastStatus(string)
	GetRunMetaData() RunMetadata
}

type Stream

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

func (*Stream) AddRunMeta

func (s *Stream) AddRunMeta(rmd RunMetadata) error

func (*Stream) BeginAutoMergeApply added in v0.7.0

func (s *Stream) BeginAutoMergeApply(ref AutoMergeRef, workspaces []string) error

BeginAutoMergeApply atomically marks every workspace selected by one apply command pending before any per-workspace run is dispatched.

func (*Stream) ClaimWorkspaceDispatch added in v0.8.4

func (s *Stream) ClaimWorkspaceDispatch(claim WorkspaceDispatchClaim) (bool, error)

ClaimWorkspaceDispatch records that claim's trigger is dispatching its workspace. It returns false when that trigger already claimed the workspace, so a redelivered trigger skips the workspaces it already ran.

func (*Stream) EnsureAutoMergeState added in v0.7.0

func (s *Stream) EnsureAutoMergeState(state *AutoMergeState) error

func (*Stream) FinalizeAutoMerge added in v0.7.0

func (s *Stream) FinalizeAutoMerge(ref AutoMergeRef, merged bool) (AutoMergeResult, bool, error)

func (*Stream) GetRunMeta

func (s *Stream) GetRunMeta(runID string) (RunMetadata, error)

func (*Stream) HealthCheck

func (s *Stream) HealthCheck() error

func (*Stream) NewTFRunPollingTask

func (s *Stream) NewTFRunPollingTask(meta RunMetadata, delay time.Duration) RunPollingTask

func (*Stream) PublishTFRunEvent

func (s *Stream) PublishTFRunEvent(ctx context.Context, re RunEvent) error

func (*Stream) RecordAutoMergeRequested added in v0.7.0

func (s *Stream) RecordAutoMergeRequested(ref AutoMergeRef) error

func (*Stream) RecordAutoMergeSuccess added in v0.7.0

func (s *Stream) RecordAutoMergeSuccess(ref AutoMergeRef) (bool, error)

RecordAutoMergeSuccess marks the current run successful and atomically claims the merge when every expected workspace is applied. Duplicate or stale run events are harmless and cannot claim the merge.

func (*Stream) RecordRunFinished added in v0.8.6

func (s *Stream) RecordRunFinished(provider string, re RunEvent)

RecordRunFinished counts re's run once its final status event has been handled. That means the handler ran to the end, not that every comment and commit status reached the merge request: those failures are logged.

Run events are deduplicated when they are published, but JetStream delivers the final event again when its ack is lost, for example while a NATS pod restarts. So the first worker to handle it records the run in the RUN_COMPLETIONS bucket, and a later delivery of the same run is not counted. If the record cannot be written the run is counted anyway, since a double count would also need the ack to be lost.

func (*Stream) RegisterAutoMergeRun added in v0.7.0

func (s *Stream) RegisterAutoMergeRun(ref AutoMergeRef) error

func (*Stream) ReleaseAutoMergeClaim added in v0.7.0

func (s *Stream) ReleaseAutoMergeClaim(ref AutoMergeRef) error

func (*Stream) SubscribeTFRunEvents

func (s *Stream) SubscribeTFRunEvents(vcsProvider string, cb func(run RunEvent) bool) (closer func(), err error)

SubscribeTFRunEvents hands vcsProvider's run events to cb, one at a time per replica. An event cb does not handle (cb returns false) is retried after a delay, a limited number of times.

func (*Stream) SubscribeTFRunPollingTasks

func (s *Stream) SubscribeTFRunPollingTasks(cb func(task RunPollingTask) bool) (closer func(), err error)

SubscribeTFRunPollingTasks hands polling tasks to cb, one at a time per replica. When cb fails to poll a run (it returns false), the task goes back to the dispatcher, which polls the run again after the usual delay.

type StreamClient

type StreamClient interface {
	HealthCheck() error
	PublishTFRunEvent(ctx context.Context, re RunEvent) error
	AddRunMeta(rmd RunMetadata) error
	GetRunMeta(runID string) (RunMetadata, error)
	EnsureAutoMergeState(state *AutoMergeState) error
	BeginAutoMergeApply(ref AutoMergeRef, workspaces []string) error
	RegisterAutoMergeRun(ref AutoMergeRef) error
	RecordAutoMergeSuccess(ref AutoMergeRef) (bool, error)
	ReleaseAutoMergeClaim(ref AutoMergeRef) error
	RecordAutoMergeRequested(ref AutoMergeRef) error
	FinalizeAutoMerge(ref AutoMergeRef, merged bool) (AutoMergeResult, bool, error)
	ClaimWorkspaceDispatch(claim WorkspaceDispatchClaim) (bool, error)
	RecordRunFinished(provider string, re RunEvent)
	NewTFRunPollingTask(meta RunMetadata, delay time.Duration) RunPollingTask
	SubscribeTFRunPollingTasks(cb func(task RunPollingTask) bool) (closer func(), err error)
	SubscribeTFRunEvents(queue string, cb func(run RunEvent) bool) (closer func(), err error)
}

func NewStream

func NewStream(js nats.JetStreamContext, jsc jetstream.JetStream, dedupWindow time.Duration) StreamClient

NewStream wires up the runstream JetStream client. dedupWindow is the JetStream Duplicates window applied to the RUN_EVENTS stream so that Nats-Msg-Id-based dedup actually fires server-side. Operators tune it via TFBUDDY_JETSTREAM_DEDUP_WINDOW. jsc, created from the same connection, reads the run event and polling queues.

type TFRunEvent

type TFRunEvent struct {
	RunID        string
	Organization string
	Workspace    string
	NewStatus    string
	Metadata     RunMetadata
	Carrier      propagation.MapCarrier `json:"Carrier"`
	// contains filtered or unexported fields
}

TFRunEvent represents a status change on a run

func (*TFRunEvent) GetContext added in v0.2.1

func (e *TFRunEvent) GetContext() context.Context

func (*TFRunEvent) GetMetadata

func (e *TFRunEvent) GetMetadata() RunMetadata

func (*TFRunEvent) GetNewStatus

func (e *TFRunEvent) GetNewStatus() string

func (*TFRunEvent) GetRunID

func (e *TFRunEvent) GetRunID() string

func (*TFRunEvent) SetCarrier added in v0.2.1

func (e *TFRunEvent) SetCarrier(carrier map[string]string)

func (*TFRunEvent) SetContext added in v0.2.1

func (e *TFRunEvent) SetContext(ctx context.Context)

func (*TFRunEvent) SetMetadata

func (e *TFRunEvent) SetMetadata(meta RunMetadata)

type TFRunMetadata

type TFRunMetadata struct {
	// RunID is the ID generated by TFC for the run
	RunID string
	// Organization is the TFC organization name
	Organization string
	// Workspace is the TFC workspace name
	Workspace string

	// Source is the trigger source of the TFC run
	// options include:
	// "merge_request" - for runs started via MR push or comment
	// "merge" - for runs started when MR is merged (apply after merge repos) (NOT IMPLEMENTED)
	// "slack" - for runs started via ChatOps (NOT IMPLEMENTED)
	Source string

	// Action is the triggered action (i.e. plan / apply)
	Action string

	// The git Commit SHA for which the run has been triggered
	CommitSHA string

	// MergeRequestProjectNameWithNamespace is the fully qualified Gitlab project name (e.g. /group/subgroup/project)
	MergeRequestProjectNameWithNamespace string

	// MergeRequestIID is the Gitlab Merge Request IID for which the Run has been triggered
	MergeRequestIID int

	// DiscussionID is the MergeRequest discussion thread where status updates should be written (optional)
	DiscussionID string
	// RootNoteID is the top level note of the discussion thread. It will be updated with progress info.
	RootNoteID int64

	VcsProvider string

	AutoMerge           bool
	AutoMergeGeneration string
	AutoMergeSequence   int64
}

func (*TFRunMetadata) GetAction

func (r *TFRunMetadata) GetAction() string

func (*TFRunMetadata) GetAutoMerge added in v0.3.0

func (r *TFRunMetadata) GetAutoMerge() bool

func (*TFRunMetadata) GetAutoMergeGeneration added in v0.7.0

func (r *TFRunMetadata) GetAutoMergeGeneration() string

func (*TFRunMetadata) GetAutoMergeSequence added in v0.7.0

func (r *TFRunMetadata) GetAutoMergeSequence() int64

func (*TFRunMetadata) GetCommitSHA

func (r *TFRunMetadata) GetCommitSHA() string

func (*TFRunMetadata) GetDiscussionID

func (r *TFRunMetadata) GetDiscussionID() string

func (*TFRunMetadata) GetMRInternalID

func (r *TFRunMetadata) GetMRInternalID() int

func (*TFRunMetadata) GetMRProjectNameWithNamespace

func (r *TFRunMetadata) GetMRProjectNameWithNamespace() string

func (*TFRunMetadata) GetOrganization

func (r *TFRunMetadata) GetOrganization() string

func (*TFRunMetadata) GetRootNoteID

func (r *TFRunMetadata) GetRootNoteID() int64

func (*TFRunMetadata) GetRunID

func (r *TFRunMetadata) GetRunID() string

func (*TFRunMetadata) GetVcsProvider

func (r *TFRunMetadata) GetVcsProvider() string

func (*TFRunMetadata) GetWorkspace

func (r *TFRunMetadata) GetWorkspace() string

type TFRunPollingTask

type TFRunPollingTask struct {
	RunMetadata

	LastStatus string
	NextPoll   time.Time
	Processing bool
	LastUpdate time.Time

	// Revision is the NATS KV entry revision
	Revision uint64

	Carrier propagation.MapCarrier `json:"Carrier"`
	// contains filtered or unexported fields
}

func (*TFRunPollingTask) Completed

func (task *TFRunPollingTask) Completed() error

func (*TFRunPollingTask) GetContext added in v0.2.1

func (task *TFRunPollingTask) GetContext() context.Context

func (*TFRunPollingTask) GetLastStatus

func (task *TFRunPollingTask) GetLastStatus() string

func (*TFRunPollingTask) GetRunID

func (task *TFRunPollingTask) GetRunID() string

func (*TFRunPollingTask) GetRunMetaData

func (task *TFRunPollingTask) GetRunMetaData() RunMetadata

func (*TFRunPollingTask) Reschedule

func (task *TFRunPollingTask) Reschedule(ctx context.Context) error

func (*TFRunPollingTask) Schedule

func (task *TFRunPollingTask) Schedule(ctx context.Context) error

func (*TFRunPollingTask) SetCarrier added in v0.2.1

func (task *TFRunPollingTask) SetCarrier(carrier map[string]string)

func (*TFRunPollingTask) SetLastStatus

func (task *TFRunPollingTask) SetLastStatus(status string)

type WorkspaceDispatchClaim added in v0.8.4

type WorkspaceDispatchClaim struct {
	VcsProvider  string `json:"vcsProvider"`
	Project      string `json:"project"`
	MergeRequest int    `json:"mergeRequest"`
	// CommitSHA is recorded for debugging but is not part of the claim's
	// identity: the GitHub comment path reads it from the live pull request
	// on every delivery, so a redelivery after the target branch moved would
	// otherwise claim the workspace a second time. Trigger already tells new
	// triggers apart.
	CommitSHA    string `json:"commitSHA"`
	Action       string `json:"action"`
	Trigger      string `json:"trigger"`
	Organization string `json:"organization"`
	Workspace    string `json:"workspace"`
}

WorkspaceDispatchClaim names one workspace run requested by one trigger: a webhook delivery, or a merge request comment.

Jump to

Keyboard shortcuts

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