rpc

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrValidation         = "validation_error"
	ErrUnauthorized       = "unauthorized"
	ErrForbidden          = "forbidden"
	ErrNotFound           = "not_found"
	ErrFunctionNotFound   = "function_not_found"
	ErrInvalidBody        = "invalid_body"
	ErrInvalidContentType = "invalid_content_type"
	ErrPayloadTooLarge    = "payload_too_large"
	ErrConflict           = "conflict"
	ErrRateLimited        = "rate_limited"
	ErrTimeout            = "timeout"
	ErrInternal           = "internal_error"
	ErrSchemaMismatch     = "schema_mismatch"
)

Standard Error Codes matching the CellsWeb RPC protocol

Variables

This section is empty.

Functions

func FormatFunctionKey

func FormatFunctionKey(namespace, functionName string) string

FormatFunctionKey computes the unique lookup key supporting both standard and nested dot-names

func GetContext

func GetContext[T any](c *Context, key string) (T, bool)

GetContext is a generic helper to retrieve a strictly-typed context value

func InjectFilesForTest added in v1.0.1

func InjectFilesForTest(target any, raw map[string]any)

InjectFilesForTest exposes injectFilesIntoStruct for test suites

func ParseMultipartPhase1

func ParseMultipartPhase1(reqCtx *fasthttp.RequestCtx) (namespace, functionName string, err error)

ParseMultipartPhase1 parses only the routing keys (namespace, functionName) from multipart stream without reading any files

func RegisterFunction

func RegisterFunction(fn *FunctionDefinition)

RegisterFunction adds a function to the global registry (usable in package init())

func RegisterMiddleware

func RegisterMiddleware(name, description string, fn MiddlewareFn, optionsSchema *schema.SchemaRule, headersSchema *schema.SchemaRule)

RegisterMiddleware registers a reusable middleware in the global registry

func SanitizeFilename

func SanitizeFilename(name string) string

SanitizeFilename strips directory traversal sequences (../, ..\), null bytes, and path delimiters

func SplitFunctionKey

func SplitFunctionKey(key string) (string, string)

SplitFunctionKey parses a combined key "admin.products.create" into namespace and functionName

Types

type AppError

type AppError struct {
	Code    string                  `json:"code"`
	Message string                  `json:"message"`
	Details []ValidationErrorDetail `json:"details,omitempty"`
}

AppError represents a uniform business, validation, or operational RPC error

func NewError

func NewError(code, message string) *AppError

NewError creates a new AppError with code and message

func NewValidationError

func NewValidationError(message string, details []ValidationErrorDetail) *AppError

NewValidationError creates an AppError with field-level schema validation details

func (*AppError) Error

func (e *AppError) Error() string

type CallOptions

type CallOptions struct {
	Headers  map[string]string
	ClientIP string
}

CallOptions configures in-memory RPC execution parameters

type Config

type Config struct {
	// RpcPath is the required endpoint path (e.g. "/rpc"). Must be non-empty. No silent fallback.
	RpcPath string

	// Port is the listening port (e.g. 4000)
	Port int

	// Host to bind to (e.g. "0.0.0.0" or "127.0.0.1")
	Host string

	// CORS is the required CORS policy. Must be explicitly provided. No silent fallback.
	CORS *CorsConfig

	// DocsEnabled controls whether the interactive documentation UI (/docs) is active
	DocsEnabled bool

	// DocsPath is the custom path for docs (e.g. "/docs"). Defaults to "/docs" if DocsEnabled is true.
	DocsPath string

	// MaxRequestBodySize in bytes (e.g. 10 * 1024 * 1024 for 10MB).
	MaxRequestBodySize int

	// MaxMultipartFiles is the maximum total number of files allowed in a single multipart request (default: 20).
	MaxMultipartFiles int

	// UseHttpStatusCodes maps RPC error codes to standard HTTP status codes (e.g. 400, 401, 404, 429, 500)
	// for enhanced integration with cloud monitoring, load balancers, and APM tools.
	// Defaults to false (standard uniform HTTP 200 RPC protocol).
	UseHttpStatusCodes bool

	// TelemetryHooks are optional callbacks for external metrics, Sentry, or batch loggers
	TelemetryHooks []TelemetryHook

	// TrustProxy determines whether X-Forwarded-For is trusted for client IP extraction
	TrustProxy bool

	// TrustedProxies is a list of trusted upstream proxy IP addresses or CIDRs
	TrustedProxies []string

	// ReadTimeout is the maximum duration for reading the entire request (default: 30s)
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration for writing the response (default: 30s)
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled (default: 60s)
	IdleTimeout time.Duration
}

Config defines the strict configuration for CoreRPC

func (*Config) Validate

func (c *Config) Validate() error

Validate ensures all mandatory configuration settings are present without ambiguous defaults

type Context

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

Context represents the request lifecycle context and dependency injection container

func NewContext

func NewContext(reqCtx *fasthttp.RequestCtx, requestID string, trustProxy bool) *Context

NewContext creates a new Context for an incoming fasthttp request

func (*Context) Cleanup

func (c *Context) Cleanup()

Cleanup releases all temporary files associated with this context

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP returns the client IP address

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get retrieves a value from the request context

func (*Context) Header

func (c *Context) Header(name string) string

Header returns a request header by case-insensitive name

func (*Context) Headers

func (c *Context) Headers() map[string]string

Headers returns a copy of all request headers

func (*Context) MustGet

func (c *Context) MustGet(key string) any

MustGet retrieves a value or panics if it does not exist

func (*Context) Raw

func (c *Context) Raw() *fasthttp.RequestCtx

Raw returns the underlying fasthttp RequestCtx (or nil for in-process tests)

func (*Context) RequestID

func (c *Context) RequestID() string

RequestID returns the unique correlation ID for this request

func (*Context) Set

func (c *Context) Set(key string, value any)

Set stores a value in the request context (dependency injection)

func (*Context) TrackFile

func (c *Context) TrackFile(f *UploadedFile)

TrackFile registers an uploaded file for automatic cleanup when the request completes

type CoreRPC

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

CoreRPC is the high-performance RPC server engine built on fasthttp

func New

func New(config Config) (*CoreRPC, error)

New creates and strictly validates a new CoreRPC server instance

func (*CoreRPC) CallInMemory

func (app *CoreRPC) CallInMemory(functionKey string, input any, outputTarget any, opts ...CallOptions) error

CallInMemory executes an RPC function in-process without network overhead

func (*CoreRPC) DELETE

func (app *CoreRPC) DELETE(path string, handler HTTPHandlerFunc) *CoreRPC

func (*CoreRPC) Functions

func (app *CoreRPC) Functions() map[string]*FunctionDefinition

Functions returns a copy of all registered functions (used by docs engine)

func (*CoreRPC) GET

func (app *CoreRPC) GET(path string, handler HTTPHandlerFunc) *CoreRPC

func (*CoreRPC) Handler

func (app *CoreRPC) Handler() fasthttp.RequestHandler

Handler returns the primary fasthttp RequestHandler

func (*CoreRPC) ListenAndServe

func (app *CoreRPC) ListenAndServe() error

ListenAndServe starts the server with graceful shutdown handling

func (*CoreRPC) Middlewares

func (app *CoreRPC) Middlewares() map[string]*RegisteredMiddleware

Middlewares returns a copy of all registered middlewares (used by docs engine)

func (*CoreRPC) NetHTTPHandler

func (app *CoreRPC) NetHTTPHandler() http.Handler

NetHTTPHandler provides standard net/http.Handler compatibility

func (*CoreRPC) POST

func (app *CoreRPC) POST(path string, handler HTTPHandlerFunc) *CoreRPC

func (*CoreRPC) PUT

func (app *CoreRPC) PUT(path string, handler HTTPHandlerFunc) *CoreRPC

func (*CoreRPC) RegisterFunction

func (app *CoreRPC) RegisterFunction(fn *FunctionDefinition) *CoreRPC

RegisterFunction registers a function directly on the server instance

func (*CoreRPC) RegisterMiddleware

func (app *CoreRPC) RegisterMiddleware(name, description string, fn MiddlewareFn, optionsSchema *schema.SchemaRule, headersSchema *schema.SchemaRule) *CoreRPC

RegisterMiddleware registers a reusable middleware on the server instance

func (*CoreRPC) Serve added in v1.0.1

func (app *CoreRPC) Serve(ln net.Listener) error

Serve starts the server on the provided listener without installing OS signal handlers

func (*CoreRPC) Shutdown

func (app *CoreRPC) Shutdown() error

Shutdown gracefully terminates the server

func (*CoreRPC) UseGlobalRegistry

func (app *CoreRPC) UseGlobalRegistry() *CoreRPC

UseGlobalRegistry imports all functions and middlewares registered via package init()

type CorsConfig

type CorsConfig struct {
	AllowOrigins     []string      `json:"allowOrigins"`     // Allowed origins, e.g. ["http://localhost:3000"]
	AllowMethods     []string      `json:"allowMethods"`     // Allowed methods, e.g. ["POST", "OPTIONS"]
	AllowHeaders     []string      `json:"allowHeaders"`     // Allowed headers, e.g. ["Content-Type", "Authorization"]
	AllowCredentials bool          `json:"allowCredentials"` // Access-Control-Allow-Credentials
	MaxAge           time.Duration `json:"maxAge"`           // Preflight cache duration
}

CorsConfig defines explicit CORS access control policies

type FunctionConfig

type FunctionConfig[TInput any, TOutput any] struct {
	Namespace    string
	FunctionName string
	ContentType  string // "application/json" (default) or "multipart/form-data"
	Metadata     FunctionMetadata
	InputSchema  *schema.SchemaRule
	OutputSchema *schema.SchemaRule
	Middlewares  []MiddlewareAttachment
	Handler      func(ctx *Context, input TInput) (*TOutput, error)
}

FunctionConfig provides type-safe configuration for registering an RPC function

type FunctionDefinition

type FunctionDefinition struct {
	Namespace    string
	FunctionName string
	Key          string // e.g. "user.getProfile" or "admin.catalog.products.create"
	ContentType  string // "application/json" or "multipart/form-data"
	Metadata     FunctionMetadata
	InputSchema  *schema.SchemaRule
	OutputSchema *schema.SchemaRule
	Middlewares  []MiddlewareAttachment
	Handler      func(ctx *Context, rawInput any) (any, error)
	InputType    reflect.Type
}

FunctionDefinition holds metadata, schemas, and execution handlers

func Register

func Register[TInput any, TOutput any](cfg FunctionConfig[TInput, TOutput]) *FunctionDefinition

Register registers a type-safe RPC function into the global or local registry

type FunctionMetadata

type FunctionMetadata struct {
	Description string `json:"description,omitempty"`
	// Deprecated: Ignored. Has no documentation visibility, authentication or
	// authorization meaning. Retained for source compatibility until a future major release.
	IsPublic   bool     `json:"isPublic,omitempty"`
	Deprecated bool     `json:"deprecated,omitempty"`
	Tags       []string `json:"tags,omitempty"`
}

FunctionMetadata contains documentation and legacy compatibility fields.

type HTTPContext

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

HTTPContext wraps fasthttp.RequestCtx with Express/Fiber-like helper methods

func NewHTTPContext

func NewHTTPContext(reqCtx *fasthttp.RequestCtx, app *CoreRPC) *HTTPContext

NewHTTPContext creates an HTTPContext wrapper

func (*HTTPContext) Body

func (c *HTTPContext) Body() []byte

Body returns the raw request body bytes

func (*HTTPContext) Call

func (c *HTTPContext) Call(functionKey string, input any, outputTarget any, opts ...CallOptions) error

Call executes an RPC function directly in-memory from within a custom HTTP route handler

func (*HTTPContext) Header

func (c *HTTPContext) Header(key string) string

Header returns a request header by key

func (*HTTPContext) JSON

func (c *HTTPContext) JSON(data any) error

JSON sends a JSON response

func (*HTTPContext) Method

func (c *HTTPContext) Method() string

Method returns the HTTP method

func (*HTTPContext) Path

func (c *HTTPContext) Path() string

Path returns the requested URL path

func (*HTTPContext) Query

func (c *HTTPContext) Query(key string) string

Query returns a query string parameter by key

func (*HTTPContext) Raw

func (c *HTTPContext) Raw() *fasthttp.RequestCtx

Raw returns the underlying fasthttp RequestCtx

func (*HTTPContext) Redirect

func (c *HTTPContext) Redirect(location string, statusCode int) error

Redirect sends an HTTP redirect

func (*HTTPContext) SendString

func (c *HTTPContext) SendString(str string) error

SendString sends a plain text response

func (*HTTPContext) SetHeader

func (c *HTTPContext) SetHeader(key, value string)

SetHeader sets an HTTP response header

func (*HTTPContext) Status

func (c *HTTPContext) Status(code int) *HTTPContext

Status sets the HTTP response status code

type HTTPHandlerFunc

type HTTPHandlerFunc func(c *HTTPContext) error

HTTPHandlerFunc represents a standard custom route handler (Express/Fiber style)

type MiddlewareAttachment

type MiddlewareAttachment struct {
	Name    string         `json:"name"`
	Options map[string]any `json:"options"`
}

MiddlewareAttachment defines a named middleware with options attached to a function

func DefineMiddlewares

func DefineMiddlewares(items ...MiddlewareAttachment) []MiddlewareAttachment

DefineMiddlewares creates a slice of MiddlewareAttachments

func M

func M(name string, options map[string]any) MiddlewareAttachment

M is a clean helper to define a middleware attachment with zero boilerplate

type MiddlewareFn

type MiddlewareFn func(ctx *Context, headers map[string]string, options map[string]any) error

MiddlewareFn is the executable middleware handler function

type MiddlewareMetadata

type MiddlewareMetadata struct {
	Name        string             `json:"name"`
	Description string             `json:"description"`
	Options     *schema.SchemaRule `json:"options,omitempty"`
	Headers     *schema.SchemaRule `json:"headers,omitempty"`
}

MiddlewareMetadata contains descriptive documentation for the /docs UI

type ParsedMultipartData

type ParsedMultipartData struct {
	Namespace    string
	FunctionName string
	Data         map[string]any
	Files        []*UploadedFile
}

ParsedMultipartData holds the extracted routing parameters, fields, and file references

func ParseMultipartPhase2

func ParseMultipartPhase2(reqCtx *fasthttp.RequestCtx, maxSizeBytes int64, maxFiles ...int) (*ParsedMultipartData, error)

ParseMultipartPhase2 extracts all remaining fields and streams binary files directly to disk temp storage

type RegisteredMiddleware

type RegisteredMiddleware struct {
	Metadata MiddlewareMetadata
	Handler  MiddlewareFn
}

RegisteredMiddleware holds the execution handler and metadata

type ResponseEnvelope

type ResponseEnvelope struct {
	Status  string                  `json:"status"`            // "ok" or "error"
	Data    any                     `json:"data,omitempty"`    // Present on status == "ok"
	Code    string                  `json:"code,omitempty"`    // Present on status == "error"
	Message string                  `json:"message,omitempty"` // Present on status == "error"
	Details []ValidationErrorDetail `json:"details,omitempty"` // Present on status == "error"
	Meta    ResponseMeta            `json:"meta"`
}

ResponseEnvelope represents the uniform HTTP 200 JSON envelope

func (*ResponseEnvelope) ToJSON

func (r *ResponseEnvelope) ToJSON() ([]byte, error)

ToJSON serializes the envelope into bytes

type ResponseMeta

type ResponseMeta struct {
	RequestID  string  `json:"requestId"`
	DurationMs float64 `json:"durationMs"`
}

ResponseMeta contains request lifecycle tracing metadata

type TelemetryEvent

type TelemetryEvent struct {
	RequestID  string
	Namespace  string
	Function   string
	DurationMs float64
	Status     string // "ok" or "error"
	ErrorCode  string
	ClientIP   string
	UserAgent  string
	Error      error
}

TelemetryHandler is invoked for request metrics, logging, or crash reporting

type TelemetryHook

type TelemetryHook func(event TelemetryEvent)

type TestCaller

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

TestCaller provides direct in-process RPC test execution with zero network socket binding

func NewTestCaller

func NewTestCaller(app *CoreRPC, defaultOptions ...TestOptions) *TestCaller

NewTestCaller initializes a TestCaller

func (*TestCaller) Call

func (tc *TestCaller) Call(functionKey string, input any, outputTarget any) error

Call executes the RPC function in-process, unwraps data into outputTarget or returns an AppError

func (*TestCaller) CallRaw

func (tc *TestCaller) CallRaw(functionKey string, input any, customOpts ...TestOptions) (*ResponseEnvelope, error)

CallRaw executes the RPC function in-process and returns the full ResponseEnvelope (status, code, details, meta)

type TestOptions

type TestOptions struct {
	Headers  map[string]string
	ClientIP string
}

TestOptions configures test execution parameters

type UploadedFile

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

UploadedFile represents a validated binary file uploaded via multipart/form-data

func NewUploadedFile

func NewUploadedFile(rawFilename string, mimeType string, data []byte, tempPath string) *UploadedFile

NewUploadedFile creates an UploadedFile from in-memory bytes or temp path

func NewUploadedFileDetailed added in v1.0.1

func NewUploadedFileDetailed(rawFilename string, declaredMime string, detectedMime string, size int64, data []byte, tempPath string) *UploadedFile

NewUploadedFileDetailed creates an UploadedFile with explicit declared vs detected MIME types

func (*UploadedFile) Bytes

func (f *UploadedFile) Bytes() ([]byte, error)

Bytes returns the raw bytes of the file

func (*UploadedFile) Cleanup

func (f *UploadedFile) Cleanup()

Cleanup removes any temporary on-disk files associated with this upload

func (*UploadedFile) DeclaredMimeType added in v1.0.1

func (f *UploadedFile) DeclaredMimeType() string

DeclaredMimeType returns the content-type header declared by the client

func (*UploadedFile) DetectedMimeType added in v1.0.1

func (f *UploadedFile) DetectedMimeType() string

DetectedMimeType returns the content-type detected via magic bytes sniffing

func (*UploadedFile) Filename

func (f *UploadedFile) Filename() string

Filename returns the safe, sanitized base filename (free of directory traversal)

func (*UploadedFile) MimeType

func (f *UploadedFile) MimeType() string

MimeType returns the detected content-type MIME string (falling back to declared)

func (*UploadedFile) OriginalFilename added in v1.0.1

func (f *UploadedFile) OriginalFilename() string

OriginalFilename returns the raw unescaped filename provided by the client

func (*UploadedFile) Reader

func (f *UploadedFile) Reader() (io.ReadCloser, error)

Reader returns an io.ReadCloser for streaming the file contents

func (*UploadedFile) SaveTo

func (f *UploadedFile) SaveTo(destPath string) error

SaveTo writes the uploaded file to the specified destination path safely with atomic creation and 0600 permissions

func (*UploadedFile) Size

func (f *UploadedFile) Size() int64

Size returns the file size in bytes

func (*UploadedFile) TempPath added in v1.0.1

func (f *UploadedFile) TempPath() string

TempPath returns the underlying temporary file path on disk, if any

type ValidationErrorDetail

type ValidationErrorDetail = schema.ValidationErrorDetail

ValidationErrorDetail alias to schema.ValidationErrorDetail

Jump to

Keyboard shortcuts

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