YamlResourceCollection.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. using System.Collections.Specialized;
  2. using RackPeek.Domain.Resources;
  3. using RackPeek.Domain.Resources.AccessPoints;
  4. using RackPeek.Domain.Resources.Desktops;
  5. using RackPeek.Domain.Resources.Firewalls;
  6. using RackPeek.Domain.Resources.Hardware;
  7. using RackPeek.Domain.Resources.Laptops;
  8. using RackPeek.Domain.Resources.Routers;
  9. using RackPeek.Domain.Resources.Servers;
  10. using RackPeek.Domain.Resources.Services;
  11. using RackPeek.Domain.Resources.Switches;
  12. using RackPeek.Domain.Resources.SystemResources;
  13. using RackPeek.Domain.Resources.UpsUnits;
  14. using YamlDotNet.Core;
  15. using YamlDotNet.Serialization;
  16. using YamlDotNet.Serialization.NamingConventions;
  17. namespace RackPeek.Domain.Persistence.Yaml;
  18. public class ResourceCollection
  19. {
  20. public readonly SemaphoreSlim FileLock = new(1, 1);
  21. public List<Resource> Resources { get; } = new();
  22. }
  23. public sealed class YamlResourceCollection(
  24. string filePath,
  25. ITextFileStore fileStore,
  26. ResourceCollection resourceCollection)
  27. : IResourceCollection
  28. {
  29. // Bump this when your YAML schema changes, and add a migration step below.
  30. private const int CurrentSchemaVersion = 1;
  31. public Task<bool> Exists(string name)
  32. {
  33. return Task.FromResult(resourceCollection.Resources.Exists(r =>
  34. r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
  35. }
  36. public Task<Dictionary<string, int>> GetTagsAsync()
  37. {
  38. var result = resourceCollection.Resources
  39. .SelectMany(r => r.Tags) // flatten all tag arrays
  40. .Where(t => !string.IsNullOrWhiteSpace(t))
  41. .GroupBy(t => t)
  42. .ToDictionary(g => g.Key, g => g.Count());
  43. return Task.FromResult(result);
  44. }
  45. public Task<IReadOnlyList<T>> GetAllOfTypeAsync<T>()
  46. {
  47. return Task.FromResult<IReadOnlyList<T>>(resourceCollection.Resources.OfType<T>().ToList());
  48. }
  49. public Task<IReadOnlyList<Resource>> GetDependantsAsync(string name)
  50. {
  51. return Task.FromResult<IReadOnlyList<Resource>>(resourceCollection.Resources
  52. .Where(r => r.RunsOn?.Equals(name, StringComparison.OrdinalIgnoreCase) ?? false)
  53. .ToList());
  54. }
  55. public Task<IReadOnlyList<Resource>> GetByTagAsync(string name)
  56. {
  57. return Task.FromResult<IReadOnlyList<Resource>>(
  58. resourceCollection.Resources
  59. .Where(r => r.Tags.Contains(name))
  60. .ToList()
  61. );
  62. }
  63. public IReadOnlyList<Hardware> HardwareResources =>
  64. resourceCollection.Resources.OfType<Hardware>().ToList();
  65. public IReadOnlyList<SystemResource> SystemResources =>
  66. resourceCollection.Resources.OfType<SystemResource>().ToList();
  67. public IReadOnlyList<Service> ServiceResources =>
  68. resourceCollection.Resources.OfType<Service>().ToList();
  69. public Task<Resource?> GetByNameAsync(string name)
  70. {
  71. return Task.FromResult(resourceCollection.Resources.FirstOrDefault(r =>
  72. r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
  73. }
  74. public Task<T?> GetByNameAsync<T>(string name) where T : Resource
  75. {
  76. var resource =
  77. resourceCollection.Resources.FirstOrDefault(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
  78. return Task.FromResult(resource as T);
  79. }
  80. public Resource? GetByName(string name)
  81. {
  82. return resourceCollection.Resources.FirstOrDefault(r =>
  83. r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
  84. }
  85. public async Task LoadAsync()
  86. {
  87. // Read raw YAML so we can back it up exactly before any migration writes.
  88. var yaml = await fileStore.ReadAllTextAsync(filePath);
  89. if (string.IsNullOrWhiteSpace(yaml))
  90. {
  91. resourceCollection.Resources.Clear();
  92. return;
  93. }
  94. var root = DeserializeRoot(yaml);
  95. if (root == null)
  96. {
  97. // Keep behavior aligned with your previous code: if YAML is invalid, treat as empty.
  98. resourceCollection.Resources.Clear();
  99. return;
  100. }
  101. // Guard: config is newer than this app understands.
  102. if (root.Version > CurrentSchemaVersion)
  103. {
  104. throw new InvalidOperationException(
  105. $"Config schema version {root.Version} is newer than this application supports ({CurrentSchemaVersion}).");
  106. }
  107. // If older, backup first, then migrate step-by-step, then save.
  108. if (root.Version < CurrentSchemaVersion)
  109. {
  110. await BackupOriginalAsync(yaml);
  111. root = await MigrateAsync(root);
  112. // Ensure we persist the migrated root (with updated version)
  113. await SaveRootAsync(root);
  114. }
  115. resourceCollection.Resources.Clear();
  116. resourceCollection.Resources.AddRange(root.Resources ?? []);
  117. }
  118. public Task AddAsync(Resource resource)
  119. {
  120. return UpdateWithLockAsync(list =>
  121. {
  122. if (list.Any(r => r.Name.Equals(resource.Name, StringComparison.OrdinalIgnoreCase)))
  123. throw new InvalidOperationException($"'{resource.Name}' already exists.");
  124. resource.Kind = GetKind(resource);
  125. list.Add(resource);
  126. });
  127. }
  128. public Task UpdateAsync(Resource resource)
  129. {
  130. return UpdateWithLockAsync(list =>
  131. {
  132. var index = list.FindIndex(r => r.Name.Equals(resource.Name, StringComparison.OrdinalIgnoreCase));
  133. if (index == -1) throw new InvalidOperationException("Not found.");
  134. resource.Kind = GetKind(resource);
  135. list[index] = resource;
  136. });
  137. }
  138. public Task DeleteAsync(string name)
  139. {
  140. return UpdateWithLockAsync(list =>
  141. list.RemoveAll(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
  142. }
  143. private async Task UpdateWithLockAsync(Action<List<Resource>> action)
  144. {
  145. await resourceCollection.FileLock.WaitAsync();
  146. try
  147. {
  148. action(resourceCollection.Resources);
  149. // Always write current schema version when app writes the file.
  150. var root = new YamlRoot
  151. {
  152. Version = CurrentSchemaVersion,
  153. Resources = resourceCollection.Resources
  154. };
  155. await SaveRootAsync(root);
  156. }
  157. finally
  158. {
  159. resourceCollection.FileLock.Release();
  160. }
  161. }
  162. // ----------------------------
  163. // Versioning + migration
  164. // ----------------------------
  165. private async Task BackupOriginalAsync(string originalYaml)
  166. {
  167. // Timestamped backup for safe rollback
  168. var backupPath = $"{filePath}.bak.{DateTime.UtcNow:yyyyMMddHHmmss}";
  169. await fileStore.WriteAllTextAsync(backupPath, originalYaml);
  170. }
  171. private Task<YamlRoot> MigrateAsync(YamlRoot root)
  172. {
  173. // Step-by-step migrations until we reach CurrentSchemaVersion
  174. while (root.Version < CurrentSchemaVersion)
  175. {
  176. root = root.Version switch
  177. {
  178. 0 => MigrateV0ToV1(root),
  179. _ => throw new InvalidOperationException(
  180. $"No migration is defined from version {root.Version} to {root.Version + 1}.")
  181. };
  182. }
  183. return Task.FromResult(root);
  184. }
  185. private YamlRoot MigrateV0ToV1(YamlRoot root)
  186. {
  187. // V0 -> V1 example migration:
  188. // - Ensure 'kind' is normalized on all resources
  189. // - Ensure tags collections aren’t null
  190. if (root.Resources != null)
  191. {
  192. foreach (var r in root.Resources)
  193. {
  194. r.Kind = GetKind(r);
  195. r.Tags ??= [];
  196. }
  197. }
  198. root.Version = 1;
  199. return root;
  200. }
  201. // ----------------------------
  202. // YAML read/write
  203. // ----------------------------
  204. private YamlRoot? DeserializeRoot(string yaml)
  205. {
  206. var deserializer = new DeserializerBuilder()
  207. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  208. .WithCaseInsensitivePropertyMatching()
  209. .WithTypeConverter(new StorageSizeYamlConverter())
  210. .WithTypeConverter(new NotesStringYamlConverter())
  211. .WithTypeDiscriminatingNodeDeserializer(options =>
  212. {
  213. options.AddKeyValueTypeDiscriminator<Resource>("kind", new Dictionary<string, Type>
  214. {
  215. { Server.KindLabel, typeof(Server) },
  216. { Switch.KindLabel, typeof(Switch) },
  217. { Firewall.KindLabel, typeof(Firewall) },
  218. { Router.KindLabel, typeof(Router) },
  219. { Desktop.KindLabel, typeof(Desktop) },
  220. { Laptop.KindLabel, typeof(Laptop) },
  221. { AccessPoint.KindLabel, typeof(AccessPoint) },
  222. { Ups.KindLabel, typeof(Ups) },
  223. { SystemResource.KindLabel, typeof(SystemResource) },
  224. { Service.KindLabel, typeof(Service) }
  225. });
  226. })
  227. .Build();
  228. try
  229. {
  230. // If 'version' is missing, int defaults to 0 => treated as V0.
  231. var root = deserializer.Deserialize<YamlRoot>(yaml);
  232. // If YAML had only "resources:" previously, this will still work.
  233. root ??= new YamlRoot { Version = 0, Resources = new List<Resource>() };
  234. root.Resources ??= new List<Resource>();
  235. return root;
  236. }
  237. catch (YamlException)
  238. {
  239. return null;
  240. }
  241. }
  242. private async Task SaveRootAsync(YamlRoot root)
  243. {
  244. var serializer = new SerializerBuilder()
  245. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  246. .WithTypeConverter(new StorageSizeYamlConverter())
  247. .WithTypeConverter(new NotesStringYamlConverter())
  248. .ConfigureDefaultValuesHandling(
  249. DefaultValuesHandling.OmitNull |
  250. DefaultValuesHandling.OmitEmptyCollections
  251. )
  252. .Build();
  253. // Preserve ordering: version first, then resources
  254. var payload = new OrderedDictionary
  255. {
  256. ["version"] = root.Version,
  257. ["resources"] = (root.Resources ?? new List<Resource>()).Select(SerializeResource).ToList()
  258. };
  259. await fileStore.WriteAllTextAsync(filePath, serializer.Serialize(payload));
  260. }
  261. private string GetKind(Resource resource)
  262. {
  263. return resource switch
  264. {
  265. Server => "Server",
  266. Switch => "Switch",
  267. Firewall => "Firewall",
  268. Router => "Router",
  269. Desktop => "Desktop",
  270. Laptop => "Laptop",
  271. AccessPoint => "AccessPoint",
  272. Ups => "Ups",
  273. SystemResource => "System",
  274. Service => "Service",
  275. _ => throw new InvalidOperationException($"Unknown resource type: {resource.GetType().Name}")
  276. };
  277. }
  278. private OrderedDictionary SerializeResource(Resource resource)
  279. {
  280. var map = new OrderedDictionary
  281. {
  282. ["kind"] = GetKind(resource)
  283. };
  284. var serializer = new SerializerBuilder()
  285. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  286. .WithTypeConverter(new NotesStringYamlConverter())
  287. .ConfigureDefaultValuesHandling(
  288. DefaultValuesHandling.OmitNull |
  289. DefaultValuesHandling.OmitEmptyCollections
  290. )
  291. .Build();
  292. var yaml = serializer.Serialize(resource);
  293. var props = new DeserializerBuilder()
  294. .Build()
  295. .Deserialize<Dictionary<string, object?>>(yaml);
  296. foreach (var (key, value) in props)
  297. if (!string.Equals(key, "kind", StringComparison.OrdinalIgnoreCase))
  298. map[key] = value;
  299. return map;
  300. }
  301. }
  302. public class YamlRoot
  303. {
  304. public int Version { get; set; } // <- NEW: YAML schema version
  305. public List<Resource>? Resources { get; set; }
  306. }