orpc

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2025 License: MIT Imports: 15 Imported by: 0

README

oRPC Extension for Forge v2

The oRPC (Open RPC) extension automatically exposes your Forge application's REST API as JSON-RPC 2.0 methods with OpenRPC schema support. This provides a unified RPC interface for your existing HTTP endpoints.

Features

  • Automatic Method Generation: Converts REST routes to JSON-RPC 2.0 methods
  • OpenRPC Schema: Generates OpenRPC 1.3.2 compliant schema documentation
  • Route Execution: Executes underlying HTTP endpoints via JSON-RPC calls
  • Batch Requests: Supports JSON-RPC 2.0 batch request specification
  • Custom Method Names: Override auto-generated method names
  • Schema Annotations: Add custom param/result schemas via route options
  • Pattern Matching: Include/exclude routes with glob patterns
  • Flexible Naming: Multiple naming strategies (path-based, method-based, custom)
  • Observability: Integrated metrics and logging
  • Type Safety: Schema validation and type hints

Installation

go get github.com/xraph/forge/extensions/orpc

Quick Start

Basic Setup (Auto-Exposure)
package main

import (
    "github.com/xraph/forge"
    "github.com/xraph/forge/extensions/orpc"
)

func main() {
    app := forge.NewApp(forge.AppConfig{
        Name:    "my-api",
        Version: "1.0.0",
    })
    
    // Add REST routes
    app.Router().GET("/users/:id", getUserHandler)
    app.Router().POST("/users", createUserHandler)
    
    // Enable oRPC - automatically exposes routes as JSON-RPC methods
    app.RegisterExtension(orpc.NewExtension(
        orpc.WithEnabled(true),
        orpc.WithAutoExposeRoutes(true),
    ))
    
    app.Run()
}

This automatically creates JSON-RPC methods:

  • get.users.idGET /users/:id
  • create.usersPOST /users
Access Endpoints
Endpoint Method Description
/rpc POST Main JSON-RPC 2.0 endpoint
/rpc/schema GET OpenRPC schema document
/rpc/methods GET List available methods

Configuration

In config.yaml:

extensions:
  orpc:
    enabled: true
    endpoint: "/rpc"
    openrpc_endpoint: "/rpc/schema"
    auto_expose_routes: true
    method_prefix: "api."
    exclude_patterns:
      - "/_/*"
      - "/internal/*"
    include_patterns: []
    enable_openrpc: true
    enable_discovery: true
    enable_batch: true
    batch_limit: 10
    naming_strategy: "path"
    max_request_size: 1048576
    request_timeout: 30
    schema_cache: true
    enable_metrics: true

Then in code:

// Config loaded automatically from ConfigManager
app.RegisterExtension(orpc.NewExtension())
Programmatic Configuration
app.RegisterExtension(orpc.NewExtension(
    orpc.WithEnabled(true),
    orpc.WithEndpoint("/rpc"),
    orpc.WithAutoExposeRoutes(true),
    orpc.WithMethodPrefix("api."),
    orpc.WithExcludePatterns([]string{"/_/*", "/internal/*"}),
    orpc.WithIncludePatterns([]string{"/api/*"}), // Only expose /api/* routes
    orpc.WithOpenRPC(true),
    orpc.WithDiscovery(true),
    orpc.WithBatch(true),
    orpc.WithBatchLimit(10),
    orpc.WithNamingStrategy("path"),
    orpc.WithAuth("X-API-Key", []string{"secret-token"}),
    orpc.WithRateLimit(100), // 100 requests per minute
    orpc.WithMaxRequestSize(1024 * 1024), // 1MB
    orpc.WithRequestTimeout(30), // seconds
))
Configuration Options
Option Type Default Description
Enabled bool true Enable/disable oRPC server
Endpoint string "/rpc" JSON-RPC endpoint path
OpenRPCEndpoint string "/rpc/schema" OpenRPC schema endpoint
AutoExposeRoutes bool true Auto-generate methods from routes
MethodPrefix string "" Prefix for method names
ExcludePatterns []string ["/_/*"] Patterns to exclude
IncludePatterns []string [] Only expose matching patterns
EnableOpenRPC bool true Generate OpenRPC schema
EnableDiscovery bool true Enable method discovery endpoint
EnableBatch bool true Support batch requests
BatchLimit int 10 Max batch size
NamingStrategy string "path" Method naming: "path", "method", "custom"
MaxRequestSize int64 1048576 Max request size in bytes
RequestTimeout int 30 Request timeout in seconds
SchemaCache bool true Cache generated schemas
EnableMetrics bool true Enable metrics collection

Usage Examples

Custom Method Names
app.Router().GET("/users/:id", getUserHandler,
    forge.WithORPCMethod("user.get"),  // Custom RPC method name
    forge.WithSummary("Get user by ID"),
)

// JSON-RPC method: "user.get" (instead of auto-generated "get.users.id")
Schema Annotations
app.Router().GET("/users/:id", getUserHandler,
    forge.WithORPCParams(&orpc.ParamsSchema{
        Type: "object",
        Properties: map[string]*orpc.PropertySchema{
            "id": {
                Type:        "string",
                Description: "User ID",
            },
        },
        Required: []string{"id"},
    }),
    forge.WithORPCResult(&orpc.ResultSchema{
        Type:        "object",
        Description: "User details",
        Properties: map[string]*orpc.PropertySchema{
            "id":    {Type: "string"},
            "name":  {Type: "string"},
            "email": {Type: "string"},
        },
    }),
)
Exclude Specific Routes
// Explicitly exclude from oRPC
app.Router().GET("/internal/debug", debugHandler,
    forge.WithORPCExclude(),
)
Making JSON-RPC Calls
Single Request
curl -X POST http://localhost:8080/rpc \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "get.users.id",
    "params": {
      "id": "123",
      "query": {"include": "profile"}
    },
    "id": 1
  }'

Response:

{
  "jsonrpc": "2.0",
  "result": {
    "id": "123",
    "name": "John Doe",
    "email": "john@example.com"
  },
  "id": 1
}
Batch Request
curl -X POST http://localhost:8080/rpc \
  -H "Content-Type: application/json" \
  -d '[
    {
      "jsonrpc": "2.0",
      "method": "get.users.id",
      "params": {"id": "123"},
      "id": 1
    },
    {
      "jsonrpc": "2.0",
      "method": "get.users.id",
      "params": {"id": "456"},
      "id": 2
    }
  ]'

Response:

[
  {
    "jsonrpc": "2.0",
    "result": {"id": "123", "name": "John"},
    "id": 1
  },
  {
    "jsonrpc": "2.0",
    "result": {"id": "456", "name": "Jane"},
    "id": 2
  }
]
Error Response
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32601,
    "message": "Method 'user.delete' not found"
  },
  "id": 1
}
OpenRPC Schema
curl http://localhost:8080/rpc/schema

Returns OpenRPC 1.3.2 compliant schema:

{
  "openrpc": "1.3.2",
  "info": {
    "title": "my-api",
    "version": "1.0.0",
    "description": "JSON-RPC 2.0 API"
  },
  "methods": [
    {
      "name": "get.users.id",
      "summary": "Get user by ID",
      "params": [
        {
          "name": "params",
          "required": true,
          "schema": {
            "type": "object",
            "properties": {
              "id": {"type": "string", "description": "User ID"}
            },
            "required": ["id"]
          }
        }
      ],
      "result": {
        "name": "result",
        "schema": {"type": "object"}
      }
    }
  ]
}

Method Naming

Methods are named based on HTTP method and path:

Route HTTP Method Auto-Generated Name With Prefix api.
/users GET get.users api.get.users
/users POST create.users api.create.users
/users/:id GET get.users.id api.get.users.id
/users/:id PUT update.users.id api.update.users.id
/users/:id DELETE delete.users.id api.delete.users.id
/users/:id PATCH patch.users.id api.patch.users.id
/api/v1/posts GET get.api.v1.posts api.get.api.v1.posts
Naming Strategies
  1. Path-based (default): Generates from HTTP method + path
  2. Method-based: Uses route name if available
  3. Custom: Uses forge.WithORPCMethod() annotation

Pattern Matching

Exclude Patterns
orpc.NewExtension(
    orpc.WithExcludePatterns([]string{
        "/_/*",        // Exclude /_/health, /_/metrics
        "/internal/*", // Exclude /internal/admin
        "/debug/*",    // Exclude debug routes
    }),
)
Include Patterns
orpc.NewExtension(
    orpc.WithIncludePatterns([]string{
        "/api/*",      // Only expose /api/* routes
        "/public/*",   // And /public/* routes
    }),
)

Note: If IncludePatterns is set, only matching routes are exposed.

Route Options Reference

forge.WithORPCMethod(name string)

Set custom JSON-RPC method name.

forge.WithORPCMethod("user.get")
forge.WithORPCParams(schema *orpc.ParamsSchema)

Define parameter schema for OpenRPC.

forge.WithORPCParams(&orpc.ParamsSchema{
    Type: "object",
    Properties: map[string]*orpc.PropertySchema{
        "id": {Type: "string"},
    },
})
forge.WithORPCResult(schema *orpc.ResultSchema)

Define result schema for OpenRPC.

forge.WithORPCResult(&orpc.ResultSchema{
    Type: "object",
    Description: "User object",
})
forge.WithORPCExclude()

Exclude route from oRPC auto-exposure.

forge.WithORPCExclude()
forge.WithORPCTags(tags ...string)

Add custom tags for OpenRPC schema.

forge.WithORPCTags("users", "admin")

Observability

Metrics

The extension automatically records:

  • orpc_methods_total - Total registered methods (gauge)
  • orpc_requests_total{status,method} - Total requests by status and method (counter)
Logging

All operations are logged with structured fields:

logger.Debug("orpc: method registered", forge.F("method", methodName))
logger.Warn("orpc: failed to generate method", forge.F("path", path), forge.F("error", err))
logger.Info("orpc: routes exposed as methods", forge.F("total_routes", count), forge.F("methods", methodCount))

JSON-RPC 2.0 Error Codes

Code Message Description
-32700 Parse error Invalid JSON
-32600 Invalid Request Invalid Request object
-32601 Method not found Method does not exist
-32602 Invalid params Invalid method parameters
-32603 Internal error Internal JSON-RPC error
-32000 Server error Implementation-defined server error

Advanced Usage

Manual Method Registration

Register custom methods without routes:

ext := app.GetExtension("orpc").(*orpc.Extension)
server := ext.Server()

server.RegisterMethod(&orpc.Method{
    Name:        "custom.operation",
    Description: "Custom operation not tied to HTTP route",
    Handler: func(ctx context.Context, params interface{}) (interface{}, error) {
        // Custom logic
        return map[string]string{"result": "success"}, nil
    },
})
Interceptors

Add middleware to JSON-RPC method execution:

server.Use(func(ctx context.Context, req *orpc.Request, next orpc.MethodHandler) (interface{}, error) {
    // Pre-processing
    log.Printf("Calling method: %s", req.Method)
    
    // Execute method
    result, err := next(ctx, req.Params)
    
    // Post-processing
    if err != nil {
        log.Printf("Method failed: %s", err)
    }
    
    return result, err
})

Testing

func TestORPCExtension(t *testing.T) {
    app := forge.NewApp(forge.AppConfig{
        Name: "test-app",
    })
    
    app.RegisterExtension(orpc.NewExtension(
        orpc.WithEnabled(true),
    ))
    
    app.Router().GET("/test", func(ctx forge.Context) error {
        return ctx.JSON(200, map[string]string{"status": "ok"})
    })
    
    app.Start(context.Background())
    defer app.Stop(context.Background())
    
    // Test JSON-RPC request
    reqBody := map[string]interface{}{
        "jsonrpc": "2.0",
        "method":  "get.test",
        "id":      1,
    }
    body, _ := json.Marshal(reqBody)
    
    req := httptest.NewRequest("POST", "/rpc", bytes.NewReader(body))
    rec := httptest.NewRecorder()
    
    app.Router().ServeHTTP(rec, req)
    
    assert.Equal(t, 200, rec.Code)
}

Architecture

┌─────────────────────────────────────────────┐
│           Forge Application                 │
│  ┌──────────────────────────────────────┐  │
│  │     Router (REST API)                │  │
│  │  GET /users/:id                      │  │
│  │  POST /users                         │  │
│  │  PUT /users/:id                      │  │
│  └──────────────────────────────────────┘  │
│                    │                        │
│                    ▼                        │
│  ┌──────────────────────────────────────┐  │
│  │     oRPC Extension                   │  │
│  │  • Auto-generate JSON-RPC methods    │  │
│  │  • Generate OpenRPC schema           │  │
│  │  • Execute via internal HTTP calls   │  │
│  └──────────────────────────────────────┘  │
│                    │                        │
│                    ▼                        │
│  ┌──────────────────────────────────────┐  │
│  │     JSON-RPC Endpoints               │  │
│  │  POST /rpc                           │  │
│  │  GET /rpc/schema (OpenRPC)           │  │
│  │  GET /rpc/methods                    │  │
│  └──────────────────────────────────────┘  │
└─────────────────────────────────────────────┘
                    │
                    ▼
        ┌───────────────────────┐
        │   JSON-RPC Clients    │
        │   (Any language)      │
        └───────────────────────┘

Comparison with Other Protocols

Feature REST oRPC (JSON-RPC) gRPC GraphQL
Transport HTTP HTTP HTTP/2 HTTP
Format JSON/XML JSON Protobuf JSON
Schema OpenAPI OpenRPC .proto SDL
Batching ✅ (streaming)
Type Safety Via OpenAPI Via OpenRPC ✅ Native ✅ Native
Browser Support ⚠️ Limited
Debugging Easy Easy Harder Easy
Auto-generation ⚠️ ✅ (Forge)

Best Practices

  1. Use Custom Method Names: For public APIs, use semantic names via WithORPCMethod()
  2. Add Schema Annotations: Document params/results with WithORPCParams() and WithORPCResult()
  3. Exclude Internal Routes: Use patterns to exclude /_/* and /internal/*
  4. Enable OpenRPC: Always enable schema generation for documentation
  5. Add Descriptions: Use forge.WithSummary() and forge.WithDescription() on routes
  6. Use Method Prefix: Namespace your methods with WithMethodPrefix("api.")
  7. Monitor Metrics: Track method usage and error rates
  8. Version Your API: Include version in prefix or method names

License

MIT

Contributing

Contributions welcome! Please submit PRs to the main Forge repository.

Support


Built with ❤️ by Dr. Ruby
Part of the Forge v2 framework

Documentation

Index

Constants

View Source
const (
	ErrParseError     = -32700 // Invalid JSON
	ErrInvalidRequest = -32600 // Invalid Request object
	ErrMethodNotFound = -32601 // Method not found
	ErrInvalidParams  = -32602 // Invalid method parameters
	ErrInternalError  = -32603 // Internal JSON-RPC error
	ErrServerError    = -32000 // Server error (implementation-defined)
)

Standard JSON-RPC 2.0 error codes

Variables

View Source
var (
	ErrMethodExists        = errors.New("orpc: method already exists")
	ErrMethodNotFoundError = errors.New("orpc: method not found")
	ErrInvalidMethodName   = errors.New("orpc: invalid method name")
	ErrDisabled            = errors.New("orpc: extension is disabled")
	ErrBatchDisabled       = errors.New("orpc: batch requests are disabled")
	ErrBatchTooLarge       = errors.New("orpc: batch size exceeds limit")
	ErrRequestTooLarge     = errors.New("orpc: request size exceeds limit")
)

Package-level errors for internal use

Functions

func GetErrorMessage

func GetErrorMessage(code int) string

GetErrorMessage returns the standard message for a JSON-RPC error code

func NewExtension

func NewExtension(opts ...ConfigOption) forge.Extension

NewExtension creates a new oRPC extension with functional options. Config is loaded from ConfigManager by default, with options providing overrides.

Example:

// Load from ConfigManager (tries "extensions.orpc", then "orpc")
orpc.NewExtension()

// Override specific fields
orpc.NewExtension(
    orpc.WithEnabled(true),
    orpc.WithEndpoint("/rpc"),
    orpc.WithAutoExposeRoutes(true),
)

// Require config from ConfigManager
orpc.NewExtension(orpc.WithRequireConfig(true))

func NewExtensionWithConfig

func NewExtensionWithConfig(config Config) forge.Extension

NewExtensionWithConfig creates a new oRPC extension with a complete config. This is for backward compatibility or when config is fully known at initialization.

Types

type Config

type Config struct {
	// Core
	Enabled         bool   `json:"enabled" yaml:"enabled" mapstructure:"enabled"`
	Endpoint        string `json:"endpoint" yaml:"endpoint" mapstructure:"endpoint"`
	OpenRPCEndpoint string `json:"openrpc_endpoint" yaml:"openrpc_endpoint" mapstructure:"openrpc_endpoint"`

	// Server info for OpenRPC
	ServerName    string `json:"server_name" yaml:"server_name" mapstructure:"server_name"`
	ServerVersion string `json:"server_version" yaml:"server_version" mapstructure:"server_version"`

	// Auto-exposure
	AutoExposeRoutes bool     `json:"auto_expose_routes" yaml:"auto_expose_routes" mapstructure:"auto_expose_routes"`
	MethodPrefix     string   `json:"method_prefix" yaml:"method_prefix" mapstructure:"method_prefix"`
	ExcludePatterns  []string `json:"exclude_patterns" yaml:"exclude_patterns" mapstructure:"exclude_patterns"`
	IncludePatterns  []string `json:"include_patterns" yaml:"include_patterns" mapstructure:"include_patterns"`

	// Features
	EnableOpenRPC   bool `json:"enable_openrpc" yaml:"enable_openrpc" mapstructure:"enable_openrpc"`
	EnableDiscovery bool `json:"enable_discovery" yaml:"enable_discovery" mapstructure:"enable_discovery"`
	EnableBatch     bool `json:"enable_batch" yaml:"enable_batch" mapstructure:"enable_batch"`
	BatchLimit      int  `json:"batch_limit" yaml:"batch_limit" mapstructure:"batch_limit"`

	// Naming strategy: "path" (default), "method", "custom"
	NamingStrategy string `json:"naming_strategy" yaml:"naming_strategy" mapstructure:"naming_strategy"`

	// Security
	RequireAuth        bool     `json:"require_auth" yaml:"require_auth" mapstructure:"require_auth"`
	AuthHeader         string   `json:"auth_header" yaml:"auth_header" mapstructure:"auth_header"`
	AuthTokens         []string `json:"auth_tokens" yaml:"auth_tokens" mapstructure:"auth_tokens"`
	RateLimitPerMinute int      `json:"rate_limit_per_minute" yaml:"rate_limit_per_minute" mapstructure:"rate_limit_per_minute"`

	// Performance
	MaxRequestSize int64 `json:"max_request_size" yaml:"max_request_size" mapstructure:"max_request_size"`
	RequestTimeout int   `json:"request_timeout" yaml:"request_timeout" mapstructure:"request_timeout"` // seconds
	SchemaCache    bool  `json:"schema_cache" yaml:"schema_cache" mapstructure:"schema_cache"`

	// Observability
	EnableMetrics bool `json:"enable_metrics" yaml:"enable_metrics" mapstructure:"enable_metrics"`

	// Config loading flag (internal use)
	RequireConfig bool `json:"-" yaml:"-" mapstructure:"-"`
}

Config holds the oRPC extension configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration

func (*Config) ShouldExpose

func (c *Config) ShouldExpose(path string) bool

ShouldExpose checks if a route should be exposed based on include/exclude patterns

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration

type ConfigOption

type ConfigOption func(*Config)

ConfigOption is a functional option for configuring the oRPC extension

func WithAuth

func WithAuth(header string, tokens []string) ConfigOption

WithAuth configures authentication

func WithAutoExposeRoutes

func WithAutoExposeRoutes(enabled bool) ConfigOption

WithAutoExposeRoutes sets auto-exposure of routes

func WithBatch

func WithBatch(enabled bool) ConfigOption

WithBatch enables/disables batch requests

func WithBatchLimit

func WithBatchLimit(limit int) ConfigOption

WithBatchLimit sets the maximum batch size

func WithConfig

func WithConfig(cfg Config) ConfigOption

WithConfig sets the entire config

func WithDiscovery

func WithDiscovery(enabled bool) ConfigOption

WithDiscovery enables/disables method discovery endpoint

func WithEnabled

func WithEnabled(enabled bool) ConfigOption

WithEnabled sets the enabled flag

func WithEndpoint

func WithEndpoint(endpoint string) ConfigOption

WithEndpoint sets the RPC endpoint

func WithExcludePatterns

func WithExcludePatterns(patterns []string) ConfigOption

WithExcludePatterns sets the patterns to exclude from exposure

func WithIncludePatterns

func WithIncludePatterns(patterns []string) ConfigOption

WithIncludePatterns sets the patterns to include for exposure

func WithMaxRequestSize

func WithMaxRequestSize(size int64) ConfigOption

WithMaxRequestSize sets the maximum request size

func WithMethodPrefix

func WithMethodPrefix(prefix string) ConfigOption

WithMethodPrefix sets the method name prefix

func WithMetrics

func WithMetrics(enabled bool) ConfigOption

WithMetrics enables/disables metrics collection

func WithNamingStrategy

func WithNamingStrategy(strategy string) ConfigOption

WithNamingStrategy sets the method naming strategy

func WithOpenRPC

func WithOpenRPC(enabled bool) ConfigOption

WithOpenRPC enables/disables OpenRPC schema generation

func WithOpenRPCEndpoint

func WithOpenRPCEndpoint(endpoint string) ConfigOption

WithOpenRPCEndpoint sets the OpenRPC schema endpoint

func WithRateLimit

func WithRateLimit(perMinute int) ConfigOption

WithRateLimit sets the rate limit per minute

func WithRequestTimeout

func WithRequestTimeout(seconds int) ConfigOption

WithRequestTimeout sets the request timeout in seconds

func WithRequireConfig

func WithRequireConfig(required bool) ConfigOption

WithRequireConfig sets whether config must be loaded from ConfigManager

func WithSchemaCache

func WithSchemaCache(enabled bool) ConfigOption

WithSchemaCache enables/disables schema caching

func WithServerInfo

func WithServerInfo(name, version string) ConfigOption

WithServerInfo sets the server name and version for OpenRPC

type Error

type Error struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

Error represents a JSON-RPC 2.0 error

func (*Error) Error

func (e *Error) Error() string

String returns a string representation of the error

type Extension

type Extension struct {
	*forge.BaseExtension
	// contains filtered or unexported fields
}

Extension implements forge.Extension for oRPC (JSON-RPC 2.0 / OpenRPC) functionality

func (*Extension) Health

func (e *Extension) Health(ctx context.Context) error

Health checks if the oRPC extension is healthy

func (*Extension) Register

func (e *Extension) Register(app forge.App) error

Register registers the oRPC extension with the app

func (*Extension) Server

func (e *Extension) Server() ORPC

Server returns the oRPC server instance

func (*Extension) Start

func (e *Extension) Start(ctx context.Context) error

Start starts the oRPC extension

func (*Extension) Stop

func (e *Extension) Stop(ctx context.Context) error

Stop stops the oRPC extension

type Interceptor

type Interceptor func(ctx context.Context, req *Request, next MethodHandler) (interface{}, error)

Interceptor wraps method execution

type Method

type Method struct {
	Name        string
	Description string
	Params      *ParamsSchema
	Result      *ResultSchema
	Handler     MethodHandler
	RouteInfo   interface{} // Reference to forge.RouteInfo
	Tags        []string
	Deprecated  bool
	Metadata    map[string]interface{}
}

Method represents a registered JSON-RPC method

type MethodHandler

type MethodHandler func(ctx interface{}, params interface{}) (interface{}, error)

MethodHandler is a function that executes a JSON-RPC method

type ORPC

type ORPC interface {
	// Method management
	RegisterMethod(method *Method) error
	GetMethod(name string) (*Method, error)
	ListMethods() []Method

	// Route introspection (auto-expose)
	GenerateMethodFromRoute(route forge.RouteInfo) (*Method, error)

	// Execution
	HandleRequest(ctx context.Context, req *Request) *Response
	HandleBatch(ctx context.Context, requests []*Request) []*Response

	// OpenRPC schema
	OpenRPCDocument() *OpenRPCDocument

	// Interceptors
	Use(interceptor Interceptor)

	// Stats
	GetStats() ServerStats

	// Internal
	SetRouter(router forge.Router)
}

ORPC represents the oRPC server interface

func NewORPCServer

func NewORPCServer(config Config, logger forge.Logger, metrics forge.Metrics) ORPC

NewORPCServer creates a new oRPC server

type OpenRPCComponents

type OpenRPCComponents struct {
	Schemas map[string]interface{} `json:"schemas,omitempty"`
}

OpenRPCComponents contains reusable schemas

type OpenRPCContact

type OpenRPCContact struct {
	Name  string `json:"name,omitempty"`
	URL   string `json:"url,omitempty"`
	Email string `json:"email,omitempty"`
}

OpenRPCContact contains contact information

type OpenRPCDocument

type OpenRPCDocument struct {
	OpenRPC    string             `json:"openrpc"`
	Info       *OpenRPCInfo       `json:"info"`
	Methods    []*OpenRPCMethod   `json:"methods"`
	Components *OpenRPCComponents `json:"components,omitempty"`
	Servers    []*OpenRPCServer   `json:"servers,omitempty"`
}

OpenRPCDocument represents an OpenRPC document

type OpenRPCError

type OpenRPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

OpenRPCError represents an error in OpenRPC schema

type OpenRPCInfo

type OpenRPCInfo struct {
	Title          string          `json:"title"`
	Version        string          `json:"version"`
	Description    string          `json:"description,omitempty"`
	TermsOfService string          `json:"termsOfService,omitempty"`
	Contact        *OpenRPCContact `json:"contact,omitempty"`
	License        *OpenRPCLicense `json:"license,omitempty"`
}

OpenRPCInfo contains API metadata

type OpenRPCLicense

type OpenRPCLicense struct {
	Name string `json:"name"`
	URL  string `json:"url,omitempty"`
}

OpenRPCLicense contains license information

type OpenRPCMethod

type OpenRPCMethod struct {
	Name        string          `json:"name"`
	Summary     string          `json:"summary,omitempty"`
	Description string          `json:"description,omitempty"`
	Tags        []*OpenRPCTag   `json:"tags,omitempty"`
	Params      []*OpenRPCParam `json:"params,omitempty"`
	Result      *OpenRPCResult  `json:"result,omitempty"`
	Deprecated  bool            `json:"deprecated,omitempty"`
	Errors      []*OpenRPCError `json:"errors,omitempty"`
}

OpenRPCMethod represents a method in OpenRPC schema

type OpenRPCParam

type OpenRPCParam struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	Required    bool                   `json:"required,omitempty"`
	Schema      map[string]interface{} `json:"schema"`
}

OpenRPCParam represents a parameter in OpenRPC schema

type OpenRPCResult

type OpenRPCResult struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	Schema      map[string]interface{} `json:"schema"`
}

OpenRPCResult represents a result in OpenRPC schema

type OpenRPCServer

type OpenRPCServer struct {
	Name        string `json:"name,omitempty"`
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

OpenRPCServer describes a server

type OpenRPCTag

type OpenRPCTag struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

OpenRPCTag represents a tag for grouping methods

type ParamsSchema

type ParamsSchema struct {
	Type        string                     `json:"type"`
	Properties  map[string]*PropertySchema `json:"properties,omitempty"`
	Required    []string                   `json:"required,omitempty"`
	Description string                     `json:"description,omitempty"`
}

ParamsSchema describes the parameters schema

type PropertySchema

type PropertySchema struct {
	Type        string                     `json:"type"`
	Description string                     `json:"description,omitempty"`
	Properties  map[string]*PropertySchema `json:"properties,omitempty"`
	Items       *PropertySchema            `json:"items,omitempty"`
	Required    []string                   `json:"required,omitempty"`
	Example     interface{}                `json:"example,omitempty"`
}

PropertySchema describes a property in a schema

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
	ID      interface{}     `json:"id,omitempty"` // string, number, or null
}

Request represents a JSON-RPC 2.0 request

func (*Request) IsNotification

func (r *Request) IsNotification() bool

IsNotification returns true if this is a notification (no ID)

type Response

type Response struct {
	JSONRPC string      `json:"jsonrpc"`
	Result  interface{} `json:"result,omitempty"`
	Error   *Error      `json:"error,omitempty"`
	ID      interface{} `json:"id"`
}

Response represents a JSON-RPC 2.0 response

func NewErrorResponse

func NewErrorResponse(id interface{}, code int, message string) *Response

NewErrorResponse creates an error response

func NewErrorResponseWithData

func NewErrorResponseWithData(id interface{}, code int, message string, data interface{}) *Response

NewErrorResponseWithData creates an error response with additional data

func NewSuccessResponse

func NewSuccessResponse(id interface{}, result interface{}) *Response

NewSuccessResponse creates a success response

type ResponseSchemaDef

type ResponseSchemaDef struct {
	Description string
	Schema      interface{}
}

ResponseSchemaDef mirrors the OpenAPI response schema definition This is imported from the router package's internal structure

type ResultSchema

type ResultSchema struct {
	Type        string                     `json:"type"`
	Properties  map[string]*PropertySchema `json:"properties,omitempty"`
	Description string                     `json:"description,omitempty"`
}

ResultSchema describes the result schema

type ServerStats

type ServerStats struct {
	TotalMethods   int64
	TotalRequests  int64
	TotalErrors    int64
	TotalBatchReqs int64
	ActiveRequests int64
	AverageLatency float64
}

ServerStats contains server statistics

Jump to

Keyboard shortcuts

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