Add analytics metrics and failure ingestion

This commit is contained in:
2026-02-05 23:40:18 +03:00
parent aa6ba73bb3
commit 5af1462645
12 changed files with 1130 additions and 5 deletions

View File

@@ -0,0 +1,69 @@
package failures
import (
"context"
"database/sql"
"reanimator/internal/domain"
)
type FailureRepository struct {
db *sql.DB
}
func NewFailureRepository(db *sql.DB) *FailureRepository {
return &FailureRepository{db: db}
}
func (r *FailureRepository) BeginTx(ctx context.Context) (*sql.Tx, error) {
return r.db.BeginTx(ctx, nil)
}
type execer interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
func execerFor(db *sql.DB, tx *sql.Tx) execer {
if tx != nil {
return tx
}
return db
}
func (r *FailureRepository) Upsert(ctx context.Context, tx *sql.Tx, event domain.FailureEvent) (int64, error) {
execer := execerFor(r.db, tx)
_, err := execer.ExecContext(ctx,
`INSERT INTO failure_events (source, external_id, component_id, asset_id, failure_type, failure_time, details, confidence)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
component_id = VALUES(component_id),
asset_id = VALUES(asset_id),
failure_type = VALUES(failure_type),
failure_time = VALUES(failure_time),
details = VALUES(details),
confidence = VALUES(confidence)`,
event.Source,
event.ExternalID,
event.ComponentID,
event.AssetID,
event.FailureType,
event.FailureTime,
event.Details,
event.Confidence,
)
if err != nil {
return 0, err
}
var id int64
row := execer.QueryRowContext(ctx,
`SELECT id FROM failure_events WHERE source = ? AND external_id = ?`,
event.Source,
event.ExternalID,
)
if err := row.Scan(&id); err != nil {
return 0, err
}
return id, nil
}