1use ironflow_store::models::{Run, RunActor, TriggerKind};
4use serde::{Deserialize, Serialize};
5use uuid::Uuid;
6
7const ID_PREFIX_LEN: usize = 8;
9
10#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum CreatedByKind {
15 User,
17 ApiKey,
19 System,
21}
22
23#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct CreatedBy {
46 pub kind: CreatedByKind,
48 pub id: Option<Uuid>,
51 pub label: String,
56}
57
58fn short_id(id: Uuid) -> String {
60 let text = id.to_string();
61 text[..ID_PREFIX_LEN.min(text.len())].to_string()
62}
63
64fn trigger_label(trigger: &TriggerKind) -> String {
66 match trigger {
67 TriggerKind::Manual => "manual".to_string(),
68 TriggerKind::Api => "api".to_string(),
69 TriggerKind::Workflow => "workflow".to_string(),
70 TriggerKind::Retry { .. } => "retry".to_string(),
71 TriggerKind::Replay { .. } => "replay".to_string(),
72 TriggerKind::Webhook { path } => path.clone(),
73 TriggerKind::Cron { schedule } => schedule.clone(),
74 TriggerKind::Nats { subject } => format!("nats:{subject}"),
75 TriggerKind::RunEvent { event_kind, .. } => format!("event:{event_kind}"),
76 TriggerKind::Polling { probe } => format!("polling:{probe}"),
77 }
78}
79
80impl From<&Run> for CreatedBy {
81 fn from(run: &Run) -> Self {
82 match run.created_by {
83 None => CreatedBy {
84 kind: CreatedByKind::System,
85 id: None,
86 label: trigger_label(&run.trigger),
87 },
88 Some(RunActor::User { user_id }) => CreatedBy {
89 kind: CreatedByKind::User,
90 id: Some(user_id),
91 label: run
92 .created_by_label
93 .clone()
94 .unwrap_or_else(|| format!("user {}", short_id(user_id))),
95 },
96 Some(RunActor::ApiKey { api_key_id, .. }) => CreatedBy {
97 kind: CreatedByKind::ApiKey,
98 id: Some(api_key_id),
99 label: run
100 .created_by_label
101 .clone()
102 .unwrap_or_else(|| format!("key {}", short_id(api_key_id))),
103 },
104 }
105 }
106}
107
108#[cfg(test)]
109mod tests {
110 use std::collections::HashMap;
111
112 use ironflow_store::api_key_store::ApiKeyStore;
113 use ironflow_store::memory::InMemoryStore;
114 use ironflow_store::models::{ApiKeyScope, NewApiKey, NewRun, NewUser};
115 use ironflow_store::store::RunStore;
116 use ironflow_store::user_store::UserStore;
117 use serde_json::json;
118
119 use super::*;
120
121 async fn run_with(
124 store: &InMemoryStore,
125 trigger: TriggerKind,
126 created_by: Option<RunActor>,
127 ) -> Run {
128 store
129 .create_run(NewRun {
130 workflow_name: "deploy".to_string(),
131 trigger,
132 payload: json!({}),
133 max_retries: 0,
134 handler_version: None,
135 labels: HashMap::new(),
136 scheduled_at: None,
137 created_by,
138 idempotency_key: None,
139 concurrency_key: None,
140 concurrency_limits: Vec::new(),
141 max_cost_usd: None,
142 })
143 .await
144 .expect("create run")
145 .into_run()
146 }
147
148 async fn seed_user(store: &InMemoryStore, username: &str) -> Uuid {
149 store
150 .create_user(NewUser {
151 email: format!("{username}@example.com"),
152 username: username.to_string(),
153 password_hash: "hash".to_string(),
154 is_admin: Some(false),
155 })
156 .await
157 .expect("create user")
158 .id
159 }
160
161 async fn seed_api_key(store: &InMemoryStore, user_id: Uuid, name: &str) -> Uuid {
162 store
163 .create_api_key(NewApiKey {
164 user_id,
165 name: name.to_string(),
166 key_hash: "hash".to_string(),
167 key_prefix: "irfl_0000".to_string(),
168 scopes: vec![ApiKeyScope::RunsWrite],
169 expires_at: None,
170 rate_limit_override: None,
171 })
172 .await
173 .expect("create api key")
174 .id
175 }
176
177 #[tokio::test]
178 async fn user_actor_uses_the_resolved_username() {
179 let store = InMemoryStore::new();
180 let user_id = seed_user(&store, "alice").await;
181 let run = run_with(&store, TriggerKind::Api, Some(RunActor::User { user_id })).await;
182
183 let created_by = CreatedBy::from(&run);
184 assert_eq!(created_by.kind, CreatedByKind::User);
185 assert_eq!(created_by.id, Some(user_id));
186 assert_eq!(created_by.label, "alice");
187 }
188
189 #[tokio::test]
190 async fn user_actor_falls_back_to_a_short_id() {
191 let store = InMemoryStore::new();
192 let user_id = Uuid::now_v7();
193 let run = run_with(&store, TriggerKind::Api, Some(RunActor::User { user_id })).await;
194
195 let created_by = CreatedBy::from(&run);
196 assert_eq!(created_by.kind, CreatedByKind::User);
197 assert_eq!(created_by.id, Some(user_id));
198 assert_eq!(created_by.label, format!("user {}", short_id(user_id)));
199 }
200
201 #[tokio::test]
202 async fn api_key_actor_exposes_the_key_id_and_a_combined_label() {
203 let store = InMemoryStore::new();
204 let user_id = seed_user(&store, "alice").await;
205 let api_key_id = seed_api_key(&store, user_id, "ci-deploy").await;
206 let run = run_with(
207 &store,
208 TriggerKind::Api,
209 Some(RunActor::ApiKey {
210 api_key_id,
211 user_id,
212 }),
213 )
214 .await;
215
216 let created_by = CreatedBy::from(&run);
217 assert_eq!(created_by.kind, CreatedByKind::ApiKey);
218 assert_eq!(created_by.id, Some(api_key_id));
219 assert_eq!(created_by.label, "ci-deploy (alice)");
220 }
221
222 #[tokio::test]
223 async fn api_key_actor_falls_back_to_a_short_id() {
224 let store = InMemoryStore::new();
225 let api_key_id = Uuid::now_v7();
226 let run = run_with(
227 &store,
228 TriggerKind::Api,
229 Some(RunActor::ApiKey {
230 api_key_id,
231 user_id: Uuid::now_v7(),
232 }),
233 )
234 .await;
235
236 let created_by = CreatedBy::from(&run);
237 assert_eq!(created_by.kind, CreatedByKind::ApiKey);
238 assert_eq!(created_by.label, format!("key {}", short_id(api_key_id)));
239 }
240
241 #[tokio::test]
242 async fn system_label_is_derived_from_every_trigger() {
243 let store = InMemoryStore::new();
244 let cases = [
245 (TriggerKind::Manual, "manual"),
246 (TriggerKind::Api, "api"),
247 (TriggerKind::Workflow, "workflow"),
248 (
249 TriggerKind::Retry {
250 parent_run_id: Uuid::now_v7(),
251 },
252 "retry",
253 ),
254 (
255 TriggerKind::Replay {
256 original_run_id: Uuid::now_v7(),
257 },
258 "replay",
259 ),
260 (
261 TriggerKind::Webhook {
262 path: "/hooks/github".to_string(),
263 },
264 "/hooks/github",
265 ),
266 (
267 TriggerKind::Cron {
268 schedule: "0 */5 * * * *".to_string(),
269 },
270 "0 */5 * * * *",
271 ),
272 (
273 TriggerKind::Nats {
274 subject: "orders.created".to_string(),
275 },
276 "nats:orders.created",
277 ),
278 (
279 TriggerKind::RunEvent {
280 source_run_id: Uuid::now_v7(),
281 event_kind: "completed".to_string(),
282 },
283 "event:completed",
284 ),
285 (
286 TriggerKind::Polling {
287 probe: "http".to_string(),
288 },
289 "polling:http",
290 ),
291 ];
292
293 for (trigger, expected) in cases {
294 let run = run_with(&store, trigger, None).await;
295 let created_by = CreatedBy::from(&run);
296
297 assert_eq!(created_by.kind, CreatedByKind::System);
298 assert_eq!(created_by.id, None);
299 assert_eq!(created_by.label, expected);
300 }
301 }
302
303 #[tokio::test]
304 async fn a_pre_migration_run_reports_a_system_author() {
305 let store = InMemoryStore::new();
306 let run = run_with(&store, TriggerKind::Manual, None).await;
308
309 let created_by = CreatedBy::from(&run);
310 assert_eq!(created_by.kind, CreatedByKind::System);
311 assert_eq!(created_by.id, None);
312 assert_eq!(created_by.label, "manual");
313 }
314
315 #[tokio::test]
316 async fn label_is_never_empty() {
317 let store = InMemoryStore::new();
318 let run = run_with(
319 &store,
320 TriggerKind::Webhook {
321 path: "/h".to_string(),
322 },
323 None,
324 )
325 .await;
326
327 assert!(!CreatedBy::from(&run).label.is_empty());
328 }
329
330 #[test]
331 fn short_id_keeps_eight_characters() {
332 let id = Uuid::now_v7();
333 assert_eq!(short_id(id).len(), ID_PREFIX_LEN);
334 assert!(id.to_string().starts_with(&short_id(id)));
335 }
336
337 #[test]
338 fn serde_uses_snake_case_kinds() {
339 let created_by = CreatedBy {
340 kind: CreatedByKind::ApiKey,
341 id: Some(Uuid::now_v7()),
342 label: "ci (alice)".to_string(),
343 };
344
345 let json = serde_json::to_value(&created_by).expect("serialize");
346 assert_eq!(json["kind"], "api_key");
347
348 let back: CreatedBy = serde_json::from_value(json).expect("deserialize");
349 assert_eq!(back, created_by);
350 }
351}