server

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package server provides the public runtime contract used by generated Go servers.

Index

Constants

View Source
const (
	ErrorMessageAuthenticationOperationSuperseded       = "The authentication operation was superseded by a newer session operation."
	ErrorMessageAuthenticationSessionChanged            = "The authentication session changed."
	ErrorMessageBrowserSessionCoordinationRequired      = "This browser must support same-origin session coordination to use application sessions safely."
	ErrorMessageCustomerAuthenticationCookieInvalid     = "The customer authentication cookie is invalid."
	ErrorMessageCustomerSessionRequired                 = "A customer session is required."
	ErrorMessageExpectedSessionScopeInvalid             = "The expected session scope is invalid."
	ErrorMessageGithubOauthBrowserCompletionInvalid     = "The GitHub OAuth browser completion is missing or invalid."
	ErrorMessageGithubOauthBrowserOriginInvalid         = "The GitHub OAuth browser completion must come from the application origin."
	ErrorMessageGithubOauthBrowserStateInvalid          = "The GitHub OAuth browser state is invalid."
	ErrorMessageGithubOauthBrowserTransitionUnavailable = "The GitHub OAuth browser transition is unavailable."
	ErrorMessageGithubOauthCallbackInvalid              = "The GitHub OAuth callback is invalid."
	ErrorMessageGithubOauthNonceCookieRequired          = "The GitHub OAuth nonce cookie is required."
	ErrorMessageGithubOauthSessionSnapshotInvalid       = "The GitHub OAuth session snapshot has an invalid format."
	ErrorMessageGithubOauthStateInvalid                 = "The GitHub OAuth state has an invalid format."
)

Variables

This section is empty.

Functions

func DatabaseDelete

func DatabaseDelete[Row any](ctx context.Context, database Database, model string, key map[string]any) (*Row, error)

DatabaseDelete deletes one row by its generated primary key.

func DatabaseFindByID

func DatabaseFindByID[Row any](ctx context.Context, database Database, model string, key map[string]any) (*Row, error)

DatabaseFindByID reads one row by its generated primary key.

func DatabaseFindMany

func DatabaseFindMany[Row any](ctx context.Context, database Database, model string, options FindManyOptions) ([]Row, error)

DatabaseFindMany reads rows through a generated repository.

func DatabaseInsert

func DatabaseInsert[Row any](ctx context.Context, database Database, model string, row map[string]any) (*Row, error)

DatabaseInsert inserts one row.

func DatabaseInsertIfAbsent

func DatabaseInsertIfAbsent[Row any](ctx context.Context, database Database, model string, row map[string]any) (*Row, error)

DatabaseInsertIfAbsent inserts one row or returns nil on a uniqueness conflict.

func DatabaseTransaction

func DatabaseTransaction(ctx context.Context, database Database, fn func(context.Context, Database) error) (err error)

DatabaseTransaction runs generated repository work in one atomic transaction.

func DatabaseUpdate

func DatabaseUpdate[Row any](ctx context.Context, database Database, model string, key, patch map[string]any) (*Row, error)

DatabaseUpdate updates one row by its generated primary key.

func DatabaseUpdateMany

func DatabaseUpdateMany[Row any](ctx context.Context, database Database, model string, where Filter, patch map[string]any) ([]Row, error)

DatabaseUpdateMany updates every row matched by a generated predicate.

func Dispatch

func Dispatch(services []Service, input []byte) (output []byte)

Dispatch invokes one generated unary handler and returns its runtime envelope.

func DispatchWithHost

func DispatchWithHost(ctx context.Context, services []Service, input []byte, executor HostExecutor) (output []byte)

DispatchWithHost invokes one generated handler with request-bound runtime ports.

func DispatchWithHostAndStream

func DispatchWithHostAndStream(
	ctx context.Context,
	services []Service,
	input []byte,
	executor HostExecutor,
	emit func(json.RawMessage) error,
) (output []byte)

DispatchWithHostAndStream invokes one generated handler and emits response-stream items as they are produced.

func DispatchWithHostAndStreams

func DispatchWithHostAndStreams(
	ctx context.Context,
	services []Service,
	input []byte,
	executor HostExecutor,
	receive RequestStreamReceiver,
	emit func(json.RawMessage) error,
) (output []byte)

DispatchWithHostAndStreams invokes one generated handler with request and response stream bridges.

func NewError

func NewError(code ErrorCode, message string, status int) error

NewError creates a public application error with a stable code.

func Unimplemented

func Unimplemented(message string) error

Unimplemented reports a handler method that still needs an implementation.

Types

type AI

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

AI invokes the provider-neutral AI runtime selected by the application.

func (AI) Generate

func (port AI) Generate(ctx context.Context, input AIGenerateInput) (AIGenerateResult, error)

Generate returns one complete text generation result.

func (AI) ModelCapability

func (port AI) ModelCapability(ctx context.Context, provider, model string) (*AIModelCapability, error)

ModelCapability returns the generated capability snapshot for one model.

func (AI) Stream

func (port AI) Stream(ctx context.Context, input AIGenerateInput) iter.Seq2[AIStreamEvent, error]

Stream yields generation events as the runtime receives them.

type AIGenerateInput

type AIGenerateInput struct {
	Provider        string              `json:"provider"`
	Model           string              `json:"model"`
	Messages        []AITextMessage     `json:"messages"`
	Reasoning       *AIReasoningRequest `json:"reasoning,omitempty"`
	MaxOutputTokens *int                `json:"maxOutputTokens,omitempty"`
}

AIGenerateInput is a provider-neutral text generation request.

type AIGenerateResult

type AIGenerateResult struct {
	Provider     string   `json:"provider"`
	Model        string   `json:"model"`
	Text         string   `json:"text"`
	FinishReason string   `json:"finishReason,omitempty"`
	Usage        *AIUsage `json:"usage,omitempty"`
}

AIGenerateResult is one complete text generation result.

type AIMessageRole

type AIMessageRole string

AIMessageRole identifies one text message participant.

const (
	AIMessageRoleSystem    AIMessageRole = "system"
	AIMessageRoleUser      AIMessageRole = "user"
	AIMessageRoleAssistant AIMessageRole = "assistant"
)

type AIModelCapability

type AIModelCapability struct {
	ID        string                 `json:"id"`
	Reasoning *AIReasoningCapability `json:"reasoning,omitempty"`
	Tools     *bool                  `json:"tools,omitempty"`
}

AIModelCapability is the generation-time capability snapshot for one model.

type AIProviderKind

type AIProviderKind string

AIProviderKind identifies one provider contract selected by the application.

const (
	AIProviderKindManaged          AIProviderKind = "managed"
	AIProviderKindOpenAI           AIProviderKind = "openai"
	AIProviderKindAnthropic        AIProviderKind = "anthropic"
	AIProviderKindGemini           AIProviderKind = "gemini"
	AIProviderKindOpenAICompatible AIProviderKind = "openai-compatible"
)

type AIReasoningCapability

type AIReasoningCapability struct {
	Efforts                       []string       `json:"efforts,omitempty"`
	TokenBudget                   *AITokenBudget `json:"tokenBudget,omitempty"`
	SupportsEffortWithTokenBudget bool           `json:"supportsEffortWithTokenBudget,omitempty"`
}

AIReasoningCapability describes the reasoning controls accepted by a model.

type AIReasoningRequest

type AIReasoningRequest struct {
	Effort      string `json:"effort,omitempty"`
	TokenBudget *int   `json:"tokenBudget,omitempty"`
}

AIReasoningRequest selects one supported reasoning control.

type AIStreamEvent

type AIStreamEvent struct {
	Type         AIStreamEventType `json:"type"`
	Text         string            `json:"text,omitempty"`
	FinishReason string            `json:"finishReason,omitempty"`
	Usage        *AIUsage          `json:"usage,omitempty"`
}

AIStreamEvent is one progressive generation event.

type AIStreamEventType

type AIStreamEventType string

AIStreamEventType identifies one progressive generation event.

const (
	AIStreamEventTypeTextDelta AIStreamEventType = "text_delta"
	AIStreamEventTypeDone      AIStreamEventType = "done"
)

type AITextMessage

type AITextMessage struct {
	Role    AIMessageRole `json:"role"`
	Content string        `json:"content"`
}

AITextMessage is one provider-neutral text generation message.

type AITokenBudget

type AITokenBudget struct {
	Minimum int `json:"minimum"`
	Maximum int `json:"maximum"`
}

AITokenBudget bounds a model's supported reasoning token budget.

type AIUsage

type AIUsage struct {
	InputTokens  *int `json:"inputTokens,omitempty"`
	OutputTokens *int `json:"outputTokens,omitempty"`
	TotalTokens  *int `json:"totalTokens,omitempty"`
}

AIUsage reports provider token accounting when available.

type Auth

type Auth struct {
	UserID           string `json:"userId,omitempty"`
	SessionID        string `json:"sessionId,omitempty"`
	SessionExpiresAt string `json:"sessionExpiresAt,omitempty"`
	APIKeyID         string `json:"apiKeyId,omitempty"`
}

Auth contains the authenticated identity attached to the current request.

type BidiStreamMethod

type BidiStreamMethod func(Context, iter.Seq2[json.RawMessage, error], func(json.RawMessage) error) error

BidiStreamMethod is the generated adapter shape for one bidirectional stream.

type ClientStreamMethod

type ClientStreamMethod func(Context, iter.Seq2[json.RawMessage, error]) (json.RawMessage, error)

ClientStreamMethod is the generated adapter shape for one request stream.

type Column

type Column[Value any] struct {
	// contains filtered or unexported fields
}

Column is one typed field in a generated repository.

func NewColumn

func NewColumn[Value any](model, property string) Column[Value]

NewColumn creates a generated repository column.

func (Column[Value]) Asc

func (column Column[Value]) Asc() Order

Asc sorts by a column in ascending order.

func (Column[Value]) Desc

func (column Column[Value]) Desc() Order

Desc sorts by a column in descending order.

func (Column[Value]) Equals

func (column Column[Value]) Equals(value Value) Filter

Equals compares a column with a value.

func (Column[Value]) GreaterThan

func (column Column[Value]) GreaterThan(value Value) Filter

GreaterThan compares a column with a lower bound.

func (Column[Value]) GreaterThanOrEquals

func (column Column[Value]) GreaterThanOrEquals(value Value) Filter

GreaterThanOrEquals compares a column with an inclusive lower bound.

func (Column[Value]) In

func (column Column[Value]) In(values ...Value) Filter

In matches any value in the supplied set.

func (Column[Value]) IsNotNull

func (column Column[Value]) IsNotNull() Filter

IsNotNull excludes SQL null.

func (Column[Value]) IsNull

func (column Column[Value]) IsNull() Filter

IsNull matches SQL null.

func (Column[Value]) LessThan

func (column Column[Value]) LessThan(value Value) Filter

LessThan compares a column with an upper bound.

func (Column[Value]) LessThanOrEquals

func (column Column[Value]) LessThanOrEquals(value Value) Filter

LessThanOrEquals compares a column with an inclusive upper bound.

func (Column[Value]) NotEquals

func (column Column[Value]) NotEquals(value Value) Filter

NotEquals compares a column with a different value.

type Context

type Context struct {
	context.Context
	TenantID string
	Auth     Auth
	DB       Database
	Realtime Realtime
	Events   Events
	Queue    Queue
	Jobs     Jobs
	AI       AI
	Push     Push
	Secrets  map[string]string
	Fetch    Fetch
}

Context contains request data that is safe for an application handler.

type Database

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

Database is the request-bound handle used by generated repositories. Its implementation remains owned by the application runtime.

func DatabaseFromContext

func DatabaseFromContext(ctx context.Context) Database

DatabaseFromContext returns the opaque database handle bound to this request.

type ErrorCode

type ErrorCode string

ErrorCode is a stable public failure classification.

const (
	ErrorCodeCanceled              ErrorCode = "canceled"
	ErrorCodeUnknown               ErrorCode = "unknown"
	ErrorCodeInvalidArgument       ErrorCode = "invalid_argument"
	ErrorCodeDeadlineExceeded      ErrorCode = "deadline_exceeded"
	ErrorCodeAlreadyExists         ErrorCode = "already_exists"
	ErrorCodeUnauthenticated       ErrorCode = "unauthenticated"
	ErrorCodePermissionDenied      ErrorCode = "permission_denied"
	ErrorCodeNotFound              ErrorCode = "not_found"
	ErrorCodeFailedPrecondition    ErrorCode = "failed_precondition"
	ErrorCodeAborted               ErrorCode = "aborted"
	ErrorCodeOutOfRange            ErrorCode = "out_of_range"
	ErrorCodeUnimplemented         ErrorCode = "unimplemented"
	ErrorCodeResourceExhausted     ErrorCode = "resource_exhausted"
	ErrorCodeInternal              ErrorCode = "internal"
	ErrorCodeUnavailable           ErrorCode = "unavailable"
	ErrorCodeDataLoss              ErrorCode = "data_loss"
	ErrorCodeNetworkFailure        ErrorCode = "network_error"
	ErrorCodeInvalidResponse       ErrorCode = "invalid_response"
	ErrorCodeStorageError          ErrorCode = "storage_error"
	ErrorCodeCommitUnknown         ErrorCode = "commit_unknown"
	ErrorCodeInvalidUploadUrl      ErrorCode = "invalid_upload_url"
	ErrorCodeInvalidMultipartPlan  ErrorCode = "invalid_multipart_plan"
	ErrorCodeMultipartBodyRequired ErrorCode = "multipart_body_required"
	ErrorCodeInvalidMultipartPart  ErrorCode = "invalid_multipart_part"
	ErrorCodePayloadTooLarge       ErrorCode = "payload_too_large"
	ErrorCodeResponseCredit        ErrorCode = "response_credit"
	ErrorCodeChannelLimit          ErrorCode = "channel_limit"
	ErrorCodeUnauthorized          ErrorCode = "unauthorized"
	ErrorCodeFrameAuth             ErrorCode = "frame_auth"
	ErrorCodeHalfClose             ErrorCode = "half_close"
)

func ParseErrorCode

func ParseErrorCode(value string) ErrorCode

ParseErrorCode never turns an unknown wire value into a known contract value.

func ParseWireErrorCode

func ParseWireErrorCode(value string) (ErrorCode, string)

ParseWireErrorCode preserves an unrecognized received code separately from the safe fallback.

func (ErrorCode) DefaultHTTPStatus

func (code ErrorCode) DefaultHTTPStatus() int

DefaultHTTPStatus returns the catalog fallback. Zero means no HTTP response exists.

func (ErrorCode) IsProtocol

func (code ErrorCode) IsProtocol() bool

IsProtocol reports whether this code is valid on the shared RPC/HTTP wire.

type EventAppendResult

type EventAppendResult struct {
	Seq int64 `json:"seq"`
}

EventAppendResult identifies one event in an append-only channel.

type Events

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

Events appends durable application events.

func (Events) Append

func (port Events) Append(ctx context.Context, channel string, event any) (EventAppendResult, error)

Append records one event and returns its sequence.

type Fetch

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

Fetch performs outbound HTTP requests through the mounted runtime.

func (Fetch) Do

func (port Fetch) Do(ctx context.Context, request FetchRequest) (FetchResponse, error)

Do performs one outbound HTTP request.

type FetchRequest

type FetchRequest struct {
	URL     string              `json:"url"`
	Method  string              `json:"method,omitempty"`
	Headers map[string][]string `json:"headers,omitempty"`
	Body    []byte              `json:"body,omitempty"`
}

FetchRequest is one provider-neutral outbound HTTP request.

type FetchResponse

type FetchResponse struct {
	Status  int                 `json:"status"`
	Headers map[string][]string `json:"headers"`
	Body    []byte              `json:"body"`
}

FetchResponse is one complete outbound HTTP response.

type Filter

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

Filter is a typed predicate produced by generated columns.

func And

func And(filters ...Filter) Filter

And requires every supplied predicate.

func Not

func Not(filter Filter) Filter

Not negates one predicate.

func Or

func Or(filters ...Filter) Filter

Or requires at least one supplied predicate.

type FindManyOptions

type FindManyOptions struct {
	Where   Filter
	OrderBy []Order
	Limit   *int
	Offset  *int
}

FindManyOptions controls filtering, ordering, and pagination.

type HostExecutor

type HostExecutor func(context.Context, []byte) ([]byte, error)

HostExecutor connects generated server ports to the mounted runtime. It is consumed by generated private entry code, not application handlers.

type JSONValue

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

JSONValue preserves a top-level JSON null separately from SQL null.

func JSONValueOf

func JSONValueOf(value any) JSONValue

JSONValueOf creates a database JSON value. Passing nil means a JSON literal null.

func (JSONValue) MarshalJSON

func (value JSONValue) MarshalJSON() ([]byte, error)

func (*JSONValue) UnmarshalJSON

func (value *JSONValue) UnmarshalJSON(data []byte) error

func (JSONValue) Value

func (value JSONValue) Value() any

Value returns the ordinary Go representation of a database JSON value.

type JobEnqueueInput

type JobEnqueueInput struct {
	Name           string `json:"name"`
	Payload        string `json:"payload"`
	IdempotencyKey string `json:"idempotencyKey"`
	DelaySeconds   *int   `json:"delaySeconds,omitempty"`
}

JobEnqueueInput identifies one declared Background Job invocation.

type JobEnqueueResult

type JobEnqueueResult struct {
	ID string `json:"id"`
}

JobEnqueueResult identifies one accepted Background Job.

type JobExecution

type JobExecution struct {
	ID             string `json:"id"`
	Attempts       int    `json:"attempts"`
	IdempotencyKey string `json:"idempotencyKey"`
}

JobExecution describes the currently running Background Job.

func (JobExecution) Retry

func (execution JobExecution) Retry(delaySeconds *int) *JobRetry

Retry creates a retry result for the current Background Job.

type JobRetry

type JobRetry struct {
	Kind         string `json:"kind"`
	DelaySeconds *int   `json:"delaySeconds,omitempty"`
}

JobRetry asks the platform to retry a Background Job.

type Jobs

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

Jobs enqueues declared Background Jobs through the mounted runtime.

func (Jobs) Enqueue

func (port Jobs) Enqueue(ctx context.Context, input JobEnqueueInput) (JobEnqueueResult, error)

Enqueue submits one generated Background Job payload.

type Nullable

type Nullable[Value any] struct {
	// contains filtered or unexported fields
}

Nullable distinguishes SQL null from the zero value of a generated field.

func NullValue

func NullValue[Value any]() Nullable[Value]

NullValue creates an explicit SQL null for a generated database field.

func NullableValue

func NullableValue[Value any](value Value) Nullable[Value]

NullableValue creates a non-null generated database value.

func (Nullable[Value]) IsNull

func (value Nullable[Value]) IsNull() bool

IsNull reports whether the field is SQL null.

func (Nullable[Value]) MarshalJSON

func (value Nullable[Value]) MarshalJSON() ([]byte, error)

func (*Nullable[Value]) UnmarshalJSON

func (value *Nullable[Value]) UnmarshalJSON(data []byte) error

func (Nullable[Value]) Value

func (value Nullable[Value]) Value() (Value, bool)

Value returns the field value and false for SQL null.

type Optional

type Optional[Value any] struct {
	// contains filtered or unexported fields
}

Optional distinguishes an omitted generated input field from its zero value.

func Null

func Null[Value any]() Optional[Nullable[Value]]

Null marks an optional nullable field as an explicit SQL null.

func ValueOf

func ValueOf[Value any](value Value) Optional[Value]

ValueOf marks a generated input field as present.

func (Optional[Value]) Get

func (value Optional[Value]) Get() (Value, bool)

Get returns the value and whether it was explicitly supplied.

type Order

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

Order is a generated repository sort instruction.

type Push

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

Push sends messages to registered user subscriptions.

func (Push) ToUser

func (port Push) ToUser(
	ctx context.Context,
	userID string,
	message PushMessage,
	options *PushSendOptions,
) ([]PushDeliveryResult, error)

ToUser sends one message to a user's selected subscriptions.

type PushDeliveryResult

type PushDeliveryResult struct {
	SubscriptionID    string       `json:"subscriptionId"`
	Platform          PushPlatform `json:"platform"`
	OK                bool         `json:"ok"`
	ProviderMessageID string       `json:"providerMessageId,omitempty"`
	Expired           bool         `json:"expired,omitempty"`
	Retryable         bool         `json:"retryable,omitempty"`
	RetryAfterSeconds *int         `json:"retryAfterSeconds,omitempty"`
	Reason            string       `json:"reason,omitempty"`
}

PushDeliveryResult reports the outcome for one subscription.

type PushMessage

type PushMessage struct {
	Title      string            `json:"title"`
	Body       string            `json:"body"`
	URL        string            `json:"url,omitempty"`
	Topic      string            `json:"topic,omitempty"`
	TTLSeconds *int              `json:"ttlSeconds,omitempty"`
	Data       map[string]string `json:"data,omitempty"`
}

PushMessage is sent to each selected subscription for a user.

type PushPlatform

type PushPlatform string

PushPlatform selects one registered push transport.

const (
	PushPlatformWeb  PushPlatform = "web"
	PushPlatformAPNS PushPlatform = "apns"
	PushPlatformFCM  PushPlatform = "fcm"
)

type PushSendOptions

type PushSendOptions struct {
	Platforms              []PushPlatform `json:"platforms,omitempty"`
	ExcludeSubscriptionIDs []string       `json:"excludeSubscriptionIds,omitempty"`
}

PushSendOptions narrows a push send to selected subscriptions.

type Queue

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

Queue enqueues application work.

func (Queue) Enqueue

func (port Queue) Enqueue(ctx context.Context, job QueueJob) error

Enqueue submits one queue item.

type QueueJob

type QueueJob struct {
	Kind     string `json:"kind"`
	Payload  any    `json:"payload"`
	DelaySec *int   `json:"delaySec,omitempty"`
}

QueueJob is one application queue item.

type Realtime

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

Realtime publishes application channel messages.

func (Realtime) Publish

func (port Realtime) Publish(ctx context.Context, channel string, payload any) error

Publish sends one value to a realtime channel.

type RequestStreamReceiver

type RequestStreamReceiver func() (item json.RawMessage, ok bool, err error)

RequestStreamReceiver returns the next request item, or ok=false after half-close.

type RuntimeError

type RuntimeError struct {
	Code    ErrorCode
	Message string
	Status  int
}

RuntimeError is a typed application error returned by a handler.

func (*RuntimeError) Error

func (value *RuntimeError) Error() string

type ServerStreamMethod

type ServerStreamMethod func(Context, json.RawMessage, func(json.RawMessage) error) error

ServerStreamMethod is the generated adapter shape for one response stream.

type Service

type Service struct {
	Name          string
	AuthRequired  bool
	Methods       map[string]UnaryMethod
	ServerStreams map[string]ServerStreamMethod
	ClientStreams map[string]ClientStreamMethod
	BidiStreams   map[string]BidiStreamMethod
}

Service is a generated service registration consumed by the application runtime.

type UnaryMethod

type UnaryMethod func(Context, json.RawMessage) (json.RawMessage, error)

UnaryMethod is the generated adapter shape for one unary method.

Jump to

Keyboard shortcuts

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