From ee848e3ebfd7c73b04dd419683be54fb450b8779 Mon Sep 17 00:00:00 2001 From: J Logan Date: Mon, 8 Jun 2026 15:02:18 -0700 Subject: [PATCH] Add backward compat for ContainerConfig `cpuOverhead`. (#1665) 1.0 data migration requirement --- .../Container/ContainerConfiguration.swift | 8 +++++++ .../ContainerConfigurationTests.swift | 22 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/Sources/ContainerResource/Container/ContainerConfiguration.swift b/Sources/ContainerResource/Container/ContainerConfiguration.swift index aa6a7e8e..b1f23491 100644 --- a/Sources/ContainerResource/Container/ContainerConfiguration.swift +++ b/Sources/ContainerResource/Container/ContainerConfiguration.swift @@ -160,6 +160,14 @@ public struct ContainerConfiguration: Sendable, Codable { public var cpuOverhead: Int = 1 public init() {} + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.cpus = try c.decodeIfPresent(Int.self, forKey: .cpus) ?? 4 + self.memoryInBytes = try c.decodeIfPresent(UInt64.self, forKey: .memoryInBytes) ?? 1024.mib() + self.storage = try c.decodeIfPresent(UInt64.self, forKey: .storage) + self.cpuOverhead = try c.decodeIfPresent(Int.self, forKey: .cpuOverhead) ?? 1 + } } public init( diff --git a/Tests/ContainerResourceTests/ContainerConfigurationTests.swift b/Tests/ContainerResourceTests/ContainerConfigurationTests.swift index fe1a350e..b1aafa0b 100644 --- a/Tests/ContainerResourceTests/ContainerConfigurationTests.swift +++ b/Tests/ContainerResourceTests/ContainerConfigurationTests.swift @@ -51,6 +51,28 @@ func makeTestConfiguration( return config } +struct ContainerConfigurationResourcesTests { + @Test func roundTripsCpuOverhead() throws { + var config = makeTestConfiguration() + config.resources.cpuOverhead = 2 + let data = try JSONEncoder().encode(config) + let decoded = try JSONDecoder().decode(ContainerConfiguration.self, from: data) + #expect(decoded.resources.cpuOverhead == 2) + } + + @Test func decodesMissingCpuOverheadAsDefault() throws { + let config = makeTestConfiguration() + let data = try JSONEncoder().encode(config) + var obj = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + var resources = try #require(obj["resources"] as? [String: Any]) + resources.removeValue(forKey: "cpuOverhead") + obj["resources"] = resources + let stripped = try JSONSerialization.data(withJSONObject: obj) + let decoded = try JSONDecoder().decode(ContainerConfiguration.self, from: stripped) + #expect(decoded.resources.cpuOverhead == 1) + } +} + struct ContainerConfigurationCreationDateTests { @Test func roundTripsCreationDate() throws { let when = Date(timeIntervalSince1970: 1_700_000_000)