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 max_cost_usd: None,
141 })
142 .await
143 .expect("create run")
144 .into_run()
145 }
146
147 async fn seed_user(store: &InMemoryStore, username: &str) -> Uuid {
148 store
149 .create_user(NewUser {
150 email: format!("{username}@example.com"),
151 username: username.to_string(),
152 password_hash: "hash".to_string(),
153 is_admin: Some(false),
154 })
155 .await
156 .expect("create user")
157 .id
158 }
159
160 async fn seed_api_key(store: &InMemoryStore, user_id: Uuid, name: &str) -> Uuid {
161 store
162 .create_api_key(NewApiKey {
163 user_id,
164 name: name.to_string(),
165 key_hash: "hash".to_string(),
166 key_prefix: "irfl_0000".to_string(),
167 scopes: vec![ApiKeyScope::RunsWrite],
168 expires_at: None,
169 rate_limit_override: None,
170 })
171 .await
172 .expect("create api key")
173 .id
174 }
175
176 #[tokio::test]
177 async fn user_actor_uses_the_resolved_username() {
178 let store = InMemoryStore::new();
179 let user_id = seed_user(&store, "alice").await;
180 let run = run_with(&store, TriggerKind::Api, Some(RunActor::User { user_id })).await;
181
182 let created_by = CreatedBy::from(&run);
183 assert_eq!(created_by.kind, CreatedByKind::User);
184 assert_eq!(created_by.id, Some(user_id));
185 assert_eq!(created_by.label, "alice");
186 }
187
188 #[tokio::test]
189 async fn user_actor_falls_back_to_a_short_id() {
190 let store = InMemoryStore::new();
191 let user_id = Uuid::now_v7();
192 let run = run_with(&store, TriggerKind::Api, Some(RunActor::User { user_id })).await;
193
194 let created_by = CreatedBy::from(&run);
195 assert_eq!(created_by.kind, CreatedByKind::User);
196 assert_eq!(created_by.id, Some(user_id));
197 assert_eq!(created_by.label, format!("user {}", short_id(user_id)));
198 }
199
200 #[tokio::test]
201 async fn api_key_actor_exposes_the_key_id_and_a_combined_label() {
202 let store = InMemoryStore::new();
203 let user_id = seed_user(&store, "alice").await;
204 let api_key_id = seed_api_key(&store, user_id, "ci-deploy").await;
205 let run = run_with(
206 &store,
207 TriggerKind::Api,
208 Some(RunActor::ApiKey {
209 api_key_id,
210 user_id,
211 }),
212 )
213 .await;
214
215 let created_by = CreatedBy::from(&run);
216 assert_eq!(created_by.kind, CreatedByKind::ApiKey);
217 assert_eq!(created_by.id, Some(api_key_id));
218 assert_eq!(created_by.label, "ci-deploy (alice)");
219 }
220
221 #[tokio::test]
222 async fn api_key_actor_falls_back_to_a_short_id() {
223 let store = InMemoryStore::new();
224 let api_key_id = Uuid::now_v7();
225 let run = run_with(
226 &store,
227 TriggerKind::Api,
228 Some(RunActor::ApiKey {
229 api_key_id,
230 user_id: Uuid::now_v7(),
231 }),
232 )
233 .await;
234
235 let created_by = CreatedBy::from(&run);
236 assert_eq!(created_by.kind, CreatedByKind::ApiKey);
237 assert_eq!(created_by.label, format!("key {}", short_id(api_key_id)));
238 }
239
240 #[tokio::test]
241 async fn system_label_is_derived_from_every_trigger() {
242 let store = InMemoryStore::new();
243 let cases = [
244 (TriggerKind::Manual, "manual"),
245 (TriggerKind::Api, "api"),
246 (TriggerKind::Workflow, "workflow"),
247 (
248 TriggerKind::Retry {
249 parent_run_id: Uuid::now_v7(),
250 },
251 "retry",
252 ),
253 (
254 TriggerKind::Replay {
255 original_run_id: Uuid::now_v7(),
256 },
257 "replay",
258 ),
259 (
260 TriggerKind::Webhook {
261 path: "/hooks/github".to_string(),
262 },
263 "/hooks/github",
264 ),
265 (
266 TriggerKind::Cron {
267 schedule: "0 */5 * * * *".to_string(),
268 },
269 "0 */5 * * * *",
270 ),
271 (
272 TriggerKind::Nats {
273 subject: "orders.created".to_string(),
274 },
275 "nats:orders.created",
276 ),
277 (
278 TriggerKind::RunEvent {
279 source_run_id: Uuid::now_v7(),
280 event_kind: "completed".to_string(),
281 },
282 "event:completed",
283 ),
284 (
285 TriggerKind::Polling {
286 probe: "http".to_string(),
287 },
288 "polling:http",
289 ),
290 ];
291
292 for (trigger, expected) in cases {
293 let run = run_with(&store, trigger, None).await;
294 let created_by = CreatedBy::from(&run);
295
296 assert_eq!(created_by.kind, CreatedByKind::System);
297 assert_eq!(created_by.id, None);
298 assert_eq!(created_by.label, expected);
299 }
300 }
301
302 #[tokio::test]
303 async fn a_pre_migration_run_reports_a_system_author() {
304 let store = InMemoryStore::new();
305 let run = run_with(&store, TriggerKind::Manual, None).await;
307
308 let created_by = CreatedBy::from(&run);
309 assert_eq!(created_by.kind, CreatedByKind::System);
310 assert_eq!(created_by.id, None);
311 assert_eq!(created_by.label, "manual");
312 }
313
314 #[tokio::test]
315 async fn label_is_never_empty() {
316 let store = InMemoryStore::new();
317 let run = run_with(
318 &store,
319 TriggerKind::Webhook {
320 path: "/h".to_string(),
321 },
322 None,
323 )
324 .await;
325
326 assert!(!CreatedBy::from(&run).label.is_empty());
327 }
328
329 #[test]
330 fn short_id_keeps_eight_characters() {
331 let id = Uuid::now_v7();
332 assert_eq!(short_id(id).len(), ID_PREFIX_LEN);
333 assert!(id.to_string().starts_with(&short_id(id)));
334 }
335
336 #[test]
337 fn serde_uses_snake_case_kinds() {
338 let created_by = CreatedBy {
339 kind: CreatedByKind::ApiKey,
340 id: Some(Uuid::now_v7()),
341 label: "ci (alice)".to_string(),
342 };
343
344 let json = serde_json::to_value(&created_by).expect("serialize");
345 assert_eq!(json["kind"], "api_key");
346
347 let back: CreatedBy = serde_json::from_value(json).expect("deserialize");
348 assert_eq!(back, created_by);
349 }
350}