observability

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidTenantID = NewValidationError("tenant ID must be positive")
	ErrInvalidUserID   = NewValidationError("user ID must be positive")
	ErrEmptyAction     = NewValidationError("action cannot be empty")
	ErrEmptyResource   = NewValidationError("resource cannot be empty")
	ErrInvalidID       = NewValidationError("ID must be positive")
	ErrNotFound        = NewNotFoundError("audit log not found")
)

Error types for business logic validation

Functions

func RegisterRoutes

func RegisterRoutes(router *gin.RouterGroup, postgres *database.Postgres, logger *logger.Logger, metrics Metrics, tracer *Tracer)

RegisterRoutes registers observability routes.

Types

type AuditEvent

type AuditEvent struct {
	Action   string
	ActorID  string
	TenantID string
	TraceID  string
	Resource string
	Status   string
}

type AuditLog

type AuditLog struct {
	ID         int64  `json:"id" db:"id"`
	TenantID   int64  `json:"tenant_id" db:"tenant_id"`
	UserID     int64  `json:"user_id" db:"user_id"`
	Action     string `json:"action" db:"action"`
	Resource   string `json:"resource" db:"resource"`
	ResourceID string `json:"resource_id" db:"resource_id"`
	Details    string `json:"details" db:"details"` // JSON stringified details
	IPAddress  string `json:"ip_address" db:"ip_address"`
	UserAgent  string `json:"user_agent" db:"user_agent"`
	CreatedAt  int64  `json:"created_at" db:"created_at"`
}

AuditLog represents an audit log entry stored in the database.

type AuditLogCreateDTO

type AuditLogCreateDTO struct {
	TenantID   int64  `json:"tenant_id" validate:"required"`
	UserID     int64  `json:"user_id" validate:"required"`
	Action     string `json:"action" validate:"required"`
	Resource   string `json:"resource" validate:"required"`
	ResourceID string `json:"resource_id,omitempty"`
	Details    string `json:"details,omitempty"` // JSON stringified details
	IPAddress  string `json:"ip_address,omitempty"`
	UserAgent  string `json:"user_agent,omitempty"`
}

AuditLogCreateDTO represents the data needed to create an audit log entry.

type AuditLogHandler

type AuditLogHandler struct {
	// contains filtered or unexported fields
}

AuditLogHandler handles HTTP requests for audit logs. Handler layer only processes requests - no business logic or DB access.

func NewAuditLogHandler

func NewAuditLogHandler(service Service, logger *logger.Logger, metrics Metrics, tracer *Tracer) *AuditLogHandler

NewAuditLogHandler creates a new audit log handler.

func (*AuditLogHandler) CreateAuditLog

func (h *AuditLogHandler) CreateAuditLog(c *gin.Context)

CreateAuditLog handles POST /audit-logs

func (*AuditLogHandler) GetAuditLog

func (h *AuditLogHandler) GetAuditLog(c *gin.Context)

GetAuditLog handles GET /audit-logs/:id

func (*AuditLogHandler) ListAuditLogs

func (h *AuditLogHandler) ListAuditLogs(c *gin.Context)

ListAuditLogs handles GET /audit-logs

type AuditLogListResponse

type AuditLogListResponse struct {
	Items      []AuditLogResponse `json:"items"`
	TotalCount int64              `json:"total_count"`
	Page       int                `json:"page"`
	PageSize   int                `json:"page_size"`
	TotalPages int                `json:"total_pages"`
}

AuditLogListResponse represents a paginated list of audit logs.

type AuditLogRepository

type AuditLogRepository struct {
	// contains filtered or unexported fields
}

AuditLogRepository handles persistence of audit log entries. Repository layer only talks to DB - no business logic or request handling.

func NewAuditLogRepository

func NewAuditLogRepository(db *database.Postgres, logger *logger.Logger) *AuditLogRepository

NewAuditLogRepository creates a new audit log repository.

func (*AuditLogRepository) Create

func (r *AuditLogRepository) Create(ctx context.Context, log AuditLog) (int64, error)

Create inserts a new audit log entry.

func (*AuditLogRepository) GetByID

func (r *AuditLogRepository) GetByID(ctx context.Context, id int64) (*AuditLog, error)

GetByID retrieves an audit log entry by ID.

func (*AuditLogRepository) List

func (r *AuditLogRepository) List(ctx context.Context, tenantID int64, userID int64,
	action string, resource string, page int, pageSize int) ([]AuditLog, int64, error)

List retrieves paginated audit log entries with optional filtering.

type AuditLogResponse

type AuditLogResponse struct {
	ID         int64  `json:"id"`
	TenantID   int64  `json:"tenant_id"`
	UserID     int64  `json:"user_id"`
	Action     string `json:"action"`
	Resource   string `json:"resource"`
	ResourceID string `json:"resource_id"`
	Details    string `json:"details"`
	IPAddress  string `json:"ip_address"`
	UserAgent  string `json:"user_agent"`
	CreatedAt  int64  `json:"created_at"`
}

AuditLogResponse represents the audit log entry for API responses.

type AuditLogService

type AuditLogService struct {
	// contains filtered or unexported fields
}

AuditLogService handles business logic for audit logs. Service layer only does business logic - no DB access or request handling.

func NewAuditLogService

func NewAuditLogService(repo Repository, logger logger.Logger, auditLogger Logger, metrics Metrics, tracer *Tracer) *AuditLogService

NewAuditLogService creates a new audit log service.

func (*AuditLogService) CreateAuditLog

func (s *AuditLogService) CreateAuditLog(ctx context.Context, input AuditLogCreateDTO) (AuditLogResponse, error)

CreateAuditLog creates a new audit log entry after applying business rules.

func (*AuditLogService) GetAuditLog

func (s *AuditLogService) GetAuditLog(ctx context.Context, id int64) (*AuditLogResponse, error)

GetAuditLog retrieves an audit log entry by ID after applying business rules.

func (*AuditLogService) ListAuditLogs

func (s *AuditLogService) ListAuditLogs(ctx context.Context, tenantID int64, userID int64,
	action string, resource string, page int, pageSize int) (*AuditLogListResponse, error)

ListAuditLogs retrieves paginated audit log entries with filtering.

type AuditLogger

type AuditLogger interface {
	Write(ctx context.Context, event AuditEvent) error
}

type Logger

type Logger interface {
	Info(ctx context.Context, msg string, fields map[string]any)
	Error(ctx context.Context, msg string, err error, fields map[string]any)
}

type Metrics

type Metrics interface {
	IncCounter(name string, labels map[string]string)
	ObserveHistogram(name string, value float64, labels map[string]string)
	SetGauge(name string, value float64, labels map[string]string)
}

type MetricsAdapter

type MetricsAdapter struct {
	// contains filtered or unexported fields
}

MetricsAdapter adapts our MetricsCollector to the Metrics interface.

func NewMetricsAdapter

func NewMetricsAdapter(collector *MetricsCollector) *MetricsAdapter

NewMetricsAdapter creates a new metrics adapter.

func (*MetricsAdapter) AddCounter

func (a *MetricsAdapter) AddCounter(name string, value int64, labels map[string]string)

AddCounter adds a value to a counter.

func (*MetricsAdapter) IncCounter

func (a *MetricsAdapter) IncCounter(name string, labels map[string]string)

IncCounter increments a counter by 1.

func (*MetricsAdapter) ObserveHistogram

func (a *MetricsAdapter) ObserveHistogram(name string, value float64, labels map[string]string)

ObserveHistogram adds a value to a histogram.

func (*MetricsAdapter) SetGauge

func (a *MetricsAdapter) SetGauge(name string, value float64, labels map[string]string)

SetGauge sets a gauge value.

type MetricsCollector

type MetricsCollector struct {
	// contains filtered or unexported fields
}

MetricsCollector collects and stores metrics. This is a simple in-memory implementation that can be replaced with Prometheus, etc.

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector creates a new metrics collector.

func (*MetricsCollector) AddCounter

func (m *MetricsCollector) AddCounter(name string, value int64, labels map[string]string)

AddCounter adds a value to a counter.

func (*MetricsCollector) GetCounter

func (m *MetricsCollector) GetCounter(name string, labels map[string]string) int64

GetCounter returns the current value of a counter.

func (*MetricsCollector) GetGauge

func (m *MetricsCollector) GetGauge(name string, labels map[string]string) float64

GetGauge returns the current value of a gauge.

func (*MetricsCollector) GetHistogram

func (m *MetricsCollector) GetHistogram(name string, labels map[string]string) []float64

GetHistogram returns a copy of the histogram values.

func (*MetricsCollector) IncCounter

func (m *MetricsCollector) IncCounter(name string, labels map[string]string)

IncCounter increments a counter by 1.

func (*MetricsCollector) ObserveHistogram

func (m *MetricsCollector) ObserveHistogram(name string, value float64, labels map[string]string)

ObserveHistogram adds a value to a histogram.

func (*MetricsCollector) SetGauge

func (m *MetricsCollector) SetGauge(name string, value float64, labels map[string]string)

SetGauge sets a gauge value.

type NotFoundError

type NotFoundError struct {
	Message string
}

NotFoundError represents a not found error in business logic.

func NewNotFoundError

func NewNotFoundError(message string) *NotFoundError

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type Repository

type Repository interface {
	Create(context.Context, AuditLog) (int64, error)
	GetByID(context.Context, int64) (*AuditLog, error)
	List(context.Context, int64, int64, string, string, int, int) ([]AuditLog, int64, error)
}

Repository defines the interface for audit log persistence.

type Service

type Service interface {
	CreateAuditLog(context.Context, AuditLogCreateDTO) (AuditLogResponse, error)
	GetAuditLog(context.Context, int64) (*AuditLogResponse, error)
	ListAuditLogs(context.Context, int64, int64, string, string, int, int) (*AuditLogListResponse, error)
}

Service defines the interface for audit log business logic.

type SimpleTraceIDGenerator

type SimpleTraceIDGenerator struct{}

SimpleTraceIDGenerator generates simple UUID-based trace IDs. In production, this would integrate with OpenTelemetry, Jaeger, etc.

func NewSimpleTraceIDGenerator

func NewSimpleTraceIDGenerator() *SimpleTraceIDGenerator

NewSimpleTraceIDGenerator creates a new simple trace ID generator.

func (*SimpleTraceIDGenerator) GenerateSpanID

func (g *SimpleTraceIDGenerator) GenerateSpanID() string

GenerateSpanID generates a span ID.

func (*SimpleTraceIDGenerator) GenerateTraceID

func (g *SimpleTraceIDGenerator) GenerateTraceID() string

GenerateTraceID generates a trace ID from context if available, otherwise creates new one.

type Span

type Span struct {
	TraceID    string
	SpanID     string
	ParentID   string
	Operation  string
	StartTime  time.Time
	EndTime    time.Time
	Attributes map[string]string
	Events     []SpanEvent
	Status     SpanStatus
}

Span represents a single operation in a trace.

func GetSpanFromContext

func GetSpanFromContext(ctx context.Context) *Span

GetSpanFromContext retrieves the current span from context.

type SpanEvent

type SpanEvent struct {
	Time       time.Time
	Name       string
	Attributes map[string]string
}

SpanEvent represents an event within a span.

type SpanStatus

type SpanStatus struct {
	Code    string // OK, ERROR, etc.
	Message string
}

SpanStatus represents the status of a span.

type TraceIDGenerator

type TraceIDGenerator interface {
	GenerateTraceID() string
	GenerateSpanID() string
}

TraceIDGenerator generates trace IDs for distributed tracing.

type Tracer

type Tracer struct {
	// contains filtered or unexported fields
}

Tracer creates and manages spans.

func NewTracer

func NewTracer(traceIDGenerator TraceIDGenerator) *Tracer

NewTracer creates a new tracer.

func (*Tracer) AddSpanEvent

func (t *Tracer) AddSpanEvent(span *Span, name string, attributes map[string]string)

AddSpanEvent adds an event to a span.

func (*Tracer) EndSpan

func (t *Tracer) EndSpan(span *Span)

EndSpan ends a span.

func (*Tracer) SetSpanAttribute

func (t *Tracer) SetSpanAttribute(span *Span, key string, value string)

SetSpanAttribute sets an attribute on a span.

func (*Tracer) SetSpanStatus

func (t *Tracer) SetSpanStatus(span *Span, code string, message string)

SetSpanStatus sets the status of a span.

func (*Tracer) StartSpan

func (t *Tracer) StartSpan(ctx context.Context, operation string, parentSpanID string) (*Span, context.Context)

StartSpan starts a new span. Attempts to extract trace ID from context first, then generates new if not found.

type ValidationError

type ValidationError struct {
	Message string
}

ValidationError represents a validation error in business logic.

func NewValidationError

func NewValidationError(message string) *ValidationError

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL