core

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: EUPL-1.2 Imports: 8 Imported by: 0

Documentation

Overview

Package core provides a standardized error handling mechanism for the Core library. It allows for wrapping errors with contextual information, making it easier to trace the origin of an error and provide meaningful feedback.

The design of this package is influenced by the need for a simple, yet powerful way to handle errors that can occur in different layers of the application, from low-level file operations to high-level service interactions.

The key features of this package are:

  • Error wrapping: The Op and an optional Msg field provide context about where and why an error occurred.
  • Stack traces: By wrapping errors, we can build a logical stack trace that is more informative than a raw stack trace.
  • Consistent error handling: Encourages a uniform approach to error handling across the entire codebase.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func App

func App() any

App returns the global application instance. It panics if the Core has not been initialized via SetInstance. This is typically used by GUI runtimes that need global access.

func ClearInstance added in v0.0.4

func ClearInstance()

ClearInstance resets the global Core instance to nil. This is primarily useful for testing to ensure a clean state between tests.

func E

func E(op, msg string, err error) error

E is a helper function to create a new Error. This is the primary way to create errors that will be consumed by the system. For example:

return e.E("config.Load", "failed to load config file", err)

The 'op' parameter should be in the format of 'package.function' or 'service.method'. The 'msg' parameter should be a human-readable message that can be displayed to the user. The 'err' parameter is the underlying error that is being wrapped.

func MustServiceFor

func MustServiceFor[T any](c *Core, name string) T

MustServiceFor retrieves a registered service by name and asserts its type to the given interface T. It panics if the service is not found or cannot be cast to T.

func ServiceFor

func ServiceFor[T any](c *Core, name string) (T, error)

ServiceFor retrieves a registered service by name and asserts its type to the given interface T.

func SetInstance

func SetInstance(c *Core)

SetInstance sets the global Core instance for App() access. This is typically called by GUI runtimes during initialization.

Types

type ActionServiceShutdown

type ActionServiceShutdown struct{}

ActionServiceShutdown is a message sent when the application is shutting down. This allows services to perform cleanup tasks, such as saving state or closing resources.

type ActionServiceStartup

type ActionServiceStartup struct{}

ActionServiceStartup is a message sent when the application's services are starting up. This provides a hook for services to perform initialization tasks.

type Config

type Config interface {
	// Get retrieves a configuration value by key and stores it in the 'out' variable.
	Get(key string, out any) error
	// Set stores a configuration value by key.
	Set(key string, v any) error
}

Config provides access to application configuration.

type Contract

type Contract struct {
	// DontPanic, if true, instructs the Core to recover from panics and return an error instead.
	DontPanic bool
	// DisableLogging, if true, disables all logging from the Core and its services.
	DisableLogging bool
}

Contract specifies the operational guarantees that the Core and its services must adhere to. This is used for configuring panic handling and other resilience features.

type Core

type Core struct {
	App any // GUI runtime (e.g., Wails App) - set by WithApp option

	Features *Features
	// contains filtered or unexported fields
}

Core is the central application object that manages services, assets, and communication.

func GetInstance added in v0.0.4

func GetInstance() *Core

GetInstance returns the global Core instance, or nil if not set. Use this for non-panicking access to the global instance.

func New

func New(opts ...Option) (*Core, error)

New initialises a Core instance using the provided options and performs the necessary setup. It is the primary entry point for creating a new Core application.

Example:

core, err := core.New(
	core.WithService(&MyService{}),
	core.WithAssets(assets),
)

func (*Core) ACTION

func (c *Core) ACTION(msg Message) error

ACTION dispatches a message to all registered IPC handlers. This is the primary mechanism for services to communicate with each other.

func (*Core) Assets

func (c *Core) Assets() embed.FS

Assets returns the embedded filesystem containing the application's assets.

func (*Core) Config

func (c *Core) Config() Config

Config returns the registered Config service.

func (*Core) Core

func (c *Core) Core() *Core

Core returns self, implementing the CoreProvider interface.

func (*Core) Display

func (c *Core) Display() Display

Display returns the registered Display service.

func (*Core) PERFORM

func (c *Core) PERFORM(t Task) (any, bool, error)

PERFORM dispatches a task to handlers until one executes it. Returns (result, handled, error). If no handler responds, handled is false.

func (*Core) QUERY

func (c *Core) QUERY(q Query) (any, bool, error)

QUERY dispatches a query to handlers until one responds. Returns (result, handled, error). If no handler responds, handled is false.

func (*Core) QUERYALL

func (c *Core) QUERYALL(q Query) ([]any, error)

QUERYALL dispatches a query to all handlers and collects all responses. Returns all results from handlers that responded.

func (*Core) RegisterAction

func (c *Core) RegisterAction(handler func(*Core, Message) error)

RegisterAction adds a new IPC handler to the Core.

func (*Core) RegisterActions

func (c *Core) RegisterActions(handlers ...func(*Core, Message) error)

RegisterActions adds multiple IPC handlers to the Core.

func (*Core) RegisterQuery

func (c *Core) RegisterQuery(handler QueryHandler)

RegisterQuery adds a query handler to the Core.

func (*Core) RegisterService

func (c *Core) RegisterService(name string, api any) error

RegisterService adds a new service to the Core.

func (*Core) RegisterTask

func (c *Core) RegisterTask(handler TaskHandler)

RegisterTask adds a task handler to the Core.

func (*Core) Service

func (c *Core) Service(name string) any

Service retrieves a registered service by name. It returns nil if the service is not found.

func (*Core) ServiceShutdown

func (c *Core) ServiceShutdown(ctx context.Context) error

ServiceShutdown is the entry point for the Core service's shutdown lifecycle. It is called by the GUI runtime when the application shuts down.

func (*Core) ServiceStartup

func (c *Core) ServiceStartup(ctx context.Context, options any) error

ServiceStartup is the entry point for the Core service's startup lifecycle. It is called by the GUI runtime when the application starts.

type Display

type Display interface {
	// OpenWindow creates a new window with the given options.
	OpenWindow(opts ...WindowOption) error
}

Display provides access to windowing and visual elements.

type Error

type Error struct {
	// Op is the operation being performed, e.g., "config.Load".
	Op string
	// Msg is a human-readable message explaining the error.
	Msg string
	// Err is the underlying error that was wrapped.
	Err error
}

Error represents a standardized error with operational context.

func (*Error) Error

func (e *Error) Error() string

Error returns the string representation of the error.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap provides compatibility for Go's errors.Is and errors.As functions.

type Features

type Features struct {
	// Flags is a list of enabled feature flags.
	Flags []string
}

Features provides a way to check if a feature is enabled. This is used for feature flagging and conditional logic.

func (*Features) IsEnabled

func (f *Features) IsEnabled(feature string) bool

IsEnabled returns true if the given feature is enabled.

type Message

type Message interface{}

Message is the interface for all messages that can be sent through the Core's IPC system. Any struct can be a message, allowing for structured data to be passed between services. Used with ACTION for fire-and-forget broadcasts.

type Option

type Option func(*Core) error

Option is a function that configures the Core. This is used to apply settings and register services during initialization.

func WithApp

func WithApp(app any) Option

WithApp creates an Option that injects the GUI runtime (e.g., Wails App) into the Core. This is essential for services that need to interact with the GUI runtime.

func WithAssets

func WithAssets(fs embed.FS) Option

WithAssets creates an Option that registers the application's embedded assets. This is necessary for the application to be able to serve its frontend.

func WithName

func WithName(name string, factory func(*Core) (any, error)) Option

WithName creates an option that registers a service with a specific name. This is useful when the service name cannot be inferred from the package path, such as when using anonymous functions as factories. Note: Unlike WithService, this does not automatically discover or register IPC handlers. If your service needs IPC handling, implement HandleIPCEvents and register it manually.

func WithService

func WithService(factory func(*Core) (any, error)) Option

WithService creates an Option that registers a service. It automatically discovers the service name from its package path and registers its IPC handler if it implements a method named `HandleIPCEvents`.

Example:

// In myapp/services/calculator.go
package services

type Calculator struct{}

func (s *Calculator) Add(a, b int) int { return a + b }

// In main.go
import "myapp/services"

core.New(core.WithService(services.NewCalculator))

func WithServiceLock

func WithServiceLock() Option

WithServiceLock creates an Option that prevents any further services from being registered after the Core has been initialized. This is a security measure to prevent late-binding of services that could have unintended consequences.

type Query

type Query interface{}

Query is the interface for read-only requests that return data. Used with QUERY (first responder) or QUERYALL (all responders).

type QueryHandler

type QueryHandler func(*Core, Query) (any, bool, error)

QueryHandler handles Query requests. Returns (result, handled, error). If handled is false, the query will be passed to the next handler.

type Runtime

type Runtime struct {
	Core *Core
	// contains filtered or unexported fields
}

Runtime is the container that holds all instantiated services. Its fields are the concrete types, allowing GUI runtimes to bind them directly. This struct is the primary entry point for the application.

func NewRuntime

func NewRuntime(app any) (*Runtime, error)

NewRuntime creates and wires together all application services. This is the simplest way to create a new Runtime, but it does not allow for the registration of any custom services.

func NewWithFactories

func NewWithFactories(app any, factories map[string]ServiceFactory) (*Runtime, error)

NewWithFactories creates a new Runtime instance using the provided service factories. This is the most flexible way to create a new Runtime, as it allows for the registration of any number of services.

func (*Runtime) ServiceName

func (r *Runtime) ServiceName() string

ServiceName returns the name of the service. This is used by GUI runtimes to identify the service.

func (*Runtime) ServiceShutdown

func (r *Runtime) ServiceShutdown(ctx context.Context)

ServiceShutdown is called by the GUI runtime at application shutdown. This is where the Core's shutdown lifecycle is initiated.

func (*Runtime) ServiceStartup

func (r *Runtime) ServiceStartup(ctx context.Context, options any)

ServiceStartup is called by the GUI runtime at application startup. This is where the Core's startup lifecycle is initiated.

type ServiceFactory

type ServiceFactory func() (any, error)

ServiceFactory defines a function that creates a service instance. This is used to decouple the service creation from the runtime initialization.

type ServiceRuntime

type ServiceRuntime[T any] struct {
	// contains filtered or unexported fields
}

ServiceRuntime is a helper struct embedded in services to provide access to the core application. It is generic and can be parameterized with a service-specific options struct.

func NewServiceRuntime

func NewServiceRuntime[T any](c *Core, opts T) *ServiceRuntime[T]

NewServiceRuntime creates a new ServiceRuntime instance for a service. This is typically called by a service's constructor.

func (*ServiceRuntime[T]) Config

func (r *ServiceRuntime[T]) Config() Config

Config returns the registered Config service from the core application. This is a convenience method for accessing the application's configuration.

func (*ServiceRuntime[T]) Core

func (r *ServiceRuntime[T]) Core() *Core

Core returns the central core instance, providing access to all registered services.

func (*ServiceRuntime[T]) Opts

func (r *ServiceRuntime[T]) Opts() T

Opts returns the service-specific options.

type Startable

type Startable interface {
	OnStartup(ctx context.Context) error
}

Startable is an interface for services that need to perform initialization.

type Stoppable

type Stoppable interface {
	OnShutdown(ctx context.Context) error
}

Stoppable is an interface for services that need to perform cleanup.

type Task

type Task interface{}

Task is the interface for requests that perform side effects. Used with PERFORM (first responder executes).

type TaskHandler

type TaskHandler func(*Core, Task) (any, bool, error)

TaskHandler handles Task requests. Returns (result, handled, error). If handled is false, the task will be passed to the next handler.

type WindowOption

type WindowOption interface {
	Apply(any)
}

WindowOption is an interface for applying configuration options to a window.

Jump to

Keyboard shortcuts

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