systemprompt-sync 0.1.18

Sync services for systemprompt.io - file, database, and crate deployment synchronization
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
434
use flate2::Compression;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use tar::{Archive, Builder};
use zip::ZipWriter;
use zip::write::SimpleFileOptions;

use crate::api_client::SyncApiClient;
use crate::error::SyncResult;
use crate::{SyncConfig, SyncDirection, SyncOperationResult};

const INCLUDE_DIRS: [&str; 8] = [
    "agents", "skills", "content", "web", "config", "profiles", "plugins", "hooks",
];

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileBundle {
    pub manifest: FileManifest,
    #[serde(skip)]
    pub data: Vec<u8>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileManifest {
    pub files: Vec<FileEntry>,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub checksum: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileEntry {
    pub path: String,
    pub checksum: String,
    pub size: u64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum FileDiffStatus {
    Added,
    Modified,
    Deleted,
    Unchanged,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SyncDiffEntry {
    pub path: String,
    pub status: FileDiffStatus,
    pub size: u64,
}

#[derive(Debug)]
pub struct SyncDiffResult {
    pub entries: Vec<SyncDiffEntry>,
    pub added: usize,
    pub modified: usize,
    pub deleted: usize,
    pub unchanged: usize,
}

impl SyncDiffResult {
    pub const fn has_changes(&self) -> bool {
        self.added > 0 || self.modified > 0 || self.deleted > 0
    }

    pub fn changed_paths(&self) -> Vec<String> {
        self.entries
            .iter()
            .filter(|e| e.status != FileDiffStatus::Unchanged)
            .map(|e| e.path.clone())
            .collect()
    }
}

#[derive(Debug)]
pub struct PullDownload {
    pub data: Vec<u8>,
    pub diff: SyncDiffResult,
}

#[derive(Debug)]
pub struct FileSyncService {
    config: SyncConfig,
    api_client: SyncApiClient,
}

impl FileSyncService {
    pub const fn new(config: SyncConfig, api_client: SyncApiClient) -> Self {
        Self { config, api_client }
    }

    pub async fn sync(&self) -> SyncResult<SyncOperationResult> {
        match self.config.direction {
            SyncDirection::Push => self.push().await,
            SyncDirection::Pull => self.pull().await,
        }
    }

    pub async fn download_and_diff(&self) -> SyncResult<PullDownload> {
        let services_path = PathBuf::from(&self.config.services_path);
        let data = self
            .api_client
            .download_files(&self.config.tenant_id)
            .await?;

        let diff = Self::compare_tarball_with_local(&data, &services_path)?;

        Ok(PullDownload { data, diff })
    }

    pub fn backup_services(services_path: &Path) -> SyncResult<PathBuf> {
        let project_root = services_path.parent().unwrap_or(services_path);
        let backup_dir = project_root.join("backup");
        fs::create_dir_all(&backup_dir)?;

        let timestamp = chrono::Utc::now().format("%Y%m%d-%H%M%S");
        let zip_path = backup_dir.join(format!("{timestamp}.zip"));

        let file = fs::File::create(&zip_path)?;
        let mut zip = ZipWriter::new(file);
        let options =
            SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);

        for dir in INCLUDE_DIRS {
            let dir_path = services_path.join(dir);
            if dir_path.exists() {
                Self::add_dir_to_zip(&mut zip, &dir_path, services_path, options)?;
            }
        }

        zip.finish()?;
        Ok(zip_path)
    }

    pub fn apply(data: &[u8], services_path: &Path, paths: Option<&[String]>) -> SyncResult<usize> {
        paths.map_or_else(
            || Self::extract_tarball(data, services_path),
            |paths| Self::extract_tarball_selective(data, services_path, paths),
        )
    }

    async fn push(&self) -> SyncResult<SyncOperationResult> {
        let services_path = PathBuf::from(&self.config.services_path);
        let bundle = Self::collect_files(&services_path)?;
        let file_count = bundle.manifest.files.len();

        if self.config.dry_run {
            return Ok(SyncOperationResult::dry_run(
                "files_push",
                file_count,
                serde_json::to_value(&bundle.manifest)?,
            ));
        }

        let data = Self::create_tarball(&services_path, &bundle.manifest)?;

        let upload = self
            .api_client
            .upload_files(&self.config.tenant_id, data)
            .await?;

        Ok(SyncOperationResult::success(
            "files_push",
            upload.files_uploaded,
        ))
    }

    async fn pull(&self) -> SyncResult<SyncOperationResult> {
        let services_path = PathBuf::from(&self.config.services_path);
        let data = self
            .api_client
            .download_files(&self.config.tenant_id)
            .await?;

        if self.config.dry_run {
            let manifest = Self::peek_manifest(&data)?;
            return Ok(SyncOperationResult::dry_run(
                "files_pull",
                manifest.files.len(),
                serde_json::to_value(&manifest)?,
            ));
        }

        let count = Self::extract_tarball(&data, &services_path)?;
        Ok(SyncOperationResult::success("files_pull", count))
    }

    fn collect_files(services_path: &Path) -> SyncResult<FileBundle> {
        let mut files = vec![];

        for dir in INCLUDE_DIRS {
            let dir_path = services_path.join(dir);
            if dir_path.exists() {
                Self::collect_dir(&dir_path, services_path, &mut files)?;
            }
        }

        let mut hasher = Sha256::new();
        for file_entry in &files {
            hasher.update(&file_entry.checksum);
        }
        let checksum = format!("{:x}", hasher.finalize());

        Ok(FileBundle {
            manifest: FileManifest {
                files,
                timestamp: chrono::Utc::now(),
                checksum,
            },
            data: vec![],
        })
    }

    fn collect_dir(dir: &Path, base: &Path, files: &mut Vec<FileEntry>) -> SyncResult<()> {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_dir() {
                Self::collect_dir(&path, base, files)?;
            } else if path.is_file() {
                let relative = path.strip_prefix(base)?;
                let content = fs::read(&path)?;
                let checksum = format!("{:x}", Sha256::digest(&content));

                files.push(FileEntry {
                    path: relative.to_string_lossy().to_string(),
                    checksum,
                    size: content.len() as u64,
                });
            }
        }
        Ok(())
    }

    fn create_tarball(base: &Path, manifest: &FileManifest) -> SyncResult<Vec<u8>> {
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        {
            let mut tar = Builder::new(&mut encoder);
            for file in &manifest.files {
                let full_path = base.join(&file.path);
                tar.append_path_with_name(&full_path, &file.path)?;
            }
            tar.finish()?;
        }
        Ok(encoder.finish()?)
    }

    fn extract_tarball(data: &[u8], target: &Path) -> SyncResult<usize> {
        let decoder = GzDecoder::new(data);
        let mut archive = Archive::new(decoder);
        let mut count = 0;

        for entry in archive.entries()? {
            let mut entry = entry?;
            let path = target.join(entry.path()?);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent)?;
            }
            entry.unpack(&path)?;
            count += 1;
        }

        Ok(count)
    }

    fn extract_tarball_selective(
        data: &[u8],
        target: &Path,
        paths_to_sync: &[String],
    ) -> SyncResult<usize> {
        let allowed: std::collections::HashSet<&str> =
            paths_to_sync.iter().map(String::as_str).collect();

        let decoder = GzDecoder::new(data);
        let mut archive = Archive::new(decoder);
        let mut count = 0;

        for entry in archive.entries()? {
            let mut entry = entry?;
            let entry_path = entry.path()?.to_string_lossy().to_string();

            if !allowed.contains(entry_path.as_str()) {
                continue;
            }

            let path = target.join(&entry_path);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent)?;
            }
            entry.unpack(&path)?;
            count += 1;
        }

        Ok(count)
    }

    fn compare_tarball_with_local(data: &[u8], services_path: &Path) -> SyncResult<SyncDiffResult> {
        let temp_dir = tempfile::tempdir()?;
        Self::extract_tarball(data, temp_dir.path())?;

        let mut remote_files: HashMap<String, (String, u64)> = HashMap::new();
        for dir in INCLUDE_DIRS {
            let dir_path = temp_dir.path().join(dir);
            if dir_path.exists() {
                let mut entries = vec![];
                Self::collect_dir(&dir_path, temp_dir.path(), &mut entries)?;
                for entry in entries {
                    remote_files.insert(entry.path, (entry.checksum, entry.size));
                }
            }
        }

        let mut local_files: HashMap<String, String> = HashMap::new();
        for dir in INCLUDE_DIRS {
            let dir_path = services_path.join(dir);
            if dir_path.exists() {
                let mut entries = vec![];
                Self::collect_dir(&dir_path, services_path, &mut entries)?;
                for entry in entries {
                    local_files.insert(entry.path, entry.checksum);
                }
            }
        }

        let mut entries = Vec::new();
        let mut added = 0;
        let mut modified = 0;
        let mut unchanged = 0;

        for (path, (remote_checksum, size)) in &remote_files {
            match local_files.get(path) {
                Some(local_checksum) if local_checksum == remote_checksum => {
                    unchanged += 1;
                    entries.push(SyncDiffEntry {
                        path: path.clone(),
                        status: FileDiffStatus::Unchanged,
                        size: *size,
                    });
                },
                Some(_) => {
                    modified += 1;
                    entries.push(SyncDiffEntry {
                        path: path.clone(),
                        status: FileDiffStatus::Modified,
                        size: *size,
                    });
                },
                None => {
                    added += 1;
                    entries.push(SyncDiffEntry {
                        path: path.clone(),
                        status: FileDiffStatus::Added,
                        size: *size,
                    });
                },
            }
        }

        let mut deleted = 0;
        for path in local_files.keys() {
            if !remote_files.contains_key(path) {
                deleted += 1;
                entries.push(SyncDiffEntry {
                    path: path.clone(),
                    status: FileDiffStatus::Deleted,
                    size: 0,
                });
            }
        }

        entries.sort_by(|a, b| a.path.cmp(&b.path));

        Ok(SyncDiffResult {
            entries,
            added,
            modified,
            deleted,
            unchanged,
        })
    }

    fn peek_manifest(data: &[u8]) -> SyncResult<FileManifest> {
        let decoder = GzDecoder::new(data);
        let mut archive = Archive::new(decoder);
        let mut files = vec![];

        for entry in archive.entries()? {
            let entry = entry?;
            files.push(FileEntry {
                path: entry.path()?.to_string_lossy().to_string(),
                checksum: String::new(),
                size: entry.size(),
            });
        }

        Ok(FileManifest {
            files,
            timestamp: chrono::Utc::now(),
            checksum: String::new(),
        })
    }

    fn add_dir_to_zip<W: Write + std::io::Seek>(
        zip: &mut ZipWriter<W>,
        dir: &Path,
        base: &Path,
        options: SimpleFileOptions,
    ) -> SyncResult<()> {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_dir() {
                Self::add_dir_to_zip(zip, &path, base, options)?;
            } else if path.is_file() {
                let relative = path.strip_prefix(base)?;
                let name = relative.to_string_lossy().to_string();
                zip.start_file(&name, options)?;
                let mut file = fs::File::open(&path)?;
                let mut buf = Vec::new();
                file.read_to_end(&mut buf)?;
                zip.write_all(&buf)?;
            }
        }
        Ok(())
    }
}