contract

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 25 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 contract 实现跨模块契约调用的边界语义。

对于 Unary 契约方法,无论对端是进程内实现还是远程 client,都必须经过 Call: 由合约仓库生成的 wrapper/client 在方法体内调用它。Call 保证两种部署形态下 语义一致(ServiceWeaver 教训的反向落地——不隐藏网络边界,而是让进程内调用 也表现得像一次可失败的远程调用):

  1. 运行时守卫:事务内发起契约调用直接失败(apperr.CodeTxBoundary)。 静态分析对这条规则只能提高绕过成本,运行时守卫在任何测试里都会暴露。
  2. ctx 防火墙:剥离事务句柄与请求作用域值,只保留取消/超时传播、 OpenTelemetry span 与 callctx.Meta 白名单——与跨网络传播的信息一致。
  3. 协作式超时:每次调用有独立 deadline(默认 5s),通过 ctx 传给进程内 或远程实现;发起时 ctx 已取消/超时的调用直接失败(CodeUnavailable), 不进入实现——跨网络时这种调用本来就发不出去。已经启动的同步 fn 不会被 goroutine+select 强杀;若忽略 ctx,Call 可能在 deadline 后才返回,写操作 的调用方必须按成功或未知结果用幂等/查询收敛。
  4. 错误规范化:任何错误折叠为 *apperr.Error,错误身份 = 错误码。

每次 Unary 调用还自动产出一条 span 与一条 appkit.contract.call.duration 观测 (标签 system/method/outcome,失败时附错误码)——契约边界是模块间唯一的 交互面,这里的延迟与错误率就是模块间的 SLI,不该等到出事才补埋点。 双向流是独立调用形态,见 stream.go;它不改变下方 Call 的语义。

Index

Examples

Constants

View Source
const DefaultTimeout = 5 * time.Second

DefaultTimeout 是单次契约调用的默认超时。

View Source
const HeaderServiceAuthorization = "X-Service-Authorization"

HeaderServiceAuthorization carries a service credential, never a user token.

Variables

This section is empty.

Functions

func Call

func Call[T any](ctx context.Context, system, method string, timeout time.Duration, fn func(ctx context.Context) (T, error)) (T, error)

Call 执行一次契约调用。system/method 用于 span 命名与错误归属, 形如 Call(ctx, "ledger", "PostEntries", 0, func(ctx) (T, error) { ... })。 timeout 为 0 时取 DefaultTimeout。

func Firewall

func Firewall(ctx context.Context) context.Context

Firewall 返回剥离了全部 ctx 值(含事务句柄)的 ctx,保留取消/超时、 当前 span 与 callctx.Meta。

保留的这三样恰好是跨网络调用里本来也会传的东西(deadline、traceparent、 request/tenant 头),一件不多——所以进程内调用拿不到任何比远程调用更多的 上下文,两种部署形态下代码行为一致。

func NewSecureHTTPClient added in v0.9.1

func NewSecureHTTPClient(base string, opts SecureClientOptions) (*http.Client, error)

NewSecureHTTPClient constructs an HTTPS-only client bound to base's origin. 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.

Types

type ClientStream added in v0.9.6

type ClientStream[Send, Receive any] interface {
	Stream[Send, Receive]
	// CloseSend half-closes the client-to-server direction after any active Send.
	CloseSend(context.Context) error
	// Close cancels the root stream and waits up to StreamConfig.CloseTimeout.
	Close() error
}

ClientStream is returned by a stream adapter. Close cancels the whole stream, waits up to the configured CloseTimeout, and is idempotent.

func OpenLocal added in v0.9.6

func OpenLocal[Send, Receive any](ctx context.Context, system, method string, cfg StreamConfig, handler StreamHandler[Send, Receive]) (ClientStream[Send, Receive], error)

OpenLocal 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.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"time"

	"github.com/forgeplex/appkit/contract"
)

type exampleStreamRequest struct{ Text string }
type exampleStreamReply struct{ Text string }

func main() {
	stream, err := contract.OpenLocal(context.Background(), "greeter", "GreetStream",
		contract.StreamConfig{
			MaxDuration:  time.Minute,
			CloseTimeout: time.Second,
			QueueSize:    1,
		},
		func(ctx context.Context, peer contract.Stream[exampleStreamReply, exampleStreamRequest]) error {
			request, err := peer.Recv(ctx)
			if err != nil {
				return err
			}
			return peer.Send(ctx, exampleStreamReply{Text: request.Text})
		},
	)
	if err != nil {
		panic(err)
	}
	if err := stream.Send(context.Background(), exampleStreamRequest{Text: "hello"}); err != nil {
		panic(err)
	}
	if err := stream.CloseSend(context.Background()); err != nil {
		panic(err)
	}
	reply, err := stream.Recv(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Println(reply.Text)
	_, err = stream.Recv(context.Background())
	fmt.Println(errors.Is(err, io.EOF))
	if err := stream.Close(); err != nil {
		panic(err)
	}
}
Output:
hello
true

type SecureClientOptions added in v0.9.1

type SecureClientOptions struct {
	Audience    string
	Credentials ServiceCredentialProvider
	HTTPClient  *http.Client
}

SecureClientOptions 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.

type ServerStream added in v0.10.0

type ServerStream[T any] interface {
	Recv(context.Context) (T, error)
	Close() error
}

ServerStream 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.

type ServiceCredential added in v0.9.1

type ServiceCredential struct {
	Token     string
	ExpiresAt time.Time
}

ServiceCredential 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.

type ServiceCredentialProvider added in v0.9.1

type ServiceCredentialProvider interface {
	ServiceCredential(context.Context, ServiceScope) (ServiceCredential, error)
}

ServiceCredentialProvider 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.

type ServiceCredentialProviderFunc added in v0.9.1

type ServiceCredentialProviderFunc func(context.Context, ServiceScope) (ServiceCredential, error)

ServiceCredentialProviderFunc adapts an explicit provider function.

func (ServiceCredentialProviderFunc) ServiceCredential added in v0.9.1

type ServiceScope added in v0.9.1

type ServiceScope struct {
	Audience  string
	Partition string
	TenantID  string
}

ServiceScope is an explicit delegation request, not proof of authorization. The provider must authorize its audience and every nonempty scope before signing. Tenant and partition originate in the contract context whitelist; user actors, merchant IDs and incoming HTTP credentials are not forwarded.

type Stream added in v0.9.6

type Stream[Send, Receive any] interface {
	// Send enqueues a message in order. A full queue waits for capacity or for
	// either the operation or stream context to end.
	Send(context.Context, Send) error
	// Recv returns the next message, io.EOF, or a stable stream terminal error.
	Recv(context.Context) (Receive, error)
}

Stream 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.

type StreamConfig added in v0.9.6

type StreamConfig struct {
	// MaxDuration is the required maximum lifetime of the stream.
	MaxDuration time.Duration
	// IdleTimeout ends the stream after this much time without successful Send or
	// Recv activity. Zero disables idle detection.
	IdleTimeout time.Duration
	// CloseTimeout is the required budget for waiting for the producer to exit.
	CloseTimeout time.Duration
	// QueueSize is the bounded message capacity in each direction. Zero applies
	// direct rendezvous backpressure with no buffered messages.
	QueueSize int
}

StreamConfig 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.

type StreamHandler added in v0.9.6

type StreamHandler[Send, Receive any] func(context.Context, Stream[Receive, Send]) error

StreamHandler handles the server side of an in-process stream. Its Send and Receive types are reversed from the client endpoint.

Directories

Path Synopsis
Package streamtest provides a reusable behavioral suite for contract stream adapters.
Package streamtest provides a reusable behavioral suite for contract stream adapters.

Jump to

Keyboard shortcuts

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