runtime

package
v0.0.0-...-d0ab517 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

Runtime 模块重构说明

概述

本次重构整合了 backend/modules/evaluation/infra/runtime 目录下的所有运行时代码,实现了统一的运行时架构,提供了更简洁、高效和易维护的代码执行解决方案。

架构设计1. Runtime (runtime.go)

  • 统一的运行时实现,专注于HTTP FaaS模式
  • 通过环境变量 COZE_LOOP_PYTHON_FAAS_URLCOZE_LOOP_JS_FAAS_URL 配置FaaS服务
  • 根据语言类型自动路由到对应的FaaS服务
  1. RuntimeFactory (factory.go)
  • 统一的运行时工厂实现
  • 使用单例模式管理运行时实例
  • 支持多语言类型的运行时创建
  1. RuntimeManager (manager.go)
  • 统一的运行时管理器
  • 提供线程安全的实例缓存和管理
  • 支持运行时的生命周期管理
运行模式
1. HTTP FaaS 模式
  • 当设置环境变量 COZE_LOOP_FAAS_URL 时自动启用
  • 通过HTTP调用远程FaaS服务执行代码
  • 适用于生产环境和分布式部署
2. 精简架构
  • 移除了本地增强运行时模式
  • 仅支持HTTP FaaS模式,简化了架构复杂度
  • 专注于Python和JavaScript的FaaS执行

支持的语言

  • JavaScript/TypeScript: js, javascript, ts, typescript
  • Python: python, py

主要特性

1. 统一接口
  • 完全实现 IRuntime 接口
  • 统一的代码执行和验证接口
  • 一致的错误处理和结果格式
2. FaaS服务配置
// 设置环境变量配置FaaS服务
os.Setenv("COZE_LOOP_PYTHON_FAAS_URL", "http://python-faas:8000")
os.Setenv("COZE_LOOP_JS_FAAS_URL", "http://js-faas:8000")

// 创建运行时(自动路由到对应FaaS服务)
runtime, err := NewRuntime(config, logger)
3. 资源管理
  • 自动资源清理
  • 线程安全的实例管理
  • 优雅的错误处理
4. 监控和指标
  • 健康状态检查
  • 运行时指标收集
  • 详细的执行日志

使用方式

基本使用
import (
    "github.com/coze-dev/coze-loop/backend/modules/evaluation/infra/runtime"
    "github.com/coze-dev/coze-loop/backend/modules/evaluation/domain/entity"
)

// 创建运行时管理器
logger := logrus.New()
config := entity.DefaultSandboxConfig()
factory := runtime.NewRuntimeFactory(logger, config)
manager := runtime.NewRuntimeManager(factory, logger)

// 获取JavaScript运行时
jsRuntime, err := manager.GetRuntime(entity.LanguageTypeJS)
if err != nil {
    return err
}

// 执行代码
result, err := jsRuntime.RunCode(ctx, "console.log('Hello World')", "javascript", 5000)
if err != nil {
    return err
}

// 验证代码
isValid := jsRuntime.ValidateCode(ctx, "function test() {}", "javascript")
工厂模式使用
// 创建工厂
factory := runtime.NewRuntimeFactory(logger, config)

// 创建运行时
pythonRuntime, err := factory.CreateRuntime(entity.LanguageTypePython)
if err != nil {
    return err
}

// 执行Python代码
result, err := pythonRuntime.RunCode(ctx, "print('Hello Python')", "python", 5000)

配置选项

沙箱配置
config := &entity.SandboxConfig{
    MemoryLimit:    256,              // 内存限制 (MB)
    TimeoutLimit:   30 * time.Second, // 执行超时
    MaxOutputSize:  2 * 1024 * 1024,  // 最大输出 (2MB)
    NetworkEnabled: false,            // 网络访问
}
HTTP FaaS 配置
// 通过环境变量配置
os.Setenv("COZE_LOOP_PYTHON_FAAS_URL", "http://coze-loop-python-faas:8000")
os.Setenv("COZE_LOOP_JS_FAAS_URL", "http://coze-loop-js-faas:8000")

迁移指南

从旧版本迁移
  1. 替换工厂创建
// 旧版本
factory := runtime.NewRuntimeFactory(logger, config)// 新版本
factory := runtime.NewRuntimeFactory(logger, config)
manager := runtime.NewRuntimeManager(factory, logger)
  1. 替换管理器创建
// 旧版本
manager := runtime.NewRuntimeManager(factory)

// 新版本
factory := runtime.NewRuntimeFactory(logger, config)
manager := runtime.NewRuntimeManager(factory, logger)
  1. 接口保持兼容
  • 所有 IRuntime 接口方法保持不变
  • 所有 IRuntimeFactory 接口方法保持不变
  • 所有 IRuntimeManager 接口方法保持不变

性能优化

  1. 单例模式: 统一运行时使用单例模式,减少资源消耗
  2. 实例缓存: 管理器缓存运行时实例,避免重复创建
  3. 资源复用: 内部组件支持资源复用和连接池
  4. 异步处理: 支持异步任务调度和并发执行

测试

运行测试:

cd backend/modules/evaluation/infra/runtime
go test -v ./...

测试覆盖:

  • 基本功能测试
  • 模式切换测试
  • 并发安全测试
  • 错误处理测试
  • 资源清理测试

精简后的架构

本次精简重构删除了以下文件和目录:

删除的本地执行相关代码
  • enhanced/ 目录 - 增强运行时实现(沙箱池、任务调度器等)
  • deno/ 目录 - Deno客户端实现
  • pyodide/ 目录 - Pyodide运行时实现
  • simple_faas_server.py - 本地FaaS服务器
  • simple_runtime.go - 简单运行时实现
  • factory.go - 旧版运行时工厂
  • manager.go - 旧版运行时管理器
  • 相关测试文件
保留的核心文件
  • unified_runtime.go - 统一运行时(仅支持HTTP FaaS)
  • unified_factory.go - 统一运行时工厂
  • unified_manager.go - 统一运行时管理器
  • http_faas_runtime.go - HTTP FaaS适配器
  • 相关测试文件

未来扩展

  1. 新语言支持: 可通过扩展统一运行时轻松添加新语言
  2. 新运行模式: 可添加新的运行时后端(如Docker、Kubernetes等)
  3. 高级特性: 可添加代码缓存、预编译、热重载等特性
  4. 监控增强: 可添加更详细的指标和追踪功能

Documentation

Index

Constants

This section is empty.

Variables

Functions

func NewLogger

func NewLogger() *logrus.Logger

func NewRuntimeFactory

func NewRuntimeFactory(logger *logrus.Logger, sandboxConfig *entity.SandboxConfig) component.IRuntimeFactory

NewRuntimeFactory 创建统一运行时工厂实例

func NewRuntimeManagerFromFactory

func NewRuntimeManagerFromFactory(factory component.IRuntimeFactory, logger *logrus.Logger) component.IRuntimeManager

func NewSandboxConfig

func NewSandboxConfig() *entity.SandboxConfig

Types

type HTTPFaaSRequest

type HTTPFaaSRequest struct {
	Language string            `json:"language"`
	Code     string            `json:"code"`
	Input    interface{}       `json:"input,omitempty"`
	Timeout  int64             `json:"timeout,omitempty"`
	Priority string            `json:"priority,omitempty"`
	Ext      map[string]string `json:"ext,omitempty"`
}

HTTPFaaSRequest HTTP FaaS请求结构

type HTTPFaaSResponse

type HTTPFaaSResponse struct {
	Output struct {
		Stdout string `json:"stdout"`
		Stderr string `json:"stderr"`
		RetVal string `json:"ret_val"`
	} `json:"output"`
	Metadata *struct {
		TaskID     string `json:"task_id"`
		InstanceID string `json:"instance_id"`
		Duration   int64  `json:"duration"`
		PoolStats  struct {
			TotalInstances  int `json:"totalInstances"`
			IdleInstances   int `json:"idleInstances"`
			ActiveInstances int `json:"activeInstances"`
		} `json:"pool_stats"`
	} `json:"metadata,omitempty"`
	Error   string `json:"error,omitempty"`
	Details string `json:"details,omitempty"`
}

HTTPFaaSResponse HTTP FaaS响应结构

type HTTPFaaSRuntimeAdapter

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

HTTPFaaSRuntimeAdapter 基于HTTP调用的FaaS运行时适配器

func NewHTTPFaaSRuntimeAdapter

func NewHTTPFaaSRuntimeAdapter(languageType entity.LanguageType, config *HTTPFaaSRuntimeConfig, logger *logrus.Logger) (*HTTPFaaSRuntimeAdapter, error)

NewHTTPFaaSRuntimeAdapter 创建HTTP FaaS运行时适配器

func (*HTTPFaaSRuntimeAdapter) Cleanup

func (adapter *HTTPFaaSRuntimeAdapter) Cleanup() error

Cleanup 清理资源

func (*HTTPFaaSRuntimeAdapter) GetLanguageType

func (adapter *HTTPFaaSRuntimeAdapter) GetLanguageType() entity.LanguageType

GetLanguageType 获取支持的语言类型

func (*HTTPFaaSRuntimeAdapter) GetReturnValFunction

func (adapter *HTTPFaaSRuntimeAdapter) GetReturnValFunction() string

GetReturnValFunction 获取return_val函数实现

func (*HTTPFaaSRuntimeAdapter) RunCode

func (adapter *HTTPFaaSRuntimeAdapter) RunCode(ctx context.Context, code string, language string, timeoutMS int64, ext map[string]string) (*entity.ExecutionResult, error)

RunCode 通过HTTP调用FaaS服务执行代码

type HTTPFaaSRuntimeConfig

type HTTPFaaSRuntimeConfig struct {
	BaseURL        string        `json:"base_url"`        // FaaS服务基础URL
	Timeout        time.Duration `json:"timeout"`         // HTTP请求超时
	MaxRetries     int           `json:"max_retries"`     // 最大重试次数
	RetryInterval  time.Duration `json:"retry_interval"`  // 重试间隔
	EnableEnhanced bool          `json:"enable_enhanced"` // 是否启用增强版FaaS
}

HTTPFaaSRuntimeConfig HTTP FaaS运行时配置

type JavaScriptRuntime

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

JavaScriptRuntime JavaScript运行时实现,专门处理JavaScript代码执行

func NewJavaScriptRuntime

func NewJavaScriptRuntime(config *entity.SandboxConfig, logger *logrus.Logger) (*JavaScriptRuntime, error)

NewJavaScriptRuntime 创建JavaScript运行时实例

func (*JavaScriptRuntime) GetHealthStatus

func (jr *JavaScriptRuntime) GetHealthStatus() map[string]interface{}

GetHealthStatus 获取健康状态

func (*JavaScriptRuntime) GetLanguageType

func (jr *JavaScriptRuntime) GetLanguageType() entity.LanguageType

GetLanguageType 获取语言类型

func (*JavaScriptRuntime) GetMetrics

func (jr *JavaScriptRuntime) GetMetrics() map[string]interface{}

GetMetrics 获取运行时指标

func (*JavaScriptRuntime) GetReturnValFunction

func (jr *JavaScriptRuntime) GetReturnValFunction() string

GetReturnValFunction 获取JavaScript return_val函数实现

func (*JavaScriptRuntime) GetSupportedLanguages

func (jr *JavaScriptRuntime) GetSupportedLanguages() []entity.LanguageType

GetSupportedLanguages 获取支持的语言类型列表

func (*JavaScriptRuntime) RunCode

func (jr *JavaScriptRuntime) RunCode(ctx context.Context, code string, language string, timeoutMS int64, ext map[string]string) (*entity.ExecutionResult, error)

RunCode 执行JavaScript代码

func (*JavaScriptRuntime) ValidateCode

func (jr *JavaScriptRuntime) ValidateCode(ctx context.Context, code string, language string) bool

ValidateCode 验证JavaScript代码语法

type PythonRuntime

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

PythonRuntime Python运行时实现,专门处理Python代码执行

func NewPythonRuntime

func NewPythonRuntime(config *entity.SandboxConfig, logger *logrus.Logger) (*PythonRuntime, error)

NewPythonRuntime 创建Python运行时实例

func (*PythonRuntime) GetHealthStatus

func (pr *PythonRuntime) GetHealthStatus() map[string]interface{}

GetHealthStatus 获取健康状态

func (*PythonRuntime) GetLanguageType

func (pr *PythonRuntime) GetLanguageType() entity.LanguageType

GetLanguageType 获取语言类型

func (*PythonRuntime) GetMetrics

func (pr *PythonRuntime) GetMetrics() map[string]interface{}

GetMetrics 获取运行时指标

func (*PythonRuntime) GetReturnValFunction

func (pr *PythonRuntime) GetReturnValFunction() string

GetReturnValFunction 获取Python return_val函数实现

func (*PythonRuntime) GetSupportedLanguages

func (pr *PythonRuntime) GetSupportedLanguages() []entity.LanguageType

GetSupportedLanguages 获取支持的语言类型列表

func (*PythonRuntime) RunCode

func (pr *PythonRuntime) RunCode(ctx context.Context, code string, language string, timeoutMS int64, ext map[string]string) (*entity.ExecutionResult, error)

RunCode 执行Python代码

func (*PythonRuntime) ValidateCode

func (pr *PythonRuntime) ValidateCode(ctx context.Context, code string, language string) bool

ValidateCode 验证Python代码语法

type RuntimeFactory

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

RuntimeFactory 统一的运行时工厂实现

func (*RuntimeFactory) CreateRuntime

func (f *RuntimeFactory) CreateRuntime(languageType entity.LanguageType) (component.IRuntime, error)

CreateRuntime 根据语言类型创建Runtime实例

func (*RuntimeFactory) GetHealthStatus

func (f *RuntimeFactory) GetHealthStatus() map[string]interface{}

GetHealthStatus 获取工厂健康状态

func (*RuntimeFactory) GetMetrics

func (f *RuntimeFactory) GetMetrics() map[string]interface{}

GetMetrics 获取工厂指标

func (*RuntimeFactory) GetSupportedLanguages

func (f *RuntimeFactory) GetSupportedLanguages() []entity.LanguageType

GetSupportedLanguages 获取支持的语言类型列表

type RuntimeManager

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

RuntimeManager 统一的运行时管理器,提供线程安全的Runtime实例缓存和管理

func NewRuntimeManager

func NewRuntimeManager(factory component.IRuntimeFactory, logger *logrus.Logger) *RuntimeManager

NewRuntimeManager 创建统一运行时管理器实例

func (*RuntimeManager) ClearCache

func (m *RuntimeManager) ClearCache()

ClearCache 清空缓存(主要用于测试和重置)

func (*RuntimeManager) GetHealthStatus

func (m *RuntimeManager) GetHealthStatus() map[string]interface{}

GetHealthStatus 获取管理器健康状态

func (*RuntimeManager) GetMetrics

func (m *RuntimeManager) GetMetrics() map[string]interface{}

GetMetrics 获取管理器指标

func (*RuntimeManager) GetRuntime

func (m *RuntimeManager) GetRuntime(languageType entity.LanguageType) (component.IRuntime, error)

GetRuntime 获取指定语言类型的Runtime实例,支持缓存和线程安全

func (*RuntimeManager) GetSupportedLanguages

func (m *RuntimeManager) GetSupportedLanguages() []entity.LanguageType

GetSupportedLanguages 获取支持的语言类型列表

Jump to

Keyboard shortcuts

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