sema-config 0.1.0

Layered configuration: files, env vars, profiles, and reference expansion

Source

package.sema

322 lines dcb04426a665
File details

Source stored with sema-config 0.1.0. Line links refer to these exact bytes.

SHA-256 dcb04426a6657a36aa8d3c8742a8f92d58072cf93e0ed8f087e9c912b3fcb27d

1;; sema-config — layered configuration: files, env vars, profiles, and
2;; reference expansion, modeled on Clojure's aero + environ.
3;;
4;; Directive keys use a % sigil (:%env, :%ref, :%or, :%profiles) because the
5;; Sema reader does not accept $ in keywords — % is the closest readable sigil
6;; and works both in source code and in .sema config files.
7
8(module sema-config
9  (export config/read
10          config/load
11          config/env-overrides
12          config/get
13          config/get-in
14          config/require!)
15
16  ;; -------------------------------------------------------------------------
17  ;; Directive keys
18  ;; -------------------------------------------------------------------------
19
20  (define env-key      :%env)
21  (define ref-key      :%ref)
22  (define or-key       :%or)
23  (define profiles-key :%profiles)
24
25  ;; -------------------------------------------------------------------------
26  ;; Small helpers
27  ;; -------------------------------------------------------------------------
28
29  ;; Vectors and lists are both valid sequences in config data; lists are the
30  ;; common denominator for internal traversal.
31  (define (seq->list x)
32    (if (vector? x) (map (fn (e) e) x) x))
33
34  ;; Map f over a list or vector, preserving the input's sequence type.
35  (define (seq-map f x)
36    (if (vector? x)
37      (list->vector (map f x))
38      (map f x)))
39
40  (define (key->name k)
41    (if (keyword? k) (keyword/to-string k) (str k)))
42
43  ;; Render a key path for error messages: (:db :host) → "db.host".
44  (define (path->str path)
45    (if (null? path)
46      "<root>"
47      (string/join (map key->name path) ".")))
48
49  ;; #t iff every key in path exists (contains?, not nil-valued) in m.
50  (define (path-present? m path)
51    (cond
52      ((null? path) #t)
53      ((and (map? m) (contains? m (first path)))
54       (path-present? (get m (first path)) (rest path)))
55      (#t #f)))
56
57  ;; Recursively convert string map keys to keywords; values are normalized
58  ;; too. Lists/vectors are traversed; scalars pass through.
59  (define (normalize-keys v)
60    (cond
61      ((map? v)
62       (foldl (fn (acc entry)
63                (let ((k (first entry)))
64                  (assoc acc
65                         (if (string? k) (string/to-keyword k) k)
66                         (normalize-keys (nth entry 1)))))
67              {}
68              (map/entries v)))
69      ((or (list? v) (vector? v)) (seq-map normalize-keys v))
70      (#t v)))
71
72  ;; -------------------------------------------------------------------------
73  ;; File parsing
74  ;; -------------------------------------------------------------------------
75
76  ;; Dispatch on file extension: .toml, .json, or .sema (a single map literal
77  ;; read with the Sema reader).
78  (define (parse-file path)
79    (let* ((raw-ext (path/extension path))
80           (ext (if (nil? raw-ext) "" (string/lower raw-ext))))
81      (cond
82        ((= ext "toml") (toml/decode (file/read path)))
83        ((= ext "json") (json/decode (file/read path)))
84        ((= ext "sema")
85         (let ((v (read/string (file/read path))))
86           (if (map? v)
87             v
88             (error (format "config/read: ~a must contain a single map literal — got ~a"
89                            path v)))))
90        (#t (error (format "config/read: unsupported extension ~s for ~a — use .toml, .json, or .sema"
91                           ext path))))))
92
93  ;; -------------------------------------------------------------------------
94  ;; Profiles
95  ;; -------------------------------------------------------------------------
96
97  ;; opts :profile (keyword or string) wins; else the SEMA_PROFILE env var;
98  ;; else nil (no profile sections are applied).
99  (define (resolve-profile opts)
100    (let ((p (get opts :profile)))
101      (cond
102        ((keyword? p) p)
103        ((string? p) (string/to-keyword p))
104        ((nil? p)
105         (let ((e (env "SEMA_PROFILE")))
106           (if (nil? e) nil (string/to-keyword e))))
107        (#t (error (format "config/load: :profile must be a keyword or string — got ~a" p))))))
108
109  ;; Merge the selected profile's map over its parent level and drop the
110  ;; :%profiles key everywhere, recursively. With no profile selected the
111  ;; :%profiles sections are simply removed.
112  (define (apply-profiles v profile)
113    (cond
114      ((map? v)
115       (let* ((profs (get v profiles-key))
116              (base (dissoc v profiles-key))
117              (merged (if (and (map? profs)
118                               (not (nil? profile))
119                               (contains? profs profile))
120                        (map/deep-merge base (get profs profile))
121                        base)))
122         (if (contains? merged profiles-key)
123           (apply-profiles merged profile)
124           (map/map-vals (fn (val) (apply-profiles val profile)) merged))))
125      ((or (list? v) (vector? v))
126       (seq-map (fn (x) (apply-profiles x profile)) v))
127      (#t v)))
128
129  ;; -------------------------------------------------------------------------
130  ;; Expansion
131  ;; -------------------------------------------------------------------------
132
133  ;; Coerce an env var's string value per :as — :int, :float, :bool, or :str.
134  (define (coerce-env raw as path var)
135    (cond
136      ((or (nil? as) (= as :str)) raw)
137      ((= as :int)
138       (try (int raw)
139            (catch e
140              (error (format "config/load: at ~a — cannot coerce ~a value ~s to :int"
141                             (path->str path) var raw)))))
142      ((= as :float)
143       (try (float raw)
144            (catch e
145              (error (format "config/load: at ~a — cannot coerce ~a value ~s to :float"
146                             (path->str path) var raw)))))
147      ((= as :bool)
148       (let ((v (string/lower raw)))
149         (cond
150           ((or (= v "true") (= v "1")) #t)
151           ((or (= v "false") (= v "0")) #f)
152           (#t (error (format "config/load: at ~a — cannot coerce ~a value ~s to :bool (expected true/false/1/0)"
153                              (path->str path) var raw))))))
154      (#t (error (format "config/load: at ~a — unknown :as coercion ~a (use :int, :float, :bool, or :str)"
155                         (path->str path) as)))))
156
157  ;; {:%env "PORT" :default 3000 :as :int} → coerced env value; the :default
158  ;; is returned as-is (already typed) when the var is unset.
159  (define (expand-env directive path)
160    (let ((name (get directive env-key)))
161      (when (not (string? name))
162        (error (format "config/load: at ~a — :%env expects a variable name string, got ~a"
163                       (path->str path) name)))
164      (let ((raw (env name)))
165        (if (nil? raw)
166          (if (contains? directive :default)
167            (get directive :default)
168            (error (format "config/load: at ~a — environment variable ~a is not set and no :default was given"
169                           (path->str path) name)))
170          (coerce-env raw (get directive :as) path name)))))
171
172  ;; Substitute ${VAR} / ${VAR:default} substrings in s with env var values.
173  (define (interpolate s path)
174    (let ((start (string/index-of s "${")))
175      (if (nil? start)
176        s
177        (let* ((prefix (substring s 0 start))
178               (tail (substring s (+ start 2) (string-length s)))
179               (close (string/index-of tail "}")))
180          (when (nil? close)
181            (error (format "config/load: at ~a — unterminated ${ in ~s"
182                           (path->str path) s)))
183          (let* ((inner (substring tail 0 close))
184                 (remainder (substring tail (+ close 1) (string-length tail)))
185                 (colon (string/index-of inner ":"))
186                 (var (if (nil? colon) inner (substring inner 0 colon)))
187                 (dflt (if (nil? colon) nil (substring inner (+ colon 1) (string-length inner))))
188                 (val (env var)))
189            (when (and (nil? val) (nil? dflt))
190              (error (format "config/load: at ~a — environment variable ~a is not set and ${~a} has no default"
191                             (path->str path) var var)))
192            (str prefix
193                 (if (nil? val) dflt val)
194                 (interpolate remainder path)))))))
195
196  ;; {:%ref [:db :host]} → the expanded value at that path in the same config.
197  ;; visiting is the chain of ref paths currently being resolved, used to
198  ;; detect reference cycles.
199  (define (expand-ref directive root path visiting)
200    (let* ((rp (seq->list (get directive ref-key)))
201           (key (path->str rp)))
202      (when (any (fn (seen) (= seen key)) visiting)
203        (error (format "config/load: at ~a — :%ref cycle: ~a"
204                       (path->str path)
205                       (string/join (reverse (cons key visiting)) " -> "))))
206      (when (not (path-present? root rp))
207        (error (format "config/load: at ~a — :%ref path ~a does not exist in the config"
208                       (path->str path) key)))
209      (expand (map/get-in root rp) root rp (cons key visiting))))
210
211  ;; {:%or [a b c]} → the first alternative that expands to non-nil.
212  ;; Alternatives are expanded one at a time, so later ones are untouched
213  ;; once a value is found. An unset :%env alternative still needs
214  ;; {:default nil} to fall through rather than error — nil-on-missing is
215  ;; opted into, never silent.
216  (define (first-non-nil alts root path visiting)
217    (if (null? alts)
218      nil
219      (let ((v (expand (first alts) root path visiting)))
220        (if (nil? v)
221          (first-non-nil (rest alts) root path visiting)
222          v))))
223
224  ;; Recursive expansion over the merged, profile-applied config. root is that
225  ;; same whole map (so :%ref resolves absolute paths); path tracks the current
226  ;; location for error messages.
227  (define (expand v root path visiting)
228    (cond
229      ((map? v)
230       (cond
231         ((contains? v env-key) (expand-env v path))
232         ((contains? v ref-key) (expand-ref v root path visiting))
233         ((contains? v or-key)
234          (first-non-nil (seq->list (get v or-key)) root path visiting))
235         (#t
236          (foldl (fn (acc entry)
237                   (let ((k (first entry)))
238                     (assoc acc k (expand (nth entry 1) root
239                                          (append path (list k)) visiting))))
240                 {}
241                 (map/entries v)))))
242      ((or (list? v) (vector? v))
243       (seq-map (fn (x) (expand x root path visiting)) v))
244      ((string? v) (interpolate v path))
245      (#t v)))
246
247  ;; -------------------------------------------------------------------------
248  ;; Sources
249  ;; -------------------------------------------------------------------------
250
251  ;; A source is a file path (string) or an inline map (already keyword-keyed,
252  ;; e.g. from config/env-overrides).
253  (define (load-source src)
254    (cond
255      ((string? src) (config/read src))
256      ((map? src) (normalize-keys src))
257      (#t (error (format "config/load: sources must be file paths or maps — got ~a" src)))))
258
259  ;; -------------------------------------------------------------------------
260  ;; Public API
261  ;; -------------------------------------------------------------------------
262
263  (define (config/read path . opts)
264    "Read one config file by extension (.toml, .json, or .sema) into a keyword-keyed map. Options: {:optional #t} returns {} instead of erroring when the file is missing."
265    (let* ((o (if (null? opts) {} (first opts)))
266           (optional (get o :optional #f)))
267      (if (file/exists? path)
268        (normalize-keys (parse-file path))
269        (if optional
270          {}
271          (error (format "config/read: file not found: ~a — create it or pass {:optional #t}" path))))))
272
273  (define (config/load sources . opts)
274    "Load layered configuration: deep-merge sources left-to-right (later wins), apply the selected profile, then expand :%env/:%ref/:%or directives and ${VAR} strings. Sources are file paths and/or maps; a single path or map is also accepted. Options: {:profile :prod} (falls back to the SEMA_PROFILE env var)."
275    (let* ((o (if (null? opts) {} (first opts)))
276           (srcs (cond
277                   ((or (string? sources) (map? sources)) (list sources))
278                   ((or (list? sources) (vector? sources)) (seq->list sources))
279                   (#t (error (format "config/load: sources must be a list of paths/maps — got ~a" sources)))))
280           (profile (resolve-profile o))
281           ;; Profiles resolve per source before merging, so a base file's
282           ;; :%profiles section can never clobber a later source's override.
283           (layers (map (fn (src) (apply-profiles (load-source src) profile))
284                        srcs))
285           (merged (foldl map/deep-merge {} layers)))
286      (expand merged merged (list) (list))))
287
288  (define (config/env-overrides prefix)
289    "Collect all environment variables starting with prefix into a nested map: APP_DB__HOST=x → {:db {:host \"x\"}}. Double underscores nest; single segments become lowercase kebab-case keywords. Values stay strings — coerce at the consumer via :%env or your own parsing."
290    (foldl (fn (acc entry)
291             (let ((name (keyword/to-string (first entry))))
292               (if (string/starts-with? name prefix)
293                 (let* ((tail (substring name (string-length prefix) (string-length name)))
294                        (segments (filter (fn (s) (not (= s "")))
295                                          (string/split tail "__")))
296                        (path (map (fn (s)
297                                     (string/to-keyword
298                                       (string/replace (string/lower s) "_" "-")))
299                                   segments)))
300                   (if (null? path)
301                     acc
302                     (map/assoc-in acc path (nth entry 1))))
303                 acc)))
304           {}
305           (map/entries (sys/env-all))))
306
307  (define (config/get cfg key . default)
308    "Get a top-level config value, falling back to default (nil when omitted). Thin wrapper over the stdlib get, kept for API symmetry."
309    (get cfg key (if (null? default) nil (first default))))
310
311  (define (config/get-in cfg path . default)
312    "Get a nested config value at a key path, falling back to default (nil when omitted). Same semantics as the stdlib map/get-in, kept for API symmetry."
313    (map/get-in cfg (seq->list path) (if (null? default) nil (first default))))
314
315  (define (config/require! cfg paths)
316    "Assert that every key path in paths exists in cfg — errors listing ALL missing paths at once. Returns cfg for chaining."
317    (let ((missing (filter (fn (p) (not (path-present? cfg (seq->list p))))
318                           (seq->list paths))))
319      (when (not (null? missing))
320        (error (format "config/require!: missing required config paths: ~a — provide them in a config source or env override"
321                       (string/join (map (fn (p) (path->str (seq->list p))) missing) ", "))))
322      cfg)))