models

package
v0.1.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2025 License: AGPL-3.0 Imports: 3 Imported by: 0

Documentation

Overview

Package models defines the core data structures used throughout LogChef. It includes database entity models, API request/response structures, and validation rules for ensuring data integrity across the application.

Index

Constants

View Source
const (
	// OTELLogsTableSchema is the schema for OpenTelemetry logs
	OTELLogsTableSchema = `` /* 1124-byte string literal not displayed */

	// HTTPLogsTableSchema is the schema for HTTP logs table
	HTTPLogsTableSchema = `` /* 869-byte string literal not displayed */

)

Schema Constants

Variables

View Source
var (
	// ErrUserNotFound is returned when a user is not found
	ErrUserNotFound = errors.New("user not found")
	// ErrTeamNotFound is returned when a team is not found
	ErrTeamNotFound = errors.New("team not found")
	// ErrNotFound is returned when a resource is not found
	ErrNotFound = errors.New("not found")
)

Error definitions

Functions

This section is empty.

Types

type ColumnInfo

type ColumnInfo struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

ColumnInfo represents column metadata from ClickHouse

type ConnectionInfo

type ConnectionInfo struct {
	Host      string `json:"host"`
	Username  string `json:"username"`
	Password  string `json:"password"`
	Database  string `json:"database"`
	TableName string `json:"table_name"`
}

ConnectionInfo represents the connection details for a ClickHouse database

type ConnectionInfoResponse

type ConnectionInfoResponse struct {
	Host      string `json:"host"`
	Database  string `json:"database"`
	TableName string `json:"table_name"`
}

ConnectionInfoResponse represents the connection details for API responses, omitting sensitive fields

type ConnectionValidationResult

type ConnectionValidationResult struct {
	Message string `json:"message"`
}

ConnectionValidationResult represents the result of a connection validation

type CreateSourceRequest

type CreateSourceRequest struct {
	Name              string         `json:"name"`
	MetaIsAutoCreated bool           `json:"meta_is_auto_created"`
	MetaTSField       string         `json:"meta_ts_field"`
	MetaSeverityField string         `json:"meta_severity_field"`
	Connection        ConnectionInfo `json:"connection"`
	Description       string         `json:"description"`
	TTLDays           int            `json:"ttl_days"`
	Schema            string         `json:"schema,omitempty"`
}

CreateSourceRequest represents a request to create a new data source

type CreateTeamQueryRequest

type CreateTeamQueryRequest struct {
	Name         string         `json:"name" validate:"required"`
	Description  string         `json:"description"`
	SourceID     SourceID       `json:"source_id" validate:"required"`
	QueryType    SavedQueryType `json:"query_type" validate:"required"`
	QueryContent string         `json:"query_content" validate:"required"`
}

CreateTeamQueryRequest represents a request to create a team query

type CreateUserRequest

type CreateUserRequest struct {
	Email    string   `json:"email"`
	FullName string   `json:"full_name"`
	Role     UserRole `json:"role"`
}

CreateUserRequest represents a request to create a new user

type ErrorResponse

type ErrorResponse struct {
	Message string    `json:"message"`
	Type    ErrorType `json:"error_type"`
	Details any       `json:"details,omitempty"`
}

ErrorResponse represents a standardized error response

func NewErrorResponse

func NewErrorResponse(message string, errorType ErrorType, details any) ErrorResponse

NewErrorResponse creates a new error response

type ErrorType

type ErrorType string

ErrorType represents the type of error that occurred

const (
	// ValidationErrorType indicates a validation error
	ValidationErrorType ErrorType = "ValidationError"

	// NotFoundErrorType indicates a resource was not found
	NotFoundErrorType ErrorType = "NotFoundError"

	// AuthenticationErrorType indicates an authentication error
	AuthenticationErrorType ErrorType = "AuthenticationError"

	// AuthorizationErrorType indicates an authorization error
	AuthorizationErrorType ErrorType = "AuthorizationError"

	// ConflictErrorType indicates a resource conflict (e.g., already exists)
	ConflictErrorType ErrorType = "ConflictError"

	// DatabaseErrorType indicates a database error
	DatabaseErrorType ErrorType = "DatabaseError"

	// ExternalServiceErrorType indicates an error with an external service
	ExternalServiceErrorType ErrorType = "ExternalServiceError"

	// GeneralErrorType is a fallback for general errors
	GeneralErrorType ErrorType = "GeneralError"

	// DemoInstanceErrorType indicates an operation not permitted in demo mode
	DemoInstanceErrorType ErrorType = "DEMO_INSTANCE"
)

Common error types

type FilterCondition

type FilterCondition struct {
	Field    string         `json:"field"`
	Operator FilterOperator `json:"operator"`
	Value    string         `json:"value"` // Changed from interface{} for better type safety
}

FilterCondition represents a single filter condition

type FilterOperator

type FilterOperator string

FilterOperator represents a filter operation

const (
	// FilterOperatorEquals represents an equality comparison
	FilterOperatorEquals FilterOperator = "="

	// FilterOperatorNotEquals represents an inequality comparison
	FilterOperatorNotEquals FilterOperator = "!="

	// FilterOperatorContains represents a case-sensitive LIKE operation
	FilterOperatorContains FilterOperator = "contains"

	// FilterOperatorNotContains represents a case-sensitive NOT LIKE operation
	FilterOperatorNotContains FilterOperator = "not_contains"

	// FilterOperatorIContains represents a case-insensitive LIKE operation
	FilterOperatorIContains FilterOperator = "icontains"

	// FilterOperatorStartsWith represents a prefix match operation
	FilterOperatorStartsWith FilterOperator = "startswith"

	// FilterOperatorEndsWith represents a suffix match operation
	FilterOperatorEndsWith FilterOperator = "endswith"

	// FilterOperatorIn represents an IN operation
	FilterOperatorIn FilterOperator = "in"

	// FilterOperatorNotIn represents a NOT IN operation
	FilterOperatorNotIn FilterOperator = "not_in"

	// FilterOperatorIsNull represents an IS NULL check
	FilterOperatorIsNull FilterOperator = "is_null"

	// FilterOperatorIsNotNull represents an IS NOT NULL check
	FilterOperatorIsNotNull FilterOperator = "is_not_null"
)

type GroupOperator

type GroupOperator string

GroupOperator represents a logical operator for combining filter groups

const (
	// GroupOperatorAnd represents a logical AND operation
	GroupOperatorAnd GroupOperator = "AND"

	// GroupOperatorOr represents a logical OR operation
	GroupOperatorOr GroupOperator = "OR"
)

type HealthStatus

type HealthStatus string

HealthStatus represents the health status of a resource

const (
	// HealthStatusHealthy indicates the resource is healthy
	HealthStatusHealthy HealthStatus = "healthy"

	// HealthStatusUnhealthy indicates the resource is unhealthy
	HealthStatusUnhealthy HealthStatus = "unhealthy"
)

type LogContextRequest

type LogContextRequest struct {
	SourceID    SourceID `json:"source_id"`
	Timestamp   int64    `json:"timestamp"`    // Target timestamp in milliseconds
	BeforeLimit int      `json:"before_limit"` // Optional, defaults to 5
	AfterLimit  int      `json:"after_limit"`  // Optional, defaults to 5
}

LogContextRequest represents a request to get temporal context around a log

type LogContextResponse

type LogContextResponse struct {
	TargetTimestamp int64                    `json:"target_timestamp"`
	BeforeLogs      []map[string]interface{} `json:"before_logs"`
	TargetLogs      []map[string]interface{} `json:"target_logs"` // Multiple logs might have the same timestamp
	AfterLogs       []map[string]interface{} `json:"after_logs"`
	Stats           QueryStats               `json:"stats"`
}

LogContextResponse represents temporal context query results

type LogQueryRequest

type LogQueryRequest struct {
	StartTimestamp int64        `json:"start_timestamp"`
	EndTimestamp   int64        `json:"end_timestamp"`
	Limit          int          `json:"limit"`
	RawSQL         string       `json:"raw_sql"`
	Sort           *SortOptions `json:"sort,omitempty"`
	Window         string       `json:"window,omitempty"`   // For histogram queries: time window size like "1m", "5m", "1h"
	GroupBy        string       `json:"group_by,omitempty"` // For histogram queries: field to group by
}

LogQueryRequest represents the request for querying logs

type LogQueryResult

type LogQueryResult struct {
	Data    []map[string]interface{} `json:"data"`
	Stats   QueryStats               `json:"stats"`
	Columns []ColumnInfo             `json:"columns"`
}

LogQueryResult represents the result of a log query

type QueryResult

type QueryResult struct {
	Logs    []map[string]interface{} `json:"logs"`
	Stats   QueryStats               `json:"stats"`
	Columns []ColumnInfo             `json:"columns"`
}

QueryResult represents the result of a query

type QueryStats

type QueryStats struct {
	ExecutionTimeMs float64 `json:"execution_time_ms"`
	RowsRead        int     `json:"rows_read"`
	BytesRead       int     `json:"bytes_read,omitempty"`
}

QueryStats represents statistics about query execution

type SavedQuery

type SavedQuery struct {
	ID          int       `json:"id" db:"id"`
	TeamID      string    `json:"team_id" db:"team_id"`
	SourceID    string    `json:"source_id" db:"source_id"`
	Name        string    `json:"name" db:"name"`
	Description string    `json:"description" db:"description"`
	QuerySQL    string    `json:"query_sql" db:"query_sql"`
	CreatedBy   UserID    `json:"created_by" db:"created_by"`
	CreatedAt   time.Time `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time `json:"updated_at" db:"updated_at"`
}

SavedQuery represents a generic saved query

type SavedQueryContent

type SavedQueryContent struct {
	Version   int                 `json:"version"`
	SourceID  SourceID            `json:"sourceId"`
	TimeRange SavedQueryTimeRange `json:"timeRange"`
	Limit     int                 `json:"limit"`
	Content   string              `json:"content"` // Query content (SQL or LogchefQL)
}

SavedQueryContent represents the content of a saved query

type SavedQueryTab

type SavedQueryTab string

SavedQueryTab represents the active tab in the explorer

const (
	// SavedQueryTabFilters represents the filters tab
	SavedQueryTabFilters SavedQueryTab = "filters"

	// SavedQueryTabRawSQL represents the raw SQL tab
	SavedQueryTabRawSQL SavedQueryTab = "raw_sql"
)

type SavedQueryTimeRange

type SavedQueryTimeRange struct {
	Absolute struct {
		Start int64 `json:"start"` // Unix timestamp in milliseconds
		End   int64 `json:"end"`   // Unix timestamp in milliseconds
	} `json:"absolute"`
}

SavedQueryTimeRange represents a time range for a saved query

type SavedQueryType

type SavedQueryType string

SavedQueryType represents the type of saved query

const (
	// SavedQueryTypeLogchefQL represents a query saved in LogchefQL format
	SavedQueryTypeLogchefQL SavedQueryType = "logchefql"

	// SavedQueryTypeSQL represents a query saved in SQL format
	SavedQueryTypeSQL SavedQueryType = "sql"
)

type SavedTeamQuery

type SavedTeamQuery struct {
	ID           int            `json:"id" db:"id"`
	TeamID       TeamID         `json:"team_id" db:"team_id"`
	SourceID     SourceID       `json:"source_id" db:"source_id"`
	Name         string         `json:"name" db:"name"`
	Description  string         `json:"description" db:"description"`
	QueryType    SavedQueryType `json:"query_type" db:"query_type"`
	QueryContent string         `json:"query_content" db:"query_content"` // JSON string of SavedQueryContent
	CreatedAt    time.Time      `json:"created_at" db:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at" db:"updated_at"`
}

SavedTeamQuery represents a saved query associated with a team

type Session

type Session struct {
	ID        SessionID `db:"id" json:"id"`
	UserID    UserID    `db:"user_id" json:"user_id"`
	ExpiresAt time.Time `db:"expires_at" json:"expires_at"`
	CreatedAt time.Time `db:"created_at" json:"created_at"`
}

Session represents a user session

type SessionID

type SessionID string

SessionID represents a unique session identifier

type SortOptions

type SortOptions struct {
	Field string    `json:"field"`
	Order SortOrder `json:"order"`
}

SortOptions represents sorting configuration

type SortOrder

type SortOrder string

SortOrder represents sort direction

const (
	// SortOrderAsc represents ascending sort order
	SortOrderAsc SortOrder = "ASC"

	// SortOrderDesc represents descending sort order
	SortOrderDesc SortOrder = "DESC"
)

type Source

type Source struct {
	ID                SourceID       `db:"id" json:"id"`
	Name              string         `db:"name" json:"name"`
	MetaIsAutoCreated bool           `db:"_meta_is_auto_created" json:"_meta_is_auto_created"`
	MetaTSField       string         `db:"_meta_ts_field" json:"_meta_ts_field"`
	MetaSeverityField string         `db:"_meta_severity_field" json:"_meta_severity_field"`
	Connection        ConnectionInfo `db:"connection" json:"connection"`
	Description       string         `db:"description" json:"description,omitempty"`
	TTLDays           int            `db:"ttl_days" json:"ttl_days"`
	Timestamps
	IsConnected bool         `db:"-" json:"is_connected"`
	Schema      string       `db:"-" json:"schema,omitempty"`
	Columns     []ColumnInfo `db:"-" json:"columns,omitempty"`
	// Enhanced schema information
	Engine       string   `db:"-" json:"engine,omitempty"`
	EngineParams []string `db:"-" json:"engine_params,omitempty"`
	SortKeys     []string `db:"-" json:"sort_keys,omitempty"`
}

Source represents a ClickHouse data source in our system

func (*Source) GetFullTableName

func (s *Source) GetFullTableName() string

GetFullTableName returns the fully qualified table name (database.table)

func (*Source) ToResponse

func (s *Source) ToResponse() *SourceResponse

ToResponse converts a Source to a SourceResponse, removing sensitive information

type SourceHealth

type SourceHealth struct {
	SourceID    SourceID     `json:"source_id"`
	Status      HealthStatus `json:"status"`
	Error       string       `json:"error,omitempty"`
	LastChecked time.Time    `json:"last_checked"`
}

SourceHealth represents the health status of a source

type SourceID

type SourceID int

SourceID represents a unique data source identifier

type SourceResponse

type SourceResponse struct {
	ID                SourceID               `json:"id"`
	Name              string                 `json:"name"`
	MetaIsAutoCreated bool                   `json:"_meta_is_auto_created"`
	MetaTSField       string                 `json:"_meta_ts_field"`
	MetaSeverityField string                 `json:"_meta_severity_field"`
	Connection        ConnectionInfoResponse `json:"connection"`
	Description       string                 `json:"description,omitempty"`
	TTLDays           int                    `json:"ttl_days"`
	CreatedAt         time.Time              `json:"created_at"`
	UpdatedAt         time.Time              `json:"updated_at"`
	IsConnected       bool                   `json:"is_connected"`
	Schema            string                 `json:"schema,omitempty"`
	Columns           []ColumnInfo           `json:"columns,omitempty"`
	// Enhanced schema information
	Engine       string   `json:"engine,omitempty"`
	EngineParams []string `json:"engine_params,omitempty"`
	SortKeys     []string `json:"sort_keys,omitempty"`
}

SourceResponse represents a Source for API responses, with sensitive information removed

type SourceWithTeams

type SourceWithTeams struct {
	Source *SourceResponse `json:"source"`
	Teams  []*Team         `json:"teams"`
}

SourceWithTeams represents a source along with the teams that have access to it

type TableSchema

type TableSchema struct {
	Columns []ColumnInfo `json:"columns"`
}

TableSchema represents a table's schema information

type Team

type Team struct {
	ID          TeamID `db:"id" json:"id"`
	Name        string `db:"name" json:"name"`
	Description string `db:"description" json:"description"`
	MemberCount int    `db:"-" json:"member_count"`
	Timestamps
}

Team represents a team in the system

type TeamGroupedQuery

type TeamGroupedQuery struct {
	TeamID   TeamID            `json:"team_id"`
	TeamName string            `json:"team_name"`
	Queries  []*SavedTeamQuery `json:"queries"`
}

TeamGroupedQuery represents a query grouped by team

type TeamID

type TeamID int

TeamID represents a unique team identifier

type TeamMember

type TeamMember struct {
	TeamID    TeamID    `db:"team_id" json:"team_id"`
	UserID    UserID    `db:"user_id" json:"user_id"`
	Role      TeamRole  `db:"role" json:"role"`
	CreatedAt time.Time `db:"created_at" json:"created_at"`
	Email     string    `db:"email" json:"email,omitempty"`
	FullName  string    `db:"full_name" json:"full_name,omitempty"`
}

TeamMember represents a user's membership in a team

type TeamQuery

type TeamQuery struct {
	ID           int            `json:"id" db:"id"`
	TeamID       TeamID         `json:"team_id" db:"team_id"`
	SourceID     SourceID       `json:"source_id" db:"source_id"`
	Name         string         `json:"name" db:"name"`
	Description  string         `json:"description" db:"description"`
	QueryType    SavedQueryType `json:"query_type" db:"query_type"`
	QueryContent string         `json:"query_content" db:"query_content"`
	Timestamps
}

TeamQuery represents a saved query in a team

type TeamRole

type TeamRole string

TeamRole represents the possible team member roles

const (
	// TeamRoleOwner represents the owner of a team
	TeamRoleOwner TeamRole = "owner"

	// TeamRoleAdmin represents a team admin
	TeamRoleAdmin TeamRole = "admin"

	// TeamRoleMember represents a regular team member
	TeamRoleMember TeamRole = "member"
)

type Timestamps

type Timestamps struct {
	CreatedAt time.Time `db:"created_at" json:"created_at"`
	UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}

Timestamps provides common timestamp fields used across multiple models

type UpdateTeamQueryRequest

type UpdateTeamQueryRequest struct {
	Name         string         `json:"name"`
	Description  string         `json:"description"`
	SourceID     SourceID       `json:"source_id"`
	QueryType    SavedQueryType `json:"query_type"`
	QueryContent string         `json:"query_content"`
}

UpdateTeamQueryRequest represents a request to update a team query

type UpdateUserRequest

type UpdateUserRequest struct {
	Email    string     `json:"email,omitempty"`
	FullName string     `json:"full_name,omitempty"`
	Role     UserRole   `json:"role,omitempty"`
	Status   UserStatus `json:"status,omitempty"`
}

UpdateUserRequest represents a request to update a user

type User

type User struct {
	ID           UserID     `json:"id" db:"id"`
	Email        string     `json:"email" db:"email"`
	FullName     string     `json:"full_name" db:"full_name"`
	Role         UserRole   `json:"role" db:"role"`
	Status       UserStatus `json:"status" db:"status"`
	LastLoginAt  *time.Time `json:"last_login_at,omitempty" db:"last_login_at"`
	LastActiveAt *time.Time `json:"last_active_at,omitempty" db:"last_active_at"`
	Timestamps
}

User represents a user in the system

type UserID

type UserID int

UserID represents a unique user identifier

type UserRole

type UserRole string

UserRole represents the possible user roles

const (
	// UserRoleAdmin represents a user with administrative privileges
	UserRoleAdmin UserRole = "admin"

	// UserRoleMember represents a regular user with standard permissions
	UserRoleMember UserRole = "member"
)

type UserStatus

type UserStatus string

UserStatus represents the possible user statuses

const (
	// UserStatusActive represents an active user account
	UserStatusActive UserStatus = "active"

	// UserStatusInactive represents an inactive/suspended user account
	UserStatusInactive UserStatus = "inactive"
)

type ValidateConnectionRequest

type ValidateConnectionRequest struct {
	ConnectionInfo
	TimestampField string `json:"timestamp_field"`
	SeverityField  string `json:"severity_field"`
}

ValidateConnectionRequest represents a request to validate a connection

Jump to

Keyboard shortcuts

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