Documentation
¶
Overview ¶
Package plug is where kit's opt-in subsystems plug in: the HTTP engine, the frontends' file server and the process sampler of the runtime graph (framework/kit/server), the Studio — the tool's variables, its routes and kit's sentences in the languages after English (framework/kit/studio) —, the stores and the databases (framework/kit/store), the queues (framework/kit/queue), the workflows (framework/kit/workflow), the mailers (framework/kit/mail), the jobs (framework/kit/jobs). kit reads what they registered through the hooks declared here, and imports none of the SDK packages behind them: a product that does not import a subsystem neither links nor initialises its packages.
It is also the contract between kit's core and the subsystems ADR 0179 takes out of it, as database/sql/driver is between database/sql and a driver: the store subsystem's engine over documents, its siblings, kit's scope on a database and its migrations (Stores), which framework/kit/store sets; the refusals an engine says in kit's terms (Refusal); what kit's transactions offer an engine that takes part in them (Transaction); the queue subsystem's brokers and their consumer (Queues), which framework/kit/queue sets; the workflow subsystem's engine and the ports it runs on (Workflows), which framework/kit/workflow sets; the mail subsystem's outbox and transports (Mail), which framework/kit/mail sets; the jobs subsystem's schedules and scheduler (Jobs), which framework/kit/jobs sets; kit's catalogues in the languages after English (Words), and the Studio's routes and the tool's variables (Studio, ADR 0180 step 1), which framework/kit/studio sets, the routes reading the running app through a StudioHost kit gives.
The package imports the standard library and the framework's model only, so that kit and every subsystem can import it.
Index ¶
- Constants
- Variables
- func Refuse(kind Refusal, err error) error
- func Refused(err error, kind Refusal) bool
- type Broker
- type Checker
- type Clock
- type ConsumeConfig
- type Database
- type DatabaseConfig
- type DeadLetterValue
- type DeliveryValue
- type DocumentSink
- type DocumentSource
- type DocumentValue
- type Documents
- type EnterHookSpec
- type EntrySource
- type EntryValue
- type Executor
- type Folder
- type HTTPConfig
- type HTTPServer
- type HTTPState
- type IndexSpec
- type JobDriverConfig
- type JobEntryValue
- type JobResultValue
- type JobScheduleFunc
- type JobScheduler
- type JobSchedulerConfig
- type Keyser
- type LiveMessageValue
- type MailAttemptValue
- type MailCaptureSource
- type MailDriverConfig
- type MailEvent
- type MailEventValue
- type MailRefusal
- type MailRelayValue
- type MailSink
- type MailSpool
- type MailSpoolConfig
- type MailValue
- type MessageMover
- type MessageValue
- type MigrationValue
- type Migrator
- type MigratorProvider
- type QueueConfig
- type QueueDriverConfig
- type QueuePolicyValue
- type Refusal
- type RefusalError
- type Reindexer
- type StampValue
- type Step
- type StoreConfig
- type StoreDriverConfig
- type StoreEngine
- type StudioDriverConfig
- type StudioEnvValue
- type StudioHost
- type StudioStateValue
- type TableSpec
- type Ticker
- type Timer
- type TombstoneValue
- type Transaction
- type TransitionSpec
- type Translator
- type Trasher
- type VersionKeeper
- type VersionValue
- type VersionWeightValue
- type VersionWeighter
- type WordsConfig
- type WorkflowChangeValue
- type WorkflowConfig
- type WorkflowDriverConfig
- type WorkflowEngine
- type WorkflowEntityValue
- type WorkflowFailure
- type WorkflowFiringValue
- type WorkflowJournal
- type WorkflowLoopEvent
- type WorkflowLoopEventValue
- type WorkflowRecordValue
- type WorkflowStepValue
- type WorkflowStore
- type WorkflowTrigger
- type WorkflowWake
- type WriteMode
Constants ¶
const ( // LabelNode is the pprof label naming the node a goroutine works for. LabelNode string = "kit_node" // LabelLoop is the pprof label naming the loop a goroutine belongs to. LabelLoop string = "kit_loop" )
const WorkflowCreateEvent string = "create"
WorkflowCreateEvent is the event of a transition Start fires: an entity entering its workflow.
Variables ¶
var ( // NewHTTPServer builds the HTTP engine an app in the server profile // serves on; nil until framework/kit/server is imported. NewHTTPServer atomic.Pointer[func(cfg HTTPConfig) HTTPServer] // NewStaticFiles builds the file server of a frontend's tree; nil until // framework/kit/server is imported. NewStaticFiles atomic.Pointer[func(fsys fs.FS, csp string) (http.Handler, error)] // SampleProcess samples the running process — its heap, goroutines, // collections and CPU time — for the runtime graph a serving app answers; // nil until framework/kit/server is imported, and the graph then carries // no process (ADR 0172). SampleProcess atomic.Pointer[func() *model.Process] )
var Jobs atomic.Pointer[JobDriverConfig]
Jobs is the jobs subsystem: the schedules of kit's jobs and the scheduler that fires them; nil until framework/kit/jobs is imported. A product that declares a job without it is refused at the start (ADR 0179 §6).
var Mail atomic.Pointer[MailDriverConfig]
Mail is the mail subsystem: the outbox kit's mailers keep and the transports that empty it; nil until framework/kit/mail is imported. A product that declares a mailer without it is refused at the start (ADR 0179 §6).
var Queues atomic.Pointer[QueueDriverConfig]
Queues is the queue subsystem: the brokers kit's consumers' queues run on and the migration of a queue's table on a database; nil until framework/kit/queue is imported. A product that declares a topic, a subscription, a watch, a queued command or a mailer whose outbox is on a database without it is refused at the start (ADR 0179 §6).
var Stores atomic.Pointer[StoreDriverConfig]
Stores is the store subsystem: the engines kit's stores run on, kit's scope on a database and the migrations of kit's tables; nil until framework/kit/store is imported. A product that declares a store or a database without it is refused at the start (ADR 0179 §6).
var Studio atomic.Pointer[StudioDriverConfig]
Studio is the Studio subsystem: the tool's variables and the Studio's routes; nil until framework/kit/studio is imported, and kit then reads none of the tool's variables and serves no route of the Studio.
var Words atomic.Pointer[WordsConfig]
Words is kit's sentences in the languages after English, the catalogues the Studio shows its reader's language from; nil until framework/kit/studio is imported, and kit then speaks English alone. The terminal, the logs and an error read English whatever a program imports (ADR 0179 Q6).
var Workflows atomic.Pointer[WorkflowDriverConfig]
Workflows is the workflow subsystem: the engine kit's workflows run on; nil until framework/kit/workflow is imported. A product that declares a workflow without it is refused at the start (ADR 0179 §6).
Functions ¶
Types ¶
type Broker ¶ added in v0.33.0
type Broker interface {
// Publish puts payload in the queue: in the transaction ctx carries for
// its database, when it lives on one.
Publish(ctx context.Context, payload []byte) error
// Consume delivers the queue's messages to cfg's handler until ctx ends
// or the queue's storage fails.
Consume(ctx context.Context, cfg ConsumeConfig) error
// DeadLetters are up to maxLetters of the queue's dead letters, oldest
// first.
DeadLetters(ctx context.Context, maxLetters int) ([]DeadLetterValue, error)
}
Broker is one queue as kit's core uses it: a publication, the consumer that delivers it, and its dead letters. It grows by the sibling below.
type Checker ¶ added in v0.32.0
type Checker interface {
// Check asks the database whether it answers, within its check timeout.
Check(ctx context.Context) error
}
Checker is a Database that says whether it answers. A sibling of Database.
type Clock ¶ added in v0.33.0
type Clock interface {
// Now is the clock's instant.
Now() time.Time
// Since is how long ago t was, on the clock.
Since(t time.Time) time.Duration
// After is a channel that receives the clock's instant once d passed.
After(d time.Duration) <-chan time.Time
// NewTimer is a timer that fires once d passed.
NewTimer(d time.Duration) Timer
// NewTicker is a ticker that fires every d.
NewTicker(d time.Duration) Ticker
// Sleep waits until d passed.
Sleep(d time.Duration)
}
Clock is the app's clock as a queue stamps and waits on it: kit's core hands the one its app runs on, a test's manual clock included.
type ConsumeConfig ¶ added in v0.33.0
type ConsumeConfig struct {
// Handler handles one delivery: nil acknowledges it, an error has it
// retried or, through DoNotRetry, dead-lettered at once. Every handler
// kit runs tolerates a redelivery.
Handler func(ctx context.Context, d DeliveryValue) error
// PollInterval bounds an idle wait.
PollInterval time.Duration
// Parallelism is how many deliveries are handled at once.
Parallelism int
// BatchSize is how many messages the consumer takes at a time.
BatchSize int
}
ConsumeConfig is how a queue's consumer runs: its handler, how long it waits idle, how many messages it handles at once and takes at a time.
type Database ¶ added in v0.31.0
type Database interface {
// Transact runs fn in a transaction of the database, or in a savepoint
// of the one ctx carries for it: nil commits or releases, an error
// rolls back.
Transact(ctx context.Context, fn func(ctx context.Context) error) error
// InTransaction reports whether ctx carries a transaction of this
// database.
InTransaction(ctx context.Context) bool
// Defer holds fn until the transaction ctx carries for the database
// commits, and reports true; outside one it holds nothing and reports
// false.
Defer(ctx context.Context, fn func()) bool
// OnAbort holds fn until the work of the scope ctx carries for the
// database is undone, and reports true; outside one it holds nothing
// and reports false.
OnAbort(ctx context.Context, fn func(ctx context.Context)) bool
}
Database is kit's scope on one database (ADR 0179 §2): the transactions kit.Transact opens on it, their savepoints, and the functions held until their end. The core knows a database only through it; the store package implements it over the SDK's sql. It grows by the siblings below.
type DatabaseConfig ¶ added in v0.31.0
type DatabaseConfig struct {
// Name is the database's, as the product declared it.
Name string
// DB is the pool kit.Engine opened.
DB *sql.DB
// Dialect is the engine's SQL dialect: "postgres", "mysql" or
// "sqlite".
Dialect string
// Timeout bounds each call kit makes on the database.
Timeout time.Duration
// MaxOpen and MaxIdle bound the pool's connections.
MaxOpen, MaxIdle int
// MaxLifetime and MaxIdleTime bound a connection's life.
MaxLifetime, MaxIdleTime time.Duration
// CheckTimeout bounds a check of the database.
CheckTimeout time.Duration
}
DatabaseConfig is one database a product declares, as kit opened it: its pool, its dialect, its tuning and the timeout of each call.
type DeadLetterValue ¶ added in v0.33.0
type DeadLetterValue struct {
// FailedAt is when its last attempt failed.
FailedAt time.Time
// Reason is the failure's identifier.
Reason string
// Cause is the failure's public text, "" for none.
Cause string
// Message is the message, unmodified.
Message MessageValue
// Code is the failure's error code, 0 for none.
Code uint32
// Deliveries counts its deliveries.
Deliveries int
}
DeadLetterValue is a message its queue gave up on: when, why, and how many times it was delivered.
type DeliveryValue ¶ added in v0.33.0
type DeliveryValue struct {
// Message is what is delivered.
Message MessageValue
// Deliveries counts the deliveries, this one included.
Deliveries int
}
DeliveryValue is one delivery of a message: the message, and how many times it has been delivered, this one included.
type DocumentSink ¶ added in v0.32.0
type DocumentSink interface {
// PutDocument writes the document key with its versions and its trash
// as they are given.
PutDocument(ctx context.Context, key string, versions []VersionValue, trashedAt time.Time) error
// InsertRaw writes a document of a store that keeps no versions, as it
// rests.
InsertRaw(ctx context.Context, raw json.RawMessage) error
}
DocumentSink is a store's documents on the database a data copy writes. A sibling of Documents.
type DocumentSource ¶ added in v0.32.0
type DocumentSource interface {
// Documents is the document store the engine runs on, and whether there
// is one.
Documents() (Documents, bool)
}
DocumentSource is an engine that says the document store it runs on: itself, or the one what it wraps runs on. A data copy reads and writes a store through it (ADR 0178 C7). A sibling of StoreEngine.
type DocumentValue ¶ added in v0.31.0
type DocumentValue struct {
// JSON is the record as it rests.
JSON json.RawMessage
// Value is the entity decoded from JSON, nil until something decoded it;
// the store's typed facade asserts it to its type.
Value any
}
DocumentValue is a record as a store's engine holds it (ADR 0179 §2): its JSON as it rests, byte for byte what kit encodes, and the entity once decoded, kept beside it so that a read, an index or a privacy walk does not decode it twice.
type Documents ¶ added in v0.32.0
type Documents interface {
// KeyList yields every key the store holds, in key order.
KeyList(ctx context.Context) iter.Seq2[string, error]
// TombstoneList is the trash, in key order: none when the store keeps
// no versions.
TombstoneList(ctx context.Context) ([]TombstoneValue, error)
// VersionList is the versions of the document key, newest first.
VersionList(ctx context.Context, key string) ([]VersionValue, error)
// Current is the document key as the store keeps it.
Current(ctx context.Context, key string) (json.RawMessage, error)
// KeepsVersions reports whether the store keeps versions.
KeepsVersions() bool
}
Documents is a store's documents as they rest, as a data copy reads them.
type EnterHookSpec ¶ added in v0.34.0
type EnterHookSpec struct {
// Fn runs the hook; it may change the entity, not its state nor its
// key.
Fn func(ctx context.Context, e *WorkflowEntityValue) error
// State is the state whose entering runs it.
State string
}
EnterHookSpec is one hook run as an entity enters a state, before it is stored: an error cancels the transition.
type EntrySource ¶ added in v0.32.0
type EntrySource interface {
// KeyedEntries returns up to limit records as they rest, in key order.
KeyedEntries(ctx context.Context, limit int) ([]EntryValue, error)
}
EntrySource is an engine that lists its records as they rest with their keys: what a sealing store reads its records by. A sibling of StoreEngine.
type EntryValue ¶ added in v0.32.0
type EntryValue struct {
// Key is the record's key.
Key string
// JSON is the record as it rests.
JSON json.RawMessage
}
EntryValue is a record as it rests, with its key: what an engine lists for a reader that cannot key a record itself.
type Executor ¶ added in v0.32.0
type Executor interface {
// ExecContext runs a statement that returns no rows.
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
// QueryContext runs a query that returns rows.
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
// QueryRowContext runs a query that returns at most one row.
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
Executor is what a migration's step runs its statements on: the transaction its migration runs in.
type Folder ¶ added in v0.31.0
type Folder interface {
// Fold rewrites the store's data with only what it holds now.
Fold(ctx context.Context) error
}
Folder is an engine that keeps what its writes left beside its data, and can fold it in now. A sibling of StoreEngine.
type HTTPConfig ¶
type HTTPConfig struct {
// Addr is where to listen, "host:port".
Addr string
// Shards is how many sockets the engine opens on Addr.
Shards int
// ReadHeader, Read, Write and Idle bound a request's phases.
ReadHeader, Read, Write, Idle time.Duration
// MaxHeaderBytes bounds a request's header.
MaxHeaderBytes int
// Handler answers every request.
Handler http.Handler
}
HTTPConfig is what kit asks of the HTTP engine: where to listen, its one socket, its bounds, and the handler.
type HTTPServer ¶
type HTTPServer interface {
// Start binds the address and serves, returning once bound.
Start(ctx context.Context) error
// State says what the engine binds and serves.
State() HTTPState
// Shutdown drains the engine within ctx.
Shutdown(ctx context.Context) error
}
HTTPServer is the HTTP engine kit starts, reads and stops.
type HTTPState ¶
type HTTPState struct {
// Addr is the address the engine bound, "" before it did.
Addr string
// Listeners is how many sockets it listens on.
Listeners int
// Active are the connections being served, Total those accepted since
// the start, Rejected those refused.
Active int64
Total, Rejected uint64
}
HTTPState is what the HTTP engine says of itself once it runs: the address it bound, and its connections.
type IndexSpec ¶ added in v0.31.0
type IndexSpec struct {
// Name reads the index, and names it in a refusal.
Name string
// Unique refuses a write that would file two documents under one key.
Unique bool
// Keys are a document's keys in the index; an empty key is not indexed.
Keys func(d DocumentValue) []string
}
IndexSpec declares one secondary index of a store, over documents: the product's index function on its type, wrapped once at the declaration.
type JobDriverConfig ¶ added in v0.35.0
type JobDriverConfig struct {
// Every is the schedule of a job that runs every period, first one
// period after the scheduler starts; a period that is not positive is
// refused.
Every func(period time.Duration) (JobScheduleFunc, error)
// Cron is the schedule of a five-field POSIX cron expression, in the
// process's local time zone; an expression it cannot read is refused.
Cron func(expr string) (JobScheduleFunc, error)
// Open opens the scheduler the app's jobs run on, as cfg says, with no
// entry yet.
Open func(cfg *JobSchedulerConfig) JobScheduler
}
JobDriverConfig is what framework/kit/jobs plugs into kit: how a job's schedule is read from its declaration, and how the scheduler that fires the app's jobs opens.
type JobEntryValue ¶ added in v0.35.0
type JobEntryValue struct {
// Name names the job; the scheduler refuses a name it holds already.
Name string
// Schedule says when the job runs next.
Schedule JobScheduleFunc
// Run runs the job once; its error is the result's.
Run func(ctx context.Context) error
}
JobEntryValue is one job as the scheduler fires it: its name, its schedule, and the run.
type JobResultValue ¶ added in v0.35.0
type JobResultValue struct {
// Name is the job's.
Name string
// Scheduled is the instant the fire was due.
Scheduled time.Time
// Started and Finished bound the run; zero for a fire that did not run.
Started, Finished time.Time
// Missed counts the fires that came due while the scheduler could not
// fire them, skipped rather than caught up.
Missed int
// Skipped says the fire did not run: a run of the same job was going.
Skipped bool
// Err is the run's error.
Err error
}
JobResultValue is one decision of the scheduler: a run of a job, or a fire it skipped.
type JobScheduleFunc ¶ added in v0.35.0
JobScheduleFunc says when a job runs next after an instant: the instant, and false when it never runs again.
type JobScheduler ¶ added in v0.35.0
type JobScheduler interface {
// Add registers a job; it is refused while the scheduler runs, for a
// name it holds already, and for an entry with no name, run or
// schedule.
Add(entry JobEntryValue) error
// Run fires the jobs until ctx ends, then waits for the runs going.
Run(ctx context.Context) error
}
JobScheduler fires the app's jobs, each on its schedule, on the app's clock: a fire due while the previous run of the same job is going is skipped, a missed one is counted, never caught up.
type JobSchedulerConfig ¶ added in v0.35.0
type JobSchedulerConfig struct {
// Clock is the app's clock, which the scheduler stamps and waits on.
Clock Clock
// OnResult hears every decision of the scheduler — each run, with the
// job's own error, and each fire skipped or missed —, one at a time.
OnResult func(res JobResultValue)
}
JobSchedulerConfig is the scheduler the app's jobs run on: the app's clock and what kit hears of each fire.
type Keyser ¶ added in v0.31.0
type Keyser interface {
// Keys yields the keys above after, in order, then its failure if any.
Keys(ctx context.Context, after string) iter.Seq2[string, error]
}
Keyser is an engine that lists the keys of its documents, in key order, above after, without reading a document. A sibling of StoreEngine.
type LiveMessageValue ¶ added in v0.33.0
type LiveMessageValue struct {
// VisibleAt is when the message is next delivered.
VisibleAt time.Time
// Message is the message.
Message MessageValue
// Deliveries counts its deliveries so far.
Deliveries int
// Leased reports whether a consumer holds it.
Leased bool
}
LiveMessageValue is a message waiting in its queue, as it lies: when it is next visible, how many times it was delivered, and whether a consumer holds it.
type MailAttemptValue ¶ added in v0.34.0
type MailAttemptValue struct {
// QueuedAt is when the mail was put in the outbox.
QueuedAt time.Time
// Meta is what Annotate kept of the Send.
Meta map[string]string
// ID is the mail's outbox ID.
ID string
// Attempt numbers the attempt, from 1.
Attempt int
}
MailAttemptValue is one delivery attempt of a mail: its outbox ID, its number, when the mail was queued, and what the spool kept of its Send.
type MailCaptureSource ¶ added in v0.34.0
type MailCaptureSource interface {
// Composed is the last message the transport composed, nil for none.
Composed() []byte
}
MailCaptureSource is a transport that keeps what it composed: the capture transport, whose last message the Studio's mailbox shows. A sibling of MailSink.
type MailDriverConfig ¶ added in v0.34.0
type MailDriverConfig struct {
// Open opens one mailer's outbox as cfg says, closed until it runs.
Open func(cfg *MailSpoolConfig) (MailSpool, error)
// Validate is the SDK's verdict on a mail: nil when the outbox takes it,
// else what is wrong with it, in the SDK's public words.
Validate func(msg MailValue) error
// Capture is a transport that delivers nothing and keeps the last
// message it composed (MailCaptureSource).
Capture func() MailSink
// ParseSMTP reads an SMTP URL — smtp://user:password@host:port?tls=
// starttls|implicit|none, smtps:// for implicit TLS — as the SDK's
// SMTP transport would take it.
ParseSMTP func(url string) (MailRelayValue, error)
// NewSMTP is the SDK's SMTP transport to relay, which dials nothing
// until a mail is sent.
NewSMTP func(relay *MailRelayValue) (MailSink, error)
// Refused reports whether err, or an error it wraps, is the spool's or
// the URL's refusal of kind: the SDK's sentinels stay in the subsystem,
// and the error keeps the fields the SDK gave it.
Refused func(err error, kind MailRefusal) bool
}
MailDriverConfig is what framework/kit/mail plugs into kit: how a mailer's outbox opens, the SDK's verdict on a mail, the transports a mailer hands its mail to, and how kit tells the spool's refusals apart.
type MailEvent ¶ added in v0.34.0
type MailEvent uint8
MailEvent is what a spool reports of a mail.
const ( // MailEventOther is an event of the spool kit shows nothing of. MailEventOther MailEvent = iota // MailEventQueued is a mail put in the outbox. MailEventQueued // MailEventSent is a mail the transport accepted. MailEventSent // MailEventRetrying is a failed attempt that will be retried. MailEventRetrying // MailEventDeadLettered is a mail given up on after its last attempt. MailEventDeadLettered // MailEventDuplicate is a redelivery of a mail already sent, dropped. MailEventDuplicate )
What a spool reports of a mail.
type MailEventValue ¶ added in v0.34.0
type MailEventValue struct {
// Err is a failed attempt's failure.
Err error
// Meta is what Annotate kept of the Send.
Meta map[string]string
// At is when the event happened.
At time.Time
// QueuedAt is when the mail was put in the outbox.
QueuedAt time.Time
// Message is the mail.
Message MailValue
// ID is the mail's outbox ID.
ID string
// Attempt numbers the attempt the event is about.
Attempt int
// Kind is what happened.
Kind MailEvent
}
MailEventValue is what a spool reports of a mail: its kind, the mail and its outbox ID, the attempt, when, and the failure of a failed attempt.
type MailRefusal ¶ added in v0.34.0
type MailRefusal uint8
MailRefusal is a refusal of the mail subsystem, as kit words it.
const ( // MailRefusalNone is no refusal kit words. MailRefusalNone MailRefusal = iota // MailRefusalClosed is a spool that is closed: its mailer is not // running. MailRefusalClosed // MailRefusalUnencodable is a mail the outbox cannot encode. MailRefusalUnencodable // MailRefusalInvalidURL is an SMTP URL that is not one of the form // smtp://user:password@host:port; its "problem" field says the clause. MailRefusalInvalidURL )
The spool's refusals kit tells apart, which it words for the product.
type MailRelayValue ¶ added in v0.34.0
type MailRelayValue struct {
// Config is the SDK's SMTP configuration, held as any.
Config any
// Server is where it delivers, host:port.
Server string
// TLS is its TLS mode as the URL spells it: starttls, implicit or none.
TLS string
}
MailRelayValue is an SMTP relay as the SDK's transport takes it: its configuration, which holds the password and is handed to NewSMTP and never kept or printed, and what may be shown of it.
type MailSink ¶ added in v0.34.0
MailSink is what a mailer hands a mail to: the SDK's SMTP transport, or its capture transport, which delivers nothing. It grows by the sibling below.
type MailSpool ¶ added in v0.34.0
type MailSpool interface {
// Send puts msg in the outbox — in the transaction ctx carries for its
// database, when it lives on one — and returns its outbox ID.
Send(ctx context.Context, msg MailValue) (string, error)
// SendWithID puts msg in the outbox under id, minted by kit.
SendWithID(ctx context.Context, id string, msg MailValue) error
// DeadLetters counts up to maxLetters of the mails earlier runs gave up
// on.
DeadLetters(ctx context.Context, maxLetters int) (int, error)
// Run hands each mail to the transport until ctx ends.
Run(ctx context.Context) error
// Close releases the outbox.
Close() error
}
MailSpool is one mailer's outbox as kit's core uses it: a mail put in it at once or under an ID kit minted, the loop that hands each mail to the transport, and its dead letters.
type MailSpoolConfig ¶ added in v0.34.0
type MailSpoolConfig struct {
// Transport makes one delivery attempt of msg; the spool retries a
// failure, or dead-letters the mail after its last attempt.
Transport func(ctx context.Context, msg MailValue, attempt MailAttemptValue) error
// Clock is the app's clock, which the spool stamps and waits on.
Clock Clock
// Observe is told each event of each mail.
Observe func(e *MailEventValue)
// Annotate is what the spool keeps of a Send for its deliveries, read
// from the Send's context.
Annotate func(ctx context.Context) map[string]string
// NewID mints a mail's outbox ID.
NewID func() (string, error)
// Outbox is the queue the spool keeps its mails in on a database —
// the queue subsystem's, sealed —, nil for a directory or memory.
Outbox Broker
// Database is the database Outbox is on, whose transaction a mail sent
// in one joins; nil for none.
Database Database
// From is the sender of every mail that names none: the SDK's
// mail.Address, held as any.
From MailValue
// Dir is the directory the spool keeps its own queue in; with no Outbox
// and no Dir, the outbox is in memory.
Dir string
// BackoffBase is the wait after a failed attempt, doubled after each,
// up to BackoffMax.
BackoffBase time.Duration
// BackoffMax bounds the wait after a failed attempt.
BackoffMax time.Duration
// SendTimeout bounds one attempt.
SendTimeout time.Duration
// PollInterval bounds an idle wait.
PollInterval time.Duration
// MaxAttempts is how many attempts a mail gets before it is
// dead-lettered.
MaxAttempts int
// MaxMessageBytes bounds one mail in the spool's own queue; zero is the
// spool's own bound.
MaxMessageBytes int
}
MailSpoolConfig is one mailer's outbox: the transport each attempt runs, the app's clock, what kit hears of its mails, its retries, and where it keeps them — a queue on the database that keeps the mailer's service, a directory, or memory.
type MailValue ¶ added in v0.34.0
type MailValue struct {
// Value is the SDK's mail value.
Value any
}
MailValue is a value of the SDK's mail package as it crosses the contract: a mail.Message, or a sender's mail.Address, held as any — kit's core names the SDK's mail types, plug names none.
type MessageMover ¶ added in v0.33.0
type MessageMover interface {
// Messages are up to maxMessages live messages after the identifier
// after, "" for the first, in their queue's order.
Messages(ctx context.Context, after string, maxMessages int) ([]LiveMessageValue, error)
// PutMessage writes live under an identifier of the queue's own, and
// returns it.
PutMessage(ctx context.Context, live LiveMessageValue) (string, error)
// PutDeadLetter writes dead, with its cause, under an identifier of the
// queue's own, and returns it.
PutDeadLetter(ctx context.Context, dead DeadLetterValue) (string, error)
}
MessageMover is a Broker whose messages a data copy reads and writes as they lie, without a lease, with their counts and their instants. A sibling of Broker.
type MessageValue ¶ added in v0.33.0
type MessageValue struct {
// EnqueuedAt is when the message was published.
EnqueuedAt time.Time
// ID identifies the message in its queue.
ID string
// Payload is the message as kit encoded it.
Payload []byte
}
MessageValue is one message of a queue: its identifier, its payload as kit encoded it, and when it was published.
type MigrationValue ¶ added in v0.32.0
type MigrationValue struct {
// Version orders the migration in its set: non-zero and unique.
Version uint64
// Name labels it in the version table.
Name string
// Up applies the change.
Up Step
// Down reverses it.
Down Step
}
MigrationValue is one versioned change of a database's schema and its reversal, as the core hands it to the store subsystem: a product's kit.Migration, or one of kit's own, its steps on the standard library's types.
type Migrator ¶ added in v0.32.0
type Migrator interface {
// Plan is the set's pending migrations, oldest first, applying nothing.
Plan(ctx context.Context) ([]MigrationValue, error)
// Up applies every pending migration, in order.
Up(ctx context.Context) error
// Down reverses the applied migrations above version, newest first.
Down(ctx context.Context, version uint64) error
}
Migrator is one set of migrations on a database.
type MigratorProvider ¶ added in v0.32.0
type MigratorProvider interface {
// Migrator is the set ms, under the version table table.
Migrator(table string, ms []MigrationValue) (Migrator, error)
}
MigratorProvider is a Database that runs a set of migrations under a version table of its own, and so a lock of its own. A sibling of Database.
type QueueConfig ¶ added in v0.33.0
type QueueConfig struct {
// Name names the queue's node in a refusal: the consumer's or the
// mailer's node ID.
Name string
// Dir is the directory a file queue lies in; with no Database and no
// Dir, the queue is in memory.
Dir string
// Database keeps the queue, nil when Dir or memory does: a scope the
// store subsystem's Database opened, whose transaction a publication in
// it joins.
Database Database
// Table is the queue's table on Database.
Table string
// Policy is how the queue leases, retries and bounds its messages.
Policy QueuePolicyValue
// Clock is the app's clock, which the queue stamps and waits on.
Clock Clock
// Seal, when set, seals every payload on its way in — a mail's, in a
// mailer's outbox on a database —, and Unseal opens one on its way out;
// MaxPayload bounds a payload before it is sealed.
Seal func(ctx context.Context, payload []byte) ([]byte, error)
// Unseal is the payload a box holds, the box as it lies when it does
// not open.
Unseal func(ctx context.Context, box []byte) []byte
// MaxPayload bounds a payload Seal seals.
MaxPayload int
// Wrap, when a test sets it, stands in front of the queue the subsystem
// opens: a func(queue.Broker) queue.Broker of the SDK's queue, which
// kit's core does not name. Nil in every app a product builds.
Wrap any
}
QueueConfig is what kit asks of one queue: where it lies, its policy, the app's clock, and for a mailer's outbox the sealing of what it keeps.
type QueueDriverConfig ¶ added in v0.33.0
type QueueDriverConfig struct {
// Open opens one queue, as cfg places it: on a database, in a
// directory, or in memory.
Open func(cfg QueueConfig) (Broker, error)
// TableMigration is the migration that makes the queue table on a
// database of the dialect named, at version.
TableMigration func(dialect, table string, version uint64) (MigrationValue, error)
// DoNotRetry is err as a delivery's handler returns it when no retry
// can help: its queue dead-letters the message at once.
DoNotRetry func(err error) error
// NotRetryable reports whether err, a delivery's handler's, says that no
// retry can help: what DoNotRetry returned, the product's own included.
NotRetryable func(err error) bool
}
QueueDriverConfig is what framework/kit/queue plugs into kit: how a consumer's queue opens, the migration that makes its table on a database, and how a delivery's handler says that no retry can help.
type QueuePolicyValue ¶ added in v0.33.0
type QueuePolicyValue struct {
// VisibilityTimeout is how long a delivery is leased.
VisibilityTimeout time.Duration
// RetryDelay is the wait after a message's first failure, doubled after
// each, up to MaxRetryDelay.
RetryDelay time.Duration
// MaxRetryDelay bounds the wait before a retry; zero leaves it unbound.
MaxRetryDelay time.Duration
// MaxDeliveries is how often a message is delivered before it is
// dead-lettered.
MaxDeliveries int
// MaxMessageBytes bounds a message; zero is the queue's own bound.
MaxMessageBytes int
}
QueuePolicyValue is how a queue leases, retries and bounds its messages: the SDK's queue policy, in kit's terms.
type Refusal ¶ added in v0.32.0
type Refusal uint8
Refusal is a kind of refusal of a store's engine or a database, as kit words it.
const ( // RefusalNone is no refusal kit words. RefusalNone Refusal = iota // RefusalNotFound is no document under the key, or under the index's // key. RefusalNotFound // RefusalExists is a document already under the key an insertion names. RefusalExists // RefusalUniqueTaken is another document under a unique index's key. RefusalUniqueTaken // RefusalKeyEmpty is a document whose key is empty. RefusalKeyEmpty // RefusalKeyChanged is an update that changes the document's key. RefusalKeyChanged // RefusalIndexUnknown is an index the store does not declare. RefusalIndexUnknown // RefusalIndexNotUnique is a lookup on an index that is not unique. RefusalIndexNotUnique // RefusalIndexBroken is stored documents that break a unique index. RefusalIndexBroken // RefusalUndecodable is a record that does not decode into its type. RefusalUndecodable // RefusalUnencodable is an entity that does not encode. RefusalUnencodable // RefusalPersist is a write the store could not keep. RefusalPersist // RefusalLoad is a store that could not be loaded; its "problem" field // says why. RefusalLoad // RefusalClosed is a call on a closed engine. RefusalClosed // RefusalUnconfirmed is a write that stands but whose survival across a // power loss is in doubt. RefusalUnconfirmed // RefusalVersionsNotKept is a call on the versions of a store that keeps // none. RefusalVersionsNotKept // RefusalVersionsRewrite is a rewrite of versions that adds or // renumbers one. RefusalVersionsRewrite // RefusalNotTrashed is no record in the trash under the key. RefusalNotTrashed // RefusalKeyTooLong is a key longer than a database's key columns hold; // its "max" field says how long they hold. RefusalKeyTooLong // RefusalStatement is a statement the database did not complete. RefusalStatement // RefusalTxClosed is a call with the context of a transaction that // ended. RefusalTxClosed // RefusalTxFailed is a transaction or a savepoint the database would // not open, commit or roll back. RefusalTxFailed // RefusalOutOfOrder is a migration older than one already applied; its // "applied" field names the newer. RefusalOutOfOrder )
The kinds of refusal.
type RefusalError ¶ added in v0.32.0
type RefusalError struct {
// Err is what the engine met.
Err error
// Kind is how kit words it.
Kind Refusal
}
RefusalError is an engine's refusal of one kind: the error it met, and the kind kit words it by.
func (*RefusalError) Error ¶ added in v0.32.0
func (e *RefusalError) Error() string
Error is what the engine met's.
func (*RefusalError) Unwrap ¶ added in v0.32.0
func (e *RefusalError) Unwrap() error
Unwrap is what the engine met.
type Reindexer ¶ added in v0.32.0
type Reindexer interface {
// Reindex files every record's index rows again.
Reindex(ctx context.Context) error
}
Reindexer is an engine on a database that files its index rows again. A sibling of StoreEngine.
type StampValue ¶ added in v0.32.0
type StampValue struct {
// Meta is kept with the version the write makes.
Meta map[string]string
// InPlace makes the write change the document without making a version.
InPlace bool
}
StampValue is what a write says about the version it makes: who made it and which command, kept with the version; and whether it changes the document in place, without a version of its own.
type StoreConfig ¶ added in v0.31.0
type StoreConfig struct {
// Name is the store's, as a log line and a rollback name it.
Name string
// Key is a document's key: the product's key function on its type,
// wrapped once at the declaration. It reads the document's Value, which
// the engine decodes first unless KeyAtRest gives the key.
Key func(d DocumentValue) string
// KeyAtRest, when set, gives the key of a record as it rests, without
// decoding it; false when it cannot.
KeyAtRest func(raw json.RawMessage) (string, bool)
// Decode is the entity a document's JSON holds, which the engine keeps
// as the document's Value.
Decode func(raw json.RawMessage) (any, error)
// Indexes are the store's secondary indexes.
Indexes []IndexSpec
// Data is the data directory the store rests in — the SDK's writable
// file system, which the engine asserts — and Path its snapshot there;
// a nil Data and a nil Database keep the store in memory.
Data fs.FS
// Path is the store's snapshot in Data.
Path string
// Database keeps the store, nil when the data directory or memory does:
// a scope the store subsystem's Database opened.
Database Database
// Table is the store's table on Database.
Table string
// IndexKey is the key a table's index keys are hashed under, nil for
// none: an index key reaches the table as its keyed hash.
IndexKey func(index, key string) []byte
// Call is the context one call of the engine on Database runs with: on
// the transaction ctx carries for it, else on the pool, within the
// database's timeout; done ends it.
Call func(ctx context.Context, write bool) (call context.Context, done func(), err error)
// Versions is how many former versions of each record the engine keeps,
// none when zero; Clock stamps them.
Versions int
// Clock is the app's clock, which stamps a version.
Clock func() time.Time
// Held reports whether a record's versions are held, and no write may
// prune them: asked with the write's context, on a database inside its
// transaction.
Held func(ctx context.Context, key string) bool
// Stamp is what a write under ctx says about the version it makes.
Stamp func(ctx context.Context) StampValue
// Transaction is kit's transaction, which the engine's writes take part
// in.
Transaction Transaction
}
StoreConfig is what kit asks of one store's engine: the store, its key and its indexes over documents, where it rests and what it keeps, and how its writes take part in kit's transactions.
type StoreDriverConfig ¶ added in v0.31.0
type StoreDriverConfig struct {
// Open opens the engine of one store, as cfg places it: loaded from the
// data directory, empty in memory, or on a database.
Open func(cfg StoreConfig) (StoreEngine, error)
// Database opens kit's scope on one database's pool.
Database func(cfg DatabaseConfig) (Database, error)
// TableMigration is the migration that makes the table t on a database
// of the dialect named, at version.
TableMigration func(dialect string, t TableSpec, version uint64) (MigrationValue, error)
}
StoreDriverConfig is what framework/kit/store plugs into kit: how a store's engine opens, how kit opens its scope on a database, and the migration that makes one of kit's tables.
type StoreEngine ¶ added in v0.31.0
type StoreEngine interface {
// Get returns the document under key.
Get(ctx context.Context, key string) (DocumentValue, error)
// List returns every document, in key order.
List(ctx context.Context) ([]DocumentValue, error)
// Filter returns the documents keep accepts, in key order.
Filter(ctx context.Context, keep func(d DocumentValue) bool) ([]DocumentValue, error)
// Lookup returns the document a unique index files under key.
Lookup(ctx context.Context, index, key string) (DocumentValue, error)
// Find returns the documents an index files under key, in key order.
Find(ctx context.Context, index, key string) ([]DocumentValue, error)
// Count says how many documents the store holds.
Count(ctx context.Context) (int, error)
// Entries returns up to limit documents as they rest, in key order.
Entries(ctx context.Context, limit int) ([]json.RawMessage, error)
// Write stores d as mode says. The document and its index keys are kept
// together, or neither.
Write(ctx context.Context, d DocumentValue, mode WriteMode) error
// Update applies fn to the document under key and stores the result,
// atomically with respect to every other write of the store.
Update(ctx context.Context, key string, fn func(d *DocumentValue) error) (DocumentValue, error)
// Delete removes the document under key.
Delete(ctx context.Context, key string) error
// Watch registers the functions told the key of every document written
// and deleted, once the write stands.
Watch(onWrite, onDelete func(key string))
// Close releases the engine.
Close() error
}
StoreEngine is what a store runs on, over documents (ADR 0179 §2): the non-generic engine under Store[T]. Its refusals are kit's (Refusal): the engine translates the SDK's before they reach the core. Every call takes the caller's context, which carries the transaction the call joins. It grows by the sibling interfaces below, never by a method (the SDK's ADR 0039).
type StudioDriverConfig ¶ added in v0.38.0
type StudioDriverConfig struct {
// Env reads what the tool's variables ask of the Studio in this run.
Env func(getenv func(string) string) StudioEnvValue
// Settings are the tool's variables as the settings of a run show them,
// in order, each with its value as the run resolved it and where it
// came from: the product's code, the environment, or kit's default.
Settings func(getenv func(string) string, state StudioStateValue) []model.Setting
// Forced are the variables kit dev says it set itself for this launch,
// as it names them; kit labels only those it lets kit dev set.
Forced func(getenv func(string) string) []string
// DevBuild is what kit dev said about the build it launched, nil when
// the process was not started by kit dev.
DevBuild func(getenv func(string) string) *model.DevBuild
// Mount registers the Studio's routes on mux, each behind the Studio's
// guard, reading the running app through host.
Mount func(mux *http.ServeMux, host StudioHost)
}
StudioDriverConfig is what framework/kit/studio plugs into kit: how the tool's variables are read, and how the Studio's routes mount.
type StudioEnvValue ¶ added in v0.38.0
type StudioEnvValue struct {
// Studio is what the environment says of the Studio: on — which
// production refuses —, off, or empty when it says neither.
Studio string
// Remote: the Studio answers a client that is not on this machine.
Remote bool
// NoAnalysis: the environment turns the static analysis off.
NoAnalysis bool
}
StudioEnvValue is what the tool's variables ask of the Studio: their zero value is a run in which none is set.
type StudioHost ¶ added in v0.38.0
type StudioHost interface {
// Graph is the app's graph, as it is now.
Graph() *model.Graph
// Phase is where the app is in its life, as the graph says it.
Phase() string
// Now is the time on the app's clock.
Now() time.Time
// Subscribe streams the app's live events until cancel is called.
Subscribe() (events <-chan model.Event, cancel func())
// Stopping is closed when the app ends its live streams.
Stopping() <-chan struct{}
// Traces are the latest traces the app keeps, at most limit, those of
// root's trace or through node when either is given.
Traces(limit int, root, node string) []model.Trace
// Trace is one trace, while the app keeps it.
Trace(id string) (model.Trace, bool)
// Logs are the latest records the product logged, those of a trace or
// a node and from a level when given, at most limit — a default when
// it is empty; a level or a limit the app does not take is refused.
Logs(trace, node, level, limit string) ([]model.LogRecord, error)
// Instances are a workflow's entities and where each is; false for no
// such workflow.
Instances(workflow string) ([]model.Instance, bool)
// Items are a store's latest entities, redacted as payloads are; false
// for no such store.
Items(store string) ([]json.RawMessage, bool)
// Source is a file the graph names, of the product's Go module or of
// the one module names: a regular file within the bound, never a link;
// false for any other name.
Source(ctx context.Context, module, file string) ([]byte, bool)
// Locate says where the function fn, at file:line, lies in the
// product's own module; nil anywhere else.
Locate(file string, line int, fn string) *model.Source
// Mails are every mailer's latest mails, at most limit of each.
Mails(limit int) []model.MailSummary
// Mail is one mail, whole when its mailer keeps bodies; false when no
// mailer remembers it.
Mail(id string) (model.MailMessage, bool)
// Stores reports whether the app runs on the store subsystem: the
// Studio's routes on the stores and the databases are mounted only then.
Stores() bool
// Databases are the app's databases, each checked and its migrations
// read again now.
Databases(ctx context.Context) []model.Database
// Former are the former values of the record under key in store, as
// the Studio's data view shows them.
Former(ctx context.Context, store, key string) (model.RecordHistory, error)
// Revisions are the versions of the record under key in store, and
// what changed from version from to version to when both are given.
Revisions(ctx context.Context, store, key, from, to string) (model.RecordVersions, error)
// Trash is a page of store's trash, from offset and at most limit
// records — defaults when they are empty.
Trash(ctx context.Context, store, offset, limit string) (model.StoreTrash, error)
// Privacy is what the Studio's Privacy page shows.
Privacy(ctx context.Context) (model.Privacy, error)
// Remote reports whether the Studio answers a client that is not on
// this machine.
Remote() bool
// AllowedHost reports whether a request's Host, its port, brackets and
// case removed, may reach the Studio.
AllowedHost(host string) bool
// Reply answers r with body, a JSON document, or with err as kit
// answers an error.
Reply(w http.ResponseWriter, r *http.Request, body json.RawMessage, err error)
// Forbid answers that the caller may not reach the Studio, saying
// message.
Forbid(w http.ResponseWriter, message string)
// Fail answers an internal error, saying message and nothing of the
// error.
Fail(w http.ResponseWriter, message string)
// NotFound is kit's answer to a request for what does not exist,
// saying message.
NotFound(message string) error
// Invalid is kit's answer to a request the caller must change, saying
// message.
Invalid(message string) error
// ProfileUnreadable is kit's refusal of a profile the process could
// not read: public says which, cause why, for the logs.
ProfileUnreadable(public string, cause error) error
// Debug logs, at the debug level, a failure nobody is told of.
Debug(ctx context.Context, message string, err error)
}
StudioHost is the running app, as the Studio's routes read it and answer through it.
type StudioStateValue ¶ added in v0.38.0
type StudioStateValue struct {
// StudioOption and AnalyzeOption are the product's code's choice of the
// Studio and of the static analysis, which wins over the environment;
// nil when the code chose nothing.
StudioOption, AnalyzeOption *bool
// Studio, Remote and Analyze are the Studio's switches, as resolved and
// as the settings spell them: on or off.
Studio, Remote, Analyze string
}
StudioStateValue is what a run resolved of the Studio, and what the product's code chose of it: what the settings show of the tool's variables.
type TableSpec ¶ added in v0.32.0
type TableSpec struct {
// Name is the table's.
Name string
// VersionsOf is, for a store's versions, the store's table, from which
// the versions' table is named.
VersionsOf string
}
TableSpec is one of kit's tables on a database, as the store subsystem's migration makes it: a store's, or a store's versions beside the store's table VersionsOf. A consumer's queue's table is the queue subsystem's (QueueDriverConfig's TableMigration).
type Ticker ¶ added in v0.33.0
type Ticker interface {
// C receives the clock's instant at each tick.
C() <-chan time.Time
// Stop stops the ticker.
Stop()
// Reset makes the ticker fire every d.
Reset(d time.Duration)
}
Ticker is a ticker of a Clock.
type Timer ¶ added in v0.33.0
type Timer interface {
// C receives the clock's instant when the timer fires.
C() <-chan time.Time
// Stop stops the timer, and reports whether it had not fired.
Stop() bool
// Reset makes the timer fire once d passed, and reports whether it had
// not fired.
Reset(d time.Duration) bool
}
Timer is a timer of a Clock.
type TombstoneValue ¶ added in v0.31.0
type TombstoneValue struct {
// Key is the trashed record's key.
Key string
// At is when the record was trashed, in UTC.
At time.Time
}
TombstoneValue is one record in a store's trash: its key, and when it was trashed.
type Transaction ¶ added in v0.32.0
type Transaction interface {
// Local reports whether ctx runs in a transaction that holds the data's
// writer turn: a write in the data directory or in memory then records
// what it replaces.
Local(ctx context.Context) bool
// Undo keeps restore, which a rollback of the transaction ctx carries
// runs; nothing outside one. store names the store in a log line.
Undo(ctx context.Context, store string, restore func(ctx context.Context) error)
// AtCommit holds fn until the transaction ctx carries commits, and
// reports whether it did: false outside one, where the caller runs it
// now.
AtCommit(ctx context.Context, fn func()) bool
// Retell keeps fn, which announces a write on a database again when the
// transaction ctx carries rolls it back.
Retell(ctx context.Context, fn func())
}
Transaction is kit's transaction as a store's engine takes part in it (ADR 0139, ADR 0178): the core implements it, an engine calls it with its caller's context.
type TransitionSpec ¶ added in v0.34.0
type TransitionSpec struct {
// Instant is when a deadline's transition comes due, false for no
// instant for now; set for WorkflowTriggerDeadline.
Instant func(e WorkflowEntityValue) (time.Time, bool)
// Guard is the condition a guard's transition waits for; set for
// WorkflowTriggerGuard.
Guard func(e WorkflowEntityValue) bool
// Event names the transition.
Event string
// From is the state it leaves.
From string
// To is the state it enters.
To string
// Delay is how long a delay's transition waits in From.
Delay time.Duration
// Trigger is what fires it: an event, a delay, a deadline or a guard.
Trigger WorkflowTrigger
}
TransitionSpec declares one transition: an event's, a timer's after a delay or at an instant the entity carries, or a guard's.
type Translator ¶ added in v0.36.0
type Translator interface {
// Languages are the languages it speaks after English, in order.
Languages() []string
// Keys are the keys of lang's catalogue, sorted; nil for a language
// it does not speak.
Keys(lang string) []string
// Render is the sentence of key in lang, its placeholders filled from
// args by name; a key the catalogue lacks, or a name the sentence
// takes that args does not give, is an error.
Render(lang, key string, args map[string]string) (string, error)
}
Translator says kit's sentences in the languages after English, which only the Studio shows, in its reader's language.
type Trasher ¶ added in v0.31.0
type Trasher interface {
// Trash moves the record under key to the trash: gone from every read,
// its index keys freed, its versions kept.
Trash(ctx context.Context, key string) error
// Untrash brings the record trashed under key back as it was.
Untrash(ctx context.Context, key string) error
// Purge empties the trash of the record trashed under key, its versions
// with it.
Purge(ctx context.Context, key string) error
// Tombstones are every record in the trash, in key order.
Tombstones(ctx context.Context) ([]TombstoneValue, error)
}
Trasher is an engine that keeps a trash. A sibling of StoreEngine.
type VersionKeeper ¶ added in v0.31.0
type VersionKeeper interface {
// StoredVersions are the versions of the record under key, newest
// first, the current one first.
StoredVersions(ctx context.Context, key string) ([]VersionValue, error)
// RewriteVersions rewrites the former versions of the record under key
// as fn returns them: fn may drop a version or change what one holds,
// never add or renumber one.
RewriteVersions(ctx context.Context, key string, fn func(vs []VersionValue) ([]VersionValue, error)) error
}
VersionKeeper is an engine that keeps its records' versions. A sibling of StoreEngine.
type VersionValue ¶ added in v0.31.0
type VersionValue struct {
// Number counts a record's versions from 1.
Number uint64
// At is when the write that made the version ran, in UTC.
At time.Time
// Meta is what the write said about it: who made it, which command.
Meta map[string]string
// JSON is the record as the version holds it.
JSON json.RawMessage
}
VersionValue is one version of a record: its number, when the write that made it ran, what that write said about it, and the record as it held it.
type VersionWeightValue ¶ added in v0.31.0
type VersionWeightValue struct {
// Former is how many former versions the store keeps.
Former int
// Trashed is how many records are in the trash.
Trashed int
// Bytes is what the former versions and the trashed records weigh.
Bytes int64
}
VersionWeightValue is what a store keeps beyond the records it holds: its former versions and its trash, counted and weighed.
type VersionWeighter ¶ added in v0.31.0
type VersionWeighter interface {
// VersionWeight is what the store's versions and trash weigh.
VersionWeight(ctx context.Context) (VersionWeightValue, error)
}
VersionWeighter is an engine that says what its records' versions weigh. A sibling of StoreEngine.
type WordsConfig ¶ added in v0.36.0
type WordsConfig struct {
// Open reads and compiles the catalogue of every language after
// English, each falling back to english — kit's own sentences, by
// key, as its core holds them; a catalogue that does not decode or
// does not compile is refused.
Open func(english map[string]string) (Translator, error)
}
WordsConfig is what framework/kit/studio plugs into kit: how kit's catalogues in the languages after English open.
type WorkflowChangeValue ¶ added in v0.34.0
type WorkflowChangeValue struct {
// At is when it happened.
At time.Time
// Entity is the entity, as stored after the transition.
Entity WorkflowEntityValue
// Key is the entity's key.
Key string
// Event is the transition's name; WorkflowCreateEvent for Start.
Event string
// From is the state left, "" on creation.
From string
// To is the state entered.
To string
// Actor is who fired it, "" for the loop.
Actor string
// Trigger is what fired it.
Trigger WorkflowTrigger
}
WorkflowChangeValue is one stored transition: the entity as stored after it, the states it left and entered, what fired it, who and when.
type WorkflowConfig ¶ added in v0.34.0
type WorkflowConfig struct {
// Store is the workflow's entities, as the engine reads and writes them.
Store WorkflowStore
// Journal keeps what the engine knows of each entity — its state, since
// when, its latest transitions —; nil keeps it in memory alone.
Journal WorkflowJournal
// Clock is the app's clock, which the engine stamps and waits on.
Clock Clock
// Actor names, from the context of a transition someone fired, who
// fired it.
Actor func(ctx context.Context) string
// Observe brackets each transition the loop fires: the context it runs
// with, and the function told how it ended.
Observe func(ctx context.Context, f WorkflowFiringValue) (context.Context, func(err error))
// Report receives what the engine reports and no caller's return value
// carries: an OnTransition hook that failed, a panic, a journal's write
// that failed.
Report func(ctx context.Context, err error)
// OnLoop is told each run of the loop, and each wait.
OnLoop func(e WorkflowLoopEventValue)
// Initial is the state Start enters an entity in.
Initial string
// Transitions are the declared transitions, in declaration order.
Transitions []TransitionSpec
// OnEnter are the hooks run as an entity enters a state, in
// declaration order.
OnEnter []EnterHookSpec
// OnTransition are the hooks run after every stored transition, in
// declaration order.
OnTransition []func(ctx context.Context, c WorkflowChangeValue) error
// MinGap is the least a wake for a due transition waits after a run.
MinGap time.Duration
// BackoffBase is the wait after a run that failed, doubled after each,
// up to BackoffMax.
BackoffBase time.Duration
// BackoffMax bounds the wait after a run that failed.
BackoffMax time.Duration
// MaxHistory caps the transitions remembered per entity.
MaxHistory int
}
WorkflowConfig is one workflow as its engine runs it: its states and transitions, its hooks, the store and the journal it runs over, and how the app's loop, clock and spans see it.
type WorkflowDriverConfig ¶ added in v0.34.0
type WorkflowDriverConfig struct {
// Open opens the engine of one workflow, as cfg declares it: it reads
// the journal and every entity of the store once.
Open func(ctx context.Context, cfg *WorkflowConfig) (WorkflowEngine, error)
// Failed reports whether err, or an error it wraps, is the engine's
// failure of kind: the SDK's sentinels stay in the subsystem, and the
// error keeps the fields the engine gave it.
Failed func(err error, kind WorkflowFailure) bool
}
WorkflowDriverConfig is what framework/kit/workflow plugs into kit: how a workflow's engine opens, and how kit tells the engine's failures apart.
type WorkflowEngine ¶ added in v0.34.0
type WorkflowEngine interface {
// Start enters e in the workflow, in the initial state: its OnEnter
// hooks run, then it is inserted in the store.
Start(ctx context.Context, e WorkflowEntityValue) (WorkflowEntityValue, error)
// Fire moves the entity under key along the event's transition leaving
// its state.
Fire(ctx context.Context, key, event string) (WorkflowEntityValue, error)
// Changed tells the engine the entity under key was written.
Changed(ctx context.Context, key string) error
// Deleted tells the engine the entity under key was deleted.
Deleted(ctx context.Context, key string) error
// Census counts the entities per state.
Census() map[string]int
// Records are what the engine knows of each entity.
Records() []WorkflowRecordValue
// Run runs the loop that fires the timers and the guards, until ctx
// ends.
Run(ctx context.Context) error
}
WorkflowEngine is one workflow's engine as kit's core uses it: the transitions code fires, what a write of the store tells it, what it counts and records, and its loop.
type WorkflowEntityValue ¶ added in v0.34.0
type WorkflowEntityValue struct {
// Value is the product's entity.
Value any
// State is the entity's state, spelled.
State string
}
WorkflowEntityValue is one entity as a workflow's engine holds it: the product's, kept as any — the workflow's typed facade asserts it to its type —, and its state as the facade spells it, which the engine reads and sets.
type WorkflowFailure ¶ added in v0.34.0
type WorkflowFailure uint8
WorkflowFailure is a failure of a workflow's engine, as kit words it.
const ( // WorkflowFailureNone is no failure kit words. WorkflowFailureNone WorkflowFailure = iota // WorkflowTransitionRefused is an event that leaves no transition from // the entity's state. WorkflowTransitionRefused // WorkflowEntityMissing is no entity under the key. WorkflowEntityMissing // WorkflowEntityExists is an entity already under the key Start names. WorkflowEntityExists // WorkflowKeyEmpty is an entity whose key is empty. WorkflowKeyEmpty // WorkflowHookFailed is a hook that returned an error, joined to it; // its "hook" and "event" fields name the hook's kind and the event. WorkflowHookFailed // WorkflowHookPanicked is a hook that panicked; its "hook", "panic" and // "stack" fields say which and how. WorkflowHookPanicked // WorkflowHookChangedState is an OnEnter hook that changed the state // it entered. WorkflowHookChangedState // WorkflowHookChangedKey is an OnEnter hook that changed its entity's // key. WorkflowHookChangedKey // WorkflowReentrant is an OnEnter hook that fired its own workflow. WorkflowReentrant // WorkflowStoreFailed is the workflow's store that failed. WorkflowStoreFailed // WorkflowJournalFailed is the workflow's journal that failed. WorkflowJournalFailed // WorkflowFunctionPanicked is a guard or an instant function that // panicked. WorkflowFunctionPanicked // WorkflowLoopPanicked is the loop that panicked. WorkflowLoopPanicked // WorkflowWaitAbandoned is a caller that stopped waiting for its // entity: its context ended. WorkflowWaitAbandoned )
The engine's failures kit tells apart, which it words for the product.
type WorkflowFiringValue ¶ added in v0.34.0
type WorkflowFiringValue struct {
// Key is the entity's key.
Key string
// Event is the transition's name.
Event string
// From is the state it leaves.
From string
// To is the state it enters.
To string
// Trigger is what fires it.
Trigger WorkflowTrigger
}
WorkflowFiringValue is one transition the loop is about to fire: the entity's key, the event, the states it leaves and enters, and its trigger.
type WorkflowJournal ¶ added in v0.34.0
type WorkflowJournal interface {
// Load reads every record the journal kept.
Load(ctx context.Context) ([]WorkflowRecordValue, error)
// Save keeps records, in the transaction ctx carries for a database.
Save(ctx context.Context, records ...WorkflowRecordValue) error
// Delete forgets the records of keys; one already gone is no error.
Delete(ctx context.Context, keys ...string) error
}
WorkflowJournal is the port a workflow's engine keeps what it knows of each entity in: the workflow's file under the data directory, or its table on the database that keeps its store.
type WorkflowLoopEvent ¶ added in v0.34.0
type WorkflowLoopEvent uint8
WorkflowLoopEvent is what a workflow's loop reports.
const ( // WorkflowLoopOther is an event of the loop kit shows nothing of. WorkflowLoopOther WorkflowLoopEvent = iota // WorkflowLoopRunStarted is a run starting: Wake and Started are set. WorkflowLoopRunStarted // WorkflowLoopRunEnded is a run ending: Started, Ended, Next and what // it could not fire, Err, are set. WorkflowLoopRunEnded // WorkflowLoopWaiting is the loop asleep until Next, zero for no // transition due. WorkflowLoopWaiting )
What a workflow's loop reports.
type WorkflowLoopEventValue ¶ added in v0.34.0
type WorkflowLoopEventValue struct {
// Err is what a run could not fire, nil for nothing.
Err error
// Started is when the run started.
Started time.Time
// Ended is when the run ended.
Ended time.Time
// Next is when the loop wakes next, zero for no transition due.
Next time.Time
// Kind is what the event reports.
Kind WorkflowLoopEvent
// Wake is why the run started.
Wake WorkflowWake
}
WorkflowLoopEventValue is what a workflow's loop reports: a run started, a run ended, a wait.
type WorkflowRecordValue ¶ added in v0.34.0
type WorkflowRecordValue struct {
// Entered is when the entity entered its state.
Entered time.Time
// Key is the entity's key.
Key string
// State is the entity's state.
State string
// History are its latest transitions, oldest first.
History []WorkflowStepValue
}
WorkflowRecordValue is what a workflow's engine knows of one entity: its state, since when, and its latest transitions, oldest first.
type WorkflowStepValue ¶ added in v0.34.0
type WorkflowStepValue struct {
// At is when it happened.
At time.Time
// Event is the transition's name.
Event string
// From is the state left, "" on creation.
From string
// To is the state entered.
To string
// Actor is who fired it, "" for the loop.
Actor string
// Trigger is what fired it.
Trigger WorkflowTrigger
}
WorkflowStepValue is one transition of an entity's history: the event, the states it left and entered, what fired it, who and when.
type WorkflowStore ¶ added in v0.34.0
type WorkflowStore interface {
// Key is e's key.
Key(e WorkflowEntityValue) string
// Get reads the entity under key; false when there is none.
Get(ctx context.Context, key string) (WorkflowEntityValue, bool, error)
// Insert writes e unless its key is taken; false when it was.
Insert(ctx context.Context, e WorkflowEntityValue) (bool, error)
// Replace writes e over the entity of its key; false when there was
// none.
Replace(ctx context.Context, e WorkflowEntityValue) (bool, error)
// All yields every entity of the store.
All(ctx context.Context) iter.Seq2[WorkflowEntityValue, error]
}
WorkflowStore is the port a workflow's engine reads and writes its entities through: the workflow's store.
type WorkflowTrigger ¶ added in v0.34.0
type WorkflowTrigger uint8
WorkflowTrigger is what fires a transition.
const ( // WorkflowTriggerStart is a creation, which Start fires. WorkflowTriggerStart WorkflowTrigger = iota // WorkflowTriggerEvent is an event code fires. WorkflowTriggerEvent // WorkflowTriggerDelay is a timer: a duration spent in a state. WorkflowTriggerDelay // WorkflowTriggerDeadline is a timer at an instant the entity carries. WorkflowTriggerDeadline // WorkflowTriggerGuard is a condition on the entity that holds. WorkflowTriggerGuard )
The triggers of a transition.
type WorkflowWake ¶ added in v0.34.0
type WorkflowWake uint8
WorkflowWake is why a run of a workflow's loop started.
const ( // WorkflowWakeStart is the loop's first run. WorkflowWakeStart WorkflowWake = iota // WorkflowWakeDue is a transition coming due. WorkflowWakeDue // WorkflowWakeChange is a write that may have brought one forward. WorkflowWakeChange )
Why a run of a workflow's loop started.
type WriteMode ¶ added in v0.31.0
type WriteMode int
WriteMode says what a write expects to find under the document's key.
const ( // WriteUpsert writes whatever the key holds: a creation or a // replacement. WriteUpsert WriteMode = iota // WriteInsert expects nothing under the key, and is refused otherwise. WriteInsert // WriteReplace expects a document under the key, and is refused // otherwise: never a resurrection. WriteReplace )
The write modes.