{"modulePath":"github.com/LeanerCloud/cloud-commitments-platform","version":"v0.0.0-20261202160902-a99bcb5bfea3","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package analytics\n\nPackage analytics provides the scheduled collector for savings time-series data.\n\n## Constants\n\n```go\nconst (\n\t// HoursPerYear is the approximate number of hours in a year (365 days).\n\tHoursPerYear = 365 * 24\n\n\t// MonthsPerYear amortizes an upfront commitment cost into a monthly run-rate\n\t// over the commitment term (term is expressed in years).\n\tMonthsPerYear = 12\n)\n```\nConstants for time calculations.\n\n## Types\n\n```go\ntype AnalyticsStore interface {\n\t// SaveSnapshot stores a single savings snapshot.\n\tSaveSnapshot(ctx context.Context, snapshot *SavingsSnapshot) error\n\n\t// BulkInsertSnapshots inserts multiple snapshots efficiently.\n\tBulkInsertSnapshots(ctx context.Context, snapshots []SavingsSnapshot) error\n\n\t// QuerySavings retrieves savings snapshots based on query parameters.\n\tQuerySavings(ctx context.Context, req QueryRequest) ([]SavingsSnapshot, error)\n\n\t// Aggregated queries (using materialized views for performance). Scoping is\n\t// the dual-column model; pass empty filters only after enforcing scope.\n\tQueryMonthlyTotals(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, months int) ([]MonthlySummary, error)\n\tQueryByProvider(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, startDate, endDate time.Time) ([]ProviderBreakdown, error)\n\tQueryByService(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, provider string, startDate, endDate time.Time) ([]ServiceBreakdown, error)\n\n\t// Partition management.\n\tCreatePartition(ctx context.Context, forMonth time.Time) error\n\tCreateFuturePartitions(ctx context.Context, monthsAhead int) error\n\tDropOldPartitions(ctx context.Context, retentionMonths int) error\n\tCreatePartitionsForRange(ctx context.Context, startDate, endDate time.Time) error\n\n\t// Materialized view management.\n\tRefreshMaterializedViews(ctx context.Context) error\n\n\t// Close cleans up resources.\n\tClose() error\n}\n```\nAnalyticsStore defines the interface for analytics storage.\n\n```go\ntype Collector struct {\n\t// contains filtered or unexported fields\n}\n```\nCollector aggregates savings data and writes point-in-time snapshots to PostgreSQL for the historical-savings analytics time-series. It runs on a schedule (see server.handleCollectAnalytics) across all tenants.\n\n```go\nfunc NewCollector(cfg CollectorConfig, configStore config.StoreInterface) (*Collector, error)\n```\nNewCollector creates a new savings collector.\n\n```go\nfunc (c *Collector) Collect(ctx context.Context) error\n```\nCollect aggregates current savings data across all tenants and writes a snapshot row per bucket. Intended to be called on a schedule.\n\n```go\ntype CollectorConfig struct {\n\tAnalyticsStore AnalyticsStore\n}\n```\nCollectorConfig holds configuration for the collector.\n\n```go\ntype MonthlySummary struct {\n\tMonth          time.Time `json:\"month\"`\n\tCloudAccountID *string   `json:\"cloud_account_id,omitempty\"`\n\t// AvgCoverage is the average reservation coverage for the month.\n\t// A nil value means coverage data is absent for this period and must\n\t// not be treated as zero coverage by consumers.\n\tAvgCoverage *float64 `json:\"avg_coverage,omitempty\"`\n\t// TotalCommitment is the upfront cost amortized per month (each active\n\t// purchase's upfront payment spread evenly over its term) and TotalUsage\n\t// the recurring monthly fees; committed spend is their sum. Both are\n\t// monthly run-rates: the bucket's per-collection totals averaged over the\n\t// month, as for TotalSavings. nil means unknown, because at least one\n\t// snapshot in the bucket had no figure (monthly_savings_summary propagates\n\t// that NULL, migration 000143), and must never be read as 0. A known zero\n\t// (for example a no-upfront portfolio's TotalCommitment) is 0.\n\tTotalCommitment *float64 `json:\"total_commitment,omitempty\"`\n\tTotalUsage      *float64 `json:\"total_usage,omitempty\"`\n\tAccountID       string   `json:\"account_id\"`\n\tProvider        string   `json:\"provider\"`\n\tService         string   `json:\"service\"`\n\tTotalSavings    float64  `json:\"total_savings\"`\n\tSnapshotCount   int      `json:\"snapshot_count\"`\n}\n```\nMonthlySummary represents aggregated monthly savings.\n\n```go\ntype PostgresAnalyticsStore struct {\n\t// contains filtered or unexported fields\n}\n```\nPostgresAnalyticsStore implements AnalyticsStore using PostgreSQL.\n\n```go\nfunc NewPostgresAnalyticsStore(db *database.Connection) *PostgresAnalyticsStore\n```\nNewPostgresAnalyticsStore creates a new PostgreSQL analytics store.\n\n```go\nfunc (s *PostgresAnalyticsStore) BulkInsertSnapshots(ctx context.Context, snapshots []SavingsSnapshot) error\n```\nBulkInsertSnapshots inserts multiple snapshots efficiently via COPY.\n\n```go\nfunc (s *PostgresAnalyticsStore) Close() error\n```\nClose cleans up resources (no-op for PostgreSQL store).\n\n```go\nfunc (s *PostgresAnalyticsStore) CreateFuturePartitions(ctx context.Context, monthsAhead int) error\n```\nCreateFuturePartitions ensures partitions exist for the current month plus monthsAhead months ahead via the create\\_future\\_savings\\_partitions SQL helper.\n\n```go\nfunc (s *PostgresAnalyticsStore) CreatePartition(ctx context.Context, forMonth time.Time) error\n```\nCreatePartition creates a partition for a specific month.\n\n```go\nfunc (s *PostgresAnalyticsStore) CreatePartitionsForRange(ctx context.Context, startDate, endDate time.Time) error\n```\nCreatePartitionsForRange creates partitions for each month in a date range (used during backfill / migration).\n\n```go\nfunc (s *PostgresAnalyticsStore) DropOldPartitions(ctx context.Context, retentionMonths int) error\n```\nDropOldPartitions removes partitions older than the retention period.\n\n```go\nfunc (s *PostgresAnalyticsStore) QueryByProvider(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, startDate, endDate time.Time) ([]ProviderBreakdown, error)\n```\nQueryByProvider retrieves savings breakdown by provider/service.\n\n```go\nfunc (s *PostgresAnalyticsStore) QueryByService(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, provider string, startDate, endDate time.Time) ([]ServiceBreakdown, error)\n```\nQueryByService retrieves savings breakdown by service/region, optionally filtered to a single provider. An empty provider returns all providers' services.\n\n```go\nfunc (s *PostgresAnalyticsStore) QueryMonthlyTotals(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, months int) ([]MonthlySummary, error)\n```\nQueryMonthlyTotals retrieves monthly aggregated totals for the last N months (inclusive of the current month). months \\\u003c= 0 returns no rows.\n\n```go\nfunc (s *PostgresAnalyticsStore) QuerySavings(ctx context.Context, req QueryRequest) ([]SavingsSnapshot, error)\n```\nQuerySavings retrieves savings snapshots based on query parameters.\n\n```go\nfunc (s *PostgresAnalyticsStore) RefreshMaterializedViews(ctx context.Context) error\n```\nRefreshMaterializedViews refreshes all analytics materialized views.\n\n```go\nfunc (s *PostgresAnalyticsStore) SaveSnapshot(ctx context.Context, snapshot *SavingsSnapshot) error\n```\nSaveSnapshot stores a single savings snapshot.\n\n```go\ntype ProviderBreakdown struct {\n\tAvgCoverage  *float64 `json:\"avg_coverage,omitempty\"`\n\tProvider     string   `json:\"provider\"`\n\tService      string   `json:\"service\"`\n\tTotalSavings float64  `json:\"total_savings\"`\n}\n```\nProviderBreakdown represents savings breakdown by provider.\n\n```go\ntype QueryRequest struct {\n\tStartDate                    time.Time\n\tEndDate                      time.Time\n\tAccountExternalIDsByProvider map[string][]string\n\tProvider                     string\n\tService                      string\n\tAccountUUIDs                 []string\n\tLimit                        int\n}\n```\nQueryRequest defines parameters for querying savings data.\n\nScoping uses the same dual-column model as the live purchase\\_history path: rows match when cloud\\_account\\_id = ANY(AccountUUIDs) OR (provider = p AND account\\_id = ANY(AccountExternalIDsByProvider\\[p])). Both nil/empty means \"all accounts accessible to the caller\" — the caller MUST enforce scoping upstream before passing empty filters.\n\n```go\ntype SavingsSnapshot struct {\n\tTimestamp          time.Time      `json:\"timestamp\"`\n\tTotalUsage         *float64       `json:\"total_usage,omitempty\"`\n\tCloudAccountID     *string        `json:\"cloud_account_id,omitempty\"`\n\tCoveragePercentage *float64       `json:\"coverage_percentage,omitempty\"`\n\tMetadata           map[string]any `json:\"metadata,omitempty\"`\n\tTotalCommitment    *float64       `json:\"total_commitment\"`\n\tProvider           string         `json:\"provider\"`\n\tService            string         `json:\"service\"`\n\tRegion             string         `json:\"region\"`\n\tCommitmentType     string         `json:\"commitment_type\"`\n\tID                 string         `json:\"id\"`\n\tAccountID          string         `json:\"account_id\"`\n\tTotalSavings       float64        `json:\"total_savings\"`\n}\n```\nSavingsSnapshot represents a single savings data point.\n\nTenant key: CloudAccountID (the cloud\\_accounts UUID FK) is the multi-tenant scoping key, mirroring purchase\\_history / purchase\\_executions. AccountID is the cloud-provider external account string (AWS account number, Azure subscription id, GCP project id), kept as a descriptive attribute. A row may carry only one of them populated (CloudAccountID is NULL on the AWS ambient- credentials path and on legacy rows), so both are written when available.\n\n```go\ntype ServiceBreakdown struct {\n\tAvgCoverage  *float64 `json:\"avg_coverage,omitempty\"`\n\tService      string   `json:\"service\"`\n\tRegion       string   `json:\"region\"`\n\tTotalSavings float64  `json:\"total_savings\"`\n}\n```\nServiceBreakdown represents savings breakdown by service.\n\n","path":"github.com/LeanerCloud/cloud-commitments-platform/internal/analytics","name":"analytics","synopsis":"Package analytics provides the scheduled collector for savings time-series data.","isRedistributable":true}
