imaging

package
v0.107.28 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CodeInvalidInput         = "IMAGE_INVALID_INPUT"
	CodeUnsupportedOperation = "IMAGE_UNSUPPORTED_OPERATION"
	CodeRevisionConflict     = "IMAGE_REVISION_CONFLICT"
	CodeIdempotencyConflict  = "IMAGE_IDEMPOTENCY_CONFLICT"
	CodeConnectionInUse      = "IMAGE_CONNECTION_IN_USE"
	CodeAuthRequired         = "IMAGE_AUTH_REQUIRED"
	CodeRateLimited          = "IMAGE_RATE_LIMITED"
	CodeEventGap             = "IMAGE_EVENT_GAP"
	CodeNotFound             = "IMAGE_NOT_FOUND"
	CodeForbidden            = "IMAGE_FORBIDDEN"
	CodeUnavailable          = "IMAGE_UNAVAILABLE"
	CodeNoImageOutput        = "IMAGE_NO_IMAGE_OUTPUT"
	CodeResultUnknown        = "IMAGE_RESULT_UNKNOWN"
	CodeTooLarge             = "IMAGE_TOO_LARGE"
	// CodeOutputSaveFailed means the provider produced an image that was then lost: the
	// download or local save failed, so the request has very likely been billed.
	CodeOutputSaveFailed = "IMAGE_OUTPUT_SAVE_FAILED"
)
View Source
const (
	EventJobAccepted      = "job.accepted"
	EventJobStateChanged  = "job.state_changed"
	EventItemStateChanged = "item.state_changed"
	EventAssetReady       = "asset.ready"
	EventJobFinished      = "job.finished"
)
View Source
const CodeProjectBusy = "IMAGE_PROJECT_BUSY"
View Source
const CodeStoreCorrupt = "IMAGE_STORE_CORRUPT"
View Source
const CodeStoreLocked = "IMAGE_STORE_LOCKED"
View Source
const MaxSafeInteger uint64 = 1<<53 - 1
View Source
const VerificationKeyPrefix = "image-verification:"
View Source
const WireVersion = "kbrain.image.v1"

Variables

View Source
var OutputImageLimits = ImageLimits{MaxBytes: 100 << 20, MaxPixels: 100_000_000}
View Source
var UploadImageLimits = ImageLimits{MaxBytes: 20 << 20, MaxPixels: 40_000_000}

Functions

func HashRequest

func HashRequest(r CreateJobRequest) (string, error)

func IsTerminal

func IsTerminal(s JobStatus) bool

IsTerminal is shared by transport stream termination and shutdown callers.

func KnownAdapter

func KnownAdapter(id string) bool

KnownAdapter identifies a protocol, not an implementation or proof of verification.

func MarshalSettingsConfig

func MarshalSettingsConfig(s ImageSettings) ([]byte, error)

MarshalSettingsConfig is only for private backend configuration files. Never use its output in an HTTP response. Secret literals belong in a separate store.

func NormalizeRequest

func NormalizeRequest(r CreateJobRequest) ([]byte, error)

NormalizeRequest preserves text and array order, sorts object keys, and uses one exact decimal spelling for numbers. Empty inputs/parameters have one form.

func SafeReason added in v0.107.17

func SafeReason(s string) string

SafeReason is the last line of defence for reasons on the public wire: one short line without URLs, credentials, addresses, e-mail addresses or file paths. A blocklist cannot clean arbitrary text, so callers pass fixed phrases and enums, never provider prose.

func TransportReason added in v0.107.17

func TransportReason(err error) string

TransportReason describes a transport failure with fixed phrases only, so an error that embeds a request URL or header can never leak through it.

func ValidateRequest

func ValidateRequest(r CreateJobRequest, t TargetSnapshot) error

ValidateRequest performs structural checks against a frozen target. Asset ownership, decoded dimensions and mask transparency require the asset stage.

func ValidateSettings

func ValidateSettings(s ImageSettings) error

func ValidateSettingsWithProviders

func ValidateSettingsWithProviders(s ImageSettings, providerExists func(string) bool) error

ValidateSettingsWithProviders adds the external provider catalog check without inventing provider state inside the public settings document. The caller must supply the current trusted catalog when accepting provider_ref updates.

func ValidateVerificationProfile

func ValidateVerificationProfile(t TargetSnapshot) error

ValidateVerificationProfile deliberately certifies only the minimal generate profile. Extra operations/parameters need their own contract and live tests.

func WithScope

func WithScope(ctx context.Context, scope Scope) context.Context

WithScope binds authenticated server identity. Never fill Scope from request JSON.

Types

type AdapterError

type AdapterError struct {
	Code       string        `json:"code"`
	Delivery   Delivery      `json:"delivery"`
	RetryAfter time.Duration `json:"-"`
	Cause      error         `json:"-"`
	// Reason is sanitized by PublicError before it leaves the process.
	Reason string `json:"-"`
}

func (*AdapterError) Error

func (e *AdapterError) Error() string

func (AdapterError) MarshalJSON

func (e AdapterError) MarshalJSON() ([]byte, error)

func (*AdapterError) Unwrap

func (e *AdapterError) Unwrap() error

type AdapterResolver

type AdapterResolver func(context.Context, Scope, TargetSnapshot) (Adapter, error)

type AssetGCOptions

type AssetGCOptions struct {
	Now                func() time.Time
	UploadRetention    time.Duration
	TombstoneRetention time.Duration
	OrphanRetention    time.Duration
	GracePeriod        time.Duration
}

AssetGCOptions configures a single maintenance pass. Zero durations select the defaults; negative durations are rejected. Now is independent of wall-clock time. This API is internal maintenance: it deliberately takes no caller-owned Scope.

type AssetGCResult

type AssetGCResult struct {
	MarkedAssets      int
	MarkedFiles       int
	UnavailableAssets int
	RemovedFiles      int
	DeferredBusy      bool
}

type AssetSink

type AssetSink interface {
	SaveOutput(context.Context, Scope, OutputSource) (ImageAsset, error)
}

AssetSink saves bytes before the engine atomically publishes ownership and references.

type AssetStore

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

func NewAssetStore

func NewAssetStore(store *Store, dir string) (*AssetStore, error)

func (*AssetStore) Close

func (s *AssetStore) Close() error

func (*AssetStore) CollectGarbage

func (s *AssetStore) CollectGarbage(ctx context.Context, options AssetGCOptions) (AssetGCResult, error)

CollectGarbage marks candidates durably and only sweeps candidates seen again after GracePeriod. Durable asset records remain as unavailable metadata, keeping historical references and tombstones valid. No project WorkspaceRef is opened.

Writers must use the same AssetStore and hold its mutex through import+commit. SaveOutput callers must have a durable busy job or a nonempty execution lease until their output commit; either defers the entire pass, including otherwise unidentifiable staged outputs. Lease deadlines never authorize reclamation. Standalone staged output users must finish their commit before running this API. Lock order is AssetStore.mu, then Store.mu; never call it inside Store.Update.

func (*AssetStore) ImportAsset

func (s *AssetStore) ImportAsset(ctx context.Context, scope Scope, input io.Reader, mime string) (ImageAsset, error)

func (*AssetStore) OpenAsset

func (s *AssetStore) OpenAsset(ctx context.Context, scope Scope, id, variant string) (io.ReadCloser, ImageAsset, error)

func (*AssetStore) ResolveAsset

func (s *AssetStore) ResolveAsset(scope Scope, id string) (ResolvedAsset, error)

func (*AssetStore) SaveOutput

func (s *AssetStore) SaveOutput(ctx context.Context, scope Scope, source OutputSource) (ImageAsset, error)

SaveOutput stages files; the caller commits the asset and job result together. A durable busy job or nonempty execution lease must protect the entire interval through that commit, including cancellation after this method returns.

type Clock

type Clock interface {
	Now() time.Time
	After(time.Duration) <-chan time.Time
}

type ConnectionBinding

type ConnectionBinding struct {
	Kind           string            `json:"kind"`
	ProviderID     string            `json:"providerId,omitempty"`
	BaseURL        string            `json:"baseUrl,omitempty"`
	AuthKind       string            `json:"authKind,omitempty"`
	SecretRefs     map[string]string `json:"secretRefs,omitempty"`
	CustomHeaders  map[string]string `json:"customHeaders,omitempty"`
	UseSystemProxy bool              `json:"useSystemProxy,omitempty"`
}

type CreateJobRequest

type CreateJobRequest struct {
	ProjectID     string         `json:"projectId"`
	TargetID      string         `json:"targetId"`
	Operation     Operation      `json:"operation"`
	Prompt        string         `json:"prompt"`
	Inputs        []InputAsset   `json:"inputs"`
	Parameters    map[string]any `json:"parameters"`
	Count         int            `json:"count"`
	ParentAssetID string         `json:"parentAssetId,omitempty"`
}

type Delivery

type Delivery string
const (
	DeliveryNotSent   Delivery = "not_sent"
	DeliveryRejected  Delivery = "rejected"
	DeliveryUncertain Delivery = "uncertain"
)

func (Delivery) Valid

func (d Delivery) Valid() bool

type ErrorDetails

type ErrorDetails struct {
	ParameterKey      string  `json:"parameterKey,omitempty"`
	ConnectionID      string  `json:"connectionId,omitempty"`
	TargetID          string  `json:"targetId,omitempty"`
	ExpectedRevision  *uint64 `json:"expectedRevision,omitempty"`
	ActualRevision    *uint64 `json:"actualRevision,omitempty"`
	FirstAvailableSeq *uint64 `json:"firstAvailableSeq,omitempty"`
	LastEventSeq      *uint64 `json:"lastEventSeq,omitempty"`
}

ErrorDetails is a whitelist. Raw upstream bodies, headers and causes are excluded.

func (ErrorDetails) MarshalJSON

func (d ErrorDetails) MarshalJSON() ([]byte, error)

type EventPosition

type EventPosition struct {
	FirstAvailableSeq uint64 `json:"firstAvailableSeq"`
	LastEventSeq      uint64 `json:"lastEventSeq"`
}

type ExecuteRequest

type ExecuteRequest struct {
	ItemID        string           `json:"-"`
	Target        TargetSnapshot   `json:"-"`
	Request       CreateJobRequest `json:"-"`
	Inputs        []ResolvedAsset  `json:"-"`
	SubmissionKey string           `json:"-"`
	Continuation  []byte           `json:"-"`
}

func (ExecuteRequest) MarshalJSON

func (ExecuteRequest) MarshalJSON() ([]byte, error)

type ExecutionRecord

type ExecutionRecord struct {
	JobID    string
	Items    map[string]ItemExecution
	Deadline time.Time
}

ExecutionRecord is an internal API; marshaling it as a response is prohibited. Durable storage uses the separate typed executionDisk projection below.

func (ExecutionRecord) MarshalJSON

func (ExecutionRecord) MarshalJSON() ([]byte, error)

type IdempotencyRecord

type IdempotencyRecord struct {
	Hash      string
	JobID     string
	ExpiresAt time.Time
}

type ImageAsset

type ImageAsset struct {
	ID             string    `json:"id"`
	Hash           string    `json:"hash"`
	MIME           string    `json:"mime"`
	Bytes          int64     `json:"bytes"`
	Width          int       `json:"width"`
	Height         int       `json:"height"`
	Source         string    `json:"source"`
	ParentAssetIDs []string  `json:"parentAssetIds"`
	JobID          string    `json:"jobId,omitempty"`
	CreatedAt      time.Time `json:"createdAt"`
	Available      bool      `json:"available"`
}

func PublicAsset

func PublicAsset(a ImageAsset) ImageAsset

func (ImageAsset) MarshalJSON

func (a ImageAsset) MarshalJSON() ([]byte, error)

type ImageAttempt

type ImageAttempt struct {
	AttemptNo       int         `json:"-"`
	StartedAt       time.Time   `json:"-"`
	SubmissionState string      `json:"-"`
	RequestID       string      `json:"-"`
	ProviderHandle  string      `json:"-"`
	Delivery        Delivery    `json:"-"`
	Error           *ImageError `json:"-"`
	Usage           *Usage      `json:"-"`
}

ImageAttempt is private execution history; it is not a wire object.

func (ImageAttempt) MarshalJSON

func (ImageAttempt) MarshalJSON() ([]byte, error)

type ImageConnection

type ImageConnection struct {
	ID                   string            `json:"id"`
	Name                 string            `json:"name"`
	Vendor               string            `json:"vendor"`
	Enabled              bool              `json:"enabled"`
	Binding              ConnectionBinding `json:"binding"`
	CredentialConfigured bool              `json:"credentialConfigured"`
	MaxConcurrent        int               `json:"maxConcurrent"`
}

func PublicConnection

func PublicConnection(c ImageConnection, configured bool) ImageConnection

func (ImageConnection) MarshalJSON

func (c ImageConnection) MarshalJSON() ([]byte, error)

type ImageContent

type ImageContent struct {
	MIME      string
	Hash      string
	Width     int
	Height    int
	Data      []byte
	Thumbnail []byte
}

ImageContent contains validated original bytes and a PNG thumbnail.

func DecodeImageContent

func DecodeImageContent(ctx context.Context, input io.Reader, declaredMIME string, limits ImageLimits) (ImageContent, error)

type ImageError

type ImageError struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	RequestID string `json:"requestId"`
	Retryable bool   `json:"retryable"`
	// Reason is an optional, sanitized, length-bounded hint about what went wrong.
	Reason  string        `json:"reason,omitempty"`
	Details *ErrorDetails `json:"details,omitempty"`
}

func PublicError

func PublicError(e *ImageError) *ImageError

func (ImageError) Error

func (e ImageError) Error() string

func (ImageError) MarshalJSON

func (e ImageError) MarshalJSON() ([]byte, error)

type ImageEvent

type ImageEvent struct {
	JobID     string         `json:"jobId"`
	Seq       uint64         `json:"seq"`
	Revision  uint64         `json:"revision"`
	Type      string         `json:"type"`
	Timestamp time.Time      `json:"timestamp"`
	Data      ImageEventData `json:"data"`
}

func PublicEvent

func PublicEvent(e ImageEvent) ImageEvent

func (ImageEvent) MarshalJSON

func (e ImageEvent) MarshalJSON() ([]byte, error)

type ImageEventData

type ImageEventData struct {
	Status JobStatus   `json:"status,omitempty"`
	ItemID string      `json:"itemId,omitempty"`
	Asset  *ImageAsset `json:"asset,omitempty"`
	Error  *ImageError `json:"error,omitempty"`
}

type ImageItem

type ImageItem struct {
	ID             string      `json:"id"`
	Status         JobStatus   `json:"status"`
	AttemptCount   int         `json:"attemptCount"`
	OutputAssetIDs []string    `json:"outputAssetIds"`
	Error          *ImageError `json:"error,omitempty"`
}

type ImageJob

type ImageJob struct {
	ID             string           `json:"id"`
	ProjectID      string           `json:"projectId"`
	Request        CreateJobRequest `json:"request"`
	TargetSnapshot TargetSnapshot   `json:"targetSnapshot"`
	Status         JobStatus        `json:"status"`
	Revision       uint64           `json:"revision"`
	AssetIDs       []string         `json:"assetIds"`
	Items          []ImageItem      `json:"items"`
	Usage          *Usage           `json:"usage"`
	CancelEffect   string           `json:"cancelEffect,omitempty"`
	Error          *ImageError      `json:"error,omitempty"`
	CreatedAt      time.Time        `json:"createdAt"`
	UpdatedAt      time.Time        `json:"updatedAt"`
}

func PublicJob

func PublicJob(j ImageJob) ImageJob

Public projections list every permitted field instead of reflecting persistence.

func (ImageJob) MarshalJSON

func (j ImageJob) MarshalJSON() ([]byte, error)

type ImageLimits

type ImageLimits struct {
	MaxBytes  int64
	MaxPixels int64
}

type ImageProject

type ImageProject struct {
	ID           string    `json:"id"`
	Title        string    `json:"title"`
	WorkspaceRef string    `json:"workspaceRef,omitempty"`
	Revision     uint64    `json:"revision"`
	CreatedAt    time.Time `json:"createdAt"`
	UpdatedAt    time.Time `json:"updatedAt"`
}

func (ImageProject) MarshalJSON

func (p ImageProject) MarshalJSON() ([]byte, error)

type ImageSecretInput

type ImageSecretInput struct {
	ConnectionID string `json:"connectionId"`
	Purpose      string `json:"purpose"`
	Value        string `json:"value"` // Write-only request, never a settings field.
}

func (ImageSecretInput) MarshalJSON

func (ImageSecretInput) MarshalJSON() ([]byte, error)

The secret input is decoded only; accidental response/persistence serialization fails.

type ImageSecretResult

type ImageSecretResult struct {
	Ref        string `json:"ref"`
	Configured bool   `json:"configured"`
}

type ImageSettings

type ImageSettings struct {
	Revision    uint64            `json:"revision"`
	Connections []ImageConnection `json:"connections"`
	Targets     []ImageTarget     `json:"targets"`
}

func CloneSettings

func CloneSettings(s ImageSettings) ImageSettings

CloneSettings preserves execution-only fields without using public JSON.

func PublicSettings

func PublicSettings(s ImageSettings) ImageSettings

func UnmarshalSettingsConfig

func UnmarshalSettingsConfig(raw []byte) (ImageSettings, error)

UnmarshalSettingsConfig keeps strict unknown-field rejection, including nested verification records. Only trusted disk loading may restore this evidence.

func (ImageSettings) MarshalJSON

func (s ImageSettings) MarshalJSON() ([]byte, error)

type ImageSettingsUpdate

type ImageSettingsUpdate struct {
	ExpectedRevision uint64            `json:"expectedRevision"`
	Connections      []ImageConnection `json:"connections"`
	Targets          []ImageTarget     `json:"targets"`
}

func (ImageSettingsUpdate) MarshalJSON

func (s ImageSettingsUpdate) MarshalJSON() ([]byte, error)

type ImageTarget

type ImageTarget struct {
	Source            string               `json:"source,omitempty"` // "provider" for read-only targets derived from ordinary providers.
	ProviderID        string               `json:"providerId,omitempty"`
	ModelID           string               `json:"modelId,omitempty"`
	ID                string               `json:"id"`
	Name              string               `json:"name"`
	ConnectionID      string               `json:"connectionId"`
	Adapter           string               `json:"adapter"`
	AdapterVersion    string               `json:"adapterVersion"`
	Kind              string               `json:"kind"`
	RemoteID          string               `json:"remoteId"`
	Revision          uint64               `json:"revision"`
	Enabled           bool                 `json:"enabled"`
	DisabledReason    string               `json:"disabledReason,omitempty"`
	Capabilities      TargetCapabilities   `json:"capabilities"`
	Parameters        []ParameterSpec      `json:"parameters"`
	WorkflowMapping   *WorkflowMapping     `json:"workflowMapping,omitempty"`
	VerificationState *VerificationSummary `json:"verification,omitempty"` // Read-only; ignored on settings writes.
	Verification      TargetVerification   `json:"-"`                      // Trusted backend evidence, never accepted over HTTP.
}

func PublicTarget

func PublicTarget(t ImageTarget) ImageTarget

func (ImageTarget) MarshalJSON

func (t ImageTarget) MarshalJSON() ([]byte, error)

type InputAsset

type InputAsset struct {
	AssetID string `json:"assetId"`
	Role    string `json:"role"`
}

type InputResolver

type InputResolver interface {
	ResolveAsset(Scope, string) (ResolvedAsset, error)
}

type ItemExecution

type ItemExecution struct {
	ProviderHandle   string
	SubmissionKey    string
	Continuation     []byte
	Attempts         []ImageAttempt
	LeaseOwner       string
	LeaseExpiresAt   time.Time
	NextPollAt       time.Time
	QueryFailures    int
	DownloadAttempts int
}

func (ItemExecution) MarshalJSON

func (ItemExecution) MarshalJSON() ([]byte, error)

type JobRecord

type JobRecord struct {
	Job       ImageJob
	Execution ExecutionRecord
}

JobRecord is the private service-facing view of a job and its execution state. A missing execution entry is represented by an empty Execution with the job ID. Only Job may be returned to a transport, after PublicJob projection.

func (JobRecord) MarshalJSON

func (JobRecord) MarshalJSON() ([]byte, error)

type JobStatus

type JobStatus string
const (
	JobQueued           JobStatus = "queued"
	JobRunning          JobStatus = "running"
	JobSaving           JobStatus = "saving"
	JobSucceeded        JobStatus = "succeeded"
	JobPartialSucceeded JobStatus = "partial_succeeded"
	JobFailed           JobStatus = "failed"
	JobCancelRequested  JobStatus = "cancel_requested"
	JobCancelled        JobStatus = "cancelled"
	JobResultUnknown    JobStatus = "result_unknown"
)

type NetworkProfile

type NetworkProfile struct {
	AllowPrivateAddresses bool     `json:"-"`
	AllowedHosts          []string `json:"-"`
}

type Operation

type Operation string
const (
	OperationGenerate  Operation = "generate"
	OperationReference Operation = "reference"
	OperationEdit      Operation = "edit"
	OperationMask      Operation = "mask"
)

type OutputSource

type OutputSource struct {
	Kind string `json:"-"` // bytes | url
	MIME string `json:"-"`
	Data []byte `json:"-"`
	URL  string `json:"-"`
	// UseProxy fetches URL through the app proxy, as the connection's own requests go.
	UseProxy bool `json:"-"`
}

func (OutputSource) MarshalJSON

func (OutputSource) MarshalJSON() ([]byte, error)

type Page

type Page[T any] struct {
	Items      []T    `json:"items"`
	NextCursor string `json:"nextCursor,omitempty"`
}

type PageRequest

type PageRequest struct {
	Cursor string `json:"cursor"`
	Limit  int    `json:"limit"`
}

type ParameterSpec

type ParameterSpec struct {
	Key      string   `json:"key"`
	Label    string   `json:"label"`
	Type     string   `json:"type"`
	Required bool     `json:"required"`
	Enum     []any    `json:"enum,omitempty"`
	Minimum  *float64 `json:"minimum,omitempty"`
	Maximum  *float64 `json:"maximum,omitempty"`
	Default  any      `json:"default,omitempty"`
	Unit     string   `json:"unit,omitempty"`
}

type Registry

type Registry interface {
	ResolveTarget(context.Context, Scope, string) (TargetSnapshot, error)
}

Registry resolves authorized, enabled targets and freezes their verified definition. Registration and credential lookup belong to later implementation stages.

type RemoteResult

type RemoteResult struct {
	State         string         `json:"-"` // pending | completed | failed | unknown
	Handle        string         `json:"-"`
	Outputs       []OutputSource `json:"-"`
	Usage         *Usage         `json:"-"`
	NextPollAfter time.Duration  `json:"-"`
	ErrorCode     string         `json:"-"`
	ErrorReason   string         `json:"-"`
}

func (RemoteResult) MarshalJSON

func (RemoteResult) MarshalJSON() ([]byte, error)

type ResolvedAsset

type ResolvedAsset struct {
	AssetID string                        `json:"-"`
	MIME    string                        `json:"-"`
	Bytes   int64                         `json:"-"`
	Open    func() (io.ReadCloser, error) `json:"-"`
}

func (ResolvedAsset) MarshalJSON

func (ResolvedAsset) MarshalJSON() ([]byte, error)

type ResolvedConnection

type ResolvedConnection struct {
	HTTPClient     *http.Client   `json:"-"`
	SecretResolver SecretResolver `json:"-"`
	NetworkProfile NetworkProfile `json:"-"`
}

func (ResolvedConnection) MarshalJSON

func (ResolvedConnection) MarshalJSON() ([]byte, error)

type Scheduler

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

func NewScheduler

func NewScheduler(s *Service) *Scheduler

func (*Scheduler) Close

func (q *Scheduler) Close(ctx context.Context) error

func (*Scheduler) Done

func (q *Scheduler) Done() <-chan struct{}

Done closes after all workers have exited, even when Close reports an error.

func (*Scheduler) Recover

func (q *Scheduler) Recover(ctx context.Context) error

Recover reclaims leases held by the previous process. A recorded submitting attempt never becomes queued: only a persisted not_sent outcome can retry.

func (*Scheduler) Start

func (q *Scheduler) Start(ctx context.Context) error

type Scope

type Scope struct {
	OwnerID   string `json:"-"`
	BackendID string `json:"-"`
}

Scope is supplied by trusted authentication, never by a public request.

type SecretResolver

type SecretResolver interface {
	ResolveSecret(context.Context, Scope, string) (string, error)
}

type Service

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

func NewService

func NewService(store *Store, registry Registry, clock Clock, options ...ServiceOptions) *Service

func (*Service) CancelJob

func (s *Service) CancelJob(ctx context.Context, scope Scope, id string) (ImageJob, error)

func (*Service) ConnectionInUse

func (s *Service) ConnectionInUse(scope Scope, id string) bool

ConnectionInUse is safe to call while holding a settings lock: it only takes the store's read lock and never calls the registry or an adapter resolver.

func (*Service) CreateJob

func (s *Service) CreateJob(ctx context.Context, scope Scope, key string, r CreateJobRequest) (ImageJob, bool, error)

func (*Service) CreateVerificationJob

func (s *Service) CreateVerificationJob(ctx context.Context, scope Scope, key string, r CreateJobRequest, target TargetSnapshot) (ImageJob, bool, error)

CreateVerificationJob is a trusted backend entry point, never a public job request option. The caller must hold its configuration lock, validate consent and persist its receipt before calling. Execution uses the ordinary scheduler, submission journal and asset transaction; it does not change target enablement.

func (*Service) GetJob

func (s *Service) GetJob(ctx context.Context, scope Scope, id string) (ImageJob, error)

func (*Service) ImageDependenciesInUse

func (s *Service) ImageDependenciesInUse(ctx context.Context, scope Scope, connections, targets []string) (bool, error)

ImageDependenciesInUse implements the settings integration without importing backend.

func (*Service) ListJobs

func (s *Service) ListJobs(ctx context.Context, scope Scope, project string, p PageRequest) (Page[ImageJob], error)

func (*Service) ReadEvents

func (s *Service) ReadEvents(ctx context.Context, scope Scope, id string, after uint64, limit int) ([]ImageEvent, error)

func (*Service) ReadJobSnapshot

func (s *Service) ReadJobSnapshot(ctx context.Context, scope Scope, id string) (ImageJob, EventPosition, error)

func (*Service) ReconcileJob

func (s *Service) ReconcileJob(ctx context.Context, scope Scope, id string) (ImageJob, error)

ReconcileJob explicitly reopens unknown items for read-only provider lookup. It preserves submission keys, attempts, assets and handles and never submits.

func (*Service) Recover

func (s *Service) Recover(ctx context.Context) error

func (*Service) StopAccepting

func (s *Service) StopAccepting()

func (*Service) VerificationJob

func (s *Service) VerificationJob(ctx context.Context, scope Scope, key string) (ImageJob, error)

VerificationJob reads the durable idempotency journal, including after restart.

type ServiceOptions

type ServiceOptions struct {
	AssetSink             AssetSink
	InputResolver         InputResolver
	AdapterResolver       AdapterResolver
	GlobalConcurrency     int
	ConnectionConcurrency func(Scope, string) int
	JobTimeout            time.Duration
	SubmitTimeout         time.Duration
	PollInterval          time.Duration
	MaxPollInterval       time.Duration
	LeaseDuration         time.Duration
	LeaseRenewInterval    time.Duration
}

ServiceOptions contains execution dependencies only, never provider credentials. AdapterResolver must resolve current authorization against the frozen target.

type Store

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

func OpenStore

func OpenStore(dir string) (*Store, error)

func (*Store) AssetReferenceCounts

func (s *Store) AssetReferenceCounts(scope Scope) map[string]int

AssetReferenceCounts is derived from durable live jobs and asset ancestry; it deliberately retains parent references across project deletion for safe GC.

func (*Store) Checkpoint

func (s *Store) Checkpoint() error

func (*Store) Close

func (s *Store) Close() error

func (*Store) CreateProject

func (s *Store) CreateProject(ctx context.Context, scope Scope, title, workspaceRef string) (ImageProject, error)

func (*Store) DeleteJob

func (s *Store) DeleteJob(ctx context.Context, scope Scope, id string) error

func (*Store) DeleteProject

func (s *Store) DeleteProject(ctx context.Context, scope Scope, id string, expectedRevision uint64) error

func (*Store) GetIdempotency

func (s *Store) GetIdempotency(scope Scope, key string) (IdempotencyRecord, bool)

func (*Store) GetJobRecord

func (s *Store) GetJobRecord(scope Scope, id string) (JobRecord, error)

GetJobRecord returns a detached, scope-checked consistent view for execution.

func (*Store) ListAssets

func (s *Store) ListAssets(ctx context.Context, scope Scope, p PageRequest) (Page[ImageAsset], error)

ListAssets supports asset maintenance using exactly the same signed scope-bound pagination contract as projects/jobs. It never exposes private execution state.

func (*Store) ListJobRecords

func (s *Store) ListJobRecords(ctx context.Context, scope Scope, projectID string, p PageRequest) (Page[JobRecord], error)

ListJobRecords is the private service recovery listing. Cursors are distinct from public job cursors and bound to owner, backend, and project filter.

func (*Store) ListJobs

func (s *Store) ListJobs(ctx context.Context, scope Scope, projectID string, p PageRequest) (Page[ImageJob], error)

func (*Store) ListProjects

func (s *Store) ListProjects(ctx context.Context, scope Scope, p PageRequest) (Page[ImageProject], error)

func (*Store) MaintenanceError

func (s *Store) MaintenanceError() error

MaintenanceError reports a failed automatic checkpoint. Its preceding transaction is already durable; Update therefore still succeeds. Checkpoint can be retried.

func (*Store) ReadAsset

func (s *Store) ReadAsset(scope Scope, id string) (ImageAsset, error)

func (*Store) ReadEvents

func (s *Store) ReadEvents(ctx context.Context, scope Scope, id string, after uint64, limit int) ([]ImageEvent, error)

func (*Store) ReadExecution

func (s *Store) ReadExecution(scope Scope, id string) (ExecutionRecord, error)

func (*Store) ReadJob

func (s *Store) ReadJob(scope Scope, id string) (ImageJob, error)

func (*Store) ReadJobSnapshot

func (s *Store) ReadJobSnapshot(scope Scope, id string) (ImageJob, EventPosition, error)

ReadJobSnapshot reads the job and event cursor in a single consistent view.

func (*Store) ReadProject

func (s *Store) ReadProject(scope Scope, id string) (ImageProject, error)

func (*Store) Update

func (s *Store) Update(ctx context.Context, fn func(*Transaction) error) error

func (*Store) UpdateProject

func (s *Store) UpdateProject(ctx context.Context, scope Scope, id, title string, expectedRevision uint64) (ImageProject, error)

type TargetCapabilities

type TargetCapabilities struct {
	Operations           []Operation `json:"operations"`
	SupportsCancel       bool        `json:"supportsCancel"`
	SupportsReconcile    bool        `json:"supportsReconcile"`
	SupportsContinuation bool        `json:"supportsContinuation"`
	SupportsPreview      bool        `json:"supportsPreview"`
	MaxInputs            int         `json:"maxInputs"`
	MaxCount             int         `json:"maxCount"`
	OutputFormats        []string    `json:"outputFormats"`
}

type TargetResolver

type TargetResolver = Registry

type TargetSnapshot

type TargetSnapshot struct {
	Source          string             `json:"source,omitempty"`
	ProviderID      string             `json:"providerId,omitempty"`
	ModelID         string             `json:"modelId,omitempty"`
	VerificationID  string             `json:"verificationId,omitempty"` // Backend-issued receipt identity; never a credential.
	ID              string             `json:"id"`
	Name            string             `json:"name"`
	ConnectionID    string             `json:"connectionId"`
	Adapter         string             `json:"adapter"`
	AdapterVersion  string             `json:"adapterVersion"`
	Kind            string             `json:"kind"`
	RemoteID        string             `json:"remoteId"`
	Revision        uint64             `json:"revision"`
	Capabilities    TargetCapabilities `json:"capabilities"`
	Parameters      []ParameterSpec    `json:"parameters"`
	WorkflowMapping *WorkflowMapping   `json:"workflowMapping,omitempty"`
}

func SnapshotTarget

func SnapshotTarget(t ImageTarget) TargetSnapshot

func (TargetSnapshot) MarshalJSON

func (t TargetSnapshot) MarshalJSON() ([]byte, error)

type TargetVerification

type TargetVerification struct {
	BindingDigest    string    `json:"-"`
	JobID            string    `json:"-"`
	ContractComplete bool      `json:"-"`
	LiveVerifiedAt   time.Time `json:"-"`
	ConnectionID     string    `json:"-"`
	AdapterVersion   string    `json:"-"`
	TargetRevision   uint64    `json:"-"`
}

Evidence is bound to the connection, adapter version and target revision. The registration layer must supply genuine evidence; zero values disable execution.

type Transaction

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

func (*Transaction) AppendEvent

func (tx *Transaction) AppendEvent(v ImageEvent) error

func (*Transaction) DeleteJob

func (tx *Transaction) DeleteJob(id string) error

func (*Transaction) DeleteProject

func (tx *Transaction) DeleteProject(id string, expectedRevision uint64) error

func (*Transaction) GetIdempotency

func (tx *Transaction) GetIdempotency(scope Scope, key string) (IdempotencyRecord, bool)

func (*Transaction) GetJobRecord

func (tx *Transaction) GetJobRecord(scope Scope, id string) (JobRecord, error)

func (*Transaction) PruneEvents

func (tx *Transaction) PruneEvents(id string) error

PruneEvents only removes the contiguous prefix older than 30 days.

func (*Transaction) PutAsset

func (tx *Transaction) PutAsset(v ImageAsset) error

func (*Transaction) PutExecution

func (tx *Transaction) PutExecution(v ExecutionRecord) error

func (*Transaction) PutIdempotency

func (tx *Transaction) PutIdempotency(scope Scope, key, hash, jobID string) error

func (*Transaction) PutJob

func (tx *Transaction) PutJob(v ImageJob) error

func (*Transaction) PutJobRecord

func (tx *Transaction) PutJobRecord(record JobRecord) error

PutJobRecord stages the public job and its private execution in one transaction. The caller must also AppendEvent for the new job revision. For private-only changes (poll schedules, leases), use PutExecution without a public revision.

func (*Transaction) PutProject

func (tx *Transaction) PutProject(v ImageProject) error

func (*Transaction) ReadAsset

func (tx *Transaction) ReadAsset(scope Scope, id string) (ImageAsset, error)

func (*Transaction) ReadExecution

func (tx *Transaction) ReadExecution(scope Scope, id string) (ExecutionRecord, error)

func (*Transaction) ReadJob

func (tx *Transaction) ReadJob(scope Scope, id string) (ImageJob, error)

func (*Transaction) ReadProject

func (tx *Transaction) ReadProject(scope Scope, id string) (ImageProject, error)

type Usage

type Usage struct {
	Amount    *string `json:"amount"`
	Currency  string  `json:"currency"`
	Source    string  `json:"source"`
	Estimated bool    `json:"estimated"`
}

type VerificationReceipt

type VerificationReceipt struct {
	ID               string    `json:"id"`
	TargetID         string    `json:"targetId"`
	JobID            string    `json:"jobId,omitempty"`
	State            string    `json:"state"`
	JobStatus        JobStatus `json:"jobStatus,omitempty"`
	SettingsRevision uint64    `json:"settingsRevision"`
	Reason           string    `json:"reason,omitempty"`
}

type VerificationSummary

type VerificationSummary struct {
	State          string     `json:"state"`
	JobID          string     `json:"jobId,omitempty"`
	LiveVerifiedAt *time.Time `json:"liveVerifiedAt,omitempty"`
	Reason         string     `json:"reason,omitempty"`
}

VerificationSummary is read-only public evidence. It contains no binding fingerprint, credential reference, provider handle, endpoint or output URL.

type VerifyTargetRequest

type VerifyTargetRequest struct {
	ExpectedRevision *uint64   `json:"expectedRevision"`
	ProjectID        string    `json:"projectId"`
	ConnectionID     string    `json:"connectionId"`
	RemoteID         string    `json:"remoteId"`
	TargetRevision   *uint64   `json:"targetRevision"`
	Operation        Operation `json:"operation"`
	Count            int       `json:"count"`
	Prompt           string    `json:"prompt"`
	ConfirmPaid      bool      `json:"confirmPaid"`
}

type WorkflowInput

type WorkflowInput struct {
	ParameterKey string `json:"parameterKey"`
	NodeID       string `json:"nodeId"`
	InputName    string `json:"inputName"`
}

type WorkflowMapping

type WorkflowMapping struct {
	Revision uint64           `json:"revision"`
	Inputs   []WorkflowInput  `json:"inputs"`
	Outputs  []WorkflowOutput `json:"outputs"`
}

func (WorkflowMapping) MarshalJSON

func (m WorkflowMapping) MarshalJSON() ([]byte, error)

type WorkflowOutput

type WorkflowOutput struct {
	NodeID     string `json:"nodeId"`
	OutputName string `json:"outputName"`
}

Directories

Path Synopsis
adapters
async
Package asyncadapter implements evidence-scoped asynchronous image protocols.
Package asyncadapter implements evidence-scoped asynchronous image protocols.
direct
Package direct implements restricted, synchronous image provider protocols.
Package direct implements restricted, synchronous image provider protocols.

Jump to

Keyboard shortcuts

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