1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//! Time-based data evolution
//!
//! This module handles data aging rules, automatic cleanup of expired data,
//! and time-based field updates.
use crate::Result;
use mockforge_core::VirtualClock;
use std::sync::Arc;
/// Data aging rule
#[derive(Debug, Clone)]
pub struct AgingRule {
/// Entity name
pub entity_name: String,
/// Field to check for expiration
pub expiration_field: String,
/// Expiration duration in seconds
pub expiration_duration: u64,
/// Action to take when expired
pub action: AgingAction,
}
/// Action to take when data expires
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgingAction {
/// Delete the record
Delete,
/// Mark as expired (set a flag)
MarkExpired,
/// Archive (move to archive table)
Archive,
}
/// Data aging manager
pub struct AgingManager {
/// Aging rules
rules: Vec<AgingRule>,
/// Virtual clock for time travel (optional)
virtual_clock: Option<Arc<VirtualClock>>,
}
impl AgingManager {
/// Create a new aging manager
pub fn new() -> Self {
Self {
rules: Vec::new(),
virtual_clock: None,
}
}
/// Create a new aging manager with virtual clock
pub fn with_virtual_clock(clock: Arc<VirtualClock>) -> Self {
Self {
rules: Vec::new(),
virtual_clock: Some(clock),
}
}
/// Set the virtual clock
pub fn set_virtual_clock(&mut self, clock: Option<Arc<VirtualClock>>) {
self.virtual_clock = clock;
}
/// Get the current time (virtual or real)
fn now(&self) -> chrono::DateTime<chrono::Utc> {
if let Some(ref clock) = self.virtual_clock {
clock.now()
} else {
chrono::Utc::now()
}
}
/// Add an aging rule
pub fn add_rule(&mut self, rule: AgingRule) {
self.rules.push(rule);
}
/// Clean up expired data
///
/// Checks all aging rules and applies the configured action to expired records.
pub async fn cleanup_expired(
&self,
database: &dyn crate::database::VirtualDatabase,
registry: &crate::entities::EntityRegistry,
) -> Result<usize> {
let mut total_cleaned = 0;
for rule in &self.rules {
// Get entity info
let entity = match registry.get(&rule.entity_name) {
Some(e) => e,
None => continue, // Entity not found, skip this rule
};
let table_name = entity.table_name();
let now = self.now();
// Query all records for this entity
let query = format!("SELECT * FROM {}", table_name);
let records = database.query(&query, &[]).await?;
for record in records {
// Check expiration field
if let Some(expiration_value) = record.get(&rule.expiration_field) {
// Parse timestamp
let expiration_time = match expiration_value {
serde_json::Value::String(s) => {
// Try parsing as ISO8601 timestamp
match chrono::DateTime::parse_from_rfc3339(s) {
Ok(dt) => dt.with_timezone(&chrono::Utc),
Err(_) => continue, // Invalid timestamp, skip
}
}
serde_json::Value::Number(n) => {
// Unix timestamp
if let Some(ts) = n.as_i64() {
chrono::DateTime::from_timestamp(ts, 0)
.unwrap_or_else(|| self.now())
} else {
continue; // Invalid timestamp
}
}
_ => continue, // Not a timestamp field
};
// Check if expired
let age = now.signed_duration_since(expiration_time);
if age.num_seconds() > rule.expiration_duration as i64 {
// Apply action
match rule.action {
AgingAction::Delete => {
// Get primary key value
let pk_field = entity
.schema
.primary_key
.first()
.map(|s| s.as_str())
.unwrap_or("id");
if let Some(pk_value) = record.get(pk_field) {
let delete_query = format!(
"DELETE FROM {} WHERE {} = ?",
table_name, pk_field
);
database
.execute(&delete_query, std::slice::from_ref(pk_value))
.await?;
total_cleaned += 1;
}
}
AgingAction::MarkExpired => {
// Update status field
let pk_field = entity
.schema
.primary_key
.first()
.map(|s| s.as_str())
.unwrap_or("id");
if let Some(pk_value) = record.get(pk_field) {
let update_query = format!(
"UPDATE {} SET status = ? WHERE {} = ?",
table_name, pk_field
);
database
.execute(
&update_query,
&[
serde_json::Value::String("expired".to_string()),
pk_value.clone(),
],
)
.await?;
total_cleaned += 1;
}
}
AgingAction::Archive => {
// For now, just mark as archived (full archive would require archive table)
let pk_field = entity
.schema
.primary_key
.first()
.map(|s| s.as_str())
.unwrap_or("id");
if let Some(pk_value) = record.get(pk_field) {
let update_query = format!(
"UPDATE {} SET archived = ? WHERE {} = ?",
table_name, pk_field
);
database
.execute(
&update_query,
&[serde_json::Value::Bool(true), pk_value.clone()],
)
.await?;
total_cleaned += 1;
}
}
}
}
}
}
}
Ok(total_cleaned)
}
/// Update timestamp fields
///
/// Automatically updates `updated_at` fields when `auto_update_timestamps` is enabled.
pub async fn update_timestamps(
&self,
database: &dyn crate::database::VirtualDatabase,
table: &str,
primary_key_field: &str,
primary_key_value: &serde_json::Value,
) -> Result<()> {
// Update updated_at field if it exists
let now = self.now().to_rfc3339();
let update_query =
format!("UPDATE {} SET updated_at = ? WHERE {} = ?", table, primary_key_field);
// Try to update, but ignore if column doesn't exist
let _ = database
.execute(&update_query, &[serde_json::Value::String(now), primary_key_value.clone()])
.await;
Ok(())
}
}
impl Default for AgingManager {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use mockforge_core::VirtualClock;
use std::sync::Arc;
#[test]
fn test_aging_with_virtual_clock() {
// Create aging manager with virtual clock
let clock = Arc::new(VirtualClock::new());
let initial_time = chrono::Utc::now();
clock.enable_and_set(initial_time);
let aging_manager = AgingManager::with_virtual_clock(clock.clone());
// Verify that aging manager uses virtual clock
let now = aging_manager.now();
assert!((now - initial_time).num_seconds().abs() < 1);
// Advance virtual clock by 2 hours
clock.advance(chrono::Duration::hours(2));
// Verify aging manager now sees the advanced time
let advanced_now = aging_manager.now();
let elapsed = advanced_now - initial_time;
assert!(elapsed.num_hours() >= 1 && elapsed.num_hours() <= 3);
}
#[test]
fn test_aging_timestamps_with_virtual_clock() {
let clock = Arc::new(VirtualClock::new());
let initial_time = chrono::Utc::now();
clock.enable_and_set(initial_time);
let aging_manager = AgingManager::with_virtual_clock(clock.clone());
// Advance time by 1 month
clock.advance(chrono::Duration::days(30));
// Update timestamps should use virtual clock
// This is tested indirectly through the now() method
let now = aging_manager.now();
let elapsed = now - initial_time;
assert!(elapsed.num_days() >= 29 && elapsed.num_days() <= 31);
}
#[test]
fn test_one_month_aging_scenario() {
// Simulate "1 month later" scenario with data aging
let clock = Arc::new(VirtualClock::new());
let initial_time = chrono::Utc::now();
clock.enable_and_set(initial_time);
let aging_manager = AgingManager::with_virtual_clock(clock.clone());
// Initial time check
let start_time = aging_manager.now();
assert!((start_time - initial_time).num_seconds().abs() < 1);
// Advance by 1 month (30 days)
clock.advance(chrono::Duration::days(30));
// Verify aging manager sees the advanced time
let month_later = aging_manager.now();
let elapsed = month_later - start_time;
// Should be approximately 30 days
assert!(
elapsed.num_days() >= 29 && elapsed.num_days() <= 31,
"Expected ~30 days, got {} days",
elapsed.num_days()
);
}
}