Skip to main content

forge_core/function/
traits.rs

1use std::future::Future;
2use std::pin::Pin;
3
4use serde::{Serialize, de::DeserializeOwned};
5
6use super::context::{MutationContext, QueryContext};
7use crate::error::Result;
8
9/// Information about a registered function.
10#[derive(Debug, Clone)]
11pub struct FunctionInfo {
12    /// Function name (used for routing).
13    pub name: &'static str,
14    /// Human-readable description.
15    pub description: Option<&'static str>,
16    /// Kind of function.
17    pub kind: FunctionKind,
18    /// Required role (if any, implies auth required).
19    pub required_role: Option<&'static str>,
20    /// Whether this function is public (no auth).
21    pub is_public: bool,
22    /// Cache TTL in seconds (for queries).
23    pub cache_ttl: Option<u64>,
24    /// Timeout in seconds.
25    pub timeout: Option<u64>,
26    /// Rate limit: requests per time window.
27    pub rate_limit_requests: Option<u32>,
28    /// Rate limit: time window in seconds.
29    pub rate_limit_per_secs: Option<u64>,
30    /// Rate limit: bucket key type (user, ip, tenant, global).
31    pub rate_limit_key: Option<&'static str>,
32    /// Log level for access logging: "trace", "debug", "info", "warn", "error", "off".
33    /// Defaults to "trace" if not specified.
34    pub log_level: Option<&'static str>,
35    /// Table dependencies extracted at compile time for reactive subscriptions.
36    /// Empty slice means tables could not be determined (dynamic SQL).
37    pub table_dependencies: &'static [&'static str],
38    /// Whether this mutation should be wrapped in a database transaction.
39    /// Only applies to mutations. When true, jobs are buffered and inserted
40    /// atomically with the mutation via the outbox pattern.
41    pub transactional: bool,
42}
43
44/// The kind of function.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum FunctionKind {
47    Query,
48    Mutation,
49}
50
51impl std::fmt::Display for FunctionKind {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match self {
54            FunctionKind::Query => write!(f, "query"),
55            FunctionKind::Mutation => write!(f, "mutation"),
56        }
57    }
58}
59
60/// A query function (read-only, cacheable, subscribable).
61///
62/// Queries:
63/// - Can only read from the database
64/// - Are automatically cached based on arguments
65/// - Can be subscribed to for real-time updates
66/// - Should be deterministic (same inputs → same outputs)
67/// - Should not have side effects
68pub trait ForgeQuery: Send + Sync + 'static {
69    /// The input arguments type.
70    type Args: DeserializeOwned + Serialize + Send + Sync;
71    /// The output type.
72    type Output: Serialize + Send;
73
74    /// Function metadata.
75    fn info() -> FunctionInfo;
76
77    /// Execute the query.
78    fn execute(
79        ctx: &QueryContext,
80        args: Self::Args,
81    ) -> Pin<Box<dyn Future<Output = Result<Self::Output>> + Send + '_>>;
82}
83
84/// A mutation function (transactional write).
85///
86/// Mutations:
87/// - Run within a database transaction
88/// - Can read and write to the database
89/// - Should NOT call external APIs (use Actions)
90/// - Are atomic: all changes commit or none do
91pub trait ForgeMutation: Send + Sync + 'static {
92    /// The input arguments type.
93    type Args: DeserializeOwned + Serialize + Send + Sync;
94    /// The output type.
95    type Output: Serialize + Send;
96
97    /// Function metadata.
98    fn info() -> FunctionInfo;
99
100    /// Execute the mutation within a transaction.
101    fn execute(
102        ctx: &MutationContext,
103        args: Self::Args,
104    ) -> Pin<Box<dyn Future<Output = Result<Self::Output>> + Send + '_>>;
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[test]
112    fn test_function_kind_display() {
113        assert_eq!(format!("{}", FunctionKind::Query), "query");
114        assert_eq!(format!("{}", FunctionKind::Mutation), "mutation");
115    }
116
117    #[test]
118    fn test_function_info() {
119        let info = FunctionInfo {
120            name: "get_user",
121            description: Some("Get a user by ID"),
122            kind: FunctionKind::Query,
123            required_role: None,
124            is_public: false,
125            cache_ttl: Some(300),
126            timeout: Some(30),
127            rate_limit_requests: Some(100),
128            rate_limit_per_secs: Some(60),
129            rate_limit_key: Some("user"),
130            log_level: Some("debug"),
131            table_dependencies: &["users"],
132            transactional: false,
133        };
134
135        assert_eq!(info.name, "get_user");
136        assert_eq!(info.kind, FunctionKind::Query);
137        assert_eq!(info.cache_ttl, Some(300));
138        assert_eq!(info.rate_limit_requests, Some(100));
139        assert_eq!(info.log_level, Some("debug"));
140        assert_eq!(info.table_dependencies, &["users"]);
141    }
142}