utils

package
v1.0.29 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2025 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TokenErrorInvalid     = "invalid_token"
	TokenErrorExpired     = "token_expired"
	TokenErrorMalformed   = "malformed_token"
	TokenErrorMissing     = "missing_token"
	TokenErrorPermissions = "insufficient_permissions"
)

Common token error codes

Variables

View Source
var ErrDuplicateRequest = errors.New("duplicate request")

ErrDuplicateRequest indicates a duplicate request was detected

Functions

func ExtractTokenFromHeader

func ExtractTokenFromHeader(authHeader string) (string, error)

ExtractTokenFromHeader extracts the JWT token from the Authorization header

func FormatCostReport

func FormatCostReport(breakdown *CostBreakdown, recommendations *OptimizationRecommendations) string

FormatCostReport generates a human-readable cost report

func ValidateAndExtractMerchantID

func ValidateAndExtractMerchantID(authHeader string, validator *SimpleJWTValidator) (string, error)

ValidateAndExtractMerchantID is a convenience function that extracts and validates the token

Types

type AuditLog

type AuditLog struct {
	ID         string         `dynamorm:"pk" json:"id"`
	EntityType string         `dynamorm:"index:gsi-entity,pk" json:"entity_type"`
	EntityID   string         `dynamorm:"index:gsi-entity,sk" json:"entity_id"`
	Action     string         `json:"action"`
	UserID     string         `json:"user_id,omitempty"`
	MerchantID string         `dynamorm:"index:gsi-merchant" json:"merchant_id"`
	IPAddress  string         `json:"ip_address,omitempty"`
	UserAgent  string         `json:"user_agent,omitempty"`
	Before     map[string]any `dynamorm:"json" json:"before,omitempty"`
	After      map[string]any `dynamorm:"json" json:"after,omitempty"`
	Metadata   map[string]any `dynamorm:"json" json:"metadata,omitempty"`
	Timestamp  time.Time      `dynamorm:"created_at" json:"timestamp"`
}

AuditLog represents an audit log entry

type AuditTracker

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

AuditTracker provides audit trail functionality

func NewAuditTracker

func NewAuditTracker(db core.ExtendedDB) *AuditTracker

NewAuditTracker creates a new audit tracker

func (*AuditTracker) ExportAuditLogs

func (a *AuditTracker) ExportAuditLogs(ctx context.Context, merchantID string, format string) ([]byte, error)

ExportAuditLogs exports audit logs in a specific format

func (*AuditTracker) GenerateComplianceReport

func (a *AuditTracker) GenerateComplianceReport(ctx context.Context, merchantID string, startDate, endDate time.Time) (*ComplianceReport, error)

GenerateComplianceReport creates a compliance report

func (*AuditTracker) GetAuditHistory

func (a *AuditTracker) GetAuditHistory(ctx context.Context, entityType, entityID string, limit int) ([]*AuditLog, error)

GetAuditHistory retrieves audit history for an entity

func (*AuditTracker) GetMerchantAuditLogs

func (a *AuditTracker) GetMerchantAuditLogs(ctx context.Context, merchantID string, startTime, endTime time.Time) ([]*AuditLog, error)

GetMerchantAuditLogs retrieves audit logs for a merchant

func (*AuditTracker) Track

func (a *AuditTracker) Track(action string, entityType string, metadata map[string]any) error

Track records an audit event

func (*AuditTracker) TrackChange

func (a *AuditTracker) TrackChange(ctx context.Context, req TrackChangeRequest) error

TrackChange records changes to an entity

type ComplianceAnomaly

type ComplianceAnomaly struct {
	Type        string    `json:"type"`
	Description string    `json:"description"`
	Severity    string    `json:"severity"`
	Timestamp   time.Time `json:"timestamp"`
	EntityID    string    `json:"entity_id,omitempty"`
}

ComplianceAnomaly represents a potential compliance issue

type ComplianceReport

type ComplianceReport struct {
	MerchantID   string              `json:"merchant_id"`
	StartDate    time.Time           `json:"start_date"`
	EndDate      time.Time           `json:"end_date"`
	TotalEvents  int                 `json:"total_events"`
	EventsByType map[string]int      `json:"events_by_type"`
	UserActivity map[string]int      `json:"user_activity"`
	Anomalies    []ComplianceAnomaly `json:"anomalies,omitempty"`
	Generated    time.Time           `json:"generated"`
}

ComplianceReport generates a compliance report

type CostBreakdown

type CostBreakdown struct {
	ReadCost         float64            `json:"read_cost"`
	WriteCost        float64            `json:"write_cost"`
	StorageCost      float64            `json:"storage_cost"`
	GSICost          float64            `json:"gsi_cost"`
	StreamsCost      float64            `json:"streams_cost"`
	BackupCost       float64            `json:"backup_cost"`
	TotalMonthlyCost float64            `json:"total_monthly_cost"`
	TotalYearlyCost  float64            `json:"total_yearly_cost"`
	CostPerItem      float64            `json:"cost_per_item"`
	CostPerRequest   float64            `json:"cost_per_request"`
	Details          map[string]float64 `json:"details"`
}

CostBreakdown provides detailed cost breakdown

type CostEstimator

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

CostEstimator estimates AWS DynamoDB costs

func NewCostEstimator

func NewCostEstimator() *CostEstimator

NewCostEstimator creates a new cost estimator with default pricing

func (*CostEstimator) EstimateMonthly

func (c *CostEstimator) EstimateMonthly(metrics Metrics) *CostBreakdown

EstimateMonthly calculates monthly DynamoDB costs

func (*CostEstimator) EstimatePaymentPlatformCosts

func (c *CostEstimator) EstimatePaymentPlatformCosts(
	monthlyTransactions int64,
	averageQueriesPerTransaction float64,
	retentionDays int,
) *CostBreakdown

EstimatePaymentPlatformCosts estimates costs for a payment platform

func (*CostEstimator) GetOptimizationRecommendations

func (c *CostEstimator) GetOptimizationRecommendations(metrics Metrics, breakdown *CostBreakdown) *OptimizationRecommendations

GetOptimizationRecommendations analyzes metrics and provides recommendations

type IdempotencyMiddleware

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

IdempotencyMiddleware handles idempotent request processing

func NewIdempotencyMiddleware

func NewIdempotencyMiddleware(db core.ExtendedDB, ttl time.Duration) *IdempotencyMiddleware

NewIdempotencyMiddleware creates a new idempotency middleware

func (*IdempotencyMiddleware) CleanupExpired

func (m *IdempotencyMiddleware) CleanupExpired(ctx context.Context) error

CleanupExpired removes expired idempotency records

func (*IdempotencyMiddleware) GenerateKey

func (m *IdempotencyMiddleware) GenerateKey(merchantID string, data any) string

GenerateKey generates an idempotency key from request data

func (*IdempotencyMiddleware) Process

func (m *IdempotencyMiddleware) Process(ctx context.Context, merchantID, key string, fn func() (any, error)) (any, error)

Process executes a function with idempotency protection

type JWTClaims

type JWTClaims struct {
	MerchantID  string   `json:"merchant_id"`
	Email       string   `json:"email"`
	Permissions []string `json:"permissions,omitempty"`
	Issuer      string   `json:"iss,omitempty"`
	Subject     string   `json:"sub,omitempty"`
	Audience    []string `json:"aud,omitempty"`
	ExpiresAt   int64    `json:"exp,omitempty"`
	NotBefore   int64    `json:"nbf,omitempty"`
	IssuedAt    int64    `json:"iat,omitempty"`
	JWTID       string   `json:"jti,omitempty"`
}

JWTClaims represents the custom claims in our JWT tokens

type Metrics

type Metrics struct {
	// Table metrics
	ReadCapacityUnits  int     // Provisioned RCU (0 for on-demand)
	WriteCapacityUnits int     // Provisioned WCU (0 for on-demand)
	StorageGB          float64 // Total storage in GB
	ItemCount          int64   // Number of items
	AverageItemSizeKB  float64 // Average item size in KB

	// Request metrics (for on-demand billing)
	MonthlyReadRequests  int64 // Total read requests per month
	MonthlyWriteRequests int64 // Total write requests per month

	// GSI metrics
	GSICount              int // Number of GSIs
	GSIReadCapacityUnits  int // Total RCU across all GSIs
	GSIWriteCapacityUnits int // Total WCU across all GSIs

	// Additional features
	StreamsEnabled     bool    // DynamoDB Streams enabled
	StreamReadRequests int64   // Monthly stream read requests
	BackupEnabled      bool    // Backup enabled
	BackupStorageGB    float64 // Backup storage in GB

	// Usage patterns
	PeakHoursPerDay int  // Hours of peak usage per day
	IsMultiRegion   bool // Multi-region replication
	RegionCount     int  // Number of regions
}

Metrics represents usage metrics for cost calculation

type OptimizationRecommendations

type OptimizationRecommendations struct {
	Recommendations  []Recommendation `json:"recommendations"`
	PotentialSavings float64          `json:"potential_savings"`
}

OptimizationRecommendations provides cost optimization suggestions

type Recommendation

type Recommendation struct {
	Title       string  `json:"title"`
	Description string  `json:"description"`
	Impact      string  `json:"impact"`
	Savings     float64 `json:"estimated_savings"`
	Effort      string  `json:"effort"`
}

Recommendation represents a cost optimization suggestion

type RetryWorker

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

RetryWorker processes failed webhooks from the retry queue

func NewRetryWorker

func NewRetryWorker(db *dynamorm.DB, sender *WebhookSender, interval time.Duration) *RetryWorker

NewRetryWorker creates a new retry worker

func (*RetryWorker) Start

func (r *RetryWorker) Start()

Start begins processing the retry queue

func (*RetryWorker) Stop

func (r *RetryWorker) Stop()

Stop gracefully shuts down the retry worker

type SimpleJWTValidator

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

SimpleJWTValidator handles JWT validation with HMAC

func NewSimpleJWTValidator

func NewSimpleJWTValidator(secretKey string, issuer, audience string) *SimpleJWTValidator

NewSimpleJWTValidator creates a new JWT validator with HMAC-SHA256

func (*SimpleJWTValidator) ExtractMerchantID

func (v *SimpleJWTValidator) ExtractMerchantID(tokenString string) (string, error)

ExtractMerchantID extracts the merchant ID from a JWT token

func (*SimpleJWTValidator) ValidateToken

func (v *SimpleJWTValidator) ValidateToken(tokenString string) (*JWTClaims, error)

ValidateToken validates a JWT token and returns the claims

type TokenError

type TokenError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Details string `json:"details,omitempty"`
}

TokenError represents a JWT validation error with details

func NewTokenError

func NewTokenError(code, message, details string) *TokenError

NewTokenError creates a new token error

func (*TokenError) Error

func (e *TokenError) Error() string

type TrackChangeRequest

type TrackChangeRequest struct {
	EntityType string         `json:"entity_type"`
	EntityID   string         `json:"entity_id"`
	Action     string         `json:"action"`
	UserID     string         `json:"user_id,omitempty"`
	MerchantID string         `json:"merchant_id"`
	IPAddress  string         `json:"ip_address,omitempty"`
	UserAgent  string         `json:"user_agent,omitempty"`
	Before     map[string]any `json:"before,omitempty"`
	After      map[string]any `json:"after,omitempty"`
	Metadata   map[string]any `json:"metadata,omitempty"`
}

TrackChangeRequest contains details for tracking a change

type WebhookJob

type WebhookJob struct {
	MerchantID string
	EventType  string
	PaymentID  string
	Data       any
}

WebhookJob represents a webhook to be sent

type WebhookPayload

type WebhookPayload struct {
	ID        string    `json:"id"`
	EventType string    `json:"event_type"`
	Created   time.Time `json:"created"`
	Data      any       `json:"data"`
}

WebhookPayload represents the webhook request body

type WebhookSender

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

WebhookSender handles async webhook deliveries

func NewWebhookSender

func NewWebhookSender(db core.ExtendedDB, workers int) *WebhookSender

NewWebhookSender creates a new webhook sender

func (*WebhookSender) Send

func (w *WebhookSender) Send(job *WebhookJob) error

Send queues a webhook for delivery

func (*WebhookSender) Stop

func (w *WebhookSender) Stop()

Stop gracefully shuts down the webhook sender

Jump to

Keyboard shortcuts

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