{"modulePath":"github.com/forgeplex/appkit","version":"v0.17.5","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package contract\n\nPackage contract 实现跨模块契约调用的边界语义。\n\n对于 Unary 契约方法，无论对端是进程内实现还是远程 client，都必须经过 Call： 由合约仓库生成的 wrapper/client 在方法体内调用它。Call 保证两种部署形态下 语义一致（ServiceWeaver 教训的反向落地——不隐藏网络边界，而是让进程内调用 也表现得像一次可失败的远程调用）：\n\n 1. 运行时守卫：事务内发起契约调用直接失败（apperr.CodeTxBoundary）。 静态分析对这条规则只能提高绕过成本，运行时守卫在任何测试里都会暴露。\n 2. ctx 防火墙：剥离事务句柄与请求作用域值，只保留取消/超时传播、 OpenTelemetry span 与 callctx.Meta 白名单——与跨网络传播的信息一致。\n 3. 协作式超时：每次调用有独立 deadline（默认 5s），通过 ctx 传给进程内 或远程实现；发起时 ctx 已取消/超时的调用直接失败（CodeUnavailable）， 不进入实现——跨网络时这种调用本来就发不出去。已经启动的同步 fn 不会被 goroutine+select 强杀；若忽略 ctx，Call 可能在 deadline 后才返回，写操作 的调用方必须按成功或未知结果用幂等/查询收敛。\n 4. 错误规范化：任何错误折叠为 \\*apperr.Error，错误身份 = 错误码。\n\n每次 Unary 调用还自动产出一条 span 与一条 appkit.contract.call.duration 观测 （标签 system/method/outcome，失败时附错误码）——契约边界是模块间唯一的 交互面，这里的延迟与错误率就是模块间的 SLI，不该等到出事才补埋点。 双向流是独立调用形态，见 stream.go；它不改变下方 Call 的语义。\n\n## Constants\n\n```go\nconst DefaultTimeout = 5 * time.Second\n```\nDefaultTimeout 是单次契约调用的默认超时。\n\n```go\nconst HeaderServiceAuthorization = \"X-Service-Authorization\"\n```\nHeaderServiceAuthorization carries a service credential, never a user token.\n\n## Functions\n\n```go\nfunc Call[T any](ctx context.Context, system, method string, timeout time.Duration, fn func(ctx context.Context) (T, error)) (T, error)\n```\nCall 执行一次契约调用。system/method 用于 span 命名与错误归属， 形如 Call(ctx, \"ledger\", \"PostEntries\", 0, func(ctx) (T, error) { ... })。 timeout 为 0 时取 DefaultTimeout。\n\n```go\nfunc Firewall(ctx context.Context) context.Context\n```\nFirewall 返回剥离了全部 ctx 值（含事务句柄）的 ctx，保留取消/超时、 当前 span 与 callctx.Meta。\n\n保留的这三样恰好是跨网络调用里本来也会传的东西（deadline、traceparent、 request/tenant 头），一件不多——所以进程内调用拿不到任何比远程调用更多的 上下文，两种部署形态下代码行为一致。\n\n```go\nfunc NewSecureHTTPClient(base string, opts SecureClientOptions) (*http.Client, error)\n```\nNewSecureHTTPClient constructs an origin-bound authenticated client for base. By default only HTTPS origins are permitted; set AllowInsecureHTTP for trusted internal cluster HTTP endpoints. Use it through a generated NewSecureClient so contract.Call also supplies the transaction guard, timeout and error normalization. Configuration and provider code are trusted application code, not a sandbox. Do not mutate the returned client's fields to replace its security transport or redirect policy.\n\n## Types\n\n```go\ntype ClientStream[Send, Receive any] interface {\n\tStream[Send, Receive]\n\t// CloseSend half-closes the client-to-server direction after any active Send.\n\tCloseSend(context.Context) error\n\t// Close cancels the root stream and waits up to StreamConfig.CloseTimeout.\n\tClose() error\n}\n```\nClientStream is returned by a stream adapter. Close cancels the whole stream, waits up to the configured CloseTimeout, and is idempotent.\n\n```go\nfunc OpenLocal[Send, Receive any](ctx context.Context, system, method string, cfg StreamConfig, handler StreamHandler[Send, Receive]) (ClientStream[Send, Receive], error)\n```\nOpenLocal establishes a bidirectional in-process contract stream. Synchronous validation, transaction-boundary, and pre-cancelled-context errors are returned before the handler starts. Once established, handler errors are delivered by Recv and normalized to \\*apperr.Error. Callers should pass stable system and method names, just as with Call.\n\n```go\ntype SecureClientOptions struct {\n\tAudience          string\n\tCredentials       ServiceCredentialProvider\n\tHTTPClient        *http.Client\n\tAllowInsecureHTTP bool\n}\n```\nSecureClientOptions configures authenticated, origin-bound contract HTTP. Audience and Credentials are mandatory. HTTPClient may customize timeouts and a standard \\*http.Transport (including trusted root certificates). Custom round trippers, TLS dialers/protocol handlers, insecure TLS and cookie jars are rejected. Requests with trailers are rejected rather than forwarding hidden credentials or silently dropping a caller's integrity trailer. The supplied client/transport configuration is copied. Redirects are always refused; a supplied CheckRedirect callback is not used.\n\nAllowInsecureHTTP opts in to plaintext http:// base URLs for trusted in-cluster or service-mesh internal networks. Even with AllowInsecureHTTP set, origin binding, redirect refusal, trailer refusal, context firewalling, and service JWT injection remain strictly enforced.\n\n```go\ntype ServerStream[T any] interface {\n\tRecv(context.Context) (T, error)\n\tClose() error\n}\n```\nServerStream receives a server-to-client stream after its single request has been sent. It deliberately exposes neither Send nor CloseSend. Recv contexts affect only that operation; Close cancels the whole stream and is idempotent. As with ClientStream, overlapping Recv calls are rejected, accepted messages drain before the terminal error, and Close has the configured close budget. Streaming APIs remain experimental until explicitly promoted under ADR-0047.\n\n```go\ntype ServiceCredential struct {\n\tToken     string\n\tExpiresAt time.Time\n}\n```\nServiceCredential contains a bare service JWT and its actual signed expiry. Providers must not return a user token or invent a later expiry for a token.\n\n```go\ntype ServiceCredentialProvider interface {\n\tServiceCredential(context.Context, ServiceScope) (ServiceCredential, error)\n}\n```\nServiceCredentialProvider obtains a fresh, explicitly authorized service credential for each HTTP attempt. Implementations must honor cancellation and be safe for concurrent calls. The transport does not cache credentials.\n\n```go\ntype ServiceCredentialProviderFunc func(context.Context, ServiceScope) (ServiceCredential, error)\n```\nServiceCredentialProviderFunc adapts an explicit provider function.\n\n```go\nfunc (f ServiceCredentialProviderFunc) ServiceCredential(ctx context.Context, scope ServiceScope) (ServiceCredential, error)\n```\n\n```go\ntype ServiceScope struct {\n\tAudience string\n\tTenantID string\n}\n```\nServiceScope is an explicit delegation request, not proof of authorization. The provider must authorize its audience and every nonempty scope before signing. Tenant originates in the contract context whitelist; user actors, merchant IDs and incoming HTTP credentials are not forwarded.\n\n```go\ntype Stream[Send, Receive any] interface {\n\t// Send enqueues a message in order. A full queue waits for capacity or for\n\t// either the operation or stream context to end.\n\tSend(context.Context, Send) error\n\t// Recv returns the next message, io.EOF, or a stable stream terminal error.\n\tRecv(context.Context) (Receive, error)\n}\n```\nStream is one endpoint of a bidirectional contract stream. Send and Recv each accept an operation context: cancellation of that context affects only that operation. The stream's root context is controlled by the adapter's Open and ClientStream.Close operations. Concurrent Send calls and concurrent Recv calls are rejected; one Send and one Recv may run at the same time. Streaming APIs remain experimental until explicitly promoted under ADR-0047.\n\n```go\ntype StreamConfig struct {\n\t// MaxDuration is the required maximum lifetime of the stream.\n\tMaxDuration time.Duration\n\t// IdleTimeout ends the stream after this much time without successful Send or\n\t// Recv activity. Zero disables idle detection.\n\tIdleTimeout time.Duration\n\t// CloseTimeout is the required budget for waiting for the producer to exit.\n\tCloseTimeout time.Duration\n\t// QueueSize is the bounded message capacity in each direction. Zero applies\n\t// direct rendezvous backpressure with no buffered messages.\n\tQueueSize int\n}\n```\nStreamConfig defines the independent lifetime and buffering policy of a stream. MaxDuration and CloseTimeout are required. IdleTimeout disables idle detection when zero. QueueSize is the bounded capacity of each direction; zero means rendezvous-only backpressure. No field inherits contract.Call's unary timeout.\n\n```go\ntype StreamHandler[Send, Receive any] func(context.Context, Stream[Receive, Send]) error\n```\nStreamHandler handles the server side of an in-process stream. Its Send and Receive types are reversed from the client endpoint.\n\n","path":"github.com/forgeplex/appkit/contract","name":"contract","synopsis":"Package contract 实现跨模块契约调用的边界语义。","isRedistributable":true}
