Skip to main content

sofie_model/
messages.rs

1use std::path::Path;
2
3use syn::parse::ParseStream;
4use syn::{Attribute, FnArg, Ident, Item, ItemFn, LitStr, Meta, Token, Type};
5
6use crate::areas::{area_definition, implementing};
7use crate::code::{Code, derives};
8use crate::contract_traits::{ContractTrait, contract_trait};
9use crate::gateways::{GatewayTrait, gateway_trait};
10use crate::handlers::HandlerScope;
11use crate::provisions::{ImplSite, impl_site, unit_struct};
12use crate::syntax::{is_attribute, line_of, segments};
13use crate::{
14    AreaDefinition, Cadence, EventDeclaration, Job, Listener, ModelError, PrivateItem, Schedule,
15    Task, WallClock,
16};
17
18const TASK_MODULE: &str = "tasks";
19
20#[derive(Default)]
21pub(crate) struct Found {
22    pub listeners: Vec<Listener>,
23    pub schedules: Vec<Schedule>,
24    pub events: Vec<EventDeclaration>,
25    pub areas: Vec<AreaDefinition>,
26    pub member_areas: Vec<String>,
27    pub sign_up_areas: Vec<String>,
28    pub jobs: Vec<Job>,
29    pub tasks: Vec<Task>,
30    pub impls: Vec<ImplSite>,
31    pub units: Vec<Vec<String>>,
32    pub gateways: Vec<GatewayTrait>,
33    pub contract_traits: Vec<ContractTrait>,
34    pub private_items: Vec<PrivateItem>,
35    pub code: Code,
36}
37
38impl Found {
39    pub(crate) fn wired_count(&self) -> usize {
40        self.listeners.len()
41            + self.schedules.len()
42            + self.events.len()
43            + self.areas.len()
44            + self.jobs.len()
45            + self.tasks.len()
46    }
47}
48
49pub(crate) fn collect_item(
50    item: &Item,
51    file: &Path,
52    scope: &HandlerScope,
53    found: &mut Found,
54) -> Result<(), ModelError> {
55    let module_path = scope.module_path();
56    found.code.collect(item, file, scope);
57    found.units.extend(unit_struct(item, module_path));
58    found
59        .gateways
60        .extend(gateway_trait(item, file, module_path));
61    found
62        .contract_traits
63        .extend(contract_trait(item, file, module_path));
64    match item {
65        Item::Fn(function) => collect_function(function, file, scope, found),
66        // `sofie gen` writes a pruned event per aggregate; listing each would only repeat them.
67        Item::Struct(_)
68            if is_contract_gen(file) && module_path.last().is_some_and(|name| name == "pruned") =>
69        {
70            Ok(())
71        }
72        Item::Struct(structure) if derives(&structure.attrs, "Event") => {
73            found.events.push(EventDeclaration {
74                name: structure.ident.to_string(),
75                file: file.to_path_buf(),
76                line: line_of(structure),
77            });
78            Ok(())
79        }
80        Item::Impl(implementation) => {
81            found
82                .impls
83                .extend(impl_site(implementation, file, module_path));
84            found
85                .areas
86                .extend(area_definition(implementation, file, module_path)?);
87            if !is_contract_gen(file) {
88                found
89                    .member_areas
90                    .extend(implementing(implementation, "MemberArea"));
91            }
92            found
93                .sign_up_areas
94                .extend(implementing(implementation, "SignUp"));
95            Ok(())
96        }
97        _ => Ok(()),
98    }
99}
100
101/// `sofie gen` writes a `MemberArea` there itself; read as hand-written, the next run would
102/// drop it and the one after write it again.
103fn is_contract_gen(file: &Path) -> bool {
104    file.ends_with(
105        Path::new("src")
106            .join(crate::naming::GEN_MODULE)
107            .join("mod.rs"),
108    )
109}
110
111fn collect_function(
112    function: &ItemFn,
113    file: &Path,
114    scope: &HandlerScope,
115    found: &mut Found,
116) -> Result<(), ModelError> {
117    let module_path = scope.module_path();
118    let mut path = module_path.to_vec();
119    path.push(function.sig.ident.to_string());
120    for attribute in &function.attrs {
121        let line = line_of(attribute);
122        if is_attribute(attribute, "on") {
123            found.listeners.push(Listener {
124                file: file.to_path_buf(),
125                line,
126                function: path.clone(),
127                event: listened_event(attribute, function)
128                    .and_then(|written| scope.qualified(&written))
129                    .map_err(|message| ModelError::new(file, line, message))?,
130            });
131        } else if is_attribute(attribute, "job") {
132            found.jobs.push(Job {
133                file: file.to_path_buf(),
134                line,
135                function: path.clone(),
136            });
137        } else if is_attribute(attribute, "task") {
138            let task = task(&found.tasks, file, line, path.clone())
139                .map_err(|message| ModelError::new(file, line, message))?;
140            found.tasks.push(task);
141        } else if is_attribute(attribute, "every") {
142            let (cadence, each) = schedule_arguments(attribute);
143            found.schedules.push(Schedule {
144                file: file.to_path_buf(),
145                line,
146                function: path.clone(),
147                cadence,
148                each: each.map(|each| scope.callee(&each)),
149            });
150        }
151    }
152    Ok(())
153}
154
155fn task(
156    tasks: &[Task],
157    file: &Path,
158    line: usize,
159    function: Vec<String>,
160) -> Result<Task, &'static str> {
161    if function.first().map(String::as_str) != Some(TASK_MODULE) {
162        return Err("a task lives in its module's `src/tasks.rs` or `src/tasks/`");
163    }
164    if tasks
165        .iter()
166        .any(|task| task.function.last() == function.last())
167    {
168        return Err(
169            "another task of this module has this function's name; a task is named \
170             `<module>.<function>`",
171        );
172    }
173    Ok(Task {
174        file: file.to_path_buf(),
175        line,
176        function,
177    })
178}
179
180/// The attribute macro refuses a malformed one; read as written, the schedule rules report it.
181fn schedule_arguments(attribute: &Attribute) -> (Cadence, Option<Vec<String>>) {
182    attribute
183        .parse_args_with(read_schedule)
184        .unwrap_or_else(|_| {
185            let written = attribute
186                .meta
187                .require_list()
188                .map(|list| list.tokens.to_string());
189            (Cadence::Interval(written.unwrap_or_default()), None)
190        })
191}
192
193fn read_schedule(input: ParseStream) -> syn::Result<(Cadence, Option<Vec<String>>)> {
194    let interval = input
195        .peek(LitStr)
196        .then(|| input.parse::<LitStr>())
197        .transpose()?;
198    let (mut each, mut daily_at, mut weekly_on, mut zone) = (None, None, None, None);
199    let mut follows_an_argument = interval.is_some();
200    while !input.is_empty() {
201        if follows_an_argument {
202            input.parse::<Token![,]>()?;
203            if input.is_empty() {
204                break;
205            }
206        }
207        follows_an_argument = true;
208        let key: Ident = input.parse()?;
209        input.parse::<Token![=]>()?;
210        if key == "each" {
211            each = Some(segments(&input.parse::<syn::Path>()?));
212            continue;
213        }
214        let value = input.parse::<LitStr>()?.value();
215        match key.to_string().as_str() {
216            "daily_at" => daily_at = Some(value),
217            "weekly_on" => weekly_on = Some(value),
218            "zone" => zone = Some(value),
219            _ => return Err(syn::Error::new(key.span(), "unknown schedule argument")),
220        }
221    }
222    let cadence = match (interval, daily_at) {
223        (Some(interval), None) => Cadence::Interval(interval.value()),
224        (None, Some(daily_at)) => Cadence::WallClock(WallClock {
225            daily_at,
226            weekly_on,
227            zone: zone.unwrap_or_default(),
228        }),
229        _ => return Err(input.error("an interval or `daily_at`")),
230    };
231    Ok((cadence, each))
232}
233
234fn listened_event(attribute: &Attribute, function: &ItemFn) -> Result<Vec<String>, String> {
235    if !matches!(attribute.meta, Meta::Path(_)) {
236        return Err(
237            "write a bare `#[on]`: the listener's first argument's type is the event".to_owned(),
238        );
239    }
240    if let Some(FnArg::Typed(argument)) = function.sig.inputs.first()
241        && let Type::Path(path) = argument.ty.as_ref()
242    {
243        return Ok(segments(&path.path));
244    }
245    Err(
246        "a listener takes the event it hears as its first argument: `event: OrderPlaced`"
247            .to_owned(),
248    )
249}
250
251#[must_use]
252pub fn interval_seconds(text: &str) -> Option<u64> {
253    let unit_at = text.len().checked_sub(1)?;
254    let (count, unit) = text.split_at_checked(unit_at)?;
255    let scale = match unit {
256        "s" => 1,
257        "m" => 60,
258        "h" => 60 * 60,
259        "d" => 24 * 60 * 60,
260        _ => return None,
261    };
262    if !count.bytes().all(|byte| byte.is_ascii_digit()) {
263        return None;
264    }
265    count
266        .parse::<u64>()
267        .ok()
268        .filter(|count| *count > 0)
269        .and_then(|count| count.checked_mul(scale))
270}
271
272#[cfg(test)]
273mod tests {
274    #[test]
275    fn the_contract_s_generated_file_is_not_hand_written() {
276        assert!(super::is_contract_gen(std::path::Path::new(
277            "shop/modules/order/contract/src/gen/mod.rs"
278        )));
279        assert!(!super::is_contract_gen(std::path::Path::new(
280            "shop/modules/order/contract/src/area.rs"
281        )));
282    }
283
284    use super::interval_seconds;
285
286    #[test]
287    fn reads_whole_numbers_of_one_unit() {
288        assert_eq!(interval_seconds("30s"), Some(30));
289        assert_eq!(interval_seconds("15m"), Some(900));
290        assert_eq!(interval_seconds("1h"), Some(3600));
291        assert_eq!(interval_seconds("2d"), Some(172_800));
292    }
293
294    #[test]
295    fn refuses_anything_else() {
296        for text in [
297            "",
298            "h",
299            "0h",
300            "-1h",
301            "+1h",
302            "1.5h",
303            "1w",
304            "1 h",
305            "1H",
306            "99999999999999999999d",
307        ] {
308            assert_eq!(interval_seconds(text), None, "{text}");
309        }
310    }
311}