mdk

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2026 License: MIT Imports: 11 Imported by: 0

README

mdk — Hyperrr Module Development Kit

Go Reference Go Coverage

The mdk package contains the interfaces and types needed to build a Hyperrr module. It has minimal dependencies and is the only Hyperrr package third-party modules need to import.

Install

go get github.com/GoHyperrr/mdk

Implementing a Module

package mymodule

import (
	"context"
	"github.com/GoHyperrr/mdk"
)

func init() {
	mdk.Register(func() mdk.Module { return &MyModule{} })
}

type MyModule struct{ rt mdk.Runtime }

func (m *MyModule) ID() string       { return "mymodule" }
func (m *MyModule) Models() []any    { return []any{&MyModel{}} }
func (m *MyModule) Routes() []mdk.Route { return nil }

func (m *MyModule) Init(ctx context.Context, rt mdk.Runtime) error {
	m.rt = rt
	return nil
}

func (m *MyModule) Shutdown(ctx context.Context) error { return nil }

Configuration Access

Inside your module's Init(ctx context.Context, rt mdk.Runtime) method, you can access environment-expanded configurations defined in hyperrr.yml using:

val, ok := rt.Config("my_module_key").(string)

This preserves full domain isolation since modules only read config keys from the shared mdk.Runtime context.

Then declare it in your hyperrr.yml and run hyperrr build.

Documentation

Index

Constants

View Source
const LockOwnerKey lockContextKey = "lock_owner"
View Source
const Version = "0.1.0"

Variables

View Source
var (
	ErrModuleNotFound    = errors.New("mdk: module not found")
	ErrWorkflowNotFound  = errors.New("mdk: workflow not found")
	ErrRunNotFound       = errors.New("mdk: run not found")
	ErrAlreadyRegistered = errors.New("mdk: already registered")
)
View Source
var (
	ErrLockAcquisitionTimeout = errors.New("lock acquisition timed out")
	ErrLockNotHeld            = errors.New("lock not held")
)

Functions

func Register

func Register(factory Factory)

Register adds a module factory to the global registry. Call this inside an init() function in your module package.

Example:

func init() {
    mdk.Register(func() mdk.Module { return &MyModule{} })
}

func RegisterDialect added in v0.3.0

func RegisterDialect(name string, provider DialectProvider)

RegisterDialect registers a database dialect provider.

func RegisterEventBusProvider added in v0.3.0

func RegisterEventBusProvider(name string, provider BusProvider)

RegisterEventBusProvider registers an event bus provider.

func RegisterLocker added in v0.3.0

func RegisterLocker(name string, provider LockerProvider)

RegisterLocker registers a lock manager provider.

func RegisterStateStore added in v0.3.0

func RegisterStateStore(name string, provider StoreProvider)

RegisterStateStore registers a state store provider.

func Registered

func Registered() map[string]Factory

Registered returns a snapshot of all registered module factories.

func WithActor

func WithActor(ctx context.Context, actor Actor) context.Context

WithActor stores the Actor in the context.

Types

type Actor

type Actor interface {
	GetID() string
	GetType() ActorType
	GetName() string
	GetMetadata() map[string]string
}

Actor represents the minimal interface for any security principal or identity.

func ActorFromContext

func ActorFromContext(ctx context.Context) (Actor, bool)

ActorFromContext retrieves the Actor from the context.

type ActorType

type ActorType string

ActorType represents the type of entity performing an action.

const (
	ActorHuman   ActorType = "HUMAN"
	ActorAIAgent ActorType = "AI_AGENT"
	ActorSystem  ActorType = "SYSTEM"
)

type BaseActor

type BaseActor struct {
	ID       string            `json:"id"`
	Type     ActorType         `json:"type"`
	Name     string            `json:"name"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

BaseActor is a simple, serializable struct that implements mdk.Actor.

func (*BaseActor) GetID

func (b *BaseActor) GetID() string

func (*BaseActor) GetMetadata

func (b *BaseActor) GetMetadata() map[string]string

func (*BaseActor) GetName

func (b *BaseActor) GetName() string

func (*BaseActor) GetType

func (b *BaseActor) GetType() ActorType

type BusProvider added in v0.3.0

type BusProvider func(url string) (EventBusCloser, error)

BusProvider constructor signature for event buses.

func GetEventBusProvider added in v0.3.0

func GetEventBusProvider(name string) (BusProvider, bool)

GetEventBusProvider retrieves an event bus provider.

type DialectProvider added in v0.3.0

type DialectProvider func(dsn string) gorm.Dialector

DialectProvider constructor signature for database dialects.

func GetDialect added in v0.3.0

func GetDialect(name string) (DialectProvider, bool)

GetDialect retrieves a database dialect provider.

type Event

type Event struct {
	ID         string
	Namespace  string // e.g. "commerce.order"
	Type       string // e.g. "created", "cancelled"
	Payload    map[string]any
	OccurredAt time.Time
	TraceID    string
}

Event is an immutable record of something that happened.

type EventBus

type EventBus interface {
	// Publish emits an event to all subscribers.
	Publish(ctx context.Context, e Event) error

	// Subscribe registers a handler for a namespace+type combination.
	// Returns an unsubscribe function.
	Subscribe(namespace, eventType string, handler EventHandler) (unsubscribe func(), err error)
}

EventBus is the pub/sub interface modules use to emit and react to events.

type EventBusCloser added in v0.3.0

type EventBusCloser interface {
	EventBus
	Close() error
}

EventBusCloser extends EventBus to support graceful shutdowns.

type EventHandler

type EventHandler func(ctx context.Context, e Event) error

EventHandler is a function that processes an event.

type Factory

type Factory func() Module

Factory is a constructor function for a Module.

type GetPromptResult

type GetPromptResult struct {
	Description string             `json:"description,omitempty"`
	Messages    []MCPPromptMessage `json:"messages"`
}

GetPromptResult is returned by GetPrompt.

type HTMLUIProvider

type HTMLUIProvider interface {
	RenderHTML(ctx context.Context) (title, html string, err error)
}

HTMLUIProvider can be implemented by modules that want to expose a dashboard UI to MCP.

type JSONMap

type JSONMap map[string]string

JSONMap is a custom type for map[string]string that implements GORM/SQL scanner/valuer.

func (*JSONMap) Scan

func (m *JSONMap) Scan(value interface{}) error

func (JSONMap) Value

func (m JSONMap) Value() (driver.Value, error)

type LineageData

type LineageData interface {
	GetID() string
	GetName() string
	GetState() string
	GetError() string
	GetStartedAt() time.Time
	GetEndedAt() *time.Time
	GetEvents() []Event
}

LineageData defines the minimal interface for accessing workflow execution data.

type Locker added in v0.3.0

type Locker interface {
	Acquire(ctx context.Context, key string, ttl time.Duration, timeout time.Duration) (bool, error)
	Release(ctx context.Context, key string) error
	Close() error
}

Locker defines the interface for distributed locking.

type LockerProvider added in v0.3.0

type LockerProvider func(url string, bucketOrPrefix string) (Locker, error)

LockerProvider constructor signature for lockers.

func GetLocker added in v0.3.0

func GetLocker(name string) (LockerProvider, bool)

GetLocker retrieves a lock manager provider.

type MCPPrompt

type MCPPrompt struct {
	Name        string              `json:"name"`
	Description string              `json:"description,omitempty"`
	Arguments   []MCPPromptArgument `json:"arguments,omitempty"`
}

MCPPrompt represents a reusable prompt template.

type MCPPromptArgument

type MCPPromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

MCPPromptArgument represents an argument for a prompt template.

type MCPPromptMessage

type MCPPromptMessage struct {
	Role    string                  `json:"role"`
	Content MCPPromptMessageContent `json:"content"`
}

MCPPromptMessage represents a prompt message history node.

type MCPPromptMessageContent

type MCPPromptMessageContent struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

MCPPromptMessageContent represents the content inside a prompt message.

type MCPResource

type MCPResource struct {
	URI         string
	Name        string
	Description string
	MimeType    string
}

MCPResource represents a discoverable data resource exposed to AI agents.

type Metadata

type Metadata map[string]interface{}

Metadata represents custom optional JSON metadata stored as a text/json field.

func (*Metadata) Scan

func (m *Metadata) Scan(val interface{}) error

Scan scans value into Metadata.

func (Metadata) Value

func (m Metadata) Value() (driver.Value, error)

Value returns the driver Value.

type Module

type Module interface {
	// ID returns a unique, stable identifier for this module e.g. "order", "auth.emailpass"
	ID() string

	// Models returns GORM model structs for automigration.
	// Return nil if the module has no DB models.
	Models() []any

	// Routes returns HTTP handlers to mount on the server.
	// Return nil if the module exposes no routes.
	Routes() []Route

	// Init is called once when the runtime starts, after DB migration.
	Init(ctx context.Context, rt Runtime) error

	// Shutdown is called on graceful shutdown.
	Shutdown(ctx context.Context) error
}

Module is the interface every hyperrr module must implement. Register your module in an init() function using mdk.Register().

type ObjectStorage added in v0.3.0

type ObjectStorage interface {
	// Upload saves a file to storage and returns its path or URL.
	Upload(ctx context.Context, path string, data io.Reader) (string, error)

	// Open retrieves a file from storage.
	Open(ctx context.Context, path string) (io.ReadCloser, error)

	// Delete removes a file from storage.
	Delete(ctx context.Context, path string) error

	// GetURL returns a public or signed URL for a file.
	GetURL(ctx context.Context, path string) (string, error)
}

ObjectStorage defines the contract for OS-level file handling.

type Projector

type Projector interface {
	ListLineages() []LineageData
	QueryLineages(filter func(LineageData) bool) []LineageData
}

Projector defines the interface for querying execution lineages.

type ProjectorProvider

type ProjectorProvider interface {
	Projector() Projector
}

ProjectorProvider is implemented by modules that expose an execution lineage Projector.

type PromptProvider

type PromptProvider interface {
	ListPrompts(ctx context.Context) ([]MCPPrompt, error)
	GetPrompt(ctx context.Context, name string, arguments map[string]string) (*GetPromptResult, error)
}

PromptProvider is implemented by modules that want to expose custom prompt templates to LLMs.

type ResourceProvider

type ResourceProvider interface {
	ListResources(ctx context.Context) ([]MCPResource, error)
	ReadResource(ctx context.Context, uri string) (string, error)
}

ResourceProvider is implemented by modules that want to expose resources to MCP.

type Route

type Route struct {
	Method  string // "GET", "POST", etc. Empty means all methods.
	Pattern string // e.g. "/orders", "/orders/{id}"
	Handler http.Handler
}

Route is an HTTP route a module wants to register.

type Runtime

type Runtime interface {
	// DB returns the shared GORM database connection.
	DB() *gorm.DB

	// Bus returns the event bus for pub/sub.
	Bus() EventBus

	// Workflows returns the workflow engine.
	Workflows() WorkflowEngine

	// Config returns a config value by key.
	Config(key string) any

	// Logger returns the structured logger.
	Logger() *slog.Logger

	// Module returns a registered and initialized module by its ID.
	Module(id string) (Module, bool)
}

Runtime is provided by hyperrr to every module at Init time. Modules use this to access shared infrastructure.

type Saga

type Saga struct {
	Uses       string `json:"uses" yaml:"uses"`
	IsCritical bool   `json:"is_critical" yaml:"is_critical"`
}

Saga defines the compensation step on rollback.

type StateStore added in v0.3.0

type StateStore interface {
	SaveState(ctx context.Context, execID string, stepID string, state string) error
	GetState(ctx context.Context, execID string) (map[string]string, error)
	InitializeExecution(ctx context.Context, execID string, input []byte) error
	SaveInput(ctx context.Context, execID string, input []byte) error
	GetInput(ctx context.Context, execID string) ([]byte, error)
	SetTTL(ctx context.Context, execID string, ttl time.Duration) error
	SaveStepOutput(ctx context.Context, execID string, stepID string, output []byte) error
	GetStepOutput(ctx context.Context, execID string, stepID string) ([]byte, error)
	ListExecutions(ctx context.Context, state string) ([]string, error)
	RecordEventEmitted(ctx context.Context, execID string, eventType string) error
	IsEventEmitted(ctx context.Context, execID string, eventType string) (bool, error)
}

StateStore defines the interface for checkpointing workflow states.

type Step

type Step struct {
	ID         string   `json:"id" yaml:"id"`
	Name       string   `json:"name" yaml:"name"`
	DependsOn  []string `json:"depends_on" yaml:"depends_on"` // step IDs this step waits for
	MaxRetries int      `json:"max_retries" yaml:"max_retries"`
	Uses       string   `json:"uses" yaml:"uses"` // String-based resolution key
	Saga       *Saga    `json:"saga,omitempty" yaml:"saga,omitempty"`
}

Step is a single node in a workflow DAG.

type StepContext

type StepContext struct {
	Ctx        context.Context
	Runtime    Runtime
	WorkflowID string
	RunID      string
	StepID     string
	Input      map[string]any // output from previous steps, merged
}

StepContext is passed to every step handler and compensation handler.

type StepHandler

type StepHandler func(ctx StepContext) StepResult

StepHandler is the function signature for a workflow step.

type StepResult

type StepResult struct {
	Output map[string]any // merged into input for downstream steps
	Err    error
}

StepResult is returned by a step handler.

type StepStatus

type StepStatus string

StepStatus represents the current state of a workflow step.

const (
	StepPending   StepStatus = "pending"
	StepRunning   StepStatus = "running"
	StepCompleted StepStatus = "completed"
	StepFailed    StepStatus = "failed"
	StepRetrying  StepStatus = "retrying"
	StepSkipped   StepStatus = "skipped"
)

type StoreProvider added in v0.3.0

type StoreProvider func(url string, bucketOrPrefix string) (StateStore, error)

StoreProvider constructor signature for workflow state stores.

func GetStateStore added in v0.3.0

func GetStateStore(name string) (StoreProvider, bool)

GetStateStore retrieves a state store provider.

type TokenValidator

type TokenValidator interface {
	ValidateToken(ctx context.Context, token string) (Actor, error)
}

TokenValidator defines the interface for validating authentication tokens.

type Workflow

type Workflow struct {
	ID          string         `json:"id" yaml:"id"`
	Name        string         `json:"name" yaml:"name"`
	Description string         `json:"description,omitempty" yaml:"description,omitempty"`
	ExposeToAI  bool           `json:"expose_to_ai" yaml:"expose_to_ai"`
	InputSchema map[string]any `json:"input_schema,omitempty" yaml:"input_schema,omitempty"`
	Steps       []Step         `json:"steps" yaml:"steps"`
}

Workflow is a declarative DAG of steps.

type WorkflowEngine

type WorkflowEngine interface {
	// Register makes a workflow available for execution.
	Register(w Workflow) error

	// Execute starts a workflow run and returns a run ID.
	Execute(ctx context.Context, workflowID string, input map[string]any) (runID string, err error)

	// Status returns the status of a specific run.
	Status(ctx context.Context, runID string) (StepStatus, error)

	// Cancel requests cancellation of a running workflow.
	Cancel(ctx context.Context, runID string) error

	// RegisterHandler registers a named step handler for string-based step resolution.
	RegisterHandler(name string, handler StepHandler) error
}

WorkflowEngine registers and executes workflow DAGs.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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