contracts

package
v0.90.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: AGPL-3.0 Imports: 4 Imported by: 0

Documentation

Overview

Package contracts defines clean, focused interface contracts for the Orama Network.

This package follows the Interface Segregation Principle (ISP) by providing small, focused interfaces that define clear contracts between components. Each interface represents a specific capability or service without exposing implementation details.

Design Principles:

  • Small, focused interfaces (ISP compliance)
  • No concrete type leakage in signatures
  • Comprehensive documentation for all public methods
  • Domain-aligned contracts (storage, cache, database, auth, serverless, etc.)

Interfaces:

  • StorageProvider: Decentralized content storage (IPFS)
  • CacheProvider/CacheClient: Distributed caching (Olric)
  • DatabaseClient: ORM-like database operations (RQLite)
  • AuthService: Wallet-based authentication and JWT management
  • FunctionExecutor: WebAssembly function execution
  • FunctionRegistry: Function metadata and bytecode storage
  • PubSubService: Topic-based messaging
  • PeerDiscovery: Peer discovery and connection management
  • Logger: Structured logging

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AddResponse

type AddResponse struct {
	Name string `json:"name"`
	Cid  string `json:"cid"`
	Size int64  `json:"size"`
}

AddResponse represents the result of adding content to storage.

type AuthService

type AuthService interface {
	// CreateNonce generates a cryptographic nonce for wallet authentication.
	// The nonce is valid for a limited time and used to prevent replay attacks.
	// wallet is the wallet address, purpose describes the nonce usage,
	// and namespace isolates nonces across different contexts.
	CreateNonce(ctx context.Context, wallet, purpose, namespace string) (string, error)

	// VerifySignature validates a cryptographic signature from a wallet.
	// Supports multiple blockchain types (ETH, SOL) for signature verification.
	// Returns true if the signature is valid for the given nonce.
	VerifySignature(ctx context.Context, wallet, nonce, signature, chainType string) (bool, error)

	// IssueTokens generates a new access token and refresh token pair.
	// Access tokens are short-lived (typically 15 minutes).
	// Refresh tokens are long-lived (typically 30 days).
	// Returns: accessToken, refreshToken, expirationUnix, error.
	IssueTokens(ctx context.Context, wallet, namespace string) (string, string, int64, error)

	// RefreshToken validates a refresh token and issues a new access token.
	// Returns: newAccessToken, subject (wallet), expirationUnix, error.
	RefreshToken(ctx context.Context, refreshToken, namespace string) (string, string, int64, error)

	// RevokeToken invalidates a refresh token or all tokens for a subject.
	// If token is provided, revokes that specific token.
	// If all is true and subject is provided, revokes all tokens for that subject.
	RevokeToken(ctx context.Context, namespace, token string, all bool, subject string) error

	// ParseAndVerifyJWT validates a JWT access token and returns its claims.
	// Verifies signature, expiration, and issuer.
	ParseAndVerifyJWT(token string) (*JWTClaims, error)

	// GenerateJWT creates a new signed JWT with the specified claims and TTL.
	// Returns: token, expirationUnix, error.
	GenerateJWT(namespace, subject string, ttl time.Duration) (string, int64, error)

	// RegisterApp registers a new client application with the gateway.
	// Returns an application ID that can be used for OAuth flows.
	RegisterApp(ctx context.Context, wallet, namespace, name, publicKey string) (string, error)

	// GetOrCreateAPIKey retrieves an existing API key or creates a new one.
	// API keys provide programmatic access without interactive authentication.
	GetOrCreateAPIKey(ctx context.Context, wallet, namespace string) (string, error)

	// ResolveNamespaceID ensures a namespace exists and returns its internal ID.
	// Creates the namespace if it doesn't exist.
	ResolveNamespaceID(ctx context.Context, namespace string) (interface{}, error)
}

AuthService handles wallet-based authentication and authorization. Provides nonce generation, signature verification, JWT lifecycle management, and application registration for the gateway.

type CacheClient

type CacheClient interface {
	CacheProvider

	// UnderlyingClient returns the native cache client for advanced operations.
	// The returned client can be used to access DMap operations like Get, Put, Delete, etc.
	// Return type is interface{} to avoid leaking concrete implementation details.
	UnderlyingClient() interface{}
}

CacheClient provides extended cache operations beyond basic connectivity. This interface is intentionally kept minimal as cache operations are typically accessed through the underlying client's DMap API.

type CacheProvider

type CacheProvider interface {
	// Health checks if the cache service is operational.
	// Returns an error if the service is unavailable or cannot be reached.
	Health(ctx context.Context) error

	// Close gracefully shuts down the cache client and releases resources.
	Close(ctx context.Context) error
}

CacheProvider defines the interface for distributed cache operations. Implementations provide a distributed key-value store with eventual consistency.

type DatabaseClient

type DatabaseClient interface {
	// Query executes a SELECT query and scans results into dest.
	// dest must be a pointer to a slice of structs or []map[string]any.
	Query(ctx context.Context, dest any, query string, args ...any) error

	// Exec executes a write statement (INSERT/UPDATE/DELETE) and returns the result.
	Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

	// FindBy retrieves multiple records matching the criteria.
	// dest must be a pointer to a slice, table is the table name,
	// criteria is a map of column->value filters, and opts customize the query.
	FindBy(ctx context.Context, dest any, table string, criteria map[string]any, opts ...FindOption) error

	// FindOneBy retrieves a single record matching the criteria.
	// dest must be a pointer to a struct or map.
	FindOneBy(ctx context.Context, dest any, table string, criteria map[string]any, opts ...FindOption) error

	// Save inserts or updates an entity based on its primary key.
	// If the primary key is zero, performs an INSERT.
	// If the primary key is set, performs an UPDATE.
	Save(ctx context.Context, entity any) error

	// Remove deletes an entity by its primary key.
	Remove(ctx context.Context, entity any) error

	// Repository returns a generic repository for a table.
	// Return type is any to avoid exposing generic type parameters in the interface.
	Repository(table string) any

	// CreateQueryBuilder creates a fluent query builder for advanced queries.
	// Supports joins, where clauses, ordering, grouping, and pagination.
	CreateQueryBuilder(table string) QueryBuilder

	// Tx executes a function within a database transaction.
	// If fn returns an error, the transaction is rolled back.
	// Otherwise, it is committed.
	Tx(ctx context.Context, fn func(tx DatabaseTransaction) error) error
}

DatabaseClient defines the interface for ORM-like database operations. Provides both raw SQL execution and fluent query building capabilities.

type DatabaseTransaction

type DatabaseTransaction interface {
	// Query executes a SELECT query within the transaction.
	Query(ctx context.Context, dest any, query string, args ...any) error

	// Exec executes a write statement within the transaction.
	Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

	// CreateQueryBuilder creates a query builder that executes within the transaction.
	CreateQueryBuilder(table string) QueryBuilder

	// Save inserts or updates an entity within the transaction.
	Save(ctx context.Context, entity any) error

	// Remove deletes an entity within the transaction.
	Remove(ctx context.Context, entity any) error
}

DatabaseTransaction provides database operations within a transaction context.

type DiscoveryConfig

type DiscoveryConfig struct {
	// DiscoveryInterval is how often to run peer discovery.
	DiscoveryInterval time.Duration

	// MaxConnections is the maximum number of new connections per discovery round.
	MaxConnections int
}

DiscoveryConfig contains configuration for peer discovery.

type Field

type Field interface {
	// Key returns the field's key name.
	Key() string

	// Value returns the field's value.
	Value() interface{}
}

Field represents a structured logging field with a key and value. Implementations typically use zap.Field or similar structured logging types.

type FindOption

type FindOption func(q QueryBuilder)

FindOption is a function that configures a FindBy/FindOneBy query.

type Function

type Function struct {
	ID                string         `json:"id"`
	Name              string         `json:"name"`
	Namespace         string         `json:"namespace"`
	Version           int            `json:"version"`
	WASMCID           string         `json:"wasm_cid"`
	SourceCID         string         `json:"source_cid,omitempty"`
	MemoryLimitMB     int            `json:"memory_limit_mb"`
	TimeoutSeconds    int            `json:"timeout_seconds"`
	IsPublic          bool           `json:"is_public"`
	RetryCount        int            `json:"retry_count"`
	RetryDelaySeconds int            `json:"retry_delay_seconds"`
	DLQTopic          string         `json:"dlq_topic,omitempty"`
	Status            FunctionStatus `json:"status"`
	CreatedAt         time.Time      `json:"created_at"`
	UpdatedAt         time.Time      `json:"updated_at"`
	CreatedBy         string         `json:"created_by"`
}

Function represents a deployed serverless function with its metadata.

type FunctionDefinition

type FunctionDefinition struct {
	Name              string            `json:"name"`
	Namespace         string            `json:"namespace"`
	Version           int               `json:"version,omitempty"`
	MemoryLimitMB     int               `json:"memory_limit_mb,omitempty"`
	TimeoutSeconds    int               `json:"timeout_seconds,omitempty"`
	IsPublic          bool              `json:"is_public,omitempty"`
	RetryCount        int               `json:"retry_count,omitempty"`
	RetryDelaySeconds int               `json:"retry_delay_seconds,omitempty"`
	DLQTopic          string            `json:"dlq_topic,omitempty"`
	EnvVars           map[string]string `json:"env_vars,omitempty"`
}

FunctionDefinition contains the configuration for deploying a function.

type FunctionExecutor

type FunctionExecutor interface {
	// Execute runs a function with the given input and returns the output.
	// fn contains the function metadata, input is the function's input data,
	// and invCtx provides context about the invocation (caller, trigger type, etc.).
	Execute(ctx context.Context, fn *Function, input []byte, invCtx *InvocationContext) ([]byte, error)

	// Precompile compiles a WASM module and caches it for faster execution.
	// wasmCID is the content identifier, wasmBytes is the raw WASM bytecode.
	// Precompiling reduces cold-start latency for subsequent invocations.
	Precompile(ctx context.Context, wasmCID string, wasmBytes []byte) error

	// Invalidate removes a compiled module from the cache.
	// Call this when a function is updated or deleted.
	Invalidate(wasmCID string)
}

FunctionExecutor handles the execution of WebAssembly serverless functions. Manages compilation, caching, and runtime execution of WASM modules.

type FunctionRegistry

type FunctionRegistry interface {
	// Register deploys a new function or updates an existing one.
	// fn contains the function definition, wasmBytes is the compiled WASM code.
	// Returns the old function definition if it was updated, or nil for new registrations.
	Register(ctx context.Context, fn *FunctionDefinition, wasmBytes []byte) (*Function, error)

	// Get retrieves a function by name and optional version.
	// If version is 0, returns the latest active version.
	// Returns an error if the function is not found.
	Get(ctx context.Context, namespace, name string, version int) (*Function, error)

	// List returns all active functions in a namespace.
	// Returns only the latest version of each function.
	List(ctx context.Context, namespace string) ([]*Function, error)

	// Delete marks a function as inactive (soft delete).
	// If version is 0, marks all versions as inactive.
	Delete(ctx context.Context, namespace, name string, version int) error

	// GetWASMBytes retrieves the compiled WASM bytecode for a function.
	// wasmCID is the content identifier returned during registration.
	GetWASMBytes(ctx context.Context, wasmCID string) ([]byte, error)

	// GetLogs retrieves execution logs for a function.
	// limit constrains the number of log entries returned.
	GetLogs(ctx context.Context, namespace, name string, limit int) ([]LogEntry, error)
}

FunctionRegistry manages function metadata and bytecode storage. Responsible for CRUD operations on function definitions.

type FunctionStatus

type FunctionStatus string

FunctionStatus represents the current state of a deployed function.

const (
	FunctionStatusActive   FunctionStatus = "active"
	FunctionStatusInactive FunctionStatus = "inactive"
	FunctionStatusError    FunctionStatus = "error"
)

type HandlerID

type HandlerID string

HandlerID uniquely identifies a subscription handler. Each Subscribe call generates a new HandlerID, allowing multiple independent subscriptions to the same topic.

type InvocationContext

type InvocationContext struct {
	RequestID    string            `json:"request_id"`
	FunctionID   string            `json:"function_id"`
	FunctionName string            `json:"function_name"`
	Namespace    string            `json:"namespace"`
	CallerWallet string            `json:"caller_wallet,omitempty"`
	TriggerType  TriggerType       `json:"trigger_type"`
	WSClientID   string            `json:"ws_client_id,omitempty"`
	EnvVars      map[string]string `json:"env_vars,omitempty"`
}

InvocationContext provides context for a function invocation.

type JWTClaims

type JWTClaims struct {
	Iss       string `json:"iss"`       // Issuer
	Sub       string `json:"sub"`       // Subject (wallet address)
	Aud       string `json:"aud"`       // Audience
	Iat       int64  `json:"iat"`       // Issued At
	Nbf       int64  `json:"nbf"`       // Not Before
	Exp       int64  `json:"exp"`       // Expiration
	Namespace string `json:"namespace"` // Namespace isolation
}

JWTClaims represents the claims contained in a JWT access token.

type LogEntry

type LogEntry struct {
	Level     string    `json:"level"`
	Message   string    `json:"message"`
	Timestamp time.Time `json:"timestamp"`
}

LogEntry represents a log message from a function execution.

type Logger

type Logger interface {
	// Debug logs a debug-level message with optional fields.
	Debug(msg string, fields ...Field)

	// Info logs an info-level message with optional fields.
	Info(msg string, fields ...Field)

	// Warn logs a warning-level message with optional fields.
	Warn(msg string, fields ...Field)

	// Error logs an error-level message with optional fields.
	Error(msg string, fields ...Field)

	// Fatal logs a fatal-level message and terminates the application.
	Fatal(msg string, fields ...Field)

	// With creates a child logger with additional context fields.
	// The returned logger includes all parent fields plus the new ones.
	With(fields ...Field) Logger

	// Sync flushes any buffered log entries.
	// Should be called before application shutdown.
	Sync() error
}

Logger defines a structured logging interface. Provides leveled logging with contextual fields for debugging and monitoring.

type LoggerFactory

type LoggerFactory interface {
	// NewLogger creates a new logger with the given name.
	// The name is typically used as a component identifier in logs.
	NewLogger(name string) Logger

	// NewLoggerWithFields creates a new logger with pre-set context fields.
	NewLoggerWithFields(name string, fields ...Field) Logger
}

LoggerFactory creates logger instances with configuration.

type MessageHandler

type MessageHandler func(topic string, data []byte) error

MessageHandler processes messages received from a subscribed topic. Each handler receives the topic name and message data. Multiple handlers for the same topic each receive a copy of the message. Handlers should return an error only for critical failures.

type PeerDiscovery

type PeerDiscovery interface {
	// Start begins periodic peer discovery with the given configuration.
	// Runs discovery in the background until Stop is called.
	Start(config DiscoveryConfig) error

	// Stop halts the peer discovery process and cleans up resources.
	Stop()

	// StartProtocolHandler registers the peer exchange protocol handler.
	// Must be called to enable incoming peer exchange requests.
	StartProtocolHandler()

	// TriggerPeerExchange manually triggers peer exchange with all connected peers.
	// Useful for bootstrapping or refreshing peer metadata.
	// Returns the number of peers from which metadata was collected.
	TriggerPeerExchange(ctx context.Context) int
}

PeerDiscovery handles peer discovery and connection management. Provides mechanisms for finding and connecting to network peers without relying on a DHT (Distributed Hash Table).

type PinResponse

type PinResponse struct {
	Cid  string `json:"cid"`
	Name string `json:"name"`
}

PinResponse represents the result of a pin operation.

type PinStatus

type PinStatus struct {
	Cid               string   `json:"cid"`
	Name              string   `json:"name"`
	Status            string   `json:"status"` // "pinned", "pinning", "queued", "unpinned", "error"
	ReplicationMin    int      `json:"replication_min"`
	ReplicationMax    int      `json:"replication_max"`
	ReplicationFactor int      `json:"replication_factor"`
	Peers             []string `json:"peers"` // List of peer IDs storing the content
	Error             string   `json:"error,omitempty"`
}

PinStatus represents the replication status of pinned content.

type PubSubService

type PubSubService interface {
	// Publish sends a message to all subscribers of a topic.
	// The message is delivered asynchronously to all registered handlers.
	Publish(ctx context.Context, topic string, data []byte) error

	// Subscribe registers a handler for messages on a topic.
	// Multiple handlers can be registered for the same topic.
	// Returns a HandlerID that can be used to unsubscribe.
	Subscribe(ctx context.Context, topic string, handler MessageHandler) (HandlerID, error)

	// Unsubscribe removes a specific handler from a topic.
	// The subscription is reference-counted per topic.
	Unsubscribe(ctx context.Context, topic string, handlerID HandlerID) error

	// Close gracefully shuts down the pubsub service and releases resources.
	Close(ctx context.Context) error
}

PubSubService defines the interface for publish-subscribe messaging. Provides topic-based message broadcasting with support for multiple handlers.

type QueryBuilder

type QueryBuilder interface {
	// Select specifies which columns to retrieve (default: *).
	Select(cols ...string) QueryBuilder

	// Alias sets a table alias for the query.
	Alias(alias string) QueryBuilder

	// Where adds a WHERE condition (same as AndWhere).
	Where(expr string, args ...any) QueryBuilder

	// AndWhere adds a WHERE condition with AND conjunction.
	AndWhere(expr string, args ...any) QueryBuilder

	// OrWhere adds a WHERE condition with OR conjunction.
	OrWhere(expr string, args ...any) QueryBuilder

	// InnerJoin adds an INNER JOIN clause.
	InnerJoin(table string, on string) QueryBuilder

	// LeftJoin adds a LEFT JOIN clause.
	LeftJoin(table string, on string) QueryBuilder

	// Join adds a JOIN clause (default join type).
	Join(table string, on string) QueryBuilder

	// GroupBy adds a GROUP BY clause.
	GroupBy(cols ...string) QueryBuilder

	// OrderBy adds an ORDER BY clause.
	// Supports expressions like "name ASC", "created_at DESC".
	OrderBy(exprs ...string) QueryBuilder

	// Limit sets the maximum number of rows to return.
	Limit(n int) QueryBuilder

	// Offset sets the number of rows to skip.
	Offset(n int) QueryBuilder

	// Build constructs the final SQL query and returns it with positional arguments.
	Build() (query string, args []any)

	// GetMany executes the query and scans results into dest (pointer to slice).
	GetMany(ctx context.Context, dest any) error

	// GetOne executes the query with LIMIT 1 and scans into dest (pointer to struct/map).
	GetOne(ctx context.Context, dest any) error
}

QueryBuilder provides a fluent interface for building SQL queries.

type StorageProvider

type StorageProvider interface {
	// Add uploads content to the storage network and returns metadata.
	// The content is read from the provided reader and associated with the given name.
	// Returns information about the stored content including its CID (Content IDentifier).
	Add(ctx context.Context, reader io.Reader, name string) (*AddResponse, error)

	// Pin ensures content is persistently stored across the network.
	// The CID identifies the content, name provides a human-readable label,
	// and replicationFactor specifies how many nodes should store the content.
	Pin(ctx context.Context, cid string, name string, replicationFactor int) (*PinResponse, error)

	// PinStatus retrieves the current replication status of pinned content.
	// Returns detailed information about which peers are storing the content
	// and the current state of the pin operation.
	PinStatus(ctx context.Context, cid string) (*PinStatus, error)

	// Get retrieves content from the storage network by its CID.
	// The ipfsAPIURL parameter specifies which IPFS API endpoint to query.
	// Returns a ReadCloser that must be closed by the caller.
	Get(ctx context.Context, cid string, ipfsAPIURL string) (io.ReadCloser, error)

	// Unpin removes a pin, allowing the content to be garbage collected.
	// This does not immediately delete the content but makes it eligible for removal.
	Unpin(ctx context.Context, cid string) error

	// Health checks if the storage service is operational.
	// Returns an error if the service is unavailable or unhealthy.
	Health(ctx context.Context) error

	// GetPeerCount returns the number of storage peers in the cluster.
	// Useful for monitoring cluster health and connectivity.
	GetPeerCount(ctx context.Context) (int, error)

	// Close gracefully shuts down the storage client and releases resources.
	Close(ctx context.Context) error
}

StorageProvider defines the interface for decentralized storage operations. Implementations typically use IPFS Cluster for distributed content storage.

type TriggerType

type TriggerType string

TriggerType identifies the type of event that triggered a function invocation.

const (
	TriggerTypeHTTP      TriggerType = "http"
	TriggerTypeWebSocket TriggerType = "websocket"
	TriggerTypeCron      TriggerType = "cron"
	TriggerTypeDatabase  TriggerType = "database"
	TriggerTypePubSub    TriggerType = "pubsub"
	TriggerTypeTimer     TriggerType = "timer"
	TriggerTypeJob       TriggerType = "job"
)

Jump to

Keyboard shortcuts

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