SnapshotState captures the current state of all prebuilds across templates.
(ctx context.Context, store database.Store)
| 554 | |
| 555 | // SnapshotState captures the current state of all prebuilds across templates. |
| 556 | func (c *StoreReconciler) SnapshotState(ctx context.Context, store database.Store) (*prebuilds.GlobalSnapshot, error) { |
| 557 | ctx, span := c.tracer.Start(ctx, "prebuilds.SnapshotState") |
| 558 | defer span.End() |
| 559 | |
| 560 | if err := ctx.Err(); err != nil { |
| 561 | return nil, err |
| 562 | } |
| 563 | |
| 564 | var state prebuilds.GlobalSnapshot |
| 565 | |
| 566 | // If called with a store that is already in a transaction, |
| 567 | // InTx will reuse that transaction rather than creating a new one. |
| 568 | err := store.InTx(func(db database.Store) error { |
| 569 | // TODO: implement template-specific reconciliations later |
| 570 | presetsWithPrebuilds, err := db.GetTemplatePresetsWithPrebuilds(ctx, uuid.NullUUID{}) |
| 571 | if err != nil { |
| 572 | return xerrors.Errorf("failed to get template presets with prebuilds: %w", err) |
| 573 | } |
| 574 | if len(presetsWithPrebuilds) == 0 { |
| 575 | return nil |
| 576 | } |
| 577 | |
| 578 | presetPrebuildSchedules, err := db.GetActivePresetPrebuildSchedules(ctx) |
| 579 | if err != nil { |
| 580 | return xerrors.Errorf("failed to get preset prebuild schedules: %w", err) |
| 581 | } |
| 582 | |
| 583 | // Get results from both original and optimized queries for comparison |
| 584 | allRunningPrebuilds, err := db.GetRunningPrebuiltWorkspaces(ctx) |
| 585 | if err != nil { |
| 586 | return xerrors.Errorf("failed to get running prebuilds: %w", err) |
| 587 | } |
| 588 | |
| 589 | allPrebuildsInProgress, err := db.CountInProgressPrebuilds(ctx) |
| 590 | if err != nil { |
| 591 | return xerrors.Errorf("failed to get prebuilds in progress: %w", err) |
| 592 | } |
| 593 | |
| 594 | allPendingPrebuilds, err := db.CountPendingNonActivePrebuilds(ctx) |
| 595 | if err != nil { |
| 596 | return xerrors.Errorf("failed to get pending prebuilds: %w", err) |
| 597 | } |
| 598 | |
| 599 | presetsBackoff, err := db.GetPresetsBackoff(ctx, c.clock.Now().Add(-c.cfg.ReconciliationBackoffLookback.Value())) |
| 600 | if err != nil { |
| 601 | return xerrors.Errorf("failed to get backoffs for presets: %w", err) |
| 602 | } |
| 603 | |
| 604 | hardLimitedPresets, err := db.GetPresetsAtFailureLimit(ctx, c.cfg.FailureHardLimit.Value()) |
| 605 | if err != nil { |
| 606 | return xerrors.Errorf("failed to get hard limited presets: %w", err) |
| 607 | } |
| 608 | |
| 609 | state = prebuilds.NewGlobalSnapshot( |
| 610 | presetsWithPrebuilds, |
| 611 | presetPrebuildSchedules, |
| 612 | allRunningPrebuilds, |
| 613 | allPrebuildsInProgress, |