/*
* Copyright 2024 The RuleGo Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Package endpoint provides the core definitions and interfaces for endpoints in the RuleGo framework.
// Endpoints serve as entry points for external data to flow into rule chains, abstracting different
// input sources and providing a unified interface for message processing and routing.
//
// Package endpoint 为 RuleGo 框架中的端点提供核心定义和接口。
// 端点作为外部数据流入规则链的入口点,抽象不同的输入源并提供统一的消息处理和路由接口。
//
// Core Concepts / 核心概念:
//
// • Endpoint: The main abstraction for input sources (HTTP, MQTT, WebSocket, etc.) 端点:输入源的主要抽象
// • Router: Defines how incoming messages are routed to rule chains 路由器:定义传入消息如何路由到规则链
// • Message: Abstracts incoming and outgoing message data 消息:抽象传入和传出的消息数据
// • Exchange: Contains both request and response messages 交换:包含请求和响应消息
// • Process: Middleware-style processing functions 处理:中间件风格的处理函数
//
// Architecture / 架构:
//
// The endpoint system follows a layered architecture:
// 端点系统遵循分层架构:
//
// 1. Message Layer: Abstracts incoming/outgoing data 消息层:抽象传入/传出数据
// 2. Processing Layer: Transforms and validates messages 处理层:转换和验证消息
// 3. Routing Layer: Routes messages to appropriate destinations 路由层:将消息路由到适当的目标
// 4. Execution Layer: Executes rule chains or components 执行层:执行规则链或组件
//
// Endpoint Lifecycle / 端点生命周期:
//
// 1. Creation: Endpoint is created and configured 创建:端点被创建和配置
// 2. Initialization: Resources are allocated and connections established 初始化:分配资源并建立连接
// 3. Start: Endpoint begins accepting incoming messages 启动:端点开始接受传入消息
// 4. Processing: Messages are processed through routers 处理:消息通过路由器处理
// 5. Shutdown: Resources are cleaned up gracefully 关闭:优雅地清理资源
//
// Usage Patterns / 使用模式:
//
// Static Configuration / 静态配置:
//
// endpoint := &rest.Rest{}
// endpoint.Init(config, restConfig)
// router := endpoint.NewRouter().From("/api/data").To("chain:processing")
// endpoint.POST(router)
// endpoint.Start()
//
// Dynamic Configuration / 动态配置:
//
// factory := endpoint.NewFactory()
// dynamicEndpoint, err := factory.NewFromDsl(dslBytes)
// dynamicEndpoint.Start()
//
// Message Processing Pipeline / 消息处理管道:
//
// The message processing follows this flow:
// 消息处理遵循以下流程:
//
// 1. External Message → Endpoint 外部消息 → 端点
// 2. Message → RequestMessage 消息 → 请求消息
// 3. Router Matching & Processing 路由器匹配和处理
// 4. Rule Chain/Component Execution 规则链/组件执行
// 5. Response Generation → ResponseMessage 响应生成 → 响应消息
// 6. ResponseMessage → External Response 响应消息 → 外部响应
package endpoint
import (
"context"
"net/http"
"net/textproto"
"sync"
"github.com/rulego/rulego/api/types"
)
// Event constants define various lifecycle and operational events in the endpoint system.
// These events enable monitoring and handling of endpoint state changes and operations.
// 事件常量定义端点系统中的各种生命周期和操作事件。
// 这些事件使得监控和处理端点状态变化和操作成为可能。
const (
// EventConnect represents a connection establishment event.
// Triggered when a new client connection is established (e.g., WebSocket connection).
// EventConnect 表示连接建立事件。
// 当建立新的客户端连接时触发(例如,WebSocket 连接)。
EventConnect = "Connect"
// EventDisconnect represents a connection termination event.
// Triggered when a client connection is closed or lost.
// EventDisconnect 表示连接终止事件。
// 当客户端连接关闭或丢失时触发。
EventDisconnect = "Disconnect"
// EventInitServer represents a server initialization event.
// Triggered when the endpoint server is being initialized.
// EventInitServer 表示服务器初始化事件。
// 当端点服务器正在初始化时触发。
EventInitServer = "InitServer"
// EventCompletedServer represents a server completion event.
// Triggered when the endpoint server has completed its operations.
// EventCompletedServer 表示服务器完成事件。
// 当端点服务器完成其操作时触发。
EventCompletedServer = "completedServer"
)
// OnEvent is a callback function type for handling endpoint events.
// It provides a flexible way to respond to various endpoint lifecycle and operational events.
//
// OnEvent 是处理端点事件的回调函数类型。
// 它提供了响应各种端点生命周期和操作事件的灵活方式。
//
// Parameters / 参数:
// • eventName: The name of the event being triggered 被触发的事件名称
// • params: Variable number of parameters specific to the event type 特定于事件类型的可变数量参数
//
// Usage Examples / 使用示例:
//
// endpoint.SetOnEvent(func(eventName string, params ...interface{}) {
// switch eventName {
// case endpoint.EventConnect:
// log.Printf("Client connected: %v", params[0])
// case endpoint.EventDisconnect:
// log.Printf("Client disconnected: %v", params[0])
// }
// })
type OnEvent func(eventName string, params ...interface{})
// Endpoint defines the core interface for all endpoint implementations in the RuleGo framework.
// It provides the fundamental operations needed for message input, routing, and lifecycle management.
//
// Endpoint 定义 RuleGo 框架中所有端点实现的核心接口。
// 它提供消息输入、路由和生命周期管理所需的基本操作。
//
// Key Responsibilities / 主要职责:
//
// • Message Input: Accept messages from external sources 消息输入:接受来自外部源的消息
// • Router Management: Add, remove, and configure message routers 路由器管理:添加、删除和配置消息路由器
// • Lifecycle Control: Start, stop, and manage endpoint lifecycle 生命周期控制:启动、停止和管理端点生命周期
// • Event Handling: Process and notify about endpoint events 事件处理:处理和通知端点事件
// • Interceptor Support: Apply cross-cutting concerns through interceptors 拦截器支持:通过拦截器应用横切关注点
//
// Implementation Guidelines / 实现指南:
//
// All endpoint implementations should:
// 所有端点实现应该:
//
// • Be thread-safe for concurrent operations 对并发操作是线程安全的
// • Support graceful shutdown procedures 支持优雅关闭程序
// • Handle connection failures and recovery 处理连接故障和恢复
// • Provide meaningful error messages 提供有意义的错误消息
// • Support dynamic router configuration 支持动态路由器配置
type Endpoint interface {
// Node interface provides basic component functionality including initialization,
// type identification, and lifecycle management.
// Node 接口提供基本的组件功能,包括初始化、类型识别和生命周期管理。
typ