statemachine

package
v0.0.0-...-230ac96 Latest Latest
Warning

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

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

Overview

Package statemachine implements the PostgreSQL proxy's Extended Query and transaction state machine per docs/agentmon-db-access-spec.md §14 and the design doc 2026-05-11-db-plan-05-pg-extended-tx-design.md §4.

Transition is a pure function: it consumes (state, frame, cache, rules, service) and returns (nextState, []Action). It mutates the CacheView directly (for Put/Delete/Clear) so the Action stream is I/O-only.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Transition

func Transition(
	s ConnState,
	frame Frame,
	cache CacheView,
	rules *policy.RuleSet,
	svc policy.ServiceID,
) (ConnState, []Action)

Transition is the pure state-transition function. It consumes the current ConnState, the next inbound frontend frame, a CacheView (mutated directly for Put/Delete/Clear), the active RuleSet, and the per-connection service identifier (used to scope policy evaluation). Returns the next state and the Action stream the dispatcher must execute.

Plan 05a implements: Sync, Parse, Bind, Describe, Execute, Flush, Close, Query (Simple Query), Terminate. Other frame kinds fall through to a default-deny path that produces SynthError(0A000) + Close. Plan 05b lifts FunctionCall and SQL prepared interception; Plan 05c lifts COPY frames and the approval-wait variant.

func TransitionWithParser

func TransitionWithParser(
	s ConnState,
	frame Frame,
	cache CacheView,
	rules *policy.RuleSet,
	svc policy.ServiceID,
	parser PolicyClassifier,
	opts classify_pg.Options,
) (ConnState, []Action)

TransitionWithParser is the parser-injected variant; tests use it when they need to assert against a non-postgres dialect or a mock classifier.

Types

type Action

type Action interface {
	// contains filtered or unexported methods
}

Action is a single thing the dispatcher must execute after a Transition. Concrete types are sealed via the private isAction() method so the dispatcher can rely on a closed sum type. Cache mutations are NOT Actions — Transition mutates the CacheView directly.

func DenyRoute

func DenyRoute(s ConnState, rule policy.StatementRule, msg, sqlstate string) []Action

DenyRoute returns the Action sequence implementing the spec §14.3 + §14.4 deny path. Callers pass the rendered deny message (already templated) and the SQLSTATE chosen by the rule kind.

  • Out-of-tx (lastUpstreamRFQ in {0, 'I'}) and not dirty: [SynthError, SynthReadyForQuery(I)]
  • Out-of-tx and dirty: [SynthError, DrainUntilRFQ]
  • In-tx (lastUpstreamRFQ in {'T', 'E'}), terminate (default or explicit): [SynthError(Severity=FATAL), Close]
  • In-tx, rollback_then_continue: [SynthError, InjectRollback, DrainUntilRFQ, SynthReadyForQuery(I)]

type ActionApproverWait

type ActionApproverWait struct {
	Timeout time.Duration
	Stmt    effects.ClassifiedStatement
	Rule    policy.StatementRule
}

ActionApproverWait instructs the dispatcher to invoke the configured Approver and wait up to Timeout before either forwarding or routing a deny.

type ActionClose

type ActionClose struct{}

ActionClose tears down both client and upstream connections. After this the dispatcher returns from the per-connection driver.

type ActionDrainUntilRFQ

type ActionDrainUntilRFQ struct{}

ActionDrainUntilRFQ reads upstream frames and forwards them to the client (subject to the per-row demux for counters in upstreamread.go) until an upstream ReadyForQuery is observed. Updates LastUpstreamRFQ on the way.

type ActionForward

type ActionForward struct{}

ActionForward emits the original frontend frame to upstream unchanged. The dispatcher reads pc.lastFrame and forwards via upstream framer.

type ActionInjectRollback

type ActionInjectRollback struct{}

ActionInjectRollback sends a synthetic "ROLLBACK" Simple Query upstream as if from the client. Used by the rollback_then_continue deny mode. The dispatcher composes a 'Q' frame with body "ROLLBACK".

type ActionSuppress

type ActionSuppress struct{}

ActionSuppress instructs the dispatcher to drop the current frontend frame without forwarding upstream and without responding to client. Used inside an absorbing-deny window.

type ActionSynthBindComplete

type ActionSynthBindComplete struct{}

ActionSynthBindComplete mirrors ActionSynthParseComplete for Bind.

type ActionSynthError

type ActionSynthError struct {
	SQLState string
	Message  string
	// Severity overrides "ERROR" when non-empty. The terminate-in-tx path
	// uses Severity="FATAL" so libpq clients surface the SQLSTATE alongside
	// the EOF that follows.
	Severity string
}

ActionSynthError synthesizes ErrorResponse to the client. The dispatcher chooses Severity based on the deny path (ERROR for resumable; FATAL for terminate). SQLState is the §10 / §13 / §14 SQLSTATE.

type ActionSynthParseComplete

type ActionSynthParseComplete struct{}

ActionSynthParseComplete synthesizes a ParseComplete frame to the client (used in absorbing-window denies to satisfy clients expecting one frame per Parse). Plan 05a does not emit this in standard paths; reserved for future tightening.

type ActionSynthReadyForQuery

type ActionSynthReadyForQuery struct {
	Status byte // 'I' | 'T' | 'E'
}

ActionSynthReadyForQuery synthesizes ReadyForQuery to the client.

type ActionTrackUpstreamRFQ

type ActionTrackUpstreamRFQ struct {
	Status byte
}

ActionTrackUpstreamRFQ updates ConnState.LastUpstreamRFQ and Phase to match Status. Emitted when the dispatcher observes an upstream 'Z' frame during normal forwarding.

type BindFrame

type BindFrame struct {
	Portal    string
	Statement string // prepared-statement name
}

func (*BindFrame) Kind

func (*BindFrame) Kind() FrameKind

type CacheOp

type CacheOp struct {
	Method string // "Get" | "Put" | "Delete" | "Clear"
	Key    string
	Value  CacheValue
	Hit    bool // only meaningful for "Get"
}

CacheOp records one observation against a FakeCacheView.

type CacheValue

type CacheValue struct {
	Verb                     string // RawVerb from effects.ClassifiedStatement
	GroupID                  uint8  // primary effect group_id; used for re-evaluate at Execute
	OpaqueID                 string // optional: spine-test correlation
	CatalogRefreshSearchPath bool
	CatalogRefreshSnapshot   bool
}

CacheValue is the value stored in a CacheView. The transition logic reads/writes this type; production wraps it around a preparedcache.Entry at the dispatcher boundary so the state-machine package stays decoupled from the cache implementation.

type CacheView

type CacheView interface {
	Get(name string) (CacheValue, bool)
	Put(name string, v CacheValue)
	Delete(name string)
	Clear()
}

CacheView is the subset of preparedcache.Cache that Transition consumes. Implementations must be safe for concurrent reads with one writer per connection (the per-conn goroutine).

type CloseFrame

type CloseFrame struct {
	ObjectType byte // 'S' (statement) or 'P' (portal)
	Name       string
}

func (*CloseFrame) Kind

func (*CloseFrame) Kind() FrameKind

type ConnState

type ConnState struct {
	// Phase reflects the per-connection lifecycle position.
	Phase Phase

	// LastUpstreamRFQ is the most recent ReadyForQuery status byte observed
	// from upstream. Zero (0x00) means pre-auth. Otherwise 'I', 'T', or 'E'.
	LastUpstreamRFQ byte

	// Absorbing is true when a previous Parse/Bind/Execute denied within
	// the current Sync window. Subsequent non-Sync frames are suppressed
	// until the next Sync resolves the window.
	Absorbing bool

	// UpstreamDirtySinceSync is true once any Parse/Bind/Execute/Describe/
	// Close has been forwarded upstream in the current Sync window. Reset
	// on the next observed upstream RFQ.
	UpstreamDirtySinceSync bool

	// TxStartedAt is the local timestamp the proxy observed transitioning
	// into 'T' (in-tx) state on a fresh transaction. Cleared when the next
	// observed upstream RFQ is 'I'. Used by the DBEvent tx_context schema.
	TxStartedAt time.Time
}

ConnState is the per-connection state the Extended Query and transaction state machine carries. All fields are exported so the dispatcher can read them after Transition returns; mutations happen only through Transition (or through the dispatcher updating LastUpstreamRFQ + Phase when an upstream 'Z' arrives during forwarding).

type CopyDataFrame

type CopyDataFrame struct {
	Body []byte // borrowed; do not retain past the Transition call
}

func (*CopyDataFrame) Kind

func (*CopyDataFrame) Kind() FrameKind

type CopyDoneFrame

type CopyDoneFrame struct{}

func (*CopyDoneFrame) Kind

func (*CopyDoneFrame) Kind() FrameKind

type CopyFailFrame

type CopyFailFrame struct {
	Message string
}

func (*CopyFailFrame) Kind

func (*CopyFailFrame) Kind() FrameKind

type DescribeFrame

type DescribeFrame struct {
	ObjectType byte // 'S' (statement) or 'P' (portal)
	Name       string
}

func (*DescribeFrame) Kind

func (*DescribeFrame) Kind() FrameKind

type ExecuteFrame

type ExecuteFrame struct {
	Portal string
}

func (*ExecuteFrame) Kind

func (*ExecuteFrame) Kind() FrameKind

type FakeCacheView

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

FakeCacheView records every operation and is safe for unit tests. NOT for production.

func NewFakeCacheView

func NewFakeCacheView() *FakeCacheView

NewFakeCacheView returns an empty fake.

func (*FakeCacheView) Clear

func (f *FakeCacheView) Clear()

func (*FakeCacheView) Delete

func (f *FakeCacheView) Delete(name string)

func (*FakeCacheView) Get

func (f *FakeCacheView) Get(name string) (CacheValue, bool)

func (*FakeCacheView) Put

func (f *FakeCacheView) Put(name string, v CacheValue)

func (*FakeCacheView) Recorded

func (f *FakeCacheView) Recorded() []CacheOp

Recorded returns the operation history.

type FlushFrame

type FlushFrame struct{}

func (*FlushFrame) Kind

func (*FlushFrame) Kind() FrameKind

type Frame

type Frame interface {
	Kind() FrameKind
}

Frame is a thin protocol-level view of one PostgreSQL frontend message. The dispatcher constructs concrete adapters from pgproto3.FrontendMessage before calling Transition. The state machine does not depend on pgproto3.

type FrameKind

type FrameKind uint8

FrameKind enumerates the per-frame kinds Transition dispatches on.

const (
	FrameKindQuery FrameKind = iota
	FrameKindParse
	FrameKindBind
	FrameKindDescribe
	FrameKindExecute
	FrameKindSync
	FrameKindFlush
	FrameKindClose
	FrameKindTerminate
	FrameKindFunctionCall // Plan 05b live; Plan 05a falls through to default-deny
	FrameKindCopyData
	FrameKindCopyDone
	FrameKindCopyFail
)

type FunctionCallFrame

type FunctionCallFrame struct {
	FunctionOID uint32
}

func (*FunctionCallFrame) Kind

func (*FunctionCallFrame) Kind() FrameKind

type ParseFrame

type ParseFrame struct {
	Name string // empty string is unnamed prepared statement
	SQL  string
}

func (*ParseFrame) Kind

func (*ParseFrame) Kind() FrameKind

type Phase

type Phase uint8

Phase enumerates the per-connection lifecycle phases. The state machine tracks both Phase (for human-readable invariants) and LastUpstreamRFQ (the on-wire 'Z' status byte) because the two convey slightly different information — Phase encodes COPY-in/COPY-out which RFQ cannot represent.

const (
	PhasePreAuth Phase = iota
	PhaseIdle
	PhaseInQuery
	PhaseInTx
	PhaseInTxError
	PhaseInCopyIn
	PhaseInCopyOut
)

func (Phase) String

func (p Phase) String() string

type PolicyClassifier

type PolicyClassifier interface {
	Classify(sql string, sess classify_pg.SessionState, opts classify_pg.Options) ([]effects.ClassifiedStatement, error)
}

PolicyClassifier is the minimal classifier surface Transition needs at the state-machine boundary. The dispatcher injects a real classify_pg.Parser via TransitionWithParser; transition_test.go uses the live parser via classify_pg.New(classify_pg.DialectPostgres).

type QueryFrame

type QueryFrame struct {
	SQL string
}

func (*QueryFrame) Kind

func (*QueryFrame) Kind() FrameKind

type SyncFrame

type SyncFrame struct{}

func (*SyncFrame) Kind

func (*SyncFrame) Kind() FrameKind

type TerminateFrame

type TerminateFrame struct{}

func (*TerminateFrame) Kind

func (*TerminateFrame) Kind() FrameKind

Jump to

Keyboard shortcuts

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