Documentation
¶
Overview ¶
Package app — who may call an operation: the principal, the rules and their checks.
Package app — activities: what a daemon's idle stop waits for besides its connections, a notion of the product's own — sessions still open, work still queued.
Package app — the App: the services a product mounts, served by one process.
Package app — the static analysis a product can be given: the platform's analyzer, run in the background in dev (ADR 0147 §1).
Package app — process profiles: what an app does with its process (ADR 0147 §5) — serve, run as a daemon, or run one CLI command — and the singleton lock.
Package app — authentication: the handler that says who calls, and the user it names.
Package app — the catalog of the generic mechanics a node is built from.
Package app — CLI commands: a short command of the product that Main runs once, in the CLI profile, and whose status is the process's.
Package app — commands: an operation that changes something, with one handler.
Package app — the app's options and environments.
Package app — databases: the SQL engines a store can be kept on.
Package app — the interfaces of databases: the engine a connector gives, and what the framework asks of it.
Package app — the decoding of a request into its typed value.
Package app is a framework in which every product is its own diagram.
A product is made of services. A service declares its building blocks as package-level values, through its methods:
var Service = app.NewService("todos", "The todo list.")
var Todos = Service.Store("todos", func(t Todo) string { return t.ID })
var Changes = Service.Topic[ChangeEvent]("changes")
var Lifecycle = Service.Workflow("lifecycle", Todos, func(t *Todo) *Status { return &t.Status }).
Initial(Open).
On("complete", Open, Done).
After("auto-archive", 2*time.Minute, Done, Archived).
OnTransition(announce)
var Complete = Service.Command("complete", complete).
Expose("POST /todos/{id}/complete", app.Anyone())
func complete(ctx context.Context, in ByID) (Todo, error) {
return Lifecycle.Fire(ctx, in.ID, "complete")
}
An App mounts services and runs them as one process:
var App = app.NewApp("todo", todos.Service, activity.Service)
func main() { os.Exit(App.Main(context.Background(), os.Args[1:])) }
The diagram ¶
The values a product declares are also its description. App.Graph returns the product as a model.Graph: every node with the position of its declaration and of the function it runs, the edges that exist by construction, the edges the running product observed — each with its counters — and, in dev, the edges the static analysis found in the code, each with its call sites. In dev the app serves it, live, in the Studio at /_app/.
Building blocks ¶
- Service.Command and Service.Query: the product's operations — a command changes something and runs in one transaction, a query reads. Each is internal until it is exposed: the code that needs it runs it with Command.Dispatch or Query.Ask, which is how one service reaches another. Command.Expose and Query.Expose give it a route, which says who may run it: the operation's permission (Command.Allow) or rule (Command.Authorize), or a marker that it is open on purpose — Anyone, AnyUser. The start refuses an exposure that says none.
- Service.Endpoint: a typed HTTP endpoint, for what HTTP itself is about — a webhook a third party calls. The request is decoded strictly — path, query and header fields by tag, the rest from a JSON body — validated from its `validate` tags, then run through the endpoint's mechanics (RateLimit, RateLimitPerClient, Timeout, Bulkhead). Endpoint.Call runs it in-process; a port calls its implementation (Service.Implement) so.
- Service.Store: a typed, keyed collection, persisted atomically when the app has a data directory, or in a table of the database that keeps it.
- Transact: one transaction — what it writes commits together, what it publishes, mails or dispatches leaves at the commit.
- Service.Topic and Service.Subscribe: asynchronous messages, delivered at least once to every subscription, retried, dead-lettered.
- Service.Workflow: a state machine over a store — event transitions fired by code, timer and guard transitions fired by the daemon's own loop, hooks on entry and after every transition.
- Service.Every and Service.Cron: scheduled jobs.
- Service.Static: a frontend.
- Service.Listen: an inbound port that is not HTTP — a private socket on this machine speaking a versioned contract (pkg/v1/proc/ipc).
- Service.CLI: a short command-line command, run once by App.Main.
The app, the composition root, says where the data lives: Database declares a database on an engine module the product's main imports — github.com/kitsunium/sdk/framework/connectors/postgres and its siblings, the only code that imports a driver — and Keeps which stores it keeps. A service never names a database: its handle is its store, which runs on the SDK's document store over SQL there, a table per store.
Declaring never fails: a mistake is recorded with its position and App.Start reports every one at once (DiagnosticsError).
Modules ¶
A module (NewModule) is a Go module's services, which a product mounts as one — App.With at its defaults, Mount with a Prefix or a Bind. What it declares is qualified with its name: its services are "<module>.<service>", its settings and secrets "<module>.<name>", its routes served under its prefix; a module it Requires is mounted with it, and the modules start first. A mount given Only holds in the environments it names alone — app.Mount(m, app.Only("dev", "staging")).
Processes ¶
An app has a process profile (Profile): a server (the default) serves HTTP; a daemon serves no HTTP, answers on its listeners and may stop when idle (IdleStop) — no connection open and no Service.Activity busy —; a CLI run opens what one command reads, runs it and exits. A command may be the app's default (DefaultCommand: every argument that names no other command is its) and never fail its shell (FailSafe). Singleton keeps one process of an app per machine, SingletonPer one per user, executable or configuration (PerUID, PerExecutable, PerConfigDir, PerEnv), and SocketPer names a listener's socket the same way (SocketPathFor computes it for a client). Stop ends the run of the app a context runs in. A binary (NewBinary) holds process roles — an app each, selected by the leading arguments — which talk only through a declared contract (Binary.Talks).
Running ¶
App.Main understands its commands — serve, graph, healthcheck, config, secrets, migrate — and the environment: <PRODUCT>_ENV (dev serves the Studio; production is the default), <PRODUCT>_ADDR or PORT, <PRODUCT>_DATA_DIR, <PRODUCT>_ALLOWED_HOSTS, <PRODUCT>_LOG_LEVEL. The Studio's pages are the kit tool's, not the product's: in dev a server serves the read-only API the Studio reads, and no route that acts on the product exists. The mechanics underneath — lifecycle, health, scheduler, queue, tracing, logging, validation, resilience, identifiers — are the kitsunium SDK's.
Package app — endpoints: an HTTP route and the operation it serves.
Package app — the errors a product returns to its callers, and their wire mapping.
Package app — exposures: an operation an endpoint serves over HTTP, and who may run it.
Package app — reading a record's former values.
Package app — legal holds: records kept whatever their retention says.
Package app — secondary indexes of a store.
Package app — jobs: scheduled work run by the daemon's loop.
Package app — listeners: inbound ports that are not HTTP, a private socket speaking a versioned contract (ADR 0148).
Package app — loops: work the daemon waits for, woken by time or by events.
Package app — mailers: a durable outbox and the transport that empties it.
Package app — modules: a set of services a product mounts as one.
Package app — the mount of a module: its prefix and its bindings.
Package app — operations: a typed request answered by a typed response.
Package app — the password policy of a store's fields.
Package app — ports: an operation a service needs and does not implement.
Package app — privacy: the framework's own service for holds and the journal.
Package app — erasure: a record's personal data removed as its retention would.
Package app — export: a person's data as the framework gives it back.
Package app — CPU profiles of the running process, for the Studio.
Package app — queries: an operation that reads and changes nothing.
Package app — rate limits on an endpoint, per client.
Package app — records: the product's data as modules and the Studio reach it.
Package app — replacements: a test's substitute for an operation.
Package app — the HTTP request and response an endpoint can reach.
Package app — retention: how long a store keeps its personal data.
Package app — revisions: a record keeps its versions, diffed and restored.
Package app — binaries and their process roles: one executable, several Apps, and the versioned contracts between them (D22).
Package app — scopes: the parts of a singleton's lock or of a socket's path that are only known at the start — the user, the executable, a configuration directory —, so one declaration keeps one process per user, per installed copy or per configuration.
Package app — secrets: the values the product declares and the operator provides.
Package app — where the secrets are kept, per environment.
Package app — services: a bounded context and the building blocks it owns.
Package app — settings: a value the environment gives a service.
Package app — the interfaces of settings: the values a setting holds, and what the framework reads of a declaration.
Package app — frontends: static assets the product serves.
Package app — stores: a typed, keyed collection of entities.
Package app — telemetry: the numbers a product reports, exported on a private socket when the deployment asks for them (ADR 0149).
Package app — topics and subscriptions: asynchronous messages of one type.
Package app — transactions: what a unit of work writes commits together, and what it sends leaves at its commit.
Package app — watches: how a module hears the writes of a product's marked fields.
Package app — workflows: a state machine over the entities of one store.
Index ¶
- Constants
- func After(ctx context.Context, d time.Duration) <-chan time.Time
- func AuthData[D any](ctx context.Context) (D, bool)
- func Bind[Req, Resp any](port *iapp.PortService[Req, Resp], op iapp.Operation[Req, Resp]) interface{ ... }
- func Catalog() []model.Mechanic
- func ClearCookie(ctx context.Context, name string)
- func ClientIP(ctx context.Context) string
- func Fallback[Req, Resp any](op iapp.Operation[Req, Resp]) iapp.PortConfigurer[Req, Resp]
- func HoldSubject(ctx context.Context, reason string, ids ...string) error
- func InMemory() interface{ ... }
- func Irreversible(ctx context.Context, ex MigrationExecutor) error
- func Log(ctx context.Context) logger.Logger
- func Meter(ctx context.Context) metrics.FullMeter
- func Migrations(m ...Migration) interface{ ... }
- func NewID(prefix string) string
- func NewTicker(ctx context.Context, d time.Duration) clock.Ticker
- func Now(ctx context.Context) time.Time
- func RetryIn(d time.Duration, cause error) error
- func ScopeKey(scopes ...Scope) (string, error)
- func SetCookie(ctx context.Context, c *http.Cookie)
- func SocketPathFor(product, service, name string, scopes ...Scope) (string, error)
- func Stop(ctx context.Context) bool
- func Transact(ctx context.Context, fn func(context.Context) error, opts ...TransactOption) error
- func UserAgent(ctx context.Context) string
- func WithUser[D any](ctx context.Context, uid UID, data D) context.Context
- type Activity
- type AnalyzeFunc
- type App
- type AppOption
- func Analyze(on bool) AppOption
- func Analyzer(fn AnalyzeFunc) AppOption
- func Clock(c clock.Timed) AppOption
- func ConfigFiles(fsys fs.FS) AppOption
- func DataDir(dir string) AppOption
- func Database(name string, engine Engine, opts ...DatabaseOption) AppOption
- func DesignDigest(digest string) AppOption
- func Env(env string) AppOption
- func IdleStop(d time.Duration) AppOption
- func Listen(addr string) AppOption
- func Logs(w io.Writer) AppOption
- func Mount(m *Module, opts ...MountOption) AppOption
- func OTLP(opts ...OTLPOption) AppOption
- func Profile(p string) AppOption
- func Replace[Req, Resp any](op iapp.Operation[Req, Resp], fn func(context.Context, Req) (Resp, error)) AppOption
- func SecretStore(store secret.Store) AppOption
- func Set[V any](name string, value V) AppOption
- func Singleton(scope string) AppOption
- func SingletonPer(scopes ...Scope) AppOption
- func Studio(on bool) AppOption
- func Telemetry(path string, gids ...int) AppOption
- type Authenticator
- type Binary
- type Bounce
- type BreakerOption
- type BulkheadOption
- type CLI
- type CLIFunc
- type CLIOption
- type Change
- type Classifier
- type Command
- type CommandOption
- type DatabaseOption
- type DatabaseURL
- type Delay
- type DeliveryOption
- type DiagnosticsError
- type Dialect
- type Edit
- type Empty
- type Endpoint
- type EndpointOption
- type Engine
- type Erasure
- type Error
- type ExposeOption
- type FieldRef
- type Former
- type Frontend
- type Job
- type JobOption
- type Keepable
- type ListenHandler
- type Listener
- type ListenerOption
- type LockWaiter
- type Loop
- type LoopOption
- type Mailer
- type MailerOption
- type Mark
- type Migration
- type MigrationExecutor
- type MigrationStep
- type Module
- type ModulePart
- type MountOption
- type OTLPBatch
- type OTLPFullPolicy
- type OTLPOption
- func OTLPBounds(maxBatches, maxBytes int) OTLPOption
- func OTLPDatabase(name string) OTLPOption
- func OTLPEndpoint(url string) OTLPOption
- func OTLPMaxAge(d time.Duration) OTLPOption
- func OTLPSampleRatio(ratio float64) OTLPOption
- func OTLPSendTimeout(d time.Duration) OTLPOption
- func OTLPSender(send func(ctx context.Context, batch OTLPBatch) error) OTLPOption
- func OTLPWhenFull(p OTLPFullPolicy) OTLPOption
- type Operation
- type OperationOption
- type OverlapPolicy
- type PasswordOption
- type PasswordPolicy
- type PersonalData
- type Port
- type PortOption
- type PortPolicyOption
- func Breaker(failures int, open time.Duration, opts ...BreakerOption) PortPolicyOption
- func Budget(maxTokens int, tokenRatio float64) PortPolicyOption
- func Hedge(delay time.Duration, inFlight int) PortPolicyOption
- func Idempotent() PortPolicyOption
- func Retry(maxAttempts int, delay time.Duration, opts ...RetryOption) PortPolicyOption
- func Throttle(k float64) PortPolicyOption
- type Principal
- type Query
- type QueryOption
- type RateLimitOption
- type Records
- type RetryOption
- type Revision
- type Routine
- type RoutineOption
- type Scope
- type Secret
- type SecretOption
- type Service
- type Setting
- type SettingOption
- type SettingValue
- type StaticOption
- type Stdio
- type Store
- type StoreOption
- func Anonymise[T any](fn func(*T)) StoreOption
- func DeleteAfter[T any, D Delay](delay D, since func(T) (time.Time, bool)) StoreOption
- func DeleteAt[T any](at func(T) (time.Time, bool)) StoreOption
- func DeleteOnErasure() StoreOption
- func EraseAfter[T any, D Delay](delay D, since func(T) (time.Time, bool)) StoreOption
- func EraseAt[T any](at func(T) (time.Time, bool)) StoreOption
- func HeldUntil[T any](until func(T) (time.Time, bool), reason string) StoreOption
- func Index[T any](name string, keys func(T) []string) StoreOption
- func Purpose(text string) StoreOption
- func ReadModel() StoreOption
- func RetentionByProduct(limits string) StoreOption
- func Revisions(n int) StoreOption
- func Unique[T any](name string, key func(T) string) StoreOption
- type Subscription
- type SubscriptionOption
- type SupervisionOption
- type TimeoutOption
- type Tombstone
- type Topic
- type TransactOption
- type UID
- type Violation
- type WaitOption
- type Wake
- type Watch
- type Workflow
- type Written
Constants ¶
const ( // EnvDev serves the Studio, analyzes the source and binds loopback. Only // `kit dev` or an explicit <PRODUCT>_ENV=dev turns it on. EnvDev string = iapp.EnvDev // EnvProduction is the default: no Studio, no source, no analysis. EnvProduction string = iapp.EnvProduction )
const ( // WireInvalid is WireInvalid. WireInvalid string = iapp.WireInvalid // WireNotFound is WireNotFound. WireNotFound string = iapp.WireNotFound // WireConflict is WireConflict. WireConflict string = iapp.WireConflict // WireUnauth is WireUnauth. WireUnauth string = iapp.WireUnauth // WireForbidden is WireForbidden. WireForbidden string = iapp.WireForbidden // WireTooLarge is WireTooLarge. WireTooLarge string = iapp.WireTooLarge // WireUnsupported is WireUnsupported. WireUnsupported string = iapp.WireUnsupported // WireRateLimited is WireRateLimited. WireRateLimited string = iapp.WireRateLimited WireUnavailable string = iapp.WireUnavailable // WireTimeout is WireTimeout. WireTimeout string = iapp.WireTimeout // WireCanceled is WireCanceled. WireCanceled string = iapp.WireCanceled // WireInternal is WireInternal. WireInternal string = iapp.WireInternal // CodeStoreDecode is CodeStoreDecode. CodeStoreDecode errs.Code = iapp.CodeStoreDecode // CodeStoreEncode is CodeStoreEncode. CodeStoreEncode errs.Code = iapp.CodeStoreEncode // CodeStorePersist is CodeStorePersist. CodeStorePersist errs.Code = iapp.CodeStorePersist // CodeStoreLoad is CodeStoreLoad. CodeStoreLoad errs.Code = iapp.CodeStoreLoad // CodeStoreIndex is CodeStoreIndex. CodeStoreIndex errs.Code = iapp.CodeStoreIndex // CodeTopicEncode is CodeTopicEncode. CodeTopicEncode errs.Code = iapp.CodeTopicEncode // CodeTopicPublish is CodeTopicPublish. CodeTopicPublish errs.Code = iapp.CodeTopicPublish // CodeQueueOpen is CodeQueueOpen. CodeQueueOpen errs.Code = iapp.CodeQueueOpen // CodeUndecodable is CodeUndecodable. CodeUndecodable errs.Code = iapp.CodeUndecodable // CodeHandlerPanic is CodeHandlerPanic. CodeHandlerPanic errs.Code = iapp.CodeHandlerPanic // CodeNotMounted is CodeNotMounted. CodeNotMounted errs.Code = iapp.CodeNotMounted // CodeWorkflowLoad is CodeWorkflowLoad. CodeWorkflowLoad errs.Code = iapp.CodeWorkflowLoad // A workflow hook panicked: an OnEnter hook fails its transition with it, // an OnTransition hook is reported and the transition stands. CodeWorkflowHookPanic errs.Code = iapp.CodeWorkflowHookPanic // An OnEnter hook changed the state its entity was entering, or the // entity's key: the transition is refused. CodeWorkflowHookChange errs.Code = iapp.CodeWorkflowHookChange // An OnEnter hook fired its own workflow: refused, where it would wait // for itself. CodeWorkflowReentrant errs.Code = iapp.CodeWorkflowReentrant // CodeAppConfig is CodeAppConfig. CodeAppConfig errs.Code = iapp.CodeAppConfig // CodeAppRunning is CodeAppRunning. CodeAppRunning errs.Code = iapp.CodeAppRunning // CodeAppListen is CodeAppListen. CodeAppListen errs.Code = iapp.CodeAppListen // Mailers. CodeMailConfig errs.Code = iapp.CodeMailConfig // CodeMailEncode is CodeMailEncode. CodeMailEncode errs.Code = iapp.CodeMailEncode // CodeMailQueue is CodeMailQueue. CodeMailQueue errs.Code = iapp.CodeMailQueue // Deprecated: the framework no longer returns it. The outbox is the SDK's mail // spool, which dead-letters a record that does not decode itself // (MessageUndecodable, in pkg/v1/app/mail/spool). CodeMailUndecodable errs.Code = iapp.CodeMailUndecodable // CodeMailPanic is CodeMailPanic. CodeMailPanic errs.Code = iapp.CodeMailPanic // Loops. CodeLoopPanic errs.Code = iapp.CodeLoopPanic // CodeLoopNotMounted is CodeLoopNotMounted. CodeLoopNotMounted errs.Code = iapp.CodeLoopNotMounted // CodeLoopStart is CodeLoopStart. CodeLoopStart errs.Code = iapp.CodeLoopStart // Secrets. CodeSecretStore errs.Code = iapp.CodeSecretStore // CodeSecretMissing is CodeSecretMissing. CodeSecretMissing errs.Code = iapp.CodeSecretMissing // CodeSecretRead is CodeSecretRead. CodeSecretRead errs.Code = iapp.CodeSecretRead // CodeSecretRotate is CodeSecretRotate. CodeSecretRotate errs.Code = iapp.CodeSecretRotate // Databases, ADR 0004. CodeDatabaseOpen errs.Code = iapp.CodeDatabaseOpen // CodeDatabaseMigrate is CodeDatabaseMigrate. CodeDatabaseMigrate errs.Code = iapp.CodeDatabaseMigrate CodeDatabaseUnavailable errs.Code = iapp.CodeDatabaseUnavailable // CodeDatabaseConfig is CodeDatabaseConfig. CodeDatabaseConfig errs.Code = iapp.CodeDatabaseConfig // CodeDatabaseVersion refuses the start of a database whose server is below // the framework's floor: MySQL 8.0.1 or MariaDB 10.6, which lease with SKIP LOCKED. CodeDatabaseVersion errs.Code = iapp.CodeDatabaseVersion // CodeTransactionSpan is CodeTransactionSpan. CodeTransactionSpan errs.Code = iapp.CodeTransactionSpan // Privacy (ADR 0006). CodePrivacyKey errs.Code = iapp.CodePrivacyKey // CodePrivacyErase is CodePrivacyErase. CodePrivacyErase errs.Code = iapp.CodePrivacyErase // CodePrivacyJournal is CodePrivacyJournal. CodePrivacyJournal errs.Code = iapp.CodePrivacyJournal // CodePrivacyData is CodePrivacyData. CodePrivacyData errs.Code = iapp.CodePrivacyData // History (ADR 0007). CodeHistoryLoad errs.Code = iapp.CodeHistoryLoad // CodeHistoryWrite is CodeHistoryWrite. CodeHistoryWrite errs.Code = iapp.CodeHistoryWrite // CodeHistoryRead is CodeHistoryRead. CodeHistoryRead errs.Code = iapp.CodeHistoryRead // CodePasswordHash is CodePasswordHash. CodePasswordHash errs.Code = iapp.CodePasswordHash // Commands and queries. CodeCommandReentrant errs.Code = iapp.CodeCommandReentrant // CodeCommandKey is CodeCommandKey. CodeCommandKey errs.Code = iapp.CodeCommandKey // CodeCommandQueue is CodeCommandQueue. CodeCommandQueue errs.Code = iapp.CodeCommandQueue // CodeCommandEncode is CodeCommandEncode. CodeCommandEncode errs.Code = iapp.CodeCommandEncode // Watches (ADR 0008). CodeWatchQueue errs.Code = iapp.CodeWatchQueue // CodeRecordsKeys refuses [Records].Keys to a caller none of whose module's // watches the store feeds: only a module that watches a store lists its // keys (ADR 0178 C6). CodeRecordsKeys errs.Code = iapp.CodeRecordsKeys // CodeWatchReplay refuses `<product> watch replay WATCH` when WATCH names no // watch of the product: the command replays a watch the product declares, // and nothing else (ADR 0178 C6). CodeWatchReplay errs.Code = iapp.CodeWatchReplay // Sealing at rest (ADR 0006, step 3). CodeSealKey errs.Code = iapp.CodeSealKey // CodeSealWrite is CodeSealWrite. CodeSealWrite errs.Code = iapp.CodeSealWrite // CodeSealOpen is CodeSealOpen. CodeSealOpen errs.Code = iapp.CodeSealOpen // CodeSealRewrap is CodeSealRewrap. CodeSealRewrap errs.Code = iapp.CodeSealRewrap // CodeSealShred is CodeSealShred. CodeSealShred errs.Code = iapp.CodeSealShred // Revisions (ADR 0007 §3). CodeRevisionRead errs.Code = iapp.CodeRevisionRead // CodeRevisionWrite is CodeRevisionWrite. CodeRevisionWrite errs.Code = iapp.CodeRevisionWrite // CodeRevisionDecode is CodeRevisionDecode. CodeRevisionDecode errs.Code = iapp.CodeRevisionDecode // CodeTrash is a store's trash that cannot be read or emptied: what the // product deleted stays in it until a later purge (ADR 0178 C4). CodeTrash errs.Code = iapp.CodeTrash // CodeTrashList refuses the Studio's list of a store's trash (GET // /_app/api/trash) when the store named is none of the product's — a // NotFound — or keeps no trash, having no app.Revisions — an Invalid (ADR // 0178 C4). CodeTrashList errs.Code = iapp.CodeTrashList // The framework's own signals and refusals, typed since the move into the // SDK (rule 2: no fmt.Errorf, no errors.New in production code). CodeJobOverlapped errs.Code = iapp.CodeJobOverlapped // CodeHistoryMoved is CodeHistoryMoved. CodeHistoryMoved errs.Code = iapp.CodeHistoryMoved // CodeNotSource is CodeNotSource. CodeNotSource errs.Code = iapp.CodeNotSource // CodePasswordMoved is CodePasswordMoved. CodePasswordMoved errs.Code = iapp.CodePasswordMoved // CodeNothingToErase is CodeNothingToErase. CodeNothingToErase errs.Code = iapp.CodeNothingToErase // CodeKeyRekeyed is CodeKeyRekeyed. CodeKeyRekeyed errs.Code = iapp.CodeKeyRekeyed // CodeMigrateRefused is CodeMigrateRefused. CodeMigrateRefused errs.Code = iapp.CodeMigrateRefused // CodeCatalogue is CodeCatalogue. CodeCatalogue errs.Code = iapp.CodeCatalogue // CodeRetentionPanic is CodeRetentionPanic. CodeRetentionPanic errs.Code = iapp.CodeRetentionPanic // CodeDataCopy refuses a data copy: a database the product does not declare // or cannot open, data kept in memory, a product that answers on its // address, a table of the database that already holds a row. CodeDataCopy errs.Code = iapp.CodeDataCopy // CodeDataCopyDiverged reports a data copy whose fingerprints differ: the // copy is rolled back, and the first key that differs is named. CodeDataCopyDiverged errs.Code = iapp.CodeDataCopyDiverged // CodeSubsystemMissing refuses a start whose declarations need a subsystem // the program does not import (ADR 0179 §6): the [DiagnosticsError] names // each declaration and the package to import, and carries this code. CodeSubsystemMissing errs.Code = iapp.CodeSubsystemMissing // CodeMigrationIrreversible refuses the Down of a migration declared // irreversible with [Irreversible]: what it changed is undone by a new // forward migration, never by migrate down. CodeMigrationIrreversible errs.Code = iapp.CodeMigrationIrreversible // CodeRenamed refuses a start that meets a runtime name the framework no // longer reads (ADR 0180 §3): a KIT_<NAME> variable of the operator's, a // field tagged kit:"…". The [DiagnosticsError] names each old name and // the one that replaces it, and carries this code. CodeRenamed errs.Code = iapp.CodeRenamed // CodeRenameTarget refuses a start that meets data a former release kept // under the tool's name while its present name is taken too (ADR 0180 // step 5): nothing is moved, and both names are said. CodeRenameTarget errs.Code = iapp.CodeRenameTarget // CodeRenameFailed refuses a start whose move of a name at rest did not // complete (ADR 0180 step 5): what was not moved stays readable under its // former name, and the next start resumes the move. CodeRenameFailed errs.Code = iapp.CodeRenameFailed // CodeRetryIn marks a failure a handler returned through [RetryIn]: its // queue hands the message back with the delay it asked for, the delivery // counted. CodeRetryIn errs.Code = iapp.CodeRetryIn // CodeGaveUp marks a declared loop the framework stopped running: its runs // failed more often than its [GiveUpAfter] allows, and the product is no // longer live until the process restarts. CodeGaveUp errs.Code = iapp.CodeGaveUp // CodeOTLPExport refuses a start whose OTLP export ([OTLP]) cannot be // opened — its queue, its collector's endpoint, its headers —, says a // stop that did not let it flush within its budget, marks a batch the // product's own sender refused for good, and refuses the otlp command // a queue it cannot read or a dead letter it does not hold. CodeOTLPExport errs.Code = iapp.CodeOTLPExport // CodeTransactionNested refuses a Transact inside another that asks for an // isolation level or read-only ([Serializable], [RepeatableRead], // [ReadOnly]): the inner level is a savepoint, which can change neither. CodeTransactionNested errs.Code = iapp.CodeTransactionNested // CodeTransactionReadOnly refuses a store's write inside a transaction // opened with [ReadOnly], on every backend. CodeTransactionReadOnly errs.Code = iapp.CodeTransactionReadOnly // The signals the framework ends one of its own steps with and catches itself — a // caller never receives one —, typed when the SDK made rule 2 a gate. CodeSealErased errs.Code = iapp.CodeSealErased // CodeSealKeyMoved is CodeSealKeyMoved. CodeSealKeyMoved errs.Code = iapp.CodeSealKeyMoved // CodeResealInPlace is CodeResealInPlace. CodeResealInPlace errs.Code = iapp.CodeResealInPlace // CodeResealMoved is CodeResealMoved. CodeResealMoved errs.Code = iapp.CodeResealMoved // CodeWorkflowNotInPlace is CodeWorkflowNotInPlace. CodeWorkflowNotInPlace errs.Code = iapp.CodeWorkflowNotInPlace // CodeTransactionPanic is CodeTransactionPanic. CodeTransactionPanic errs.Code = iapp.CodeTransactionPanic )
const ( // OTLPTraces names the trace signal: an OTLP/JSON // ExportTraceServiceRequest. OTLPTraces string = iapp.OTLPTraces // OTLPMetrics names the metrics signal: an OTLP/JSON // ExportMetricsServiceRequest. OTLPMetrics string = iapp.OTLPMetrics )
The two signals an export forwards, as an OTLPBatch names them.
const CodeCLIFailed errs.Code = iapp.CodeCLIFailed
CodeCLIFailed marks the span of a CLI command that exited non-zero.
const CodeProfileRead errs.Code = iapp.CodeProfileRead
CodeProfileRead reports a profile of the process that could not be written or read back. It is in the framework's 0.4.2.* range.
const CodeScopeUnknown errs.Code = iapp.CodeScopeUnknown
CodeScopeUnknown reports a scope whose value could not be read at the start: no current user, no executable path, no configuration directory.
const CodeSingletonHeld errs.Code = iapp.CodeSingletonHeld
CodeSingletonHeld reports a start refused because another process of the app holds its singleton lock.
const DefaultMaxBody int64 = iapp.DefaultMaxBody
DefaultMaxBody is the largest request body an endpoint reads, unless the endpoint says otherwise with MaxBody.
Variables ¶
This section is empty.
Functions ¶
func AuthData ¶
AuthData returns what the auth handler said about the caller, and whether there is a caller whose data has type D.
func Bind ¶
func Bind[Req, Resp any](port *iapp.PortService[Req, Resp], op iapp.Operation[Req, Resp]) interface { AppOption MountOption }
Bind makes the app's port call op, whatever implements the port and whatever its fallback: an endpoint — or, with ADR 0005, a command or a query — of the port's types. A binding is code, the same in every environment; a binding to a port, or to a service the app does not mount, is refused when the app starts. Given twice for one port, the last wins.
a := app.NewApp("vigie", desk.Service, posts.Service).With(app.Bind(desk.Enforcer, posts.EnforceAPI))
It is an option of Mount too, under the same name: there it binds a port of the module mounted, and another is refused.
a := app.NewApp("shop", posts.Service).With(app.Mount(moderation.Module, app.Bind(moderation.Enforcer, posts.EnforceAPI)))
func Catalog ¶
Catalog lists the generic mechanics the framework offers: the building blocks a node composes rather than implements, each one backed by an SDK package. It is part of every graph, so the Studio — and an AI agent reading the graph — knows what can be added to a product and the exact code that adds it.
func ClearCookie ¶
ClearCookie tells the browser to forget the cookie called name.
func ClientIP ¶
ClientIP returns the address of the client of the request ctx serves: the connection's peer, or — only when <PRODUCT>_TRUST_PROXY=on — the last address of X-Forwarded-For, the one the trusted proxy appended. It is "" outside an HTTP request.
func Fallback ¶
func Fallback[Req, Resp any](op iapp.Operation[Req, Resp]) iapp.PortConfigurer[Req, Resp]
Fallback gives a port an implementation from its own side, which it calls when the app binds nothing else: an endpoint — or, with ADR 0005, a command or a query — of the port's types. A port given here is refused when the app starts.
var Enforcer = Service.Port[Measure, Applied]("enforcer", app.Fallback(QueueAPI))
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func HoldSubject ¶
HoldSubject places a legal hold on every record whose subject is one of ids, in every store of the app: an authority's request about a person. It holds the records they have now; a record written later is not held. reason is kept as Store.Hold keeps it.
func InMemory ¶
func InMemory() interface {
StoreOption
AppOption
}
InMemory keeps data in memory. On an app, it overrides the data directory for every store and queue — <PRODUCT>_DATA_DIR, and a DataDir given before it: what a test wants. On a store, it keeps that store in memory even when the app has a data directory.
func Irreversible ¶
func Irreversible(ctx context.Context, ex MigrationExecutor) error
Irreversible is the Down of a migration that cannot be reversed, said out loud rather than left nil: it refuses, with CodeMigrationIrreversible, and `<product> migrate down` below its version stops there.
func Log ¶
Log returns the app's logger, for the node ctx runs inside. In dev, every record it writes inside a span is also kept beside that span, so the Studio shows a request's logs with its trace.
func Meter ¶ added in v0.54.0
Meter is the product's own meter, for the app ctx runs inside: the counters, gauges and histograms it makes land in the OTLP export's metrics stream, under the app's resource and an instrumentation scope named after the app, collected every otlp-interval beside the framework's own. Without a running export — none declared, the export off, a CLI command, or outside an app — it is a meter that keeps nothing. An instrument is found again by its name and attributes, so a handler may ask for it at each call; its Collect is the export's.
func Migrations ¶
func Migrations(m ...Migration) interface { DatabaseOption ModulePart }
Migrations are migrations, the framework's own [Migration]s (ADR 0179 step 10), run when the database starts (<name>-migrate: start) or by `<product> migrate up`, the framework's own first, each set under its own version table — and so its own lock. On MySQL a DDL statement commits by itself: write one per migration. The store subsystem runs them: a program that declares a database imports framework/app/store, as its engine module does.
Given to Database, they are the product's, under schema_migrations. Given to NewModule, they are the module's (ADR 0008), for the data it keeps outside the framework's stores: run on the database that keeps the module, under <module>_migrations.
func NewID ¶
NewID returns a new identifier with the given prefix: a TypeID, time ordered, like "todo_01k5zq7m3xe8tvbfg0s7zr4w6c". The prefix must be one to sixty-three lower-case letters, with '_' only between two letters; any other prefix is a programming error and panics.
func NewTicker ¶
NewTicker is a ticker of period d on the app's clock, for a loop written by hand (Service.Go): a test's manual clock drives it like every timer the framework runs itself, where a time.Ticker would tick on the wall clock whatever the test does. It panics on a non-positive d, as time.NewTicker does.
func Now ¶
Now returns the app's time: the system clock, or the clock a test gave with Clock. Product code that compares with a deadline reads it rather than time.Now, so that a test's manual clock reaches it.
func RetryIn ¶ added in v0.50.0
RetryIn marks cause as a failure to retry in d, no sooner: returned from the handler of a subscription, a watch or a queued command, it hands the message back to its queue with that delay, in place of the queue's own — half a second after a first failure, doubling, never more than a minute —: a downstream that answered with a Retry-After, a resource that frees at a known instant. The delivery counts as an attempt: a message that used its MaxDeliveries is dead-lettered with cause, the delay unused. A negative d is read as zero.
if resp.StatusCode == http.StatusTooManyRequests {
return app.RetryIn(30*time.Second, errThrottled)
}
cause keeps its own code, reason and words — what a dead letter records — and CodeRetryIn joins its trail; a cause that is no error of the SDK's, or none, is recorded as CodeRetryIn itself. Outside a consumer's handler it is an error like any other.
func ScopeKey ¶
ScopeKey is the name the scopes give in this process: 16 hex digits of the SHA-256 of their values. A client computes the key the daemon computed from the same declaration, and so finds its lock or its socket.
func SetCookie ¶
SetCookie adds a Set-Cookie header to the HTTP response of the endpoint ctx serves. The framework fills what a cookie left zero with safe defaults — Path "/", HttpOnly, SameSite Lax, and Secure outside dev — so a session cookie is hardened unless the code says otherwise. In an in-process Endpoint.Call there is no response: the cookie is dropped.
HttpOnly is always set, and Secure always outside dev (and in dev for SameSite=None, which browsers require): a boolean has no "unset" a default could fill, and the framework chooses the hardened reading. A cookie set more than once in one response keeps its last value, and cookies set before an error are sent with the error — clearing a stale session on a 401 works.
func SocketPathFor ¶
SocketPathFor is the socket of the listener name of service in product — the binary's name for a role of one, else the app's —, placed by default and named after scopes (SocketPer): the one rule, for a client of another process role that does not import the daemon's declarations (D22) — it names the three words and the scopes its contract states. The service is its qualified name for a module's.
func Stop ¶
Stop asks the app ctx runs in to end its run: Run returns as it does on a signal, its stop draining every component — a daemon told "stop" by its client, on its listener, ends itself so. It returns at once, before the stop; it reports false when ctx runs in no app — a handler's, a loop's, a command's context does — or the app does not run.
func Transact ¶
Transact runs fn in one transaction and returns fn's error: nil commits what fn wrote, an error undoes it — a panic too, which then continues.
err := app.Transact(ctx, func(ctx context.Context) error {
if _, err := Cases.Update(ctx, id, closeCase); err != nil {
return err // what this function wrote is undone
}
if err := Decisions.Insert(ctx, d); err != nil {
return err
}
return Changes.Publish(ctx, Closed{ID: id}) // held: queued at the commit
})
A transaction belongs to one database: the one its first store call reaches — at its first call on a database, at its first write on the data directory, which counts as one, memory with it. Inside it, a store of another database is read as usual; writing one is refused (Invalid, CodeTransactionSpan). A Transact inside another is a savepoint: its failure undoes its own writes, and the outer transaction goes on if its caller handles the error.
What leaves the process waits for the outermost commit: a topic's publish, a queued command's dispatch, a mail — whose outbox ID Mailer.Send returns at once —, a watch's notice, the store's write hooks that wake workflows and loops, a workflow's OnTransition hooks. Each is checked when it is made, so a caller's mistake returns to the caller; a rollback drops them, and a savepoint's rollback its own. A publish, a dispatch, a mail or a notice whose queue lives on the transaction's database — the one that keeps the service of its subscription, command, mailer or watch, by a store's rules — is written in the transaction, just before it commits, a mail sealed under the framework's data-key: a queue that refuses it fails the transaction, every write undone, and Transact returns the refusal. Every other one leaves after the commit: one a queue refuses then is logged and reported, and the commit stands; a process that dies between the commit and the release loses what was held.
On a database the transaction is the database's own, at its default isolation unless opts ask for another: Serializable or RepeatableRead opens it at that level, ReadOnly tells the database it only reads, and a store's write inside it is refused (Invalid, CodeTransactionReadOnly) on every backend. Options go on the outermost Transact: a nested one given any is refused (Invalid, CodeTransactionNested), its savepoint able to change neither. On the data directory and in memory the framework keeps its own: it takes the data's writer turn — one transaction at a time; a write outside any waits for it, and such writes share the turn among themselves —, its writes land at once, and an error writes each entity's previous value back, newest first. It is atomic against an error, not against a crash, and a reader may see a write before its commit. A store kept in memory by InMemory — a cache — is in no transaction: its writes land and stay.
A command's handler runs in one already (NoTransaction opts out), and so does a workflow's transition.
Types ¶
type Activity ¶
type Activity = iapp.ActivityHandler
Activity is a declared activity of a service: a function that says whether the product is busy. A daemon's IdleStop waits until every activity of its mounted services says false AND no connection is open on its listeners.
type AnalyzeFunc ¶
type AnalyzeFunc = iapp.AnalyzeFunc
AnalyzeFunc reads the product's source — the Go module rooted at dir, and the packages that declare the modules it mounts — into a graph the runtime merges into its own: the edges found in handler bodies, each function's steps. The framework links no analyzer (ADR 0147 §1): the platform's former runtime tool gives one, in dev, through Analyzer.
type App ¶
App is the whole product: the services it mounts, served by one process. The same services can be mounted by several apps — one binary per service, or all of them in one — and each app draws exactly what it runs.
type AppOption ¶
type AppOption = iapp.AppConfigurer
AppOption configures an app. Options win over the environment.
func Analyzer ¶
func Analyzer(fn AnalyzeFunc) AppOption
Analyzer runs fn in the background once the product serves, in dev and when KIT_ANALYZE allows it. Without one, the graph is the runtime's alone.
func Clock ¶
Clock makes the app read and wait on c instead of the system clock: a test drives timer transitions and jobs with a clock.ManualClock.
func ConfigFiles ¶
ConfigFiles gives the framework the product's configuration files: config/config.<ext>, which every environment reads, and config/<env>.<ext>, the environment's own — <env> being <PRODUCT>_ENV as written, dev when kit dev runs the product — in JSON, YAML or TOML (json, yaml or yml, toml). A file maps the names of the settings to their values; it never holds a secret, and a key no service declares stops the start. The files belong in the binary:
//go:embed config
var configFiles embed.FS
a := app.NewApp("todo", ...).With(app.ConfigFiles(configFiles))
func DataDir ¶
DataDir sets where stores and queues persist, instead of <PRODUCT>_DATA_DIR. Given to an app after InMemory, it wins: the last of the two says where the data is — so a test helper that runs the product in memory runs it on disk with the one option its test gives (apptest.NewDisk).
func Database ¶
func Database(name string, engine Engine, opts ...DatabaseOption) AppOption
Database declares a database the product keeps its stores in, named name, on engine — an engine module's, which the product's main imports:
import (
"github.com/kitsunium/sdk/framework/connectors/postgres"
"github.com/kitsunium/sdk/framework/connectors/sqlite"
)
var App = app.NewApp("vigie", intake.Service, desk.Service, audit.Service).With(
// Keeps every store no other database keeps.
app.Database("database", postgres.Engine()),
// The audit trail apart.
app.Database("archive", sqlite.Engine(), app.Keeps(audit.Service)),
)
name is 1 to 49 lower-case letters, digits and dashes, not starting with "app-" nor "kit-", unique among the app's databases. It names the database's URL, the secret <name>-url — the variable <APP>_<NAME>_URL, or <APP>_<NAME>_URL_FILE naming a file that holds it, then the environment's secret store —, and its settings: <name>-max-open (10), <name>-max-idle (2), <name>-max-lifetime (30m), <name>-max-idle-time (0: none), <name>-timeout (5s), <name>-check-timeout (5s), <name>-tx-retries (3: how many times a transaction the database asks to run again runs again, 0 for never — Classifier), <name>-tx-retry-delay (50ms: the first wait before it does) and <name>-migrate (start, or manual). Outside dev the URL is required and writes its TLS mode; in dev a database without one leaves its stores in the data directory, and a SQLite database without one is the file <data>/<name>.sqlite. InMemory on the app opens none.
func DesignDigest ¶
DesignDigest records the digest of the design the product's code was generated from — what the generated wiring passes —, so the telemetry handshake can say it and a tool attached to the product can tell a process built from another design.
func IdleStop ¶
IdleStop makes a daemon stop itself once, for d, no connection was open on any of its listeners and no activity of its services (Service.Activity) said it was busy: a daemon launched on demand by its clients ends when they stop coming. It is refused outside the daemon profile.
func Listen ¶
Listen sets the listening address, instead of <PRODUCT>_ADDR or PORT. ":0" picks a free port; App.URL tells which.
func Mount ¶
func Mount(m *Module, opts ...MountOption) AppOption
Mount mounts module m with options: Prefix serves its routes elsewhere than "/<module>/", Bind chooses what one of its ports calls.
a := app.NewApp("vigie", identity.Service).
With(app.Mount(moderation.Module, app.Prefix("/"), app.Bind(moderation.Enforcer, posts.EnforceAPI)))
A module is mounted once per app: mounted again, its prefix is the last one given, and its bindings join the others, the last of a port winning.
func OTLP ¶ added in v0.52.0
func OTLP(opts ...OTLPOption) AppOption
OTLP declares that the app forwards its traces and the metrics the framework derives from them to an OpenTelemetry collector over OTLP/HTTP: the spans the framework starts — the share otlp-sample-ratio keeps —, and per node and operation its runs, failures and durations (app.node.runs, app.node.failures, app.node.duration), with what the export itself holds and lost (app.otlp.*) and the product's own instruments (Meter). The export is on once its endpoint is set — the setting otlp-endpoint, OTLPEndpoint its default — or once OTLPSender replaces the network; a CLI command never exports. A program that declares it imports framework/app/otlp, or its start is refused, naming the import:
import _ "github.com/kitsunium/sdk/framework/app/otlp"
var App = app.NewApp("shop", catalog.Service).With(
app.OTLP(app.OTLPEndpoint("http://collector:4318")),
)
Every value given here is the default of the setting that tunes it, which config/<env>.* and <PRODUCT>_OTLP_<KNOB> override. Given twice, the last wins.
func Profile ¶
Profile selects the app's process profile: model.ProfileServer (the default), model.ProfileDaemon or model.ProfileCLI.
func Replace ¶
func Replace[Req, Resp any](op iapp.Operation[Req, Resp], fn func(context.Context, Req) (Resp, error)) AppOption
Replace runs fn in place of op's code, in the app it is given to: an endpoint's handler — or, with ADR 0005, a command's or a query's — or what a port calls. It replaces the code, not the mechanics: authentication, decoding, validation and the policies still run, and a replaced port needs no binding, so a module's tests run without a host. fn takes op's request and returns its response, or it does not compile.
A replaced run's span carries mock: replace, and runtime.mocks lists the replacement. It is for tests: the start refuses it in a program go test did not build — neither a production binary nor kit dev can carry one. Given twice for one operation, the last wins.
app := App.With(app.Replace(apps.AppAPI, func(ctx context.Context, in apps.IDInput) (apps.Profile, error) {
return apps.Profile{ID: in.AppID}, nil
}))
func SecretStore ¶
SecretStore keeps the secrets in store instead of the environment's: a test gives a store holding what its provided secrets hold. The environment's variables are still read first.
func Set ¶
Set gives the setting name a value in code, over the environment and the files: a value of the setting's type, or its text as a variable would hold it. It is for tests.
func Singleton ¶
Singleton keeps one process of the app alive per scope on this machine: the start takes an exclusive file lock named after scope in the app's runtime directory (pkg/v1/app/lock: flock, LockFileEx) and holds it until the process ends. A second process refuses to start with CodeSingletonHeld — for a daemon's client, the sign to talk to the one that runs. The kernel drops the lock with a dead process.
func SingletonPer ¶
SingletonPer keeps one process of the app alive per value of scopes on this machine — per user, per installed executable, per configuration directory (PerUID, PerExecutable, PerConfigDir, PerEnv) —: the lock is named after the scopes' key (ScopeKey), computed at the start, and held as Singleton's is. A client that must find the process computes the same key from the same scopes.
type Authenticator ¶
type Authenticator[P, D any] = iapp.AuthenticatorHandler[P, D]
Authenticator is the app's authentication handler: it turns the credentials of a request — a session cookie, a bearer token — into a user, in front of every endpoint declared with Auth or AuthOptional. An app has at most one.
P is the credentials: a struct whose fields are tagged cookie:"…" or header:"…", decoded like an endpoint's request. D is what the handler says about the user; endpoints read it with AuthData.
type Binary ¶
Binary is one executable the product ships, made of process roles: a status line and its daemon are two roles of one binary, "statusline" and "statusline daemon". Each role is an App — its own services, its own profile — and two roles talk only through a declared, versioned contract (D22): a listener one serves and the other dials, never each other's code.
var Binary = app.NewBinary("statusline", "The status line of a Claude session.").
Role("render", RenderApp). // statusline ...
Role("daemon", DaemonApp, "daemon"). // statusline daemon ...
Talks("render", "daemon", "render/v1")
func main() { os.Exit(Binary.Main(context.Background(), os.Args[1:])) }
The package that declares a binary and its roles is wiring, generated from the design (D22).
type Bounce ¶ added in v0.47.0
type Bounce = iapp.BounceEvent
Bounce is a mail its mailer gave up on: the receiving server refused it for good, it outlived its mailer's max-age, or its last attempt failed — GivenUp says which. It stays in the outbox as a dead letter.
Reply is the receiving server's own answer: the hook may read it, log it or act on it, but the framework never puts it in a message it shows — the Studio's mailbox keeps its code alone.
type BreakerOption ¶ added in v0.49.0
type BreakerOption = iapp.BreakerConfigurer
BreakerOption configures a Breaker.
func BreakerWindow ¶ added in v0.49.0
func BreakerWindow(size time.Duration, minCalls int, failureRatio float64) BreakerOption
BreakerWindow makes a Breaker open on a rate rather than on failures in a row: once the last size of calls holds at least minCalls, a share of failures of failureRatio or more opens it. Its values are the defaults of the port's settings <service>-port-<name>-breaker-window, -breaker-window-calls and -breaker-window-ratio; a window of 0 is none, a ratio outside (0, 1] stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func HalfOpenTrials ¶ added in v0.49.0
func HalfOpenTrials(n int) BreakerOption
HalfOpenTrials is how many trial calls in a row must succeed to close a Breaker once its open time is over — one by default. It is the default of the port's setting <service>-port-<name>-breaker-trials; fewer than one stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func OpenBackoff ¶ added in v0.49.0
func OpenBackoff(maxOpen time.Duration) BreakerOption
OpenBackoff lengthens the open time of a Breaker that opens again without having closed: it doubles at each opening, from the breaker's open time up to max. It is the default of the port's setting <service>-port-<name>-breaker-open-max, 0 — the same open time every time — without it; a negative one stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type BulkheadOption ¶ added in v0.48.0
type BulkheadOption = iapp.BulkheadConfigurer
BulkheadOption configures a Bulkhead.
func BulkheadQueue ¶ added in v0.48.0
func BulkheadQueue(n int) BulkheadOption
BulkheadQueue lets up to n calls beyond those a Bulkhead runs wait for a slot, each for its MaxWait: without a wait, or with n at 0, the overflow is refused at once, and a negative n stops the start. A call that finds the queue full answers 503. It is the default of the operation's setting <service>-<kind>-<operation>-bulkhead-queue, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type CLI ¶
CLI is a short command-line command of the product: it runs once, in the CLI profile, and exits with its status. Main runs it when the process's first argument is its name.
type CLIFunc ¶
CLIFunc is a CLI command's body: its arguments after its name, and the streams; it returns the process exit status (0 success, 64 usage, 70 software — the sysexits a shell script branches on).
type CLIOption ¶
type CLIOption = iapp.CommandLineConfigurer
CLIOption tunes a CLI command.
func DefaultCommand ¶
func DefaultCommand() CLIOption
DefaultCommand makes the command Main's default: it runs with every argument when the first names no other command — neither one of the product's nor one of Main's (serve, help…) —, and with none when there is none. Main then never answers a usage error. One command of an app may be its default.
IFACE-OPAQUE: CLIOption is sealed — its one method is unexported — so only this package makes one, and a caller only passes it to CLI.
func FailSafe ¶
func FailSafe() CLIOption
FailSafe makes the command's status always 0: a status line, a prompt hook, anything a shell runs on every keystroke must never fail the shell. A non-zero status, a start that fails and a panic are logged instead.
IFACE-OPAQUE: CLIOption is sealed — its one method is unexported — so only this package makes one, and a caller only passes it to CLI.
type Change ¶
type Change[E any, S comparable] = iapp.ChangeEvent[E, S]
Change describes one transition, for Workflow.OnTransition hooks: the entity, the event, and the states it left and entered.
type Classifier ¶ added in v0.59.0
type Classifier = iapp.Classifier
Classifier is an Engine that reads its driver's errors: Transient says whether a failed transaction is one the database asks to run again. The framework runs such a transaction again, its outermost level, up to <name>-tx-retries times — never one a Service.Go body opens.
type Command ¶
Command changes something: a typed input, a typed result, and one handler — the one declared with it. Declare it with Service.Command; dispatch it with Command.Dispatch from any building block, which draws a dispatches edge from the caller; give it a route with Command.Expose.
A dispatch runs, in this order: the caller's user when the command asks for one (Auth, implied by Command.Allow) — an in-process dispatch carries its caller's and is not authenticated again —, the input's validate tags, the policies (RateLimit, RateLimitPerClient, Timeout, Bulkhead), the key (Command.Key), the authorization (Command.Allow, then Command.Authorize), then the handler. A queued command (Queued) is checked at its dispatch, as its caller — its validate tags, its authorization, its key —, and handled by its queue's consumer, the policies around the handling.
ADR 0004's step 2 makes a command its unit of work: its authorization and its handler will run in one transaction, which holds its effects until the commit. Until then, a command's writes and effects are made as the handler makes them.
type CommandOption ¶
type CommandOption = iapp.CommandConfigurer
CommandOption configures a command: Queued; the options every operation takes — Auth, AuthOptional, RateLimit, RateLimitPerClient, Timeout, Bulkhead; and, for a queued one, MaxDeliveries and Parallelism.
func NoTransaction ¶
func NoTransaction() CommandOption
NoTransaction runs a command outside a transaction of its own: its writes land as its handler makes them, and its effects leave when made — a failed command may have written or announced something. On the data directory and in memory, where a writing command's transaction takes the writer turn, it lets such commands run side by side. Dispatched inside another command, it still runs in that one's transaction.
func Queued ¶
func Queued() CommandOption
Queued sends a command to the background. Dispatch returns once the command's own queue accepted it — a file queue under the data directory, memory without one —, and a consumer handles it, Parallelism at a time, retried up to MaxDeliveries attempts (5) — half a second after the first failure, the wait doubling after each, never more than a minute —, then dead-lettered; a dispatch that does not decode is dead-lettered at its first failure, since no retry makes it decode. It answers nothing: its result is Empty, and exposed, it answers 202 Accepted.
Delivery is at least once: Queued is the product's promise that the handler tolerates a redelivery, and a Command.Key narrows the duplicates without removing them. The handler runs in the dispatcher's trace, as the user who dispatched it (UserID); what the auth handler said about that user is not queued. A queued command's input is a contract with the messages already queued: add a field, never rename one.
type DatabaseOption ¶
type DatabaseOption = iapp.DatabaseConfigurer
DatabaseOption configures a database: Keeps, Migrations.
func Keeps ¶
func Keeps(things ...Keepable) DatabaseOption
Keeps says what the database keeps: a service's stores, a store, a module's stores. The most precise wins: a store kept by name, then its service, then its module, then the default database — the one declared without Keeps —, then the data directory, then memory. InMemory wins over all of them, on the app as on a store.
type DatabaseURL ¶
type DatabaseURL = iapp.DatabaseURLValue
DatabaseURL is what a database's URL points at, as its engine describes it for the graph, the Studio, the logs and every error: never a user, never a password, never a parameter.
type Delay ¶
Delay is how long a timer transition waits: a duration, or a setting that holds one — read when the delay is needed, so each environment can give its own.
type DeliveryOption ¶
type DeliveryOption = iapp.DeliveryOption
DeliveryOption configures a queue's deliveries: a subscription's, or a queued command's (MaxDeliveries, Parallelism).
func AutoExtend ¶ added in v0.50.0
func AutoExtend(on bool) DeliveryOption
AutoExtend says whether the lease of the message a handler is running is renewed, a third of the lease after it was granted or last renewed, for as long as the handler runs — a subscription's, a watch's, or a queued command's. It is on by default: a slow handler keeps its message instead of seeing it delivered to another while it runs. Off, the handler is stopped a margin before its Lease ends. A renewal the queue refuses cancels the handler's context. A mailer's outbox never renews: the mail spool parks a mail by its own lease.
on is the default of the consumer's setting <service>-<kind>-<name>-auto-extend, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Drain ¶ added in v0.50.0
func Drain(d time.Duration) DeliveryOption
Drain is how long the message a handler is running when the app stops may still run before its context is cancelled — a subscription's, a watch's, or a queued command's. A handler that finishes within it is acknowledged; one it cuts short is handed back uncounted, delivered again at the next start, and is no failure. The default is 5 seconds; zero cancels the handler at once, and a negative one stops the start. The app's stop gives each component the longest drain plus its settle (Settle), and tells every consumer at once, so that their drains overlap.
d is the default of the consumer's setting <service>-<kind>-<name>-drain, the kind subscription or command, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Lease ¶ added in v0.50.0
func Lease(d time.Duration) DeliveryOption
Lease is how long a delivered message is held by its consumer before the queue hands it to another — a subscription's, a watch's, or a queued command's. The default is 30 seconds; one that is not positive stops the start. With AutoExtend, a handler that runs longer keeps it.
d is the default of the consumer's setting <service>-<kind>-<name>-lease, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func MaxDeliveries ¶
func MaxDeliveries(n int) DeliveryOption
MaxDeliveries is how many attempts a message gets before it is dead-lettered — a subscription's, or a queued command's. The default is 5.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Parallelism ¶
func Parallelism(n int) DeliveryOption
Parallelism is how many messages are handled at once — a subscription's, or a queued command's. The default is 1.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Settle ¶ added in v0.50.0
func Settle(d time.Duration) DeliveryOption
Settle bounds each outcome a consumer sends once the app began to stop — an acknowledgement, a nack, a message handed back — and each renewal of a lease (AutoExtend): a queue that stopped answering cannot hold the stop. The default is 5 seconds; one that is not positive stops the start.
d is the default of the consumer's setting <service>-<kind>-<name>-settle, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type DiagnosticsError ¶
type DiagnosticsError = iapp.DiagnosticsError
DiagnosticsError is returned by Start when declarations are wrong. It lists every problem at once, each with its position.
type Dialect ¶
Dialect is the SQL an Engine speaks: DialectPostgres, DialectMySQL or DialectSQLite, the framework's own names (ADR 0179 Q5) — the graph names the engine by it.
const ( // DialectPostgres is PostgreSQL. DialectPostgres Dialect = iapp.DialectPostgres // DialectMySQL is MySQL or MariaDB. DialectMySQL Dialect = iapp.DialectMySQL // DialectSQLite is SQLite. DialectSQLite Dialect = iapp.DialectSQLite )
The SQL dialects an Engine speaks: the framework's own names (ADR 0179 Q5), which the store subsystem maps onto the SDK's.
type Edit ¶
Edit is one change between two versions of a record, in RFC 6902's words: Op is add, remove or replace, Path the RFC 6901 JSON pointer of the member it changes, From the value it had and To the value it has, as JSON. A secret member says it changed, never what: its From and To are empty.
type Empty ¶
type Empty = iapp.EmptyValue
Empty is the request or the response of an endpoint that has none. An endpoint answering EmptyValue replies 204 No Content.
type Endpoint ¶
type Endpoint[Req, Resp any] = iapp.EndpointService[Req, Resp]
Endpoint is an HTTP endpoint with a typed request and a typed response. Declare it with Service.Endpoint; call it from another service with Endpoint.Call, which is how the diagram sees service-to-service calls.
type EndpointOption ¶
type EndpointOption = iapp.EndpointConfigurer
EndpointOption configures an endpoint.
func MaxBody ¶
func MaxBody(bytes int64) EndpointOption
MaxBody bounds the request body the endpoint reads. The default is DefaultMaxBody.
func Name ¶
func Name(name string) EndpointOption
Name overrides the endpoint's name, which otherwise is its handler's function name, or its route when the handler is a function literal.
type Engine ¶
Engine is an SQL engine a database runs on. An engine module returns one — github.com/kitsunium/sdk/framework/connectors/postgres, …/mysql, …/sqlite —; the framework calls it when the database starts. Like an SDK port, it grows by sibling interfaces, never by a method.
type Erasure ¶
Erasure is what app.Erase did, store by store.
func Erase ¶
Erase erases every record whose subject is one of ids, in every store of the app, as its retention would — or deletes it where the store says app.DeleteOnErasure — and folds the stores it wrote, so that what it overwrote leaves their files. A held record is left in place, and the result says so: it lists, per store, what was erased, deleted and held. Telling the recipients (GDPR art. 19) is the product's job; the register lists them. reason is journaled.
Once sealing lands (ADR 0006, step 3), an erasure also moves the held records under keys of their own and destroys the subject's data key, so that it reaches every copy the framework sealed.
type Error ¶
Error is an error a product returns to its callers. Message travels on the wire; the cause attached with Error.Wrap is logged and never sent.
Return one from a handler to choose the HTTP status and the message the caller reads. Any other error becomes a 500 whose body says nothing about it: an error message is the classic place a secret leaks from.
func Unauthenticated ¶
Unauthenticated reports a caller who did not prove who they are (401).
func Unavailable ¶
Unavailable reports a transient failure worth retrying later (503).
type ExposeOption ¶
type ExposeOption = iapp.ExposeConfigurer
ExposeConfigurer configures an exposure (Command.Expose, Query.Expose): every EndpointOption — Name, MaxBody, RateLimitPerClient… — and the markers that say who may run an operation declaring no rule of its own: Anyone, AnyUser.
func AnyUser ¶
func AnyUser() ExposeOption
AnyUser says that an exposure is open to any signed-in user, on purpose: its operation asks for a user (Auth) and declares no permission and no rule — its handler reads UserID and keeps to what that user owns.
var MyOrders = Service.Query("my-orders", myOrders, app.Auth()).Expose("GET /orders", app.AnyUser())
It adds no authentication of its own: an exposure authenticates as its operation asks, so the operation declares Auth.
func Anyone ¶
func Anyone() ExposeOption
Anyone says that an exposure is open to everyone, on purpose: its operation declares no permission and no rule, and whoever reaches the route may run it — a public form, say. It says so on the exposure's node, where the diagram and the API page read it. An exposure whose operation declares no rule refuses the start unless it says this, or AnyUser.
var Report = Service.Command("report", file).Expose("POST /reports", app.Anyone())
It adds no authentication: an operation that asks for a user (Auth) takes AnyUser instead, and one with AuthOptional still knows the caller who signed in.
type FieldRef ¶
type FieldRef = iapp.FieldRefValue
FieldRef is one field of one store that carries a mark: where the field is, and what its tag says of it.
type Former ¶
Former is one former value of a field that keeps its history: what it was, until when, and who replaced it.
type Frontend ¶
Frontend is static assets the product serves: a single page application, a documentation site. Requests the page makes to the product's endpoints are attributed to it in the diagram.
type Job ¶
Job is scheduled work: a piece of the daemon's internal loop. It runs on the SDK scheduler, whose decisions about time are documented rather than emergent: a fire that is due while the previous run of the same job is still going is skipped and counted, and a missed deadline is skipped and counted, never caught up.
type JobOption ¶ added in v0.51.0
type JobOption = iapp.JobConfigurer
JobOption configures a job (Service.Every, Service.Cron): Overlap, StartingDeadline.
func Overlap ¶ added in v0.51.0
func Overlap(p OverlapPolicy) JobOption
Overlap says what a fire of the job does while its previous run is still going: OverlapSkip, the default, skips it and counts it; OverlapAllow runs it beside; OverlapReplace cancels the previous run's context and runs it once that run returned. Any other word stops the start.
p is the default of the job's setting <service>-job-<name>-overlap, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func StartingDeadline ¶ added in v0.51.0
StartingDeadline bounds how late a fire of the job may still start: a scheduler that comes to a fire more than d after its instant — a machine that slept, a run that held the slot — does not run it, and counts it missed, as Kubernetes' startingDeadlineSeconds does. The default, zero, is no bound: the latest fire missed runs however late, never more than one. A negative d stops the start.
d is the default of the job's setting <service>-job-<name>-starting-deadline, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type Keepable ¶
Keepable is what a database keeps: a service — every store it declares —, a store, or a module (ADR 0008) — every store of its services.
type ListenHandler ¶
type ListenHandler = iapp.ListenHandler
ListenHandler serves one connection of a Listener until it returns; the connection is closed after it. conn.Peer says who connected, as the kernel says where it can (pkg/v1/proc/ipc).
type Listener ¶
Listener is an inbound port that is not HTTP: a private socket on this machine — a Unix socket in a directory only the product's account can reach, the kernel naming the peer on Linux (ADR 0148) — speaking a versioned contract. It is how a daemon profile serves its clients, and how two process roles of one binary talk (D22): through the contract, never through each other's code.
type ListenerOption ¶
type ListenerOption = iapp.ListenerConfigurer
ListenerOption tunes a listener.
func AllowPeers ¶
func AllowPeers(uids, gids []int) ListenerOption
AllowPeers admits accounts besides the product's own: an on-call group declared at deployment. The kernel checks them where it names the peer; the socket's directory must still let them through, which is the deployment's to arrange.
IFACE-OPAQUE: ListenerOption is sealed — its one method is unexported — so only this package makes one, and a caller only passes it to Listen.
func SocketPath ¶
func SocketPath(path string) ListenerOption
SocketPath places the listener's socket at path — absolute, at most 103 bytes — instead of <runtime dir of the app>/<service>-<name>.sock.
IFACE-OPAQUE: ListenerOption is sealed — its one method is unexported — so only this package makes one, and a caller only passes it to Listen.
func SocketPer ¶
func SocketPer(scopes ...Scope) ListenerOption
SocketPer names the listener's socket after the value of scopes in this process — <runtime dir of the app>/<service>-<name>-<key>.sock, the key being ScopeKey's —: one daemon per user, per executable, per configuration directory. A client finds it with SocketPathIn or DialIn, which compute the same key from the same declaration.
IFACE-OPAQUE: ListenerOption is sealed — its one method is unexported — so only this package makes one, and a caller only passes it to Listen.
type LockWaiter ¶
type LockWaiter = iapp.LockWaiter
LockWaiter is an Engine whose connections wait a bounded time for a lock another connection holds — SQLite's busy timeout —, a sibling of Engine (ADR 0178 C2). The framework opens such an engine's pool with OpenWaiting instead of Open, and gives it a wait under <name>-timeout, so that a lost race on the lock comes back as the engine's refusal before the call's own deadline. An engine that does not implement it keeps its own wait.
type Loop ¶
Loop is a declared loop of the daemon: the framework owns the wait, the product owns the work. Its wake sources — a period, a deadline the product computes, a topic — are data, so the diagram draws exactly what wakes it; the framework runs it on its own goroutine, one run at a time, observes every run, and restarts it after a panic.
type LoopOption ¶
type LoopOption = iapp.LoopConfigurer
LoopOption configures a declared loop.
func WakeAt ¶
WakeAt wakes the loop at the time next returns, asked again after every run; false means "no deadline for now". It is how a loop sleeps exactly until its next piece of work — the next reminder due — rather than polling.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func WakeEvery ¶
func WakeEvery(d time.Duration) LoopOption
WakeEvery wakes the loop every d.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func WakeOn ¶
func WakeOn[T any](topic *iapp.TopicService[T]) LoopOption
WakeOn wakes the loop whenever a message is published on topic. It is a nudge, not a subscription: the loop is not handed the message and wakes once for a burst — it re-reads the state it works on.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type Mailer ¶
Mailer is outbound mail: a durable outbox and the transport that empties it. Mailer.Send only queues — it returns once the message is safely in the outbox — and the mailer's own loop hands each message to the transport, retrying a failure and dead-lettering a message after its last attempt.
The transport is the SDK's mail package: SMTP when the mail connector's secret smtp-url is set — <PRODUCT>_SMTP_URL, smtp://user:password@host:587?tls= starttls|implicit|none — and otherwise the capture transport, which keeps every message for the Studio's mailbox and for tests (Mailer.Captured) and delivers nothing. Outside dev, the capture transport is reported as a warning. The URL is read again before every delivery: replacing it where it lives — a new version in the store, a new file behind <PRODUCT>_SMTP_URL_FILE — takes effect at the next mail. The outbox and the transports are the SDK's, which the mail subsystem plugs in (framework/app/mail, ADR 0179 step 6).
type MailerOption ¶
type MailerOption = iapp.MailerConfigurer
MailerOption configures a mailer.
func From ¶
func From(name, addr string) MailerOption
From sets the sender of every message that names none.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func MailAttempts ¶
func MailAttempts(n int) MailerOption
MailAttempts is how many deliveries a message gets before it is dead-lettered. The default is 6, backing off from one second.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func MailMaxAge ¶ added in v0.47.0
func MailMaxAge(d time.Duration) MailerOption
MailMaxAge is how long after it was queued a mail may still be retried: an attempt that fails later gives it up, as expired, whatever attempts it had left. It is the default of the mailer's setting <mailer>-max-age, which config/<env>.* and <PRODUCT>_<MAILER>_MAX_AGE override; 0 sets no age. The default is 5 days (RFC 5321 §4.5.4.1).
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func OnBounce ¶ added in v0.47.0
func OnBounce(fn func(ctx context.Context, b *Bounce)) MailerOption
OnBounce replaces what the mailer does with a mail it gives up — by default, it logs it as an error naming why — with fn: mark an address undeliverable, tell an operator, send it another way. fn runs on a goroutine of its own once the mailbox is updated — the outbox goes on meanwhile, and fn may send mail —, with a context on the mailer's node that continues the trace of the Send; the mailer's stop waits for it. A panic in fn is logged and changes nothing else. A nil fn keeps the framework's own.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type Mark ¶
Mark is what a module looks for in the product's fields: app.Personal, app.Special or app.Moderated. There is no mark for public or secret: there is nothing to find in the first, and nothing may watch the second.
const ( // Personal marks a field that holds data about a person: personal, // special, or a record's subject. Personal Mark = iapp.Personal // Special marks a field of GDPR art. 9(1) or art. 10. Special Mark = iapp.Special // Moderated marks content others see and a moderator may act on. Moderated Mark = iapp.Moderated )
type Migration ¶
type Migration = iapp.MigrationValue
Migration is one versioned change of a database's schema and its reversal, the framework's own (ADR 0179 step 10): the shape the SDK's sql runs, which the store subsystem hands it.
app.Migration{
Version: 20261017120000,
Name: "notes",
Up: app.Statements("CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT)"),
Down: app.Statements("DROP TABLE notes"),
}
type MigrationExecutor ¶
type MigrationExecutor = iapp.MigrationExecutor
MigrationExecutor is what a migration's step runs its statements on: a transaction, which a step cannot end.
type MigrationStep ¶
type MigrationStep = iapp.MigrationStep
MigrationStep is one direction of a Migration, run on ex — the transaction its version row is written in, so that both commit together.
func Statements ¶
func Statements(stmts ...string) MigrationStep
Statements is the MigrationStep that runs stmts in order on its executor, stopping at the first that fails — whose error it returns as the driver said it.
type Module ¶
Module is a set of services a product mounts as one: NewModule declares it, App.With or Mount mounts it.
func NewModule ¶
func NewModule(name, doc string, parts ...ModulePart) *Module
NewModule declares a module named name — lower-case letters, digits and dashes, starting with a letter; "app", "kit", "external" and "schema" are the framework's — that doc describes, made of parts: its services, which it adopts, the modules it requires (Requires), and the migrations of the data it keeps outside the framework's stores (Migrations), run on the database that keeps it. Declare it as a package-level variable of the one package a product imports:
var Module = app.NewModule("moderation",
"Reports and moderation under the DSA.\n\nfr: Signalements et modération selon le DSA.",
intake.Service, desk.Service, app.Requires(identity.Module))
A service a module lists is its own: what it declared so far is renamed, and what it declares later is born qualified. Listing a service links its package; a service is a module's only, and a module's services take declarations from the module's own Go module only.
type ModulePart ¶
type ModulePart = iapp.ModuleConfigurer
ModulePart is what a module is made of: its services, the modules it requires (Requires), and the migrations of the data it keeps outside the framework's stores (Migrations).
func Requires ¶
func Requires(other *Module) ModulePart
Requires says the module needs other: an app that mounts the module and not other mounts other at its defaults, and starts it first. The Go import this takes makes a cycle impossible. A collaboration a module can do without is a port with a fallback instead (Fallback).
type MountOption ¶
type MountOption = iapp.MountConfigurer
MountOption configures the mount of a module: Prefix, Bind, Only.
func Only ¶
func Only(envs ...string) MountOption
Only makes a mount hold in the environments envs names alone — the name <PRODUCT>_ENV or Env gives, lower-cased, "production" when neither does:
a := app.NewApp("vigie", identity.Service).
With(app.Mount(debugbar.Module, app.Only("dev", "staging")))
Elsewhere the mount is as if it had not been given, its Prefix and its Bind with it; another mount of the module without Only still mounts it. Several Only on one mount add up. The start refuses an Only that names no environment, a name that cannot be one — lower-case letters, digits and dashes inside, 63 at most —, and a module a mounted module requires (Requires) that its mount leaves out, rather than mounting it at its defaults behind the product's back.
func Prefix ¶
func Prefix(prefix string) MountOption
Prefix serves a module's routes under prefix — "/trust/" — instead of "/<module>/"; "/" shares the product's route space, where a route both declare is refused as any two are. A prefix starts and ends with '/', and never lies under /_app/, nor under /_kit/ while its probes answer there.
type OTLPBatch ¶ added in v0.52.0
type OTLPBatch = iapp.OTLPBatchValue
OTLPBatch is one batch as the product's own sender receives it (OTLPSender): its signal, OTLPTraces or OTLPMetrics, and its OTLP/JSON document, which a collector takes as it is.
type OTLPFullPolicy ¶ added in v0.52.0
type OTLPFullPolicy = iapp.OTLPFullPolicy
OTLPFullPolicy is what an export's full queue does with a new batch.
const ( // OTLPDropOldest, the default: the oldest batches not being sent are // taken out, counted dropped, until the new one fits. OTLPDropOldest OTLPFullPolicy = iapp.OTLPDropOldest // OTLPDropNewest: the new batch is refused, counted dropped. OTLPDropNewest OTLPFullPolicy = iapp.OTLPDropNewest // OTLPBlock: the span or the snapshot waits for room a few seconds, then // is refused, counted dropped. OTLPBlock OTLPFullPolicy = iapp.OTLPBlock )
What an export's full queue does with a new batch: the setting otlp-when-full spells it.
type OTLPOption ¶ added in v0.52.0
type OTLPOption = iapp.OpenTelemetryConfigurer
OTLPOption configures the app's export: OTLPEndpoint, OTLPBounds, OTLPWhenFull, OTLPMaxAge, OTLPSendTimeout, OTLPSampleRatio, OTLPDatabase, OTLPSender.
func OTLPBounds ¶ added in v0.52.0
func OTLPBounds(maxBatches, maxBytes int) OTLPOption
OTLPBounds bounds each signal's queue: at most maxBatches batches and maxBytes bytes — the defaults of the settings otlp-max-batches (10000) and otlp-max-bytes (256 MiB). A batch larger than maxBytes on its own is dropped.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func OTLPDatabase ¶ added in v0.55.0
func OTLPDatabase(name string) OTLPOption
OTLPDatabase keeps the export's queues on the database the app declares under name — the default of the setting otlp-database —, one table per signal (app_otlp__traces, app_otlp__metrics), made by the framework's own migrations: a backlog then outlives a restart with no data directory — a container with no volume — and on the platforms whose file queue the SDK refuses. It needs framework/app/queue, which the start names when the program does not import it; a name the app does not declare stops the start. The empty default keeps the queues in the data directory, else in memory, and so does a declared database that is not open — the app in memory, or in dev without its URL —, which the log says.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func OTLPEndpoint ¶ added in v0.52.0
func OTLPEndpoint(url string) OTLPOption
OTLPEndpoint is the collector's base URL — "http://collector:4318" —, each signal's path (/v1/traces, /v1/metrics) appended to it: the default of the setting otlp-endpoint. An absolute http or https URL with a host; the empty default leaves the export off.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func OTLPMaxAge ¶ added in v0.52.0
func OTLPMaxAge(d time.Duration) OTLPOption
OTLPMaxAge is how long after it was queued a batch may still be sent — the default of the setting otlp-max-age (24h): one older is dropped unsent, counted expired. A collector's Retry-After is waited in full, but never past it.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func OTLPSampleRatio ¶ added in v0.54.0
func OTLPSampleRatio(ratio float64) OTLPOption
OTLPSampleRatio is the share of the traces the app starts that the export keeps — the default of the setting otlp-sample-ratio (1, every one): from 0, none, to 1, every one, decided on the trace's identifier, so every service that sees the same trace decides alike. A trace another process started is kept or not as that process decided, whatever the ratio: a span is never cut off from its parent. The metrics the framework derives count every unit of work, kept or not.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func OTLPSendTimeout ¶ added in v0.52.0
func OTLPSendTimeout(d time.Duration) OTLPOption
OTLPSendTimeout bounds one attempt to send a batch — the default of the setting otlp-send-timeout (10s, OTEL_EXPORTER_OTLP_TIMEOUT's).
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func OTLPSender ¶ added in v0.52.0
func OTLPSender(send func(ctx context.Context, batch OTLPBatch) error) OTLPOption
OTLPSender replaces the network: each batch is handed to send instead of being posted to a collector — the product's own sender, a bridge to another transport. The queue, its bounds, its age and its retries stay the framework's. A failure send returns is tried again on the backoff — after the delay it carries when it is a resilience.RetryAfter's —, but for a refusal the caller must fix, an Error of a 4xx other than 408 and 429, which dead-letters the batch. The export is then on whatever otlp-endpoint says. A nil send keeps the network.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func OTLPWhenFull ¶ added in v0.52.0
func OTLPWhenFull(p OTLPFullPolicy) OTLPOption
OTLPWhenFull is what a full queue does with a new batch — the default of the setting otlp-when-full: OTLPDropOldest (the default), OTLPDropNewest or OTLPBlock.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type Operation ¶
Operation takes a typed request and answers a typed response: an endpoint, a port — and, with ADR 0005, a command or a query. It is what Fallback and Bind give a port, and what Replace replaces in a test; a request or a response of other types does not compile. Its methods are unexported: only the framework implements it.
Every operation is a node of the graph, and runs in a span of its own through its whole pipeline — authentication, validation, policies, the Studio's mocks — whoever calls it.
type OperationOption ¶
type OperationOption = iapp.OperationOption
OperationOption configures an endpoint, a command or a query alike: the authentication it asks for (Auth, AuthOptional) and the policies in front of its handler (RateLimit, RateLimitPerClient, Timeout, Bulkhead).
func Auth ¶
func Auth() OperationOption
Auth makes an endpoint require an authenticated caller: the app's auth handler runs first, and a request without valid credentials is answered 401 before the handler runs. A command or a query that asks for one is refused 401 when its caller carries no user: an in-process dispatch carries its caller's, and is not authenticated again.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func AuthOptional ¶
func AuthOptional() OperationOption
AuthOptional runs the app's auth handler when the request carries credentials, and serves anonymous callers too: UserID tells which.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Bulkhead ¶
func Bulkhead(maxConcurrent int, opts ...BulkheadOption) OperationOption
Bulkhead caps how many requests the handler serves at once; the overflow answers 503 — at once, or, given BulkheadQueue and MaxWait, once the queue is full or the wait ran out. It is the SDK's resilience bulkhead.
The values are the defaults of the operation's settings <service>-<kind>-<operation>-bulkhead, -bulkhead-queue and -bulkhead-wait, which config/<env>.* and <PRODUCT>_<NAME> override; a bulkhead below one stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func RateLimit ¶
func RateLimit(perSecond float64, burst int, opts ...RateLimitOption) OperationOption
RateLimit puts a token bucket in front of the handler: perSecond tokens a second, up to burst at once. An empty bucket answers 429 at once — with Retry-After, the seconds the bucket needs to earn its next token —, or, given MaxWait, once the token due within it did not come. It is the SDK's resilience rate limiter.
The values are the defaults of the operation's settings <service>-<kind>-<operation>-rate, -burst and -rate-wait, which config/<env>.* and <PRODUCT>_<NAME> override; a rate that is not above zero or a burst below one stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func RateLimitPerClient ¶
func RateLimitPerClient(perSecond float64, burst int) OperationOption
RateLimitPerClient gives every client of an endpoint a token bucket of its own: perSecond tokens a second, up to burst at once. A client is the authenticated user when there is one, and the client's address otherwise (ClientIP); in-process calls through Endpoint.Call share one bucket. One client emptying its bucket is answered 429, with Retry-After; the others are not — which is what a sign-in endpoint needs, where one shared bucket would let a single client lock everybody out.
Buckets unused for ten minutes are forgotten, and at most 10 000 are kept: the least recently used goes first. It is the SDK's keyed rate limiter.
The values are the defaults of the operation's settings <service>-<kind>-<operation>-client-rate and -client-burst, which config/<env>.* and <PRODUCT>_<NAME> override; a rate that is not above zero or a burst below one stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type OverlapPolicy ¶ added in v0.51.0
type OverlapPolicy = iapp.OverlapPolicy
OverlapPolicy is what a job's fire does while the job's previous run is still going: OverlapSkip, OverlapAllow or OverlapReplace. It is the word of the job's setting <service>-job-<name>-overlap.
const ( // OverlapSkip skips the fire, counted, the previous run going on: the // default, since the framework cannot know that two runs of a job may // run at once. OverlapSkip OverlapPolicy = iapp.OverlapSkip // OverlapAllow runs the fire beside the previous run. OverlapAllow OverlapPolicy = iapp.OverlapAllow // OverlapReplace cancels the previous run's context and runs the fire // once that run returned: the newest fire wins, two runs never overlap. OverlapReplace OverlapPolicy = iapp.OverlapReplace )
type PasswordOption ¶
type PasswordOption = iapp.PasswordConfigurer
PasswordOption configures a password policy: MinLength, NotReused.
func MinLength ¶
func MinLength(n int) PasswordOption
MinLength refuses a password shorter than n characters, counted as NIST counts them: one per Unicode code point. The default is 15, NIST's figure for a password used alone; 8 is the floor NIST allows with a second factor, and a smaller n is refused. There is no composition rule, ever: NIST says SHALL NOT.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func NotCommon ¶
func NotCommon() PasswordOption
NotCommon refuses a password among the ten thousand most common ones — the SDK's password.IsCommon, which compares them without regard to case —: the blocklist NIST SP 800-63B-4 requires a verifier to check, beyond the three thousand OWASP ASVS 5.0 (6.2.4) asks for. Every policy checks it (ADR 0007 §2: on by default once the SDK has the list); the option says so where a policy is declared. Beside NIST's fifteen characters the list has little left to refuse; beside a shorter MinLength, it matters.
func NotReused ¶
func NotReused(n int) PasswordOption
NotReused refuses a password that the current hash, or any of the n former ones, verifies — n from 1 to 100. It is a compliance policy, off by default: PCI DSS asks for it, OWASP ASVS 4.0.3 asks most products not to impose it. The framework keeps the field's last n hashes, so it implies history=n, and a tag whose history is smaller than n is refused.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type PasswordPolicy ¶
type PasswordPolicy[T any] = iapp.PasswordPolicyService[T]
PasswordPolicy is the policy of one secret field that holds a password's hash: how long a password is at least, and how many former passwords it refuses. Store.Passwords declares it; Set, Change and Verify apply it.
type PersonalData ¶
type PersonalData = iapp.PersonalData
PersonalData is a person's data as app.Export gives it.
func Export ¶
func Export(ctx context.Context, ids ...string) (PersonalData, error)
Export returns every record whose subject is one of ids, in every store of the app: each without its secret members, with the former values its fields keep (ADR 0007) — never a secret field's —, and per store what GDPR art. 15(1) asks beside the data — the purpose, the retention and the recipients inside the product. A held record is exported like any other. The result is JSON, structured and machine-readable (art. 20); keeping the month of art. 12(3) is the product's job, and so is deciding who may call it.
A person known under several identities — a user's ID in one store, an e-mail address in another — is found by giving all of them. ctx must run inside the app: an endpoint's, a job's, a loop's.
type Port ¶
type Port[Req, Resp any] = iapp.PortService[Req, Resp]
Port is an operation a service needs and does not implement: a typed request, a typed response, a name. Declare it with Service.Port, and call it with Port.Call as an endpoint is called: validated, observed, drawn.
What a port calls is decided when the app starts, by one rule the static analysis shares: the app's Bind, else the one Service.Implement among the services the app mounts, else the port's own Fallback. The start refuses a port it cannot bind, with every other problem at once.
A port is how a service reaches what it cannot import — a module its host's content, a service another that imports it — the consumer owning the contract.
type PortOption ¶
type PortOption[Req, Resp any] = iapp.PortConfigurer[Req, Resp]
PortOption configures a port: Fallback.
type PortPolicyOption ¶ added in v0.49.0
type PortPolicyOption = iapp.PortPolicyConfigurer
PortPolicyOption guards the calls a port makes: Retry, Budget, Breaker, Hedge, Idempotent, Throttle and Timeout, given to Port.Guard.
func Breaker ¶ added in v0.49.0
func Breaker(failures int, open time.Duration, opts ...BreakerOption) PortPolicyOption
Breaker stops a port's calls from reaching a dependency that keeps failing: after failures failures of the dependency's in a row — or, given BreakerWindow, a share of a window's calls — it opens, and every call fails at once with the SDK's CircuitOpen (503) for open; then it lets HalfOpenTrials trial calls through, one at a time, which close it or open it again, for longer each time under OpenBackoff. A refusal of the caller's own does not count, nor a caller that left, nor a throttle's refusal. It is the SDK's resilience circuit breaker, on the app's clock, one per port and per start.
Its state is the product's: a readiness check, breaker:<port>, degraded — never unready — while it is not closed; each change of phase logged and put on the telemetry port. An operator opens it until reset with the product's `breaker isolate PORT` and closes it with `breaker reset PORT`, kept in the data directory: a start applies it, and so does a running product, within five seconds.
The values are the defaults of the port's settings <service>-port-<name>-breaker-failures, -breaker-open, -breaker-open-max, -breaker-trials, -breaker-window, -breaker-window-calls and -breaker-window-ratio, which config/<env>.* and <PRODUCT>_<NAME> override; a value the breaker cannot run with stops the start, and so does a breaker the SDK refuses.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Budget ¶ added in v0.49.0
func Budget(maxTokens int, tokenRatio float64) PortPolicyOption
Budget sizes the retry budget a port's Retry and Hedge share: a bucket of maxTokens tokens, a failure costing one and a success putting back tokenRatio; retries and duplicates are refused once half the tokens are spent, so a dependency that fails for every caller receives fewer extra calls, not every call times the attempts. A port that retries or hedges without it has 10 tokens and a ratio of 0.1, gRPC's example; a Budget on a port that does neither stops the start. It is the SDK's resilience retry budget, one per port and per start.
The values are the defaults of the port's settings <service>-port-<name>-budget-tokens and -budget-ratio, which config/<env>.* and <PRODUCT>_<NAME> override; fewer than one token, or a ratio below a thousandth, stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Hedge ¶ added in v0.49.0
func Hedge(delay time.Duration, inFlight int) PortPolicyOption
Hedge races a port's slow call: an attempt that has not answered after delay is joined by a duplicate, and the first to succeed answers — the tail of a dependency's latency cut, at the price of more calls. At most inFlight duplicates run at once across every call, and the port's retry budget (Budget) refuses them while the dependency fails for many: then the call goes on with the attempts it has. Only a port declared Idempotent may hedge — the start refuses another. It is the SDK's resilience hedge, on the app's clock.
The values are the defaults of the port's settings <service>-port-<name>-hedge-delay, -hedge-in-flight and -hedge-max — the duplicates one call may make, 1 —, which config/<env>.* and <PRODUCT>_<NAME> override; a delay that is not positive, or fewer than one, stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Idempotent ¶ added in v0.49.0
func Idempotent() PortPolicyOption
Idempotent declares that the port's operation may run more than once for one call, concurrently, with no harm done: what a Hedge needs, which is refused on a port that does not say so. The graph draws it on the port.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Retry ¶ added in v0.49.0
func Retry(maxAttempts int, delay time.Duration, opts ...RetryOption) PortPolicyOption
Retry runs a port's call again when it fails for a reason of the dependency's — what the start answers as a 5xx, a 408 or a 429 —, up to maxAttempts attempts in all, waiting between them a backoff that starts at delay and doubles, with full jitter, up to RetryMaxDelay — 30 seconds unless the code says otherwise. A failure that says how long to wait — a Retry-After, a rate limiter's next token (the SDK's resilience.RetryAfter) — is waited that long instead, held at the longest delay, unless NoRetryAfter. A refusal of the caller's own is not retried, nor an open breaker, a throttle or another retry's exhaustion. It is the SDK's resilience retry, on the app's clock, sharing the port's retry budget (Budget) with its hedge.
Each retry is an event on the port's span, which counts them, and a retry event on the telemetry port.
The values are the defaults of the port's settings <service>-port-<name>-retry-attempts, -retry-delay, -retry-max-delay, -retry-jitter (full, decorrelated or none) and -retry-after (whether a failure's own delay is honoured), which config/<env>.* and <PRODUCT>_<NAME> override; fewer than one attempt, or a delay that is not positive, stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Throttle ¶ added in v0.49.0
func Throttle(k float64) PortPolicyOption
Throttle refuses, on the caller's side and without sending them, a share of a port's calls while the dependency refuses more than 1/k of the recent ones — the client-side throttling of Google's SRE book: a call is refused with probability (requests − k × accepts) / (requests + 1), over the last two minutes, with the SDK's Throttled (503). A refusal is a 5xx, a 408 or a 429 of the dependency's; a refusal of the caller's own is an accept. It is the SDK's resilience adaptive throttle, on the app's clock; 2 is the book's k.
k is the default of the port's setting <service>-port-<name>-throttle-k, which config/<env>.* and <PRODUCT>_<NAME> override; a k below 1 stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type Principal ¶
type Principal = iapp.AttrsProvider
Principal is what the app's auth data says about the caller to the SDK's authz: the attributes Command.Allow and Query.Allow hand a policy — the caller's roles, its groups. Auth data that does not implement it gives none, and every Allow refuses: the start warns of it.
type Me struct{ Roles []string }
func (m Me) Attrs() []authz.Attr { return []authz.Attr{authz.AttrStrings("roles", m.Roles...)} }
The framework calls the caller a principal: in the framework, a subject is the person personal data is about (ADR 0006).
type Query ¶
Query reads and changes nothing: a typed input, a typed result, and one handler — the one declared with it. Declare it with Service.Query; ask it with Query.Ask from any building block, which draws an asks edge from the caller; give it a route with Query.Expose. The static analysis warns of a query whose code writes a store, fires a workflow, publishes, sends a mail or dispatches a command.
A question runs, in this order: the caller's user when the query asks for one (Auth, implied by Query.Allow), the input's validate tags, the policies, the authorization (Query.Allow, then Query.Authorize), then the handler, on the caller's goroutine.
type QueryOption ¶
type QueryOption = iapp.QueryConfigurer
QueryOption configures a query: the options every operation takes — Auth, AuthOptional, RateLimit, RateLimitPerClient, Timeout, Bulkhead — and a transaction's — ReadOnly, Serializable, RepeatableRead —, which run its Ask in a transaction opened with them.
type RateLimitOption ¶ added in v0.48.0
type RateLimitOption = iapp.RateLimitConfigurer
RateLimitOption configures a RateLimit.
type Records ¶
type Records = iapp.RecordsService
Records is one store's records without their type. Get returns a record without its secret members; Keys lists the records' keys, to a module that watches the store; EraseFields and Delete take a reason and are refused on a held record. Each call is a span on the store's node and an entry in the privacy journal.
func RecordsOf ¶
RecordsOf is App.Records for code the app runs and that does not hold it — a module's watch, its endpoints: the records port of the store whose node ID is store, in the app ctx runs in. Outside a running app it is an Unavailable error.
func Screen(ctx context.Context, w app.Written) error {
recs, err := app.RecordsOf(ctx, w.Store)
…
record, err := recs.Get(ctx, w.Key)
type RetryOption ¶ added in v0.49.0
type RetryOption = iapp.RetryConfigurer
RetryOption configures a Retry.
func NoRetryAfter ¶ added in v0.49.0
func NoRetryAfter() RetryOption
NoRetryAfter makes a Retry wait its backoff whatever a failure says: a Retry-After, a rate limiter's next token. It is the default of the port's setting <service>-port-<name>-retry-after, false, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func RetryMaxDelay ¶ added in v0.49.0
func RetryMaxDelay(d time.Duration) RetryOption
RetryMaxDelay is the longest a Retry waits between two attempts: the backoff's cap, and the cap on a delay a failure asks for. It is the default of the port's setting <service>-port-<name>-retry-max-delay; one that is not positive stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type Revision ¶
type Revision[T any] = iapp.RevisionEvent[T]
Revision is one version of a record a store with Revisions keeps: its number — from 1, never given twice while the record exists —, when the write that made it ran, on the app's clock, zero for a record stored before its store kept revisions; who made it — the caller's UserID, empty for a write with no user —; which command made it — its node ID, empty outside a command —; and the record as it was, its secret members zeroed.
type Routine ¶
Routine is a loop written by hand: a function that runs until its context ends. The framework starts it with the app, cancels its context on shutdown and waits for it, restarts it after an error or a panic — backing off from one second to one minute — and reads its select statements to draw what it waits on.
type RoutineOption ¶ added in v0.51.0
type RoutineOption = iapp.RoutineConfigurer
RoutineOption configures a hand-written loop (Service.Go).
type Scope ¶
type Scope = iapp.ScopeValue
Scope is one part of a path computed at the start: the user, the executable, a configuration directory. Two processes share a singleton or a socket when every scope gives them the same value.
var ( // PerUID is the current user: one process per user of the machine (its // UID on Unix, its SID on Windows). PerUID Scope = iapp.PerUID // PerExecutable is the running executable's path, links resolved: one // process per installed copy of the binary. PerExecutable Scope = iapp.PerExecutable // PerConfigDir is the user's configuration directory (os.UserConfigDir): // one process per configuration home. PerConfigDir Scope = iapp.PerConfigDir )
type Secret ¶
Secret is a secret the product declares: provided by the operator — an SMTP URL, an API token — or generated by the framework — a signing or sealing key — and rotated on its schedule.
type SecretOption ¶
type SecretOption = iapp.SecretConfigurer
SecretOption configures a secret.
func Generated ¶
func Generated(bytes int) SecretOption
Generated makes the secret the framework's to make: versions of bytes random bytes — 32 for a key — the first made on the first start, a new one every 30 days, the last 3 kept, unless RotateEvery and KeepVersions say otherwise.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func KeepVersions ¶
func KeepVersions(n int) SecretOption
KeepVersions is how many versions of a generated secret a rotation leaves, the new one included: at least 2, so that what the version it replaces sealed or signed still opens and verifies. Cover the longest-lived box or signature in flight: its lifetime divided by the interval, plus one.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
func Optional ¶
func Optional() SecretOption
Optional makes a provided secret one the product can do without — the key of a feature that stays off while nobody gives it. A start where it is set nowhere goes on; Secret.Present says whether it is set now, and a use of it while it is absent — Secret.Value, Seal, Open, Sign or Verify — answers an error errs.HasCode matches with CodeSecretMissing. It is read where it lives at every use, as every provided secret is: given later — `secrets set` in the environment's store, a new content in the file its _FILE variable names —, it is found at its next use. A generated secret is the framework's to make and never absent: Optional with Generated is refused.
func RotateEvery ¶
func RotateEvery(d time.Duration) SecretOption
RotateEvery is how often the framework makes a new version of a generated secret.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type Service ¶
Service is a bounded context of the product: it owns its building blocks — endpoints, stores, topics, subscriptions, workflows, jobs, frontends — and is the unit an App mounts. Declare one per package, as a package-level variable, and declare its building blocks through its methods:
var Service = app.NewService("todos", "The todo list.")
var Todos = Service.Store("todos", func(t Todo) string { return t.ID })
var _ = Service.Endpoint("GET /todos", List)
Declaring never fails: a mistake — a malformed route, a duplicate name — is recorded with its source position and reported, all at once, when the App starts. The diagram shows it too.
Privacy is the framework's own service: the legal holds and the privacy journal of an app that keeps personal data. The framework mounts a copy of it — named app.privacy, a name no service of a product can take — in every app whose stores keep personal data or declare a retention, before the product's services. Its stores stay in the data directory unless the product places them (ADR 0004). A product never mounts it itself.
func NewService ¶
NewService declares a service. name must be lower-case letters, digits and dashes, starting with a letter; doc is one sentence saying what it owns.
type Setting ¶
type Setting[T SettingValue] = iapp.SettingService[T]
Setting is a value the environment gives a service, declared with Service.Setting.
type SettingOption ¶
type SettingOption = iapp.SettingConfigurer
SettingOption configures a setting.
func Required ¶
func Required() SettingOption
Required drops a setting's default: a start without a value for it fails, saying where to give one.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type StaticOption ¶
type StaticOption = iapp.StaticConfigurer
StaticOption configures a frontend.
func Root ¶
func Root(dir string) StaticOption
Root serves the sub-directory dir of the file system rather than its root — "assets" for a //go:embed assets directive.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type Stdio ¶
type Stdio = iapp.StdioValue
Stdio is where a CLI command reads and writes: the process's own streams under Main, buffers in a test.
type Store ¶
type Store[T any] = iapp.StoreService[T]
Store is a typed, keyed collection of entities. Every read returns a copy and every write stores one: an entity is kept as its JSON encoding, so what a handler holds can never alias what the store holds, and the memory and file backends behave identically.
With a data directory (<PRODUCT>_DATA_DIR; ".app/data" in dev) the store persists every write before returning, atomically — a crash never leaves a torn file — and a write costs one entity, whatever the store holds. Without one, it lives in memory. A store is a port (ADR 0004): what it runs on is its engine (store_engine.go), today the SDK's document store (docstore); the framework makes it a node of the graph, observes every call, and speaks for its refusals.
type StoreOption ¶
type StoreOption = iapp.StoreConfigurer
StoreOption configures a store.
func Anonymise ¶
func Anonymise[T any](fn func(*T)) StoreOption
Anonymise says what an erased record keeps: fn runs first, and generalises into unclassified fields — a birth date to its year, an address to its region; then the framework clears the rest. The framework cannot prove that what remains identifies no one: by declaring the function, the product asserts it.
func DeleteAfter ¶
DeleteAfter deletes a record delay after the instant since returns.
func DeleteAt ¶
func DeleteAt[T any](at func(T) (time.Time, bool)) StoreOption
DeleteAt deletes a record at the instant at returns.
func DeleteOnErasure ¶
func DeleteOnErasure() StoreOption
DeleteOnErasure makes a person's erasure (app.Erase) delete the store's records instead of clearing them, as sessions and accounts want.
func EraseAfter ¶
EraseAfter erases a record's personal data delay after the instant since returns — its closing, say; false means "not yet": an open record is never due. delay is a duration, or a duration setting.
func EraseAt ¶
func EraseAt[T any](at func(T) (time.Time, bool)) StoreOption
EraseAt erases a record's personal data at the instant at returns: one the product computed and stored on the record — a retention in calendar months, one that depends on a tenant.
func HeldUntil ¶
HeldUntil holds each record until the instant until returns: the law's own retention, such as an invoice kept ten years (GDPR art. 17(3)(b)). reason is the legal ground, for the register. A held record is exported and updated like any other, and neither erased nor deleted.
func Index ¶
func Index[T any](name string, keys func(T) []string) StoreOption
Index declares an index where an entity may have several keys and a key several entities — the users a task is shared with. Store.Find reads it. Empty keys are not indexed.
func Purpose ¶
func Purpose(text string) StoreOption
Purpose says why the store keeps its records (GDPR art. 30(1)(b)): the register lists it, and a person's export carries it.
func ReadModel ¶
func ReadModel() StoreOption
ReadModel marks a store as derived from others (ADR 0005): written by projections — the subscriptions that keep it from the write side's events —, read by queries. It changes nothing of how the store runs; the diagram draws it on its domain's read side, and the static analysis warns of a read model written by anything but a subscription. The framework's topics are queues, not logs: a read model cannot be replayed from its events, and one fed by a topic lags the commands that feed it — a query that must read its own writes reads the write side.
var Summaries = Service.Store("summaries", Summary.Key, app.ReadModel())
func RetentionByProduct ¶
func RetentionByProduct(limits string) StoreOption
RetentionByProduct says the product keeps the store's retention itself: its own code erases and deletes what it no longer needs — a record whose life the product's own rules end, a lifecycle the framework cannot read from the entity. limits says, in the product's words, for how long and how, which the register publishes as the store's time limits (GDPR art. 30(1)(f)); "" says only that the product keeps them.
The framework then runs no retention for the store, and warns of neither a missing retention nor a missing subject. Its classified fields keep every other promise: sealed at rest, never shown, exported with their person — when the store names one — and erased by app.Erase and Store.Erase. It goes with app.Purpose, app.HeldUntil, app.Anonymise and app.DeleteOnErasure; with app.EraseAfter, app.EraseAt, app.DeleteAfter or app.DeleteAt it is refused: a store's retention is the framework's or the product's, never both.
func Revisions ¶
func Revisions(n int) StoreOption
Revisions keeps the n previous versions of each record of the store, n from 1 to 100, as WordPress keeps a post's revisions: every write that changes a record makes a version, numbered from 1 and never renumbered, stamped with when it was made, the caller's user and the command that made it; the oldest beyond n are pruned by the write that makes a newer one, unless a legal hold keeps the record.
var Pages = Service.Store("pages", Page.Key, app.Revisions(20))
revs, err := Pages.Revisions(ctx, id) // newest first
edits, err := Pages.Diff(ctx, id, revs[3].Number, revs[0].Number)
page, err := Pages.Restore(ctx, id, revs[3].Number) // a new version
page, err = Pages.Restore(ctx, id, revs[3].Number, "/title") // the title only
A store with Revisions(n) holds up to n+1 times its records: in memory with the store in the data directory, in the table <table>___vs on a database, which the framework's migrations create.
func Unique ¶
func Unique[T any](name string, key func(T) string) StoreOption
Unique declares a unique index: no two entities may share a key, and a write that would is refused with a Conflict error. An empty key is not indexed. Store.Lookup reads it.
var Accounts = Service.Store("accounts", Account.Key,
app.Unique("email", func(a Account) string { return a.Email }))
type Subscription ¶
type Subscription[T any] = iapp.SubscriptionWorker[T]
Subscription consumes a topic: its handler runs once per message, at least once, retried on error, and dead-lettered after MaxDeliveries attempts.
type SubscriptionOption ¶
type SubscriptionOption = iapp.SubscriptionConfigurer
SubscriptionOption configures a subscription.
func OwnStores ¶
func OwnStores() SubscriptionOption
OwnStores lets a watch (Service.Watch) hear the stores of its own module too — the product's own, for a watch of the product's —, which a watch never hears by default. Such a watch never hears the writes its own handler makes, in its handler's context — a handler that writes what it watches, a screening that stamps the record it screened, would otherwise hear itself forever —; a write the handler only causes, later and elsewhere — a queued command's handling, a topic's delivery — is heard. A subscription to a topic refuses it: a topic has no stores.
type SupervisionOption ¶ added in v0.51.0
type SupervisionOption = iapp.SupervisionConfigurer
SupervisionOption configures what the framework restarts after a failure: a subscription's, a watch's or a queued command's consumer, a declared loop, a hand-written loop (GiveUpAfter).
func GiveUpAfter ¶ added in v0.51.0
func GiveUpAfter(restarts int, within time.Duration) SupervisionOption
GiveUpAfter bounds how often the framework restarts what fails — a subscription's, a watch's or a queued command's consumer whose queue failed, a hand-written loop (Service.Go) that returned, a declared loop (Service.Loop) whose run failed or panicked —: once it failed more than restarts times within within, it is not restarted again, and the product is no longer live — its liveness check "supervised:<node>" fails, the problem names it — so that whatever watches its liveness — an orchestrator's probe — restarts the process; a product nothing probes keeps running without it, and says so in its log, its problems and its telemetry. It is Erlang's restart intensity, the SDK's lifecycle supervisor's GiveUpAfter.
The default is 10 within 10 minutes: with the restarts' backoff — one second, doubling up to a minute — a component that fails at every start is given up about five minutes after its first failure, and one that fails once a minute or less often is restarted forever. A within of zero never gives up; a negative value stops the start.
restarts and within are the defaults of the settings <service>-<kind>-<name>-give-up-restarts and -give-up-within, the kind subscription, command or loop, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its methods are unexported — so a caller only hands it to the declaration it configures.
type TimeoutOption ¶ added in v0.49.0
type TimeoutOption = iapp.TimeoutConfigurer
TimeoutOption configures an endpoint, a command, a query and a port alike: Timeout.
func Timeout ¶
func Timeout(d time.Duration) TimeoutOption
Timeout cancels the handler's context after d and answers 504. A caller that leaves first is no timeout: its request is recorded as 499, logged as information, and nothing it could read is written. It is the SDK's resilience timeout, on the app's clock.
Given to a port's Port.Guard, it is a deadline on each attempt of the port's call, the innermost of its policies: an attempt that outruns it fails with the SDK's TimeoutExceeded, which the port's breaker counts and its retry replays.
d is the default of the operation's setting <service>-<kind>-<operation>-timeout — <service>-port-<name>-timeout for a port —, which config/<env>.* and <PRODUCT>_<NAME> override; one that is not positive stops the start.
IFACE-OPAQUE: the option is sealed — its method is unexported — so a caller only hands it to the declaration it configures.
type Tombstone ¶
type Tombstone = iapp.TombstoneEvent
Tombstone is one record in a store's trash: its key, when the product deleted it, on the app's clock, and when the framework purges it — its trash's length after the deletion, or sooner when its retention says so.
type Topic ¶
type Topic[T any] = iapp.TopicService[T]
Topic is an asynchronous channel of messages of type T. Every subscription receives every message, at least once: a subscription's handler must tolerate a redelivery.
type TransactOption ¶ added in v0.59.0
type TransactOption = iapp.TransactOption
TransactOption asks a transaction for an isolation level or for read-only: Serializable, RepeatableRead, ReadOnly.
func ReadOnly ¶ added in v0.59.0
func ReadOnly() TransactOption
ReadOnly opens the transaction read-only: the database is told it only reads, and a store's write inside it is refused (Invalid, CodeTransactionReadOnly) on every backend, before it reaches one. Given to a query's declaration, it runs the query's Ask in such a transaction — the caller's own, when the Ask runs inside one.
func RepeatableRead ¶ added in v0.59.0
func RepeatableRead() TransactOption
RepeatableRead opens the transaction at the REPEATABLE READ isolation level: a row it read reads the same until it ends. On the data directory and in memory it changes nothing.
func Serializable ¶ added in v0.59.0
func Serializable() TransactOption
Serializable opens the transaction at the SERIALIZABLE isolation level: it commits only if running it alone would have given the same result, and a concurrent transaction that would break that fails instead — on PostgreSQL with SQLSTATE 40001, which the database asks to run again. On the data directory and in memory, whose transactions already take one writer at a time, it changes nothing.
type UID ¶
UID identifies an authenticated user. It is what the auth handler returns and what every endpoint reads with UserID.
type Violation ¶
type Violation = iapp.ViolationMessage
Violation is one validation rule a request failed: where, which rule, and why — never the value.
type WaitOption ¶ added in v0.48.0
type WaitOption = iapp.WaitConfigurer
WaitOption configures a RateLimit and a Bulkhead alike.
func MaxWait ¶ added in v0.48.0
func MaxWait(d time.Duration) WaitOption
MaxWait lets a call wait, at most d on the app's clock, instead of being refused at once: given to RateLimit, for a token due within d — the calls after it queue behind it —; given to Bulkhead, for a slot to free, in the queue BulkheadQueue sizes. A call still refused answers 429 or 503 as before; a caller that leaves while it waits leaves the queue. Its default is no wait, and a negative one stops the start. It is the default of the operation's setting <service>-<kind>-<operation>-rate-wait or -bulkhead-wait, which config/<env>.* and <PRODUCT>_<NAME> override.
IFACE-OPAQUE: the option is sealed — its methods are unexported — so a caller only hands it to the declaration it configures.
type Wake ¶
Wake says why a declared loop runs: the reason, the instant, and the topic that woke it when one did. Wakes that come while it runs, or while it backs off after a failure, are gathered into one run: Reasons and Topics say every one of them, and Reason the one that decides the run.
type Watch ¶
Watch is a subscription fed by stores instead of a topic: its handler is told of every write the framework confirms on a store whose entity holds a field with its mark. Service.Watch declares one.
type Workflow ¶
type Workflow[E any, S comparable] = iapp.WorkflowService[E, S]
Workflow is a state machine over the entities of one store: the states an entity goes through, and the arrows between them. It is declared as data — which is why the diagram can draw it exactly — and it runs four kinds of transitions:
- event transitions (Workflow.On), fired by code with Workflow.Fire;
- timer transitions (Workflow.After), fired by the workflow's own loop once an entity has spent a duration in a state;
- timer transitions at an instant the entity carries (Workflow.At) — a due date, a deadline — fired by the same loop when it comes;
- guard transitions (Workflow.When), fired by the same loop as soon as a condition on the entity holds.
The SDK's state-machine engine runs it (statemachine). Its loop never polls: it keeps an agenda of the transitions due, sleeps until the earliest, and a write of the store — which may bring one forward — wakes it. A workflow with nothing due does not run at all. Transitions of one entity run one at a time, of different entities at once.
The entity's state lives in the entity itself (the state function returns a pointer to it), so the store stays the single source of truth; the engine keeps, beside it, when each entity entered its state and the history of its transitions — in the workflow's file under the data directory, so a timer keeps counting across a restart.
type Written ¶
type Written = iapp.WrittenEvent
Written is what a watch is told of a write: which store, which record, and whether it was deleted — never a value. The watch reads the record itself (RecordsOf): without its secret members, and journaled.
Source Files
¶
- access.go
- activity.go
- app.go
- app_analysis.go
- app_profiles.go
- auth.go
- catalog.go
- cli.go
- command.go
- config.go
- database.go
- database_interface.go
- decode.go
- doc.go
- endpoint.go
- errors.go
- expose.go
- history_read.go
- hold.go
- index.go
- job.go
- listener.go
- loop.go
- mailer.go
- module.go
- mount.go
- operation.go
- otlp.go
- otlp_meter.go
- passwords.go
- policy.go
- policy_interface.go
- port.go
- port_policy.go
- port_policy_interface.go
- privacy.go
- privacy_erase.go
- privacy_export.go
- profile.go
- query.go
- ratelimit.go
- records.go
- replace.go
- request.go
- retention.go
- revisions.go
- roles.go
- scope.go
- secret.go
- secretstore.go
- service.go
- setting.go
- setting_interface.go
- static.go
- store.go
- telemetry.go
- topic.go
- transact.go
- watch.go
- workflow.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package apptest runs a product in its own tests as production runs it: on a data directory, where the framework seals what it keeps at rest, a transaction writes files and a rollback writes them back, a store's retention erases and folds what it overwrote, and a restart reads everything back — none of which a product kept in memory (app.InMemory) ever meets: the framework seals nothing in memory.
|
Package apptest runs a product in its own tests as production runs it: on a data directory, where the framework seals what it keeps at rest, a transaction writes files and a rollback writes them back, a store's retention erases and folds what it overwrote, and a restart reads everything back — none of which a product kept in memory (app.InMemory) ever meets: the framework seals nothing in memory. |
|
config
|
|
|
toml
Package toml lets a kit product read TOML configuration files — config/config.toml, config/<env>.toml — as it reads JSON ones.
|
Package toml lets a kit product read TOML configuration files — config/config.toml, config/<env>.toml — as it reads JSON ones. |
|
yaml
Package yaml lets a kit product read YAML configuration files — config/config.yaml, config/<env>.yaml, and .yml — as it reads JSON ones.
|
Package yaml lets a kit product read YAML configuration files — config/config.yaml, config/<env>.yaml, and .yml — as it reads JSON ones. |
|
Package jobs plugs kit's jobs in: the work a service declares on a schedule — every period (Service.Every) or on a five-field cron expression (Service.Cron) —, which the SDK's scheduler fires on the app's clock.
|
Package jobs plugs kit's jobs in: the work a service declares on a schedule — every period (Service.Every) or on a five-field cron expression (Service.Cron) —, which the SDK's scheduler fires on the app's clock. |
|
Package mail plugs kit's mailers in: the outbox a mailer keeps — the SDK's mail spool, sealed on the database that keeps the mailer's service, else in the data directory or in memory — and the transports that empty it, the SDK's SMTP transport and its capture transport.
|
Package mail plugs kit's mailers in: the outbox a mailer keeps — the SDK's mail spool, sealed on the database that keeps the mailer's service, else in the data directory or in memory — and the transports that empty it, the SDK's SMTP transport and its capture transport. |
|
Package otlp plugs the framework's OTLP export in: the product's traces and the metrics the framework derives from them, each signal kept in a durable queue of its own — the SDK's app/forward over its data/queue, in the data directory, or on the product's database when otlp-database names one, which needs framework/app/queue too — and forwarded to an OpenTelemetry collector over OTLP/HTTP, retried on a backoff, a Retry-After waited in full.
|
Package otlp plugs the framework's OTLP export in: the product's traces and the metrics the framework derives from them, each signal kept in a durable queue of its own — the SDK's app/forward over its data/queue, in the data directory, or on the product's database when otlp-database names one, which needs framework/app/queue too — and forwarded to an OpenTelemetry collector over OTLP/HTTP, retried on a backoff, a Retry-After waited in full. |
|
Package queue plugs kit's queues in: the queues of the topics a service declares and of their subscriptions, of its watches and of its queued commands, and the outbox of a mailer on a database — the brokers the SDK's queue runs them on, in memory, in the data directory or on a database, and their consumers.
|
Package queue plugs kit's queues in: the queues of the topics a service declares and of their subscriptions, of its watches and of its queued commands, and the outbox of a mailer on a database — the brokers the SDK's queue runs them on, in memory, in the data directory or on a database, and their consumers. |
|
Package server makes a kit app in the server profile — the default — serve HTTP: its endpoints, its frontends and its health probes, on the SDK's server engine.
|
Package server makes a kit app in the server profile — the default — serve HTTP: its endpoints, its frontends and its health probes, on the SDK's server engine. |
|
Package store plugs kit's stores in: the stores a service declares, the databases a product keeps them in and their migrations, app.Transact on a database, sealing at rest, history, revisions, trash, retention, holds, the privacy journal, Records and `data copy` — the engines the SDK's document store and sql run them on.
|
Package store plugs kit's stores in: the stores a service declares, the databases a product keeps them in and their migrations, app.Transact on a database, sealing at rest, history, revisions, trash, retention, holds, the privacy journal, Records and `data copy` — the engines the SDK's document store and sql run them on. |
|
Package storetest is the conformance suite of the framework's stores (ADR 0004): what a store does on every backend — in memory, in the data directory, on each database engine —, run by the framework's tests on memory, files and the framework's fake database, and by each engine module's tests on its engine.
|
Package storetest is the conformance suite of the framework's stores (ADR 0004): what a store does on every backend — in memory, in the data directory, on each database engine —, run by the framework's tests on memory, files and the framework's fake database, and by each engine module's tests on its engine. |
|
Package studio serves, in dev, the read-only API the kit tool's Studio reads: the graph and its event stream, traces, instances and items, the source, the dev tools — the process, the databases, goroutines, the heap profile, logs, the mailbox, former values.
|
Package studio serves, in dev, the read-only API the kit tool's Studio reads: the graph and its event stream, traces, instances and items, the source, the dev tools — the process, the databases, goroutines, the heap profile, logs, the mailbox, former values. |
|
Package workflow plugs kit's workflows in: the state machines a service declares over the entities of its stores — their event, timer and guard transitions, their hooks and their loop —, which the SDK's statemachine runs.
|
Package workflow plugs kit's workflows in: the state machines a service declares over the entities of its stores — their event, timer and guard transitions, their hooks and their loop —, which the SDK's statemachine runs. |