Initial commit: unified dashboard suite state with Khira and Image Manipulator 3-file setup
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func EnvOr(key, fallback string) string {
|
||||
if val := os.Getenv(key); val != "" {
|
||||
return val
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func PrefixMiddleware(prefix string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// InitLogger configures structured JSON logging for a tool.
|
||||
// It ensures the log directory exists, opens logs/<toolName>.log,
|
||||
// and configures slog and log to output there.
|
||||
func InitLogger(toolName string) *os.File {
|
||||
logPath := os.Getenv("LOG_FILE")
|
||||
if logPath == "" {
|
||||
logPath = filepath.Join("logs", toolName+".log")
|
||||
}
|
||||
|
||||
dir := filepath.Dir(logPath)
|
||||
if dir != "" {
|
||||
_ = os.MkdirAll(dir, 0755)
|
||||
}
|
||||
|
||||
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "failed to open log file %s: %v\n", logPath, err)
|
||||
}
|
||||
|
||||
var writer io.Writer = os.Stdout
|
||||
if logFile != nil {
|
||||
if os.Getenv("MANAGED_BY_GATEWAY") == "1" {
|
||||
// Managed by gateway: gateway redirects stdout/stderr to logFile,
|
||||
// writing directly to logFile ensures immediate availability.
|
||||
writer = logFile
|
||||
} else {
|
||||
// Standalone run: duplicate to both stdout and log file
|
||||
writer = io.MultiWriter(os.Stdout, logFile)
|
||||
}
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewJSONHandler(writer, &slog.HandlerOptions{
|
||||
Level: slog.LevelInfo,
|
||||
}))
|
||||
slog.SetDefault(logger)
|
||||
log.SetOutput(writer)
|
||||
|
||||
return logFile
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type ToolConfig struct {
|
||||
Key string `mapstructure:"key"`
|
||||
Name string `mapstructure:"name"`
|
||||
Icon string `mapstructure:"icon"`
|
||||
Description string `mapstructure:"description"`
|
||||
Port int `mapstructure:"port"`
|
||||
InternalPort int `mapstructure:"internal_port"` // bound to 127.0.0.1 only
|
||||
Command string `mapstructure:"command"`
|
||||
Args []string `mapstructure:"args"`
|
||||
WorkDir string `mapstructure:"work_dir"`
|
||||
LogFile string `mapstructure:"log_file"`
|
||||
Category string `mapstructure:"category"`
|
||||
}
|
||||
|
||||
// Registry holds all loaded tools
|
||||
var Registry []ToolConfig
|
||||
|
||||
// LoadConfig loads the tools registry from a yaml file
|
||||
func LoadConfig(path string) error {
|
||||
viper.SetConfigFile(path)
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
return fmt.Errorf("error reading config file: %w", err)
|
||||
}
|
||||
|
||||
var config struct {
|
||||
Tools []ToolConfig `mapstructure:"tools"`
|
||||
}
|
||||
|
||||
if err := viper.Unmarshal(&config); err != nil {
|
||||
return fmt.Errorf("unable to decode into struct: %w", err)
|
||||
}
|
||||
|
||||
for i := range config.Tools {
|
||||
if config.Tools[i].LogFile == "" {
|
||||
config.Tools[i].LogFile = filepath.Join("logs", fmt.Sprintf("%s.log", config.Tools[i].Key))
|
||||
}
|
||||
if config.Tools[i].WorkDir == "" {
|
||||
config.Tools[i].WorkDir = "."
|
||||
}
|
||||
}
|
||||
|
||||
Registry = config.Tools
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ProcessState int
|
||||
|
||||
const (
|
||||
StateIdle ProcessState = iota
|
||||
StateStarting
|
||||
StateRunning
|
||||
StateFailed
|
||||
)
|
||||
|
||||
type ManagedProcess struct {
|
||||
Config ToolConfig
|
||||
Cmd *exec.Cmd
|
||||
State ProcessState
|
||||
mu sync.Mutex
|
||||
cancel context.CancelFunc
|
||||
LogFile *os.File
|
||||
}
|
||||
|
||||
type ProcessManager struct {
|
||||
processes map[string]*ManagedProcess
|
||||
mu sync.RWMutex
|
||||
rootCtx context.Context
|
||||
}
|
||||
|
||||
func NewProcessManager(ctx context.Context) *ProcessManager {
|
||||
return &ProcessManager{
|
||||
processes: make(map[string]*ManagedProcess),
|
||||
rootCtx: ctx,
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *ProcessManager) getConfig(toolID string) *ToolConfig {
|
||||
for i := range Registry {
|
||||
if Registry[i].Key == toolID {
|
||||
return &Registry[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func filterEnv(env []string, keysToRemove ...string) []string {
|
||||
var res []string
|
||||
removeMap := make(map[string]bool)
|
||||
for _, k := range keysToRemove {
|
||||
removeMap[k] = true
|
||||
}
|
||||
for _, e := range env {
|
||||
parts := strings.SplitN(e, "=", 2)
|
||||
if len(parts) > 0 && !removeMap[parts[0]] {
|
||||
res = append(res, e)
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func (pm *ProcessManager) cleanup(toolID string) {
|
||||
if proc, ok := pm.processes[toolID]; ok {
|
||||
if proc.cancel != nil {
|
||||
proc.cancel()
|
||||
}
|
||||
if proc.LogFile != nil {
|
||||
proc.LogFile.Close()
|
||||
}
|
||||
delete(pm.processes, toolID)
|
||||
}
|
||||
}
|
||||
|
||||
// IsRunning checks whether a tool's process is currently active and healthy.
|
||||
func (pm *ProcessManager) IsRunning(toolID string) bool {
|
||||
if toolID == "docs" || toolID == "khira" {
|
||||
return true
|
||||
}
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
proc, ok := pm.processes[toolID]
|
||||
if !ok || proc.Cmd == nil || proc.Cmd.Process == nil || proc.Cmd.ProcessState != nil {
|
||||
return false
|
||||
}
|
||||
return syscall.Kill(proc.Cmd.Process.Pid, 0) == nil
|
||||
}
|
||||
|
||||
// EnsureRunning launches the tool on demand if it is not currently running.
|
||||
func (pm *ProcessManager) EnsureRunning(ctx context.Context, toolID string) error {
|
||||
if pm.IsRunning(toolID) {
|
||||
return nil
|
||||
}
|
||||
cfg := pm.getConfig(toolID)
|
||||
if cfg == nil {
|
||||
return fmt.Errorf("unknown tool: %s", toolID)
|
||||
}
|
||||
if _, err := pm.Launch(toolID); err != nil {
|
||||
return err
|
||||
}
|
||||
return pm.waitReady(ctx, cfg.Port, 30, 100*time.Millisecond)
|
||||
}
|
||||
|
||||
func (pm *ProcessManager) Launch(toolID string) (string, error) {
|
||||
if toolID == "docs" {
|
||||
return "/docs/", nil
|
||||
}
|
||||
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
cfg := pm.getConfig(toolID)
|
||||
if cfg == nil {
|
||||
return "", fmt.Errorf("unknown tool: %s", toolID)
|
||||
}
|
||||
|
||||
// Already running?
|
||||
if proc, ok := pm.processes[toolID]; ok {
|
||||
isAlive := false
|
||||
if proc.Cmd != nil && proc.Cmd.Process != nil && proc.Cmd.ProcessState == nil {
|
||||
if err := syscall.Kill(proc.Cmd.Process.Pid, 0); err == nil {
|
||||
isAlive = true
|
||||
}
|
||||
}
|
||||
if isAlive {
|
||||
slog.Info("tool already running", "tool", toolID, "pid", proc.Cmd.Process.Pid)
|
||||
return fmt.Sprintf("/tool/%s/", toolID), nil
|
||||
}
|
||||
// Dead — clean up
|
||||
pm.cleanup(toolID)
|
||||
}
|
||||
|
||||
// Spawn
|
||||
ctx, cancel := context.WithCancel(pm.rootCtx)
|
||||
|
||||
logFilePath := cfg.LogFile
|
||||
if logFilePath == "" {
|
||||
logFilePath = filepath.Join("logs", toolID+".log")
|
||||
}
|
||||
|
||||
// ensure log directory exists
|
||||
if lastSlash := strings.LastIndex(logFilePath, "/"); lastSlash != -1 {
|
||||
os.MkdirAll(logFilePath[:lastSlash], 0755)
|
||||
}
|
||||
|
||||
logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
slog.Error("failed to open tool log file", "tool", toolID, "path", logFilePath, "err", err)
|
||||
}
|
||||
|
||||
env := os.Environ()
|
||||
// Remove inherited PORT and Flask reloader vars
|
||||
env = filterEnv(env, "PORT", "WERKZEUG_SERVER_FD", "WERKZEUG_RUN_MAIN")
|
||||
env = append(env, fmt.Sprintf("SCRIPT_NAME=/tool/%s", toolID))
|
||||
env = append(env, fmt.Sprintf("PORT=%d", cfg.Port))
|
||||
env = append(env, "MANAGED_BY_GATEWAY=1")
|
||||
env = append(env, fmt.Sprintf("LOG_FILE=%s", logFilePath))
|
||||
|
||||
cmd := exec.CommandContext(ctx, cfg.Command, cfg.Args...)
|
||||
cmd.Dir = cfg.WorkDir
|
||||
cmd.Env = env
|
||||
if logFile != nil {
|
||||
cmd.Stdout = logFile
|
||||
cmd.Stderr = logFile
|
||||
} else {
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
cancel()
|
||||
if logFile != nil {
|
||||
logFile.Close()
|
||||
}
|
||||
return "", fmt.Errorf("failed to start %s: %w", toolID, err)
|
||||
}
|
||||
|
||||
proc := &ManagedProcess{
|
||||
Config: *cfg,
|
||||
Cmd: cmd,
|
||||
State: StateStarting,
|
||||
cancel: cancel,
|
||||
LogFile: logFile,
|
||||
}
|
||||
pm.processes[toolID] = proc
|
||||
slog.Info("process started", "tool", toolID, "pid", cmd.Process.Pid, "log_file", logFilePath)
|
||||
|
||||
// Clean up process table when process exits
|
||||
go func() {
|
||||
_ = cmd.Wait()
|
||||
pm.mu.Lock()
|
||||
if p, exists := pm.processes[toolID]; exists && p == proc {
|
||||
pm.cleanup(toolID)
|
||||
}
|
||||
pm.mu.Unlock()
|
||||
}()
|
||||
|
||||
// Wait for readiness asynchronously
|
||||
go func() {
|
||||
if err := pm.waitReady(ctx, cfg.Port, 40, 500*time.Millisecond); err != nil {
|
||||
slog.Warn("tool slow to respond", "tool", toolID, "err", err)
|
||||
} else {
|
||||
slog.Info("tool is ready", "tool", toolID, "port", cfg.Port)
|
||||
}
|
||||
proc.State = StateRunning
|
||||
}()
|
||||
|
||||
return fmt.Sprintf("/tool/%s/", toolID), nil
|
||||
}
|
||||
|
||||
// waitReady polls the internal port with exponential backoff
|
||||
func (pm *ProcessManager) waitReady(ctx context.Context, port int, maxAttempts int, interval time.Duration) error {
|
||||
client := &http.Client{Timeout: 300 * time.Millisecond}
|
||||
url := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
for i := 0; i < maxAttempts; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
resp, err := client.Get(url)
|
||||
if err == nil && resp.StatusCode < 500 {
|
||||
resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
time.Sleep(interval)
|
||||
}
|
||||
return fmt.Errorf("tool not ready after %d attempts", maxAttempts)
|
||||
}
|
||||
|
||||
// GracefulShutdown sends SIGTERM to all children and waits with timeout
|
||||
func (pm *ProcessManager) GracefulShutdown(timeout time.Duration) {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
slog.Info("shutting down all managed processes", "count", len(pm.processes))
|
||||
var wg sync.WaitGroup
|
||||
for id, proc := range pm.processes {
|
||||
wg.Add(1)
|
||||
go func(id string, p *ManagedProcess) {
|
||||
defer wg.Done()
|
||||
p.cancel() // triggers SIGTERM via CommandContext
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
if p.Cmd != nil {
|
||||
p.Cmd.Wait()
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
slog.Info("process exited cleanly", "tool", id)
|
||||
case <-time.After(timeout):
|
||||
slog.Warn("force-killing process", "tool", id)
|
||||
if p.Cmd != nil && p.Cmd.Process != nil {
|
||||
p.Cmd.Process.Kill()
|
||||
}
|
||||
}
|
||||
if p.LogFile != nil {
|
||||
p.LogFile.Close()
|
||||
}
|
||||
}(id, proc)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
htmlAttrRegex = regexp.MustCompile(`(?i)(href|src|action|data-src|data-url)="(/[^"]*)"`)
|
||||
)
|
||||
|
||||
func rewriteHTMLResponse(resp *http.Response, toolID, prefix string) error {
|
||||
contentType := strings.ToLower(resp.Header.Get("Content-Type"))
|
||||
|
||||
// NEVER buffer streaming responses — SSE, chunked, binary, etc.
|
||||
// Only rewrite actual text/html pages.
|
||||
if !strings.Contains(contentType, "text/html") {
|
||||
return nil
|
||||
}
|
||||
// Also skip event-streams even if they somehow claim text/html
|
||||
if strings.Contains(contentType, "event-stream") {
|
||||
return nil
|
||||
}
|
||||
|
||||
bodyBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
htmlStr := string(bodyBytes)
|
||||
|
||||
// Rewrite attributes
|
||||
htmlStr = htmlAttrRegex.ReplaceAllStringFunc(htmlStr, func(match string) string {
|
||||
parts := htmlAttrRegex.FindStringSubmatch(match)
|
||||
if len(parts) == 3 {
|
||||
attr := parts[1]
|
||||
path := parts[2]
|
||||
if strings.HasPrefix(path, prefix) || strings.HasPrefix(path, "http") || strings.HasPrefix(path, "//") || strings.HasPrefix(path, "data:") {
|
||||
return match
|
||||
}
|
||||
return fmt.Sprintf(`%s="%s%s"`, attr, prefix, path)
|
||||
}
|
||||
return match
|
||||
})
|
||||
|
||||
// Inject JS shim right after <head> or at top if no head
|
||||
shim := fmt.Sprintf(`<script>
|
||||
(function(){
|
||||
var _P = '%s';
|
||||
function _fix(u) {
|
||||
if (typeof u !== 'string') return u;
|
||||
if (u.startsWith('/') && !u.startsWith(_P) && !u.startsWith('//')) return _P + u;
|
||||
return u;
|
||||
}
|
||||
// Patch fetch
|
||||
var _fetch = window.fetch;
|
||||
window.fetch = function(input, init) {
|
||||
if (typeof input === 'string') input = _fix(input);
|
||||
else if (input instanceof Request) {
|
||||
try { input = new Request(_fix(input.url), input); } catch(e) {}
|
||||
}
|
||||
return _fetch.call(this, input, init);
|
||||
};
|
||||
// Patch XHR
|
||||
var _open = XMLHttpRequest.prototype.open;
|
||||
XMLHttpRequest.prototype.open = function(method, url) {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args[1] = _fix(url);
|
||||
return _open.apply(this, args);
|
||||
};
|
||||
// Patch history
|
||||
var _push = history.pushState;
|
||||
history.pushState = function(state, title, url) {
|
||||
return _push.call(this, state, title, url ? _fix(url) : url);
|
||||
};
|
||||
var _replace = history.replaceState;
|
||||
history.replaceState = function(state, title, url) {
|
||||
return _replace.call(this, state, title, url ? _fix(url) : url);
|
||||
};
|
||||
// Patch EventSource (used for SSE streams)
|
||||
var _ES = window.EventSource;
|
||||
window.EventSource = function(url, cfg) {
|
||||
return new _ES(_fix(url), cfg);
|
||||
};
|
||||
window.EventSource.prototype = _ES.prototype;
|
||||
window.EventSource.CONNECTING = _ES.CONNECTING;
|
||||
window.EventSource.OPEN = _ES.OPEN;
|
||||
window.EventSource.CLOSED = _ES.CLOSED;
|
||||
})();
|
||||
</script>`, prefix)
|
||||
|
||||
headIdx := strings.Index(strings.ToLower(htmlStr), "<head>")
|
||||
if headIdx != -1 {
|
||||
htmlStr = htmlStr[:headIdx+6] + shim + htmlStr[headIdx+6:]
|
||||
} else {
|
||||
htmlStr = shim + htmlStr
|
||||
}
|
||||
|
||||
newBody := []byte(htmlStr)
|
||||
resp.Body = io.NopCloser(bytes.NewReader(newBody))
|
||||
resp.ContentLength = int64(len(newBody))
|
||||
resp.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// toolProxy creates a new ReverseProxy for a given tool port.
|
||||
func toolProxy(pm *ProcessManager, toolID string, port int) *httputil.ReverseProxy {
|
||||
target, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port))
|
||||
proxy := httputil.NewSingleHostReverseProxy(target)
|
||||
prefix := fmt.Sprintf("/tool/%s", toolID)
|
||||
|
||||
// FlushInterval=-1 means flush every write immediately.
|
||||
// This is required for SSE (text/event-stream) and chunked responses
|
||||
// to reach the browser in real-time instead of being buffered.
|
||||
proxy.FlushInterval = -1
|
||||
// Customize Director: strip prefix, set correct headers
|
||||
proxy.Director = func(req *http.Request) {
|
||||
if pm != nil && !pm.IsRunning(toolID) {
|
||||
slog.Info("auto-launching tool on demand", "tool", toolID)
|
||||
_ = pm.EnsureRunning(req.Context(), toolID)
|
||||
}
|
||||
|
||||
req.URL.Scheme = target.Scheme
|
||||
req.URL.Host = target.Host
|
||||
req.URL.Path = strings.TrimPrefix(req.URL.Path, prefix)
|
||||
if req.URL.Path == "" {
|
||||
req.URL.Path = "/"
|
||||
}
|
||||
req.Host = target.Host
|
||||
|
||||
// Force re-fetch so we can rewrite HTML (prevents 304 Not Modified)
|
||||
req.Header.Del("If-None-Match")
|
||||
req.Header.Del("If-Modified-Since")
|
||||
|
||||
// Forward real client IP
|
||||
if clientIP := req.Header.Get("X-Real-IP"); clientIP == "" {
|
||||
req.Header.Set("X-Real-IP", req.RemoteAddr)
|
||||
}
|
||||
req.Header.Set("X-Forwarded-Prefix", prefix)
|
||||
}
|
||||
|
||||
proxy.ModifyResponse = func(resp *http.Response) error {
|
||||
// Rewrite redirect Location headers
|
||||
if loc := resp.Header.Get("Location"); loc != "" {
|
||||
if strings.HasPrefix(loc, "/") && !strings.HasPrefix(loc, prefix) {
|
||||
resp.Header.Set("Location", prefix+loc)
|
||||
}
|
||||
}
|
||||
return rewriteHTMLResponse(resp, toolID, prefix)
|
||||
}
|
||||
|
||||
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
slog.Error("tool proxy forwarding error", "tool", toolID, "path", r.URL.Path, "err", err)
|
||||
http.Error(w, fmt.Sprintf("Tool %s proxy error: %v", toolID, err), http.StatusBadGateway)
|
||||
}
|
||||
|
||||
return proxy
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"unified-dashboard/internal/khira"
|
||||
mymiddleware "unified-dashboard/internal/middleware"
|
||||
)
|
||||
|
||||
type DashboardData struct {
|
||||
ExclusiveTool DashboardTool
|
||||
KhiraTool DashboardTool
|
||||
Tools []DashboardTool
|
||||
TotalTools int
|
||||
}
|
||||
|
||||
type DashboardTool struct {
|
||||
Key string
|
||||
Name string
|
||||
Icon string
|
||||
Description string
|
||||
Category string
|
||||
Path string
|
||||
Exclusive bool
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, data any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func dashboardHandler(w http.ResponseWriter, r *http.Request) {
|
||||
tmpl, err := template.ParseFiles("web/dashboard/index.html")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
exclusive := DashboardTool{
|
||||
Key: "docs",
|
||||
Name: "FastAPI Backend API Docs",
|
||||
Icon: "fa-solid fa-book-bookmark",
|
||||
Description: "Complete interactive API reference, schema definitions, endpoints, models and request/response specifications for the FastAPI Generative AI Backend services.",
|
||||
Category: "API Documentation",
|
||||
Path: "/docs/",
|
||||
Exclusive: true,
|
||||
}
|
||||
|
||||
khiraTool := DashboardTool{
|
||||
Key: "khira",
|
||||
Name: "Khira Dev Ticketing System",
|
||||
Icon: "fa-solid fa-ticket-simple",
|
||||
Description: "Interactive cross-team developer ticketing system. Report issues across frontend, backend and QA teams with API details, priority assignment, hold/resume workflows, resolution remarks and live browser notifications.",
|
||||
Category: "Dev Productivity & QA",
|
||||
Path: "/khira/",
|
||||
Exclusive: true,
|
||||
}
|
||||
|
||||
var tools []DashboardTool
|
||||
for _, t := range Registry {
|
||||
if t.Key == "docs" || t.Key == "khira" {
|
||||
continue
|
||||
}
|
||||
tools = append(tools, DashboardTool{
|
||||
Key: t.Key,
|
||||
Name: t.Name,
|
||||
Icon: t.Icon,
|
||||
Description: t.Description,
|
||||
Category: t.Category,
|
||||
Path: fmt.Sprintf("/tool/%s/", t.Key),
|
||||
})
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
tmpl.Execute(w, DashboardData{
|
||||
ExclusiveTool: exclusive,
|
||||
KhiraTool: khiraTool,
|
||||
Tools: tools,
|
||||
TotalTools: len(tools) + 2,
|
||||
})
|
||||
}
|
||||
|
||||
const (
|
||||
docsRequiredPassword = "docdoc@crecre"
|
||||
docsAuthCookieName = "nexus_docs_session"
|
||||
docsAdminUser = "admin"
|
||||
docsAdminPassword = "Polonium#209.00"
|
||||
docsAdminCookieName = "nexus_docs_admin_session"
|
||||
docsSessionDuration = 10 * time.Minute // 10 minutes session duration
|
||||
docsSalt = "nexus_docs_salt_2026"
|
||||
docsAdminSalt = "nexus_admin_salt_2026"
|
||||
)
|
||||
|
||||
func makeTimedToken(secret string, salt string) string {
|
||||
now := time.Now().Unix()
|
||||
payload := fmt.Sprintf("%d:%s:%s", now, secret, salt)
|
||||
sig := fmt.Sprintf("%x", sha256.Sum256([]byte(payload)))
|
||||
return fmt.Sprintf("%d.%s", now, sig)
|
||||
}
|
||||
|
||||
func verifyTimedToken(token string, secret string, salt string) (bool, int64) {
|
||||
parts := strings.SplitN(token, ".", 2)
|
||||
if len(parts) != 2 {
|
||||
return false, 0
|
||||
}
|
||||
ts, err := strconv.ParseInt(parts[0], 10, 64)
|
||||
if err != nil {
|
||||
return false, 0
|
||||
}
|
||||
issuedAt := time.Unix(ts, 0)
|
||||
now := time.Now()
|
||||
elapsed := now.Sub(issuedAt)
|
||||
if elapsed < 0 || elapsed > docsSessionDuration {
|
||||
return false, 0 // Expired after 10 minutes
|
||||
}
|
||||
expectedPayload := fmt.Sprintf("%d:%s:%s", ts, secret, salt)
|
||||
expectedSig := fmt.Sprintf("%x", sha256.Sum256([]byte(expectedPayload)))
|
||||
if subtle.ConstantTimeCompare([]byte(parts[1]), []byte(expectedSig)) != 1 {
|
||||
return false, 0
|
||||
}
|
||||
remaining := int64(docsSessionDuration.Seconds() - elapsed.Seconds())
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
return true, remaining
|
||||
}
|
||||
|
||||
func isDocsAuthenticated(r *http.Request) bool {
|
||||
cookie, err := r.Cookie(docsAuthCookieName)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
valid, _ := verifyTimedToken(cookie.Value, docsRequiredPassword, docsSalt)
|
||||
return valid
|
||||
}
|
||||
|
||||
func getDocsSessionRemaining(r *http.Request) (bool, int64) {
|
||||
cookie, err := r.Cookie(docsAuthCookieName)
|
||||
if err != nil {
|
||||
return false, 0
|
||||
}
|
||||
return verifyTimedToken(cookie.Value, docsRequiredPassword, docsSalt)
|
||||
}
|
||||
|
||||
func isDocsAdminAuthenticated(r *http.Request) bool {
|
||||
if cookie, err := r.Cookie(docsAdminCookieName); err == nil {
|
||||
valid, _ := verifyTimedToken(cookie.Value, docsAdminUser+":"+docsAdminPassword, docsAdminSalt)
|
||||
if valid {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if user, pass, ok := r.BasicAuth(); ok {
|
||||
if user == docsAdminUser && pass == docsAdminPassword {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func renderDocsLogin(w http.ResponseWriter, r *http.Request, errMsg string) {
|
||||
tmpl, err := template.ParseFiles("web/docs/login.html")
|
||||
if err != nil {
|
||||
http.Error(w, "Documentation authentication required. Please enter password.", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
tmpl.Execute(w, map[string]string{
|
||||
"Error": errMsg,
|
||||
})
|
||||
}
|
||||
|
||||
func renderDocsAdminLogin(w http.ResponseWriter, r *http.Request, errMsg string) {
|
||||
tmpl, err := template.ParseFiles("web/docs/admin_login.html")
|
||||
if err != nil {
|
||||
http.Error(w, "Admin authentication required. Enter admin credentials.", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
tmpl.Execute(w, map[string]string{
|
||||
"Error": errMsg,
|
||||
})
|
||||
}
|
||||
|
||||
func healthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func prometheusHandler(w http.ResponseWriter, r *http.Request) {
|
||||
promhttp.Handler().ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func NewRouter(pm *ProcessManager) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
// Global middleware stack
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(mymiddleware.RequestLogger) // slog-based
|
||||
r.Use(middleware.Recoverer)
|
||||
r.Use(middleware.Compress(5)) // gzip
|
||||
|
||||
// Dashboard
|
||||
r.Get("/", dashboardHandler)
|
||||
r.Get("/health", healthHandler)
|
||||
r.Get("/metrics", prometheusHandler)
|
||||
|
||||
loginDocsHandler := func(w http.ResponseWriter, r *http.Request) {
|
||||
var password string
|
||||
if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
|
||||
var reqBody struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&reqBody); err == nil {
|
||||
password = reqBody.Password
|
||||
}
|
||||
} else {
|
||||
_ = r.ParseForm()
|
||||
password = r.FormValue("password")
|
||||
}
|
||||
|
||||
wantsJSON := strings.Contains(r.Header.Get("Accept"), "application/json") ||
|
||||
strings.Contains(r.Header.Get("Content-Type"), "application/json")
|
||||
|
||||
if strings.TrimSpace(password) == docsRequiredPassword {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: docsAuthCookieName,
|
||||
Value: makeTimedToken(docsRequiredPassword, docsSalt),
|
||||
Path: "/",
|
||||
MaxAge: int(docsSessionDuration.Seconds()), // 10 minutes = 600s
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
|
||||
if wantsJSON {
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": "ok",
|
||||
"redirect": "/docs/",
|
||||
})
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/docs/", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
if wantsJSON {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]interface{}{
|
||||
"status": "error",
|
||||
"error": "Invalid password. Access denied.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
renderDocsLogin(w, r, "Invalid password. Access denied.")
|
||||
}
|
||||
|
||||
logoutDocsHandler := func(w http.ResponseWriter, r *http.Request) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: docsAuthCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
http.Redirect(w, r, "/docs/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// Documentation Admin & Editor Handlers
|
||||
editorHandler := func(w http.ResponseWriter, req *http.Request) {
|
||||
if !isDocsAdminAuthenticated(req) {
|
||||
renderDocsAdminLogin(w, req, "")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
http.ServeFile(w, req, "web/docs/editor.html")
|
||||
}
|
||||
|
||||
loginEditorHandler := func(w http.ResponseWriter, r *http.Request) {
|
||||
var username, password string
|
||||
|
||||
if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
username = body.Username
|
||||
password = body.Password
|
||||
} else {
|
||||
_ = r.ParseForm()
|
||||
username = r.FormValue("username")
|
||||
password = r.FormValue("password")
|
||||
}
|
||||
|
||||
wantsJSON := strings.Contains(r.Header.Get("Accept"), "application/json") ||
|
||||
strings.Contains(r.Header.Get("Content-Type"), "application/json")
|
||||
|
||||
if strings.TrimSpace(username) == docsAdminUser && strings.TrimSpace(password) == docsAdminPassword {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: docsAdminCookieName,
|
||||
Value: makeTimedToken(docsAdminUser+":"+docsAdminPassword, docsAdminSalt),
|
||||
Path: "/",
|
||||
MaxAge: int(docsSessionDuration.Seconds()), // 10 minutes = 600s
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
// Also ensure docs reader session is active for 10 minutes
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: docsAuthCookieName,
|
||||
Value: makeTimedToken(docsRequiredPassword, docsSalt),
|
||||
Path: "/",
|
||||
MaxAge: int(docsSessionDuration.Seconds()), // 10 minutes = 600s
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
|
||||
if wantsJSON {
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": "ok",
|
||||
"redirect": "/docs/editor",
|
||||
})
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/docs/editor", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
if wantsJSON {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]interface{}{
|
||||
"status": "error",
|
||||
"error": "Invalid admin username or password. Access denied.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
renderDocsAdminLogin(w, r, "Invalid admin username or password. Access denied.")
|
||||
}
|
||||
|
||||
logoutEditorHandler := func(w http.ResponseWriter, r *http.Request) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: docsAdminCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
http.Redirect(w, r, "/docs/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
saveEditorHandler := func(w http.ResponseWriter, r *http.Request) {
|
||||
if !isDocsAdminAuthenticated(r) {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]interface{}{
|
||||
"status": "error",
|
||||
"error": "Unauthorized. Admin credentials required.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
HTML string `json:"html"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil || len(payload.HTML) < 100 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]interface{}{
|
||||
"status": "error",
|
||||
"error": "Invalid HTML payload received.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Save both index.html and FASTAPI_BACKEND_API_DOCS.html
|
||||
if err := os.WriteFile("web/docs/index.html", []byte(payload.HTML), 0644); err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]interface{}{
|
||||
"status": "error",
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
_ = os.WriteFile("web/docs/FASTAPI_BACKEND_API_DOCS.html", []byte(payload.HTML), 0644)
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": "ok",
|
||||
"bytes_written": len(payload.HTML),
|
||||
})
|
||||
}
|
||||
|
||||
// Documentation Routes (/docs and /docs/)
|
||||
docsHandler := func(w http.ResponseWriter, req *http.Request) {
|
||||
if !isDocsAuthenticated(req) {
|
||||
renderDocsLogin(w, req, "")
|
||||
return
|
||||
}
|
||||
filePath := "web/docs/index.html"
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
filePath = "web/docs/FASTAPI_BACKEND_API_DOCS.html"
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
http.ServeFile(w, req, filePath)
|
||||
}
|
||||
|
||||
// Admin Editor Routes
|
||||
r.Get("/docs/editor", editorHandler)
|
||||
r.Head("/docs/editor", editorHandler)
|
||||
r.Get("/docs/editor/", editorHandler)
|
||||
r.Head("/docs/editor/", editorHandler)
|
||||
r.Get("/docs/editor.html", editorHandler)
|
||||
r.Post("/docs/editor/login", loginEditorHandler)
|
||||
r.Get("/docs/editor/logout", logoutEditorHandler)
|
||||
r.Post("/docs/editor/logout", logoutEditorHandler)
|
||||
r.Post("/docs/editor/save", saveEditorHandler)
|
||||
|
||||
r.Get("/docs", func(w http.ResponseWriter, req *http.Request) {
|
||||
http.Redirect(w, req, "/docs/", http.StatusMovedPermanently)
|
||||
})
|
||||
r.Head("/docs", func(w http.ResponseWriter, req *http.Request) {
|
||||
http.Redirect(w, req, "/docs/", http.StatusMovedPermanently)
|
||||
})
|
||||
r.Get("/docs/", docsHandler)
|
||||
r.Head("/docs/", docsHandler)
|
||||
r.Post("/docs/login", loginDocsHandler)
|
||||
r.Get("/docs/logout", logoutDocsHandler)
|
||||
r.Post("/docs/logout", logoutDocsHandler)
|
||||
r.Get("/docs/session", func(w http.ResponseWriter, req *http.Request) {
|
||||
valid, remaining := getDocsSessionRemaining(req)
|
||||
if !valid {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]interface{}{
|
||||
"authenticated": false,
|
||||
"remaining_seconds": 0,
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"authenticated": true,
|
||||
"remaining_seconds": remaining,
|
||||
"expires_in": fmt.Sprintf("%dm %ds", remaining/60, remaining%60),
|
||||
})
|
||||
})
|
||||
r.Get("/docs/data.json", func(w http.ResponseWriter, req *http.Request) {
|
||||
paths := []string{"web/docs/data.json", "scratch/faithful_docs_data.json"}
|
||||
for _, p := range paths {
|
||||
if b, err := os.ReadFile(p); err == nil {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(b)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "data not found"})
|
||||
})
|
||||
r.Get("/docs/health", func(w http.ResponseWriter, req *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
})
|
||||
r.Head("/docs/health", func(w http.ResponseWriter, req *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
})
|
||||
r.Get("/docs/*", func(w http.ResponseWriter, req *http.Request) {
|
||||
if strings.HasSuffix(req.URL.Path, "/session") {
|
||||
valid, remaining := getDocsSessionRemaining(req)
|
||||
if !valid {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]interface{}{
|
||||
"authenticated": false,
|
||||
"remaining_seconds": 0,
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"authenticated": true,
|
||||
"remaining_seconds": remaining,
|
||||
"expires_in": fmt.Sprintf("%dm %ds", remaining/60, remaining%60),
|
||||
})
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(req.URL.Path, "/docs/editor") {
|
||||
if strings.HasSuffix(req.URL.Path, "/login") {
|
||||
renderDocsAdminLogin(w, req, "")
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(req.URL.Path, "/logout") {
|
||||
logoutEditorHandler(w, req)
|
||||
return
|
||||
}
|
||||
editorHandler(w, req)
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(req.URL.Path, "/health") {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(req.URL.Path, "/login") {
|
||||
renderDocsLogin(w, req, "")
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(req.URL.Path, "/logout") {
|
||||
logoutDocsHandler(w, req)
|
||||
return
|
||||
}
|
||||
docsHandler(w, req)
|
||||
})
|
||||
r.Head("/docs/*", func(w http.ResponseWriter, req *http.Request) {
|
||||
if strings.HasPrefix(req.URL.Path, "/docs/editor") {
|
||||
editorHandler(w, req)
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(req.URL.Path, "/health") {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
return
|
||||
}
|
||||
docsHandler(w, req)
|
||||
})
|
||||
|
||||
// Initialize Khira ticketing store & routes
|
||||
khiraStore, err := khira.NewStore("data/khira")
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "warning: failed to init khira store: %v\n", err)
|
||||
}
|
||||
khiraServer := khira.NewServer(khiraStore)
|
||||
|
||||
r.Route("/khira", func(kr chi.Router) {
|
||||
khiraServer.RegisterRoutes(kr)
|
||||
})
|
||||
r.Get("/tool/khira", func(w http.ResponseWriter, req *http.Request) {
|
||||
http.Redirect(w, req, "/khira/", http.StatusTemporaryRedirect)
|
||||
})
|
||||
r.Get("/tool/khira/*", func(w http.ResponseWriter, req *http.Request) {
|
||||
http.Redirect(w, req, "/khira/", http.StatusTemporaryRedirect)
|
||||
})
|
||||
|
||||
// Tool launcher — idempotent (POST is best to bypass CDN caching)
|
||||
r.Post("/launch/{toolID}", func(w http.ResponseWriter, r *http.Request) {
|
||||
toolID := chi.URLParam(r, "toolID")
|
||||
if toolID == "docs" {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "started", "path": "/docs/"})
|
||||
return
|
||||
}
|
||||
if toolID == "khira" {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "started", "path": "/khira/"})
|
||||
return
|
||||
}
|
||||
path, err := pm.Launch(toolID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "started", "path": path})
|
||||
})
|
||||
|
||||
// Per-tool reverse proxy — catch-all under /tool/<id>/
|
||||
for _, cfg := range Registry {
|
||||
if cfg.Port == 0 || cfg.Command == "" {
|
||||
continue // Static or internal tools handled directly
|
||||
}
|
||||
cfg := cfg // capture loop var
|
||||
prefix := "/tool/" + cfg.Key
|
||||
r.Mount(prefix, http.StripPrefix(prefix, toolProxy(pm, cfg.Key, cfg.Port)))
|
||||
}
|
||||
|
||||
// Route /tool/docs to /docs/
|
||||
r.Get("/tool/docs", func(w http.ResponseWriter, req *http.Request) {
|
||||
http.Redirect(w, req, "/docs/", http.StatusTemporaryRedirect)
|
||||
})
|
||||
r.Get("/tool/docs/*", func(w http.ResponseWriter, req *http.Request) {
|
||||
http.Redirect(w, req, "/docs/", http.StatusTemporaryRedirect)
|
||||
})
|
||||
|
||||
// Special custom domain routing for Image Hoster (/hoster -> image-hoster:/files)
|
||||
r.Route("/hoster", func(r chi.Router) {
|
||||
r.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
// Find image-hoster config
|
||||
var cfg *ToolConfig
|
||||
for i := range Registry {
|
||||
if Registry[i].Key == "image-hoster" {
|
||||
cfg = &Registry[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if cfg == nil {
|
||||
http.Error(w, "Image Hoster not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure it is running
|
||||
_ = pm.EnsureRunning(req.Context(), "image-hoster")
|
||||
|
||||
// Rewrite URL from /hoster/SID/file to /files/SID/file
|
||||
originalPath := req.URL.Path
|
||||
req.URL.Path = "/files" + strings.TrimPrefix(originalPath, "/hoster")
|
||||
|
||||
// Proxy
|
||||
proxy := toolProxy(pm, "image-hoster", cfg.Port)
|
||||
proxy.ServeHTTP(w, req)
|
||||
}))
|
||||
})
|
||||
|
||||
// Fallback routing aliases for Image Manipulator batch operations
|
||||
r.HandleFunc("/upload-batch", func(w http.ResponseWriter, req *http.Request) {
|
||||
_ = pm.EnsureRunning(req.Context(), "image-manipulator")
|
||||
cfg := pm.getConfig("image-manipulator")
|
||||
if cfg != nil {
|
||||
proxy := toolProxy(pm, "image-manipulator", cfg.Port)
|
||||
proxy.ServeHTTP(w, req)
|
||||
return
|
||||
}
|
||||
http.Error(w, "Image manipulator not found", http.StatusNotFound)
|
||||
})
|
||||
|
||||
r.HandleFunc("/batch-process-session", func(w http.ResponseWriter, req *http.Request) {
|
||||
_ = pm.EnsureRunning(req.Context(), "image-manipulator")
|
||||
cfg := pm.getConfig("image-manipulator")
|
||||
if cfg != nil {
|
||||
proxy := toolProxy(pm, "image-manipulator", cfg.Port)
|
||||
proxy.ServeHTTP(w, req)
|
||||
return
|
||||
}
|
||||
http.Error(w, "Image manipulator not found", http.StatusNotFound)
|
||||
})
|
||||
|
||||
r.HandleFunc("/preview-batch", func(w http.ResponseWriter, req *http.Request) {
|
||||
_ = pm.EnsureRunning(req.Context(), "image-manipulator")
|
||||
cfg := pm.getConfig("image-manipulator")
|
||||
if cfg != nil {
|
||||
proxy := toolProxy(pm, "image-manipulator", cfg.Port)
|
||||
proxy.ServeHTTP(w, req)
|
||||
return
|
||||
}
|
||||
http.Error(w, "Image manipulator not found", http.StatusNotFound)
|
||||
})
|
||||
|
||||
r.HandleFunc("/download-batch", func(w http.ResponseWriter, req *http.Request) {
|
||||
_ = pm.EnsureRunning(req.Context(), "image-manipulator")
|
||||
cfg := pm.getConfig("image-manipulator")
|
||||
if cfg != nil {
|
||||
proxy := toolProxy(pm, "image-manipulator", cfg.Port)
|
||||
proxy.ServeHTTP(w, req)
|
||||
return
|
||||
}
|
||||
http.Error(w, "Image manipulator not found", http.StatusNotFound)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,186 @@
|
||||
package khira
|
||||
|
||||
import "time"
|
||||
|
||||
type Role string
|
||||
|
||||
const (
|
||||
RoleFrontend Role = "frontend_dev"
|
||||
RoleBackend Role = "backend_dev"
|
||||
RoleTester Role = "tester"
|
||||
RoleLead Role = "team_lead"
|
||||
)
|
||||
|
||||
func (r Role) DisplayName() string {
|
||||
switch r {
|
||||
case RoleFrontend:
|
||||
return "Frontend Dev"
|
||||
case RoleBackend:
|
||||
return "Backend Dev"
|
||||
case RoleTester:
|
||||
return "Tester"
|
||||
case RoleLead:
|
||||
return "Team Lead"
|
||||
default:
|
||||
return string(r)
|
||||
}
|
||||
}
|
||||
|
||||
func (r Role) IsValid() bool {
|
||||
switch r {
|
||||
case RoleFrontend, RoleBackend, RoleTester, RoleLead:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
PasswordHash string `json:"password_hash,omitempty"`
|
||||
Role string `json:"role"`
|
||||
RoleDisplay string `json:"role_display"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (u *User) Public() *User {
|
||||
if u == nil {
|
||||
return nil
|
||||
}
|
||||
clone := *u
|
||||
clone.PasswordHash = ""
|
||||
return &clone
|
||||
}
|
||||
|
||||
type Priority string
|
||||
|
||||
const (
|
||||
PriorityCritical Priority = "critical"
|
||||
PriorityHigh Priority = "high"
|
||||
PriorityMedium Priority = "medium"
|
||||
PriorityLow Priority = "low"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusOpen Status = "open"
|
||||
StatusInProgress Status = "in_progress"
|
||||
StatusOnHold Status = "on_hold"
|
||||
StatusCompleted Status = "completed"
|
||||
StatusClosed Status = "closed"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Size int64 `json:"size"`
|
||||
Type string `json:"type"` // "file", "image", "link"
|
||||
UploadedBy string `json:"uploaded_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Remark struct {
|
||||
ID string `json:"id"`
|
||||
AuthorUsername string `json:"author_username"`
|
||||
AuthorName string `json:"author_name"`
|
||||
AuthorRole string `json:"author_role"`
|
||||
Type string `json:"type"` // comment, hold, resume, complete, priority_change, reassign, created, attachment, link
|
||||
Text string `json:"text"`
|
||||
Attachments []Attachment `json:"attachments,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Ticket struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
TicketType string `json:"ticket_type"` // "general" | "application"
|
||||
GeneralCategory string `json:"general_category,omitempty"`
|
||||
Department string `json:"department,omitempty"`
|
||||
AppName string `json:"app_name,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
FeatureName string `json:"feature_name,omitempty"`
|
||||
APIKey string `json:"api_key,omitempty"`
|
||||
IssueType string `json:"issue_type,omitempty"`
|
||||
Priority string `json:"priority"`
|
||||
Status string `json:"status"`
|
||||
Description string `json:"description"`
|
||||
AssistanceRequired string `json:"assistance_required"`
|
||||
AdditionalInfo string `json:"additional_info,omitempty"`
|
||||
CreatedBy string `json:"created_by"`
|
||||
CreatedByName string `json:"created_by_name"`
|
||||
CreatedByRole string `json:"created_by_role"`
|
||||
AssignedTo string `json:"assigned_to"`
|
||||
AssignedToName string `json:"assigned_to_name"`
|
||||
AssignedToRole string `json:"assigned_to_role"`
|
||||
HoldReason string `json:"hold_reason,omitempty"`
|
||||
HeldBy string `json:"held_by,omitempty"`
|
||||
HeldAt *time.Time `json:"held_at,omitempty"`
|
||||
CompletionRemarks string `json:"completion_remarks,omitempty"`
|
||||
CompletedBy string `json:"completed_by,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
Attachments []Attachment `json:"attachments,omitempty"`
|
||||
Links []string `json:"links,omitempty"`
|
||||
LinkedErrorID string `json:"linked_error_id,omitempty"`
|
||||
Remarks []Remark `json:"remarks"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ErrorSeverity string
|
||||
|
||||
const (
|
||||
SeverityCritical ErrorSeverity = "critical"
|
||||
SeverityHigh ErrorSeverity = "high"
|
||||
SeverityMedium ErrorSeverity = "medium"
|
||||
SeverityLow ErrorSeverity = "low"
|
||||
)
|
||||
|
||||
type ErrorStatus string
|
||||
|
||||
const (
|
||||
ErrorStatusUnresolved ErrorStatus = "unresolved"
|
||||
ErrorStatusInvestigating ErrorStatus = "investigating"
|
||||
ErrorStatusResolved ErrorStatus = "resolved"
|
||||
ErrorStatusIgnored ErrorStatus = "ignored"
|
||||
)
|
||||
|
||||
type AppError struct {
|
||||
ID string `json:"id"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
AppName string `json:"app_name"`
|
||||
Version string `json:"version"`
|
||||
Environment string `json:"environment"` // production, staging, development
|
||||
Service string `json:"service"` // feature / subsystem name
|
||||
Endpoint string `json:"endpoint,omitempty"`
|
||||
ExceptionType string `json:"exception_type"`
|
||||
Message string `json:"message"`
|
||||
StackTrace string `json:"stack_trace"`
|
||||
Severity string `json:"severity"` // critical, high, medium, low
|
||||
Status string `json:"status"` // unresolved, investigating, resolved, ignored
|
||||
Occurrences int `json:"occurrences"`
|
||||
FirstSeen time.Time `json:"first_seen"`
|
||||
LastSeen time.Time `json:"last_seen"`
|
||||
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
|
||||
ResolvedBy string `json:"resolved_by,omitempty"`
|
||||
ResolutionNotes string `json:"resolution_notes,omitempty"`
|
||||
LinkedTicketID string `json:"linked_ticket_id,omitempty"`
|
||||
CreatedBy string `json:"created_by"`
|
||||
RequestPayload string `json:"request_payload,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
}
|
||||
|
||||
type Notification struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
TicketID string `json:"ticket_id"`
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"` // assignment, status_change, hold, complete, remark
|
||||
Read bool `json:"read"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,44 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
)
|
||||
|
||||
// RequestLogger is a middleware that logs each request using slog
|
||||
func RequestLogger(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
start := time.Now()
|
||||
|
||||
defer func() {
|
||||
status := ww.Status()
|
||||
duration := time.Since(start).Milliseconds()
|
||||
reqID := middleware.GetReqID(r.Context())
|
||||
|
||||
attrs := []any{
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", status,
|
||||
"duration_ms", duration,
|
||||
"bytes", ww.BytesWritten(),
|
||||
"remote_addr", r.RemoteAddr,
|
||||
}
|
||||
if reqID != "" {
|
||||
attrs = append(attrs, "request_id", reqID)
|
||||
}
|
||||
|
||||
if status >= 500 {
|
||||
slog.Error("http request error", attrs...)
|
||||
} else if status >= 400 {
|
||||
slog.Warn("http request warning", attrs...)
|
||||
} else {
|
||||
slog.Info("http request", attrs...)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(ww, r)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user