Skip to content

Commit 8b54022

Browse files
committed
feat(sync): attach metrics recorder to sync engine if database is available
Added functionality to attach a metrics recorder to the sync engine, allowing for performance tracking when the database is accessible. If the database is not found or cannot be opened, logging is performed and sync continues without metrics.
1 parent e7b10b7 commit 8b54022

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

internal/cli/sync.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,10 @@ func runSync(cmd *cobra.Command, args []string) error {
273273
return fmt.Errorf("failed to initialize sync engine: %w", err)
274274
}
275275

276+
// Attach sync metrics recorder if database is available
277+
closeMetrics := tryAttachMetricsRecorder(engine, logrus.StandardLogger())
278+
defer closeMetrics()
279+
276280
// Execute sync
277281
if err := engine.Sync(ctx, targets); err != nil {
278282
return fmt.Errorf("sync failed: %w", err)
@@ -319,6 +323,10 @@ func createRunSync(flags *Flags) func(*cobra.Command, []string) error {
319323
return fmt.Errorf("failed to initialize sync engine: %w", err)
320324
}
321325

326+
// Attach sync metrics recorder if database is available
327+
closeMetrics := tryAttachMetricsRecorder(engine, logger)
328+
defer closeMetrics()
329+
322330
// Execute sync
323331
if err := engine.Sync(ctx, targets); err != nil {
324332
return fmt.Errorf("sync failed: %w", err)
@@ -440,6 +448,33 @@ func loadConfigWithFlags(flags *Flags, logger *logrus.Logger) (*config.Config, e
440448
return cfg, nil
441449
}
442450

451+
// tryAttachMetricsRecorder attempts to open the database and attach a sync metrics
452+
// recorder to the engine. If the database does not exist or cannot be opened, it
453+
// logs and returns a no-op closer so sync continues without metrics.
454+
// The returned function must be called (typically via defer) when the sync completes.
455+
func tryAttachMetricsRecorder(engine *sync.Engine, log *logrus.Logger) func() {
456+
path := getDBPath()
457+
if _, err := os.Stat(path); os.IsNotExist(err) {
458+
log.Debug("Database not found; sync metrics will not be recorded")
459+
return func() {}
460+
}
461+
462+
database, err := db.Open(db.OpenOptions{
463+
Path: path,
464+
LogLevel: logger.Silent,
465+
})
466+
if err != nil {
467+
log.WithError(err).Warn("Failed to open database; sync metrics will not be recorded")
468+
return func() {}
469+
}
470+
471+
repo := db.NewBroadcastSyncRepo(database.DB())
472+
adapter := sync.NewDBMetricsAdapter(repo)
473+
engine.SetSyncMetricsRecorder(adapter)
474+
475+
return func() { _ = database.Close() }
476+
}
477+
443478
// createSyncEngine initializes the sync engine with all required dependencies
444479
func createSyncEngine(ctx context.Context, cfg *config.Config) (*sync.Engine, error) {
445480
logger := logrus.StandardLogger()

0 commit comments

Comments
 (0)