v0.15.0 deprecated http/tcp plugins (fasthttp/gnet2), migrated stdtcp/stdhttp to tcp/http

This commit is contained in:
2026-07-17 18:29:26 -04:00
parent dc3e9910a3
commit f0aca019f3
12 changed files with 551 additions and 1646 deletions
+253 -316
View File
@@ -1,11 +1,14 @@
package http
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
@@ -19,8 +22,6 @@ import (
lconfig "github.com/lixenwraith/config"
"github.com/lixenwraith/log"
"github.com/lixenwraith/log/compat"
"github.com/valyala/fasthttp"
)
func init() {
@@ -29,7 +30,19 @@ func init() {
}
}
// HTTPSink streams log entries via Server-Sent Events (SSE)
const (
DefaultHTTPHost = "0.0.0.0"
DefaultHTTPBufferSize = 1000
DefaultHTTPClientBufferSize = 256
DefaultHTTPStreamPath = "/stream"
DefaultHTTPStatusPath = "/status"
HTTPReadHeaderTimeout = 10 * time.Second
HTTPShutdownTimeout = 2 * time.Second
)
// HTTPSink streams log entries via Server-Sent Events
// Server.WriteTimeout is deliberately unset (it would terminate long-lived SSE streams)
// per-write deadlines are applied via http.ResponseController
type HTTPSink struct {
// Plugin identity and session management
id string
@@ -37,49 +50,43 @@ type HTTPSink struct {
// Configuration
config *config.HTTPSinkOptions
addr string
// Network
server *fasthttp.Server
server *http.Server
// Application
input chan core.TransportEvent
logger *log.Logger
// Client registry
clients map[uint64]*sseClient
clientsMu sync.Mutex
nextClientID atomic.Uint64
// Runtime
done chan struct{}
stopOnce sync.Once
wg sync.WaitGroup
startTime time.Time
// Broker
clients map[uint64]chan []byte
clientsMu sync.RWMutex
unregister chan uint64
nextClientID atomic.Uint64
// Client session tracking
clientSessions map[uint64]string // clientID -> sessionID
sessionsMu sync.RWMutex
writeTimeout time.Duration
// Statistics
activeClients atomic.Int64
totalProcessed atomic.Uint64
lastProcessed atomic.Value // time.Time
activeClients atomic.Int64
totalProcessed atomic.Uint64
droppedWrites atomic.Uint64
rejectedClients atomic.Uint64
lastProcessed atomic.Value // time.Time
}
const (
// Server lifecycle
HttpServerStartTimeout = 100 * time.Millisecond
HttpServerShutdownTimeout = 2 * time.Second
// sseClient is a registered stream consumer with a bounded send queue
type sseClient struct {
send chan []byte
sessionID string
}
// Defaults
DefaultHTTPHost = "0.0.0.0"
DefaultHTTPBufferSize = 1000
DefaultHTTPStreamPath = "/stream"
DefaultHTTPStatusPath = "/status"
HTTPMaxPort = 65535
)
// NewHTTPSinkPlugin creates an HTTP sink through plugin factory
// NewHTTPSinkPlugin creates a http sink through plugin factory
func NewHTTPSinkPlugin(
id string,
configMap map[string]any,
@@ -87,57 +94,61 @@ func NewHTTPSinkPlugin(
proxy *session.Proxy,
) (sink.Sink, error) {
opts := &config.HTTPSinkOptions{
Host: DefaultHTTPHost,
Port: 0,
WriteTimeout: 0, // SSE indefinite streaming
Host: DefaultHTTPHost,
WriteTimeoutMS: 0, // SSE indefinite streaming
}
if err := lconfig.ScanMap(configMap, opts); err != nil {
return nil, fmt.Errorf("failed to parse config: %w", err)
}
// Validate
if opts.Port <= 0 || opts.Port > HTTPMaxPort {
return nil, fmt.Errorf("port must be between 1 and %d", HTTPMaxPort)
}
// Defaults
if opts.BufferSize <= 0 {
opts.BufferSize = DefaultHTTPBufferSize
if err := lconfig.Port(opts.Port); err != nil {
return nil, fmt.Errorf("port: %w", err)
}
if opts.StreamPath == "" {
opts.StreamPath = DefaultHTTPStreamPath
} else if !strings.HasPrefix(opts.StreamPath, "/") {
return nil, fmt.Errorf("stream_path: must start with '/'")
}
if opts.StatusPath == "" {
opts.StatusPath = DefaultHTTPStatusPath
} else if !strings.HasPrefix(opts.StatusPath, "/") {
return nil, fmt.Errorf("status_path: must start with '/'")
}
if opts.StreamPath == opts.StatusPath {
return nil, fmt.Errorf("stream_path and status_path must differ")
}
if opts.BufferSize <= 0 {
opts.BufferSize = DefaultHTTPBufferSize
}
if opts.ClientBufferSize <= 0 {
opts.ClientBufferSize = DefaultHTTPClientBufferSize
}
h := &HTTPSink{
id: id,
proxy: proxy,
config: opts,
input: make(chan core.TransportEvent, opts.BufferSize),
done: make(chan struct{}),
logger: logger,
clients: make(map[uint64]chan []byte),
unregister: make(chan uint64),
clientSessions: make(map[uint64]string),
id: id,
proxy: proxy,
config: opts,
addr: net.JoinHostPort(opts.Host, strconv.FormatInt(opts.Port, 10)),
input: make(chan core.TransportEvent, opts.BufferSize),
done: make(chan struct{}),
logger: logger,
clients: make(map[uint64]*sseClient),
writeTimeout: time.Duration(opts.WriteTimeoutMS) * time.Millisecond,
}
h.lastProcessed.Store(time.Time{})
logger.Info("msg", "HTTP sink initialized",
logger.Info("msg", " HTTP sink initialized",
"component", "http_sink",
"instance_id", id,
"host", opts.Host,
"port", opts.Port,
"stream_path", opts.StreamPath,
"status_path", opts.StatusPath)
return h, nil
}
// Capabilities returns supported capabilities
func (h *HTTPSink) Capabilities() []core.Capability {
// CapTLS/CapAuth appended when transport security lands
return []core.Capability{
core.CapSessionAware,
core.CapMultiSession,
@@ -149,33 +160,38 @@ func (h *HTTPSink) Input() chan<- core.TransportEvent {
return h.input
}
// Start initializes the HTTP server and begins the broker loop
// Start binds the listener and serves stream/status endpoints
func (h *HTTPSink) Start(ctx context.Context) error {
// IPv4-only, parity with existing network sinks.
// TLS extension point: wrap ln with tls.NewListener (or set
// server.TLSConfig and use ServeTLS); single seam, handlers unchanged.
ln, err := net.Listen("tcp4", h.addr)
if err != nil {
return fmt.Errorf("http sink bind %s: %w", h.addr, err)
}
mux := http.NewServeMux()
// Method-scoped patterns: mux answers 405 with Allow header on non-GET
mux.HandleFunc(http.MethodGet+" "+h.config.StreamPath, h.handleStream)
mux.HandleFunc(http.MethodGet+" "+h.config.StatusPath, h.handleStatus)
// Auth extension point: wrap mux with auth middleware once credentials
// land, e.g. handler = authMiddleware(cfg)(handler)
var handler http.Handler = mux
h.server = &http.Server{
Handler: handler,
ReadHeaderTimeout: HTTPReadHeaderTimeout,
// WriteTimeout unset by design: SSE responses are long-lived.
// Per-write deadlines via ResponseController in handleStream.
}
h.startTime = time.Now()
// Start central broker goroutine
h.wg.Add(1)
go h.brokerLoop(ctx)
fasthttpLogger := compat.NewFastHTTPAdapter(h.logger)
h.server = &fasthttp.Server{
Name: fmt.Sprintf("LogWisp/%s", version.Short()),
Handler: h.requestHandler,
DisableKeepalive: false,
StreamRequestBody: true,
Logger: fasthttpLogger,
WriteTimeout: time.Duration(h.config.WriteTimeout) * time.Millisecond,
}
addr := fmt.Sprintf("%s:%d", h.config.Host, h.config.Port)
ln, err := net.Listen("tcp4", addr)
if err != nil {
return fmt.Errorf("http sink bind %s: %w", addr, err)
}
go func() {
if err := h.server.Serve(ln); err != nil {
if err := h.server.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
h.logger.Error("msg", "HTTP server terminated",
"component", "http_sink",
"instance_id", h.id,
@@ -183,297 +199,201 @@ func (h *HTTPSink) Start(ctx context.Context) error {
}
}()
// Monitor context for shutdown
go func() {
<-ctx.Done()
if h.server != nil {
shutdownCtx, cancel := context.WithTimeout(context.Background(), HttpServerShutdownTimeout)
defer cancel()
h.server.ShutdownWithContext(shutdownCtx)
select {
case <-ctx.Done():
h.shutdown()
case <-h.done:
}
}()
h.logger.Info("msg", "HTTP server started",
h.logger.Info("msg", " HTTP server started",
"component", "http_sink",
"instance_id", h.id,
"host", h.config.Host,
"port", h.config.Port)
"addr", h.addr)
return nil
}
// Stop gracefully shuts down the HTTP server and all client connections
// Stop gracefully shuts down the sink
func (h *HTTPSink) Stop() {
h.logger.Info("msg", "Stopping HTTP sink",
"component", "http_sink",
"instance_id", h.id)
close(h.done)
if h.server != nil {
ctx, cancel := context.WithTimeout(context.Background(), HttpServerShutdownTimeout)
defer cancel()
h.server.ShutdownWithContext(ctx)
}
h.shutdown()
h.wg.Wait()
close(h.unregister)
h.clientsMu.Lock()
for _, ch := range h.clients {
close(ch)
}
h.clients = make(map[uint64]chan []byte)
h.clientsMu.Unlock()
h.logger.Info("msg", "HTTP sink stopped",
h.logger.Info("msg", " HTTP sink stopped",
"component", "http_sink",
"instance_id", h.id,
"total_processed", h.totalProcessed.Load())
}
// GetStats returns sink statistics
func (h *HTTPSink) GetStats() sink.SinkStats {
lastProc, _ := h.lastProcessed.Load().(time.Time)
// shutdown funnels ctx-cancel and Stop() teardown through a single path.
// done is closed first so SSE handlers exit and Shutdown can complete;
// Server.Close force-closes any handler stalled in a deadline-free write.
func (h *HTTPSink) shutdown() {
h.stopOnce.Do(func() {
close(h.done)
if h.server != nil {
sctx, cancel := context.WithTimeout(context.Background(), HTTPShutdownTimeout)
defer cancel()
if err := h.server.Shutdown(sctx); err != nil {
h.server.Close()
}
}
})
}
return sink.SinkStats{
ID: h.id,
Type: "http",
TotalProcessed: h.totalProcessed.Load(),
ActiveConnections: h.activeClients.Load(),
StartTime: h.startTime,
LastProcessed: lastProc,
Details: map[string]any{
"host": h.config.Host,
"port": h.config.Port,
"buffer_size": h.config.BufferSize,
"endpoints": map[string]string{
"stream": h.config.StreamPath,
"status": h.config.StatusPath,
},
},
// removeClient unregisters a client; the first caller closes the send
// channel and removes the session. Broker (stale-session eviction) and
// stream handler (disconnect) may race here safely.
func (h *HTTPSink) removeClient(id uint64) {
h.clientsMu.Lock()
c, ok := h.clients[id]
if ok {
delete(h.clients, id)
}
h.clientsMu.Unlock()
if ok {
close(c.send)
h.proxy.RemoveSession(c.sessionID)
}
}
// brokerLoop manages client connections and broadcasts transport events
// brokerLoop fans out transport events to all client queues, non-blocking,
// and evicts clients whose sessions were idle-expired by the session manager
func (h *HTTPSink) brokerLoop(ctx context.Context) {
defer h.wg.Done()
for {
select {
case <-ctx.Done():
h.logger.Debug("msg", "Broker loop stopping due to context cancellation",
"component", "http_sink")
return
case <-h.done:
h.logger.Debug("msg", "Broker loop stopping due to shutdown signal",
"component", "http_sink")
return
case clientID := <-h.unregister:
h.clientsMu.Lock()
if clientChan, exists := h.clients[clientID]; exists {
delete(h.clients, clientID)
close(clientChan)
h.logger.Debug("msg", "Unregistered client",
"component", "http_sink",
"client_id", clientID)
}
h.clientsMu.Unlock()
h.sessionsMu.Lock()
delete(h.clientSessions, clientID)
h.sessionsMu.Unlock()
case event, ok := <-h.input:
if !ok {
h.logger.Debug("msg", "Input channel closed, broker stopping",
"component", "http_sink")
return
}
h.totalProcessed.Add(1)
h.lastProcessed.Store(time.Now())
h.clientsMu.RLock()
clientCount := len(h.clients)
if clientCount > 0 {
var staleClients []uint64
for id, ch := range h.clients {
h.sessionsMu.RLock()
sessionID, hasSession := h.clientSessions[id]
h.sessionsMu.RUnlock()
if !hasSession {
staleClients = append(staleClients, id)
continue
}
// Check session still exists via proxy
if _, exists := h.proxy.GetSession(sessionID); !exists {
staleClients = append(staleClients, id)
continue
}
select {
case ch <- event.Payload:
h.proxy.UpdateActivity(sessionID)
default:
h.logger.Debug("msg", "Dropped event for slow client",
"component", "http_sink",
"client_id", id)
}
var stale []uint64
h.clientsMu.Lock()
for id, c := range h.clients {
if _, exists := h.proxy.GetSession(c.sessionID); !exists {
stale = append(stale, id)
continue
}
if len(staleClients) > 0 {
go func() {
for _, clientID := range staleClients {
select {
case h.unregister <- clientID:
case <-h.done:
return
}
}
}()
select {
case c.send <- event.Payload:
h.proxy.UpdateActivity(c.sessionID)
default:
h.droppedWrites.Add(1)
}
}
h.clientsMu.RUnlock()
h.clientsMu.Unlock()
for _, id := range stale {
h.removeClient(id)
}
}
}
}
// requestHandler is the main entry point for all incoming HTTP requests
func (h *HTTPSink) requestHandler(ctx *fasthttp.RequestCtx) {
// IPv4-only enforcement - silent drop IPv6
remoteAddr := ctx.RemoteAddr()
if tcpAddr, ok := remoteAddr.(*net.TCPAddr); ok {
if tcpAddr.IP.To4() == nil {
h.logger.Debug("msg", "IPv6 connection rejected",
"component", "http_sink", "remote_addr", remoteAddr.String())
ctx.SetConnectionClose()
return
}
// handleStream serves one client's SSE stream
func (h *HTTPSink) handleStream(w http.ResponseWriter, r *http.Request) {
if h.config.MaxConnections > 0 && h.activeClients.Load() >= h.config.MaxConnections {
h.rejectedClients.Add(1)
http.Error(w, "too many clients", http.StatusServiceUnavailable)
return
}
path := string(ctx.Path())
rc := http.NewResponseController(w)
remote := r.RemoteAddr
switch path {
case h.config.StatusPath:
h.handleStatus(ctx)
case h.config.StreamPath:
h.handleStream(ctx)
default:
ctx.SetStatusCode(fasthttp.StatusNotFound)
ctx.SetContentType("application/json")
json.NewEncoder(ctx).Encode(map[string]any{
"error": "Not Found",
})
}
}
// handleStream manages a client's Server-Sent Events (SSE) stream
func (h *HTTPSink) handleStream(ctx *fasthttp.RequestCtx) {
remoteAddrStr := ctx.RemoteAddr().String()
// Create session via proxy
sess := h.proxy.CreateSession(remoteAddrStr, map[string]any{
sess := h.proxy.CreateSession(remote, map[string]any{
"type": "http_client",
})
// Set SSE headers
ctx.Response.Header.Set("Content-Type", "text/event-stream")
ctx.Response.Header.Set("Cache-Control", "no-cache")
ctx.Response.Header.Set("Connection", "keep-alive")
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
ctx.Response.Header.Set("X-Accel-Buffering", "no")
// Register client with broker
clientID := h.nextClientID.Add(1)
clientChan := make(chan []byte, h.config.BufferSize)
c := &sseClient{
send: make(chan []byte, h.config.ClientBufferSize),
sessionID: sess.ID,
}
id := h.nextClientID.Add(1)
h.clientsMu.Lock()
h.clients[clientID] = clientChan
h.clients[id] = c
h.clientsMu.Unlock()
h.sessionsMu.Lock()
h.clientSessions[clientID] = sess.ID
h.sessionsMu.Unlock()
count := h.activeClients.Add(1)
h.logger.Debug("msg", "HTTP client connected",
"component", "http_sink",
"remote_addr", remote,
"session_id", sess.ID,
"client_id", id,
"active_clients", count)
streamFunc := func(w *bufio.Writer) {
connectCount := h.activeClients.Add(1)
h.logger.Debug("msg", "HTTP client connected",
defer func() {
h.removeClient(id)
newCount := h.activeClients.Add(-1)
h.logger.Debug("msg", "HTTP client disconnected",
"component", "http_sink",
"remote_addr", remoteAddrStr,
"remote_addr", remote,
"session_id", sess.ID,
"client_id", clientID,
"active_clients", connectCount)
"client_id", id,
"active_clients", newCount)
}()
defer func() {
disconnectCount := h.activeClients.Add(-1)
h.logger.Debug("msg", "HTTP client disconnected",
"component", "http_sink",
"remote_addr", remoteAddrStr,
"session_id", sess.ID,
"client_id", clientID,
"active_clients", disconnectCount)
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("X-Accel-Buffering", "no")
w.WriteHeader(http.StatusOK)
select {
case h.unregister <- clientID:
case <-h.done:
}
h.proxy.RemoveSession(sess.ID)
}()
// Send connected event with metadata
connectionInfo := map[string]any{
"client_id": fmt.Sprintf("%d", clientID),
"session_id": sess.ID,
"instance_id": h.id,
"stream_path": h.config.StreamPath,
"status_path": h.config.StatusPath,
"buffer_size": h.config.BufferSize,
}
data, _ := json.Marshal(connectionInfo)
fmt.Fprintf(w, "event: connected\ndata: %s\n\n", data)
if err := w.Flush(); err != nil {
return
}
for {
select {
case payload, ok := <-clientChan:
if !ok {
return
}
if err := h.writeSSE(w, payload); err != nil {
return
}
if err := w.Flush(); err != nil {
return
}
h.proxy.UpdateActivity(sess.ID)
case <-h.done:
fmt.Fprintf(w, "event: disconnect\ndata: {\"reason\":\"server_shutdown\"}\n\n")
w.Flush()
return
}
}
// Connected event with metadata, parity with fasthttp sink
info, _ := json.Marshal(map[string]any{
"client_id": strconv.FormatUint(id, 10),
"session_id": sess.ID,
"instance_id": h.id,
"stream_path": h.config.StreamPath,
"status_path": h.config.StatusPath,
"buffer_size": h.config.ClientBufferSize,
})
fmt.Fprintf(w, "event: connected\ndata: %s\n\n", info)
if err := rc.Flush(); err != nil {
return
}
ctx.SetBodyStreamWriter(streamFunc)
clientGone := r.Context().Done()
for {
select {
case payload, ok := <-c.send:
if !ok {
return // broker evicted (stale session)
}
if h.writeTimeout > 0 {
_ = rc.SetWriteDeadline(time.Now().Add(h.writeTimeout))
}
if err := writeSSE(w, payload); err != nil {
return
}
if err := rc.Flush(); err != nil {
return
}
h.proxy.UpdateActivity(sess.ID)
case <-clientGone:
return
case <-h.done:
fmt.Fprintf(w, "event: disconnect\ndata: {\"reason\":\"server_shutdown\"}\n\n")
rc.Flush()
return
}
}
}
// handleStatus provides a JSON status report
func (h *HTTPSink) handleStatus(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("application/json")
func (h *HTTPSink) handleStatus(w http.ResponseWriter, r *http.Request) {
status := map[string]any{
"service": "LogWisp",
"version": version.Short(),
@@ -491,41 +411,59 @@ func (h *HTTPSink) handleStatus(ctx *fasthttp.RequestCtx) {
"status": h.config.StatusPath,
},
"statistics": map[string]any{
"total_processed": h.totalProcessed.Load(),
"total_processed": h.totalProcessed.Load(),
"dropped_writes": h.droppedWrites.Load(),
"rejected_clients": h.rejectedClients.Load(),
},
}
data, _ := json.Marshal(status)
ctx.SetBody(data)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(status)
}
// writeSSE formats payload into SSE data format
func (h *HTTPSink) writeSSE(w *bufio.Writer, payload []byte) error {
// Handle multi-line payloads per W3C SSE spec
lines := splitLines(payload)
for _, line := range lines {
// GetStats returns sink statistics
func (h *HTTPSink) GetStats() sink.SinkStats {
lastProc, _ := h.lastProcessed.Load().(time.Time)
return sink.SinkStats{
ID: h.id,
Type: "http",
TotalProcessed: h.totalProcessed.Load(),
ActiveConnections: h.activeClients.Load(),
StartTime: h.startTime,
LastProcessed: lastProc,
Details: map[string]any{
"host": h.config.Host,
"port": h.config.Port,
"buffer_size": h.config.BufferSize,
"dropped_writes": h.droppedWrites.Load(),
"rejected_clients": h.rejectedClients.Load(),
"endpoints": map[string]string{
"stream": h.config.StreamPath,
"status": h.config.StatusPath,
},
},
}
}
// writeSSE frames a payload per the W3C SSE spec (multi-line safe)
func writeSSE(w http.ResponseWriter, payload []byte) error {
for _, line := range splitLines(payload) {
if _, err := fmt.Fprintf(w, "data: %s\n", line); err != nil {
return err
}
}
// Empty line terminates event
if _, err := w.WriteString("\n"); err != nil {
return err
}
return nil
_, err := fmt.Fprint(w, "\n")
return err
}
// splitLines splits payload by newlines, handling different line endings
// splitLines splits payload by newlines, trimming a single trailing newline
func splitLines(data []byte) [][]byte {
if len(data) == 0 {
return nil
}
// Trim trailing newline if present
if data[len(data)-1] == '\n' {
data = data[:len(data)-1]
}
var lines [][]byte
start := 0
for i := 0; i < len(data); i++ {
@@ -537,7 +475,6 @@ func splitLines(data []byte) [][]byte {
if start < len(data) {
lines = append(lines, data[start:])
}
if len(lines) == 0 {
return [][]byte{data}
}