blob: b7d2a16069d477e7c181243c0af4b875574faee0 [file] [log] [blame]
Akron57ee5582025-05-21 15:25:13 +02001package config
2
3import (
4 "fmt"
5 "os"
Akronf98ba282026-02-24 11:13:30 +01006 "strconv"
Akron57ee5582025-05-21 15:25:13 +02007
Akron2ef703c2025-07-03 15:57:42 +02008 "github.com/KorAP/Koral-Mapper/ast"
9 "github.com/KorAP/Koral-Mapper/parser"
Akron7e8da932025-07-01 11:56:46 +020010 "github.com/rs/zerolog/log"
Akron57ee5582025-05-21 15:25:13 +020011 "gopkg.in/yaml.v3"
12)
13
Akron06d21f02025-06-04 14:36:07 +020014const (
Akron2ac2ec02025-06-05 15:26:42 +020015 defaultServer = "https://korap.ids-mannheim.de/"
16 defaultSDK = "https://korap.ids-mannheim.de/js/korap-plugin-latest.js"
Akron43fb1022026-02-20 11:38:49 +010017 defaultStylesheet = "https://korap.ids-mannheim.de/css/kalamar-plugin-latest.css"
Akron2ef703c2025-07-03 15:57:42 +020018 defaultServiceURL = "https://korap.ids-mannheim.de/plugin/koralmapper"
Akron43fb1022026-02-20 11:38:49 +010019 defaultCookieName = "km-config"
Akron14c13a52025-06-06 15:36:23 +020020 defaultPort = 5725
Akron2ac2ec02025-06-05 15:26:42 +020021 defaultLogLevel = "warn"
Akron06d21f02025-06-04 14:36:07 +020022)
23
Akron57ee5582025-05-21 15:25:13 +020024// MappingRule represents a single mapping rule in the configuration
25type MappingRule string
26
27// MappingList represents a list of mapping rules with metadata
28type MappingList struct {
Akrondab27112025-06-05 13:52:43 +020029 ID string `yaml:"id"`
Akron2f93c582026-02-19 16:49:13 +010030 Type string `yaml:"type,omitempty"` // "annotation" (default) or "corpus"
Akrondab27112025-06-05 13:52:43 +020031 Description string `yaml:"desc,omitempty"`
32 FoundryA string `yaml:"foundryA,omitempty"`
33 LayerA string `yaml:"layerA,omitempty"`
34 FoundryB string `yaml:"foundryB,omitempty"`
35 LayerB string `yaml:"layerB,omitempty"`
Akrona67de8f2026-02-23 17:54:26 +010036 FieldA string `yaml:"fieldA,omitempty"`
37 FieldB string `yaml:"fieldB,omitempty"`
Akron8414ae52026-05-19 13:31:14 +020038 Rewrites bool `yaml:"rewrites,omitempty"`
Akrondab27112025-06-05 13:52:43 +020039 Mappings []MappingRule `yaml:"mappings"`
Akron57ee5582025-05-21 15:25:13 +020040}
41
Akron2f93c582026-02-19 16:49:13 +010042// IsCorpus returns true if the mapping list type is "corpus".
43func (list *MappingList) IsCorpus() bool {
44 return list.Type == "corpus"
45}
46
47// ParseCorpusMappings parses all mapping rules as corpus rules.
Akrona67de8f2026-02-23 17:54:26 +010048// Bare values (without key=) are always allowed and receive the default
49// field name from the mapping list header (FieldA/FieldB) when set.
Akron2f93c582026-02-19 16:49:13 +010050func (list *MappingList) ParseCorpusMappings() ([]*parser.CorpusMappingResult, error) {
51 corpusParser := parser.NewCorpusParser()
Akrona67de8f2026-02-23 17:54:26 +010052 corpusParser.AllowBareValues = true
53
Akron2f93c582026-02-19 16:49:13 +010054 results := make([]*parser.CorpusMappingResult, len(list.Mappings))
55 for i, rule := range list.Mappings {
56 if rule == "" {
57 return nil, fmt.Errorf("empty corpus mapping rule at index %d in list '%s'", i, list.ID)
58 }
59 result, err := corpusParser.ParseMapping(string(rule))
60 if err != nil {
61 return nil, fmt.Errorf("failed to parse corpus mapping rule %d in list '%s': %w", i, list.ID, err)
62 }
Akrona67de8f2026-02-23 17:54:26 +010063
64 if list.FieldA != "" {
65 applyDefaultCorpusKey(result.Upper, list.FieldA)
66 }
67 if list.FieldB != "" {
68 applyDefaultCorpusKey(result.Lower, list.FieldB)
69 }
70
Akron2f93c582026-02-19 16:49:13 +010071 results[i] = result
72 }
73 return results, nil
74}
75
Akrona67de8f2026-02-23 17:54:26 +010076// applyDefaultCorpusKey recursively fills in empty keys on CorpusField nodes.
77func applyDefaultCorpusKey(node parser.CorpusNode, defaultKey string) {
78 switch n := node.(type) {
79 case *parser.CorpusField:
80 if n.Key == "" {
81 n.Key = defaultKey
82 }
83 case *parser.CorpusGroup:
84 for _, op := range n.Operands {
85 applyDefaultCorpusKey(op, defaultKey)
86 }
87 }
88}
89
Akron06d21f02025-06-04 14:36:07 +020090// MappingConfig represents the root configuration containing multiple mapping lists
91type MappingConfig struct {
Akron2ac2ec02025-06-05 15:26:42 +020092 SDK string `yaml:"sdk,omitempty"`
Akron43fb1022026-02-20 11:38:49 +010093 Stylesheet string `yaml:"stylesheet,omitempty"`
Akron2ac2ec02025-06-05 15:26:42 +020094 Server string `yaml:"server,omitempty"`
95 ServiceURL string `yaml:"serviceURL,omitempty"`
Akron43fb1022026-02-20 11:38:49 +010096 CookieName string `yaml:"cookieName,omitempty"`
Akron2ac2ec02025-06-05 15:26:42 +020097 Port int `yaml:"port,omitempty"`
98 LogLevel string `yaml:"loglevel,omitempty"`
99 Lists []MappingList `yaml:"lists,omitempty"`
Akron57ee5582025-05-21 15:25:13 +0200100}
101
Akrone1cff7c2025-06-04 18:43:32 +0200102// LoadFromSources loads configuration from multiple sources and merges them:
103// - A main configuration file (optional) containing global settings and lists
104// - Individual mapping files (optional) containing single mapping lists each
105// At least one source must be provided
106func LoadFromSources(configFile string, mappingFiles []string) (*MappingConfig, error) {
107 var allLists []MappingList
108 var globalConfig MappingConfig
Akron57ee5582025-05-21 15:25:13 +0200109
Akrone1cff7c2025-06-04 18:43:32 +0200110 // Track seen IDs across all sources to detect duplicates
111 seenIDs := make(map[string]bool)
Akrona5d88142025-05-22 14:42:09 +0200112
Akrone1cff7c2025-06-04 18:43:32 +0200113 // Load main configuration file if provided
114 if configFile != "" {
115 data, err := os.ReadFile(configFile)
116 if err != nil {
117 return nil, fmt.Errorf("failed to read config file '%s': %w", configFile, err)
Akron06d21f02025-06-04 14:36:07 +0200118 }
Akrone1cff7c2025-06-04 18:43:32 +0200119
120 if len(data) == 0 {
121 return nil, fmt.Errorf("EOF: config file '%s' is empty", configFile)
122 }
123
124 // Try to unmarshal as new format first (object with optional sdk/server and lists)
Akron813780f2025-06-05 15:44:28 +0200125 if err := yaml.Unmarshal(data, &globalConfig); err == nil {
126 // Successfully parsed as new format - accept it regardless of whether it has lists
Akrone1cff7c2025-06-04 18:43:32 +0200127 for _, list := range globalConfig.Lists {
128 if seenIDs[list.ID] {
129 return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID)
130 }
131 seenIDs[list.ID] = true
132 }
133 allLists = append(allLists, globalConfig.Lists...)
134 } else {
135 // Fall back to old format (direct list)
136 var lists []MappingList
137 if err := yaml.Unmarshal(data, &lists); err != nil {
138 return nil, fmt.Errorf("failed to parse YAML config file '%s': %w", configFile, err)
139 }
140
141 for _, list := range lists {
142 if seenIDs[list.ID] {
143 return nil, fmt.Errorf("duplicate mapping list ID found: %s", list.ID)
144 }
145 seenIDs[list.ID] = true
146 }
147 allLists = append(allLists, lists...)
148 // Clear the lists from globalConfig since we got them from the old format
149 globalConfig.Lists = nil
150 }
Akron06d21f02025-06-04 14:36:07 +0200151 }
152
Akrone1cff7c2025-06-04 18:43:32 +0200153 // Load individual mapping files
154 for _, file := range mappingFiles {
155 data, err := os.ReadFile(file)
156 if err != nil {
Akron7e8da932025-07-01 11:56:46 +0200157 log.Error().Err(err).Str("file", file).Msg("Failed to read mapping file")
158 continue
Akrone1cff7c2025-06-04 18:43:32 +0200159 }
160
161 if len(data) == 0 {
Akron7e8da932025-07-01 11:56:46 +0200162 log.Error().Err(err).Str("file", file).Msg("EOF: mapping file is empty")
163 continue
Akrone1cff7c2025-06-04 18:43:32 +0200164 }
165
166 var list MappingList
167 if err := yaml.Unmarshal(data, &list); err != nil {
Akron7e8da932025-07-01 11:56:46 +0200168 log.Error().Err(err).Str("file", file).Msg("Failed to parse YAML mapping file")
169 continue
Akrone1cff7c2025-06-04 18:43:32 +0200170 }
171
172 if seenIDs[list.ID] {
Akron7e8da932025-07-01 11:56:46 +0200173 log.Error().Err(err).Str("file", file).Str("list-id", list.ID).Msg("Duplicate mapping list ID found")
174 continue
Akrone1cff7c2025-06-04 18:43:32 +0200175 }
176 seenIDs[list.ID] = true
177 allLists = append(allLists, list)
Akron57ee5582025-05-21 15:25:13 +0200178 }
179
Akrone1cff7c2025-06-04 18:43:32 +0200180 // Ensure we have at least some configuration
181 if len(allLists) == 0 {
182 return nil, fmt.Errorf("no mapping lists found: provide either a config file (-c) with lists or mapping files (-m)")
183 }
184
Akron585f50f2025-07-03 13:55:47 +0200185 // Validate all mapping lists (skip duplicate ID check since we already did it)
Akrone1cff7c2025-06-04 18:43:32 +0200186 if err := validateMappingLists(allLists); err != nil {
Akron06d21f02025-06-04 14:36:07 +0200187 return nil, err
188 }
189
Akrone1cff7c2025-06-04 18:43:32 +0200190 // Create final configuration
191 result := &MappingConfig{
Akron2ac2ec02025-06-05 15:26:42 +0200192 SDK: globalConfig.SDK,
Akron43fb1022026-02-20 11:38:49 +0100193 Stylesheet: globalConfig.Stylesheet,
Akron2ac2ec02025-06-05 15:26:42 +0200194 Server: globalConfig.Server,
195 ServiceURL: globalConfig.ServiceURL,
196 Port: globalConfig.Port,
197 LogLevel: globalConfig.LogLevel,
198 Lists: allLists,
Akrone1cff7c2025-06-04 18:43:32 +0200199 }
200
Akronf98ba282026-02-24 11:13:30 +0100201 // Apply environment variable overrides (ENV > config file)
202 ApplyEnvOverrides(result)
203
Akron06d21f02025-06-04 14:36:07 +0200204 // Apply defaults if not specified
Akron2ac2ec02025-06-05 15:26:42 +0200205 ApplyDefaults(result)
Akrone1cff7c2025-06-04 18:43:32 +0200206
207 return result, nil
208}
209
Akron585f50f2025-07-03 13:55:47 +0200210// ApplyDefaults sets default values for configuration fields if they are empty
Akron2ac2ec02025-06-05 15:26:42 +0200211func ApplyDefaults(config *MappingConfig) {
Akron585f50f2025-07-03 13:55:47 +0200212 defaults := map[*string]string{
213 &config.SDK: defaultSDK,
Akron43fb1022026-02-20 11:38:49 +0100214 &config.Stylesheet: defaultStylesheet,
Akron585f50f2025-07-03 13:55:47 +0200215 &config.Server: defaultServer,
216 &config.ServiceURL: defaultServiceURL,
Akron43fb1022026-02-20 11:38:49 +0100217 &config.CookieName: defaultCookieName,
Akron585f50f2025-07-03 13:55:47 +0200218 &config.LogLevel: defaultLogLevel,
Akron06d21f02025-06-04 14:36:07 +0200219 }
Akron585f50f2025-07-03 13:55:47 +0200220
221 for field, defaultValue := range defaults {
222 if *field == "" {
223 *field = defaultValue
224 }
Akron06d21f02025-06-04 14:36:07 +0200225 }
Akron585f50f2025-07-03 13:55:47 +0200226
Akrona8a66ce2025-06-05 10:50:17 +0200227 if config.Port == 0 {
228 config.Port = defaultPort
229 }
Akron06d21f02025-06-04 14:36:07 +0200230}
231
Akronf98ba282026-02-24 11:13:30 +0100232// ApplyEnvOverrides overrides configuration fields from environment variables.
233// All environment variables are uppercase and prefixed with KORAL_MAPPER_.
234// Non-empty environment values override any previously loaded config values.
235func ApplyEnvOverrides(config *MappingConfig) {
236 envMappings := map[string]*string{
237 "KORAL_MAPPER_SERVER": &config.Server,
238 "KORAL_MAPPER_SDK": &config.SDK,
239 "KORAL_MAPPER_STYLESHEET": &config.Stylesheet,
240 "KORAL_MAPPER_SERVICE_URL": &config.ServiceURL,
241 "KORAL_MAPPER_COOKIE_NAME": &config.CookieName,
242 "KORAL_MAPPER_LOG_LEVEL": &config.LogLevel,
243 }
244
245 for envKey, field := range envMappings {
246 if val := os.Getenv(envKey); val != "" {
247 *field = val
248 }
249 }
250
251 if val := os.Getenv("KORAL_MAPPER_PORT"); val != "" {
252 if port, err := strconv.Atoi(val); err == nil {
253 config.Port = port
254 }
255 }
256}
257
Akron585f50f2025-07-03 13:55:47 +0200258// validateMappingLists validates a slice of mapping lists (without duplicate ID checking)
Akron06d21f02025-06-04 14:36:07 +0200259func validateMappingLists(lists []MappingList) error {
Akron57ee5582025-05-21 15:25:13 +0200260 for i, list := range lists {
261 if list.ID == "" {
Akron06d21f02025-06-04 14:36:07 +0200262 return fmt.Errorf("mapping list at index %d is missing an ID", i)
Akron57ee5582025-05-21 15:25:13 +0200263 }
Akrona5d88142025-05-22 14:42:09 +0200264
Akron57ee5582025-05-21 15:25:13 +0200265 if len(list.Mappings) == 0 {
Akron06d21f02025-06-04 14:36:07 +0200266 return fmt.Errorf("mapping list '%s' has no mapping rules", list.ID)
Akron57ee5582025-05-21 15:25:13 +0200267 }
268
269 // Validate each mapping rule
270 for j, rule := range list.Mappings {
271 if rule == "" {
Akron06d21f02025-06-04 14:36:07 +0200272 return fmt.Errorf("mapping list '%s' rule at index %d is empty", list.ID, j)
Akron57ee5582025-05-21 15:25:13 +0200273 }
274 }
275 }
Akron06d21f02025-06-04 14:36:07 +0200276 return nil
Akron57ee5582025-05-21 15:25:13 +0200277}
278
279// ParseMappings parses all mapping rules in a list and returns a slice of parsed rules
280func (list *MappingList) ParseMappings() ([]*parser.MappingResult, error) {
281 // Create a grammar parser with the list's default foundries and layers
282 grammarParser, err := parser.NewGrammarParser("", "")
283 if err != nil {
284 return nil, fmt.Errorf("failed to create grammar parser: %w", err)
285 }
286
287 results := make([]*parser.MappingResult, len(list.Mappings))
288 for i, rule := range list.Mappings {
Akrona5d88142025-05-22 14:42:09 +0200289 // Check for empty rules first
290 if rule == "" {
291 return nil, fmt.Errorf("empty mapping rule at index %d in list '%s'", i, list.ID)
292 }
293
Akron57ee5582025-05-21 15:25:13 +0200294 // Parse the mapping rule
295 result, err := grammarParser.ParseMapping(string(rule))
296 if err != nil {
297 return nil, fmt.Errorf("failed to parse mapping rule %d in list '%s': %w", i, list.ID, err)
298 }
299
300 // Apply default foundries and layers if not specified in the rule
301 if list.FoundryA != "" {
302 applyDefaultFoundryAndLayer(result.Upper.Wrap, list.FoundryA, list.LayerA)
303 }
304 if list.FoundryB != "" {
305 applyDefaultFoundryAndLayer(result.Lower.Wrap, list.FoundryB, list.LayerB)
306 }
307
308 results[i] = result
309 }
310
311 return results, nil
312}
313
314// applyDefaultFoundryAndLayer recursively applies default foundry and layer to terms that don't have them specified
315func applyDefaultFoundryAndLayer(node ast.Node, defaultFoundry, defaultLayer string) {
316 switch n := node.(type) {
317 case *ast.Term:
Akron585f50f2025-07-03 13:55:47 +0200318 if n.Foundry == "" && defaultFoundry != "" {
Akron57ee5582025-05-21 15:25:13 +0200319 n.Foundry = defaultFoundry
320 }
Akron585f50f2025-07-03 13:55:47 +0200321 if n.Layer == "" && defaultLayer != "" {
Akron57ee5582025-05-21 15:25:13 +0200322 n.Layer = defaultLayer
323 }
324 case *ast.TermGroup:
325 for _, op := range n.Operands {
326 applyDefaultFoundryAndLayer(op, defaultFoundry, defaultLayer)
327 }
328 }
329}