YamlResourceCollection.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. using System.Collections.ObjectModel;
  2. using System.Collections.Specialized;
  3. using System.Diagnostics;
  4. using RackPeek.Domain.Discovery;
  5. using RackPeek.Domain.Helpers;
  6. using RackPeek.Domain.Resources;
  7. using RackPeek.Domain.Resources.AccessPoints;
  8. using RackPeek.Domain.Resources.Connections;
  9. using RackPeek.Domain.Resources.Desktops;
  10. using RackPeek.Domain.Resources.Firewalls;
  11. using RackPeek.Domain.Resources.Hardware;
  12. using RackPeek.Domain.Resources.Laptops;
  13. using RackPeek.Domain.Resources.Routers;
  14. using RackPeek.Domain.Resources.Servers;
  15. using RackPeek.Domain.Resources.Services;
  16. using RackPeek.Domain.Resources.SystemResources;
  17. using RackPeek.Domain.Resources.OtherHardware;
  18. using RackPeek.Domain.Resources.UpsUnits;
  19. using YamlDotNet.Serialization;
  20. using YamlDotNet.Serialization.NamingConventions;
  21. using Switch = RackPeek.Domain.Resources.Switches.Switch;
  22. namespace RackPeek.Domain.Persistence.Yaml;
  23. public class ResourceCollection {
  24. public readonly SemaphoreSlim FileLock = new(1, 1);
  25. private InventoryState _inventory = new(new List<Resource>(), new List<Connection>());
  26. public List<Resource> Resources {
  27. get => _inventory.Resources;
  28. set => _inventory = _inventory with { Resources = value };
  29. }
  30. public List<Connection> Connections {
  31. get => _inventory.Connections;
  32. set => _inventory = _inventory with { Connections = value };
  33. }
  34. public (List<Resource> Resources, List<Connection> Connections) GetInventorySnapshot() {
  35. InventoryState inventory = _inventory;
  36. return (inventory.Resources, inventory.Connections);
  37. }
  38. public void ReplaceInventory(List<Resource> resources, List<Connection> connections) =>
  39. _inventory = new InventoryState(resources, connections);
  40. /// <summary>
  41. /// Whether the store has ever been read successfully. Guarded by
  42. /// <see cref="FileLock" />. Write paths check it so a boot that survived an
  43. /// unreadable config cannot later persist the empty in-memory collection over
  44. /// the user's file.
  45. /// </summary>
  46. public bool Loaded { get; set; }
  47. /// <summary>
  48. /// Set when the config exists but could not be understood — damaged, truncated,
  49. /// or not YAML. The process is still allowed to boot (the web UI is how someone
  50. /// fixes the file), but every read and write must fail loudly rather than serve
  51. /// or persist an empty inventory (#337).
  52. /// </summary>
  53. public ConfigLoadException? LoadFailure { get; set; }
  54. private sealed record InventoryState(List<Resource> Resources, List<Connection> Connections);
  55. }
  56. public sealed class YamlResourceCollection(
  57. string filePath,
  58. ITextFileStore fileStore,
  59. ResourceCollection resourceCollection,
  60. IResourceYamlMigrationService migrationService)
  61. : IResourceCollection {
  62. // Bump this when your YAML schema changes, and add a migration step below.
  63. private static readonly int _currentSchemaVersion = RackPeekConfigMigrationDeserializer.ListOfMigrations.Count;
  64. public Task<bool> Exists(string name) {
  65. ThrowIfLoadFailed();
  66. return Task.FromResult(resourceCollection.Resources.Exists(r =>
  67. r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
  68. }
  69. public Task<string?> GetKind(string? name) {
  70. ThrowIfLoadFailed();
  71. return Task.FromResult(resourceCollection.Resources.FirstOrDefault(r =>
  72. r.Name.Equals(name, StringComparison.OrdinalIgnoreCase))?.Kind);
  73. }
  74. public Task<IReadOnlyList<(Resource, string)>> GetByLabelAsync(string name) {
  75. ThrowIfLoadFailed();
  76. ReadOnlyCollection<(Resource r, string)> result = resourceCollection.Resources
  77. .Where(r => r.Labels != null && r.Labels.TryGetValue(name, out _))
  78. .Select(r => (r, r.Labels![name]))
  79. .ToList()
  80. .AsReadOnly();
  81. return Task.FromResult<IReadOnlyList<(Resource, string)>>(result);
  82. }
  83. public Task<Dictionary<string, int>> GetLabelsAsync() {
  84. ThrowIfLoadFailed();
  85. var result = resourceCollection.Resources
  86. .SelectMany(r => r.Labels ?? Enumerable.Empty<KeyValuePair<string, string>>())
  87. .Where(kvp => !string.IsNullOrWhiteSpace(kvp.Key))
  88. .GroupBy(kvp => kvp.Key)
  89. .ToDictionary(g => g.Key, g => g.Count());
  90. return Task.FromResult(result);
  91. }
  92. public Task<IReadOnlyList<(Resource, string)>> GetResourceIpsAsync() {
  93. ThrowIfLoadFailed();
  94. var result = new List<(Resource, string)>();
  95. List<Resource> allResources = resourceCollection.Resources;
  96. // Build fast lookup for systems
  97. var systemsByName = allResources
  98. .OfType<SystemResource>()
  99. .ToDictionary(s => s.Name, StringComparer.OrdinalIgnoreCase);
  100. // Cache resolved system IPs (prevents repeated recursion)
  101. var resolvedSystemIps = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
  102. foreach (Resource resource in allResources)
  103. switch (resource) {
  104. case SystemResource system: {
  105. var ip = ResolveSystemIp(system, systemsByName, resolvedSystemIps);
  106. if (!string.IsNullOrWhiteSpace(ip))
  107. result.Add((system, ip));
  108. break;
  109. }
  110. case Service service: {
  111. var ip = ResolveServiceIp(service, systemsByName, resolvedSystemIps);
  112. if (!string.IsNullOrWhiteSpace(ip))
  113. result.Add((service, ip));
  114. break;
  115. }
  116. }
  117. return Task.FromResult((IReadOnlyList<(Resource, string)>)result);
  118. }
  119. public Task<Dictionary<string, int>> GetTagsAsync() {
  120. ThrowIfLoadFailed();
  121. var result = resourceCollection.Resources
  122. .SelectMany(r => r.Tags) // flatten all tag arrays
  123. .Where(t => !string.IsNullOrWhiteSpace(t))
  124. .GroupBy(t => t)
  125. .ToDictionary(g => g.Key, g => g.Count());
  126. return Task.FromResult(result);
  127. }
  128. public Task<IReadOnlyList<T>> GetAllOfTypeAsync<T>() {
  129. ThrowIfLoadFailed();
  130. return Task.FromResult<IReadOnlyList<T>>(resourceCollection.Resources.OfType<T>().ToList());
  131. }
  132. public Task<(IReadOnlyList<Resource> Resources, IReadOnlyList<Connection> Connections)>
  133. GetInventorySnapshotAsync() {
  134. ThrowIfLoadFailed();
  135. (List<Resource> resources, List<Connection> connections) = resourceCollection.GetInventorySnapshot();
  136. return Task.FromResult<(IReadOnlyList<Resource>, IReadOnlyList<Connection>)>((resources, connections));
  137. }
  138. public Task<IReadOnlyList<Resource>> GetDependantsAsync(string name) {
  139. ThrowIfLoadFailed();
  140. var result = resourceCollection.Resources
  141. .Where(r => r.RunsOn.Any(p => p.Equals(name, StringComparison.OrdinalIgnoreCase)))
  142. .ToList();
  143. return Task.FromResult<IReadOnlyList<Resource>>(result);
  144. }
  145. public async Task Merge(string incomingYaml, MergeMode mode) {
  146. if (string.IsNullOrWhiteSpace(incomingYaml))
  147. return;
  148. await resourceCollection.FileLock.WaitAsync();
  149. try {
  150. await EnsureLoadedAsync();
  151. YamlRoot incomingRoot = await migrationService.DeserializeAsync(incomingYaml);
  152. List<Resource> incomingResources = incomingRoot.Resources ?? new List<Resource>();
  153. List<Resource> existingResources = ResourceCollectionMerger.DeepCloneResources(
  154. resourceCollection.Resources);
  155. var existingConnections = resourceCollection.Connections
  156. .Select(CloneConnection)
  157. .ToList();
  158. DiscoveryIdResolver.ResolveNames(
  159. existingResources,
  160. incomingResources,
  161. incomingRoot.Connections,
  162. existingConnections,
  163. true);
  164. List<Resource> merged = ResourceCollectionMerger.Merge(
  165. existingResources,
  166. incomingResources,
  167. mode);
  168. List<Connection>? mergedConnections = ConnectionMerger.Merge(
  169. existingConnections,
  170. incomingRoot.Connections,
  171. mode);
  172. resourceCollection.ReplaceInventory(merged, mergedConnections ?? existingConnections);
  173. var rootToSave = new YamlRoot {
  174. Version = RackPeekConfigMigrationDeserializer.ListOfMigrations.Count,
  175. Resources = resourceCollection.Resources,
  176. Connections = resourceCollection.Connections
  177. };
  178. await SaveRootAsync(rootToSave);
  179. }
  180. finally {
  181. resourceCollection.FileLock.Release();
  182. }
  183. }
  184. private static Connection CloneConnection(Connection connection) => new() {
  185. A = new PortReference {
  186. Resource = connection.A.Resource,
  187. PortGroup = connection.A.PortGroup,
  188. PortIndex = connection.A.PortIndex
  189. },
  190. B = new PortReference {
  191. Resource = connection.B.Resource,
  192. PortGroup = connection.B.PortGroup,
  193. PortIndex = connection.B.PortIndex
  194. },
  195. Label = connection.Label,
  196. Notes = connection.Notes
  197. };
  198. public Task<IReadOnlyList<Resource>> GetByTagAsync(string name) {
  199. ThrowIfLoadFailed();
  200. return Task.FromResult<IReadOnlyList<Resource>>(
  201. resourceCollection.Resources
  202. .Where(r => r.Tags.Contains(name))
  203. .ToList()
  204. );
  205. }
  206. public IReadOnlyList<Hardware> HardwareResources {
  207. get {
  208. ThrowIfLoadFailed();
  209. return resourceCollection.Resources.OfType<Hardware>().ToList();
  210. }
  211. }
  212. public IReadOnlyList<SystemResource> SystemResources {
  213. get {
  214. ThrowIfLoadFailed();
  215. return resourceCollection.Resources.OfType<SystemResource>().ToList();
  216. }
  217. }
  218. public IReadOnlyList<Service> ServiceResources {
  219. get {
  220. ThrowIfLoadFailed();
  221. return resourceCollection.Resources.OfType<Service>().ToList();
  222. }
  223. }
  224. public Task<Resource?> GetByNameAsync(string name) {
  225. ThrowIfLoadFailed();
  226. return Task.FromResult(resourceCollection.Resources.FirstOrDefault(r =>
  227. r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
  228. }
  229. public Task<T?> GetByNameAsync<T>(string name) where T : Resource {
  230. ThrowIfLoadFailed();
  231. Resource? resource =
  232. resourceCollection.Resources.FirstOrDefault(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
  233. return Task.FromResult(resource as T);
  234. }
  235. public Resource? GetByName(string name) {
  236. ThrowIfLoadFailed();
  237. return resourceCollection.Resources.FirstOrDefault(r =>
  238. r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
  239. }
  240. public async Task LoadAsync() {
  241. // Routes.razor calls LoadAsync on every Blazor circuit init, so
  242. // multiple tabs / fresh page loads can run this concurrently. Without
  243. // the lock, two callers can interleave Resources.Clear() and
  244. // AddRange() and corrupt the List<T>'s internal _size, producing
  245. // "Index was outside the bounds of the array" out of List.Clear.
  246. await resourceCollection.FileLock.WaitAsync();
  247. try {
  248. await LoadUnderLockAsync();
  249. }
  250. finally {
  251. resourceCollection.FileLock.Release();
  252. }
  253. }
  254. private async Task LoadUnderLockAsync() {
  255. var yaml = await fileStore.ReadAllTextAsync(filePath);
  256. YamlRoot root;
  257. try {
  258. root = await migrationService.DeserializeAsync(
  259. yaml,
  260. async originalYaml => await BackupOriginalAsync(originalYaml),
  261. async migratedRoot => {
  262. if (migratedRoot.Version > 0)
  263. await SaveRootAsync(migratedRoot);
  264. }
  265. );
  266. }
  267. catch (Exception ex) when (ex is not ConfigLoadException
  268. and not IOException
  269. and not UnauthorizedAccessException) {
  270. // A file that exists but cannot be understood. Record it so that every
  271. // later read and write refuses, rather than quietly serving — and then
  272. // persisting — an empty inventory over a recoverable file (#337).
  273. resourceCollection.LoadFailure = new ConfigLoadException(
  274. $"The config at {filePath} could not be read: {ex.Message} " +
  275. "Fix or restore the file (recent schema migrations leave .bak copies " +
  276. "beside it); nothing has been changed.",
  277. ex);
  278. throw resourceCollection.LoadFailure;
  279. }
  280. // A RackPeek document always carries a schema version. Its absence means the
  281. // file was cut before the version line was written, or is not a RackPeek
  282. // config at all — either way the parse "succeeding" with an empty document is
  283. // not evidence of an empty inventory.
  284. if (!string.IsNullOrWhiteSpace(yaml) && root.Version <= 0) {
  285. resourceCollection.LoadFailure = new ConfigLoadException(
  286. $"The config at {filePath} is missing its schema version, so it is " +
  287. "incomplete or not a RackPeek config. Fix or restore the file; " +
  288. "nothing has been changed.");
  289. throw resourceCollection.LoadFailure;
  290. }
  291. resourceCollection.ReplaceInventory(root.Resources ?? [], root.Connections ?? []);
  292. resourceCollection.LoadFailure = null;
  293. resourceCollection.Loaded = true;
  294. }
  295. /// <summary>
  296. /// Called at the top of every read path. When the config exists but could not be
  297. /// understood, the in-memory collection is empty for a reason that has nothing to
  298. /// do with the user's inventory — serving it would report "0 resources" for a
  299. /// recoverable file, and scripted consumers would treat that as the truth (#337).
  300. /// </summary>
  301. private void ThrowIfLoadFailed() {
  302. if (resourceCollection.LoadFailure != null)
  303. throw resourceCollection.LoadFailure;
  304. }
  305. /// <summary>
  306. /// Called at the top of every write path, under the lock. Normally a no-op:
  307. /// both the CLI and the web host load at startup. When that startup load failed
  308. /// (unreadable or malformed file, tolerated so the process can boot), this
  309. /// retries — and if the store still cannot be read, the write fails HERE, before
  310. /// the empty in-memory collection can be persisted over the user's config.
  311. /// </summary>
  312. private async Task EnsureLoadedAsync() {
  313. if (!resourceCollection.Loaded)
  314. await LoadUnderLockAsync();
  315. }
  316. public Task AddAsync(Resource resource) {
  317. return UpdateWithLockAsync(list => {
  318. if (list.Any(r => r.Name.Equals(resource.Name, StringComparison.OrdinalIgnoreCase)))
  319. throw new InvalidOperationException($"'{resource.Name}' already exists.");
  320. resource.Kind = GetKind(resource);
  321. list.Add(resource);
  322. });
  323. }
  324. public Task UpdateAsync(Resource resource) {
  325. return UpdateWithLockAsync(list => {
  326. var index = list.FindIndex(r => r.Name.Equals(resource.Name, StringComparison.OrdinalIgnoreCase));
  327. if (index == -1) throw new InvalidOperationException("Not found.");
  328. resource.Kind = GetKind(resource);
  329. list[index] = resource;
  330. });
  331. }
  332. public Task DeleteAsync(string name) {
  333. return UpdateWithLockAsync(list =>
  334. list.RemoveAll(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
  335. }
  336. public Task AddConnectionAsync(Connection connection) => UpdateConnectionsWithLockAsync(list => { list.Add(connection); });
  337. public Task RemoveConnectionAsync(Connection connection) {
  338. return UpdateConnectionsWithLockAsync(list => {
  339. list.RemoveAll(c =>
  340. (PortsMatch(c.A, connection.A) && PortsMatch(c.B, connection.B)) ||
  341. (PortsMatch(c.A, connection.B) && PortsMatch(c.B, connection.A)));
  342. });
  343. }
  344. public Task RemoveConnectionsForPortAsync(PortReference port) {
  345. return UpdateConnectionsWithLockAsync(list => {
  346. list.RemoveAll(c =>
  347. PortsMatch(c.A, port) ||
  348. PortsMatch(c.B, port));
  349. });
  350. }
  351. public Task<IReadOnlyList<Connection>> GetConnectionsAsync() {
  352. ThrowIfLoadFailed();
  353. IReadOnlyList<Connection> result =
  354. resourceCollection.Connections
  355. .ToList()
  356. .AsReadOnly();
  357. return Task.FromResult(result);
  358. }
  359. public Task<IReadOnlyList<Connection>> GetConnectionsForResourceAsync(string resource) {
  360. ThrowIfLoadFailed();
  361. IReadOnlyList<Connection> result =
  362. resourceCollection.Connections
  363. .Where(c =>
  364. c.A.Resource.Equals(resource, StringComparison.OrdinalIgnoreCase) ||
  365. c.B.Resource.Equals(resource, StringComparison.OrdinalIgnoreCase))
  366. .ToList()
  367. .AsReadOnly();
  368. return Task.FromResult(result);
  369. }
  370. public Task<Connection?> GetConnectionForPortAsync(PortReference port) {
  371. ThrowIfLoadFailed();
  372. Connection? connection =
  373. resourceCollection.Connections
  374. .FirstOrDefault(c =>
  375. PortsMatch(c.A, port) ||
  376. PortsMatch(c.B, port));
  377. return Task.FromResult(connection);
  378. }
  379. private string? ResolveSystemIp(
  380. SystemResource system,
  381. Dictionary<string, SystemResource> systemsByName,
  382. Dictionary<string, string?> cache) {
  383. // Return cached result if already resolved
  384. if (cache.TryGetValue(system.Name, out var cached))
  385. return cached;
  386. // Direct IP wins
  387. if (!string.IsNullOrWhiteSpace(system.Ip)) {
  388. cache[system.Name] = system.Ip;
  389. return system.Ip;
  390. }
  391. // Must have exactly one parent
  392. if (system.RunsOn?.Count != 1) {
  393. cache[system.Name] = null;
  394. return null;
  395. }
  396. var parentName = system.RunsOn.First();
  397. if (!systemsByName.TryGetValue(parentName, out SystemResource? parent)) {
  398. cache[system.Name] = null;
  399. return null;
  400. }
  401. var resolved = ResolveSystemIp(parent, systemsByName, cache);
  402. cache[system.Name] = resolved;
  403. return resolved;
  404. }
  405. private string? ResolveServiceIp(
  406. Service service,
  407. Dictionary<string, SystemResource> systemsByName,
  408. Dictionary<string, string?> cache) {
  409. // Direct IP wins
  410. if (!string.IsNullOrWhiteSpace(service.Network?.Ip))
  411. return service.Network!.Ip;
  412. // Must have exactly one parent
  413. if (service.RunsOn?.Count != 1)
  414. return null;
  415. var parentName = service.RunsOn.First();
  416. if (!systemsByName.TryGetValue(parentName, out SystemResource? parent))
  417. return null;
  418. return ResolveSystemIp(parent, systemsByName, cache);
  419. }
  420. private async Task UpdateWithLockAsync(Action<List<Resource>> action) {
  421. await resourceCollection.FileLock.WaitAsync();
  422. try {
  423. await EnsureLoadedAsync();
  424. action(resourceCollection.Resources);
  425. // Always write current schema version when app writes the file.
  426. var root = new YamlRoot {
  427. Version = _currentSchemaVersion,
  428. Resources = resourceCollection.Resources,
  429. Connections = resourceCollection.Connections
  430. };
  431. await SaveRootAsync(root);
  432. }
  433. finally {
  434. resourceCollection.FileLock.Release();
  435. }
  436. }
  437. // ----------------------------
  438. // Versioning + migration
  439. // ----------------------------
  440. private async Task BackupOriginalAsync(string originalYaml) {
  441. // Timestamped backup for safe rollback
  442. var backupPath = $"{filePath}.bak.{DateTime.UtcNow:yyyyMMddHHmmss}";
  443. await fileStore.WriteAllTextAsync(backupPath, originalYaml);
  444. }
  445. private async Task SaveRootAsync(YamlRoot? root) {
  446. var contents = SerializeRootAsync(root);
  447. await fileStore.WriteAllTextAsync(filePath, contents);
  448. }
  449. public static string SerializeRootAsync(YamlRoot? root) {
  450. ISerializer serializer = new SerializerBuilder()
  451. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  452. .WithTypeConverter(new StorageSizeYamlConverter())
  453. .WithTypeConverter(new NotesStringYamlConverter())
  454. .ConfigureDefaultValuesHandling(
  455. DefaultValuesHandling.OmitNull |
  456. DefaultValuesHandling.OmitEmptyCollections
  457. )
  458. .Build();
  459. // Preserve ordering: version first, then resources
  460. Debug.Assert(root != null, nameof(root) + " != null");
  461. var payload = new OrderedDictionary {
  462. ["version"] = root.Version,
  463. ["resources"] = (root.Resources ?? new List<Resource>()).Select(SerializeResource).ToList(),
  464. ["connections"] = root.Connections ?? new List<Connection>()
  465. };
  466. return serializer.Serialize(payload);
  467. }
  468. private static string GetKind(Resource resource) {
  469. return resource switch {
  470. Server => "Server",
  471. Switch => "Switch",
  472. Firewall => "Firewall",
  473. Router => "Router",
  474. Desktop => "Desktop",
  475. Laptop => "Laptop",
  476. AccessPoint => "AccessPoint",
  477. Ups => "Ups",
  478. Other => "Other",
  479. SystemResource => "System",
  480. Service => "Service",
  481. _ => throw new InvalidOperationException($"Unknown resource type: {resource.GetType().Name}")
  482. };
  483. }
  484. public static OrderedDictionary SerializeResource(Resource resource) {
  485. var map = new OrderedDictionary {
  486. ["kind"] = GetKind(resource)
  487. };
  488. ISerializer serializer = new SerializerBuilder()
  489. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  490. .WithTypeConverter(new NotesStringYamlConverter())
  491. .ConfigureDefaultValuesHandling(
  492. DefaultValuesHandling.OmitNull |
  493. DefaultValuesHandling.OmitEmptyCollections
  494. )
  495. .Build();
  496. var yaml = serializer.Serialize(resource);
  497. Dictionary<string, object?> props = new DeserializerBuilder()
  498. .Build()
  499. .Deserialize<Dictionary<string, object?>>(yaml);
  500. foreach ((var key, var value) in props)
  501. if (!string.Equals(key, "kind", StringComparison.OrdinalIgnoreCase))
  502. map[key] = value;
  503. return map;
  504. }
  505. private static bool PortsMatch(PortReference a, PortReference b) {
  506. return a.Resource.Equals(b.Resource, StringComparison.OrdinalIgnoreCase)
  507. && a.PortGroup == b.PortGroup
  508. && a.PortIndex == b.PortIndex;
  509. }
  510. private async Task UpdateConnectionsWithLockAsync(Action<List<Connection>> action) {
  511. await resourceCollection.FileLock.WaitAsync();
  512. try {
  513. await EnsureLoadedAsync();
  514. action(resourceCollection.Connections);
  515. var root = new YamlRoot {
  516. Version = _currentSchemaVersion,
  517. Resources = resourceCollection.Resources,
  518. Connections = resourceCollection.Connections
  519. };
  520. await SaveRootAsync(root);
  521. }
  522. finally {
  523. resourceCollection.FileLock.Release();
  524. }
  525. }
  526. }
  527. public class YamlRoot {
  528. public int Version { get; set; }
  529. public List<Resource>? Resources { get; set; }
  530. public List<Connection>? Connections { get; set; }
  531. }