asyncadapter

package
v0.107.39 Latest Latest
Warning

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

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

README

Async adapter handoff (2026-10-11)

Only this package was changed. No registry, imaging core, service, scheduler, backend, settings, credentials, or production target was changed. No remote platform call was made. All request execution in tests uses loopback httptest servers.

Registration and execution dependencies

Import github.com/Stack-Cairn/K-brain/internal/imaging/adapters/async with package name asyncadapter.

  • Factory(adapterID, adapterVersion, Options, *WorkflowOptions) (imaging.Adapter, error) is the registration handoff. IDs: jimeng-image, runninghub-workflow; version: 1. Unknown IDs/versions return imaging.ErrUnsupported.
  • NewJimeng(Options) and NewRunningHub(WorkflowOptions) are direct constructors. Construction is not production enablement or verification. Availability() explicitly reports both as not enabled, LiveVerified=false. RunningHub remains ContractComplete=false.
  • Options.Connection uses the existing imaging.ResolvedConnection: caller injects HTTPClient, SecretResolver, and authorized scope. Resolve secret refs on each operation; do not read environment credentials. Jimeng needs AccessKeyRef/SecretKeyRef and optionally SecurityTokenRef. RunningHub needs SecretRef. Secret purpose names are a backend configuration decision, not inferred from user settings.
  • Connect factory through existing imaging.ServiceOptions.AdapterResolver. The resolver must enforce current authorization and resolve the connection against the frozen target. It must recover the same frozen RunningHub graph, mapping, revision, and webhook option for later Poll calls; do not use a newly edited live target for an old job.
  • HTTP transport must implement backend network/proxy policy, without retries, logging, auth injection, or internal redirects. Adapter copies the client, disables cookies and redirects, and supplies a 60-second timeout only when the injected client has no positive timeout. Adapter does not implement DNS/SSRF policy itself; NetworkProfile is not a substitute for an enforcing transport.
  • API defaults are only documented Visual CN / RunningHub CN hosts. A trusted BaseURL override permits HTTPS and loopback HTTP for fixtures. Do not accept this configuration from a generation request.
  • Do not serialize execution Options or WorkflowOptions: their JSON marshal methods fail. RemoteResult/OutputSource use existing core private non-serializable contracts. Upstream URLs, file references, opaque handles, AK/SK/token, webhook URLs and response messages never become public errors. Raw response metadata, WSS URLs and request IDs are deliberately discarded.
  • Output URL download, network allowlists, true image decoding, persistence and partial-result accounting remain the existing AssetSink responsibility. Base64 Visual results and upload inputs are decoded locally too. Usage stays nil; no invented price/units.

Jimeng implemented scope

Signed Visual OpenAPI /, POST, Action CVSync2AsyncSubmitTask / CVSync2AsyncGetResult, Version 2022-08-31, region cn-north-1, service cv, req_key jimeng_t2i_v40. Fixed RFC3986 query/header canonicalization, raw-body SHA256, HMAC key chain, UTC clock and optional signed STS token follow research J2/J3/J4.

Current factory supports generate, count=1, force_single=true; prompt and documented size/width/height/scale/min_ratio/max_ratio validation. Unknown parameters fail before submit. Suggested capabilities: generate only, MaxInputs=0, MaxCount=1, png; cancel/reconcile/continuation/preview false. Local prompt/response byte ceilings are implementation policy, not provider limits.

Submit pending handle; poll queued/generating pending; done requires valid output; explicit documented done/output rejection fails; unknown/not_found/expired/empty output remains unknown. Transient poll errors retain the handle. Cancel and Reconcile return ErrUnsupported. Recovery is Poll(savedHandle) only. SubmissionKey/request_id are not idempotency or recovery tokens. No automatic submission retry.

The current core provides InputResolver.ResolveAsset -> ResolvedAsset.Open; it does not provide an InputReader type or an authorized externally accessible asset URL. Consequently reference/edit are unsupported here even though the research documents native image_urls. Minimal later addition: a backend-only, scoped asset URL publisher/resolver with expiry and storage ownership; never accept arbitrary URLs through user parameters or substitute local paths. Core was not modified.

RunningHub implemented scope and workflow freeze

  • Fetch graph: /api/openapi/getJsonApiFormat, Header Bearer + body apiKey/workflowId. Compare canonical full API-format JSON SHA256 with the backend-pinned graph before uploading/submitting. Changed graph or frozen target/mapping revision fails not_sent. No upstream revision or compare-and-swap guarantee exists: a remote edit after the check is still a documented race/gap.
  • Upload: /openapi/v2/media/upload/binary, Bearer + multipart file only; validate PNG/JPEG/WebP with core decoder and close input stream. Use returned fileName, never download_url, in ComfyUI nodes. Local caps: 20 MiB and 40M pixels. No cross-attempt upload cache or assumed file lifetime.
  • Submit: /task/openapi/create, Bearer + body apiKey/workflowId/nodeInfoList, optionally explicitly backend-configured webhookUrl. Only declared node fields, ordered by mapping. fieldValue strings are the conservative current schema profile. Require matching underlying scalar type; reject links/objects and undeclared request parameters. No custom workflow, retainSeconds, instance type, accessPassword or personal queue field is exposed.
  • WorkflowOptions requires an actual reviewed graph and target. All mappings must name existing graph nodes/input keys. Each mapped parameter must be declared in Target.Parameters; parameter and node slots cannot be duplicated. Ordinary parameters use existing schema validation. Reserved prompt, count, input.<role> bindings must be declared as optional, no-default parameters (string/integer/string respectively), and their values come exclusively from Request.Prompt / Request.Count / authorized Request.Inputs+ResolvedAsset. Supplying these reserved values in Request.Parameters is rejected. A role identifies one asset, preserving mapping order; repeated assets in one role are rejected rather than guessed. Existing settings validation accepts the dot-based names. UI should not render these reserved declarations as duplicate ordinary form controls.
  • Query: /openapi/v2/query, Bearer + taskId only, without legacy body key. Preserve numeric taskId strings without float conversion. QUEUED/RUNNING pending; FAILED failed; unfamiliar or mismatched task identity unknown. Existing saved handle can be polled by a fresh adapter without submit memory. Do not fall back to deprecated status/outputs.
  • V2 SUCCESS has no node identity. It remains unknown by default, even if results contains image URLs. Never infer node/output from array position, URL or filename.
  • Optional, explicitly configured webhook candidate: after V2 SUCCESS, /task/openapi/getWebhookDetail with Header+body key retrieves authenticated detail. Require detail.taskId matches, decode bounded eventData string, require inner code=0, filter only configured output node IDs, allowed image formats and HTTPS URLs. CallbackStatus is delivery status, not generation status. Ignore callbackResponse/WSS/auth metadata. OutputName="image" is an explicit local image label, not a provider output socket; any other label is rejected. Valid images survive alongside rejected video/archive/unmapped entries. The callback is never trusted as an unauthenticated inbound event.
  • Reconcile always ErrUnsupported: current scheduler passes SubmissionKey, not handle. This avoids falsely treating it as taskId.

Parent integration blockers / minimal additions

  1. Cancel ACK mismatch: /task/openapi/cancel is implemented and tested. Current scheduler.finishCancel interprets nil error as upstream_confirmed and terminal cancelled. RunningHub code=0 proves only request ACK, not terminal cessation/refund. Therefore this adapter deliberately returns AdapterError{Code: IMAGE_RESULT_UNKNOWN, Delivery: uncertain} after ACK. Current service records local_only instead of falsely confirming upstream cancellation. Keep production supportsCancel disabled until cancellation return semantics can distinguish accepted vs terminal-confirmed (e.g. a typed cancellation result or explicit ACK sentinel handled by scheduler). No core edits made.
  2. Graph persistence: public WorkflowMapping contains revision/inputs/outputs, but not frozen graph digest/API JSON or private webhook configuration. The authorized AdapterResolver needs backend-private versioned storage for these, keyed by target revision. Factory options are sufficient for static tests, not durable production configuration.
  3. Mapping source semantics: reserved optional schema entries above fit current struct/validator shape but need an explicit API/form convention. A cleaner minimal future contract is a WorkflowInput source discriminator for prompt/count/parameter/asset role; do not silently treat asset inputs as user-provided strings. Exact provider outputName remains unproven; local image-label semantics must be explicitly accepted before production enablement.
  4. Request ID diagnostics: RemoteResult has no private RequestID field. Official request IDs are not forwarded to public fields or repurposed as handles. If required for private attempt diagnostics, core owner can add a backend-only RequestID field.
  5. Jimeng URL inputs: scoped URL publisher is absent as described above. Generate remains the implemented subset.

Evidence and outstanding verification

Sources are the caller-requested docs/research/image-studio-2026-10-11/{jimeng,runninghub,matrix}.md and docs/plans/2026-10-11-image-studio/04-provider-adapters.md. RunningHub R16/R17 are described in the research text but their primary URLs are not present in its source index; their schema/timing claims have not been independently rechecked here. web.run was unavailable in this tool environment; no alternate scraping or endpoint guess was used.

All testdata files are sanitized self-built offline fixtures based on documented structures, not official complete schemas or live receipts. Signature expected canonical/auth values were calculated independently with Python hashlib/hmac using fake keys and frozen time; Go signer matches. This is not an official CV test vector. Official CV vector still missing; generic billing vector was not misrepresented or used without its full documented inputs.

Remaining: real authorized workflow ID/graph/nodes/revision, successful upload/create/query/result/cancel receipts; native output identity/outputName guarantees, authenticated webhook-detail event availability/TTL/error samples; revision race/conditional execution guarantee; key/body auth and fieldValue type discrepancy resolution; account quotas and result/file lifetimes; Jimeng official CV vector and live credentials/permissions. Neither target may be enabled from fixtures alone. No paid call, personal config, or old logs were accessed.

Tests exercise request methods/paths/auth/body, deterministic signature and STS, queue/running/failed/unknown/expired states, empty/illegal image outputs, HTTP rejection/redirect/malformed responses, normalized sensitive errors with no unwrap cause, large task IDs, graph revision drift, missing required/undeclared mappings, multipart uploads and close, image-node filtering, cancel capability/ACK ambiguity, submit timeouts without replay and fresh-adapter poll recovery.

Documentation

Overview

Package asyncadapter implements evidence-scoped asynchronous image protocols. Factories do not register or enable production targets. See README.md.

Index

Constants

View Source
const (
	JimengID     = "jimeng-image"
	RunningHubID = "runninghub-workflow"
	Version      = "1"
)
View Source
const RunningHubLiteModel = "rhart-image-n-g31-flash-lite-official"
View Source
const RunningHubModelID = "runninghub-model"

Variables

This section is empty.

Functions

func Factory

func Factory(id, version string, o Options, workflow *WorkflowOptions) (imaging.Adapter, error)

Factory is the registration handoff; no global registry is modified. Workflow must be non-nil for RunningHub. Factories create implementations, never trusted evidence: targets remain disabled until independently verified.

Types

type FactoryAvailability

type FactoryAvailability struct {
	Adapter          string
	AdapterVersion   string
	Enabled          bool
	ContractComplete bool
	LiveVerified     bool
	DisabledReason   string
}

FactoryAvailability deliberately distinguishes implementation from deployment. RunningHub's output identity contract and real workflow evidence are incomplete.

func Availability

func Availability() []FactoryAvailability

type Jimeng

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

func NewJimeng

func NewJimeng(o Options) (*Jimeng, error)

func (*Jimeng) Cancel

func (*Jimeng) Cancel(context.Context, string) error

func (*Jimeng) Poll

func (a *Jimeng) Poll(ctx context.Context, h string) (imaging.RemoteResult, error)

func (*Jimeng) Reconcile

func (*Jimeng) Submit

type Options

type Options struct {
	Connection       imaging.ResolvedConnection
	Scope            imaging.Scope
	BaseURL          string
	SecretRef        string // RunningHub API key
	AccessKeyRef     string // Jimeng AK
	SecretKeyRef     string // Jimeng SK
	SecurityTokenRef string // Optional Jimeng STS
	Now              func() time.Time
}

Options must come from trusted backend configuration. HTTPClient's transport must enforce network policy and must not retry, log, or inject credentials. ResolvedConnection provides the existing HTTP and scoped secret contracts.

func (Options) MarshalJSON

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

Options are backend-only even if accidentally passed to an HTTP JSON encoder.

type RunningHub

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

func NewRunningHub

func NewRunningHub(o WorkflowOptions) (*RunningHub, error)

func (*RunningHub) Cancel

func (a *RunningHub) Cancel(ctx context.Context, h string) error

func (*RunningHub) Poll

func (*RunningHub) Reconcile

func (*RunningHub) Submit

type RunningHubModel

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

Model targets use documented V2 model endpoints. They do not consume a workflow graph, node mappings, or the workflow webhook-detail protocol.

func NewRunningHubModel

func NewRunningHubModel(o Options) (*RunningHubModel, error)

func (*RunningHubModel) Cancel

func (*RunningHubModel) Poll

func (*RunningHubModel) Reconcile

func (*RunningHubModel) Submit

type WorkflowOptions

type WorkflowOptions struct {
	Options
	Target        imaging.TargetSnapshot
	APIFormatJSON []byte
	WebhookURL    string
}

WorkflowOptions freezes a locally reviewed API-format graph and mapping. No workflow or operation is supplied by default. WebhookURL enables only the documented candidate authenticated event-detail path, not production evidence. OutputName must be "image" (a local label, never an inferred upstream socket). Input ParameterKey supports prompt, count, declared parameters, and input.<role>.

func (WorkflowOptions) MarshalJSON

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

Jump to

Keyboard shortcuts

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