Skip to main content

codeint_config/
boundaries.rs

1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
2
3use codeint_model::{RepoPath, SourceSet};
4use globset::{Glob, GlobBuilder, GlobSet, GlobSetBuilder};
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use crate::config_error::{ConfigFileKind, ConfigurationFileError, KeyPath, KeySegment, glob_set};
9
10#[cfg(test)]
11mod tests;
12
13const WILDCARD_ZONE: &str = "*";
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
16#[serde(rename_all = "snake_case")]
17pub enum BoundaryPreset {
18    Layered,
19    Hexagonal,
20}
21
22impl BoundaryPreset {
23    pub fn as_str(self) -> &'static str {
24        match self {
25            BoundaryPreset::Layered => "layered",
26            BoundaryPreset::Hexagonal => "hexagonal",
27        }
28    }
29
30    pub fn detect(paths: &[RepoPath]) -> Option<BoundaryPreset> {
31        let layered = preset_match_score(BoundaryPreset::Layered, paths);
32        let hexagonal = preset_match_score(BoundaryPreset::Hexagonal, paths);
33        match (layered.0 >= 2, hexagonal.0 >= 2) {
34            (false, false) => None,
35            (true, false) => Some(BoundaryPreset::Layered),
36            (false, true) => Some(BoundaryPreset::Hexagonal),
37            (true, true) => {
38                if hexagonal > layered {
39                    Some(BoundaryPreset::Hexagonal)
40                } else {
41                    Some(BoundaryPreset::Layered)
42                }
43            }
44        }
45    }
46}
47
48fn preset_match_score(preset: BoundaryPreset, paths: &[RepoPath]) -> (usize, usize) {
49    let boundaries = Boundaries::from_file(BoundariesFile {
50        preset: Some(preset),
51        ..Default::default()
52    })
53    .expect("built-in boundary presets compile without error");
54    let mut matched_zones: BTreeSet<&str> = BTreeSet::new();
55    let mut canonical_zones: BTreeSet<&str> = BTreeSet::new();
56    for path in paths {
57        if let Some(zone) = boundaries.zone_of(path) {
58            matched_zones.insert(zone);
59            if path_has_folder_segment(path, zone) {
60                canonical_zones.insert(zone);
61            }
62        }
63    }
64    (matched_zones.len(), canonical_zones.len())
65}
66
67fn path_has_folder_segment(path: &RepoPath, folder: &str) -> bool {
68    let mut segments = path.as_str().split('/');
69    let _file = segments.next_back();
70    segments.any(|segment| segment == folder)
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum BoundaryDirective {
75    Allow,
76    Deny,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum BoundaryRuleDecision {
81    Allowed,
82    Denied {
83        directive: BoundaryDirective,
84        reason: Option<String>,
85    },
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct BoundaryExternalPolicy {
90    pub directive: BoundaryDirective,
91    pub patterns: Vec<String>,
92    pub reason: Option<String>,
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
96#[serde(rename_all = "snake_case")]
97pub enum BoundarySourceSet {
98    Production,
99    Test,
100    Generated,
101    Vendored,
102}
103
104impl From<BoundarySourceSet> for SourceSet {
105    fn from(value: BoundarySourceSet) -> SourceSet {
106        match value {
107            BoundarySourceSet::Production => SourceSet::Production,
108            BoundarySourceSet::Test => SourceSet::Test,
109            BoundarySourceSet::Generated => SourceSet::Generated,
110            BoundarySourceSet::Vendored => SourceSet::Vendored,
111        }
112    }
113}
114
115#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
116#[serde(deny_unknown_fields)]
117pub(crate) struct BoundariesFile {
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    #[schemars(
120        with = "BoundaryPreset",
121        description = "Optional built-in architecture preset (\"layered\" or \"hexagonal\") providing default zones and rules that can be overridden or extended by zones and rules."
122    )]
123    preset: Option<BoundaryPreset>,
124    #[serde(default)]
125    #[schemars(
126        description = "Named architectural zones, each defined by repository-relative path globs and optional public_files globs."
127    )]
128    zones: BTreeMap<String, BoundaryZoneFile>,
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    #[schemars(
131        description = "Directional allow or deny import rules between architectural zones and for external packages."
132    )]
133    rules: Vec<BoundaryRuleFile>,
134    #[serde(default, skip_serializing_if = "is_false")]
135    #[schemars(
136        description = "When true, report files in evaluated Source sets that do not match any configured zone."
137    )]
138    strict_zones: bool,
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    #[schemars(
141        description = "Source sets evaluated by boundary rules; defaults to [\"production\"] when omitted or empty."
142    )]
143    source_sets: Vec<BoundarySourceSet>,
144}
145
146#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
147#[serde(deny_unknown_fields)]
148struct BoundaryZoneFile {
149    #[schemars(
150        description = "Repository-relative path globs that assign files to this architectural zone."
151    )]
152    patterns: Vec<String>,
153    #[serde(default, skip_serializing_if = "Vec::is_empty")]
154    #[schemars(
155        description = "Optional repository-relative path globs naming the only files in this zone that other zones may import."
156    )]
157    public_files: Vec<String>,
158}
159
160#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
161#[serde(deny_unknown_fields)]
162struct BoundaryRuleFile {
163    #[schemars(
164        description = "Source zone name, or \"*\" to match any zone without a specific rule."
165    )]
166    from: String,
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    #[schemars(
169        with = "Vec<String>",
170        description = "Target zone names (or \"*\") that the source zone is allowed to import. Mutually exclusive with deny."
171    )]
172    allow: Option<Vec<String>>,
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    #[schemars(
175        with = "Vec<String>",
176        description = "Target zone names (or \"*\") that the source zone is forbidden to import. Mutually exclusive with allow."
177    )]
178    deny: Option<Vec<String>>,
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    #[schemars(
181        with = "Vec<String>",
182        description = "External package name globs that the source zone is allowed to import (use [] to forbid all third-party packages while still permitting standard-library built-ins). Mutually exclusive with deny_external."
183    )]
184    allow_external: Option<Vec<String>>,
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    #[schemars(
187        with = "Vec<String>",
188        description = "External package name globs that the source zone is forbidden to import. Mutually exclusive with allow_external."
189    )]
190    deny_external: Option<Vec<String>>,
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    #[schemars(
193        with = "String",
194        description = "Optional human-readable explanation shown in boundary Findings."
195    )]
196    reason: Option<String>,
197}
198
199fn is_false(value: &bool) -> bool {
200    !*value
201}
202
203#[derive(Debug, Clone)]
204struct CompiledZonePattern {
205    zone_name: String,
206    literal_chars: usize,
207    pattern_len: usize,
208}
209
210#[derive(Debug, Clone)]
211struct CompiledZone {
212    public_files: Option<GlobSet>,
213    public_file_patterns: Vec<String>,
214}
215
216#[derive(Debug, Clone)]
217struct CompiledRule {
218    directive: BoundaryDirective,
219    targets: HashSet<String>,
220    has_wildcard_target: bool,
221    reason: Option<String>,
222}
223
224impl CompiledRule {
225    fn matches_target(&self, target_zone: &str) -> bool {
226        self.has_wildcard_target || self.targets.contains(target_zone)
227    }
228}
229
230#[derive(Debug, Clone)]
231struct CompiledExternalRule {
232    directive: BoundaryDirective,
233    patterns: Vec<String>,
234    matcher: GlobSet,
235    reason: Option<String>,
236}
237
238#[derive(Debug, Clone)]
239pub struct Boundaries {
240    preset: Option<BoundaryPreset>,
241    resolved_zones: BTreeMap<String, BoundaryZoneFile>,
242    resolved_rules: Vec<BoundaryRuleFile>,
243    zones: BTreeMap<String, CompiledZone>,
244    zone_matcher: GlobSet,
245    zone_patterns: Vec<CompiledZonePattern>,
246    rules_by_from: HashMap<String, Vec<CompiledRule>>,
247    wildcard_rules: Vec<CompiledRule>,
248    external_rules_by_from: HashMap<String, Vec<CompiledExternalRule>>,
249    wildcard_external_rules: Vec<CompiledExternalRule>,
250    strict_zones: bool,
251    source_sets: Vec<SourceSet>,
252}
253
254impl Boundaries {
255    pub(crate) fn from_file(file: BoundariesFile) -> Result<Boundaries, ConfigurationFileError> {
256        let preset = file.preset;
257        let (merged_zones, merged_rules) = merge_preset(preset, file.zones, file.rules);
258        let resolved_zones = merged_zones.clone();
259        let resolved_rules = merged_rules.clone();
260        let boundaries_key = KeyPath::default().child(KeySegment::Key("boundaries".to_owned()));
261        let compiled_zones = compile_zones(&boundaries_key, merged_zones)?;
262        let (rules_by_from, wildcard_rules, external_rules_by_from, wildcard_external_rules) =
263            compile_rules(&boundaries_key, &compiled_zones.zones, merged_rules)?;
264        let source_sets = resolve_source_sets(file.source_sets);
265        Ok(Boundaries {
266            preset,
267            resolved_zones,
268            resolved_rules,
269            zones: compiled_zones.zones,
270            zone_matcher: compiled_zones.matcher,
271            zone_patterns: compiled_zones.patterns,
272            rules_by_from,
273            wildcard_rules,
274            external_rules_by_from,
275            wildcard_external_rules,
276            strict_zones: file.strict_zones,
277            source_sets,
278        })
279    }
280
281    pub(crate) fn preset(&self) -> Option<BoundaryPreset> {
282        self.preset
283    }
284
285    pub(crate) fn source_set_keys(&self) -> Vec<&'static str> {
286        self.source_sets.iter().map(|set| set.key()).collect()
287    }
288
289    pub(crate) fn resolved_zones_json(&self) -> serde_json::Value {
290        serde_json::to_value(&self.resolved_zones).unwrap_or(serde_json::Value::Null)
291    }
292
293    pub(crate) fn resolved_rules_json(&self) -> serde_json::Value {
294        serde_json::to_value(&self.resolved_rules).unwrap_or(serde_json::Value::Null)
295    }
296
297    pub fn applies_to_source_set(&self, source_set: SourceSet) -> bool {
298        self.source_sets.contains(&source_set)
299    }
300
301    pub fn strict_zones(&self) -> bool {
302        self.strict_zones
303    }
304
305    pub fn zone_names(&self) -> Vec<&str> {
306        self.zones.keys().map(String::as_str).collect()
307    }
308
309    pub fn public_file_patterns(&self, zone: &str) -> &[String] {
310        self.zones
311            .get(zone)
312            .map_or(&[], |compiled| compiled.public_file_patterns.as_slice())
313    }
314
315    pub fn allow_reason(&self, source_zone: &str, target_zone: &str) -> Option<&str> {
316        if source_zone == target_zone {
317            return None;
318        }
319        let applicable = self.applicable_rules(source_zone);
320        let first = applicable.first()?;
321        if first.directive != BoundaryDirective::Allow {
322            return None;
323        }
324        applicable
325            .iter()
326            .find(|rule| rule.matches_target(target_zone))
327            .and_then(|rule| rule.reason.as_deref())
328    }
329
330    fn applicable_rules(&self, source_zone: &str) -> &[CompiledRule] {
331        self.rules_by_from
332            .get(source_zone)
333            .map(Vec::as_slice)
334            .unwrap_or(&self.wildcard_rules)
335    }
336
337    pub fn zone_of(&self, path: &RepoPath) -> Option<&str> {
338        let mut best: Option<(&str, usize, usize)> = None;
339        for index in self.zone_matcher.matches(path.as_str()) {
340            let pattern = &self.zone_patterns[index];
341            let candidate = (
342                pattern.zone_name.as_str(),
343                pattern.literal_chars,
344                pattern.pattern_len,
345            );
346            let replaces = match best {
347                None => true,
348                Some((best_name, best_literals, best_len)) => {
349                    (candidate.1, candidate.2) > (best_literals, best_len)
350                        || ((candidate.1, candidate.2) == (best_literals, best_len)
351                            && candidate.0 < best_name)
352                }
353            };
354            if replaces {
355                best = Some(candidate);
356            }
357        }
358        best.map(|(name, _, _)| name)
359    }
360
361    pub fn has_public_files(&self, zone: &str) -> bool {
362        self.zones
363            .get(zone)
364            .is_some_and(|compiled| compiled.public_files.is_some())
365    }
366
367    pub fn is_public_file(&self, zone: &str, path: &RepoPath) -> bool {
368        match self.zones.get(zone).and_then(|z| z.public_files.as_ref()) {
369            Some(globs) => globs.is_match(path.as_str()),
370            None => true,
371        }
372    }
373
374    pub fn has_external_rules(&self) -> bool {
375        !self.external_rules_by_from.is_empty() || !self.wildcard_external_rules.is_empty()
376    }
377
378    pub fn external_policy_for(&self, source_zone: &str) -> Option<BoundaryExternalPolicy> {
379        let applicable = self.applicable_external_rules(source_zone);
380        let first = applicable.first()?;
381        let mut patterns = Vec::new();
382        let mut reasons = Vec::new();
383        for rule in applicable {
384            for pattern in &rule.patterns {
385                if !patterns.contains(pattern) {
386                    patterns.push(pattern.clone());
387                }
388            }
389            if let Some(reason) = &rule.reason
390                && !reasons.contains(reason)
391            {
392                reasons.push(reason.clone());
393            }
394        }
395        let reason = (!reasons.is_empty()).then(|| reasons.join("; "));
396        Some(BoundaryExternalPolicy {
397            directive: first.directive,
398            patterns,
399            reason,
400        })
401    }
402
403    fn applicable_external_rules(&self, source_zone: &str) -> &[CompiledExternalRule] {
404        self.external_rules_by_from
405            .get(source_zone)
406            .map(Vec::as_slice)
407            .unwrap_or(&self.wildcard_external_rules)
408    }
409
410    pub fn check_external_import(&self, source_zone: &str, package: &str) -> BoundaryRuleDecision {
411        let applicable = self.applicable_external_rules(source_zone);
412        evaluate_directive_rules(
413            applicable,
414            |rule| rule.directive,
415            |rule| rule.reason.as_deref(),
416            |rule| rule.matcher.is_match(package),
417        )
418    }
419
420    pub fn check_import(&self, source_zone: &str, target_zone: &str) -> BoundaryRuleDecision {
421        if source_zone == target_zone {
422            return BoundaryRuleDecision::Allowed;
423        }
424        let applicable = self.applicable_rules(source_zone);
425        evaluate_directive_rules(
426            applicable,
427            |rule| rule.directive,
428            |rule| rule.reason.as_deref(),
429            |rule| rule.matches_target(target_zone),
430        )
431    }
432}
433
434fn evaluate_directive_rules<T>(
435    applicable: &[T],
436    directive_of: impl Fn(&T) -> BoundaryDirective,
437    reason_of: impl Fn(&T) -> Option<&str>,
438    matches_rule: impl Fn(&T) -> bool,
439) -> BoundaryRuleDecision {
440    let Some(first) = applicable.first() else {
441        return BoundaryRuleDecision::Allowed;
442    };
443    match directive_of(first) {
444        BoundaryDirective::Allow => {
445            if applicable.iter().any(matches_rule) {
446                BoundaryRuleDecision::Allowed
447            } else {
448                let reason = applicable
449                    .iter()
450                    .find_map(|rule| reason_of(rule).map(str::to_owned));
451                BoundaryRuleDecision::Denied {
452                    directive: BoundaryDirective::Allow,
453                    reason,
454                }
455            }
456        }
457        BoundaryDirective::Deny => {
458            for rule in applicable {
459                if matches_rule(rule) {
460                    return BoundaryRuleDecision::Denied {
461                        directive: BoundaryDirective::Deny,
462                        reason: reason_of(rule).map(str::to_owned),
463                    };
464                }
465            }
466            BoundaryRuleDecision::Allowed
467        }
468    }
469}
470
471struct CompiledZones {
472    zones: BTreeMap<String, CompiledZone>,
473    matcher: GlobSet,
474    patterns: Vec<CompiledZonePattern>,
475}
476
477fn compile_zones(
478    boundaries_key: &KeyPath,
479    merged_zones: BTreeMap<String, BoundaryZoneFile>,
480) -> Result<CompiledZones, ConfigurationFileError> {
481    let zones_key = boundaries_key.child(KeySegment::Key("zones".to_owned()));
482    let mut zones = BTreeMap::new();
483    let mut matcher_builder = GlobSetBuilder::new();
484    let mut patterns = Vec::new();
485    for (name, zone_file) in merged_zones {
486        let (compiled_name, compiled_zone, compiled_globs) =
487            compile_zone(&zones_key, name, zone_file)?;
488        for (glob, literal_chars, pattern_len) in compiled_globs {
489            matcher_builder.add(glob);
490            patterns.push(CompiledZonePattern {
491                zone_name: compiled_name.clone(),
492                literal_chars,
493                pattern_len,
494            });
495        }
496        zones.insert(compiled_name, compiled_zone);
497    }
498    let matcher =
499        matcher_builder
500            .build()
501            .map_err(|source| ConfigurationFileError::InvalidGlob {
502                file: ConfigFileKind::Json,
503                key: zones_key,
504                source,
505            })?;
506    Ok(CompiledZones {
507        zones,
508        matcher,
509        patterns,
510    })
511}
512
513type CompiledZoneGlobs = Vec<(Glob, usize, usize)>;
514
515fn compile_zone(
516    zones_key: &KeyPath,
517    name: String,
518    zone_file: BoundaryZoneFile,
519) -> Result<(String, CompiledZone, CompiledZoneGlobs), ConfigurationFileError> {
520    let zone_key = zones_key.child(KeySegment::Key(name.clone()));
521    if name.trim().is_empty() || name == WILDCARD_ZONE {
522        return Err(ConfigurationFileError::InvalidBoundaryZoneName {
523            file: ConfigFileKind::Json,
524            key: zone_key,
525            name,
526        });
527    }
528    let patterns_key = zone_key.child(KeySegment::Key("patterns".to_owned()));
529    if zone_file.patterns.is_empty() {
530        return Err(ConfigurationFileError::EmptyBoundaryZonePatterns {
531            file: ConfigFileKind::Json,
532            key: patterns_key,
533            zone: name,
534        });
535    }
536    let patterns = compile_patterns(&patterns_key, &zone_file.patterns)?;
537    let public_file_patterns = zone_file.public_files;
538    let public_files = if public_file_patterns.is_empty() {
539        None
540    } else {
541        let public_key = zone_key.child(KeySegment::Key("public_files".to_owned()));
542        Some(glob_set(&public_key, &public_file_patterns)?)
543    };
544    Ok((
545        name,
546        CompiledZone {
547            public_files,
548            public_file_patterns,
549        },
550        patterns,
551    ))
552}
553
554type CompiledRuleIndex = (
555    HashMap<String, Vec<CompiledRule>>,
556    Vec<CompiledRule>,
557    HashMap<String, Vec<CompiledExternalRule>>,
558    Vec<CompiledExternalRule>,
559);
560
561fn compile_rules(
562    boundaries_key: &KeyPath,
563    zones: &BTreeMap<String, CompiledZone>,
564    merged_rules: Vec<BoundaryRuleFile>,
565) -> Result<CompiledRuleIndex, ConfigurationFileError> {
566    let known_zones: Vec<String> = zones.keys().cloned().collect();
567    let rules_key = boundaries_key.child(KeySegment::Key("rules".to_owned()));
568    let mut rules_by_from: HashMap<String, Vec<CompiledRule>> = HashMap::new();
569    let mut wildcard_rules = Vec::new();
570    let mut external_rules_by_from: HashMap<String, Vec<CompiledExternalRule>> = HashMap::new();
571    let mut wildcard_external_rules = Vec::new();
572    let mut internal_by_from: BTreeMap<String, BoundaryDirective> = BTreeMap::new();
573    let mut external_by_from: BTreeMap<String, BoundaryDirective> = BTreeMap::new();
574    for (index, rule) in merged_rules.into_iter().enumerate() {
575        let rule_key = rules_key.child(KeySegment::Index(index));
576        let from = rule.from.clone();
577        let (internal, external) = compile_rule(
578            &rule_key,
579            rule,
580            zones,
581            &known_zones,
582            &mut internal_by_from,
583            &mut external_by_from,
584        )?;
585        if let Some(compiled) = internal {
586            if from == WILDCARD_ZONE {
587                wildcard_rules.push(compiled);
588            } else {
589                rules_by_from
590                    .entry(from.clone())
591                    .or_default()
592                    .push(compiled);
593            }
594        }
595        if let Some(compiled) = external {
596            if from == WILDCARD_ZONE {
597                wildcard_external_rules.push(compiled);
598            } else {
599                external_rules_by_from
600                    .entry(from)
601                    .or_default()
602                    .push(compiled);
603            }
604        }
605    }
606    Ok((
607        rules_by_from,
608        wildcard_rules,
609        external_rules_by_from,
610        wildcard_external_rules,
611    ))
612}
613
614fn compile_rule(
615    rule_key: &KeyPath,
616    rule: BoundaryRuleFile,
617    zones: &BTreeMap<String, CompiledZone>,
618    known_zones: &[String],
619    internal_by_from: &mut BTreeMap<String, BoundaryDirective>,
620    external_by_from: &mut BTreeMap<String, BoundaryDirective>,
621) -> Result<(Option<CompiledRule>, Option<CompiledExternalRule>), ConfigurationFileError> {
622    validate_source_zone(rule_key, &rule.from, zones, known_zones)?;
623    let internal = extract_directive_pair(
624        rule_key,
625        &rule.from,
626        rule.allow,
627        rule.deny,
628        ("allow", "deny"),
629        |key, from| ConfigurationFileError::ConflictingBoundaryRule {
630            file: ConfigFileKind::Json,
631            key,
632            from,
633        },
634    )?;
635    let external = extract_directive_pair(
636        rule_key,
637        &rule.from,
638        rule.allow_external,
639        rule.deny_external,
640        ("allow_external", "deny_external"),
641        |key, from| ConfigurationFileError::ConflictingExternalBoundaryRule {
642            file: ConfigFileKind::Json,
643            key,
644            from,
645        },
646    )?;
647    if internal.is_none() && external.is_none() {
648        return Err(ConfigurationFileError::MissingBoundaryRuleDirective {
649            file: ConfigFileKind::Json,
650            key: rule_key.clone(),
651            from: rule.from,
652        });
653    }
654    let reason = rule.reason.filter(|text| !text.trim().is_empty());
655    let compiled_internal = internal
656        .map(|entry| {
657            compile_internal_rule(
658                rule_key,
659                &rule.from,
660                entry,
661                reason.clone(),
662                zones,
663                known_zones,
664                internal_by_from,
665            )
666        })
667        .transpose()?;
668    let compiled_external = external
669        .map(|entry| compile_external_rule(rule_key, &rule.from, entry, reason, external_by_from))
670        .transpose()?;
671    Ok((compiled_internal, compiled_external))
672}
673
674fn validate_source_zone(
675    rule_key: &KeyPath,
676    from: &str,
677    zones: &BTreeMap<String, CompiledZone>,
678    known_zones: &[String],
679) -> Result<(), ConfigurationFileError> {
680    if from != WILDCARD_ZONE && !zones.contains_key(from) {
681        return Err(ConfigurationFileError::UnknownBoundaryZone {
682            file: ConfigFileKind::Json,
683            key: rule_key.child(KeySegment::Key("from".to_owned())),
684            zone: from.to_owned(),
685            known: known_zones.to_vec(),
686        });
687    }
688    Ok(())
689}
690
691fn prepare_rule_key(
692    rule_key: &KeyPath,
693    from: &str,
694    entry: &RuleDirectiveValues,
695    by_from: &mut BTreeMap<String, BoundaryDirective>,
696    external: bool,
697) -> Result<KeyPath, ConfigurationFileError> {
698    record_rule_directive(rule_key, from, entry.directive, by_from, |key, zone| {
699        if external {
700            ConfigurationFileError::ConflictingExternalBoundaryDirectives {
701                file: ConfigFileKind::Json,
702                key,
703                from: zone,
704            }
705        } else {
706            ConfigurationFileError::ConflictingBoundaryDirectives {
707                file: ConfigFileKind::Json,
708                key,
709                from: zone,
710            }
711        }
712    })?;
713    Ok(rule_key.child(KeySegment::Key(entry.key_name.to_owned())))
714}
715
716fn compile_internal_rule(
717    rule_key: &KeyPath,
718    from: &str,
719    entry: RuleDirectiveValues,
720    reason: Option<String>,
721    zones: &BTreeMap<String, CompiledZone>,
722    known_zones: &[String],
723    by_from: &mut BTreeMap<String, BoundaryDirective>,
724) -> Result<CompiledRule, ConfigurationFileError> {
725    let targets_key = prepare_rule_key(rule_key, from, &entry, by_from, false)?;
726    validate_rule_targets(&targets_key, &entry.values, zones, known_zones)?;
727    let has_wildcard_target = entry.values.iter().any(|target| target == WILDCARD_ZONE);
728    let targets = entry
729        .values
730        .into_iter()
731        .filter(|target| target != WILDCARD_ZONE)
732        .collect();
733    Ok(CompiledRule {
734        directive: entry.directive,
735        targets,
736        has_wildcard_target,
737        reason,
738    })
739}
740
741fn compile_external_rule(
742    rule_key: &KeyPath,
743    from: &str,
744    entry: RuleDirectiveValues,
745    reason: Option<String>,
746    by_from: &mut BTreeMap<String, BoundaryDirective>,
747) -> Result<CompiledExternalRule, ConfigurationFileError> {
748    let patterns_key = prepare_rule_key(rule_key, from, &entry, by_from, true)?;
749    let matcher = compile_external_globs(&patterns_key, &entry.values)?;
750    Ok(CompiledExternalRule {
751        directive: entry.directive,
752        patterns: entry.values,
753        matcher,
754        reason,
755    })
756}
757
758struct RuleDirectiveValues {
759    directive: BoundaryDirective,
760    values: Vec<String>,
761    key_name: &'static str,
762}
763
764fn record_rule_directive(
765    rule_key: &KeyPath,
766    from: &str,
767    directive: BoundaryDirective,
768    by_from: &mut BTreeMap<String, BoundaryDirective>,
769    conflict_error: impl FnOnce(KeyPath, String) -> ConfigurationFileError,
770) -> Result<(), ConfigurationFileError> {
771    if let Some(&previous) = by_from.get(from)
772        && previous != directive
773    {
774        return Err(conflict_error(rule_key.clone(), from.to_owned()));
775    }
776    by_from.insert(from.to_owned(), directive);
777    Ok(())
778}
779
780fn extract_directive_pair(
781    rule_key: &KeyPath,
782    from: &str,
783    allow: Option<Vec<String>>,
784    deny: Option<Vec<String>>,
785    key_names: (&'static str, &'static str),
786    conflict_error: impl FnOnce(KeyPath, String) -> ConfigurationFileError,
787) -> Result<Option<RuleDirectiveValues>, ConfigurationFileError> {
788    match (allow, deny) {
789        (Some(values), None) => Ok(Some(RuleDirectiveValues {
790            directive: BoundaryDirective::Allow,
791            values,
792            key_name: key_names.0,
793        })),
794        (None, Some(values)) => Ok(Some(RuleDirectiveValues {
795            directive: BoundaryDirective::Deny,
796            values,
797            key_name: key_names.1,
798        })),
799        (Some(_), Some(_)) => Err(conflict_error(rule_key.clone(), from.to_owned())),
800        (None, None) => Ok(None),
801    }
802}
803
804fn compile_external_globs(
805    key: &KeyPath,
806    patterns: &[String],
807) -> Result<GlobSet, ConfigurationFileError> {
808    let mut builder = GlobSetBuilder::new();
809    for (index, pattern) in patterns.iter().enumerate() {
810        let pattern_key = key.child(KeySegment::Index(index));
811        if pattern.trim().is_empty() {
812            return Err(ConfigurationFileError::EmptyBoundaryExternalPattern {
813                file: ConfigFileKind::Json,
814                key: pattern_key,
815            });
816        }
817        let compiled = GlobBuilder::new(pattern)
818            .literal_separator(false)
819            .backslash_escape(true)
820            .build()
821            .map_err(|source| ConfigurationFileError::InvalidGlob {
822                file: ConfigFileKind::Json,
823                key: pattern_key,
824                source,
825            })?;
826        builder.add(compiled);
827    }
828    builder
829        .build()
830        .map_err(|source| ConfigurationFileError::InvalidGlob {
831            file: ConfigFileKind::Json,
832            key: key.clone(),
833            source,
834        })
835}
836
837fn validate_rule_targets(
838    targets_key: &KeyPath,
839    targets: &[String],
840    zones: &BTreeMap<String, CompiledZone>,
841    known_zones: &[String],
842) -> Result<(), ConfigurationFileError> {
843    for (target_index, target) in targets.iter().enumerate() {
844        if target != WILDCARD_ZONE && !zones.contains_key(target) {
845            return Err(ConfigurationFileError::UnknownBoundaryZone {
846                file: ConfigFileKind::Json,
847                key: targets_key.child(KeySegment::Index(target_index)),
848                zone: target.clone(),
849                known: known_zones.to_vec(),
850            });
851        }
852    }
853    Ok(())
854}
855
856fn resolve_source_sets(source_sets: Vec<BoundarySourceSet>) -> Vec<SourceSet> {
857    if source_sets.is_empty() {
858        vec![SourceSet::Production]
859    } else {
860        source_sets.into_iter().map(SourceSet::from).collect()
861    }
862}
863
864fn compile_patterns(
865    key: &KeyPath,
866    globs: &[String],
867) -> Result<CompiledZoneGlobs, ConfigurationFileError> {
868    globs
869        .iter()
870        .enumerate()
871        .map(|(index, glob)| {
872            let compiled = GlobBuilder::new(glob)
873                .literal_separator(true)
874                .backslash_escape(true)
875                .build()
876                .map_err(|source| ConfigurationFileError::InvalidGlob {
877                    file: ConfigFileKind::Json,
878                    key: key.child(KeySegment::Index(index)),
879                    source,
880                })?;
881            Ok((compiled, literal_char_count(glob), glob.len()))
882        })
883        .collect()
884}
885
886fn literal_char_count(pattern: &str) -> usize {
887    pattern
888        .chars()
889        .filter(|character| !matches!(character, '*' | '?' | '[' | ']' | '{' | '}'))
890        .count()
891}
892
893fn merge_preset(
894    preset: Option<BoundaryPreset>,
895    user_zones: BTreeMap<String, BoundaryZoneFile>,
896    user_rules: Vec<BoundaryRuleFile>,
897) -> (BTreeMap<String, BoundaryZoneFile>, Vec<BoundaryRuleFile>) {
898    let Some(preset) = preset else {
899        return (user_zones, user_rules);
900    };
901    let (mut zones, preset_rules) = preset_defaults(preset);
902    for (name, zone) in user_zones {
903        zones.insert(name, zone);
904    }
905    let overridden_from: BTreeSet<String> = user_rules
906        .iter()
907        .filter(|rule| rule.allow.is_some() || rule.deny.is_some())
908        .map(|rule| rule.from.clone())
909        .collect();
910    let mut rules: Vec<BoundaryRuleFile> = preset_rules
911        .into_iter()
912        .filter(|rule| !overridden_from.contains(&rule.from))
913        .collect();
914    rules.extend(user_rules);
915    (zones, rules)
916}
917
918fn preset_defaults(
919    preset: BoundaryPreset,
920) -> (BTreeMap<String, BoundaryZoneFile>, Vec<BoundaryRuleFile>) {
921    match preset {
922        BoundaryPreset::Layered => layered_preset(),
923        BoundaryPreset::Hexagonal => hexagonal_preset(),
924    }
925}
926
927fn zone_patterns(patterns: &[&str]) -> BoundaryZoneFile {
928    BoundaryZoneFile {
929        patterns: patterns
930            .iter()
931            .map(|pattern| (*pattern).to_owned())
932            .collect(),
933        public_files: Vec::new(),
934    }
935}
936
937fn allow_rule(from: &str, allow: &[&str], reason: &str) -> BoundaryRuleFile {
938    BoundaryRuleFile {
939        from: from.to_owned(),
940        allow: Some(allow.iter().map(|target| (*target).to_owned()).collect()),
941        deny: None,
942        allow_external: None,
943        deny_external: None,
944        reason: Some(reason.to_owned()),
945    }
946}
947
948fn layered_preset() -> (BTreeMap<String, BoundaryZoneFile>, Vec<BoundaryRuleFile>) {
949    let mut zones = BTreeMap::new();
950    zones.insert(
951        "presentation".to_owned(),
952        zone_patterns(&[
953            "**/presentation/**",
954            "**/ui/**",
955            "**/web/**",
956            "**/api/**",
957            "**/controllers/**",
958            "**/routes/**",
959        ]),
960    );
961    zones.insert(
962        "application".to_owned(),
963        zone_patterns(&[
964            "**/application/**",
965            "**/app/**",
966            "**/services/**",
967            "**/usecases/**",
968            "**/use-cases/**",
969            "**/use_cases/**",
970        ]),
971    );
972    zones.insert(
973        "domain".to_owned(),
974        zone_patterns(&[
975            "**/domain/**",
976            "**/core/**",
977            "**/entities/**",
978            "**/models/**",
979        ]),
980    );
981    zones.insert(
982        "infrastructure".to_owned(),
983        zone_patterns(&[
984            "**/infrastructure/**",
985            "**/infra/**",
986            "**/adapters/**",
987            "**/repositories/**",
988            "**/db/**",
989            "**/persistence/**",
990        ]),
991    );
992    let rules = vec![
993        allow_rule(
994            "domain",
995            &["domain"],
996            "Layered preset: domain layer must not depend on outer layers",
997        ),
998        allow_rule(
999            "application",
1000            &["domain"],
1001            "Layered preset: application layer may only depend on domain",
1002        ),
1003        allow_rule(
1004            "infrastructure",
1005            &["domain", "application"],
1006            "Layered preset: infrastructure layer may only depend on domain and application",
1007        ),
1008        allow_rule(
1009            "presentation",
1010            &["application", "domain"],
1011            "Layered preset: presentation layer must not depend directly on infrastructure",
1012        ),
1013    ];
1014    (zones, rules)
1015}
1016
1017fn hexagonal_preset() -> (BTreeMap<String, BoundaryZoneFile>, Vec<BoundaryRuleFile>) {
1018    let mut zones = BTreeMap::new();
1019    zones.insert(
1020        "domain".to_owned(),
1021        zone_patterns(&["**/domain/**", "**/core/**", "**/entities/**"]),
1022    );
1023    zones.insert("ports".to_owned(), zone_patterns(&["**/ports/**"]));
1024    zones.insert(
1025        "application".to_owned(),
1026        zone_patterns(&[
1027            "**/application/**",
1028            "**/app/**",
1029            "**/usecases/**",
1030            "**/use-cases/**",
1031            "**/use_cases/**",
1032        ]),
1033    );
1034    zones.insert(
1035        "adapters".to_owned(),
1036        zone_patterns(&[
1037            "**/adapters/**",
1038            "**/infrastructure/**",
1039            "**/infra/**",
1040            "**/driving/**",
1041            "**/driven/**",
1042            "**/inbound/**",
1043            "**/outbound/**",
1044        ]),
1045    );
1046    let rules = vec![
1047        allow_rule(
1048            "domain",
1049            &["domain"],
1050            "Hexagonal preset: domain must stay independent of ports, application, and adapters",
1051        ),
1052        allow_rule(
1053            "ports",
1054            &["domain"],
1055            "Hexagonal preset: ports may only depend on domain",
1056        ),
1057        allow_rule(
1058            "application",
1059            &["domain", "ports"],
1060            "Hexagonal preset: application may only depend on domain and ports, not adapters",
1061        ),
1062        allow_rule(
1063            "adapters",
1064            &["domain", "ports", "application"],
1065            "Hexagonal preset: adapters may depend on domain, ports, and application",
1066        ),
1067    ];
1068    (zones, rules)
1069}