ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Ory Hydra Metadata API 使用指南:版本查询与健康检查端点全解析

Ory Hydra Metadata API 使用指南:版本查询与健康检查端点全解析 Ory Hydra Metadata API 使用指南版本查询与健康检查端点全解析【免费下载链接】hydraInternet-scale OpenID Certified™ OpenID Connect and OAuth2.1 provider that integrates with your user management through headless APIs. Solve OIDC/OAuth2 user cases over night. Consume as a service on Ory Network or self-host. Trusted by OpenAI and many others for scale and security. Written in Go.项目地址: https://gitcode.com/gh_mirrors/hydra2/hydraOry Hydra 是一个用 Go 编写的开源 OIDC/OAuth2.1 服务提供商官方生成的 Go SDKory/hydra-client-go/v2仓库内位于 internal/httpclient为其公共与管理 API 提供了类型安全的客户端封装。本文以 SDK 文档 MetadataAPI.md 为主体深入讲解 Metadata API 的GetVersion、IsAlive、IsReady三个端点从 HTTP 语义、Go 客户端调用方式、响应模型到服务端 oryx/healthx/handler.go 的底层实现与路由注册逻辑帮助你掌握用 Ory Hydra 做版本管理与存活/就绪探测的完整方案。Metadata API 概览Metadata API 是 Ory Hydra 中一组无需鉴权No authorization required的元信息端点全部通过 HTTP GET 访问。根据 MetadataAPI.md所有 URI 均相对于http://localhost端点总览如下方法HTTP 请求描述GetVersionGET /version返回正在运行的软件版本Return Running Software VersionIsAliveGET /health/alive检查 HTTP 服务器状态Check HTTP Server StatusIsReadyGET /health/ready检查 HTTP 服务器与数据库状态Check HTTP Server and Database Status这三个端点共同构成运维探测的三件套/version用于确认部署的版本号/health/alive用于判断进程是否在接收 HTTP 请求/health/ready用于判断实例及其依赖如数据库是否已就绪。它们既可以直接用curl访问也可以通过 SDK 的MetadataAPI服务对象在 Go 程序中调用。服务端的路径常量定义在 oryx/healthx/handler.goconst ( // AliveCheckPath is the path where information about the life state of the instance is provided. AliveCheckPath /health/alive // ReadyCheckPath is the path where information about the ready state of the instance is provided. ReadyCheckPath /health/ready // VersionPath is the path where information about the software version of the instance is provided. VersionPath /version )环境准备与客户端初始化在调用 Metadata API 之前需要先创建 API 客户端。所有示例使用同一个configuration与apiClientimport openapiclient github.com/ory/hydra-client-go/v2 configuration : openapiclient.NewConfiguration() apiClient : openapiclient.NewAPIClient(configuration)NewConfiguration()会使用默认服务器地址http://localhost与文档中All URIs are relative tohttp://localhost一致。如果你的 Ory Hydra 实例运行在其他地址例如https://hydra.example.com或本地https://127.0.0.1:4444需要修改configuration.Servers或 Host 配置。注意Ory Hydra 默认的公共端口是4444管理端口是4445例如 conformance 测试就使用https://127.0.0.1:4444/health/ready进行就绪探测见 test/conformance/run_test.go。GetVersion查询正在运行的软件版本接口语义GetVersion对应GET /version返回 Ory Hydra 实例的版本号。根据 api_metadata.go 中的注释该端点返回 Ory Hydra 的版本如果服务启用了 TLS 边缘终结TLS Edge Termination此端点不要求设置X-Forwarded-Proto头如果以多节点方式运行该服务版本号只反映单个实例绝不代表集群整体状态。Go 客户端调用示例SDK 采用构造请求结构体 Execute()的 Builder 模式。GetVersion(ctx)返回ApiGetVersionRequest调用.Execute()后返回三元组(*GetVersion200Response, *http.Response, error)package main import ( context fmt os openapiclient github.com/ory/hydra-client-go/v2 ) func main() { configuration : openapiclient.NewConfiguration() apiClient : openapiclient.NewAPIClient(configuration) resp, r, err : apiClient.MetadataAPI.GetVersion(context.Background()).Execute() if err ! nil { fmt.Fprintf(os.Stderr, Error when calling MetadataAPI.GetVersion: %v\n, err) fmt.Fprintf(os.Stderr, Full HTTP response: %v\n, r) } // response from GetVersion: GetVersion200Response fmt.Fprintf(os.Stdout, Response from MetadataAPI.GetVersion: %v\n, resp) }请求参数与返回模型该端点不需要任何路径参数也没有可选的查询/表单参数。请求结构体ApiGetVersionRequest仅由ctx与ApiService组成见 api_metadata.go其他参数均通过指向apiGetVersionRequest结构体的 Builder 模式传递当前为空。返回类型为GetVersion200Response其模型定义在 model_get_version_200_response.go核心字段名称类型描述必填Version*stringOry Hydra 的版本号可选optional请求头信息Content-Type未定义无需设置Acceptapplication/json服务端实现在 oryx/healthx/handler.go将VersionString直接写入 JSON 响应func (h *Handler) Version() http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { h.H.Write(rw, r, swaggerVersion{ Version: h.VersionString, }) }) }典型响应示例{version: v2.x.x}VersionString由构造器NewHandler(h, version, readyChecks)注入版本号通常遵循语义化版本Semantic Versioning规范。IsAlive检查 HTTP 服务器存活状态接口语义IsAlive对应GET /health/alive。当 Ory Hydra 正在接受传入的 HTTP 请求时该端点返回 HTTP 200。根据 api_metadata.go 中的注释当前该状态不包含数据库连接是否正常的检查——它只验证 HTTP 层如果服务启用了 TLS 边缘终结此端点不要求设置X-Forwarded-Proto头多节点部署时健康状态只反映单个实例不反映集群状态。Go 客户端调用示例package main import ( context fmt os openapiclient github.com/ory/hydra-client-go/v2 ) func main() { configuration : openapiclient.NewConfiguration() apiClient : openapiclient.NewAPIClient(configuration) resp, r, err : apiClient.MetadataAPI.IsAlive(context.Background()).Execute() if err ! nil { fmt.Fprintf(os.Stderr, Error when calling MetadataAPI.IsAlive: %v\n, err) fmt.Fprintf(os.Stderr, Full HTTP response: %v\n, r) } // response from IsAlive: HealthStatus fmt.Fprintf(os.Stdout, Response from MetadataAPI.IsAlive: %v\n, resp) }请求参数与返回模型该端点同样不需要任何参数。返回类型为HealthStatus模型定义在 model_health_status.go名称类型描述必填Status*string状态值恒为ok可选optional请求头Content-Type未定义Acceptapplication/json服务端实现 oryx/healthx/handler.go 非常直接——不做任何检查恒定返回200 {status:ok}func (h *Handler) Alive() http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { h.H.Write(rw, r, swaggerHealthStatus{ Status: ok, }) }) }IsReady检查服务器与数据库就绪状态接口语义IsReady对应GET /health/ready。当 Ory Hydra 正在运行且环境依赖例如数据库也响应正常时该端点返回 HTTP 200。根据 api_metadata.go 的注释它同样具备单实例语义与TLS 边缘终结友好两个特性。这是三个端点中唯一可能返回非 200 状态的端点当任一就绪检查失败时返回HTTP 503 Service Unavailable。Go 客户端调用示例package main import ( context fmt os openapiclient github.com/ory/hydra-client-go/v2 ) func main() { configuration : openapiclient.NewConfiguration() apiClient : openapiclient.NewAPIClient(configuration) resp, r, err : apiClient.MetadataAPI.IsReady(context.Background()).Execute() if err ! nil { fmt.Fprintf(os.Stderr, Error when calling MetadataAPI.IsReady: %v\n, err) fmt.Fprintf(os.Stderr, Full HTTP response: %v\n, r) } // response from IsReady: IsReady200Response fmt.Fprintf(os.Stdout, Response from MetadataAPI.IsReady: %v\n, resp) }请求参数与返回模型该端点不需要任何参数。成功时返回类型为IsReady200Response模型见 model_is_ready_200_response.go名称类型描述必填Status*string恒为ok可选optional失败503时返回类型为IsReady503Response模型见 model_is_ready_503_response.go名称类型描述必填Errorsmap[string]string导致未就绪状态的错误列表可选optional请求头Content-Type未定义Accept为application/json。客户端在收到 503 时会自动把IsReady503Response解码进GenericOpenAPIError.model你可以在错误处理中通过类型断言取出错误明细见 api_metadata.go。服务端就绪检查机制ReadyCheckers 与错误脱敏服务端实现体现了可插拔就绪检查的设计oryx/healthx/handler.gofunc (h *Handler) Ready(shareErrors bool) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { var notReady swaggerNotReadyStatus{ Errors: map[string]string{}, } for n, c : range h.ReadyChecks { if err : c(r); err ! nil { if shareErrors { notReady.Errors[n] err.Error() } else { notReady.Errors[n] error may contain sensitive information and was obfuscated } } } if len(notReady.Errors) 0 { h.H.WriteErrorCode(rw, r, http.StatusServiceUnavailable, notReady) return } h.H.Write(rw, r, swaggerHealthStatus{ Status: ok, }) }) }关键点解读ReadyCheckers是一个map[string]ReadyChecker每个检查项的名字作为 map 的 key值是一个func(r *http.Request) error类型的函数handler.go。NoopReadyChecker()代表恒为就绪的空检查handler.go。错误脱敏开关shareErrors为true时503 响应的Errors中暴露每个检查项的真实错误信息为false时所有错误统一替换为error may contain sensitive information and was obfuscated避免把数据库连接串等敏感细节泄露给公网调用方。只要存在任何一个失败检查项就整体返回503全部通过才返回200 {status:ok}。公共与管理路由的差异配置shareErrors参数在路由注册时被设定见 driver/registry_sql.gofunc (m *RegistrySQL) RegisterPublicRoutes(ctx context.Context, public *httprouterx.RouterPublic) { m.HealthHandler().SetHealthRoutes(public, false, healthx.WithMiddleware(m.addPublicCORSOnHandler(ctx))) ... } func (m *RegistrySQL) RegisterAdminRoutes(admin *httprouterx.RouterAdmin) { m.HealthHandler().SetHealthRoutes(admin, true) m.HealthHandler().SetVersionRoutes(admin) ... }从源码结构可以看出公共接口上的/health/alive、/health/ready以shareErrorsfalse注册对外脱敏且可选挂 CORS 中间件管理接口上的健康检查以shareErrorstrue注册返回真实错误/version只挂在管理路由上。这意味着如果想知道数据库为何未就绪应通过管理端口默认 4445访问/health/ready获取详细的Errors明细。实战curl 调用与监控场景除了 SDK这三个端点可直接用 curl 探测# 查询版本管理端口 4445 curl -s http://localhost:4445/version # 存活检查公共端口 4444 curl -s http://localhost:4444/health/alive # 就绪检查公共端口 4444错误已脱敏 curl -s http://localhost:4444/health/ready # 就绪检查管理端口 4445返回真实错误明细 curl -s http://localhost:4445/health/ready典型输出// GET /version {version:v2.3.0} // GET /health/alive {status:ok} // GET /health/ready就绪时 {status:ok} // GET /health/ready未就绪时管理端口返回详细错误 {errors:{database:dial tcp 127.0.0.1:5432: connect: connection refused}}在真实部署中这三个端点最常见的用法是Kubernetes livenessProbe 与 readinessProbe分别指向/health/alive与/health/ready。liveness 探针只关心进程是否活着readiness 探针则确保数据库依赖正常后才把流量切进来。服务注册与负载均衡注册中心或网关通过/health/ready判断实例是否可以从实例池中摘除。多实例运维记住三个端点都只反映单个实例的状态版本与健康均不指代集群多节点部署时应分别对每个 Pod/实例做探测。常见问题与注意事项为什么/health/ready在数据库挂掉后仍返回 200不会。就绪检查会遍历所有ReadyCheckers其中包含数据库连通性检查任一失败即返回 503。而/health/alive才是不管数据库只问 HTTP 层的端点两者语义不要混用。为什么公共端点的 503 错误信息看不懂因为公共路由以shareErrorsfalse注册所有错误被统一替换为error may contain sensitive information and was obfuscated这是刻意的安全设计需要真实错误请走管理端口。需要鉴权吗不需要。文档明确标注三个端点均 No authorization required因此适合作为探活端点但也意味着不要让它们暴露在不可信网络中。Content-Type / Accept 头怎么设请求无需 Content-Type响应为application/json/health/alive与/health/ready在服务端还支持text/plain见 handler.go 的 swagger 注释。TLS 边缘终结场景如果服务启用了 TLS Edge Termination这三个端点均不要求设置X-Forwarded-Proto头可直接访问。SDK 代码从哪来MetadataAPIService由 OpenAPI Generator 基于 spec/swagger.json 自动生成见 api_metadata.go 的文件头注释服务端对应的 swagger 路由注释定义在 health/doc.go 与 handler.go 中两者一一对应可作为客户端方法 ↔ 服务端路由的对照表。小结Metadata API 是 Ory Hydra 运维观测的最小但关键的接口集合GetVersion提供单实例版本号IsAlive提供 HTTP 层存活信号IsReady提供包含依赖数据库在内的就绪信号并且通过shareErrors区分公共/管理接口的报错粒度。结合 MetadataAPI.md 的 SDK 用法与 oryx/healthx/handler.go 的服务端实现你可以快速将版本查询与健康探测接入监控系统、Kubernetes 探针或自定义运维工具为 Ory Hydra 的规模化部署提供可靠的可观测性基础。【免费下载链接】hydraInternet-scale OpenID Certified™ OpenID Connect and OAuth2.1 provider that integrates with your user management through headless APIs. Solve OIDC/OAuth2 user cases over night. Consume as a service on Ory Network or self-host. Trusted by OpenAI and many others for scale and security. Written in Go.项目地址: https://gitcode.com/gh_mirrors/hydra2/hydra创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表