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