{"modulePath":"github.com/LeanerCloud/cloud-commitments-platform","version":"v0.0.0-20261202160902-a99bcb5bfea3","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package server\n\nPackage server provides a cloud-agnostic server implementation for CUDly. It supports both AWS Lambda and standard HTTP server modes.\n\n## Constants\n\n```go\nconst ScheduledTaskFailedLogMarker = \"scheduled_task_failed\"\n```\nScheduledTaskFailedLogMarker is the stable token logged whenever a scheduled task returns an error, including a partial failure (issue #714). The per-cloud monitoring modules alert on any occurrence, so it is a contract with terraform/modules/monitoring/{aws,gcp,azure}: rename it only together with those filters (TestMonitoringLogMarkersMatchGo guards the pairing).\n\n## Variables\n\n```go\nvar ErrScheduledPurchasesFailed = errors.New(\"scheduled purchases failed\")\n```\nErrScheduledPurchasesFailed marks a process\\_scheduled\\_purchases run in which at least one execution failed. The run returns it instead of success so the scheduler (EventBridge/Lambda, Cloud Scheduler, Logic Apps) records a failed invocation and the HTTP path answers 500 rather than 200 (issue #714).\n\n```go\nvar ErrTaskLockStuck = errors.New(\"scheduled task lock held longer than any run can last\")\n```\nErrTaskLockStuck is returned by HandleScheduledTask when the advisory lock for the task has been held past stuckTaskLockThreshold. Returning an error (rather than the 200 \"already\\_running\" skip) makes a wedged lock visible: the /api/scheduled/ HTTP path answers 500, the Lambda invocation fails and counts toward the function's Errors metric, and the --task CLI exits non-zero (issue #105's third ask, tracked in #394).\n\n## Functions\n\n```go\nfunc CreateHTTPServer(app *Application, port int) *http.Server\n```\nCreateHTTPServer builds the HTTP server with routes and timeouts configured, but does not start listening. This is useful for testing.\n\n```go\nfunc InitConfigStore(ctx context.Context) (*database.Config, secrets.Resolver, error)\n```\nInitConfigStore exposes initConfigStore so cmd/server can run the migrator without building a full Application.\n\n```go\nfunc ParseScheduledEvent(rawEvent json.RawMessage) (ScheduledTaskType, ScheduledTaskParams, error)\n```\nParseScheduledEvent parses a scheduled event and returns the task type plus any per-task parameters.\n\n```go\nfunc ScheduledTaskNames() []string\n```\nScheduledTaskNames returns every task name the server accepts from a scheduler, sorted. Infrastructure tests use it to check that each task is wired on every platform.\n\n```go\nfunc StartHTTPServer(app *Application, port int) error\n```\nStartHTTPServer starts the HTTP server with graceful shutdown on SIGINT/SIGTERM. It blocks until the server exits cleanly. In container orchestrators (Cloud Run, Container Apps, Fargate) SIGTERM is the normal stop signal; without this wiring the process is killed before deferred app.Close() runs, leaving in-flight requests cut and the DB pool/advisory locks undrained (issue #1025).\n\n```go\nfunc StartLambdaHandler(app *Application)\n```\nStartLambdaHandler starts the AWS Lambda handler.\n\n## Types\n\n```go\ntype AnalyticsCollectorInterface interface {\n\tCollect(ctx context.Context) error\n}\n```\nAnalyticsCollectorInterface aggregates current savings into a point-in-time snapshot row per (tenant, provider, service, region, commitment\\_type) bucket.\n\n```go\ntype AnalyticsConfig struct {\n\t// Enabled gates the analytics_collect scheduled task. When false the task\n\t// returns a \"disabled\" status without touching the DB. Default true.\n\tEnabled bool\n\t// RetentionMonths is how many months of snapshot partitions to keep before\n\t// the retention job drops them. Default 24. Must be \u003e= 1.\n\tRetentionMonths int\n\t// PartitionsAhead is how many future monthly partitions to keep provisioned\n\t// ahead of the current month so inserts never fall into the catch-all\n\t// default partition (M3). Default 3. Must be \u003e= 1.\n\tPartitionsAhead int\n}\n```\nAnalyticsConfig holds the savings-snapshot collector knobs, read from env at startup and validated at the boundary (see Validate).\n\n```go\nfunc LoadAnalyticsConfig() (AnalyticsConfig, error)\n```\nLoadAnalyticsConfig defaults unset/blank values and rejects malformed booleans. Integer validation remains in Validate.\n\n```go\nfunc (c AnalyticsConfig) Validate() error\n```\nValidate rejects out-of-range analytics knobs so a misconfiguration fails fast at startup instead of silently producing a broken retention/partition policy at the first scheduled run.\n\n```go\ntype AnalyticsStoreInterface interface {\n\tRefreshMaterializedViews(ctx context.Context) error\n\t// CreatePartition idempotently ensures the monthly partition containing\n\t// forMonth exists. The collect task requires the current month's partition\n\t// before writing so snapshots never land in the default partition (#271).\n\tCreatePartition(ctx context.Context, forMonth time.Time) error\n\t// CreateFuturePartitions ensures partitions exist for the current month\n\t// plus monthsAhead months ahead (M3: partitions otherwise stop after the\n\t// seeded months and every insert falls into the catch-all default).\n\tCreateFuturePartitions(ctx context.Context, monthsAhead int) error\n\t// DropOldPartitions drops partitions older than retentionMonths (retention).\n\tDropOldPartitions(ctx context.Context, retentionMonths int) error\n}\n```\nAnalyticsStoreInterface defines the methods required for analytics storage. Beyond the materialized-view refresh, the scheduled analytics task also keeps monthly partitions provisioned ahead of time and applies retention.\n\n```go\ntype Application struct {\n\tPurchase PurchaseManagerInterface\n\tEmail    email.SenderInterface // Multi-cloud email sender (AWS SES, GCP SendGrid, Azure ACS)\n\n\tRateLimiter api.RateLimiterInterface // Distributed rate limiter (DB-backed for multi-instance)\n\tAnalytics   AnalyticsStoreInterface  // Analytics store for savings data\n\t// AnalyticsCollector aggregates savings into snapshots on a schedule.\n\t// Nil until reinitializeAfterConnect wires it; the collect task no-ops\n\t// when nil so test builds without a DB stay quiet.\n\tAnalyticsCollector AnalyticsCollectorInterface\n\n\tTaskLocker TaskLocker // Advisory lock for scheduled tasks (defaults to DB)\n\n\tScheduler SchedulerInterface\n\n\tConfig config.StoreInterface\n\tDB     *database.Connection // PostgreSQL database connection\n\n\t// LadderAccountResolver resolves the Lambda's own AWS account ID and region\n\t// for the single-account ladder gate (Q1). It MUST fail loud when the\n\t// account cannot be determined: the account ID gates which configs run, so a\n\t// transient STS failure must abort the whole ladder_run rather than silently\n\t// skip every config as multi-account. Nil in production -\u003e the default\n\t// STS-backed resolver (defaultLadderAccountResolver); tests inject a stub.\n\tLadderAccountResolver func(ctx context.Context) (accountID, region string, err error)\n\n\t// LadderCapabilityFactory constructs a LadderCapability for the given region\n\t// and accountID. It is called once per ladder_run task invocation.\n\t// Defaults to awsladder.NewFromAWSConfig in production; tests replace it\n\t// with a fake factory that returns a hermetic LadderCapability.\n\tLadderCapabilityFactory func(ctx context.Context, region, accountID string) (pkgladder.LadderCapability, error)\n\n\tAPI  *api.Handler\n\tAuth *auth.Service\n\n\tVersion string\n\t// contains filtered or unexported fields\n}\n```\nApplication holds all components of the CUDly server.\n\n```go\nfunc NewApplication(ctx context.Context, version string) (*Application, error)\n```\nNewApplication creates and initializes a new Application instance. version overrides the VERSION env var when non-empty, so cmd entrypoints can pass the ldflags-stamped value directly instead of round-tripping through os.Setenv / os.Getenv (04-N1). Pass \"\" to fall back to the env.\n\n```go\nfunc NewApplicationFromDeps(ctx context.Context, cfg ApplicationConfig, deps ExternalDeps) (*Application, error)\n```\nNewApplicationFromDeps creates an Application from pre-built configuration and dependencies. This is the testable constructor - all external I/O is done before calling this.\n\n```go\nfunc (app *Application) Close() error\n```\nClose gracefully shuts down the application.\n\n```go\nfunc (app *Application) HandleLambdaEvent(ctx context.Context, rawEvent json.RawMessage) (any, error)\n```\nHandleLambdaEvent processes any Lambda event type.\n\n```go\nfunc (app *Application) HandleScheduledTask(ctx context.Context, taskType ScheduledTaskType, params ScheduledTaskParams) (any, error)\n```\nHandleScheduledTask processes a scheduled task by type and logs ScheduledTaskFailedLogMarker when it fails, whichever entry point (Lambda event, /api/scheduled/ HTTP, CLI) invoked it.\n\n```go\ntype ApplicationConfig struct {\n\t// RecommendationSchedule is RECOMMENDATION_SCHEDULE: the schedule\n\t// Terraform gave the deployment's recommendation-collection trigger\n\t// (EventBridge rate()/cron() or five-field cron), empty when scheduled\n\t// collection is off. Only read to report the next run (issue #756).\n\tRecommendationSchedule  string\n\tIssuerURL               string\n\tScheduledTaskSecretName string\n\tVersion                 string\n\tDefaultRampSchedule     string\n\tCORSAllowedOrigin       string\n\tDashboardURL            string\n\tDashboardBucket         string\n\tAPIKeySecretARN         string\n\tScheduledTaskSecret     string\n\tAnalytics               AnalyticsConfig\n\tNotificationDaysBefore  int\n\tDefaultCoverage         float64\n\tDefaultTerm             int\n\t// TrustedProxyHops is the number of proxies that append to\n\t// X-Forwarded-For before the app (CUDLY_TRUSTED_PROXY_HOPS). 0 ignores\n\t// the header and uses the peer address.\n\tTrustedProxyHops int\n\t// ScheduledPurchaseMaxOverdue is SCHEDULED_PURCHASE_MAX_OVERDUE, the\n\t// fire and process sweeps' due-row age cap (issue #712). Zero means\n\t// purchase.DefaultMaxDueRowAge.\n\tScheduledPurchaseMaxOverdue time.Duration\n\n\tEnableDashboard bool\n\tIsLambda        bool\n\t// FireSweepOff is FIRE_SWEEP_SCHEDULED=false: Terraform scheduled no\n\t// fire_scheduled_purchases sweep, so delayed purchases cannot execute\n\t// (issue #1588). Unset means unknown and leaves saves unrestricted.\n\tFireSweepOff bool\n\t// contains filtered or unexported fields\n}\n```\nApplicationConfig holds all env-based configuration for the application.\n\n```go\nfunc LoadApplicationConfig() (ApplicationConfig, error)\n```\nLoadApplicationConfig reads all configuration from environment variables.\n\n```go\ntype CheckResult struct {\n\tStatus  string `json:\"status\"`\n\tMessage string `json:\"message,omitempty\"`\n\tReason  string `json:\"reason,omitempty\"`\n}\n```\nCheckResult represents the result of a health check.\n\n/health and /ready are unauthenticated, so Message is always a fixed string and never carries a raw error: pgx and golang-migrate errors name the database host, user, migration file and schema objects (issue #111). A failed check sets Reason to a stable code instead, and the error itself goes to the server log only.\n\n```go\ntype ExternalDeps struct {\n\tEmailSender    email.SenderInterface\n\tConfigStore    config.StoreInterface\n\tDBConfig       *database.Config\n\tSecretResolver secrets.Resolver\n\tSTSClient      purchase.STSClient\n}\n```\nExternalDeps holds pre-built external dependencies that require infrastructure.\n\n```go\ntype HealthStatus struct {\n\tTimestamp time.Time              `json:\"timestamp\"`\n\tChecks    map[string]CheckResult `json:\"checks\"`\n\tStatus    string                 `json:\"status\"`\n\tVersion   string                 `json:\"version\"`\n}\n```\nHealthStatus represents the overall health of the application.\n\n```go\ntype LadderRunResult struct {\n\tPlanned             int `json:\"planned\"`\n\tSkippedCadence      int `json:\"skipped_cadence\"`\n\tSkippedDisabled     int `json:\"skipped_disabled\"`\n\tSkippedMultiAccount int `json:\"skipped_multi_account\"`\n\tErrored             int `json:\"errored\"`\n}\n```\nLadderRunResult is the aggregate outcome of one ladder\\_run task invocation. Each counter increments once per ladder\\_config entry processed.\n\n```go\ntype MigrateOptions struct {\n\t// ForceVersion clears a dirty schema_migrations row at this version. It is\n\t// accepted only for the dirty version N or the highest version below N\n\t// that has a migration file (see validateForceVersion).\n\tForceVersion *int\n\t// Timeout bounds the run; zero means defaultMigrateTimeout.\n\tTimeout time.Duration\n}\n```\nMigrateOptions tunes one deploy-time migration run.\n\n```go\ntype MigrateReport struct {\n\tFrom int\n\tTo   int\n}\n```\nMigrateReport is the schema version before and after a run.\n\n```go\nfunc RunDeployMigrations(ctx context.Context, dbCfg *database.Config, resolver secrets.Resolver, opts MigrateOptions) (MigrateReport, error)\n```\nRunDeployMigrations applies pending migrations once and reports the version range. It is the deploy-time runner used by \\`cudly --migrate\\` and the Lambda migrate event; nothing here auto-heals a dirty row.\n\n```go\ntype PurchaseManagerInterface interface {\n\tProcessScheduledPurchases(ctx context.Context) (*purchase.ProcessResult, error)\n\tSendUpcomingPurchaseNotifications(ctx context.Context) (*purchase.NotificationResult, error)\n\t// ApproveExecution, ApproveAndExecute and RunPlannedPurchaseNow return the\n\t// raw revocation token minted on a successful execute (issue #103: only\n\t// its hash is stored, so a re-read cannot yield an emailable token).\n\t// Empty on failure. Each also returns the row with its final status, nil\n\t// when the run never started (issue #532), and takes the caller's\n\t// ClaimedRowCheck, run against the claimed row before any provider call\n\t// (issue #415).\n\tApproveExecution(ctx context.Context, execID, token, actor string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)\n\tApproveAndExecute(ctx context.Context, execID, actor string, transitionedBy *string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)\n\t// DirectExecute is ApproveAndExecute for the direct-execute permission; it\n\t// stamps the executed_* audit fields only after the claim is won.\n\tDirectExecute(ctx context.Context, execID, actor string, transitionedBy *string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)\n\t// RunPlannedPurchaseNow forces a pending or paused scheduled purchase to\n\t// execute immediately (the \"Run now\" button), sharing ApproveAndExecute's\n\t// 4-eyes-gated, CAS-guarded funnel instead of a bare status flip that\n\t// nothing else consumes (issue #218).\n\tRunPlannedPurchaseNow(ctx context.Context, execID, actor string, transitionedBy *string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)\n\tCancelExecution(ctx context.Context, execID, token, actor string) error\n\t// ReapStuckExecutions sweeps purchase_executions stuck in\n\t// approved/running longer than reapAfter and flips them to \"failed\"\n\t// via the existing TransitionExecutionStatus CAS. Wired into the\n\t// \"reap_stuck_purchases\" scheduled task. See issue #678.\n\tReapStuckExecutions(ctx context.Context, reapAfter time.Duration) (*purchase.ReapResult, error)\n\t// FireScheduledDelayedPurchases fires purchase_executions in status=scheduled\n\t// whose scheduled_execution_at is in the past (Gmail-style pre-fire delay,\n\t// issue #291 wave-2). Called on the \"fire_scheduled_purchases\" scheduler tick.\n\tFireScheduledDelayedPurchases(ctx context.Context) (*purchase.FireResult, error)\n\t// FinalizeInFlightRevocations sweeps unrevoked purchase_history rows with a\n\t// recorded Azure Return and retries MarkPurchaseRevoked for each, and\n\t// releases flags that stayed set with no recorded Return (issue #1523). Handles\n\t// the partial-success case where Azure Return succeeded but the DB write\n\t// failed (issue #290 Finding #6). Called on the \"finalize_revocations\" tick.\n\tFinalizeInFlightRevocations(ctx context.Context) (*purchase.FinalizeResult, error)\n}\n```\nPurchaseManagerInterface defines the methods required for the purchase manager component.\n\n```go\ntype ScheduledEvent struct {\n\tSource     string `json:\"source\"`\n\tDetailType string `json:\"detail-type\"`\n\tAction     string `json:\"action\"`\n\t// OwnerToken carries the collection-marker owner token (issue #261\n\t// compare-and-clear guard) for TaskCollectRecommendations events fired\n\t// by the async self-invoke in handler_recommendations_refresh.go.\n\t// EventBridge cron deliveries and the --task CLI never set this field,\n\t// so it decodes to \"\" and the scheduler treats the run as owning no\n\t// marker (see ScheduledTaskParams / clearCollectionStartedBestEffort).\n\tOwnerToken string          `json:\"owner_token\"`\n\tDetail     json.RawMessage `json:\"detail\"`\n}\n```\nScheduledEvent represents a generic scheduled event. Source, DetailType and Detail are the EventBridge envelope: ParseScheduledEvent never reads them (lambda.go routes on source separately), only Action and OwnerToken drive the task.\n\n```go\ntype ScheduledTaskParams struct {\n\tOwnerToken string\n}\n```\nScheduledTaskParams carries per-task-type data extracted from a ScheduledEvent. Only TaskCollectRecommendations currently reads a field (OwnerToken); other task types receive a zero-value struct.\n\n```go\ntype ScheduledTaskType string\n```\nScheduledTaskType represents different types of scheduled tasks.\n\n```go\nconst (\n\tTaskCollectRecommendations    ScheduledTaskType = \"collect_recommendations\"\n\tTaskProcessScheduledPurchases ScheduledTaskType = \"process_scheduled_purchases\"\n\tTaskSendNotifications         ScheduledTaskType = \"send_notifications\"\n\tTaskCleanupExpiredRecords     ScheduledTaskType = \"cleanup\"\n\tTaskRefreshAnalytics          ScheduledTaskType = \"analytics_refresh\"\n\t// TaskCollectAnalytics runs the savings-snapshot collector end to end:\n\t// ensure upcoming partitions, collect a snapshot across all tenants, apply\n\t// retention, and refresh the materialized views. Scheduled separately from\n\t// TaskRefreshAnalytics (the legacy refresh-only task) so the snapshot\n\t// ingestion cadence can differ from a pure view refresh. See issues\n\t// #1023 / #1033.\n\tTaskCollectAnalytics  ScheduledTaskType = \"analytics_collect\"\n\tTaskRIExchangeReshape ScheduledTaskType = \"ri_exchange_reshape\"\n\t// TaskReapStuckPurchases sweeps purchase_executions stuck in\n\t// running longer than PURCHASE_APPROVED_REAP_AFTER (approved rows wait\n\t// longer, see purchase.minApprovedReapAfter) and flips them to \"failed\"\n\t// via the existing TransitionExecutionStatus CAS.\n\t// Backstop for synchronous-executor crashes (Lambda timeout, OOM,\n\t// network hang) that leave rows orphaned in an in-flight state.\n\t// See internal/purchase/reaper.go + issue #678.\n\tTaskReapStuckPurchases ScheduledTaskType = \"reap_stuck_purchases\"\n\t// TaskFireScheduledPurchases fires purchase_executions in status=scheduled\n\t// whose scheduled_execution_at is in the past (Gmail-style pre-fire delay,\n\t// issue #291 wave-2). Wires the \"fire_scheduled_purchases\" event action\n\t// to purchase.Manager.FireScheduledDelayedPurchases.\n\tTaskFireScheduledPurchases ScheduledTaskType = \"fire_scheduled_purchases\"\n\t// TaskFinalizeRevocations sweeps unrevoked purchase_history rows with a\n\t// recorded Azure Return and retries MarkPurchaseRevoked for each (a row\n\t// that is only flagged in flight is never marked revoked, issue #1523).\n\t// These rows represent partial-success cases where the Azure Return API call\n\t// succeeded but the subsequent DB write failed. The sweep ensures the audit\n\t// record is eventually consistent without requiring the user to retry (which\n\t// would be rejected by Azure). See issue #290 Finding #6. The same sweep\n\t// also polls RI Marketplace listings for sales, proceeds and fees (issue\n\t// #27, handleFinalizeSweep).\n\tTaskFinalizeRevocations ScheduledTaskType = \"finalize_revocations\"\n\t// TaskLadderRun runs the commitment-laddering planner for every enabled\n\t// ladder_config. It computes a plan (Allocate + BuildTranches), persists the\n\t// ladder_run and ladder_tranches rows with status=planned, and stops. No\n\t// purchases, no emails, no reshapes, no approval tokens are issued in this\n\t// plan-only phase (PR-2). Execution arrives in a later PR.\n\tTaskLadderRun ScheduledTaskType = \"ladder_run\"\n\t// TaskLadderReconcile settles fired ladder tranches from their executions.\n\t// It is not gated by the ladder switches, so in-flight tranches keep\n\t// settling after a switch is turned off.\n\tTaskLadderReconcile ScheduledTaskType = \"ladder_reconcile\"\n\t// TaskLadderFire claims due ladder tranches into scheduled executions. It\n\t// is gated by laddering_enabled, ladder_execution_enabled and each config's\n\t// auto_approve mode, and no schedule sends it by default.\n\tTaskLadderFire ScheduledTaskType = \"ladder_fire\"\n\t// TaskLadderReshape runs the commitment-laddering RI-exchange reshape for\n\t// eligible configs (laddering_enabled, ladder_execution_enabled,\n\t// ri_exchange_enabled, !require_different_approver, auto_approve, own\n\t// account). Off by default.\n\tTaskLadderReshape ScheduledTaskType = \"ladder_reshape\"\n)\n```\n\n```go\nfunc ParseScheduledTaskType(name string) (ScheduledTaskType, error)\n```\nParseScheduledTaskType maps a raw task name (an event action or the /api/scheduled/{task} path segment) to its ScheduledTaskType, rejecting names that are not in the roster.\n\n```go\ntype SchedulerInterface interface {\n\tCollectRecommendations(ctx context.Context, ownerToken string) (*scheduler.CollectResult, error)\n\tListRecommendations(ctx context.Context, filter config.RecommendationFilter) ([]config.RecommendationRecord, error)\n\t// ListRecommendationsStrict is ListRecommendations for the money path:\n\t// suppressions and overrides applied, read errors returned (planstep.Source).\n\tListRecommendationsStrict(ctx context.Context, filter config.RecommendationFilter) ([]config.RecommendationRecord, error)\n\t// ScanRecommendations walks the same rows as ListRecommendations in\n\t// ID-ordered chunks for the paginated list endpoint (issue #981).\n\tScanRecommendations(ctx context.Context, filter config.RecommendationFilter, chunkSize int, fn func([]config.RecommendationRecord) error) error\n\t// PageRecommendations reads one list page and the full-set summary in\n\t// SQL for the paginated list endpoint (issue #981).\n\tPageRecommendations(ctx context.Context, scope config.RecommendationListScope, afterID string, limit int) (*config.RecommendationPage, error)\n\t// GetRecommendationByID fetches a single rec by application-level id,\n\t// bypassing account-override filtering. hiddenBy is non-nil when the rec\n\t// exists but would be dropped by the override filter. Returns nil, nil,\n\t// nil when absent or fully suppressed.\n\tGetRecommendationByID(ctx context.Context, id string) (rec *config.RecommendationRecord, hiddenBy []string, err error)\n}\n```\nSchedulerInterface defines the methods required for the scheduler component.\n\n```go\ntype TaskLocker interface {\n\tTryAdvisoryLock(ctx context.Context, lockID int64) (bool, error)\n\tReleaseAdvisoryLock(ctx context.Context, lockID int64)\n\t// AdvisoryLockHeldFor reports how long the current holder has held\n\t// lockID; found is false when nobody holds it or the age is unknown.\n\t// Used to tell a genuinely running task from a stuck lock (issue #394).\n\tAdvisoryLockHeldFor(ctx context.Context, lockID int64) (heldFor time.Duration, found bool, err error)\n}\n```\nTaskLocker abstracts advisory lock operations for scheduled task concurrency control.\n\n","path":"github.com/LeanerCloud/cloud-commitments-platform/internal/server","name":"server","synopsis":"Package server provides a cloud-agnostic server implementation for CUDly.","isRedistributable":true}
