cluster

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: 28 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 直接提供 WebSocket RPC、角色身份、HMAC/STS、节点 Registry 和持久代数/撤销门禁。调用方按职责直接导入所需子包;父包不导入子包,也不转发其 API。

公开导入路径 包名 职责
github.com/lfhy/compactfs/fs/cluster/auth auth 独立账号库、资源策略与精确签票
github.com/lfhy/compactfs/fs/cluster/authority authority Meta/Auth共用应用WAL、确定Apply、quorum门禁与共识适配
github.com/lfhy/compactfs/fs/cluster/placement placement RF3位置索引、对象发布、修复和再均衡
github.com/lfhy/compactfs/fs/cluster/files files 远程core.Access、文件会话与传输计划
github.com/lfhy/compactfs/fs/cluster/backup backup 协调镜像、manifest及离线恢复
github.com/lfhy/compactfs/fs/cluster/data data 不可变对象HTTP流、完整性与签名回执
github.com/lfhy/compactfs/fs/cluster/gateway gateway 对等发现、服务租约与HTTP/WS转发

Meta 和 Auth 各自组装独立共识组。authority 持有应用日志,通用加权协议与Raft WAL由独立的 utils/raft 拥有;fs/replica 适配本地 fs/meta 事务引擎。文件语义与元数据事务、对象位置与对象传输保持独立职责。

部署入口见加权Raft部署,开发约束见本层指南。上述包路径调整保留网络字段和持久schema版本;Auth新编码的Gob类型描述随包名变化,旧payload仍按原字节校验并重放,不能据此宣称所有编码字节相同。

Documentation

Overview

Package cluster provides bounded control RPC and scoped credentials for a trusted storage network. It does not supply metadata consensus or replication.

Index

Constants

View Source
const (
	ProtocolVersion        = 1
	NamespaceTokenVersion  = 2
	CredentialTokenVersion = 3
	HeaderAccessKey        = "X-Cpfs-Access-Key"
	HeaderSecurityToken    = "X-Cpfs-Security-Token"
	HeaderSignature        = "X-Cpfs-Signature"
	HeaderRequestID        = "X-Cpfs-Request-Id"
	HeaderOperation        = "X-Cpfs-Operation"
	HeaderObjectID         = "X-Cpfs-Object-Id"
	HeaderObjectHash       = "X-Cpfs-Object-Hash"
	HeaderObjectSize       = "X-Cpfs-Object-Size"
	HeaderTargetNode       = "X-Cpfs-Target-Node"
)
View Source
const (
	CodeInvalidArgument   = "invalid_argument"
	CodeUnauthenticated   = "unauthenticated"
	CodePermissionDenied  = "permission_denied"
	CodeNotFound          = "not_found"
	CodeAlreadyExists     = "already_exists"
	CodeConflict          = "conflict"
	CodeResourceExhausted = "resource_exhausted"
	CodeCanceled          = "canceled"
	CodeDeadlineExceeded  = "deadline_exceeded"
	CodeUnavailable       = "unavailable"
	CodeInternal          = "internal"
)
View Source
const HeaderGateSignature = "X-Cpfs-Gate-Signature"

Variables

This section is empty.

Functions

func GateSignature

func GateSignature(key string, body []byte) string

func InstallAuthorityGate

func InstallAuthorityGate(ctx context.Context, client *http.Client, endpoint string, keys NodeKeys, next AuthorityGateState) error

func InstallRevocations

func InstallRevocations(ctx context.Context, client *http.Client, endpoint string, keys NodeKeys, state AuthorityGateState, entries []CredentialRevocation) error

InstallRevocations first reads an authenticated cursor, then installs only newer events. Success means the target persisted and acknowledged the table.

func NewSecret

func NewSecret() (string, error)

NewSecret returns a high-entropy printable key suitable for an offline identity file. It does not register or authorize a principal.

func SignReceipt

func SignReceipt(key string, payload []byte) string

SignReceipt authenticates a service-owned receipt payload; it deliberately signs the exact bytes so callers need not assume canonical map JSON.

func SignRequest

func SignRequest(req *http.Request, credentials Credentials, scope RequestScope) error

func SignResponseProof

func SignResponseProof(key string, payload []byte) string

SignResponseProof authenticates a bounded response description, excluding body bytes. Keep its purpose separate from durable storage receipts.

func VerifyGateSignature

func VerifyGateSignature(key string, body []byte, signature string) error

func VerifyReceipt

func VerifyReceipt(key string, payload []byte, signature string) error

func VerifyResponseProof

func VerifyResponseProof(key string, payload []byte, signature string) error

Types

type Authenticator

type Authenticator func(accessKeyID, securityToken string) (Identity, error)

type Authority

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

func NewAuthority

func NewAuthority(cfg AuthorityConfig) (*Authority, error)

func (*Authority) Issue

func (a *Authority) Issue(principal string, grant Grant) (Credentials, error)

func (*Authority) VerifyCredentials

func (a *Authority) VerifyCredentials(accessKeyID, token, targetNodeID string) (Claims, string, error)

VerifyCredentials authenticates token scope for a node and reconstructs its temporary signing secret. It never trusts the caller-provided secret field.

func (*Authority) VerifyRequest

func (a *Authority) VerifyRequest(req *http.Request, targetNodeID, operation string, object ObjectScope) (VerifiedRequest, error)

VerifyRequest validates headers against an independently resolved operation and exact object. The caller must still validate full body length/XXH3 before publishing or delivering bytes; this MAC intentionally does not cover body.

type AuthorityConfig

type AuthorityConfig struct {
	ClusterID   string
	Incarnation string
	AuthEpoch   uint64
	Nodes       map[string]NodeKeys
	MaxTTL      time.Duration
	MaxObjects  int
}

type AuthorityGateState

type AuthorityGateState struct {
	Version     int    `json:"version"`
	ClusterID   string `json:"cluster_id"`
	NodeID      string `json:"node_id"`
	Epoch       uint64 `json:"epoch"`
	Incarnation string `json:"incarnation"`
}

type Claims

type Claims struct {
	Version     int    `json:"version"`
	ClusterID   string `json:"cluster_id"`
	Incarnation string `json:"incarnation"`
	AuthEpoch   uint64 `json:"auth_epoch"`
	Principal   string `json:"principal"`
	AccessKeyID string `json:"access_key_id"`
	Grant       Grant  `json:"grant"`
}

Claims are authenticated by the token MAC and checked locally by the target.

type Config

type Config struct {
	Version                int                 `json:"version"`
	Role                   string              `json:"role"`
	Region                 string              `json:"region,omitempty"`
	ClusterID              string              `json:"cluster_id"`
	Incarnation            string              `json:"incarnation"`
	MetaNodeID             string              `json:"meta_node_id"`
	MetaServer             string              `json:"meta_server"`
	MetaServers            []string            `json:"meta_servers,omitempty"`
	Consensus              *ConsensusConfig    `json:"consensus,omitempty"`
	NodeID                 string              `json:"node_id,omitempty"`
	AccessKeyID            string              `json:"access_key_id,omitempty"`
	SecretAccessKey        string              `json:"secret_access_key,omitempty"`
	AuthEpoch              uint64              `json:"auth_epoch,omitempty"`
	Identities             map[string]Identity `json:"identities,omitempty"`
	NodeKeys               map[string]NodeKeys `json:"node_keys,omitempty"`
	OwnKeys                *NodeKeys           `json:"own_keys,omitempty"`
	ReplicaID              string              `json:"replica_id,omitempty"`
	PeerReplicaID          string              `json:"peer_replica_id,omitempty"`
	PeerServer             string              `json:"peer_server,omitempty"`
	AuthorityRole          string              `json:"authority_role,omitempty"`
	ReplicaAccessKeyID     string              `json:"replica_access_key_id,omitempty"`
	ReplicaSecretAccessKey string              `json:"replica_secret_access_key,omitempty"`
	DataNodeIDs            []string            `json:"data_node_ids,omitempty"`
	MultiUser              bool                `json:"multi_user,omitempty"`
	Namespaces             map[string]string   `json:"namespaces,omitempty"`
	NamespaceID            string              `json:"namespace_id,omitempty"`
}

Config is an offline role-scoped identity file. Client files contain only one client identity; data files contain only their own identity and node keys. Meta and standalone Auth role files own identity and node-key catalogs.

func LoadConfig

func LoadConfig(path string) (Config, error)

func (Config) Authority

func (c Config) Authority() (*Authority, error)

func (Config) AuthorizeGrant

func (c Config) AuthorizeGrant(origin string, grant Grant) (Identity, error)

AuthorizeGrant resolves an originating offline AK and checks its namespace and role. Multi-user clients must use AKs; only unique Meta service IDs keep the internal compatibility spelling. Meta still owns object/volume checks.

func (Config) HasNamespaceID

func (c Config) HasNamespaceID(id string) bool

func (Config) NamespaceIDs

func (c Config) NamespaceIDs() []string

NamespaceIDs returns a stable catalog view, always including the default.

func (Config) RPCConfig

func (c Config) RPCConfig() RPCClientConfig

func (Config) ResolveNamespace

func (c Config) ResolveNamespace(name string) (string, error)

func (Config) Validate

func (c Config) Validate() error

type ConsensusConfig

type ConsensusConfig struct {
	Version       int               `json:"version"`
	GroupID       string            `json:"group_id"`
	Generation    uint64            `json:"generation"`
	Members       []ConsensusMember `json:"members"`
	BootstrapFile string            `json:"bootstrap_file,omitempty"`
}

ConsensusConfig is immutable for the lifetime of a weighted Raft group. Discovery supplies routes; this explicit membership supplies voting power.

type ConsensusMember

type ConsensusMember struct {
	ID       string `json:"id"`
	Endpoint string `json:"endpoint"`
	Region   string `json:"region,omitempty"`
	Weight   uint64 `json:"weight"`
	Priority uint32 `json:"priority"`
}

type CredentialRevocation

type CredentialRevocation struct {
	Sequence uint64 `json:"sequence"`
	AK       string `json:"ak"`
	Revision uint64 `json:"revision"`
	Disabled bool   `json:"disabled"`
}

CredentialRevocation is a monotonically advancing minimum accepted revision. Disabled entries are retained as tombstones, including after key deletion.

type Credentials

type Credentials struct {
	AccessKeyID     string    `json:"access_key_id"`
	SecretAccessKey string    `json:"secret_access_key"`
	SecurityToken   string    `json:"security_token"`
	Expiration      time.Time `json:"expiration"`
}

type Grant

type Grant struct {
	TargetNodeID       string        `json:"target_node_id"`
	StorageIncarnation string        `json:"storage_incarnation,omitempty"`
	Operation          string        `json:"operation"`
	VolumeID           string        `json:"volume_id,omitempty"`
	NamespaceID        string        `json:"namespace_id,omitempty"`
	OriginAccessKeyID  string        `json:"origin_access_key_id,omitempty"`
	CredentialRevision uint64        `json:"credential_revision,omitempty"`
	PlanID             string        `json:"plan_id"`
	UploadID           string        `json:"upload_id,omitempty"`
	AttemptID          string        `json:"attempt_id,omitempty"`
	Objects            []ObjectScope `json:"objects"`
	Expires            time.Time     `json:"expires"`
}

Grant must originate from the metadata authority after permission and layout checks. Issuing credentials does not itself protect objects from garbage collection or publish a file version.

type Identity

type Identity struct {
	Principal       string    `json:"principal"`
	SecretAccessKey string    `json:"secret_access_key"`
	Roles           []string  `json:"roles"`
	Expires         time.Time `json:"expires,omitempty"`
	NamespaceID     string    `json:"namespace_id,omitempty"`
	Revision        uint64    `json:"revision,omitempty"`
}

Identity is an approved offline principal. Expires is optional for long-term identities and required by callers returning temporary identities.

type Issuer

type Issuer func(context.Context, string, Grant) (Credentials, error)

Credentials are short-lived credentials for exactly one target node and bounded grant. SecretAccessKey must never be logged or sent to a data server. The trusted-network control response carries it to the caller in plaintext. Issuer signs a metadata-approved grant, locally or through an Auth service. The caller retains layout, version and permission authority.

type NodeKeys

type NodeKeys struct {
	TokenKey   string `json:"token_key"`
	SecretKey  string `json:"secret_key"`
	ReceiptKey string `json:"receipt_key"`
}

NodeKeys are separate offline keys for one node. A node knows only its own keys; the issuing authority knows the corresponding copies. ReceiptKey is exposed for durable-receipt users and is never used to issue credentials.

type NodeRegistration

type NodeRegistration struct {
	NodeID               string    `json:"node_id"`
	Region               string    `json:"region,omitempty"`
	StorageIncarnation   string    `json:"storage_incarnation"`
	Endpoints            []string  `json:"endpoints"`
	PublicEndpoints      []string  `json:"public_endpoints,omitempty"`
	Capabilities         []string  `json:"capabilities,omitempty"`
	CapacityBytes        uint64    `json:"capacity_bytes,omitempty"`
	UsedBytes            uint64    `json:"used_bytes,omitempty"`
	Weight               float64   `json:"weight,omitempty"`
	Draining             bool      `json:"draining,omitempty"`
	Expires              time.Time `json:"expires"`
	AuthorityEpoch       uint64    `json:"authority_epoch,omitempty"`
	AuthorityIncarnation string    `json:"authority_incarnation,omitempty"`
}

NodeRegistration is an ephemeral lease, not a durable replica record. An expired node is excluded from placement; existing replica identities remain in the storage index until an explicit repair changes them.

type ObjectScope

type ObjectScope struct {
	ID   string `json:"id"`
	Size int64  `json:"size"`
	Hash string `json:"hash"`
}

ObjectScope authorizes one exact immutable object. Hash is XXH3-128, encoded as 32 lowercase hexadecimal characters; it is not cryptographic protection.

type PersistentGate

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

PersistentGate owns its small durable epoch record and dynamic credential verifier. Node keys remain offline; changing authority epochs never exports them to clients or replaces storage incarnation identity.

func OpenPersistentGate

func OpenPersistentGate(path string, cfg Config) (*PersistentGate, error)

func (*PersistentGate) Authority

func (g *PersistentGate) Authority() *Authority

func (*PersistentGate) Guard

func (g *PersistentGate) Guard(ctx context.Context, fn func() error) error

Guard orders a destructive operation before an epoch change. The callback may call Authority/State; it must not recursively update this gate.

func (*PersistentGate) ServeHTTP

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

func (*PersistentGate) State

func (*PersistentGate) Update

func (g *PersistentGate) Update(next AuthorityGateState) error

type Principal

type Principal struct {
	ID          string
	AccessKeyID string
	Roles       []string
	NamespaceID string
	Revision    uint64
}

type RPCClient

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

RPCClient owns its WebSocket and background loops. It does not reconnect or retry operations: a failed call may already have committed at the server.

func DialRPC

func DialRPC(ctx context.Context, endpoint string, cfg RPCClientConfig) (*RPCClient, error)

func (*RPCClient) Call

func (c *RPCClient) Call(ctx context.Context, method string, args, result any) error

func (*RPCClient) Close

func (c *RPCClient) Close() error

func (*RPCClient) Done

func (c *RPCClient) Done() <-chan struct{}

type RPCClientConfig

type RPCClientConfig struct {
	ClusterID        string
	NodeID           string // Empty accepts the authenticated server's node identity.
	AccessKeyID      string
	SecretAccessKey  string
	SecurityToken    string
	HTTPClient       *http.Client
	MaxMessageBytes  int64
	MaxInflight      int
	WriteQueue       int
	HandshakeTimeout time.Duration
	WriteTimeout     time.Duration
	PingInterval     time.Duration
}

type RPCError

type RPCError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

RPCError is a machine-readable operation error. A transport failure does not prove whether an operation committed; callers retain their logical request ID.

func Error

func Error(code, message string) *RPCError

func (*RPCError) Error

func (e *RPCError) Error() string

type RPCHandler

type RPCHandler func(context.Context, Principal, string, json.RawMessage) (any, error)

type RPCServer

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

RPCServer owns upgraded connections, not the enclosing HTTP server/listener. Its handler must honor context cancellation so Close can drain it.

func NewRPCServer

func NewRPCServer(cfg RPCServerConfig) (*RPCServer, error)

func (*RPCServer) Close

func (s *RPCServer) Close(ctx context.Context) error

func (*RPCServer) ServeHTTP

func (s *RPCServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

type RPCServerConfig

type RPCServerConfig struct {
	ClusterID        string
	NodeID           string
	Keys             map[string]Identity
	Authenticate     Authenticator
	Handler          RPCHandler
	MaxMessageBytes  int64
	MaxInflight      int
	MaxConnections   int
	WriteQueue       int
	HandshakeTimeout time.Duration
	WriteTimeout     time.Duration
	MaxCallDuration  time.Duration
	PingInterval     time.Duration
}

type Registry

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

func NewRegistry

func NewRegistry(ttl time.Duration) (*Registry, error)

func (*Registry) Handle

func (r *Registry) Handle(_ context.Context, p Principal, method string, raw json.RawMessage) (any, error)

Handle accepts node RPCs only from the offline identity bound to that node. Clients receive approved endpoints in metadata plans instead of using this registration API as a source of authority.

func (*Registry) Lookup

func (r *Registry) Lookup(nodeID string) (NodeRegistration, bool)

func (*Registry) Nodes

func (r *Registry) Nodes() []NodeRegistration

func (*Registry) WaitNodes

func (r *Registry) WaitNodes(ctx context.Context, count int) error

type RequestScope

type RequestScope struct {
	TargetNodeID string
	Operation    string
	Object       ObjectScope
	RequestID    string
}

RequestScope contains logical signed fields. URL/Host may change when a gateway forwards a request; the receiving service compares these fields with the resolved route and object rather than trusting them as routing input.

type RevocationGate

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

RevocationGate owns an in-memory admission table backed by a transactional local database. No disk or network lookup occurs on the data hot path.

func OpenRevocationGate

func OpenRevocationGate(path string, gate *PersistentGate) (*RevocationGate, error)

func (*RevocationGate) Check

func (g *RevocationGate) Check(grant Grant) error

func (*RevocationGate) Guard

func (g *RevocationGate) Guard(ctx context.Context, fn func() error) error

func (*RevocationGate) Sequence

func (g *RevocationGate) Sequence() (uint64, error)

func (*RevocationGate) ServeHTTP

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

func (*RevocationGate) Update

func (g *RevocationGate) Update(u RevocationUpdate) error

type RevocationUpdate

type RevocationUpdate struct {
	Authority AuthorityGateState     `json:"authority"`
	Since     uint64                 `json:"since"`
	Entries   []CredentialRevocation `json:"entries"`
}

type VerifiedRequest

type VerifiedRequest struct {
	Claims Claims
	Scope  RequestScope
}

Directories

Path Synopsis
Package auth hosts offline identities and signs metadata-approved object grants without owning namespace, placement or a metadata write lease.
Package auth hosts offline identities and signs metadata-approved object grants without owning namespace, placement or a metadata write lease.
Package authority supplies an ordered application authority journal and fixed-membership weighted Raft consensus for metadata and auth state machines.
Package authority supplies an ordered application authority journal and fixed-membership weighted Raft consensus for metadata and auth state machines.
Package backup publishes coordinated authority, namespace and placement checkpoints to an independent backend and restores them only while offline.
Package backup publishes coordinated authority, namespace and placement checkpoints to an independent backend and restores them only while offline.
Package data implements bounded immutable-object HTTP transfers.
Package data implements bounded immutable-object HTTP transfers.
Package files exposes authoritative namespace cores over WebSocket control RPC and bounded HTTP file transfers, with an injected metadata authority gate.
Package files exposes authoritative namespace cores over WebSocket control RPC and bounded HTTP file transfers, with an injected metadata authority gate.
Package gateway provides a peer mesh for service discovery and HTTP forwarding.
Package gateway provides a peer mesh for service discovery and HTTP forwarding.
Package placement publishes opaque backend objects to three Data nodes.
Package placement publishes opaque backend objects to three Data nodes.

Jump to

Keyboard shortcuts

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