| package engine |
|
|
| import ( |
| "context" |
| "time" |
|
|
| "github.com/alpacahq/alpacadecimal" |
| "github.com/samber/lo" |
|
|
| "github.com/openmeterio/openmeter/openmeter/credit/balance" |
| "github.com/openmeterio/openmeter/openmeter/credit/grant" |
| "github.com/openmeterio/openmeter/openmeter/meter" |
| "github.com/openmeterio/openmeter/pkg/timeutil" |
| ) |
|
|
| type RunParams struct { |
| |
| Meter meter.Meter |
| |
| Grants []grant.Grant |
| |
| Until time.Time |
| |
| StartingSnapshot balance.Snapshot |
| |
| ResetBehavior grant.ResetBehavior |
| |
| |
| Resets timeutil.SimpleTimeline |
| } |
|
|
| func (p RunParams) Clone() RunParams { |
| grants := make([]grant.Grant, len(p.Grants)) |
| copy(grants, p.Grants) |
|
|
| resets := timeutil.NewSimpleTimeline(p.Resets.GetTimes()) |
|
|
| res := RunParams{ |
| Meter: p.Meter, |
| Grants: grants, |
| Until: p.Until, |
| StartingSnapshot: p.StartingSnapshot, |
| ResetBehavior: p.ResetBehavior, |
| Resets: resets, |
| } |
|
|
| return res |
| } |
|
|
| type RunResult struct { |
| |
| Snapshot balance.Snapshot |
| |
| History GrantBurnDownHistory |
| |
| RunParams RunParams |
| } |
|
|
| |
| |
| func (r RunResult) TotalAvailableGrantAmountAtLastPeriod() float64 { |
| lastUsagePeriodHistory, _ := lo.Last(r.History.ChunkByResets()) |
|
|
| return lastUsagePeriodHistory.TotalGrantUsage(). |
| Add(alpacadecimal.NewFromFloat(r.Snapshot.Balance())). |
| InexactFloat64() |
| } |
|
|
| type Engine interface { |
| |
| |
| |
| |
| Run(ctx context.Context, params RunParams) (RunResult, error) |
| } |
|
|
| |
| type QueryUsageFn func(ctx context.Context, from, to time.Time) (float64, error) |
|
|
| type EngineConfig struct { |
| QueryUsage QueryUsageFn |
| } |
|
|
| func NewEngine(conf EngineConfig) Engine { |
| return &engine{ |
| EngineConfig: conf, |
| } |
| } |
|
|
| |
| type engine struct { |
| EngineConfig |
| } |
|
|
| |
| var _ Engine = (*engine)(nil) |
|
|