port

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

pkg/domain/port/audit_port.go

pkg/domain/port/cache_port.go

Package port defines the interfaces (ports) for the hexagonal architecture. Adapters implement these interfaces to provide concrete functionality for caching, queuing, metrics, storage, privacy, rule evaluation, and more.

pkg/domain/port/enrichment_port.go

pkg/domain/port/metrics_port.go

pkg/domain/port/privacy_port.go

pkg/domain/port/queue_port.go

pkg/domain/port/rule_engine.go

pkg/domain/port/storage_port.go

pkg/domain/port/transformer_port.go

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidPriority     = errors.New("invalid priority")
	ErrQueueEmpty          = errors.New("queue is empty")
	ErrShutdownTimeout     = errors.New("shutdown timeout exceeded")
	ErrQueueFull           = errors.New("queue is full")
	ErrMemoryLimitExceeded = errors.New("memory limit exceeded")
	ErrCircuitOpen         = errors.New("circuit breaker is open")
)

Functions

This section is empty.

Types

type AuditPort

type AuditPort interface {
	// LogDetection logs PII detection events
	// Records what PII was detected, where, and when
	LogDetection(ctx context.Context, userID string, detections []PIIDetectionResult) error

	// LogMasking logs PII masking events
	// Records when PII was masked and in what context
	LogMasking(ctx context.Context, userID string, resource string, count int) error

	// LogTokenization logs tokenization events
	// Records when PII was tokenized (encrypted)
	LogTokenization(ctx context.Context, userID string, resource string, count int) error

	// LogDetokenization logs detokenization events
	// Records when tokens were decrypted back to original PII
	LogDetokenization(ctx context.Context, userID string, resource string, count int) error

	// LogAccess logs data access events
	// Records who accessed what data and when (for audit trail)
	LogAccess(ctx context.Context, userID string, action string, resource string) error

	// LogError logs privacy-related errors
	// Records when privacy operations failed and why
	LogError(ctx context.Context, userID string, errorType string, message string) error

	// GetLogs returns all logged events
	// Used for retrieving audit trail for compliance reports
	GetLogs() []map[string]any

	// ExportLogs exports logs for compliance
	// Returns logs in a format suitable for external auditors
	ExportLogs() string

	// IsCompliant checks if operations are compliant
	// Validates that all required privacy operations were logged
	IsCompliant() bool
}

AuditPort defines the interface for audit logging operations This port is implemented by audit loggers to track privacy-related operations for compliance with regulations like GDPR, HIPAA, and SOC 2.

type CachePort

type CachePort interface {
	// Get retrieves a cached value
	Get(ctx context.Context, key string) (any, error)

	// Set stores a value with TTL
	Set(ctx context.Context, key string, value any, ttl time.Duration) error

	// Delete removes a cached value
	Delete(ctx context.Context, key string) error

	// Clear removes all cached values
	Clear(ctx context.Context) error

	// Stats returns cache statistics
	Stats() *CacheStats
}

CachePort defines caching interface for transformation results

type CacheStats

type CacheStats struct {
	Hits      int64
	Misses    int64
	Evictions int64
	Size      int64
	HitRate   float64
}

CacheStats holds cache metrics

type EnrichmentPort

type EnrichmentPort interface {
	// Enrich enhances single data with external source
	Enrich(ctx context.Context, key string, data map[string]any) (map[string]any, error)

	// BatchEnrich enhances multiple records
	BatchEnrich(ctx context.Context, keys []string, data []map[string]any) ([]map[string]any, error)

	// IsAvailable checks if enrichment service is available
	IsAvailable(ctx context.Context) bool
}

EnrichmentPort defines data enrichment interface

type FunctionExecutorPort

type FunctionExecutorPort interface {
	// Execute runs a custom function with given input
	Execute(ctx context.Context, functionName string, input any) (any, error)

	// ExecuteAsync runs a function asynchronously and returns a job ID
	ExecuteAsync(ctx context.Context, functionName string, input any) (string, error)

	// GetResult retrieves the result of an async execution
	GetResult(ctx context.Context, jobID string) (any, error)

	// IsHealthy checks if the executor service is available
	IsHealthy(ctx context.Context) bool

	// RegisterFunction registers a local function
	RegisterFunction(name string, fn FunctionHandler) error

	// DeregisterFunction removes a registered function
	DeregisterFunction(name string) error
}

FunctionExecutorPort defines the interface for executing custom functions Supports both local and serverless execution

type FunctionHandler

type FunctionHandler func(ctx context.Context, input any) (any, error)

FunctionHandler is the signature for custom functions

type FunctionMetadata

type FunctionMetadata struct {
	Name        string
	Description string
	InputType   string
	OutputType  string
	Timeout     int // seconds
	Retries     int
	Local       bool // true for local, false for serverless
}

FunctionMetadata contains information about a function

type FunctionResult

type FunctionResult struct {
	Success  bool
	Output   any
	Error    string
	Duration int64 // milliseconds
	Executed int64 // unix timestamp
	Retried  int
}

FunctionResult wraps execution result

type MetricsPort

type MetricsPort interface {
	// RecordDuration records operation timing
	RecordDuration(operation string, duration time.Duration)

	// IncrementCounter increments a counter metric
	IncrementCounter(metric string, value int64)

	// SetGauge sets a gauge metric
	SetGauge(metric string, value float64)

	// RecordHistogram records a histogram value
	RecordHistogram(metric string, value float64)
}

MetricsPort defines metrics collection interface

type PIIDetectionResult

type PIIDetectionResult struct {
	Type       PIIType `json:"type"`
	Value      string  `json:"value"`
	StartIdx   int     `json:"start_idx"`
	EndIdx     int     `json:"end_idx"`
	Confidence float64 `json:"confidence"` // 0.0 to 1.0
	Field      string  `json:"field"`      // Field name where PII was found
}

PIIDetectionResult represents a detected PII instance

type PIIType

type PIIType string

PIIType represents different types of Personally Identifiable Information

const (
	PIITypeEmail      PIIType = "email"
	PIITypePhone      PIIType = "phone"
	PIITypeCreditCard PIIType = "credit_card"
	PIITypeSSN        PIIType = "ssn"
	PIITypePassport   PIIType = "passport"
	PIITypeIPAddress  PIIType = "ip_address"
)

type PipelineExecutorPort

type PipelineExecutorPort interface {
	// Execute runs a complete pipeline and returns results
	Execute(ctx context.Context, pipeline *entity.Pipeline, input map[string]any) (*entity.PipelineResult, error)

	// ExecuteStage executes a single stage within a pipeline
	ExecuteStage(ctx context.Context, stage *entity.Stage, input map[string]any) (*entity.StageResult, error)

	// ValidatePipeline validates pipeline structure
	ValidatePipeline(ctx context.Context, pipeline *entity.Pipeline) error

	// GetExecutionPlan returns the optimal execution order for stages
	GetExecutionPlan(ctx context.Context, pipeline *entity.Pipeline) ([][]string, error)
}

PipelineExecutorPort defines the interface for executing pipelines

type PipelineExecutorStats

type PipelineExecutorStats struct {
	TotalPipelines    int64
	SuccessfulCount   int64
	FailedCount       int64
	AverageExecTime   int64 // milliseconds
	FastestExecTime   int64 // milliseconds
	SlowestExecTime   int64 // milliseconds
	ParallelGainRatio float64
}

PipelineExecutorStats tracks execution statistics

type PrivacyPort

type PrivacyPort interface {
	// DetectPII detects all PII types in the given data
	// Returns a list of detected PII instances with their locations
	DetectPII(ctx context.Context, data any) ([]PIIDetectionResult, error)

	// MaskPII returns a masked version of the input data
	// PII values are replaced with masked versions (e.g., u***@domain.com)
	MaskPII(ctx context.Context, data any) (any, error)

	// TokenizePII replaces PII with encrypted tokens
	// The tokens can be later detokenized to recover original values
	TokenizePII(ctx context.Context, data any) (any, error)

	// DetokenizePII recovers original PII from tokens
	DetokenizePII(ctx context.Context, data any, tokens map[string]string) (any, error)
}

PrivacyPort defines the interface for PII detection and masking operations

type QueuePort

type QueuePort interface {
	// Enqueue adds a job to the appropriate priority queue
	Enqueue(ctx context.Context, job *entity.Job) error

	// Dequeue retrieves and removes the next job from specified priority
	Dequeue(ctx context.Context, priority entity.Priority) (*entity.Job, error)

	// GetDepth returns queue length for priority
	GetDepth(priority entity.Priority) int

	// GetStats returns queue statistics
	GetStats() *QueueStats

	// Start begins processing jobs
	Start(ctx context.Context) error

	// Stop gracefully shuts down the queue
	Stop(ctx context.Context) error
}

QueuePort defines the interface for queue implementations This is the PRIMARY external dependency interface

type QueueStats

type QueueStats struct {
	HighDepth      int
	MediumDepth    int
	LowDepth       int
	ProcessedCount int64
	FailedCount    int64
	AvgLatencyMs   float64
	MemoryUsageMB  int64
}

QueueStats holds queue metrics

type RuleEnginePort

type RuleEnginePort interface {
	// Compile takes rule definitions and returns compiled rules
	Compile(ctx context.Context, rules []string) error

	// Evaluate takes data, applies matching rules and transformations, returns modified data and matched rule names
	Evaluate(ctx context.Context, data map[string]any) (map[string]any, []string, error)

	// GetStats returns engine statistics
	GetStats() *RuleEngineStats
}

type RuleEngineStats

type RuleEngineStats struct {
	CompiledRulesCount int64
	EvaluatedCount     int64
	CacheHitRate       float64
}

type StoragePort

type StoragePort interface {
	// Save persists data with key
	Save(ctx context.Context, key string, data any) error

	// Load retrieves persisted data
	Load(ctx context.Context, key string) (any, error)

	// Delete removes persisted data
	Delete(ctx context.Context, key string) error

	// List retrieves keys with prefix
	List(ctx context.Context, prefix string) ([]string, error)
}

StoragePort defines persistent storage interface

type TransformerPort

type TransformerPort interface {
	// Transform applies a transformation to a field value
	// Returns the transformed value or error if transformation fails
	Transform(ctx context.Context, name string, value any, params map[string]any) (any, error)

	// CanTransform checks if a transformer with the given name exists
	CanTransform(name string) bool

	// List returns all available transformer names
	List() []string
}

TransformerPort defines the interface for executing transformations on data

Jump to

Keyboard shortcuts

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