{"modulePath":"github.com/cruxstack/github-app-setup-go","version":"v0.8.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package ghappsetup\n\nPackage ghappsetup provides a unified runtime for GitHub App lifecycle management. It coordinates configuration loading, readiness gating, and hot reloading for both HTTP servers and AWS Lambda functions.\n\nThe Runtime type provides a consistent interface across both environments:\n\n  - HTTP servers use Start() to block until config loads, Handler() to wrap requests with a ReadyGate, and ListenForReloads() for SIGHUP handling.\n\n  - Lambda functions use EnsureLoaded() for lazy initialization with retry logic on each invocation.\n\n### HTTP Server Usage {#hdr-HTTP_Server_Usage}\n\nFor HTTP servers, create a Runtime and use its methods to manage the application lifecycle:\n\n\truntime, err := ghappsetup.NewRuntime(ghappsetup.Config{\n\t    LoadFunc:     loadConfig,\n\t    AllowedPaths: []string{\"/healthz\", \"/setup\", \"/callback\", \"/\"},\n\t})\n\tif err != nil {\n\t    log.Fatal(err)\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/healthz\", runtime.HealthHandler())\n\tmux.HandleFunc(\"/webhook\", webhookHandler)\n\n\t// Option A: Manual installer wiring\n\tinstallerHandler, _ := installer.New(installer.Config{\n\t    Store:          runtime.Store(),\n\t    Manifest:       manifest,\n\t    OnReloadNeeded: runtime.ReloadCallback(),\n\t})\n\n\t// Option B: Convenience method (recommended)\n\tinstallerHandler, _ := runtime.InstallerHandler(installer.Config{\n\t    Manifest: manifest,\n\t})\n\n\tmux.Handle(\"/setup\", installerHandler)\n\n\tsrv := \u0026http.Server{Handler: runtime.Handler(mux)}\n\tgo srv.ListenAndServe()\n\n\t// Block until config loads, then listen for SIGHUP reloads\n\truntime.Start(ctx)\n\truntime.ListenForReloads(ctx)\n\n### Lambda Usage {#hdr-Lambda_Usage}\n\nFor Lambda functions, use EnsureLoaded() at the start of each handler invocation:\n\n\tvar runtime *ghappsetup.Runtime\n\n\tfunc init() {\n\t    runtime, _ = ghappsetup.NewRuntime(ghappsetup.Config{\n\t        LoadFunc: func(ctx context.Context) error {\n\t            // Resolve SSM parameters if needed\n\t            if err := ssmresolver.ResolveEnvironmentWithDefaults(ctx); err != nil {\n\t                return err\n\t            }\n\t            return initHandler()\n\t        },\n\t    })\n\t}\n\n\tfunc handler(ctx context.Context, req events.APIGatewayV2HTTPRequest) (Response, error) {\n\t    if err := runtime.EnsureLoaded(ctx); err != nil {\n\t        return serviceUnavailableResponse(), nil\n\t    }\n\t    return handleRequest(ctx, req)\n\t}\n\n### Environment Detection {#hdr-Environment_Detection}\n\nThe Runtime automatically detects whether it's running in an HTTP server or Lambda environment by checking for the AWS\\_LAMBDA\\_FUNCTION\\_NAME environment variable. This affects default retry settings:\n\n  - HTTP: 30 retries with 2-second intervals (suitable for startup)\n  - Lambda: 5 retries with 1-second intervals (suitable for cold starts)\n\n### Installer Integration {#hdr-Installer_Integration}\n\nThe Runtime integrates with the installer package for GitHub App creation. When credentials are saved via the installer, the Runtime's reload callback is invoked to trigger configuration reloading. This eliminates the need for global state and enables proper dependency injection.\n\n## Types\n\n```go\ntype Config struct {\n\t// Store is the credential storage backend. If nil, one will be created\n\t// automatically using configstore.NewFromEnv().\n\tStore configstore.Store\n\n\t// LoadFunc is called to load application configuration. This is required.\n\t// The function should read configuration from environment variables or\n\t// other sources and initialize application state. It will be called\n\t// during startup and on reload triggers.\n\tLoadFunc LoadFunc\n\n\t// AllowedPaths specifies HTTP paths that should be served even before\n\t// configuration is loaded. This is typically used for health checks and\n\t// installer endpoints. Only applicable in HTTP environments.\n\t//\n\t// Each entry matches the path itself and anything beneath it on a\n\t// path-segment boundary (\"/setup\" allows \"/setup/disable\" but not\n\t// \"/setupadmin\"); \"/\" matches only the root path. Non-canonical request\n\t// paths (dot segments, repeated slashes) are never allowed early.\n\tAllowedPaths []string\n\n\t// MaxRetries is the maximum number of times to retry loading configuration.\n\t// If zero, defaults are used based on detected environment:\n\t// HTTP: 30 retries, Lambda: 5 retries.\n\tMaxRetries int\n\n\t// RetryInterval is the time to wait between retry attempts.\n\t// If zero, defaults are used based on detected environment:\n\t// HTTP: 2 seconds, Lambda: 1 second.\n\tRetryInterval time.Duration\n}\n```\nConfig configures the Runtime behavior.\n\n```go\ntype Environment int\n```\nEnvironment represents the detected runtime environment.\n\n```go\nconst (\n\t// EnvironmentHTTP indicates a long-running HTTP server environment.\n\tEnvironmentHTTP Environment = iota\n\t// EnvironmentLambda indicates an AWS Lambda function environment.\n\tEnvironmentLambda\n)\n```\n\n```go\ntype LoadFunc func(ctx context.Context) error\n```\nLoadFunc is the function called to load application configuration. It should return an error if configuration is not yet available, which will trigger a retry according to the configured retry policy.\n\n```go\ntype Runtime struct {\n\t// contains filtered or unexported fields\n}\n```\nRuntime coordinates GitHub App configuration loading, readiness gating, and hot reloading. It provides a unified interface for both HTTP servers and Lambda functions.\n\n```go\nfunc NewRuntime(cfg Config) (*Runtime, error)\n```\nNewRuntime creates a new Runtime with the given configuration. It auto-detects the runtime environment (HTTP vs Lambda) and applies appropriate defaults for retry behavior.\n\n```go\nfunc (r *Runtime) EnsureLoaded(ctx context.Context) error\n```\nEnsureLoaded ensures that configuration has been loaded, performing lazy initialization if needed. It is safe to call from multiple goroutines.\n\nThe first call loads configuration using the configured retry policy. Once a load succeeds, subsequent calls return nil immediately. While a load is in progress, concurrent callers wait for it and receive its result. If a load fails, its error is returned and the next call starts a fresh load (again with the full retry policy), so a later invocation can succeed once configuration becomes available, e.g. after the installer saves credentials.\n\nThis method is intended for Lambda environments where configuration loading happens lazily on first request. For HTTP servers, use Start instead.\n\nExample usage in a Lambda handler:\n\n\tfunc handler(ctx context.Context, req events.APIGatewayV2HTTPRequest) (Response, error) {\n\t    if err := runtime.EnsureLoaded(ctx); err != nil {\n\t        return serviceUnavailableResponse(), nil\n\t    }\n\t    return handleRequest(ctx, req)\n\t}\n\n```go\nfunc (r *Runtime) Environment() Environment\n```\nEnvironment returns the detected runtime environment.\n\n```go\nfunc (r *Runtime) Handler(inner http.Handler) http.Handler\n```\nHandler wraps the given http.Handler with a ReadyGate that returns 503 Service Unavailable for requests to non-allowed paths before the runtime is ready. Paths specified in Config.AllowedPaths are always forwarded to the inner handler.\n\nThe returned handler should be used as the server's main handler.\n\n```go\nfunc (r *Runtime) HealthHandler() http.HandlerFunc\n```\nHealthHandler returns an http.HandlerFunc that reports the runtime's readiness status. It returns 200 OK with body \"ok\" when ready, or 503 Service Unavailable with body \"not ready\" when not ready.\n\n```go\nfunc (r *Runtime) InstallerHandler(cfg installer.Config) (http.Handler, error)\n```\nInstallerHandler creates an installer http.Handler with the Runtime's store and reload callback pre-configured. This is a convenience method that simplifies the common case of wiring up the installer with the runtime.\n\nThe returned handler should be mounted at /setup, /setup/, /callback, and / paths. For example:\n\n\tinstallerHandler, err := runtime.InstallerHandler(installer.Config{\n\t    Manifest:       manifest,\n\t    AppDisplayName: \"My App\",\n\t})\n\tif err != nil {\n\t    log.Fatal(err)\n\t}\n\tmux.Handle(\"/setup\", installerHandler)\n\tmux.Handle(\"/setup/\", installerHandler)\n\tmux.Handle(\"/callback\", installerHandler)\n\tmux.Handle(\"/\", installerHandler)\n\nThe Config.Store and Config.OnReloadNeeded fields are automatically set by this method and should not be provided in the input config.\n\n```go\nfunc (r *Runtime) IsReady() bool\n```\nIsReady returns true if configuration has been successfully loaded.\n\n```go\nfunc (r *Runtime) ListenForReloads(ctx context.Context) \u003c-chan struct{}\n```\nListenForReloads starts listening for SIGHUP signals and reload triggers from ReloadCallback. When a reload is triggered, LoadFunc is called. The returned channel is closed when the context is canceled.\n\nThis should be called after Start() completes successfully.\n\n```go\nfunc (r *Runtime) Reload(ctx context.Context) error\n```\nReload triggers a configuration reload by calling LoadFunc. On success the runtime is marked ready, so a reload after a failed or still-pending Start (e.g., once the installer has saved credentials) opens the ReadyGate. Use ReloadCallback for asynchronous, coalesced reload requests.\n\n```go\nfunc (r *Runtime) ReloadCallback() func()\n```\nReloadCallback returns a function suitable for use as installer.Config.OnReloadNeeded. The returned function triggers an asynchronous reload.\n\n```go\nfunc (r *Runtime) ResetLoadState()\n```\nResetLoadState resets the Lambda loading state, allowing EnsureLoaded to attempt loading again. This is primarily useful for testing.\n\n```go\nfunc (r *Runtime) Start(ctx context.Context) error\n```\nStart blocks until configuration is successfully loaded, then marks the runtime as ready. It uses the configured retry policy to attempt loading. Returns an error if configuration cannot be loaded after all retries.\n\nThis method is intended for HTTP server environments. For Lambda, use EnsureLoaded instead.\n\n```go\nfunc (r *Runtime) StartAsync(ctx context.Context) \u003c-chan error\n```\nStartAsync begins configuration loading in the background and returns immediately. The returned channel receives the result of the loading operation - nil on success or an error if loading failed after all retries. The channel is closed after sending the result.\n\nThis method is intended for HTTP server environments where you want to start serving immediately (for health checks and installer endpoints) while configuration loads in the background.\n\n```go\nfunc (r *Runtime) Store() configstore.Store\n```\nStore returns the credential storage backend used by this Runtime. This is useful when manually wiring up the installer.\n\n","path":"github.com/cruxstack/github-app-setup-go/ghappsetup","name":"ghappsetup","synopsis":"Package ghappsetup provides a unified runtime for GitHub App lifecycle management.","isRedistributable":true}
