| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os" |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 6 | "path/filepath" |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 7 | "strconv" |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 8 | "strings" |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 9 | |
| Akron | 2ef703c | 2025-07-03 15:57:42 +0200 | [diff] [blame] | 10 | "github.com/KorAP/Koral-Mapper/ast" |
| 11 | "github.com/KorAP/Koral-Mapper/parser" |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 12 | "github.com/rs/zerolog/log" |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 13 | "gopkg.in/yaml.v3" |
| 14 | ) |
| 15 | |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 16 | const ( |
| Akron | 2ac2ec0 | 2025-06-05 15:26:42 +0200 | [diff] [blame] | 17 | defaultServer = "https://korap.ids-mannheim.de/" |
| 18 | defaultSDK = "https://korap.ids-mannheim.de/js/korap-plugin-latest.js" |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame] | 19 | defaultStylesheet = "https://korap.ids-mannheim.de/css/kalamar-plugin-latest.css" |
| Akron | 2ef703c | 2025-07-03 15:57:42 +0200 | [diff] [blame] | 20 | defaultServiceURL = "https://korap.ids-mannheim.de/plugin/koralmapper" |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame] | 21 | defaultCookieName = "km-config" |
| Akron | 14c13a5 | 2025-06-06 15:36:23 +0200 | [diff] [blame] | 22 | defaultPort = 5725 |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame^] | 23 | defaultLogLevel = "warn" |
| 24 | defaultRateLimit = 100 |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 25 | ) |
| 26 | |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 27 | // MappingRule represents a single mapping rule in the configuration |
| 28 | type MappingRule string |
| 29 | |
| 30 | // MappingList represents a list of mapping rules with metadata |
| 31 | type MappingList struct { |
| Akron | dab2711 | 2025-06-05 13:52:43 +0200 | [diff] [blame] | 32 | ID string `yaml:"id"` |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 33 | Type string `yaml:"type,omitempty"` // "annotation" (default) or "corpus" |
| Akron | dab2711 | 2025-06-05 13:52:43 +0200 | [diff] [blame] | 34 | Description string `yaml:"desc,omitempty"` |
| 35 | FoundryA string `yaml:"foundryA,omitempty"` |
| 36 | LayerA string `yaml:"layerA,omitempty"` |
| 37 | FoundryB string `yaml:"foundryB,omitempty"` |
| 38 | LayerB string `yaml:"layerB,omitempty"` |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 39 | FieldA string `yaml:"fieldA,omitempty"` |
| 40 | FieldB string `yaml:"fieldB,omitempty"` |
| Akron | 8414ae5 | 2026-05-19 13:31:14 +0200 | [diff] [blame] | 41 | Rewrites bool `yaml:"rewrites,omitempty"` |
| Akron | dab2711 | 2025-06-05 13:52:43 +0200 | [diff] [blame] | 42 | Mappings []MappingRule `yaml:"mappings"` |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 43 | } |
| 44 | |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 45 | // IsCorpus returns true if the mapping list type is "corpus". |
| 46 | func (list *MappingList) IsCorpus() bool { |
| 47 | return list.Type == "corpus" |
| 48 | } |
| 49 | |
| 50 | // ParseCorpusMappings parses all mapping rules as corpus rules. |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 51 | // Bare values (without key=) are always allowed and receive the default |
| 52 | // field name from the mapping list header (FieldA/FieldB) when set. |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 53 | func (list *MappingList) ParseCorpusMappings() ([]*parser.CorpusMappingResult, error) { |
| 54 | corpusParser := parser.NewCorpusParser() |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 55 | corpusParser.AllowBareValues = true |
| 56 | |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 57 | results := make([]*parser.CorpusMappingResult, len(list.Mappings)) |
| 58 | for i, rule := range list.Mappings { |
| 59 | if rule == "" { |
| 60 | return nil, fmt.Errorf("empty corpus mapping rule at index %d in list '%s'", i, list.ID) |
| 61 | } |
| 62 | result, err := corpusParser.ParseMapping(string(rule)) |
| 63 | if err != nil { |
| 64 | return nil, fmt.Errorf("failed to parse corpus mapping rule %d in list '%s': %w", i, list.ID, err) |
| 65 | } |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 66 | |
| 67 | if list.FieldA != "" { |
| 68 | applyDefaultCorpusKey(result.Upper, list.FieldA) |
| 69 | } |
| 70 | if list.FieldB != "" { |
| 71 | applyDefaultCorpusKey(result.Lower, list.FieldB) |
| 72 | } |
| 73 | |
| Akron | 2f93c58 | 2026-02-19 16:49:13 +0100 | [diff] [blame] | 74 | results[i] = result |
| 75 | } |
| 76 | return results, nil |
| 77 | } |
| 78 | |
| Akron | a67de8f | 2026-02-23 17:54:26 +0100 | [diff] [blame] | 79 | // applyDefaultCorpusKey recursively fills in empty keys on CorpusField nodes. |
| 80 | func applyDefaultCorpusKey(node parser.CorpusNode, defaultKey string) { |
| 81 | switch n := node.(type) { |
| 82 | case *parser.CorpusField: |
| 83 | if n.Key == "" { |
| 84 | n.Key = defaultKey |
| 85 | } |
| 86 | case *parser.CorpusGroup: |
| 87 | for _, op := range n.Operands { |
| 88 | applyDefaultCorpusKey(op, defaultKey) |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 93 | // MappingConfig represents the root configuration containing multiple mapping lists |
| 94 | type MappingConfig struct { |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame^] | 95 | SDK string `yaml:"sdk,omitempty"` |
| 96 | Stylesheet string `yaml:"stylesheet,omitempty"` |
| 97 | Server string `yaml:"server,omitempty"` |
| 98 | ServiceURL string `yaml:"serviceURL,omitempty"` |
| 99 | CookieName string `yaml:"cookieName,omitempty"` |
| 100 | BasePath string `yaml:"basePath,omitempty"` // restricts config file loading to this directory tree |
| 101 | AllowOrigins string `yaml:"allowOrigins,omitempty"` // comma-separated list of allowed CORS origins |
| 102 | Port int `yaml:"port,omitempty"` |
| 103 | LogLevel string `yaml:"loglevel,omitempty"` |
| 104 | RateLimit int `yaml:"rateLimit,omitempty"` // max requests per minute per IP (0 = use default 100) |
| 105 | Lists []MappingList `yaml:"lists,omitempty"` |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 106 | } |
| 107 | |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 108 | // AllowedBasePath restricts file loading to a specific directory tree. |
| 109 | // When set, all file paths must resolve to a location at or below this |
| 110 | // directory (or under the system temp directory). Defaults to the CWD at |
| 111 | // application startup; can be overridden via the "basePath" YAML config |
| 112 | // field or the KORAL_MAPPER_BASE_PATH environment variable. In Docker |
| 113 | // (WORKDIR /), the default "/" naturally allows all paths. |
| 114 | var AllowedBasePath string |
| 115 | |
| 116 | // isWithinDir checks whether absPath is at or below the given directory. |
| 117 | // Uses a trailing-separator comparison to avoid prefix false positives |
| 118 | // (e.g. /home/user must not match /home/username). |
| 119 | func isWithinDir(absPath, dir string) bool { |
| 120 | if dir == "/" { |
| 121 | return true |
| 122 | } |
| 123 | return absPath == dir || strings.HasPrefix(absPath, dir+string(filepath.Separator)) |
| 124 | } |
| 125 | |
| 126 | // sanitizeFilePath cleans a file path, resolves it to an absolute path, and |
| 127 | // (when AllowedBasePath is set) verifies it resides at or below the allowed |
| 128 | // base directory or the system temp directory. This prevents path |
| 129 | // traversal attacks by ensuring os.ReadFile never receives |
| 130 | // unsanitized user input and cannot access files outside the application's |
| 131 | // working tree. |
| 132 | func sanitizeFilePath(path string) (string, error) { |
| 133 | if path == "" { |
| 134 | return "", fmt.Errorf("empty file path") |
| 135 | } |
| 136 | |
| 137 | // Clean the path to remove redundant separators and resolve "." and ".." |
| 138 | cleaned := filepath.Clean(path) |
| 139 | |
| 140 | // Convert to absolute path so all traversal is resolved against the CWD |
| 141 | absPath, err := filepath.Abs(cleaned) |
| 142 | if err != nil { |
| 143 | return "", fmt.Errorf("failed to resolve absolute path for '%s': %w", path, err) |
| 144 | } |
| 145 | |
| 146 | // If a base path is configured, confine access to that tree or temp dir |
| 147 | if AllowedBasePath != "" { |
| 148 | base := filepath.Clean(AllowedBasePath) |
| 149 | tmpDir := filepath.Clean(os.TempDir()) |
| 150 | |
| 151 | if !isWithinDir(absPath, base) && !isWithinDir(absPath, tmpDir) { |
| 152 | return "", fmt.Errorf( |
| 153 | "path traversal detected: '%s' resolves to '%s' which is outside the allowed base '%s'", |
| 154 | path, absPath, base) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | return absPath, nil |
| 159 | } |
| 160 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 161 | // LoadFromSources loads configuration from multiple sources and merges them: |
| 162 | // - A main configuration file (optional) containing global settings and lists |
| 163 | // - Individual mapping files (optional) containing single mapping lists each |
| 164 | // At least one source must be provided |
| 165 | func LoadFromSources(configFile string, mappingFiles []string) (*MappingConfig, error) { |
| 166 | var allLists []MappingList |
| 167 | var globalConfig MappingConfig |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 168 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 169 | // Track seen IDs across all sources to detect duplicates |
| 170 | seenIDs := make(map[string]bool) |
| Akron | a5d8814 | 2025-05-22 14:42:09 +0200 | [diff] [blame] | 171 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 172 | // Load main configuration file if provided |
| 173 | if configFile != "" { |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 174 | safePath, err := sanitizeFilePath(configFile) |
| 175 | if err != nil { |
| 176 | return nil, err |
| 177 | } |
| 178 | data, err := os.ReadFile(safePath) // #nosec G304 -- path sanitized above |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 179 | if err != nil { |
| 180 | return nil, fmt.Errorf("failed to read config file '%s': %w", configFile, err) |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 181 | } |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 182 | |
| 183 | if len(data) == 0 { |
| 184 | return nil, fmt.Errorf("EOF: config file '%s' is empty", configFile) |
| 185 | } |
| 186 | |
| 187 | // Try to unmarshal as new format first (object with optional sdk/server and lists) |
| Akron | 813780f | 2025-06-05 15:44:28 +0200 | [diff] [blame] | 188 | if err := yaml.Unmarshal(data, &globalConfig); err == nil { |
| 189 | // Successfully parsed as new format - accept it regardless of whether it has lists |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 190 | for _, list := range globalConfig.Lists { |
| 191 | if seenIDs[list.ID] { |
| 192 | return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID) |
| 193 | } |
| 194 | seenIDs[list.ID] = true |
| 195 | } |
| 196 | allLists = append(allLists, globalConfig.Lists...) |
| 197 | } else { |
| 198 | // Fall back to old format (direct list) |
| 199 | var lists []MappingList |
| 200 | if err := yaml.Unmarshal(data, &lists); err != nil { |
| 201 | return nil, fmt.Errorf("failed to parse YAML config file '%s': %w", configFile, err) |
| 202 | } |
| 203 | |
| 204 | for _, list := range lists { |
| 205 | if seenIDs[list.ID] { |
| 206 | return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID) |
| 207 | } |
| 208 | seenIDs[list.ID] = true |
| 209 | } |
| 210 | allLists = append(allLists, lists...) |
| 211 | // Clear the lists from globalConfig since we got them from the old format |
| 212 | globalConfig.Lists = nil |
| 213 | } |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 214 | } |
| 215 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 216 | // Load individual mapping files |
| 217 | for _, file := range mappingFiles { |
| Akron | ed787d0 | 2026-05-20 12:31:07 +0200 | [diff] [blame] | 218 | safePath, err := sanitizeFilePath(file) |
| 219 | if err != nil { |
| 220 | return nil, err |
| 221 | } |
| 222 | data, err := os.ReadFile(safePath) // #nosec G304 -- path sanitized above |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 223 | if err != nil { |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 224 | log.Error().Err(err).Str("file", file).Msg("Failed to read mapping file") |
| 225 | continue |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 226 | } |
| 227 | |
| 228 | if len(data) == 0 { |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 229 | log.Error().Err(err).Str("file", file).Msg("EOF: mapping file is empty") |
| 230 | continue |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 231 | } |
| 232 | |
| 233 | var list MappingList |
| 234 | if err := yaml.Unmarshal(data, &list); err != nil { |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 235 | log.Error().Err(err).Str("file", file).Msg("Failed to parse YAML mapping file") |
| 236 | continue |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 237 | } |
| 238 | |
| 239 | if seenIDs[list.ID] { |
| Akron | 7e8da93 | 2025-07-01 11:56:46 +0200 | [diff] [blame] | 240 | log.Error().Err(err).Str("file", file).Str("list-id", list.ID).Msg("Duplicate mapping list ID found") |
| 241 | continue |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 242 | } |
| 243 | seenIDs[list.ID] = true |
| 244 | allLists = append(allLists, list) |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 245 | } |
| 246 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 247 | // Ensure we have at least some configuration |
| 248 | if len(allLists) == 0 { |
| 249 | return nil, fmt.Errorf("no mapping lists found: provide either a config file (-c) with lists or mapping files (-m)") |
| 250 | } |
| 251 | |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 252 | // Validate all mapping lists (skip duplicate ID check since we already did it) |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 253 | if err := validateMappingLists(allLists); err != nil { |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 254 | return nil, err |
| 255 | } |
| 256 | |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 257 | // Create final configuration |
| 258 | result := &MappingConfig{ |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame^] | 259 | SDK: globalConfig.SDK, |
| 260 | Stylesheet: globalConfig.Stylesheet, |
| 261 | Server: globalConfig.Server, |
| 262 | ServiceURL: globalConfig.ServiceURL, |
| 263 | BasePath: globalConfig.BasePath, |
| 264 | AllowOrigins: globalConfig.AllowOrigins, |
| 265 | Port: globalConfig.Port, |
| 266 | LogLevel: globalConfig.LogLevel, |
| 267 | RateLimit: globalConfig.RateLimit, |
| 268 | Lists: allLists, |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 269 | } |
| 270 | |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 271 | // Apply environment variable overrides (ENV > config file) |
| 272 | ApplyEnvOverrides(result) |
| 273 | |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 274 | // Apply defaults if not specified |
| Akron | 2ac2ec0 | 2025-06-05 15:26:42 +0200 | [diff] [blame] | 275 | ApplyDefaults(result) |
| Akron | e1cff7c | 2025-06-04 18:43:32 +0200 | [diff] [blame] | 276 | |
| 277 | return result, nil |
| 278 | } |
| 279 | |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 280 | // ApplyDefaults sets default values for configuration fields if they are empty |
| Akron | 2ac2ec0 | 2025-06-05 15:26:42 +0200 | [diff] [blame] | 281 | func ApplyDefaults(config *MappingConfig) { |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 282 | defaults := map[*string]string{ |
| 283 | &config.SDK: defaultSDK, |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame] | 284 | &config.Stylesheet: defaultStylesheet, |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 285 | &config.Server: defaultServer, |
| 286 | &config.ServiceURL: defaultServiceURL, |
| Akron | 43fb102 | 2026-02-20 11:38:49 +0100 | [diff] [blame] | 287 | &config.CookieName: defaultCookieName, |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 288 | &config.LogLevel: defaultLogLevel, |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 289 | } |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 290 | |
| 291 | for field, defaultValue := range defaults { |
| 292 | if *field == "" { |
| 293 | *field = defaultValue |
| 294 | } |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 295 | } |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 296 | |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame^] | 297 | // AllowOrigins defaults to the Server value (with trailing slash |
| 298 | // stripped to form a proper origin). This avoids duplicating the |
| 299 | // server URL string and keeps CORS in sync with the deployment. |
| 300 | if config.AllowOrigins == "" { |
| 301 | config.AllowOrigins = strings.TrimRight(config.Server, "/") |
| 302 | } |
| 303 | |
| Akron | a8a66ce | 2025-06-05 10:50:17 +0200 | [diff] [blame] | 304 | if config.Port == 0 { |
| 305 | config.Port = defaultPort |
| 306 | } |
| Akron | e6767de | 2026-05-20 10:06:24 +0200 | [diff] [blame] | 307 | if config.RateLimit == 0 { |
| 308 | config.RateLimit = defaultRateLimit |
| 309 | } |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 310 | } |
| 311 | |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 312 | // ApplyEnvOverrides overrides configuration fields from environment variables. |
| 313 | // All environment variables are uppercase and prefixed with KORAL_MAPPER_. |
| 314 | // Non-empty environment values override any previously loaded config values. |
| 315 | func ApplyEnvOverrides(config *MappingConfig) { |
| 316 | envMappings := map[string]*string{ |
| Akron | f1ca882 | 2026-05-20 15:44:00 +0200 | [diff] [blame^] | 317 | "KORAL_MAPPER_SERVER": &config.Server, |
| 318 | "KORAL_MAPPER_SDK": &config.SDK, |
| 319 | "KORAL_MAPPER_STYLESHEET": &config.Stylesheet, |
| 320 | "KORAL_MAPPER_SERVICE_URL": &config.ServiceURL, |
| 321 | "KORAL_MAPPER_COOKIE_NAME": &config.CookieName, |
| 322 | "KORAL_MAPPER_LOG_LEVEL": &config.LogLevel, |
| 323 | "KORAL_MAPPER_BASE_PATH": &config.BasePath, |
| 324 | "KORAL_MAPPER_ALLOW_ORIGINS": &config.AllowOrigins, |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 325 | } |
| 326 | |
| 327 | for envKey, field := range envMappings { |
| 328 | if val := os.Getenv(envKey); val != "" { |
| 329 | *field = val |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | if val := os.Getenv("KORAL_MAPPER_PORT"); val != "" { |
| 334 | if port, err := strconv.Atoi(val); err == nil { |
| 335 | config.Port = port |
| 336 | } |
| 337 | } |
| Akron | e6767de | 2026-05-20 10:06:24 +0200 | [diff] [blame] | 338 | |
| 339 | if val := os.Getenv("KORAL_MAPPER_RATE_LIMIT"); val != "" { |
| 340 | if rl, err := strconv.Atoi(val); err == nil { |
| 341 | config.RateLimit = rl |
| 342 | } |
| 343 | } |
| Akron | f98ba28 | 2026-02-24 11:13:30 +0100 | [diff] [blame] | 344 | } |
| 345 | |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 346 | // validateMappingLists validates a slice of mapping lists (without duplicate ID checking) |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 347 | func validateMappingLists(lists []MappingList) error { |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 348 | for i, list := range lists { |
| 349 | if list.ID == "" { |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 350 | return fmt.Errorf("mapping list at index %d is missing an ID", i) |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 351 | } |
| Akron | a5d8814 | 2025-05-22 14:42:09 +0200 | [diff] [blame] | 352 | |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 353 | if len(list.Mappings) == 0 { |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 354 | return fmt.Errorf("mapping list '%s' has no mapping rules", list.ID) |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 355 | } |
| 356 | |
| 357 | // Validate each mapping rule |
| 358 | for j, rule := range list.Mappings { |
| 359 | if rule == "" { |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 360 | return fmt.Errorf("mapping list '%s' rule at index %d is empty", list.ID, j) |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 361 | } |
| 362 | } |
| 363 | } |
| Akron | 06d21f0 | 2025-06-04 14:36:07 +0200 | [diff] [blame] | 364 | return nil |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 365 | } |
| 366 | |
| 367 | // ParseMappings parses all mapping rules in a list and returns a slice of parsed rules |
| 368 | func (list *MappingList) ParseMappings() ([]*parser.MappingResult, error) { |
| 369 | // Create a grammar parser with the list's default foundries and layers |
| 370 | grammarParser, err := parser.NewGrammarParser("", "") |
| 371 | if err != nil { |
| 372 | return nil, fmt.Errorf("failed to create grammar parser: %w", err) |
| 373 | } |
| 374 | |
| 375 | results := make([]*parser.MappingResult, len(list.Mappings)) |
| 376 | for i, rule := range list.Mappings { |
| Akron | a5d8814 | 2025-05-22 14:42:09 +0200 | [diff] [blame] | 377 | // Check for empty rules first |
| 378 | if rule == "" { |
| 379 | return nil, fmt.Errorf("empty mapping rule at index %d in list '%s'", i, list.ID) |
| 380 | } |
| 381 | |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 382 | // Parse the mapping rule |
| 383 | result, err := grammarParser.ParseMapping(string(rule)) |
| 384 | if err != nil { |
| 385 | return nil, fmt.Errorf("failed to parse mapping rule %d in list '%s': %w", i, list.ID, err) |
| 386 | } |
| 387 | |
| 388 | // Apply default foundries and layers if not specified in the rule |
| 389 | if list.FoundryA != "" { |
| 390 | applyDefaultFoundryAndLayer(result.Upper.Wrap, list.FoundryA, list.LayerA) |
| 391 | } |
| 392 | if list.FoundryB != "" { |
| 393 | applyDefaultFoundryAndLayer(result.Lower.Wrap, list.FoundryB, list.LayerB) |
| 394 | } |
| 395 | |
| 396 | results[i] = result |
| 397 | } |
| 398 | |
| 399 | return results, nil |
| 400 | } |
| 401 | |
| 402 | // applyDefaultFoundryAndLayer recursively applies default foundry and layer to terms that don't have them specified |
| 403 | func applyDefaultFoundryAndLayer(node ast.Node, defaultFoundry, defaultLayer string) { |
| 404 | switch n := node.(type) { |
| 405 | case *ast.Term: |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 406 | if n.Foundry == "" && defaultFoundry != "" { |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 407 | n.Foundry = defaultFoundry |
| 408 | } |
| Akron | 585f50f | 2025-07-03 13:55:47 +0200 | [diff] [blame] | 409 | if n.Layer == "" && defaultLayer != "" { |
| Akron | 57ee558 | 2025-05-21 15:25:13 +0200 | [diff] [blame] | 410 | n.Layer = defaultLayer |
| 411 | } |
| 412 | case *ast.TermGroup: |
| 413 | for _, op := range n.Operands { |
| 414 | applyDefaultFoundryAndLayer(op, defaultFoundry, defaultLayer) |
| 415 | } |
| 416 | } |
| 417 | } |