Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ public SyncWorker(Task task, CancellationTokenSource cts)
}
}

public class SyncService : BackgroundService
public abstract class BaseSyncService : BackgroundService
{
private readonly ConcurrentDictionary<string, SyncWorker> _vaults = new();
private readonly ILogger<SyncService> _logger;
private readonly TaskQueuer _queuer;
private readonly ILogger<BaseSyncService> _logger;

public SyncService(ILogger<SyncService> logger, TaskQueuer queuer)
protected readonly ConcurrentDictionary<string, SyncWorker> Vaults = new();
protected readonly TaskQueuer _queuer;

public BaseSyncService(ILogger<BaseSyncService> logger, TaskQueuer queuer)
{
_logger = logger;
_queuer = queuer;
Expand All @@ -39,30 +40,30 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
LocalVaultConfig[] enabledVaults = ParallelConfig.GetEnabledVaults();
string[] enabledVaultIds = enabledVaults.Select(v => v.Id).ToArray();
string[] disabledVaults = _vaults.Keys.Where(v => !enabledVaultIds.Contains(v)).ToArray();
string[] disabledVaults = Vaults.Keys.Where(v => !enabledVaultIds.Contains(v)).ToArray();

// Adds newly enabled vaults to be synced.
foreach (LocalVaultConfig vault in enabledVaults)
{
if (_vaults.ContainsKey(vault.Id)) continue;
if (Vaults.ContainsKey(vault.Id)) continue;

_logger.LogDebug("Adding vault to syncing...");
CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
Task workerTask = SyncVaultAsync(new FileSyncManager(vault), cts.Token);
SyncWorker worker = new SyncWorker(workerTask, cts);

if (!_vaults.TryAdd(vault.Id, worker)) continue;
if (!Vaults.TryAdd(vault.Id, worker)) continue;
_logger.LogInformation("Added vault to be synced: {VaultId}", vault.Id);
}

// Removes disabled vaults from being synced
foreach (string id in disabledVaults)
{
_logger.LogDebug("Removing vault from syncing...");
if (!_vaults.TryGetValue(id, out SyncWorker? worker)) continue;
if (!Vaults.TryGetValue(id, out SyncWorker? worker)) continue;
await worker.Cts.CancelAsync();
await worker.WorkerTask;
_vaults.TryRemove(id, out _);
Vaults.TryRemove(id, out _);

_logger.LogInformation("Removed vault from syncing: {VaultId}", id);
}
Expand All @@ -71,20 +72,6 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
}
}

private async Task SyncVaultAsync(FileSyncManager syncManager, CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_queuer.Enqueue(syncManager.Id, (ct) =>
{
Console.WriteLine($"Syncing vault {syncManager.Id}");
return Task.CompletedTask;
});

Log.Debug($"{syncManager.Id} will sync every {syncManager.RemoteVault.SyncInterval} minutes");
//await Task.Delay(TimeSpan.FromMinutes(syncManager.RemoteVault.SyncInterval), stoppingToken);
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
protected abstract Task SyncVaultAsync(FileSyncManager syncManager, CancellationToken stoppingToken);
}
}
9 changes: 7 additions & 2 deletions Parallel.Cli/Services/RunCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,14 @@ private async Task HandleCommandAsync()
if (OperatingSystem.IsLinux()) builder.Services.AddSystemd();

builder.Services.AddHostedService<LifetimeService>();
builder.Services.AddHostedService<TaskService>();
//builder.Services.AddHostedService<CleanService>();
//builder.Services.AddHostedService<PruneService>();

builder.Services.AddHostedService<WatcherSyncService>();

//builder.Services.AddHostedService<TaskService>();

builder.Services.AddSingleton<TaskQueueExecutor>();
//builder.Services.AddSingleton<TaskQueueExecutor>();
builder.Services.AddSingleton<TaskQueuer>();

builder.Logging.ClearProviders();
Expand Down
74 changes: 74 additions & 0 deletions Parallel.Cli/Services/WatcherSyncService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright 2026 Entex Interactive

using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Parallel.Core.IO.Scanning;
using Parallel.Core.IO.Syncing;
using Parallel.Core.Tasks;

namespace Parallel.Cli.Services
{
public class WatcherSyncService : BaseSyncService
{
private readonly ILogger<WatcherSyncService> _logger;
private readonly ConcurrentBag<FileSystemWatcher> _watchers = new ConcurrentBag<FileSystemWatcher>();

public WatcherSyncService(ILogger<WatcherSyncService> logger, TaskQueuer queuer) : base(logger, queuer)
{
_logger = logger;
}

protected override async Task SyncVaultAsync(FileSyncManager syncManager, CancellationToken stoppingToken)
{
foreach (string path in syncManager.RemoteVault.SyncDirectories)
{
_logger.LogDebug("Watching directory: {Path}", path);
FileSystemWatcher watcher = new FileSystemWatcher()
{
Path = path,
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size,
InternalBufferSize = 32 * 1024,
EnableRaisingEvents = true
};

watcher.Created += OnCreated;
watcher.Changed += OnChanged;
watcher.Deleted += OnDeleted;
watcher.Renamed += OnRenamed;
watcher.Error += OnError;
_watchers.Add(watcher);
}
}

private void OnCreated(object sender, FileSystemEventArgs e)
{
if (FileScanner.IsDirectory(e.FullPath)) return;

_logger.LogDebug("Created file: {Path}", e.FullPath);
}

private void OnChanged(object sender, FileSystemEventArgs e)
{
if (FileScanner.IsDirectory(e.FullPath)) return;
_logger.LogDebug("Changed file: {Path}", e.FullPath);
}

private void OnDeleted(object sender, FileSystemEventArgs e)
{
if (FileScanner.IsDirectory(e.FullPath)) return;
_logger.LogDebug("Deleted file: {Path}", e.FullPath);
}

private void OnRenamed(object sender, RenamedEventArgs e)
{
if (FileScanner.IsDirectory(e.FullPath)) return;
_logger.LogDebug("Renamed file: {Path}", e.FullPath);
}

private void OnError(object sender, ErrorEventArgs e)
{
_logger.LogError("Exception throw: {Exception}", e.GetException().ToString());
}
}
}
4 changes: 2 additions & 2 deletions Parallel.Core/IO/Syncing/BaseSyncManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@ public abstract class BaseSyncManager : ISyncManager
public IStorageProvider StorageProvider { get; set; }

/// <summary>
///
/// Represents the base functionality for syncing files to an associated file system.
/// </summary>
/// <param name="localVault"></param>
protected BaseSyncManager(LocalVaultConfig localVault)
{
LocalVault = localVault;
Expand Down Expand Up @@ -134,6 +133,7 @@ public async Task DisconnectAsync()
/// <inheritdoc />
public abstract Task<int> PruneFilesAsync(IReadOnlyList<LocalFile> files, IProgressReporter progress);

/// <inheritdoc />
public abstract Task<int> ScrubFilesAsync(IReadOnlyList<LocalFile> files, IProgressReporter progress);
}
}
30 changes: 19 additions & 11 deletions Parallel.Core/IO/Syncing/ISyncManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,28 +49,36 @@ public interface ISyncManager
Task DisconnectAsync();

/// <summary>
/// Backs up an array of files to a vault.
/// Synchronizes a list of local files with the remote storage. Files will be uploaded if they differ from their remote counterpart or if they do not exist in the remote storage.
/// </summary>
/// <param name="files"></param>
/// <param name="progress"></param>
/// <param name="overwrite"></param>
/// <param name="files">A read-only list of local files to be considered for synchronization.</param>
/// <param name="progress">An <see cref="IProgressReporter"/> instance to report the progress of the sync operation.</param>
/// <param name="overwrite">A boolean flag indicating whether existing files on the remote storage should be overwritten.</param>
/// <returns>Returns the number of files that were successfully synchronized.</returns>
Task<int> SyncFilesAsync(IReadOnlyList<LocalFile> files, IProgressReporter progress, bool overwrite);

/// <summary>
/// Restores an array of files from a vault.
/// Restores the specified list of local files from a remote storage, updating the progress through the provided progress reporter.
/// </summary>
/// <param name="files"></param>
/// <param name="progress"></param>
/// <param name="files">A read-only list of local files to be considered for restoration.</param>
/// <param name="progress">An <see cref="IProgressReporter"/> instance to report the progress of the restore operation.</param>
/// <returns>Returns the number of files that were successfully restored.</returns>
Task<int> RestoreFilesAsync(IReadOnlyList<LocalFile> files, IProgressReporter progress);

/// <summary>
/// Deletes files from a vault.
/// Removes unnecessary or transient files from the provided list of local files to clean up storage, retaining only essential data.
/// </summary>
/// <param name="files"></param>
/// <param name="progress"></param>
/// <returns></returns>
/// <param name="files">A read-only list of local files to be considered for pruning.</param>
/// <param name="progress">An <see cref="IProgressReporter"/> instance to report the progress of the pruning operation.</param>
/// <returns>Returns the number of files that were successfully pruned.</returns>
Task<int> PruneFilesAsync(IReadOnlyList<LocalFile> files, IProgressReporter progress);

/// <summary>
/// Scrubs the specified files to ensure they are in a valid state.
/// </summary>
/// <param name="files">A read-only list of local files to be considered for scrubbing.</param>
/// <param name="progress">An <see cref="IProgressReporter"/> instance to report the progress of the scrubbing operation.</param>
/// <returns>Returns the number of files that were successfully scrubbed.</returns>
Task<int> ScrubFilesAsync(IReadOnlyList<LocalFile> files, IProgressReporter progress);
}
}
2 changes: 1 addition & 1 deletion Parallel.Core/Tasks/TaskQueuer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public async Task<Func<CancellationToken, Task>> WaitAsync(CancellationToken ct)
EnqueuedTask? next = _tasks.Values.MaxBy(t => t.Priority + (DateTime.UtcNow - t.EnqueuedAt).TotalSeconds * 0.1);
if (ReferenceEquals(candidate, next))
{
_logger.LogDebug($"Starting task with key: '{candidate.Key}', remaining: {_queue.Count - 1}");
_logger.LogDebug("Starting task with key: '{CandidateKey}', remaining: {QueueCount}", candidate.Key, _queue.Count - 1);
_tasks.TryRemove(candidate.Key, out _);
return candidate.TaskFunc;
}
Expand Down
Loading