Documentation
¶
Index ¶
- Constants
- Variables
- func ErrorIsNotFound(err error) bool
- func FormatNamespaceDisplay(namespace string) string
- func SubmitJob[T any](ctx context.Context, s *Service, job workerpool.Job[T]) error
- func ToContext(ctx context.Context, service *Service) context.Context
- type Checker
- type CheckerFunc
- type HealthCheckResult
- type HealthResponse
- type NamedChecker
- type OPLSpec
- type Option
- func WithBackgroundConsumer(deque func(_ context.Context) error) Option
- func WithCache(name string, rawCache cache.RawCache) Option
- func WithCacheManager() Option
- func WithConfig(cfg any) Option
- func WithDatastore(opts ...pool.Option) Option
- func WithDatastoreConnection(postgresqlConnection string, readOnly bool) Option
- func WithDatastoreConnectionWithName(name string, postgresqlConnection string, readOnly bool, opts ...pool.Option) Option
- func WithDatastoreConnectionWithOptions(name string, opts ...pool.Option) Option
- func WithDatastoreManager() Option
- func WithDebugEndpoints() Option
- func WithDebugEndpointsAt(basePath string) Option
- func WithDriver(driver server.Driver) Option
- func WithEnvironment(environment string) Option
- func WithHTTPClient(opts ...client.HTTPOption) Option
- func WithHTTPHandler(h http.Handler) Option
- func WithHTTPMiddleware(middleware ...func(http.Handler) http.Handler) Option
- func WithHTTPRequestTimeout(timeout time.Duration) Option
- func WithHealthCheckPath(path string) Option
- func WithInMemoryCache(name string) Option
- func WithLogger(opts ...util.Option) Option
- func WithName(name string) Option
- func WithOPL(namespace string, data []byte) Option
- func WithOpenAPIBasePath(path string) Option
- func WithOpenAPISpec(name, filename string, content []byte) Option
- func WithOpenAPISpecsFromFS(f fs.FS, dir string) Option
- func WithPermissionRegistration(sd protoreflect.ServiceDescriptor) Option
- func WithPlugin(name string, opt Option) Option
- func WithRegisterEvents(evt ...events.EventI) Option
- func WithRegisterPublisher(reference string, queueURL string) Option
- func WithRegisterSubscriber(reference string, queueURL string, handlers ...queue.SubscribeWorker) Option
- func WithTelemetry(opts ...telemetry.Option) Option
- func WithTenancyProvider(prov tenancy.Provider) Option
- func WithTranslation(translationsFolder string, languages ...string) Option
- func WithVersion(version string) Option
- func WithWorkerPoolOptions(options ...workerpool.Option) Option
- type RouteInfo
- type RouteLister
- type RouteRegistry
- func (r *RouteRegistry) Handle(pattern string, handler http.Handler)
- func (r *RouteRegistry) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
- func (r *RouteRegistry) HandleRoute(method, pattern, name string, handler func(http.ResponseWriter, *http.Request))
- func (r *RouteRegistry) Routes() []RouteInfo
- func (r *RouteRegistry) ServeHTTP(w http.ResponseWriter, req *http.Request)
- type Service
- func (s *Service) AddCleanupMethod(f func(ctx context.Context))
- func (s *Service) AddHealthCheck(checker Checker)
- func (s *Service) AddPreStartMethod(f func(ctx context.Context, s *Service))
- func (s *Service) AddPublisherStartup(f func(ctx context.Context, s *Service))
- func (s *Service) AddStartupError(err error)
- func (s *Service) AddSubscriberStartup(f func(ctx context.Context, s *Service))
- func (s *Service) CacheManager() cache.Manager
- func (s *Service) Config() any
- func (s *Service) DatastoreManager() datastore.Manager
- func (s *Service) Environment() string
- func (s *Service) EventsManager() events.Manager
- func (s *Service) GetRawCache(name string) (cache.RawCache, bool)
- func (s *Service) GetStartupErrors() []error
- func (s *Service) H() http.Handler
- func (s *Service) HTTPClientManager() client.Manager
- func (s *Service) HandleHealth(w http.ResponseWriter, _ *http.Request)
- func (s *Service) HandleHealthByDefault(w http.ResponseWriter, r *http.Request)
- func (s *Service) HealthCheckers() []Checker
- func (s *Service) Init(ctx context.Context, opts ...Option)
- func (s *Service) LocalizationManager() localization.Manager
- func (s *Service) Log(ctx context.Context) *util.LogEntry
- func (s *Service) Name() string
- func (s *Service) OpenAPIRegistry() *openapi.Registry
- func (s *Service) QueueManager() queue.Manager
- func (s *Service) Run(ctx context.Context, address string) error
- func (s *Service) SLog(ctx context.Context) *slog.Logger
- func (s *Service) SecurityManager() security.Manager
- func (s *Service) SetShutdownTimeout(timeout time.Duration)
- func (s *Service) Stop(ctx context.Context)
- func (s *Service) TLSEnabled() bool
- func (s *Service) TelemetryManager() telemetry.Manager
- func (s *Service) TenancyProvider() tenancy.Provider
- func (s *Service) Version() string
- func (s *Service) WorkManager() workerpool.Manager
Constants ¶
const ManifestRegistrationPath = "/_internal/register/permissions"
ManifestRegistrationPath is the default HTTP path for the internal permission manifest registration endpoint on the tenancy service.
const ManifestRegistrationURLEnvVar = "PERMISSIONS_REGISTRATION_URL"
ManifestRegistrationURLEnvVar is the environment variable that provides the full URL for permission manifest registration. Services set this to point at the tenancy service's internal registration endpoint.
Variables ¶
var ErrHTTPServerConfigRequired = errors.New("configuration must implement config.ConfigurationHTTPServer")
var ErrHealthCheckFailed = errors.New("health check failed")
Functions ¶
func ErrorIsNotFound ¶
ErrorIsNotFound checks if an error represents a "not found" condition. It handles multiple error types: - Database errors: gorm.ErrRecordNotFound, sql.ErrNoRows (via ErrorIsNoRows) - gRPC errors: codes.NotFound - Generic errors: error messages containing "not found" (case-insensitive).
func FormatNamespaceDisplay ¶
FormatNamespaceDisplay returns a human-readable name from a service namespace identifier (e.g. "service_profile" → "Profile").
Types ¶
type Checker ¶
type Checker interface {
CheckHealth() error
}
Checker wraps the CheckHealth method.
CheckHealth returns nil if the resource is healthy, or a non-nil error if the resource is not healthy. CheckHealth must be safe to call from multiple goroutines.
type CheckerFunc ¶
type CheckerFunc func() error
CheckerFunc is an adapter type to allow the use of ordinary functions as health checks. If f is a function with the appropriate signature, CheckerFunc(f) is a Checker that calls f.
type HealthCheckResult ¶
type HealthCheckResult struct {
Name string `json:"name"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
}
HealthCheckResult holds the result of an individual health checker.
type HealthResponse ¶
type HealthResponse struct {
Service string `json:"service"`
Version string `json:"version"`
Repository string `json:"repository,omitempty"`
Commit string `json:"commit,omitempty"`
BuildDate string `json:"build_date,omitempty"`
Uptime string `json:"uptime"`
Status string `json:"status"`
Checks []HealthCheckResult `json:"checks"`
}
HealthResponse is the JSON structure returned by the health check endpoint.
type NamedChecker ¶
type NamedChecker interface {
Name() string
}
NamedChecker is an optional interface that a Checker can implement to provide a human-readable name in health check responses.
type Option ¶
func WithBackgroundConsumer ¶
WithBackgroundConsumer sets a background consumer function for the worker pool.
func WithCacheManager ¶
func WithCacheManager() Option
WithCacheManager adds a cache manager to the service.
func WithConfig ¶
WithConfig Option that helps to specify or override the configuration object of our service.
func WithDatastore ¶
func WithDatastoreConnection ¶
WithDatastoreConnection Option method to store a connection that will be utilized when connecting to the database.
func WithDatastoreManager ¶
func WithDatastoreManager() Option
WithDatastoreManager creates and initializes a datastore manager with the given options. This is the low-level function that should rarely be called directly - use WithDatastore instead.
func WithDebugEndpoints ¶
func WithDebugEndpoints() Option
WithDebugEndpoints enables AI-friendly introspection endpoints.
func WithDebugEndpointsAt ¶
WithDebugEndpointsAt enables introspection endpoints at a custom base path.
func WithDriver ¶
WithDriver setsup a driver, mostly useful when writing tests against the frame service.
func WithEnvironment ¶
WithEnvironment specifies the environment the service will utilize.
func WithHTTPClient ¶
func WithHTTPClient(opts ...client.HTTPOption) Option
WithHTTPClient configures the HTTP client used by the service. This allows customizing the HTTP client's behavior such as timeout, transport, etc.
func WithHTTPHandler ¶
WithHTTPHandler specifies an HTTP handlers that can be used to handle inbound HTTP requests.
func WithHTTPMiddleware ¶
WithHTTPMiddleware registers one or more HTTP middlewares. Middlewares wrap the application handler in the order supplied.
func WithHTTPRequestTimeout ¶ added in v2.0.2
WithHTTPRequestTimeout adds a middleware that enforces a per-request timeout. The context will be canceled after the specified duration.
func WithHealthCheckPath ¶
WithHealthCheckPath Option checks that the system is up and running.
func WithInMemoryCache ¶
WithInMemoryCache adds an in-memory cache with the given name.
func WithLogger ¶
WithLogger Option that helps with initialization of our internal dbLogger.
func WithOPL ¶
WithOPL registers an OPL (Open Policy Language) namespace definition to be served at /_internal/opl/{namespace}. Multiple OPL specs can be registered for services that span multiple namespaces.
func WithOpenAPIBasePath ¶
WithOpenAPIBasePath sets the base path used to serve OpenAPI specs. The default is /debug/frame/openapi.
func WithOpenAPISpec ¶
WithOpenAPISpec registers a single OpenAPI spec with the service. Content should be provided from compile-time embedded assets.
func WithOpenAPISpecsFromFS ¶
WithOpenAPISpecsFromFS registers all .json OpenAPI specs from an embedded FS directory. Use //go:embed to provide the fs.FS at compile time.
func WithPermissionRegistration ¶
func WithPermissionRegistration(sd protoreflect.ServiceDescriptor) Option
WithPermissionRegistration registers a service's permission manifest with the tenancy service. The manifest (namespace, permissions, role bindings) is extracted from the proto service descriptor's service_permissions annotation using proto reflection.
Registration runs as a PreStartMethod whenever PERMISSIONS_REGISTRATION_URL is set and the proto descriptor carries a service_permissions extension. It fires once per process start, before the service begins serving traffic. The tenancy registration endpoint is an idempotent upsert keyed on namespace, so repeat registrations across pod restarts are safe and keep the tenancy.service_namespaces table in sync with whatever the running binary declares.
Earlier versions gated registration on DO_MIGRATION=true so that only the migration job published manifests. That coupling broke whenever a service's cmd/main.go short-circuited before svc.Run (typical pattern): the migration pod never reached the PreStartMethod, the regular pod was locked out by the gate, and the namespace was never registered. Decoupling from migration mode fixes that without forcing every consumer to invent glue around svc.Run.
The tenancy service URL is read from PERMISSIONS_REGISTRATION_URL. When unset, the option is a no-op — services that don't want to register can leave it unset in their environment.
Usage:
sd := profilepb.File_profile_v1_profile_proto.Services().ByName("ProfileService")
frame.WithPermissionRegistration(sd)
func WithPlugin ¶
WithPlugin wraps an option and registers its name for introspection.
func WithRegisterEvents ¶
WithRegisterEvents registers events for the service. All events are unique and shouldn't share a name otherwise the last one registered will take precedence.
func WithRegisterPublisher ¶
WithRegisterPublisher Option to register publishing path referenced within the system.
func WithRegisterSubscriber ¶
func WithRegisterSubscriber(reference string, queueURL string, handlers ...queue.SubscribeWorker) Option
WithRegisterSubscriber Option to register a new subscription handlers.
func WithTelemetry ¶
WithTelemetry adds required telemetry config options to the service.
func WithTenancyProvider ¶
WithTenancyProvider overrides the default Postgres-RLS tenancy provider that WithDatastore wires by default. Pass nil to disable tenancy enforcement entirely (useful for tests).
May be passed before or after WithDatastore in the option list — WithDatastore resolves s.tenancyProvider at construction time, and the resolved provider flows through to pool.NewPool via opts.
func WithTranslation ¶
WithTranslation Option that helps to specify or override the configuration object of our service.
func WithVersion ¶
WithVersion specifies the version the service will utilize.
func WithWorkerPoolOptions ¶
func WithWorkerPoolOptions(options ...workerpool.Option) Option
WithWorkerPoolOptions provides a way to set custom options for the ants worker pool. Renamed from WithAntsOptions and changed parameter type.
type RouteLister ¶
type RouteLister interface {
Routes() []RouteInfo
}
type RouteRegistry ¶
type RouteRegistry struct {
// contains filtered or unexported fields
}
RouteRegistry wraps http.ServeMux and records registered routes for introspection.
func NewRouteRegistry ¶
func NewRouteRegistry() *RouteRegistry
func (*RouteRegistry) HandleFunc ¶
func (r *RouteRegistry) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
func (*RouteRegistry) HandleRoute ¶
func (r *RouteRegistry) HandleRoute(method, pattern, name string, handler func(http.ResponseWriter, *http.Request))
HandleRoute records method-aware routes for introspection.
func (*RouteRegistry) Routes ¶
func (r *RouteRegistry) Routes() []RouteInfo
func (*RouteRegistry) ServeHTTP ¶
func (r *RouteRegistry) ServeHTTP(w http.ResponseWriter, req *http.Request)
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service framework struct to hold together all application components An instance of this type scoped to stay for the lifetime of the application. It is pushed and pulled from contexts to make it easy to pass around.
func FromContext ¶
func NewService ¶
NewService creates a new instance of Service with the name and supplied options. Internally it calls NewServiceWithContext and creates a background context for use.
func NewServiceWithContext ¶
NewServiceWithContext creates a new instance of Service with context, name and supplied options It is used together with the Init option to setup components of a service that is not yet running.
func (*Service) AddCleanupMethod ¶
AddCleanupMethod Adds user defined functions to be run just before completely stopping the service. These are responsible for properly and gracefully stopping active components.
func (*Service) AddHealthCheck ¶
AddHealthCheck Adds health checks that are run periodically to ascertain the system is ok The arguments are implementations of the checker interface and should work with just about any system that is given to them.
func (*Service) AddPreStartMethod ¶
AddPreStartMethod Adds user defined functions that can be run just before the service starts receiving requests but is fully initialized.
func (*Service) AddPublisherStartup ¶
AddPublisherStartup Adds publisher initialization functions that run before subscribers.
func (*Service) AddStartupError ¶
AddStartupError stores errors that occur during startup initialization.
func (*Service) AddSubscriberStartup ¶
AddSubscriberStartup Adds subscriber initialization functions that run after publishers.
func (*Service) CacheManager ¶
CacheManager returns the service's cache manager.
func (*Service) DatastoreManager ¶
DatastoreManager returns the service's datastore manager.
func (*Service) Environment ¶
Environment gets the runtime environment of the service.
func (*Service) EventsManager ¶
func (*Service) GetRawCache ¶
GetRawCache is a convenience method to get a raw cache by name from the service.
func (*Service) GetStartupErrors ¶
GetStartupErrors returns all errors that occurred during startup.
func (*Service) HTTPClientManager ¶
HTTPClientManager obtains an instrumented http client for making appropriate calls downstream.
func (*Service) HandleHealth ¶
func (s *Service) HandleHealth(w http.ResponseWriter, _ *http.Request)
HandleHealth returns 200 with a JSON health report if all checks pass, 500 otherwise.
func (*Service) HandleHealthByDefault ¶
func (s *Service) HandleHealthByDefault(w http.ResponseWriter, r *http.Request)
HandleHealthByDefault returns the health report at root, 404 for other paths.
func (*Service) HealthCheckers ¶
func (*Service) Init ¶
Init evaluates the options provided as arguments and supplies them to the service object. If called after initial startup, it will execute any new startup methods immediately.
func (*Service) LocalizationManager ¶
func (s *Service) LocalizationManager() localization.Manager
func (*Service) Name ¶
Name gets the name of the service. Its the first argument used when NewService is called.
func (*Service) OpenAPIRegistry ¶
func (*Service) QueueManager ¶
func (*Service) SecurityManager ¶
func (*Service) SetShutdownTimeout ¶ added in v2.0.2
SetShutdownTimeout sets the overall shutdown timeout for the service. If not set, defaults to HTTP server shutdown timeout from config.
func (*Service) Stop ¶
Stop Used to gracefully run clean up methods ensuring all requests that were being handled are completed well without interuptions.
func (*Service) TLSEnabled ¶
func (*Service) TelemetryManager ¶
func (*Service) TenancyProvider ¶
TenancyProvider returns the tenancy provider wired for the default pool. Used by tests and diagnostics. May be nil when tenancy has been explicitly disabled via WithTenancyProvider(nil).
func (*Service) WorkManager ¶
func (s *Service) WorkManager() workerpool.Manager
Source Files
¶
- common.go
- debug_endpoints.go
- oauth2_client_jwks.go
- opl_endpoints.go
- options_cache.go
- options_client.go
- options_config.go
- options_datastore.go
- options_events.go
- options_localization.go
- options_logger.go
- options_openapi.go
- options_permissions.go
- options_plugin.go
- options_queue.go
- options_security.go
- options_server.go
- options_telemetry.go
- options_worker.go
- route_registry.go
- service.go
- service_health.go
- tls_certificates.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
frame
command
|
|
|
dialect
Package dialect defines the driver abstraction frame uses to talk to a database.
|
Package dialect defines the driver abstraction frame uses to talk to a database. |
|
dialect/postgres
Package postgres provides the Postgres concrete DialectAdapter.
|
Package postgres provides the Postgres concrete DialectAdapter. |
|
examples
|
|
|
datastore-basic
command
|
|
|
http-basic
command
|
|
|
queue-basic
command
|
|
|
rlstest
Package rlstest provides a test-only tenancy.Provider wrapper that drops connections to an unprivileged role so Postgres FORCE ROW LEVEL SECURITY is actually enforced.
|
Package rlstest provides a test-only tenancy.Provider wrapper that drops connections to an unprivileged role so Postgres FORCE ROW LEVEL SECURITY is actually enforced. |
|
Package ratelimiter provides admission-control primitives for protecting services from overload.
|
Package ratelimiter provides admission-control primitives for protecting services from overload. |
|
authorizer
Package authorizer provides an Ory Keto adapter implementation for the security.Authorizer interface.
|
Package authorizer provides an Ory Keto adapter implementation for the security.Authorizer interface. |
|
Package tenancy provides the storage-layer view of a principal's tenancy (Claims), the Provider abstraction for enforcement, and helpers to bind tenancy to a request context.
|
Package tenancy provides the storage-layer view of a principal's tenancy (Claims), the Provider abstraction for enforcement, and helpers to bind tenancy to a request context. |
|
postgres
Package postgres provides the Postgres concrete tenancy.Provider.
|
Package postgres provides the Postgres concrete tenancy.Provider. |
|
tools
|
|