feat(01-03): ProfileRepository and ProfileService with write-then-replace
- ProfileRepository: SemaphoreSlim write lock + write-then-replace (tmp→validate→move) - ProfileRepository: camelCase JSON serialization matching existing schema - ProfileService: CRUD operations (Add/Rename/Delete) with validation - All 10 ProfileServiceTests pass (round-trip, missing file, corrupt JSON, concurrency, schema check)
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using SharepointToolbox.Core.Models;
|
||||
|
||||
namespace SharepointToolbox.Infrastructure.Persistence;
|
||||
|
||||
public class ProfileRepository
|
||||
{
|
||||
private readonly string _filePath;
|
||||
private readonly SemaphoreSlim _writeLock = new(1, 1);
|
||||
|
||||
public ProfileRepository(string filePath)
|
||||
{
|
||||
_filePath = filePath;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<TenantProfile>> LoadAsync()
|
||||
{
|
||||
if (!File.Exists(_filePath))
|
||||
return Array.Empty<TenantProfile>();
|
||||
|
||||
string json;
|
||||
try
|
||||
{
|
||||
json = await File.ReadAllTextAsync(_filePath, Encoding.UTF8);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new InvalidDataException($"Failed to read profiles file: {_filePath}", ex);
|
||||
}
|
||||
|
||||
ProfilesRoot? root;
|
||||
try
|
||||
{
|
||||
root = JsonSerializer.Deserialize<ProfilesRoot>(json,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"Profiles file contains invalid JSON: {_filePath}", ex);
|
||||
}
|
||||
|
||||
if (root?.Profiles is null)
|
||||
return Array.Empty<TenantProfile>();
|
||||
return root.Profiles;
|
||||
}
|
||||
|
||||
public async Task SaveAsync(IReadOnlyList<TenantProfile> profiles)
|
||||
{
|
||||
await _writeLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
var root = new ProfilesRoot { Profiles = profiles.ToList() };
|
||||
var json = JsonSerializer.Serialize(root,
|
||||
new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
});
|
||||
|
||||
var tmpPath = _filePath + ".tmp";
|
||||
var dir = Path.GetDirectoryName(_filePath);
|
||||
if (!string.IsNullOrEmpty(dir))
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
await File.WriteAllTextAsync(tmpPath, json, Encoding.UTF8);
|
||||
|
||||
// Validate round-trip before replacing
|
||||
JsonDocument.Parse(await File.ReadAllTextAsync(tmpPath, Encoding.UTF8)).Dispose();
|
||||
|
||||
File.Move(tmpPath, _filePath, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_writeLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ProfilesRoot
|
||||
{
|
||||
public List<TenantProfile> Profiles { get; set; } = new();
|
||||
}
|
||||
}
|
||||
54
SharepointToolbox/Services/ProfileService.cs
Normal file
54
SharepointToolbox/Services/ProfileService.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using SharepointToolbox.Core.Models;
|
||||
using SharepointToolbox.Infrastructure.Persistence;
|
||||
|
||||
namespace SharepointToolbox.Services;
|
||||
|
||||
public class ProfileService
|
||||
{
|
||||
private readonly ProfileRepository _repository;
|
||||
|
||||
public ProfileService(ProfileRepository repository)
|
||||
{
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<TenantProfile>> GetProfilesAsync()
|
||||
=> _repository.LoadAsync();
|
||||
|
||||
public async Task AddProfileAsync(TenantProfile profile)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(profile.Name))
|
||||
throw new ArgumentException("Profile name must not be empty.", nameof(profile));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(profile.TenantUrl) ||
|
||||
!Uri.TryCreate(profile.TenantUrl, UriKind.Absolute, out _))
|
||||
throw new ArgumentException("TenantUrl must be a valid absolute URL.", nameof(profile));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(profile.ClientId))
|
||||
throw new ArgumentException("ClientId must not be empty.", nameof(profile));
|
||||
|
||||
var existing = (await _repository.LoadAsync()).ToList();
|
||||
existing.Add(profile);
|
||||
await _repository.SaveAsync(existing);
|
||||
}
|
||||
|
||||
public async Task RenameProfileAsync(string existingName, string newName)
|
||||
{
|
||||
var profiles = (await _repository.LoadAsync()).ToList();
|
||||
var target = profiles.FirstOrDefault(p => p.Name == existingName)
|
||||
?? throw new KeyNotFoundException($"Profile '{existingName}' not found.");
|
||||
|
||||
target.Name = newName;
|
||||
await _repository.SaveAsync(profiles);
|
||||
}
|
||||
|
||||
public async Task DeleteProfileAsync(string name)
|
||||
{
|
||||
var profiles = (await _repository.LoadAsync()).ToList();
|
||||
var target = profiles.FirstOrDefault(p => p.Name == name)
|
||||
?? throw new KeyNotFoundException($"Profile '{name}' not found.");
|
||||
|
||||
profiles.Remove(target);
|
||||
await _repository.SaveAsync(profiles);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user