| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 4 | "bytes" |
| 5 | "embed" |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 6 | "fmt" |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 7 | "html/template" |
| 8 | "io/fs" |
| Akron | 8006720 | 2025-06-06 14:16:25 +0200 | [diff] [blame] | 9 | "net/url" |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 10 | "os" |
| 11 | "os/signal" |
| Akron | 8006720 | 2025-06-06 14:16:25 +0200 | [diff] [blame] | 12 | "path" |
| Akron | 14678dc | 2025-06-05 13:01:38 +0200 | [diff] [blame] | 13 | "path/filepath" |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 14 | "strconv" |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 15 | "strings" |
| 16 | "syscall" |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 17 | texttemplate "text/template" |
| Akron | 3caee16 | 2025-07-01 17:44:58 +0200 | [diff] [blame] | 18 | "time" |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 19 | |
| Akron | 2ef703c | 2025-07-03 15:57:42 +0200 | [diff] [blame] | 20 | "github.com/KorAP/Koral-Mapper/config" |
| 21 | "github.com/KorAP/Koral-Mapper/mapper" |
| Akron | 1fc750e | 2025-05-26 16:54:18 +0200 | [diff] [blame] | 22 | "github.com/alecthomas/kong" |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 23 | "github.com/gofiber/fiber/v2" |
| 24 | "github.com/rs/zerolog" |
| 25 | "github.com/rs/zerolog/log" |
| 26 | ) |
| 27 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 28 | //go:embed static/* |
| 29 | var staticFS embed.FS |
| 30 | |
| Akron | 74e1c07 | 2025-05-26 14:38:25 +0200 | [diff] [blame] | 31 | const ( |
| 32 | maxInputLength = 1024 * 1024 // 1MB |
| 33 | maxParamLength = 1024 // 1KB |
| 34 | ) |
| 35 | |
| Akron | a00d475 | 2025-05-26 17:34:36 +0200 | [diff] [blame] | 36 | type appConfig struct { |
| Akron | a8a66ce | 2025-06-05 10:50:17 +0200 | [diff] [blame] | 37 | Port *int `kong:"short='p',help='Port to listen on'"` |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 38 | Config string `kong:"short='c',help='YAML configuration file containing mapping directives and global settings'"` |
| Akron | 14678dc | 2025-06-05 13:01:38 +0200 | [diff] [blame] | 39 | Mappings []string `kong:"short='m',help='Individual YAML mapping files to load (supports glob patterns like dir/*.yaml)'"` |
| Akron | a8a66ce | 2025-06-05 10:50:17 +0200 | [diff] [blame] | 40 | LogLevel *string `kong:"short='l',help='Log level (debug, info, warn, error)'"` |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 41 | } |
| 42 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 43 | type BasePageData struct { |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 44 | Title string |
| 45 | Version string |
| Akron | fc77b5e | 2025-06-04 11:44:43 +0200 | [diff] [blame] | 46 | Hash string |
| 47 | Date string |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 48 | Description string |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 49 | Server string |
| 50 | SDK string |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame^] | 51 | Stylesheet string |
| Akron | 2ac2ec0 | 2025-06-05 15:26:42 +0200 | [diff] [blame] | 52 | ServiceURL string |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame^] | 53 | CookieName string |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 54 | } |
| 55 | |
| 56 | type SingleMappingPageData struct { |
| 57 | BasePageData |
| Akron | c376dcc | 2025-06-04 17:00:18 +0200 | [diff] [blame] | 58 | MapID string |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 59 | Mappings []config.MappingList |
| 60 | QueryURL string |
| 61 | ResponseURL string |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 62 | } |
| 63 | |
| Akron | cb51f81 | 2025-06-30 15:24:20 +0200 | [diff] [blame] | 64 | type QueryParams struct { |
| 65 | Dir string |
| 66 | FoundryA string |
| 67 | FoundryB string |
| 68 | LayerA string |
| 69 | LayerB string |
| 70 | } |
| 71 | |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 72 | // requestParams holds common request parameters |
| 73 | type requestParams struct { |
| 74 | MapID string |
| 75 | Dir string |
| 76 | FoundryA string |
| 77 | FoundryB string |
| 78 | LayerA string |
| 79 | LayerB string |
| 80 | } |
| 81 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 82 | // ConfigPageData holds all data passed to the configuration page template. |
| 83 | type ConfigPageData struct { |
| 84 | BasePageData |
| 85 | AnnotationMappings []config.MappingList |
| 86 | CorpusMappings []config.MappingList |
| 87 | } |
| 88 | |
| Akron | a00d475 | 2025-05-26 17:34:36 +0200 | [diff] [blame] | 89 | func parseConfig() *appConfig { |
| 90 | cfg := &appConfig{} |
| Akron | fc77b5e | 2025-06-04 11:44:43 +0200 | [diff] [blame] | 91 | |
| 92 | desc := config.Description |
| 93 | desc += " [" + config.Version + "]" |
| 94 | |
| Akron | 1fc750e | 2025-05-26 16:54:18 +0200 | [diff] [blame] | 95 | ctx := kong.Parse(cfg, |
| Akron | fc77b5e | 2025-06-04 11:44:43 +0200 | [diff] [blame] | 96 | kong.Description(desc), |
| Akron | 1fc750e | 2025-05-26 16:54:18 +0200 | [diff] [blame] | 97 | kong.UsageOnError(), |
| 98 | ) |
| 99 | if ctx.Error != nil { |
| 100 | fmt.Fprintln(os.Stderr, ctx.Error) |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 101 | os.Exit(1) |
| 102 | } |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 103 | return cfg |
| 104 | } |
| 105 | |
| 106 | func setupLogger(level string) { |
| 107 | // Parse log level |
| 108 | lvl, err := zerolog.ParseLevel(strings.ToLower(level)) |
| 109 | if err != nil { |
| 110 | log.Error().Err(err).Str("level", level).Msg("Invalid log level, defaulting to info") |
| 111 | lvl = zerolog.InfoLevel |
| 112 | } |
| 113 | |
| 114 | // Configure zerolog |
| 115 | zerolog.SetGlobalLevel(lvl) |
| 116 | log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) |
| 117 | } |
| 118 | |
| Akron | 3caee16 | 2025-07-01 17:44:58 +0200 | [diff] [blame] | 119 | // setupFiberLogger configures fiber's logger middleware to integrate with zerolog |
| 120 | func setupFiberLogger() fiber.Handler { |
| 121 | // Check if HTTP request logging should be enabled based on current log level |
| 122 | currentLevel := zerolog.GlobalLevel() |
| 123 | |
| 124 | // Only enable HTTP request logging if log level is debug or info |
| 125 | if currentLevel > zerolog.InfoLevel { |
| 126 | return func(c *fiber.Ctx) error { |
| 127 | return c.Next() |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | return func(c *fiber.Ctx) error { |
| 132 | // Record start time |
| 133 | start := time.Now() |
| 134 | |
| 135 | // Process request |
| 136 | err := c.Next() |
| 137 | |
| 138 | // Calculate latency |
| 139 | latency := time.Since(start) |
| 140 | status := c.Response().StatusCode() |
| 141 | |
| 142 | // Determine log level based on status code |
| 143 | logEvent := log.Info() |
| 144 | if status >= 400 && status < 500 { |
| 145 | logEvent = log.Warn() |
| 146 | } else if status >= 500 { |
| 147 | logEvent = log.Error() |
| 148 | } |
| 149 | |
| 150 | // Log the request |
| 151 | logEvent. |
| 152 | Int("status", status). |
| 153 | Dur("latency", latency). |
| 154 | Str("method", c.Method()). |
| 155 | Str("path", c.Path()). |
| 156 | Str("ip", c.IP()). |
| 157 | Str("user_agent", c.Get("User-Agent")). |
| 158 | Msg("HTTP request") |
| 159 | |
| 160 | return err |
| 161 | } |
| 162 | } |
| 163 | |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 164 | // extractRequestParams extracts and validates common request parameters |
| 165 | func extractRequestParams(c *fiber.Ctx) (*requestParams, error) { |
| 166 | params := &requestParams{ |
| 167 | MapID: c.Params("map"), |
| 168 | Dir: c.Query("dir", "atob"), |
| 169 | FoundryA: c.Query("foundryA", ""), |
| 170 | FoundryB: c.Query("foundryB", ""), |
| 171 | LayerA: c.Query("layerA", ""), |
| 172 | LayerB: c.Query("layerB", ""), |
| 173 | } |
| 174 | |
| 175 | // Validate input parameters |
| 176 | if err := validateInput(params.MapID, params.Dir, params.FoundryA, params.FoundryB, params.LayerA, params.LayerB, c.Body()); err != nil { |
| 177 | return nil, err |
| 178 | } |
| 179 | |
| 180 | // Validate direction |
| 181 | if params.Dir != "atob" && params.Dir != "btoa" { |
| 182 | return nil, fmt.Errorf("invalid direction, must be 'atob' or 'btoa'") |
| 183 | } |
| 184 | |
| 185 | return params, nil |
| 186 | } |
| 187 | |
| 188 | // parseRequestBody parses JSON request body and direction |
| 189 | func parseRequestBody(c *fiber.Ctx, dir string) (any, mapper.Direction, error) { |
| 190 | var jsonData any |
| 191 | if err := c.BodyParser(&jsonData); err != nil { |
| 192 | return nil, mapper.BtoA, fmt.Errorf("invalid JSON in request body") |
| 193 | } |
| 194 | |
| 195 | direction, err := mapper.ParseDirection(dir) |
| 196 | if err != nil { |
| 197 | return nil, mapper.BtoA, err |
| 198 | } |
| 199 | |
| 200 | return jsonData, direction, nil |
| 201 | } |
| 202 | |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 203 | func main() { |
| 204 | // Parse command line flags |
| Akron | 1fc750e | 2025-05-26 16:54:18 +0200 | [diff] [blame] | 205 | cfg := parseConfig() |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 206 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 207 | // Validate command line arguments |
| 208 | if cfg.Config == "" && len(cfg.Mappings) == 0 { |
| 209 | log.Fatal().Msg("At least one configuration source must be provided: use -c for main config file or -m for mapping files") |
| 210 | } |
| 211 | |
| Akron | 14678dc | 2025-06-05 13:01:38 +0200 | [diff] [blame] | 212 | // Expand glob patterns in mapping files |
| 213 | expandedMappings, err := expandGlobs(cfg.Mappings) |
| 214 | if err != nil { |
| 215 | log.Fatal().Err(err).Msg("Failed to expand glob patterns in mapping files") |
| 216 | } |
| 217 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 218 | // Load configuration from multiple sources |
| Akron | 14678dc | 2025-06-05 13:01:38 +0200 | [diff] [blame] | 219 | yamlConfig, err := config.LoadFromSources(cfg.Config, expandedMappings) |
| Akron | a00d475 | 2025-05-26 17:34:36 +0200 | [diff] [blame] | 220 | if err != nil { |
| 221 | log.Fatal().Err(err).Msg("Failed to load configuration") |
| 222 | } |
| 223 | |
| Akron | a8a66ce | 2025-06-05 10:50:17 +0200 | [diff] [blame] | 224 | finalPort := yamlConfig.Port |
| 225 | finalLogLevel := yamlConfig.LogLevel |
| 226 | |
| 227 | // Use command line values if provided (they override config file) |
| 228 | if cfg.Port != nil { |
| 229 | finalPort = *cfg.Port |
| 230 | } |
| 231 | if cfg.LogLevel != nil { |
| 232 | finalLogLevel = *cfg.LogLevel |
| 233 | } |
| 234 | |
| 235 | // Set up logging with the final log level |
| 236 | setupLogger(finalLogLevel) |
| 237 | |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 238 | // Create a new mapper instance |
| Akron | a00d475 | 2025-05-26 17:34:36 +0200 | [diff] [blame] | 239 | m, err := mapper.NewMapper(yamlConfig.Lists) |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 240 | if err != nil { |
| 241 | log.Fatal().Err(err).Msg("Failed to create mapper") |
| 242 | } |
| 243 | |
| 244 | // Create fiber app |
| 245 | app := fiber.New(fiber.Config{ |
| 246 | DisableStartupMessage: true, |
| Akron | 74e1c07 | 2025-05-26 14:38:25 +0200 | [diff] [blame] | 247 | BodyLimit: maxInputLength, |
| Akron | afbe86d | 2025-07-01 08:45:13 +0200 | [diff] [blame] | 248 | ReadBufferSize: 64 * 1024, // 64KB - increase header size limit |
| 249 | WriteBufferSize: 64 * 1024, // 64KB - increase response buffer size |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 250 | }) |
| 251 | |
| Akron | 3caee16 | 2025-07-01 17:44:58 +0200 | [diff] [blame] | 252 | // Add zerolog-integrated logger middleware |
| 253 | app.Use(setupFiberLogger()) |
| 254 | |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 255 | // Set up routes |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 256 | setupRoutes(app, m, yamlConfig) |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 257 | |
| 258 | // Start server |
| 259 | go func() { |
| Akron | a8a66ce | 2025-06-05 10:50:17 +0200 | [diff] [blame] | 260 | log.Info().Int("port", finalPort).Msg("Starting server") |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 261 | fmt.Printf("Starting server port=%d\n", finalPort) |
| Akron | ae3ffde | 2025-06-05 14:04:06 +0200 | [diff] [blame] | 262 | |
| 263 | for _, list := range yamlConfig.Lists { |
| 264 | log.Info().Str("id", list.ID).Str("desc", list.Description).Msg("Loaded mapping") |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 265 | fmt.Printf("Loaded mapping desc=%s id=%s\n", |
| 266 | formatConsoleField(list.Description), |
| 267 | list.ID, |
| 268 | ) |
| Akron | ae3ffde | 2025-06-05 14:04:06 +0200 | [diff] [blame] | 269 | } |
| 270 | |
| Akron | a8a66ce | 2025-06-05 10:50:17 +0200 | [diff] [blame] | 271 | if err := app.Listen(fmt.Sprintf(":%d", finalPort)); err != nil { |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 272 | log.Fatal().Err(err).Msg("Server error") |
| 273 | } |
| 274 | }() |
| 275 | |
| 276 | // Wait for interrupt signal |
| 277 | sigChan := make(chan os.Signal, 1) |
| 278 | signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) |
| 279 | <-sigChan |
| 280 | |
| 281 | // Graceful shutdown |
| 282 | log.Info().Msg("Shutting down server") |
| 283 | if err := app.Shutdown(); err != nil { |
| 284 | log.Error().Err(err).Msg("Error during shutdown") |
| 285 | } |
| 286 | } |
| 287 | |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 288 | func setupRoutes(app *fiber.App, m *mapper.Mapper, yamlConfig *config.MappingConfig) { |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 289 | configTmpl := template.Must(template.ParseFS(staticFS, "static/config.html")) |
| 290 | pluginTmpl := texttemplate.Must(texttemplate.ParseFS(staticFS, "static/plugin.html")) |
| 291 | |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 292 | // Health check endpoint |
| 293 | app.Get("/health", func(c *fiber.Ctx) error { |
| 294 | return c.SendString("OK") |
| 295 | }) |
| 296 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 297 | // Static file serving from embedded FS |
| 298 | app.Get("/static/*", handleStaticFile()) |
| 299 | |
| Akron | 512aab6 | 2026-02-20 08:36:12 +0100 | [diff] [blame] | 300 | // Composite cascade transformation endpoints |
| 301 | app.Post("/query", handleCompositeQueryTransform(m, yamlConfig.Lists)) |
| 302 | app.Post("/response", handleCompositeResponseTransform(m, yamlConfig.Lists)) |
| 303 | |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 304 | // Transformation endpoint |
| 305 | app.Post("/:map/query", handleTransform(m)) |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 306 | |
| Akron | 4de47a9 | 2025-06-27 11:58:11 +0200 | [diff] [blame] | 307 | // Response transformation endpoint |
| 308 | app.Post("/:map/response", handleResponseTransform(m)) |
| 309 | |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 310 | // Kalamar plugin endpoint |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 311 | app.Get("/", handleKalamarPlugin(yamlConfig, configTmpl, pluginTmpl)) |
| 312 | app.Get("/:map", handleKalamarPlugin(yamlConfig, configTmpl, pluginTmpl)) |
| 313 | } |
| 314 | |
| 315 | func handleStaticFile() fiber.Handler { |
| 316 | return func(c *fiber.Ctx) error { |
| 317 | name := c.Params("*") |
| 318 | data, err := fs.ReadFile(staticFS, "static/"+name) |
| 319 | if err != nil { |
| 320 | return c.Status(fiber.StatusNotFound).SendString("not found") |
| 321 | } |
| 322 | switch { |
| 323 | case strings.HasSuffix(name, ".js"): |
| 324 | c.Set("Content-Type", "text/javascript; charset=utf-8") |
| 325 | case strings.HasSuffix(name, ".css"): |
| 326 | c.Set("Content-Type", "text/css; charset=utf-8") |
| 327 | case strings.HasSuffix(name, ".html"): |
| 328 | c.Set("Content-Type", "text/html; charset=utf-8") |
| 329 | } |
| 330 | return c.Send(data) |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | func buildBasePageData(yamlConfig *config.MappingConfig) BasePageData { |
| 335 | return BasePageData{ |
| 336 | Title: config.Title, |
| 337 | Version: config.Version, |
| 338 | Hash: config.Buildhash, |
| 339 | Date: config.Buildtime, |
| 340 | Description: config.Description, |
| 341 | Server: yamlConfig.Server, |
| 342 | SDK: yamlConfig.SDK, |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame^] | 343 | Stylesheet: yamlConfig.Stylesheet, |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 344 | ServiceURL: yamlConfig.ServiceURL, |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame^] | 345 | CookieName: yamlConfig.CookieName, |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 346 | } |
| 347 | } |
| 348 | |
| 349 | func buildConfigPageData(yamlConfig *config.MappingConfig) ConfigPageData { |
| 350 | data := ConfigPageData{ |
| 351 | BasePageData: buildBasePageData(yamlConfig), |
| 352 | } |
| 353 | |
| 354 | for _, list := range yamlConfig.Lists { |
| 355 | normalized := list |
| 356 | if normalized.Type == "" { |
| 357 | normalized.Type = "annotation" |
| 358 | } |
| 359 | if list.IsCorpus() { |
| 360 | data.CorpusMappings = append(data.CorpusMappings, normalized) |
| 361 | } else { |
| 362 | data.AnnotationMappings = append(data.AnnotationMappings, normalized) |
| 363 | } |
| 364 | } |
| 365 | return data |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 366 | } |
| 367 | |
| Akron | 512aab6 | 2026-02-20 08:36:12 +0100 | [diff] [blame] | 368 | func handleCompositeQueryTransform(m *mapper.Mapper, lists []config.MappingList) fiber.Handler { |
| 369 | return func(c *fiber.Ctx) error { |
| 370 | cfgRaw := c.Query("cfg", "") |
| 371 | if len(cfgRaw) > maxParamLength { |
| 372 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 373 | "error": fmt.Sprintf("cfg too long (max %d bytes)", maxParamLength), |
| 374 | }) |
| 375 | } |
| 376 | |
| 377 | var jsonData any |
| 378 | if err := c.BodyParser(&jsonData); err != nil { |
| 379 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 380 | "error": "invalid JSON in request body", |
| 381 | }) |
| 382 | } |
| 383 | |
| 384 | entries, err := ParseCfgParam(cfgRaw, lists) |
| 385 | if err != nil { |
| 386 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 387 | "error": err.Error(), |
| 388 | }) |
| 389 | } |
| 390 | |
| 391 | if len(entries) == 0 { |
| 392 | return c.JSON(jsonData) |
| 393 | } |
| 394 | |
| 395 | orderedIDs := make([]string, 0, len(entries)) |
| 396 | opts := make([]mapper.MappingOptions, 0, len(entries)) |
| 397 | for _, entry := range entries { |
| 398 | dir := mapper.AtoB |
| 399 | if entry.Direction == "btoa" { |
| 400 | dir = mapper.BtoA |
| 401 | } |
| 402 | |
| 403 | orderedIDs = append(orderedIDs, entry.ID) |
| 404 | opts = append(opts, mapper.MappingOptions{ |
| 405 | Direction: dir, |
| 406 | FoundryA: entry.FoundryA, |
| 407 | LayerA: entry.LayerA, |
| 408 | FoundryB: entry.FoundryB, |
| 409 | LayerB: entry.LayerB, |
| 410 | }) |
| 411 | } |
| 412 | |
| 413 | result, err := m.CascadeQueryMappings(orderedIDs, opts, jsonData) |
| 414 | if err != nil { |
| 415 | log.Error().Err(err).Str("cfg", cfgRaw).Msg("Failed to apply composite query mappings") |
| 416 | return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ |
| 417 | "error": err.Error(), |
| 418 | }) |
| 419 | } |
| 420 | |
| 421 | return c.JSON(result) |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | func handleCompositeResponseTransform(m *mapper.Mapper, lists []config.MappingList) fiber.Handler { |
| 426 | return func(c *fiber.Ctx) error { |
| 427 | cfgRaw := c.Query("cfg", "") |
| 428 | if len(cfgRaw) > maxParamLength { |
| 429 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 430 | "error": fmt.Sprintf("cfg too long (max %d bytes)", maxParamLength), |
| 431 | }) |
| 432 | } |
| 433 | |
| 434 | var jsonData any |
| 435 | if err := c.BodyParser(&jsonData); err != nil { |
| 436 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 437 | "error": "invalid JSON in request body", |
| 438 | }) |
| 439 | } |
| 440 | |
| 441 | entries, err := ParseCfgParam(cfgRaw, lists) |
| 442 | if err != nil { |
| 443 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 444 | "error": err.Error(), |
| 445 | }) |
| 446 | } |
| 447 | |
| 448 | if len(entries) == 0 { |
| 449 | return c.JSON(jsonData) |
| 450 | } |
| 451 | |
| 452 | orderedIDs := make([]string, 0, len(entries)) |
| 453 | opts := make([]mapper.MappingOptions, 0, len(entries)) |
| 454 | for _, entry := range entries { |
| 455 | dir := mapper.AtoB |
| 456 | if entry.Direction == "btoa" { |
| 457 | dir = mapper.BtoA |
| 458 | } |
| 459 | |
| 460 | orderedIDs = append(orderedIDs, entry.ID) |
| 461 | opts = append(opts, mapper.MappingOptions{ |
| 462 | Direction: dir, |
| 463 | FoundryA: entry.FoundryA, |
| 464 | LayerA: entry.LayerA, |
| 465 | FoundryB: entry.FoundryB, |
| 466 | LayerB: entry.LayerB, |
| 467 | }) |
| 468 | } |
| 469 | |
| 470 | result, err := m.CascadeResponseMappings(orderedIDs, opts, jsonData) |
| 471 | if err != nil { |
| 472 | log.Error().Err(err).Str("cfg", cfgRaw).Msg("Failed to apply composite response mappings") |
| 473 | return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ |
| 474 | "error": err.Error(), |
| 475 | }) |
| 476 | } |
| 477 | |
| 478 | return c.JSON(result) |
| 479 | } |
| 480 | } |
| 481 | |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 482 | func handleTransform(m *mapper.Mapper) fiber.Handler { |
| 483 | return func(c *fiber.Ctx) error { |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 484 | // Extract and validate parameters |
| 485 | params, err := extractRequestParams(c) |
| 486 | if err != nil { |
| Akron | 74e1c07 | 2025-05-26 14:38:25 +0200 | [diff] [blame] | 487 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 488 | "error": err.Error(), |
| 489 | }) |
| 490 | } |
| 491 | |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 492 | // Parse request body |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 493 | jsonData, direction, err := parseRequestBody(c, params.Dir) |
| Akron | a1a183f | 2025-05-26 17:47:33 +0200 | [diff] [blame] | 494 | if err != nil { |
| 495 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 496 | "error": err.Error(), |
| 497 | }) |
| 498 | } |
| 499 | |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 500 | // Apply mappings |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 501 | result, err := m.ApplyQueryMappings(params.MapID, mapper.MappingOptions{ |
| Akron | a1a183f | 2025-05-26 17:47:33 +0200 | [diff] [blame] | 502 | Direction: direction, |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 503 | FoundryA: params.FoundryA, |
| 504 | FoundryB: params.FoundryB, |
| 505 | LayerA: params.LayerA, |
| 506 | LayerB: params.LayerB, |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 507 | }, jsonData) |
| 508 | |
| 509 | if err != nil { |
| 510 | log.Error().Err(err). |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 511 | Str("mapID", params.MapID). |
| 512 | Str("direction", params.Dir). |
| Akron | 49ceeb4 | 2025-05-23 17:46:01 +0200 | [diff] [blame] | 513 | Msg("Failed to apply mappings") |
| 514 | |
| 515 | return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ |
| 516 | "error": err.Error(), |
| 517 | }) |
| 518 | } |
| 519 | |
| 520 | return c.JSON(result) |
| 521 | } |
| 522 | } |
| Akron | 74e1c07 | 2025-05-26 14:38:25 +0200 | [diff] [blame] | 523 | |
| Akron | 4de47a9 | 2025-06-27 11:58:11 +0200 | [diff] [blame] | 524 | func handleResponseTransform(m *mapper.Mapper) fiber.Handler { |
| 525 | return func(c *fiber.Ctx) error { |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 526 | // Extract and validate parameters |
| 527 | params, err := extractRequestParams(c) |
| 528 | if err != nil { |
| Akron | 4de47a9 | 2025-06-27 11:58:11 +0200 | [diff] [blame] | 529 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 530 | "error": err.Error(), |
| 531 | }) |
| 532 | } |
| 533 | |
| Akron | 4de47a9 | 2025-06-27 11:58:11 +0200 | [diff] [blame] | 534 | // Parse request body |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 535 | jsonData, direction, err := parseRequestBody(c, params.Dir) |
| Akron | 4de47a9 | 2025-06-27 11:58:11 +0200 | [diff] [blame] | 536 | if err != nil { |
| 537 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 538 | "error": err.Error(), |
| 539 | }) |
| 540 | } |
| 541 | |
| 542 | // Apply response mappings |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 543 | result, err := m.ApplyResponseMappings(params.MapID, mapper.MappingOptions{ |
| Akron | 4de47a9 | 2025-06-27 11:58:11 +0200 | [diff] [blame] | 544 | Direction: direction, |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 545 | FoundryA: params.FoundryA, |
| 546 | FoundryB: params.FoundryB, |
| 547 | LayerA: params.LayerA, |
| 548 | LayerB: params.LayerB, |
| Akron | 4de47a9 | 2025-06-27 11:58:11 +0200 | [diff] [blame] | 549 | }, jsonData) |
| 550 | |
| 551 | if err != nil { |
| 552 | log.Error().Err(err). |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 553 | Str("mapID", params.MapID). |
| 554 | Str("direction", params.Dir). |
| Akron | 4de47a9 | 2025-06-27 11:58:11 +0200 | [diff] [blame] | 555 | Msg("Failed to apply response mappings") |
| 556 | |
| 557 | return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ |
| 558 | "error": err.Error(), |
| 559 | }) |
| 560 | } |
| 561 | |
| 562 | return c.JSON(result) |
| 563 | } |
| 564 | } |
| 565 | |
| Akron | 74e1c07 | 2025-05-26 14:38:25 +0200 | [diff] [blame] | 566 | // validateInput checks if the input parameters are valid |
| 567 | func validateInput(mapID, dir, foundryA, foundryB, layerA, layerB string, body []byte) error { |
| Akron | 69d43bf | 2025-05-26 17:09:00 +0200 | [diff] [blame] | 568 | // Define parameter checks |
| 569 | params := []struct { |
| Akron | 74e1c07 | 2025-05-26 14:38:25 +0200 | [diff] [blame] | 570 | name string |
| 571 | value string |
| 572 | }{ |
| 573 | {"mapID", mapID}, |
| 574 | {"dir", dir}, |
| 575 | {"foundryA", foundryA}, |
| 576 | {"foundryB", foundryB}, |
| 577 | {"layerA", layerA}, |
| 578 | {"layerB", layerB}, |
| Akron | 69d43bf | 2025-05-26 17:09:00 +0200 | [diff] [blame] | 579 | } |
| 580 | |
| 581 | for _, param := range params { |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 582 | // Check input lengths and invalid characters in one combined condition |
| Akron | 69d43bf | 2025-05-26 17:09:00 +0200 | [diff] [blame] | 583 | if len(param.value) > maxParamLength { |
| 584 | return fmt.Errorf("%s too long (max %d bytes)", param.name, maxParamLength) |
| 585 | } |
| Akron | 74e1c07 | 2025-05-26 14:38:25 +0200 | [diff] [blame] | 586 | if strings.ContainsAny(param.value, "<>{}[]\\") { |
| 587 | return fmt.Errorf("%s contains invalid characters", param.name) |
| 588 | } |
| 589 | } |
| 590 | |
| Akron | 69d43bf | 2025-05-26 17:09:00 +0200 | [diff] [blame] | 591 | if len(body) > maxInputLength { |
| 592 | return fmt.Errorf("request body too large (max %d bytes)", maxInputLength) |
| 593 | } |
| 594 | |
| Akron | 74e1c07 | 2025-05-26 14:38:25 +0200 | [diff] [blame] | 595 | return nil |
| 596 | } |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 597 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 598 | func handleKalamarPlugin(yamlConfig *config.MappingConfig, configTmpl *template.Template, pluginTmpl *texttemplate.Template) fiber.Handler { |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 599 | return func(c *fiber.Ctx) error { |
| Akron | c376dcc | 2025-06-04 17:00:18 +0200 | [diff] [blame] | 600 | mapID := c.Params("map") |
| 601 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 602 | // Config page (GET /) |
| 603 | if mapID == "" { |
| 604 | data := buildConfigPageData(yamlConfig) |
| 605 | var buf bytes.Buffer |
| 606 | if err := configTmpl.Execute(&buf, data); err != nil { |
| 607 | log.Error().Err(err).Msg("Failed to execute config template") |
| 608 | return c.Status(fiber.StatusInternalServerError).SendString("internal error") |
| 609 | } |
| 610 | c.Set("Content-Type", "text/html") |
| 611 | return c.Send(buf.Bytes()) |
| 612 | } |
| 613 | |
| 614 | // Single-mapping page (GET /:map) — existing behavior |
| Akron | cb51f81 | 2025-06-30 15:24:20 +0200 | [diff] [blame] | 615 | // Get query parameters |
| 616 | dir := c.Query("dir", "atob") |
| 617 | foundryA := c.Query("foundryA", "") |
| 618 | foundryB := c.Query("foundryB", "") |
| 619 | layerA := c.Query("layerA", "") |
| 620 | layerB := c.Query("layerB", "") |
| 621 | |
| Akron | 49b525c | 2025-07-03 15:17:06 +0200 | [diff] [blame] | 622 | // Validate input parameters and direction in one step |
| Akron | cb51f81 | 2025-06-30 15:24:20 +0200 | [diff] [blame] | 623 | if err := validateInput(mapID, dir, foundryA, foundryB, layerA, layerB, []byte{}); err != nil { |
| 624 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 625 | "error": err.Error(), |
| 626 | }) |
| 627 | } |
| 628 | |
| Akron | cb51f81 | 2025-06-30 15:24:20 +0200 | [diff] [blame] | 629 | if dir != "atob" && dir != "btoa" { |
| 630 | return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ |
| 631 | "error": "invalid direction, must be 'atob' or 'btoa'", |
| 632 | }) |
| 633 | } |
| 634 | |
| Akron | cb51f81 | 2025-06-30 15:24:20 +0200 | [diff] [blame] | 635 | queryParams := QueryParams{ |
| 636 | Dir: dir, |
| 637 | FoundryA: foundryA, |
| 638 | FoundryB: foundryB, |
| 639 | LayerA: layerA, |
| 640 | LayerB: layerB, |
| 641 | } |
| 642 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 643 | queryURL, err := buildMapServiceURL(yamlConfig.ServiceURL, mapID, "query", queryParams) |
| 644 | if err != nil { |
| 645 | log.Warn().Err(err).Msg("Failed to build query service URL") |
| 646 | return c.Status(fiber.StatusInternalServerError).SendString("internal error") |
| 647 | } |
| 648 | reversed := queryParams |
| 649 | if queryParams.Dir == "btoa" { |
| 650 | reversed.Dir = "atob" |
| 651 | } else { |
| 652 | reversed.Dir = "btoa" |
| 653 | } |
| 654 | responseURL, err := buildMapServiceURL(yamlConfig.ServiceURL, mapID, "response", reversed) |
| 655 | if err != nil { |
| 656 | log.Warn().Err(err).Msg("Failed to build response service URL") |
| 657 | return c.Status(fiber.StatusInternalServerError).SendString("internal error") |
| 658 | } |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 659 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 660 | data := SingleMappingPageData{ |
| 661 | BasePageData: buildBasePageData(yamlConfig), |
| 662 | MapID: mapID, |
| 663 | Mappings: yamlConfig.Lists, |
| 664 | QueryURL: queryURL, |
| 665 | ResponseURL: responseURL, |
| 666 | } |
| 667 | |
| 668 | var buf bytes.Buffer |
| 669 | if err := pluginTmpl.Execute(&buf, data); err != nil { |
| 670 | log.Error().Err(err).Msg("Failed to execute plugin template") |
| 671 | return c.Status(fiber.StatusInternalServerError).SendString("internal error") |
| 672 | } |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 673 | c.Set("Content-Type", "text/html") |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 674 | return c.Send(buf.Bytes()) |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 675 | } |
| 676 | } |
| 677 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 678 | func buildMapServiceURL(serviceURL, mapID, endpoint string, params QueryParams) (string, error) { |
| 679 | service, err := url.Parse(serviceURL) |
| 680 | if err != nil { |
| 681 | return "", err |
| Akron | c376dcc | 2025-06-04 17:00:18 +0200 | [diff] [blame] | 682 | } |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 683 | service.Path = path.Join(service.Path, mapID, endpoint) |
| 684 | service.RawQuery = buildQueryParams(params.Dir, params.FoundryA, params.FoundryB, params.LayerA, params.LayerB) |
| 685 | return service.String(), nil |
| 686 | } |
| Akron | c376dcc | 2025-06-04 17:00:18 +0200 | [diff] [blame] | 687 | |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 688 | func formatConsoleField(value string) string { |
| 689 | if strings.ContainsAny(value, " \t") { |
| 690 | return strconv.Quote(value) |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 691 | } |
| Akron | d8a76b3 | 2026-02-20 09:31:56 +0100 | [diff] [blame] | 692 | return value |
| Akron | 40aaa63 | 2025-06-03 17:57:52 +0200 | [diff] [blame] | 693 | } |
| Akron | 14678dc | 2025-06-05 13:01:38 +0200 | [diff] [blame] | 694 | |
| Akron | cb51f81 | 2025-06-30 15:24:20 +0200 | [diff] [blame] | 695 | // buildQueryParams builds a query string from the provided parameters |
| 696 | func buildQueryParams(dir, foundryA, foundryB, layerA, layerB string) string { |
| 697 | params := url.Values{} |
| 698 | if dir != "" { |
| 699 | params.Add("dir", dir) |
| 700 | } |
| 701 | if foundryA != "" { |
| 702 | params.Add("foundryA", foundryA) |
| 703 | } |
| 704 | if foundryB != "" { |
| 705 | params.Add("foundryB", foundryB) |
| 706 | } |
| 707 | if layerA != "" { |
| 708 | params.Add("layerA", layerA) |
| 709 | } |
| 710 | if layerB != "" { |
| 711 | params.Add("layerB", layerB) |
| 712 | } |
| 713 | return params.Encode() |
| 714 | } |
| 715 | |
| Akron | 14678dc | 2025-06-05 13:01:38 +0200 | [diff] [blame] | 716 | // expandGlobs expands glob patterns in the slice of file paths |
| 717 | // Returns the expanded list of files or an error if glob expansion fails |
| 718 | func expandGlobs(patterns []string) ([]string, error) { |
| 719 | var expanded []string |
| 720 | |
| 721 | for _, pattern := range patterns { |
| 722 | // Use filepath.Glob which works cross-platform |
| 723 | matches, err := filepath.Glob(pattern) |
| 724 | if err != nil { |
| 725 | return nil, fmt.Errorf("failed to expand glob pattern '%s': %w", pattern, err) |
| 726 | } |
| 727 | |
| 728 | // If no matches found, treat as literal filename (consistent with shell behavior) |
| 729 | if len(matches) == 0 { |
| 730 | log.Warn().Str("pattern", pattern).Msg("Glob pattern matched no files, treating as literal filename") |
| 731 | expanded = append(expanded, pattern) |
| 732 | } else { |
| 733 | expanded = append(expanded, matches...) |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | return expanded, nil |
| 738 | } |