gateway

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 21 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.

README

对等网关发现

公开包 github.com/lfhy/compactfs/fs/cluster/gateway 的 Gateway 是 HTTP handler,提供对等成员发现、服务租约和流式 HTTP/WebSocket 转发。Join(A, B) 让双方互相学习成员;后台交换使第三个网关发现已有成员和服务。服务地址只保存在有界租约中,元数据和数据对象仍由原服务拥有。

import "github.com/lfhy/compactfs/fs/cluster/gateway"

gw, err := gateway.New(gateway.Config{
    Advertise: "http://10.0.0.1:7420",
    StatePath: "/var/lib/compactfs/gateway-peers.json",
    Peers: []string{"http://10.0.0.2:7420"},
})
// 检查 err;把 gw 交给已持有 listener 的 HTTP server。
go gw.Run(ctx)
// 退出先停止 HTTP server 和升级连接,再 gw.Close()。

应用可以用 OnPeers func([]string) error 把成员保存到自己的配置文件,替代 StatePath。回调串行执行,禁止重入 gateway;返回失败会拒绝本地更新。种子暂时不可达不阻止启动,Run 会持续尝试连接。服务进程用顶层 Register 定期续租,Discover 返回当前成员和有效服务。

管理路径为 /v1/gateway/join、exchange、state、register、discover。默认面向可信存储内网且不认证管理调用;配置同一个 Key 后,管理请求必须携带 X-Cpfs-Mesh-Key。该 key 不转发到应用服务。HTTP/WebSocket 的原有 HMAC/STS 认证仍在 Auth、Meta 和 Data 处验证。

  • /v1/auth/* 转发到明确登记为 leader 的独立 Auth。
  • /v1/control 与文件流转发到明确登记为 leader 的 Meta;不把 follower 自动升级为主。服务用物理副本 ID 注册,每次续租读取当前角色、Epoch 和 Raft Term;网关先比较 Epoch,再比较 Term。
  • /nodes/{id}/v1/data/* 和 compute 路径转发到该服务的归属网关,再剥掉节点前缀连接本地服务。转发不复制请求 body,不重试结果未知的修改。
  • /v1/services/{kind}/{physicalID}/... 定向到固定副本;kind 可为 meta、auth、data、compute。只有所属网关剥前缀并访问内网服务,其他网关始终转发到 owner 地址。ServiceEndpoint(gateway, kind, id) 返回此前缀,可直接作为 Raft 成员的 base URL;精确路径允许访问 follower,服务继续验证端到端 HMAC 和复制身份。
  • /healthz 只反映 Gateway 本身可接收请求,不代表 Auth/Meta 已就绪。

网关保留每种权威服务已观察的最高 Epoch/Term。较高 term 的 follower 会阻止继续路由到旧 term 的 leader,租约过期也不会撤销这个记录;gossip 继续传播记录。StatePath 同时保存此记录、地址和 ClusterID,不恢复服务租约;OnPeers 回调只保存成员。完全没有观察过权威服务时仍可使用固定 Upstream 代理;观察过却没有有效 leader 时返回不可用。

服务过期时间保留原始 owner 时间戳,gossip 不会续命。一个 mesh 拒绝混入不同 ClusterID。与新 term 隔离的网关可能仍连接旧地址,因此 Meta/Auth 必须自己用 quorum/read barrier 拒绝失去领导权的请求;网关发现不提供选主或一致性。转发失败不重放写操作,客户端只能对已分类的只读查询重新认证和连接。

跨公网部署可以仅公开 Gateway 地址,内部 Meta/Auth/Data/Compute 只监听私网。每个网关的 Advertise 填其公网入口,其他网关以 Peers/Join 互连;服务向自己的网关注册私网 Endpoint。Data/Compute 从网关学习实际 Advertise,并把固定服务路径作为备用 PublicEndpoints;客户端使用 --data-route proxy 时也可经接入网关的 /nodes 路由流式访问远端 owner,无需暴露 Data 端口。

配置 Key 时,网关之间的应用转发附带有时限的 HMAC,绑定方法、路径、查询、目标网关和有界 hop history;签名不读取 bulk body,原有 RPC/STS 和数据完整性检查继续端到端验证。mesh 管理密钥与内部转发凭据不会进入后端服务。公网保密由部署在网关前的 TLS 入口提供。

可选 Config.Region(CLI cpfs gw --region west,TOML [gateway] region = "west")是网络区域标签。未显式填写 Region 的服务继承所属网关标签,gossip 保留它;同代数、同 term 的等价路由平局优先同区,固定副本始终按 owner。Region 不授予身份或投票权。

Documentation

Overview

Package gateway provides a peer mesh for service discovery and HTTP forwarding. Its leases do not provide metadata consensus or leader election.

Index

Constants

View Source
const (
	ProtocolVersion  = 1
	ManagementPrefix = "/v1/gateway/"
	KeyHeader        = "X-Cpfs-Mesh-Key"
	HopHeader        = "X-Cpfs-Gateway-Hops"
)
View Source
const (
	ForwardTimeHeader      = "X-Cpfs-Forward-Time"
	ForwardSignatureHeader = "X-Cpfs-Forward-Signature"
)
View Source
const ServicePrefix = "/v1/services/"

Variables

This section is empty.

Functions

func Join

func Join(ctx context.Context, gateway, target, key string) error

Join asks gateway A to exchange membership with target B. Both become peers.

func ServiceEndpoint

func ServiceEndpoint(gateway, kind, id string) (string, error)

ServiceEndpoint addresses one physical service through a gateway. Append the existing service path (for example /v1/control) to this base. Exact routes may reach followers for authenticated Raft replication; they grant no authority.

Types

type AuthorityTerm

type AuthorityTerm struct {
	Epoch uint64 `json:"epoch,omitempty"`
	Term  uint64 `json:"term,omitempty"`
}

type Config

type Config struct {
	Advertise, StatePath, Upstream, ClusterID, Key string
	Region                                         string
	Peers                                          []string
	// OnPeers persists an updated peer set before it becomes visible. It runs
	// serially under the gateway lock and must not call back into the gateway.
	// Use either this callback or StatePath, never both.
	OnPeers                      func([]string) error
	Lease, SyncInterval, Timeout time.Duration
	MaxPeers, MaxServices        int
}

type Gateway

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

Gateway owns its anti-entropy loop and HTTP transport. The enclosing HTTP server/listener (including upgraded sockets) remains the caller's property.

func New

func New(cfg Config) (*Gateway, error)

func (*Gateway) Close

func (g *Gateway) Close() error

func (*Gateway) Join

func (g *Gateway) Join(ctx context.Context, target string) error

Join exchanges both peers' membership. Neither gateway becomes the parent.

func (*Gateway) Register

func (g *Gateway) Register(r Registration) (Service, error)

func (*Gateway) Run

func (g *Gateway) Run(ctx context.Context) error

func (*Gateway) ServeHTTP

func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Gateway) State

func (g *Gateway) State() State

func (*Gateway) String

func (g *Gateway) String() string

type Registration

type Registration struct {
	ID        string        `json:"id"`
	Kind      string        `json:"kind"`
	Endpoint  string        `json:"endpoint"`
	ClusterID string        `json:"cluster_id"`
	Role      string        `json:"role,omitempty"`
	Epoch     uint64        `json:"epoch,omitempty"`
	Term      uint64        `json:"term,omitempty"`
	Region    string        `json:"region,omitempty"`
	TTL       time.Duration `json:"ttl,omitempty"`
}

Registration contains a service's current address and authority role. Meta roles and epochs come from its existing authority, never a mesh election.

type Service

type Service struct {
	ID        string    `json:"id"`
	Kind      string    `json:"kind"`
	Endpoint  string    `json:"endpoint"`
	ClusterID string    `json:"cluster_id"`
	Role      string    `json:"role,omitempty"`
	Epoch     uint64    `json:"epoch,omitempty"`
	Term      uint64    `json:"term,omitempty"`
	Region    string    `json:"region,omitempty"`
	Owner     string    `json:"owner"`
	Version   uint64    `json:"version"`
	Expires   time.Time `json:"expires"`
}

Service is an origin-stamped lease. Exchanging it never extends Expires.

func Register

func Register(ctx context.Context, gateway string, registration Registration, key string) (Service, error)

type State

type State struct {
	Version   int       `json:"version"`
	Address   string    `json:"address"`
	ClusterID string    `json:"cluster_id,omitempty"`
	Region    string    `json:"region,omitempty"`
	Peers     []string  `json:"peers"`
	Services  []Service `json:"services"`
	// Authorities remembers observed leadership generations, independently of
	// lease expiry. It suppresses routing to an older leader, not elects one.
	Authorities map[string]AuthorityTerm `json:"authorities,omitempty"`
}

func Discover

func Discover(ctx context.Context, gateway, key string) (State, error)

Jump to

Keyboard shortcuts

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