Documentation
¶
Index ¶
- Constants
- func ActorFromContext(ctx context.Context) (uuid, ip string)
- func Allow(pattern, minRole string)
- func CheckPermission(group, method string) bool
- func CheckPrincipal(p *Principal, method string) bool
- func GetParamAs[T any](req *JsonRpcRequest, name string) (val T, ok bool)
- func GetPositionalParamAs[T any](req *JsonRpcRequest, idx int) (val T, ok bool)
- func IsSensitive(method string) bool
- func ListMethods() []string
- func MarkSensitive(method string)
- func MustRegister(method string, h Handler)
- func NamespaceOf(method string) string
- func NewContextWithMeta(parent context.Context, meta *ContextMeta) context.Context
- func ParseRequest(data []byte) (*JsonRpcRequest, *JsonRpcError)
- func ParseRequests(data []byte) ([]*JsonRpcRequest, *JsonRpcError)
- func Register(method string, h Handler) error
- func RegisterMeta(name string, meta *MethodMeta)
- func RegisterNamespace(namespace, requiredRole string)
- func RegisterWithMeta(method string, h Handler, meta *MethodMeta) error
- func RequiredRole(method string) string
- func Unregister(method string) bool
- type ContextMeta
- type Handler
- type JsonRpcError
- type JsonRpcRequest
- type JsonRpcResponse
- func Call(id any, method string, params any) *JsonRpcResponse
- func CallWithContext(ctx context.Context, id any, method string, params any) *JsonRpcResponse
- func ErrorResponse(id any, code int, msg string, data any) *JsonRpcResponse
- func InternalErrorResponse(id any, err error) *JsonRpcResponse
- func SuccessResponse(id any, result any) *JsonRpcResponse
- type MethodMeta
- type ParamMeta
- type Principal
- type PrincipalType
- type UserInfo
Constants ¶
const ( ParseError = -32700 InvalidRequest = -32600 MethodNotFound = -32601 InvalidParams = -32602 InternalError = -32603 )
预定义错误码 JSON-RPC 2.0 标准
const ( NotFound = -32044 AlreadyExists = -32045 PermissionDenied = -32041 Unauthenticated = -32040 // 未登录/无身份 Cancelled = -32010 // 主动取消 DeadlineExceeded = -32011 // 超时 Aborted = -32021 // 并发冲突/事务中断 OutOfRange = -32022 // 数值/索引越界 Unimplemented = -32050 // 尚未实现 DataLoss = -32052 // 不可恢复的数据丢失 )
Komari 定义错误码
const ( RoleGuest = "guest" RoleClient = "client" RoleAdmin = "admin" )
角色常量。与 transport 中的角色保持一致(guest/client/admin)。
const DefaultNamespace = "common"
DefaultNamespace 是方法名不含 ":" 时归入的命名空间。
const RPC_VERSION = "2.0"
Variables ¶
This section is empty.
Functions ¶
func ActorFromContext ¶
ActorFromContext 从上下文提取审计日志常用的 actor UUID 与来源 IP; 无 meta 时返回空字符串。
func Allow ¶
func Allow(pattern, minRole string)
Allow 声明一条 ACL 规则:匹配 pattern 的方法允许 minRole 及以上等级的角色调用。 同一 pattern 重复声明时覆盖原规则。供插件声明自定义权限。
func CheckPermission ¶
CheckPermission 判定 group 角色是否有权调用 method。
func CheckPrincipal ¶
CheckPrincipal 基于主体的能力集判定是否有权调用 method。 采用集合成员语义(而非线性等级):方法要求某最低角色,主体须在其角色集中持有该角色; guest 为公共基线,任何主体均隐式可访问。 该模型使 agent 与 admin 成为正交主体:admin 不再自动获得 client 能力(反之亦然), 从而堵住"admin 会话冒充 agent 调用 client:* 上报方法"等越权路径。
func GetParamAs ¶
func GetParamAs[T any](req *JsonRpcRequest, name string) (val T, ok bool)
GetParamAs 获取具名参数并尝试转换为类型 T
func GetPositionalParamAs ¶
func GetPositionalParamAs[T any](req *JsonRpcRequest, idx int) (val T, ok bool)
GetPositionalParamAs 获取位置参数 idx 的值为 T
func MarkSensitive ¶
func MarkSensitive(method string)
MarkSensitive 标记某方法为敏感操作。method 为完整方法名(如 "admin:exec")。 重复标记是幂等的。供方法注册处声明。
func NamespaceOf ¶
NamespaceOf 解析方法名的命名空间。"ns:method" 返回 "ns";无 ":" 返回 DefaultNamespace。
func NewContextWithMeta ¶
func NewContextWithMeta(parent context.Context, meta *ContextMeta) context.Context
NewContextWithMeta 将 meta 写入 context
func ParseRequest ¶
func ParseRequest(data []byte) (*JsonRpcRequest, *JsonRpcError)
ParseRequest 解析单个 JSON-RPC 请求。返回请求与错误(解析层面)。
func ParseRequests ¶
func ParseRequests(data []byte) ([]*JsonRpcRequest, *JsonRpcError)
ParseRequests 解析单个或批量 JSON-RPC 请求。返回请求切片与错误(解析层面), 若是批量空数组则返回 InvalidRequest 错误(协议要求)。
func RegisterMeta ¶
func RegisterMeta(name string, meta *MethodMeta)
RegisterMeta 为已注册方法附加/覆盖元数据(Name 字段若为空自动填充)。
func RegisterNamespace ¶
func RegisterNamespace(namespace, requiredRole string)
RegisterNamespace 便捷封装:为整个命名空间声明所需最低角色(等价于 Allow("ns:*", role))。
func RegisterWithMeta ¶
func RegisterWithMeta(method string, h Handler, meta *MethodMeta) error
RegisterWithMeta 同时注册方法与元数据;若注册失败返回错误。
func Unregister ¶
Unregister 注销已注册的方法,并清理其元数据。 保留前缀 "rpc." 的内部方法禁止注销。返回是否存在并被移除。 主要供插件卸载时动态移除其注册的方法。
Types ¶
type ContextMeta ¶
type ContextMeta struct {
// Principal 调用主体(身份 + 能力)。新身份模型的权威来源,由身份识别层统一构建。
// Permission 字段保留用于向后兼容,等价于 Principal.PrimaryRole()。
Principal *Principal
// Permission 当前权限分组 guest/client/admin
Permission string
// User 登录的管理员用户(仅 admin 会话存在)
User *UserInfo
// UserUUID 方便无需解引用就能快速判断
UserUUID string
// ClientToken 来自客户端的私钥 / 鉴权 token(仅 client 链接可能存在)
ClientToken string
// ClientUUID 解析出的客户端 UUID(若 token 合法)
ClientUUID string
// SessionToken 当前管理员会话的 session token(仅 admin 会话存在,用于区分当前会话等场景)
SessionToken string
// RemoteIP 请求来源 IP(可选)
RemoteIP string
// UserAgent 请求 UA(可选)
UserAgent string
TempShareValid bool
}
ContextMeta 保存一次 RPC 调用可用的鉴权/身份元数据。 为了便于扩展,字段保持冗余:既保存结构体,也保存对应 UUID / Token。 未来如需添加字段(如 IP、UserAgent、TraceID 等)直接在此结构体上扩展即可。
func MetaFromContext ¶
func MetaFromContext(ctx context.Context) *ContextMeta
MetaFromContext 读取 meta;不存在返回 nil
type Handler ¶
type Handler func(ctx context.Context, req *JsonRpcRequest) (any, *JsonRpcError)
Handler 方法签名:返回 result (成功) 或 *JsonRpcError (失败)
type JsonRpcError ¶
type JsonRpcError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
JsonRpcError 错误对象 Code 按 JSON-RPC 规范使用 -32768 ~ -32000 的预留范围,其它业务自定义可使用正数或自定义区间。 Message 为简短描述,Data 可携带扩展信息(结构化或字符串)。
func Invoke ¶
func Invoke(method string, params any) (any, *JsonRpcError)
Invoke 便捷调用:构造请求并执行已注册方法,返回 result 或 *JsonRpcError。 不生成 JsonRpcResponse。
@ref Call
func (*JsonRpcError) Error ¶
func (e *JsonRpcError) Error() string
func (*JsonRpcError) Response ¶
func (e *JsonRpcError) Response() *JsonRpcResponse
func (*JsonRpcError) ResponseWithID ¶
func (e *JsonRpcError) ResponseWithID(id any) *JsonRpcResponse
type JsonRpcRequest ¶
type JsonRpcRequest struct {
Version string `json:"jsonrpc"` // 必须 === "2.0"
Method string `json:"method"` // 方法名;以 "rpc." 前缀的为保留内部方法
Params any `json:"params,omitempty"` // 参数(位置数组或命名对象)
ID any `json:"id,omitempty"` // 字符串 / 数值 / null;Notification 时省略
}
JsonRpcRequest 表示 JSON-RPC 2.0 请求(单个或批量中的一个元素) 说明:为了能区分 Notification(无 id),这里将 ID 定义为 any 并打上 omitempty。 你可以通过 req.HasID() 判断是否为普通请求(需要返回)还是通知。
func NewNotification ¶
func NewNotification(method string, params any) *JsonRpcRequest
NewNotification 创建一个 Notification(无 id,不会收到返回)
func NewRequest ¶
func NewRequest(id any, method string, params any) *JsonRpcRequest
NewRequest 创建一个普通请求(带 id)
func (*JsonRpcRequest) BindParams ¶
func (r *JsonRpcRequest) BindParams(target any) error
BindParams 将 Params 绑定到给定结构体指针。 支持:
- object(map) -> 按字段名反序列化(标准 encoding/json 行为,大小写不敏感)
- array([]any) -> 若 target 是结构体指针,按导出字段声明顺序依次填充; 数组更短: 剩余字段保持零值;数组更长: 忽略多余元素。 非结构体指针则退回原逻辑整体反序列化。
- 单一标量 -> 若 target 是结构体指针,则赋值给第一个导出字段;否则整体反序列化。
- 其它类型 -> 直接整体反序列化。
func (*JsonRpcRequest) GetParams ¶
func (r *JsonRpcRequest) GetParams(name string, target *any)
GetParams(兼容旧接口):按名称获取参数(仅 map Object 情况),没有则 target 不变
func (*JsonRpcRequest) HasID ¶
func (r *JsonRpcRequest) HasID() bool
HasID 判断是否包含 id(Notification 没有 id,不需要返回)
func (*JsonRpcRequest) Validate ¶
func (r *JsonRpcRequest) Validate() *JsonRpcError
Validate 校验请求格式合法性(不校验方法是否存在)
type JsonRpcResponse ¶
type JsonRpcResponse struct {
Version string `json:"jsonrpc"`
ID any `json:"id,omitempty"`
Result any `json:"result,omitempty"`
Error *JsonRpcError `json:"error,omitempty"`
}
JsonRpcResponse JSON-RPC 2.0 响应 成功时包含 result,失败时包含 error;二者互斥。 在 Notification 情况下服务器不会发送任何响应。
func Call ¶
func Call(id any, method string, params any) *JsonRpcResponse
Call 执行方法并直接返回完整的 JSON-RPC Response。 适用于对外暴露:始终返回结构(包括错误)。 ctx: 执行上下文;id: 请求 id;method/params: 方法与参数。
func CallWithContext ¶
func ErrorResponse ¶
func ErrorResponse(id any, code int, msg string, data any) *JsonRpcResponse
ErrorResponse 构造失败响应
func InternalErrorResponse ¶
func InternalErrorResponse(id any, err error) *JsonRpcResponse
InternalErrorResponse 统一内部错误
func SuccessResponse ¶
func SuccessResponse(id any, result any) *JsonRpcResponse
SuccessResponse 构造成功响应
type MethodMeta ¶
type MethodMeta struct {
Name string `json:"name"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Params []ParamMeta `json:"params,omitempty"`
Returns string `json:"returns,omitempty"`
Example any `json:"example,omitempty"`
}
MethodMeta 描述方法的帮助信息。
type ParamMeta ¶
type ParamMeta struct {
Name string `json:"name"`
Type string `json:"type,omitempty"`
Required bool `json:"required,omitempty"`
Description string `json:"description,omitempty"`
}
ParamMeta 描述单个参数。
type Principal ¶
type Principal struct {
// Type 主体类型
Type PrincipalType
// UserUUID 用户 UUID(PrincipalUser 时存在)
UserUUID string
// ClientUUID agent 客户端 UUID(PrincipalAgent 时存在)
ClientUUID string
// IsAPIKey 是否为 API Key 调用(快速判定,等价于 Type==PrincipalAPIKey)
IsAPIKey bool
// Roles 角色/能力集。默认由 Type 推导:
// - PrincipalAnonymous → [RoleGuest]
// - PrincipalAgent → [RoleClient]
// - PrincipalUser / PrincipalAPIKey → [RoleAdmin]
// 未来可扩展为多角色(只读 admin / API Key scope 等)。
Roles []string
}
Principal 调用主体,携带身份信息和能力。
func NewAgentPrincipal ¶
NewAgentPrincipal 创建 agent 客户端主体
func NewUserPrincipal ¶
NewUserPrincipal 创建管理员用户主体
func PrincipalFromRole ¶
PrincipalFromRole 按角色构造一个最小主体,用于内部调用(OnInternalRequest)等 仅知道角色、无具体身份信息的场景。Type 按角色合理推断:
guest → Anonymous, client → Agent, admin → User。
注意:此构造不携带 UUID/token,仅用于权限判定与兜底,不应据此做审计 actor 归属。
func (*Principal) PrimaryRole ¶
PrimaryRole 返回主体的主要角色(兼容现有单角色模型)。 多角色场景下返回权限等级最高的那个。
type PrincipalType ¶
type PrincipalType int
PrincipalType 调用主体类型
const ( // PrincipalAnonymous 匿名访客(未认证) PrincipalAnonymous PrincipalType = iota // PrincipalAgent 通过 client token 认证的 agent 客户端 PrincipalAgent // PrincipalUser 通过 session cookie 认证的管理员用户 PrincipalUser // PrincipalAPIKey 通过 API Key 认证的调用方 PrincipalAPIKey )