utils

package
v7.0.1-rc Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
var ErrIdempotencyConflict = errors.New("idempotency key conflict")

ErrIdempotencyConflict indicates an idempotency key cannot be replayed for the current request: the stored request hash does not match, or the stored record predates request-hash binding. The request must not execute.

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

AuditLog represents an audit log entry

func (AuditLog) TableName

func (AuditLog) TableName() string

TableName keeps this example's audit rows out of the shared "AuditLogs" name the multi-tenant example derives, whose gsi-user-audit index would reject an audit row without a user id.

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 {
	StartDate    time.Time           `json:"start_date"`
	EndDate      time.Time           `json:"end_date"`
	Generated    time.Time           `json:"generated"`
	EventsByType map[string]int      `json:"events_by_type"`
	UserActivity map[string]int      `json:"user_activity"`
	MerchantID   string              `json:"merchant_id"`
	Anomalies    []ComplianceAnomaly `json:"anomalies,omitempty"`
	TotalEvents  int                 `json:"total_events"`
}

ComplianceReport generates a compliance report

type CostBreakdown

type CostBreakdown struct {
	Details          map[string]float64 `json:"details"`
	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"`
}

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, requestHash string, fn func() (any, error)) (any, error)

Process executes a function with idempotency protection. requestHash is a deterministic digest of the validated request payload; an existing record is replayed only when its stored hash matches. An empty hash is not a valid request identity and is refused.

type JWTClaims

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

JWTClaims represents the custom claims in our JWT tokens

func ValidateAndExtractClaims

func ValidateAndExtractClaims(authHeader string, validator *SimpleJWTValidator) (*JWTClaims, error)

ValidateAndExtractClaims validates the bearer token and returns its claims so callers can enforce merchant-scoped permissions, not just the merchant ID.

type Metrics

type Metrics struct {
	GSIReadCapacityUnits  int
	GSIWriteCapacityUnits int
	StorageGB             float64
	ItemCount             int64
	AverageItemSizeKB     float64
	MonthlyReadRequests   int64
	MonthlyWriteRequests  int64
	GSICount              int
	WriteCapacityUnits    int
	RegionCount           int
	ReadCapacityUnits     int
	StreamReadRequests    int64
	PeakHoursPerDay       int
	BackupStorageGB       float64
	BackupEnabled         bool
	IsMultiRegion         bool
	StreamsEnabled        bool
}

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"`
	Effort      string  `json:"effort"`
	Savings     float64 `json:"estimated_savings"`
}

Recommendation represents a cost optimization suggestion

type Replay

type Replay struct {
	StatusCode int
	Body       any
}

Replay is the stored outcome of an idempotent request. A caller that receives ErrDuplicateRequest with a *Replay must return the recorded status and body instead of executing the handler again.

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 {
	Before     map[string]any `json:"before,omitempty"`
	After      map[string]any `json:"after,omitempty"`
	Metadata   map[string]any `json:"metadata,omitempty"`
	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"`
}

TrackChangeRequest contains details for tracking a change

type WebhookJob

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

WebhookJob represents a webhook to be sent

type WebhookPayload

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

WebhookPayload represents the webhook request body

type WebhookSender

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

WebhookSender delivers webhooks synchronously inside the calling invocation. It starts no goroutine and owns no queue: Lambda freezes the execution environment as soon as the handler returns, so a delivery parked on an in-process channel would be frozen with it. Durable hand-off belongs in a queue or stream that outlives the invocation on purpose, not in process memory.

func NewWebhookSender

func NewWebhookSender(db core.ExtendedDB) *WebhookSender

NewWebhookSender creates a new webhook sender. Every connection resolves the destination, rejects any non-public answer, dials the validated address, and checks the address again at the socket boundary. Redirects pass through the same policy before the redirected request is sent.

func (*WebhookSender) SendSync

func (w *WebhookSender) SendSync(ctx context.Context, job *WebhookJob) error

SendSync delivers a webhook synchronously and returns only after the delivery attempt has finished. ctx bounds the whole attempt, and no work is left running when SendSync returns.

Jump to

Keyboard shortcuts

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