storage

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package storage provides the persistence layer abstraction for CVT.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsNotFound

func IsNotFound(err error) bool

IsNotFound checks if the error is an ErrNotFound.

func Register

func Register(storeType StoreType, factory StoreFactory)

Register registers a store factory for a given type. This should be called from init() in implementation packages.

Types

type ComparisonRecord

type ComparisonRecord struct {
	ID              string
	SchemaID        string
	OldVersion      string
	NewVersion      string
	Compatible      bool
	BreakingChanges []*pb.BreakingChange
	ComparedAt      time.Time
}

ComparisonRecord represents a stored schema comparison.

type Config

type Config struct {
	Type            StoreType
	DSN             string        // Data source name
	MaxConnections  int           // Max open connections (postgres only)
	MaxIdleConns    int           // Max idle connections
	ConnMaxLifetime time.Duration // Connection max lifetime

	// Cache settings (for hybrid cache+db mode)
	CacheEnabled    bool
	CacheMaxSchemas int
	CacheTTL        time.Duration

	// Retention settings
	ValidationRetentionDays int // How long to keep validation records
}

Config holds storage configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default configuration for SQLite.

func LoadConfigFromEnv

func LoadConfigFromEnv() Config

LoadConfigFromEnv loads storage configuration from environment variables.

func (Config) IsEnabled

func (c Config) IsEnabled() bool

IsEnabled returns true if persistent storage is enabled.

type ConsumerRecord

type ConsumerRecord struct {
	ID              string          // Internal UUID
	ConsumerID      string          // User-facing identifier (e.g., "order-service")
	ConsumerVersion string          // Consumer's version (e.g., "2.1.0")
	SchemaID        string          // Schema this consumer depends on
	SchemaVersion   string          // Schema version consumer was tested against
	Environment     string          // Environment (dev, staging, prod)
	RegisteredAt    time.Time       // Initial registration timestamp
	LastValidatedAt time.Time       // Last successful validation timestamp
	UsedEndpoints   []EndpointUsage // Which endpoints the consumer uses
}

ConsumerRecord represents a stored consumer registration.

type EndpointUsage

type EndpointUsage struct {
	Method     string   // HTTP method (GET, POST, etc.)
	Path       string   // API path (e.g., "/users/{id}")
	UsedFields []string // Fields used in response (e.g., ["email", "name"])
}

EndpointUsage describes which endpoints and fields a consumer uses.

type ErrNotFound

type ErrNotFound struct {
	Resource string
	ID       string
}

ErrNotFound is returned when a requested record does not exist.

func (*ErrNotFound) Error

func (e *ErrNotFound) Error() string

type ErrorCount

type ErrorCount struct {
	Error string
	Count int64
}

ErrorCount represents an error with its occurrence count.

type ListConsumersFilter

type ListConsumersFilter struct {
	SchemaID    string // Filter by schema ID
	Environment string // Filter by environment
	ConsumerID  string // Filter by consumer ID
}

ListConsumersFilter provides filtering options for consumer queries.

type ListSchemasFilter

type ListSchemasFilter struct {
	Owner       string
	Team        string
	Environment string
	PageSize    int32
	PageToken   string
}

ListSchemasFilter provides filtering options for schema queries.

type ListValidationsFilter

type ListValidationsFilter struct {
	SchemaID    string
	Method      string
	Environment string
	Valid       *bool // nil = all, true = valid only, false = invalid only
	StartTime   time.Time
	EndTime     time.Time
	PageSize    int32
	PageToken   string
}

ListValidationsFilter provides filtering options for validation queries.

type MemoryStore

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

MemoryStore implements storage.Store using in-memory maps. Useful for testing and development.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates a new in-memory store.

func (*MemoryStore) Close

func (s *MemoryStore) Close() error

func (*MemoryStore) DeleteSchema

func (s *MemoryStore) DeleteSchema(ctx context.Context, schemaID string) error

func (*MemoryStore) DeleteSchemaVersion

func (s *MemoryStore) DeleteSchemaVersion(ctx context.Context, schemaID, version string) error

func (*MemoryStore) DeregisterConsumer

func (s *MemoryStore) DeregisterConsumer(ctx context.Context, consumerID, schemaID, environment string) error

func (*MemoryStore) GetComparison

func (s *MemoryStore) GetComparison(ctx context.Context, schemaID, oldVersion, newVersion string) (*ComparisonRecord, error)

func (*MemoryStore) GetConsumer

func (s *MemoryStore) GetConsumer(ctx context.Context, consumerID, schemaID, environment string) (*ConsumerRecord, error)

func (*MemoryStore) GetPreviousVersion

func (s *MemoryStore) GetPreviousVersion(ctx context.Context, schemaID, currentVersion string) (string, error)

func (*MemoryStore) GetSchema

func (s *MemoryStore) GetSchema(ctx context.Context, schemaID string) (*SchemaRecord, error)

func (*MemoryStore) GetSchemaVersion

func (s *MemoryStore) GetSchemaVersion(ctx context.Context, schemaID, version string) (*SchemaRecord, error)

func (*MemoryStore) GetValidationAnalytics

func (s *MemoryStore) GetValidationAnalytics(ctx context.Context, filter ListValidationsFilter) (*ValidationAnalytics, error)

func (*MemoryStore) ListConsumers

func (s *MemoryStore) ListConsumers(ctx context.Context, filter ListConsumersFilter) ([]*ConsumerRecord, error)

func (*MemoryStore) ListSchemaIDs

func (s *MemoryStore) ListSchemaIDs(ctx context.Context) ([]string, error)

func (*MemoryStore) ListSchemas

func (s *MemoryStore) ListSchemas(ctx context.Context, filter ListSchemasFilter) ([]*SchemaRecord, string, int32, error)

func (*MemoryStore) ListValidations

func (s *MemoryStore) ListValidations(ctx context.Context, filter ListValidationsFilter) ([]*ValidationRecord, string, error)

func (*MemoryStore) ListVersions

func (s *MemoryStore) ListVersions(ctx context.Context, schemaID string) ([]string, error)

func (*MemoryStore) Migrate

func (s *MemoryStore) Migrate(ctx context.Context) error

func (*MemoryStore) Ping

func (s *MemoryStore) Ping(ctx context.Context) error

func (*MemoryStore) RecordComparison

func (s *MemoryStore) RecordComparison(ctx context.Context, record *ComparisonRecord) error

func (*MemoryStore) RecordValidation

func (s *MemoryStore) RecordValidation(ctx context.Context, record *ValidationRecord) error

func (*MemoryStore) RegisterConsumer

func (s *MemoryStore) RegisterConsumer(ctx context.Context, record *ConsumerRecord) error

func (*MemoryStore) SetSchema

func (s *MemoryStore) SetSchema(ctx context.Context, record *SchemaRecord) error

func (*MemoryStore) UpdateConsumerValidation

func (s *MemoryStore) UpdateConsumerValidation(ctx context.Context, consumerID, schemaID, environment string, validatedAt time.Time) error

type SchemaRecord

type SchemaRecord struct {
	ID             string              // Internal UUID
	SchemaID       string              // User-facing identifier (e.g., "user-service")
	Version        string              // Semantic version (e.g., "1.2.3")
	Content        string              // Raw OpenAPI content (JSON/YAML)
	ContentHash    string              // SHA256 hash of normalized content
	Document       *openapi3.T         // Parsed document (transient, not stored)
	OpenAPIVersion string              // Detected OpenAPI version (e.g., "3.0.0")
	EndpointCount  int32               // Number of endpoints in schema
	IsLatest       bool                // True if this is the latest version
	RegisteredAt   time.Time           // Creation timestamp
	UpdatedAt      time.Time           // Last update timestamp
	Ownership      *pb.SchemaOwnership // Ownership information
	Environment    string              // Environment tag (dev, staging, prod)
}

SchemaRecord represents a stored schema with all metadata.

type Store

type Store interface {
	// Schema operations
	SetSchema(ctx context.Context, record *SchemaRecord) error
	GetSchema(ctx context.Context, schemaID string) (*SchemaRecord, error)
	GetSchemaVersion(ctx context.Context, schemaID, version string) (*SchemaRecord, error)
	DeleteSchema(ctx context.Context, schemaID string) error
	DeleteSchemaVersion(ctx context.Context, schemaID, version string) error
	ListSchemaIDs(ctx context.Context) ([]string, error)
	ListVersions(ctx context.Context, schemaID string) ([]string, error)
	ListSchemas(ctx context.Context, filter ListSchemasFilter) (schemas []*SchemaRecord, nextPageToken string, totalCount int32, err error)
	GetPreviousVersion(ctx context.Context, schemaID, currentVersion string) (string, error)

	// Validation run operations
	RecordValidation(ctx context.Context, record *ValidationRecord) error
	ListValidations(ctx context.Context, filter ListValidationsFilter) ([]*ValidationRecord, string, error)
	GetValidationAnalytics(ctx context.Context, filter ListValidationsFilter) (*ValidationAnalytics, error)

	// Comparison operations
	RecordComparison(ctx context.Context, record *ComparisonRecord) error
	GetComparison(ctx context.Context, schemaID, oldVersion, newVersion string) (*ComparisonRecord, error)

	// Consumer registry operations
	RegisterConsumer(ctx context.Context, record *ConsumerRecord) error
	GetConsumer(ctx context.Context, consumerID, schemaID, environment string) (*ConsumerRecord, error)
	ListConsumers(ctx context.Context, filter ListConsumersFilter) ([]*ConsumerRecord, error)
	DeregisterConsumer(ctx context.Context, consumerID, schemaID, environment string) error
	UpdateConsumerValidation(ctx context.Context, consumerID, schemaID, environment string, validatedAt time.Time) error

	// Lifecycle
	Migrate(ctx context.Context) error
	Close() error
	Ping(ctx context.Context) error
}

Store defines the persistence layer interface for CVT. All implementations must be thread-safe.

func MustNewStore

func MustNewStore(ctx context.Context, cfg Config) Store

MustNewStore creates a new Store and panics on error.

func NewStore

func NewStore(ctx context.Context, cfg Config) (Store, error)

NewStore creates a new Store based on the provided configuration.

type StoreFactory

type StoreFactory func(ctx context.Context, cfg Config) (Store, error)

StoreFactory is a function that creates a Store from configuration.

type StoreType

type StoreType string

StoreType represents the storage backend type.

const (
	StoreTypeSQLite   StoreType = "sqlite"
	StoreTypePostgres StoreType = "postgres"
	StoreTypeMemory   StoreType = "memory" // For testing
)

type ValidationAnalytics

type ValidationAnalytics struct {
	TotalValidations int64
	PassCount        int64
	FailCount        int64
	PassRate         float64
	TopErrors        []ErrorCount
	ByMethod         map[string]int64
	BySchema         map[string]int64
}

ValidationAnalytics provides aggregated validation statistics.

type ValidationRecord

type ValidationRecord struct {
	ID              string
	SchemaID        string
	SchemaVersion   string
	SchemaHash      string
	RequestMethod   string
	RequestPath     string
	RequestHeaders  map[string]string
	RequestBody     string
	ResponseStatus  int32
	ResponseHeaders map[string]string
	ResponseBody    string
	Valid           bool
	Errors          []string
	DurationMs      int64
	ValidatedAt     time.Time
	Environment     string
	ClientID        string
	ClientIP        string
}

ValidationRecord represents a stored validation run.

Directories

Path Synopsis
Package postgres provides PostgreSQL storage implementation for CVT.
Package postgres provides PostgreSQL storage implementation for CVT.
Package sqlite provides SQLite storage implementation for CVT.
Package sqlite provides SQLite storage implementation for CVT.

Jump to

Keyboard shortcuts

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