icepick 0.4.1

Experimental Rust client for Apache Iceberg with WASM support for AWS S3 Tables and Cloudflare R2
Documentation
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Snapshot commands for listing and cleanup

use crate::cli::catalog::CatalogConfig;
use crate::cli::output::{format_number, print, OutputFormat, Outputable};
use crate::cli::util::parse_table_ident;
use crate::snapshot_cleanup::{
    plan_snapshot_cleanup, CleanupOptions, CleanupPlan, RetentionReason,
};
use chrono::{TimeZone, Utc};
use clap::Subcommand;
use comfy_table::{Row, Table as ComfyTable};
use serde::Serialize;

/// Snapshot commands
#[derive(Debug, Subcommand)]
pub enum SnapshotCommand {
    /// List snapshots in a table
    List {
        /// Table identifier (namespace.table)
        table: String,
    },

    /// Cleanup old snapshots based on retention policy
    Cleanup {
        /// Table identifier (namespace.table)
        table: String,

        /// Minimum age in days before a snapshot can be expired
        #[arg(long, default_value = "7")]
        older_than_days: u32,

        /// Minimum number of snapshots to always retain (most recent)
        #[arg(long, default_value = "10")]
        retain_last: usize,

        /// Show plan without executing
        #[arg(long)]
        dry_run: bool,
    },
}

/// Snapshot list output
#[derive(Debug, Serialize)]
pub struct SnapshotList {
    pub table: String,
    pub snapshots: Vec<SnapshotEntry>,
    pub total_count: usize,
    pub current_snapshot_id: Option<i64>,
}

#[derive(Debug, Serialize)]
pub struct SnapshotEntry {
    pub snapshot_id: i64,
    pub timestamp: String,
    pub age_days: f64,
    pub operation: String,
    pub is_current: bool,
    pub refs: Vec<String>,
}

impl Outputable for SnapshotList {
    fn to_text(&self) -> String {
        if self.snapshots.is_empty() {
            return format!("No snapshots found in table '{}'.", self.table);
        }

        let mut lines = vec![format!("Snapshots in '{}':", self.table), String::new()];

        let mut table = ComfyTable::new();
        table.set_header(Row::from(vec![
            "Snapshot ID",
            "Timestamp",
            "Age",
            "Operation",
            "Current",
            "Refs",
        ]));

        for snapshot in &self.snapshots {
            table.add_row(Row::from(vec![
                snapshot.snapshot_id.to_string(),
                snapshot.timestamp.clone(),
                format_age(snapshot.age_days),
                snapshot.operation.clone(),
                if snapshot.is_current { "yes" } else { "" }.to_string(),
                snapshot.refs.join(", "),
            ]));
        }
        lines.push(table.to_string());

        lines.push(String::new());
        lines.push(format!("Total: {} snapshots", self.total_count));

        lines.join("\n")
    }
}

/// Cleanup plan output
#[derive(Debug, Serialize)]
pub struct CleanupPlanOutput {
    pub table: String,
    pub older_than_days: u32,
    pub retain_last: usize,
    pub total_snapshots: usize,
    pub snapshots_to_remove: Vec<SnapshotToRemove>,
    pub snapshots_to_retain: Vec<SnapshotToRetain>,
    pub dry_run: bool,
}

#[derive(Debug, Serialize)]
pub struct SnapshotToRemove {
    pub snapshot_id: i64,
    pub timestamp: String,
    pub age_days: f64,
    pub operation: String,
}

#[derive(Debug, Serialize)]
pub struct SnapshotToRetain {
    pub snapshot_id: i64,
    pub timestamp: String,
    pub age_days: f64,
    pub reason: String,
}

impl Outputable for CleanupPlanOutput {
    fn to_text(&self) -> String {
        let mut lines = vec![
            format!("Snapshot Cleanup Plan for {}", self.table),
            String::new(),
            format!("Policy:"),
            format!("  Older than:  {} days", self.older_than_days),
            format!("  Retain last: {} snapshots", self.retain_last),
            String::new(),
        ];

        if self.snapshots_to_remove.is_empty() {
            lines.push("No snapshots eligible for removal.".to_string());
        } else {
            lines.push(format!(
                "Snapshots to remove ({}):",
                self.snapshots_to_remove.len()
            ));

            let mut table = ComfyTable::new();
            table.set_header(Row::from(vec![
                "Snapshot ID",
                "Timestamp",
                "Age",
                "Operation",
            ]));

            for snapshot in &self.snapshots_to_remove {
                table.add_row(Row::from(vec![
                    snapshot.snapshot_id.to_string(),
                    snapshot.timestamp.clone(),
                    format!("{:.1}d", snapshot.age_days),
                    snapshot.operation.clone(),
                ]));
            }
            lines.push(table.to_string());
        }

        lines.push(String::new());
        lines.push(format!(
            "Snapshots to retain ({}):",
            self.snapshots_to_retain.len()
        ));

        if !self.snapshots_to_retain.is_empty() {
            let mut retain_table = ComfyTable::new();
            retain_table.set_header(Row::from(vec!["Snapshot ID", "Timestamp", "Age", "Reason"]));

            for snapshot in &self.snapshots_to_retain {
                retain_table.add_row(Row::from(vec![
                    snapshot.snapshot_id.to_string(),
                    snapshot.timestamp.clone(),
                    format_age(snapshot.age_days),
                    snapshot.reason.clone(),
                ]));
            }
            lines.push(retain_table.to_string());
        }

        lines.push(String::new());
        lines.push("Summary".to_string());
        lines.push(format!(
            "  Total:   {} snapshots",
            format_number(self.total_snapshots as u64)
        ));
        lines.push(format!(
            "  Remove:  {} snapshots",
            format_number(self.snapshots_to_remove.len() as u64)
        ));
        lines.push(format!(
            "  Retain:  {} snapshots",
            format_number(self.snapshots_to_retain.len() as u64)
        ));

        if self.dry_run && !self.snapshots_to_remove.is_empty() {
            lines.push(String::new());
            lines.push("Dry run complete. Remove --dry-run to execute.".to_string());
        }

        lines.join("\n")
    }
}

/// Cleanup result output
#[derive(Debug, Serialize)]
pub struct CleanupResultOutput {
    pub table: String,
    pub snapshots_removed: usize,
    pub snapshots_retained: usize,
    pub removed_snapshot_ids: Vec<i64>,
}

impl Outputable for CleanupResultOutput {
    fn to_text(&self) -> String {
        let mut lines = vec![format!("Snapshot Cleanup Complete for {}", self.table)];

        lines.push(String::new());
        lines.push(format!(
            "Removed:  {} snapshots",
            format_number(self.snapshots_removed as u64)
        ));
        lines.push(format!(
            "Retained: {} snapshots",
            format_number(self.snapshots_retained as u64)
        ));

        if !self.removed_snapshot_ids.is_empty() && self.removed_snapshot_ids.len() <= 10 {
            lines.push(String::new());
            lines.push("Removed snapshot IDs:".to_string());
            for id in &self.removed_snapshot_ids {
                lines.push(format!("  {}", id));
            }
        }

        lines.join("\n")
    }
}

fn format_timestamp(timestamp_ms: i64) -> String {
    Utc.timestamp_millis_opt(timestamp_ms)
        .single()
        .map(|dt| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
        .unwrap_or_else(|| "Invalid timestamp".to_string())
}

fn format_age(age_days: f64) -> String {
    if age_days < 1.0 {
        format!("{:.1}h", age_days * 24.0)
    } else {
        format!("{:.1}d", age_days)
    }
}

fn format_retention_reason(reason: &RetentionReason) -> String {
    match reason {
        RetentionReason::CurrentSnapshot => "Current snapshot".to_string(),
        RetentionReason::WithinRetainCount => "Within retain-last count".to_string(),
        RetentionReason::NotOldEnough => "Not old enough".to_string(),
        RetentionReason::ReferencedByRef(refs) => format!("Referenced by: {}", refs),
    }
}

fn build_cleanup_plan_output(table: &str, plan: &CleanupPlan, dry_run: bool) -> CleanupPlanOutput {
    let snapshots_to_remove: Vec<SnapshotToRemove> = plan
        .snapshots_to_remove
        .iter()
        .map(|s| SnapshotToRemove {
            snapshot_id: s.snapshot_id,
            timestamp: format_timestamp(s.timestamp_ms),
            age_days: s.age_days,
            operation: s.operation.clone(),
        })
        .collect();

    let snapshots_to_retain: Vec<SnapshotToRetain> = plan
        .snapshots_to_retain
        .iter()
        .map(|s| SnapshotToRetain {
            snapshot_id: s.info.snapshot_id,
            timestamp: format_timestamp(s.info.timestamp_ms),
            age_days: s.info.age_days,
            reason: format_retention_reason(&s.reason),
        })
        .collect();

    CleanupPlanOutput {
        table: table.to_string(),
        older_than_days: plan.older_than_days,
        retain_last: plan.retain_last,
        total_snapshots: plan.total_snapshots,
        snapshots_to_remove,
        snapshots_to_retain,
        dry_run,
    }
}

/// Execute a snapshot command
pub async fn execute(
    command: SnapshotCommand,
    config: &CatalogConfig,
    format: OutputFormat,
) -> Result<(), String> {
    let catalog = config.create_catalog().await?;

    match command {
        SnapshotCommand::List { table: table_str } => {
            let table_ident = parse_table_ident(&table_str)?;
            let table = catalog
                .load_table(&table_ident)
                .await
                .map_err(|e| format!("Failed to load table: {}", e))?;

            let metadata = table.metadata();
            let current_snapshot_id = metadata.current_snapshot_id();

            // Build map of snapshot_id -> ref names
            let mut snapshot_refs: std::collections::HashMap<i64, Vec<String>> =
                std::collections::HashMap::new();
            for (ref_name, snapshot_ref) in metadata.refs() {
                snapshot_refs
                    .entry(snapshot_ref.snapshot_id())
                    .or_default()
                    .push(ref_name.clone());
            }

            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_err(|e| format!("Failed to get current time: {}", e))?
                .as_millis() as i64;

            let mut snapshots: Vec<SnapshotEntry> = metadata
                .snapshots()
                .iter()
                .map(|s| {
                    let age_ms = now_ms - s.timestamp_ms();
                    let age_days = age_ms as f64 / (24.0 * 60.0 * 60.0 * 1000.0);

                    SnapshotEntry {
                        snapshot_id: s.snapshot_id(),
                        timestamp: format_timestamp(s.timestamp_ms()),
                        age_days,
                        operation: s.summary().operation().to_string(),
                        is_current: current_snapshot_id == Some(s.snapshot_id()),
                        refs: snapshot_refs
                            .get(&s.snapshot_id())
                            .cloned()
                            .unwrap_or_default(),
                    }
                })
                .collect();

            // Sort by timestamp descending (newest first)
            snapshots.sort_by(|a, b| b.snapshot_id.cmp(&a.snapshot_id));

            let result = SnapshotList {
                table: table_str,
                total_count: snapshots.len(),
                current_snapshot_id,
                snapshots,
            };

            print(&result, format);
            Ok(())
        }

        SnapshotCommand::Cleanup {
            table: table_str,
            older_than_days,
            retain_last,
            dry_run,
        } => {
            let table_ident = parse_table_ident(&table_str)?;
            let table = catalog
                .load_table(&table_ident)
                .await
                .map_err(|e| format!("Failed to load table: {}", e))?;

            // Build cleanup options
            let options = CleanupOptions::new()
                .with_older_than_days(older_than_days)
                .with_retain_last(retain_last);

            // Create cleanup plan
            let plan = plan_snapshot_cleanup(&table, &options)
                .map_err(|e| format!("Failed to create cleanup plan: {}", e))?;

            if plan.is_empty() {
                println!("No snapshots eligible for cleanup.");
                return Ok(());
            }

            if dry_run {
                // Output plan
                let plan_output = build_cleanup_plan_output(&table_str, &plan, true);
                print(&plan_output, format);
                return Ok(());
            }

            // Show plan first
            let plan_output = build_cleanup_plan_output(&table_str, &plan, false);
            print(&plan_output, format);

            println!("\nExecuting cleanup...");

            // Execute cleanup
            let snapshot_ids: Vec<i64> = plan
                .snapshots_to_remove
                .iter()
                .map(|s| s.snapshot_id)
                .collect();

            catalog
                .expire_snapshots(&table_ident, &snapshot_ids)
                .await
                .map_err(|e| format!("Cleanup failed: {}", e))?;

            let result = CleanupResultOutput {
                table: table_str,
                snapshots_removed: plan.snapshots_to_remove.len(),
                snapshots_retained: plan.snapshots_to_retain.len(),
                removed_snapshot_ids: snapshot_ids,
            };

            print(&result, format);
            Ok(())
        }
    }
}