scion_stack/path/policy.rs
1// Copyright 2025 Anapaya Systems
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//! Path policies.
15
16use std::cmp::Ordering;
17
18use scion_proto::path;
19
20/// A path wrapper that is passed to the path policy when selecting a path.
21/// In the future, this will be used to add additional information to the path.
22#[derive(Debug, Clone)]
23pub struct PolicyPath<'a> {
24 path: &'a path::Path,
25 from_registration: bool,
26}
27
28impl<'a> PolicyPath<'a> {
29 /// Create a new policy path from a scion path
30 pub fn new(path: &'a path::Path, from_registration: bool) -> Self {
31 Self {
32 path,
33 from_registration,
34 }
35 }
36
37 /// Returns true if this path came from registration rather than fetching
38 pub fn is_from_registration(&self) -> bool {
39 self.from_registration
40 }
41
42 /// Get the underlying scion path
43 pub fn scion_path(&self) -> &'a path::Path {
44 self.path
45 }
46}
47
48impl<'a> From<&'a path::Path> for PolicyPath<'a> {
49 fn from(path: &'a path::Path) -> Self {
50 Self {
51 path,
52 from_registration: false,
53 }
54 }
55}
56
57/// Path policy trait.
58pub trait PathPolicy {
59 /// Returns true if the path should be considered for selection.
60 fn predicate(&self, path: &PolicyPath<'_>) -> bool;
61 /// Indicates which of two paths is preferred, greater values are preferred.
62 fn rank(&self, path1: &PolicyPath<'_>, path2: &PolicyPath<'_>) -> Ordering;
63}
64
65/// Selects the shortest path based on the number of hops.
66#[derive(Default)]
67pub struct Shortest {}
68
69impl PathPolicy for Shortest {
70 fn predicate(&self, _: &PolicyPath<'_>) -> bool {
71 true
72 }
73
74 fn rank(&self, a: &PolicyPath<'_>, b: &PolicyPath<'_>) -> Ordering {
75 // Prefer shorter paths and paths that come from registration.
76 (a.path.interface_count(), a.is_from_registration())
77 .cmp(&(b.path.interface_count(), b.is_from_registration()))
78 }
79}