server

package
v0.0.0-...-a99bcb5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: OSL-3.0 Imports: 62 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package server provides a cloud-agnostic server implementation for CUDly. It supports both AWS Lambda and standard HTTP server modes.

Index

Constants

View Source
const ScheduledTaskFailedLogMarker = "scheduled_task_failed"

ScheduledTaskFailedLogMarker 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).

Variables

View Source
var ErrScheduledPurchasesFailed = errors.New("scheduled purchases failed")

ErrScheduledPurchasesFailed 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).

View Source
var ErrTaskLockStuck = errors.New("scheduled task lock held longer than any run can last")

ErrTaskLockStuck 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).

Functions

func CreateHTTPServer

func CreateHTTPServer(app *Application, port int) *http.Server

CreateHTTPServer builds the HTTP server with routes and timeouts configured, but does not start listening. This is useful for testing.

func InitConfigStore

func InitConfigStore(ctx context.Context) (*database.Config, secrets.Resolver, error)

InitConfigStore exposes initConfigStore so cmd/server can run the migrator without building a full Application.

func ParseScheduledEvent

func ParseScheduledEvent(rawEvent json.RawMessage) (ScheduledTaskType, ScheduledTaskParams, error)

ParseScheduledEvent parses a scheduled event and returns the task type plus any per-task parameters.

func ScheduledTaskNames

func ScheduledTaskNames() []string

ScheduledTaskNames 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.

func StartHTTPServer

func StartHTTPServer(app *Application, port int) error

StartHTTPServer 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).

func StartLambdaHandler

func StartLambdaHandler(app *Application)

StartLambdaHandler starts the AWS Lambda handler.

Types

type AnalyticsCollectorInterface

type AnalyticsCollectorInterface interface {
	Collect(ctx context.Context) error
}

AnalyticsCollectorInterface aggregates current savings into a point-in-time snapshot row per (tenant, provider, service, region, commitment_type) bucket.

type AnalyticsConfig

type AnalyticsConfig struct {
	// Enabled gates the analytics_collect scheduled task. When false the task
	// returns a "disabled" status without touching the DB. Default true.
	Enabled bool
	// RetentionMonths is how many months of snapshot partitions to keep before
	// the retention job drops them. Default 24. Must be >= 1.
	RetentionMonths int
	// PartitionsAhead is how many future monthly partitions to keep provisioned
	// ahead of the current month so inserts never fall into the catch-all
	// default partition (M3). Default 3. Must be >= 1.
	PartitionsAhead int
}

AnalyticsConfig holds the savings-snapshot collector knobs, read from env at startup and validated at the boundary (see Validate).

func LoadAnalyticsConfig

func LoadAnalyticsConfig() (AnalyticsConfig, error)

LoadAnalyticsConfig defaults unset/blank values and rejects malformed booleans. Integer validation remains in Validate.

func (AnalyticsConfig) Validate

func (c AnalyticsConfig) Validate() error

Validate 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.

type AnalyticsStoreInterface

type AnalyticsStoreInterface interface {
	RefreshMaterializedViews(ctx context.Context) error
	// CreatePartition idempotently ensures the monthly partition containing
	// forMonth exists. The collect task requires the current month's partition
	// before writing so snapshots never land in the default partition (#271).
	CreatePartition(ctx context.Context, forMonth time.Time) error
	// CreateFuturePartitions ensures partitions exist for the current month
	// plus monthsAhead months ahead (M3: partitions otherwise stop after the
	// seeded months and every insert falls into the catch-all default).
	CreateFuturePartitions(ctx context.Context, monthsAhead int) error
	// DropOldPartitions drops partitions older than retentionMonths (retention).
	DropOldPartitions(ctx context.Context, retentionMonths int) error
}

AnalyticsStoreInterface 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.

type Application

type Application struct {
	Purchase PurchaseManagerInterface
	Email    email.SenderInterface // Multi-cloud email sender (AWS SES, GCP SendGrid, Azure ACS)

	RateLimiter api.RateLimiterInterface // Distributed rate limiter (DB-backed for multi-instance)
	Analytics   AnalyticsStoreInterface  // Analytics store for savings data
	// AnalyticsCollector aggregates savings into snapshots on a schedule.
	// Nil until reinitializeAfterConnect wires it; the collect task no-ops
	// when nil so test builds without a DB stay quiet.
	AnalyticsCollector AnalyticsCollectorInterface

	TaskLocker TaskLocker // Advisory lock for scheduled tasks (defaults to DB)

	Scheduler SchedulerInterface

	Config config.StoreInterface
	DB     *database.Connection // PostgreSQL database connection

	// LadderAccountResolver resolves the Lambda's own AWS account ID and region
	// for the single-account ladder gate (Q1). It MUST fail loud when the
	// account cannot be determined: the account ID gates which configs run, so a
	// transient STS failure must abort the whole ladder_run rather than silently
	// skip every config as multi-account. Nil in production -> the default
	// STS-backed resolver (defaultLadderAccountResolver); tests inject a stub.
	LadderAccountResolver func(ctx context.Context) (accountID, region string, err error)

	// LadderCapabilityFactory constructs a LadderCapability for the given region
	// and accountID. It is called once per ladder_run task invocation.
	// Defaults to awsladder.NewFromAWSConfig in production; tests replace it
	// with a fake factory that returns a hermetic LadderCapability.
	LadderCapabilityFactory func(ctx context.Context, region, accountID string) (pkgladder.LadderCapability, error)

	API  *api.Handler
	Auth *auth.Service

	Version string
	// contains filtered or unexported fields
}

Application holds all components of the CUDly server.

func NewApplication

func NewApplication(ctx context.Context, version string) (*Application, error)

NewApplication 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.

func NewApplicationFromDeps

func NewApplicationFromDeps(ctx context.Context, cfg ApplicationConfig, deps ExternalDeps) (*Application, error)

NewApplicationFromDeps creates an Application from pre-built configuration and dependencies. This is the testable constructor - all external I/O is done before calling this.

func (*Application) Close

func (app *Application) Close() error

Close gracefully shuts down the application.

func (*Application) HandleLambdaEvent

func (app *Application) HandleLambdaEvent(ctx context.Context, rawEvent json.RawMessage) (any, error)

HandleLambdaEvent processes any Lambda event type.

func (*Application) HandleScheduledTask

func (app *Application) HandleScheduledTask(ctx context.Context, taskType ScheduledTaskType, params ScheduledTaskParams) (any, error)

HandleScheduledTask processes a scheduled task by type and logs ScheduledTaskFailedLogMarker when it fails, whichever entry point (Lambda event, /api/scheduled/ HTTP, CLI) invoked it.

type ApplicationConfig

type ApplicationConfig struct {
	// RecommendationSchedule is RECOMMENDATION_SCHEDULE: the schedule
	// Terraform gave the deployment's recommendation-collection trigger
	// (EventBridge rate()/cron() or five-field cron), empty when scheduled
	// collection is off. Only read to report the next run (issue #756).
	RecommendationSchedule  string
	IssuerURL               string
	ScheduledTaskSecretName string
	Version                 string
	DefaultRampSchedule     string
	CORSAllowedOrigin       string
	DashboardURL            string
	DashboardBucket         string
	APIKeySecretARN         string
	ScheduledTaskSecret     string
	Analytics               AnalyticsConfig
	NotificationDaysBefore  int
	DefaultCoverage         float64
	DefaultTerm             int
	// TrustedProxyHops is the number of proxies that append to
	// X-Forwarded-For before the app (CUDLY_TRUSTED_PROXY_HOPS). 0 ignores
	// the header and uses the peer address.
	TrustedProxyHops int
	// ScheduledPurchaseMaxOverdue is SCHEDULED_PURCHASE_MAX_OVERDUE, the
	// fire and process sweeps' due-row age cap (issue #712). Zero means
	// purchase.DefaultMaxDueRowAge.
	ScheduledPurchaseMaxOverdue time.Duration

	EnableDashboard bool
	IsLambda        bool
	// FireSweepOff is FIRE_SWEEP_SCHEDULED=false: Terraform scheduled no
	// fire_scheduled_purchases sweep, so delayed purchases cannot execute
	// (issue #1588). Unset means unknown and leaves saves unrestricted.
	FireSweepOff bool
	// contains filtered or unexported fields
}

ApplicationConfig holds all env-based configuration for the application.

func LoadApplicationConfig

func LoadApplicationConfig() (ApplicationConfig, error)

LoadApplicationConfig reads all configuration from environment variables.

type CheckResult

type CheckResult struct {
	Status  string `json:"status"`
	Message string `json:"message,omitempty"`
	Reason  string `json:"reason,omitempty"`
}

CheckResult represents the result of a health check.

/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.

type ExternalDeps

type ExternalDeps struct {
	EmailSender    email.SenderInterface
	ConfigStore    config.StoreInterface
	DBConfig       *database.Config
	SecretResolver secrets.Resolver
	STSClient      purchase.STSClient
}

ExternalDeps holds pre-built external dependencies that require infrastructure.

type HealthStatus

type HealthStatus struct {
	Timestamp time.Time              `json:"timestamp"`
	Checks    map[string]CheckResult `json:"checks"`
	Status    string                 `json:"status"`
	Version   string                 `json:"version"`
}

HealthStatus represents the overall health of the application.

type LadderRunResult

type LadderRunResult struct {
	Planned             int `json:"planned"`
	SkippedCadence      int `json:"skipped_cadence"`
	SkippedDisabled     int `json:"skipped_disabled"`
	SkippedMultiAccount int `json:"skipped_multi_account"`
	Errored             int `json:"errored"`
}

LadderRunResult is the aggregate outcome of one ladder_run task invocation. Each counter increments once per ladder_config entry processed.

type MigrateOptions

type MigrateOptions struct {
	// ForceVersion clears a dirty schema_migrations row at this version. It is
	// accepted only for the dirty version N or the highest version below N
	// that has a migration file (see validateForceVersion).
	ForceVersion *int
	// Timeout bounds the run; zero means defaultMigrateTimeout.
	Timeout time.Duration
}

MigrateOptions tunes one deploy-time migration run.

type MigrateReport

type MigrateReport struct {
	From int
	To   int
}

MigrateReport is the schema version before and after a run.

func RunDeployMigrations

func RunDeployMigrations(ctx context.Context, dbCfg *database.Config, resolver secrets.Resolver, opts MigrateOptions) (MigrateReport, error)

RunDeployMigrations 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.

type PurchaseManagerInterface

type PurchaseManagerInterface interface {
	ProcessScheduledPurchases(ctx context.Context) (*purchase.ProcessResult, error)
	SendUpcomingPurchaseNotifications(ctx context.Context) (*purchase.NotificationResult, error)
	// ApproveExecution, ApproveAndExecute and RunPlannedPurchaseNow return the
	// raw revocation token minted on a successful execute (issue #103: only
	// its hash is stored, so a re-read cannot yield an emailable token).
	// Empty on failure. Each also returns the row with its final status, nil
	// when the run never started (issue #532), and takes the caller's
	// ClaimedRowCheck, run against the claimed row before any provider call
	// (issue #415).
	ApproveExecution(ctx context.Context, execID, token, actor string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)
	ApproveAndExecute(ctx context.Context, execID, actor string, transitionedBy *string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)
	// DirectExecute is ApproveAndExecute for the direct-execute permission; it
	// stamps the executed_* audit fields only after the claim is won.
	DirectExecute(ctx context.Context, execID, actor string, transitionedBy *string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)
	// RunPlannedPurchaseNow forces a pending or paused scheduled purchase to
	// execute immediately (the "Run now" button), sharing ApproveAndExecute's
	// 4-eyes-gated, CAS-guarded funnel instead of a bare status flip that
	// nothing else consumes (issue #218).
	RunPlannedPurchaseNow(ctx context.Context, execID, actor string, transitionedBy *string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)
	CancelExecution(ctx context.Context, execID, token, actor string) error
	// ReapStuckExecutions sweeps purchase_executions stuck in
	// approved/running longer than reapAfter and flips them to "failed"
	// via the existing TransitionExecutionStatus CAS. Wired into the
	// "reap_stuck_purchases" scheduled task. See issue #678.
	ReapStuckExecutions(ctx context.Context, reapAfter time.Duration) (*purchase.ReapResult, error)
	// FireScheduledDelayedPurchases fires purchase_executions in status=scheduled
	// whose scheduled_execution_at is in the past (Gmail-style pre-fire delay,
	// issue #291 wave-2). Called on the "fire_scheduled_purchases" scheduler tick.
	FireScheduledDelayedPurchases(ctx context.Context) (*purchase.FireResult, error)
	// FinalizeInFlightRevocations sweeps unrevoked purchase_history rows with a
	// recorded Azure Return and retries MarkPurchaseRevoked for each, and
	// releases flags that stayed set with no recorded Return (issue #1523). Handles
	// the partial-success case where Azure Return succeeded but the DB write
	// failed (issue #290 Finding #6). Called on the "finalize_revocations" tick.
	FinalizeInFlightRevocations(ctx context.Context) (*purchase.FinalizeResult, error)
}

PurchaseManagerInterface defines the methods required for the purchase manager component.

type ScheduledEvent

type ScheduledEvent struct {
	Source     string `json:"source"`
	DetailType string `json:"detail-type"`
	Action     string `json:"action"`
	// OwnerToken carries the collection-marker owner token (issue #261
	// compare-and-clear guard) for TaskCollectRecommendations events fired
	// by the async self-invoke in handler_recommendations_refresh.go.
	// EventBridge cron deliveries and the --task CLI never set this field,
	// so it decodes to "" and the scheduler treats the run as owning no
	// marker (see ScheduledTaskParams / clearCollectionStartedBestEffort).
	OwnerToken string          `json:"owner_token"`
	Detail     json.RawMessage `json:"detail"`
}

ScheduledEvent 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.

type ScheduledTaskParams

type ScheduledTaskParams struct {
	OwnerToken string
}

ScheduledTaskParams carries per-task-type data extracted from a ScheduledEvent. Only TaskCollectRecommendations currently reads a field (OwnerToken); other task types receive a zero-value struct.

type ScheduledTaskType

type ScheduledTaskType string

ScheduledTaskType represents different types of scheduled tasks.

const (
	TaskCollectRecommendations    ScheduledTaskType = "collect_recommendations"
	TaskProcessScheduledPurchases ScheduledTaskType = "process_scheduled_purchases"
	TaskSendNotifications         ScheduledTaskType = "send_notifications"
	TaskCleanupExpiredRecords     ScheduledTaskType = "cleanup"
	TaskRefreshAnalytics          ScheduledTaskType = "analytics_refresh"
	// TaskCollectAnalytics runs the savings-snapshot collector end to end:
	// ensure upcoming partitions, collect a snapshot across all tenants, apply
	// retention, and refresh the materialized views. Scheduled separately from
	// TaskRefreshAnalytics (the legacy refresh-only task) so the snapshot
	// ingestion cadence can differ from a pure view refresh. See issues
	// #1023 / #1033.
	TaskCollectAnalytics  ScheduledTaskType = "analytics_collect"
	TaskRIExchangeReshape ScheduledTaskType = "ri_exchange_reshape"
	// TaskReapStuckPurchases sweeps purchase_executions stuck in
	// running longer than PURCHASE_APPROVED_REAP_AFTER (approved rows wait
	// longer, see purchase.minApprovedReapAfter) and flips them to "failed"
	// via the existing TransitionExecutionStatus CAS.
	// Backstop for synchronous-executor crashes (Lambda timeout, OOM,
	// network hang) that leave rows orphaned in an in-flight state.
	// See internal/purchase/reaper.go + issue #678.
	TaskReapStuckPurchases ScheduledTaskType = "reap_stuck_purchases"
	// TaskFireScheduledPurchases fires purchase_executions in status=scheduled
	// whose scheduled_execution_at is in the past (Gmail-style pre-fire delay,
	// issue #291 wave-2). Wires the "fire_scheduled_purchases" event action
	// to purchase.Manager.FireScheduledDelayedPurchases.
	TaskFireScheduledPurchases ScheduledTaskType = "fire_scheduled_purchases"
	// TaskFinalizeRevocations sweeps unrevoked purchase_history rows with a
	// recorded Azure Return and retries MarkPurchaseRevoked for each (a row
	// that is only flagged in flight is never marked revoked, issue #1523).
	// These rows represent partial-success cases where the Azure Return API call
	// succeeded but the subsequent DB write failed. The sweep ensures the audit
	// record is eventually consistent without requiring the user to retry (which
	// would be rejected by Azure). See issue #290 Finding #6. The same sweep
	// also polls RI Marketplace listings for sales, proceeds and fees (issue
	// #27, handleFinalizeSweep).
	TaskFinalizeRevocations ScheduledTaskType = "finalize_revocations"
	// TaskLadderRun runs the commitment-laddering planner for every enabled
	// ladder_config. It computes a plan (Allocate + BuildTranches), persists the
	// ladder_run and ladder_tranches rows with status=planned, and stops. No
	// purchases, no emails, no reshapes, no approval tokens are issued in this
	// plan-only phase (PR-2). Execution arrives in a later PR.
	TaskLadderRun ScheduledTaskType = "ladder_run"
	// TaskLadderReconcile settles fired ladder tranches from their executions.
	// It is not gated by the ladder switches, so in-flight tranches keep
	// settling after a switch is turned off.
	TaskLadderReconcile ScheduledTaskType = "ladder_reconcile"
	// TaskLadderFire claims due ladder tranches into scheduled executions. It
	// is gated by laddering_enabled, ladder_execution_enabled and each config's
	// auto_approve mode, and no schedule sends it by default.
	TaskLadderFire ScheduledTaskType = "ladder_fire"
	// TaskLadderReshape runs the commitment-laddering RI-exchange reshape for
	// eligible configs (laddering_enabled, ladder_execution_enabled,
	// ri_exchange_enabled, !require_different_approver, auto_approve, own
	// account). Off by default.
	TaskLadderReshape ScheduledTaskType = "ladder_reshape"
)

func ParseScheduledTaskType

func ParseScheduledTaskType(name string) (ScheduledTaskType, error)

ParseScheduledTaskType 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.

type SchedulerInterface

type SchedulerInterface interface {
	CollectRecommendations(ctx context.Context, ownerToken string) (*scheduler.CollectResult, error)
	ListRecommendations(ctx context.Context, filter config.RecommendationFilter) ([]config.RecommendationRecord, error)
	// ListRecommendationsStrict is ListRecommendations for the money path:
	// suppressions and overrides applied, read errors returned (planstep.Source).
	ListRecommendationsStrict(ctx context.Context, filter config.RecommendationFilter) ([]config.RecommendationRecord, error)
	// ScanRecommendations walks the same rows as ListRecommendations in
	// ID-ordered chunks for the paginated list endpoint (issue #981).
	ScanRecommendations(ctx context.Context, filter config.RecommendationFilter, chunkSize int, fn func([]config.RecommendationRecord) error) error
	// PageRecommendations reads one list page and the full-set summary in
	// SQL for the paginated list endpoint (issue #981).
	PageRecommendations(ctx context.Context, scope config.RecommendationListScope, afterID string, limit int) (*config.RecommendationPage, error)
	// GetRecommendationByID fetches a single rec by application-level id,
	// bypassing account-override filtering. hiddenBy is non-nil when the rec
	// exists but would be dropped by the override filter. Returns nil, nil,
	// nil when absent or fully suppressed.
	GetRecommendationByID(ctx context.Context, id string) (rec *config.RecommendationRecord, hiddenBy []string, err error)
}

SchedulerInterface defines the methods required for the scheduler component.

type TaskLocker

type TaskLocker interface {
	TryAdvisoryLock(ctx context.Context, lockID int64) (bool, error)
	ReleaseAdvisoryLock(ctx context.Context, lockID int64)
	// AdvisoryLockHeldFor reports how long the current holder has held
	// lockID; found is false when nobody holds it or the age is unknown.
	// Used to tell a genuinely running task from a stuck lock (issue #394).
	AdvisoryLockHeldFor(ctx context.Context, lockID int64) (heldFor time.Duration, found bool, err error)
}

TaskLocker abstracts advisory lock operations for scheduled task concurrency control.

Directories

Path Synopsis
Package scheduledauth provides authentication for the /api/scheduled/* endpoints invoked by Cloud Scheduler / Logic Apps.
Package scheduledauth provides authentication for the /api/scheduled/* endpoints invoked by Cloud Scheduler / Logic Apps.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL