Path: blob/main/components/usage/pkg/scheduler/ledger_job.go
2498 views
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package scheduler56import (7"context"8"fmt"9"time"1011"github.com/gitpod-io/gitpod/common-go/log"12v1 "github.com/gitpod-io/gitpod/usage-api/v1"13"github.com/robfig/cron"14"google.golang.org/protobuf/types/known/timestamppb"15)1617func NewLedgerTriggerJob(schedule time.Duration, job Job) (JobSpec, error) {18parsed, err := cron.Parse(fmt.Sprintf("@every %s", schedule.String()))19if err != nil {20return JobSpec{}, fmt.Errorf("failed to parse period into schedule: %w", err)21}2223return JobSpec{24Job: job,25ID: "ledger",26Schedule: parsed,27InitialLockDuration: schedule,28}, nil29}3031type ClientsConstructor func() (v1.UsageServiceClient, v1.BillingServiceClient, error)3233func NewLedgerTrigger(clientConstructor ClientsConstructor) *LedgerJob {34return &LedgerJob{35clientsConstructor: clientConstructor,36}37}3839type LedgerJob struct {40clientsConstructor ClientsConstructor41}4243func (r *LedgerJob) Run() (err error) {44ctx := context.Background()45now := time.Now().UTC()46hourAgo := now.Add(-1 * time.Hour)4748defer func() {49reportLedgerCompleted(err)50}()5152logger := log.53WithField("from", hourAgo).54WithField("to", now)5556usageClient, billingClient, err := r.clientsConstructor()57if err != nil {58return fmt.Errorf("failed to construct usage and billing client: %w", err)59}6061logger.Info("Running ledger job. Reconciling usage records.")62_, err = usageClient.ReconcileUsage(ctx, &v1.ReconcileUsageRequest{63From: timestamppb.New(hourAgo),64To: timestamppb.New(now),65})66if err != nil {67logger.WithError(err).Errorf("Failed to reconcile usage with ledger.")68return fmt.Errorf("failed to reconcile usage with ledger: %w", err)69}7071logger.Info("Starting invoice reconciliation.")72_, err = billingClient.ReconcileInvoices(ctx, &v1.ReconcileInvoicesRequest{})73if err != nil {74logger.WithError(err).Errorf("Failed to reconcile invoices.")75return fmt.Errorf("failed to reconcile invoices: %w", err)76}7778return nil79}808182