Documentation
¶
Overview ¶
Package ankka is the Go SDK for ankka, a serverless platform for agentic AI on the actor model.
A service written with it is a Go program that declares its components (entities, views, consumers, workflows, timed actions, agents, endpoints) as values, hands them to NewService, and calls Start. The platform's own program, the sidecar, runs beside it, owns the journal, the cluster and HTTP, and asks the program to run its handlers over the sidecar protocol. Handlers return effects: inert descriptions of what should happen, which the sidecar interprets.
The test kits are in the package github.com/thinkmorestupidless/ankka-go/testkit.
Index ¶
- Constants
- func AwaitEnd[R any](ctx context.Context, workflowID, id string, within time.Duration) (R, error)
- func BucketNameProblem(name string) string
- func Cancel(ctx context.Context, timerID string) error
- func CancelTask(ctx context.Context, id, reason string) error
- func CodecProblems[T any](c Codec[T]) []string
- func ConfigFrom(ctx context.Context) map[string]string
- func CreateTask(ctx context.Context, t AnyTaskType, instructions string, opts TaskOptions) (string, error)
- func DecideApproval[R any](ctx context.Context, componentID, sessionID, handler, approvalID string, ...) (R, error)
- func EdgeKey(id string) string
- func Fingerprint(document []byte) (string, error)
- func FormatDuration(d time.Duration) string
- func FormatInstant(t time.Time) string
- func Invoke[R any](ctx context.Context, componentID, entityID, wire string, input any) (R, error)
- func InvokeStream(ctx context.Context, componentID, entityID, wire string, input any) iter.Seq2[string, error]
- func NodeKey(id string) string
- func ObjectNameProblem(name string) string
- func ParseDuration(text string) (time.Duration, error)
- func ParseInstant(text string) (time.Time, error)
- func PrefixProblem(prefix string) string
- func QueryStream[Row any](ctx context.Context, viewID string, q ViewQuery) iter.Seq2[Row, error]
- func QueryView[Row any](ctx context.Context, viewID string, q ViewQuery) ([]Row, error)
- func Refuse(code ErrorCode, message string) error
- func Refusef(code ErrorCode, format string, args ...any) error
- func RunSingleTask(ctx context.Context, componentID string, t AnyTaskType, instructions string, ...) (string, error)
- func Schedule(ctx context.Context, timerID string, delay time.Duration, target TimerTarget, ...) error
- func ScheduleRecurring(ctx context.Context, timerID string, delay, period time.Duration, ...) error
- func SendAndAwait[R any](ctx context.Context, workflowID, id, wire string, input any, ...) (R, error)
- func SpanProblem(span time.Duration) string
- func TableOf(viewID string) string
- func Version() string
- func ViewRow[Row any](ctx context.Context, viewID, key string) (Row, bool, error)
- func Watch[Row any](ctx context.Context, viewID string, target WatchTarget) iter.Seq2[WatchEvent[Row], error]
- func WatchEvents[Row any](watch iter.Seq2[WatchEvent[Row], error]) iter.Seq2[SSEEvent, error]
- func WithClient(ctx context.Context, c *Client) context.Context
- func WithStorage(ctx context.Context, s Storage) context.Context
- type ACL
- type ActionEffect
- type AgentComponent
- type AgentEffect
- func (e AgentEffect) Failure() *Refusal
- func (e AgentEffect) Guardrails(names ...string) AgentEffect
- func (e AgentEffect) Memory(session bool) AgentEffect
- func (e AgentEffect) SystemMessage(text string) AgentEffect
- func (e AgentEffect) ThenReply() AgentEffect
- func (e AgentEffect) ThenReplyJSON(schemaHint string) AgentEffect
- func (e AgentEffect) Tools(names ...string) AgentEffect
- func (e AgentEffect) UserMessage(text string) AgentEffect
- func (e AgentEffect) WithContext(text string) AgentEffect
- func (e AgentEffect) WithModel(name string) AgentEffect
- type AgentGuardrail
- type AgentInstance
- func (a AgentInstance) Assign(ctx context.Context, taskIDs ...string) (Assigned, error)
- func (a AgentInstance) Decide(ctx context.Context, approvalID string, d Decision) error
- func (a AgentInstance) Notifications(ctx context.Context) iter.Seq2[Notification, error]
- func (a AgentInstance) Resume(ctx context.Context) error
- func (a AgentInstance) State(ctx context.Context) (InstanceState, error)
- func (a AgentInstance) Suspend(ctx context.Context) error
- func (a AgentInstance) Terminate(ctx context.Context) error
- type AgentScope
- type AgentTool
- type AnyTaskType
- type ApprovalAwaitedError
- type ApprovalRequest
- type Assigned
- type Assignee
- type AssignmentRefusal
- type Attachment
- type AutonomousComponent
- type AutonomousSettings
- type Bucket
- type Caller
- type CallerKind
- type CallerMatch
- type CaseOf
- type ChangeScope
- type Client
- type ClientKey
- type ClientKeyRequest
- type ClientKeyStore
- type Codec
- type CodecOption
- type CommandScope
- type ConsumerComponent
- type ConsumerEffect
- type Contract
- type Decision
- type Declaration
- type DeclaredQuery
- type DecodingError
- type Delta
- type DirectoryStorage
- type Done
- type Effect
- type Element
- type ElementOption
- type EncodingError
- type Endpoint
- type EndpointOption
- type Enum
- type ErrorCode
- type EventScope
- type EventSourcedEntity
- type Exposure
- type GraphEffect
- type GraphError
- type GuardrailStage
- type HttpProblem
- type InstancePhase
- type InstanceState
- type IssuedClientKey
- type IssuerRef
- type KeyValueBuilder
- func (b KeyValueBuilder[S, R]) DeleteEntity() KeyValueBuilder[S, R]
- func (b KeyValueBuilder[S, R]) ExpireAfter(d time.Duration) KeyValueBuilder[S, R]
- func (b KeyValueBuilder[S, R]) ThenNoReply() KeyValueEffect[S, R]
- func (b KeyValueBuilder[S, R]) ThenReply(compute func(S) R) KeyValueEffect[S, R]
- func (b KeyValueBuilder[S, R]) ThenReplyState() KeyValueEffect[S, R]
- func (b KeyValueBuilder[S, R]) ThenReplyValue(v R) KeyValueEffect[S, R]
- type KeyValueEffect
- type KeyValueEntity
- type KeyedViewComponent
- type KeyedViewEffect
- type LocalDate
- type LocalDateTime
- type McpEndpoint
- type McpPart
- func Brokered() McpPart
- func McpCommandRef(name, description, componentID, handler, idArg string, opts ...McpToolOption) McpPart
- func McpQueryRef(name, description, componentID, handler, idArg string, opts ...McpToolOption) McpPart
- func McpRouteRef(name, description, method, path string, opts ...McpToolOption) McpPart
- func McpTool[I, R any](name, description string, f func(ctx context.Context, input I) (R, error), ...) McpPart
- func ServerInfo(name, version string) McpPart
- type McpServerOption
- type McpServerRef
- type McpToolOption
- type MemoryOption
- type MemoryStorage
- type Message
- type Metadata
- type Notification
- type ObjectEntry
- type ObjectInfo
- type Part
- func Accepts(t AnyTaskType, maxIterations int) Part
- func Action[I any](wire string, f func(ctx context.Context, input I) (ActionEffect, error)) Part
- func ApplyWithContext[S, E any](apply func(ctx context.Context, state S, event E) S) Part
- func Ask[I any](wire string, f func(ctx context.Context, input I) (AgentEffect, error)) Part
- func AskStream[I any](wire string, f func(ctx context.Context, input I) (AgentEffect, error)) Part
- func AutonomousModel(name string) Part
- func Command[S, E, I, R any](wire string, ...) Part
- func EventCodec[E any](c Codec[E]) Part
- func ForStep(step string, opts ...WorkflowOption) Part
- func Guardrails(guardrails ...AgentGuardrail) Part
- func Instructions(text string) Part
- func MaxToolCallSteps(n int) Part
- func McpServers(servers ...McpServerRef) Part
- func MirroredChanges() Part
- func On[Src, Row any](source Source, ...) Part
- func OnChange[Src, Row any](source Source, ...) Part
- func OnDelete[Row any](f func(ctx context.Context, row *Row) (ViewEffect[Row], error)) Part
- func ProducesTo[Out any](topic string, opts ...PublicationOption) Part
- func ProducesWith[Out any](topic string, c Codec[Out], opts ...PublicationOption) Part
- func Queries(queries ...DeclaredQuery) Part
- func Query[S, I, R any](wire string, ...) Part
- func Replicated() Part
- func Role(text string) Part
- func RowCodec[Row any](c Codec[Row]) Part
- func SnapshotEvery(n int) Part
- func SourceVersion(n int) Part
- func StateCodec[S any](c Codec[S]) Part
- func Step[S, I any](name string, ...) Part
- func Tools(tools ...AgentTool) Part
- func Update[S, I, R any](wire string, ...) Part
- func WhenDeleted[Eff ConsumerEffect | GraphEffect](f func(ctx context.Context) (Eff, error)) Part
- func WithAutonomousSettings(s AutonomousSettings) Part
- func WorkflowCommand[S, I, R any](wire string, ...) Part
- func WorkflowTimeout(d time.Duration) Part
- type PauseOptions
- type PersistBuilder
- func (b PersistBuilder[S, E, R]) DeleteEntity() PersistBuilder[S, E, R]
- func (b PersistBuilder[S, E, R]) ExpireAfter(d time.Duration) PersistBuilder[S, E, R]
- func (b PersistBuilder[S, E, R]) HandOverTo(installation string) PersistBuilder[S, E, R]
- func (b PersistBuilder[S, E, R]) ReplicateTo(installation string) PersistBuilder[S, E, R]
- func (b PersistBuilder[S, E, R]) StopReplicatingTo(installation string) PersistBuilder[S, E, R]
- func (b PersistBuilder[S, E, R]) ThenNoReply() Effect[S, E, R]
- func (b PersistBuilder[S, E, R]) ThenReply(compute func(S) R) Effect[S, E, R]
- func (b PersistBuilder[S, E, R]) ThenReplyState() Effect[S, E, R]
- func (b PersistBuilder[S, E, R]) ThenReplyValue(v R) Effect[S, E, R]
- func (b PersistBuilder[S, E, R]) ThenReplyWithMetadata(compute func(S) R, md Metadata) Effect[S, E, R]
- type Principal
- type Problem
- type ProblemsError
- type Properties
- type ProtocolTooOldError
- type Publication
- type PublicationOption
- type RawResponse
- type ReadOnlyEffect
- type Recovery
- type Refusal
- type RefusalError
- type ReplicationChange
- type Request
- type Route
- func Delete[R any](template string, f func(ctx context.Context, req *Request) (R, error)) *Route
- func Get[R any](template string, f func(ctx context.Context, req *Request) (R, error)) *Route
- func Patch[B, R any](template string, f func(ctx context.Context, req *Request, body B) (R, error)) *Route
- func Post[B, R any](template string, f func(ctx context.Context, req *Request, body B) (R, error)) *Route
- func Put[B, R any](template string, f func(ctx context.Context, req *Request, body B) (R, error)) *Route
- func SSE(template string, ...) *Route
- func SSEEvents(template string, ...) *Route
- func SocketRoute(template string, f func(ctx context.Context, s *Socket) error) *Route
- type RouteOrOption
- type RowChange
- type S3Storage
- type SSEEvent
- type SecretStore
- type Service
- func (s *Service) Client() *Client
- func (s *Service) Problems() []Problem
- func (s *Service) Reported() []string
- func (s *Service) Serve(ctx context.Context, lis net.Listener, opts ...StartOption) error
- func (s *Service) SidecarProtocol() string
- func (s *Service) Spec() *pb.Spec
- func (s *Service) Start(ctx context.Context, opts ...StartOption) error
- type ServiceError
- type ServiceFailureReason
- type ServiceRequest
- type ServiceResponse
- type SignedAccess
- type Socket
- type Source
- type Standing
- type StartOption
- type StartPosition
- type StepBuilder
- type StepEffect
- type StepRef
- type Storage
- type StorageBackend
- type StoredObject
- type SumType
- type TaskOptions
- type TaskRule
- type TaskSnapshot
- type TaskStatus
- type TaskType
- type TimedActionComponent
- type TimerScope
- type TimerTarget
- type TopicOption
- type Unit
- type Verdict
- type ViewComponent
- type ViewEffect
- type ViewQuery
- type ViewRows
- type WatchEndedError
- type WatchEvent
- type WatchTarget
- type WorkflowBuilder
- func (b WorkflowBuilder[S, R]) ThenNoReply() WorkflowEffect[S, R]
- func (b WorkflowBuilder[S, R]) ThenReply(compute func(S) R) WorkflowEffect[S, R]
- func (b WorkflowBuilder[S, R]) ThenReplyState() WorkflowEffect[S, R]
- func (b WorkflowBuilder[S, R]) ThenReplyValue(v R) WorkflowEffect[S, R]
- func (b WorkflowBuilder[S, R]) ThenTransitionTo(step string, input any) WorkflowBuilder[S, R]
- type WorkflowComponent
- type WorkflowEffect
- type WorkflowOption
Constants ¶
const ( JSONContent = "application/json" TextContent = "text/plain" BinaryContent = "application/octet-stream" )
Content types of protocol/ENCODING.md.
const ( // MaxObjectNameBytes is the longest object name, in bytes of UTF-8. MaxObjectNameBytes = 1024 // MaxSignedURLSpan is the longest a signed URL is made for: seven days. MaxSignedURLSpan = 7 * 24 * time.Hour // DefaultSignedURLSpan is a signed URL's span when none is given: fifteen minutes. DefaultSignedURLSpan = 15 * time.Minute )
const GraphDeltaSchema = "ankka.graph-delta.v1"
GraphDeltaSchema is the graph delta contract's name: the manifest and the ce-type of every delta.
const MaxSecretValue = 65536
MaxSecretValue is the largest secret value, in bytes of UTF-8.
const MaxServiceBody = 4_000_000
MaxServiceBody is the largest body, either way, a call through the sidecar carries.
const ProtocolVersion = "1.22"
ProtocolVersion is the sidecar protocol this SDK speaks, declared in discovery.
const SDKName = "ankka-go"
SDKName is how this SDK names itself to the sidecar, and how a deployed service says which SDK built it.
Variables ¶
This section is empty.
Functions ¶
func AwaitEnd ¶
AwaitEnd waits up to within for the workflow workflowID (instance id) to end and answers its final state (1.18).
func BucketNameProblem ¶
BucketNameProblem is what is wrong with a bucket's name, or "", in the descriptor's words.
func CancelTask ¶
CancelTask cancels the task: at once when it waits, at the end of the current iteration when an instance works it.
func CodecProblems ¶
CodecProblems is what is wrong with a codec, if anything: a default codec for a type the encoding cannot describe, or a custom codec with no manifest. A service refuses to start on any.
func ConfigFrom ¶
ConfigFrom is the service's variables as the platform hands them, or nil outside a handler.
func CreateTask ¶
func CreateTask(ctx context.Context, t AnyTaskType, instructions string, opts TaskOptions) (string, error)
CreateTask creates a task of type t and answers its id. A dependency that does not exist is refused before anything is written; one that has already ended cancels the new task.
func DecideApproval ¶
func DecideApproval[R any](ctx context.Context, componentID, sessionID, handler, approvalID string, d Decision) (R, error)
DecideApproval decides an approval request an agent's turn waits on: the agent componentID, the session sessionID and the handler that was called (1.11). It answers as the turn's caller would have been answered once the turn goes on: its reply as R, or an *ApprovalAwaitedError when it waits on another decision.
func EdgeKey ¶
EdgeKey is the record key of every delta for the edge id. Nodes and edges are separate id spaces.
func Fingerprint ¶
Fingerprint is "sha256:" and the hex SHA-256 of document canonicalised under RFC 8785.
func FormatDuration ¶
FormatDuration renders d as java.time.Duration.toString does: "PT0S", "PT1.5S", "PT2H30M", "PT-0.5S". Hours are never folded into days.
func FormatInstant ¶
FormatInstant renders t as the encoding's instant: UTC, "Z", and as many fractional digits as the nanoseconds need (none, 3, 6 or 9). The monotonic clock reading, if any, plays no part.
func Invoke ¶
Invoke calls the handler wire of the entity, workflow or agent componentID (the instance entityID) with input, and answers its reply. A refusal is a *RefusalError with the callee's code.
func InvokeStream ¶
func InvokeStream(ctx context.Context, componentID, entityID, wire string, input any) iter.Seq2[string, error]
InvokeStream calls a streaming agent handler and yields its tokens as they come. The sequence ends after the last token, or with the error that ended it.
func ObjectNameProblem ¶
ObjectNameProblem is what is wrong with an object's name, or "".
func ParseDuration ¶
ParseDuration reads the ISO-8601 forms java.time.Duration.parse reads: "PT1.5S", "PT2H30M", "P1DT12H", "-PT1S". A day is 24 hours, as Java has it; years, months and weeks are refused, as Java refuses them.
func ParseInstant ¶
ParseInstant reads an ISO-8601 instant with "Z" or an offset and up to nine fractional digits, returning it in UTC.
func PrefixProblem ¶
PrefixProblem is what is wrong with a listing's prefix, or "". Empty is everything.
func QueryStream ¶
QueryStream asks the view viewID query q and yields its rows as the database gives them (1.17).
func RunSingleTask ¶
func RunSingleTask(ctx context.Context, componentID string, t AnyTaskType, instructions string, opts TaskOptions) (string, error)
RunSingleTask creates a task of type t, starts a fresh instance of the agent on it, and answers the task's id at once.
func Schedule ¶
func Schedule(ctx context.Context, timerID string, delay time.Duration, target TimerTarget, input any) error
Schedule makes the timer timerID call target with input after delay, replacing any timer under the id. A timer is a database row: it survives a restart and fires once.
func ScheduleRecurring ¶
func ScheduleRecurring(ctx context.Context, timerID string, delay, period time.Duration, target TimerTarget, input any) error
ScheduleRecurring makes the timer timerID call a timed action's handler first after delay, then once every period, until it is cancelled or replaced (1.12). Scheduling again with the same target and period keeps the next due and takes the input.
func SendAndAwait ¶
func SendAndAwait[R any](ctx context.Context, workflowID, id, wire string, input any, within time.Duration) (R, error)
SendAndAwait sends wire to the workflow workflowID (instance id) and waits up to within for the workflow to end, answering its final state (1.18). A workflow that failed is a *RefusalError with code WorkflowFailed and its step and reason in Details; one still running after within is a refusal with code Timeout, and the workflow runs on.
func SpanProblem ¶
SpanProblem is what is wrong with a signed URL's span, or "".
func TableOf ¶
TableOf is the table a view's rows are kept in, for a declared query's statement to name.
func Version ¶
func Version() string
Version is the SDK's version as the service's build recorded it, without the "v": the version of the ankka-go module the service depends on, or "0.0.0" when the dependency is replaced by a local directory, when the SDK is itself the main module, or when the build recorded nothing (V5).
func Watch ¶
func Watch[Row any](ctx context.Context, viewID string, target WatchTarget) iter.Seq2[WatchEvent[Row], error]
Watch follows target in the view viewID (1.17): the rows now, CaughtUp, then each change, until ctx ends or the watch does (a *WatchEndedError).
func WatchEvents ¶
WatchEvents is a watch as server-sent events: each row as row carrying {key, row}, each removal as removed carrying {key}, the marker as caught-up, and a watch that ended with a reason as a last event ended carrying {reason}, so a page is told why.
func WithClient ¶
WithClient is ctx carrying c, so the calls below can be made from outside a handler.
Types ¶
type ACL ¶
type ACL struct {
// contains filtered or unexported fields
}
ACL is who may call an endpoint, a route, an MCP endpoint or a tool. There is no default: an endpoint is given one, and a nil ACL is a problem the service names at start.
func AllowClientKeys ¶
func AllowClientKeys() *ACL
AllowClientKeys admits a client key issued for the MCP endpoint (1.20); its subject and attributes are the principal. An MCP endpoint's ACL only.
func AllowIf ¶
func AllowIf(first CallerMatch, rest ...CallerMatch) *ACL
AllowIf admits only the callers named, read from the certificate the platform issued. Outside a cluster every caller is local, and AllowIf admits it.
func Authenticate ¶
Authenticate admits a caller whose token the sidecar verified, issued by one of the issuers named (or by the endpoint's Issuers when none is named here); the principal reaches the handler.
type ActionEffect ¶
type ActionEffect struct {
// contains filtered or unexported fields
}
ActionEffect is what a timed action answers: done, or failed (and retried by the sweeper).
func ActionFail ¶
func ActionFail(code ErrorCode, message string) ActionEffect
ActionFail says the action failed; the sweeper retries it on its schedule.
type AgentComponent ¶
type AgentComponent struct {
// contains filtered or unexported fields
}
AgentComponent is an agent's declaration.
func Agent ¶
func Agent(id string, parts ...Part) *AgentComponent
Agent declares an agent: its handlers (Ask, AskStream) and its Tools, Guardrails, McpServers, MaxToolCallSteps and Role.
type AgentEffect ¶
type AgentEffect struct {
Model string
System string
User string
Context []string
SessionMemory bool
ToolNames []string
GuardrailNames []string
JSONReply bool
SchemaHint string
// contains filtered or unexported fields
}
AgentEffect describes one interaction with a model: which model, the instructions, the context, the tools and guardrails, whether to keep the session's memory, and the shape of the reply. Building one calls no model; the sidecar's loop interprets it and calls back for tools and guardrails. The model's key never lives in this process.
func AgentError ¶
func AgentError(code ErrorCode, message string) AgentEffect
AgentError refuses the request without calling a model.
func AgentModel ¶
func AgentModel(name string) AgentEffect
AgentModel starts an agent effect on the model the sidecar configured under name.
func SystemMessage ¶
func SystemMessage(text string) AgentEffect
SystemMessage starts an agent effect with the system instructions.
func UserMessage ¶
func UserMessage(text string) AgentEffect
UserMessage starts an agent effect with the user's message.
func (AgentEffect) Failure ¶
func (e AgentEffect) Failure() *Refusal
Failure is AgentError's refusal, or nil.
func (AgentEffect) Guardrails ¶
func (e AgentEffect) Guardrails(names ...string) AgentEffect
Guardrails applies the named guardrails.
func (AgentEffect) Memory ¶
func (e AgentEffect) Memory(session bool) AgentEffect
Memory keeps (true) or drops (false) the session's memory; false is for a one-shot classification.
func (AgentEffect) SystemMessage ¶
func (e AgentEffect) SystemMessage(text string) AgentEffect
SystemMessage sets the system instructions.
func (AgentEffect) ThenReply ¶
func (e AgentEffect) ThenReply() AgentEffect
ThenReply replies with the model's text.
func (AgentEffect) ThenReplyJSON ¶
func (e AgentEffect) ThenReplyJSON(schemaHint string) AgentEffect
ThenReplyJSON replies with the model's JSON, decoded by the handler's reply type. The schema is not sent to the model: say what you want in the system message.
func (AgentEffect) Tools ¶
func (e AgentEffect) Tools(names ...string) AgentEffect
Tools offers the model the named tools.
func (AgentEffect) UserMessage ¶
func (e AgentEffect) UserMessage(text string) AgentEffect
UserMessage sets the user's message.
func (AgentEffect) WithContext ¶
func (e AgentEffect) WithContext(text string) AgentEffect
WithContext adds context the user did not type (a retrieved document, an entity's state), kept apart from the user message so memory records what the user said.
func (AgentEffect) WithModel ¶
func (e AgentEffect) WithModel(name string) AgentEffect
WithModel uses the model the sidecar configured under name.
type AgentGuardrail ¶
type AgentGuardrail interface {
// contains filtered or unexported methods
}
AgentGuardrail is a check an agent consults: Guardrail or ResultGuardrail.
func Guardrail ¶
func Guardrail(name string, f func(ctx context.Context, stage GuardrailStage, text string) (string, error)) AgentGuardrail
Guardrail is a check named name of what goes to the model and what it answers, consulted where the effect names it: "" passes, anything else blocks with that reason. An error blocks too.
func ResultGuardrail ¶
func ResultGuardrail(name string, f func(ctx context.Context, tool, text string) (string, error)) AgentGuardrail
ResultGuardrail is a check of what an MCP server's tool answered, before the model is told it (1.11): "" passes, anything else blocks with that reason.
type AgentInstance ¶
AgentInstance is calls to one instance of an autonomous agent, by the id the caller chose.
func Instance ¶
func Instance(componentID, instanceID string) AgentInstance
Instance is the instance instanceID of the autonomous agent componentID.
func (AgentInstance) Decide ¶
Decide decides one of the instance's approval requests. Approved, the tool runs and the task goes on; refused, the model is told so. A request already decided is a conflict.
func (AgentInstance) Notifications ¶
func (a AgentInstance) Notifications(ctx context.Context) iter.Seq2[Notification, error]
Notifications is what the instance does from now on, as it happens; nothing is replayed. The sequence ends when ctx does, or with the error that ended it.
func (AgentInstance) Resume ¶
func (a AgentInstance) Resume(ctx context.Context) error
Resume lets a suspended instance go on.
func (AgentInstance) State ¶
func (a AgentInstance) State(ctx context.Context) (InstanceState, error)
State is the instance's state.
type AgentScope ¶
type AgentScope struct {
ComponentID string
// SessionID is the session; for an autonomous agent, "task:<task id>".
SessionID string
// TaskID is the task an autonomous agent's tool, guardrail or rule runs for; "" for an agent.
TaskID string
Metadata Metadata
}
AgentScope is what an agent's handler, tool or guardrail sees of the session it runs for.
type AgentTool ¶
type AgentTool interface {
// contains filtered or unexported methods
}
AgentTool is a tool an agent or an autonomous agent offers the model: Tool or ApprovedTool.
func ApprovedTool ¶
func ApprovedTool[I, R any](name, description string, within time.Duration, f func(ctx context.Context, input I) (R, error)) AgentTool
ApprovedTool is a Tool that waits for a person's decision before it runs (1.11). Within zero waits until decided; otherwise the platform refuses it when that much time passes undecided.
func Tool ¶
func Tool[I, R any](name, description string, f func(ctx context.Context, input I) (R, error)) AgentTool
Tool is a tool named name the model may call with an I, its JSON Schema derived from I's fields (a field's `desc` tag describes it), answered with f's result: text as it is, anything else in its encoding. An error is told to the model, which usually corrects itself; it is never thrown. A tool may run more than once for one call of the model, after a crash, so a side effect should tolerate a repeat.
type AnyTaskType ¶
type AnyTaskType interface {
Name() string
// contains filtered or unexported methods
}
AnyTaskType is a task type of any result type.
type ApprovalAwaitedError ¶
type ApprovalAwaitedError struct{ Requests []ApprovalRequest }
ApprovalAwaitedError is an agent's turn waiting for a person's decision (1.11).
func (*ApprovalAwaitedError) Error ¶
func (e *ApprovalAwaitedError) Error() string
type ApprovalRequest ¶
type ApprovalRequest struct {
ID string
Tool string
ArgumentsJSON string
RequestedAt time.Time
ExpiresAt *time.Time
}
ApprovalRequest is a tool call waiting for a person's decision.
type Assigned ¶
type Assigned struct {
Accepted []string `json:"accepted"`
Refused map[string]AssignmentRefusal `json:"refused"`
}
Assigned is what an instance answered an assignment with.
type Assignee ¶
type Assignee struct {
ComponentID string `json:"componentId"`
InstanceID string `json:"instanceId"`
}
Assignee is the instance a task is assigned to.
type AssignmentRefusal ¶
AssignmentRefusal is why an instance refused a task.
type Attachment ¶
Attachment is a file a task carries: its text inline, or a URI it is read from.
type AutonomousComponent ¶
type AutonomousComponent struct {
// contains filtered or unexported fields
}
AutonomousComponent is an autonomous agent's declaration.
func Autonomous ¶
func Autonomous(id, description string, parts ...Part) *AutonomousComponent
Autonomous declares an autonomous agent: what it is for, the task types it Accepts, and its Instructions, Tools, Guardrails, McpServers, AutonomousModel and Settings.
func (*AutonomousComponent) ID ¶
func (a *AutonomousComponent) ID() string
ID is the autonomous agent's component id.
type AutonomousSettings ¶
type AutonomousSettings struct {
ApproachingBudgetAt float64
RepeatedFailureAt int
MaxConsecutiveFailures int
DependencyStuckAfter time.Duration
}
AutonomousSettings tune when an instance notices it is in trouble. A zero field keeps the platform's default: 0.8 of the budget, 3 repeated failures, 5 consecutive failures, five minutes waiting on a dependency.
type Bucket ¶
type Bucket interface {
// Name is the descriptor's name for it; "" for the unnamed bucket.
Name() string
Exposure() Exposure
// Put keeps length bytes of body under name, as contentType, replacing what was there. A body
// that ends before length fails and keeps nothing, and the old object, if any, stays.
Put(ctx context.Context, name string, body io.Reader, length int64, contentType string) error
// Get is the object kept under name, or nil when there is none.
Get(ctx context.Context, name string) (*StoredObject, error)
// Stat is what is kept under name, without its bytes, or nil.
Stat(ctx context.Context, name string) (*ObjectInfo, error)
// List is every object whose name begins with prefix, in name order; pages are read as it is
// walked.
List(ctx context.Context, prefix string) iter.Seq2[ObjectEntry, error]
// Delete removes what is kept under name. Removing nothing is not an error.
Delete(ctx context.Context, name string) error
// SignedURL is a URL a browser may use, until span has passed (15 minutes when 0, at most seven
// days), to read or keep the object under name. Computed: no request reaches the store. A signed
// bucket's, or the unnamed bucket's when the service sets exposeObjectStorage.
SignedURL(name string, access SignedAccess, span time.Duration) (string, error)
// PublicURL is the address a browser reads the object under name at, with no signature: a public
// bucket's only.
PublicURL(name string) (string, error)
}
Bucket is one bucket. Its objects are named with / between segments, so a listing by prefix reads like a directory; it is not one. A put replaces the whole object or leaves the old one.
type Caller ¶
type Caller struct {
Kind CallerKind
// Project and Name name a calling service.
Project string
Name string
// Organization names a calling machine's organization, Name the machine.
Organization string
}
Caller is which workload sent a request, as the platform established it from the client certificate, never from anything the request says about itself.
func CallerFrom ¶
CallerFrom is the caller of the request ctx carries; a request with nothing said is local.
type CallerKind ¶
type CallerKind int
CallerKind is what sort of workload sent a request.
const ( // CallerLocal is the local machine, outside a cluster, where there is no certificate. CallerLocal CallerKind = iota // CallerGateway is the internet, through the installation's gateway. CallerGateway // CallerService is a named service of this installation. CallerService // CallerMachine is a machine registered on an organization (protocol 1.15). CallerMachine )
func (CallerKind) String ¶
func (k CallerKind) String() string
type CallerMatch ¶
type CallerMatch struct {
// contains filtered or unexported fields
}
CallerMatch is one kind of caller an AllowIf admits.
func AnyInProject ¶
func AnyInProject() CallerMatch
AnyInProject is any service of this service's project.
func Granted ¶
func Granted() CallerMatch
Granted is whoever this service's project has granted the route to: a service of another project, or a registered machine (1.15). A route that does not name it can never be granted.
func Internet ¶
func Internet() CallerMatch
Internet is a caller through the installation's gateway.
func ServiceIn ¶
func ServiceIn(project, name string) CallerMatch
ServiceIn is the service name of project.
func ServiceNamed ¶
func ServiceNamed(name string) CallerMatch
ServiceNamed is the service name of this service's own project.
type CaseOf ¶
type CaseOf[I any] struct { // contains filtered or unexported fields }
CaseOf is one case of a sum type: a struct type and its discriminator. Built by Case.
type ChangeScope ¶
type ChangeScope struct {
ComponentID string
// Subject is the id of the source instance the change came from (ce-subject).
Subject string
// Sequence is the change's sequence number (an event's, or a key value state's revision), 0
// when it has none, as a topic's message has none.
Sequence int64
// SourceID is, for a keyed view, the component the change came from.
SourceID string
// Deleted is whether the source instance was deleted.
Deleted bool
// Standing is where a workflow source stood, or nil for a change from an entity or a topic.
Standing *Standing
// Installation is where a replicated entity's change was written (protocol 1.19), else "".
Installation string
// Local is whether the change was written at this installation: false only for a replicated
// entity's mirrored change.
Local bool
// Metadata is the change's metadata as it arrived.
Metadata Metadata
}
ChangeScope is the change a view's or a consumer's handler is handling.
func ChangeFrom ¶
func ChangeFrom(ctx context.Context) (ChangeScope, bool)
ChangeFrom is the change ctx's handler is handling, when it is a view's or a consumer's.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the way back to the sidecar beside this process: calls to the service's own components, view queries, timers, secrets, client keys and calls to other services. A handler reaches it through its context (ClientFrom); every call carries the handler's metadata, so the runtime makes it as that handler, and the trace nests under it. One channel is opened, lazily.
func ClientFrom ¶
ClientFrom is the client ctx carries, or nil outside a handler.
type ClientKey ¶
type ClientKey struct {
ID string
Subject string
Attributes map[string]string
Label string
Endpoint string
Scope []string
IssuedAt time.Time
ExpiresAt *time.Time
LastUsed *time.Time
RevokedAt *time.Time
}
ClientKey is a key as listed: never the key, nor anything it could be derived from.
type ClientKeyRequest ¶
type ClientKeyRequest struct {
Subject string
ExpiresAfter time.Duration
ExpiresAt time.Time
Never bool
// Endpoint is the MCP endpoint's path; required when the service has several.
Endpoint string
// Scope names the tools the key may call; empty is every tool.
Scope []string
// Attributes become the principal's claims.
Attributes map[string]string
Label string
}
ClientKeyRequest is what a key is issued for. Exactly one of ExpiresAfter, ExpiresAt and Never.
type ClientKeyStore ¶
type ClientKeyStore struct {
// contains filtered or unexported fields
}
ClientKeyStore issues, lists and revokes the service's client keys for its MCP endpoints (1.20).
func ClientKeys ¶
func ClientKeys(ctx context.Context) *ClientKeyStore
ClientKeys is the client key store, as the handler ctx belongs to.
func (*ClientKeyStore) Issue ¶
func (s *ClientKeyStore) Issue(req ClientKeyRequest) (IssuedClientKey, error)
Issue issues a key for req.
func (*ClientKeyStore) List ¶
func (s *ClientKeyStore) List() ([]ClientKey, error)
List is every key the service has issued.
func (*ClientKeyStore) Revoke ¶
func (s *ClientKeyStore) Revoke(id string) error
Revoke revokes the key id; one already revoked is no error.
type Codec ¶
type Codec[T any] interface { Manifest() string ContentType() string Encode(value T) ([]byte, error) Decode(data []byte) (T, error) }
Codec turns a value of T into the bytes of a Payload and back, under a manifest and a content type. The default codec for a type is CodecFor's; a developer may supply their own with CustomCodec, and then portability across languages is their contract.
func CodecFor ¶
func CodecFor[T any](opts ...CodecOption) Codec[T]
CodecFor is the default codec for T: the text codec for a top-level string, integer, double, boolean or time.Duration ("duration-millis"); the binary codec for []byte, Done, Unit and a top-level pointer ("option[<inner>]"); JSON under the type's name for everything else. A type the encoding cannot describe gives a codec whose every call fails naming why; a service or a test kit that uses it refuses to start.
type CodecOption ¶
type CodecOption func(*codecSettings)
CodecOption changes a default codec.
func Manifest ¶
func Manifest(name string) CodecOption
Manifest names a default JSON codec's manifest, which is what the journal stores beside each value; without it the manifest is the type's name.
type CommandScope ¶
type CommandScope struct {
ComponentID string
EntityID string
// Sequence is the sequence number of the last event applied before the command; 0 for a fresh entity.
Sequence int64
Metadata Metadata
// Installation is the installation handling the command, for a replicated entity (1.19); "" when none is named.
Installation string
// AtHome reports whether this installation is the replicated entity's home: false only for a
// query a follower answers, true for an entity that is not replicated.
AtHome bool
// Attribution is the subject of the principal who made the original call (1.22), "" when none named one.
Attribution string
// ForwardedFrom is the installation the command was forwarded from to its home (1.22), "" when it was not.
ForwardedFrom string
}
CommandScope is what a stateful component's command sees of itself.
func CommandFrom ¶
func CommandFrom(ctx context.Context) (CommandScope, bool)
CommandFrom is the command ctx carries, and whether it carries one.
type ConsumerComponent ¶
type ConsumerComponent[Msg any] struct { // contains filtered or unexported fields }
ConsumerComponent is a consumer's declaration: it reacts to each of a source's changes, at least once, optionally producing onward to a topic. A graph consumer is one too (GraphConsumer).
func Consumer ¶
func Consumer[Msg any](id string, source Source, f func(ctx context.Context, message Msg) (ConsumerEffect, error), parts ...Part) *ConsumerComponent[Msg]
Consumer declares a consumer of source: f handles each change, answering ConsumerDone, ConsumerIgnore, Produce or ProduceAll; an error, or a panic, fails the change, which comes again. The parts are its options (ProducesTo, WhenDeleted, SourceVersion, MirroredChanges).
func GraphConsumer ¶
func GraphConsumer[Msg any](id string, source Source, topic string, f func(ctx context.Context, message Msg) (GraphEffect, error), parts ...Part) *ConsumerComponent[Msg]
GraphConsumer declares a consumer that publishes a graph to topic: f answers the elements a change leaves in which state, each published as a graph delta under its element key, at its stated version or the change's sequence number. The topic must be compacted to hold the graph.
func (*ConsumerComponent[Msg]) ID ¶
func (c *ConsumerComponent[Msg]) ID() string
ID is the consumer's component id.
type ConsumerEffect ¶
type ConsumerEffect struct {
// contains filtered or unexported fields
}
ConsumerEffect is what a consumer's handler answers: done, ignored, or messages produced onward.
func ConsumerIgnore ¶
func ConsumerIgnore() ConsumerEffect
ConsumerIgnore acknowledges the change, saying it was of no interest.
func Produce ¶
func Produce(payload any, md ...Metadata) ConsumerEffect
Produce publishes payload to the topic the consumer produces to, with optional headers.
func ProduceAll ¶
func ProduceAll(messages ...Message) ConsumerEffect
ProduceAll publishes several messages for this change, in order. The change is handled when the broker has accepted every one; if one is refused the change comes again and all are published again. None publishes nothing and is handled at once.
func (ConsumerEffect) Messages ¶
func (e ConsumerEffect) Messages() []Message
Messages are what the effect publishes.
type Contract ¶
Contract is what a topic carries, as a project declares it and a component states it: a name and the fingerprint of the schema document. The platform refuses, at a service's start, a side whose name or fingerprint is not the declared one; the name travels as every message's ce-type. Nothing checks a message against the schema.
The fingerprint is "sha256:" and the hex SHA-256 of the document under RFC 8785 (the JSON Canonicalization Scheme), so whitespace and key order in a saved file do not change it and a changed field does.
func ContractFromBytes ¶
ContractFromBytes is the contract name of a schema document held in memory.
func ContractFromFile ¶
ContractFromFile is the contract name of the schema document at path.
type Decision ¶
Decision is a person's decision of an approval request: By, who decided, is required.
type Declaration ¶
type Declaration interface {
// contains filtered or unexported methods
}
A Declaration is a component or an endpoint, built by its constructor and handed to NewService. Only this package's constructors make one.
type DeclaredQuery ¶
type DeclaredQuery struct {
Name string
Statement string
// Watched is whether it may be watched (protocol 1.17): its statement selects row_key beside
// payload, has no limit and does not aggregate.
Watched bool
}
DeclaredQuery is a question a view can be asked by name: one SQL statement over the view's own table (TableOf), whose values are the :names it holds. The platform checks it when the service starts and binds each value as a parameter.
func WatchedQuery ¶
func WatchedQuery(name, statement string) DeclaredQuery
WatchedQuery is a declared query that may also be watched.
type DecodingError ¶
DecodingError is a document the codec refuses, with where in the document the refusal is.
func (*DecodingError) Error ¶
func (e *DecodingError) Error() string
type Delta ¶
type Delta struct {
// Kind is node, edge or tombstone; Element, of a tombstone, is node or edge.
Kind, Element string
ID string
Version int64
Labels []string
Type string
From, To string
// Properties hold string, bool, int64 and float64 values, or slices of one of them.
Properties map[string]any
}
Delta is a graph delta as read back: one element's whole state at a version, or a tombstone.
type DirectoryStorage ¶
type DirectoryStorage struct {
// contains filtered or unexported fields
}
DirectoryStorage is a service's buckets in a directory on a developer's machine: what a service keeps when it runs with no variable of an object store. The runtime's layout exactly, so a Scala service and a Go one read each other's: one directory per bucket under the root (_default for the unnamed one), an object's name encoded into one file name under objects/ (its hash when too long), and beside it under meta/ its name, content type, length and when it was kept. A put writes a temporary file and moves it into place, so a body that ends short leaves the old object.
A signed URL and a public address point at the service's own HTTP port, under /_ankka/storage, which the SDK serves through the sidecar while this is the service's store.
func NewDirectoryStorage ¶
func NewDirectoryStorage(root, address string) *DirectoryStorage
NewDirectoryStorage is a directory store under root, with the unnamed bucket and any named one asked for, as private, and URLs at address (http://127.0.0.1:9000 when "").
func (*DirectoryStorage) Buckets ¶
func (s *DirectoryStorage) Buckets() []Bucket
func (*DirectoryStorage) Default ¶
func (s *DirectoryStorage) Default() (Bucket, error)
func (*DirectoryStorage) Root ¶
func (s *DirectoryStorage) Root() string
Root is the directory the store keeps its buckets under.
type Done ¶
type Done struct{}
Done is the reply of a handler that answers nothing but that it finished: manifest "done", zero bytes.
type Effect ¶
type Effect[S, E, R any] struct { // contains filtered or unexported fields }
Effect is what an event sourced entity's command returns: events to persist, then a reply computed from the state after them, or no reply. Built by Persist.
type Element ¶
type Element struct {
// contains filtered or unexported fields
}
Element is a graph element as a handler describes it: a node, an edge, or a tombstone marking one deleted. Without a version it takes its change's sequence number. An element the merge sink would refuse is refused when the result is published, naming why.
func Edge ¶
func Edge(id, typ, from, to string, opts ...ElementOption) Element
Edge is an edge of type typ from one node to another, with WithProperties.
func EdgeTombstone ¶
func EdgeTombstone(id, typ, from, to string, opts ...ElementOption) Element
EdgeTombstone marks an edge deleted, naming its type and endpoints so it is found without a scan.
func Node ¶
func Node(id string, opts ...ElementOption) Element
Node is a node, with Labels and WithProperties.
func NodeTombstone ¶
func NodeTombstone(id string, opts ...ElementOption) Element
NodeTombstone marks a node deleted. It stays in the graph, marked, so a straggling older delta cannot bring it back.
type ElementOption ¶
type ElementOption func(*Element)
ElementOption is an option of an element.
func AtVersion ¶
func AtVersion(v int64) ElementOption
AtVersion is the element's version, in place of its change's sequence number: 1 or more.
func Labels ¶
func Labels(labels ...string) ElementOption
Labels are a node's labels, each an identifier.
func WithProperties ¶
func WithProperties(p Properties) ElementOption
WithProperties are an element's properties.
type EncodingError ¶
EncodingError is a value the codec cannot write, with where in the value it is.
func (*EncodingError) Error ¶
func (e *EncodingError) Error() string
type Endpoint ¶
type Endpoint struct {
// contains filtered or unexported fields
}
Endpoint is an HTTP endpoint's declaration: a prefix, who may call, and its routes. The sidecar serves the routes on the service's HTTP port, applies the ACL and forwards each request here; the process never binds an HTTP port.
func NewEndpoint ¶
func NewEndpoint(prefix string, acl *ACL, routes ...RouteOrOption) *Endpoint
NewEndpoint declares an endpoint at prefix ("/carts") admitting the callers acl admits, with its routes. The ACL is required and has no default.
type EndpointOption ¶
type EndpointOption struct {
// contains filtered or unexported fields
}
EndpointOption is an option of NewEndpoint, given among its routes.
func Issuers ¶
func Issuers(issuers ...IssuerRef) EndpointOption
Issuers are the issuers an authenticated route of the endpoint accepts when it names none.
type Enum ¶
type Enum[E ~string] struct { // contains filtered or unexported fields }
Enum is the registration of a named string type's values, written as {"type":"Ready"} as the Scala codecs write a fieldless enum; a bare string is accepted on read. Built by Enumeration.
func Enumeration ¶
Enumeration registers the values of the string type E.
type ErrorCode ¶
type ErrorCode int
ErrorCode is the code of a refusal: what a caller sees, and the HTTP status it becomes at an endpoint.
const ( Internal ErrorCode = 0 BadRequest ErrorCode = 1 Forbidden ErrorCode = 3 NotFound ErrorCode = 4 Conflict ErrorCode = 5 Timeout ErrorCode = 6 // WorkflowFailed: a workflow a caller waited for failed or was deleted (protocol 1.18); the step and // the reason are in the refusal's Details. WorkflowFailed ErrorCode = 8 // NotHome: a replicated entity's copy here cannot answer (1.19); the message names its home. NotHome ErrorCode = 9 )
The refusal codes, as the protocol numbers them.
func (ErrorCode) HTTPStatus ¶
HTTPStatus is the status a refusal with this code answers at an endpoint.
type EventScope ¶
type EventScope struct {
Installation string
Local bool
Sequence int64
Attribution string
ForwardedFrom string
}
EventScope is where an event being applied was written (1.19, 1.22), read inside an entity's apply function through EventFrom.
type EventSourcedEntity ¶
type EventSourcedEntity[S, E any] struct { // contains filtered or unexported fields }
EventSourcedEntity is an event sourced entity's declaration: its id, the events it persists, its empty state, how an event changes the state, and its handlers. Its state is the fold of its events, recovered from its journal; the sidecar holds the journal and this process the state, for as long as the sidecar keeps the instance's conversation open.
func EventSourced ¶
func EventSourced[S, E any](id string, events *SumType[E], empty func(entityID string) S, apply func(state S, event E) S, parts ...Part) *EventSourcedEntity[S, E]
EventSourced declares an event sourced entity. events is the registration of the event interface's cases (nil when E is a struct, a single kind of event); empty is the state of an entity with no events, given its id; apply folds one event into the state and must do nothing else. The parts are its handlers (Command, Query) and options (SnapshotEvery, StateCodec, EventCodec, Replicated, ApplyWithContext).
func (*EventSourcedEntity[S, E]) ID ¶
func (e *EventSourcedEntity[S, E]) ID() string
ID is the entity's component id.
type Exposure ¶
type Exposure string
Exposure is how a bucket is reached from outside the installation.
type GraphEffect ¶
type GraphEffect struct {
// contains filtered or unexported fields
}
GraphEffect is what a graph consumer's handler answers: elements to publish, done, or ignored.
func GraphIgnore ¶
func GraphIgnore() GraphEffect
GraphIgnore acknowledges the change, saying it was of no interest.
func Publish ¶
func Publish(elements ...Element) GraphEffect
Publish publishes these elements, each as a delta under its own key. None publishes nothing.
func (GraphEffect) Elements ¶
func (e GraphEffect) Elements() []Element
Elements are what the effect publishes.
type GraphError ¶
GraphError is why an element or a result was refused: Why is the name the shared fixtures use (id, endpoints, identifier, reserved, property-value, integer-range, version, duplicate, no-sequence).
func (*GraphError) Error ¶
func (e *GraphError) Error() string
type GuardrailStage ¶
type GuardrailStage string
GuardrailStage is what a guardrail checks: what goes to the model, or what it answered.
const ( // GuardrailInput is what goes to the model. GuardrailInput GuardrailStage = "input" // GuardrailOutput is what the model answered. GuardrailOutput GuardrailStage = "output" )
type HttpProblem ¶
HttpProblem is an endpoint's answer with a status of its own and a plain text body, returned as a handler's error. A RefusalError returned from an endpoint answers its code's status.
func (*HttpProblem) Error ¶
func (e *HttpProblem) Error() string
type InstancePhase ¶
type InstancePhase string
InstancePhase is what an instance is doing.
const ( PhaseIdle InstancePhase = "idle" PhaseWorking InstancePhase = "working" PhaseWaiting InstancePhase = "waiting" PhaseSuspended InstancePhase = "suspended" PhaseTerminated InstancePhase = "terminated" )
The phases of an instance.
type InstanceState ¶
type InstanceState struct {
Phase InstancePhase
CurrentTask string
Iteration int
Queued []string
// Awaiting are the approval requests the current task's tool calls wait on; while any does, the
// instance calls no model.
Awaiting []ApprovalRequest
}
InstanceState is an instance as its record holds it.
type IssuedClientKey ¶
IssuedClientKey is a key as issued: the key itself is here and nowhere else.
type IssuerRef ¶
type IssuerRef struct {
// contains filtered or unexported fields
}
IssuerRef names an issuer by the service's own name for it, as ANKKA_AUTH_ISSUERS gives it.
type KeyValueBuilder ¶
type KeyValueBuilder[S, R any] struct { // contains filtered or unexported fields }
KeyValueBuilder is UpdateState's, KeepState's or DeleteState's result.
func DeleteState ¶
func DeleteState[S, R any]() KeyValueBuilder[S, R]
DeleteState deletes the entity.
func KeepState ¶
func KeepState[S, R any]() KeyValueBuilder[S, R]
KeepState leaves the state as it is, for a command that only replies.
func UpdateState ¶
func UpdateState[S, R any](s S) KeyValueBuilder[S, R]
UpdateState replaces the state with s.
func (KeyValueBuilder[S, R]) DeleteEntity ¶
func (b KeyValueBuilder[S, R]) DeleteEntity() KeyValueBuilder[S, R]
DeleteEntity deletes the entity once the state is stored.
func (KeyValueBuilder[S, R]) ExpireAfter ¶
func (b KeyValueBuilder[S, R]) ExpireAfter(d time.Duration) KeyValueBuilder[S, R]
ExpireAfter deletes the entity d after this command, unless another comes first.
func (KeyValueBuilder[S, R]) ThenNoReply ¶
func (b KeyValueBuilder[S, R]) ThenNoReply() KeyValueEffect[S, R]
ThenNoReply answers nothing.
func (KeyValueBuilder[S, R]) ThenReply ¶
func (b KeyValueBuilder[S, R]) ThenReply(compute func(S) R) KeyValueEffect[S, R]
ThenReply replies with a value computed from the new state.
func (KeyValueBuilder[S, R]) ThenReplyState ¶
func (b KeyValueBuilder[S, R]) ThenReplyState() KeyValueEffect[S, R]
ThenReplyState replies with the new state; the reply type must be the state's type.
func (KeyValueBuilder[S, R]) ThenReplyValue ¶
func (b KeyValueBuilder[S, R]) ThenReplyValue(v R) KeyValueEffect[S, R]
ThenReplyValue replies with v.
type KeyValueEffect ¶
type KeyValueEffect[S, R any] struct { // contains filtered or unexported fields }
KeyValueEffect is what a key value entity's command returns: a new state (or none), then a reply.
type KeyValueEntity ¶
type KeyValueEntity[S any] struct { // contains filtered or unexported fields }
KeyValueEntity is a key value entity's declaration: its id, its empty state and its handlers. Its state is kept whole by the sidecar, replaced by each command that updates it.
func KeyValue ¶
func KeyValue[S any](id string, empty func(entityID string) S, parts ...Part) *KeyValueEntity[S]
KeyValue declares a key value entity. empty is the state of an entity nothing has written, given its id. The parts are its handlers (Update, Query) and options (StateCodec).
func (*KeyValueEntity[S]) ID ¶
func (e *KeyValueEntity[S]) ID() string
ID is the entity's component id.
type KeyedViewComponent ¶
type KeyedViewComponent[Row any] struct { // contains filtered or unexported fields }
KeyedViewComponent is a keyed view's declaration: several entities' changes, each through a handler of its own, written to whichever rows a change is about, by key. The sidecar handles one change at a time across all of them (protocol 1.13).
func KeyedView ¶
func KeyedView[Row any](id string, parts ...Part) *KeyedViewComponent[Row]
KeyedView declares a keyed view: one On per entity it reads, and its options (Queries, SourceVersion, RowCodec).
func (*KeyedViewComponent[Row]) ID ¶
func (v *KeyedViewComponent[Row]) ID() string
ID is the keyed view's component id.
type KeyedViewEffect ¶
type KeyedViewEffect[Row any] struct { // contains filtered or unexported fields }
KeyedViewEffect is what a keyed view's handler says to do with one change: rows to write and rows to delete, in order. Empty is nothing. A row is moved by deleting its old key and writing the new.
func AllRows ¶
func AllRows[Row any](effects ...KeyedViewEffect[Row]) KeyedViewEffect[Row]
AllRows is several keyed view effects as one, in order.
func DeleteRowAt ¶
func DeleteRowAt[Row any](key string) KeyedViewEffect[Row]
DeleteRowAt deletes key's row.
func IgnoreRows ¶
func IgnoreRows[Row any]() KeyedViewEffect[Row]
IgnoreRows writes and deletes nothing.
func UpdateRowAt ¶
func UpdateRowAt[Row any](key string, row Row) KeyedViewEffect[Row]
UpdateRowAt writes row under key.
func (KeyedViewEffect[Row]) Changes ¶
func (e KeyedViewEffect[Row]) Changes() []RowChange[Row]
Changes are the effect's rows, in order.
type LocalDate ¶
type LocalDate struct {
// contains filtered or unexported fields
}
LocalDate is a date with no time and no zone, "2026-09-23", as java.time.LocalDate.
func LocalDateOf ¶
LocalDateOf is t's date, in t's own location.
func NewLocalDate ¶
NewLocalDate is the date in the year, month and day given.
func ParseLocalDate ¶
ParseLocalDate reads "YYYY-MM-DD", refusing a date that does not exist.
type LocalDateTime ¶
type LocalDateTime struct {
// contains filtered or unexported fields
}
LocalDateTime is a date and a time of day with no zone, "2026-09-23T10:00:00", as java.time.LocalDateTime.
func LocalDateTimeOf ¶
func LocalDateTimeOf(t time.Time) LocalDateTime
LocalDateTimeOf is t's wall clock in t's own location, written as java.time.LocalDateTime.toString writes it: seconds omitted when they and the fraction are zero, the fraction in 3, 6 or 9 digits.
func ParseLocalDateTime ¶
func ParseLocalDateTime(text string) (LocalDateTime, error)
ParseLocalDateTime reads "YYYY-MM-DDTHH:MM[:SS[.fraction]]", refusing a time that does not exist. The value keeps the text it was read from, so it is written back exactly.
func (LocalDateTime) IsZero ¶
func (d LocalDateTime) IsZero() bool
IsZero reports whether d was never set.
func (LocalDateTime) Time ¶
func (d LocalDateTime) Time() time.Time
Time is d's wall clock read as UTC.
type McpEndpoint ¶
type McpEndpoint struct {
// contains filtered or unexported fields
}
McpEndpoint is an MCP endpoint's declaration.
func NewMcpEndpoint ¶
func NewMcpEndpoint(path string, acl *ACL, parts ...McpPart) *McpEndpoint
NewMcpEndpoint declares an MCP endpoint at path ("/mcp") admitting the callers acl admits: AllowClientKeys(), Authenticate(...), AnyOf(...) or any other rule. The ACL is required.
type McpPart ¶
type McpPart interface {
// contains filtered or unexported methods
}
McpPart is a tool of an MCP endpoint, or one of its options.
func Brokered ¶
func Brokered() McpPart
Brokered has the platform sign people in for clients that cannot hold a token; the endpoint's ACL must admit Authenticate.
func McpCommandRef ¶
func McpCommandRef(name, description, componentID, handler, idArg string, opts ...McpToolOption) McpPart
McpCommandRef is a tool that runs the command handler of the entity or workflow componentID; the argument idArg names the instance.
func McpQueryRef ¶
func McpQueryRef(name, description, componentID, handler, idArg string, opts ...McpToolOption) McpPart
McpQueryRef is a tool that runs a query of the entity or workflow componentID; it cannot change anything.
func McpRouteRef ¶
func McpRouteRef(name, description, method, path string, opts ...McpToolOption) McpPart
McpRouteRef is a tool that calls a request route of one of this service's endpoints, in process: method and the full path ("/orders/{day}"), its path parameters the arguments and "body" its body.
func McpTool ¶
func McpTool[I, R any](name, description string, f func(ctx context.Context, input I) (R, error), opts ...McpToolOption) McpPart
McpTool is a tool this process runs: its arguments read as an I (a struct, whose JSON Schema is the tool's), its answer R as text, and as structured content too when it is a record or a map. An error, a refusal or a panic is the tool error the client is shown.
func ServerInfo ¶
ServerInfo is the name and version the endpoint answers initialize with; unsaid, the service's name and its image's tag.
type McpServerOption ¶
McpServerOption says where an MCP server is and how it is reached.
func McpApproval ¶
func McpApproval(within time.Duration) McpServerOption
McpApproval makes every tool of the server wait for a person's decision; within as ApprovedTool.
func McpHeader ¶
func McpHeader(name, variable string) McpServerOption
McpHeader sends the header name with the value of variable, read from the sidecar's environment; the variable starts ANKKA_MCP_.
func McpService ¶
func McpService(project, service, path string) McpServerOption
McpService is a service of the installation serving MCP at path; project "" is this one.
func McpURL ¶
func McpURL(url string) McpServerOption
McpURL is the server's address. Unsaid, with no McpService, ANKKA_MCP_<NAME>_URL must be set.
type McpServerRef ¶
type McpServerRef struct {
// contains filtered or unexported fields
}
McpServerRef is an MCP server an agent lists: the sidecar connects to it, reads its tools and offers them as mcp__<name>__<tool>; the process is never asked to run one.
func McpServer ¶
func McpServer(name string, opts ...McpServerOption) McpServerRef
McpServer names an MCP server ([a-z0-9-]+).
type McpToolOption ¶
type McpToolOption func(*mcpToolDecl)
McpToolOption is an option of an MCP tool.
func InputArgument ¶
func InputArgument(name string) McpToolOption
InputArgument names the argument holding a referenced handler's input; unsaid, a record input's fields sit beside the id, and any other input is the argument "input".
func ToolACL ¶
func ToolACL(acl *ACL) McpToolOption
ToolACL is who may call this tool, beside the endpoint's rule.
type MemoryOption ¶
type MemoryOption func(*MemoryStorage)
MemoryOption is an option of NewMemoryStorage.
func MemoryPublicBase ¶
func MemoryPublicBase(f func(bucket string) string) MemoryOption
MemoryPublicBase is where a public bucket's objects are read: http://memory/public/<bucket> by default, reaching nothing.
func MemoryUnnamed ¶
func MemoryUnnamed(has bool) MemoryOption
MemoryUnnamed says whether the service has the unnamed bucket; it has by default.
func MemoryUnnamedExposure ¶
func MemoryUnnamedExposure(e Exposure) MemoryOption
MemoryUnnamedExposure is the unnamed bucket's exposure: signed by default, so a test may sign a URL for it.
type MemoryStorage ¶
type MemoryStorage struct {
// contains filtered or unexported fields
}
MemoryStorage is a service's buckets in memory: the test kits' store, so a test of a handler that keeps or reads an object needs no object store and no Docker. It applies every rule the other stores apply, in the same words. A signed URL is computed (http://memory/...) and reaches nothing.
func NewMemoryStorage ¶
func NewMemoryStorage(opts ...MemoryOption) *MemoryStorage
NewMemoryStorage is an empty memory store with the unnamed bucket and no named one; Declare adds them.
func (*MemoryStorage) Buckets ¶
func (m *MemoryStorage) Buckets() []Bucket
func (*MemoryStorage) Clear ¶
func (m *MemoryStorage) Clear()
Clear forgets every object; the declared buckets stay.
func (*MemoryStorage) Declare ¶
func (m *MemoryStorage) Declare(name string, exposure Exposure) error
Declare declares a named bucket, before or after the service starts.
func (*MemoryStorage) Default ¶
func (m *MemoryStorage) Default() (Bucket, error)
type Message ¶
Message is one message a consumer publishes: the payload, optionally the record key it is published under (empty: keyed by its subject, the source instance's id), and its headers.
type Metadata ¶
Metadata is a request's or a reply's headers: trace and span ids, a source's id, a timer's name.
func MetadataFrom ¶
MetadataFrom is the metadata of the request or call ctx carries: trace ids, a source's id.
type Notification ¶
type Notification struct {
Type string
ComponentID string
InstanceID string
TaskID string
At time.Time
Fields map[string]json.RawMessage
}
Notification is one thing an instance did: Type names it, and Fields holds every field as sent.
type ObjectEntry ¶
ObjectEntry is one object in a listing.
type ObjectInfo ¶
ObjectInfo is what a bucket keeps under a name, without the bytes.
type Part ¶
type Part interface {
// contains filtered or unexported methods
}
Part is one thing a component's constructor is given beside what it cannot do without: a handler (Command, Query, Update, ...) or an option (SnapshotEvery, StateCodec, ...). A part meant for another kind, or for another state type, is a problem the service names at start.
func Accepts ¶
func Accepts(t AnyTaskType, maxIterations int) Part
Accepts is a task type the agent takes, and how many iterations a task of it may use (at least 1).
func Action ¶
Action is a timed action's handler named wire: given its input, it answers ActionDone or ActionFail. An error, or a panic, fails the timer, which the sweeper retries; a refusal fails it with the refusal's code.
func ApplyWithContext ¶
ApplyWithContext replaces the entity's apply with one that is given a context, from which EventFrom reads where the event was written (1.19, 1.22).
func Ask ¶
Ask is an agent's handler named wire: given its input, it describes the interaction, and the caller is answered with the model's reply once the loop ends.
func AutonomousModel ¶
AutonomousModel is a model named in the sidecar's configuration; unsaid, its default.
func Command ¶
func Command[S, E, I, R any](wire string, f func(ctx context.Context, state S, input I) (Effect[S, E, R], error)) Part
Command is a handler named wire of an event sourced entity: given the state and its input, it answers an effect, persisting events and replying from the state after them, or a refusal (Refuse) as its error. Any other error, or a panic, fails the command and changes nothing.
func EventCodec ¶
EventCodec is the codec the events are encoded with in the journal, in place of the default.
func ForStep ¶
func ForStep(step string, opts ...WorkflowOption) Part
ForStep gives one step its own timeout or recovery, in place of the workflow's.
func Guardrails ¶
func Guardrails(guardrails ...AgentGuardrail) Part
Guardrails are the guardrails an agent or an autonomous agent consults.
func Instructions ¶
Instructions are what the agent is told for every task, beside the task's own.
func MaxToolCallSteps ¶
MaxToolCallSteps is how many tool calls one turn may make; 100 by default.
func McpServers ¶
func McpServers(servers ...McpServerRef) Part
McpServers are the MCP servers whose tools are offered beside the agent's own (1.11).
func MirroredChanges ¶
func MirroredChanges() Part
MirroredChanges gives a consumer that publishes a replicated entity's changes written at other installations too (protocol 1.19); without it, each is published once, where it was written.
func On ¶
func On[Src, Row any](source Source, f func(ctx context.Context, change Src, rows ViewRows[Row]) (KeyedViewEffect[Row], error), deleted ...func(ctx context.Context, rows ViewRows[Row]) (KeyedViewEffect[Row], error)) Part
On is a keyed view's handler of one entity's changes: given the change and the view's own rows, it answers which rows to write and delete, by key. deleted, when given, is what the view does when the entity is deleted; without it, nothing.
func OnChange ¶
func OnChange[Src, Row any](source Source, f func(ctx context.Context, change Src, row *Row) (ViewEffect[Row], error)) Part
OnChange is a view's handler of source's changes: given the change and the current row (nil when there is none yet), it answers what becomes of the row. An error, or a panic, fails the change, which comes again.
func OnDelete ¶
OnDelete is what a view does when its source instance is deleted; without it, the row is deleted with it. An order history keeps a checked-out cart's row.
func ProducesTo ¶
func ProducesTo[Out any](topic string, opts ...PublicationOption) Part
ProducesTo is the topic a consumer publishes to, and the type of what it publishes there: a message's payload must be an Out.
func ProducesWith ¶
func ProducesWith[Out any](topic string, c Codec[Out], opts ...PublicationOption) Part
ProducesWith is ProducesTo with the codec the messages are encoded by, as a manifest of the service's own choosing: ankka.ProducesWith("orders", ankka.CodecFor[Order](ankka.Manifest("order"))).
func Queries ¶
func Queries(queries ...DeclaredQuery) Part
Queries are the view's declared queries (protocol 1.13). A recursive one is a statement like any other, a WITH RECURSIVE over the view's table.
func Query ¶
func Query[S, I, R any](wire string, f func(ctx context.Context, state S, input I) (ReadOnlyEffect[R], error)) Part
Query is a read-only handler named wire, for an event sourced entity, a key value entity or a workflow: it answers from the state with Reply or NoReply and cannot change it.
func Replicated ¶
func Replicated() Part
Replicated declares the entity held at several installations and written only at its home (1.19).
func SnapshotEvery ¶
SnapshotEvery asks the sidecar to keep a snapshot of the state every n events, so recovery folds at most n events. 0, the default, never.
func SourceVersion ¶
SourceVersion is the version of what a view or consumer reads; raising it has a view emptied and read again from its start, and a consumer over a topic read again under a group of its own. 1 when unsaid.
func StateCodec ¶
StateCodec is the codec the state is encoded with, in snapshots and replies of the state, in place of the default.
func Step ¶
func Step[S, I any](name string, f func(ctx context.Context, state S, input I) (StepEffect[S], error)) Part
Step is a step named name of a workflow: given the state and its input (Unit for a step that takes none), it answers what the state becomes and what happens next. An error or a panic is a fault, which the engine retries and fails over as the workflow's settings say; ThenFail is a decision, which ends the workflow.
func Update ¶
func Update[S, I, R any](wire string, f func(ctx context.Context, state S, input I) (KeyValueEffect[S, R], error)) Part
Update is a handler named wire of a key value entity: given the state and its input, it answers an effect, replacing the state (UpdateState), keeping it (KeepState) or deleting the entity (DeleteState), then replying; or a refusal (Refuse) as its error. Any other error, or a panic, fails the command and changes nothing.
func WhenDeleted ¶
func WhenDeleted[Eff ConsumerEffect | GraphEffect](f func(ctx context.Context) (Eff, error)) Part
WhenDeleted is what a consumer does when its source instance is deleted; without it, the deletion is ignored. Eff is ConsumerEffect for a consumer and GraphEffect for a graph consumer, which publishes tombstones here.
func WithAutonomousSettings ¶
func WithAutonomousSettings(s AutonomousSettings) Part
WithAutonomousSettings are the autonomous agent's AutonomousSettings.
func WorkflowCommand ¶
func WorkflowCommand[S, I, R any](wire string, f func(ctx context.Context, state S, input I) (WorkflowEffect[S, R], error)) Part
WorkflowCommand is a handler named wire of a workflow: given the state and its input, it answers an effect, recording a state, starting a step, and replying; or a refusal (Refuse) as its error. A command is answered while a step runs, from the state before the step. Secrets and other services are a step's, never a command's.
func WorkflowTimeout ¶
WorkflowTimeout is a ceiling on the whole workflow, from its start. It is a workflow's setting only, not a step's.
type PauseOptions ¶
PauseOptions say how a step's pause ends: a command moves the workflow on, or After passes and OnTimeout runs (with OnTimeoutInput). Zero After waits for a command.
type PersistBuilder ¶
type PersistBuilder[S, E, R any] struct { // contains filtered or unexported fields }
PersistBuilder is Persist's result, finished by ThenReply, ThenReplyValue, ThenReplyState or ThenNoReply.
func Persist ¶
func Persist[S, E, R any](events ...E) PersistBuilder[S, E, R]
Persist persists the events, in order; none persists nothing, which is how a command replies without changing anything.
func (PersistBuilder[S, E, R]) DeleteEntity ¶
func (b PersistBuilder[S, E, R]) DeleteEntity() PersistBuilder[S, E, R]
DeleteEntity deletes the entity once the events are persisted.
func (PersistBuilder[S, E, R]) ExpireAfter ¶
func (b PersistBuilder[S, E, R]) ExpireAfter(d time.Duration) PersistBuilder[S, E, R]
ExpireAfter deletes the entity d after the events are persisted, unless another command comes first.
func (PersistBuilder[S, E, R]) HandOverTo ¶
func (b PersistBuilder[S, E, R]) HandOverTo(installation string) PersistBuilder[S, E, R]
HandOverTo hands a replicated entity's home to installation once the events are persisted; it must be in the entity's replication set.
func (PersistBuilder[S, E, R]) ReplicateTo ¶
func (b PersistBuilder[S, E, R]) ReplicateTo(installation string) PersistBuilder[S, E, R]
ReplicateTo adds installation to a replicated entity's replication set.
func (PersistBuilder[S, E, R]) StopReplicatingTo ¶
func (b PersistBuilder[S, E, R]) StopReplicatingTo(installation string) PersistBuilder[S, E, R]
StopReplicatingTo takes installation out of a replicated entity's replication set; it keeps its copy.
func (PersistBuilder[S, E, R]) ThenNoReply ¶
func (b PersistBuilder[S, E, R]) ThenNoReply() Effect[S, E, R]
ThenNoReply answers nothing.
func (PersistBuilder[S, E, R]) ThenReply ¶
func (b PersistBuilder[S, E, R]) ThenReply(compute func(S) R) Effect[S, E, R]
ThenReply replies with a value computed from the state after the events.
func (PersistBuilder[S, E, R]) ThenReplyState ¶
func (b PersistBuilder[S, E, R]) ThenReplyState() Effect[S, E, R]
ThenReplyState replies with the state after the events; the reply type must be the state's type.
func (PersistBuilder[S, E, R]) ThenReplyValue ¶
func (b PersistBuilder[S, E, R]) ThenReplyValue(v R) Effect[S, E, R]
ThenReplyValue replies with v.
func (PersistBuilder[S, E, R]) ThenReplyWithMetadata ¶
func (b PersistBuilder[S, E, R]) ThenReplyWithMetadata(compute func(S) R, md Metadata) Effect[S, E, R]
ThenReplyWithMetadata is ThenReply with headers on the reply.
type Principal ¶
type Principal struct {
Subject string
Name string
Email string
EmailVerified bool
Roles []string
// Claims are every other claim of the verified token, as text.
Claims map[string]string
// Issuer is the service's own name for the issuer that verified the token.
Issuer string
}
Principal is the caller an authenticated route was invoked by.
type Problem ¶
type Problem struct {
// Where names the component, endpoint or route, when the problem is one's.
Where string
Message string
}
Problem is something wrong with a service's declarations, found before it starts.
type ProblemsError ¶
type ProblemsError struct{ Problems []Problem }
ProblemsError is a service that refuses to start, with every problem at once.
func (*ProblemsError) Error ¶
func (e *ProblemsError) Error() string
type Properties ¶
Properties are an element's properties: each a string, a bool, an integer, a float, or a non-empty slice of one of those kinds. A float with a whole value counts as an integer, as the sink reads it.
type ProtocolTooOldError ¶
ProtocolTooOldError is a call the sidecar beside this process cannot make, because it speaks an older protocol than the call needs; Needs names the minor ("1.18").
func (*ProtocolTooOldError) Error ¶
func (e *ProtocolTooOldError) Error() string
type Publication ¶
type Publication struct {
// contains filtered or unexported fields
}
Publication is the topic a consumer produces to, with the contract it states and its broker.
type PublicationOption ¶
type PublicationOption func(*Publication)
PublicationOption is an option of a publication.
func StatesContract ¶
func StatesContract(c Contract) PublicationOption
StatesContract is the contract the published messages carry (protocol 1.14).
func ToBroker ¶
func ToBroker(name string) PublicationOption
ToBroker publishes on a declared broker; without it, the installation's (protocol 1.14).
func ToProject ¶
func ToProject(project string) PublicationOption
ToProject publishes to another project's topic, which that project must grant produce on (protocol 1.15).
type RawResponse ¶
RawResponse is a route's answer whose status, content type, headers and body the handler chooses.
type ReadOnlyEffect ¶
type ReadOnlyEffect[R any] struct { // contains filtered or unexported fields }
ReadOnlyEffect is what a query returns, of any stateful kind: a reply or no reply, never a change. It is a type of its own so that a query declared with a persisting handler does not compile.
func ReplyWithMetadata ¶
func ReplyWithMetadata[R any](v R, md Metadata) ReadOnlyEffect[R]
ReplyWithMetadata answers v with headers on the reply.
type Recovery ¶
Recovery is what the engine does when a step fails (returns an error, panics or times out): try it again up to MaxRetries times, then run FailoverTo (a declared step, with no input) or, with none named, fail the workflow.
type RefusalError ¶
type RefusalError struct {
Code ErrorCode
Message string
// Details is what a caller reads without parsing the message: a failed workflow's "step",
// "reason" and "deleted".
Details map[string]string
}
RefusalError is a refusal: a handler's on purpose ("quantity must be positive"), with nothing persisted, or what a call answers when the component it called refused. A handler refuses by returning one, made by Refuse; any other error a handler returns is a failure.
func AsRefusal ¶
func AsRefusal(err error) (*RefusalError, bool)
AsRefusal is the refusal in err's chain, if there is one.
func (*RefusalError) Error ¶
func (e *RefusalError) Error() string
func (*RefusalError) ProtocolError ¶
func (e *RefusalError) ProtocolError() *pb.Error
ProtocolError is the refusal as the protocol's error, so a servicer that fails with it keeps its code.
type ReplicationChange ¶
ReplicationChange is what a replicated entity's handler asks of its home beside its events (1.19): hand the home over, or change the replication set.
type Request ¶
type Request struct {
Method string
// Path is the route's template, relative to the endpoint's prefix ("/{cartId}/items").
Path string
// Params are the path parameters, by the names the template gives them.
Params map[string]string
// Query is the query string in request order; a name may repeat.
Query url.Values
// Headers are the request's headers; Get matches names case-insensitively.
Headers http.Header
// ContentType is the body's media type, as the request said it.
ContentType string
// Body is the raw body; a route's typed body is decoded from it.
Body []byte
// Principal is the caller when the route's ACL authenticated one; nil otherwise.
Principal *Principal
// Caller is which workload sent the request.
Caller Caller
// Metadata carries the trace and span ids of the request's span.
Metadata Metadata
}
Request is what an endpoint handler sees of its HTTP request.
func RequestFrom ¶
RequestFrom is the endpoint request ctx carries, or nil outside an endpoint handler.
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route is one route of an endpoint.
func Patch ¶
func Patch[B, R any](template string, f func(ctx context.Context, req *Request, body B) (R, error)) *Route
Patch is a PATCH route taking a body B and answering a R.
func Post ¶
func Post[B, R any](template string, f func(ctx context.Context, req *Request, body B) (R, error)) *Route
Post is a POST route taking a body B and answering a R.
func Put ¶
func Put[B, R any](template string, f func(ctx context.Context, req *Request, body B) (R, error)) *Route
Put is a PUT route taking a body B and answering a R.
func SSE ¶
func SSE(template string, f func(ctx context.Context, req *Request) iter.Seq2[string, error]) *Route
SSE is a GET route streamed to the caller as server-sent events: each text f yields is one event, and an error ends the stream failed. The stream ends when the sequence does; the context ends when the caller goes away.
func SSEEvents ¶
func SSEEvents(template string, f func(ctx context.Context, req *Request) iter.Seq2[SSEEvent, error]) *Route
SSEEvents is SSE whose frames may be named events beside text: an event a page listens for by name, such as WatchEvents' row, removed and caught-up.
func SocketRoute ¶
SocketRoute is a GET route at template answered by opening a socket (1.9): f runs for as long as the socket is open. Returning nil closes it "finished"; an error closes it "failed".
type RouteOrOption ¶
type RouteOrOption interface {
// contains filtered or unexported methods
}
RouteOrOption is a route of an endpoint, or one of its options.
type S3Storage ¶
type S3Storage struct {
// contains filtered or unexported fields
}
S3Storage is the S3 store's buckets, by name.
type SSEEvent ¶
SSEEvent is one frame of an SSEEvents route: with Name empty, Text sent as an SSE route sends it; otherwise an event under Name (one non-empty line) whose data is Data as JSON (1.11).
type SecretStore ¶
type SecretStore struct {
// contains filtered or unexported fields
}
SecretStore is the service's secret store: named text values the runtime keeps in the service's own database, encrypted with a key this process never sees. It is offered to endpoints, workflow steps, consumers, timed actions and agents; from an entity, a view or a workflow's command every call fails, naming which.
func Secrets ¶
func Secrets(ctx context.Context) *SecretStore
Secrets is the secret store, as the handler ctx belongs to.
func (*SecretStore) Delete ¶
func (s *SecretStore) Delete(name string) error
Delete removes what is kept under name; nothing there is no error.
func (*SecretStore) Get ¶
func (s *SecretStore) Get(name string) (string, bool, error)
Get is the value kept under name, and whether there is one.
func (*SecretStore) Put ¶
func (s *SecretStore) Put(name, value string) error
Put keeps value under name, replacing what was there.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is a set of declarations served to the sidecar beside this process.
func NewService ¶
func NewService(declarations ...Declaration) *Service
NewService is a service of the components and endpoints given, in any order. Nothing is checked until Start, which refuses with every problem at once; Problems lists them before that.
func (*Service) Client ¶
Client is the service's client of its sidecar, once Start or Serve has begun; nil before.
func (*Service) Reported ¶
Reported is every problem the sidecar has reported to this process, in order.
func (*Service) Serve ¶
Serve serves the service on lis until ctx ends, then stops gracefully. The integration test kit uses it; a deployed service uses Start.
func (*Service) SidecarProtocol ¶
SidecarProtocol is the protocol version the sidecar stated at its last discovery, or "".
func (*Service) Start ¶
func (s *Service) Start(ctx context.Context, opts ...StartOption) error
Start serves the service until it is stopped: on SIGTERM or SIGINT, or when ctx ends, it stops accepting, lets handlers in flight finish within the grace period, then returns. It refuses before binding anything when the declarations have problems, naming every one.
type ServiceError ¶
type ServiceError struct {
Service string
Reason ServiceFailureReason
Detail string
}
ServiceError is a call to another service that ended without its answer.
func (*ServiceError) Error ¶
func (e *ServiceError) Error() string
type ServiceFailureReason ¶
type ServiceFailureReason int
ServiceFailureReason is why no answer came from a service.
const ( // ServiceUnanswered: the connection was refused or broke, or no answer came in time. The // service may have received the request. ServiceUnanswered ServiceFailureReason = iota // ServiceUnresolvable: no such service was found; nothing was sent. ServiceUnresolvable // ServiceIdentityMismatch: what answered is not the service asked for; nothing was sent. ServiceIdentityMismatch )
type ServiceRequest ¶
type ServiceRequest struct {
// Project names another project's service; empty is this service's own project.
Project string
Method string
Path string // starts with "/"; the query is part of it
Headers http.Header
ContentType string
Body []byte // nil: no body
}
ServiceRequest is one request to another service, by its name: never an address.
type ServiceResponse ¶
ServiceResponse is what the other service answered, whatever its status.
func CallService ¶
func CallService(ctx context.Context, service string, req ServiceRequest) (*ServiceResponse, error)
CallService sends req to the service named service, made by the sidecar as this service (1.8): it resolves the service, presents this service's certificate and checks the other's. Any status is an answer; an error is a *ServiceError when no answer came, or a *RefusalError when the sidecar would not make the call.
type SignedAccess ¶
type SignedAccess string
SignedAccess is what a signed URL lets its holder do with one object.
const ( AccessRead SignedAccess = "read" AccessKeep SignedAccess = "keep" )
type Socket ¶
type Socket struct {
// contains filtered or unexported fields
}
Socket is an open socket of a socket route (1.9): Receive reads the frames the client sends, in order; Send reaches the client. The socket closes when the handler returns, and the handler's context ends when the client, or the platform, closes it.
func (*Socket) CloseReason ¶
CloseReason is why the socket was closed ("client" for the client's own close, or a word: "going away", "too large", "unread", "not text", "failed"); "" while it is open.
func (*Socket) Receive ¶
Receive is the next text frame the client sent: io.EOF once the socket is closed and every frame before the close has been read.
type Source ¶
type Source struct {
// contains filtered or unexported fields
}
Source is what a view or a consumer reads: a component's changes (Changes) or a topic (Topic).
func Changes ¶
func Changes(c changeSource) Source
Changes is a component's changes as a source: an event sourced entity's events, a key value entity's state, or a workflow's state each time it records one (protocol 1.16), with where the workflow stood (ChangeScope.Standing).
func Topic ¶
func Topic(name string, opts ...TopicOption) Source
Topic is a topic as a source, under the name the project declares it by.
func WorkflowSource ¶
func WorkflowSource[S any](w *WorkflowComponent[S]) Source
WorkflowSource is a workflow's changes as a source; the same as Changes(w).
type Standing ¶
type Standing struct {
// Status is NotStarted, Running, Paused, Completed, Failed, or Unknown for a state recorded
// before the platform stamped standings.
Status string
// Step is the step the workflow is on, or the step a pause names or follows.
Step string
// Retries are the retries so far, per step.
Retries map[string]int
// Failure is why it failed, when it did.
Failure string
}
Standing is where a workflow stood once the effect that recorded a state was applied.
type StartOption ¶
type StartOption func(*startSettings)
StartOption is an option of Start and Serve.
func GracePeriod ¶
func GracePeriod(d time.Duration) StartOption
GracePeriod is how long handlers in flight may run after SIGTERM or SIGINT before the server stops them; 25 seconds by default, inside the platform's 30.
func Host ¶
func Host(host string) StartOption
Host is the address the process listens on: loopback (the default) or "0.0.0.0", which the integration test kit needs for a sidecar in a container. Any other is refused.
func Logger ¶
func Logger(l *slog.Logger) StartOption
Logger is where the service logs; slog's default otherwise.
func Port ¶
func Port(port int) StartOption
Port is the port the process listens on; by default ANKKA_PROCESS_PORT, else 9010. 0 picks one.
func ServiceDirectory ¶
func ServiceDirectory(dir string) StartOption
ServiceDirectory is the directory that holds service.json, whose buckets the directory store refuses names beside, and under which ANKKA_STORAGE_DIR is read; the working directory by default.
func SidecarAddress ¶
func SidecarAddress(address string) StartOption
SidecarAddress is where the sidecar's Client service answers; by default ANKKA_SIDECAR_ADDRESS, else 127.0.0.1:9011.
func StorageOf ¶
func StorageOf(store Storage) StartOption
StorageOf gives the service's handlers store in place of the one the environment chooses.
type StartPosition ¶
type StartPosition struct {
// contains filtered or unexported fields
}
StartPosition is where a topic source begins the first time its consumer group reads a partition. It applies once and is committed at once, so a restart or a new instance resumes where the group got to.
func Earliest ¶
func Earliest() StartPosition
Earliest is the oldest message the broker still holds.
func Latest ¶
func Latest() StartPosition
Latest is after the newest: only what is published from then on.
func StartAt ¶
func StartAt(t time.Time) StartPosition
StartAt is the first message published at or after t.
type StepBuilder ¶
type StepBuilder[S any] struct { // contains filtered or unexported fields }
StepBuilder is StepUpdate's or StepKeep's result.
func StepUpdate ¶
func StepUpdate[S any](s S) StepBuilder[S]
StepUpdate records s as the workflow's state.
func (StepBuilder[S]) ThenEnd ¶
func (b StepBuilder[S]) ThenEnd() StepEffect[S]
ThenEnd ends the workflow.
func (StepBuilder[S]) ThenFail ¶
func (b StepBuilder[S]) ThenFail(code ErrorCode, message string) StepEffect[S]
ThenFail ends the workflow as failed, on purpose. A step that returns an error or panics is retried and failed over as the workflow's settings declare; this is not.
func (StepBuilder[S]) ThenPause ¶
func (b StepBuilder[S]) ThenPause(opts PauseOptions) StepEffect[S]
ThenPause pauses the workflow until a command moves it on or the pause times out.
func (StepBuilder[S]) ThenTransitionTo ¶
func (b StepBuilder[S]) ThenTransitionTo(step string, input any) StepEffect[S]
ThenTransitionTo runs step next, with input (nil for none).
type StepEffect ¶
type StepEffect[S any] struct { // contains filtered or unexported fields }
StepEffect is what a workflow's step returns: a new state (or none) and what happens next: a transition, a pause, the end, or a failure.
func FailWorkflow ¶
func FailWorkflow[S any](code ErrorCode, message string) StepEffect[S]
FailWorkflow ends the workflow as failed without changing the state.
func Pause ¶
func Pause[S any](opts PauseOptions) StepEffect[S]
Pause pauses without changing the state.
func TransitionTo ¶
func TransitionTo[S any](step string, input any) StepEffect[S]
TransitionTo runs step next without changing the state.
type Storage ¶
type Storage interface {
// Default is the unnamed bucket, refused, naming provisionObjectStorage, when there is none.
Default() (Bucket, error)
// Bucket is a bucket the descriptor's buckets list names, refused, naming the ones it does name,
// otherwise.
Bucket(name string) (Bucket, error)
// Buckets are every named bucket, in name order.
Buckets() []Bucket
}
Storage is a service's buckets: the unnamed one, and the named ones by name.
var NoStorage Storage = noStorage{}
NoStorage is the store of a service with no bucket: every call refuses, naming provisionObjectStorage.
func StorageFrom ¶
StorageFrom is the service's buckets, as the handler ctx belongs to; nil for an entity, a view or a workflow's command, which may not wait on a store.
type StorageBackend ¶
type StorageBackend string
StorageBackend is what stands behind every bucket of a service.
const ( BackendS3 StorageBackend = "s3" BackendDirectory StorageBackend = "directory" BackendMemory StorageBackend = "memory" )
type StoredObject ¶
StoredObject is an object read from a bucket. Read its Body once and close it.
func (*StoredObject) Bytes ¶
func (o *StoredObject) Bytes() ([]byte, error)
Bytes reads the whole body and closes it.
type SumType ¶
type SumType[I any] struct { // contains filtered or unexported fields }
SumType is the registration of an interface's cases: which struct types a value of the interface may hold, and the discriminator each is written under ("type":"ItemAdded"). Built by Cases, it is referenced by the declaration that stores values of the interface.
type TaskOptions ¶
type TaskOptions struct {
ID string
Attachments []Attachment
DependsOn []string
}
TaskOptions are a new task's id (a random one when ""), attachments and the tasks it waits for.
type TaskRule ¶
type TaskRule[R any] struct { Name string Check func(ctx context.Context, result R) (Verdict, error) }
TaskRule is a check a task's result must pass. Rules run in declaration order; the first rejection is reported. A rule that fails or panics decides nothing, and the sidecar tries the iteration again.
type TaskSnapshot ¶
type TaskSnapshot[R any] struct { ID string TypeName string Status TaskStatus Result *R Reason string Iterations int Assignee *Assignee // Record is the whole record, as JSON. Record json.RawMessage }
TaskSnapshot is a task as its record holds it, its result decoded as R.
type TaskStatus ¶
type TaskStatus string
TaskStatus is where a task is in its life.
const ( TaskPending TaskStatus = "pending" TaskAssigned TaskStatus = "assigned" TaskInProgress TaskStatus = "in-progress" TaskResultRejected TaskStatus = "result-rejected" TaskCompleted TaskStatus = "completed" TaskFailed TaskStatus = "failed" TaskCancelled TaskStatus = "cancelled" )
The statuses a task passes through.
func (TaskStatus) Ended ¶
func (s TaskStatus) Ended() bool
Ended reports whether the task has completed, failed or been cancelled.
type TaskType ¶
type TaskType[R any] struct { // contains filtered or unexported fields }
TaskType is a kind of work, with the result type R its tasks complete with. Its name is the wire name, written into every task of the type. A string result is text; any other type's JSON Schema is the result the model is asked for.
func NewTaskType ¶
NewTaskType is the task type named name, described for the model, with its rules.
type TimedActionComponent ¶
type TimedActionComponent struct {
// contains filtered or unexported fields
}
TimedActionComponent is a timed action's declaration: the calls a timer makes later. Timers are scheduled through Schedule and ScheduleRecurring; the sidecar's sweeper delivers each one here and retries a failure with backoff.
func TimedAction ¶
func TimedAction(id string, parts ...Part) *TimedActionComponent
TimedAction declares a timed action and its actions (Action).
func (*TimedActionComponent) ID ¶
func (t *TimedActionComponent) ID() string
ID is the timed action's component id.
type TimerScope ¶
type TimerScope struct {
// Name is the timer's id.
Name string
// Due is the due time this run is for: the same on every retry of one due time, and for a
// recurring timer a whole number of periods after the one before. Zero on a runtime before
// protocol 1.12, which does not send it.
Due time.Time
// Attempts is how many times the timer has fired for this due time.
Attempts int
}
TimerScope is what a timed action sees of the timer that fired it.
type TimerTarget ¶
TimerTarget is what a timer calls when it is due: a handler of one of this service's components, with the instance for an entity, workflow or agent.
type TopicOption ¶
type TopicOption func(*Source)
TopicOption is an option of a topic source.
func ExpectContract ¶
func ExpectContract(c Contract) TopicOption
ExpectContract is the contract the topic is expected to carry, checked at start against the project's declaration (protocol 1.14).
func FromProject ¶
func FromProject(project string) TopicOption
FromProject reads another project's topic, which that project must grant this service consume on (protocol 1.15).
func OnBroker ¶
func OnBroker(name string) TopicOption
OnBroker is the declared broker the topic is on; without it, the installation's (protocol 1.14).
func Parallel ¶
func Parallel() TopicOption
Parallel handles the partitions an instance holds at once, each in order (protocol 1.14).
func StartFrom ¶
func StartFrom(p StartPosition) TopicOption
StartFrom is where the topic source begins; a consumer over a topic must say.
type Unit ¶
type Unit struct{}
Unit is the input of a handler that takes nothing: manifest "unit", zero bytes.
type Verdict ¶
type Verdict struct {
// contains filtered or unexported fields
}
Verdict is what a task rule decides of a result.
type ViewComponent ¶
type ViewComponent[Row any] struct { // contains filtered or unexported fields }
ViewComponent is a view's declaration: a queryable projection of one source's changes, one row per source instance. The sidecar runs the projection and keeps the rows; this process says what each change does to its row.
func View ¶
func View[Row any](id string, parts ...Part) *ViewComponent[Row]
View declares a view of one source: its handler (OnChange) and its options (OnDelete, Queries, SourceVersion, RowCodec).
func (*ViewComponent[Row]) ID ¶
func (v *ViewComponent[Row]) ID() string
ID is the view's component id.
type ViewEffect ¶
type ViewEffect[Row any] struct { // contains filtered or unexported fields }
ViewEffect is what a view's handler says a change does to its row.
func IgnoreChange ¶
func IgnoreChange[Row any]() ViewEffect[Row]
IgnoreChange leaves the row as it is.
func UpdateRow ¶
func UpdateRow[Row any](row Row) ViewEffect[Row]
UpdateRow writes row as the change's row.
type ViewQuery ¶
type ViewQuery struct {
Name string
Values map[string]string
// Limit is the most rows to read; 0 is the runtime's 1000. A stream ignores it unless set.
Limit uint32
}
ViewQuery names what a view is asked: one of its declared queries with its values, or "all".
type ViewRows ¶
type ViewRows[Row any] interface { // Get is the row under key, and whether there is one. Get(key string) (Row, bool, error) // Ask is the rows one of the view's declared queries answers, given its values. Ask(name string, values map[string]string) ([]Row, error) }
ViewRows are a keyed view's own rows, for the length of one change. They reach no other view.
type WatchEndedError ¶
type WatchEndedError struct{ Reason string }
WatchEndedError is a watch that ended for Reason: rebuilt, instance-stopping, listener-lost or unread. Watch again for the rows now.
func (*WatchEndedError) Error ¶
func (e *WatchEndedError) Error() string
type WatchEvent ¶
WatchEvent is one element of a watch: a row now matching (Removed false), a row no longer matching (Removed true, Row zero), or CaughtUp once the rows there were when it began are given.
type WatchTarget ¶
type WatchTarget struct {
// contains filtered or unexported fields
}
WatchTarget is what a watch follows: a declared query declared watched, or one row by key.
func WatchQuery ¶
func WatchQuery(name string, values map[string]string) WatchTarget
WatchQuery follows the declared query name with its values.
type WorkflowBuilder ¶
type WorkflowBuilder[S, R any] struct { // contains filtered or unexported fields }
WorkflowBuilder is WorkflowUpdate's or WorkflowKeep's result.
func WorkflowKeep ¶
func WorkflowKeep[S, R any]() WorkflowBuilder[S, R]
WorkflowKeep leaves the state as it is.
func WorkflowUpdate ¶
func WorkflowUpdate[S, R any](s S) WorkflowBuilder[S, R]
WorkflowUpdate records s as the workflow's state.
func (WorkflowBuilder[S, R]) ThenNoReply ¶
func (b WorkflowBuilder[S, R]) ThenNoReply() WorkflowEffect[S, R]
ThenNoReply answers nothing.
func (WorkflowBuilder[S, R]) ThenReply ¶
func (b WorkflowBuilder[S, R]) ThenReply(compute func(S) R) WorkflowEffect[S, R]
ThenReply replies with a value computed from the state after the command.
func (WorkflowBuilder[S, R]) ThenReplyState ¶
func (b WorkflowBuilder[S, R]) ThenReplyState() WorkflowEffect[S, R]
ThenReplyState replies with the state; the reply type must be the state's type.
func (WorkflowBuilder[S, R]) ThenReplyValue ¶
func (b WorkflowBuilder[S, R]) ThenReplyValue(v R) WorkflowEffect[S, R]
ThenReplyValue replies with v.
func (WorkflowBuilder[S, R]) ThenTransitionTo ¶
func (b WorkflowBuilder[S, R]) ThenTransitionTo(step string, input any) WorkflowBuilder[S, R]
ThenTransitionTo starts step, with input (nil for a step that takes none), once the state is recorded.
type WorkflowComponent ¶
type WorkflowComponent[S any] struct { // contains filtered or unexported fields }
WorkflowComponent is a workflow's declaration: its id, its empty state, its steps and its commands. The sidecar's engine journals every transition and runs a step only once its transition is journalled; this process holds the state and runs the handlers.
func Workflow ¶
func Workflow[S any](id string, empty func(workflowID string) S, parts ...Part) *WorkflowComponent[S]
Workflow declares a workflow. empty is the state of a workflow not yet started, given its id. The parts are its steps (Step), its commands (WorkflowCommand, Query) and its settings (WorkflowTimeout, StepTimeout, StepRecovery, ForStep, StateCodec).
func (*WorkflowComponent[S]) ID ¶
func (w *WorkflowComponent[S]) ID() string
ID is the workflow's component id.
type WorkflowEffect ¶
type WorkflowEffect[S, R any] struct { // contains filtered or unexported fields }
WorkflowEffect is what a workflow's command returns: a new state (or none), a step to start (or none), and a reply.
type WorkflowOption ¶
type WorkflowOption struct {
// contains filtered or unexported fields
}
WorkflowOption is a setting of a workflow, or of one step through ForStep.
func StepRecovery ¶
func StepRecovery(r Recovery) WorkflowOption
StepRecovery is what the engine does with a failed step; with none, the workflow fails.
func StepTimeout ¶
func StepTimeout(d time.Duration) WorkflowOption
StepTimeout bounds how long a step may run before it counts as failed; 30 seconds when unsaid.
Source Files
¶
- acl.go
- agent.go
- ankka.go
- autonomous.go
- cases.go
- client.go
- clientkeys.go
- codec.go
- consumer.go
- context.go
- contract.go
- doubles.go
- effects.go
- endpoint.go
- errors.go
- eventsourced.go
- graph.go
- handlers.go
- json_parse.go
- json_read.go
- json_write.go
- keyvalue.go
- kitbridge.go
- materialise.go
- mcp.go
- plan.go
- schema.go
- secrets.go
- service.go
- services.go
- sigv4.go
- socket.go
- spec.go
- storage.go
- storage_dir.go
- storage_endpoint.go
- storage_mem.go
- storage_s3.go
- timedaction.go
- timers.go
- times.go
- topic.go
- version.go
- view.go
- workflow.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
kit
Package kit is the seam between the SDK and its test kits.
|
Package kit is the seam between the SDK and its test kits. |
|
server
Package server is the process's side of the sidecar protocol: the grpc-go server, one servicer per kind, and the conversations they hold.
|
Package server is the process's side of the sidecar protocol: the grpc-go server, one servicer per kind, and the conversations they hold. |
|
Package testkit tests ankka services written in Go.
|
Package testkit tests ankka services written in Go. |