diff --git a/.github/ISSUE_TEMPLATE/01-bug.yml b/.github/ISSUE_TEMPLATE/01-bug.yml new file mode 100644 index 0000000..992c052 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/01-bug.yml @@ -0,0 +1,74 @@ +name: Bug report +description: File a bug report. +title: "[Bug]: " +type: "Bug" +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + - type: checkboxes + id: prereqs + attributes: + label: I have done the following + description: Select that you have completed the following prerequisites. + options: + - label: I have searched the existing issues + required: true + - label: If possible, I've reproduced the issue using the 'main' branch of this project + required: false + - type: textarea + id: reproduce + attributes: + label: Steps to reproduce + description: Explain how to reproduce the incorrect behavior. + validations: + required: true + - type: textarea + id: what-happened + attributes: + label: Current behavior + description: A concise description of what you're experiencing. Screenshots or screen recordings are very helpful for UI issues. + validations: + required: true + - type: textarea + id: expected + attributes: + label: Expected behavior + description: A concise description of what you expected to happen. + validations: + required: true + - type: textarea + id: environment + attributes: + label: Environment + description: | + Examples: + - **OS**: macOS 26.2 (25C56) + - **Mac**: MacBook Pro, M3 Pro + - **Containers**: Version 1.0 (1) + - **Xcode** (if building from source): Version 26.2 (17C52) + value: | + - OS: + - Mac: + - Containers: + - Xcode: + render: markdown + validations: + required: true + - type: textarea + id: logs + attributes: + label: Relevant log output + description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks. + value: | + N/A + render: shell + - type: checkboxes + id: terms + attributes: + label: Code of Conduct + description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/try-containers/Containers/blob/main/CODE_OF_CONDUCT.md). + options: + - label: I agree to follow this project's Code of Conduct + required: true diff --git a/.github/ISSUE_TEMPLATE/02-feature.yml b/.github/ISSUE_TEMPLATE/02-feature.yml new file mode 100644 index 0000000..2c460f4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/02-feature.yml @@ -0,0 +1,24 @@ +name: Feature or enhancement request +description: File a request for a feature or enhancement +title: "[Request]: " +type: "Feature" +body: + - type: markdown + attributes: + value: | + Thanks for contributing to the Containers project! + - type: textarea + id: request + attributes: + label: Feature or enhancement request details + description: Describe your proposed feature or enhancement. Mockups or screenshots that show what's missing, or what new capabilities will be possible, are very helpful! Provide links to existing issues or external references/discussions, if appropriate. + validations: + required: true + - type: checkboxes + id: terms + attributes: + label: Code of Conduct + description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/try-containers/Containers/blob/main/CODE_OF_CONDUCT.md). + options: + - label: I agree to follow this project's Code of Conduct + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..3ba13e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..418b6ce --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,25 @@ +> [!IMPORTANT] +> For all but trivial fixes, make sure to first create a GitHub issue that concisely describes the bug or desired enhancement as justification for the change. Large PRs with no justifying issue will be closed. + +## Related Issue +Closes # + +## Type of Change +- [ ] Bug fix +- [ ] New feature +- [ ] Breaking change +- [ ] Documentation update + +## Motivation and Context +[Why is this change needed?] + +## Description +[What changed?] + +## Screenshots +[If you made changes to the UI, add a screenshot or video. Otherwise remove this section.] + +## Testing +- [ ] Tested locally +- [ ] Added/updated tests +- [ ] Added/updated docs diff --git a/.github/store_badge.svg b/.github/store_badge.svg deleted file mode 100755 index c36a76a..0000000 --- a/.github/store_badge.svg +++ /dev/null @@ -1,51 +0,0 @@ - - Download_on_the_Mac_App_Store_Badge_US-UK_RGB_blk_092917 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.github/workflows/containers-build-template.yml b/.github/workflows/containers-build-template.yml index a115992..f088ce8 100644 --- a/.github/workflows/containers-build-template.yml +++ b/.github/workflows/containers-build-template.yml @@ -13,7 +13,7 @@ on: jobs: buildAndTest: - name: Build and Test repo + name: Build and Test if: github.repository == 'try-containers/Containers' timeout-minutes: 60 runs-on: macos-26 @@ -40,19 +40,19 @@ jobs: run: | xcodebuild -resolvePackageDependencies \ -project Containers.xcodeproj \ - -scheme Development + -scheme "Containers (macOS)" - - name: Build Containers + - name: Build run: | set -o pipefail xcodebuild build \ -project Containers.xcodeproj \ - -scheme Development \ + -scheme "Containers (macOS)" \ -configuration "${BUILD_CONFIGURATION}" \ -destination 'platform=macOS' \ CODE_SIGNING_ALLOWED=NO - - name: Test ContainerSystem + - name: Test run: | set -o pipefail xcodebuild test \ diff --git a/.gitignore b/.gitignore index 06539a7..bd4d474 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ xcuserdata/ DerivedData/ .claude +Configuration/Local.xcconfig diff --git a/.swift-format b/.swift-format new file mode 100644 index 0000000..dcd6005 --- /dev/null +++ b/.swift-format @@ -0,0 +1,68 @@ +{ + "fileScopedDeclarationPrivacy" : { + "accessLevel" : "private" + }, + "indentation" : { + "spaces" : 4 + }, + "indentConditionalCompilationBlocks" : false, + "indentSwitchCaseLabels" : false, + "lineBreakAroundMultilineExpressionChainComponents" : false, + "lineBreakBeforeControlFlowKeywords" : false, + "lineBreakBeforeEachArgument" : false, + "lineBreakBeforeEachGenericRequirement" : false, + "lineLength" : 180, + "maximumBlankLines" : 1, + "multiElementCollectionTrailingCommas" : true, + "noAssignmentInExpressions" : { + "allowedFunctions" : [ + "XCTAssertNoThrow" + ] + }, + "prioritizeKeepingFunctionOutputTogether" : false, + "respectsExistingLineBreaks" : true, + "rules" : { + "AllPublicDeclarationsHaveDocumentation" : false, + "AlwaysUseLowerCamelCase" : true, + "AmbiguousTrailingClosureOverload" : false, + "BeginDocumentationCommentWithOneLineSummary" : false, + "DoNotUseSemicolons" : true, + "DontRepeatTypeInStaticProperties" : true, + "FileScopedDeclarationPrivacy" : true, + "FullyIndirectEnum" : true, + "GroupNumericLiterals" : true, + "IdentifiersMustBeASCII" : true, + "NeverForceUnwrap" : true, + "NeverUseForceTry" : true, + "NeverUseImplicitlyUnwrappedOptionals" : true, + "NoAccessLevelOnExtensionDeclaration" : true, + "NoAssignmentInExpressions" : true, + "NoBlockComments" : false, + "NoCasesWithOnlyFallthrough" : true, + "NoEmptyTrailingClosureParentheses" : true, + "NoLabelsInCasePatterns" : true, + "NoLeadingUnderscores" : false, + "NoParensAroundConditions" : true, + "NoPlaygroundLiterals" : true, + "NoVoidReturnOnFunctionSignature" : true, + "OmitExplicitReturns" : true, + "OneCasePerLine" : true, + "OneVariableDeclarationPerLine" : true, + "OnlyOneTrailingClosureArgument" : true, + "OrderedImports" : true, + "ReplaceForEachWithForLoop" : true, + "ReturnVoidInsteadOfEmptyTuple" : true, + "TypeNamesShouldBeCapitalized" : true, + "UseEarlyExits" : true, + "UseLetInEveryBoundCaseVariable" : true, + "UseShorthandTypeNames" : true, + "UseSingleLinePropertyGetter" : true, + "UseSynthesizedInitializer" : true, + "UseTripleSlashForDocumentationComments" : true, + "UseWhereClausesInForLoops" : false, + "ValidateDocumentationComments" : true + }, + "spacesAroundRangeFormationOperators" : false, + "tabWidth" : 2, + "version" : 1 +} diff --git a/.swift-format-nolint b/.swift-format-nolint new file mode 100644 index 0000000..8f600e5 --- /dev/null +++ b/.swift-format-nolint @@ -0,0 +1,68 @@ +{ + "fileScopedDeclarationPrivacy" : { + "accessLevel" : "private" + }, + "indentation" : { + "spaces" : 4 + }, + "indentConditionalCompilationBlocks" : false, + "indentSwitchCaseLabels" : false, + "lineBreakAroundMultilineExpressionChainComponents" : false, + "lineBreakBeforeControlFlowKeywords" : false, + "lineBreakBeforeEachArgument" : false, + "lineBreakBeforeEachGenericRequirement" : false, + "lineLength" : 180, + "maximumBlankLines" : 1, + "multiElementCollectionTrailingCommas" : true, + "noAssignmentInExpressions" : { + "allowedFunctions" : [ + "XCTAssertNoThrow" + ] + }, + "prioritizeKeepingFunctionOutputTogether" : false, + "respectsExistingLineBreaks" : true, + "rules" : { + "AllPublicDeclarationsHaveDocumentation" : false, + "AlwaysUseLowerCamelCase" : false, + "AmbiguousTrailingClosureOverload" : false, + "BeginDocumentationCommentWithOneLineSummary" : false, + "DoNotUseSemicolons" : true, + "DontRepeatTypeInStaticProperties" : false, + "FileScopedDeclarationPrivacy" : false, + "FullyIndirectEnum" : false, + "GroupNumericLiterals" : false, + "IdentifiersMustBeASCII" : false, + "NeverForceUnwrap" : false, + "NeverUseForceTry" : false, + "NeverUseImplicitlyUnwrappedOptionals" : false, + "NoAccessLevelOnExtensionDeclaration" : false, + "NoAssignmentInExpressions" : false, + "NoBlockComments" : false, + "NoCasesWithOnlyFallthrough" : false, + "NoEmptyTrailingClosureParentheses" : true, + "NoLabelsInCasePatterns" : false, + "NoLeadingUnderscores" : false, + "NoParensAroundConditions" : true, + "NoPlaygroundLiterals" : false, + "NoVoidReturnOnFunctionSignature" : true, + "OmitExplicitReturns" : false, + "OneCasePerLine" : true, + "OneVariableDeclarationPerLine" : true, + "OnlyOneTrailingClosureArgument" : false, + "OrderedImports" : true, + "ReplaceForEachWithForLoop" : false, + "ReturnVoidInsteadOfEmptyTuple" : false, + "TypeNamesShouldBeCapitalized" : false, + "UseEarlyExits" : false, + "UseLetInEveryBoundCaseVariable" : false, + "UseShorthandTypeNames" : true, + "UseSingleLinePropertyGetter" : true, + "UseSynthesizedInitializer" : false, + "UseTripleSlashForDocumentationComments" : true, + "UseWhereClausesInForLoops" : false, + "ValidateDocumentationComments" : false + }, + "spacesAroundRangeFormationOperators" : false, + "tabWidth" : 2, + "version" : 1 +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..2249e11 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,114 @@ +# AGENTS.md + +Guidance for coding agents working in this repository. + +## Build / Test / Format + +The project is a single Xcode project with two schemes: + +- `Containers (macOS)` builds the app and the `ContainerSystem` framework it embeds. +- `ContainerSystemTests` runs the framework's tests. The app target has no tests. + +Signing reads `DEVELOPMENT_TEAM` from `Configuration/Local.xcconfig`, which is ignored by git. Copy `Configuration/Local.xcconfig.example` and fill in a team ID. + +```bash +xcodebuild -project Containers.xcodeproj -scheme 'Containers (macOS)' build +``` + +```bash +xcodebuild -project Containers.xcodeproj -scheme ContainerSystemTests test +``` + +```bash +xcrun swift-format lint -r --configuration .swift-format Containers ContainerSystem ContainerSystemTests +``` + +- The app target runs the same lint as a build phase, so warnings show up in every build. Keep it clean. +- `.swift-format` and `.swift-format-nolint` hold the project's style. Don't change them. Format only the files you touched: `xcrun swift-format format -i --configuration .swift-format `. Never run it with `respectsExistingLineBreaks: false`. +- `Builder.pb.swift` and `Builder.grpc.swift` are generated from BuildKit's protocol. Don't edit them. + +## Architecture + +The app runs Linux containers with Apple's [Containerization](https://github.com/apple/containerization) package, in process: the engine runs as actors inside the sandboxed app, with no separate server, XPC service or helper processes. + +Calls flow in one direction: + +``` +SwiftUI / AppKit views + → Managers (ContainerSystem, @MainActor, public) + → Services (ContainerSystem, actors, internal) + → Containerization +``` + +- `ContainerRuntime` (`ContainerRuntime.shared`) owns the services and the runtime's shared state: system status, setup progress and reports. It also installs the prerequisites (kernel, init image) on first start. +- Managers are thin handles over the runtime, one per domain. `ImageManager()` uses the shared runtime; tests pass a `MockContainerRuntime` through `init(testRuntime:)`. +- Services are the engine: internal actors that hold the state of containers, images and kernels. Only managers call them. +- Progress is Foundation's `Progress`. A method that reports progress takes `progress: Progress? = nil`, sets `totalUnitCount` to its own steps and runs each with `progress.performStep("…") { step in … }` (`Progress/Progress+Steps.swift`). Callers compose operations by weighting steps with `pendingUnitCount`. +- Failed work is recorded by `ReportManager` into `ReportStore`: a plist manifest plus one gzipped body per report. +- Errors are thrown as they are. Views turn them into an `ErrorAlert`; the framework and app models never build alerts. + +## ContainerSystem layout + +Role first, with domains inside each role: + +- `Managers/`: `ContainerManager`, `ImageManager`, `VolumeManager`, `NetworkManager`, `SystemManager`, `ReportManager`. +- `Services/`: `ContainersService`, `ImagesService`, `KernelService`. +- `Container/`, `Image/`, `Network/`, `Volume/`: value types for each domain (`ContainerConfiguration`, `ContainerSnapshot`, `ImageSummary`, `VolumeSummary`, …). +- `Build/`: the BuildKit client. `Builder/` holds the gRPC client and the builder container's controller; `BuildPipeline/` handles the stream, split by concern (`+ImageResolver`, `+ContentStore`, `+FSSync`, `+Export`, `+Stdio`). +- `Persistence/`, `Plugin/`, `Log/`, `Progress/`, `Reports/`, `Common/`: one folder per infrastructure concern. + +## Containers (app) layout + +Layer first, like Apple's SwiftUI samples: + +- `ContainersApp.swift`: scenes, window IDs and the objects put in the environment. +- `Models/`: value types, grouped by feature to mirror `Views/` (`Containers/`, `Images/`, `Volumes/`, `Reports/`, `Dashboard/`, `Shared/`). Models never fetch or do work. +- `ViewModels/`: `@Observable` objects a single view creates and owns with `@State` (`RegistryLookup`). +- `Utilities/`: `@Observable` objects the app owns and shares through the environment (`ActivityCenter`, `SystemActions`), plus support types (`ProgressObserver`, `WindowResizer`). +- `Controllers/`: AppKit controllers only, such as the `NSToolbarDelegate` objects. Their `NSViewRepresentable` binders live in `Views/`. +- `Views//`: one folder per screen. `Views/Shared/` holds complete units that appear once on a screen (`TableView`, `DetailView`, `CreateView`, `ScopeBar`). `Views/Components/` holds small reusable elements that can repeat on a screen (`BarToggle`, `SearchToken`, form rows). +- `Extensions/`: one `Type+Topic.swift` per extension. +- `Supporting Files/`: Info.plist, assets and entitlements. Don't rename it; the Info.plist membership exception depends on the path. + +Rules for where logic goes: + +- Split a large view into subviews or modifiers first. Add a view model only when that isn't enough. +- Exactly one place drives each fetch: a view, its view model, or an app-owned object. Fetching for display never happens in a model. +- Form state for a sheet lives in value models (`ImagePullRequest`, `ImageBuildRequest`, `ImageLoadRequest`) with an `isComplete` check. +- Long-running work (pull, build, create, start) runs through `ActivityCenter`, so its progress and failures show on the item's row. + +## Naming + +- Suffixes mean one thing each: + - `Store`: persistence (`ReportStore`, `DefaultsStore`). + - `Manager`: a framework facade. + - `Service`: a framework engine actor. + - `Controller`: an AppKit controller. + - `Center`: an app-wide hub (`ActivityCenter`). +- Entries in a table are `…Item` (`ContainerItem`); framework list results are `…Summary`; value copies of live state are `…Snapshot`; a description of one operation to perform is `…Request`; a lifecycle enum is a nested `Status` (`SystemManager.Status`). +- Where a type mirrors one in Containerization, keep Apple's name and shape. +- Extension files are `Type+Topic.swift`, never `Type+Extensions.swift`. One primary type per file. + +## Conventions + +- **Concurrency:** Swift 6 language mode. The app target defaults to `MainActor` isolation; the framework is nonisolated by default. Add `nonisolated` only where the compiler needs it (table sort key paths, `Layout`, AppKit overrides that AppKit calls off the main actor), and group such constants in a `nonisolated` enum rather than marking each one. +- **Layout:** write like Apple's Containerization code. 180 columns is a ceiling, not a target: most lines stay under about 110. A call or signature that gets long goes one argument per line, with `)` on its own line. Don't nest a call inside another call's arguments (`append(Item(…))`); name the value first. Long `if`/`guard` conditions break at their commas, with `else {` on its own line. Blank lines contain no spaces. +- **Comments:** few, around 6% of lines. Comment only where the code would otherwise be "fixed" into something broken: an AppKit or SwiftUI ordering constraint, an API contract, an isolation assumption. State the reason itself. Don't narrate what the code does, record history, or justify a design by pointing at another app ("as Xcode does"). +- **`let` over `var`:** a stored property is `var` only when something writes it after creation, such as a binding, a modified copy or state filled in later. +- **Native over forced:** accept AppKit's and SwiftUI's own sizing, toolbar behavior and dividers instead of working around them. The dashboard and detail toolbars are AppKit's for that reason. +- **Foundation first:** prefer platform APIs (`Progress`, `URLCache`, `@AppStorage` for state a view keeps in user defaults) over hand-written equivalents. +- **Unreleased:** the app hasn't shipped. Renaming storage keys, folders or labels needs no migration code yet. + +## Tests + +- Swift Testing only. Tests cover `ContainerSystem` and don't start virtual machines. +- One suite per file: `FooTests.swift` holds `@Suite("Foo") struct FooTests`, with traits after the name (`@Suite("Volume manager", .serialized)`). +- Tests read `@Test("Short sentence-case phrase") func camelCaseName()`, with no `test` prefix. +- Each test works in its own `TemporaryDirectory` (`ContainerSystemTests/Support`) and removes it with `defer`. Tests that need managers use `MockContainerRuntime` (`ContainerSystemTests/Mocks`); service tests build the service directly over a temporary folder. + +## Requirements + +- macOS 26 or later on Apple silicon. +- Xcode 26 or later, Swift 6. +- [apple/containerization](https://github.com/apple/containerization) 0.28.0 or later, up to the next major version, through Swift Package Manager. +- The Linux kernel and init image are downloaded when the app first starts the container system. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6002dc2..1ecd663 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,42 +1,104 @@ -# Contribute to Containers +# Containers Contributor’s Guide -## Explore Issues +Welcome to the Containers community, and thank you for contributing! +This guide explains how to get involved. -Find issues from the [Issues tab](https://github.com/try-containers/Containers/issues). If you find an issue you want to work on, please indicate it in the issue and/or attach a draft PR once available. An admin or maintainer will then assign the Issue and/or PR to you. +* [Licensing](#licensing) +* [Issue Tracking](#issue-tracking) +* [Pull Requests](#pull-requests) +* [AI Contribution Guidelines](#ai-contribution-guidelines) +* [Code of Conduct](#code-of-conduct) +* [Maintainers](#maintainers) -> [!IMPORTANT] -> Please make sure to first comment under an issue or ask a maintainer to assign you to the issue before working on it. This helps prevent multiple people from working on the same -> thing, which could result in your work not being merged. Additionally, some issues might be reserved for those with more in-depth knowledge of the codebase. +## Licensing + +The source code of Containers is released under the +[PolyForm Noncommercial License 1.0.0](LICENSE.md), and the app is distributed +on the Mac App Store, which requires Apple's own end-user license terms for the +shipped binary. -## Code Style +By submitting a pull request or otherwise contributing to this project, you +agree that: -Please follow the [Google Swift Style Guide](https://google.github.io/swift/). +1. You are the author of your contribution, or you otherwise have the right to + submit it under these terms. +2. You grant Axel Martinez a perpetual, worldwide, irrevocable, royalty-free + license to use, reproduce, modify, and distribute your contribution as part + of Containers — both under the project license and under the license terms + required by app store distribution channels, including Apple's Licensed + Application End User License Agreement. +3. You retain copyright in your contribution. -## Pull Request +This exists solely so the project can ship through the App Store without a +licensing conflict. It does not transfer ownership of your work. -Once you are happy with your changes, submit a `Pull Request`. +## Issue Tracking -The pull request opens with a template loaded. Fill out all fields that are relevant. +To file a bug or feature request, use [GitHub](https://github.com/try-containers/Containers/issues/new/choose) +and fill in the template for it. -The `PR` should include following information: -* A descriptive **title** on what changed. -* A detailed **description** of changes. -* If you made changes to the UI please add a **screenshot** or **video** as well. -* If there is a related issue please add a **reference to the issue**. If not, create one beforehand and link it. -* If your PR is still in progress mark it as **Draft**. +Before working on an issue, comment on it or ask a maintainer to assign it to you. +This prevents multiple people from working on the same thing. -### Checks, Tests & Documentation +## Pull Requests -Request a review from one of our admins @armartinez +When preparing a pull request, follow this checklist: -> [!TIP] -> If it is your first PR, an admin will need to request a review for you. +* Imitate the conventions of surrounding code. +* Set your own `DEVELOPMENT_TEAM` in `Configuration/Local.xcconfig` (copy it from `Configuration/Local.xcconfig.example`) rather than in Xcode's Signing & Capabilities tab, which writes it into the project file. +* Format code as described in [Formatting contributions](#formatting-contributions) (otherwise the build will fail). +* Verify that the app builds and that the unit tests pass (`xcodebuild test -project Containers.xcodeproj -scheme ContainerSystemTests -destination 'platform=macOS'`). +* If you changed the UI, add a screenshot or video to the pull request. +* Follow the [seven rules](https://cbea.ms/git-commit/#seven-rules) of great Git commit messages: + * Separate subject from body with a blank line. + * Limit the subject line to 50 characters.[^not-enforced] + * Capitalize the subject line. + * Do not end the subject line with a period. + * Use the imperative mood in the subject line. + * Wrap the body at 72 characters.[^not-enforced] + * Use the body to explain what and why vs. how. > [!IMPORTANT] -> Please resolve all `Violation` errors in Xcode (except: _TODO:_ warnings). Otherwise the swiftlint check on GitHub will fail. +> If you plan to make substantial changes or add new features, +> we encourage you to first discuss them by filing a [GitHub Issue](https://github.com/try-containers/Containers/issues/new/choose). +> This will save time and increases the chance of your pull request being accepted. -Once you submit the `PR` GitHub will run a couple of actions which run tests and `SwiftLint` (this can take a couple of minutes). Should a test fail, it cannot be merged until tests succeed. +[^not-enforced]: This rule is not enforced in the Containers project. -Make sure to resolve all merge-conflicts otherwise the `PR` cannot be merged. -> [!IMPORTANT] -> Make sure your code is well documented so others can interact with your code easily! +### Formatting contributions + +Make sure your contributions are consistent with the rest of the project's formatting. Format only the Swift files you changed, using `swift format` and the project's `.swift-format` configuration, so the pull request doesn't pick up changes to files you didn't touch: + +```bash +{ git diff --name-only --diff-filter=d main -- '*.swift'; git ls-files --others --exclude-standard -- '*.swift'; } | sort -u | xargs swift format --configuration .swift-format -i +``` + +This covers every Swift file your branch adds or changes compared with `main`, committed or not. The build runs the linter, so you can check the result before pushing: + +```bash +swift format lint --recursive --configuration .swift-format Containers ContainerSystem ContainerSystemTests +``` + +### .gitignore contributions + +We do not currently accept contributions to add editor specific additions to the root `.gitignore`. We urge contributors to make a global `.gitignore` file with the rulesets they may want to add instead. A global `.gitignore` file can be set like so: + +```bash +git config --global core.excludesfile ~/.gitignore +``` + +## AI Contribution Guidelines + +We welcome thoughtful use of AI tools in your contributions to this repository. We ask that you adhere to these rules in order to preserve the project's integrity, clarity, and quality, and to respect maintainer bandwidth: + +* You should be able to explain and justify every line of code or documentation that was generated or assisted by AI. Your submission should reflect your own understanding and intent. +* Use AI to augment, not totally replace, your reasoning or familiarity, especially for non-trivial parts of the system. +* Avoid dumping AI-generated walls of text that you cannot explain. Low-effort, unexplained submissions will be deprioritized to protect maintainer bandwidth. + +## Code of Conduct + +To clarify what is expected of our contributors and community members, Containers has adopted the code of conduct defined by the Contributor Covenant. For more detail, please read the [Code of Conduct](CODE_OF_CONDUCT.md). + +## Maintainers + +The project’s maintainer is [@armartinez](https://github.com/armartinez). Request a review from them once your pull request is ready. diff --git a/Configuration/Base.xcconfig b/Configuration/Base.xcconfig new file mode 100644 index 0000000..db58430 --- /dev/null +++ b/Configuration/Base.xcconfig @@ -0,0 +1,2 @@ +// Signing settings live in the untracked Local.xcconfig; copy Local.xcconfig.example to create it. +#include? "Local.xcconfig" diff --git a/Configuration/Local.xcconfig.example b/Configuration/Local.xcconfig.example new file mode 100644 index 0000000..f7b09bc --- /dev/null +++ b/Configuration/Local.xcconfig.example @@ -0,0 +1 @@ +DEVELOPMENT_TEAM = YOUR_TEAM_ID diff --git a/ContainerSystem/Build/BuildPipeline/BuildPipeline+ContentStore.swift b/ContainerSystem/Build/BuildPipeline/BuildPipeline+ContentStore.swift new file mode 100644 index 0000000..1f4c33e --- /dev/null +++ b/ContainerSystem/Build/BuildPipeline/BuildPipeline+ContentStore.swift @@ -0,0 +1,127 @@ +// +// BuildPipeline+ContentStore.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import Containerization +import ContainerizationOCI +import Foundation + +extension BuildPipeline { + func handleContentStoreRequest( + _ imageTransfer: ImageTransfer, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + let method = imageTransfer.metadata["method"] + + switch method { + case "/containerd.services.content.v1.Content/Info": + try await handleContentStoreInfo(imageTransfer, sender: sender, buildID: buildID) + case "/containerd.services.content.v1.Content/ReaderAt": + try await handleContentStoreReaderAt(imageTransfer, sender: sender, buildID: buildID) + default: + logger.error("Unknown content-store method: \(method ?? "nil")") + } + } + + private func handleContentStoreInfo( + _ packet: ImageTransfer, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + // BuildKit is asking for information about a blob in the content store + let digest = packet.tag + + // Get the blob descriptor from content store + let descriptor = try await contentStore.get(digest: digest) + let size = try descriptor?.size() + + var transfer = ImageTransfer() + transfer.id = packet.id + transfer.tag = digest + transfer.metadata = [ + "os": "linux", + "stage": "content-store", + "method": "/containerd.services.content.v1.Content/Info", + ] + if let size = size { + transfer.metadata["size"] = String(size) + } + transfer.complete = true + transfer.direction = .into + + var response = ClientStream() + response.buildID = buildID + response.imageTransfer = transfer + response.packetType = .imageTransfer(transfer) + sender.yield(response) + } + + private func handleContentStoreReaderAt( + _ packet: ImageTransfer, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + // BuildKit is asking to read data from a blob + let digest = packet.descriptor.digest + let offset = UInt64(packet.metadata["offset"] ?? "0") ?? 0 + let length = Int(packet.metadata["length"] ?? "0") ?? 0 + + guard let descriptor = try await contentStore.get(digest: digest) else { + logger.error("Blob not found in content store: \(digest)") + throw BuilderError.imageNotInContentStore(digest) + } + + // If offset and length are both 0, this is a metadata request (just size) + if offset == 0 && length == 0 { + let size = try descriptor.size() + var transfer = ImageTransfer() + transfer.id = packet.id + transfer.tag = digest + transfer.metadata = [ + "os": "linux", + "stage": "content-store", + "method": "/containerd.services.content.v1.Content/ReaderAt", + "size": String(size), + ] + transfer.complete = true + transfer.direction = .into + transfer.data = Data() + + var response = ClientStream() + response.buildID = buildID + response.imageTransfer = transfer + response.packetType = .imageTransfer(transfer) + sender.yield(response) + return + } + + // Read the blob data at the requested offset and length + guard let data = try descriptor.data(offset: offset, length: length) + else { + logger.error("Failed to read data from content store: digest=\(digest), offset=\(offset), length=\(length)") + throw BuilderError.imageNotInContentStore(digest) + } + + var transfer = ImageTransfer() + transfer.id = packet.id + transfer.tag = digest + transfer.metadata = [ + "os": "linux", + "stage": "content-store", + "method": "/containerd.services.content.v1.Content/ReaderAt", + ] + transfer.complete = true + transfer.direction = .into + transfer.data = data + + var response = ClientStream() + response.buildID = buildID + response.imageTransfer = transfer + response.packetType = .imageTransfer(transfer) + sender.yield(response) + } +} diff --git a/ContainerSystem/Build/BuildPipeline/BuildPipeline+Export.swift b/ContainerSystem/Build/BuildPipeline/BuildPipeline+Export.swift new file mode 100644 index 0000000..af411cc --- /dev/null +++ b/ContainerSystem/Build/BuildPipeline/BuildPipeline+Export.swift @@ -0,0 +1,84 @@ +// +// BuildPipeline+Export.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import Containerization +import Foundation + +extension BuildPipeline { + func handleExportTransfer( + _ buildTransfer: BuildTransfer, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + // BuildKit is trying to write export data through the filesync protocol + // We need to receive the data and write it to the export directory + + logger.info( + "Export transfer: direction=\(buildTransfer.direction), complete=\(buildTransfer.complete), source=\(buildTransfer.source), dataSize=\(buildTransfer.data.count)" + ) + + guard let exportPath = exportDestination(for: buildTransfer) else { + logger.error("Could not resolve export destination for: \(buildTransfer.source)") + return + } + + logger.info("Writing export data to: \(exportPath.path)") + + // Create parent directory if needed + let parentDir = exportPath.deletingLastPathComponent() + try? FileManager.default.createDirectory(at: parentDir, withIntermediateDirectories: true) + + // Write or append the data + if buildTransfer.data.count > 0 { + if FileManager.default.fileExists(atPath: exportPath.path) { + // Append to existing file + let fileHandle = try FileHandle(forWritingTo: exportPath) + defer { try? fileHandle.close() } + try fileHandle.seekToEnd() + try fileHandle.write(contentsOf: buildTransfer.data) + } else { + // Create new file + try buildTransfer.data.write(to: exportPath) + } + } + + // Send acknowledgment back to BuildKit + var response = ClientStream() + response.buildID = buildID + response.buildTransfer = BuildTransfer() + response.buildTransfer.id = buildTransfer.id + response.buildTransfer.source = buildTransfer.source + response.buildTransfer.complete = true + response.buildTransfer.direction = .outof + response.buildTransfer.metadata = ["os": "linux"] + + response.packetType = .buildTransfer(response.buildTransfer) + sender.yield(response) + + if buildTransfer.complete { + logger.info("Export transfer complete for: \(exportPath.path)") + } + } + + private func exportDestination(for buildTransfer: BuildTransfer) -> URL? { + let sourceLastPathComponent = URL(fileURLWithPath: buildTransfer.source) + .lastPathComponent + let destinations = config.exports.compactMap(\.destination) + + if let matchingDestination = destinations.first(where: { + $0.lastPathComponent == sourceLastPathComponent + }) { + return matchingDestination + } + + guard destinations.count == 1 else { + return nil + } + + return destinations[0] + } +} diff --git a/ContainerSystem/Build/BuildPipeline/BuildPipeline+FSSync.swift b/ContainerSystem/Build/BuildPipeline/BuildPipeline+FSSync.swift new file mode 100644 index 0000000..39a386a --- /dev/null +++ b/ContainerSystem/Build/BuildPipeline/BuildPipeline+FSSync.swift @@ -0,0 +1,426 @@ +// +// BuildPipeline+FSSync.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import ContainerizationArchive +import ContainerizationOS +import CryptoKit +import Foundation + +extension BuildPipeline { + func handleFSSyncTransfer( + _ buildTransfer: BuildTransfer, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + guard let method = buildTransfer.metadata["method"] else { + logger.error("BuildTransfer missing method") + return + } + + let contextDir = URL(fileURLWithPath: config.contextDir) + + switch method { + case "Read": + try await handleFSSyncRead( + buildTransfer, + contextDir: contextDir, + sender: sender, + buildID: buildID + ) + case "Info": + try await handleFSSyncInfo( + buildTransfer, + contextDir: contextDir, + sender: sender, + buildID: buildID + ) + case "Walk": + try await handleFSSyncWalk( + buildTransfer, + contextDir: contextDir, + sender: sender, + buildID: buildID + ) + default: + logger.error("Unknown FSSync method: \(method)") + } + } + + private func handleFSSyncRead( + _ packet: BuildTransfer, + contextDir: URL, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + let path = contextDir.appendingPathComponent(packet.source) + .standardizedFileURL + + // Read file data + let data: Data + + if FileManager.default.fileExists(atPath: path.path) { + let offset = UInt64(packet.metadata["offset"] ?? "0") ?? 0 + let length = Int(packet.metadata["length"] ?? "0") ?? 0 + + if path.hasDirectoryPath == true { + data = Data() + } else { + let fileData = try Data(contentsOf: path) + if offset == 0 && length == 0 { + data = fileData + } else { + let start = Int(offset) + let end = length > 0 ? start + length : fileData.count + data = fileData.subdata(in: start...Continuation, + buildID: String + ) async throws { + let path = contextDir.appendingPathComponent(packet.source) + .standardizedFileURL + + var response = ClientStream() + response.buildID = buildID + response.buildTransfer = BuildTransfer() + response.buildTransfer.id = packet.id + response.buildTransfer.source = packet.source + response.buildTransfer.complete = true + response.buildTransfer.direction = .outof + response.buildTransfer.isDirectory = path.hasDirectoryPath + response.buildTransfer.metadata = ["os": "linux", "stage": "fssync"] + + // Add file metadata if file exists + if FileManager.default.fileExists(atPath: path.path), + let attrs = try? FileManager.default.attributesOfItem(atPath: path.path) + { + if let size = attrs[.size] as? UInt64 { + response.buildTransfer.metadata["size"] = String(size) + } + if let mode = attrs[.posixPermissions] as? NSNumber { + response.buildTransfer.metadata["mode"] = String(mode.uint32Value) + } + if let modDate = attrs[.modificationDate] as? Date { + let formatter = ISO8601DateFormatter() + response.buildTransfer.metadata["modified_at"] = formatter.string(from: modDate) + } + response.buildTransfer.metadata["uid"] = "0" + response.buildTransfer.metadata["gid"] = "0" + } + + response.packetType = .buildTransfer(response.buildTransfer) + sender.yield(response) + } + + private func handleFSSyncWalk( + _ packet: BuildTransfer, + contextDir: URL, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + let mode = packet.metadata["mode"] ?? "json" + let followPaths = packet.metadata["followpaths"]?.split(separator: ",").map(String.init) ?? [] + + logger.info("FSSync walk: contextDir=\(contextDir.path), mode=\(mode), followpaths=\(followPaths)") + + let matchedFiles = try matchPaths(contextDir: contextDir, followPaths: followPaths) + + logger.info( + "FSSync walk matched \(matchedFiles.count) files: \(matchedFiles.prefix(5).map { $0.relativePath })" + ) + + if mode == "tar" { + try await sendTarWalk( + packet: packet, + contextDir: contextDir, + files: matchedFiles, + sender: sender, + buildID: buildID + ) + } else { + try sendJSONWalk( + packet: packet, + contextDir: contextDir, + files: matchedFiles, + sender: sender, + buildID: buildID + ) + } + } + + private struct MatchedFile { + let url: URL + let relativePath: String + let isDirectory: Bool + } + + private func matchPaths(contextDir: URL, followPaths: [String]) throws -> [MatchedFile] { + let fm = FileManager.default + let root = contextDir.standardizedFileURL + var results: [MatchedFile] = [] + + for pattern in followPaths { + let candidate = root.appendingPathComponent(pattern) + if fm.fileExists(atPath: candidate.path) { + let attrs = try fm.attributesOfItem(atPath: candidate.path) + let isDir = (attrs[.type] as? FileAttributeType) == .typeDirectory + results.append(MatchedFile(url: candidate, relativePath: pattern, isDirectory: isDir)) + } + } + + results.sort { $0.relativePath < $1.relativePath } + return results + } + + private func sendJSONWalk( + packet: BuildTransfer, + contextDir: URL, + files: [MatchedFile], + sender: AsyncStream.Continuation, + buildID: String + ) throws { + let fm = FileManager.default + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime] + + let fileInfos = try files.map { match -> FSSyncFileInfo in + let attrs = try fm.attributesOfItem(atPath: match.url.path) + let size = (attrs[.size] as? UInt64) ?? 0 + let mode = (attrs[.posixPermissions] as? NSNumber)?.uint32Value ?? 0o644 + let modDate = (attrs[.modificationDate] as? Date) ?? Date() + let target: String = { + guard + (attrs[.type] as? FileAttributeType) == .typeSymbolicLink + else { return "" } + return (try? fm.destinationOfSymbolicLink(atPath: match.url.path)) + ?? "" + }() + return FSSyncFileInfo( + name: match.relativePath, + modTime: formatter.string(from: modDate), + mode: mode, + size: size, + isDir: match.isDirectory, + uid: 0, + gid: 0, + target: target + ) + } + + var response = ClientStream() + response.buildID = buildID + response.buildTransfer = BuildTransfer() + response.buildTransfer.id = packet.id + response.buildTransfer.source = packet.source + response.buildTransfer.complete = true + response.buildTransfer.direction = .outof + response.buildTransfer.metadata = ["os": "linux", "stage": "fssync", "mode": "json"] + response.buildTransfer.data = try JSONEncoder().encode(fileInfos) + response.packetType = .buildTransfer(response.buildTransfer) + sender.yield(response) + } + + private func sendTarWalk( + packet: BuildTransfer, + contextDir: URL, + files: [MatchedFile], + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + let tarURL = URL(fileURLWithPath: NSTemporaryDirectory()) + .appendingPathComponent(UUID().uuidString + ".tar") + defer { try? FileManager.default.removeItem(at: tarURL) } + + let hash = try writeTar(files: files, contextDir: contextDir, destination: tarURL) + let hashString = hash.compactMap { String(format: "%02x", $0) }.joined() + + logger.info("FSSync tar walk created \(tarURL.lastPathComponent) hash=\(hashString)") + + // Send header packet with hash (no data yet) + var header = BuildTransfer() + header.id = packet.id + header.source = tarURL.path + header.complete = false + header.direction = .outof + header.metadata = ["os": "linux", "stage": "fssync", "mode": "tar", "hash": hashString] + var headerResp = ClientStream() + headerResp.buildID = buildID + headerResp.buildTransfer = header + headerResp.packetType = .buildTransfer(header) + sender.yield(headerResp) + + // Stream tar file in chunks + let chunkSize = 1 << 20 // 1 MiB + guard let handle = try? FileHandle(forReadingFrom: tarURL) else { + throw BuilderError.imageMissing + } + defer { try? handle.close() } + + while true { + let chunk = handle.readData(ofLength: chunkSize) + if chunk.isEmpty { break } + + var part = BuildTransfer() + part.id = packet.id + part.source = tarURL.path + part.complete = false + part.direction = .outof + part.metadata = ["os": "linux", "stage": "fssync", "mode": "tar"] + part.data = chunk + + var partResp = ClientStream() + partResp.buildID = buildID + partResp.buildTransfer = part + partResp.packetType = .buildTransfer(part) + sender.yield(partResp) + } + + // Final packet (complete=true, no data) + var done = BuildTransfer() + done.id = packet.id + done.source = tarURL.path + done.complete = true + done.direction = .outof + done.metadata = ["os": "linux", "stage": "fssync", "mode": "tar"] + + var doneResp = ClientStream() + doneResp.buildID = buildID + doneResp.buildTransfer = done + doneResp.packetType = .buildTransfer(done) + sender.yield(doneResp) + } + + private func writeTar(files: [MatchedFile], contextDir: URL, destination: URL) throws -> SHA256.Digest { + let fm = FileManager.default + + try? fm.removeItem(at: destination) + + let config = ArchiveWriterConfiguration(format: .paxRestricted, filter: .none) + let writer = try ArchiveWriter(configuration: config) + + try writer.open(file: destination) + + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + + var hasher = SHA256() + + for match in files { + let attrs = try fm.attributesOfItem(atPath: match.url.path) + let entry = WriteEntry() + entry.path = match.relativePath + + if let fileType = attrs[.type] as? FileAttributeType { + switch fileType { + case .typeDirectory: + entry.fileType = .directory + case .typeSymbolicLink: + entry.fileType = .symbolicLink + entry.symlinkTarget = (try? fm.destinationOfSymbolicLink(atPath: match.url.path)) ?? "" + case .typeRegular: + entry.fileType = .regular + default: + continue + } + } + + if let perms = attrs[.posixPermissions] as? NSNumber { + #if os(macOS) + entry.permissions = perms.uint16Value + #else + entry.permissions = perms.uint32Value + #endif + } + + if let size = attrs[.size] as? UInt64 { + entry.size = Int64(size) + } + + entry.owner = 0 + entry.group = 0 + + if let modDate = attrs[.modificationDate] as? Date { + entry.modificationDate = modDate + } + + hasher.update(data: try encoder.encode(entry)) + + if entry.fileType == .regular { + let data = try Data(contentsOf: match.url) + hasher.update(data: data) + try writer.writeEntry(entry: entry, data: data) + } else { + try writer.writeEntry(entry: entry, data: nil) + } + } + + try writer.finishEncoding() + return hasher.finalize() + } +} + +private struct FSSyncFileInfo: Codable { + let name: String + let modTime: String + let mode: UInt32 + let size: UInt64 + let isDir: Bool + let uid: UInt32 + let gid: UInt32 + let target: String +} + +extension WriteEntry: @retroactive Encodable { + enum CodingKeys: String, CodingKey { + case path + case fileType + case size + case permissions + case owner + case group + case symlinkTarget + case hardlink + case creationDate + case modificationDate + case contentAccessDate + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(fileType.rawValue, forKey: .fileType) + try container.encodeIfPresent(permissions, forKey: .permissions) + try container.encodeIfPresent(path, forKey: .path) + try container.encodeIfPresent(size, forKey: .size) + try container.encodeIfPresent(owner, forKey: .owner) + try container.encodeIfPresent(group, forKey: .group) + try container.encodeIfPresent(symlinkTarget, forKey: .symlinkTarget) + try container.encodeIfPresent(hardlink, forKey: .hardlink) + try container.encodeIfPresent(creationDate, forKey: .creationDate) + try container.encodeIfPresent(modificationDate, forKey: .modificationDate) + try container.encodeIfPresent(contentAccessDate, forKey: .contentAccessDate) + } +} diff --git a/ContainerSystem/Build/BuildPipeline/BuildPipeline+ImageResolver.swift b/ContainerSystem/Build/BuildPipeline/BuildPipeline+ImageResolver.swift new file mode 100644 index 0000000..7566d1c --- /dev/null +++ b/ContainerSystem/Build/BuildPipeline/BuildPipeline+ImageResolver.swift @@ -0,0 +1,130 @@ +// +// BuildPipeline+ImageResolver.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import Containerization +import ContainerizationOCI +import Foundation + +extension BuildPipeline { + func handleImageTransfer( + _ imageTransfer: ImageTransfer, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + let stage = imageTransfer.metadata["stage"] + let method = imageTransfer.metadata["method"] + + // Handle resolver requests + if stage == "resolver" && method == "/resolve" { + try await handleResolverRequest(imageTransfer, sender: sender, buildID: buildID) + return + } + + // Handle content-store requests + if stage == "content-store" { + try await handleContentStoreRequest(imageTransfer, sender: sender, buildID: buildID) + return + } + + logger.debug("Skipping ImageTransfer(stage=\(stage ?? "nil"), method=\(method ?? "nil"))") + } + + private func handleResolverRequest( + _ imageTransfer: ImageTransfer, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + guard let ref = imageTransfer.ref() else { + throw BuilderError.imageMissing + } + + guard let platform = try imageTransfer.platform() else { + throw BuilderError.platformMissing + } + + logger.info("Resolving image: \(ref) for platform: \(platform.description)") + + let imageDescription = try await pullImage(reference: ref, platform: platform) + + guard let indexContent: Content = try await contentStore.get(digest: imageDescription.digest) else { + throw BuilderError.imageNotFound + } + + let index: Index = try indexContent.decode() + + for manifest in index.manifests { + if manifest.platform == platform { + guard let manifestContent: Content = try await contentStore.get(digest: manifest.digest) else { + continue + } + + let manifestData: Manifest = try manifestContent.decode() + + guard + let ociImage: ContainerizationOCI.Image = try await contentStore.get( + digest: manifestData.config.digest + ) + else { + continue + } + + let enc = JSONEncoder() + let data = try enc.encode(ociImage) + let transfer = try ImageTransfer( + id: imageTransfer.id, + digest: imageDescription.digest, + ref: ref, + platform: platform.description, + data: data + ) + + var response = ClientStream() + response.buildID = buildID + response.imageTransfer = transfer + response.packetType = .imageTransfer(transfer) + sender.yield(response) + + logger.info("Resolved: \(ref)") + return + } + } + + throw BuilderError.unknownPlatformForImage(platform.description, ref) + } + + private func pullImage(reference: String, platform: Platform) async throws -> ImageDescription { + let normalizedRef = try Reference.normalized(reference).description + + // Check if image already exists + let existingImages = try await imagesService.list() + + if let existing = existingImages.first(where: { + $0.reference == normalizedRef || $0.reference == reference + }) { + logger.debug("Using existing image: \(normalizedRef)") + return existing + } + + // Pull the image + logger.info("Pulling \(normalizedRef)...") + + let imageDescription = try await imagesService.pull( + reference: normalizedRef, + platform: platform, + insecure: false, + progressUpdate: { events in + // Progress events are string-based (e.g., "add-items", "add-size") + } + ) + + try await imagesService.unpack(description: imageDescription, platform: platform, progressUpdate: nil) + + logger.info("Pulled \(normalizedRef)") + + return imageDescription + } +} diff --git a/ContainerSystem/Build/BuildPipeline/BuildPipeline+Stdio.swift b/ContainerSystem/Build/BuildPipeline/BuildPipeline+Stdio.swift new file mode 100644 index 0000000..86c4433 --- /dev/null +++ b/ContainerSystem/Build/BuildPipeline/BuildPipeline+Stdio.swift @@ -0,0 +1,32 @@ +// +// BuildPipeline+Stdio.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import Foundation + +extension BuildPipeline { + func handleIO(_ io: IO, sender: AsyncStream.Continuation, buildID: String) async throws { + // Write the output to our terminal if not quiet + if !config.quiet { + if let handle = config.terminal?.handle { + try handle.write(contentsOf: io.data) + } else { + // Fallback to stderr + try FileHandle.standardError.write(contentsOf: io.data) + } + } + + // CRITICAL: Send terminal command response back to BuildKit + // BuildKit waits for this response before continuing + let cmdString = try TerminalCommand().json() + var response = ClientStream() + response.buildID = buildID + response.command = .init() + response.command.id = buildID + response.command.command = cmdString + sender.yield(response) + } +} diff --git a/ContainerSystem/Build/BuildPipeline/BuildPipeline.swift b/ContainerSystem/Build/BuildPipeline/BuildPipeline.swift new file mode 100644 index 0000000..de45814 --- /dev/null +++ b/ContainerSystem/Build/BuildPipeline/BuildPipeline.swift @@ -0,0 +1,107 @@ +// +// BuildPipeline.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import Containerization +import ContainerizationOCI +import Foundation +import Logging + +/// Custom build pipeline that uses ImagesService for image resolution instead of XPC +actor BuildPipeline { + let config: Builder.BuildConfig + let imagesService: ImagesService + let contentStore: ContentStore + let logger: Logger + + init(config: Builder.BuildConfig, imagesService: ImagesService, contentStore: ContentStore) { + self.config = config + self.imagesService = imagesService + self.contentStore = contentStore + var logger = Logger(label: "app.containers.sandboxed-pipeline") + logger.logLevel = .debug + self.logger = logger + } + + func run( + sender: AsyncStream.Continuation, + receiver: Receiver + ) async throws where Receiver.Element == ServerStream { + defer { sender.finish() } + + logger.info("Build pipeline started") + + var packetCount = 0 + + for try await packet in receiver { + try Task.checkCancellation() + packetCount += 1 + + if packetCount == 1 { + logger.info("Received first packet from BuildKit") + } + + // Log packet type + switch packet.packetType { + case .imageTransfer(let transfer): + logger.debug("Packet #\(packetCount): ImageTransfer(stage:\(transfer.stage() ?? "nil"), method:\(transfer.method() ?? "nil"))") + case .buildTransfer(let transfer): + logger.debug("Packet #\(packetCount): BuildTransfer(stage:\(transfer.metadata["stage"] ?? "nil"), method:\(transfer.metadata["method"] ?? "nil"))") + case .io(let io): + if let message = String(data: io.data, encoding: .utf8), + !message.trimmingCharacters(in: .whitespacesAndNewlines) + .isEmpty + { + logger.info("\(message)") + await config.statusUpdate?(message) + } + case .buildError(let error): + logger.error("Build error: \(error.message)") + case .commandComplete: + logger.info("Build command completed") + throw BuilderError.buildComplete + case .none: + logger.debug("Packet #\(packetCount): Empty") + } + + // Handle different packet types + if let imageTransfer = packet.getImageTransfer() { + try await handleImageTransfer(imageTransfer, sender: sender, buildID: packet.buildID) + } else if let buildTransfer = packet.getBuildTransfer() { + try await handleBuildTransfer(buildTransfer, sender: sender, buildID: packet.buildID) + } else if let io = packet.getIO() { + try await handleIO(io, sender: sender, buildID: packet.buildID) + } + } + + logger.info("Build pipeline finished (\(packetCount) packets)") + logger.info("Stream ended - build should be complete") + } + + private func handleBuildTransfer( + _ buildTransfer: BuildTransfer, + sender: AsyncStream.Continuation, + buildID: String + ) async throws { + // BuildTransfer packets are used for syncing files (both build context and exports) + let stage = buildTransfer.metadata["stage"] + let direction = buildTransfer.direction + + logger.info("BuildTransfer: stage=\(stage ?? "nil"), direction=\(direction), source=\(buildTransfer.source), dataSize=\(buildTransfer.data.count)") + + switch stage { + case "fssync": + // Handle build context file sync + try await handleFSSyncTransfer(buildTransfer, sender: sender, buildID: buildID) + case "export", nil: + // Handle export file write - BuildKit is trying to write the export tar + logger.info("Handling export transfer") + try await handleExportTransfer(buildTransfer, sender: sender, buildID: buildID) + default: + logger.warning("Ignoring BuildTransfer with unknown stage: \(stage ?? "unknown")") + } + } +} diff --git a/ContainerSystem/Build/BuildTransfer+Metadata.swift b/ContainerSystem/Build/BuildTransfer+Metadata.swift new file mode 100644 index 0000000..49b4e9c --- /dev/null +++ b/ContainerSystem/Build/BuildTransfer+Metadata.swift @@ -0,0 +1,57 @@ +// +// BuildTransfer+Metadata.swift +// Containers +// + +import Foundation + +extension BuildTransfer { + func stage() -> String? { + let stage = self.metadata["stage"] + return stage == "" ? nil : stage + } + + func method() -> String? { + let method = self.metadata["method"] + return method == "" ? nil : method + } + + func includePatterns() -> [String]? { + guard let includePatternsString = self.metadata["include-patterns"] else { + return nil + } + return includePatternsString == "" ? nil : includePatternsString.components(separatedBy: ",") + } + + func followPaths() -> [String]? { + guard let followPathString = self.metadata["followpaths"] else { + return nil + } + return followPathString == "" ? nil : followPathString.components(separatedBy: ",") + } + + func mode() -> String? { + self.metadata["mode"] + } + + func size() -> Int? { + guard let sizeString = self.metadata["size"] else { + return nil + } + return sizeString == "" ? nil : Int(sizeString) + } + + func offset() -> UInt64? { + guard let offsetString = self.metadata["offset"] else { + return nil + } + return offsetString == "" ? nil : UInt64(offsetString) + } + + func len() -> Int? { + guard let lengthString = self.metadata["length"] else { + return nil + } + return lengthString == "" ? nil : Int(lengthString) + } +} diff --git a/ContainerSystem/Build/Builder/Builder+Configuration.swift b/ContainerSystem/Build/Builder/Builder+Configuration.swift new file mode 100644 index 0000000..73af4f5 --- /dev/null +++ b/ContainerSystem/Build/Builder/Builder+Configuration.swift @@ -0,0 +1,122 @@ +// +// BuildTypes.swift +// Containers +// +// Supporting types for the builder system. +// + +import Containerization +import ContainerizationError +import ContainerizationOCI +import Foundation + +// MARK: - Builder Configuration + +extension Builder { + /// Configuration for a build operation. + public struct BuildConfig: Sendable { + public let id: String + public let contentStore: ContentStore + public let args: [String] + public let contextDir: String + public let dockerfile: Data + public let labels: [String] + public let noCache: Bool + public let platforms: [Platform] + public let terminal: BuildTerminal? + public let tags: [String] + public let target: String + public let quiet: Bool + public let exports: [BuildExport] + public let cacheIn: [String] + public let cacheOut: [String] + public let statusUpdate: (@Sendable (String) async -> Void)? + + public init( + id: String, + contentStore: ContentStore, + args: [String] = [], + contextDir: String, + dockerfile: Data, + labels: [String] = [], + noCache: Bool = false, + platforms: [Platform] = [.current], + terminal: BuildTerminal? = nil, + tags: [String] = [], + target: String = "", + quiet: Bool = false, + exports: [BuildExport] = [], + cacheIn: [String] = [], + cacheOut: [String] = [], + statusUpdate: (@Sendable (String) async -> Void)? = nil + ) { + self.id = id + self.contentStore = contentStore + self.args = args + self.contextDir = contextDir + self.dockerfile = dockerfile + self.labels = labels + self.noCache = noCache + self.platforms = platforms + self.terminal = terminal + self.tags = tags + self.target = target + self.quiet = quiet + self.exports = exports + self.cacheIn = cacheIn + self.cacheOut = cacheOut + self.statusUpdate = statusUpdate + } + } + + /// Represents a build export configuration. + public struct BuildExport: Sendable { + public let type: String + public var destination: URL? + public let additionalFields: [String: String] + public let rawValue: String + + public init( + type: String, + destination: URL? = nil, + additionalFields: [String: String] = [:], + rawValue: String = "" + ) { + self.type = type + self.destination = destination + self.additionalFields = additionalFields + self.rawValue = rawValue + } + + public var stringValue: String { + get throws { + var components = ["type=\(type)"] + + switch type { + case "oci", "tar", "local": + break + default: + throw ContainerizationError( + .invalidArgument, + message: "Unsupported build output type: \(type)" + ) + } + + for (key, value) in additionalFields { + components.append("\(key)=\(value)") + } + + return components.joined(separator: ",") + } + } + } + + /// Terminal handle for build output. + public struct BuildTerminal: Sendable { + public let handle: FileHandle? + + public init(handle: FileHandle? = nil) { + self.handle = handle + } + } +} diff --git a/ContainerSystem/Build/Builder/Builder.grpc.swift b/ContainerSystem/Build/Builder/Builder.grpc.swift new file mode 100644 index 0000000..d0bdd97 --- /dev/null +++ b/ContainerSystem/Build/Builder/Builder.grpc.swift @@ -0,0 +1,1219 @@ +//===----------------------------------------------------------------------===// +// Copyright © 2025-2026 Apple Inc. and the container project authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +//===----------------------------------------------------------------------===// + +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the gRPC Swift generator plugin for the protocol buffer compiler. +// Source: Builder.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/grpc/grpc-swift + +import GRPCCore +import GRPCProtobuf + +// MARK: - com.apple.container.build.v1.Builder + +/// Namespace containing generated types for the "com.apple.container.build.v1.Builder" service. +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +public enum Com_Apple_Container_Build_V1_Builder: Sendable { + /// Service descriptor for the "com.apple.container.build.v1.Builder" service. + public static let descriptor = GRPCCore.ServiceDescriptor(fullyQualifiedService: "com.apple.container.build.v1.Builder") + /// Namespace for method metadata. + public enum Method: Sendable { + /// Namespace for "CreateBuild" metadata. + public enum CreateBuild: Sendable { + /// Request type for "CreateBuild". + public typealias Input = Com_Apple_Container_Build_V1_CreateBuildRequest + /// Response type for "CreateBuild". + public typealias Output = Com_Apple_Container_Build_V1_CreateBuildResponse + /// Descriptor for "CreateBuild". + public static let descriptor = GRPCCore.MethodDescriptor( + service: GRPCCore.ServiceDescriptor(fullyQualifiedService: "com.apple.container.build.v1.Builder"), + method: "CreateBuild", + type: .unary + ) + } + /// Namespace for "PerformBuild" metadata. + public enum PerformBuild: Sendable { + /// Request type for "PerformBuild". + public typealias Input = Com_Apple_Container_Build_V1_ClientStream + /// Response type for "PerformBuild". + public typealias Output = Com_Apple_Container_Build_V1_ServerStream + /// Descriptor for "PerformBuild". + public static let descriptor = GRPCCore.MethodDescriptor( + service: GRPCCore.ServiceDescriptor(fullyQualifiedService: "com.apple.container.build.v1.Builder"), + method: "PerformBuild", + type: .bidirectionalStreaming + ) + } + /// Namespace for "Info" metadata. + public enum Info: Sendable { + /// Request type for "Info". + public typealias Input = Com_Apple_Container_Build_V1_InfoRequest + /// Response type for "Info". + public typealias Output = Com_Apple_Container_Build_V1_InfoResponse + /// Descriptor for "Info". + public static let descriptor = GRPCCore.MethodDescriptor( + service: GRPCCore.ServiceDescriptor(fullyQualifiedService: "com.apple.container.build.v1.Builder"), + method: "Info", + type: .unary + ) + } + /// Descriptors for all methods in the "com.apple.container.build.v1.Builder" service. + public static let descriptors: [GRPCCore.MethodDescriptor] = [ + CreateBuild.descriptor, + PerformBuild.descriptor, + Info.descriptor + ] + } +} + +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +extension GRPCCore.ServiceDescriptor { + /// Service descriptor for the "com.apple.container.build.v1.Builder" service. + public static let com_apple_container_build_v1_Builder = GRPCCore.ServiceDescriptor(fullyQualifiedService: "com.apple.container.build.v1.Builder") +} + +// MARK: com.apple.container.build.v1.Builder (server) + +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +extension Com_Apple_Container_Build_V1_Builder { + /// Streaming variant of the service protocol for the "com.apple.container.build.v1.Builder" service. + /// + /// This protocol is the lowest-level of the service protocols generated for this service + /// giving you the most flexibility over the implementation of your service. This comes at + /// the cost of more verbose and less strict APIs. Each RPC requires you to implement it in + /// terms of a request stream and response stream. Where only a single request or response + /// message is expected, you are responsible for enforcing this invariant is maintained. + /// + /// Where possible, prefer using the stricter, less-verbose ``ServiceProtocol`` + /// or ``SimpleServiceProtocol`` instead. + /// + /// > Source IDL Documentation: + /// > + /// > Builder service implements APIs for performing an image build with + /// > Container image builder agent. + /// > + /// > To perform a build: + /// > + /// > 1. CreateBuild to create a new build + /// > 2. StartBuild to start the build execution where client and server + /// > both have a stream for exchanging data during the build. + /// > + /// > The client may send: + /// > a) signal packet to signal to the build process (e.g. SIGINT) + /// > + /// > b) command packet for executing a command in the build file on the + /// > server + /// > NOTE: the server will need to switch on the command to determine the + /// > type of command to execute (e.g. RUN, ENV, etc.) + /// > + /// > c) transfer build data either to or from the server + /// > - INTO direction is for sending build data to the server at specific + /// > location (e.g. COPY) + /// > - OUTOF direction is for copying build data from the server to be + /// > used in subsequent build stages + /// > + /// > d) transfer image content data either to or from the server + /// > - INTO direction is for sending inherited image content data to the + /// > server's local content store + /// > - OUTOF direction is for copying successfully built OCI image from + /// > the server to the client + /// > + /// > The server may send: + /// > a) stdio packet for the build progress + /// > + /// > b) build error indicating unsuccessful build + /// > + /// > c) command complete packet indicating a command has finished executing + /// > + /// > d) handle transfer build data either to or from the client + /// > + /// > e) handle transfer image content data either to or from the client + /// > + /// > + /// > NOTE: The build data and image content data transfer is ALWAYS initiated + /// > by the client. + /// > + /// > Sequence for transferring from the client to the server: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'INTO', + /// > destination path, and first chunk of data + /// > 2. server starts to receive the data and stream to a temporary file + /// > 3. client continues to send all chunks of data until last chunk, which + /// > client will + /// > send with 'complete' set to true + /// > 4. server continues to receive until the last chunk with 'complete' set + /// > to true, + /// > server will finish writing the last chunk and un-archive the + /// > temporary file to the destination path + /// > 5. server completes the transfer by sending a last + /// > BuildTransfer/ImageTransfer with + /// > 'complete' set to true + /// > 6. client waits for the last BuildTransfer/ImageTransfer with 'complete' + /// > set to true + /// > before proceeding with the rest of the commands + /// > + /// > Sequence for transferring from the server to the client: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'OUTOF', + /// > source path, and empty data + /// > 2. server archives the data at source path, and starts to send chunks to + /// > the client + /// > 3. server continues to send all chunks until last chunk, which server + /// > will send with + /// > 'complete' set to true + /// > 4. client starts to receive the data and stream to a temporary file + /// > 5. client continues to receive until the last chunk with 'complete' set + /// > to true, + /// > client will finish writing last chunk and un-archive the temporary + /// > file to the destination path + /// > 6. client MAY choose to send one last BuildTransfer/ImageTransfer with + /// > 'complete' + /// > set to true, but NOT required. + /// > + /// > + /// > NOTE: the client should close the send stream once it has finished + /// > receiving the build output or abandon the current build due to error. + /// > Server should keep the stream open until it receives the EOF that client + /// > has closed the stream, which the server should then close its send stream. + public protocol StreamingServiceProtocol: GRPCCore.RegistrableRPCService { + /// Handle the "CreateBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Create a build request. + /// + /// - Parameters: + /// - request: A streaming request of `Com_Apple_Container_Build_V1_CreateBuildRequest` messages. + /// - context: Context providing information about the RPC. + /// - Throws: Any error which occurred during the processing of the request. Thrown errors + /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted + /// to an internal error. + /// - Returns: A streaming response of `Com_Apple_Container_Build_V1_CreateBuildResponse` messages. + func createBuild( + request: GRPCCore.StreamingServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.StreamingServerResponse + + /// Handle the "PerformBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Perform the build. + /// > Executes the entire build sequence with attaching input/output + /// > to handling data exchange with the server during the build. + /// + /// - Parameters: + /// - request: A streaming request of `Com_Apple_Container_Build_V1_ClientStream` messages. + /// - context: Context providing information about the RPC. + /// - Throws: Any error which occurred during the processing of the request. Thrown errors + /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted + /// to an internal error. + /// - Returns: A streaming response of `Com_Apple_Container_Build_V1_ServerStream` messages. + func performBuild( + request: GRPCCore.StreamingServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.StreamingServerResponse + + /// Handle the "Info" method. + /// + /// - Parameters: + /// - request: A streaming request of `Com_Apple_Container_Build_V1_InfoRequest` messages. + /// - context: Context providing information about the RPC. + /// - Throws: Any error which occurred during the processing of the request. Thrown errors + /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted + /// to an internal error. + /// - Returns: A streaming response of `Com_Apple_Container_Build_V1_InfoResponse` messages. + func info( + request: GRPCCore.StreamingServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.StreamingServerResponse + } + + /// Service protocol for the "com.apple.container.build.v1.Builder" service. + /// + /// This protocol is higher level than ``StreamingServiceProtocol`` but lower level than + /// the ``SimpleServiceProtocol``, it provides access to request and response metadata and + /// trailing response metadata. If you don't need these then consider using + /// the ``SimpleServiceProtocol``. If you need fine grained control over your RPCs then + /// use ``StreamingServiceProtocol``. + /// + /// > Source IDL Documentation: + /// > + /// > Builder service implements APIs for performing an image build with + /// > Container image builder agent. + /// > + /// > To perform a build: + /// > + /// > 1. CreateBuild to create a new build + /// > 2. StartBuild to start the build execution where client and server + /// > both have a stream for exchanging data during the build. + /// > + /// > The client may send: + /// > a) signal packet to signal to the build process (e.g. SIGINT) + /// > + /// > b) command packet for executing a command in the build file on the + /// > server + /// > NOTE: the server will need to switch on the command to determine the + /// > type of command to execute (e.g. RUN, ENV, etc.) + /// > + /// > c) transfer build data either to or from the server + /// > - INTO direction is for sending build data to the server at specific + /// > location (e.g. COPY) + /// > - OUTOF direction is for copying build data from the server to be + /// > used in subsequent build stages + /// > + /// > d) transfer image content data either to or from the server + /// > - INTO direction is for sending inherited image content data to the + /// > server's local content store + /// > - OUTOF direction is for copying successfully built OCI image from + /// > the server to the client + /// > + /// > The server may send: + /// > a) stdio packet for the build progress + /// > + /// > b) build error indicating unsuccessful build + /// > + /// > c) command complete packet indicating a command has finished executing + /// > + /// > d) handle transfer build data either to or from the client + /// > + /// > e) handle transfer image content data either to or from the client + /// > + /// > + /// > NOTE: The build data and image content data transfer is ALWAYS initiated + /// > by the client. + /// > + /// > Sequence for transferring from the client to the server: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'INTO', + /// > destination path, and first chunk of data + /// > 2. server starts to receive the data and stream to a temporary file + /// > 3. client continues to send all chunks of data until last chunk, which + /// > client will + /// > send with 'complete' set to true + /// > 4. server continues to receive until the last chunk with 'complete' set + /// > to true, + /// > server will finish writing the last chunk and un-archive the + /// > temporary file to the destination path + /// > 5. server completes the transfer by sending a last + /// > BuildTransfer/ImageTransfer with + /// > 'complete' set to true + /// > 6. client waits for the last BuildTransfer/ImageTransfer with 'complete' + /// > set to true + /// > before proceeding with the rest of the commands + /// > + /// > Sequence for transferring from the server to the client: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'OUTOF', + /// > source path, and empty data + /// > 2. server archives the data at source path, and starts to send chunks to + /// > the client + /// > 3. server continues to send all chunks until last chunk, which server + /// > will send with + /// > 'complete' set to true + /// > 4. client starts to receive the data and stream to a temporary file + /// > 5. client continues to receive until the last chunk with 'complete' set + /// > to true, + /// > client will finish writing last chunk and un-archive the temporary + /// > file to the destination path + /// > 6. client MAY choose to send one last BuildTransfer/ImageTransfer with + /// > 'complete' + /// > set to true, but NOT required. + /// > + /// > + /// > NOTE: the client should close the send stream once it has finished + /// > receiving the build output or abandon the current build due to error. + /// > Server should keep the stream open until it receives the EOF that client + /// > has closed the stream, which the server should then close its send stream. + public protocol ServiceProtocol: Com_Apple_Container_Build_V1_Builder.StreamingServiceProtocol { + /// Handle the "CreateBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Create a build request. + /// + /// - Parameters: + /// - request: A request containing a single `Com_Apple_Container_Build_V1_CreateBuildRequest` message. + /// - context: Context providing information about the RPC. + /// - Throws: Any error which occurred during the processing of the request. Thrown errors + /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted + /// to an internal error. + /// - Returns: A response containing a single `Com_Apple_Container_Build_V1_CreateBuildResponse` message. + func createBuild( + request: GRPCCore.ServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.ServerResponse + + /// Handle the "PerformBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Perform the build. + /// > Executes the entire build sequence with attaching input/output + /// > to handling data exchange with the server during the build. + /// + /// - Parameters: + /// - request: A streaming request of `Com_Apple_Container_Build_V1_ClientStream` messages. + /// - context: Context providing information about the RPC. + /// - Throws: Any error which occurred during the processing of the request. Thrown errors + /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted + /// to an internal error. + /// - Returns: A streaming response of `Com_Apple_Container_Build_V1_ServerStream` messages. + func performBuild( + request: GRPCCore.StreamingServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.StreamingServerResponse + + /// Handle the "Info" method. + /// + /// - Parameters: + /// - request: A request containing a single `Com_Apple_Container_Build_V1_InfoRequest` message. + /// - context: Context providing information about the RPC. + /// - Throws: Any error which occurred during the processing of the request. Thrown errors + /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted + /// to an internal error. + /// - Returns: A response containing a single `Com_Apple_Container_Build_V1_InfoResponse` message. + func info( + request: GRPCCore.ServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.ServerResponse + } + + /// Simple service protocol for the "com.apple.container.build.v1.Builder" service. + /// + /// This is the highest level protocol for the service. The API is the easiest to use but + /// doesn't provide access to request or response metadata. If you need access to these + /// then use ``ServiceProtocol`` instead. + /// + /// > Source IDL Documentation: + /// > + /// > Builder service implements APIs for performing an image build with + /// > Container image builder agent. + /// > + /// > To perform a build: + /// > + /// > 1. CreateBuild to create a new build + /// > 2. StartBuild to start the build execution where client and server + /// > both have a stream for exchanging data during the build. + /// > + /// > The client may send: + /// > a) signal packet to signal to the build process (e.g. SIGINT) + /// > + /// > b) command packet for executing a command in the build file on the + /// > server + /// > NOTE: the server will need to switch on the command to determine the + /// > type of command to execute (e.g. RUN, ENV, etc.) + /// > + /// > c) transfer build data either to or from the server + /// > - INTO direction is for sending build data to the server at specific + /// > location (e.g. COPY) + /// > - OUTOF direction is for copying build data from the server to be + /// > used in subsequent build stages + /// > + /// > d) transfer image content data either to or from the server + /// > - INTO direction is for sending inherited image content data to the + /// > server's local content store + /// > - OUTOF direction is for copying successfully built OCI image from + /// > the server to the client + /// > + /// > The server may send: + /// > a) stdio packet for the build progress + /// > + /// > b) build error indicating unsuccessful build + /// > + /// > c) command complete packet indicating a command has finished executing + /// > + /// > d) handle transfer build data either to or from the client + /// > + /// > e) handle transfer image content data either to or from the client + /// > + /// > + /// > NOTE: The build data and image content data transfer is ALWAYS initiated + /// > by the client. + /// > + /// > Sequence for transferring from the client to the server: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'INTO', + /// > destination path, and first chunk of data + /// > 2. server starts to receive the data and stream to a temporary file + /// > 3. client continues to send all chunks of data until last chunk, which + /// > client will + /// > send with 'complete' set to true + /// > 4. server continues to receive until the last chunk with 'complete' set + /// > to true, + /// > server will finish writing the last chunk and un-archive the + /// > temporary file to the destination path + /// > 5. server completes the transfer by sending a last + /// > BuildTransfer/ImageTransfer with + /// > 'complete' set to true + /// > 6. client waits for the last BuildTransfer/ImageTransfer with 'complete' + /// > set to true + /// > before proceeding with the rest of the commands + /// > + /// > Sequence for transferring from the server to the client: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'OUTOF', + /// > source path, and empty data + /// > 2. server archives the data at source path, and starts to send chunks to + /// > the client + /// > 3. server continues to send all chunks until last chunk, which server + /// > will send with + /// > 'complete' set to true + /// > 4. client starts to receive the data and stream to a temporary file + /// > 5. client continues to receive until the last chunk with 'complete' set + /// > to true, + /// > client will finish writing last chunk and un-archive the temporary + /// > file to the destination path + /// > 6. client MAY choose to send one last BuildTransfer/ImageTransfer with + /// > 'complete' + /// > set to true, but NOT required. + /// > + /// > + /// > NOTE: the client should close the send stream once it has finished + /// > receiving the build output or abandon the current build due to error. + /// > Server should keep the stream open until it receives the EOF that client + /// > has closed the stream, which the server should then close its send stream. + public protocol SimpleServiceProtocol: Com_Apple_Container_Build_V1_Builder.ServiceProtocol { + /// Handle the "CreateBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Create a build request. + /// + /// - Parameters: + /// - request: A `Com_Apple_Container_Build_V1_CreateBuildRequest` message. + /// - context: Context providing information about the RPC. + /// - Throws: Any error which occurred during the processing of the request. Thrown errors + /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted + /// to an internal error. + /// - Returns: A `Com_Apple_Container_Build_V1_CreateBuildResponse` to respond with. + func createBuild( + request: Com_Apple_Container_Build_V1_CreateBuildRequest, + context: GRPCCore.ServerContext + ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse + + /// Handle the "PerformBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Perform the build. + /// > Executes the entire build sequence with attaching input/output + /// > to handling data exchange with the server during the build. + /// + /// - Parameters: + /// - request: A stream of `Com_Apple_Container_Build_V1_ClientStream` messages. + /// - response: A response stream of `Com_Apple_Container_Build_V1_ServerStream` messages. + /// - context: Context providing information about the RPC. + /// - Throws: Any error which occurred during the processing of the request. Thrown errors + /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted + /// to an internal error. + func performBuild( + request: GRPCCore.RPCAsyncSequence, + response: GRPCCore.RPCWriter, + context: GRPCCore.ServerContext + ) async throws + + /// Handle the "Info" method. + /// + /// - Parameters: + /// - request: A `Com_Apple_Container_Build_V1_InfoRequest` message. + /// - context: Context providing information about the RPC. + /// - Throws: Any error which occurred during the processing of the request. Thrown errors + /// of type `RPCError` are mapped to appropriate statuses. All other errors are converted + /// to an internal error. + /// - Returns: A `Com_Apple_Container_Build_V1_InfoResponse` to respond with. + func info( + request: Com_Apple_Container_Build_V1_InfoRequest, + context: GRPCCore.ServerContext + ) async throws -> Com_Apple_Container_Build_V1_InfoResponse + } +} + +// Default implementation of 'registerMethods(with:)'. +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +extension Com_Apple_Container_Build_V1_Builder.StreamingServiceProtocol { + public func registerMethods(with router: inout GRPCCore.RPCRouter) where Transport: GRPCCore.ServerTransport { + router.registerHandler( + forMethod: Com_Apple_Container_Build_V1_Builder.Method.CreateBuild.descriptor, + deserializer: GRPCProtobuf.ProtobufDeserializer(), + serializer: GRPCProtobuf.ProtobufSerializer(), + handler: { request, context in + try await self.createBuild( + request: request, + context: context + ) + } + ) + router.registerHandler( + forMethod: Com_Apple_Container_Build_V1_Builder.Method.PerformBuild.descriptor, + deserializer: GRPCProtobuf.ProtobufDeserializer(), + serializer: GRPCProtobuf.ProtobufSerializer(), + handler: { request, context in + try await self.performBuild( + request: request, + context: context + ) + } + ) + router.registerHandler( + forMethod: Com_Apple_Container_Build_V1_Builder.Method.Info.descriptor, + deserializer: GRPCProtobuf.ProtobufDeserializer(), + serializer: GRPCProtobuf.ProtobufSerializer(), + handler: { request, context in + try await self.info( + request: request, + context: context + ) + } + ) + } +} + +// Default implementation of streaming methods from 'StreamingServiceProtocol'. +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +extension Com_Apple_Container_Build_V1_Builder.ServiceProtocol { + public func createBuild( + request: GRPCCore.StreamingServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.StreamingServerResponse { + let response = try await self.createBuild( + request: GRPCCore.ServerRequest(stream: request), + context: context + ) + return GRPCCore.StreamingServerResponse(single: response) + } + + public func info( + request: GRPCCore.StreamingServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.StreamingServerResponse { + let response = try await self.info( + request: GRPCCore.ServerRequest(stream: request), + context: context + ) + return GRPCCore.StreamingServerResponse(single: response) + } +} + +// Default implementation of methods from 'ServiceProtocol'. +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +extension Com_Apple_Container_Build_V1_Builder.SimpleServiceProtocol { + public func createBuild( + request: GRPCCore.ServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.ServerResponse { + return GRPCCore.ServerResponse( + message: try await self.createBuild( + request: request.message, + context: context + ), + metadata: [:] + ) + } + + public func performBuild( + request: GRPCCore.StreamingServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.StreamingServerResponse { + return GRPCCore.StreamingServerResponse( + metadata: [:], + producer: { writer in + try await self.performBuild( + request: request.messages, + response: writer, + context: context + ) + return [:] + } + ) + } + + public func info( + request: GRPCCore.ServerRequest, + context: GRPCCore.ServerContext + ) async throws -> GRPCCore.ServerResponse { + return GRPCCore.ServerResponse( + message: try await self.info( + request: request.message, + context: context + ), + metadata: [:] + ) + } +} + +// MARK: com.apple.container.build.v1.Builder (client) + +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +extension Com_Apple_Container_Build_V1_Builder { + /// Generated client protocol for the "com.apple.container.build.v1.Builder" service. + /// + /// You don't need to implement this protocol directly, use the generated + /// implementation, ``Client``. + /// + /// > Source IDL Documentation: + /// > + /// > Builder service implements APIs for performing an image build with + /// > Container image builder agent. + /// > + /// > To perform a build: + /// > + /// > 1. CreateBuild to create a new build + /// > 2. StartBuild to start the build execution where client and server + /// > both have a stream for exchanging data during the build. + /// > + /// > The client may send: + /// > a) signal packet to signal to the build process (e.g. SIGINT) + /// > + /// > b) command packet for executing a command in the build file on the + /// > server + /// > NOTE: the server will need to switch on the command to determine the + /// > type of command to execute (e.g. RUN, ENV, etc.) + /// > + /// > c) transfer build data either to or from the server + /// > - INTO direction is for sending build data to the server at specific + /// > location (e.g. COPY) + /// > - OUTOF direction is for copying build data from the server to be + /// > used in subsequent build stages + /// > + /// > d) transfer image content data either to or from the server + /// > - INTO direction is for sending inherited image content data to the + /// > server's local content store + /// > - OUTOF direction is for copying successfully built OCI image from + /// > the server to the client + /// > + /// > The server may send: + /// > a) stdio packet for the build progress + /// > + /// > b) build error indicating unsuccessful build + /// > + /// > c) command complete packet indicating a command has finished executing + /// > + /// > d) handle transfer build data either to or from the client + /// > + /// > e) handle transfer image content data either to or from the client + /// > + /// > + /// > NOTE: The build data and image content data transfer is ALWAYS initiated + /// > by the client. + /// > + /// > Sequence for transferring from the client to the server: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'INTO', + /// > destination path, and first chunk of data + /// > 2. server starts to receive the data and stream to a temporary file + /// > 3. client continues to send all chunks of data until last chunk, which + /// > client will + /// > send with 'complete' set to true + /// > 4. server continues to receive until the last chunk with 'complete' set + /// > to true, + /// > server will finish writing the last chunk and un-archive the + /// > temporary file to the destination path + /// > 5. server completes the transfer by sending a last + /// > BuildTransfer/ImageTransfer with + /// > 'complete' set to true + /// > 6. client waits for the last BuildTransfer/ImageTransfer with 'complete' + /// > set to true + /// > before proceeding with the rest of the commands + /// > + /// > Sequence for transferring from the server to the client: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'OUTOF', + /// > source path, and empty data + /// > 2. server archives the data at source path, and starts to send chunks to + /// > the client + /// > 3. server continues to send all chunks until last chunk, which server + /// > will send with + /// > 'complete' set to true + /// > 4. client starts to receive the data and stream to a temporary file + /// > 5. client continues to receive until the last chunk with 'complete' set + /// > to true, + /// > client will finish writing last chunk and un-archive the temporary + /// > file to the destination path + /// > 6. client MAY choose to send one last BuildTransfer/ImageTransfer with + /// > 'complete' + /// > set to true, but NOT required. + /// > + /// > + /// > NOTE: the client should close the send stream once it has finished + /// > receiving the build output or abandon the current build due to error. + /// > Server should keep the stream open until it receives the EOF that client + /// > has closed the stream, which the server should then close its send stream. + public protocol ClientProtocol: Sendable { + /// Call the "CreateBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Create a build request. + /// + /// - Parameters: + /// - request: A request containing a single `Com_Apple_Container_Build_V1_CreateBuildRequest` message. + /// - serializer: A serializer for `Com_Apple_Container_Build_V1_CreateBuildRequest` messages. + /// - deserializer: A deserializer for `Com_Apple_Container_Build_V1_CreateBuildResponse` messages. + /// - options: Options to apply to this RPC. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + func createBuild( + request: GRPCCore.ClientRequest, + serializer: some GRPCCore.MessageSerializer, + deserializer: some GRPCCore.MessageDeserializer, + options: GRPCCore.CallOptions, + onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse) async throws -> Result + ) async throws -> Result where Result: Sendable + + /// Call the "PerformBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Perform the build. + /// > Executes the entire build sequence with attaching input/output + /// > to handling data exchange with the server during the build. + /// + /// - Parameters: + /// - request: A streaming request producing `Com_Apple_Container_Build_V1_ClientStream` messages. + /// - serializer: A serializer for `Com_Apple_Container_Build_V1_ClientStream` messages. + /// - deserializer: A deserializer for `Com_Apple_Container_Build_V1_ServerStream` messages. + /// - options: Options to apply to this RPC. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + func performBuild( + request: GRPCCore.StreamingClientRequest, + serializer: some GRPCCore.MessageSerializer, + deserializer: some GRPCCore.MessageDeserializer, + options: GRPCCore.CallOptions, + onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse) async throws -> Result + ) async throws -> Result where Result: Sendable + + /// Call the "Info" method. + /// + /// - Parameters: + /// - request: A request containing a single `Com_Apple_Container_Build_V1_InfoRequest` message. + /// - serializer: A serializer for `Com_Apple_Container_Build_V1_InfoRequest` messages. + /// - deserializer: A deserializer for `Com_Apple_Container_Build_V1_InfoResponse` messages. + /// - options: Options to apply to this RPC. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + func info( + request: GRPCCore.ClientRequest, + serializer: some GRPCCore.MessageSerializer, + deserializer: some GRPCCore.MessageDeserializer, + options: GRPCCore.CallOptions, + onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse) async throws -> Result + ) async throws -> Result where Result: Sendable + } + + /// Generated client for the "com.apple.container.build.v1.Builder" service. + /// + /// The ``Client`` provides an implementation of ``ClientProtocol`` which wraps + /// a `GRPCCore.GRPCCClient`. The underlying `GRPCClient` provides the long-lived + /// means of communication with the remote peer. + /// + /// > Source IDL Documentation: + /// > + /// > Builder service implements APIs for performing an image build with + /// > Container image builder agent. + /// > + /// > To perform a build: + /// > + /// > 1. CreateBuild to create a new build + /// > 2. StartBuild to start the build execution where client and server + /// > both have a stream for exchanging data during the build. + /// > + /// > The client may send: + /// > a) signal packet to signal to the build process (e.g. SIGINT) + /// > + /// > b) command packet for executing a command in the build file on the + /// > server + /// > NOTE: the server will need to switch on the command to determine the + /// > type of command to execute (e.g. RUN, ENV, etc.) + /// > + /// > c) transfer build data either to or from the server + /// > - INTO direction is for sending build data to the server at specific + /// > location (e.g. COPY) + /// > - OUTOF direction is for copying build data from the server to be + /// > used in subsequent build stages + /// > + /// > d) transfer image content data either to or from the server + /// > - INTO direction is for sending inherited image content data to the + /// > server's local content store + /// > - OUTOF direction is for copying successfully built OCI image from + /// > the server to the client + /// > + /// > The server may send: + /// > a) stdio packet for the build progress + /// > + /// > b) build error indicating unsuccessful build + /// > + /// > c) command complete packet indicating a command has finished executing + /// > + /// > d) handle transfer build data either to or from the client + /// > + /// > e) handle transfer image content data either to or from the client + /// > + /// > + /// > NOTE: The build data and image content data transfer is ALWAYS initiated + /// > by the client. + /// > + /// > Sequence for transferring from the client to the server: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'INTO', + /// > destination path, and first chunk of data + /// > 2. server starts to receive the data and stream to a temporary file + /// > 3. client continues to send all chunks of data until last chunk, which + /// > client will + /// > send with 'complete' set to true + /// > 4. server continues to receive until the last chunk with 'complete' set + /// > to true, + /// > server will finish writing the last chunk and un-archive the + /// > temporary file to the destination path + /// > 5. server completes the transfer by sending a last + /// > BuildTransfer/ImageTransfer with + /// > 'complete' set to true + /// > 6. client waits for the last BuildTransfer/ImageTransfer with 'complete' + /// > set to true + /// > before proceeding with the rest of the commands + /// > + /// > Sequence for transferring from the server to the client: + /// > 1. client send a BuildTransfer/ImageTransfer request with ID, direction + /// > of 'OUTOF', + /// > source path, and empty data + /// > 2. server archives the data at source path, and starts to send chunks to + /// > the client + /// > 3. server continues to send all chunks until last chunk, which server + /// > will send with + /// > 'complete' set to true + /// > 4. client starts to receive the data and stream to a temporary file + /// > 5. client continues to receive until the last chunk with 'complete' set + /// > to true, + /// > client will finish writing last chunk and un-archive the temporary + /// > file to the destination path + /// > 6. client MAY choose to send one last BuildTransfer/ImageTransfer with + /// > 'complete' + /// > set to true, but NOT required. + /// > + /// > + /// > NOTE: the client should close the send stream once it has finished + /// > receiving the build output or abandon the current build due to error. + /// > Server should keep the stream open until it receives the EOF that client + /// > has closed the stream, which the server should then close its send stream. + public struct Client: ClientProtocol where Transport: GRPCCore.ClientTransport { + private let client: GRPCCore.GRPCClient + + /// Creates a new client wrapping the provided `GRPCCore.GRPCClient`. + /// + /// - Parameters: + /// - client: A `GRPCCore.GRPCClient` providing a communication channel to the service. + public init(wrapping client: GRPCCore.GRPCClient) { + self.client = client + } + + /// Call the "CreateBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Create a build request. + /// + /// - Parameters: + /// - request: A request containing a single `Com_Apple_Container_Build_V1_CreateBuildRequest` message. + /// - serializer: A serializer for `Com_Apple_Container_Build_V1_CreateBuildRequest` messages. + /// - deserializer: A deserializer for `Com_Apple_Container_Build_V1_CreateBuildResponse` messages. + /// - options: Options to apply to this RPC. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + public func createBuild( + request: GRPCCore.ClientRequest, + serializer: some GRPCCore.MessageSerializer, + deserializer: some GRPCCore.MessageDeserializer, + options: GRPCCore.CallOptions = .defaults, + onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse) async throws -> Result = { response in + try response.message + } + ) async throws -> Result where Result: Sendable { + try await self.client.unary( + request: request, + descriptor: Com_Apple_Container_Build_V1_Builder.Method.CreateBuild.descriptor, + serializer: serializer, + deserializer: deserializer, + options: options, + onResponse: handleResponse + ) + } + + /// Call the "PerformBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Perform the build. + /// > Executes the entire build sequence with attaching input/output + /// > to handling data exchange with the server during the build. + /// + /// - Parameters: + /// - request: A streaming request producing `Com_Apple_Container_Build_V1_ClientStream` messages. + /// - serializer: A serializer for `Com_Apple_Container_Build_V1_ClientStream` messages. + /// - deserializer: A deserializer for `Com_Apple_Container_Build_V1_ServerStream` messages. + /// - options: Options to apply to this RPC. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + public func performBuild( + request: GRPCCore.StreamingClientRequest, + serializer: some GRPCCore.MessageSerializer, + deserializer: some GRPCCore.MessageDeserializer, + options: GRPCCore.CallOptions = .defaults, + onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse) async throws -> Result + ) async throws -> Result where Result: Sendable { + try await self.client.bidirectionalStreaming( + request: request, + descriptor: Com_Apple_Container_Build_V1_Builder.Method.PerformBuild.descriptor, + serializer: serializer, + deserializer: deserializer, + options: options, + onResponse: handleResponse + ) + } + + /// Call the "Info" method. + /// + /// - Parameters: + /// - request: A request containing a single `Com_Apple_Container_Build_V1_InfoRequest` message. + /// - serializer: A serializer for `Com_Apple_Container_Build_V1_InfoRequest` messages. + /// - deserializer: A deserializer for `Com_Apple_Container_Build_V1_InfoResponse` messages. + /// - options: Options to apply to this RPC. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + public func info( + request: GRPCCore.ClientRequest, + serializer: some GRPCCore.MessageSerializer, + deserializer: some GRPCCore.MessageDeserializer, + options: GRPCCore.CallOptions = .defaults, + onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse) async throws -> Result = { response in + try response.message + } + ) async throws -> Result where Result: Sendable { + try await self.client.unary( + request: request, + descriptor: Com_Apple_Container_Build_V1_Builder.Method.Info.descriptor, + serializer: serializer, + deserializer: deserializer, + options: options, + onResponse: handleResponse + ) + } + } +} + +// Helpers providing default arguments to 'ClientProtocol' methods. +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +extension Com_Apple_Container_Build_V1_Builder.ClientProtocol { + /// Call the "CreateBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Create a build request. + /// + /// - Parameters: + /// - request: A request containing a single `Com_Apple_Container_Build_V1_CreateBuildRequest` message. + /// - options: Options to apply to this RPC. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + public func createBuild( + request: GRPCCore.ClientRequest, + options: GRPCCore.CallOptions = .defaults, + onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse) async throws -> Result = { response in + try response.message + } + ) async throws -> Result where Result: Sendable { + try await self.createBuild( + request: request, + serializer: GRPCProtobuf.ProtobufSerializer(), + deserializer: GRPCProtobuf.ProtobufDeserializer(), + options: options, + onResponse: handleResponse + ) + } + + /// Call the "PerformBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Perform the build. + /// > Executes the entire build sequence with attaching input/output + /// > to handling data exchange with the server during the build. + /// + /// - Parameters: + /// - request: A streaming request producing `Com_Apple_Container_Build_V1_ClientStream` messages. + /// - options: Options to apply to this RPC. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + public func performBuild( + request: GRPCCore.StreamingClientRequest, + options: GRPCCore.CallOptions = .defaults, + onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse) async throws -> Result + ) async throws -> Result where Result: Sendable { + try await self.performBuild( + request: request, + serializer: GRPCProtobuf.ProtobufSerializer(), + deserializer: GRPCProtobuf.ProtobufDeserializer(), + options: options, + onResponse: handleResponse + ) + } + + /// Call the "Info" method. + /// + /// - Parameters: + /// - request: A request containing a single `Com_Apple_Container_Build_V1_InfoRequest` message. + /// - options: Options to apply to this RPC. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + public func info( + request: GRPCCore.ClientRequest, + options: GRPCCore.CallOptions = .defaults, + onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse) async throws -> Result = { response in + try response.message + } + ) async throws -> Result where Result: Sendable { + try await self.info( + request: request, + serializer: GRPCProtobuf.ProtobufSerializer(), + deserializer: GRPCProtobuf.ProtobufDeserializer(), + options: options, + onResponse: handleResponse + ) + } +} + +// Helpers providing sugared APIs for 'ClientProtocol' methods. +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +extension Com_Apple_Container_Build_V1_Builder.ClientProtocol { + /// Call the "CreateBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Create a build request. + /// + /// - Parameters: + /// - message: request message to send. + /// - metadata: Additional metadata to send, defaults to empty. + /// - options: Options to apply to this RPC, defaults to `.defaults`. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + public func createBuild( + _ message: Com_Apple_Container_Build_V1_CreateBuildRequest, + metadata: GRPCCore.Metadata = [:], + options: GRPCCore.CallOptions = .defaults, + onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse) async throws -> Result = { response in + try response.message + } + ) async throws -> Result where Result: Sendable { + let request = GRPCCore.ClientRequest( + message: message, + metadata: metadata + ) + return try await self.createBuild( + request: request, + options: options, + onResponse: handleResponse + ) + } + + /// Call the "PerformBuild" method. + /// + /// > Source IDL Documentation: + /// > + /// > Perform the build. + /// > Executes the entire build sequence with attaching input/output + /// > to handling data exchange with the server during the build. + /// + /// - Parameters: + /// - metadata: Additional metadata to send, defaults to empty. + /// - options: Options to apply to this RPC, defaults to `.defaults`. + /// - producer: A closure producing request messages to send to the server. The request + /// stream is closed when the closure returns. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + public func performBuild( + metadata: GRPCCore.Metadata = [:], + options: GRPCCore.CallOptions = .defaults, + requestProducer producer: @Sendable @escaping (GRPCCore.RPCWriter) async throws -> Void, + onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse) async throws -> Result + ) async throws -> Result where Result: Sendable { + let request = GRPCCore.StreamingClientRequest( + metadata: metadata, + producer: producer + ) + return try await self.performBuild( + request: request, + options: options, + onResponse: handleResponse + ) + } + + /// Call the "Info" method. + /// + /// - Parameters: + /// - message: request message to send. + /// - metadata: Additional metadata to send, defaults to empty. + /// - options: Options to apply to this RPC, defaults to `.defaults`. + /// - handleResponse: A closure which handles the response, the result of which is + /// returned to the caller. Returning from the closure will cancel the RPC if it + /// hasn't already finished. + /// - Returns: The result of `handleResponse`. + public func info( + _ message: Com_Apple_Container_Build_V1_InfoRequest, + metadata: GRPCCore.Metadata = [:], + options: GRPCCore.CallOptions = .defaults, + onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse) async throws -> Result = { response in + try response.message + } + ) async throws -> Result where Result: Sendable { + let request = GRPCCore.ClientRequest( + message: message, + metadata: metadata + ) + return try await self.info( + request: request, + options: options, + onResponse: handleResponse + ) + } +} \ No newline at end of file diff --git a/ContainerSystem/Build/Builder/Builder.pb.swift b/ContainerSystem/Build/Builder/Builder.pb.swift new file mode 100644 index 0000000..6b6c116 --- /dev/null +++ b/ContainerSystem/Build/Builder/Builder.pb.swift @@ -0,0 +1,1422 @@ +//===----------------------------------------------------------------------===// +// Copyright © 2025-2026 Apple Inc. and the container project authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +//===----------------------------------------------------------------------===// + +// DO NOT EDIT. +// swift-format-ignore-file +// swiftlint:disable all +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: Builder.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +#if canImport(FoundationEssentials) +import FoundationEssentials +#else +import Foundation +#endif +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +public enum Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf.Enum, Swift.CaseIterable { + public typealias RawValue = Int + case into // = 0 + case outof // = 1 + case UNRECOGNIZED(Int) + + public init() { + self = .into + } + + public init?(rawValue: Int) { + switch rawValue { + case 0: self = .into + case 1: self = .outof + default: self = .UNRECOGNIZED(rawValue) + } + } + + public var rawValue: Int { + switch self { + case .into: return 0 + case .outof: return 1 + case .UNRECOGNIZED(let i): return i + } + } + + // The compiler won't synthesize support with the UNRECOGNIZED case. + public static let allCases: [Com_Apple_Container_Build_V1_TransferDirection] = [ + .into, + .outof, + ] + +} + +/// Standard input/output. +public enum Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf.Enum, Swift.CaseIterable { + public typealias RawValue = Int + case stdin // = 0 + case stdout // = 1 + case stderr // = 2 + case UNRECOGNIZED(Int) + + public init() { + self = .stdin + } + + public init?(rawValue: Int) { + switch rawValue { + case 0: self = .stdin + case 1: self = .stdout + case 2: self = .stderr + default: self = .UNRECOGNIZED(rawValue) + } + } + + public var rawValue: Int { + switch self { + case .stdin: return 0 + case .stdout: return 1 + case .stderr: return 2 + case .UNRECOGNIZED(let i): return i + } + } + + // The compiler won't synthesize support with the UNRECOGNIZED case. + public static let allCases: [Com_Apple_Container_Build_V1_Stdio] = [ + .stdin, + .stdout, + .stderr, + ] + +} + +/// Build error type. +public enum Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf.Enum, Swift.CaseIterable { + public typealias RawValue = Int + case buildFailed // = 0 + case `internal` // = 1 + case UNRECOGNIZED(Int) + + public init() { + self = .buildFailed + } + + public init?(rawValue: Int) { + switch rawValue { + case 0: self = .buildFailed + case 1: self = .internal + default: self = .UNRECOGNIZED(rawValue) + } + } + + public var rawValue: Int { + switch self { + case .buildFailed: return 0 + case .internal: return 1 + case .UNRECOGNIZED(let i): return i + } + } + + // The compiler won't synthesize support with the UNRECOGNIZED case. + public static let allCases: [Com_Apple_Container_Build_V1_BuildErrorType] = [ + .buildFailed, + .internal, + ] + +} + +public struct Com_Apple_Container_Build_V1_InfoRequest: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +public struct Com_Apple_Container_Build_V1_InfoResponse: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +public struct Com_Apple_Container_Build_V1_CreateBuildRequest: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The name of the build stage. + public var stageName: String = String() + + /// The tag of the image to be created. + public var tag: String = String() + + /// Any additional metadata to be associated with the build. + public var metadata: Dictionary = [:] + + /// Additional build arguments. + public var buildArgs: [String] = [] + + /// Enable debug logging. + public var debug: Bool = false + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +public struct Com_Apple_Container_Build_V1_CreateBuildResponse: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// A unique ID for the build. + public var buildID: String = String() + + /// Any additional metadata to be associated with the build. + public var metadata: Dictionary = [:] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +public struct Com_Apple_Container_Build_V1_ClientStream: @unchecked Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// A unique ID for the build. + public var buildID: String { + get {_storage._buildID} + set {_uniqueStorage()._buildID = newValue} + } + + /// The packet type. + public var packetType: OneOf_PacketType? { + get {return _storage._packetType} + set {_uniqueStorage()._packetType = newValue} + } + + public var signal: Com_Apple_Container_Build_V1_Signal { + get { + if case .signal(let v)? = _storage._packetType {return v} + return Com_Apple_Container_Build_V1_Signal() + } + set {_uniqueStorage()._packetType = .signal(newValue)} + } + + public var command: Com_Apple_Container_Build_V1_Run { + get { + if case .command(let v)? = _storage._packetType {return v} + return Com_Apple_Container_Build_V1_Run() + } + set {_uniqueStorage()._packetType = .command(newValue)} + } + + public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer { + get { + if case .buildTransfer(let v)? = _storage._packetType {return v} + return Com_Apple_Container_Build_V1_BuildTransfer() + } + set {_uniqueStorage()._packetType = .buildTransfer(newValue)} + } + + public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer { + get { + if case .imageTransfer(let v)? = _storage._packetType {return v} + return Com_Apple_Container_Build_V1_ImageTransfer() + } + set {_uniqueStorage()._packetType = .imageTransfer(newValue)} + } + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + /// The packet type. + public enum OneOf_PacketType: Equatable, Sendable { + case signal(Com_Apple_Container_Build_V1_Signal) + case command(Com_Apple_Container_Build_V1_Run) + case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer) + case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer) + + } + + public init() {} + + fileprivate var _storage = _StorageClass.defaultInstance +} + +public struct Com_Apple_Container_Build_V1_Signal: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// A POSIX signal to send to the build process. + /// Can be used for cancelling builds. + public var signal: Int32 = 0 + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +public struct Com_Apple_Container_Build_V1_Run: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// A unique ID for the execution. + public var id: String = String() + + /// The type of command to execute. + public var command: String = String() + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +public struct Com_Apple_Container_Build_V1_RunComplete: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// A unique ID for the execution. + public var id: String = String() + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +public struct Com_Apple_Container_Build_V1_BuildTransfer: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// A unique ID for the transfer. + public var id: String = String() + + /// The direction for transferring data (either to the server or from the + /// server). + public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into + + /// The absolute path to the source from the server perspective. + public var source: String { + get {_source ?? String()} + set {_source = newValue} + } + /// Returns true if `source` has been explicitly set. + public var hasSource: Bool {self._source != nil} + /// Clears the value of `source`. Subsequent reads from it will return its default value. + public mutating func clearSource() {self._source = nil} + + /// The absolute path for the destination from the server perspective. + public var destination: String { + get {_destination ?? String()} + set {_destination = newValue} + } + /// Returns true if `destination` has been explicitly set. + public var hasDestination: Bool {self._destination != nil} + /// Clears the value of `destination`. Subsequent reads from it will return its default value. + public mutating func clearDestination() {self._destination = nil} + + /// The actual data bytes to be transferred. + public var data: Data = Data() + + /// Signal to indicate that the transfer of data for the request has finished. + public var complete: Bool = false + + /// Boolean to indicate if the content is a directory. + public var isDirectory: Bool = false + + /// Metadata for the transfer. + public var metadata: Dictionary = [:] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _source: String? = nil + fileprivate var _destination: String? = nil +} + +public struct Com_Apple_Container_Build_V1_ImageTransfer: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// A unique ID for the transfer. + public var id: String = String() + + /// The direction for transferring data (either to the server or from the + /// server). + public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into + + /// The tag for the image. + public var tag: String = String() + + /// The descriptor for the image content. + public var descriptor: Com_Apple_Container_Build_V1_Descriptor { + get {_descriptor ?? Com_Apple_Container_Build_V1_Descriptor()} + set {_descriptor = newValue} + } + /// Returns true if `descriptor` has been explicitly set. + public var hasDescriptor: Bool {self._descriptor != nil} + /// Clears the value of `descriptor`. Subsequent reads from it will return its default value. + public mutating func clearDescriptor() {self._descriptor = nil} + + /// The actual data bytes to be transferred. + public var data: Data = Data() + + /// Signal to indicate that the transfer of data for the request has finished. + public var complete: Bool = false + + /// Metadata for the image. + public var metadata: Dictionary = [:] + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _descriptor: Com_Apple_Container_Build_V1_Descriptor? = nil +} + +public struct Com_Apple_Container_Build_V1_ServerStream: @unchecked Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// A unique ID for the build. + public var buildID: String { + get {_storage._buildID} + set {_uniqueStorage()._buildID = newValue} + } + + /// The packet type. + public var packetType: OneOf_PacketType? { + get {return _storage._packetType} + set {_uniqueStorage()._packetType = newValue} + } + + public var io: Com_Apple_Container_Build_V1_IO { + get { + if case .io(let v)? = _storage._packetType {return v} + return Com_Apple_Container_Build_V1_IO() + } + set {_uniqueStorage()._packetType = .io(newValue)} + } + + public var buildError: Com_Apple_Container_Build_V1_BuildError { + get { + if case .buildError(let v)? = _storage._packetType {return v} + return Com_Apple_Container_Build_V1_BuildError() + } + set {_uniqueStorage()._packetType = .buildError(newValue)} + } + + public var commandComplete: Com_Apple_Container_Build_V1_RunComplete { + get { + if case .commandComplete(let v)? = _storage._packetType {return v} + return Com_Apple_Container_Build_V1_RunComplete() + } + set {_uniqueStorage()._packetType = .commandComplete(newValue)} + } + + public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer { + get { + if case .buildTransfer(let v)? = _storage._packetType {return v} + return Com_Apple_Container_Build_V1_BuildTransfer() + } + set {_uniqueStorage()._packetType = .buildTransfer(newValue)} + } + + public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer { + get { + if case .imageTransfer(let v)? = _storage._packetType {return v} + return Com_Apple_Container_Build_V1_ImageTransfer() + } + set {_uniqueStorage()._packetType = .imageTransfer(newValue)} + } + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + /// The packet type. + public enum OneOf_PacketType: Equatable, Sendable { + case io(Com_Apple_Container_Build_V1_IO) + case buildError(Com_Apple_Container_Build_V1_BuildError) + case commandComplete(Com_Apple_Container_Build_V1_RunComplete) + case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer) + case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer) + + } + + public init() {} + + fileprivate var _storage = _StorageClass.defaultInstance +} + +public struct Com_Apple_Container_Build_V1_IO: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The type of IO. + public var type: Com_Apple_Container_Build_V1_Stdio = .stdin + + /// The IO data bytes. + public var data: Data = Data() + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +public struct Com_Apple_Container_Build_V1_BuildError: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The type of build error. + public var type: Com_Apple_Container_Build_V1_BuildErrorType = .buildFailed + + /// Additional message for the build failure. + public var message: String = String() + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// OCI Platform metadata. +public struct Com_Apple_Container_Build_V1_Platform: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var architecture: String = String() + + public var os: String = String() + + public var osVersion: String = String() + + public var osFeatures: [String] = [] + + public var variant: String = String() + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} +} + +/// OCI Descriptor metadata. +public struct Com_Apple_Container_Build_V1_Descriptor: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + public var mediaType: String = String() + + public var digest: String = String() + + public var size: Int64 = 0 + + public var urls: [String] = [] + + public var annotations: Dictionary = [:] + + public var platform: Com_Apple_Container_Build_V1_Platform { + get {_platform ?? Com_Apple_Container_Build_V1_Platform()} + set {_platform = newValue} + } + /// Returns true if `platform` has been explicitly set. + public var hasPlatform: Bool {self._platform != nil} + /// Clears the value of `platform`. Subsequent reads from it will return its default value. + public mutating func clearPlatform() {self._platform = nil} + + public var unknownFields = SwiftProtobuf.UnknownStorage() + + public init() {} + + fileprivate var _platform: Com_Apple_Container_Build_V1_Platform? = nil +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "com.apple.container.build.v1" + +extension Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf._ProtoNameProviding { + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{2}\0INTO\0\u{1}OUTOF\0") +} + +extension Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf._ProtoNameProviding { + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{2}\0STDIN\0\u{1}STDOUT\0\u{1}STDERR\0") +} + +extension Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf._ProtoNameProviding { + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{2}\0BUILD_FAILED\0\u{1}INTERNAL\0") +} + +extension Com_Apple_Container_Build_V1_InfoRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".InfoRequest" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + public mutating func decodeMessage(decoder: inout D) throws { + // Load everything into unknown fields + while try decoder.nextFieldNumber() != nil {} + } + + public func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_InfoRequest, rhs: Com_Apple_Container_Build_V1_InfoRequest) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_InfoResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".InfoResponse" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + public mutating func decodeMessage(decoder: inout D) throws { + // Load everything into unknown fields + while try decoder.nextFieldNumber() != nil {} + } + + public func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_InfoResponse, rhs: Com_Apple_Container_Build_V1_InfoResponse) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_CreateBuildRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".CreateBuildRequest" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}stage_name\0\u{1}tag\0\u{1}metadata\0\u{3}build_args\0\u{1}debug\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.stageName) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.tag) }() + case 3: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }() + case 4: try { try decoder.decodeRepeatedStringField(value: &self.buildArgs) }() + case 5: try { try decoder.decodeSingularBoolField(value: &self.debug) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.stageName.isEmpty { + try visitor.visitSingularStringField(value: self.stageName, fieldNumber: 1) + } + if !self.tag.isEmpty { + try visitor.visitSingularStringField(value: self.tag, fieldNumber: 2) + } + if !self.metadata.isEmpty { + try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 3) + } + if !self.buildArgs.isEmpty { + try visitor.visitRepeatedStringField(value: self.buildArgs, fieldNumber: 4) + } + if self.debug != false { + try visitor.visitSingularBoolField(value: self.debug, fieldNumber: 5) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildRequest, rhs: Com_Apple_Container_Build_V1_CreateBuildRequest) -> Bool { + if lhs.stageName != rhs.stageName {return false} + if lhs.tag != rhs.tag {return false} + if lhs.metadata != rhs.metadata {return false} + if lhs.buildArgs != rhs.buildArgs {return false} + if lhs.debug != rhs.debug {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_CreateBuildResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".CreateBuildResponse" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}build_id\0\u{1}metadata\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.buildID) }() + case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.buildID.isEmpty { + try visitor.visitSingularStringField(value: self.buildID, fieldNumber: 1) + } + if !self.metadata.isEmpty { + try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildResponse, rhs: Com_Apple_Container_Build_V1_CreateBuildResponse) -> Bool { + if lhs.buildID != rhs.buildID {return false} + if lhs.metadata != rhs.metadata {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_ClientStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".ClientStream" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}build_id\0\u{1}signal\0\u{1}command\0\u{3}build_transfer\0\u{3}image_transfer\0") + + fileprivate class _StorageClass { + var _buildID: String = String() + var _packetType: Com_Apple_Container_Build_V1_ClientStream.OneOf_PacketType? + + // This property is used as the initial default value for new instances of the type. + // The type itself is protecting the reference to its storage via CoW semantics. + // This will force a copy to be made of this reference when the first mutation occurs; + // hence, it is safe to mark this as `nonisolated(unsafe)`. + static nonisolated(unsafe) let defaultInstance = _StorageClass() + + private init() {} + + init(copying source: _StorageClass) { + _buildID = source._buildID + _packetType = source._packetType + } + } + + fileprivate mutating func _uniqueStorage() -> _StorageClass { + if !isKnownUniquelyReferenced(&_storage) { + _storage = _StorageClass(copying: _storage) + } + return _storage + } + + public mutating func decodeMessage(decoder: inout D) throws { + _ = _uniqueStorage() + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }() + case 2: try { + var v: Com_Apple_Container_Build_V1_Signal? + var hadOneofValue = false + if let current = _storage._packetType { + hadOneofValue = true + if case .signal(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._packetType = .signal(v) + } + }() + case 3: try { + var v: Com_Apple_Container_Build_V1_Run? + var hadOneofValue = false + if let current = _storage._packetType { + hadOneofValue = true + if case .command(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._packetType = .command(v) + } + }() + case 4: try { + var v: Com_Apple_Container_Build_V1_BuildTransfer? + var hadOneofValue = false + if let current = _storage._packetType { + hadOneofValue = true + if case .buildTransfer(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._packetType = .buildTransfer(v) + } + }() + case 5: try { + var v: Com_Apple_Container_Build_V1_ImageTransfer? + var hadOneofValue = false + if let current = _storage._packetType { + hadOneofValue = true + if case .imageTransfer(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._packetType = .imageTransfer(v) + } + }() + default: break + } + } + } + } + + public func traverse(visitor: inout V) throws { + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if !_storage._buildID.isEmpty { + try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1) + } + switch _storage._packetType { + case .signal?: try { + guard case .signal(let v)? = _storage._packetType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case .command?: try { + guard case .command(let v)? = _storage._packetType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + }() + case .buildTransfer?: try { + guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + }() + case .imageTransfer?: try { + guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 5) + }() + case nil: break + } + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_ClientStream, rhs: Com_Apple_Container_Build_V1_ClientStream) -> Bool { + if lhs._storage !== rhs._storage { + let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in + let _storage = _args.0 + let rhs_storage = _args.1 + if _storage._buildID != rhs_storage._buildID {return false} + if _storage._packetType != rhs_storage._packetType {return false} + return true + } + if !storagesAreEqual {return false} + } + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_Signal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Signal" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}signal\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularInt32Field(value: &self.signal) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if self.signal != 0 { + try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_Signal, rhs: Com_Apple_Container_Build_V1_Signal) -> Bool { + if lhs.signal != rhs.signal {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_Run: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Run" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0\u{1}command\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.id) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.command) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.id.isEmpty { + try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) + } + if !self.command.isEmpty { + try visitor.visitSingularStringField(value: self.command, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_Run, rhs: Com_Apple_Container_Build_V1_Run) -> Bool { + if lhs.id != rhs.id {return false} + if lhs.command != rhs.command {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_RunComplete: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".RunComplete" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.id) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.id.isEmpty { + try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_RunComplete, rhs: Com_Apple_Container_Build_V1_RunComplete) -> Bool { + if lhs.id != rhs.id {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_BuildTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".BuildTransfer" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0\u{1}direction\0\u{1}source\0\u{1}destination\0\u{1}data\0\u{1}complete\0\u{3}is_directory\0\u{1}metadata\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.id) }() + case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }() + case 3: try { try decoder.decodeSingularStringField(value: &self._source) }() + case 4: try { try decoder.decodeSingularStringField(value: &self._destination) }() + case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }() + case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }() + case 7: try { try decoder.decodeSingularBoolField(value: &self.isDirectory) }() + case 8: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if !self.id.isEmpty { + try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) + } + if self.direction != .into { + try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2) + } + try { if let v = self._source { + try visitor.visitSingularStringField(value: v, fieldNumber: 3) + } }() + try { if let v = self._destination { + try visitor.visitSingularStringField(value: v, fieldNumber: 4) + } }() + if !self.data.isEmpty { + try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5) + } + if self.complete != false { + try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6) + } + if self.isDirectory != false { + try visitor.visitSingularBoolField(value: self.isDirectory, fieldNumber: 7) + } + if !self.metadata.isEmpty { + try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 8) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_BuildTransfer, rhs: Com_Apple_Container_Build_V1_BuildTransfer) -> Bool { + if lhs.id != rhs.id {return false} + if lhs.direction != rhs.direction {return false} + if lhs._source != rhs._source {return false} + if lhs._destination != rhs._destination {return false} + if lhs.data != rhs.data {return false} + if lhs.complete != rhs.complete {return false} + if lhs.isDirectory != rhs.isDirectory {return false} + if lhs.metadata != rhs.metadata {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_ImageTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".ImageTransfer" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0\u{1}direction\0\u{1}tag\0\u{1}descriptor\0\u{1}data\0\u{1}complete\0\u{1}metadata\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.id) }() + case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }() + case 3: try { try decoder.decodeSingularStringField(value: &self.tag) }() + case 4: try { try decoder.decodeSingularMessageField(value: &self._descriptor) }() + case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }() + case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }() + case 7: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if !self.id.isEmpty { + try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) + } + if self.direction != .into { + try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2) + } + if !self.tag.isEmpty { + try visitor.visitSingularStringField(value: self.tag, fieldNumber: 3) + } + try { if let v = self._descriptor { + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + } }() + if !self.data.isEmpty { + try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5) + } + if self.complete != false { + try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6) + } + if !self.metadata.isEmpty { + try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 7) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_ImageTransfer, rhs: Com_Apple_Container_Build_V1_ImageTransfer) -> Bool { + if lhs.id != rhs.id {return false} + if lhs.direction != rhs.direction {return false} + if lhs.tag != rhs.tag {return false} + if lhs._descriptor != rhs._descriptor {return false} + if lhs.data != rhs.data {return false} + if lhs.complete != rhs.complete {return false} + if lhs.metadata != rhs.metadata {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_ServerStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".ServerStream" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}build_id\0\u{1}io\0\u{3}build_error\0\u{3}command_complete\0\u{3}build_transfer\0\u{3}image_transfer\0") + + fileprivate class _StorageClass { + var _buildID: String = String() + var _packetType: Com_Apple_Container_Build_V1_ServerStream.OneOf_PacketType? + + // This property is used as the initial default value for new instances of the type. + // The type itself is protecting the reference to its storage via CoW semantics. + // This will force a copy to be made of this reference when the first mutation occurs; + // hence, it is safe to mark this as `nonisolated(unsafe)`. + static nonisolated(unsafe) let defaultInstance = _StorageClass() + + private init() {} + + init(copying source: _StorageClass) { + _buildID = source._buildID + _packetType = source._packetType + } + } + + fileprivate mutating func _uniqueStorage() -> _StorageClass { + if !isKnownUniquelyReferenced(&_storage) { + _storage = _StorageClass(copying: _storage) + } + return _storage + } + + public mutating func decodeMessage(decoder: inout D) throws { + _ = _uniqueStorage() + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }() + case 2: try { + var v: Com_Apple_Container_Build_V1_IO? + var hadOneofValue = false + if let current = _storage._packetType { + hadOneofValue = true + if case .io(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._packetType = .io(v) + } + }() + case 3: try { + var v: Com_Apple_Container_Build_V1_BuildError? + var hadOneofValue = false + if let current = _storage._packetType { + hadOneofValue = true + if case .buildError(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._packetType = .buildError(v) + } + }() + case 4: try { + var v: Com_Apple_Container_Build_V1_RunComplete? + var hadOneofValue = false + if let current = _storage._packetType { + hadOneofValue = true + if case .commandComplete(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._packetType = .commandComplete(v) + } + }() + case 5: try { + var v: Com_Apple_Container_Build_V1_BuildTransfer? + var hadOneofValue = false + if let current = _storage._packetType { + hadOneofValue = true + if case .buildTransfer(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._packetType = .buildTransfer(v) + } + }() + case 6: try { + var v: Com_Apple_Container_Build_V1_ImageTransfer? + var hadOneofValue = false + if let current = _storage._packetType { + hadOneofValue = true + if case .imageTransfer(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._packetType = .imageTransfer(v) + } + }() + default: break + } + } + } + } + + public func traverse(visitor: inout V) throws { + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if !_storage._buildID.isEmpty { + try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1) + } + switch _storage._packetType { + case .io?: try { + guard case .io(let v)? = _storage._packetType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case .buildError?: try { + guard case .buildError(let v)? = _storage._packetType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + }() + case .commandComplete?: try { + guard case .commandComplete(let v)? = _storage._packetType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + }() + case .buildTransfer?: try { + guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 5) + }() + case .imageTransfer?: try { + guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 6) + }() + case nil: break + } + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_ServerStream, rhs: Com_Apple_Container_Build_V1_ServerStream) -> Bool { + if lhs._storage !== rhs._storage { + let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in + let _storage = _args.0 + let rhs_storage = _args.1 + if _storage._buildID != rhs_storage._buildID {return false} + if _storage._packetType != rhs_storage._packetType {return false} + return true + } + if !storagesAreEqual {return false} + } + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_IO: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".IO" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}type\0\u{1}data\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.data) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if self.type != .stdin { + try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1) + } + if !self.data.isEmpty { + try visitor.visitSingularBytesField(value: self.data, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_IO, rhs: Com_Apple_Container_Build_V1_IO) -> Bool { + if lhs.type != rhs.type {return false} + if lhs.data != rhs.data {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_BuildError: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".BuildError" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}type\0\u{1}message\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.message) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if self.type != .buildFailed { + try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1) + } + if !self.message.isEmpty { + try visitor.visitSingularStringField(value: self.message, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_BuildError, rhs: Com_Apple_Container_Build_V1_BuildError) -> Bool { + if lhs.type != rhs.type {return false} + if lhs.message != rhs.message {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_Platform: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Platform" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}architecture\0\u{1}os\0\u{3}os_version\0\u{3}os_features\0\u{1}variant\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.architecture) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.os) }() + case 3: try { try decoder.decodeSingularStringField(value: &self.osVersion) }() + case 4: try { try decoder.decodeRepeatedStringField(value: &self.osFeatures) }() + case 5: try { try decoder.decodeSingularStringField(value: &self.variant) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.architecture.isEmpty { + try visitor.visitSingularStringField(value: self.architecture, fieldNumber: 1) + } + if !self.os.isEmpty { + try visitor.visitSingularStringField(value: self.os, fieldNumber: 2) + } + if !self.osVersion.isEmpty { + try visitor.visitSingularStringField(value: self.osVersion, fieldNumber: 3) + } + if !self.osFeatures.isEmpty { + try visitor.visitRepeatedStringField(value: self.osFeatures, fieldNumber: 4) + } + if !self.variant.isEmpty { + try visitor.visitSingularStringField(value: self.variant, fieldNumber: 5) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_Platform, rhs: Com_Apple_Container_Build_V1_Platform) -> Bool { + if lhs.architecture != rhs.architecture {return false} + if lhs.os != rhs.os {return false} + if lhs.osVersion != rhs.osVersion {return false} + if lhs.osFeatures != rhs.osFeatures {return false} + if lhs.variant != rhs.variant {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Com_Apple_Container_Build_V1_Descriptor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + public static let protoMessageName: String = _protobuf_package + ".Descriptor" + public static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{3}media_type\0\u{1}digest\0\u{1}size\0\u{1}urls\0\u{1}annotations\0\u{1}platform\0") + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.mediaType) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.digest) }() + case 3: try { try decoder.decodeSingularInt64Field(value: &self.size) }() + case 4: try { try decoder.decodeRepeatedStringField(value: &self.urls) }() + case 5: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.annotations) }() + case 6: try { try decoder.decodeSingularMessageField(value: &self._platform) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + if !self.mediaType.isEmpty { + try visitor.visitSingularStringField(value: self.mediaType, fieldNumber: 1) + } + if !self.digest.isEmpty { + try visitor.visitSingularStringField(value: self.digest, fieldNumber: 2) + } + if self.size != 0 { + try visitor.visitSingularInt64Field(value: self.size, fieldNumber: 3) + } + if !self.urls.isEmpty { + try visitor.visitRepeatedStringField(value: self.urls, fieldNumber: 4) + } + if !self.annotations.isEmpty { + try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.annotations, fieldNumber: 5) + } + try { if let v = self._platform { + try visitor.visitSingularMessageField(value: v, fieldNumber: 6) + } }() + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Com_Apple_Container_Build_V1_Descriptor, rhs: Com_Apple_Container_Build_V1_Descriptor) -> Bool { + if lhs.mediaType != rhs.mediaType {return false} + if lhs.digest != rhs.digest {return false} + if lhs.size != rhs.size {return false} + if lhs.urls != rhs.urls {return false} + if lhs.annotations != rhs.annotations {return false} + if lhs._platform != rhs._platform {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/ContainerSystem/Build/Builder/Builder.swift b/ContainerSystem/Build/Builder/Builder.swift new file mode 100644 index 0000000..fcb8913 --- /dev/null +++ b/ContainerSystem/Build/Builder/Builder.swift @@ -0,0 +1,217 @@ +// +// Builder.swift +// Containers +// +// Sandboxed version of Builder that implements build protocol without XPC dependencies +// +// Created by Axel Martinez on 2026/02/09. +// + +import Containerization +import ContainerizationArchive +import ContainerizationError +import ContainerizationOCI +import ContainerizationOS +import CryptoKit +import Foundation +import GRPCCore +import GRPCNIOTransportHTTP2 +import Logging +import NIO +import NIOCore +import NIOHPACK +import NIOHTTP2 +import NIOPosix + +/// Builder that uses ImagesService instead of XPC-based ClientImage +public struct Builder: Sendable { + public static let builderContainerId = "buildkit" + + let client: + Com_Apple_Container_Build_V1_Builder.Client< + HTTP2ClientTransport.WrappedChannel + > + let grpcClient: GRPCClient + let group: EventLoopGroup + let builderShimSocket: FileHandle + let clientTask: Task + let imagesService: ImagesService + let contentStore: ContentStore + + private let logger: Logger + + init( + socket: FileHandle, + group: EventLoopGroup, + imagesService: ImagesService, + contentStore: ContentStore + ) throws { + try socket.setSendBufSize(4 << 20) + try socket.setRecvBufSize(2 << 20) + + let channel = try ClientBootstrap(group: group) + .channelInitializer { channel in + channel.eventLoop.makeCompletedFuture(withResultOf: { + try channel.pipeline.syncOperations.addHandler(HTTP2ConnectBufferingHandler()) + }) + } + .withConnectedSocket(socket.fileDescriptor) + .wait() + + let transport = HTTP2ClientTransport.WrappedChannel.wrapping(channel: channel) + let grpcClient = GRPCClient(transport: transport) + + self.grpcClient = grpcClient + self.client = Com_Apple_Container_Build_V1_Builder.Client(wrapping: grpcClient) + self.group = group + self.builderShimSocket = socket + self.imagesService = imagesService + self.contentStore = contentStore + + var logger = Logger(label: "app.containers.sandboxed-builder") + logger.logLevel = .info + self.logger = logger + self.clientTask = Task { + do { + try await grpcClient.runConnections() + } catch is CancellationError { + throw CancellationError() + } catch let error as RPCError where error.code == .unavailable { + logger.debug("gRPC connection closed: \(error)") + throw error + } catch { + logger.error("gRPC client connection error: \(error)") + throw error + } + } + } + + public func info() async throws -> InfoResponse { + var options = CallOptions.defaults + options.timeout = .seconds(30) + return try await self.client.info(InfoRequest(), options: options) + } + + /// Perform a sandboxed build using custom pipeline that handles image resolution + public func build(_ config: Builder.BuildConfig) async throws { + let logger = Logger(label: "app.containers.sandboxed-builder.build") + logger.info("SandboxedBuilder.build() called with buildID: \(config.id)") + + var continuation: AsyncStream.Continuation? + let reqStream = AsyncStream { + (cont: AsyncStream.Continuation) in + continuation = cont + } + guard let continuation else { + throw BuilderError.invalidContinuation + } + + defer { + continuation.finish() + } + + // Terminal handling would go here if needed + // For now, we skip this as it requires internal TerminalCommand type + + logger.info("Creating gRPC stream to BuildKit") + logger.info("Build config: buildID=\(config.id), contextDir=\(config.contextDir)") + logger.info("Build config: dockerfile size=\(config.dockerfile.count) bytes, tags=\(config.tags)") + logger.info( + "Build config: platforms=\(config.platforms.map { $0.description }), target=\(config.target)" + ) + logger.info("Build config: exports=\(config.exports.map { $0.type })") + + logger.info("Initializing sandboxed build pipeline") + let pipeline = BuildPipeline( + config: config, + imagesService: self.imagesService, + contentStore: self.contentStore + ) + + logger.info("Starting pipeline execution") + + // Start a background task to log progress + let progressTask = Task { + try? await Task.sleep(for: .seconds(30)) + logger.warning("Pipeline has been running for 30 seconds without completion") + try? await Task.sleep(for: .seconds(30)) + logger.error("Pipeline has been running for 60 seconds - BuildKit may not be responding") + } + + do { + try await self.client.performBuild( + metadata: try Self.buildMetadata(config), + options: .defaults, + requestProducer: { writer in + for await message in reqStream { + try await writer.write(message) + } + }, + onResponse: { response in + try await pipeline.run(sender: continuation, receiver: response.messages) + } + ) + progressTask.cancel() + grpcClient.beginGracefulShutdown() + clientTask.cancel() + try await group.shutdownGracefully() + logger.info("Build completed successfully") + } catch { + progressTask.cancel() + + // Check if this is the normal build complete signal + if let builderError = error as? BuilderError, builderError == .buildComplete { + grpcClient.beginGracefulShutdown() + clientTask.cancel() + try await group.shutdownGracefully() + logger.info("Build completed successfully") + return + } + + logger.error("Pipeline execution failed: \(error)") + grpcClient.beginGracefulShutdown() + clientTask.cancel() + try await group.shutdownGracefully() + throw error + } + } + + static func buildMetadata(_ config: Builder.BuildConfig) throws -> Metadata { + var metadata = Metadata() + metadata.addString(config.id, forKey: "build-id") + metadata.addString( + URL(fileURLWithPath: config.contextDir).path(percentEncoded: false), + forKey: "context" + ) + metadata.addString(config.dockerfile.base64EncodedString(), forKey: "dockerfile") + metadata.addString(config.terminal != nil ? "tty" : "plain", forKey: "progress") + metadata.addString(config.target, forKey: "target") + + for tag in config.tags { + metadata.addString(tag, forKey: "tag") + } + for platform in config.platforms { + metadata.addString(platform.description, forKey: "platforms") + } + if config.noCache { + metadata.addString("", forKey: "no-cache") + } + for label in config.labels { + metadata.addString(label, forKey: "labels") + } + for buildArg in config.args { + metadata.addString(buildArg, forKey: "build-args") + } + for output in config.exports { + metadata.addString(try output.stringValue, forKey: "outputs") + } + for cacheIn in config.cacheIn { + metadata.addString(cacheIn, forKey: "cache-in") + } + for cacheOut in config.cacheOut { + metadata.addString(cacheOut, forKey: "cache-out") + } + + return metadata + } +} diff --git a/ContainerSystem/Build/Builder/BuilderController.swift b/ContainerSystem/Build/Builder/BuilderController.swift new file mode 100644 index 0000000..72048a0 --- /dev/null +++ b/ContainerSystem/Build/Builder/BuilderController.swift @@ -0,0 +1,319 @@ +// +// BuilderController.swift +// Containers +// +// Created by Axel Martinez on 2026/02/08. +// + +import Containerization +import ContainerizationError +import ContainerizationExtras +import ContainerizationOCI +import ContainerizationOS +import Foundation +import Logging + +/// Coordinates the BuildKit builder container lifecycle. +@MainActor +final class BuilderController { + private let runtime: ContainerRuntime + private let logger: Logger + + static let builderContainerId = Builder.builderContainerId + + init() { + self.runtime = ContainerRuntime.shared + var logger = Logger(label: "app.containers.builder.controller") + logger.logLevel = .info + self.logger = logger + } + + #if DEBUG + /// Internal initializer for testing - allows injection of test runtime + init(testRuntime: ContainerRuntime) { + self.runtime = testRuntime + var logger = Logger(label: "app.containers.builder.controller.test") + logger.logLevel = .debug + self.logger = logger + } + #endif + + // MARK: - Internal API + + /// Start the BuildKit builder container + /// This method is idempotent - if builder is already running, it will restart it to ensure fresh mounts + func start(cpus: Int64 = 2, memory: UInt64 = 1024.mib(), progress: Progress? = nil) async throws { + logger.info("Starting builder with cpus=\(cpus), memory=\(memory)") + + let containersService = try await runtime.getContainersService() + let imagesService = try await runtime.getImagesService() + let kernelService = try await runtime.getKernelService() + let appRoot = try runtime.getAppRoot() + + let builderImage: String = DefaultsStore.get(key: .defaultBuilderImage) + let exportsMount: String = appRoot.appendingPathComponent(".build").path + + if !FileManager.default.fileExists(atPath: exportsMount) { + try FileManager.default.createDirectory( + atPath: exportsMount, + withIntermediateDirectories: true, + attributes: nil + ) + } + + // Content store path needs to be accessible by builder for image operations + let imagesPath = appRoot.appendingPathComponent("images").path + + // BuildKit data directory - needs to be persistent and support mmap for BoltDB + let buildkitDataPath = appRoot.appendingPathComponent("buildkit-data") + .path + + // Check if BoltDB database exists and might be corrupted + // If BuildKit previously crashed, the database can be in a bad state + let workerDbPath = (buildkitDataPath as NSString) + .appendingPathComponent("worker.db") + if FileManager.default.fileExists(atPath: workerDbPath) { + logger.info("Found existing BuildKit database, checking if it needs cleanup") + // For now, always delete and recreate to avoid corruption issues + // In the future, we could try to validate the database first + try? FileManager.default.removeItem(atPath: buildkitDataPath) + logger.info("Cleaned up BuildKit data directory") + } + + if !FileManager.default.fileExists(atPath: buildkitDataPath) { + try FileManager.default.createDirectory( + atPath: buildkitDataPath, + withIntermediateDirectories: true, + attributes: nil + ) + } + + let builderPlatform = ContainerizationOCI.Platform(arch: "arm64", os: "linux", variant: "v8") + + // Check if builder container already exists + let containerList = await containersService.list() + let existingContainer = containerList.first(where: { + $0.configuration.id == Self.builderContainerId + }) + + if let existingContainer { + logger.info("Found existing builder container, cleaning it up to ensure fresh start") + if existingContainer.status == .running { + do { + try await containersService.stop(id: Self.builderContainerId, options: .default) + } catch { + logger.warning("Failed to stop existing builder, proceeding with delete: \(error)") + } + } + do { + try await containersService.delete(id: Self.builderContainerId) + } catch { + logger.warning("Failed to delete existing builder, continuing anyway: \(error)") + } + } + + let shimArguments: [String] = ["--debug", "--vsock"] + + try validEntityName(Self.builderContainerId) + + let processConfig = ProcessConfiguration( + executable: "/usr/local/bin/container-builder-shim", + arguments: shimArguments, + environment: [], + workingDirectory: "/", + terminal: false, + user: .id(uid: 0, gid: 0) + ) + + var resources = ContainerConfiguration.Resources() + resources.cpus = Int(cpus) + resources.memoryInBytes = memory + + logger.info("Pulling builder image: \(builderImage)") + + let progress = progress ?? Progress(parent: nil) + progress.totalUnitCount = 3 + + let imageDescription = try await progress.performStep("Fetching builder image") { step in + try await imagesService.pull( + reference: builderImage, + platform: builderPlatform, + insecure: false, + progressUpdate: step.updateHandler() + ) + } + + logger.info("Unpacking builder image") + + try await progress.performStep("Unpacking builder image") { step in + try await imagesService.unpack( + description: imageDescription, + platform: builderPlatform, + progressUpdate: step.updateHandler() + ) + } + + var config = ContainerConfiguration( + id: Self.builderContainerId, + image: imageDescription, + process: processConfig + ) + config.resources = resources + config.capabilities = ["ALL"] + config.mounts = [ + .init(type: .tmpfs, source: "", destination: "/run", options: []), + .init( + type: .virtiofs, + source: exportsMount, + destination: "/var/lib/container-builder-shim/exports", + options: [] + ), + .init(type: .virtiofs, source: imagesPath, destination: imagesPath, options: []), + // Use tmpfs for BuildKit data directory because virtiofs doesn't support mmap + // which BoltDB requires. This means BuildKit state is ephemeral (lost on restart) + // but that's acceptable for a build cache. + // However, we need BuildKit to be able to access our content store for images + .init(type: .tmpfs, source: "", destination: "/var/lib/buildkit", options: []), + ] + // Enable Rosetta only if the user didn't ask to disable it + config.rosetta = DefaultsStore.getBool(key: .buildRosetta) ?? true + + // Attach to default network (sandboxed mode uses built-in NAT networking with automatic DNS) + let defaultNetworkName = "default" + config.networks = [ + AttachmentConfiguration( + network: defaultNetworkName, + options: AttachmentOptions(hostname: Self.builderContainerId) + ) + ] + config.dns = ContainerConfiguration.DNSConfiguration() + + try await progress.performStep("Starting BuildKit") { _ in + logger.info("Getting kernel") + let kernel = try await kernelService.getDefaultKernel(platform: .current) + + logger.info("Creating BuildKit container") + let options = ContainerCreateOptions(autoRemove: false) + try await containersService.create(configuration: config, kernel: kernel, options: options) + + try await startBuildKitProcess(service: containersService) + } + + logger.info("Builder started successfully") + } + + /// Restart the builder container to pick up fresh virtiofs mounts + /// This is necessary when new subdirectories have been created in mounted paths + /// because virtiofs in sandboxed apps doesn't dynamically show new subdirectories + func restart(cpus: Int64 = 2, memory: UInt64 = 1024.mib(), progress: Progress? = nil) async throws { + logger.info("Restarting builder to pick up fresh mounts") + + let containersService = try await runtime.getContainersService() + + // Stop the existing builder + let containerList = await containersService.list() + let existingContainer = containerList.first(where: { + $0.configuration.id == Self.builderContainerId + }) + + if let existingContainer { + if existingContainer.status == .running { + logger.info("Stopping existing builder") + do { + try await containersService.stop(id: Self.builderContainerId, options: .default) + } catch { + logger.warning("Failed to cleanly stop existing builder, proceeding with delete: \(error)") + } + } else { + logger.info("Deleting existing builder (status: \(existingContainer.status))") + } + + do { + try await containersService.delete(id: Self.builderContainerId) + } catch { + logger.warning("Failed to delete existing builder cleanly, continuing anyway: \(error)") + } + } + + // Start a fresh builder with the new mounts + try await start(cpus: cpus, memory: memory, progress: progress) + } + + // MARK: - Private Methods + + /// Validate that a name is a valid entity name. + @discardableResult + private func validEntityName(_ name: String) throws -> Bool { + guard !name.isEmpty, name.count <= 255 else { + throw ContainerizationError( + .invalidArgument, + message: "invalid entity name '\(name)': must be between 1 and 255 characters" + ) + } + + let entityNamePattern = "^[A-Za-z0-9][A-Za-z0-9_.-]*$" + let regex = try NSRegularExpression(pattern: entityNamePattern) + let range = NSRange(name.startIndex..., in: name) + + guard regex.firstMatch(in: name, range: range) != nil else { + throw ContainerizationError( + .invalidArgument, + message: "invalid entity name '\(name)': must match \(entityNamePattern)" + ) + } + + return true + } + + private func startBuildKitProcess(service: ContainersService) async throws { + do { + logger.info("Bootstrapping BuildKit container") + + // Create pipes to capture BuildKit's stdout/stderr for debugging + let stdoutPipe = Pipe() + let stderrPipe = Pipe() + + try await service.bootstrap( + id: Self.builderContainerId, + stdio: [nil, stdoutPipe.fileHandleForWriting, stderrPipe.fileHandleForWriting] + ) + + logger.info("Starting BuildKit process") + + logOutput(of: stdoutPipe, named: "stdout", at: .info) + logOutput(of: stderrPipe, named: "stderr", at: .error) + + try await service.startProcess(id: Self.builderContainerId, processID: Self.builderContainerId) + + logger.info("BuildKit process started successfully") + } catch { + logger.error("Failed to start BuildKit: \(error)") + + try? await service.stop(id: Self.builderContainerId, options: .default) + + try? await service.delete(id: Self.builderContainerId) + + if error is ContainerizationError { + throw error + } + + throw ContainerizationError(.internalError, message: "failed to start BuildKit: \(error)") + } + } + + /// Logs what BuildKit writes to a pipe, line by line, until it closes. A + /// pipe that fails to read only ends the logging, never the build. + private func logOutput(of pipe: Pipe, named stream: String, at level: Logger.Level) { + let logger = logger + + Task { + do { + for try await line in pipe.fileHandleForReading.bytes.lines { + logger.log(level: level, "BuildKit \(stream): \(line)") + } + } catch { + logger.warning("Stopped reading BuildKit \(stream): \(error)") + } + } + } +} diff --git a/ContainerSystem/Build/Builder/BuilderError.swift b/ContainerSystem/Build/Builder/BuilderError.swift new file mode 100644 index 0000000..9a718c7 --- /dev/null +++ b/ContainerSystem/Build/Builder/BuilderError.swift @@ -0,0 +1,40 @@ +// +// BuilderError.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import Foundation + +enum BuilderError: Swift.Error, CustomStringConvertible, Equatable { + case invalidContinuation + case imageMissing + case platformMissing + case imageNotFound + case imageNotInContentStore(String) + case unknownPlatformForImage(String, String) + case buildComplete + case buildTimeout + + var description: String { + switch self { + case .invalidContinuation: + return "Failed to create stream continuation" + case .imageMissing: + return "Image reference missing in metadata" + case .platformMissing: + return "Platform parameter missing in metadata" + case .imageNotFound: + return "Image not found in content store" + case .imageNotInContentStore(let ref): + return "Image not found in content store: \(ref)" + case .unknownPlatformForImage(let platform, let ref): + return "Platform \(platform) for image \(ref) not found" + case .buildComplete: + return "Build completed successfully" + case .buildTimeout: + return "Build timed out" + } + } +} diff --git a/ContainerSystem/Build/Builder/BuilderMessages.swift b/ContainerSystem/Build/Builder/BuilderMessages.swift new file mode 100644 index 0000000..c873084 --- /dev/null +++ b/ContainerSystem/Build/Builder/BuilderMessages.swift @@ -0,0 +1,12 @@ +// +// BuilderMessages.swift +// Containers +// + +public typealias IO = Com_Apple_Container_Build_V1_IO +public typealias InfoRequest = Com_Apple_Container_Build_V1_InfoRequest +public typealias InfoResponse = Com_Apple_Container_Build_V1_InfoResponse +public typealias ClientStream = Com_Apple_Container_Build_V1_ClientStream +public typealias ServerStream = Com_Apple_Container_Build_V1_ServerStream +public typealias ImageTransfer = Com_Apple_Container_Build_V1_ImageTransfer +public typealias BuildTransfer = Com_Apple_Container_Build_V1_BuildTransfer diff --git a/ContainerSystem/Build/FileHandle+SocketOptions.swift b/ContainerSystem/Build/FileHandle+SocketOptions.swift new file mode 100644 index 0000000..a7cf402 --- /dev/null +++ b/ContainerSystem/Build/FileHandle+SocketOptions.swift @@ -0,0 +1,35 @@ +// +// FileHandle+SocketOptions.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import Foundation + +extension FileHandle { + @discardableResult + func setSendBufSize(_ bytes: Int) throws -> Int { + try setSockOpt(level: SOL_SOCKET, name: SO_SNDBUF, value: bytes) + return bytes + } + + @discardableResult + func setRecvBufSize(_ bytes: Int) throws -> Int { + try setSockOpt(level: SOL_SOCKET, name: SO_RCVBUF, value: bytes) + return bytes + } + + private func setSockOpt(level: Int32, name: Int32, value: Int) throws { + var socketValue = Int32(value) + let result = withUnsafePointer(to: &socketValue) { pointer -> Int32 in + pointer.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size) { rawPointer in + setsockopt(self.fileDescriptor, level, name, rawPointer, socklen_t(MemoryLayout.size)) + } + } + + if result == -1 { + throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EPERM) + } + } +} diff --git a/ContainerSystem/Build/HTTP2ConnectBufferingHandler.swift b/ContainerSystem/Build/HTTP2ConnectBufferingHandler.swift new file mode 100644 index 0000000..366cbcb --- /dev/null +++ b/ContainerSystem/Build/HTTP2ConnectBufferingHandler.swift @@ -0,0 +1,49 @@ +// +// HTTP2ConnectBufferingHandler.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import NIOCore + +/// Buffers incoming bytes until the gRPC HTTP/2 pipeline is configured. +final class HTTP2ConnectBufferingHandler: + ChannelDuplexHandler, RemovableChannelHandler +{ + typealias InboundIn = ByteBuffer + typealias InboundOut = ByteBuffer + typealias OutboundIn = ByteBuffer + typealias OutboundOut = ByteBuffer + + private var removalScheduled = false + private var bufferedReads: [NIOAny] = [] + + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + bufferedReads.append(data) + } + + func channelReadComplete(context: ChannelHandlerContext) {} + + func flush(context: ChannelHandlerContext) { + if !removalScheduled { + removalScheduled = true + context.eventLoop.assumeIsolatedUnsafeUnchecked().execute { + context.pipeline.syncOperations.removeHandler(self, promise: nil) + } + } + context.flush() + } + + func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { + var didRead = false + while !bufferedReads.isEmpty { + context.fireChannelRead(bufferedReads.removeFirst()) + didRead = true + } + if didRead { + context.fireChannelReadComplete() + } + context.leavePipeline(removalToken: removalToken) + } +} diff --git a/ContainerSystem/Extensions/ImageTransfer+Metadata.swift b/ContainerSystem/Build/ImageTransfer+Metadata.swift similarity index 60% rename from ContainerSystem/Extensions/ImageTransfer+Metadata.swift rename to ContainerSystem/Build/ImageTransfer+Metadata.swift index 779516a..c515acd 100644 --- a/ContainerSystem/Extensions/ImageTransfer+Metadata.swift +++ b/ContainerSystem/Build/ImageTransfer+Metadata.swift @@ -1,47 +1,69 @@ // -// SandboxedBuilder+Extension.swift +// ImageTransfer+Metadata.swift // Containers // -// Created by Axel Martinez on 9/2/26. -// -import Foundation -import ContainerBuild import ContainerizationOCI +import Foundation extension ImageTransfer { + init(id: String, digest: String, ref: String, platform: String, data: Data) throws { + self.init() + self.id = id + self.tag = digest + self.metadata = [ + "os": "linux", + "stage": "resolver", + "method": "/resolve", + "ref": ref, + "platform": platform, + ] + self.complete = true + self.direction = .into + self.data = data + } + func stage() -> String? { self.metadata["stage"] } - + func method() -> String? { self.metadata["method"] } - + func ref() -> String? { self.metadata["ref"] } - + func platform() throws -> Platform? { guard let platform = self.metadata["platform"] else { return nil } return try Platform(from: platform) } - - init(id: String, digest: String, ref: String, platform: String, data: Data) throws { - self.init() - self.id = id - self.tag = digest - self.metadata = [ - "os": "linux", - "stage": "resolver", - "method": "/resolve", - "ref": ref, - "platform": platform, - ] - self.complete = true - self.direction = .into - self.data = data + + func mode() -> String? { + self.metadata["mode"] + } + + func size() -> Int? { + guard let sizeString = self.metadata["size"] else { + return nil + } + return Int(sizeString) + } + + func len() -> Int? { + guard let lengthString = self.metadata["length"] else { + return nil + } + return Int(lengthString) + } + + func offset() -> UInt64? { + guard let offsetString = self.metadata["offset"] else { + return nil + } + return UInt64(offsetString) } } diff --git a/ContainerSystem/Build/ServerStream+Packets.swift b/ContainerSystem/Build/ServerStream+Packets.swift new file mode 100644 index 0000000..b2325f3 --- /dev/null +++ b/ContainerSystem/Build/ServerStream+Packets.swift @@ -0,0 +1,27 @@ +// +// ServerStream+Packets.swift +// Containers +// + +extension ServerStream { + func getImageTransfer() -> ImageTransfer? { + if case .imageTransfer(let transfer) = self.packetType { + return transfer + } + return nil + } + + func getBuildTransfer() -> BuildTransfer? { + if case .buildTransfer(let transfer) = self.packetType { + return transfer + } + return nil + } + + func getIO() -> IO? { + if case .io(let io) = self.packetType { + return io + } + return nil + } +} diff --git a/ContainerSystem/Build/TerminalCommand.swift b/ContainerSystem/Build/TerminalCommand.swift new file mode 100644 index 0000000..1aad62f --- /dev/null +++ b/ContainerSystem/Build/TerminalCommand.swift @@ -0,0 +1,38 @@ +// +// TerminalCommand.swift +// Containers +// +// Created by Axel Martinez on 2026/02/09. +// + +import Foundation + +/// Simple terminal command for sending responses to BuildKit +/// Matches the structure from ContainerBuild/TerminalCommand.swift +struct TerminalCommand: Codable { + let commandType: String + let code: String + let rows: UInt16 + let cols: UInt16 + + enum CodingKeys: String, CodingKey { + case commandType = "command_type" + case code + case rows + case cols + } + + init() { + self.commandType = "terminal" + self.code = "ack" + self.rows = 0 + self.cols = 0 + } + + func json() throws -> String { + let encoder = JSONEncoder() + let data = try encoder.encode(self) + // CRITICAL: The command must be base64 encoded (without padding) + return data.base64EncodedString().trimmingCharacters(in: CharacterSet(charactersIn: "=")) + } +} diff --git a/ContainerSystem/Common/EntityName.swift b/ContainerSystem/Common/EntityName.swift new file mode 100644 index 0000000..7691739 --- /dev/null +++ b/ContainerSystem/Common/EntityName.swift @@ -0,0 +1,34 @@ +// +// EntityName.swift +// ContainerSystem +// +// Created by Axel Martinez on 2026/08/26. +// + +import Foundation + +/// The name a container or a volume can be given. +public enum EntityName { + public static let pattern = "^[A-Za-z0-9][A-Za-z0-9_.-]*$" + public static let maximumLength = 255 + + public static func isValid(_ name: String) -> Bool { + guard !name.isEmpty, name.count <= maximumLength else { return false } + + return name.range(of: pattern, options: .regularExpression) != nil + } + + public static func valid(from name: String) -> String { + let kept = name.filter { character in + character.isASCII + && (character.isLetter || character.isNumber + || character == "_" || character == "." + || character == "-") + } + + let start = + kept.firstIndex { $0.isLetter || $0.isNumber } ?? kept.endIndex + + return String(kept[start...].prefix(maximumLength)) + } +} diff --git a/ContainerSystem/Common/FileDownloader.swift b/ContainerSystem/Common/FileDownloader.swift new file mode 100644 index 0000000..c3d3711 --- /dev/null +++ b/ContainerSystem/Common/FileDownloader.swift @@ -0,0 +1,92 @@ +// +// FileDownloader.swift +// Containers +// +// A download that says how far along it is, for what arrives over HTTP +// rather than as an image. +// + +import Foundation + +/// Downloads a file to `destination`, reporting the bytes as they land. +/// +/// The delegate takes delivery of the file itself. `URLSession`'s async +/// `download(from:)` and its completion-handler form both leave the progress +/// callbacks unsent, so a task with neither is the only one that reports. +final class FileDownloader: NSObject, URLSessionDownloadDelegate, + @unchecked Sendable +{ + private let destination: URL + private let progress: Progress + private var continuation: CheckedContinuation? + + init(destination: URL, progress: Progress) { + self.destination = destination + self.progress = progress + } + + func download(from url: URL) async throws -> URLResponse { + let session = URLSession( + configuration: .default, + delegate: self, + delegateQueue: nil + ) + + defer { + session.finishTasksAndInvalidate() + } + + let task = session.downloadTask(with: url) + + return try await withTaskCancellationHandler { + try Task.checkCancellation() + + return try await withCheckedThrowingContinuation { continuation in + self.continuation = continuation + task.resume() + } + } onCancel: { + task.cancel() + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64 + ) { + progress.kind = .file + progress.fileOperationKind = .downloading + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL + ) { + do { + try? FileManager.default.removeItem(at: destination) + try FileManager.default.moveItem(at: location, to: destination) + continuation?.resume(returning: downloadTask.response ?? URLResponse()) + } catch { + continuation?.resume(throwing: error) + } + + continuation = nil + } + + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didCompleteWithError error: Error? + ) { + guard let error else { return } + + continuation?.resume(throwing: error) + continuation = nil + } +} diff --git a/ContainerSystem/Common/FileIO.swift b/ContainerSystem/Common/FileIO.swift new file mode 100644 index 0000000..f4b425d --- /dev/null +++ b/ContainerSystem/Common/FileIO.swift @@ -0,0 +1,78 @@ +// +// FileIO.swift +// Containers +// +// Blocking filesystem and archive work. +// +// Created by Axel Martinez on 2026/09/02. +// + +import ContainerizationArchive +import Foundation + +/// Copies, moves and archive (un)packing, performed on this actor's executor. +actor FileIO { + static let shared = FileIO() + + func copyItem(at source: URL, to destination: URL) throws { + try FileManager.default.copyItem(at: source, to: destination) + } + + func moveItem(at source: URL, to destination: URL) throws { + try FileManager.default.moveItem(at: source, to: destination) + } + + func contents(of file: URL) throws -> Data { + try Data(contentsOf: file) + } + + /// Extracts `archive` into `directory`, returning the members it rejected. + @discardableResult + func extractArchive(at archive: URL, to directory: URL) throws -> [String] { + let reader = try ArchiveReader(file: archive) + + return try reader.extractContents(to: directory) + } + + func writeArchive(directory: URL, to destination: URL) throws { + let writer = try ArchiveWriter( + format: .pax, + filter: .none, + file: destination + ) + + try writer.archiveDirectory(directory) + try writer.finishEncoding() + } + + /// How much space the files under a directory take on disk. What is + /// counted is what is allocated, so a sparse disk image counts for what has + /// been written to it rather than for the size it was made at. + func allocatedSize(of directory: URL) -> Int64 { + let keys: [URLResourceKey] = [ + .totalFileAllocatedSizeKey, .isRegularFileKey, + ] + + guard + let enumerator = FileManager.default.enumerator( + at: directory, + includingPropertiesForKeys: keys, + errorHandler: { _, _ in true } + ) + else { + return 0 + } + + var total: Int64 = 0 + + for case let url as URL in enumerator { + guard let values = try? url.resourceValues(forKeys: Set(keys)), values.isRegularFile == true else { + continue + } + + total += Int64(values.totalFileAllocatedSize ?? 0) + } + + return total + } +} diff --git a/ContainerSystem/Models/KeyValue.swift b/ContainerSystem/Common/KeyValue.swift similarity index 91% rename from ContainerSystem/Models/KeyValue.swift rename to ContainerSystem/Common/KeyValue.swift index 023477e..48cffa4 100644 --- a/ContainerSystem/Models/KeyValue.swift +++ b/ContainerSystem/Common/KeyValue.swift @@ -6,11 +6,9 @@ // import Foundation -import ContainerAPIService -import ContainerResource /// A mutable key-value pair model for SwiftUI forms and lists -/// +/// /// This type bridges between Swift's native Dictionary type and SwiftUI's requirements /// for Identifiable, mutable collections in forms. It maintains insertion order and /// provides utilities for parsing container configurations. @@ -18,7 +16,7 @@ public struct KeyValue: Identifiable, Equatable, Hashable, Sendable { public let id: UUID public var key: String public var value: String - + /// Creates a new key-value pair /// - Parameters: /// - key: The key string @@ -29,39 +27,42 @@ public struct KeyValue: Identifiable, Equatable, Hashable, Sendable { self.key = key self.value = value } - + /// Creates key-value pairs from container environment variables /// - Parameter snapshot: Container snapshot containing environment variables /// - Returns: Array of key-value pairs parsed from "KEY=VALUE" format - public static func fromEnvironment(_ snapshot: ContainerSnapshot) -> [KeyValue] { + public static func fromEnvironment(_ snapshot: ContainerSnapshot) + -> [KeyValue] + { snapshot.configuration.initProcess.environment .compactMap { Self.parse($0) } } - + /// Creates key-value pairs from container port mappings /// - Parameter snapshot: Container snapshot containing published ports /// - Returns: Array of key-value pairs with host and container port information public static func fromPorts(_ snapshot: ContainerSnapshot) -> [KeyValue] { snapshot.configuration.publishedPorts.map { port in let host = "\(port.hostAddress):\(port.hostPort)" - let container = "\(port.containerPort)[\(port.proto.rawValue.uppercased())]" + let container = + "\(port.containerPort)[\(port.proto.rawValue.uppercased())]" return KeyValue(key: host, value: container) } } - + /// Parses a key-value string in "KEY=VALUE" format /// - Parameter string: String to parse /// - Returns: KeyValue if parsing succeeds, nil if string is invalid public static func parse(_ string: String) -> KeyValue? { let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return nil } - + let parts = trimmed.split(separator: "=", maxSplits: 1) guard parts.count == 2 else { return nil } - + return KeyValue(key: String(parts[0]), value: String(parts[1])) } - + /// Creates key-value pairs from a dictionary /// - Parameter dictionary: Dictionary to convert /// - Returns: Array of key-value pairs (order not guaranteed) @@ -75,9 +76,12 @@ extension Array where Element == KeyValue { /// Converts the array of key-value pairs to a dictionary /// - Returns: Dictionary representation (later values override earlier ones for duplicate keys) var asDictionary: [String: String] { - Dictionary(map { ($0.key, $0.value) }, uniquingKeysWith: { _, last in last }) + Dictionary( + map { ($0.key, $0.value) }, + uniquingKeysWith: { _, last in last } + ) } - + /// Converts the array to environment variable format strings /// - Returns: Array of "KEY=VALUE" formatted strings var asEnvironmentStrings: [String] { diff --git a/ContainerSystem/Container/Bundle.swift b/ContainerSystem/Container/Bundle.swift new file mode 100644 index 0000000..8cf4c8a --- /dev/null +++ b/ContainerSystem/Container/Bundle.swift @@ -0,0 +1,219 @@ +// +// Bundle.swift +// Containers +// +// Container bundle that wraps an OCI bundle with container-specific configuration. +// Stores kernel, init filesystem, container rootfs, and configuration on disk. +// + +import Containerization +import ContainerizationError +import Foundation + +/// A container bundle that manages on-disk storage for a container's configuration, +/// kernel, init filesystem, and root filesystem. +public struct Bundle: Sendable { + + /// The root path of this bundle on disk. + public let path: URL + + // Filenames for bundle contents + private static let configFilename = "config.json" + private static let kernelFilename = "kernel.json" + private static let kernelBinaryFilename = "kernel.bin" + private static let initFsFilename = "initfs.ext4" + private static let rootFsFilename = "rootfs.json" + private static let rootFsBlockFilename = "rootfs.ext4" + private static let optionsFilename = "options.json" + private static let stateFilename = "state.json" + private static let bootLogFilename = "vminitd.log" + + /// What a container carries over from one run to the next. + public struct State: Codable, Sendable { + public let startedDate: Date? + + public init(startedDate: Date? = nil) { + self.startedDate = startedDate + } + } + + /// Load an existing bundle from the given path. + public init(path: URL) { + self.path = path + } + + /// Load the container configuration from disk. + public var configuration: ContainerConfiguration { + get throws { + try load(filename: Self.configFilename) + } + } + + /// Load the kernel configuration from disk. + public var kernel: Kernel { + get throws { + try load(filename: Self.kernelFilename) + } + } + + /// The initial filesystem, described from the copy the bundle holds + /// rather than from a stored descriptor pointing elsewhere. + public var initialFilesystem: Filesystem { + Filesystem( + type: .block(format: "ext4"), + source: path.appendingPathComponent(Self.initFsFilename).path, + destination: "/", + options: ["ro"] + ) + } + + /// Where the VM writes its console output. + public var bootLog: URL { + path.appendingPathComponent(Self.bootLogFilename) + } + + /// The block holding the container's own root filesystem. + public var containerRootfsBlock: URL { + path.appendingPathComponent(Self.rootFsBlockFilename) + } + + /// Load the container root filesystem configuration from disk. + public var containerRootfs: Filesystem { + get throws { + try load(filename: Self.rootFsFilename) + } + } + + /// Create a new container bundle at the given path. + public static func create( + path: URL, + initialFilesystem: Filesystem, + kernel: Kernel, + containerConfiguration: ContainerConfiguration, + options: ContainerCreateOptions? = nil + ) throws -> Bundle { + let fm = FileManager.default + + try fm.createDirectory(at: path, withIntermediateDirectories: true) + + let bundle = Bundle(path: path) + + // The kernel binary is copied in, so the container keeps booting the + // one it was made with even if the original moves or is replaced. + var kernel = kernel + let kernelBinary = path.appendingPathComponent(kernelBinaryFilename) + try fm.copyItem(at: kernel.path, to: kernelBinary) + kernel.path = kernelBinary + + try bundle.write(filename: kernelFilename, value: kernel) + + // The init filesystem is cloned in for the same reason, which is why + // `initialFilesystem` reads from the bundle instead of a descriptor. + guard case .block(let format, _, _) = initialFilesystem.type, + format == "ext4" + else { + throw ContainerizationError( + .invalidArgument, + message: "initial filesystem must be an ext4 block" + ) + } + + try fm.copyItem( + atPath: initialFilesystem.source, + toPath: path.appendingPathComponent(initFsFilename).path + ) + + try bundle.write( + filename: configFilename, + value: containerConfiguration + ) + + if let options { + try bundle.write(filename: optionsFilename, value: options) + } + + return bundle + } + + /// Point the container root filesystem at a filesystem that already sits + /// where it is going to stay. + public func setContainerRootFs(_ fs: Filesystem) throws { + try write(filename: Self.rootFsFilename, value: fs) + } + + /// Clone a filesystem into the bundle and make it the container root. + public func cloneContainerRootFs( + cloning source: Filesystem, + readonly: Bool = false + ) throws { + var options = source.options + if readonly, !options.contains("ro") { + options.append("ro") + } + + try FileManager.default.copyItem( + atPath: source.source, + toPath: containerRootfsBlock.path + ) + + try setContainerRootFs( + Filesystem( + type: source.type, + source: containerRootfsBlock.path, + destination: source.destination, + options: options + ) + ) + } + + /// The options the container was created with, so that what they ask for + /// still holds on a later run of the app. + public var createOptions: ContainerCreateOptions { + get throws { + try load(filename: Self.optionsFilename) + } + } + + /// What the container kept from its last run, empty until it has had one. + public var state: State { + (try? load(filename: Self.stateFilename)) ?? State() + } + + public func setState(_ state: State) throws { + try write(filename: Self.stateFilename, value: state) + } + + /// Delete this bundle and all its contents from disk. + public func delete() throws { + let fm = FileManager.default + if fm.fileExists(atPath: path.path) { + try fm.removeItem(at: path) + } + } + + /// Write a Codable value to a file in the bundle. + public func write(filename: String, value: T) throws { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes] + + let data = try encoder.encode(value) + let file = path.appendingPathComponent(filename) + try data.write(to: file) + } + + /// Load a Codable value from a file in the bundle. + public func load(filename: String) throws -> T { + let file = path.appendingPathComponent(filename) + + guard FileManager.default.fileExists(atPath: file.path) else { + throw ContainerizationError( + .notFound, + message: "bundle file not found: \(filename)" + ) + } + + let data = try Data(contentsOf: file) + let decoder = JSONDecoder() + return try decoder.decode(T.self, from: data) + } +} diff --git a/ContainerSystem/Container/ContainerConfiguration.swift b/ContainerSystem/Container/ContainerConfiguration.swift new file mode 100644 index 0000000..c253d43 --- /dev/null +++ b/ContainerSystem/Container/ContainerConfiguration.swift @@ -0,0 +1,137 @@ +// +// ContainerConfiguration.swift +// Containers +// +// Local implementation of ContainerConfiguration (replaces ContainerResource.ContainerConfiguration) +// + +import ContainerizationOCI +import Foundation + +/// Configuration for a container instance. +public struct ContainerConfiguration: Sendable, Codable { + + /// DNS resolver configuration. + public struct DNSConfiguration: Sendable, Codable { + public let nameservers: [String] + public let domain: String? + public let searchDomains: [String] + public let options: [String] + + public static let defaultNameservers = ["1.1.1.1"] + + public init( + nameservers: [String] = defaultNameservers, + domain: String? = nil, + searchDomains: [String] = [], + options: [String] = [] + ) { + self.nameservers = nameservers + self.domain = domain + self.searchDomains = searchDomains + self.options = options + } + } + + /// Resource limits for the container. + public struct Resources: Sendable, Codable { + public var cpus: Int + public var memoryInBytes: UInt64 + public var storage: UInt64? + + public init( + cpus: Int = 2, + memoryInBytes: UInt64 = 2 * 1024 * 1024 * 1024, + storage: UInt64? = nil + ) { + self.cpus = cpus + self.memoryInBytes = memoryInBytes + self.storage = storage + } + } + + public var id: String + public var image: ImageDescription + public var mounts: [Filesystem] = [] + public var publishedPorts: [PublishPort] = [] + public var publishedSockets: [PublishSocket] = [] + public var labels: [String: String] = [:] + public var sysctls: [String: String] = [:] + public var networks: [AttachmentConfiguration] = [] + public var dns: DNSConfiguration? + public var rosetta: Bool = false + public var initProcess: ProcessConfiguration + public var platform: Platform = .current + public var resources: Resources = Resources() + public var virtualization: Bool = false + public var ssh: Bool = false + public var useInit: Bool = false + public var readOnly: Bool = false + public var capabilities: [String] = [] + public var shmSize: UInt64? + public var stopSignal: String? + public var creationDate: Date = Date() + + enum CodingKeys: String, CodingKey { + case id + case image + case mounts + case publishedPorts + case publishedSockets + case labels + case sysctls + case networks + case dns + case rosetta + case initProcess + case platform + case resources + case virtualization + case ssh + case useInit + case readOnly + case capabilities + case shmSize + case stopSignal + case creationDate + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.id = try container.decode(String.self, forKey: .id) + self.image = try container.decode(ImageDescription.self, forKey: .image) + self.mounts = try container.decodeIfPresent([Filesystem].self, forKey: .mounts) ?? [] + self.publishedPorts = try container.decodeIfPresent([PublishPort].self, forKey: .publishedPorts) ?? [] + self.publishedSockets = try container.decodeIfPresent([PublishSocket].self, forKey: .publishedSockets) ?? [] + self.labels = try container.decodeIfPresent([String: String].self, forKey: .labels) ?? [:] + self.sysctls = try container.decodeIfPresent([String: String].self, forKey: .sysctls) ?? [:] + self.networks = try container.decodeIfPresent([AttachmentConfiguration].self, forKey: .networks) ?? [] + self.dns = try container.decodeIfPresent(DNSConfiguration.self, forKey: .dns) + self.rosetta = try container.decodeIfPresent(Bool.self, forKey: .rosetta) ?? false + self.initProcess = try container.decode(ProcessConfiguration.self, forKey: .initProcess) + self.platform = try container.decodeIfPresent(Platform.self, forKey: .platform) ?? .current + self.resources = try container.decodeIfPresent(Resources.self, forKey: .resources) ?? Resources() + self.virtualization = try container.decodeIfPresent(Bool.self, forKey: .virtualization) ?? false + self.ssh = try container.decodeIfPresent(Bool.self, forKey: .ssh) ?? false + self.useInit = try container.decodeIfPresent(Bool.self, forKey: .useInit) ?? false + self.readOnly = try container.decodeIfPresent(Bool.self, forKey: .readOnly) ?? false + self.capabilities = try container.decodeIfPresent([String].self, forKey: .capabilities) ?? [] + self.shmSize = try container.decodeIfPresent(UInt64.self, forKey: .shmSize) + self.stopSignal = try container.decodeIfPresent(String.self, forKey: .stopSignal) + self.creationDate = try container.decodeIfPresent(Date.self, forKey: .creationDate) ?? Date(timeIntervalSince1970: 0) + } + + public init(id: String, image: ImageDescription, process: ProcessConfiguration) { + self.id = id + self.image = image + self.initProcess = process + } + + public init() { + let image = ImageDescription( + reference: "", + descriptor: Descriptor(mediaType: "", digest: "", size: 0) + ) + self.init(id: "", image: image, process: ProcessConfiguration(executable: "")) + } +} diff --git a/ContainerSystem/Container/ContainerOptions.swift b/ContainerSystem/Container/ContainerOptions.swift new file mode 100644 index 0000000..93a7a95 --- /dev/null +++ b/ContainerSystem/Container/ContainerOptions.swift @@ -0,0 +1,51 @@ +// +// ContainerOptions.swift +// Containers +// +// Local implementation of container create/stop options (replaces ContainerResource types) +// + +import Foundation + +/// Options for creating a container. +public struct ContainerCreateOptions: Sendable, Codable { + public let autoRemove: Bool + + public init(autoRemove: Bool = false) { + self.autoRemove = autoRemove + } +} + +/// Options for stopping a container. +public struct ContainerStopOptions: Sendable, Codable { + public var timeoutInSeconds: Int32 + public var signal: Int32 + + public init(timeoutInSeconds: Int32 = 10, signal: Int32 = SIGTERM) { + self.timeoutInSeconds = timeoutInSeconds + self.signal = signal + } + + /// Default stop options (SIGTERM with 10 second timeout). + public static let `default` = ContainerStopOptions() +} + +/// Options for managing the container +public struct ContainerManagementOptions: Sendable { + public var name = "" + public var kernel: String? + public var entryPoint: String? + public var networks: [String] = [] + public var cidfile = "" + public var deleteOnTermination = false + + // MARK: DNS + + public var dnsDisabled = false + public var dnsNameservers: [String] = [] + public var dnsDomain: String? = nil + public var dnsSearchDomains: [String] = [] + public var dnsOptions: [String] = [] + + public init() {} +} diff --git a/ContainerSystem/Models/ContainerProcess.swift b/ContainerSystem/Container/ContainerProcess.swift similarity index 98% rename from ContainerSystem/Models/ContainerProcess.swift rename to ContainerSystem/Container/ContainerProcess.swift index ce232f4..be515f1 100644 --- a/ContainerSystem/Models/ContainerProcess.swift +++ b/ContainerSystem/Container/ContainerProcess.swift @@ -15,6 +15,6 @@ public struct ContainerProcess: Sendable { public var envFile: [String] = [] public var tty = false public var user: String? - + public init() {} } diff --git a/ContainerSystem/Container/ContainerResourceUsage.swift b/ContainerSystem/Container/ContainerResourceUsage.swift new file mode 100644 index 0000000..ce4e118 --- /dev/null +++ b/ContainerSystem/Container/ContainerResourceUsage.swift @@ -0,0 +1,14 @@ +// +// ContainerResourceUsage.swift +// Containers +// +// Created by Axel Martinez on 15/09/2026. +// + +import Foundation + +public struct ContainerResourceUsage: Sendable { + public let id: String + public let memoryBytes: UInt64 + public let cpuUsageMicroseconds: UInt64 +} diff --git a/ContainerSystem/Container/ContainerSnapshot.swift b/ContainerSystem/Container/ContainerSnapshot.swift new file mode 100644 index 0000000..97f6210 --- /dev/null +++ b/ContainerSystem/Container/ContainerSnapshot.swift @@ -0,0 +1,50 @@ +// +// ContainerSnapshot.swift +// Containers +// + +import ContainerizationOCI +import Foundation + +public enum ContainerStatus: String, Sendable, Codable, Hashable { + case starting + case running + case stopped + case stopping + case unknown +} + +public struct ContainerSnapshot: Sendable, Codable { + public var configuration: ContainerConfiguration + public var status: ContainerStatus + public var networks: [Attachment] + public var startedDate: Date? + + public var id: String { + configuration.id + } + + public var platform: Platform { + configuration.platform + } + + public var volumeNames: [String] { + configuration.mounts.compactMap(\.volumeName) + } + + public var volumeFSs: [Filesystem] { + configuration.mounts.filter(\.isVolume) + } + + public init( + configuration: ContainerConfiguration, + status: ContainerStatus, + networks: [Attachment], + startedDate: Date? = nil + ) { + self.configuration = configuration + self.status = status + self.networks = networks + self.startedDate = startedDate + } +} diff --git a/ContainerSystem/Container/Filesystem.swift b/ContainerSystem/Container/Filesystem.swift new file mode 100644 index 0000000..58a8943 --- /dev/null +++ b/ContainerSystem/Container/Filesystem.swift @@ -0,0 +1,162 @@ +// +// Filesystem.swift +// Containers +// +// Created by Axel Martinez on 2026/02/04. +// + +import Foundation +import SystemPackage + +/// Represents a host filesystem attachment for a container. +public struct Filesystem: Sendable, Codable { + + /// Cache mode for block devices. + public enum CacheMode: String, Sendable, Codable, Equatable { + case on + case off + case auto + } + + /// Sync mode for block devices. + public enum SyncMode: String, Sendable, Codable, Equatable { + case full + case fsync + case nosync + case none = "" + } + + /// The type of filesystem mount. + public enum FilesystemType: Sendable, Codable, Equatable { + case block( + format: String, + cache: CacheMode = .auto, + sync: SyncMode = .none + ) + case volume( + name: String, + format: String, + cache: CacheMode = .auto, + sync: SyncMode = .none + ) + case virtiofs + case tmpfs + } + + public var type: FilesystemType + public var source: String + public var destination: String + public var options: [String] + + public init( + type: FilesystemType, + source: String, + destination: String, + options: [String] + ) { + self.type = type + self.source = source + self.destination = destination + self.options = options + } + + // MARK: - Computed Properties + + public var isVirtiofs: Bool { + if case .virtiofs = type { return true } + return false + } + + public var isBlock: Bool { + if case .block = type { return true } + return false + } + + public var isVolume: Bool { + if case .volume = type { return true } + return false + } + + public var isTmpfs: Bool { + if case .tmpfs = type { return true } + return false + } + + public var volumeName: String? { + if case .volume(let name, _, _, _) = type { + return name + } + return nil + } + + // MARK: - Factory Methods + + /// Create a block device filesystem mount. + public static func block( + format: String = "ext4", + source: String, + destination: String, + cache: CacheMode = .auto, + sync: SyncMode = .none, + options: [String] = [] + ) -> Filesystem { + Filesystem( + type: .block(format: format, cache: cache, sync: sync), + source: source, + destination: destination, + options: options + ) + } + + /// Create a volume-based filesystem mount. + public static func volume( + name: String, + format: String, + source: String, + destination: String, + options: [String] = [] + ) -> Filesystem { + Filesystem( + type: .volume(name: name, format: format), + source: source, + destination: destination, + options: options + ) + } + + /// Create a virtiofs shared filesystem mount. + public static func virtiofs( + source: String, + destination: String, + options: [String] = [] + ) -> Filesystem { + Filesystem( + type: .virtiofs, + source: source, + destination: destination, + options: options + ) + } + + /// Create a tmpfs temporary filesystem mount. + public static func tmpfs(destination: String, options: [String] = []) -> Filesystem { + Filesystem( + type: .tmpfs, + source: "", + destination: destination, + options: options + ) + } + + // MARK: - Cloning + + /// Creates a copy-on-write clone of the filesystem source. + public func clone(to destination: URL) throws { + let srcPath = FilePath(source) + let dstPath = FilePath(destination.path) + try FileManager.default.copyItem( + atPath: srcPath.string, + toPath: dstPath.string + ) + } +} diff --git a/ContainerSystem/Container/Parser.swift b/ContainerSystem/Container/Parser.swift new file mode 100644 index 0000000..124ef07 --- /dev/null +++ b/ContainerSystem/Container/Parser.swift @@ -0,0 +1,400 @@ +// +// Parser.swift +// Containers +// +// Utility for parsing container configuration values. +// + +import ContainerizationExtras +import ContainerizationOCI +import Foundation + +/// Utility for parsing container configuration values. +public enum Parser { + + /// Create a Platform from os and arch strings. + public static func platform(os: String, arch: String) -> Platform { + var variant: String? = nil + if arch == "arm64" { + variant = "v8" + } + return Platform(arch: arch, os: os, variant: variant) + } + + /// Parse a platform string (e.g. "linux/arm64") into a Platform. + public static func platform( + from platformString: String + ) throws -> Platform { + let parts = platformString.split(separator: "/") + guard parts.count >= 2 else { + return platform(os: "linux", arch: platformString) + } + let os = String(parts[0]) + let arch = String(parts[1]) + let variant = parts.count > 2 ? String(parts[2]) : nil + return Platform(arch: arch, os: os, variant: variant) + } + + /// Merge environment variables from image config, env files, and explicit envs. + public static func allEnv( + imageEnvs: [String], + envFiles: [String], + envs: [String] + ) throws -> [String] { + var result = imageEnvs + + // Parse env files + for envFile in envFiles { + let contents = try String(contentsOfFile: envFile, encoding: .utf8) + let lines = contents.components(separatedBy: .newlines) + for line in lines { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if !trimmed.isEmpty && !trimmed.hasPrefix("#") { + result.append(trimmed) + } + } + } + + // Add explicit environment variables (these override earlier ones) + result.append(contentsOf: envs) + + return result + } + + /// Parse user specification into a ProcessConfiguration.User and supplemental groups. + public static func user( + user: String?, + uid: UInt32?, + gid: UInt32?, + defaultUser: ProcessConfiguration.User + ) -> (ProcessConfiguration.User, [UInt32]) { + if let user = user, !user.isEmpty { + return (.raw(userString: user), []) + } + + if let uidValue = uid { + let gidValue = gid ?? uidValue + return (.id(uid: uidValue, gid: gidValue), []) + } + + return (defaultUser, []) + } + + // MARK: - Mount Parsing + + /// Parse a mount string into a Filesystem. + /// Supports formats: + /// - Short: `source:destination[:options]` + /// - Named: `type=volume,source=name,destination=/path,volume-opt=key=value` + public static func mount(from spec: String) throws -> Filesystem { + // Named format: key=value pairs separated by commas + if spec.contains("=") && !spec.hasPrefix("/") { + return try parseNamedMount(spec) + } + + // Short format: source:destination[:options] + let parts = spec.split(separator: ":", maxSplits: 2).map(String.init) + guard parts.count >= 2 else { + throw ParserError.invalidMountSpec("invalid mount spec: \(spec)") + } + + let source = parts[0] + let destination = parts[1] + let options = + parts.count > 2 + ? parts[2].split(separator: ",").map(String.init) : [] + + // Determine if this is a volume or bind mount + if source.hasPrefix("/") || source.hasPrefix(".") + || source.hasPrefix("~") + { + // Bind mount (virtiofs) + return Filesystem( + type: .virtiofs, + source: source, + destination: destination, + options: options + ) + } + + // Named volume + return Filesystem.volume( + name: source, + format: "ext4", + source: "", + destination: destination, + options: options + ) + } + + private static func parseNamedMount(_ spec: String) throws -> Filesystem { + var pairs: [String: String] = [:] + var volumeOpts: [String] = [] + + for component in spec.split(separator: ",") { + let kv = component.split(separator: "=", maxSplits: 1).map( + String.init + ) + guard kv.count == 2 else { continue } + + if kv[0] == "volume-opt" { + volumeOpts.append(kv[1]) + } else { + pairs[kv[0]] = kv[1] + } + } + + let destination = + pairs["destination"] ?? pairs["dst"] ?? pairs["target"] ?? "/" + let source = pairs["source"] ?? pairs["src"] ?? "" + let typeStr = pairs["type"] ?? "volume" + + switch typeStr { + case "volume": + let name = + source.isEmpty + ? VolumeStorage.generateAnonymousVolumeName() : source + return Filesystem.volume( + name: name, + format: "ext4", + source: "", + destination: destination, + options: volumeOpts + ) + case "bind": + return Filesystem( + type: .virtiofs, + source: source, + destination: destination, + options: volumeOpts + ) + case "tmpfs": + return Filesystem( + type: .tmpfs, + source: "", + destination: destination, + options: volumeOpts + ) + default: + throw ParserError.invalidMountSpec( + "unsupported mount type: \(typeStr)" + ) + } + } + + // MARK: - Port Parsing + + /// Parse a port specification string into a PublishPort. + /// Supports Docker-compatible formats: + /// - `containerPort` (e.g. "80") + /// - `hostPort:containerPort` (e.g. "8080:80") + /// - `hostPort:containerPort/protocol` (e.g. "8080:80/tcp") + /// - `hostIP:hostPort:containerPort` (e.g. "127.0.0.1:8080:80") + /// - `hostIP:hostPort:containerPort/protocol` (e.g. "0.0.0.0:8080:80/udp") + /// - Port ranges: `hostStart-hostEnd:containerStart-containerEnd` + public static func port(from spec: String) throws -> PublishPort { + var spec = spec + + // Extract protocol suffix + var proto = PublishProtocol.tcp + if let slashIdx = spec.lastIndex(of: "/") { + let protoStr = String(spec[spec.index(after: slashIdx)...]) + proto = PublishProtocol(protoStr) + spec = String(spec[.. ( + start: UInt16, count: UInt16 + ) { + if range.contains("-") { + let bounds = range.split(separator: "-").map(String.init) + guard bounds.count == 2, + let start = UInt16(bounds[0]), + let end = UInt16(bounds[1]), + end >= start + else { + throw ParserError.invalidPortSpec( + "invalid port range: \(range)" + ) + } + return (start, end - start + 1) + } + + guard let port = UInt16(range) else { + throw ParserError.invalidPortSpec("invalid port number: \(range)") + } + return (port, 1) + } + + // MARK: - Memory Parsing + + /// Parse a human-readable memory string into bytes. + /// Supports: "512m", "1g", "1024k", "1073741824", "2.5g", "64mib" + public static func memoryInBytes(from spec: String) throws -> UInt64 { + let trimmed = spec.trimmingCharacters(in: .whitespaces).lowercased() + + guard !trimmed.isEmpty else { + throw ParserError.invalidMemorySpec("empty memory specification") + } + + // Pure numeric value (already in bytes) + if let bytes = UInt64(trimmed) { + return bytes + } + + // Extract numeric part and suffix + let suffixChars: Set = [ + "k", "m", "g", "t", "p", "b", "i", + ] + var numericPart = trimmed + var suffix = "" + + while let last = numericPart.last, suffixChars.contains(last) { + suffix = String(last) + suffix + numericPart.removeLast() + } + + guard let value = Double(numericPart), value > 0 else { + throw ParserError.invalidMemorySpec( + "invalid numeric value in: \(spec)" + ) + } + + // Every unit is a binary one, so "m", "mb" and "mib" all name the + // same size, the way the container CLI reads them. + let multiplier: Double + switch suffix { + case "k", "kb", "kib": + multiplier = 1024 + case "m", "mb", "mib": + multiplier = 1024 * 1024 + case "g", "gb", "gib": + multiplier = 1024 * 1024 * 1024 + case "t", "tb", "tib": + multiplier = 1024 * 1024 * 1024 * 1024 + case "p", "pb", "pib": + multiplier = 1024 * 1024 * 1024 * 1024 * 1024 + case "b", "": + multiplier = 1 + default: + throw ParserError.invalidMemorySpec( + "unknown memory suffix: \(suffix)" + ) + } + + let bytes = value * multiplier + + guard bytes < Double(UInt64.max) else { + throw ParserError.invalidMemorySpec( + "memory value out of range: \(spec)" + ) + } + + return UInt64(bytes) + } + + // MARK: - Rlimit Parsing + + /// Parse an rlimit specification: `type=soft:hard` or `type=value` + public static func rlimit(from spec: String) throws + -> ProcessConfiguration.Rlimit + { + let parts = spec.split(separator: "=", maxSplits: 1).map(String.init) + guard parts.count == 2 else { + throw ParserError.invalidRlimitSpec( + "invalid rlimit format: \(spec)" + ) + } + + let limitType = parts[0] + let values = parts[1].split(separator: ":").map(String.init) + + guard let soft = UInt64(values[0]) else { + throw ParserError.invalidRlimitSpec( + "invalid soft limit: \(values[0])" + ) + } + + let hard: UInt64 + if values.count > 1 { + guard let h = UInt64(values[1]) else { + throw ParserError.invalidRlimitSpec( + "invalid hard limit: \(values[1])" + ) + } + hard = h + } else { + hard = soft + } + + return ProcessConfiguration.Rlimit( + limit: limitType, + soft: soft, + hard: hard + ) + } +} + +// MARK: - Parser Errors + +public enum ParserError: Error, LocalizedError { + case invalidMountSpec(String) + case invalidPortSpec(String) + case invalidMemorySpec(String) + case invalidRlimitSpec(String) + + public var errorDescription: String? { + switch self { + case .invalidMountSpec(let msg): return msg + case .invalidPortSpec(let msg): return msg + case .invalidMemorySpec(let msg): return msg + case .invalidRlimitSpec(let msg): return msg + } + } +} diff --git a/ContainerSystem/Container/ProcessConfiguration.swift b/ContainerSystem/Container/ProcessConfiguration.swift new file mode 100644 index 0000000..3b1ebe8 --- /dev/null +++ b/ContainerSystem/Container/ProcessConfiguration.swift @@ -0,0 +1,69 @@ +// +// ProcessConfiguration.swift +// Containers +// +// Local implementation of ProcessConfiguration (replaces ContainerResource.ProcessConfiguration) +// + +import Foundation + +/// Configuration for a process running inside a container. +public struct ProcessConfiguration: Sendable, Codable { + + /// Represents a user identity for the process. + public enum User: Sendable, Codable, Equatable, CustomStringConvertible { + case raw(userString: String) + case id(uid: UInt32, gid: UInt32) + + public var description: String { + switch self { + case .raw(let userString): + return userString + case .id(let uid, let gid): + return "\(uid):\(gid)" + } + } + } + + /// Resource limit configuration. + public struct Rlimit: Sendable, Codable { + public let limit: String + public let soft: UInt64 + public let hard: UInt64 + + public init(limit: String, soft: UInt64, hard: UInt64) { + self.limit = limit + self.soft = soft + self.hard = hard + } + } + + public var executable: String + public var arguments: [String] + public var environment: [String] + public var workingDirectory: String + public var terminal: Bool + public var user: User + public var supplementalGroups: [UInt32] + public var rlimits: [Rlimit] + + public init( + executable: String, + arguments: [String] = [], + environment: [String] = [], + workingDirectory: String = "/", + terminal: Bool = false, + user: User = .id(uid: 0, gid: 0), + supplementalGroups: [UInt32] = [], + rlimits: [Rlimit] = [] + ) { + self.executable = executable + self.arguments = arguments + self.environment = environment + self.workingDirectory = workingDirectory + self.terminal = terminal + self.user = user + self.supplementalGroups = supplementalGroups + self.rlimits = rlimits + } +} diff --git a/ContainerSystem/Container/PublishPort.swift b/ContainerSystem/Container/PublishPort.swift new file mode 100644 index 0000000..3eebe17 --- /dev/null +++ b/ContainerSystem/Container/PublishPort.swift @@ -0,0 +1,81 @@ +// +// PublishPort.swift +// Containers +// +// Local implementation of PublishPort (replaces ContainerResource.PublishPort) +// + +import ContainerizationExtras +import Foundation + +/// Network protocol for published ports. +public enum PublishProtocol: String, Sendable, Codable, CaseIterable { + case tcp + case udp + + public init() { + self = .tcp + } + + public init(_ value: String) { + switch value.lowercased() { + case "udp": + self = .udp + default: + self = .tcp + } + } +} + +/// Represents a port forwarding rule from host to container. +public struct PublishPort: Sendable, Codable { + public let hostAddress: IPAddress + public let hostPort: UInt16 + public let containerPort: UInt16 + public let proto: PublishProtocol + public let count: UInt16 + + public init( + hostAddress: IPAddress? = try? IPAddress("127.0.0.1"), + hostPort: UInt16, + containerPort: UInt16, + proto: PublishProtocol = .tcp, + count: UInt16 = 1 + ) { + guard let hostAddress else { + fatalError("Invalid IP Addess") + } + + self.hostAddress = hostAddress + self.hostPort = hostPort + self.containerPort = containerPort + self.proto = proto + self.count = count + } +} + +extension PublishPort: CustomStringConvertible { + public var description: String { + "\(self.hostPort):\(self.containerPort) (\(self.proto.rawValue.localizedUppercase))" + } +} + +extension Array where Element == PublishPort { + /// Check for overlapping port configurations. + public func hasOverlaps() -> Bool { + var seen = Set() + for port in self { + // Counted in Int: a range reaching the top of the port range + // would overflow UInt16 and trap on the way there. + for offset in 0.. Bool { + func isPluginRunning(pluginName: String, instanceId: String) -> Bool { let processKey = "\(pluginName).\(instanceId)" - + guard let info = pluginProcesses[processKey] else { return false } - + return info.process.isRunning } - + /// Get the PID of a running plugin - internal func getPluginPid(pluginName: String, instanceId: String) -> Int32? { + func getPluginPid( + pluginName: String, + instanceId: String + ) -> Int32? { let processKey = "\(pluginName).\(instanceId)" - - guard let info = pluginProcesses[processKey], info.process.isRunning else { + + guard let info = pluginProcesses[processKey], info.process.isRunning + else { return nil } - + return info.process.processIdentifier } - + /// Stop all running plugin processes - internal func stopAllPlugins() { - Self.logger.info("Stopping all plugin processes...") - + func stopAllPlugins() { + logger.info("Stopping all plugin processes...") + for (key, info) in pluginProcesses { - Self.logger.info("Stopping: \(key)") + logger.info("Stopping: \(key)") if info.process.isRunning { info.process.terminate() } info.standardOutput?.fileHandleForReading.readabilityHandler = nil info.standardError?.fileHandleForReading.readabilityHandler = nil } - + pluginProcesses.removeAll() } - + private func handlePluginTermination(processKey: String, exitCode: Int32) { - Self.logger.info("Plugin process terminated: \(processKey) with exit code: \(exitCode)") - + logger.info( + "Plugin process terminated: \(processKey) with exit code: \(exitCode)" + ) + if let info = pluginProcesses[processKey] { info.standardOutput?.fileHandleForReading.readabilityHandler = nil info.standardError?.fileHandleForReading.readabilityHandler = nil } - + pluginProcesses.removeValue(forKey: processKey) } } diff --git a/ContainerSystem/ContainerRuntime+Prerequisites.swift b/ContainerSystem/ContainerRuntime+Prerequisites.swift index bd1a938..f92955d 100644 --- a/ContainerSystem/ContainerRuntime+Prerequisites.swift +++ b/ContainerSystem/ContainerRuntime+Prerequisites.swift @@ -8,170 +8,183 @@ // Created by Axel Martinez on 2026/02/08. // -import Foundation -import ContainerizationOCI -import ContainerAPIService -import ContainerImagesService -import ContainerPersistence import Containerization import ContainerizationError -import ContainerizationArchive +import ContainerizationOCI +import Foundation extension ContainerRuntime { - - // MARK: - Prerequisites Installation - - /// Install system prerequisites (init image and kernel) - internal func installPrerequisites() async throws { - // Check and install init filesystem if needed + func installPrerequisites() async throws { let initExists = await initImageExists() + let kernelExistsResult = await kernelExists() + + guard !initExists || !kernelExistsResult else { return } + + // Only what is missing is counted, so the bar measures what will actually be done. + let progress = Progress.discreteProgress( + totalUnitCount: (initExists ? 0 : 2) + (kernelExistsResult ? 0 : 2) + ) + + setupProgress = progress + + defer { + setupProgress = nil + } + if !initExists { - Self.logger.info("Installing base container filesystem...") - try await installInitialFilesystem() + try Task.checkCancellation() + logger.info("Installing base container filesystem...") + try await progress.performStep(pendingUnitCount: 2) { step in + try await installInitialFilesystem(progress: step) + } } - - // Check and install default kernel if needed - let kernelExistsResult = await kernelExists() + if !kernelExistsResult { - Self.logger.info("Installing default kernel...") - try await installDefaultKernel() - Self.logger.info("Kernel installed") + try Task.checkCancellation() + logger.info("Installing default kernel...") + try await progress.performStep(pendingUnitCount: 2) { step in + try await installDefaultKernel(progress: step) + } + logger.info("Kernel installed") } } - + // MARK: - Private Helpers - - private func installInitialFilesystem() async throws { + + private func installInitialFilesystem(progress: Progress) async throws { let initFsRef = DefaultsStore.get(key: .defaultInitImage) - + let service = try await getImagesService() - - let imageDescription = try await service.pull( - reference: initFsRef, - platform: .current, - insecure: false, - progressUpdate: { _ in } - ) - - try await service.unpack( - description: imageDescription, - platform: .current, - progressUpdate: { _ in } - ) + + progress.totalUnitCount = 2 + + let imageDescription = try await progress.performStep( + "Fetching init image" + ) { step in + try await service.pull( + reference: initFsRef, + platform: .current, + insecure: false, + progressUpdate: step.updateHandler() + ) + } + + try Task.checkCancellation() + + try await progress.performStep("Unpacking init image") { step in + try await service.unpack( + description: imageDescription, + platform: .current, + progressUpdate: step.updateHandler() + ) + } } - - private func installDefaultKernel() async throws { + + private func installDefaultKernel(progress: Progress) async throws { // Get kernel URL and binary path from DefaultsStore (same as Apple Container CLI) let defaultKernelURL = DefaultsStore.get(key: .defaultKernelURL) - let defaultKernelBinaryPath = DefaultsStore.get(key: .defaultKernelBinaryPath) - - Self.logger.info("Starting kernel installation from: \(defaultKernelURL)") - Self.logger.info("Kernel binary path in archive: \(defaultKernelBinaryPath)") - + let defaultKernelBinaryPath = DefaultsStore.get( + key: .defaultKernelBinaryPath + ) + + logger.info( + "Starting kernel installation from: \(defaultKernelURL)" + ) + + logger.info( + "Kernel binary path in archive: \(defaultKernelBinaryPath)" + ) + guard let sourceURL = URL(string: defaultKernelURL) else { - throw ContainerizationError(.invalidArgument, message: "Invalid kernel URL: \(defaultKernelURL)") + throw ContainerizationError( + .invalidArgument, + message: "Invalid kernel URL: \(defaultKernelURL)" + ) } - + // Create temp directory for download and extraction let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - - try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) - + + try FileManager.default.createDirectory( + at: tempDir, + withIntermediateDirectories: true + ) + defer { try? FileManager.default.removeItem(at: tempDir) } - + // Download the kernel tar file - let tarFile = tempDir.appendingPathComponent(sourceURL.lastPathComponent) - - Self.logger.info("Downloading from: \(sourceURL) to: \(tarFile.path)") - - let (tempDownloadURL, response) = try await URLSession.shared.download(from: sourceURL) - + let tarFile = tempDir.appendingPathComponent( + sourceURL.lastPathComponent + ) + + logger.info("Downloading from: \(sourceURL) to: \(tarFile.path)") + + progress.totalUnitCount = 2 + + let response = try await progress.performStep("Downloading kernel") { step in + try await FileDownloader(destination: tarFile, progress: step).download(from: sourceURL) + } + if let httpResponse = response as? HTTPURLResponse { - Self.logger.info("Download response status: \(httpResponse.statusCode)") + logger.info("Download response status: \(httpResponse.statusCode)") + guard httpResponse.statusCode == 200 else { - throw ContainerizationError(.internalError, message: "Failed to download kernel: HTTP \(httpResponse.statusCode)") + throw ContainerizationError( + .internalError, + message: + "Failed to download kernel: HTTP \(httpResponse.statusCode)" + ) } } - - // Move downloaded file to our temp directory - try FileManager.default.moveItem(at: tempDownloadURL, to: tarFile) - - Self.logger.info("Downloaded to: \(tarFile.path)") - - // Extract the kernel using ArchiveReader (same as Apple Container CLI) - let kernelFile = try extractKernelFromArchive(tarFile: tarFile, kernelPath: defaultKernelBinaryPath, tempDir: tempDir) - - // Use the KernelService to install the kernel (creates symlink, etc.) - let service = try await getKernelService() - try await service.installKernel(kernelFile: kernelFile, platform: .current, force: true) - - Self.logger.info("Kernel installed successfully") - } - - /// Extract kernel file from archive using ArchiveReader (same approach as Apple Container CLI) - private func extractKernelFromArchive(tarFile: URL, kernelPath: String, tempDir: URL) throws -> URL { - Self.logger.info("Extracting kernel from archive: \(tarFile.path)") - Self.logger.info("Looking for: \(kernelPath)") - - var archiveReader = try ArchiveReader(file: tarFile) - var (entry, data) = try archiveReader.extractFile(path: kernelPath) - - // If the target file is a symlink, get the data for the actual file - if entry.fileType == .symbolicLink, let symlinkRelative = entry.symlinkTarget { - Self.logger.info("Kernel is a symlink to: \(symlinkRelative)") - // Reopen the archive to traverse from the beginning - archiveReader = try ArchiveReader(file: tarFile) - - let symlinkTarget = URL(filePath: kernelPath).deletingLastPathComponent().appending(path: symlinkRelative) - let resolvedPath = symlinkTarget.standardized.relativePath - - Self.logger.info("Resolved symlink path: \(resolvedPath)") - - let (_, targetData) = try archiveReader.extractFile(path: resolvedPath) - - data = targetData + + logger.info("Downloaded to: \(tarFile.path)") + + try Task.checkCancellation() + + // Unpacking happens on the kernel service's actor, off the main thread + try await progress.performStep("Unpacking kernel") { _ in + let service = try await getKernelService() + + try await service.installKernelFrom( + tar: tarFile, + kernelFilePath: defaultKernelBinaryPath, + platform: .current, + force: true + ) } - - // Write the kernel to temp directory - let fileName = URL(filePath: kernelPath).lastPathComponent - let fileURL = tempDir.appendingPathComponent(fileName) - - try data.write(to: fileURL, options: .atomic) - - Self.logger.info("Extracted kernel to: \(fileURL.path), size: \(data.count) bytes") - - return fileURL + + logger.info("Kernel installed successfully") } - + private func initImageExists() async -> Bool { guard let service = try? await getImagesService() else { return false } - + do { let images = try await service.list() let initFsRef = DefaultsStore.get(key: .defaultInitImage) - + return images.contains { $0.reference == initFsRef } } catch { return false } } - + private func kernelExists() async -> Bool { guard let service = try? await getKernelService() else { return false } - + do { _ = try await service.getDefaultKernel(platform: .current) - + return true } catch { - Self.logger.warning("Failed to check kernel: \(error)") - + logger.warning("Failed to check kernel: \(error)") + return false } } diff --git a/ContainerSystem/ContainerRuntime+Services.swift b/ContainerSystem/ContainerRuntime+Services.swift deleted file mode 100644 index 2db2e5c..0000000 --- a/ContainerSystem/ContainerRuntime+Services.swift +++ /dev/null @@ -1,97 +0,0 @@ -// -// ContainerRuntime+Services.swift -// Containers -// -// Service lifecycle management extension for ContainerRuntime. -// Handles initialization and shutdown of container services. -// -// Created by Axel Martinez on 2026/02/08. -// - -import Foundation -import ContainerAPIService -import ContainerPlugin -import ContainerNetworkService -import ContainerImagesService -import ContainerAPIClient -import Containerization -import ContainerizationError -import ContainerizationOCI - -extension ContainerRuntime { - - // MARK: - Service Lifecycle - - /// Initialize all services for sandboxed mode - internal func initializeServices(appRoot: URL) async throws { - guard !servicesInitialized else { - Self.logger.info("Services already initialized") - return - } - - Self.logger.info("Initializing services...") - - // Initialize images service (must come before containers service) - let imagesRoot = appRoot.appendingPathComponent("images") - - try FileManager.default.createDirectory(at: imagesRoot, withIntermediateDirectories: true) - - let imageStore = try ImageStore(path: imagesRoot) - let snapshotStore = try SnapshotStore(path: imagesRoot, unpackStrategy: SnapshotStore.defaultUnpackStrategy, log: Self.logger) - let contentStore = try LocalContentStore(path: imagesRoot.appendingPathComponent("content")) - - let images = try ImagesService( - contentStore: contentStore, - imageStore: imageStore, - snapshotStore: snapshotStore, - log: Self.logger - ) - self.imagesService = images - self.contentStore = contentStore - - // Initialize sandboxed containers service - let sandboxedContainers = try SandboxedContainersService(appRoot: appRoot, imagesService: images, log: Self.logger) - - self.sandboxedContainersService = sandboxedContainers - - // Initialize kernel service - let kernel = try KernelService(log: Self.logger, appRoot: appRoot) - - self.kernelService = kernel - - servicesInitialized = true - - Self.logger.info("Services initialized successfully") - - // Register callback to update runtime state when containers change - await sandboxedContainers.addStateChangeCallback { @MainActor [weak self] in - guard let self = self else { return } - - self.lastContainerStateChange = Date() - } - } - - /// Shutdown all services - internal func shutdownServices() async { - // Stop all running containers - if let sandboxedContainers = sandboxedContainersService { - let list = await sandboxedContainers.list() - for container in list where container.status == .running { - do { - try await sandboxedContainers.stop(id: container.configuration.id, options: .default) - } catch { - Self.logger.error("Error stopping container \(container.configuration.id): \(error)") - } - } - } - - containersService = nil - sandboxedContainersService = nil - imagesService = nil - kernelService = nil - contentStore = nil - pluginLoader = nil - servicesInitialized = false - } - -} diff --git a/ContainerSystem/ContainerRuntime.swift b/ContainerSystem/ContainerRuntime.swift index 3d8616a..d595aa8 100644 --- a/ContainerSystem/ContainerRuntime.swift +++ b/ContainerSystem/ContainerRuntime.swift @@ -7,242 +7,334 @@ // Created by Axel Martinez on 2026/02/04. // -import Foundation -import ContainerImagesService -import ContainerAPIService -import ContainerPlugin -import ContainerPersistence +import Containerization import ContainerizationError import ContainerizationOCI +import Foundation import Logging -/// Manages the container runtime lifecycle and services. +/// Container runtime lifecycle and services. /// Owns all services and provides factory methods for creating managers. -/// Similar to Apple's API Server but running in-process. - @Observable @MainActor -internal class ContainerRuntime { - - // MARK: - Singleton - +class ContainerRuntime { /// Shared runtime instance - internal to ContainerSystem module - internal static let shared = ContainerRuntime() - + static let shared = ContainerRuntime() + /// Private initializer - forces use of singleton in production - private init() {} - + private init() { + _ = Self._bootstrapLogging + var l = Logger(label: "app.containers.system") + #if DEBUG + l.logLevel = .debug + #else + l.logLevel = .info + #endif + self.logger = l + } + #if DEBUG /// Internal initializer for testing - allows subclassing - internal init(forTesting: Bool) { - // Empty initializer for test subclasses + init(forTesting: Bool) { + _ = Self._bootstrapLogging + var l = Logger(label: "app.containers.system.test") + l.logLevel = .debug + self.logger = l } #endif - + // MARK: - Nested Types - - internal struct PluginProcessInfo { + + struct PluginProcessInfo { let process: Foundation.Process - let plugin: ContainerPlugin.Plugin + let plugin: Plugin let instanceId: String let standardOutput: Pipe? let standardError: Pipe? } - + // MARK: - Observable State - - internal var isRunning: Bool = false - internal var isStarting: Bool = false - internal var isStopping: Bool = false - internal var startupError: Error? - - /// Timestamp of last container state change - /// All ContainerManager instances observe this property - internal var lastContainerStateChange: Date = Date() - - /// Progress message for long-running operations (image unpacking, etc.) - internal var progressMessage: String = "" - - // Plugin processes storage (used by ContainerRuntime+Plugins extension) - internal var pluginProcesses: [String: PluginProcessInfo] = [:] - - // Service storage (used by ContainerRuntime+Services extension) - internal var servicesInitialized = false - internal var pluginLoader: ContainerPlugin.PluginLoader? - internal var containersService: ContainerAPIService.ContainersService? - internal var sandboxedContainersService: SandboxedContainersService? - internal var imagesService: ContainerImagesService.ImagesService? - internal var kernelService: ContainerAPIService.KernelService? - internal var contentStore: ContentStore? - - // System status for UI - internal enum SystemStatus: Equatable { - case notStarted - case starting - case running - case stopping - case failed - } - - internal var systemStatus: SystemStatus { - if isStopping { - return .stopping - } else if isStarting { - return .starting - } else if isRunning { - return .running - } else if startupError != nil { - return .failed - } else { - return .notStarted - } - } - - // MARK: - Service Manager - - // ServiceManager is a @MainActor singleton that manages services - + + var isRunning: Bool = false + var isStarting: Bool = false + var isStopping: Bool = false + var startupError: Error? + var lastContainerStateChange: Date = Date() + var reports: [Report] = [] + + /// What a first start is fetching, while it fetches it. + var setupProgress: Progress? + + @ObservationIgnored var reportStore: ReportStore? + + var pluginProcesses: [String: PluginProcessInfo] = [:] + // Current configuration - private var appRoot: URL? - - internal static let logger: Logger = { - LoggingSystem.bootstrap(StreamLogHandler.standardError) - var logger = Logger(label: "app.containers.system") -#if DEBUG - logger.logLevel = .info -#else - logger.logLevel = .error -#endif - return logger - }() - + var appRoot: URL? + var isAccessingAppRootSecurityScope = false + + // MARK: - Private State + + private var servicesInitialized = false + private var pluginLoader: PluginLoader? + private var containersService: ContainersService? + private var imagesService: ImagesService? + private var kernelService: KernelService? + private var contentStore: ContentStore? + + let logger: Logger + + private static let _bootstrapLogging: Void = LoggingSystem.bootstrap { label in + let category = label.split(separator: ".").last.map(String.init) ?? label + return OSLogHandler(subsystem: "app.containers", category: category) + } + // MARK: - Service Accessors - - /// Get containers service. Only accessible to managers in ContainerSystem module. - /// Can be overridden in tests to provide mock services. - internal func getContainersService() async throws -> SandboxedContainersService { - guard let service = sandboxedContainersService else { - throw ContainerizationError(.internalError, message: "Containers service not initialized") + + func getContainersService() async throws -> ContainersService { + guard let service = containersService else { + throw ContainerizationError( + .internalError, + message: "Containers service not initialized" + ) } return service } - - /// Get images service. Only accessible to managers in ContainerSystem module. - /// Can be overridden in tests to provide mock services. - internal func getImagesService() async throws -> ImagesService { + + func getImagesService() async throws -> ImagesService { guard let service = imagesService else { - throw ContainerizationError(.internalError, message: "Images service not initialized") + throw ContainerizationError( + .internalError, + message: "Images service not initialized" + ) } + return service } - - /// Get kernel service. Only accessible to managers in ContainerSystem module. - /// Can be overridden in tests to provide mock services. - internal func getKernelService() async throws -> KernelService { + + func getKernelService() async throws -> KernelService { guard let service = kernelService else { - throw ContainerizationError(.internalError, message: "Kernel service not initialized") + throw ContainerizationError( + .internalError, + message: "Kernel service not initialized" + ) } + return service } - - /// Get app root directory. Only accessible to managers in ContainerSystem module. - internal func getAppRoot() throws -> URL { + + func getAppRoot() throws -> URL { guard let appRoot = appRoot else { - throw ContainerizationError(.internalError, message: "App root not initialized") + throw ContainerizationError( + .internalError, + message: "App root not initialized" + ) } + return appRoot } - - /// Get content store. Only accessible to managers in ContainerSystem module. - internal func getContentStore() throws -> ContentStore { + + func getContentStore() throws -> ContentStore { guard let contentStore = contentStore else { - throw ContainerizationError(.internalError, message: "Content store not initialized") + throw ContainerizationError( + .internalError, + message: "Content store not initialized" + ) } + return contentStore } - + // MARK: - Internal API - + /// Start the container system and initialize all managers - internal func start(appRoot: URL) async throws { + func start(appRoot: URL) async throws { guard !isRunning && !isStarting else { - Self.logger.info("System already running or starting") + logger.info("System already running or starting") return } - - Self.logger.info("Starting container system...") - + + logger.info("Starting container system...") + self.isStarting = true self.startupError = nil self.appRoot = appRoot - + self.isAccessingAppRootSecurityScope = + appRoot.startAccessingSecurityScopedResource() + defer { isStarting = false } - + do { - // Create necessary directories try createDataDirectories(appRoot: appRoot) - - // Initialize services try await initializeServices(appRoot: appRoot) - - // Install prerequisites (init image and kernel) try await installPrerequisites() - + isRunning = true startupError = nil - - Self.logger.info("Container system started successfully") - + + logger.info("Container system started successfully") + } catch { - isRunning = false - startupError = error + self.isRunning = false + + let wasCancelled = error is CancellationError || Task.isCancelled + + self.startupError = wasCancelled ? nil : error + + if isAccessingAppRootSecurityScope { + appRoot.stopAccessingSecurityScopedResource() + isAccessingAppRootSecurityScope = false + } + self.appRoot = nil - - // Cleanup on failure + + // Cleanup on failure. stopAllPlugins() - - Self.logger.error("Failed to start system: \(error)") + discardServices() + + if wasCancelled { + logger.info("Start cancelled; system left stopped") + } else { + logger.error("Failed to start system: \(error)") + } + throw error } } - + /// Stop the container system and all managers - internal func stop() async throws { + func stop() async throws { guard isRunning && !isStopping else { - Self.logger.info("System not running or already stopping") + logger.info("System not running or already stopping") return } - + isStopping = true + defer { isStopping = false } - - Self.logger.info("Stopping container system...") - - // Stop all plugins + + logger.info("Stopping container system...") + stopAllPlugins() - - // Shutdown services + await shutdownServices() - + isRunning = false + + if isAccessingAppRootSecurityScope { + appRoot?.stopAccessingSecurityScopedResource() + isAccessingAppRootSecurityScope = false + } appRoot = nil - - Self.logger.info("Container system stopped") + + logger.info("Container system stopped") } - + // MARK: - Private Helpers - + + /// Initialize all services for sandboxed mode + private func initializeServices(appRoot: URL) async throws { + guard !servicesInitialized else { + logger.info("Services already initialized") + return + } + + logger.info("Initializing services...") + + // Initialize images service (must come before containers service) + let imagesRoot = appRoot.appendingPathComponent("images") + + try FileManager.default.createDirectory( + at: imagesRoot, + withIntermediateDirectories: true + ) + + let contentStore = try LocalContentStore( + path: imagesRoot.appendingPathComponent("content") + ) + let imageStore = try ImageStore( + path: imagesRoot, + contentStore: contentStore + ) + let snapshotsPath = imagesRoot.appendingPathComponent("snapshots") + let imagesService = try ImagesService( + contentStore: contentStore, + imageStore: imageStore, + snapshotsPath: snapshotsPath, + log: logger + ) + + self.imagesService = imagesService + self.contentStore = contentStore + + let service = try ContainersService( + appRoot: appRoot, + imagesService: imagesService, + log: logger + ) + + self.containersService = service + + let kernel = try KernelService(log: logger, appRoot: appRoot) + + self.kernelService = kernel + + servicesInitialized = true + + logger.info("Services initialized successfully") + + // Register callback to update runtime state when containers change + await service.addStateChangeCallback { @MainActor [weak self] in + guard let self = self else { return } + + self.lastContainerStateChange = Date() + } + } + + /// Shutdown all services + private func shutdownServices() async { + // Stop all running containers + if let service = containersService { + let list = await service.list() + for container in list where container.status == .running { + do { + try await service.stop( + id: container.configuration.id, + options: .default + ) + } catch { + logger.error( + "Error stopping container \(container.configuration.id): \(error)" + ) + } + } + } + + discardServices() + } + + /// Lets go of the services, so that the next start builds them again + /// rather than reaching for ones whose plugins have been stopped. + private func discardServices() { + containersService = nil + imagesService = nil + kernelService = nil + contentStore = nil + pluginLoader = nil + servicesInitialized = false + } + private func createDataDirectories(appRoot: URL) throws { - Self.logger.info("Creating data directories...") - + logger.info("Creating data directories...") + // Create app data directory with subdirectories try FileManager.default.createDirectory( at: appRoot, withIntermediateDirectories: true ) - + // Create content directory (for image storage) try FileManager.default.createDirectory( at: appRoot.appendingPathComponent("content"), diff --git a/ContainerSystem/Extensions/ServerStream+Transfers.swift b/ContainerSystem/Extensions/ServerStream+Transfers.swift deleted file mode 100644 index c6126b6..0000000 --- a/ContainerSystem/Extensions/ServerStream+Transfers.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// SandboxedBuilder+Extension.swift -// Containers -// -// Created by Axel Martinez on 9/2/26. -// - -import ContainerBuild - -extension ServerStream { - func getImageTransfer() -> ImageTransfer? { - guard case .imageTransfer(let transfer) = self.packetType else { - return nil - } - return transfer - } - - func getBuildTransfer() -> BuildTransfer? { - guard case .buildTransfer(let transfer) = self.packetType else { - return nil - } - return transfer - } - - func getIO() -> IO? { - guard case .io(let io) = self.packetType else { - return nil - } - return io - } -} diff --git a/ContainerSystem/Image/ImageLayer.swift b/ContainerSystem/Image/ImageLayer.swift new file mode 100644 index 0000000..0951054 --- /dev/null +++ b/ContainerSystem/Image/ImageLayer.swift @@ -0,0 +1,28 @@ +// +// ImageLayer.swift +// Containers +// +// Created by Axel Martinez on 03/10/2026. +// + +public struct ImageLayer { + public let digest: String? + public let size: Int64 + public let createdBy: String? + public let comment: String? + public let emptyLayer: Bool + + public init( + digest: String?, + size: Int64, + createdBy: String?, + comment: String?, + emptyLayer: Bool + ) { + self.digest = digest + self.size = size + self.createdBy = createdBy + self.comment = comment + self.emptyLayer = emptyLayer + } +} diff --git a/ContainerSystem/Image/ImageResource.swift b/ContainerSystem/Image/ImageResource.swift new file mode 100644 index 0000000..9484b4b --- /dev/null +++ b/ContainerSystem/Image/ImageResource.swift @@ -0,0 +1,107 @@ +// +// ImageResource.swift +// Containers +// +// Created by Axel Martinez on 2026/06/06. +// + +import Containerization +import ContainerizationOCI +import Foundation + +public struct ImageResource: Codable, Sendable { + public let configuration: ImageConfiguration + public let variants: [Variant] + + public var id: String { + configuration.descriptor.digest.digestHex + } + + public var name: String { + configuration.name + } + + public var creationDate: Date { + configuration.creationDate + } + + public struct Variant: Codable, Sendable { + public let platform: Platform + public let digest: String + public let size: Int64 + public let config: ContainerizationOCI.Image + + public init( + platform: Platform, + digest: String, + size: Int64, + config: ContainerizationOCI.Image + ) { + self.platform = platform + self.digest = digest + self.size = size + self.config = config + } + } + + public struct ImageConfiguration: Codable, Sendable { + public let creationDate: Date + public let name: String + public let descriptor: Descriptor + + public init(description: ImageDescription, creationDate: Date) { + self.creationDate = creationDate + self.name = description.reference + self.descriptor = description.descriptor + } + + public init(name: String, descriptor: Descriptor, creationDate: Date) { + self.creationDate = creationDate + self.name = name + self.descriptor = descriptor + } + } + + public init(configuration: ImageConfiguration, variants: [Variant]) { + self.configuration = configuration + self.variants = variants + } + + public init( + name: String, + descriptor: Descriptor, + variants: [Variant], + creationDate: Date + ) { + self.configuration = ImageConfiguration( + name: name, + descriptor: descriptor, + creationDate: creationDate + ) + self.variants = variants + } +} + +extension ImageResource { + enum CodingKeys: String, CodingKey { + case id + case configuration + case variants + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(configuration, forKey: .configuration) + try container.encode(variants, forKey: .variants) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.configuration = try container.decode( + ImageConfiguration.self, + forKey: .configuration + ) + self.variants = try container.decode([Variant].self, forKey: .variants) + } +} diff --git a/ContainerSystem/Image/ImageSummary.swift b/ContainerSystem/Image/ImageSummary.swift new file mode 100644 index 0000000..afd2b56 --- /dev/null +++ b/ContainerSystem/Image/ImageSummary.swift @@ -0,0 +1,48 @@ +// +// ImageSummary.swift +// Containers +// +// Created by Axel Martinez on 03/10/2026. +// + +import Foundation + +/// An image as a list shows it: what it is, what it holds for one platform, +/// and whether a container uses it. +public struct ImageSummary { + public struct Platform { + public let variant: String? + public let created: Date + public let os: String + public let architecture: String + public let size: Int64 + + public init(variant: String?, created: Date, os: String, architecture: String, size: Int64) { + self.variant = variant + self.created = created + self.os = os + self.architecture = architecture + self.size = size + } + } + + public static let unknownCreationDate = Date(timeIntervalSince1970: 0) + + public let description: ImageDescription + /// `nil` unless the list was asked for a platform. + public let platform: Platform? + public let variants: [ImageResource.Variant] + public let isInUse: Bool + + public init( + description: ImageDescription, + platform: Platform?, + variants: [ImageResource.Variant] = [], + isInUse: Bool + ) { + self.description = description + self.platform = platform + self.variants = variants + self.isInUse = isInUse + } +} diff --git a/ContainerSystem/Image/Reference+Normalized.swift b/ContainerSystem/Image/Reference+Normalized.swift new file mode 100644 index 0000000..54c8081 --- /dev/null +++ b/ContainerSystem/Image/Reference+Normalized.swift @@ -0,0 +1,27 @@ +// +// Reference+Normalized.swift +// Containers +// +// Created by Axel Martinez on 03/10/2026. +// + +import ContainerizationOCI +import Foundation + +extension Reference { + /// Parses a reference as typed, filling in what a short name leaves out: + /// Docker Hub as the registry, `library/` for its official images, and + /// the `latest` tag. + public static func normalized(_ reference: String) throws -> Reference { + let trimmed = reference.trimmingCharacters(in: .whitespacesAndNewlines) + var parsed = try parse(trimmed) + + if parsed.domain == nil { + parsed = try parse("docker.io/\(trimmed)") + } + + parsed.normalize() + + return parsed + } +} diff --git a/ContainerSystem/Image/String+Digest.swift b/ContainerSystem/Image/String+Digest.swift new file mode 100644 index 0000000..45c7eb3 --- /dev/null +++ b/ContainerSystem/Image/String+Digest.swift @@ -0,0 +1,23 @@ +// +// String+Digest.swift +// Containers +// +// Created by Axel Martinez on 2026/09/19. +// + +import Foundation + +extension String { + /// The digest without its algorithm, whichever one it is. + public var digestHex: String { + guard let colonIndex = firstIndex(of: ":") else { + return self + } + + return String(self[index(after: colonIndex)...]) + } + + public var trimmedDigest: String { + String(digestHex.prefix(12)) + } +} diff --git a/ContainerSystem/Log/OSLogHandler.swift b/ContainerSystem/Log/OSLogHandler.swift new file mode 100644 index 0000000..162fcb2 --- /dev/null +++ b/ContainerSystem/Log/OSLogHandler.swift @@ -0,0 +1,66 @@ +// +// OSLogHandler.swift +// ContainerSystem +// + +import Logging +import os + +struct OSLogHandler: LogHandler { + private let osLogger: os.Logger + public var logLevel: Logging.Logger.Level = .info + private var formattedMetadata: String? + + public var metadata = Logging.Logger.Metadata() { + didSet { + formattedMetadata = Self.format(metadata) + } + } + + public subscript(metadataKey key: String) -> Logging.Logger.Metadata.Value? { + get { metadata[key] } + set { metadata[key] = newValue } + } + + init(subsystem: String, category: String) { + self.osLogger = os.Logger(subsystem: subsystem, category: category) + } + + public func log( + level: Logging.Logger.Level, + message: Logging.Logger.Message, + metadata: Logging.Logger.Metadata?, + source: String, + file: String, + function: String, + line: UInt + ) { + var effective = formattedMetadata + if let override = metadata, !override.isEmpty { + effective = Self.format(self.metadata.merging(override) { $1 }) + } + + let text = + effective.map { "\(message.description) \($0)" } + ?? message.description + + osLogger.log(level: level.osLogType, "\(text, privacy: .public)") + } + + private static func format(_ metadata: Logging.Logger.Metadata) -> String? { + guard !metadata.isEmpty else { return nil } + return metadata.map { "[\($0.key)=\($0.value)]" }.joined(separator: " ") + } +} + +extension Logging.Logger.Level { + var osLogType: OSLogType { + switch self { + case .trace, .debug: return .debug + case .info: return .info + case .notice, .warning: return .default + case .error: return .error + case .critical: return .fault + } + } +} diff --git a/ContainerSystem/Managers/BuilderManager.swift b/ContainerSystem/Managers/BuilderManager.swift deleted file mode 100644 index ea7257c..0000000 --- a/ContainerSystem/Managers/BuilderManager.swift +++ /dev/null @@ -1,290 +0,0 @@ -// -// BuilderManager.swift -// Containers -// -// Created by Axel Martinez on 2026/02/08. -// - -import Foundation -import Observation -import ContainerBuild -import ContainerNetworkService -import ContainerPersistence -import Containerization -import ContainerizationError -import ContainerizationExtras -import ContainerizationOCI -import ContainerizationOS -import ContainerResource -import ContainerAPIClient -import Logging - -/// Manages BuildKit builder container for building images. -/// Create instances via public init() - automatically references shared runtime. -@Observable -@MainActor -public final class BuilderManager { - - /// Internal runtime reference (hidden from UI) - internal let runtime: ContainerRuntime - private let logger: Logger - - public static let buildkitContainerId = "buildkit" - - /// Public initializer - creates instance referencing shared runtime - public init() { - self.runtime = ContainerRuntime.shared - var logger = Logger(label: "app.containers.manager.builder") - logger.logLevel = .info - self.logger = logger - } - - #if DEBUG - /// Internal initializer for testing - allows injection of test runtime - internal init(testRuntime: ContainerRuntime) { - self.runtime = testRuntime - var logger = Logger(label: "app.containers.manager.builder.test") - logger.logLevel = .debug - self.logger = logger - } - #endif - - // MARK: - Public API - - /// Start the BuildKit builder container - /// Start the BuildKit builder container - /// This method is idempotent - if builder is already running, it will restart it to ensure fresh mounts - public func start(cpus: Int64 = 2, memory: UInt64 = 1024.mib()) async throws { - logger.info("Starting builder with cpus=\(cpus), memory=\(memory)") - - let containersService = try await runtime.getContainersService() - let imagesService = try await runtime.getImagesService() - let kernelService = try await runtime.getKernelService() - let appRoot = try runtime.getAppRoot() - - let builderImage: String = DefaultsStore.get(key: .defaultBuilderImage) - let exportsMount: String = appRoot.appendingPathComponent( - ".build" - ).path - - if !FileManager.default.fileExists(atPath: exportsMount) { - try FileManager.default.createDirectory( - atPath: exportsMount, - withIntermediateDirectories: true, - attributes: nil - ) - } - - // Content store path needs to be accessible by builder for image operations - let imagesPath = appRoot.appendingPathComponent("images").path - - // BuildKit data directory - needs to be persistent and support mmap for BoltDB - let buildkitDataPath = appRoot.appendingPathComponent("buildkit-data").path - - // Check if BoltDB database exists and might be corrupted - // If BuildKit previously crashed, the database can be in a bad state - let workerDbPath = (buildkitDataPath as NSString).appendingPathComponent("worker.db") - if FileManager.default.fileExists(atPath: workerDbPath) { - logger.info("Found existing BuildKit database, checking if it needs cleanup") - // For now, always delete and recreate to avoid corruption issues - // In the future, we could try to validate the database first - try? FileManager.default.removeItem(atPath: buildkitDataPath) - logger.info("Cleaned up BuildKit data directory") - } - - if !FileManager.default.fileExists(atPath: buildkitDataPath) { - try FileManager.default.createDirectory( - atPath: buildkitDataPath, - withIntermediateDirectories: true, - attributes: nil - ) - } - - let builderPlatform = ContainerizationOCI.Platform(arch: "arm64", os: "linux", variant: "v8") - - // Check if builder container already exists - let containerList = await containersService.list() - let existingContainer = containerList.first(where: { $0.configuration.id == Self.buildkitContainerId }) - - if let existingContainer { - logger.info("Found existing builder container, cleaning it up to ensure fresh start") - // Always delete existing builder to ensure we start with clean tmpfs mount - // This avoids BoltDB corruption issues - switch existingContainer.status { - case .running: - try await containersService.stop(id: Self.buildkitContainerId, options: .default) - try await containersService.delete(id: Self.buildkitContainerId) - case .stopped: - try await containersService.delete(id: Self.buildkitContainerId) - case .stopping: - throw ContainerizationError( - .invalidState, - message: "builder is stopping, please wait until it is fully stopped before proceeding" - ) - case .unknown: - try? await containersService.delete(id: Self.buildkitContainerId) - } - } - - let shimArguments: [String] = [ - "--debug", - "--vsock", - ] - - try ContainerAPIClient.Utility.validEntityName(Self.buildkitContainerId) - - let processConfig = ProcessConfiguration( - executable: "/usr/local/bin/container-builder-shim", - arguments: shimArguments, - environment: [], - workingDirectory: "/", - terminal: false, - user: .id(uid: 0, gid: 0) - ) - - var resources = ContainerConfiguration.Resources() - resources.cpus = Int(cpus) - resources.memoryInBytes = memory - - logger.info("Pulling builder image: \(builderImage)") - - let imageDescription = try await imagesService.pull( - reference: builderImage, - platform: builderPlatform, - insecure: false, - progressUpdate: { _ in } - ) - - logger.info("Unpacking builder image") - try await imagesService.unpack( - description: imageDescription, - platform: builderPlatform, - progressUpdate: { _ in } - ) - - var config = ContainerConfiguration(id: Self.buildkitContainerId, image: imageDescription, process: processConfig) - config.resources = resources - config.mounts = [ - .init( - type: .tmpfs, - source: "", - destination: "/run", - options: [] - ), - .init( - type: .virtiofs, - source: exportsMount, - destination: "/var/lib/container-builder-shim/exports", - options: [] - ), - .init( - type: .virtiofs, - source: imagesPath, - destination: imagesPath, - options: [] - ), - // Use tmpfs for BuildKit data directory because virtiofs doesn't support mmap - // which BoltDB requires. This means BuildKit state is ephemeral (lost on restart) - // but that's acceptable for a build cache. - // However, we need BuildKit to be able to access our content store for images - .init( - type: .tmpfs, - source: "", - destination: "/var/lib/buildkit", - options: [] - ), - ] - // Enable Rosetta only if the user didn't ask to disable it - config.rosetta = DefaultsStore.getBool(key: .buildRosetta) ?? true - - // Attach to default network (sandboxed mode uses built-in NAT networking with automatic DNS) - let defaultNetworkName = "default" - config.networks = [AttachmentConfiguration(network: defaultNetworkName, options: AttachmentOptions(hostname: Self.buildkitContainerId))] - - logger.info("Getting kernel") - let kernel = try await kernelService.getDefaultKernel(platform: .current) - - logger.info("Creating BuildKit container") - let options = ContainerCreateOptions(autoRemove: false) - try await containersService.create(configuration: config, kernel: kernel, options: options) - - try await startBuildKitProcess(service: containersService) - - logger.info("Builder started successfully") - } - - /// Restart the builder container to pick up fresh virtiofs mounts - /// This is necessary when new subdirectories have been created in mounted paths - /// because virtiofs in sandboxed apps doesn't dynamically show new subdirectories - public func restart(cpus: Int64 = 2, memory: UInt64 = 1024.mib()) async throws { - logger.info("Restarting builder to pick up fresh mounts") - - let containersService = try await runtime.getContainersService() - - // Stop the existing builder - let containerList = await containersService.list() - let existingContainer = containerList.first(where: { $0.configuration.id == Self.buildkitContainerId }) - - if let existingContainer { - switch existingContainer.status { - case .running: - logger.info("Stopping existing builder") - try await containersService.stop(id: Self.buildkitContainerId, options: .default) - try await containersService.delete(id: Self.buildkitContainerId) - case .stopped: - logger.info("Deleting stopped builder") - try await containersService.delete(id: Self.buildkitContainerId) - case .stopping: - throw ContainerizationError( - .invalidState, - message: "builder is stopping, please wait until it is fully stopped before proceeding" - ) - case .unknown: - try? await containersService.delete(id: Self.buildkitContainerId) - } - } - - // Start a fresh builder with the new mounts - try await start(cpus: cpus, memory: memory) - } - - // MARK: - Private Methods - - private func startBuildKitProcess(service: SandboxedContainersService) async throws { - do { - logger.info("Bootstrapping BuildKit container") - - // Create pipes to capture BuildKit's stdout/stderr for debugging - let stdoutPipe = Pipe() - let stderrPipe = Pipe() - - try await service.bootstrap(id: Self.buildkitContainerId, stdio: [nil, stdoutPipe.fileHandleForWriting, stderrPipe.fileHandleForWriting]) - - logger.info("Starting BuildKit process") - - // Start a task to read and log BuildKit output - Task { - for try await line in stdoutPipe.fileHandleForReading.bytes.lines { - self.logger.info("BuildKit stdout: \(line)") - } - } - Task { - for try await line in stderrPipe.fileHandleForReading.bytes.lines { - self.logger.error("BuildKit stderr: \(line)") - } - } - - try await service.startProcess(id: Self.buildkitContainerId, processID: Self.buildkitContainerId) - - logger.info("BuildKit process started successfully") - } catch { - logger.error("Failed to start BuildKit: \(error)") - try? await service.stop(id: Self.buildkitContainerId, options: .default) - try? await service.delete(id: Self.buildkitContainerId) - if error is ContainerizationError { - throw error - } - throw ContainerizationError(.internalError, message: "failed to start BuildKit: \(error)") - } - } -} diff --git a/ContainerSystem/Managers/ContainerManager.swift b/ContainerSystem/Managers/ContainerManager.swift index 5312f1a..46df34c 100644 --- a/ContainerSystem/Managers/ContainerManager.swift +++ b/ContainerSystem/Managers/ContainerManager.swift @@ -2,24 +2,14 @@ // ContainerManager.swift // Containers // -// Manager for container operations - wraps SandboxedContainersService -// Architecture: Actor singleton that gets services from ContainerSystem -// // Created by Axel Martinez on 2026/02/05. // -import Foundation -import ContainerAPIClient -import ContainerAPIService -import ContainerImagesService -import ContainerizationError -import ContainerizationOS -import ArgumentParser -import ContainerPersistence -import ContainerNetworkService import Containerization +import ContainerizationError import ContainerizationOCI -import ContainerResource +import ContainerizationOS +import Foundation import Logging /// Manages container operations. @@ -27,202 +17,260 @@ import Logging @Observable @MainActor public final class ContainerManager { - /// Internal runtime reference (hidden from UI) - internal let runtime: ContainerRuntime + let runtime: ContainerRuntime + private let logger: Logger - - /// Observable property that triggers UI updates when containers change - /// This mirrors the runtime's lastContainerStateChange property + private static let internalContainerIDs: Set = ["buildkit"] + public var lastContainerChange: Date { runtime.lastContainerStateChange } - - /// Observable property for progress messages during long-running operations - /// This mirrors the runtime's progressMessage property - public var progressMessage: String { - runtime.progressMessage - } - - /// Public initializer - creates instance referencing shared runtime + public init() { self.runtime = ContainerRuntime.shared - var logger = Logger(label: "app.containers.manager.containers") + var logger = Logger(label: "app.containers.manager.container") logger.logLevel = .info self.logger = logger } - + #if DEBUG /// Internal initializer for testing - allows injection of test runtime - internal init(testRuntime: ContainerRuntime) { + init(testRuntime: ContainerRuntime) { self.runtime = testRuntime - var logger = Logger(label: "app.containers.manager.containers.test") + var logger = Logger(label: "app.containers.manager.container.test") logger.logLevel = .debug self.logger = logger } #endif - - // MARK: - Public API (similar to Apple's ClientContainer static methods) - + + // MARK: - Public API + + @discardableResult public func create( imageReference: String, imagesDir: URL, arguments: [KeyValue], process: ContainerProcess, - container: ContainerInfo, - resource: ContainerConfiguration.Resources, - registryScheme: String = RequestScheme.auto.rawValue - ) async throws { + configuration: ContainerConfiguration, + options: ContainerManagementOptions, + registryScheme: String = RequestScheme.auto.rawValue, + progress: Progress? = nil + ) async throws -> String { let service = try await runtime.getContainersService() + let containerID = try Self.createContainerID(name: options.name) + logger.info("Creating container", metadata: ["id": "\(containerID)", "image": "\(imageReference)"]) + let existingContainers = await service.list() + guard + !existingContainers.contains(where: { + $0.configuration.id == containerID + }) + else { + logger.error("Container \(containerID) already exists") + + throw ContainerizationError(.exists, message: "container already exists: \(containerID)") + } - let (configuration, kernel) = try await createContainerConfig( - imageReference: imageReference, - imagesDir: imagesDir, - arguments: arguments.map { "\($0.key)=\($0.value)" }, - process: process, - container: container, - resource: resource, - registryScheme: registryScheme - ) + let progress = progress ?? Progress(parent: nil) + progress.totalUnitCount = 6 + + let (configuration, kernel) = try await progress.performStep(pendingUnitCount: 5) { step in + try await createContainerConfig( + id: containerID, + imageReference: imageReference, + imagesDir: imagesDir, + arguments: arguments.map { "\($0.key)=\($0.value)" }, + process: process, + configuration: configuration, + options: options, + registryScheme: registryScheme, + progress: step + ) + } - let options = ContainerCreateOptions( - autoRemove: container.deleteOnTermination - ) - - try await service.create(configuration: configuration, kernel: kernel, options: options) + try Task.checkCancellation() + + try await progress.performStep("Creating container") { _ in + try await service.create( + configuration: configuration, + kernel: kernel, + options: ContainerCreateOptions(autoRemove: options.deleteOnTermination) + ) + } - if !container.cidfile.isEmpty { - try writeCIDFile(path: container.cidfile, id: configuration.id) + if Task.isCancelled { + try? await service.delete(id: configuration.id) + throw CancellationError() } + + if !options.cidfile.isEmpty { + try writeCIDFile(path: options.cidfile, id: configuration.id) + } + + return configuration.id } - - public func start(id: String, attachStdout: Bool = false, attachStdin: Bool = false) async throws { + + /// Starts a container, returning its exit code when attached to it and + /// `nil` when detached from it. + @discardableResult + public func run(id: String, detach: Bool = true, progress: Progress? = nil) async throws -> Int32? { + logger.info("Starting container", metadata: ["id": "\(id)"]) + progress?.localizedDescription = "Starting container" let service = try await runtime.getContainersService() - + do { try await service.bootstrap(id: id, stdio: [nil, nil, nil]) try await service.startProcess(id: id, processID: id) } catch { try? await service.stop(id: id, options: .default) - + + logger.error("Failed to start container \(id): \(error)") + if error is ContainerizationError { throw error } - + throw ContainerizationError(.internalError, message: "failed to start container: \(error)") } + + guard !detach else { + return nil + } + + return try await service.wait(id: id) + } + + public func resourceUsage() async -> [ContainerResourceUsage] { + guard let service = try? await runtime.getContainersService() else { + return [] + } + + return await service.resourceUsage() } public func list() async throws -> [ContainerSnapshot] { let service = try await runtime.getContainersService() - - return await service.list() + + return await service.list().filter { snapshot in + !Self.internalContainerIDs.contains(snapshot.configuration.id) + } } - + public func get(id: String) async throws -> ContainerSnapshot { let service = try await runtime.getContainersService() - + let snapshots = await service.list() - - guard let snapshot = snapshots.first(where: { $0.configuration.id == id }) else { + + guard + let snapshot = snapshots.first(where: { $0.configuration.id == id }) + else { throw ContainerizationError(.notFound, message: "Container not found: \(id)") } - + return snapshot } - + public func exec(id: String, arguments: [String]) async throws -> String { let service = try await runtime.getContainersService() return try await service.exec(id: id, arguments: arguments) } - public func getLog(id: String, containerDir: URL, boot: Bool) async throws -> String { - let logFile = containerDir.appendingPathComponent(boot ? "vminitd.log" : "stdio.log") - guard let handle = try? FileHandle(forReadingFrom: logFile), - let data = try? handle.readToEnd(), - let logs = String(data: data, encoding: .utf8) else { - return "" - } - try? handle.close() - - return logs.trimmingCharacters(in: .newlines) - } - - public func stop(snapshots: [ContainerSnapshot], timeoutSeconds: Int32) async throws { + public func stop(ids: [String], timeoutSeconds: Int32) async throws { let service = try await runtime.getContainersService() - let stopOptions = ContainerStopOptions( - timeoutInSeconds: timeoutSeconds, - signal: SIGTERM - ) + let stopOptions = ContainerStopOptions(timeoutInSeconds: timeoutSeconds, signal: SIGTERM) var failed: [(String, Error)] = [] - - for container in snapshots { + + for id in ids { do { - try await service.stop(id: container.configuration.id, options: stopOptions) + try await service.stop(id: id, options: stopOptions) } catch { - logger.error("Failed to stop container \(container.configuration.id): \(error)") - failed.append((container.configuration.id, error)) + logger.error("Failed to stop container \(id): \(error)") + failed.append((id, error)) } } if !failed.isEmpty { - throw ContainerizationError( - .internalError, - message: "Failed to stop one or more containers: \n\(failed.map({"\($0.0): \($0.1)"}).joined(separator: "\n"))" - ) + let failures = failed.map({ "\($0.0): \($0.1)" }).joined(separator: "\n") + let message = "Failed to stop one or more containers: \n\(failures)" + + throw ContainerizationError(.internalError, message: message) } } - - public func delete(snapshots: [ContainerSnapshot], force: Bool) async throws { + + public func stop(snapshots: [ContainerSnapshot], timeoutSeconds: Int32) async throws { + try await stop(ids: snapshots.map(\.configuration.id), timeoutSeconds: timeoutSeconds) + } + + public func delete(ids: [String], force: Bool) async throws { let service = try await runtime.getContainersService() + let snapshots = await service.list() var failed: [(String, Error)] = [] - - for container in snapshots { + var deleted: [String] = [] + + for id in ids { do { + guard + let container = snapshots.first(where: { + $0.configuration.id == id + }) + else { + throw ContainerizationError(.notFound, message: "Container not found: \(id)") + } + if container.status == .running && !force { - throw ContainerizationError(.invalidState, message: "container: \(container.configuration.id) is running") + throw ContainerizationError(.invalidState, message: "container: \(id) is running") } - + if container.status == .running && force { - try await service.stop(id: container.configuration.id, options: .default) + try await service.stop(id: id, options: .default) } - try await service.delete(id: container.configuration.id) + try await service.delete(id: id) + + deleted.append(id) } catch { - logger.error("Failed to delete container \(container.configuration.id): \(error)") - failed.append((container.configuration.id, error)) + logger.error("Failed to delete container \(id): \(error)") + failed.append((id, error)) } } + // What was reported against a container has nothing left to say once the container has gone. + await ReportManager(runtime: runtime).remove(named: deleted, ofKind: [.container]) + if !failed.isEmpty { - throw ContainerizationError( - .internalError, - message: "Failed to delete one or more containers: \n\(failed.map({"\($0.0): \($0.1)"}).joined(separator: "\n"))" - ) + let failures = failed.map({ "\($0.0): \($0.1)" }).joined(separator: "\n") + let message = "Failed to delete one or more containers: \n\(failures)" + + throw ContainerizationError(.internalError, message: message) } } - + + public func delete(snapshots: [ContainerSnapshot], force: Bool) async throws { + try await delete(ids: snapshots.map(\.configuration.id), force: force) + } + // MARK: - Private Helper Methods - + private func writeCIDFile(path: String, id: String) throws { let data = id.data(using: .utf8) var attributes = [FileAttributeKey: Any]() attributes[.posixPermissions] = 0o644 - - let success = FileManager.default.createFile( - atPath: path, - contents: data, - attributes: attributes - ) - + + let success = FileManager.default.createFile(atPath: path, contents: data, attributes: attributes) + guard success else { - throw ContainerizationError(.internalError, message: "failed to create cidfile at \(path): \(errno)") + logger.error("Failed to write the CID file at \(path)") + + throw ContainerizationError( + .internalError, + message: "failed to create cidfile at \(path): \(errno)" + ) } } - + /// Split a shell-like command string into components, respecting double and single quotes. private static func shellSplit(_ command: String) -> [String] { var tokens: [String] = [] @@ -250,229 +298,229 @@ public final class ContainerManager { return tokens } - private static func createContainerID(name: String?) -> String { - guard let name, !name.isEmpty else { + /// The name a container will be known by: what it was given, or one made + /// up for it. Settled before the work starts, so that what is watching it + /// can say which container it is watching. + public static func createContainerID(name: String?) throws -> String { + let trimmedName = name?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + + guard !trimmedName.isEmpty else { return UUID().uuidString.lowercased() } - return name + + guard isValidContainerName(trimmedName) else { + let message = """ + Invalid container name '\(trimmedName)': must start with a letter or number and contain only + letters, numbers, underscores, periods, and hyphens. + """ + throw ContainerizationError(.invalidArgument, message: message) + } + + return trimmedName + } + + /// Whether a name can be a container id. + public static func isValidContainerName(_ name: String) -> Bool { + EntityName.isValid(name) } private func resolveImage( reference: String, platform: Platform, insecure: Bool, - imagesService: ImagesService + imagesService: ImagesService, + progress: Progress ) async throws -> ImageDescription { let existingImages = try await imagesService.list() - + // Try exact match first - if let existing = existingImages.first(where: { $0.reference == reference }) { - try await imagesService.unpack( - description: existing, - platform: platform, - progressUpdate: { events in - Task { @MainActor in - self.runtime.progressMessage = events.map { String(describing: $0) }.joined(separator: "\n") - } - } - ) + if let existing = existingImages.first(where: { + $0.reference == reference + }) { return existing } - + // Try matching by comparing digests - most reliable let matchingByDigest = existingImages.first { image in // If the input reference contains a digest, match by digest if reference.contains("@sha256:") { - return image.digest == reference.split(separator: "@").last.map(String.init) + return image.digest + == reference.split(separator: "@").last.map(String.init) } return false } - + if let existing = matchingByDigest { - try await imagesService.unpack( - description: existing, - platform: platform, - progressUpdate: { events in - Task { @MainActor in - self.runtime.progressMessage = events.map { String(describing: $0) }.joined(separator: "\n") - } - } - ) return existing } - + // Try matching by parsing the reference to handle different formats // e.g., "alpine:latest" should match "docker.io/library/alpine:latest" if let parsedRef = try? ContainerizationOCI.Reference.parse(reference) { let matchingImage = existingImages.first { image in - guard let imageRef = try? ContainerizationOCI.Reference.parse(image.reference) else { + guard + let imageRef = try? ContainerizationOCI.Reference.parse(image.reference) + else { return false } - + // Extract just the repository name without registry let refNameComponents = parsedRef.name.split(separator: "/") - let imageNameComponents = imageRef.name.split(separator: "/") - let refShortName = refNameComponents.last ?? Substring(parsedRef.name) + + let imageNameComponents = imageRef.name.split(separator: "/") let imageShortName = imageNameComponents.last ?? Substring(imageRef.name) - + // Match on short name and tag let nameMatch = refShortName == imageShortName let tagMatch = (parsedRef.tag ?? "latest") == (imageRef.tag ?? "latest") + return nameMatch && tagMatch } - + if let existing = matchingImage { - try await imagesService.unpack( - description: existing, - platform: platform, - progressUpdate: { events in - Task { @MainActor in - self.runtime.progressMessage = events.map { String(describing: $0) }.joined(separator: "\n") - } - } - ) return existing } } - let imageDescription = try await imagesService.pull( + return try await imagesService.pull( reference: reference, platform: platform, insecure: insecure, - progressUpdate: { events in - Task { @MainActor in - self.runtime.progressMessage = events.map { String(describing: $0) }.joined(separator: "\n") - } - } + progressUpdate: progress.updateHandler() ) - - try await imagesService.unpack( - description: imageDescription, - platform: platform, - progressUpdate: { events in - Task { @MainActor in - self.runtime.progressMessage = events.map { String(describing: $0) }.joined(separator: "\n") - } - } - ) - - return imageDescription } - + private func createContainerConfig( + id: String, imageReference: String, imagesDir: URL, arguments: [String], process: ContainerProcess, - container: ContainerInfo, - resource: ContainerConfiguration.Resources, - registryScheme: String + configuration: ContainerConfiguration, + options: ContainerManagementOptions, + registryScheme: String, + progress: Progress ) async throws -> (ContainerConfiguration, Kernel) { - var requestedPlatform = Parser.platform(os: container.os, arch: container.arch) - - if let platform = container.platform { - requestedPlatform = try Parser.platform(from: platform) - } - + // What was asked for, which the sheet filled in; what follows settles + // only what could not be known until now. + var config = configuration + let platform = config.platform + let scheme = try RequestScheme(registryScheme) let insecure = scheme == .http - + // Normalize image reference to handle short names like "alpine:latest" - let processedReference = try ClientImage.normalizeReference(imageReference) - + let processedReference = try Reference.normalized(imageReference) + .description + let imagesService = try await runtime.getImagesService() - + + progress.totalUnitCount = 5 + // Resolve image - check local first, then pull if needed - let imageDescription = try await resolveImage( - reference: processedReference, - platform: requestedPlatform, - insecure: insecure, - imagesService: imagesService - ) - - let kernel = try await getKernel(container: container) - - let initImageDescription = try await imagesService.pull( - reference: ClientImage.initImageRef, - platform: .current, - insecure: insecure, - progressUpdate: { events in - Task { @MainActor in - self.runtime.progressMessage = events.map { String(describing: $0) }.joined(separator: "\n") - } - } - ) - - try await imagesService.unpack( - description: initImageDescription, - platform: requestedPlatform, - progressUpdate: { events in - Task { @MainActor in - self.runtime.progressMessage = events.map { String(describing: $0) }.joined(separator: "\n") - } - } - ) + try Task.checkCancellation() + let imageDescription = try await progress.performStep("Fetching image") { step in + try await resolveImage( + reference: processedReference, + platform: platform, + insecure: insecure, + imagesService: imagesService, + progress: step + ) + } + + try Task.checkCancellation() + try await progress.performStep("Unpacking image") { step in + try await imagesService.unpack( + description: imageDescription, + platform: platform, + progressUpdate: step.updateHandler() + ) + } + + try Task.checkCancellation() + let kernel = try await progress.performStep("Fetching kernel") { _ in + try await getKernel(options: options) + } + + let initImageReference: String = DefaultsStore.get(key: .defaultInitImage) + + try Task.checkCancellation() + let initImageDescription = try await progress.performStep("Fetching init image") { step in + try await imagesService.pull( + reference: initImageReference, + platform: .current, + insecure: insecure, + progressUpdate: step.updateHandler() + ) + } + + try Task.checkCancellation() + try await progress.performStep("Unpacking init image") { step in + try await imagesService.unpack( + description: initImageDescription, + platform: platform, + progressUpdate: step.updateHandler() + ) + } // Get image config - we need to use the lower level ImageStore for this // since ImagesService doesn't expose config fetching let imageStore = try ImageStore(path: imagesDir) let image = try await imageStore.get(reference: imageDescription.reference) - let imageConfig = try await image.config(for: requestedPlatform).config - let pc = try Self.parseProcessConfiguration( + let imageConfig = try await image.config(for: platform).config + config.id = id + config.image = imageDescription + config.initProcess = try parseProcessConfiguration( arguments: arguments, process: process, - container: container, + options: options, config: imageConfig ) - - let containerId = Self.createContainerID(name: nil) - var config = ContainerConfiguration(id: containerId, image: imageDescription, process: pc) - config.platform = requestedPlatform - config.resources = resource - - let resolvedMounts: [Filesystem] = container.virtualFileSystem + container.temporaryFileSystem + container.volumes - - config.mounts = resolvedMounts - config.virtualization = container.virtualization - config.networks = try Self.getAttachmentConfigurations(containerId: config.id, networkIds: container.networks) - - // Note: Sandboxed service uses built-in NAT networking, no validation needed + config.creationDate = Date() + config.stopSignal = config.stopSignal ?? imageConfig?.stopSignal + config.networks = try getAttachmentConfigurations(containerId: id, networkIds: options.networks) // Only configure DNS if explicitly requested // If not set, containers will use the host's DNS via the VM network // Setting DNS causes the framework to write /etc/resolv.conf which can fail on read-only rootfs - if container.dnsDisabled { + if options.dnsDisabled { config.dns = nil - } else if !container.dnsNameservers.isEmpty || container.dnsDomain != nil || !container.dnsSearchDomains.isEmpty || !container.dnsOptions.isEmpty { + } else if !options.dnsNameservers.isEmpty + || options.dnsDomain != nil + || !options.dnsSearchDomains.isEmpty + || !options.dnsOptions.isEmpty + { // User has explicitly configured DNS settings, so apply them - let domain: String? = container.dnsDomain ?? DefaultsStore.getOptional(key: .defaultDNSDomain) - + let domain: String? = options.dnsDomain ?? DefaultsStore.getOptional(key: .defaultDNSDomain) + let dnsConfig = ContainerConfiguration.DNSConfiguration( - nameservers: container.dnsNameservers.isEmpty ? getHostDNSServers() : container.dnsNameservers, + nameservers: options.dnsNameservers.isEmpty ? getHostDNSServers() : options.dnsNameservers, domain: domain, - searchDomains: container.dnsSearchDomains, - options: container.dnsOptions + searchDomains: options.dnsSearchDomains, + options: options.dnsOptions ) + config.dns = dnsConfig } else { // No DNS configuration specified - let it use host DNS via VM network config.dns = nil } - if Platform.current.architecture == "arm64" && requestedPlatform.architecture == "amd64" { + if Platform.current.architecture == "arm64" + && platform.architecture == "amd64" + { config.rosetta = true } - config.labels = container.labels - config.publishedPorts = container.publishPorts - config.publishedSockets = container.publishSockets - config.ssh = container.ssh - return (config, kernel) } - private static func getAttachmentConfigurations(containerId: String, networkIds: [String]) throws -> [AttachmentConfiguration] { + private func getAttachmentConfigurations( + containerId: String, + networkIds: [String] + ) throws -> [AttachmentConfiguration] { // make an FQDN for the first interface let fqdn: String? if !containerId.contains(".") { @@ -490,47 +538,72 @@ public final class ContainerManager { guard networkIds.isEmpty else { // networks may only be specified for macOS 26+ guard #available(macOS 26, *) else { - throw ContainerizationError(.invalidArgument, message: "non-default network configuration requires macOS 26 or newer") + logger.error("Networks were asked for on a macOS that cannot attach them") + + throw ContainerizationError( + .invalidArgument, + message: "non-default network configuration requires macOS 26 or newer" + ) } // attach the first network using the fqdn, and the rest using just the container ID return networkIds.enumerated().map { item in guard item.offset == 0 else { - return AttachmentConfiguration(network: item.element, options: AttachmentOptions(hostname: containerId)) + return AttachmentConfiguration( + network: item.element, + options: AttachmentOptions(hostname: containerId) + ) } - return AttachmentConfiguration(network: item.element, options: AttachmentOptions(hostname: fqdn ?? containerId)) + return AttachmentConfiguration( + network: item.element, + options: AttachmentOptions(hostname: fqdn ?? containerId) + ) } } + + let defaultNetworkName = "default" + // if no networks specified, attach to the default network - return [AttachmentConfiguration(network: ClientNetwork.defaultNetworkName, options: AttachmentOptions(hostname: fqdn ?? containerId))] + return [ + AttachmentConfiguration( + network: defaultNetworkName, + options: AttachmentOptions(hostname: fqdn ?? containerId) + ) + ] } - private func getKernel(container: ContainerInfo) async throws -> Kernel { + private func getKernel(options: ContainerManagementOptions) async throws -> Kernel { let kernelService = try await runtime.getKernelService() - + // For the image itself we'll take the user input and try with it as we can do userspace // emulation for x86, but for the kernel we need it to match the hosts architecture. let s: SystemPlatform = .current - if let userKernel = container.kernel { + if let userKernel = options.kernel { guard FileManager.default.fileExists(atPath: userKernel) else { + logger.error("Kernel not found at \(userKernel)") + throw ContainerizationError(.notFound, message: "Kernel file not found at path \(userKernel)") } let p = URL(filePath: userKernel) return .init(path: p, platform: s) } - + return try await kernelService.getDefaultKernel(platform: s) } - - private static func parseProcessConfiguration( + + private func parseProcessConfiguration( arguments: [String], process: ContainerProcess, - container: ContainerInfo, + options: ContainerManagementOptions, config: ContainerizationOCI.ImageConfig? ) throws -> ProcessConfiguration { let imageEnvVars = config?.env ?? [] - let envvars = try Parser.allEnv(imageEnvs: imageEnvVars, envFiles: process.envFile, envs: process.environments) + let envvars = try Parser.allEnv( + imageEnvs: imageEnvVars, + envFiles: process.envFile, + envs: process.environments + ) let workingDir: String = { if let cwd = process.workingDirectory { @@ -545,9 +618,9 @@ public final class ContainerManager { let processArguments: [String]? = { var result: [String] = [] var hasEntrypointOverride: Bool = false - + // ensure the entrypoint is honored if it has been explicitly set by the user - if let entrypoint = container.entryPoint, !entrypoint.isEmpty { + if let entrypoint = options.entryPoint, !entrypoint.isEmpty { // Split the entrypoint string into executable + arguments, // respecting quoted substrings (e.g. sh -c "echo hello" → ["sh", "-c", "echo hello"]) result = Self.shellSplit(entrypoint) @@ -555,7 +628,7 @@ public final class ContainerManager { } else if let entrypoint = config?.entrypoint, !entrypoint.isEmpty { result = entrypoint } - + if !arguments.isEmpty { result.append(contentsOf: arguments) } else { @@ -563,12 +636,15 @@ public final class ContainerManager { result.append(contentsOf: cmd) } } - + return result.count > 0 ? result : nil }() - guard let commandToRun = processArguments, commandToRun.count > 0 else { - throw ContainerizationError(.invalidArgument, message: "Command/Entrypoint not specified for container process") + guard let commandToRun = processArguments, let command = commandToRun.first else { + logger.error("Nothing to run: no command from the image or the container") + let message = "Command/Entrypoint not specified for container process" + + throw ContainerizationError(.invalidArgument, message: message) } let defaultUser: ProcessConfiguration.User = { @@ -579,11 +655,14 @@ public final class ContainerManager { }() let (user, additionalGroups) = Parser.user( - user: process.user, uid: process.uid, - gid: process.gid, defaultUser: defaultUser) + user: process.user, + uid: process.uid, + gid: process.gid, + defaultUser: defaultUser + ) return .init( - executable: commandToRun.first!, + executable: command, arguments: [String](commandToRun.dropFirst()), environment: envvars, workingDirectory: workingDir, @@ -592,16 +671,16 @@ public final class ContainerManager { supplementalGroups: additionalGroups ) } - + // MARK: - DNS Helpers - + /// Read the host's DNS nameservers from /etc/resolv.conf, falling back to public DNS. private func getHostDNSServers() -> [String] { if let contents = try? String(contentsOfFile: "/etc/resolv.conf", encoding: .utf8) { let servers = contents.components(separatedBy: .newlines) .filter { $0.hasPrefix("nameserver ") } .compactMap { $0.split(separator: " ").last.map(String.init) } - .filter { !$0.isEmpty } // Filter out empty entries + .filter { !$0.isEmpty } // Filter out empty entries if !servers.isEmpty { return servers } @@ -609,5 +688,4 @@ public final class ContainerManager { // Fallback to public DNS if /etc/resolv.conf is unavailable or has no nameservers return ["8.8.8.8", "1.1.1.1"] } - } diff --git a/ContainerSystem/Managers/ImageManager.swift b/ContainerSystem/Managers/ImageManager.swift index 5bb2854..efff6ec 100644 --- a/ContainerSystem/Managers/ImageManager.swift +++ b/ContainerSystem/Managers/ImageManager.swift @@ -7,109 +7,149 @@ // Created by Axel Martinez on 2026/02/08. // -import Foundation -import Observation -import ContainerPersistence -import ContainerizationError -import ContainerBuild -import ContainerImagesService -import ContainerImagesServiceClient import Containerization -import ContainerizationOS +import ContainerizationError import ContainerizationOCI -import ContainerResource -import ContainerAPIClient -import NIO +import ContainerizationOS +import Foundation import Logging +import NIO +import Observation /// Manages image operations. /// Create instances via public init() - automatically references shared runtime. @Observable @MainActor public final class ImageManager { - /// Internal runtime reference (hidden from UI) - internal let runtime: ContainerRuntime + let runtime: ContainerRuntime + private let logger: Logger - + /// Public initializer - creates instance referencing shared runtime public init() { self.runtime = ContainerRuntime.shared - var logger = Logger(label: "app.containers.manager.images") + var logger = Logger(label: "app.containers.manager.image") logger.logLevel = .info self.logger = logger } - + #if DEBUG /// Internal initializer for testing - allows injection of test runtime - internal init(testRuntime: ContainerRuntime) { + init(testRuntime: ContainerRuntime) { self.runtime = testRuntime - var logger = Logger(label: "app.containers.manager.images.test") + var logger = Logger(label: "app.containers.manager.image.test") logger.logLevel = .debug self.logger = logger } #endif - + // MARK: - Public API - - public func list() async throws -> [ImageDescription] { + + /// `includeVariants` reads the manifest and config of every platform in + /// each image's index, which `list` otherwise skips. + public func list( + platform: Platform? = nil, + includeVariants: Bool = false + ) async throws -> [ImageSummary] { let service = try await runtime.getImagesService() - - let images = try await service.list() - return images.filter { !Self.isInfraImage(name: $0.reference) } + let containersService = try await runtime.getContainersService() + let images = try await service.list().filter { + !Self.isInfraImage(name: $0.reference) + } + let usedImageDigests = Set( + await containersService.list().map { $0.configuration.image.digest } + ) + + guard let platform else { + return images.map { + ImageSummary(description: $0, platform: nil, isInUse: usedImageDigests.contains($0.digest)) + } + } + + let imageStore = try await getImageStore() + var items: [ImageSummary] = [] + + for description in images { + do { + let image = try await imageStore.get(reference: description.reference) + let summary = try await self.summary(for: image, platform: platform) + let variants = includeVariants ? try await self.variants(of: image) : [] + let item = ImageSummary( + description: description, + platform: summary, + variants: variants, + isInUse: usedImageDigests.contains(description.digest) + ) + + items.append(item) + } catch { + let item = ImageSummary( + description: description, + platform: Self.fallbackSummary(for: description, platform: platform), + isInUse: usedImageDigests.contains(description.digest) + ) + + items.append(item) + } + } + + return items } - - public func getImageInformation(imageReference: String, platform: Platform) async throws -> ImageInfo { - let appRoot = try runtime.getAppRoot() - let imagesDir = appRoot.appendingPathComponent("images") - - let imageStore = try ImageStore(path: imagesDir) - let image = try await imageStore.get(reference: imageReference) - - let imageData = try await image.config(for: platform) - - let createdDate: Date? = { - guard let createdString = imageData.created else { return nil } - let formatter = ISO8601DateFormatter() - return formatter.date(from: createdString) - }() - - return ImageInfo( - variant: platform.variant, - created: createdDate, - os: platform.os, - architecture: platform.architecture + + public func inspect(image: ImageDescription) async throws -> ImageResource { + let storedImage = try await getStoredImage(reference: image.reference) + let index = try await storedImage.index() + let descriptor = resolvedDescriptor(for: image.descriptor, in: index) + let variants = try await self.variants(of: storedImage, in: index) + + return ImageResource( + name: image.reference, + descriptor: descriptor, + variants: variants, + creationDate: Self.creationDate(from: variants) ) } - + public func pull( reference: String, - platform: Platform = .current, - scheme: RequestScheme = .auto + platform: Platform? = .current, + scheme: RequestScheme = .auto, + progress: Progress? = nil ) async throws { let service = try await runtime.getImagesService() - let processedReference = try ClientImage.normalizeReference(reference) + let processedReference = try Reference.normalized(reference).description let insecure = scheme == .http - + logger.info("Pulling image: \(processedReference)") - - let imageDescription = try await service.pull( - reference: processedReference, - platform: platform, - insecure: insecure, - progressUpdate: { _ in } - ) + + let progress = progress ?? Progress(parent: nil) + progress.totalUnitCount = 2 + + let imageDescription = try await progress.performStep("Fetching image") { step in + try await service.pull( + reference: processedReference, + platform: platform, + insecure: insecure, + progressUpdate: step.updateHandler() + ) + } + + try Task.checkCancellation() logger.info("Unpacking image") - try await service.unpack( - description: imageDescription, - platform: platform, - progressUpdate: { _ in } - ) - + + try await progress.performStep("Unpacking image") { step in + try await service.unpack( + description: imageDescription, + platform: platform, + progressUpdate: step.updateHandler() + ) + } + logger.info("Image pulled successfully: \(processedReference)") } - + public func build( dockerFile: URL, contextDirectory: URL, @@ -117,16 +157,15 @@ public final class ImageManager { cpus: Int64 = 2, memory: UInt64 = 1024.mib(), vSockPort: UInt32 = 8088, - outputs: [BuildImageOutputConfiguration] = [ - .init(type: .tar, additionalFields: []) - ], + outputs: [BuildImageOutputConfiguration] = [.init(type: .tar, additionalFields: [])], platforms: Set = [Platform.current], buildArguments: [KeyValue] = [], labels: [KeyValue] = [], noCache: Bool = false, targetStage: String = "", cacheIn: [String] = [], - cacheOut: [String] = [] + cacheOut: [String] = [], + progress: Progress? = nil ) async throws { let containersService = try await runtime.getContainersService() let imagesService = try await runtime.getImagesService() @@ -135,36 +174,62 @@ public final class ImageManager { logger.info("Building image from Dockerfile") + let didAccessDockerFile = dockerFile.startAccessingSecurityScopedResource() + let didAccessContextDirectory = contextDirectory.startAccessingSecurityScopedResource() + + defer { + if didAccessContextDirectory { + contextDirectory.stopAccessingSecurityScopedResource() + } + if didAccessDockerFile { + dockerFile.stopAccessingSecurityScopedResource() + } + } + let tag = tag.isEmpty ? UUID().uuidString.lowercased() : tag - + // STEP 1: Generate buildID and create export directory FIRST - let dockerFileData = try Data(contentsOf: dockerFile) + let dockerFileData = try await FileIO.shared.contents(of: dockerFile) let exportPath = appRoot.appendingPathComponent(".build") - let buildID = UUID().uuidString - + let id = UUID().uuidString + // Create the buildID subdirectory for exports BEFORE starting builder // This ensures the directory exists when virtiofs mounts are established - let buildIDDir = exportPath.appendingPathComponent(buildID) - try FileManager.default.createDirectory(at: buildIDDir, withIntermediateDirectories: true, attributes: nil) - + let buildIDDir = exportPath.appendingPathComponent(id) + try FileManager.default.createDirectory( + at: buildIDDir, + withIntermediateDirectories: true, + attributes: nil + ) + // Set permissions to 777 to ensure BuildKit (root) can write try FileManager.default.setAttributes([.posixPermissions: 0o777], ofItemAtPath: buildIDDir.path) - + // Create a session directory for this build's context - let buildSessionDir = exportPath.appendingPathComponent("session-\(buildID)") - try FileManager.default.createDirectory(at: buildSessionDir, withIntermediateDirectories: true, attributes: nil) - + let buildSessionDir = exportPath.appendingPathComponent("session-\(id)") + try FileManager.default.createDirectory( + at: buildSessionDir, + withIntermediateDirectories: true, + attributes: nil + ) + let exportDestination = buildIDDir.appendingPathComponent("out.tar") // STEP 2: Start/restart the builder NOW with the directory already in place - let builderManager = BuilderManager() - try await builderManager.restart(cpus: cpus, memory: memory) - + let builderController = BuilderController() + + let progress = progress ?? Progress(parent: nil) + progress.totalUnitCount = 3 + + try await progress.performStep("Starting builder") { step in + try await builderController.restart(cpus: cpus, memory: memory, progress: step) + } + // STEP 3: Connect to the (re)started builder let timeout: Duration = .seconds(120) - let buildkitId = BuilderManager.buildkitContainerId + let buildkitId = BuilderController.builderContainerId - let sandboxedBuilder: SandboxedBuilder = try await withThrowingTaskGroup(of: SandboxedBuilder.self) { group in + let builder: Builder = try await withThrowingTaskGroup(of: Builder.self) { group in defer { group.cancelAll() } @@ -176,31 +241,38 @@ public final class ImageManager { // Check if builder container exists and is running let containerList = await containersService.list() - guard let builderContainer = containerList.first(where: { $0.configuration.id == buildkitId }) else { + guard + let builderContainer = containerList.first(where: { + $0.configuration.id == buildkitId + }) + else { throw ContainerizationError(.notFound, message: "Builder container not found") } guard builderContainer.status == .running else { - throw ContainerizationError(.invalidState, message: "Builder container not running") + throw ContainerizationError( + .invalidState, + message: "Builder container not running" + ) } self.logger.info("Dialing Builder...") let fileHandle = try await containersService.dial(id: buildkitId, port: vSockPort) - let threadGroup: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) - + let threadGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) + // Use SandboxedBuilder to avoid XPC-based ClientImage calls - let sandboxedBuilder = try SandboxedBuilder( + let builder = try Builder( socket: fileHandle, group: threadGroup, imagesService: imagesService, contentStore: contentStore ) - + // If this call succeeds, then BuildKit is running. - let _ = try await sandboxedBuilder.info() - - return sandboxedBuilder + let _ = try await builder.info() + + return builder } catch { // wait (seconds) for builder to start listening on vSock try await Task.sleep(for: .seconds(5)) @@ -208,33 +280,38 @@ public final class ImageManager { continue } } - + throw ContainerizationError(.timeout, message: "Failed to connect to builder") } group.addTask { try await Task.sleep(for: timeout) - + throw ContainerizationError(.timeout, message: "Timeout waiting for connection to builder") } - return try await group.next()! + guard let builder = try await group.next() else { + throw ContainerizationError(.timeout, message: "Failed to connect to builder") + } + + return builder } - + // Copy context directory to a temporary location accessible by the builder // This is necessary because sandboxed apps can't directly share user-selected directories with the VM let tempContextDir = buildSessionDir.appendingPathComponent("context") + logger.info("Copying context directory from: \(contextDirectory.path)") logger.info("Copying context directory to: \(tempContextDir.path)") - + do { - try FileManager.default.copyItem(at: contextDirectory, to: tempContextDir) + try await FileIO.shared.copyItem(at: contextDirectory, to: tempContextDir) logger.info("Context directory copied successfully") } catch { logger.error("Failed to copy context directory: \(error)") throw error } - + defer { try? FileManager.default.removeItem(at: buildSessionDir) try? FileManager.default.removeItem(at: exportDestination) @@ -243,153 +320,263 @@ public final class ImageManager { let imageName: String = try { let parsedReference = try Reference.parse(tag) parsedReference.normalize() - + return parsedReference.description }() let exports: [Builder.BuildExport] = try outputs.map { output in try output.verify() - + var export = output.buildExport - + // Set destination to host path where BuildKit will write the export // Use flat file structure to avoid virtiofs subdirectory sync issues if export.destination == nil { export.destination = exportDestination } - + return export } - + var quiet = true - + #if DEBUG quiet = false #endif - - let config = Builder.BuildConfig.init( - buildID: buildID, - contentStore: contentStore, - buildArgs: buildArguments.map { "\($0.key)=\($0.value)" }, - contextDir: tempContextDir.path, - dockerfile: dockerFileData, - labels: labels.map { "\($0.key)=\($0.value)" }, - noCache: noCache, - platforms: [Platform](platforms), - terminal: nil, - tags: [imageName], - target: targetStage, - quiet: quiet, - exports: exports, - cacheIn: cacheIn, - cacheOut: cacheOut - ) - logger.info("Starting sandboxed build with config: buildID=\(buildID), contextDir=\(tempContextDir.path)") - - // Use sandboxed builder which handles image resolution without XPC - try await sandboxedBuilder.build(config) - - logger.info("Sandboxed build completed successfully") + // What the builder says is only shown as progress while the build + // runs; a build that fails is when it is worth having kept. + let transcript = BuildTranscript() + + try await progress.performStep("Building image") { step in + let config = Builder.BuildConfig.init( + id: id, + contentStore: contentStore, + args: buildArguments.map { "\($0.key)=\($0.value)" }, + contextDir: tempContextDir.path, + dockerfile: dockerFileData, + labels: labels.map { "\($0.key)=\($0.value)" }, + noCache: noCache, + platforms: [Platform](platforms), + terminal: nil, + tags: [imageName], + target: targetStage, + quiet: quiet, + exports: exports, + cacheIn: cacheIn, + cacheOut: cacheOut, + statusUpdate: { [step, transcript] line in + let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) + + if !trimmed.isEmpty { + step.localizedAdditionalDescription = trimmed.components(separatedBy: .newlines).last + } + + await MainActor.run { + transcript.append(line) + } + } + ) + + logger.info("Starting sandboxed build with config: buildID=\(id), contextDir=\(tempContextDir.path)") + + // Use sandboxed builder which handles image resolution without XPC + do { + try await builder.build(config) + } catch { + throw BuildFailure( + message: (error as? ContainerizationError)?.message ?? error.localizedDescription, + transcript: transcript.text + ) + } + } + + logger.info("Build completed successfully") // Currently, only a single export can be specified. for exp in exports { switch exp.type { case BuildImageOutputConfiguration.BuildType.oci.rawValue: try Task.checkCancellation() - + guard let dest = exp.destination else { throw ContainerizationError(.invalidArgument, message: "dest is required \(exp.rawValue)") } - + + guard FileManager.default.fileExists(atPath: dest.path) else { + throw ContainerizationError( + .notFound, + message: "Build output was not created at \(dest.path)" + ) + } + + let extractedLayoutDirectory = + buildSessionDir + .appendingPathComponent("oci-layout") + try await FileIO.shared.extractArchive(at: dest, to: extractedLayoutDirectory) + let (imageDescriptions, _) = try await imagesService.load( - from: dest, + from: extractedLayoutDirectory, force: false ) - - for imageDesc in imageDescriptions { - try Task.checkCancellation() - - try await imagesService.unpack(description: imageDesc, platform: Platform?.none, progressUpdate: { events in - }) + + try await progress.performStep("Unpacking built image") { step in + let update = step.updateHandler() + + for imageDesc in imageDescriptions { + try Task.checkCancellation() + + try await imagesService.unpack( + description: imageDesc, + platform: Platform?.none, + progressUpdate: update + ) + } } - + case BuildImageOutputConfiguration.BuildType.tar.rawValue: guard let dest = exp.destination else { throw ContainerizationError(.invalidArgument, message: "destination is required.") } - + let tarURL = exportDestination - - try FileManager.default.moveItem(at: tarURL, to: dest) - + + try await FileIO.shared.moveItem(at: tarURL, to: dest) + case BuildImageOutputConfiguration.BuildType.local.rawValue: guard let dest = exp.destination else { throw ContainerizationError(.invalidArgument, message: "destination is required.") } - + let localDir = buildSessionDir.appendingPathComponent("local") - guard FileManager.default.fileExists(atPath: localDir.path) else { + guard FileManager.default.fileExists(atPath: localDir.path) + else { throw ContainerizationError(.invalidArgument, message: "expected local output not found") } - - try FileManager.default.copyItem(at: localDir, to: dest) + + try await FileIO.shared.copyItem(at: localDir, to: dest) default: throw ContainerizationError(.invalidArgument, message: "invalid exporter.") } } - + logger.info("Image built successfully: \(tag)") } - - public func save( - images: [ImageDescription], - platform: Platform = .current, - outputDirectory: URL - ) async throws { + + public func save(images: [ImageDescription], platform: Platform = .current, outputURL: URL) async throws { let service = try await runtime.getImagesService() - + logger.info("Saving \(images.count) image(s)") let references: [String] = images.map(\.reference) - let outputPath = outputDirectory.appending(path: "\(Date().ISO8601Format()).tar") - - try await service.save(references: references, out: outputPath, platform: platform) - + let stagingDirectory = FileManager.default.temporaryDirectory + .appending(path: "oci-layout-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: stagingDirectory, withIntermediateDirectories: true) + defer { + try? FileManager.default.removeItem(at: stagingDirectory) + } + + try await service.save(references: references, out: stagingDirectory, platform: platform) + + try await FileIO.shared.writeArchive(directory: stagingDirectory, to: outputURL) + logger.info("Saved \(images.count) image(s)") } - - public func load(tar: URL) async throws { + + /// - Returns: The images the archive held, which is only known once it + /// has been read. + @discardableResult + public func load( + tar: URL, + force: Bool = false, + progress: Progress? = nil + ) async throws -> [ImageDescription] { let service = try await runtime.getImagesService() - - let path = tar.absoluteString - - guard FileManager.default.fileExists(atPath: path) else { + let didAccessTar = tar.startAccessingSecurityScopedResource() + defer { + if didAccessTar { + tar.stopAccessingSecurityScopedResource() + } + } + + var isDirectory: ObjCBool = false + guard + FileManager.default.fileExists(atPath: tar.path, isDirectory: &isDirectory) + else { throw ContainerizationError(.invalidArgument, message: "File does not exist") } - + logger.info("Loading image from: \(tar.lastPathComponent)") - - let loaded = try await service.load(from: tar, force: false) - + + let progress = progress ?? Progress(parent: nil) + progress.totalUnitCount = 2 + + let source: URL + let stagingDirectory: URL? + + if isDirectory.boolValue { + source = tar + stagingDirectory = nil + } else { + let extractedDirectory = FileManager.default.temporaryDirectory + .appending(path: "oci-layout-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: extractedDirectory, withIntermediateDirectories: true) + + let rejectedMembers = try await FileIO.shared + .extractArchive(at: tar, to: extractedDirectory) + + if !rejectedMembers.isEmpty && !force { + try? FileManager.default.removeItem(at: extractedDirectory) + let rejectedList = rejectedMembers.joined(separator: ", ") + throw ContainerizationError( + .invalidArgument, + message: "Cannot load tar image with rejected paths: \(rejectedList)" + ) + } + + source = extractedDirectory + stagingDirectory = extractedDirectory + } + + defer { + if let stagingDirectory { + try? FileManager.default.removeItem(at: stagingDirectory) + } + } + + let loaded = try await progress.performStep("Loading tar archive") { _ in + try await service.load(from: source, force: force) + } + logger.info("Unpacking images") - for imageDescription in loaded.0 { - try await service.unpack(description: imageDescription, platform: Platform?.none, progressUpdate: { _ in }) + try await progress.performStep("Unpacking image") { step in + let update = step.updateHandler() + + for imageDescription in loaded.0 { + try await service.unpack( + description: imageDescription, + platform: Platform?.none, + progressUpdate: update + ) + } } - + logger.info("Images loaded successfully") + + return loaded.0 } - + public func delete(images: [ImageDescription]) async throws { let service = try await runtime.getImagesService() - + logger.info("Deleting \(images.count) image(s)") - + var failed: [(String, Error)] = [] + var deleted: [String] = [] var didDeleteAnyImage = false - + for image in images { guard !Self.isInfraImage(name: image.reference) else { continue @@ -397,78 +584,224 @@ public final class ImageManager { do { try await service.delete(reference: image.reference, garbageCollect: false) didDeleteAnyImage = true + deleted.append(image.reference) logger.info("Image deleted: \(image.reference)") } catch { logger.error("Failed to delete image \(image.reference): \(error)") failed.append((image.reference, error)) } } - + + // A build is reported against the image it was making, so both go + // with the image itself. + await ReportManager(runtime: runtime).remove(named: deleted, ofKind: [.image, .build]) + if !failed.isEmpty { - throw ContainerizationError( - .internalError, - message: "failed to delete one or more images: \n\(failed.map({"\($0.0): \($0.1)"}).joined(separator: "\n"))" - ) + let failures = (failed.map({ "\($0.0): \($0.1)" })).joined(separator: "\n") + let message = "failed to delete one or more images: \n\(failures))" + + throw ContainerizationError(.internalError, message: message) } - + if didDeleteAnyImage { logger.info("Images deleted successfully") } } - + public func getImageLayers(imageReference: String, platform: Platform) async throws -> [ImageLayer] { let appRoot = try runtime.getAppRoot() let imagesDir = appRoot.appendingPathComponent("images") - + logger.info("Getting layer information for image: \(imageReference)") - + let imageStore = try ImageStore(path: imagesDir) let image = try await imageStore.get(reference: imageReference) - + // Get both manifest (for layer sizes) and image config (for history/commands) let manifest = try await image.manifest(for: platform) let imageData = try await image.config(for: platform) - + var layers: [ImageLayer] = [] - - // Get history from image data if available let history = imageData.history ?? [] - - // Extract layers from manifest and match with history - // Note: History entries correspond to diff_ids in rootfs, not directly to manifest layers - // We'll match by index, understanding that some history entries may be empty layers - for (index, layer) in manifest.layers.enumerated() { - var createdBy: String? = nil - var comment: String? = nil - var emptyLayer = false - - // Try to find corresponding history entry - if index < history.count { - let historyEntry = history[index] - - createdBy = historyEntry.createdBy - comment = historyEntry.comment - emptyLayer = historyEntry.emptyLayer ?? false + var layerIndex = 0 + + if history.isEmpty { + layers = manifest.layers.map { layer in + ImageLayer( + digest: layer.digest, + size: layer.size, + createdBy: nil, + comment: "Media type: \(layer.mediaType)", + emptyLayer: false + ) + } + } else { + for historyEntry in history { + let isEmptyLayer = historyEntry.emptyLayer ?? false + let layer = + isEmptyLayer || layerIndex >= manifest.layers.count + ? nil : manifest.layers[layerIndex] + + if !isEmptyLayer { + layerIndex += 1 + } + + layers.append( + ImageLayer( + digest: layer?.digest, + size: layer?.size ?? 0, + createdBy: historyEntry.createdBy, + comment: historyEntry.comment + ?? layer.map { "Media type: \($0.mediaType)" }, + emptyLayer: isEmptyLayer + ) + ) + } + + if layerIndex < manifest.layers.count { + layers.append( + contentsOf: manifest.layers[layerIndex...].map { layer in + ImageLayer( + digest: layer.digest, + size: layer.size, + createdBy: nil, + comment: "Media type: \(layer.mediaType)", + emptyLayer: false + ) + } + ) } - - let layerDetail = ImageLayer( - digest: layer.digest, - size: layer.size, - createdBy: createdBy, - comment: comment ?? "Media type: \(layer.mediaType)", - emptyLayer: emptyLayer - ) - - layers.append(layerDetail) } - - logger.info("Found \(layers.count) layers for image: \(imageReference)") - + + logger.info("Found \(layers.count) history entries for image: \(imageReference)") + return layers.reversed() } - + // MARK: - Private Helper Methods (moved from Utility) - + + private func getStoredImage(reference: String) async throws -> Containerization.Image { + let imageStore = try await getImageStore() + return try await imageStore.get(reference: reference) + } + + private func getImageStore() async throws -> ImageStore { + let appRoot = try runtime.getAppRoot() + let imagesDir = appRoot.appendingPathComponent("images") + return try ImageStore(path: imagesDir) + } + + /// Mirrors `ClientImage.toImageResource` in apple/container: one variant + /// per platform manifest in the index, skipping any whose manifest or + /// config can't be read. + private func variants( + of image: Containerization.Image, + in index: Index? = nil + ) async throws -> [ImageResource.Variant] { + let index = if let index { index } else { try await image.index() } + var variants: [ImageResource.Variant] = [] + + for manifestDescriptor in index.manifests { + guard let platform = manifestDescriptor.platform else { + continue + } + + do { + let config = try await image.config(for: platform) + let manifest = try await image.manifest(for: platform) + let size = + manifestDescriptor.size + manifest.config.size + + manifest.layers.reduce(0) { $0 + $1.size } + let variant = ImageResource.Variant( + platform: platform, + digest: manifestDescriptor.digest, + size: size, + config: config + ) + + variants.append(variant) + } catch { + continue + } + } + + return variants + } + + private func summary( + for image: Containerization.Image, + platform: Platform + ) async throws -> ImageSummary.Platform { + let imageData = try await image.config(for: platform) + let manifest = try await image.manifest(for: platform) + + let createdDate: Date = { + guard let createdString = imageData.created, let date = Self.date(from: createdString) else { + return ImageSummary.unknownCreationDate + } + return date + }() + + let size = manifest.config.size + manifest.layers.reduce(0) { $0 + $1.size } + + return ImageSummary.Platform( + variant: platform.variant, + created: createdDate, + os: platform.os, + architecture: platform.architecture, + size: size + ) + } + + private func resolvedDescriptor(for descriptor: Descriptor, in index: Index) -> Descriptor { + let isIndirect = descriptor.annotations?[AnnotationKeys.containerizationIndexIndirect]?.lowercased() + guard let isIndirect, + ["1", "true"].contains(isIndirect), + let firstManifest = index.manifests.first + else { + return descriptor + } + + return firstManifest + } + + private static func creationDate(from variants: [ImageResource.Variant]) -> Date { + for variant in variants { + guard let created = variant.config.created, let date = date(from: created) else { + continue + } + + return date + } + + return ImageSummary.unknownCreationDate + } + + private static func fallbackSummary( + for description: ImageDescription, + platform: Platform + ) -> ImageSummary.Platform { + ImageSummary.Platform( + variant: platform.variant, + created: ImageSummary.unknownCreationDate, + os: platform.os, + architecture: platform.architecture, + size: description.descriptor.size + ) + } + + private static func date(from string: String) -> Date? { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + + if let date = formatter.date(from: string) { + return date + } + + formatter.formatOptions = [.withInternetDateTime] + return formatter.date(from: string) + } + private static let infraImages = [ DefaultsStore.get(key: .defaultBuilderImage), DefaultsStore.get(key: .defaultInitImage), @@ -484,14 +817,9 @@ public final class ImageManager { } } - public struct BuildImageOutputConfiguration { // Public initializer to allow usage in default argument values - public init( - type: BuildType, - destinationDirectory: URL? = nil, - additionalFields: [KeyValue] = [] - ) { + public init(type: BuildType, destinationDirectory: URL? = nil, additionalFields: [KeyValue] = []) { self.type = type self.destinationDirectory = destinationDirectory self.additionalFields = additionalFields @@ -501,11 +829,11 @@ public struct BuildImageOutputConfiguration { case oci case tar case local - + public var id: String { - return self.rawValue + self.rawValue } - + public var description: String { switch self { case .oci: @@ -516,10 +844,10 @@ public struct BuildImageOutputConfiguration { "Exports files to a local directory." } } - + public var title: String { switch self { - + case .oci: "OCI" case .tar: @@ -529,13 +857,13 @@ public struct BuildImageOutputConfiguration { } } } - - public var type: BuildType - + + public let type: BuildType + // required for local and tar // for OCi, will use a temporary URL specific for the build - public var destinationDirectory: URL? - + public let destinationDirectory: URL? + private var destination: URL? { switch self.type { case .local: @@ -546,85 +874,85 @@ public struct BuildImageOutputConfiguration { nil } } - - public var additionalFields: [KeyValue] - + + public let additionalFields: [KeyValue] + private static func keyValueString(key: String, value: String) -> String { - return "\(key)=\(value)" + "\(key)=\(value)" } var buildExport: Builder.BuildExport { var rawInput = Self.keyValueString(key: "type", value: type.rawValue) - + if let destination { rawInput = "\(rawInput),\(Self.keyValueString(key: "dest", value: destination.path(percentEncoded: true)))" } - + if !additionalFields.isEmpty { - let additionalFieldString = additionalFields.map { "\($0.key)=\($0.value)" }.joined(separator: ",") + let additionalFieldString = additionalFields.map { + "\($0.key)=\($0.value)" + }.joined(separator: ",") rawInput = "\(rawInput),\(additionalFieldString)" } - + let additionalFieldsDict = additionalFields.reduce(into: [String: String]()) { dict, item in dict[item.key] = item.value } - - return .init(type: type.rawValue, destination: destination, additionalFields: additionalFieldsDict, rawValue: rawInput) + + return .init( + type: type.rawValue, + destination: destination, + additionalFields: additionalFieldsDict, + rawValue: rawInput + ) } - + public func verify() throws { guard let destinationDirectory = self.destinationDirectory else { if self.type == .oci { return } - - throw ContainerizationError(.invalidArgument, message: "Destination required for output type \(self.type.rawValue)") + + throw ContainerizationError( + .invalidArgument, + message: "Destination required for output type \(self.type.rawValue)" + ) } - + if self.type == .oci { throw ContainerizationError(.invalidArgument, message: "Destination cannot be specified for OCI.") } - + let fileManager = FileManager.default - - guard fileManager - .fileExists(atPath: destinationDirectory.absoluteString) else { + + guard fileManager.fileExists(atPath: destinationDirectory.absoluteString) else { throw ContainerizationError(.invalidArgument, message: "Destination directory does not exist.") } - + if !destinationDirectory.isDirectory { - throw ContainerizationError(.invalidArgument, message: "Specified Destination is not a directory.") + throw ContainerizationError( + .invalidArgument, + message: "Specified Destination is not a directory." + ) } } } -public struct ImageLayer { - public let digest: String - public let size: Int64 - public let createdBy: String? - public let comment: String? - public let emptyLayer: Bool - - public init(digest: String, size: Int64, createdBy: String?, comment: String?, emptyLayer: Bool) { - self.digest = digest - self.size = size - self.createdBy = createdBy - self.comment = comment - self.emptyLayer = emptyLayer +/// What the builder said while a build ran, kept in case it fails. +@MainActor +private final class BuildTranscript { + private var lines: [String] = [] + + var text: String { + lines.joined(separator: "\n") } -} -public struct ImageInfo { - public let variant: String? - public let created: Date? - public let os: String - public let architecture: String - - public init(variant: String?, created: Date?, os: String, architecture: String) { - self.variant = variant - self.created = created - self.os = os - self.architecture = architecture + func append(_ line: String) { + let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) + + guard !trimmed.isEmpty else { return } + + lines.append(trimmed) } } diff --git a/ContainerSystem/Managers/DNSManager.swift b/ContainerSystem/Managers/NetworkManager.swift similarity index 50% rename from ContainerSystem/Managers/DNSManager.swift rename to ContainerSystem/Managers/NetworkManager.swift index de32bec..974a81b 100644 --- a/ContainerSystem/Managers/DNSManager.swift +++ b/ContainerSystem/Managers/NetworkManager.swift @@ -9,42 +9,78 @@ // import Foundation -import Observation import Logging +import Observation /// Manages DNS resolver configuration for container domains. -/// Create instances via public init() - stateless utility manager. @Observable @MainActor -public final class DNSManager { +public final class NetworkManager { + public static let resolverDirectory = URL(fileURLWithPath: "/etc/resolver", isDirectory: true) - private static let resolverDirectory = "/etc/resolver" private static let filePrefix = "containerization." - private static let nameserver = "127.0.0.1" - private static let port = "2053" - + private let logger: Logger - + /// Public initializer - creates instance public init() { - var logger = Logger(label: "app.containers.manager.dns") + var logger = Logger(label: "app.containers.manager.network") logger.logLevel = .debug self.logger = logger } - + // MARK: - Public API - - public func listDomains() -> [String] { + + public func listDomains(in directory: URL) -> [String] { let fileManager = FileManager.default - guard let contents = try? fileManager.contentsOfDirectory(atPath: Self.resolverDirectory) else { + let isScoped = directory.startAccessingSecurityScopedResource() + + defer { + if isScoped { + directory.stopAccessingSecurityScopedResource() + } + } + + guard + let filenames = try? fileManager.contentsOfDirectory(atPath: directory.path) + else { + logger.debug("Unreadable resolver directory: \(directory.path)") + return [] } - return contents + + return + filenames .filter { $0.hasPrefix(Self.filePrefix) } - .map { String($0.dropFirst(Self.filePrefix.count)) } + .compactMap { domain(inResolverNamed: $0, in: directory) } .sorted() } + private func domain(inResolverNamed filename: String, in directory: URL) -> String? { + let path = directory.appendingPathComponent(filename) + + guard let text = try? String(contentsOf: path, encoding: .utf8) else { + logger.debug("Unreadable resolver file: \(filename)") + + return nil + } + + for line in text.components(separatedBy: .newlines) { + let fields = + line + .trimmingCharacters(in: .whitespaces) + .split(whereSeparator: \.isWhitespace) + + guard fields.count == 2, fields[0] == "domain" else { + continue + } + + return String(fields[1]) + } + + return nil + } + // MARK: - Create domain public func createDomain(name: String) throws { @@ -75,9 +111,9 @@ public final class DNSManager { return "Domain name cannot be empty." case .notSupported: return """ - DNS domain management requires administrator privileges and is not available in the GUI. - You can manually create resolver files in /etc/resolver/ if needed. - """ + DNS domain management requires administrator privileges and is not available in the GUI. + You can manually create resolver files in /etc/resolver/ if needed. + """ } } } diff --git a/ContainerSystem/Managers/ReportManager.swift b/ContainerSystem/Managers/ReportManager.swift new file mode 100644 index 0000000..5fb2d36 --- /dev/null +++ b/ContainerSystem/Managers/ReportManager.swift @@ -0,0 +1,192 @@ +// +// ReportManager.swift +// Containers +// +// Created by Axel Martinez on 16/09/2026. +// + +import Foundation +import Logging +import Observation + +/// Records failed work and keeps the reports the app shows. Every instance shares the runtime's reports. +@Observable +@MainActor +public final class ReportManager { + let runtime: ContainerRuntime + + private let logger: Logger + private let folder: String + + /// The most recent first. + public private(set) var reports: [Report] { + get { runtime.reports } + set { runtime.reports = newValue } + } + + public convenience init() { + self.init(runtime: ContainerRuntime.shared) + } + + init(runtime: ContainerRuntime, folder: String = "reports") { + self.runtime = runtime + self.logger = Logger(label: "app.containers.manager.report") + self.folder = folder + } + + /// Doesn't throw: failing to write a report isn't worth a second failure. + /// A container's own output isn't copied in, as its Logs already hold it. + @discardableResult + public func record( + level: Report.Level = .error, + kind: Report.Kind, + name: String, + message: String, + error: any Error, + startedAt: Date? = nil + ) async -> Report? { + guard let store = try? store() else { return nil } + + do { + let entry = try await store.record( + level: level, + kind: kind, + name: name, + message: message, + body: Self.body(for: error), + startedAt: startedAt + ) + + reports.insert(entry, at: 0) + + return entry + } catch { + logger.error("Couldn’t write the report: \(error)") + + return nil + } + } + + public var unreadCount: Int { + reports.count { !$0.isRead } + } + + public func markRead(_ ids: [String]) async { + guard let store = try? store() else { return } + + let unread = Set( + reports.filter { !$0.isRead && ids.contains($0.id) }.map(\.id) + ) + + guard !unread.isEmpty else { return } + + await store.markRead(Array(unread)) + + reports = reports.map { report in + guard unread.contains(report.id) else { return report } + + return Report( + id: report.id, + date: report.date, + endDate: report.endDate, + level: report.level, + kind: report.kind, + name: report.name, + message: report.message, + isRead: true + ) + } + } + + public func refresh() async { + guard let store = try? store() else { return } + + reports = await store.list() + } + + /// `kinds` lists every kind the item is filed under: an image is reported + /// both as `.image` and as `.build`. + public func latestReport(named name: String, ofKind kinds: Set) -> Report? { + reports.first { kinds.contains($0.kind) && $0.name == name } + } + + public func reports(named name: String, ofKind kinds: Set) -> [Report] { + reports.filter { kinds.contains($0.kind) && $0.name == name } + } + + public func isRead(_ id: String) -> Bool { + reports.first { $0.id == id }?.isRead ?? true + } + + public func entry(for id: String) async -> Report? { + guard let store = try? store() else { return nil } + + return await store.entry(for: id) + } + + public func body(of id: String) async -> String? { + guard let store = try? store() else { return nil } + + return try? await store.body(of: id) + } + + public func remove(_ ids: [String]) async { + guard let store = try? store() else { return } + + await store.remove(ids) + + reports.removeAll { ids.contains($0.id) } + } + + /// For items that were deleted, whose reports nothing can lead to any more. + public func remove(named names: [String], ofKind kinds: Set) async { + let names = Set(names) + let ids = + reports + .filter { kinds.contains($0.kind) && names.contains($0.name) } + .map(\.id) + + guard !ids.isEmpty else { return } + + await remove(ids) + } + + public func url(for id: String) -> URL? { + try? store().url(for: id) + } + + private func store() throws -> ReportStore { + if let store = runtime.reportStore { return store } + + let store = try ReportStore(root: runtime.getAppRoot().appendingPathComponent(folder)) + + runtime.reportStore = store + + return store + } + + static func body(for error: any Error) -> String { + if let failure = error as? BuildFailure { + return """ + \(failure.message) + + \(failure.transcript) + """ + } + + let described = String(describing: error) + let localized = error.localizedDescription + + // Often the localized text wrapped in the case name, so one is enough. + guard !described.contains(localized), !localized.contains(described) + else { + return localized + } + + return """ + \(localized) + + \(described) + """ + } +} diff --git a/ContainerSystem/Managers/SystemManager.swift b/ContainerSystem/Managers/SystemManager.swift index b58bede..3fc61e6 100644 --- a/ContainerSystem/Managers/SystemManager.swift +++ b/ContainerSystem/Managers/SystemManager.swift @@ -2,13 +2,13 @@ // SystemManager.swift // Containers // -// Public API for system lifecycle management -// UI layer uses this to start/stop the container system +// System lifecycle management // // Created by Axel Martinez on 2026/02/08. // import Foundation +import Logging import Observation /// Public system manager for controlling container system lifecycle @@ -16,60 +16,91 @@ import Observation @Observable @MainActor public final class SystemManager { - - /// Internal runtime reference (hidden from UI) - internal let runtime: ContainerRuntime - - /// Public observable state (computed from runtime) - public var isRunning: Bool { runtime.isRunning } - public var isStarting: Bool { runtime.isStarting } - public var isStopping: Bool { runtime.isStopping } - public var startupError: Error? { runtime.startupError } - - /// System status for UI - public enum SystemStatus: Equatable { + + let runtime: ContainerRuntime + private let logger: Logger + private var startTask: Task? + + public var startupError: (any Error)? { runtime.startupError } + + /// Where the system is in its life cycle; `startupError` says why a start failed. + public enum Status: Equatable { case notStarted case starting case running case stopping case failed } - - public var systemStatus: SystemStatus { - switch runtime.systemStatus { - case .notStarted: return .notStarted - case .starting: return .starting - case .running: return .running - case .stopping: return .stopping - case .failed: return .failed - } + + public var status: Status { + if runtime.isStopping { return .stopping } + if runtime.isStarting { return .starting } + if runtime.isRunning { return .running } + if runtime.startupError != nil { return .failed } + return .notStarted + } + + /// How far a first start has got with installing what the system needs, + /// while it installs it; `nil` once there is nothing left to install. + public var setupProgress: Progress? { + runtime.setupProgress } - + /// Public initializer - creates instance referencing shared runtime public init() { self.runtime = ContainerRuntime.shared + self.logger = Logger(label: "app.containers.manager.system") } - + #if DEBUG /// Internal initializer for testing - allows injection of test runtime - internal init(testRuntime: ContainerRuntime) { + init(testRuntime: ContainerRuntime) { self.runtime = testRuntime + self.logger = Logger(label: "app.containers.manager.system.test") } #endif - + // MARK: - Lifecycle Methods - - /// Start the container system - /// - Parameters: - /// - appRoot: Root directory for container data + + /// Start the container system. + /// - Parameter appRoot: Root directory for container data. + /// - Throws: An error if the runtime cannot initialize prerequisites, storage, services, or networking. public func start(appRoot: URL) async throws { - try await runtime.start(appRoot: appRoot) + logger.info("Starting system", metadata: ["appRoot": "\(appRoot.path)"]) + + let task = Task { [runtime] in + try await runtime.start(appRoot: appRoot) + } + + startTask = task + + defer { + if startTask == task { + startTask = nil + } + } + + try await withTaskCancellationHandler { + try await task.value + } onCancel: { + task.cancel() + } + } + + public func cancelStart() { + logger.info("Cancelling start") + startTask?.cancel() } - + + public func diskUsage() async -> Int64? { + guard let appRoot = try? runtime.getAppRoot() else { return nil } + + return await FileIO.shared.allocatedSize(of: appRoot) + } + /// Stop the container system public func stop() async throws { + logger.info("Stopping system") try await runtime.stop() } } - - diff --git a/ContainerSystem/Managers/VolumeManager.swift b/ContainerSystem/Managers/VolumeManager.swift index 9ba6816..d003044 100644 --- a/ContainerSystem/Managers/VolumeManager.swift +++ b/ContainerSystem/Managers/VolumeManager.swift @@ -3,56 +3,55 @@ // Containers // // Manager for volume operations -// Architecture: Actor singleton (volumes not yet implemented in sandboxed mode) // // Created by Axel Martinez on 2026/02/04. // -import Foundation -import Observation -import ContainerAPIService -import ContainerBuild -import ContainerNetworkService -import ContainerPersistence -import Containerization +import ContainerizationEXT4 import ContainerizationError -import ContainerizationExtras -import ContainerizationOCI -import ContainerizationOS -import ContainerResource +import Foundation import Logging +import Observation +import SystemPackage /// Manages volume operations. /// Create instances via public init() - automatically references shared runtime. -/// Note: Volume management not yet implemented in sandboxed mode. @Observable @MainActor public final class VolumeManager { - + /// Internal runtime reference (hidden from UI) - internal let runtime: ContainerRuntime + let runtime: ContainerRuntime + private let logger: Logger - + + // Storage constants + private static let blockFile = "volume.ext4" + /// Public initializer - creates instance referencing shared runtime public init() { self.runtime = ContainerRuntime.shared - var logger = Logger(label: "app.containers.manager.volumes") + + var logger = Logger(label: "app.containers.manager.volume") logger.logLevel = .info + self.logger = logger } - + #if DEBUG /// Internal initializer for testing - allows injection of test runtime - internal init(testRuntime: ContainerRuntime) { + init(testRuntime: ContainerRuntime) { self.runtime = testRuntime + var logger = Logger(label: "app.containers.manager.volumes.test") logger.logLevel = .debug + self.logger = logger } #endif - + // MARK: - Public API - + @discardableResult public func create( name: String, @@ -60,15 +59,162 @@ public final class VolumeManager { options: [KeyValue], sizeInBytes: UInt64? ) async throws -> Volume { - throw ContainerizationError(.internalError, message: "Volume management not yet supported in sandboxed mode") + guard VolumeStorage.isValidVolumeName(name) else { + throw VolumeError.invalidVolumeName("invalid volume name '\(name)': must match \(VolumeStorage.volumeNamePattern)") + } + + let store = try await getStore() + let existingVolumes = try await store.list() + + if existingVolumes.contains(where: { $0.name == name }) { + throw VolumeError.volumeAlreadyExists(name) + } + + let volumesRoot = try getVolumesRoot() + let volumeDir = volumesRoot.appendingPathComponent(name) + + try FileManager.default.createDirectory(at: volumeDir, withIntermediateDirectories: true) + + let blockPath = volumeDir.appendingPathComponent(Self.blockFile).path + let filesystemSize = sizeInBytes ?? VolumeStorage.defaultVolumeSizeBytes + let labelsDict = labels.reduce(into: [String: String]()) { + $0[$1.key] = $1.value + } + let optionsDict = options.reduce(into: [String: String]()) { + $0[$1.key] = $1.value + } + + do { + let formatter = try EXT4.Formatter( + FilePath(blockPath), + blockSize: 4096, + minDiskSize: filesystemSize + ) + + try formatter.close() + } catch { + // Clean up the directory on failure + try? FileManager.default.removeItem(at: volumeDir) + + throw VolumeError.storageError("failed to create volume image: \(error)") + } + + let volume = Volume( + name: name, + driver: "local", + format: "ext4", + source: blockPath, + labels: labelsDict, + options: optionsDict, + sizeInBytes: filesystemSize + ) + + try await store.create(volume) + + logger.info("Created volume: \(name)") + + return volume } - + public func list() async throws -> [Volume] { - // For now, return empty list - return [] + let store = try await getStore() + + return try await store.list() + } + + public func summaries() async throws -> [VolumeSummary] { + let store = try await getStore() + let service = try await runtime.getContainersService() + let usedVolumeNames = Set(await service.list().flatMap(\.volumeNames)) + + return try await store.list().map { volume in + VolumeSummary(volume: volume, isInUse: usedVolumeNames.contains(volume.name)) + } } - + public func delete(volumes: [Volume]) async throws { - throw ContainerizationError(.internalError, message: "Volume management not yet supported in sandboxed mode") + let store = try await getStore() + let service = try await runtime.getContainersService() + let containers = await service.list() + + var failed: [(String, Error)] = [] + var deleted: [String] = [] + + for volume in volumes { + do { + // Check if volume is in use by any container + let isInUse = containers.contains { container in + container.configuration.mounts.contains { mount in + mount.isVolume && mount.volumeName == volume.name + } + } + + if isInUse { + throw VolumeError.volumeInUse(volume.name) + } + + try await store.delete(volume.name) + + let volumesRoot = try getVolumesRoot() + let volumeDir = volumesRoot.appendingPathComponent(volume.name) + + if FileManager.default.fileExists(atPath: volumeDir.path) { + try FileManager.default.removeItem(at: volumeDir) + } + + deleted.append(volume.name) + logger.info("Deleted volume: \(volume.name)") + } catch { + logger.error("Failed to delete volume \(volume.name): \(error)") + failed.append((volume.name, error)) + } + } + + await ReportManager(runtime: runtime).remove(named: deleted, ofKind: [.volume]) + + if !failed.isEmpty { + throw ContainerizationError( + .internalError, + message: + "Failed to delete one or more volumes: \n\(failed.map({"\($0.0): \($0.1)"}).joined(separator: "\n"))" + ) + } + } + + // MARK: - Private Helpers + + private func getVolumesRoot() throws -> URL { + let appRoot = try runtime.getAppRoot() + let volumesRoot = appRoot.appendingPathComponent("volumes") + + try FileManager.default.createDirectory(at: volumesRoot, withIntermediateDirectories: true) + + return volumesRoot + } + + private func getStore() async throws -> FilesystemEntityStore { + let volumesRoot = try getVolumesRoot() + + return try FilesystemEntityStore(path: volumesRoot, type: "volumes", log: logger) + } +} + +extension VolumeManager { + /// The volume of that name, created if it does not exist yet. An empty + /// name gets a fresh anonymous one. + public func volume(named name: String, among existing: [Volume]) async throws -> Volume { + if !name.isEmpty, let match = existing.first(where: { $0.name == name }) { + return match + } + + var volumeName = name + var labels: [KeyValue] = [] + + if volumeName.isEmpty { + volumeName = VolumeStorage.generateAnonymousVolumeName() + labels.append(.init(key: Volume.anonymousLabel)) + } + + return try await create(name: volumeName, labels: labels, options: [], sizeInBytes: nil) } } diff --git a/ContainerSystem/Models/ContainerInfo.swift b/ContainerSystem/Models/ContainerInfo.swift deleted file mode 100644 index 43e2a8a..0000000 --- a/ContainerSystem/Models/ContainerInfo.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// ContainerInfo.swift -// Containers -// -// Created by Axel Martinez on 2026/02/04. -// - -import Foundation -import ContainerResource -import ContainerAPIClient - -public struct ContainerInfo: Sendable { - public var virtualFileSystem: [Filesystem] = [] - public var volumes: [Filesystem] = [] - public var publishPorts: [PublishPort] = [] - public var publishSockets: [PublishSocket] = [] - public var temporaryFileSystem: [Filesystem] = [] - public var entryPoint: String? - public var platform: String? - public var os = "linux" - public var arch: String = Arch.hostArchitecture().rawValue - public var kernel: String? - public var networks: [String] = [] - public var cidfile = "" - public var labels: [String: String] = [:] - - // PRAGMA: DNS - - public var dnsDisabled = false - public var dnsNameservers: [String] = [] - public var dnsDomain: String? = nil - public var dnsSearchDomains: [String] = [] - public var dnsOptions: [String] = [] - - // PRAGMA: FLAGS - public var deleteOnTermination = false - public var virtualization: Bool = false - public var ssh = false - - public init() {} -} diff --git a/ContainerSystem/Network/Attachment.swift b/ContainerSystem/Network/Attachment.swift new file mode 100644 index 0000000..7faa92e --- /dev/null +++ b/ContainerSystem/Network/Attachment.swift @@ -0,0 +1,58 @@ +// +// Attachment.swift +// Containers +// +// Local implementation of network attachment types (replaces ContainerResource network types) +// + +import ContainerizationExtras +import Foundation + +/// Represents a network attachment for a running container. +public struct Attachment: Sendable, Codable { + public let network: String + public let hostname: String + public let ipv4Address: CIDRv4 + public let ipv4Gateway: IPv4Address + public let ipv6Address: CIDRv6? + public let macAddress: MACAddress? + + public init( + network: String, + hostname: String, + ipv4Address: CIDRv4, + ipv4Gateway: IPv4Address, + ipv6Address: CIDRv6? = nil, + macAddress: MACAddress? = nil + ) { + self.network = network + self.hostname = hostname + self.ipv4Address = ipv4Address + self.ipv4Gateway = ipv4Gateway + self.ipv6Address = ipv6Address + self.macAddress = macAddress + } +} + +/// Configuration for attaching a container to a network. +public struct AttachmentConfiguration: Sendable, Codable { + public let network: String + public let options: AttachmentOptions + + public init( + network: String, + options: AttachmentOptions = AttachmentOptions() + ) { + self.network = network + self.options = options + } +} + +/// Options for a network attachment. +public struct AttachmentOptions: Sendable, Codable { + public let hostname: String + + public init(hostname: String = "") { + self.hostname = hostname + } +} diff --git a/ContainerSystem/Network/PortForwarder.swift b/ContainerSystem/Network/PortForwarder.swift new file mode 100644 index 0000000..4faa260 --- /dev/null +++ b/ContainerSystem/Network/PortForwarder.swift @@ -0,0 +1,283 @@ +// +// PortForwarder.swift +// Containers +// +// TCP/UDP port forwarding from host to container via vsock. +// Replaces the SocketForwarder module from the apple/container package. +// + +import Containerization +import ContainerizationError +import Foundation +import Logging + +/// Manages port forwarding from host TCP/UDP ports to container ports via vsock. +public actor PortForwarder { + + private let log: Logger + private var forwarders: [String: ActiveForwarder] = [:] + + /// Represents an active port forwarding session. + private struct ActiveForwarder { + let id: String + let hostPort: UInt16 + let containerPort: UInt16 + let proto: PublishProtocol + let listener: Task + } + + public init(log: Logger) { + self.log = log + } + + /// Start forwarding one or more host TCP ports to container ports. + /// - Parameters: + /// - publishPort: The port forwarding configuration. + /// - container: The running LinuxContainer to forward to. + /// - Throws: An error if the listener socket cannot be created, bound, or started. + public func startForwarding( + publishPort: PublishPort, + container: LinuxContainer + ) async throws { + for i: UInt16 in 0.. \(containerPort): \(error)" + ) + } + } + + forwarders[id] = ActiveForwarder( + id: id, + hostPort: hostPort, + containerPort: containerPort, + proto: publishPort.proto, + listener: listener + ) + + log.info( + "Started port forwarding: \(hostPort) -> \(containerPort)/\(publishPort.proto.rawValue)" + ) + } + } + + /// Stop all port forwarding for a specific container. + public func stopAll() { + for (_, forwarder) in forwarders { + forwarder.listener.cancel() + } + forwarders.removeAll() + log.info("Stopped all port forwarding") + } + + /// Stop forwarding for a specific port. + public func stopForwarding( + hostPort: UInt16, + containerPort: UInt16, + proto: PublishProtocol + ) { + let id = "\(hostPort)-\(containerPort)-\(proto.rawValue)" + if let forwarder = forwarders.removeValue(forKey: id) { + forwarder.listener.cancel() + log.info( + "Stopped port forwarding: \(hostPort) -> \(containerPort)/\(proto.rawValue)" + ) + } + } + + // MARK: - TCP Forwarding + + /// Creates a TCP listening socket, accepts connections, and forwards each to + /// the container's port via vsock. + private static func tcpForwardLoop( + hostPort: UInt16, + containerPort: UInt16, + hostAddress: String, + container: LinuxContainer, + log: Logger + ) async throws { + let serverFD = socket(AF_INET, SOCK_STREAM, 0) + guard serverFD >= 0 else { + throw ContainerizationError( + .internalError, + message: "Failed to create socket: \(errno)" + ) + } + + // Allow address reuse + var reuseAddr: Int32 = 1 + setsockopt( + serverFD, + SOL_SOCKET, + SO_REUSEADDR, + &reuseAddr, + socklen_t(MemoryLayout.size) + ) + + // Bind to address + var addr = sockaddr_in() + addr.sin_family = sa_family_t(AF_INET) + addr.sin_port = hostPort.bigEndian + + if hostAddress == "0.0.0.0" || hostAddress.isEmpty { + addr.sin_addr.s_addr = INADDR_ANY + } else { + _ = hostAddress.withCString { cStr in + inet_pton(AF_INET, cStr, &addr.sin_addr) + } + } + + let bindResult = withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + bind(serverFD, $0, socklen_t(MemoryLayout.size)) + } + } + + guard bindResult == 0 else { + Darwin.close(serverFD) + throw ContainerizationError( + .internalError, + message: + "Failed to bind to \(hostAddress):\(hostPort): \(errno)" + ) + } + + guard listen(serverFD, 128) == 0 else { + Darwin.close(serverFD) + throw ContainerizationError( + .internalError, + message: + "Failed to listen on \(hostAddress):\(hostPort): \(errno)" + ) + } + + // Set non-blocking so we can check for cancellation + let flags = fcntl(serverFD, F_GETFL) + _ = fcntl(serverFD, F_SETFL, flags | O_NONBLOCK) + + defer { Darwin.close(serverFD) } + + log.info( + "Listening on \(hostAddress):\(hostPort) for forwarding to container port \(containerPort)" + ) + + while !Task.isCancelled { + var clientAddr = sockaddr_in() + var clientAddrLen = socklen_t(MemoryLayout.size) + + let clientFD = withUnsafeMutablePointer(to: &clientAddr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + accept(serverFD, $0, &clientAddrLen) + } + } + + if clientFD < 0 { + if errno == EAGAIN || errno == EWOULDBLOCK { + // No pending connections, sleep briefly and retry + try await Task.sleep(for: .milliseconds(50)) + continue + } + if errno == EBADF { + // Socket was closed + break + } + log.warning("Accept failed: \(errno)") + try await Task.sleep(for: .milliseconds(100)) + continue + } + + // Handle each connection in a separate task + Task { + await Self.handleForwardedConnection( + clientFD: clientFD, + containerPort: containerPort, + container: container, + log: log + ) + } + } + } + + /// Handles a single forwarded TCP connection: dials the container's vsock port + /// and relays data bidirectionally. + private static func handleForwardedConnection( + clientFD: Int32, + containerPort: UInt16, + container: LinuxContainer, + log: Logger + ) async { + do { + let vsockHandle = try await container.dialVsock( + port: UInt32(containerPort) + ) + let clientHandle = FileHandle( + fileDescriptor: clientFD, + closeOnDealloc: true + ) + + // Relay data bidirectionally + await withTaskGroup(of: Void.self) { group in + // Client -> Container + group.addTask { + do { + while true { + let data = clientHandle.availableData + guard !data.isEmpty else { break } + try vsockHandle.write(contentsOf: data) + } + } catch { + // Connection closed or error + } + try? vsockHandle.close() + } + + // Container -> Client + group.addTask { + do { + while true { + let data = vsockHandle.availableData + guard !data.isEmpty else { break } + try clientHandle.write(contentsOf: data) + } + } catch { + // Connection closed or error + } + try? clientHandle.close() + } + } + } catch { + log.error( + "Failed to forward connection to container port \(containerPort): \(error)" + ) + Darwin.close(clientFD) + } + } +} diff --git a/ContainerSystem/Persistence/DefaultsStore.swift b/ContainerSystem/Persistence/DefaultsStore.swift new file mode 100644 index 0000000..cd1a807 --- /dev/null +++ b/ContainerSystem/Persistence/DefaultsStore.swift @@ -0,0 +1,100 @@ +// +// DefaultsStore.swift +// Containers +// +// Provides default configuration values for the container system. +// + +import Foundation + +/// Provides access to default configuration values. +public enum DefaultsStore { + + /// Suite name for shared defaults. + private static let suiteName = "app.containers.defaults" + + /// Known configuration keys. + public enum Key: String { + case defaultInitImage = "defaultInitImage" + case defaultBuilderImage = "defaultBuilderImage" + case defaultKernelURL = "defaultKernelURL" + case defaultKernelBinaryPath = "defaultKernelBinaryPath" + case defaultDNSDomain = "defaultDNSDomain" + case buildRosetta = "buildRosetta" + case defaultContainerCPUs = "defaultContainerCPUs" + case defaultContainerMemory = "defaultContainerMemory" + case defaultBuildCPUs = "defaultBuildCPUs" + case defaultBuildMemory = "defaultBuildMemory" + case defaultSubnet = "defaultSubnet" + case registryDomain = "registryDomain" + } + + /// Default values for each key. + /// Image tags match the containerization package version pinned in Package.resolved. + private static nonisolated(unsafe) let defaults: [Key: String] = [ + .defaultInitImage: "ghcr.io/apple/containerization/vminit:0.28.0", + .defaultBuilderImage: "ghcr.io/apple/container-builder-shim/builder:0.12.0", + .defaultKernelURL: "https://github.com/kata-containers/kata-containers/releases/download/3.26.0/kata-static-3.26.0-arm64.tar.zst", + .defaultKernelBinaryPath: "opt/kata/share/kata-containers/vmlinux-6.18.5-177", + .buildRosetta: "true", + .defaultContainerCPUs: "2", + .defaultContainerMemory: "2147483648", + .defaultBuildCPUs: "4", + .defaultBuildMemory: "4294967296", + .defaultSubnet: "192.168.64.1/24", + ] + + /// UserDefaults instance using the shared suite, falling back to standard. + private static var userDefaults: UserDefaults { + UserDefaults(suiteName: suiteName) ?? .standard + } + + /// Get a required configuration value. Uses UserDefaults override, then falls back to built-in defaults. + public static func get(key: Key) -> String { + if let override = userDefaults.string(forKey: key.rawValue), !override.isEmpty { + return override + } + return defaults[key] ?? "" + } + + /// Get an optional configuration value. Returns nil if not set. + public static func getOptional(key: Key) -> String? { + if let override = userDefaults.string(forKey: key.rawValue), !override.isEmpty { + return override + } + return defaults[key] + } + + /// Get a boolean configuration value. Returns nil if not set. + public static func getBool(key: Key) -> Bool? { + if userDefaults.object(forKey: key.rawValue) != nil { + return userDefaults.bool(forKey: key.rawValue) + } + if let defaultValue = defaults[key] { + return defaultValue.lowercased() == "true" + } + return nil + } + + /// Get an integer configuration value. Returns nil if not set. + public static func getInt(key: Key) -> Int? { + if userDefaults.object(forKey: key.rawValue) != nil { + return userDefaults.integer(forKey: key.rawValue) + } + if let defaultValue = defaults[key] { + return Int(defaultValue) + } + return nil + } + + /// Get a UInt64 configuration value. Returns nil if not set. + public static func getUInt64(key: Key) -> UInt64? { + if let str = userDefaults.string(forKey: key.rawValue), let val = UInt64(str) { + return val + } + if let defaultValue = defaults[key] { + return UInt64(defaultValue) + } + return nil + } +} diff --git a/ContainerSystem/Persistence/FilesystemEntityStore.swift b/ContainerSystem/Persistence/FilesystemEntityStore.swift new file mode 100644 index 0000000..bee6b16 --- /dev/null +++ b/ContainerSystem/Persistence/FilesystemEntityStore.swift @@ -0,0 +1,79 @@ +// +// FilesystemEntityStore.swift +// Containers +// +// Generic JSON-based filesystem persistence for entity types. +// + +import Foundation +import Logging + +/// A simple JSON-based store that persists entities as individual files in a directory. +public struct FilesystemEntityStore: Sendable { + private let path: URL + private let type: String + private let logger: Logger + private let metadataDir: URL + + public init(path: URL, type: String, log: Logger) throws { + self.path = path + self.type = type + self.logger = log + self.metadataDir = path.appendingPathComponent(".metadata") + + try FileManager.default.createDirectory( + at: metadataDir, + withIntermediateDirectories: true + ) + } + + public func list() async throws -> [T] { + let fm = FileManager.default + + guard fm.fileExists(atPath: metadataDir.path) else { + return [] + } + + let contents = try fm.contentsOfDirectory( + at: metadataDir, + includingPropertiesForKeys: nil + ) + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + + var entities: [T] = [] + + for file in contents where file.pathExtension == "json" { + do { + let data = try Data(contentsOf: file) + let entity = try decoder.decode(T.self, from: data) + entities.append(entity) + } catch { + logger.warning( + "Failed to decode \(type) from \(file.lastPathComponent): \(error)" + ) + } + } + + return entities + } + + public func create(_ entity: T) async throws where T: Identifiable, T.ID == String { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes] + + let data = try encoder.encode(entity) + let file = metadataDir.appendingPathComponent("\(entity.id).json") + + try data.write(to: file) + } + + public func delete(_ id: String) async throws { + let file = metadataDir.appendingPathComponent("\(id).json") + + if FileManager.default.fileExists(atPath: file.path) { + try FileManager.default.removeItem(at: file) + } + } +} diff --git a/ContainerSystem/Plugin/Plugin.swift b/ContainerSystem/Plugin/Plugin.swift new file mode 100644 index 0000000..3a1e4fc --- /dev/null +++ b/ContainerSystem/Plugin/Plugin.swift @@ -0,0 +1,19 @@ +// +// Plugin.swift +// Containers +// +// Represents a container plugin that can be registered with the runtime. +// + +import Foundation + +/// Represents a container plugin. +public struct Plugin: Sendable { + public let name: String + public let binaryURL: URL + + public init(name: String, binaryURL: URL) { + self.name = name + self.binaryURL = binaryURL + } +} diff --git a/ContainerSystem/Plugin/PluginLoader.swift b/ContainerSystem/Plugin/PluginLoader.swift new file mode 100644 index 0000000..7d9a3c2 --- /dev/null +++ b/ContainerSystem/Plugin/PluginLoader.swift @@ -0,0 +1,9 @@ +// +// PluginLoader.swift +// Containers +// + +/// Placeholder for future plugin loading support. +public struct PluginLoader: Sendable { + public init() {} +} diff --git a/ContainerSystem/Progress/Progress+Steps.swift b/ContainerSystem/Progress/Progress+Steps.swift new file mode 100644 index 0000000..65fcc50 --- /dev/null +++ b/ContainerSystem/Progress/Progress+Steps.swift @@ -0,0 +1,206 @@ +// +// Progress+Steps.swift +// Containers +// +// Created by Axel Martinez on 2026/10/02. +// + +import ContainerizationExtras +import Foundation +import os + +/// A method handed a progress sets `totalUnitCount` to its steps and runs each with `performStep`. +extension Progress { + /// Runs `work` as a child worth `pendingUnitCount`, mirroring the step's descriptions here + /// so the top progress describes the deepest step. + public func performStep( + _ description: String = "", + pendingUnitCount: Int64 = 1, + isolation: isolated (any Actor)? = #isolation, + _ work: (Progress) async throws -> T + ) async throws -> T { + let step = Step(parent: nil) + step.localizedDescription = description + addChild(step, withPendingUnitCount: pendingUnitCount) + + let observations = mirror(step) + let result: T + + do { + result = try await work(step) + } catch { + for observation in observations { + observation.invalidate() + } + + throw error + } + + // Before completing, or an unmeasured step would show "1 of 1" here. + for observation in observations { + observation.invalidate() + } + + step.complete() + + return result + } + + /// Counts bytes when there's a byte total, otherwise items, and never moves back. Each + /// handler keeps its own tally, so share one per step. Updates after the step completes + /// are dropped. + public func updateHandler() -> ProgressHandler { + let tally = OSAllocatedUnfairLock(initialState: Tally()) + + return { [self] events in + tally.withLock { tally in + guard let reading = tally.update(with: events) else { return } + + whileOpen { + if reading.measuresBytes { + kind = .file + } + + totalUnitCount = reading.total + // A step finished early counts twice towards its parent, so only + // `complete()` finishes it. + completedUnitCount = min( + Int64(reading.fraction * Double(reading.total)), + reading.total - 1 + ) + } + } + } + } + + func complete() { + whileOpen(closing: true) { + if totalUnitCount <= 0 { + totalUnitCount = 1 + } + + // Setting it again once finished removes it from its parent. + guard completedUnitCount < totalUnitCount else { return } + + completedUnitCount = totalUnitCount + } + } + + /// Skips `body` once a step has completed; other progresses are always open. + private func whileOpen(closing: Bool = false, _ body: () -> Void) { + guard let step = self as? Step else { + body() + return + } + + step.isOpen.withLockUnchecked { isOpen in + guard isOpen else { return } + + body() + + if closing { + isOpen = false + } + } + } + + private func mirror(_ step: Progress) -> [NSKeyValueObservation] { + [ + step.observe(\.localizedDescription, options: .initial) { [self] step, _ in + localizedDescription = step.localizedDescription + }, + step.observe(\.localizedAdditionalDescription, options: .initial) { [self] step, _ in + localizedAdditionalDescription = step.localizedAdditionalDescription + }, + ] + } +} + +private final class Step: Progress, @unchecked Sendable { + let isOpen = OSAllocatedUnfairLock(initialState: true) +} + +private struct Tally { + private var items = Count() + private var bytes = Count() + + private static let smallestMeasuredStage: Int64 = 1024 * 1024 + + /// The highest fraction shown so far. + private var shown = 0.0 + private var stage = Stage() + + struct Count { + var completed: Int64 = 0 + var total: Int64 = 0 + } + + struct Reading { + let total: Int64 + let fraction: Double + let measuresBytes: Bool + } + + /// The work counted since the total last changed, with the fraction shown at that point. + private struct Stage { + var total: Int64 = 0 + var measuresBytes = false + var start: Int64 = 0 + var shown = 0.0 + } + + private var measure: Count? { + if bytes.total > 0 { return bytes } + if items.total > 0 { return items } + + return nil + } + + /// `nil` leaves the step as it is: nothing is measured yet, or the count has caught up with a total that may still grow. + mutating func update(with events: [ProgressEvent]) -> Reading? { + let itemsBefore = items.completed + let bytesBefore = bytes.completed + + add(events) + + guard let count = measure else { return nil } + + let measuresBytes = bytes.total > 0 + + // Totals arrive in stages (an image's index, then its manifest, then its layers), so + // a new total spreads its work over what's left instead of moving progress back. + if count.total != stage.total || measuresBytes != stage.measuresBytes { + stage = Stage( + total: count.total, + measuresBytes: measuresBytes, + start: measuresBytes ? bytesBefore : itemsBefore, + shown: shown + ) + } + + guard count.completed < count.total else { return nil } + + // Containerization fetches blobs under 1 MiB (an image's index, manifests and configs) + // whole, ahead of the layers. Counting them would fill the bar before the layers are known. + if measuresBytes && count.total - stage.start < Self.smallestMeasuredStage { + return nil + } + + let done = Double(count.completed - stage.start) / Double(count.total - stage.start) + + shown = max(shown, stage.shown + (1 - stage.shown) * done) + + return Reading(total: count.total, fraction: shown, measuresBytes: measuresBytes) + } + + private mutating func add(_ events: [ProgressEvent]) { + for event in events { + switch event { + case .addItems(let count): items.completed += Int64(count) + case .addTotalItems(let count): items.total += Int64(count) + case .addSize(let size): bytes.completed += size + case .addTotalSize(let size): bytes.total += size + } + } + } +} diff --git a/ContainerSystem/Reports/BuildFailure.swift b/ContainerSystem/Reports/BuildFailure.swift new file mode 100644 index 0000000..53a8566 --- /dev/null +++ b/ContainerSystem/Reports/BuildFailure.swift @@ -0,0 +1,19 @@ +// +// BuildFailure.swift +// Containers +// +// Created by Axel Martinez on 16/09/2026. +// + +import Foundation + +public struct BuildFailure: LocalizedError { + public let message: String + public let transcript: String + public var errorDescription: String? { message } + + public init(message: String, transcript: String) { + self.message = message + self.transcript = transcript + } +} diff --git a/ContainerSystem/Reports/Gzip.swift b/ContainerSystem/Reports/Gzip.swift new file mode 100644 index 0000000..24084d5 --- /dev/null +++ b/ContainerSystem/Reports/Gzip.swift @@ -0,0 +1,122 @@ +// +// Gzip.swift +// Containers +// +// Created by Axel Martinez on 20/09/2026. +// + +import Compression +import Foundation + +/// Compresses report bodies as standard gzip, so any tool can still open them. +enum Gzip { + private static let header: [UInt8] = [ + 0x1f, 0x8b, // Magic number. + 0x08, // Deflate. + 0x00, // No flags. + 0x00, 0x00, 0x00, 0x00, // No modification time; the manifest has it. + 0x00, // No extra flags. + 0x03, // Unix. + ] + + static func compressed(_ text: String) -> Data? { + let source = Data(text.utf8) + + guard !source.isEmpty else { return Data(header) + footer(for: source) } + + // Incompressible input can grow when deflated. + let capacity = source.count + (source.count / 100) + 600 + var deflated = Data(count: capacity) + + let written = deflated.withUnsafeMutableBytes { destination in + source.withUnsafeBytes { input in + guard + let output = destination.bindMemory(to: UInt8.self) + .baseAddress, + let input = input.bindMemory(to: UInt8.self).baseAddress + else { return 0 } + + return compression_encode_buffer( + output, + capacity, + input, + source.count, + nil, + COMPRESSION_ZLIB + ) + } + } + + guard written > 0 else { return nil } + + return Data(header) + deflated.prefix(written) + footer(for: source) + } + + static func text(of data: Data) -> String? { + guard data.count >= header.count + 8, data.starts(with: header.prefix(2)) else { + return nil + } + + // The last four bytes hold the uncompressed length. + let size = Int(integer(at: data.endIndex - 4, of: data)) + + guard size > 0 else { return "" } + + let deflated = data.dropFirst(header.count).dropLast(8) + var inflated = Data(count: size) + + let written = inflated.withUnsafeMutableBytes { destination in + deflated.withUnsafeBytes { input in + guard + let output = destination.bindMemory(to: UInt8.self) + .baseAddress, + let input = input.bindMemory(to: UInt8.self).baseAddress + else { return 0 } + + return compression_decode_buffer( + output, + size, + input, + deflated.count, + nil, + COMPRESSION_ZLIB + ) + } + } + + guard written > 0 else { return nil } + + return String(data: inflated.prefix(written), encoding: .utf8) + } + + /// CRC-32 and length of the uncompressed data. + private static func footer(for source: Data) -> Data { + var footer = Data() + + for value in [crc32(of: source), UInt32(source.count & 0xffff_ffff)] { + withUnsafeBytes(of: value.littleEndian) { + footer.append(contentsOf: $0) + } + } + + return footer + } + + private static func integer(at index: Data.Index, of data: Data) -> UInt32 { + (0..<4).reduce(UInt32(0)) { value, offset in + value | UInt32(data[index + offset]) << (8 * UInt32(offset)) + } + } + + private static let crcTable: [UInt32] = (0..<256).map { index in + (0..<8).reduce(UInt32(index)) { value, _ in + value & 1 == 1 ? 0xedb8_8320 ^ (value >> 1) : value >> 1 + } + } + + private static func crc32(of data: Data) -> UInt32 { + ~data.reduce(UInt32.max) { crc, byte in + crcTable[Int((crc ^ UInt32(byte)) & 0xff)] ^ (crc >> 8) + } + } +} diff --git a/ContainerSystem/Reports/Report.swift b/ContainerSystem/Reports/Report.swift new file mode 100644 index 0000000..41149c4 --- /dev/null +++ b/ContainerSystem/Reports/Report.swift @@ -0,0 +1,96 @@ +// +// Report.swift +// Containers +// +// Created by Axel Martinez on 16/09/2026. +// + +import Foundation + +public struct Report: Identifiable, Sendable, Hashable { + public enum Kind: String, Sendable, CaseIterable { + case build + case image + case container + case volume + + public var title: String { + switch self { + case .build: "Build" + case .image: "Image" + case .container: "Container" + case .volume: "Volume" + } + } + + /// How the kind is written in the manifest. + var domainType: String { + "app.containers.ReportDomainType.\(rawValue.localizedCapitalized)" + } + + init?(domainType: String) { + guard let name = domainType.components(separatedBy: ".").last?.lowercased() else { + return nil + } + + self.init(rawValue: name) + } + } + + public enum Level: String, Sendable, CaseIterable { + case warning + case error + + public var title: String { + switch self { + case .warning: "Warning" + case .error: "Error" + } + } + + /// The letter the manifest keeps + var status: String { + switch self { + case .warning: "W" + case .error: "E" + } + } + + init?(status: String) { + switch status { + case "W": self = .warning + case "E": self = .error + default: return nil + } + } + } + + public let id: String + public let date: Date + public let endDate: Date + public let level: Level + public let kind: Kind + public let name: String + public let message: String + public let isRead: Bool + + public init( + id: String, + date: Date, + endDate: Date, + level: Level, + kind: Kind, + name: String, + message: String, + isRead: Bool = false + ) { + self.id = id + self.date = date + self.endDate = endDate + self.level = level + self.kind = kind + self.name = name + self.message = message + self.isRead = isRead + } +} diff --git a/ContainerSystem/Reports/ReportStore.swift b/ContainerSystem/Reports/ReportStore.swift new file mode 100644 index 0000000..cfe1df7 --- /dev/null +++ b/ContainerSystem/Reports/ReportStore.swift @@ -0,0 +1,225 @@ +// +// ReportStore.swift +// Containers +// +// Created by Axel Martinez on 16/09/2026. +// + +import Foundation + +/// A manifest listing every report, plus one gzipped file per report body. +/// Listing reads only the manifest; bodies, which can run to megabytes, are read on demand. +actor ReportStore { + private static let manifestFilename = "ReportStoreManifest.plist" + private static let fileExtension = "activitylog" + private static let formatVersion = 1 + + private let root: URL + private let manifestURL: URL + + private struct Manifest: Codable { + let reportFormatVersion: Int + var reports: [String: Record] + + init( + reportFormatVersion: Int = ReportStore.formatVersion, + reports: [String: Record] = [:] + ) { + self.reportFormatVersion = reportFormatVersion + self.reports = reports + } + } + + private struct Record: Codable { + let uniqueIdentifier: String + let fileName: String + let domainType: String + let title: String + let signature: String + let timeStartedRecording: Double + let timeStoppedRecording: Double + let primaryObservable: Observable + var hasBeenRead: Bool + } + + private struct Observable: Codable { + let highLevelStatus: String + let totalNumberOfErrors: Int + let totalNumberOfWarnings: Int + } + + /// Safe to cache, since only this store writes the manifest. + private var cached: Manifest? + + init(root: URL) throws { + self.root = root + self.manifestURL = root.appendingPathComponent(Self.manifestFilename) + + try FileManager.default.createDirectory( + at: root, + withIntermediateDirectories: true + ) + } + + @discardableResult + func record( + level: Report.Level, + kind: Report.Kind, + name: String, + message: String, + body: String, + startedAt: Date? + ) throws -> Report { + let endDate = Date() + let date = startedAt ?? endDate + let id = UUID().uuidString + let fileName = "\(id).\(Self.fileExtension)" + + guard let deflated = Gzip.compressed(body) else { + throw CocoaError(.fileWriteUnknown) + } + + try deflated.write( + to: root.appendingPathComponent(fileName), + options: .atomic + ) + + let record = Record( + uniqueIdentifier: id, + fileName: fileName, + domainType: kind.domainType, + title: name, + signature: message, + timeStartedRecording: date.timeIntervalSinceReferenceDate, + timeStoppedRecording: endDate.timeIntervalSinceReferenceDate, + primaryObservable: Observable( + highLevelStatus: level.status, + totalNumberOfErrors: level == .error ? 1 : 0, + totalNumberOfWarnings: level == .warning ? 1 : 0 + ), + hasBeenRead: false + ) + + var manifest = self.manifest() + manifest.reports[id] = record + + try write(manifest) + + return entry(for: record) + ?? Report( + id: id, + date: date, + endDate: endDate, + level: level, + kind: kind, + name: name, + message: message + ) + } + + /// Most recent first. + func list() -> [Report] { + manifest().reports.values + .compactMap(entry(for:)) + .sorted { $0.date > $1.date } + } + + func entry(for id: String) -> Report? { + manifest().reports[id].flatMap(entry(for:)) + } + + func body(of id: String) throws -> String { + let data = try Data(contentsOf: url(for: id)) + + guard let text = Gzip.text(of: data) else { + throw CocoaError(.fileReadCorruptFile) + } + + return text + } + + func markRead(_ ids: [String]) { + var manifest = self.manifest() + var changed = false + + for id in ids where manifest.reports[id]?.hasBeenRead == false { + manifest.reports[id]?.hasBeenRead = true + changed = true + } + + guard changed else { return } + + try? write(manifest) + } + + func remove(_ ids: [String]) { + var manifest = self.manifest() + + for id in ids { + manifest.reports.removeValue(forKey: id) + + try? FileManager.default.removeItem(at: url(for: id)) + } + + try? write(manifest) + } + + nonisolated func url(for id: String) -> URL { + root.appendingPathComponent("\(id).\(Self.fileExtension)") + } + + /// An unreadable manifest is treated as empty, so new reports can still be written. + private func manifest() -> Manifest { + if let cached { return cached } + + guard let data = try? Data(contentsOf: manifestURL), + let manifest = try? PropertyListDecoder().decode( + Manifest.self, + from: data + ) + else { + let empty = Manifest() + cached = empty + + return empty + } + + cached = manifest + + return manifest + } + + private func write(_ manifest: Manifest) throws { + let encoder = PropertyListEncoder() + encoder.outputFormat = .xml + + try encoder.encode(manifest).write(to: manifestURL, options: .atomic) + + cached = manifest + } + + private func entry(for record: Record) -> Report? { + guard let kind = Report.Kind(domainType: record.domainType), + let level = Report.Level( + status: record.primaryObservable.highLevelStatus + ) + else { + return nil + } + + return Report( + id: record.uniqueIdentifier, + date: Date( + timeIntervalSinceReferenceDate: record.timeStartedRecording + ), + endDate: Date( + timeIntervalSinceReferenceDate: record.timeStoppedRecording + ), + level: level, + kind: kind, + name: record.title, + message: record.signature, + isRead: record.hasBeenRead + ) + } +} diff --git a/ContainerSystem/Services/SandboxedContainersService.swift b/ContainerSystem/Services/ContainersService.swift similarity index 58% rename from ContainerSystem/Services/SandboxedContainersService.swift rename to ContainerSystem/Services/ContainersService.swift index d5cf0c5..0c83046 100644 --- a/ContainerSystem/Services/SandboxedContainersService.swift +++ b/ContainerSystem/Services/ContainersService.swift @@ -1,36 +1,24 @@ // -// SandboxedContainersService.swift +// ContainersService.swift // Containers // -// A containers service that runs LinuxContainer directly in-process, -// bypassing XPC and child process spawning entirely. +// A containers service that runs LinuxContainer. // // Created by Axel Martinez on 2026/02/04. // -import Foundation -import ContainerAPIClient -import ContainerAPIService -import ContainerPlugin -import ContainerSandboxService -import ContainerImagesService -import ContainerNetworkService import Containerization import ContainerizationError import ContainerizationExtras -import ContainerizationOS -import SystemPackage import ContainerizationOCI -import ContainerResource +import ContainerizationOS +import Foundation import Logging +import SystemPackage private struct MultiWriter: Writer { let handles: [FileHandle] - init(handles: [FileHandle]) { - self.handles = handles - } - func close() throws { for handle in handles { try handle.close() @@ -44,8 +32,75 @@ private struct MultiWriter: Writer { } } -private extension Filesystem { - var asMount: Containerization.Mount { +/// Answers a wait once, with whichever comes first: the container's exit, or the caller giving up on it. +private final class ExitWaiter: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var answered = false + + func wait(for monitor: Task) async throws -> Int32 { + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + lock.lock() + + // Cancelled before the wait even began. + guard !answered else { + lock.unlock() + continuation.resume(throwing: CancellationError()) + return + } + + self.continuation = continuation + + lock.unlock() + + Task { + let exitCode = await monitor.value + self.answer(with: .success(exitCode)) + } + } + } onCancel: { + answer(with: .failure(CancellationError())) + } + } + + private func answer(with result: Result) { + lock.lock() + + guard !answered else { + lock.unlock() + return + } + + answered = true + let continuation = self.continuation + self.continuation = nil + lock.unlock() + + continuation?.resume(with: result) + } +} + +private struct FileHandleReader: ReaderStream { + let handle: FileHandle + + func stream() -> AsyncStream { + .init { cont in + self.handle.readabilityHandler = { handle in + let data = handle.availableData + if data.isEmpty { + handle.readabilityHandler = nil + cont.finish() + return + } + cont.yield(data) + } + } + } +} + +extension Filesystem { + fileprivate var asMount: Containerization.Mount { switch self.type { case .tmpfs: return .any( @@ -77,24 +132,24 @@ private extension Filesystem { } } - func isSocket() throws -> Bool { + fileprivate func isSocket() throws -> Bool { if !self.isVirtiofs { return false } let info = try File.info(self.source) - + return info.isSocket } } /// A sandbox-compatible containers service that runs LinuxContainer in-process. -public actor SandboxedContainersService { - +actor ContainersService { private struct ContainerState { var snapshot: ContainerSnapshot var container: LinuxContainer? - var bundle: ContainerResource.Bundle? - var exitMonitorTask: Task? + var bundle: Bundle? + var exitMonitorTask: Task? + var lastExitCode: Int32? } private let log: Logger @@ -103,20 +158,22 @@ public actor SandboxedContainersService { private let imagesService: ImagesService private var containers: [String: ContainerState] = [:] private var ipAllocations: [String: UInt8] = [:] - + private var portForwarders: [String: PortForwarder] = [:] + private let containerLock = AsyncLock() + /// Callbacks to invoke when container state changes private var stateChangeCallbacks: [@Sendable @MainActor () -> Void] = [] - + /// Register a callback to be invoked when container state changes - public func addStateChangeCallback(_ callback: @escaping @Sendable @MainActor () -> Void) { + func addStateChangeCallback(_ callback: @escaping @Sendable @MainActor () -> Void) { stateChangeCallbacks.append(callback) } init(appRoot: URL, imagesService: ImagesService, log: Logger) throws { let containerRoot = appRoot.appendingPathComponent("containers") - + try FileManager.default.createDirectory(at: containerRoot, withIntermediateDirectories: true) - + self.appRoot = appRoot self.containerRoot = containerRoot self.imagesService = imagesService @@ -124,29 +181,39 @@ public actor SandboxedContainersService { self.containers = Self.loadAtBoot(root: containerRoot, log: log) let count = containers.count - - log.info("SandboxedContainersService initialized with \(count) existing container(s)") + + log.info("ContainersService initialized with \(count) existing container(s)") } private static func loadAtBoot(root: URL, log: Logger) -> [String: ContainerState] { var results = [String: ContainerState]() - - guard let directories = try? FileManager.default.contentsOfDirectory( - at: root, - includingPropertiesForKeys: [.isDirectoryKey] - ) else { + + guard + let directories = try? FileManager.default.contentsOfDirectory( + at: root, + includingPropertiesForKeys: [.isDirectoryKey] + ) + else { return results } for dir in directories where dir.isDirectory { do { - let bundle = ContainerResource.Bundle(path: dir) + let bundle = Bundle(path: dir) let config = try bundle.configuration + + if (try? bundle.createOptions)?.autoRemove ?? false { + log.info("Reaping auto-remove container \(config.id)") + try? bundle.delete() + continue + } + results[config.id] = ContainerState( snapshot: ContainerSnapshot( configuration: config, status: .stopped, - networks: [] + networks: [], + startedDate: bundle.state.startedDate ), container: LinuxContainer?.none, bundle: bundle @@ -159,13 +226,48 @@ public actor SandboxedContainersService { return results } - // MARK: - Public API + // MARK: - Internal API - public func list() async -> [ContainerSnapshot] { - return containers.values.map { $0.snapshot }.sorted { $0.configuration.id < $1.configuration.id } + func list() async -> [ContainerSnapshot] { + containers.values.map { $0.snapshot }.sorted { + $0.configuration.id < $1.configuration.id + } + } + + /// List containers with optional filters. + func list( + status: ContainerStatus? = nil, + labelFilter: [String: String]? = nil, + namePattern: String? = nil + ) async -> [ContainerSnapshot] { + var results = containers.values.map { $0.snapshot } + + if let status { + results = results.filter { $0.status == status } + } + + if let labelFilter { + results = results.filter { snapshot in + labelFilter.allSatisfy { key, value in + snapshot.configuration.labels[key] == value + } + } + } + + if let namePattern, !namePattern.isEmpty { + results = results.filter { snapshot in + snapshot.id.localizedCaseInsensitiveContains(namePattern) + } + } + + return results.sorted { $0.configuration.id < $1.configuration.id } } - public func create(configuration: ContainerConfiguration, kernel: Kernel, options: ContainerCreateOptions) async throws { + func create( + configuration: ContainerConfiguration, + kernel: Kernel, + options: ContainerCreateOptions + ) async throws { // Creating container guard containers[configuration.id] == nil else { @@ -179,24 +281,24 @@ public actor SandboxedContainersService { let initFs = try await getInitBlock(for: systemPlatform.ociPlatform()) // Create container bundle - let bundle = try ContainerResource.Bundle.create( + let bundle = try Bundle.create( path: path, initialFilesystem: initFs, kernel: kernel, - containerConfiguration: configuration + containerConfiguration: configuration, + options: options ) do { // Get container image filesystem via in-process ImagesService (no XPC) - let imageFs = try await imagesService.getImageSnapshot(description: configuration.image, platform: configuration.platform) - try bundle.setContainerRootFs(cloning: imageFs) - try bundle.write(filename: "options.json", value: options) - - let snapshot = ContainerSnapshot( - configuration: configuration, - status: .stopped, - networks: [] + let imageFs = try await imagesService.getImageSnapshot( + description: configuration.image, + platform: configuration.platform ) + try bundle.cloneContainerRootFs(cloning: imageFs, readonly: configuration.readOnly) + + let snapshot = ContainerSnapshot(configuration: configuration, status: .stopped, networks: []) + containers[configuration.id] = ContainerState( snapshot: snapshot, container: LinuxContainer?.none, @@ -204,7 +306,6 @@ public actor SandboxedContainersService { ) // Container created successfully - } catch { log.error("Failed to create container: \(error)") try? bundle.delete() @@ -212,28 +313,51 @@ public actor SandboxedContainersService { } } - public func bootstrap(id: String, stdio: [FileHandle?]) async throws { + func bootstrap(id: String, stdio: [FileHandle?]) async throws { + try await containerLock.withLock { _ in + try await self._bootstrap(id: id, stdio: stdio) + } + } + + private func _bootstrap(id: String, stdio: [FileHandle?]) async throws { guard var state = containers[id] else { throw ContainerizationError(.notFound, message: "container with ID \(id) not found") } // Already bootstrapped if state.container != nil { - // Container already bootstrapped return } - let bundle: ContainerResource.Bundle + let previousStatus = state.snapshot.status + var hasBooted = false + + // Shown while the virtual machine boots, which is most of a start. + state.snapshot.status = .starting + containers[id] = state + notifyStateChange() + + defer { + if !hasBooted { + containers[id]?.snapshot.status = previousStatus + notifyStateChange() + } + } + + let bundle: ContainerSystem.Bundle + if let existingBundle = state.bundle { bundle = existingBundle } else { let path = containerRoot.appendingPathComponent(id) - bundle = ContainerResource.Bundle(path: path) + bundle = Bundle(path: path) } let config = try bundle.configuration let bundleKernel = try bundle.kernel - let initMount = await MainActor.run { bundle.initialFilesystem.asMount } + let initMount = await MainActor.run { + bundle.initialFilesystem.asMount + } let vmm = VZVirtualMachineManager( kernel: bundleKernel, initialFilesystem: initMount, @@ -243,11 +367,11 @@ public actor SandboxedContainersService { // Create the log file for container stdio let containerLogURL = bundle.path.appendingPathComponent("stdio.log") - + do { let fd = Darwin.open(containerLogURL.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644) guard fd >= 0 else { - throw POSIXError(.init(rawValue: errno)!) + throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } Darwin.close(fd) } @@ -271,16 +395,21 @@ public actor SandboxedContainersService { return nil }() - let stdin: FileHandle? = { - stdio[0] ?? nil + let stdin: FileHandleReader? = { + if let handle = stdio[0] { + return FileHandleReader(handle: handle) + } + return nil }() - let rootfs = try await MainActor.run { try bundle.containerRootfs.asMount } + let rootfs = try await MainActor.run { + try bundle.containerRootfs.asMount + } // Precompute mounts and sockets var precomputedMounts: [Containerization.Mount] = [] var precomputedSockets: [UnixSocketConfiguration] = [] - + for mount in config.mounts { if try await MainActor.run(body: { try mount.isSocket() }) { let socket = UnixSocketConfiguration( @@ -296,9 +425,7 @@ public actor SandboxedContainersService { // Allocate IP before the closure (actor-isolated state) let (ip, gw) = try allocateIP(for: id) - - // Container assigned IP - + let container = try LinuxContainer(id, rootfs: rootfs, vmm: vmm, logger: self.log) { czConfig in try Self.configureContainer( czConfig: &czConfig, @@ -306,6 +433,7 @@ public actor SandboxedContainersService { precomputedMounts: precomputedMounts, precomputedSockets: precomputedSockets ) + // Configure NATInterface (IsolatedInterfaceStrategy pattern) czConfig.interfaces = [try NATInterface(ipv4Address: CIDRv4(ip), ipv4Gateway: IPv4Address(gw))] @@ -315,12 +443,14 @@ public actor SandboxedContainersService { czConfig.process.stdout = stdout czConfig.process.stderr = stderr czConfig.process.stdin = stdin - // bootlog configuration moved or removed in newer API + + // The console is the only account of a boot that never reaches the + // container process, which is when stdio stays empty. + czConfig.bootLog = .file(path: bundle.bootLog, append: true) } do { try await container.create() - // LinuxContainer VM created and booted state.container = container state.bundle = bundle @@ -335,7 +465,8 @@ public actor SandboxedContainersService { ) ] containers[id] = state - + hasBooted = true + // Notify observers that networks have been assigned notifyStateChange() } catch { @@ -345,7 +476,7 @@ public actor SandboxedContainersService { } } - public func startProcess(id: String, processID: String) async throws { + func startProcess(id: String, processID: String) async throws { // Starting process in container guard var state = containers[id] else { @@ -361,43 +492,136 @@ public actor SandboxedContainersService { throw ContainerizationError(.invalidState, message: "container not bootstrapped: \(id)") } - try await container.start() + do { + try await container.start() + } catch { + if isInit { + // Booted, but it never got as far as running. + containers[id]?.snapshot.status = .stopped + notifyStateChange() + } + + throw error + } // Container init process started if isInit { + let startedDate = Date() + state.snapshot.status = .running - state.snapshot.startedDate = Date() + state.snapshot.startedDate = startedDate + + // Kept on disk so the container still reports when it last ran + // after the app has been quit and reopened. + do { + try state.bundle?.setState(Bundle.State(startedDate: startedDate)) + } catch { + log.warning("Failed to record start date for container \(id): \(error)") + } + + // Start port forwarding for published ports + let config = state.snapshot.configuration + if !config.publishedPorts.isEmpty { + let forwarder = PortForwarder(log: self.log) + for port in config.publishedPorts { + do { + try await forwarder.startForwarding(publishPort: port, container: container) + } catch { + log.warning("Failed to start port forwarding for \(port.hostPort) -> \(port.containerPort): \(error)") + } + } + portForwarders[id] = forwarder + } // Monitor container exit in background let logger = self.log - + state.exitMonitorTask = Task { [weak self] in + var exitCode: Int32 = 0 do { - try await container.wait() - // Container exited + exitCode = try await container.wait().exitCode } catch { logger.error("Error waiting for container \(id): \(error)") } - await self?.handleContainerExit(id: id) + await self?.handleContainerExit(id: id, exitCode: exitCode) + return exitCode } containers[id] = state - + // Notify observers that container started notifyStateChange() } } - public func stop(id: String, options: ContainerStopOptions) async throws { + /// Waits for the container's init process to exit and returns its code. + func wait(id: String) async throws -> Int32 { + guard let state = containers[id] else { + throw ContainerizationError(.notFound, message: "container with ID \(id) not found") + } + + // A container that exited before anyone waited on it has already torn + // down its monitor, so the code it left behind is all there is. + guard let monitor = state.exitMonitorTask else { + return state.lastExitCode ?? 0 + } + + return try await ExitWaiter().wait(for: monitor) + } + + /// What each running container is using right now. A container that + /// cannot say, because it is on its way down, is left out. + func resourceUsage() async -> [ContainerResourceUsage] { + // Taken before the first await: the actor can change underneath it. + let running = containers.compactMap { id, state in + state.snapshot.status == .running + ? state.container.map { (id, $0) } : nil + } + + var usage: [ContainerResourceUsage] = [] + + for (id, container) in running { + guard + let stats = try? await container.statistics(categories: [.memory, .cpu]) + else { + continue + } + + let entry = ContainerResourceUsage( + id: id, + memoryBytes: stats.memory?.usageBytes ?? 0, + cpuUsageMicroseconds: stats.cpu?.usageUsec ?? 0 + ) + + usage.append(entry) + } + + return usage + } + + func stop(id: String, options: ContainerStopOptions) async throws { + try await containerLock.withLock { _ in + try await self._stop(id: id, options: options) + } + } + + private func _stop(id: String, options: ContainerStopOptions) async throws { guard var state = containers[id] else { throw ContainerizationError(.notFound, message: "container with ID \(id) not found") } if let container = state.container { + // Shown while the container winds down, which can last until the stop timeout. + containers[id]?.snapshot.status = .stopping + notifyStateChange() + do { try await gracefulStopContainer(container, stopOpts: options) } catch let err as ContainerizationError { if err.code != .interrupted { + // It is still running, as far as anyone can tell. + containers[id]?.snapshot.status = state.snapshot.status + notifyStateChange() throw err } } catch { @@ -411,13 +635,23 @@ public actor SandboxedContainersService { state.snapshot.networks = [] state.container = nil releaseIP(for: id) + + // Stop port forwarding + if let forwarder = portForwarders.removeValue(forKey: id) { + await forwarder.stopAll() + } + containers[id] = state - + + if autoRemoves(state) { + removeContainer(id: id) + } + // Notify observers that container stopped notifyStateChange() } - public func delete(id: String) async throws { + func delete(id: String) async throws { guard let state = containers[id] else { throw ContainerizationError(.notFound, message: "container with ID \(id) not found") } @@ -426,7 +660,13 @@ public actor SandboxedContainersService { throw ContainerizationError(.invalidState, message: "cannot delete running container") } - // Delete container bundle + removeContainer(id: id) + notifyStateChange() + } + + /// Takes the container off disk and out of the list. The caller decides + /// whether removing it is allowed and when observers hear about it. + private func removeContainer(id: String) { let path = containerRoot.appendingPathComponent(id) try? FileManager.default.removeItem(at: path) @@ -434,16 +674,24 @@ public actor SandboxedContainersService { containers.removeValue(forKey: id) } + /// Whether the container asked at create time to be taken away as soon as + /// it stops, which is answered by the options kept in its bundle. + private func autoRemoves(_ state: ContainerState) -> Bool { + guard let bundle = state.bundle else { return false } + + return (try? bundle.createOptions)?.autoRemove ?? false + } + /// Execute a command in a running container and return its output (uses vsock, no networking needed). - public func exec(id: String, arguments: [String]) async throws -> String { + func exec(id: String, arguments: [String]) async throws -> String { guard let state = containers[id], let container = state.container else { throw ContainerizationError(.invalidState, message: "container not running: \(id)") } let outputURL = containerRoot.appendingPathComponent("\(id)-exec-output.tmp") - + FileManager.default.createFile(atPath: outputURL.path, contents: nil) - + let outputHandle = try FileHandle(forWritingTo: outputURL) let writer = MultiWriter(handles: [outputHandle]) @@ -454,23 +702,24 @@ public actor SandboxedContainersService { } try await process.start() - + let exitStatus = try await process.wait() - + try? writer.close() let output = (try? String(contentsOf: outputURL, encoding: .utf8)) ?? "" - + try? FileManager.default.removeItem(at: outputURL) - + if exitStatus.exitCode != 0 { - throw ContainerizationError(.internalError, message: "command failed with exit code \(exitStatus.exitCode): \(output)") + let message = "command failed with exit code \(exitStatus.exitCode): \(output)" + throw ContainerizationError(.internalError, message: message) } - + return output } - public func dial(id: String, port: UInt32) async throws -> FileHandle { + func dial(id: String, port: UInt32) async throws -> FileHandle { guard let state = containers[id], let container = state.container else { throw ContainerizationError(.invalidState, message: "container not running: \(id)") } @@ -491,10 +740,7 @@ public actor SandboxedContainersService { return (address: "192.168.64.\(i)/24", gateway: "192.168.64.1") } } - throw ContainerizationError( - .internalError, - message: "no available IP addresses" - ) + throw ContainerizationError(.internalError, message: "no available IP addresses") } private func releaseIP(for id: String) { @@ -503,19 +749,30 @@ public actor SandboxedContainersService { // MARK: - Private Methods - private func handleContainerExit(id: String) { + private func handleContainerExit(id: String, exitCode: Int32) { guard var state = containers[id] else { log.warning("Container \(id) not found during exit handling") return } + state.lastExitCode = exitCode state.snapshot.status = .stopped state.snapshot.networks = [] state.container = nil state.exitMonitorTask?.cancel() state.exitMonitorTask = nil releaseIP(for: id) + + // Stop port forwarding + if let forwarder = portForwarders.removeValue(forKey: id) { + Task { await forwarder.stopAll() } + } + containers[id] = state - + + if autoRemoves(state) { + removeContainer(id: id) + } + notifyStateChange() } @@ -527,9 +784,9 @@ public actor SandboxedContainersService { try await lc.wait() } group.addTask { - try await lc.kill(stopOpts.signal) + try await lc.kill(Signal(rawValue: stopOpts.signal)) try await Task.sleep(for: .seconds(stopOpts.timeoutInSeconds)) - try await lc.kill(SIGKILL) + try await lc.kill(Signal(rawValue: SIGKILL)) return ExitStatus(exitCode: 137) } guard let code = try await group.next() else { @@ -557,12 +814,9 @@ public actor SandboxedContainersService { ) throws { czConfig.cpus = config.resources.cpus czConfig.memoryInBytes = config.resources.memoryInBytes - czConfig.sysctl = config.sysctls.reduce(into: [String: String]()) { - $0[$1.key] = $1.value - } + czConfig.sysctl = config.sysctls czConfig.virtualization = config.virtualization - // Use precomputed mounts and sockets czConfig.mounts.append(contentsOf: precomputedMounts) czConfig.sockets.append(contentsOf: precomputedSockets) @@ -598,26 +852,33 @@ public actor SandboxedContainersService { // If not set, containers will use the host's DNS via the VM network if let dns = config.dns, !dns.nameservers.isEmpty { czConfig.dns = DNS( - nameservers: dns.nameservers, domain: dns.domain, - searchDomains: dns.searchDomains, options: dns.options) + nameservers: dns.nameservers, + domain: dns.domain, + searchDomains: dns.searchDomains, + options: dns.options + ) } - Self.configureInitialProcess(czConfig: &czConfig, config: config) + try Self.configureInitialProcess(czConfig: &czConfig, config: config) } private static func configureInitialProcess( czConfig: inout LinuxContainer.Configuration, config: ContainerConfiguration - ) { + ) throws { let process = config.initProcess czConfig.process.arguments = [process.executable] + process.arguments czConfig.process.environmentVariables = process.environment + czConfig.process.capabilities = try capabilities(from: config.capabilities) if config.ssh, Foundation.ProcessInfo.processInfo.environment["SSH_AUTH_SOCK"] != nil { let sshEnvVar = "SSH_AUTH_SOCK" let sshGuestPath = "/run/host-services/ssh-auth.sock" - if !czConfig.process.environmentVariables.contains(where: { $0.starts(with: "\(sshEnvVar)=") }) { + + if !czConfig.process.environmentVariables.contains(where: { + $0.starts(with: "\(sshEnvVar)=") + }) { czConfig.process.environmentVariables.append("\(sshEnvVar)=\(sshGuestPath)") } } @@ -628,6 +889,7 @@ public actor SandboxedContainersService { guard let kind = try? LinuxRLimit.Kind($0.limit) else { return nil } return .init(kind: kind, hard: $0.hard, soft: $0.soft) } + switch process.user { case .raw(let name): czConfig.process.user = .init( @@ -648,25 +910,60 @@ public actor SandboxedContainersService { } } + private static func capabilities(from names: [String]) throws -> Containerization.LinuxCapabilities { + let capabilities = try capabilitySet(from: names) + + guard !capabilities.isEmpty else { + return .allCapabilities + } + + return Containerization.LinuxCapabilities(capabilities: Array(capabilities)) + } + + private static func capabilitySet(from names: [String]) throws -> Set { + var capabilities: Set = [] + + for name in names { + let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) + + guard !trimmedName.isEmpty else { + continue + } + + if trimmedName.uppercased() == "ALL" { + capabilities.formUnion(CapabilityName.allCases) + } else { + capabilities.insert(try CapabilityName(rawValue: trimmedName)) + } + } + + return capabilities + } + private func getInitBlock(for platform: Platform) async throws -> Filesystem { - // Use in-process ImagesService to get the init image snapshot (no XPC) - let initImageRef = ClientImage.initImageRef + let initImageRef: String = DefaultsStore.get(key: .defaultInitImage) let initDescription = try await imagesService.pull( reference: initImageRef, platform: platform, insecure: false, progressUpdate: nil ) + try await imagesService.unpack( description: initDescription, platform: platform, progressUpdate: nil ) - var fs = try await imagesService.getImageSnapshot(description: initDescription, platform: platform) + + var fs = try await imagesService.getImageSnapshot( + description: initDescription, + platform: platform + ) + fs.options = ["ro"] return fs } - + /// Notify all registered callbacks that container state changed private func notifyStateChange() { for callback in stateChangeCallbacks { diff --git a/ContainerSystem/Services/ImagesService.swift b/ContainerSystem/Services/ImagesService.swift new file mode 100644 index 0000000..9b5a18f --- /dev/null +++ b/ContainerSystem/Services/ImagesService.swift @@ -0,0 +1,190 @@ +// +// ImagesService.swift +// Containers +// +// In-process image management service wrapping ImageStore and EXT4Unpacker. +// +// Created by Axel on 17/3/26. +// + +import Containerization +import ContainerizationError +import ContainerizationExtras +import ContainerizationOCI +import ContainerizationOS +import Foundation +import Logging + +/// A service that handles container images, wrapping ImageStore and EXT4Unpacker. +actor ImagesService { + private let imageStore: ImageStore + private let contentStore: ContentStore + private let snapshotsPath: URL + private let log: Logger + + init(contentStore: ContentStore, imageStore: ImageStore, snapshotsPath: URL, log: Logger) throws { + self.contentStore = contentStore + self.imageStore = imageStore + self.snapshotsPath = snapshotsPath + self.log = log + + try FileManager.default.createDirectory(at: snapshotsPath, withIntermediateDirectories: true) + } + + // MARK: - Internal API + + /// List all images in the store. + func list() async throws -> [ImageDescription] { + let images = try await imageStore.list() + return images.map { $0.description } + } + + /// Pull an image from a remote registry. + func pull( + reference: String, + platform: Platform?, + insecure: Bool, + auth: Authentication? = nil, + progressUpdate: ProgressHandler? + ) async throws -> ImageDescription { + // Try provided auth first, then keychain, then environment variables + let resolvedAuth = auth ?? resolveAuthentication(for: reference) + + let image = try await imageStore.pull( + reference: reference, + platform: platform, + insecure: insecure, + auth: resolvedAuth, + progress: progressUpdate + ) + return image.description + } + + /// Unpack an image to an EXT4 block device for use as a container rootfs. + func unpack( + description: ImageDescription, + platform: Platform?, + progressUpdate: ProgressHandler? + ) async throws { + let image = try await imageStore.get(reference: description.reference) + let targetPlatform = platform ?? .current + + // Determine the EXT4 file path for this image+platform combination + let ext4Path = snapshotFilePath(for: description, platform: targetPlatform) + + // Skip if already unpacked + if FileManager.default.fileExists(atPath: ext4Path.path) { + return + } + + let initImage = DefaultsStore.get(key: .defaultInitImage) + let blockSize = image.reference == initImage ? 512.mib() : 512.gib() + let unpacker = EXT4Unpacker(blockSizeInBytes: blockSize) + _ = try await unpacker.unpack(image, for: targetPlatform, at: ext4Path, progress: progressUpdate) + } + + /// Get a Filesystem representing the unpacked image snapshot. + func getImageSnapshot(description: ImageDescription, platform: Platform) async throws -> Filesystem { + let ext4Path = snapshotFilePath(for: description, platform: platform) + + guard FileManager.default.fileExists(atPath: ext4Path.path) else { + throw ContainerizationError( + .notFound, + message: "image snapshot not found at \(ext4Path.path). Was the image unpacked?" + ) + } + + return Filesystem(type: .block(format: "ext4"), source: ext4Path.path, destination: "/", options: []) + } + + /// Load images from an OCI layout directory on disk. + func load(from directory: URL, force: Bool = false) async throws -> ([ImageDescription], [String]) { + let images = try await imageStore.load(from: directory) + let descriptions = images.map { $0.description } + let references = descriptions.map { $0.reference } + return (descriptions, references) + } + + /// Tag an image with a new reference. + func tag(existing: String, new: String) async throws -> ImageDescription { + let image = try await imageStore.tag(existing: existing, new: new) + return image.description + } + + /// Save images to an OCI layout directory. + func save(references: [String], out: URL, platform: Platform?) async throws { + try await imageStore.save(references: references, out: out, platform: platform) + } + + /// Push an image to a remote registry. + func push( + reference: String, + platform: Platform?, + insecure: Bool, + auth: Authentication? = nil, + progressUpdate: ProgressHandler? + ) async throws { + let resolvedAuth = auth ?? resolveAuthentication(for: reference) + + try await imageStore.push( + reference: reference, + platform: platform, + insecure: insecure, + auth: resolvedAuth, + progress: progressUpdate + ) + } + + /// Delete an image by reference. + func delete(reference: String, garbageCollect: Bool = false) async throws { + try await imageStore.delete(reference: reference, performCleanup: garbageCollect) + } + + // MARK: - Private Helpers + + private func snapshotFilePath(for description: ImageDescription, platform: Platform) -> URL { + // Use a stable hash of the digest + platform for the snapshot file name + let key = "\(description.digest)-\(platform.os)-\(platform.architecture)" + let fileName = key.replacingOccurrences(of: ":", with: "-") + .replacingOccurrences(of: "/", with: "-") + return snapshotsPath.appendingPathComponent(fileName) + } + + /// Security domain for keychain credential lookups. + private static let keychainDomain = "app.containers.registry" + + /// Resolve authentication for a registry reference. + private func resolveAuthentication(for reference: String) -> Authentication? { + guard let hostname = Self.extractHostname(from: reference) else { + return nil + } + + // 1. Check environment variables (highest priority, enables CI/CD) + let env = ProcessInfo.processInfo.environment + if env["CONTAINER_REGISTRY_HOST"] == hostname, + let user = env["CONTAINER_REGISTRY_USER"], + let token = env["CONTAINER_REGISTRY_TOKEN"] + { + return BasicAuthentication(username: user, password: token) + } + + // 2. Check macOS Keychain (credentials stored via `container registry login`) + let keychain = KeychainHelper(securityDomain: Self.keychainDomain) + if let keychainAuth = try? keychain.lookup(hostname: hostname) { + return keychainAuth + } + + // 3. No credentials found — return nil for anonymous access. + // The RegistryClient handles the 401 → Bearer token exchange for public images. + return nil + } + + /// Extract the registry hostname from an image reference. + private static func extractHostname(from reference: String) -> String? { + guard let parsed = try? ContainerizationOCI.Reference.parse(reference) + else { + return nil + } + return parsed.resolvedDomain + } +} diff --git a/ContainerSystem/Services/KernelService.swift b/ContainerSystem/Services/KernelService.swift new file mode 100644 index 0000000..0e78233 --- /dev/null +++ b/ContainerSystem/Services/KernelService.swift @@ -0,0 +1,95 @@ +// +// KernelService.swift +// Containers +// +// Manages kernel binaries for container VMs. +// +// Created by Axel on 17/3/26. +// + +import Containerization +import ContainerizationArchive +import ContainerizationError +import Foundation +import Logging + +/// Service for handling Linux kernel binaries used by container VMs. +actor KernelService { + private let log: Logger + private let kernelsRoot: URL + + init(log: Logger, appRoot: URL) throws { + self.log = log + self.kernelsRoot = appRoot.appendingPathComponent("kernels") + + try FileManager.default.createDirectory(at: kernelsRoot, withIntermediateDirectories: true) + } + + /// Get the default kernel for the given platform. + func getDefaultKernel(platform: SystemPlatform) async throws -> Kernel { + let kernelPath = kernelsRoot.appendingPathComponent("default-\(platform.architecture.rawValue)") + + guard FileManager.default.fileExists(atPath: kernelPath.path) else { + throw ContainerizationError( + .notFound, + message: "Default kernel not found for \(platform.architecture.rawValue)" + ) + } + + return Kernel(path: kernelPath, platform: platform) + } + + /// Install a kernel binary for the given platform from a tar archive. + /// + /// Reading the kernel out of the archive is tens of megabytes of blocking + /// I/O, so it runs on this actor rather than on the caller that asked + /// for it. + func installKernelFrom( + tar tarFile: URL, + kernelFilePath: String, + platform: SystemPlatform, + force: Bool = false + ) async throws { + let destination = kernelsRoot.appendingPathComponent("default-\(platform.architecture.rawValue)") + + if FileManager.default.fileExists(atPath: destination.path) { + guard force else { + log.info("Kernel already installed for \(platform.architecture.rawValue), skipping") + return + } + + try FileManager.default.removeItem(at: destination) + } + + let kernel = try extractFile(tarFile: tarFile, at: kernelFilePath) + + try kernel.write(to: destination, options: .atomic) + + log.info("Kernel installed at \(destination.path), size: \(kernel.count) bytes") + } + + /// Extract a file from an archive, returning its bytes rather than a path. + private func extractFile(tarFile: URL, at path: String) throws -> Data { + log.info("Extracting \(path) from archive: \(tarFile.path)") + + var archiveReader = try ArchiveReader(file: tarFile) + let (entry, extracted) = try archiveReader.extractFile(path: path) + + // If the target file is a symlink, get the data for the actual file + guard entry.fileType == .symbolicLink, let symlinkRelative = entry.symlinkTarget else { + return extracted + } + + // Reopen the archive to traverse from the beginning + archiveReader = try ArchiveReader(file: tarFile) + + let symlinkTarget = URL(filePath: path).deletingLastPathComponent().appending(path: symlinkRelative) + let resolvedPath = symlinkTarget.standardized.relativePath + + log.info("Kernel is a symlink to \(symlinkRelative), resolved: \(resolvedPath)") + + let (_, targetData) = try archiveReader.extractFile(path: resolvedPath) + + return targetData + } +} diff --git a/ContainerSystem/Services/SandboxedBuilder.swift b/ContainerSystem/Services/SandboxedBuilder.swift deleted file mode 100644 index 83054e1..0000000 --- a/ContainerSystem/Services/SandboxedBuilder.swift +++ /dev/null @@ -1,799 +0,0 @@ -// -// SandboxedBuilder.swift -// Containers -// -// Sandboxed version of Builder that implements build protocol without XPC dependencies -// -// Created by Axel Martinez on 2026/02/09. -// - -import Foundation -import ContainerBuild -import ContainerImagesService -import ContainerResource -import Containerization -import ContainerizationOCI -import ContainerizationError -import ContainerizationOS -import GRPC -import NIO -import Logging - -/// Standalone sandboxed builder that uses ImagesService instead of XPC-based ClientImage -public struct SandboxedBuilder: Sendable { - public static let builderContainerId = "buildkit" - - let client: BuilderClientProtocol - let clientAsync: BuilderClientAsyncProtocol - let group: EventLoopGroup - let builderShimSocket: FileHandle - let channel: GRPCChannel - let imagesService: ImagesService - let contentStore: ContentStore - private let logger: Logger - - public init(socket: FileHandle, group: EventLoopGroup, imagesService: ImagesService, contentStore: ContentStore) throws { - // Socket buffer configuration would be done here if the APIs were public - // For now we skip this as setSendBufSize/setRecvBufSize are internal - var config = ClientConnection.Configuration.default( - target: .connectedSocket(socket.fileDescriptor), - eventLoopGroup: group - ) - config.connectionIdleTimeout = TimeAmount(.seconds(600)) - config.connectionKeepalive = .init( - interval: TimeAmount(.seconds(600)), - timeout: TimeAmount(.seconds(500)), - permitWithoutCalls: true - ) - config.connectionBackoff = .init( - initialBackoff: TimeInterval(1), - maximumBackoff: TimeInterval(10) - ) - config.callStartBehavior = .fastFailure - config.httpMaxFrameSize = 8 << 10 - config.maximumReceiveMessageLength = 512 << 20 - config.httpTargetWindowSize = 16 << 10 - - let channel = ClientConnection(configuration: config) - self.channel = channel - self.clientAsync = BuilderClientAsync(channel: channel) - self.client = BuilderClient(channel: channel) - self.group = group - self.builderShimSocket = socket - self.imagesService = imagesService - self.contentStore = contentStore - - var logger = Logger(label: "app.containers.sandboxed-builder") - logger.logLevel = .info - self.logger = logger - } - - public func info() async throws -> InfoResponse { - let opts = CallOptions(timeLimit: .timeout(.seconds(30))) - return try await self.clientAsync.info(InfoRequest(), callOptions: opts) - } - - /// Perform a sandboxed build using custom pipeline that handles image resolution - public func build(_ config: Builder.BuildConfig) async throws { - let logger = Logger(label: "app.containers.sandboxed-builder.build") - logger.info("SandboxedBuilder.build() called with buildID: \(config.buildID)") - - var continuation: AsyncStream.Continuation? - let reqStream = AsyncStream { (cont: AsyncStream.Continuation) in - continuation = cont - } - guard let continuation else { - throw SandboxedBuilderError.invalidContinuation - } - - defer { - continuation.finish() - } - - // Terminal handling would go here if needed - // For now, we skip this as it requires internal TerminalCommand type - - logger.info("Creating gRPC stream to BuildKit") - logger.info("Build config: buildID=\(config.buildID), contextDir=\(config.contextDir)") - logger.info("Build config: dockerfile size=\(config.dockerfile.count) bytes, tags=\(config.tags)") - logger.info("Build config: platforms=\(config.platforms.map { $0.description }), target=\(config.target)") - logger.info("Build config: exports=\(config.exports.map { $0.type })") - - let respStream = self.clientAsync.performBuild(reqStream, callOptions: try CallOptions(config)) - - logger.info("Initializing sandboxed build pipeline") - let pipeline = SandboxedBuildPipeline( - config: config, - imagesService: self.imagesService, - contentStore: self.contentStore - ) - - logger.info("Starting pipeline execution") - - // Start a background task to log progress - let progressTask = Task { - try? await Task.sleep(for: .seconds(30)) - logger.warning("Pipeline has been running for 30 seconds without completion") - try? await Task.sleep(for: .seconds(30)) - logger.error("Pipeline has been running for 60 seconds - BuildKit may not be responding") - } - - do { - try await pipeline.run(sender: continuation, receiver: respStream) - progressTask.cancel() - logger.info("Build completed successfully") - } catch { - progressTask.cancel() - - // Check if this is the normal build complete signal - if let builderError = error as? SandboxedBuilderError, builderError == .buildComplete { - logger.info("Build completed successfully") - return - } - - logger.error("Pipeline execution failed: \(error)") - _ = channel.close() - try await group.shutdownGracefully() - throw error - } - } -} - -// MARK: - Sandboxed Build Pipeline - -/// Custom build pipeline that uses ImagesService for image resolution instead of XPC -private actor SandboxedBuildPipeline { - let config: Builder.BuildConfig - let imagesService: ImagesService - let contentStore: ContentStore - let logger: Logger - - init(config: Builder.BuildConfig, imagesService: ImagesService, contentStore: ContentStore) { - self.config = config - self.imagesService = imagesService - self.contentStore = contentStore - var logger = Logger(label: "app.containers.sandboxed-pipeline") - logger.logLevel = .info - self.logger = logger - } - - func run( - sender: AsyncStream.Continuation, - receiver: GRPCAsyncResponseStream - ) async throws { - defer { sender.finish() } - - logger.info("Build pipeline started") - var packetCount = 0 - - for try await packet in receiver { - try Task.checkCancellation() - packetCount += 1 - - if packetCount == 1 { - logger.info("Received first packet from BuildKit") - } - - // Log packet type - switch packet.packetType { - case .imageTransfer(let transfer): - logger.debug("Packet #\(packetCount): ImageTransfer(stage:\(transfer.stage() ?? "nil"), method:\(transfer.method() ?? "nil"))") - case .buildTransfer(let transfer): - logger.debug("Packet #\(packetCount): BuildTransfer(stage:\(transfer.metadata["stage"] ?? "nil"), method:\(transfer.metadata["method"] ?? "nil"))") - case .io(let io): - if let message = String(data: io.data, encoding: .utf8), !message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - logger.info("\(message)") - } - case .buildError(let error): - logger.error("Build error: \(error.message)") - case .commandComplete: - logger.info("Build command completed") - throw SandboxedBuilderError.buildComplete - case .none: - logger.debug("Packet #\(packetCount): Empty") - } - - // Handle different packet types - if let imageTransfer = packet.getImageTransfer() { - try await handleImageTransfer(imageTransfer, sender: sender, buildID: packet.buildID) - } else if let buildTransfer = packet.getBuildTransfer() { - try await handleBuildTransfer(buildTransfer, sender: sender, buildID: packet.buildID) - } else if let io = packet.getIO() { - try await handleIO(io, sender: sender, buildID: packet.buildID) - } - } - - logger.info("Build pipeline finished (\(packetCount) packets)") - logger.info("Stream ended - build should be complete") - } - - private func handleImageTransfer( - _ imageTransfer: ImageTransfer, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - let stage = imageTransfer.metadata["stage"] - let method = imageTransfer.metadata["method"] - - // Handle resolver requests - if stage == "resolver" && method == "/resolve" { - try await handleResolverRequest(imageTransfer, sender: sender, buildID: buildID) - return - } - - // Handle content-store requests - if stage == "content-store" { - try await handleContentStoreRequest(imageTransfer, sender: sender, buildID: buildID) - return - } - - logger.debug("Skipping ImageTransfer(stage=\(stage ?? "nil"), method=\(method ?? "nil"))") - } - - private func handleResolverRequest( - _ imageTransfer: ImageTransfer, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - guard let ref = imageTransfer.ref() else { - throw SandboxedBuilderError.imageMissing - } - - guard let platform = try imageTransfer.platform() else { - throw SandboxedBuilderError.platformMissing - } - - logger.info("Resolving image: \(ref) for platform: \(platform.description)") - - let imageDescription = try await pullImage(reference: ref, platform: platform) - - guard let indexContent: Content = try await contentStore.get(digest: imageDescription.digest) else { - throw SandboxedBuilderError.imageNotFound - } - let index: Index = try indexContent.decode() - - for manifest in index.manifests { - if manifest.platform == platform { - guard let manifestContent: Content = try await contentStore.get(digest: manifest.digest) else { - continue - } - let manifestData: Manifest = try manifestContent.decode() - - guard let ociImage: ContainerizationOCI.Image = try await contentStore.get(digest: manifestData.config.digest) else { - continue - } - - let enc = JSONEncoder() - let data = try enc.encode(ociImage) - let transfer = try ImageTransfer( - id: imageTransfer.id, - digest: imageDescription.digest, - ref: ref, - platform: platform.description, - data: data - ) - - var response = ClientStream() - response.buildID = buildID - response.imageTransfer = transfer - response.packetType = .imageTransfer(transfer) - sender.yield(response) - - logger.info("Resolved: \(ref)") - return - } - } - - throw SandboxedBuilderError.unknownPlatformForImage(platform.description, ref) - } - - private func handleContentStoreRequest( - _ imageTransfer: ImageTransfer, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - let method = imageTransfer.metadata["method"] - - switch method { - case "/containerd.services.content.v1.Content/Info": - try await handleContentStoreInfo(imageTransfer, sender: sender, buildID: buildID) - case "/containerd.services.content.v1.Content/ReaderAt": - try await handleContentStoreReaderAt(imageTransfer, sender: sender, buildID: buildID) - default: - logger.error("Unknown content-store method: \(method ?? "nil")") - } - } - - private func handleContentStoreInfo( - _ packet: ImageTransfer, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - // BuildKit is asking for information about a blob in the content store - let digest = packet.tag - - // Get the blob descriptor from content store - let descriptor = try await contentStore.get(digest: digest) - let size = try descriptor?.size() - - var transfer = ImageTransfer() - transfer.id = packet.id - transfer.tag = digest - transfer.metadata = [ - "os": "linux", - "stage": "content-store", - "method": "/containerd.services.content.v1.Content/Info", - ] - if let size = size { - transfer.metadata["size"] = String(size) - } - transfer.complete = true - transfer.direction = .into - - var response = ClientStream() - response.buildID = buildID - response.imageTransfer = transfer - response.packetType = .imageTransfer(transfer) - sender.yield(response) - } - - private func handleContentStoreReaderAt( - _ packet: ImageTransfer, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - // BuildKit is asking to read data from a blob - let digest = packet.descriptor.digest - let offset = UInt64(packet.metadata["offset"] ?? "0") ?? 0 - let length = Int(packet.metadata["length"] ?? "0") ?? 0 - - guard let descriptor = try await contentStore.get(digest: digest) else { - logger.error("Blob not found in content store: \(digest)") - throw SandboxedBuilderError.imageNotInContentStore(digest) - } - - // If offset and length are both 0, this is a metadata request (just size) - if offset == 0 && length == 0 { - let size = try descriptor.size() - var transfer = ImageTransfer() - transfer.id = packet.id - transfer.tag = digest - transfer.metadata = [ - "os": "linux", - "stage": "content-store", - "method": "/containerd.services.content.v1.Content/ReaderAt", - "size": String(size), - ] - transfer.complete = true - transfer.direction = .into - transfer.data = Data() - - var response = ClientStream() - response.buildID = buildID - response.imageTransfer = transfer - response.packetType = .imageTransfer(transfer) - sender.yield(response) - return - } - - // Read the blob data at the requested offset and length - guard let data = try descriptor.data(offset: offset, length: length) else { - logger.error("Failed to read data from content store: digest=\(digest), offset=\(offset), length=\(length)") - throw SandboxedBuilderError.imageNotInContentStore(digest) - } - - var transfer = ImageTransfer() - transfer.id = packet.id - transfer.tag = digest - transfer.metadata = [ - "os": "linux", - "stage": "content-store", - "method": "/containerd.services.content.v1.Content/ReaderAt", - ] - transfer.complete = true - transfer.direction = .into - transfer.data = data - - var response = ClientStream() - response.buildID = buildID - response.imageTransfer = transfer - response.packetType = .imageTransfer(transfer) - sender.yield(response) - } - - private func handleBuildTransfer( - _ buildTransfer: BuildTransfer, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - // BuildTransfer packets are used for syncing files (both build context and exports) - let stage = buildTransfer.metadata["stage"] - let direction = buildTransfer.direction - - logger.info("BuildTransfer: stage=\(stage ?? "nil"), direction=\(direction), source=\(buildTransfer.source), dataSize=\(buildTransfer.data.count)") - - switch stage { - case "fssync": - // Handle build context file sync - try await handleFSSyncTransfer(buildTransfer, sender: sender, buildID: buildID) - case "export", nil: - // Handle export file write - BuildKit is trying to write the export tar - logger.info("Handling export transfer") - try await handleExportTransfer(buildTransfer, sender: sender, buildID: buildID) - default: - logger.warning("Ignoring BuildTransfer with unknown stage: \(stage ?? "unknown")") - } - } - - private func handleFSSyncTransfer( - _ buildTransfer: BuildTransfer, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - guard let method = buildTransfer.metadata["method"] else { - logger.error("BuildTransfer missing method") - return - } - - let contextDir = URL(fileURLWithPath: config.contextDir) - - switch method { - case "Read": - try await handleFSSyncRead(buildTransfer, contextDir: contextDir, sender: sender, buildID: buildID) - case "Info": - try await handleFSSyncInfo(buildTransfer, contextDir: contextDir, sender: sender, buildID: buildID) - case "Walk": - try await handleFSSyncWalk(buildTransfer, contextDir: contextDir, sender: sender, buildID: buildID) - default: - logger.error("Unknown FSSync method: \(method)") - } - } - - private func handleExportTransfer( - _ buildTransfer: BuildTransfer, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - // BuildKit is trying to write export data through the filesync protocol - // We need to receive the data and write it to the export directory - - logger.info("Export transfer: direction=\(buildTransfer.direction), complete=\(buildTransfer.complete), source=\(buildTransfer.source), dataSize=\(buildTransfer.data.count)") - - // The source path from BuildKit is like "/var/lib/container-builder-shim/exports/{buildID}/out.tar" - // We need to extract the relative path and write to our export directory - let exportBasePath = "/var/lib/container-builder-shim/exports/" - guard buildTransfer.source.hasPrefix(exportBasePath) else { - logger.error("Unexpected export source path: \(buildTransfer.source)") - return - } - - let relativePath = String(buildTransfer.source.dropFirst(exportBasePath.count)) - - // Construct the host filesystem path - // The export directory structure is: appRoot/.build/{buildID}/ - guard let appRoot = try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false) - .appendingPathComponent("com.axelmartinez.Containers") else { - logger.error("Could not determine app root") - return - } - - let exportPath = appRoot.appendingPathComponent(".build").appendingPathComponent(relativePath) - - logger.info("Writing export data to: \(exportPath.path)") - - // Create parent directory if needed - let parentDir = exportPath.deletingLastPathComponent() - try? FileManager.default.createDirectory(at: parentDir, withIntermediateDirectories: true) - - // Write or append the data - if buildTransfer.data.count > 0 { - if FileManager.default.fileExists(atPath: exportPath.path) { - // Append to existing file - let fileHandle = try FileHandle(forWritingTo: exportPath) - defer { try? fileHandle.close() } - try fileHandle.seekToEnd() - try fileHandle.write(contentsOf: buildTransfer.data) - } else { - // Create new file - try buildTransfer.data.write(to: exportPath) - } - } - - // Send acknowledgment back to BuildKit - var response = ClientStream() - response.buildID = buildID - response.buildTransfer = BuildTransfer() - response.buildTransfer.id = buildTransfer.id - response.buildTransfer.source = buildTransfer.source - response.buildTransfer.complete = true - response.buildTransfer.direction = .outof - response.buildTransfer.metadata = [ - "os": "linux" - ] - - response.packetType = .buildTransfer(response.buildTransfer) - sender.yield(response) - - if buildTransfer.complete { - logger.info("Export transfer complete for: \(exportPath.path)") - } - } - - private func handleFSSyncRead( - _ packet: BuildTransfer, - contextDir: URL, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - let path = contextDir.appendingPathComponent(packet.source).standardizedFileURL - - // Read file data - let data: Data - if FileManager.default.fileExists(atPath: path.path) { - let offset = UInt64(packet.metadata["offset"] ?? "0") ?? 0 - let length = Int(packet.metadata["length"] ?? "0") ?? 0 - - if path.hasDirectoryPath == true { - data = Data() - } else { - let fileData = try Data(contentsOf: path) - if offset == 0 && length == 0 { - data = fileData - } else { - let start = Int(offset) - let end = length > 0 ? start + length : fileData.count - data = fileData.subdata(in: start...Continuation, - buildID: String - ) async throws { - let path = contextDir.appendingPathComponent(packet.source).standardizedFileURL - - var response = ClientStream() - response.buildID = buildID - response.buildTransfer = BuildTransfer() - response.buildTransfer.id = packet.id - response.buildTransfer.source = packet.source - response.buildTransfer.complete = true - response.buildTransfer.direction = .outof - response.buildTransfer.isDirectory = path.hasDirectoryPath - response.buildTransfer.metadata = [ - "os": "linux", - "stage": "fssync", - ] - - // Add file metadata if file exists - if FileManager.default.fileExists(atPath: path.path), - let attrs = try? FileManager.default.attributesOfItem(atPath: path.path) { - if let size = attrs[.size] as? UInt64 { - response.buildTransfer.metadata["size"] = String(size) - } - if let mode = attrs[.posixPermissions] as? NSNumber { - response.buildTransfer.metadata["mode"] = String(mode.uint32Value) - } - if let modDate = attrs[.modificationDate] as? Date { - let formatter = ISO8601DateFormatter() - response.buildTransfer.metadata["modified_at"] = formatter.string(from: modDate) - } - response.buildTransfer.metadata["uid"] = "0" - response.buildTransfer.metadata["gid"] = "0" - } - - response.packetType = .buildTransfer(response.buildTransfer) - sender.yield(response) - } - - private func handleFSSyncWalk( - _ packet: BuildTransfer, - contextDir: URL, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - // BuildKit is asking for a list of files to transfer - // For now, send back an empty walk response to indicate we have no files - // A full implementation would enumerate the context directory and send file info - - let mode = packet.metadata["mode"] ?? "json" - - if mode == "json" { - // Send JSON list of files - let fileList: [[String: Any]] = [] // Empty for now - let jsonData = try JSONSerialization.data(withJSONObject: fileList) - - var response = ClientStream() - response.buildID = buildID - response.buildTransfer = BuildTransfer() - response.buildTransfer.id = packet.id - response.buildTransfer.source = packet.source - response.buildTransfer.complete = true - response.buildTransfer.direction = .outof - response.buildTransfer.isDirectory = false - response.buildTransfer.metadata = [ - "os": "linux", - "stage": "fssync", - "mode": "json", - ] - response.buildTransfer.data = jsonData - response.packetType = .buildTransfer(response.buildTransfer) - sender.yield(response) - } else { - // Send empty tar for tar mode - var response = ClientStream() - response.buildID = buildID - response.buildTransfer = BuildTransfer() - response.buildTransfer.id = packet.id - response.buildTransfer.source = packet.source - response.buildTransfer.complete = true - response.buildTransfer.direction = .outof - response.buildTransfer.isDirectory = false - response.buildTransfer.metadata = [ - "os": "linux", - "stage": "fssync", - "mode": "tar", - ] - response.buildTransfer.data = Data() - response.packetType = .buildTransfer(response.buildTransfer) - sender.yield(response) - } - } - - private func handleIO( - _ io: IO, - sender: AsyncStream.Continuation, - buildID: String - ) async throws { - // Write the output to our terminal if not quiet - if !config.quiet { - if let handle = config.terminal?.handle { - try handle.write(contentsOf: io.data) - } else { - // Fallback to stderr - try FileHandle.standardError.write(contentsOf: io.data) - } - } - - // CRITICAL: Send terminal command response back to BuildKit - // BuildKit waits for this response before continuing - let cmdString = try SimpleTerminalCommand().json() - var response = ClientStream() - response.buildID = buildID - response.command = .init() - response.command.id = buildID - response.command.command = cmdString - sender.yield(response) - } - - private func pullImage(reference: String, platform: Platform) async throws -> ImageDescription { - // Normalize the image reference to include registry host - var normalizedRef = reference - if !reference.contains("/") { - normalizedRef = "docker.io/library/\(reference)" - } else if reference.split(separator: "/").count == 2 && !reference.contains(".") { - normalizedRef = "docker.io/\(reference)" - } - - // Check if image already exists - let existingImages = try await imagesService.list() - if let existing = existingImages.first(where: { $0.reference == normalizedRef || $0.reference == reference }) { - logger.debug("Using existing image: \(normalizedRef)") - return existing - } - - // Pull the image - logger.info("Pulling \(normalizedRef)...") - let imageDescription = try await imagesService.pull( - reference: normalizedRef, - platform: platform, - insecure: false, - progressUpdate: { events in - if !self.config.quiet { - for event in events { - if case .setDescription(let desc) = event { - self.logger.info("\(desc)") - } - } - } - } - ) - - try await imagesService.unpack( - description: imageDescription, - platform: platform, - progressUpdate: nil - ) - - logger.info("Pulled \(normalizedRef)") - - return imageDescription - } -} - -// MARK: - Terminal Command - -/// Simple terminal command for sending responses to BuildKit -/// Matches the structure from ContainerBuild/TerminalCommand.swift -private struct SimpleTerminalCommand: Codable { - let commandType: String - let code: String - let rows: UInt16 - let cols: UInt16 - - enum CodingKeys: String, CodingKey { - case commandType = "command_type" - case code - case rows - case cols - } - - init() { - self.commandType = "terminal" - self.code = "ack" - self.rows = 0 - self.cols = 0 - } - - func json() throws -> String { - let encoder = JSONEncoder() - let data = try encoder.encode(self) - // CRITICAL: The command must be base64 encoded (without padding) - return data.base64EncodedString().trimmingCharacters(in: CharacterSet(charactersIn: "=")) - } -} - -// MARK: - Errors - -enum SandboxedBuilderError: Swift.Error, CustomStringConvertible, Equatable { - case invalidContinuation - case imageMissing - case platformMissing - case imageNotFound - case imageNotInContentStore(String) - case unknownPlatformForImage(String, String) - case buildComplete - case buildTimeout - - var description: String { - switch self { - case .invalidContinuation: - return "Failed to create stream continuation" - case .imageMissing: - return "Image reference missing in metadata" - case .platformMissing: - return "Platform parameter missing in metadata" - case .imageNotFound: - return "Image not found in content store" - case .imageNotInContentStore(let ref): - return "Image not found in content store: \(ref)" - case .unknownPlatformForImage(let platform, let ref): - return "Platform \(platform) for image \(ref) not found" - case .buildComplete: - return "Build completed successfully" - case .buildTimeout: - return "Build timed out" - } - } -} diff --git a/ContainerSystem/Volume/Volume.swift b/ContainerSystem/Volume/Volume.swift new file mode 100644 index 0000000..058a2f3 --- /dev/null +++ b/ContainerSystem/Volume/Volume.swift @@ -0,0 +1,99 @@ +// +// Volume.swift +// Containers +// + +import Foundation + +/// Represents a container volume. +public struct Volume: Sendable, Codable, Identifiable, Equatable { + public var name: String + public var driver: String + public var format: String + public var source: String + public var createdAt: Date + public var labels: [String: String] + public var options: [String: String] + public var sizeInBytes: UInt64? + + public var id: String { name } + + /// Label key used to mark anonymous volumes. + public static let anonymousLabel = "app.containers.resource.anonymous" + + /// Whether this volume is anonymous (auto-created, not explicitly named by user). + public var isAnonymous: Bool { + labels[Self.anonymousLabel] != nil + } + + public init( + name: String, + driver: String = "local", + format: String = "ext4", + source: String = "", + createdAt: Date = Date(), + labels: [String: String] = [:], + options: [String: String] = [:], + sizeInBytes: UInt64? = nil + ) { + self.name = name + self.driver = driver + self.format = format + self.source = source + self.createdAt = createdAt + self.labels = labels + self.options = options + self.sizeInBytes = sizeInBytes + } +} + +/// Errors related to volume operations. +public enum VolumeError: Error, LocalizedError { + case volumeNotFound(String) + case volumeAlreadyExists(String) + case volumeInUse(String) + case invalidVolumeName(String) + case unsupportedDriver(String) + case storageError(String) + + public var errorDescription: String? { + switch self { + case .volumeNotFound(let name): + return "Volume not found: \(name)" + case .volumeAlreadyExists(let name): + return "Volume already exists: \(name)" + case .volumeInUse(let name): + return "Volume is in use: \(name)" + case .invalidVolumeName(let msg): + return msg + case .unsupportedDriver(let driver): + return "Unsupported volume driver: \(driver)" + case .storageError(let msg): + return "Volume storage error: \(msg)" + } + } +} + +/// Utility functions for volume storage. +public struct VolumeStorage { + /// Regex pattern for valid volume names. + public static let volumeNamePattern = EntityName.pattern + + /// Default volume size: 512 GB. + public static let defaultVolumeSizeBytes: UInt64 = 512 * 1024 * 1024 * 1024 + + /// Validate a volume name. + public static func isValidVolumeName(_ name: String) -> Bool { + EntityName.isValid(name) + } + + /// Generate a unique anonymous volume name. + public static func anonymousVolumeName() -> String { + UUID().uuidString.lowercased() + } + + /// Generate a unique anonymous volume name (alias). + public static func generateAnonymousVolumeName() -> String { + anonymousVolumeName() + } +} diff --git a/ContainerSystem/Volume/VolumeSummary.swift b/ContainerSystem/Volume/VolumeSummary.swift new file mode 100644 index 0000000..28b63b3 --- /dev/null +++ b/ContainerSystem/Volume/VolumeSummary.swift @@ -0,0 +1,17 @@ +// +// VolumeSummary.swift +// Containers +// +// Created by Axel Martinez on 03/10/2026. +// + +/// A volume as a list shows it: the volume, and whether a container uses it. +public struct VolumeSummary: Sendable { + public let volume: Volume + public let isInUse: Bool + + public init(volume: Volume, isInUse: Bool) { + self.volume = volume + self.isInUse = isInUse + } +} diff --git a/ContainerSystemTests/ContainerManagerTests.swift b/ContainerSystemTests/ContainerManagerTests.swift index f9d6177..db30e16 100644 --- a/ContainerSystemTests/ContainerManagerTests.swift +++ b/ContainerSystemTests/ContainerManagerTests.swift @@ -5,60 +5,49 @@ // Created by Axel Martinez on 2026/02/08. // -import Testing -import Foundation -import ContainerResource import ContainerizationError +import Foundation +import Testing + @testable import ContainerSystem +@Suite("Container manager") struct ContainerManagerTests { - + // MARK: - Setup Helper - + @MainActor private func setupTestSystem() async throws -> (URL, ContainerRuntime) { let appRoot = FileManager.default.temporaryDirectory .appendingPathComponent("test-containers-\(UUID().uuidString)") - + let testRuntime = MockContainerRuntime() let system = SystemManager(testRuntime: testRuntime) try await system.start(appRoot: appRoot) - + return (appRoot, testRuntime) } - + // MARK: - List Containers Tests - - @Test("List containers returns array") + + @Test("Empty store lists no containers") @MainActor - func testListContainers() async throws { + func emptyStoreListsNoContainers() async throws { let (_, testRuntime) = try await setupTestSystem() - + let manager = ContainerManager(testRuntime: testRuntime) let containers = try await manager.list() - - #expect(type(of: containers) == [ContainerSnapshot].self) - } - - @Test("List containers is callable") - @MainActor - func testListContainersCallable() async throws { - let (_, testRuntime) = try await setupTestSystem() - - let manager = ContainerManager(testRuntime: testRuntime) - let result = try await manager.list() - - // Verify result is an array - #expect(type(of: result) == [ContainerSnapshot].self) + + #expect(containers.isEmpty) } - + // MARK: - Get Container Tests - - @Test("Get non-existent container throws error") + + @Test("Get missing container throws") @MainActor - func testGetNonExistentContainer() async throws { + func getMissingContainerThrows() async throws { let (_, testRuntime) = try await setupTestSystem() - + let manager = ContainerManager(testRuntime: testRuntime) do { _ = try await manager.get(id: "nonexistent-container-id") diff --git a/ContainerSystemTests/ContainerSystemTests.swift b/ContainerSystemTests/ContainerSystemTests.swift index 3e457e1..15cc86a 100644 --- a/ContainerSystemTests/ContainerSystemTests.swift +++ b/ContainerSystemTests/ContainerSystemTests.swift @@ -5,67 +5,65 @@ // Created by Axel Martinez on 2026/02/08. // -import Testing import Foundation +import Testing @testable import ContainerSystem -@Suite(.serialized) +@Suite("Container system", .serialized) struct ContainerSystemTests { - - @Test("System starts successfully") + + @Test("Start system") @MainActor - func testSystemStart() async throws { + func startSystem() async throws { let testRuntime = MockContainerRuntime() let system = SystemManager(testRuntime: testRuntime) - + let appRoot = FileManager.default.temporaryDirectory .appendingPathComponent("test-containers-\(UUID().uuidString)") - + try await system.start(appRoot: appRoot) - - #expect(system.isRunning == true) - #expect(system.systemStatus == .running) - + + #expect(system.status == .running) + try await system.stop() } - - @Test("System can be started multiple times") + + @Test("Start twice") @MainActor - func testSystemMultipleStarts() async throws { + func startTwice() async throws { let testRuntime = MockContainerRuntime() let system = SystemManager(testRuntime: testRuntime) - + let appRoot = FileManager.default.temporaryDirectory .appendingPathComponent("test-containers-\(UUID().uuidString)") - + try await system.start(appRoot: appRoot) - #expect(system.isRunning == true) - + #expect(system.status == .running) + // Starting again should not cause error try await system.start(appRoot: appRoot) - #expect(system.isRunning == true) - + #expect(system.status == .running) + try await system.stop() } - - @Test("System stops successfully") + + @Test("Stop system") @MainActor - func testSystemStop() async throws { + func stopSystem() async throws { let testRuntime = MockContainerRuntime() let system = SystemManager(testRuntime: testRuntime) - + // Ensure system is started let appRoot = FileManager.default.temporaryDirectory .appendingPathComponent("test-containers-\(UUID().uuidString)") - + try await system.start(appRoot: appRoot) - #expect(system.isRunning == true) - + #expect(system.status == .running) + // Stop the system try await system.stop() - - #expect(system.isRunning == false) - #expect(system.systemStatus == .notStarted) + + #expect(system.status == .notStarted) } } diff --git a/ContainerSystemTests/ContainersServiceTests.swift b/ContainerSystemTests/ContainersServiceTests.swift new file mode 100644 index 0000000..f6b44a2 --- /dev/null +++ b/ContainerSystemTests/ContainersServiceTests.swift @@ -0,0 +1,172 @@ +// +// ContainersServiceTests.swift +// ContainerSystemTests +// +// Created by Axel Martinez on 2026/02/08. +// + +import Containerization +import ContainerizationError +import ContainerizationOCI +import Foundation +import Logging +import Testing + +@testable import ContainerSystem + +@Suite("Containers service") +struct ContainersServiceTests { + private func makeService(in directory: TemporaryDirectory) throws -> ContainersService { + let log = Logger(label: "tests.containers") + let imagesRoot = directory.appending("images") + let contentStore = try LocalContentStore(path: imagesRoot.appendingPathComponent("content")) + let images = try ImagesService( + contentStore: contentStore, + imageStore: try ImageStore(path: imagesRoot, contentStore: contentStore), + snapshotsPath: imagesRoot.appendingPathComponent("snapshots"), + log: log + ) + + return try ContainersService(appRoot: directory.url, imagesService: images, log: log) + } + + /// Writes the files a container's bundle is read back from at launch. + private func writeBundle( + id: String, + labels: [String: String] = [:], + autoRemove: Bool = false, + in directory: TemporaryDirectory + ) throws { + let path = directory.appending("containers/\(id)") + + try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true) + + var configuration = ContainerConfiguration( + id: id, + image: ImageDescription( + reference: "docker.io/library/alpine:latest", + descriptor: Descriptor(mediaType: "", digest: "", size: 0) + ), + process: ProcessConfiguration(executable: "/bin/sh") + ) + configuration.labels = labels + + let bundle = Bundle(path: path) + + try bundle.write(filename: "config.json", value: configuration) + try bundle.write(filename: "options.json", value: ContainerCreateOptions(autoRemove: autoRemove)) + } + + @Test("Empty root lists no containers") + func emptyRootListsNothing() async throws { + let directory = try TemporaryDirectory() + defer { directory.remove() } + + let service = try makeService(in: directory) + + #expect(await service.list().isEmpty) + } + + @Test("Bundles on disk load as stopped") + func loadsBundlesAsStopped() async throws { + let directory = try TemporaryDirectory() + defer { directory.remove() } + + try writeBundle(id: "web", in: directory) + try writeBundle(id: "db", in: directory) + + let containers = try await makeService(in: directory).list() + + #expect(containers.map(\.id) == ["db", "web"]) + #expect(containers.allSatisfy { $0.status == .stopped }) + } + + @Test("Auto-remove bundles are reaped at launch") + func reapsAutoRemoveBundles() async throws { + let directory = try TemporaryDirectory() + defer { directory.remove() } + + try writeBundle(id: "keep", in: directory) + try writeBundle(id: "temporary", autoRemove: true, in: directory) + + let containers = try await makeService(in: directory).list() + + #expect(containers.map(\.id) == ["keep"]) + #expect(!FileManager.default.fileExists(atPath: directory.appending("containers/temporary").path)) + } + + @Test("Unreadable bundle is skipped") + func skipsUnreadableBundle() async throws { + let directory = try TemporaryDirectory() + defer { directory.remove() } + + try writeBundle(id: "web", in: directory) + try directory.write("not a bundle", to: "containers/broken/notes.txt") + + let containers = try await makeService(in: directory).list() + + #expect(containers.map(\.id) == ["web"]) + } + + @Test("List filters by status, label and name") + func filtersList() async throws { + let directory = try TemporaryDirectory() + defer { directory.remove() } + + try writeBundle(id: "web-frontend", labels: ["tier": "web"], in: directory) + try writeBundle(id: "web-backend", labels: ["tier": "api"], in: directory) + try writeBundle(id: "db", labels: ["tier": "data"], in: directory) + + let service = try makeService(in: directory) + + #expect(await service.list(labelFilter: ["tier": "api"]).map(\.id) == ["web-backend"]) + #expect(await service.list(namePattern: "WEB").map(\.id) == ["web-backend", "web-frontend"]) + #expect(await service.list(status: .running).isEmpty) + #expect(await service.list(status: .stopped).count == 3) + } + + @Test("Delete removes the bundle") + func deleteRemovesBundle() async throws { + let directory = try TemporaryDirectory() + defer { directory.remove() } + + try writeBundle(id: "web", in: directory) + + let service = try makeService(in: directory) + + try await service.delete(id: "web") + + #expect(await service.list().isEmpty) + #expect(!FileManager.default.fileExists(atPath: directory.appending("containers/web").path)) + } + + @Test("Unknown container throws not found") + func unknownContainerThrows() async throws { + let directory = try TemporaryDirectory() + defer { directory.remove() } + + let service = try makeService(in: directory) + + await #expect(throws: ContainerizationError.self) { + try await service.delete(id: "missing") + } + await #expect(throws: ContainerizationError.self) { + try await service.stop(id: "missing", options: ContainerStopOptions()) + } + } + + @Test("Stopped container can't exec") + func stoppedContainerCannotExec() async throws { + let directory = try TemporaryDirectory() + defer { directory.remove() } + + try writeBundle(id: "web", in: directory) + + let service = try makeService(in: directory) + + await #expect(throws: ContainerizationError.self) { + _ = try await service.exec(id: "web", arguments: ["true"]) + } + #expect(await service.resourceUsage().isEmpty) + } +} diff --git a/ContainerSystemTests/EntityNameTests.swift b/ContainerSystemTests/EntityNameTests.swift new file mode 100644 index 0000000..b5122ca --- /dev/null +++ b/ContainerSystemTests/EntityNameTests.swift @@ -0,0 +1,90 @@ +// +// EntityNameTests.swift +// ContainerSystemTests +// +// The names a container or volume is allowed to carry. +// + +import Foundation +import Testing + +@testable import ContainerSystem + +@Suite("Entity name") +struct EntityNameTests { + + @Test( + "Valid names are accepted", + arguments: ["web", "my-app", "db_1", "a.b-c_d", "A", "9lives"] + ) + func acceptsValidNames(_ name: String) { + #expect(EntityName.isValid(name)) + } + + @Test( + "Bad first character is rejected", + arguments: ["", "-web", "_web", ".web", "/web", " web"] + ) + func rejectsBadStarts(_ name: String) { + #expect(!EntityName.isValid(name)) + } + + @Test( + "Disallowed characters are rejected", + arguments: ["my app", "web/1", "web:latest", "wéb", "web!", "a\nb"] + ) + func rejectsBadCharacters(_ name: String) { + #expect(!EntityName.isValid(name)) + } + + @Test("Length limit") + func enforcesLength() { + let atLimit = String(repeating: "a", count: EntityName.maximumLength) + let overLimit = String( + repeating: "a", + count: EntityName.maximumLength + 1 + ) + + #expect(EntityName.isValid(atLimit)) + #expect(!EntityName.isValid(overLimit)) + } + + @Test( + "Sanitize removes disallowed characters", + arguments: [ + ("my app", "myapp"), + ("--web", "web"), + ("__db.1", "db.1"), + ("web:latest", "weblatest"), + ("...9lives", "9lives"), + ] + ) + func sanitizes(_ input: String, _ expected: String) { + #expect(EntityName.valid(from: input) == expected) + } + + @Test("Sanitize truncates long names") + func sanitizeTruncates() { + let sanitized = EntityName.valid( + from: String(repeating: "a", count: EntityName.maximumLength + 50) + ) + + #expect(sanitized.count == EntityName.maximumLength) + #expect(EntityName.isValid(sanitized)) + } + + @Test( + "Sanitize returns a valid name or nil", + arguments: [ + "my app", "--web", "web:latest", "...", "!!!", "", "café", + "9lives", "___", + ] + ) + func sanitizeYieldsUsableName(_ input: String) { + let sanitized = EntityName.valid(from: input) + + // The form's fallback relies on this: anything non-empty that comes + // back out can be submitted as-is. + #expect(sanitized.isEmpty || EntityName.isValid(sanitized)) + } +} diff --git a/ContainerSystemTests/FileIOTests.swift b/ContainerSystemTests/FileIOTests.swift new file mode 100644 index 0000000..f368184 --- /dev/null +++ b/ContainerSystemTests/FileIOTests.swift @@ -0,0 +1,114 @@ +// +// FileIOTests.swift +// ContainerSystemTests +// +// The blocking filesystem work the managers hand off. +// + +import Foundation +import Testing + +@testable import ContainerSystem + +@Suite("File IO") +struct FileIOTests { + + @Test("Archive round trip") + func archiveRoundTrip() async throws { + let source = try TemporaryDirectory("archive-source") + let destination = try TemporaryDirectory("archive-destination") + defer { + source.remove() + destination.remove() + } + + try source.write("index", to: "index.json") + try source.write("layer bytes", to: "blobs/sha256/abc123") + try source.write("nested", to: "blobs/sha256/deep/def456") + + let tar = destination.appending("layout.tar") + + try await FileIO.shared.writeArchive( + directory: source.url, + to: tar + ) + + let unpacked = destination.appending("unpacked") + try FileManager.default.createDirectory( + at: unpacked, + withIntermediateDirectories: true + ) + + try await FileIO.shared.extractArchive(at: tar, to: unpacked) + + // Every file comes back at the same relative path, byte for byte. + for path in ["index.json", "blobs/sha256/abc123", "blobs/sha256/deep/def456"] { + let original = try Data(contentsOf: source.appending(path)) + let extracted = try Data(contentsOf: unpacked.appendingPathComponent(path)) + + #expect(original == extracted, "\(path) did not survive the round trip") + } + } + + @Test("Copy keeps source") + func copyKeepsSource() async throws { + let directory = try TemporaryDirectory("copy") + defer { directory.remove() } + + let source = try directory.write("dockerfile body", to: "context/Dockerfile") + let destination = directory.appending("copy-of-context") + + try await FileIO.shared.copyItem( + at: directory.appending("context"), + to: destination + ) + + #expect(FileManager.default.fileExists(atPath: source.path)) + #expect( + try Data(contentsOf: destination.appendingPathComponent("Dockerfile")) + == Data("dockerfile body".utf8) + ) + } + + @Test("Move removes source") + func moveRemovesSource() async throws { + let directory = try TemporaryDirectory("move") + defer { directory.remove() } + + let source = try directory.write("export", to: "out.tar") + let destination = directory.appending("saved.tar") + + try await FileIO.shared.moveItem(at: source, to: destination) + + #expect(!FileManager.default.fileExists(atPath: source.path)) + #expect(try Data(contentsOf: destination) == Data("export".utf8)) + } + + @Test("Copy onto existing file fails") + func copyOntoExistingFails() async throws { + let directory = try TemporaryDirectory("copy-clash") + defer { directory.remove() } + + let source = try directory.write("first", to: "a.txt") + let destination = try directory.write("second", to: "b.txt") + + await #expect(throws: (any Error).self) { + try await FileIO.shared.copyItem(at: source, to: destination) + } + + // The destination is left as it was, not half-written. + #expect(try Data(contentsOf: destination) == Data("second".utf8)) + } + + @Test("Read missing file fails") + func readMissingFails() async throws { + let directory = try TemporaryDirectory("read-missing") + defer { directory.remove() } + + await #expect(throws: (any Error).self) { + try await FileIO.shared.contents( + of: directory.appending("absent.txt") + ) + } + } +} diff --git a/ContainerSystemTests/GzipTests.swift b/ContainerSystemTests/GzipTests.swift new file mode 100644 index 0000000..e00fe18 --- /dev/null +++ b/ContainerSystemTests/GzipTests.swift @@ -0,0 +1,32 @@ +// +// GzipTests.swift +// ContainerSystemTests +// + +import Foundation +import Testing + +@testable import ContainerSystem + +@Suite("Gzip") +struct GzipTests { + @Test("Round trip") + func roundTrip() throws { + let text = "Step 1/3 : FROM alpine\nété ✓\n" + let data = try #require(Gzip.compressed(text)) + + #expect(Gzip.text(of: data) == text) + } + + @Test("Empty round trip") + func emptyRoundTrip() throws { + let data = try #require(Gzip.compressed("")) + + #expect(Gzip.text(of: data) == "") + } + + @Test("Plain text is rejected") + func plainTextIsRejected() { + #expect(Gzip.text(of: Data("plain text that was never compressed".utf8)) == nil) + } +} diff --git a/ContainerSystemTests/ImageManagerTests.swift b/ContainerSystemTests/ImageManagerTests.swift index 627a0d8..92d4c31 100644 --- a/ContainerSystemTests/ImageManagerTests.swift +++ b/ContainerSystemTests/ImageManagerTests.swift @@ -5,102 +5,134 @@ // Created by Axel Martinez on 2026/02/08. // -import Testing -import Foundation -import ContainerResource +import Containerization import ContainerizationOCI +import Foundation +import Testing @testable import ContainerSystem +@Suite("Image manager") struct ImageManagerTests { - + // MARK: - Setup Helper - + @MainActor private func setupTestSystem() async throws -> (URL, ContainerRuntime) { let appRoot = FileManager.default.temporaryDirectory .appendingPathComponent("test-containers-\(UUID().uuidString)") - + let testRuntime = MockContainerRuntime() let system = SystemManager(testRuntime: testRuntime) try await system.start(appRoot: appRoot) - + return (appRoot, testRuntime) } - + // MARK: - List Images Tests - - @Test("List images returns array") + + @Test("Empty store lists no images") @MainActor - func testListImages() async throws { + func emptyStoreListsNoImages() async throws { let (_, testRuntime) = try await setupTestSystem() - + let manager = ImageManager(testRuntime: testRuntime) let images = try await manager.list() - - #expect(type(of: images) == [ImageDescription].self) + + #expect(images.isEmpty) } - - @Test("List images filters infrastructure images") + + @Test("List fails after stop") @MainActor - func testListImagesFiltersInfra() async throws { + func listFailsAfterStop() async throws { let (_, testRuntime) = try await setupTestSystem() - + + let manager = ImageManager(testRuntime: testRuntime) + try await testRuntime.stop() + + await #expect(throws: (any Error).self) { + _ = try await manager.list() + } + } + + @Test("List hides infrastructure images") + @MainActor + func listHidesInfrastructureImages() async throws { + let (_, testRuntime) = try await setupTestSystem() + let manager = ImageManager(testRuntime: testRuntime) let images = try await manager.list() - + // Verify no infra images let hasInfraImages = images.contains { image in - image.reference.hasPrefix("infra:") + image.description.reference.hasPrefix("infra:") } #expect(hasInfraImages == false) } - + // MARK: - Save Images Tests - - @Test("Save images to valid directory") + + @Test("Save to directory") @MainActor - func testSaveImagesToDirectory() async throws { + func saveToDirectory() async throws { let (_, testRuntime) = try await setupTestSystem() - + let tempDir = FileManager.default.temporaryDirectory .appendingPathComponent("ImageManagerTests") .appendingPathComponent(UUID().uuidString) - - try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) - + + try FileManager.default.createDirectory( + at: tempDir, + withIntermediateDirectories: true + ) + let manager = ImageManager(testRuntime: testRuntime) - try await manager.save(images: [], platform: .current, outputDirectory: tempDir) - + try await manager.save( + images: [], + platform: .current, + outputURL: tempDir.appendingPathComponent("images.tar") + ) + // Cleanup - try? FileManager.default.removeItem(at: tempDir.deletingLastPathComponent()) + try? FileManager.default.removeItem( + at: tempDir.deletingLastPathComponent() + ) } - - @Test("Save images with empty list succeeds") + + @Test("Save empty list") @MainActor - func testSaveEmptyImageList() async throws { + func saveEmptyList() async throws { let (_, testRuntime) = try await setupTestSystem() - + let tempDir = FileManager.default.temporaryDirectory .appendingPathComponent("ImageManagerTests") .appendingPathComponent(UUID().uuidString) - - try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) - + + try FileManager.default.createDirectory( + at: tempDir, + withIntermediateDirectories: true + ) + let manager = ImageManager(testRuntime: testRuntime) - try await manager.save(images: [], platform: .current, outputDirectory: tempDir) - + try await manager.save( + images: [], + platform: .current, + outputURL: tempDir.appendingPathComponent("images.tar") + ) + // Cleanup - try? FileManager.default.removeItem(at: tempDir.deletingLastPathComponent()) + try? FileManager.default.removeItem( + at: tempDir.deletingLastPathComponent() + ) } - + // MARK: - Delete Images Tests - - @Test("Delete images with empty list succeeds") + + @Test("Delete empty list") @MainActor - func testDeleteEmptyImageList() async throws { + func deleteEmptyList() async throws { let (_, testRuntime) = try await setupTestSystem() - + let manager = ImageManager(testRuntime: testRuntime) try await manager.delete(images: []) } diff --git a/ContainerSystemTests/KernelServiceTests.swift b/ContainerSystemTests/KernelServiceTests.swift new file mode 100644 index 0000000..3dddad0 --- /dev/null +++ b/ContainerSystemTests/KernelServiceTests.swift @@ -0,0 +1,209 @@ +// +// KernelServiceTests.swift +// ContainerSystemTests +// +// Installing a kernel out of the archive the app downloads. +// + +import Containerization +import ContainerizationArchive +import Foundation +import Logging +import Testing + +@testable import ContainerSystem + +@Suite("Kernel service") +struct KernelServiceTests { + + private func makeService(in directory: TemporaryDirectory) throws + -> KernelService + { + try KernelService( + log: Logger(label: "tests.kernel"), + appRoot: directory.url + ) + } + + /// Writes a tar holding `files`, plus `symlinks` as real symlink entries. + private func makeArchive( + at url: URL, + files: [String: String], + symlinks: [String: String] = [:] + ) throws { + let writer = try ArchiveWriter(format: .pax, filter: .none, file: url) + + for (path, contents) in files.sorted(by: { $0.key < $1.key }) { + let data = Data(contents.utf8) + let entry = WriteEntry() + + entry.path = path + entry.fileType = .regular + entry.permissions = 0o644 + entry.size = Int64(data.count) + + try writer.writeEntry(entry: entry, data: data) + } + + for (path, target) in symlinks.sorted(by: { $0.key < $1.key }) { + let entry = WriteEntry() + + entry.path = path + entry.fileType = .symbolicLink + entry.symlinkTarget = target + entry.permissions = 0o777 + entry.size = 0 + + try writer.writeEntry(entry: entry, data: Data()) + } + + try writer.finishEncoding() + } + + private func installedKernel( + from service: KernelService + ) async throws -> Data { + let kernel = try await service.getDefaultKernel(platform: .current) + + return try Data(contentsOf: kernel.path) + } + + @Test("Install named kernel") + func installsNamedKernel() async throws { + let directory = try TemporaryDirectory("kernel-install") + defer { directory.remove() } + + let tar = directory.appending("kernel.tar") + try makeArchive( + at: tar, + files: ["boot/vmlinux": "real kernel", "boot/README": "ignore me"] + ) + + let service = try makeService(in: directory) + try await service.installKernelFrom( + tar: tar, + kernelFilePath: "boot/vmlinux", + platform: .current + ) + + #expect(try await installedKernel(from: service) == Data("real kernel".utf8)) + } + + @Test("Install follows symlink") + func followsSymlink() async throws { + let directory = try TemporaryDirectory("kernel-symlink") + defer { directory.remove() } + + // What the Apple kernel archives actually ship: a stable name that + // points at the versioned binary sitting beside it. + let tar = directory.appending("kernel.tar") + try makeArchive( + at: tar, + files: ["boot/vmlinux-6.12": "versioned kernel"], + symlinks: ["boot/vmlinux": "vmlinux-6.12"] + ) + + let service = try makeService(in: directory) + try await service.installKernelFrom( + tar: tar, + kernelFilePath: "boot/vmlinux", + platform: .current + ) + + // The link's own (empty) payload must not be what lands on disk. + #expect( + try await installedKernel(from: service) + == Data("versioned kernel".utf8) + ) + } + + @Test("Keep existing kernel") + func keepsExistingKernel() async throws { + let directory = try TemporaryDirectory("kernel-keep") + defer { directory.remove() } + + let service = try makeService(in: directory) + + let first = directory.appending("first.tar") + try makeArchive(at: first, files: ["vmlinux": "first kernel"]) + try await service.installKernelFrom( + tar: first, + kernelFilePath: "vmlinux", + platform: .current + ) + + let second = directory.appending("second.tar") + try makeArchive(at: second, files: ["vmlinux": "second kernel"]) + try await service.installKernelFrom( + tar: second, + kernelFilePath: "vmlinux", + platform: .current, + force: false + ) + + #expect(try await installedKernel(from: service) == Data("first kernel".utf8)) + } + + @Test("Force replaces kernel") + func forceReplacesKernel() async throws { + let directory = try TemporaryDirectory("kernel-force") + defer { directory.remove() } + + let service = try makeService(in: directory) + + let first = directory.appending("first.tar") + try makeArchive(at: first, files: ["vmlinux": "first kernel"]) + try await service.installKernelFrom( + tar: first, + kernelFilePath: "vmlinux", + platform: .current + ) + + let second = directory.appending("second.tar") + try makeArchive(at: second, files: ["vmlinux": "second kernel"]) + try await service.installKernelFrom( + tar: second, + kernelFilePath: "vmlinux", + platform: .current, + force: true + ) + + #expect(try await installedKernel(from: service) == Data("second kernel".utf8)) + } + + @Test("Missing kernel fails") + func missingKernelFails() async throws { + let directory = try TemporaryDirectory("kernel-missing") + defer { directory.remove() } + + let service = try makeService(in: directory) + + await #expect(throws: (any Error).self) { + _ = try await service.getDefaultKernel(platform: .current) + } + } + + @Test("Missing archive member fails") + func missingArchiveMemberFails() async throws { + let directory = try TemporaryDirectory("kernel-bad-path") + defer { directory.remove() } + + let tar = directory.appending("kernel.tar") + try makeArchive(at: tar, files: ["boot/vmlinux": "real kernel"]) + + let service = try makeService(in: directory) + + await #expect(throws: (any Error).self) { + try await service.installKernelFrom( + tar: tar, + kernelFilePath: "boot/does-not-exist", + platform: .current + ) + } + + // A failed install must not leave a half-written kernel behind. + await #expect(throws: (any Error).self) { + _ = try await service.getDefaultKernel(platform: .current) + } + } +} diff --git a/ContainerSystemTests/Mocks/MockContainerRuntime.swift b/ContainerSystemTests/Mocks/MockContainerRuntime.swift index 56cb07c..ddac28b 100644 --- a/ContainerSystemTests/Mocks/MockContainerRuntime.swift +++ b/ContainerSystemTests/Mocks/MockContainerRuntime.swift @@ -2,117 +2,163 @@ // MockContainerRuntime.swift // ContainerSystemTests // -// Mock runtime for isolated testing without real container operations +// Mock runtime for isolated testing without real container operations. // -import Foundation -import ContainerAPIService -import ContainerImagesService -import ContainerResource -import ContainerizationOCI -import ContainerizationOS import Containerization +import ContainerizationError +import ContainerizationOCI +import Foundation +import Logging @testable import ContainerSystem -/// Mock runtime that provides stub services for testing +/// Mock runtime that provides isolated services for testing. +/// +/// Creates real but lightweight service instances backed by temporary +/// directories. All stores (ContentStore, ImageStore) are filesystem-only +/// and safe to use in a test host without special entitlements. +/// +/// The services live here rather than in the superclass's own storage, which +/// is private; the runtime's accessors are the seam, so they are overridden +/// to hand back these instances. @MainActor final class MockContainerRuntime: ContainerRuntime { - - // Mock service instances - we'll create these with proper initializers - private var mockContainersService: SandboxedContainersService? + + private var mockContainersService: ContainersService? private var mockImagesService: ImagesService? private var mockKernelService: KernelService? - private let tempAppRoot: URL - + private var mockContentStore: ContentStore? + init() { - // Create a unique temp directory for this mock runtime - self.tempAppRoot = FileManager.default.temporaryDirectory - .appendingPathComponent("mock-runtime-\(UUID().uuidString)") super.init(forTesting: true) } - - // Override start to set up minimal real services that won't do actual work + + // MARK: - Service Accessors + + override func getContainersService() async throws -> ContainersService { + guard let service = mockContainersService else { + throw ContainerizationError( + .internalError, + message: "Containers service not initialized" + ) + } + + return service + } + + override func getImagesService() async throws -> ImagesService { + guard let service = mockImagesService else { + throw ContainerizationError( + .internalError, + message: "Images service not initialized" + ) + } + + return service + } + + override func getKernelService() async throws -> KernelService { + guard let service = mockKernelService else { + throw ContainerizationError( + .internalError, + message: "Kernel service not initialized" + ) + } + + return service + } + + override func getContentStore() throws -> ContentStore { + guard let store = mockContentStore else { + throw ContainerizationError( + .internalError, + message: "Content store not initialized" + ) + } + + return store + } + + // MARK: - Lifecycle + + // Override start to set up isolated services in a temp directory override func start(appRoot: URL) async throws { guard !isRunning && !isStarting else { return } - + isStarting = true defer { isStarting = false } - - // Create minimal directory structure - try FileManager.default.createDirectory(at: appRoot, withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: appRoot.appendingPathComponent("images"), withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: appRoot.appendingPathComponent("images/content"), withIntermediateDirectories: true) - - // Initialize real but isolated services + + // Create directory structure + let fm = FileManager.default + try fm.createDirectory(at: appRoot, withIntermediateDirectories: true) + let imagesRoot = appRoot.appendingPathComponent("images") - let imageStore = try ImageStore(path: imagesRoot) - let snapshotStore = try SnapshotStore(path: imagesRoot, unpackStrategy: SnapshotStore.defaultUnpackStrategy, log: ContainerRuntime.logger) - let contentStore = try LocalContentStore(path: imagesRoot.appendingPathComponent("content")) - - mockImagesService = try ImagesService( - contentStore: contentStore, + try fm.createDirectory( + at: imagesRoot, + withIntermediateDirectories: true + ) + + // Set appRoot so getAppRoot() works + self.appRoot = appRoot + + // Create stores — these are filesystem-only and safe in test hosts + let localContentStore = try LocalContentStore( + path: imagesRoot.appendingPathComponent("content") + ) + let imageStore = try ImageStore( + path: imagesRoot, + contentStore: localContentStore + ) + let snapshotsPath = imagesRoot.appendingPathComponent("snapshots") + + let images = try ImagesService( + contentStore: localContentStore, imageStore: imageStore, - snapshotStore: snapshotStore, - log: ContainerRuntime.logger + snapshotsPath: snapshotsPath, + log: logger ) - - mockContainersService = try SandboxedContainersService( + self.mockImagesService = images + self.mockContentStore = localContentStore + + // ContainersService — reads existing containers from disk (empty in tests) + self.mockContainersService = try ContainersService( appRoot: appRoot, - imagesService: mockImagesService!, - log: ContainerRuntime.logger + imagesService: images, + log: logger + ) + + // KernelService — just creates a directory + self.mockKernelService = try KernelService( + log: logger, + appRoot: appRoot ) - - mockKernelService = try KernelService(log: ContainerRuntime.logger, appRoot: appRoot) - - servicesInitialized = true + isRunning = true startupError = nil } - - // Override stop to clean up mock services + + // Override stop to clean up override func stop() async throws { guard isRunning && !isStopping else { return } - + isStopping = true defer { isStopping = false } - + mockContainersService = nil mockImagesService = nil mockKernelService = nil - servicesInitialized = false + mockContentStore = nil isRunning = false - + // Clean up temp directory - try? FileManager.default.removeItem(at: tempAppRoot) - } - - // Override service getters to return our isolated mock services - override func getContainersService() async throws -> SandboxedContainersService { - guard let service = mockContainersService else { - throw NSError(domain: "MockRuntime", code: 1, userInfo: [NSLocalizedDescriptionKey: "Mock service not initialized"]) - } - return service - } - - override func getImagesService() async throws -> ImagesService { - guard let service = mockImagesService else { - throw NSError(domain: "MockRuntime", code: 1, userInfo: [NSLocalizedDescriptionKey: "Mock service not initialized"]) - } - return service - } - - override func getKernelService() async throws -> KernelService { - guard let service = mockKernelService else { - throw NSError(domain: "MockRuntime", code: 1, userInfo: [NSLocalizedDescriptionKey: "Mock service not initialized"]) + if let root = appRoot { + try? FileManager.default.removeItem(at: root) + self.appRoot = nil } - return service } } - - - diff --git a/ContainerSystemTests/NetworkManagerTests.swift b/ContainerSystemTests/NetworkManagerTests.swift new file mode 100644 index 0000000..d73f1c1 --- /dev/null +++ b/ContainerSystemTests/NetworkManagerTests.swift @@ -0,0 +1,125 @@ +// +// NetworkManagerTests.swift +// ContainerSystemTests +// +// The DNS domains read out of the resolver files the CLI writes. +// + +import Foundation +import Testing + +@testable import ContainerSystem + +@Suite("Network manager") +@MainActor +struct NetworkManagerTests { + + /// A resolver directory of its own, since the real one cannot be written + /// to without being root. + private func resolverDirectory( + _ files: [String: String] + ) throws -> URL { + let directory = URL.temporaryDirectory + .appendingPathComponent("resolver-\(UUID().uuidString)") + + try FileManager.default.createDirectory( + at: directory, + withIntermediateDirectories: true + ) + + for (name, contents) in files { + try contents.write( + to: directory.appendingPathComponent(name), + atomically: true, + encoding: .utf8 + ) + } + + return directory + } + + /// What `container system dns create test` leaves behind. + private let cliResolver = """ + domain test + search test + nameserver 127.0.0.1 + port 2053 + + """ + + @Test("Domain is read from contents") + func readsDomainFromContents() throws { + let directory = try resolverDirectory([ + // The file is for `test`, whatever its own name says. + "containerization.renamed": cliResolver + ]) + + let manager = NetworkManager() + + #expect(manager.listDomains(in: directory) == ["test"]) + } + + @Test("Other resolvers are ignored") + func ignoresForeignResolvers() throws { + let directory = try resolverDirectory([ + "containerization.test": cliResolver, + "example.com": "domain example.com\nnameserver 8.8.8.8\n", + ]) + + let manager = NetworkManager() + + #expect(manager.listDomains(in: directory) == ["test"]) + } + + /// The CLI passes over a file it cannot read a domain out of, so a file + /// written by hand without that line is not a domain either. + @Test("Resolver without domain is skipped") + func skipsResolverWithoutDomain() throws { + let directory = try resolverDirectory([ + "containerization.test": "nameserver 127.0.0.1\nport 2053\n" + ]) + + let manager = NetworkManager() + + #expect(manager.listDomains(in: directory).isEmpty) + } + + @Test("Domains are sorted") + func sortsDomains() throws { + let directory = try resolverDirectory([ + "containerization.zulu": "domain zulu\n", + "containerization.alpha": "domain alpha\n", + "containerization.mike": "domain mike\n", + ]) + + let manager = NetworkManager() + + #expect(manager.listDomains(in: directory) == ["alpha", "mike", "zulu"]) + } + + @Test("Localhost resolver is read") + func readsLocalhostResolver() throws { + // What `--localhost` adds: a redirected address, and 1053 for a port. + let directory = try resolverDirectory([ + "containerization.local": """ + domain local + search local + nameserver 127.0.0.1 + port 1053 + options localhost:192.168.64.1 + """ + ]) + + let manager = NetworkManager() + + #expect(manager.listDomains(in: directory) == ["local"]) + } + + @Test("Missing directory yields no domains") + func toleratesMissingDirectory() { + let absent = URL.temporaryDirectory + .appendingPathComponent("absent-\(UUID().uuidString)") + + #expect(NetworkManager().listDomains(in: absent).isEmpty) + } +} diff --git a/ContainerSystemTests/ProgressStepsTests.swift b/ContainerSystemTests/ProgressStepsTests.swift new file mode 100644 index 0000000..b75bf51 --- /dev/null +++ b/ContainerSystemTests/ProgressStepsTests.swift @@ -0,0 +1,222 @@ +// +// ProgressStepsTests.swift +// ContainerSystemTests +// +// How an operation counts its steps into a Progress. +// + +import ContainerizationExtras +import Foundation +import Testing + +@testable import ContainerSystem + +@Suite("Progress steps") +@MainActor +struct ProgressStepsTests { + + @Test("Step description shows on parent") + func showsStepDescription() async throws { + let progress = Progress(totalUnitCount: 2) + + try await progress.performStep("Fetching image") { _ in + #expect(progress.localizedDescription == "Fetching image") + } + + try await progress.performStep("Unpacking image") { _ in + #expect(progress.localizedDescription == "Unpacking image") + } + } + + @Test("Deepest step describes the operation") + func deepestStepWins() async throws { + let progress = Progress(totalUnitCount: 1) + + try await progress.performStep("Starting builder") { builder in + builder.totalUnitCount = 1 + + try await builder.performStep("Fetching builder image") { step in + await step.updateHandler()([.addTotalItems(4), .addItems(1)]) + + #expect(progress.localizedDescription == "Fetching builder image") + #expect(progress.localizedAdditionalDescription == "1 of 4") + } + } + } + + @Test("Steps share the total") + func stepsShareTheOperation() async throws { + let progress = Progress(totalUnitCount: 2) + + try await progress.performStep("Fetching image") { step in + await step.updateHandler()([.addTotalItems(4), .addItems(2)]) + + #expect(progress.fractionCompleted == 0.25) + } + + #expect(progress.fractionCompleted == 0.5) + } + + @Test("Unmeasured step completes") + func unmeasuredStepCompletes() async throws { + let progress = Progress(totalUnitCount: 2) + + try await progress.performStep("Creating container") { step in + #expect(step.isIndeterminate) + } + + #expect(progress.fractionCompleted == 0.5) + } + + @Test("Failed step doesn't complete") + func failedStepDoesNotComplete() async { + struct Failure: Error {} + + let progress = Progress(totalUnitCount: 2) + + await #expect(throws: Failure.self) { + try await progress.performStep("Fetching image") { _ in + throw Failure() + } + } + + #expect(progress.fractionCompleted == 0) + } + + @Test("Finished step stops mirroring") + func finishedStepStopsMirroring() async throws { + let progress = Progress(totalUnitCount: 2) + var finished: Progress? + + try await progress.performStep("Fetching image") { step in + finished = step + } + + finished?.localizedDescription = "Stale" + + #expect(progress.localizedDescription == "Fetching image") + // Completing an unmeasured step does not say "1 of 1" here. + #expect(progress.localizedAdditionalDescription == "") + } + + @Test("Late reports are dropped") + func lateReportsAreDropped() async throws { + let progress = Progress(totalUnitCount: 2) + var update: ProgressHandler? + + try await progress.performStep("Fetching image") { step in + update = step.updateHandler() + await update?([.addTotalItems(4), .addItems(4)]) + } + + #expect(progress.fractionCompleted == 0.5) + + await update?([.addTotalItems(4), .addItems(1)]) + + #expect(progress.fractionCompleted == 0.5) + #expect(progress.completedUnitCount == 1) + } + + @Test("Bytes take precedence over items") + func bytesOverItems() async { + let progress = Progress(totalUnitCount: 0) + let update = progress.updateHandler() + + await update([.addTotalItems(10), .addItems(5)]) + + #expect(progress.fractionCompleted == 0.5) + + await update([.addTotalSize(10_000_000), .addSize(1_000_000)]) + + #expect(progress.kind == .file) + #expect(progress.totalUnitCount == 10_000_000) + #expect(progress.fractionCompleted == 0.55) + } + + @Test("Staged totals never move progress back") + func stagedTotalsStayMonotonic() async throws { + let progress = Progress(totalUnitCount: 1) + var fractions: [Double] = [] + + try await progress.performStep("Fetching image") { step in + let update = step.updateHandler() + // How an image pull reports: the index, then a manifest per platform, then the configs and layers. + let batches: [[ProgressEvent]] = [ + [.addTotalSize(10_000), .addTotalItems(1)], + [.addSize(10_000), .addItems(1)], + [.addTotalSize(30_000), .addTotalItems(3)], + [.addSize(10_000), .addItems(1)], + [.addSize(10_000), .addItems(1)], + [.addSize(10_000), .addItems(1)], + [.addTotalSize(4_000_000), .addTotalItems(2)], + [.addSize(1_000_000)], + [.addSize(2_000_000)], + [.addSize(1_000_000), .addItems(2)], + ] + + for batch in batches { + await update(batch) + fractions.append(progress.fractionCompleted) + } + } + + #expect(fractions == fractions.sorted()) + #expect(fractions[0...6].allSatisfy { $0 == 0 }) + #expect(fractions[8] == 0.75) + #expect(progress.fractionCompleted == 1) + } + + @Test("Counts without a total stay indeterminate") + func countsWithoutTotal() async { + let progress = Progress(totalUnitCount: 0) + + await progress.updateHandler()([.addItems(3)]) + + #expect(progress.isIndeterminate) + } + + @Test("Handler accumulates counts") + func handlerAccumulates() async { + let progress = Progress(totalUnitCount: 0) + let update = progress.updateHandler() + + await update([.addTotalItems(4), .addItems(1)]) + await update([.addItems(1)]) + + #expect(progress.totalUnitCount == 4) + #expect(progress.completedUnitCount == 2) + } + + @Test("Overshoot is capped") + func overshootIsCapped() async throws { + let progress = Progress(totalUnitCount: 1) + + try await progress.performStep("Fetching image") { step in + await step.updateHandler()([.addTotalItems(2), .addItems(5)]) + + #expect(progress.fractionCompleted < 1) + } + + #expect(progress.fractionCompleted == 1) + } + + @Test("Growing total counts once") + func totalGrowingAfterCatchingUp() async throws { + let progress = Progress(totalUnitCount: 2) + + try await progress.performStep("Fetching image") { step in + let update = step.updateHandler() + + await update([.addTotalItems(2), .addItems(2)]) + await update([.addTotalItems(2), .addItems(2)]) + } + + #expect(progress.fractionCompleted == 0.5) + + try await progress.performStep("Unpacking image") { _ in + #expect(progress.fractionCompleted == 0.5) + } + + #expect(progress.fractionCompleted == 1) + } +} diff --git a/ContainerSystemTests/PublishPortTests.swift b/ContainerSystemTests/PublishPortTests.swift new file mode 100644 index 0000000..bc642c9 --- /dev/null +++ b/ContainerSystemTests/PublishPortTests.swift @@ -0,0 +1,104 @@ +// +// PublishPortTests.swift +// ContainerSystemTests +// +// Clashes between the ports a container publishes. +// + +import ContainerizationExtras +import Foundation +import Testing + +@testable import ContainerSystem + +@Suite("Published ports") +struct PublishPortTests { + + private func port( + host: UInt16, + container: UInt16 = 80, + proto: PublishProtocol = .tcp, + count: UInt16 = 1 + ) -> PublishPort { + PublishPort( + hostPort: host, + containerPort: container, + proto: proto, + count: count + ) + } + + @Test("Distinct ports don't overlap") + func distinctPortsDoNotOverlap() { + #expect(!([port(host: 8080), port(host: 8081)]).hasOverlaps()) + } + + @Test("Duplicate port overlaps") + func duplicatePortOverlaps() { + // Different container ports still fight over the one host port. + #expect( + ([ + port(host: 8080, container: 80), + port(host: 8080, container: 443), + ]) + .hasOverlaps() + ) + } + + @Test("Range covers port") + func rangeCoversPort() { + #expect(([port(host: 8080, count: 5), port(host: 8082)]).hasOverlaps()) + } + + @Test("Adjacent ranges don't overlap") + func adjacentRangesDoNotOverlap() { + // 8080-8082 then 8083-8084. + #expect( + !([port(host: 8080, count: 3), port(host: 8083, count: 2)]) + .hasOverlaps() + ) + } + + @Test("Overlapping ranges overlap") + func overlappingRangesOverlap() { + #expect( + ([port(host: 8080, count: 4), port(host: 8082, count: 3)]) + .hasOverlaps() + ) + } + + @Test("Protocols are separate") + func protocolsAreSeparate() { + #expect( + !([port(host: 8080, proto: .tcp), port(host: 8080, proto: .udp)]) + .hasOverlaps() + ) + } + + @Test("Empty list doesn't overlap") + func emptyDoesNotOverlap() { + #expect(!([PublishPort]()).hasOverlaps()) + } + + @Test("Range past last port doesn't overflow") + func rangeOverflowingPortRange() { + // A count that carries 65535 past the end of the range: tallied in + // UInt16 that traps instead of reporting anything. + #expect(!([port(host: 65535, count: 2)]).hasOverlaps()) + #expect( + ([port(host: 65535, count: 2), port(host: 65535)]).hasOverlaps() + ) + } + + @Test( + "Protocol parses, defaulting to TCP", + arguments: [ + ("udp", PublishProtocol.udp), ("UDP", .udp), + ("tcp", .tcp), ("sctp", .tcp), ("", .tcp), + ] + ) + + func parsesProtocol(_ value: String, _ expected: PublishProtocol) { + #expect(PublishProtocol(value) == expected) + } +} diff --git a/ContainerSystemTests/ReferenceNormalizedTests.swift b/ContainerSystemTests/ReferenceNormalizedTests.swift new file mode 100644 index 0000000..0fa1885 --- /dev/null +++ b/ContainerSystemTests/ReferenceNormalizedTests.swift @@ -0,0 +1,48 @@ +// +// ReferenceNormalizedTests.swift +// ContainerSystemTests +// +// What a short image name is filled in to. +// + +import ContainerizationOCI +import Testing + +@testable import ContainerSystem + +@Suite("Normalized references") +struct ReferenceNormalizedTests { + + @Test( + "Short names expand to Docker Hub", + arguments: [ + ("nginx", "docker.io/library/nginx:latest"), + ("nginx:1.27", "docker.io/library/nginx:1.27"), + ("bitnami/redis", "docker.io/bitnami/redis:latest"), + ("docker.io/nginx", "docker.io/library/nginx:latest"), + (" alpine ", "docker.io/library/alpine:latest"), + ] + ) + func dockerHub(reference: String, expected: String) throws { + #expect(try Reference.normalized(reference).description == expected) + } + + @Test( + "Explicit registry is kept", + arguments: [ + ("ghcr.io/apple/containerization/vminit:0.1", "ghcr.io/apple/containerization/vminit:0.1"), + ("localhost:5000/app", "localhost:5000/app:latest"), + ("registry.example.com/team/app", "registry.example.com/team/app:latest"), + ] + ) + func explicitRegistry(reference: String, expected: String) throws { + #expect(try Reference.normalized(reference).description == expected) + } + + @Test("Invalid reference throws") + func invalid() { + #expect(throws: (any Error).self) { + try Reference.normalized("Not A Reference!") + } + } +} diff --git a/ContainerSystemTests/ReportStoreTests.swift b/ContainerSystemTests/ReportStoreTests.swift new file mode 100644 index 0000000..d3dea10 --- /dev/null +++ b/ContainerSystemTests/ReportStoreTests.swift @@ -0,0 +1,209 @@ +// +// ReportStoreTests.swift +// ContainerSystemTests +// +// Keeping a report, and reading it back. +// + +import Foundation +import Testing + +@testable import ContainerSystem + +@Suite("Report store") +struct ReportStoreTests { + /// A folder of its own for each test, so that none of them reads what + /// another wrote. + private func makeStore() throws -> (ReportStore, URL) { + let root = URL.temporaryDirectory + .appendingPathComponent("reports-\(UUID().uuidString)") + + return (try ReportStore(root: root), root) + } + + @Test("Record and list") + func recordsAndLists() async throws { + let (store, root) = try makeStore() + + defer { try? FileManager.default.removeItem(at: root) } + + let started = Date(timeIntervalSinceNow: -12) + let written = try await store.record( + level: .error, + kind: .build, + name: "nginx:latest", + message: "The image couldn’t be built.", + body: "step 3/4 failed", + startedAt: started + ) + + let listed = try #require(await store.list().first) + + #expect(listed == written) + #expect(listed.kind == .build) + #expect(listed.level == .error) + #expect(listed.name == "nginx:latest") + #expect(listed.message == "The image couldn’t be built.") + #expect(abs(listed.date.timeIntervalSince(started)) < 0.001) + #expect(listed.endDate >= listed.date) + } + + /// The account is read from the file rather than from the manifest, which + /// is the whole point of keeping the two apart. + @Test("Body round trip") + func readsBodyBack() async throws { + let (store, root) = try makeStore() + + defer { try? FileManager.default.removeItem(at: root) } + + let transcript = (1...500) + .map { "#\($0) RUN apt-get install nothing" } + .joined(separator: "\n") + + let written = try await store.record( + level: .error, + kind: .build, + name: "nginx:latest", + message: "The image couldn’t be built.", + body: transcript, + startedAt: nil + ) + + #expect(try await store.body(of: written.id) == transcript) + } + + /// Deflated as Xcode deflates its own, so that anything that reads a gzip + /// file can read one of these. + @Test("Body is gzipped") + func keepsBodyDeflated() async throws { + let (store, root) = try makeStore() + + defer { try? FileManager.default.removeItem(at: root) } + + let body = String(repeating: "the builder said something\n", count: 400) + let written = try await store.record( + level: .warning, + kind: .image, + name: "nginx:latest", + message: "The image couldn’t be fetched.", + body: body, + startedAt: nil + ) + + let data = try Data(contentsOf: store.url(for: written.id)) + + #expect(data.prefix(2) == Data([0x1f, 0x8b])) + #expect(data.count < body.utf8.count / 2) + #expect(Gzip.text(of: data) == body) + } + + @Test("Remove deletes report") + func removesReport() async throws { + let (store, root) = try makeStore() + + defer { try? FileManager.default.removeItem(at: root) } + + let written = try await store.record( + level: .error, + kind: .container, + name: "web", + message: "The container couldn’t be started.", + body: "the boot loader is invalid", + startedAt: nil + ) + + await store.remove([written.id]) + + #expect(await store.list().isEmpty) + #expect( + !FileManager.default.fileExists( + atPath: store.url(for: written.id).path + ) + ) + } + + /// The count a section carries is kept with the reports themselves, so it + /// is still right after the app has been closed and opened again. + @Test("Read state persists") + func keepsWhatHasBeenRead() async throws { + let (store, root) = try makeStore() + + defer { try? FileManager.default.removeItem(at: root) } + + let written = try await store.record( + level: .error, + kind: .container, + name: "web", + message: "The container couldn’t be started.", + body: "the boot loader is invalid", + startedAt: nil + ) + + #expect(await store.entry(for: written.id)?.isRead == false) + + await store.markRead([written.id]) + + #expect(await store.entry(for: written.id)?.isRead == true) + #expect(try await ReportStore(root: root).list().first?.isRead == true) + } + + /// Reports outlive the app, so a store opened again reads what an earlier + /// one wrote rather than starting afresh. + @Test("Reopened store keeps reports") + func readsWhatAnEarlierStoreWrote() async throws { + let (store, root) = try makeStore() + + defer { try? FileManager.default.removeItem(at: root) } + + let written = try await store.record( + level: .error, + kind: .volume, + name: "data", + message: "The volume couldn’t be created.", + body: "no space left on device", + startedAt: nil + ) + + let reopened = try ReportStore(root: root) + + #expect(await reopened.entry(for: written.id) == written) + #expect(try await reopened.body(of: written.id) == "no space left on device") + } +} + +@Suite("Report body") +@MainActor +struct ReportBodyTests { + /// The same error twice, once with the name of its case around it, is what + /// most of these are: a report says it once. + @Test("Wrapped error appears once") + func doesNotRepeatTheError() { + // What a `ContainerizationError` is: its case, then the message. + struct Wrapped: LocalizedError, CustomStringConvertible { + var errorDescription: String? { + "failed to start container: no kernel" + } + + var description: String { + "internalError: \"failed to start container: no kernel\"" + } + } + + let body = ReportManager.body(for: Wrapped()) + + #expect(body == "failed to start container: no kernel") + } + + /// Where the two say different things, both are worth keeping. + @Test("Distinct descriptions are both kept") + func keepsBothWhereTheyDiffer() { + struct Detailed: LocalizedError { + var errorDescription: String? { "The container couldn’t be started." } + } + + let body = ReportManager.body(for: Detailed()) + + #expect(body.contains("The container couldn’t be started.")) + #expect(body.contains("Detailed")) + } +} diff --git a/ContainerSystemTests/SandboxedContainersServiceTests.swift b/ContainerSystemTests/SandboxedContainersServiceTests.swift deleted file mode 100644 index bc65192..0000000 --- a/ContainerSystemTests/SandboxedContainersServiceTests.swift +++ /dev/null @@ -1,47 +0,0 @@ -// -// SandboxedContainersServiceTests.swift -// ContainerSystemTests -// -// Created by Axel Martinez on 2026/02/08. -// - -import Testing -import Foundation -@testable import ContainerSystem - -@Suite(.serialized) -struct SandboxedContainersServiceTests { - - @Test("Service initializes successfully") - @MainActor - func testServiceInitialization() async throws { - let appRoot = FileManager.default.temporaryDirectory - .appendingPathComponent("test-containers-\(UUID().uuidString)") - - let testRuntime = MockContainerRuntime() - let system = SystemManager(testRuntime: testRuntime) - - try await system.start(appRoot: appRoot) - - #expect(system.isRunning == true) - - try await system.stop() - } - - @Test("Service can be stopped") - @MainActor - func testServiceStop() async throws { - let appRoot = FileManager.default.temporaryDirectory - .appendingPathComponent("test-containers-\(UUID().uuidString)") - - let testRuntime = MockContainerRuntime() - let system = SystemManager(testRuntime: testRuntime) - try await system.start(appRoot: appRoot) - - #expect(system.isRunning == true) - - try await system.stop() - - #expect(system.isRunning == false) - } -} diff --git a/ContainerSystemTests/Support/TemporaryDirectory.swift b/ContainerSystemTests/Support/TemporaryDirectory.swift new file mode 100644 index 0000000..824c185 --- /dev/null +++ b/ContainerSystemTests/Support/TemporaryDirectory.swift @@ -0,0 +1,48 @@ +// +// TemporaryDirectory.swift +// ContainerSystemTests +// +// A unique scratch directory for a single test. +// + +import Foundation + +/// A directory under the system temp dir, unique per instance. +/// +/// Tests pair this with `defer { directory.remove() }` so a failing +/// expectation still leaves the temp dir clean. +struct TemporaryDirectory { + let url: URL + + init(_ name: String = "container-system-tests") throws { + self.url = FileManager.default.temporaryDirectory + .appendingPathComponent("\(name)-\(UUID().uuidString)") + + try FileManager.default.createDirectory( + at: url, + withIntermediateDirectories: true + ) + } + + func appending(_ path: String) -> URL { + url.appendingPathComponent(path) + } + + /// Creates `path`, and any directory above it, holding `contents`. + @discardableResult + func write(_ contents: String, to path: String) throws -> URL { + let file = appending(path) + + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try Data(contents.utf8).write(to: file) + + return file + } + + func remove() { + try? FileManager.default.removeItem(at: url) + } +} diff --git a/ContainerSystemTests/SystemManagerTests.swift b/ContainerSystemTests/SystemManagerTests.swift new file mode 100644 index 0000000..3241f7d --- /dev/null +++ b/ContainerSystemTests/SystemManagerTests.swift @@ -0,0 +1,94 @@ +// +// SystemManagerTests.swift +// ContainerSystemTests +// +// Stopping a start that is under way. +// + +import Foundation +import Testing + +@testable import ContainerSystem + +/// A start that never finishes of its own accord, so that only cancelling +/// brings it to an end. +@MainActor +private final class NeverFinishingRuntime: ContainerRuntime { + private(set) var didFinish = false + + init() { + super.init(forTesting: true) + } + + override func start(appRoot: URL) async throws { + isStarting = true + + defer { + isStarting = false + } + + try await Task.sleep(for: .seconds(30)) + + didFinish = true + } +} + +@Suite("System manager") +@MainActor +struct SystemManagerTests { + + /// The sheet that offers to stop a first run is not always the thing that + /// began it: the dashboard starts the system on later launches and the + /// sheet only opens onto the work. Cancelling has to reach it either way. + @Test("Cancel start begun elsewhere") + func cancelsStartBegunElsewhere() async throws { + let runtime = NeverFinishingRuntime() + let system = SystemManager(testRuntime: runtime) + + // Whoever is waiting here never cancels its own task, the way the + // dashboard's start task does not. + let work = Task { try await system.start(appRoot: .temporaryDirectory) } + + while system.status != .starting { + try await Task.sleep(for: .milliseconds(10)) + } + + system.cancelStart() + + await #expect(throws: CancellationError.self) { + try await work.value + } + + #expect(runtime.didFinish == false) + #expect(system.status == .notStarted) + } + + @Test("Cancel start from caller") + func cancelsStartFromTheCaller() async throws { + let runtime = NeverFinishingRuntime() + let system = SystemManager(testRuntime: runtime) + + let work = Task { try await system.start(appRoot: .temporaryDirectory) } + + while system.status != .starting { + try await Task.sleep(for: .milliseconds(10)) + } + + work.cancel() + + await #expect(throws: CancellationError.self) { + try await work.value + } + + #expect(runtime.didFinish == false) + } + + @Test("Cancel with nothing starting") + func cancelsNothingSafely() { + let system = SystemManager(testRuntime: NeverFinishingRuntime()) + + system.cancelStart() + + #expect(system.status == .notStarted) + } +} diff --git a/ContainerSystemTests/VolumeManagerTests.swift b/ContainerSystemTests/VolumeManagerTests.swift index 09ba824..2ccb674 100644 --- a/ContainerSystemTests/VolumeManagerTests.swift +++ b/ContainerSystemTests/VolumeManagerTests.swift @@ -5,85 +5,167 @@ // Created by Axel Martinez on 2026/02/08. // -import Testing -import Foundation -import ContainerResource import ContainerizationError +import Foundation +import Testing @testable import ContainerSystem -@Suite(.serialized) +@Suite("Volume manager", .serialized) struct VolumeManagerTests { - + // MARK: - Setup Helper - + @MainActor private func setupTestSystem() async throws -> (URL, ContainerRuntime) { let appRoot = FileManager.default.temporaryDirectory .appendingPathComponent("test-containers-\(UUID().uuidString)") - + let testRuntime = MockContainerRuntime() let system = SystemManager(testRuntime: testRuntime) - + try await system.start(appRoot: appRoot) - + return (appRoot, testRuntime) } - + // MARK: - List Volumes Tests - - @Test("List volumes returns array") + + @Test("Empty store lists no volumes") @MainActor - func testListVolumes() async throws { + func emptyStoreListsNoVolumes() async throws { let (_, testRuntime) = try await setupTestSystem() - + let manager = VolumeManager(testRuntime: testRuntime) let volumes = try await manager.list() - - #expect(type(of: volumes) == [Volume].self) + + #expect(volumes.isEmpty) } - + // MARK: - Create Volume Tests - - @Test("Create volume throws unsupported error in sandboxed mode") + + @Test("Created volume is listed") + @MainActor + func createdVolumeIsListed() async throws { + let (_, testRuntime) = try await setupTestSystem() + + let volumeName = "test-volume-\(UUID().uuidString)" + let manager = VolumeManager(testRuntime: testRuntime) + + let volume = try await manager.create( + name: volumeName, + labels: [], + options: [], + sizeInBytes: 1024 * 1024 // 1 MB + ) + + #expect(volume.name == volumeName) + #expect(volume.driver == "local") + #expect(volume.format == "ext4") + #expect(volume.source.hasSuffix("volume.ext4")) + #expect(volume.sizeInBytes == 1024 * 1024) + + let volumes = try await manager.list() + #expect(volumes.contains(where: { $0.name == volumeName })) + } + + @Test("Default size when none given") + @MainActor + func createWithDefaultSize() async throws { + let (_, testRuntime) = try await setupTestSystem() + + let volumeName = "test-volume-\(UUID().uuidString)" + let manager = VolumeManager(testRuntime: testRuntime) + + let volume = try await manager.create( + name: volumeName, + labels: [], + options: [], + sizeInBytes: nil + ) + + #expect(volume.source.hasSuffix("volume.ext4")) + #expect(volume.sizeInBytes == VolumeStorage.defaultVolumeSizeBytes) + + let volumes = try await manager.list() + #expect( + volumes.first(where: { $0.name == volumeName })?.sizeInBytes + == VolumeStorage.defaultVolumeSizeBytes + ) + } + + @Test("Invalid name throws") + @MainActor + func invalidNameThrows() async throws { + let (_, testRuntime) = try await setupTestSystem() + + let manager = VolumeManager(testRuntime: testRuntime) + + await #expect(throws: VolumeError.self) { + _ = try await manager.create( + name: "invalid name!", + labels: [], + options: [], + sizeInBytes: nil + ) + } + } + + @Test("Duplicate name throws") @MainActor - func testCreateVolume() async throws { + func duplicateNameThrows() async throws { let (_, testRuntime) = try await setupTestSystem() - + let volumeName = "test-volume-\(UUID().uuidString)" let manager = VolumeManager(testRuntime: testRuntime) - - do { + + _ = try await manager.create( + name: volumeName, + labels: [], + options: [], + sizeInBytes: 1024 * 1024 + ) + + await #expect(throws: VolumeError.self) { _ = try await manager.create( name: volumeName, labels: [], options: [], - sizeInBytes: nil + sizeInBytes: 1024 * 1024 ) - - Issue.record("Expected ContainerizationError for unsupported operation") - } catch let error as ContainerizationError { - #expect(error.code == .internalError) - #expect(error.message.contains("not yet supported")) } } - + // MARK: - Delete Volume Tests - - @Test("Delete volumes throws unsupported error in sandboxed mode") + + @Test("Delete empty list") @MainActor - func testDeleteEmptyVolumeList() async throws { + func deleteEmptyList() async throws { let (_, testRuntime) = try await setupTestSystem() - + let manager = VolumeManager(testRuntime: testRuntime) - - do { - try await manager.delete(volumes: []) - - Issue.record("Expected ContainerizationError for unsupported operation") - } catch let error as ContainerizationError { - #expect(error.code == .internalError) - #expect(error.message.contains("not yet supported")) - } + + try await manager.delete(volumes: []) + } + + @Test("Delete removes volume") + @MainActor + func deleteRemovesVolume() async throws { + let (_, testRuntime) = try await setupTestSystem() + + let volumeName = "test-volume-\(UUID().uuidString)" + let manager = VolumeManager(testRuntime: testRuntime) + + let volume = try await manager.create( + name: volumeName, + labels: [], + options: [], + sizeInBytes: 1024 * 1024 + ) + + try await manager.delete(volumes: [volume]) + + let volumes = try await manager.list() + #expect(!volumes.contains(where: { $0.name == volumeName })) } } diff --git a/Containers.xcodeproj/ContainersTests/ContainerManagerTests.swift b/Containers.xcodeproj/ContainersTests/ContainerManagerTests.swift deleted file mode 100644 index c104e45..0000000 --- a/Containers.xcodeproj/ContainersTests/ContainerManagerTests.swift +++ /dev/null @@ -1,212 +0,0 @@ -// -// ContainerManagerTests.swift -// ContainersTests -// -// Unit tests for ContainerManager -// - -import Testing -import Foundation -@testable import Containers - -@MainActor -@Suite("ContainerManager Tests") -struct ContainerManagerTests { - - // MARK: - Helper Methods - - /// Creates a minimal container configuration for testing - func createTestContainerInfo() -> ContainerInfo { - return ContainerInfo( - name: "test-container", - os: "linux", - arch: "arm64", - platform: nil, - kernel: nil, - entryPoint: nil, - cidfile: "", - networks: [], - labels: [], - publishPorts: [], - publishSockets: [], - ssh: false, - volumes: [], - virtualFileSystem: [], - temporaryFileSystem: [], - virtualization: .default, - dnsDisabled: false, - dnsNameservers: [], - dnsDomain: nil, - dnsSearchDomains: [], - dnsOptions: [], - deleteOnTermination: false - ) - } - - /// Creates a minimal process configuration for testing - func createTestProcess() -> ContainerProcess { - return ContainerProcess( - command: "", - workingDirectory: nil, - tty: false, - environments: [], - envFile: [], - user: nil, - uid: nil, - gid: nil - ) - } - - // MARK: - Validation Tests - - @Test("Valid entity name passes validation") - func testValidEntityName() async throws { - // Valid names should contain alphanumeric, underscore, dot, or dash - // This tests the internal validation logic - let validNames = ["test", "test-container", "test_container", "test.container", "test123"] - - // Since validEntityName is private, we test it indirectly through createContainer - // For direct testing, we'd need to make it internal or create a test-specific exposure - #expect(true) // Placeholder - would need reflection or exposure for direct testing - } - - @Test("Invalid entity name should fail validation") - func testInvalidEntityName() async throws { - // Names starting with special characters or containing invalid chars should fail - // This would be tested through createContainer failure - #expect(true) // Placeholder - } - - // MARK: - Container ID Generation Tests - - @Test("Container ID generated when name is empty") - func testContainerIDGeneration() async throws { - // When no name is provided, a UUID should be generated - // This tests the internal createContainerID logic - #expect(true) // Placeholder - tests internal logic - } - - @Test("Container ID uses provided name") - func testContainerIDFromName() async throws { - // When name is provided, it should be used as the ID - #expect(true) // Placeholder - } - - // MARK: - List Containers Tests - - @Test("List containers returns empty array initially", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testListContainersEmpty() async throws { - // Start system first - try await ContainerSystem.shared.start() - - let containers = try await ContainerManager.listContainers() - // May not be empty if system has existing containers - #expect(containers != nil) - } - - @Test("List containers is callable", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testListContainersCallable() async throws { - try await ContainerSystem.shared.start() - - let result = try await ContainerManager.listContainers() - #expect(result is [ContainerSnapshot]) - } - - // MARK: - Get Container Tests - - @Test("Get non-existent container throws error", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testGetNonExistentContainer() async throws { - try await ContainerSystem.shared.start() - - do { - _ = try await ContainerManager.getContainer("nonexistent-container-id") - Issue.record("Expected ContainerizationError") - } catch let error as ContainerizationError { - #expect(error.code == .notFound) - } catch { - Issue.record("Wrong error type: \(error)") - } - } - - // MARK: - Container Log Tests - - @Test("Get container log for non-existent container returns empty string") - func testGetContainerLogNonExistent() async throws { - let log = try await ContainerManager.getContainerLog("nonexistent", boot: false) - #expect(log.isEmpty) - } - - @Test("Get boot log returns empty for non-existent container") - func testGetBootLogNonExistent() async throws { - let log = try await ContainerManager.getContainerLog("nonexistent", boot: true) - #expect(log.isEmpty) - } - - // MARK: - Shell Split Tests - - @Test("Shell split handles simple commands") - func testShellSplitSimple() async throws { - // Tests the internal shellSplit method indirectly - // "sh -c echo" should become ["sh", "-c", "echo"] - #expect(true) // Placeholder - tests internal utility - } - - @Test("Shell split handles quoted strings") - func testShellSplitQuoted() async throws { - // Tests that "sh -c \"echo hello\"" becomes ["sh", "-c", "echo hello"] - #expect(true) // Placeholder - } - - @Test("Shell split handles single quotes") - func testShellSplitSingleQuotes() async throws { - // Tests that "sh -c 'echo hello'" becomes ["sh", "-c", "echo hello"] - #expect(true) // Placeholder - } - - // MARK: - Stop Containers Tests - - @Test("Stop empty container list succeeds", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testStopEmptyList() async throws { - try await ContainerSystem.shared.start() - - // Stopping empty list should not error - try await ContainerManager.stopContainers(containers: []) - } - - // MARK: - Delete Containers Tests - - @Test("Delete empty container list succeeds", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testDeleteEmptyList() async throws { - try await ContainerSystem.shared.start() - - // Deleting empty list should not error - try await ContainerManager.deleteContainers([], force: false) - } - - @Test("Delete running container without force fails", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testDeleteRunningContainerWithoutForce() async throws { - // This would require actually creating and starting a container - // Placeholder for integration test - #expect(true) - } - - // MARK: - Process Configuration Tests - - @Test("Process configuration uses image defaults when not overridden") - func testProcessConfigurationDefaults() async throws { - // Tests that parseProcessConfiguration correctly uses image config defaults - #expect(true) // Placeholder - tests internal logic - } - - @Test("Process configuration overrides image defaults when specified") - func testProcessConfigurationOverride() async throws { - // Tests that user-specified values override image defaults - #expect(true) // Placeholder - } - - @Test("Process configuration requires command or entrypoint") - func testProcessConfigurationRequiresCommand() async throws { - // Should fail if neither command nor entrypoint is provided - #expect(true) // Placeholder - } -} diff --git a/Containers.xcodeproj/ContainersTests/ImageManagerTests.swift b/Containers.xcodeproj/ContainersTests/ImageManagerTests.swift deleted file mode 100644 index 5388421..0000000 --- a/Containers.xcodeproj/ContainersTests/ImageManagerTests.swift +++ /dev/null @@ -1,270 +0,0 @@ -// -// ImageManagerTests.swift -// ContainersTests -// -// Unit tests for ImageManager -// - -import Testing -import Foundation -@testable import Containers - -@MainActor -@Suite("ImageManager Tests") -struct ImageManagerTests { - - // MARK: - Helper Methods - - /// Creates a test image description - func createTestImageDescription() -> ImageDescription { - // This would need actual ImageDescription initialization - // Placeholder for now - return ImageDescription(reference: "test:latest", description: "test:latest", digest: "sha256:test") - } - - // MARK: - List Images Tests - - @Test("List images returns array", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testListImages() async throws { - try await ContainerSystem.shared.start() - - let images = try await ImageManager.listImages() - #expect(images is [ImageDescription]) - } - - @Test("List images filters infrastructure images", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testListImagesFiltersInfra() async throws { - try await ContainerSystem.shared.start() - - let images = try await ImageManager.listImages() - - // Verify no infrastructure images are in the list - let hasInfraImage = images.contains { image in - image.reference.contains("buildkit") || image.reference.contains("init") - } - - // Infrastructure images should be filtered out - #expect(!hasInfraImage || images.isEmpty) - } - - // MARK: - Infrastructure Image Detection Tests - - @Test("Infrastructure image detection identifies builder image") - func testIsInfraImageBuilder() async throws { - // Tests the internal isInfraImage method - // Builder images should be detected - #expect(true) // Placeholder - tests internal logic - } - - @Test("Infrastructure image detection identifies init image") - func testIsInfraImageInit() async throws { - // Init images should be detected - #expect(true) // Placeholder - } - - @Test("Infrastructure image detection excludes regular images") - func testIsInfraImageRegular() async throws { - // Regular images should not be detected as infrastructure - #expect(true) // Placeholder - } - - // MARK: - Pull Image Tests - - @Test("Pull image with invalid reference throws error") - func testPullImageInvalidReference() async throws { - do { - try await ImageManager.pullImage(reference: "") - Issue.record("Expected error for empty reference") - } catch { - // Expected to throw - #expect(error is ContainerizationError || error is Error) - } - } - - @Test("Pull image requires started system", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testPullImageRequiresStartedSystem() async throws { - // Stop system if running - try await ContainerSystem.shared.stop() - - do { - try await ImageManager.pullImage(reference: "alpine:latest") - Issue.record("Expected error when system not started") - } catch let error as ContainerizationError { - #expect(error.code == .internalError) - } catch { - // May throw different error - } - } - - // MARK: - Save Images Tests - - @Test("Save images to valid directory", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testSaveImagesToDirectory() async throws { - try await ContainerSystem.shared.start() - - let tempDir = FileManager.default.temporaryDirectory - .appendingPathComponent("ImageManagerTests") - .appendingPathComponent(UUID().uuidString) - - try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: tempDir) } - - // Save empty list should succeed - try await ImageManager.saveImages([], outputDirectory: tempDir) - } - - @Test("Save images with empty list succeeds", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testSaveEmptyImageList() async throws { - try await ContainerSystem.shared.start() - - let tempDir = FileManager.default.temporaryDirectory - .appendingPathComponent("ImageManagerTests") - .appendingPathComponent(UUID().uuidString) - - try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: tempDir) } - - try await ImageManager.saveImages([], outputDirectory: tempDir) - } - - // MARK: - Load Images Tests - - @Test("Load images from non-existent file throws error") - func testLoadImagesNonExistentFile() async throws { - let nonExistentFile = URL(fileURLWithPath: "/nonexistent/path/image.tar") - - do { - try await ImageManager.loadImages(tar: nonExistentFile) - Issue.record("Expected error for non-existent file") - } catch let error as ContainerizationError { - #expect(error.code == .invalidArgument) - } catch { - // May throw different error - } - } - - @Test("Load images requires started system", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testLoadImagesRequiresStartedSystem() async throws { - // Stop system if running - try await ContainerSystem.shared.stop() - - let tempFile = FileManager.default.temporaryDirectory - .appendingPathComponent("test.tar") - - // Create empty file - FileManager.default.createFile(atPath: tempFile.path, contents: Data()) - defer { try? FileManager.default.removeItem(at: tempFile) } - - do { - try await ImageManager.loadImages(tar: tempFile) - Issue.record("Expected error when system not started") - } catch { - // Expected to throw - } - } - - // MARK: - Delete Images Tests - - @Test("Delete empty image list succeeds", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testDeleteEmptyImageList() async throws { - try await ContainerSystem.shared.start() - - try await ImageManager.deleteImages([]) - } - - @Test("Delete images filters infrastructure images", .enabled(if: ProcessInfo.processInfo.environment["CI"] == nil)) - func testDeleteImagesFiltersInfra() async throws { - // Infrastructure images should not be deleted - // This would require creating a mock infrastructure image - #expect(true) // Placeholder - } - - // MARK: - Build Image Tests - - @Test("Build image output configuration validates destination") - func testBuildImageOutputValidation() async throws { - // Test BuildImageOutputConfiguration validation - let config = BuildImageOutputConfiguration( - type: .tar, - destinationDirectory: nil, - additionalFields: [] - ) - - do { - try config.verify() - Issue.record("Expected error for missing destination") - } catch let error as ContainerizationError { - #expect(error.code == .invalidArgument) - } catch { - Issue.record("Wrong error type") - } - } - - @Test("Build image OCI output does not require destination") - func testBuildImageOCINoDestination() async throws { - let config = BuildImageOutputConfiguration( - type: .oci, - destinationDirectory: nil, - additionalFields: [] - ) - - // OCI output should not require destination - try config.verify() - } - - @Test("Build image local output requires destination") - func testBuildImageLocalRequiresDestination() async throws { - let config = BuildImageOutputConfiguration( - type: .local, - destinationDirectory: nil, - additionalFields: [] - ) - - do { - try config.verify() - Issue.record("Expected error for missing destination") - } catch let error as ContainerizationError { - #expect(error.code == .invalidArgument) - } catch { - Issue.record("Wrong error type") - } - } - - @Test("Build image tar output requires destination") - func testBuildImageTarRequiresDestination() async throws { - let config = BuildImageOutputConfiguration( - type: .tar, - destinationDirectory: nil, - additionalFields: [] - ) - - do { - try config.verify() - Issue.record("Expected error for missing destination") - } catch let error as ContainerizationError { - #expect(error.code == .invalidArgument) - } catch { - Issue.record("Wrong error type") - } - } - - // MARK: - Key Value String Tests - - @Test("Key value string formatting") - func testKeyValueStringFormat() { - let result = ImageManager.keyValueString(key: "foo", value: "bar") - #expect(result == "foo=bar") - } - - @Test("Key value string handles special characters") - func testKeyValueStringSpecialChars() { - let result = ImageManager.keyValueString(key: "key-with-dash", value: "value_with_underscore") - #expect(result == "key-with-dash=value_with_underscore") - } - - @Test("Key value string handles empty values") - func testKeyValueStringEmptyValue() { - let result = ImageManager.keyValueString(key: "key", value: "") - #expect(result == "key=") - } -} diff --git a/Containers.xcodeproj/ContainersTests/VolumeManagerTests.swift b/Containers.xcodeproj/ContainersTests/VolumeManagerTests.swift deleted file mode 100644 index 0a6225d..0000000 --- a/Containers.xcodeproj/ContainersTests/VolumeManagerTests.swift +++ /dev/null @@ -1,155 +0,0 @@ -// -// VolumeManagerTests.swift -// ContainersTests -// -// Unit tests for VolumeManager -// - -import Testing -import Foundation -@testable import Containers - -@Suite("VolumeManager Tests") -struct VolumeManagerTests { - - // MARK: - List Volumes Tests - - @Test("List volumes returns empty array") - func testListVolumesEmpty() async throws { - let volumes = try await VolumeManager.listVolumes() - #expect(volumes.isEmpty) - } - - @Test("List volumes returns array type") - func testListVolumesType() async throws { - let volumes = try await VolumeManager.listVolumes() - #expect(volumes is [Volume]) - } - - // MARK: - Create Volume Tests - - @Test("Create volume throws not supported error") - func testCreateVolumeNotSupported() async throws { - do { - _ = try await VolumeManager.createVolume( - name: "test-volume", - labels: [], - options: [], - sizeInBytes: nil - ) - Issue.record("Expected ContainerizationError for unsupported operation") - } catch let error as ContainerizationError { - #expect(error.code == .internalError) - #expect(error.message.contains("not yet supported")) - } catch { - Issue.record("Wrong error type: \(error)") - } - } - - @Test("Create volume with size throws not supported error") - func testCreateVolumeWithSizeNotSupported() async throws { - do { - _ = try await VolumeManager.createVolume( - name: "test-volume", - labels: [], - options: [], - sizeInBytes: 1024 * 1024 * 1024 // 1GB - ) - Issue.record("Expected ContainerizationError") - } catch let error as ContainerizationError { - #expect(error.code == .internalError) - } catch { - Issue.record("Wrong error type") - } - } - - @Test("Create volume with labels throws not supported error") - func testCreateVolumeWithLabelsNotSupported() async throws { - let labels = [KeyValue(key: "env", value: "test")] - - do { - _ = try await VolumeManager.createVolume( - name: "test-volume", - labels: labels, - options: [], - sizeInBytes: nil - ) - Issue.record("Expected ContainerizationError") - } catch let error as ContainerizationError { - #expect(error.code == .internalError) - } catch { - Issue.record("Wrong error type") - } - } - - @Test("Create volume with options throws not supported error") - func testCreateVolumeWithOptionsNotSupported() async throws { - let options = [KeyValue(key: "type", value: "tmpfs")] - - do { - _ = try await VolumeManager.createVolume( - name: "test-volume", - labels: [], - options: options, - sizeInBytes: nil - ) - Issue.record("Expected ContainerizationError") - } catch let error as ContainerizationError { - #expect(error.code == .internalError) - } catch { - Issue.record("Wrong error type") - } - } - - // MARK: - Delete Volumes Tests - - @Test("Delete empty volume list throws not supported error") - func testDeleteEmptyVolumeList() async throws { - do { - try await VolumeManager.deleteVolumes([]) - Issue.record("Expected ContainerizationError") - } catch let error as ContainerizationError { - #expect(error.code == .internalError) - #expect(error.message.contains("not yet supported")) - } catch { - Issue.record("Wrong error type: \(error)") - } - } - - // MARK: - Future Implementation Tests (Placeholders) - - @Test("Volume creation will support various sizes") - func testVolumeSizesPlaceholder() async throws { - // Placeholder for when volume management is implemented - // Should support K, M, G, T, P suffixes - #expect(true) - } - - @Test("Volume creation will support labels") - func testVolumeLabelsPlaceholder() async throws { - // Placeholder for when volume management is implemented - // Should support arbitrary key-value labels - #expect(true) - } - - @Test("Volume creation will support driver options") - func testVolumeDriverOptionsPlaceholder() async throws { - // Placeholder for when volume management is implemented - // Should support driver-specific options - #expect(true) - } - - @Test("Volume listing will return actual volumes") - func testVolumeListingPlaceholder() async throws { - // Placeholder for when volume management is implemented - // Should return list of created volumes - #expect(true) - } - - @Test("Volume deletion will remove volumes") - func testVolumeDeletionPlaceholder() async throws { - // Placeholder for when volume management is implemented - // Should delete specified volumes - #expect(true) - } -} diff --git a/Containers.xcodeproj/project.pbxproj b/Containers.xcodeproj/project.pbxproj index 7d5a8a1..5ea11dd 100644 --- a/Containers.xcodeproj/project.pbxproj +++ b/Containers.xcodeproj/project.pbxproj @@ -7,28 +7,16 @@ objects = { /* Begin PBXBuildFile section */ - 7735092E2F34EAD100C5471F /* ContainerRuntime.swift in Sources */ = {isa = PBXBuildFile; fileRef = 773508B42F34E4D000C5471F /* ContainerRuntime.swift */; }; - 7735094C2F34EB5700C5471F /* KeyValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 773508892F34E4D000C5471F /* KeyValue.swift */; }; - 7735094F2F34EBBA00C5471F /* ContainerProcess.swift in Sources */ = {isa = PBXBuildFile; fileRef = 773508872F34E4D000C5471F /* ContainerProcess.swift */; }; - 773509502F34EBBF00C5471F /* ContainerInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 773508862F34E4D000C5471F /* ContainerInfo.swift */; }; 773509582F34FC7D00C5471F /* libContainerSystem.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 773509102F34EA2F00C5471F /* libContainerSystem.dylib */; }; - 77350A742F35A14000C5471F /* ContainerAPIClient in Frameworks */ = {isa = PBXBuildFile; productRef = 77350A732F35A14000C5471F /* ContainerAPIClient */; }; - 77350A762F35A14000C5471F /* ContainerAPIService in Frameworks */ = {isa = PBXBuildFile; productRef = 77350A752F35A14000C5471F /* ContainerAPIService */; }; - 77350A782F35A14000C5471F /* ContainerBuild in Frameworks */ = {isa = PBXBuildFile; productRef = 77350A772F35A14000C5471F /* ContainerBuild */; }; - 77350A7A2F35A14000C5471F /* ContainerCommands in Frameworks */ = {isa = PBXBuildFile; productRef = 77350A792F35A14000C5471F /* ContainerCommands */; }; - 77350A7C2F35A14000C5471F /* ContainerImagesService in Frameworks */ = {isa = PBXBuildFile; productRef = 77350A7B2F35A14000C5471F /* ContainerImagesService */; }; - 77350A7E2F35A14000C5471F /* ContainerLog in Frameworks */ = {isa = PBXBuildFile; productRef = 77350A7D2F35A14000C5471F /* ContainerLog */; }; - 77350A802F35A14000C5471F /* ContainerNetworkService in Frameworks */ = {isa = PBXBuildFile; productRef = 77350A7F2F35A14000C5471F /* ContainerNetworkService */; }; - 77350A822F35A14000C5471F /* ContainerPersistence in Frameworks */ = {isa = PBXBuildFile; productRef = 77350A812F35A14000C5471F /* ContainerPersistence */; }; - 77350AA02F35A32300C5471F /* ContainerSandboxService in Frameworks */ = {isa = PBXBuildFile; productRef = 77350A9F2F35A32300C5471F /* ContainerSandboxService */; }; 77350BA92F35B17100C5471F /* libContainerSystem.dylib in Embed Libraries */ = {isa = PBXBuildFile; fileRef = 773509102F34EA2F00C5471F /* libContainerSystem.dylib */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; 77350BAB2F35B53700C5471F /* libContainerSystem.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 773509102F34EA2F00C5471F /* libContainerSystem.dylib */; }; 77350BAC2F35B53700C5471F /* libContainerSystem.dylib in Embed Libraries */ = {isa = PBXBuildFile; fileRef = 773509102F34EA2F00C5471F /* libContainerSystem.dylib */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; - 77BA16482F38B1E800D8903B /* ContainerRuntime+Prerequisites.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77BA16462F38B15500D8903B /* ContainerRuntime+Prerequisites.swift */; }; - 77BA16492F38B1ED00D8903B /* ContainerRuntime+Plugins.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77BA16442F38B13600D8903B /* ContainerRuntime+Plugins.swift */; }; - 77BA164B2F38B3A400D8903B /* ContainerRuntime+Services.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77BA164A2F38B3A400D8903B /* ContainerRuntime+Services.swift */; }; - 77D77D692F3A254F00FB803D /* ServerStream+Transfers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77D77D682F3A253A00FB803D /* ServerStream+Transfers.swift */; }; - 77D77D6B2F3A255B00FB803D /* ImageTransfer+Metadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77D77D6A2F3A255B00FB803D /* ImageTransfer+Metadata.swift */; }; + 77C44F1B2F698D0600167C4D /* Containerization in Frameworks */ = {isa = PBXBuildFile; productRef = 77C44F1A2F698D0600167C4D /* Containerization */; }; + 77C44F1D2F698D0600167C4D /* ContainerizationArchive in Frameworks */ = {isa = PBXBuildFile; productRef = 77C44F1C2F698D0600167C4D /* ContainerizationArchive */; }; + 77C44F1F2F698D0600167C4D /* ContainerizationEXT4 in Frameworks */ = {isa = PBXBuildFile; productRef = 77C44F1E2F698D0600167C4D /* ContainerizationEXT4 */; }; + 77C44F212F698D0600167C4D /* ContainerizationExtras in Frameworks */ = {isa = PBXBuildFile; productRef = 77C44F202F698D0600167C4D /* ContainerizationExtras */; }; + 77C44F232F698D0600167C4D /* ContainerizationIO in Frameworks */ = {isa = PBXBuildFile; productRef = 77C44F222F698D0600167C4D /* ContainerizationIO */; }; + 77C44F252F698E9A00167C4D /* ContainerizationOCI in Frameworks */ = {isa = PBXBuildFile; productRef = 77C44F242F698E9A00167C4D /* ContainerizationOCI */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -82,60 +70,19 @@ /* Begin PBXFileReference section */ 773508642F34E40500C5471F /* ContainerSystemTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = ContainerSystemTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 773508862F34E4D000C5471F /* ContainerInfo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerInfo.swift; sourceTree = ""; }; - 773508872F34E4D000C5471F /* ContainerProcess.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerProcess.swift; sourceTree = ""; }; - 773508892F34E4D000C5471F /* KeyValue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyValue.swift; sourceTree = ""; }; - 773508B42F34E4D000C5471F /* ContainerRuntime.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerRuntime.swift; sourceTree = ""; }; 773509102F34EA2F00C5471F /* libContainerSystem.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libContainerSystem.dylib; sourceTree = BUILT_PRODUCTS_DIR; }; - 77BA16442F38B13600D8903B /* ContainerRuntime+Plugins.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ContainerRuntime+Plugins.swift"; sourceTree = ""; }; - 77BA16462F38B15500D8903B /* ContainerRuntime+Prerequisites.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ContainerRuntime+Prerequisites.swift"; sourceTree = ""; }; - 77BA164A2F38B3A400D8903B /* ContainerRuntime+Services.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ContainerRuntime+Services.swift"; sourceTree = ""; }; - 77D77D682F3A253A00FB803D /* ServerStream+Transfers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ServerStream+Transfers.swift"; sourceTree = ""; }; - 77D77D6A2F3A255B00FB803D /* ImageTransfer+Metadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ImageTransfer+Metadata.swift"; sourceTree = ""; }; 9829EC422E17BA3C00A9F8D3 /* Containers.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Containers.app; sourceTree = BUILT_PRODUCTS_DIR; }; + A1C0F1A12F80000000C0F1A1 /* Base.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Base.xcconfig; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ - 77350E702F3877FE00C5471F /* Exceptions for "Managers" folder in "Containers" target */ = { + 774688BA2FDDEDF0000DC29F /* Exceptions for "Containers" folder in "Containers" target */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( - BuilderManager.swift, - ContainerManager.swift, - DNSManager.swift, - ImageManager.swift, - SystemManager.swift, - VolumeManager.swift, + "Supporting Files/Info.plist", ); target = 9829EC412E17BA3C00A9F8D3 /* Containers */; }; - 77350E712F3877FE00C5471F /* Exceptions for "Managers" folder in "ContainerSystem" target */ = { - isa = PBXFileSystemSynchronizedBuildFileExceptionSet; - membershipExceptions = ( - BuilderManager.swift, - ContainerManager.swift, - DNSManager.swift, - ImageManager.swift, - SystemManager.swift, - VolumeManager.swift, - ); - target = 7735090F2F34EA2F00C5471F /* ContainerSystem */; - }; - 77350E722F38780400C5471F /* Exceptions for "Services" folder in "Containers" target */ = { - isa = PBXFileSystemSynchronizedBuildFileExceptionSet; - membershipExceptions = ( - SandboxedBuilder.swift, - SandboxedContainersService.swift, - ); - target = 9829EC412E17BA3C00A9F8D3 /* Containers */; - }; - 77350E742F38780700C5471F /* Exceptions for "Services" folder in "ContainerSystem" target */ = { - isa = PBXFileSystemSynchronizedBuildFileExceptionSet; - membershipExceptions = ( - SandboxedBuilder.swift, - SandboxedContainersService.swift, - ); - target = 7735090F2F34EA2F00C5471F /* ContainerSystem */; - }; /* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ /* Begin PBXFileSystemSynchronizedRootGroup section */ @@ -144,26 +91,16 @@ path = ContainerSystemTests; sourceTree = ""; }; - 773509182F34EA9600C5471F /* Services */ = { + 77C44F6E2F69C4EE00167C4D /* ContainerSystem */ = { isa = PBXFileSystemSynchronizedRootGroup; - exceptions = ( - 77350E722F38780400C5471F /* Exceptions for "Services" folder in "Containers" target */, - 77350E742F38780700C5471F /* Exceptions for "Services" folder in "ContainerSystem" target */, - ); - path = Services; + path = ContainerSystem; sourceTree = ""; }; - 773509202F34EA9F00C5471F /* Managers */ = { + 9829EC442E17BA3C00A9F8D3 /* Containers */ = { isa = PBXFileSystemSynchronizedRootGroup; exceptions = ( - 77350E702F3877FE00C5471F /* Exceptions for "Managers" folder in "Containers" target */, - 77350E712F3877FE00C5471F /* Exceptions for "Managers" folder in "ContainerSystem" target */, + 774688BA2FDDEDF0000DC29F /* Exceptions for "Containers" folder in "Containers" target */, ); - path = Managers; - sourceTree = ""; - }; - 9829EC442E17BA3C00A9F8D3 /* Containers */ = { - isa = PBXFileSystemSynchronizedRootGroup; path = Containers; sourceTree = ""; }; @@ -182,15 +119,12 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 77350A742F35A14000C5471F /* ContainerAPIClient in Frameworks */, - 77350A782F35A14000C5471F /* ContainerBuild in Frameworks */, - 77350A7A2F35A14000C5471F /* ContainerCommands in Frameworks */, - 77350A7E2F35A14000C5471F /* ContainerLog in Frameworks */, - 77350A822F35A14000C5471F /* ContainerPersistence in Frameworks */, - 77350AA02F35A32300C5471F /* ContainerSandboxService in Frameworks */, - 77350A762F35A14000C5471F /* ContainerAPIService in Frameworks */, - 77350A802F35A14000C5471F /* ContainerNetworkService in Frameworks */, - 77350A7C2F35A14000C5471F /* ContainerImagesService in Frameworks */, + 77C44F232F698D0600167C4D /* ContainerizationIO in Frameworks */, + 77C44F252F698E9A00167C4D /* ContainerizationOCI in Frameworks */, + 77C44F1D2F698D0600167C4D /* ContainerizationArchive in Frameworks */, + 77C44F1F2F698D0600167C4D /* ContainerizationEXT4 in Frameworks */, + 77C44F212F698D0600167C4D /* ContainerizationExtras in Frameworks */, + 77C44F1B2F698D0600167C4D /* Containerization in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -205,54 +139,13 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 773509162F34EA7300C5471F /* ContainerSystem */ = { - isa = PBXGroup; - children = ( - 77D77D6E2F3A25DF00FB803D /* Extensions */, - 7735094B2F34EB3800C5471F /* Models */, - 773509202F34EA9F00C5471F /* Managers */, - 773509182F34EA9600C5471F /* Services */, - 773508B42F34E4D000C5471F /* ContainerRuntime.swift */, - 77BA16442F38B13600D8903B /* ContainerRuntime+Plugins.swift */, - 77BA16462F38B15500D8903B /* ContainerRuntime+Prerequisites.swift */, - 77BA164A2F38B3A400D8903B /* ContainerRuntime+Services.swift */, - ); - path = ContainerSystem; - sourceTree = ""; - }; - 7735094B2F34EB3800C5471F /* Models */ = { - isa = PBXGroup; - children = ( - 773508862F34E4D000C5471F /* ContainerInfo.swift */, - 773508872F34E4D000C5471F /* ContainerProcess.swift */, - 773508892F34E4D000C5471F /* KeyValue.swift */, - ); - path = Models; - sourceTree = ""; - }; - 77D77D6E2F3A25DF00FB803D /* Extensions */ = { - isa = PBXGroup; - children = ( - 77D77D6A2F3A255B00FB803D /* ImageTransfer+Metadata.swift */, - 77D77D682F3A253A00FB803D /* ServerStream+Transfers.swift */, - ); - path = Extensions; - sourceTree = ""; - }; - 77DB33FC2F4078A0006C9BD1 /* Frameworks */ = { - isa = PBXGroup; - children = ( - ); - path = Frameworks; - sourceTree = ""; - }; 9829EC392E17BA3C00A9F8D3 = { isa = PBXGroup; children = ( 9829EC442E17BA3C00A9F8D3 /* Containers */, - 773509162F34EA7300C5471F /* ContainerSystem */, + 77C44F6E2F69C4EE00167C4D /* ContainerSystem */, 773508652F34E40500C5471F /* ContainerSystemTests */, - 77DB33FC2F4078A0006C9BD1 /* Frameworks */, + A1C0F1A22F80000000C0F1A1 /* Configuration */, 9829EC432E17BA3C00A9F8D3 /* Products */, ); sourceTree = ""; @@ -267,6 +160,14 @@ name = Products; sourceTree = ""; }; + A1C0F1A22F80000000C0F1A1 /* Configuration */ = { + isa = PBXGroup; + children = ( + A1C0F1A12F80000000C0F1A1 /* Base.xcconfig */, + ); + path = Configuration; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -317,17 +218,17 @@ ); dependencies = ( ); + fileSystemSynchronizedGroups = ( + 77C44F6E2F69C4EE00167C4D /* ContainerSystem */, + ); name = ContainerSystem; packageProductDependencies = ( - 77350A732F35A14000C5471F /* ContainerAPIClient */, - 77350A752F35A14000C5471F /* ContainerAPIService */, - 77350A772F35A14000C5471F /* ContainerBuild */, - 77350A792F35A14000C5471F /* ContainerCommands */, - 77350A7B2F35A14000C5471F /* ContainerImagesService */, - 77350A7D2F35A14000C5471F /* ContainerLog */, - 77350A7F2F35A14000C5471F /* ContainerNetworkService */, - 77350A812F35A14000C5471F /* ContainerPersistence */, - 77350A9F2F35A32300C5471F /* ContainerSandboxService */, + 77C44F1A2F698D0600167C4D /* Containerization */, + 77C44F1C2F698D0600167C4D /* ContainerizationArchive */, + 77C44F1E2F698D0600167C4D /* ContainerizationEXT4 */, + 77C44F202F698D0600167C4D /* ContainerizationExtras */, + 77C44F222F698D0600167C4D /* ContainerizationIO */, + 77C44F242F698E9A00167C4D /* ContainerizationOCI */, ); productName = ContainerSystem; productReference = 773509102F34EA2F00C5471F /* libContainerSystem.dylib */; @@ -337,6 +238,7 @@ isa = PBXNativeTarget; buildConfigurationList = 9829EC4D2E17BA3D00A9F8D3 /* Build configuration list for PBXNativeTarget "Containers" */; buildPhases = ( + 771304772FE81E1000EEA64D /* ShellScript */, 9829EC3E2E17BA3C00A9F8D3 /* Sources */, 9829EC3F2E17BA3C00A9F8D3 /* Frameworks */, 9829EC402E17BA3C00A9F8D3 /* Resources */, @@ -348,8 +250,6 @@ 7735094E2F34EB8100C5471F /* PBXTargetDependency */, ); fileSystemSynchronizedGroups = ( - 773509182F34EA9600C5471F /* Services */, - 773509202F34EA9F00C5471F /* Managers */, 9829EC442E17BA3C00A9F8D3 /* Containers */, ); name = Containers; @@ -390,7 +290,7 @@ mainGroup = 9829EC392E17BA3C00A9F8D3; minimizedProjectReferenceProxies = 1; packageReferences = ( - 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */, + 77C44F192F698D0600167C4D /* XCRemoteSwiftPackageReference "containerization" */, ); preferredProjectObjectVersion = 77; productRefGroup = 9829EC432E17BA3C00A9F8D3 /* Products */; @@ -421,6 +321,27 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 771304772FE81E1000EEA64D /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "# Type a script or drag a script file from your workspace to insert its path.\nswift-format lint -r ${PROJECT_DIR} --configuration .swift-format\n"; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 773508602F34E40500C5471F /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -433,15 +354,6 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 7735094C2F34EB5700C5471F /* KeyValue.swift in Sources */, - 77D77D6B2F3A255B00FB803D /* ImageTransfer+Metadata.swift in Sources */, - 77BA16492F38B1ED00D8903B /* ContainerRuntime+Plugins.swift in Sources */, - 77BA164B2F38B3A400D8903B /* ContainerRuntime+Services.swift in Sources */, - 77BA16482F38B1E800D8903B /* ContainerRuntime+Prerequisites.swift in Sources */, - 773509502F34EBBF00C5471F /* ContainerInfo.swift in Sources */, - 77D77D692F3A254F00FB803D /* ServerStream+Transfers.swift in Sources */, - 7735094F2F34EBBA00C5471F /* ContainerProcess.swift in Sources */, - 7735092E2F34EAD100C5471F /* ContainerRuntime.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -478,7 +390,6 @@ buildSettings = { CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; - DEVELOPMENT_TEAM = ZTW69M5NDR; GENERATE_INFOPLIST_FILE = YES; MACOSX_DEPLOYMENT_TARGET = 26.2; MARKETING_VERSION = 1.0; @@ -497,7 +408,6 @@ buildSettings = { CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; - DEVELOPMENT_TEAM = ZTW69M5NDR; GENERATE_INFOPLIST_FILE = YES; MACOSX_DEPLOYMENT_TARGET = 26.2; MARKETING_VERSION = 1.0; @@ -515,12 +425,11 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = ZTW69M5NDR; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@executable_path/../Frameworks"; EXECUTABLE_PREFIX = lib; - MACOSX_DEPLOYMENT_TARGET = 26.2; + MACOSX_DEPLOYMENT_TARGET = 26.0; OTHER_SWIFT_FLAGS = ""; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; @@ -531,12 +440,11 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = ZTW69M5NDR; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@executable_path/../Frameworks"; EXECUTABLE_PREFIX = lib; - MACOSX_DEPLOYMENT_TARGET = 26.2; + MACOSX_DEPLOYMENT_TARGET = 26.0; OTHER_SWIFT_FLAGS = ""; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; @@ -545,6 +453,7 @@ }; 9829EC4B2E17BA3D00A9F8D3 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = A1C0F1A12F80000000C0F1A1 /* Base.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; @@ -579,7 +488,6 @@ COPY_PHASE_STRIP = NO; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; - DEVELOPMENT_TEAM = NLTYK5T6U3; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES; @@ -612,6 +520,7 @@ }; 9829EC4C2E17BA3D00A9F8D3 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = A1C0F1A12F80000000C0F1A1 /* Base.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; @@ -646,7 +555,6 @@ COPY_PHASE_STRIP = NO; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEVELOPMENT_TEAM = NLTYK5T6U3; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES; @@ -676,11 +584,11 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; AUTOMATION_APPLE_EVENTS = NO; CODE_SIGN_ENTITLEMENTS = "Containers/Supporting Files/Containers.entitlements"; + CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 3; + CURRENT_PROJECT_VERSION = 1; DEAD_CODE_STRIPPING = YES; - DEVELOPMENT_TEAM = ZTW69M5NDR; ENABLE_APP_SANDBOX = YES; ENABLE_HARDENED_RUNTIME = YES; ENABLE_INCOMING_NETWORK_CONNECTIONS = YES; @@ -694,7 +602,9 @@ ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO; ENABLE_USER_SCRIPT_SANDBOXING = NO; ENABLE_USER_SELECTED_FILES = readwrite; + EXCLUDED_ARCHS = "x86-64"; GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = "Containers/Supporting Files/Info.plist"; INFOPLIST_KEY_CFBundleDisplayName = Containers; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity"; INFOPLIST_KEY_LSUIElement = YES; @@ -704,11 +614,12 @@ "$(inherited)", "@executable_path/../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 26.2; + MACOSX_DEPLOYMENT_TARGET = 26.0; MARKETING_VERSION = 0.1; OTHER_SWIFT_FLAGS = ""; PRODUCT_BUNDLE_IDENTIFIER = app.containers.Containers; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; REGISTER_APP_GROUPS = YES; RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO; RUNTIME_EXCEPTION_ALLOW_JIT = NO; @@ -731,11 +642,11 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; AUTOMATION_APPLE_EVENTS = NO; CODE_SIGN_ENTITLEMENTS = "Containers/Supporting Files/Containers.entitlements"; + CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 3; + CURRENT_PROJECT_VERSION = 1; DEAD_CODE_STRIPPING = YES; - DEVELOPMENT_TEAM = ZTW69M5NDR; ENABLE_APP_SANDBOX = YES; ENABLE_HARDENED_RUNTIME = YES; ENABLE_INCOMING_NETWORK_CONNECTIONS = YES; @@ -749,7 +660,9 @@ ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO; ENABLE_USER_SCRIPT_SANDBOXING = NO; ENABLE_USER_SELECTED_FILES = readwrite; + EXCLUDED_ARCHS = "x86-64"; GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = "Containers/Supporting Files/Info.plist"; INFOPLIST_KEY_CFBundleDisplayName = Containers; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity"; INFOPLIST_KEY_LSUIElement = YES; @@ -759,11 +672,12 @@ "$(inherited)", "@executable_path/../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 26.2; + MACOSX_DEPLOYMENT_TARGET = 26.0; MARKETING_VERSION = 0.1; OTHER_SWIFT_FLAGS = ""; PRODUCT_BUNDLE_IDENTIFIER = app.containers.Containers; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; REGISTER_APP_GROUPS = YES; RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO; RUNTIME_EXCEPTION_ALLOW_JIT = NO; @@ -821,61 +735,46 @@ /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ - 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */ = { + 77C44F192F698D0600167C4D /* XCRemoteSwiftPackageReference "containerization" */ = { isa = XCRemoteSwiftPackageReference; - repositoryURL = "https://github.com/apple/container"; + repositoryURL = "https://github.com/apple/containerization"; requirement = { kind = upToNextMajorVersion; - minimumVersion = 0.9.0; + minimumVersion = 0.28.0; }; }; /* End XCRemoteSwiftPackageReference section */ /* Begin XCSwiftPackageProductDependency section */ - 77350A732F35A14000C5471F /* ContainerAPIClient */ = { - isa = XCSwiftPackageProductDependency; - package = 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */; - productName = ContainerAPIClient; - }; - 77350A752F35A14000C5471F /* ContainerAPIService */ = { - isa = XCSwiftPackageProductDependency; - package = 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */; - productName = ContainerAPIService; - }; - 77350A772F35A14000C5471F /* ContainerBuild */ = { - isa = XCSwiftPackageProductDependency; - package = 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */; - productName = ContainerBuild; - }; - 77350A792F35A14000C5471F /* ContainerCommands */ = { + 77C44F1A2F698D0600167C4D /* Containerization */ = { isa = XCSwiftPackageProductDependency; - package = 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */; - productName = ContainerCommands; + package = 77C44F192F698D0600167C4D /* XCRemoteSwiftPackageReference "containerization" */; + productName = Containerization; }; - 77350A7B2F35A14000C5471F /* ContainerImagesService */ = { + 77C44F1C2F698D0600167C4D /* ContainerizationArchive */ = { isa = XCSwiftPackageProductDependency; - package = 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */; - productName = ContainerImagesService; + package = 77C44F192F698D0600167C4D /* XCRemoteSwiftPackageReference "containerization" */; + productName = ContainerizationArchive; }; - 77350A7D2F35A14000C5471F /* ContainerLog */ = { + 77C44F1E2F698D0600167C4D /* ContainerizationEXT4 */ = { isa = XCSwiftPackageProductDependency; - package = 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */; - productName = ContainerLog; + package = 77C44F192F698D0600167C4D /* XCRemoteSwiftPackageReference "containerization" */; + productName = ContainerizationEXT4; }; - 77350A7F2F35A14000C5471F /* ContainerNetworkService */ = { + 77C44F202F698D0600167C4D /* ContainerizationExtras */ = { isa = XCSwiftPackageProductDependency; - package = 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */; - productName = ContainerNetworkService; + package = 77C44F192F698D0600167C4D /* XCRemoteSwiftPackageReference "containerization" */; + productName = ContainerizationExtras; }; - 77350A812F35A14000C5471F /* ContainerPersistence */ = { + 77C44F222F698D0600167C4D /* ContainerizationIO */ = { isa = XCSwiftPackageProductDependency; - package = 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */; - productName = ContainerPersistence; + package = 77C44F192F698D0600167C4D /* XCRemoteSwiftPackageReference "containerization" */; + productName = ContainerizationIO; }; - 77350A9F2F35A32300C5471F /* ContainerSandboxService */ = { + 77C44F242F698E9A00167C4D /* ContainerizationOCI */ = { isa = XCSwiftPackageProductDependency; - package = 77350A722F35A14000C5471F /* XCRemoteSwiftPackageReference "container" */; - productName = ContainerSandboxService; + package = 77C44F192F698D0600167C4D /* XCRemoteSwiftPackageReference "containerization" */; + productName = ContainerizationOCI; }; /* End XCSwiftPackageProductDependency section */ }; diff --git a/Containers.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Containers.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 30da74b..919434a 100644 --- a/Containers.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/Containers.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -4,7 +4,4 @@ - - diff --git a/Containers.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/Containers.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..0c67376 --- /dev/null +++ b/Containers.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,5 @@ + + + + + diff --git a/Containers.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Containers.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 44a5e1c..b48f2b1 100644 --- a/Containers.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Containers.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "e64e90ec67fe8191ed3224e151bf12e0b1f35eb998fe2f56be48dfdedf6cc320", + "originHash" : "bf267a3d407ae7e6ed913576e17f1ea11f47ddc5955b04771eb158664fe3319a", "pins" : [ { "identity" : "async-http-client", @@ -11,30 +11,39 @@ } }, { - "identity" : "container", + "identity" : "containerization", "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/container", + "location" : "https://github.com/apple/containerization.git", "state" : { - "revision" : "3e49dcef4e48121fb26a7e41f8730d7a81f5c3be", - "version" : "0.9.0" + "revision" : "f8a18e8dcd965eefcfe65ead986405533c7e3872", + "version" : "0.32.1" } }, { - "identity" : "containerization", + "identity" : "grpc-swift-2", "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/containerization.git", + "location" : "https://github.com/grpc/grpc-swift-2.git", "state" : { - "revision" : "c3fe889a2f739ee4a9b0faccedd9f36f3862dc29", - "version" : "0.24.5" + "revision" : "21fe69ab7ce0e87ac089534733c52f037e74a3eb", + "version" : "2.4.1" } }, { - "identity" : "grpc-swift", + "identity" : "grpc-swift-nio-transport", "kind" : "remoteSourceControl", - "location" : "https://github.com/grpc/grpc-swift.git", + "location" : "https://github.com/grpc/grpc-swift-nio-transport.git", "state" : { - "revision" : "a56a157218877ef3e9625f7e1f7b2cb7e46ead1b", - "version" : "1.26.1" + "revision" : "f37e0c2d293cea668b11e10e1fb1c24cb40781ff", + "version" : "2.4.4" + } + }, + { + "identity" : "grpc-swift-protobuf", + "kind" : "remoteSourceControl", + "location" : "https://github.com/grpc/grpc-swift-protobuf.git", + "state" : { + "revision" : "8723cf856dc23d9c2fad4d874e7b9ed3254acf03", + "version" : "2.3.0" } }, { @@ -51,8 +60,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-argument-parser.git", "state" : { - "revision" : "309a47b2b1d9b5e991f36961c983ecec72275be3", - "version" : "1.6.1" + "revision" : "c5d11a805e765f52ba34ec7284bd4fcd6ba68615", + "version" : "1.7.0" } }, { @@ -132,8 +141,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-log.git", "state" : { - "revision" : "ce592ae52f982c847a4efc0dd881cc9eb32d29f2", - "version" : "1.6.4" + "revision" : "bbd81b6725ae874c69e9b8c8804d462356b55523", + "version" : "1.10.1" } }, { @@ -213,8 +222,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-system.git", "state" : { - "revision" : "395a77f0aa927f0ff73941d7ac35f2b46d47c9db", - "version" : "1.6.3" + "revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df", + "version" : "1.6.4" } }, { diff --git a/Containers.xcodeproj/xcshareddata/xcschemes/App Store.xcscheme b/Containers.xcodeproj/xcshareddata/xcschemes/Containers (macOS).xcscheme similarity index 89% rename from Containers.xcodeproj/xcshareddata/xcschemes/App Store.xcscheme rename to Containers.xcodeproj/xcshareddata/xcschemes/Containers (macOS).xcscheme index 55370ce..0882f9a 100644 --- a/Containers.xcodeproj/xcshareddata/xcschemes/App Store.xcscheme +++ b/Containers.xcodeproj/xcshareddata/xcschemes/Containers (macOS).xcscheme @@ -66,7 +66,7 @@ @@ -80,6 +80,19 @@ ReferencedContainer = "container:Containers.xcodeproj"> + + + + + + + + diff --git a/Containers.xcodeproj/xcshareddata/xcschemes/Development.xcscheme b/Containers.xcodeproj/xcshareddata/xcschemes/Development.xcscheme deleted file mode 100644 index a2d4a28..0000000 --- a/Containers.xcodeproj/xcshareddata/xcschemes/Development.xcscheme +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Containers/ContainersApp.swift b/Containers/ContainersApp.swift index d69d89d..454d9f6 100644 --- a/Containers/ContainersApp.swift +++ b/Containers/ContainersApp.swift @@ -8,12 +8,13 @@ import AppKit import ContainerSystem import SwiftUI +import TipKit class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { // Start with dock icon showing since dashboard opens on launch NSApp.setActivationPolicy(.regular) - + // Observe window close notifications NotificationCenter.default.addObserver( self, @@ -22,10 +23,10 @@ class AppDelegate: NSObject, NSApplicationDelegate { object: nil ) } - + @objc func windowWillClose(_ notification: Notification) { guard let window = notification.object as? NSWindow else { return } - + // Check if this is the dashboard window by title if window.title == "Containers" { // Hide dock icon immediately when dashboard closes @@ -38,51 +39,176 @@ class AppDelegate: NSObject, NSApplicationDelegate { @main struct ContainersApp: App { - static let dashboardWindowId = "dashboard" - @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate - + + // MARK: Domain Managers @State private var containerManager = ContainerManager() @State private var imageManager = ImageManager() @State private var volumeManager = VolumeManager() - @State private var builderManager = BuilderManager() - @State private var systemManager = SystemManager() - @State private var dnsManager = DNSManager() - + @State private var networkManager = NetworkManager() + @State private var reportManager: ReportManager + @State private var systemManager: SystemManager + + // MARK: Utilities + @State private var activityCenter: ActivityCenter + @State private var systemActions: SystemActions + + init() { + let systemManager = SystemManager() + let reportManager = ReportManager() + + _systemManager = State(initialValue: systemManager) + _reportManager = State(initialValue: reportManager) + _activityCenter = State(initialValue: ActivityCenter(reports: reportManager)) + _systemActions = State(initialValue: SystemActions(manager: systemManager)) + + do { + try Tips.configure() + } catch { + print("TipKit configuration error: \(error)") + } + } + + static let dashboardWindowID = "dashboard" + static let settingsWindowID = "settings" + static let containerDetailWindowID = "container-detail" + static let imageDetailWindowID = "image-detail" + static let volumeDetailWindowID = "volume-detail" + static let reportDetailWindowID = "report-detail" + var body: some Scene { - - Window("Containers", id: Self.dashboardWindowId, content: { - DashboardView() - .environment(containerManager) - .environment(imageManager) - .environment(volumeManager) - .environment(builderManager) - .environment(systemManager) - .environment(dnsManager) - .onAppear { - // Show dock icon when dashboard appears - NSApp.setActivationPolicy(.regular) - } - }) + Window( + "Containers", + id: Self.dashboardWindowID, + content: { + DashboardView() + .environment(containerManager) + .environment(imageManager) + .environment(volumeManager) + .environment(systemManager) + .environment(networkManager) + .environment(activityCenter) + .environment(reportManager) + .environment(systemActions) + .onAppear { + // Show dock icon when dashboard appears + NSApp.setActivationPolicy(.regular) + } + } + ) .defaultSize(width: 800, height: 520) .defaultPosition(.center) .windowResizability(.contentSize) + // Links into the app are the dashboard's to open. + .handlesExternalEvents(matching: ["\(AppLink.scheme)://"]) - MenuBarExtra(content: { - MenuBarItem() - .environment(systemManager) - }, label: { - Image(systemManager.isRunning ? "server.play" : "server.pause") - }) + MenuBarExtra( + content: { + MenuBarItem() + .environment(systemManager) + .environment(systemActions) + }, + label: { + Image( + systemManager.status == .running + ? "container.stack.fill" : "container.stack" + ) + .font(.system(size: 28)) + } + ) .menuBarExtraStyle(.menu) - - Settings { + + Window("Settings", id: Self.settingsWindowID) { SettingsView() - .environment(dnsManager) - .fixedSize(horizontal: true, vertical: true) + .environment(networkManager) + .environment(systemManager) } .defaultSize(width: 600, height: 400) .defaultPosition(.center) - .windowResizability(.contentSize) + .handlesExternalEvents(matching: []) + .commands { PreferencesCommands() } + + windowGroup( + "Container Details", + id: Self.containerDetailWindowID, + placeholder: DetailPlaceholder.container + ) { id in + ContainerDetailWindow(id: id) + .environment(containerManager) + .environment(volumeManager) + .environment(imageManager) + .environment(reportManager) + .environment(activityCenter) + } + + windowGroup( + "Image Details", + id: Self.imageDetailWindowID, + placeholder: DetailPlaceholder.image + ) { reference in + ImageDetailWindow(imageReference: reference) + .environment(imageManager) + .environment(containerManager) + .environment(volumeManager) + .environment(activityCenter) + .environment(reportManager) + } + + windowGroup( + "Volume Details", + id: Self.volumeDetailWindowID, + placeholder: DetailPlaceholder.volume + ) { volumeID in + VolumeDetailWindow(id: volumeID) + .environment(volumeManager) + .environment(reportManager) + } + + windowGroup( + "Report", + id: Self.reportDetailWindowID, + placeholder: DetailPlaceholder.report + ) { reportID in + ReportDetailWindow(id: reportID) + .environment(reportManager) + } + } + + /// A detail window group, keyed by the id of what it shows. + private func windowGroup( + _ title: String, + id: String, + placeholder: CGSize, + @ViewBuilder content: @escaping (String) -> Content + ) -> some Scene { + WindowGroup(title, id: id, for: String.self) { $value in + if let value { + content(value) + } + } + .windowResizability(.contentMinSize) + .restorationBehavior(.disabled) + // Left alone, a window group opens an empty window of its own for a link meant for the dashboard. + .handlesExternalEvents(matching: []) + .defaultWindowPlacement { _, context in + DetailPlaceholder.underParentToolbar( + on: context.defaultDisplay.visibleRect, + size: placeholder + ) + } + .commandsRemoved() + } + + struct PreferencesCommands: Commands { + @Environment(\.openWindow) private var openWindow + var body: some Commands { + CommandGroup(replacing: .appSettings) { + Button { + openWindow(id: ContainersApp.settingsWindowID) + } label: { + Label("Settings...", systemImage: "gearshape") + } + } + } } } diff --git a/Containers/Controllers/DashboardToolbarController+Items.swift b/Containers/Controllers/DashboardToolbarController+Items.swift new file mode 100644 index 0000000..b515465 --- /dev/null +++ b/Containers/Controllers/DashboardToolbarController+Items.swift @@ -0,0 +1,133 @@ +// +// DashboardToolbarController+Items.swift +// Containers +// +// Created by Axel Martinez on 02/08/2026. +// + +import AppKit + +extension DashboardToolbarController: NSToolbarDelegate { + func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + Self.identifiers + } + + func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + Self.identifiers + } + + /// Hides unused items on insert, since AppKit can fill the toolbar after the + /// last update. It fills in order, so the item's index is the current count. + func toolbarWillAddItem(_ notification: Notification) { + guard let toolbar = notification.object as? NSToolbar, + let item = notification.userInfo?["item"] as? NSToolbarItem + else { + return + } + + item.isHidden = !isShown(item.itemIdentifier, at: toolbar.items.count) + } + + func toolbar( + _ toolbar: NSToolbar, + itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, + willBeInsertedIntoToolbar flag: Bool + ) -> NSToolbarItem? { + switch itemIdentifier { + case Self.filterIdentifier: filterItem(itemIdentifier) + case Self.addIdentifier: + buttonItem( + itemIdentifier, label: "New", toolTip: "New", + symbolName: "plus", isEnabled: isEnabled, + action: #selector(addInvoked)) + case Self.clearIdentifier: + buttonItem( + itemIdentifier, label: "Clear", + toolTip: "Clear all errors", + symbolName: "xmark.octagon", isEnabled: isEnabled, + action: #selector(clearInvoked)) + case Self.searchIdentifier: searchItem(itemIdentifier) + default: + SelectionToolbarItem(rawValue: itemIdentifier.rawValue) + .map(selectionItem) + } + } + + /// A one-entry group, since only `.selectAny` draws an on state. + private func filterItem(_ identifier: NSToolbarItem.Identifier) -> NSToolbarItemGroup { + let title = "Running containers only" + let image = + NSImage( + systemSymbolName: "line.3.horizontal.decrease", + accessibilityDescription: title + ) ?? NSImage() + + let group = NSToolbarItemGroup( + itemIdentifier: identifier, + images: [image], + selectionMode: .selectAny, + labels: [title], + target: self, + action: #selector(filterToggled) + ) + group.setSelected(isFilterOn, at: 0) + group.isEnabled = isEnabled + group.toolTip = title + return group + } + + private func selectionItem(_ item: SelectionToolbarItem) -> NSToolbarItem { + buttonItem( + NSToolbarItem.Identifier(item.rawValue), label: item.label, + toolTip: item.toolTip, symbolName: item.symbolName, + isEnabled: isEnabled && enabledSelectionItems.contains(item), + action: #selector(selectionItemInvoked)) + } + + private func buttonItem( + _ identifier: NSToolbarItem.Identifier, + label: String, + toolTip: String, + symbolName: String, + isEnabled: Bool, + action: Selector + ) -> NSToolbarItem { + let item = NSToolbarItem(itemIdentifier: identifier) + item.label = label + item.paletteLabel = label + item.toolTip = toolTip + item.image = NSImage( + systemSymbolName: symbolName, + accessibilityDescription: label + ) + item.isBordered = true + // Enabled from SwiftUI state; AppKit's responder-chain check would always fail. + item.autovalidates = false + item.isEnabled = isEnabled + item.target = self + item.action = action + return item + } + + @objc private func filterToggled(_ sender: NSToolbarItemGroup) { + onToggleFilter(sender.isSelected(at: 0)) + } + + @objc private func addInvoked(_ sender: NSToolbarItem) { + onAdd() + } + + @objc private func clearInvoked(_ sender: NSToolbarItem) { + onClear() + } + + @objc private func selectionItemInvoked(_ sender: NSToolbarItem) { + guard + let item = SelectionToolbarItem( + rawValue: sender.itemIdentifier.rawValue + ) + else { return } + + onSelectionItem(item) + } +} diff --git a/Containers/Controllers/DashboardToolbarController+Search.swift b/Containers/Controllers/DashboardToolbarController+Search.swift new file mode 100644 index 0000000..29d6ba7 --- /dev/null +++ b/Containers/Controllers/DashboardToolbarController+Search.swift @@ -0,0 +1,143 @@ +// +// DashboardToolbarController+Search.swift +// Containers +// +// Created by Axel Martinez on 02/08/2026. +// + +import AppKit + +extension DashboardToolbarController { + func searchItem(_ identifier: NSToolbarItem.Identifier) -> NSSearchToolbarItem { + let item = NSSearchToolbarItem(itemIdentifier: identifier) + let field = SearchField() + item.searchField = field + + field.onChooseTokenOption = { [weak self] index, title in + self?.onChooseSearchTokenOption(index, title) + } + + field.placeholderString = "Search" + field.delegate = self + // Tokens are attachments, so the field must accept attributed text. + field.allowsEditingTextAttributes = true + field.isEnabled = isEnabled + + // The preferred width is only a minimum, so the maximum is capped too. + item.preferredWidthForSearchField = 176 + field.widthAnchor.constraint(lessThanOrEqualToConstant: 260).isActive = true + item.resignsFirstResponderWithCancel = true + item.isEnabled = isEnabled + + show(in: field) + + return item + } + + /// Writes to the editor while typing, since setting the field's value would end + /// editing and lose the caret. + func show(in field: NSSearchField) { + let contents = Self.contents(of: field) + + guard + contents.searchTokens != searchTokens + || contents.searchFieldText != searchText + else { + return + } + + let wanted = NSAttributedString.searchField( + tokens: searchTokens, + text: searchText, + font: field.font ?? .systemFont(ofSize: NSFont.systemFontSize) + ) + + guard let editor = field.currentEditor() as? NSTextView else { + field.attributedStringValue = wanted + + return + } + + editor.textStorage?.setAttributedString(wanted) + editor.setSelectedRange( + NSRange(location: wanted.length, length: 0) + ) + } + + /// Read from the editor while typing, since the field's value lags until editing ends. + static func contents(of field: NSSearchField) -> NSAttributedString { + guard let editor = field.currentEditor() as? NSTextView, + let storage = editor.textStorage + else { + return field.attributedStringValue + } + + return NSAttributedString(attributedString: storage) + } +} + +extension DashboardToolbarController: NSSearchFieldDelegate { + func controlTextDidChange(_ obj: Notification) { + guard let field = obj.object as? NSSearchField else { return } + + let contents = Self.contents(of: field) + + // Removed here too, so reordering the rest doesn't restore it. + let deleted = deletedTokens(keeping: contents.searchTokens) + + if !deleted.isEmpty { + searchTokens = searchTokens.enumerated() + .filter { !deleted.contains($0.offset) } + .map(\.element) + + onDeleteSearchTokens(deleted) + } + + // Tokens always go first, even if text is typed in front of them. + if !contents.hasSearchTokensInFront { + searchText = contents.searchFieldText + show(in: field) + onSearch(searchText) + + return + } + + searchText = contents.searchFieldText + onSearch(searchText) + } + + /// Return turns the text into a token where the section supports it, as in Console. + func control( + _ control: NSControl, + textView: NSTextView, + doCommandBy commandSelector: Selector + ) -> Bool { + let text = searchText.trimmingCharacters(in: .whitespaces) + + guard commandSelector == #selector(NSResponder.insertNewline(_:)), + let onSubmitSearch, !text.isEmpty + else { + return false + } + + onSubmitSearch(text) + + return true + } + + /// Indices of tokens no longer in the field; the rest keep their order. + private func deletedTokens(keeping kept: [SearchToken]) -> IndexSet { + var kept = kept[...] + var deleted = IndexSet() + + for (index, token) in searchTokens.enumerated() { + if kept.first == token { + kept.removeFirst() + } else { + deleted.insert(index) + } + } + + return deleted + } +} diff --git a/Containers/Controllers/DashboardToolbarController.swift b/Containers/Controllers/DashboardToolbarController.swift new file mode 100644 index 0000000..aef444a --- /dev/null +++ b/Containers/Controllers/DashboardToolbarController.swift @@ -0,0 +1,239 @@ +// +// DashboardToolbarController.swift +// Containers +// +// Created by Axel Martinez on 02/08/2026. +// + +import AppKit +import SwiftUI + +/// Builds the dashboard window's toolbar in AppKit to allow more customization than SwiftUI. +@MainActor +final class DashboardToolbarController: NSObject { + var isEnabled = true + var title = "" + var showsFilter = false + var showsAdd = true + var showsClear = false + var isFilterOn = false + var selectionItems: [SelectionToolbarItem] = [] + var enabledSelectionItems: Set = [] + var searchText = "" + + var searchTokens: [SearchToken] = [] + + /// The section decides what deleting a token means; the field only shows them. + var onDeleteSearchTokens: (IndexSet) -> Void = { _ in } + + /// The token's index and the chosen option's title. + var onChooseSearchTokenOption: (Int, String) -> Void = { _, _ in } + + /// `nil` where Return only searches. + var onSubmitSearch: ((String) -> Void)? + + var onToggleFilter: (Bool) -> Void = { _ in } + var onAdd: () -> Void = {} + var onClear: () -> Void = {} + var onSelectionItem: (SelectionToolbarItem) -> Void = { _ in } + var onSearch: (String) -> Void = { _ in } + /// Presented here, since `.popoverTip` can't attach to an AppKit toolbar item. + var addTip: AnyView? + var runTip: AnyView? + + /// Shown under the toolbar, in the titlebar. + var accessory: AnyView? + + static let filterIdentifier = NSToolbarItem.Identifier("filter") + static let addIdentifier = NSToolbarItem.Identifier("add") + static let clearIdentifier = NSToolbarItem.Identifier("clear") + static let searchIdentifier = NSToolbarItem.Identifier("search") + + private weak var window: NSWindow? + + /// Keyed by the anchoring button's label. + private var tipPopovers: [String: NSPopover] = [:] + + /// Installed once and hidden when unused, so the toolbar isn't laid out again. + private let accessoryController: NSTitlebarAccessoryViewController = { + let controller = NSTitlebarAccessoryViewController() + controller.layoutAttribute = .bottom + controller.view = NSHostingView(rootView: AnyView(EmptyView())) + controller.isHidden = true + return controller + }() + + func attach(to window: NSWindow) { + guard self.window !== window else { return } + + self.window = window + + let toolbar = NSToolbar(identifier: "dashboard") + toolbar.delegate = self + toolbar.allowsUserCustomization = false + toolbar.allowsDisplayModeCustomization = false + toolbar.autosavesConfiguration = false + toolbar.displayMode = .iconOnly + + window.toolbar = toolbar + window.toolbarStyle = .unified + window.addTitlebarAccessoryViewController(accessoryController) + + applyChrome() + } + + /// Opaque, though transparent would drop the divider: over the content, the + /// glass goes darker than the search tokens. Reapplied on every update, since + /// window setup changes it once after the items are installed. + private func applyChrome() { + guard let window else { return } + + if window.title != title { + window.title = title + } + + if window.titleVisibility != .visible { + window.titleVisibility = .visible + } + + if window.titlebarAppearsTransparent { + window.titlebarAppearsTransparent = false + } + } + + /// Every section's items, always installed; each section hides what it doesn't use, + /// since inserting an item briefly collapses the search field. + static let identifiers: [NSToolbarItem.Identifier] = + [.toggleSidebar, .sidebarTrackingSeparator, .flexibleSpace, filterIdentifier] + + [SelectionToolbarItem.start, .stop, .run, .details, .delete].map { + NSToolbarItem.Identifier($0.rawValue) + } + // List actions, set apart from the row actions. + + [.space, clearIdentifier, addIdentifier, .space, searchIdentifier] + + func isShown(_ identifier: NSToolbarItem.Identifier, at index: Int) -> Bool { + switch identifier { + case Self.filterIdentifier: + return showsFilter + case Self.clearIdentifier: + return showsClear + case Self.addIdentifier: + return showsAdd + case .space: + // The first separates row and list actions, so it needs a list action. + let isBetweenGroups = + index == Self.identifiers.firstIndex(of: .space) + + return !isBetweenGroups || showsClear || showsAdd + default: + guard let item = SelectionToolbarItem(rawValue: identifier.rawValue) + else { + return true + } + + return selectionItems.contains(item) + } + } + + func update() { + guard let toolbar = window?.toolbar else { return } + + applyChrome() + + // Hidden items too, or they'd show stale state when the next section shows them. + for (index, item) in toolbar.items.enumerated() { + let isHidden = !isShown(item.itemIdentifier, at: index) + + if item.isHidden != isHidden { + item.isHidden = isHidden + } + + switch item.itemIdentifier { + case Self.filterIdentifier: + guard let group = item as? NSToolbarItemGroup else { break } + if group.isSelected(at: 0) != isFilterOn { + group.setSelected(isFilterOn, at: 0) + } + case Self.searchIdentifier: + guard let search = item as? NSSearchToolbarItem else { break } + + search.searchField.isEnabled = isEnabled + show(in: search.searchField) + default: + break + } + + if let selectionItem = SelectionToolbarItem( + rawValue: item.itemIdentifier.rawValue + ) { + item.isEnabled = + isEnabled && enabledSelectionItems.contains(selectionItem) + } else { + item.isEnabled = isEnabled + } + } + + syncTip(addTip, anchoredTo: "New") + syncTip(runTip, anchoredTo: "Run") + syncAccessory() + } + + private func syncAccessory() { + guard let accessory, + let hostingView = accessoryController.view as? NSHostingView + else { + if !accessoryController.isHidden { + accessoryController.isHidden = true + } + + return + } + + hostingView.rootView = accessory + hostingView.frame.size.height = hostingView.fittingSize.height + + if accessoryController.isHidden { + accessoryController.isHidden = false + } + } + + private func syncTip(_ tip: AnyView?, anchoredTo label: String) { + guard let tip else { + tipPopovers[label]?.close() + tipPopovers[label] = nil + return + } + + guard tipPopovers[label] == nil, let anchor = buttonView(labeled: label) + else { return } + + let popover = NSPopover() + popover.behavior = .transient + popover.contentViewController = NSHostingController( + rootView: tip.frame(width: 260) + ) + popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .minY) + tipPopovers[label] = popover + } + + /// Found by accessibility label, since a standard item doesn't expose its `view`. + private func buttonView(labeled label: String) -> NSView? { + guard let root = window?.contentView?.superview else { return nil } + + func walk(_ view: NSView) -> NSView? { + if view.accessibilityRole() == .button, + view.accessibilityLabel() == label + { + return view + } + + for subview in view.subviews { + if let found = walk(subview) { return found } + } + + return nil + } + + return walk(root) + } +} diff --git a/Containers/Controllers/DetailToolbarController.swift b/Containers/Controllers/DetailToolbarController.swift new file mode 100644 index 0000000..888c174 --- /dev/null +++ b/Containers/Controllers/DetailToolbarController.swift @@ -0,0 +1,352 @@ +// +// DetailToolbarController.swift +// Containers +// +// Created by Axel Martinez on 02/08/2026. +// + +import AppKit +import SwiftUI + +/// Built in AppKit because the tabs need an `NSToolbarItemGroup`: one control with a +/// label per entry. SwiftUI flattens a `ToolbarItemGroup` into separate items. +@MainActor +final class DetailToolbarController: NSObject, NSToolbarDelegate { + struct Tab: Equatable { + let title: String + let icon: String + } + + var tabs: [Tab] = [] + var selectedIndex = 0 + var items: [DetailToolbarItem] = [] + var onSelectTab: (Int) -> Void = { _ in } + + private static let tabsIdentifier = NSToolbarItem.Identifier("tabs") + + /// Unique per window: AppKit repeats inserts across toolbars sharing an + /// identifier, which collide with existing items. The display mode is shared + /// through the defaults instead. + private let toolbarIdentifier = NSToolbar.Identifier( + "detail-\(UUID().uuidString)" + ) + private static let displayModeKey = "detailToolbarDisplayMode" + + private static var savedDisplayMode: NSToolbar.DisplayMode? { + let raw = UserDefaults.standard.object(forKey: displayModeKey) + guard let raw = raw as? UInt else { return nil } + let mode = NSToolbar.DisplayMode(rawValue: raw) + return mode == .default ? nil : mode + } + + private weak var window: NSWindow? + private var displayModeObservation: NSKeyValueObservation? + private var isRebuildingTabs = false + private var hasSettled = false + private var builtShowingLabels: Bool? + private var builtFrom: [String] = [] + private var appearances: [NSToolbarItem.Identifier: Appearance] = [:] + + func attach(to window: NSWindow) { + guard self.window !== window else { return } + self.window = window + + let toolbar = NSToolbar(identifier: toolbarIdentifier) + toolbar.delegate = self + toolbar.allowsUserCustomization = false + toolbar.displayMode = Self.savedDisplayMode ?? .iconOnly + builtFrom = shape + + window.toolbar = toolbar + window.toolbarStyle = .unified + + // Labels are usually wider than the icons, so the tabs are rebuilt. + displayModeObservation = toolbar.observe( + \.displayMode, + options: [.initial, .new] + ) { toolbar, _ in + MainActor.assumeIsolated { + UserDefaults.standard.set( + toolbar.displayMode.rawValue, + forKey: Self.displayModeKey + ) + self.scheduleTabRebuild() + } + } + } + + /// Returns once the toolbar is installed and done resizing, or on timeout. + /// It lands a turn after the view, so sizing earlier leaves the window short. + func whenSettled(timeout: Duration) async { + let deadline = ContinuousClock.now.advanced(by: timeout) + + while !hasSettled, ContinuousClock.now < deadline { + await Task.yield() + try? await Task.sleep(for: .milliseconds(8)) + } + } + + /// Rebuilt because new images don't resize a laid-out item. Deferred and guarded, + /// since changing items re-reports the display mode, which calls back here. + private func scheduleTabRebuild() { + guard !isRebuildingTabs, builtShowingLabels != showsLabels else { + if !isRebuildingTabs { hasSettled = true } + return + } + + isRebuildingTabs = true + + Task { @MainActor in + rebuildTabs() + isRebuildingTabs = false + + // The mode can change again while a rebuild is pending. + scheduleTabRebuild() + } + } + + private func rebuildTabs() { + builtShowingLabels = showsLabels + + guard + let toolbar = window?.toolbar, + let index = toolbar.items.firstIndex(where: { + $0.itemIdentifier == Self.tabsIdentifier + }) + else { return } + + toolbar.removeItem(at: index) + toolbar.insertItem(withItemIdentifier: Self.tabsIdentifier, at: index) + } + + private var showsLabels: Bool { + switch window?.toolbar?.displayMode { + case .iconAndLabel, .labelOnly: true + default: false + } + } + + /// A tab is only as wide as its image, so the image is padded to fit the label. + private var tabImages: [NSImage] { + let font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize) + + return tabs.map { tab in + let image = + NSImage( + systemSymbolName: tab.icon, + accessibilityDescription: tab.title + ) ?? NSImage() + + guard showsLabels else { return image } + + let caption = tab.title as NSString + let width = caption.size(withAttributes: [.font: font]).width + // The caption alone; the toolbar adds its own padding. + return image.widened(to: ceil(width)) + } + } + + func update() { + guard let toolbar = window?.toolbar else { return } + + guard builtFrom == shape else { + if rebuild(toolbar) { + builtFrom = shape + } + + return + } + + for item in toolbar.items { + if let group = item as? NSToolbarItemGroup { + if group.selectedIndex != selectedIndex { + group.selectedIndex = selectedIndex + } + } else if let detailItem = detailItem(for: item.itemIdentifier) { + // Run becoming Stop, or a report badge appearing, changes the item in place. + apply(detailItem, to: item) + } + } + } + + /// Changes here rebuild the toolbar; other state is applied in place. + private var shape: [String] { + leadingItems.map(\.id) + tabs.map(\.title) + ["·"] + + trailingItems.map(\.id) + } + + private var leadingItems: [DetailToolbarItem] { + items.filter(\.isLeading) + } + + private var trailingItems: [DetailToolbarItem] { + items.filter { !$0.isLeading } + } + + /// Unanimated, so items don't fade in after the opening window's title. + private func rebuild(_ toolbar: NSToolbar) -> Bool { + var shaped = false + + NSAnimationContext.runAnimationGroup { context in + context.duration = 0 + + shaped = toolbar.setShape(identifiers) + } + + return shaped + } + + private var identifiers: [NSToolbarItem.Identifier] { + var result: [NSToolbarItem.Identifier] = [] + + result += leadingItems.map { NSToolbarItem.Identifier($0.id) } + + if !tabs.isEmpty { + // Leaves room for a badge drawn past the last leading item's edge. + if !leadingItems.isEmpty { + result.append(.space) + } + + result.append(Self.tabsIdentifier) + result.append(.flexibleSpace) + } + + result += trailingItems.map { NSToolbarItem.Identifier($0.id) } + + return result + } + + private func detailItem(for identifier: NSToolbarItem.Identifier) -> DetailToolbarItem? { + items.first { $0.id == identifier.rawValue } + } + + /// Only changes are written, since new images trigger a toolbar layout. + private struct Appearance: Equatable { + let title: String + let help: String + let icon: String + let isHidden: Bool + + init(_ detailItem: DetailToolbarItem) { + self.title = detailItem.title + self.help = detailItem.help + self.icon = detailItem.icon + self.isHidden = detailItem.isHidden + } + } + + private func apply(_ detailItem: DetailToolbarItem, to item: NSToolbarItem) { + item.isEnabled = detailItem.isEnabled + + let appearance = Appearance(detailItem) + + guard appearances[item.itemIdentifier] != appearance else { return } + + appearances[item.itemIdentifier] = appearance + + item.label = detailItem.title + item.paletteLabel = detailItem.title + item.toolTip = detailItem.help + item.isHidden = detailItem.isHidden + + item.image = image(for: detailItem) + } + + /// A system symbol, or else a badged one from the asset catalog. + /// + /// Badged symbols draw their badge, the primary layer, in red and the rest + /// in the label color. Multicolor would draw the rest too dark in Dark Mode. + private func image(for detailItem: DetailToolbarItem) -> NSImage? { + if let symbol = NSImage(systemSymbolName: detailItem.icon, accessibilityDescription: detailItem.title) { + return symbol + } + + let symbol = NSImage(named: detailItem.icon) + symbol?.accessibilityDescription = detailItem.title + return symbol?.withSymbolConfiguration(.init(paletteColors: [.systemRed, .labelColor])) + } + + // MARK: - NSToolbarDelegate + + func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + identifiers + } + + func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + identifiers + } + + func toolbar( + _ toolbar: NSToolbar, + itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, + willBeInsertedIntoToolbar flag: Bool + ) -> NSToolbarItem? { + if itemIdentifier == Self.tabsIdentifier { + return tabGroup(itemIdentifier) + } + + guard let detailItem = detailItem(for: itemIdentifier) else { return nil } + return buttonItem(itemIdentifier, for: detailItem) + } + + private func tabGroup(_ identifier: NSToolbarItem.Identifier) -> NSToolbarItemGroup { + let group = NSToolbarItemGroup( + itemIdentifier: identifier, + images: tabImages, + selectionMode: .selectOne, + labels: tabs.map(\.title), + target: self, + action: #selector(tabSelected) + ) + group.selectedIndex = selectedIndex + group.visibilityPriority = .high + group.controlRepresentation = .expanded + return group + } + + private func buttonItem( + _ identifier: NSToolbarItem.Identifier, + for detailItem: DetailToolbarItem + ) -> NSToolbarItem { + let item = NSToolbarItem(itemIdentifier: identifier) + item.isBordered = true + item.autovalidates = false + item.target = self + item.action = #selector(itemInvoked) + + appearances[identifier] = nil + apply(detailItem, to: item) + + return item + } + + @objc private func tabSelected(_ sender: NSToolbarItemGroup) { + onSelectTab(sender.selectedIndex) + } + + @objc private func itemInvoked(_ sender: NSToolbarItem) { + detailItem(for: sender.itemIdentifier)?.action() + } +} + +extension NSImage { + fileprivate func widened(to width: CGFloat) -> NSImage { + guard width > size.width else { return self } + + let padded = NSImage( + size: NSSize(width: width, height: size.height), + flipped: false + ) { [self] bounds in + draw( + at: NSPoint(x: (bounds.width - size.width) / 2, y: 0), + from: .zero, + operation: .sourceOver, + fraction: 1 + ) + return true + } + + padded.isTemplate = isTemplate + return padded + } +} diff --git a/Containers/Controllers/ReportToolbarController.swift b/Containers/Controllers/ReportToolbarController.swift new file mode 100644 index 0000000..c97793f --- /dev/null +++ b/Containers/Controllers/ReportToolbarController.swift @@ -0,0 +1,80 @@ +// +// ReportToolbarController.swift +// Containers +// +// Created by Axel Martinez on 16/09/2026. +// + +import AppKit +import SwiftUI + +/// Built in AppKit because SwiftUI's search field takes all the leftover width. +final class ReportToolbarController: NSObject, NSToolbarDelegate { + var onSearch: (String) -> Void = { _ in } + + private static let searchIdentifier = NSToolbarItem.Identifier("search") + + private weak var window: NSWindow? + + func attach(to window: NSWindow) { + guard self.window !== window else { return } + + self.window = window + + let toolbar = NSToolbar(identifier: "report") + toolbar.delegate = self + toolbar.allowsUserCustomization = false + toolbar.allowsDisplayModeCustomization = false + toolbar.autosavesConfiguration = false + toolbar.displayMode = .iconOnly + + window.toolbar = toolbar + window.toolbarStyle = .unified + } + + private var identifiers: [NSToolbarItem.Identifier] { + [.flexibleSpace, Self.searchIdentifier] + } + + // MARK: - NSToolbarDelegate + + func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + identifiers + } + + func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + identifiers + } + + func toolbar( + _ toolbar: NSToolbar, + itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, + willBeInsertedIntoToolbar flag: Bool + ) -> NSToolbarItem? { + guard itemIdentifier == Self.searchIdentifier else { return nil } + + return searchItem(itemIdentifier) + } + + /// The preferred width is only a minimum, so the maximum is capped too. + private func searchItem( + _ identifier: NSToolbarItem.Identifier + ) -> NSSearchToolbarItem { + let item = NSSearchToolbarItem(itemIdentifier: identifier) + item.searchField.placeholderString = "Search" + item.searchField.delegate = self + item.preferredWidthForSearchField = 192 + item.searchField.widthAnchor + .constraint(lessThanOrEqualToConstant: 192).isActive = true + item.resignsFirstResponderWithCancel = true + return item + } +} + +extension ReportToolbarController: NSSearchFieldDelegate { + func controlTextDidChange(_ obj: Notification) { + guard let field = obj.object as? NSSearchField else { return } + + onSearch(field.stringValue) + } +} diff --git a/Containers/Extensions/AppKit/NSToolbar+Shape.swift b/Containers/Extensions/AppKit/NSToolbar+Shape.swift new file mode 100644 index 0000000..6c7d116 --- /dev/null +++ b/Containers/Extensions/AppKit/NSToolbar+Shape.swift @@ -0,0 +1,80 @@ +// +// NSToolbar+Shape.swift +// Containers +// +// Created by Axel Martinez on 23/09/2026. +// + +import AppKit + +extension NSToolbar { + /// Changes only what differs, since emptying and refilling races AppKit's own + /// filling. Not for toolbars with a search field, which any insert collapses. + /// - Returns: Whether AppKit had filled the toolbar yet. + @discardableResult + func setShape(_ wanted: [NSToolbarItem.Identifier]) -> Bool { + guard !items.isEmpty else { return false } + + removeSurplus(of: wanted) + + for (index, identifier) in wanted.enumerated() { + let isInPlace = + index < items.count && items[index].itemIdentifier == identifier + + if !isInPlace { + place(identifier, at: index) + } + } + + while items.count > wanted.count { + removeItem(at: items.count - 1) + } + + return true + } + + /// Counted, since spacers repeat. The earliest copy goes, so later items keep their place. + private func removeSurplus(of wanted: [NSToolbarItem.Identifier]) { + var surplus: [NSToolbarItem.Identifier: Int] = [:] + + for item in items { + surplus[item.itemIdentifier, default: 0] += 1 + } + + for identifier in wanted { + surplus[identifier, default: 0] -= 1 + } + + var position = 0 + + while position < items.count { + let identifier = items[position].itemIdentifier + + guard let count = surplus[identifier], count > 0 else { + position += 1 + continue + } + + surplus[identifier] = count - 1 + removeItem(at: position) + } + } + + /// Moves an existing item, since a toolbar refuses duplicate identifiers. + private func place(_ identifier: NSToolbarItem.Identifier, at index: Int) { + guard + let current = items.firstIndex(where: { + $0.itemIdentifier == identifier + }) + else { + insertItem(withItemIdentifier: identifier, at: index) + return + } + + removeItem(at: current) + insertItem( + withItemIdentifier: identifier, + at: current < index ? index - 1 : index + ) + } +} diff --git a/Containers/Extensions/AppKit/NSView+ContentTable.swift b/Containers/Extensions/AppKit/NSView+ContentTable.swift new file mode 100644 index 0000000..b61a1ac --- /dev/null +++ b/Containers/Extensions/AppKit/NSView+ContentTable.swift @@ -0,0 +1,34 @@ +// +// NSView+ContentTable.swift +// Containers +// +// Created by Axel Martinez on 24/09/2026. +// + +import AppKit + +extension NSView { + /// The `NSTableView` behind a SwiftUI `Table`, found by walking up from this + /// view, since SwiftUI doesn't expose it. Skips the sidebar's source list. + var enclosingContentTable: NSTableView? { + var ancestor = superview + + while let current = ancestor { + let found = Self.tables(in: current).first { + $0.style != .sourceList + } + + if let found { return found } + + ancestor = current.superview + } + + return nil + } + + private static func tables(in view: NSView) -> [NSTableView] { + if let table = view as? NSTableView { return [table] } + + return view.subviews.flatMap(tables) + } +} diff --git a/Containers/Extensions/ContainerSystem/Report+Appearance.swift b/Containers/Extensions/ContainerSystem/Report+Appearance.swift new file mode 100644 index 0000000..c124d80 --- /dev/null +++ b/Containers/Extensions/ContainerSystem/Report+Appearance.swift @@ -0,0 +1,29 @@ +// +// Report+Appearance.swift +// Containers +// +// Created by Axel Martinez on 22/09/2026. +// + +import ContainerSystem +import SwiftUI + +extension Report { + /// Filled until read, hollow after. + var symbol: String { + let name = + switch level { + case .warning: "exclamationmark.triangle" + case .error: "xmark.octagon" + } + + return isRead ? name : "\(name).fill" + } + + var color: Color { + switch level { + case .warning: .yellow + case .error: .red + } + } +} diff --git a/Containers/Extensions/ContainerSystem/Report+DateText.swift b/Containers/Extensions/ContainerSystem/Report+DateText.swift new file mode 100644 index 0000000..50f4b40 --- /dev/null +++ b/Containers/Extensions/ContainerSystem/Report+DateText.swift @@ -0,0 +1,16 @@ +// +// Report+DateText.swift +// Containers +// +// Created by Axel Martinez on 02/10/2026. +// + +import ContainerSystem +import Foundation + +extension Report { + /// Shared by the table and date searches, so they match. + var dateText: String { + date.formatted(date: .abbreviated, time: .shortened) + } +} diff --git a/Containers/Extensions/ContainerSystem/SystemManager.Status+Message.swift b/Containers/Extensions/ContainerSystem/SystemManager.Status+Message.swift new file mode 100644 index 0000000..e5ddd77 --- /dev/null +++ b/Containers/Extensions/ContainerSystem/SystemManager.Status+Message.swift @@ -0,0 +1,69 @@ +// +// SystemManager.Status+Message.swift +// Containers +// +// Created by Axel Martinez on 17/09/2026. +// + +import AppKit +import ContainerSystem +import SwiftUI + +extension SystemManager.Status { + var message: String { + switch self { + case .running: "System running" + case .starting: "Starting system..." + case .stopping: "Stopping system..." + case .notStarted: "System stopped" + case .failed: "System failed to start" + } + } + + /// Names the system, since the menu bar has no window around it to say which. + var menuMessage: String { + switch self { + case .running: "Container System is running" + case .starting: "Container System is starting…" + case .stopping: "Container System is stopping…" + case .notStarted: "Container System is stopped" + case .failed: "Container System failed to start" + } + } + + /// Stopped and failed share a symbol; the colour tells them apart. + var symbol: String { + switch self { + case .running: "gauge.with.dots.needle.100percent" + case .starting: "gauge.with.dots.needle.33percent" + case .stopping: "gauge.with.dots.needle.67percent" + case .notStarted, .failed: "gauge.with.dots.needle.0percent" + } + } + + /// Darkened in light mode, where the system green reads faintly as text. + private static let runningGreen = NSColor(name: nil) { appearance in + let isDark = + appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua + + return isDark + ? .systemGreen + : NSColor.systemGreen.blended(withFraction: 0.3, of: .black) + ?? .systemGreen + } + + /// An `NSColor`, since AppKit paints the menu bar icon. + var nsColor: NSColor { + switch self { + case .running: Self.runningGreen + case .starting, .stopping: .systemOrange + // Grey, not red: a system asked to stop is not a fault. + case .notStarted: .secondaryLabelColor + case .failed: .systemRed + } + } + + var color: Color { + Color(nsColor: nsColor) + } +} diff --git a/Containers/Extensions/Foundation/Bundle+Version.swift b/Containers/Extensions/Foundation/Bundle+Version.swift new file mode 100644 index 0000000..b42ec64 --- /dev/null +++ b/Containers/Extensions/Foundation/Bundle+Version.swift @@ -0,0 +1,15 @@ +// +// Bundle+Version.swift +// Containers +// +// Created by Axel Martinez on 10/10/2026. +// + +import Foundation + +extension Bundle { + /// The marketing version, such as `1.2`. + var shortVersion: String { + infoDictionary?["CFBundleShortVersionString"] as? String ?? "" + } +} diff --git a/Containers/Extensions/Foundation/CGFloat+Layout.swift b/Containers/Extensions/Foundation/CGFloat+Layout.swift new file mode 100644 index 0000000..c648409 --- /dev/null +++ b/Containers/Extensions/Foundation/CGFloat+Layout.swift @@ -0,0 +1,21 @@ +// +// CGFloat+Layout.swift +// Containers +// +// Created by Axel Martinez on 10/08/2026. +// + +import Foundation + +extension CGFloat { + /// Set on the label: a macOS button keeps its intrinsic width whatever its frame. + static let sheetButtonLabelWidth: CGFloat = 64 + + static let fieldControlWidth: CGFloat = 260 + + /// Between a sheet's progress or failure mark and the text below it. + nonisolated static let sheetMarkSpacing: CGFloat = 12 + + /// Shared by every strip across a window, so scope bars and sheet tabs match. + static let barHeight: CGFloat = 30 +} diff --git a/Containers/Extensions/URL+Properties.swift b/Containers/Extensions/Foundation/URL+Properties.swift similarity index 80% rename from Containers/Extensions/URL+Properties.swift rename to Containers/Extensions/Foundation/URL+Properties.swift index a39c281..b0d91fa 100644 --- a/Containers/Extensions/URL+Properties.swift +++ b/Containers/Extensions/Foundation/URL+Properties.swift @@ -9,9 +9,9 @@ import Foundation extension URL { var parent: URL { - return self.appending(component: "..").standardized + self.appending(component: "..").standardized } - + var isFolder: Bool { (try? self.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false } diff --git a/Containers/Extensions/Foundation/UserDefaults+Settings.swift b/Containers/Extensions/Foundation/UserDefaults+Settings.swift new file mode 100644 index 0000000..2a55562 --- /dev/null +++ b/Containers/Extensions/Foundation/UserDefaults+Settings.swift @@ -0,0 +1,220 @@ +// +// SettingsManager.swift +// Containers +// +// Created by Axel Martinez on 02/02/26. +// + +import Foundation + +@propertyWrapper +struct UserDefault { + let key: String + let defaultValue: Value + var container: UserDefaults = UserDefaults.standard + + var wrappedValue: Value { + get { + container.object(forKey: key) as? Value ?? defaultValue + } + set { + container.set(newValue, forKey: key) + } + } +} + +extension UserDefaults { + @UserDefault(key: "lastSeenVersion", defaultValue: "") + static var lastSeenVersion: String + + @UserDefault(key: "lastSelectedTab", defaultValue: "images") + static var lastSelectedTab: String + + @UserDefault(key: "startSystemTimeoutSeconds", defaultValue: 10) + static var startSystemTimeoutSeconds: Int32 + + @UserDefault(key: "stopContainerTimeoutSeconds", defaultValue: 5) + static var stopContainerTimeoutSeconds: Int32 + + @UserDefault(key: "shutdownSystemTimeoutSeconds", defaultValue: 20) + static var shutdownSystemTimeoutSeconds: Int32 + + private static let applicationDataRootKey = "applicationDataRoot" + private static let applicationDataRootBookmarkKey = "applicationDataRootBookmark" + private static let resolverDirectoryBookmarkKey = "resolverDirectoryBookmark" + + /// Named for the bundle, as Apple's `container` names its root. + static var defaultAppRoot: URL { + applicationSupport.appendingPathComponent( + Foundation.Bundle.main.bundleIdentifier ?? "app.containers.Containers" + ) + } + + /// Root directory for containers, images, volumes, kernels, and build data. + static var applicationDataRoot: URL { + get { + if let bookmarkData = applicationDataRootBookmarkData { + var isStale = false + + do { + let url = try URL( + resolvingBookmarkData: bookmarkData, + options: [.withSecurityScope], + relativeTo: nil, + bookmarkDataIsStale: &isStale + ) + + if isStale, + let refreshedBookmark = try? url.bookmarkData( + options: [.withSecurityScope], + includingResourceValuesForKeys: nil, + relativeTo: nil + ) + { + applicationDataRootBookmarkData = refreshedBookmark + } + + return url + } catch { + // Fall back to the stored URL or the default. + } + } + + return UserDefaults.standard.url(forKey: applicationDataRootKey) ?? defaultAppRoot + } + set { + UserDefaults.standard.set(newValue, forKey: applicationDataRootKey) + } + } + + static var usesDefaultApplicationDataRoot: Bool { + applicationDataRootBookmarkData == nil && applicationDataRoot.standardizedFileURL == defaultAppRoot.standardizedFileURL + } + + static func setApplicationDataRoot(_ url: URL, bookmarkData: Data?) { + applicationDataRoot = url + applicationDataRootBookmarkData = bookmarkData + } + + /// `nil` until the user grants access, or once the bookmark stops resolving. + static var resolverDirectory: URL? { + guard let bookmarkData = resolverDirectoryBookmarkData else { + return nil + } + + var isStale = false + + do { + let url = try URL( + resolvingBookmarkData: bookmarkData, + options: [.withSecurityScope], + relativeTo: nil, + bookmarkDataIsStale: &isStale + ) + + if isStale, + let refreshedBookmark = try? url.bookmarkData( + options: [.withSecurityScope], + includingResourceValuesForKeys: nil, + relativeTo: nil + ) + { + resolverDirectoryBookmarkData = refreshedBookmark + } + + return url + } catch { + // Forgotten, so the app asks again. + resolverDirectoryBookmarkData = nil + + return nil + } + } + + static func setResolverDirectory(bookmarkData: Data) { + resolverDirectoryBookmarkData = bookmarkData + } + + static func resetApplicationDataRoot() { + UserDefaults.standard.removeObject(forKey: applicationDataRootKey) + applicationDataRootBookmarkData = nil + } + + /// Whether What's New hasn't been dismissed yet. `lastSeenVersion` is empty + /// until it is; anything that isn't a version counts the same. + static var isFirstLaunch: Bool { + AppVersion(lastSeenVersion) == nil + } + + /// Whether the user hasn't dismissed What's New since the version in the + /// Info.plist was installed. After an update, only when the release + /// announces its features. + static var shouldShowWhatsNew: Bool { + guard let current = AppVersion(Bundle.main.shortVersion) else { + return false + } + + guard let lastSeen = AppVersion(lastSeenVersion) else { + return true + } + + return AppInfo.showsUpdateFeatures && current > lastSeen + } + + static func markCurrentVersionSeen() { + lastSeenVersion = Bundle.main.shortVersion + } + + private static var resolverDirectoryBookmarkData: Data? { + get { + UserDefaults.standard.data(forKey: resolverDirectoryBookmarkKey) + } + set { + if let newValue { + UserDefaults.standard.set( + newValue, + forKey: resolverDirectoryBookmarkKey + ) + } else { + UserDefaults.standard.removeObject( + forKey: resolverDirectoryBookmarkKey + ) + } + } + } + + private static var applicationDataRootBookmarkData: Data? { + get { + UserDefaults.standard.data(forKey: applicationDataRootBookmarkKey) + } + set { + if let newValue { + UserDefaults.standard.set( + newValue, + forKey: applicationDataRootBookmarkKey + ) + } else { + UserDefaults.standard.removeObject( + forKey: applicationDataRootBookmarkKey + ) + } + } + } + + private static var applicationSupport: URL { + guard + let url = FileManager.default.urls( + for: .applicationSupportDirectory, + in: .userDomainMask + ).first + else { + fatalError("AppRoot unavailable") + } + + return url + } + + private static func escaped(_ path: String) -> String { + path.replacingOccurrences(of: "/", with: "\\/") + } +} diff --git a/Containers/Extensions/ImageDescription+CustomStringConvertible.swift b/Containers/Extensions/ImageDescription+CustomStringConvertible.swift deleted file mode 100644 index f7c122d..0000000 --- a/Containers/Extensions/ImageDescription+CustomStringConvertible.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// ImageDescription.swift -// Containers -// -// Created by Axel Martinez on 02/02/26. -// - -import ContainerizationOCI -import ContainerResource - -extension ImageDescription: @retroactive CustomStringConvertible { - public var description: String { - guard let annotations = self.descriptor.annotations else { - return self.reference - } - - if let name = annotations[AnnotationKeys.containerizationImageName] { - return name - } - - if let name = annotations[AnnotationKeys.containerdImageName] { - return name - } - - if let name = annotations[AnnotationKeys.openContainersImageName] { - return name - } - - return self.reference - } -} diff --git a/Containers/Extensions/PublishPort+CustomStringConvertible.swift b/Containers/Extensions/PublishPort+CustomStringConvertible.swift deleted file mode 100644 index cf0b61e..0000000 --- a/Containers/Extensions/PublishPort+CustomStringConvertible.swift +++ /dev/null @@ -1,15 +0,0 @@ -// -// PublishPort.swift -// Containers -// -// Created by Axel Martinez on 02/02/26. -// - -import Foundation -import ContainerResource - -extension PublishPort: @retroactive CustomStringConvertible { - public var description: String { - "\(self.hostPort):\(self.containerPort) (\(self.proto.rawValue.localizedUppercase))" - } -} diff --git a/Containers/Extensions/SwiftUI/OpenWindowAction+Report.swift b/Containers/Extensions/SwiftUI/OpenWindowAction+Report.swift new file mode 100644 index 0000000..f0913ab --- /dev/null +++ b/Containers/Extensions/SwiftUI/OpenWindowAction+Report.swift @@ -0,0 +1,14 @@ +// +// OpenWindowAction+Report.swift +// Containers +// +// Created by Axel Martinez on 23/09/2026. +// + +import SwiftUI + +extension OpenWindowAction { + func report(_ id: String) { + self(id: ContainersApp.reportDetailWindowID, value: id) + } +} diff --git a/Containers/Extensions/SwiftUI/TextField+Suggestions.swift b/Containers/Extensions/SwiftUI/TextField+Suggestions.swift new file mode 100644 index 0000000..2d92a4d --- /dev/null +++ b/Containers/Extensions/SwiftUI/TextField+Suggestions.swift @@ -0,0 +1,206 @@ +// +// TextField+Suggestions.swift +// Containers +// +// Created by Axel Martinez on 01/08/2026. +// + +import Combine +import SwiftUI + +extension TextField { + /// Suggests completions for `text` once typing stops; `nil` cancels and closes the menu. + /// On `TextField`, so it must come first in the modifier chain. + func suggestions( + for text: String?, + fetch: @escaping @Sendable (String) async throws -> [String] + ) -> some View { + modifier(TextFieldSuggestions(text: text, fetch: fetch)) + } +} + +private struct TextFieldSuggestions: ViewModifier { + let text: String? + let fetch: @Sendable (String) async throws -> [String] + + @SwiftUI.State private var resolver = SuggestionResolver() + + func body(content: Content) -> some View { + content + .overlay(alignment: .trailing) { + if resolver.isLoading { + ProgressView() + .controlSize(.small) + .padding(.trailing, 6) + } else if let failure = resolver.failure { + // An empty menu otherwise reads as "nothing matched". + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.orange) + .help(failure) + .padding(.trailing, 6) + .accessibilityLabel(failure) + } + } + .textInputSuggestions { + ForEach(resolver.suggestions, id: \.self) { suggestion in + Text(suggestion) + .textInputCompletion(suggestion) + } + } + .onChange(of: text) { _, newText in + // Text matching a suggestion was just picked from the menu. + guard let newText, !newText.isEmpty, + !resolver.suggestions.contains(newText) + else { + resolver.reset() + return + } + + resolver.send(newText, using: fetch) + } + .onDisappear { + resolver.reset() + } + } +} + +/// Debounces typing into at most one lookup, skipping text already loaded. +@Observable +private final class SuggestionResolver { + private(set) var suggestions: [String] = [] + private(set) var isLoading = false + + /// Set when the last lookup failed, as opposed to matching nothing. + private(set) var failure: String? + + private let queries = PassthroughSubject() + + /// Cleared on reset, so the text alone can be the key. + @ObservationIgnored private var cache = SuggestionCache() + @ObservationIgnored private var fetch: (@Sendable (String) async throws -> [String])? + @ObservationIgnored private var subscription: AnyCancellable? + @ObservationIgnored private var fetchTask: Task? + @ObservationIgnored private var loadedText: String? + + init(debounce: DispatchQueue.SchedulerTimeType.Stride = .milliseconds(300)) { + self.subscription = + queries + .debounce(for: debounce, scheduler: DispatchQueue.main) + .sink { [weak self] text in + MainActor.assumeIsolated { + guard let text else { return } + self?.load(text) + } + } + } + + /// Takes the lookup every time, so it never goes stale against the view. + func send( + _ text: String, + using fetch: @escaping @Sendable (String) async throws -> [String] + ) { + self.fetch = fetch + queries.send(text) + } + + func reset() { + queries.send(nil) + fetchTask?.cancel() + fetchTask = nil + loadedText = nil + suggestions = [] + failure = nil + isLoading = false + cache.removeAll() + } + + private func load(_ text: String) { + guard text != loadedText, let fetch else { return } + + fetchTask?.cancel() + loadedText = text + + if let cached = cache.values(for: text) { + suggestions = cached + failure = nil + isLoading = false + return + } + + isLoading = true + + fetchTask = Task { + do { + let results = try await fetch(text) + + // The newer text owns `isLoading` now. + guard !Task.isCancelled else { return } + + cache.store(results, for: text) + suggestions = results + failure = nil + isLoading = false + } catch { + guard !Task.isCancelled else { return } + + // Not cached, so retyping retries. + loadedText = nil + suggestions = [] + failure = error.localizedDescription + isLoading = false + } + } + } +} + +/// Lets backspacing answer from memory instead of the network. +private struct SuggestionCache { + private struct Entry { + let values: [String] + let stored: ContinuousClock.Instant + } + + private let ttl: Duration = .seconds(120) + private let limit = 32 + + private var entries: [String: Entry] = [:] + + func values(for text: String) -> [String]? { + guard let entry = entries[text], + entry.stored.duration(to: ContinuousClock.now) < ttl + else { + return nil + } + + return entry.values + } + + mutating func store(_ values: [String], for text: String) { + entries[text] = Entry(values: values, stored: ContinuousClock.now) + + guard entries.count > limit else { + return + } + + // Expired entries first, then the oldest. + let now = ContinuousClock.now + entries = entries.filter { $0.value.stored.duration(to: now) < ttl } + + guard entries.count > limit else { + return + } + + let excess = + entries + .sorted { $0.value.stored < $1.value.stored } + .prefix(entries.count - limit) + + for entry in excess { + entries[entry.key] = nil + } + } + + mutating func removeAll() { + entries.removeAll() + } +} diff --git a/Containers/Extensions/SwiftUI/View+Content.swift b/Containers/Extensions/SwiftUI/View+Content.swift new file mode 100644 index 0000000..d981839 --- /dev/null +++ b/Containers/Extensions/SwiftUI/View+Content.swift @@ -0,0 +1,58 @@ +// +// View+Content.swift +// Containers +// +// Created by Axel Martinez on 01/08/2026. +// + +import SwiftUI + +/// What a view declares about its size to a `Layout` that sizes it or its window. +/// Layout values, not preferences, which would arrive a pass late. +extension View { + /// Until ready, the layout keeps its size rather than fit a half-drawn view. + /// Apply to the outermost view: a value set inside a stack belongs to that stack. + func contentReady(_ isReady: Bool) -> some View { + layoutValue(key: ContentReadyKey.self, value: isReady) + } + + /// For content with no height of its own, such as a scroll view or an + /// `NSViewRepresentable`; the layout bounds it instead of asking. + func contentUnbounded(_ isUnbounded: Bool = true) -> some View { + layoutValue(key: ContentUnboundedKey.self, value: isUnbounded) + } + + /// The natural size of content that can't report it through `sizeThatFits`, + /// such as a scroll view. Zero on an axis means ask the usual way. + func contentIdealSize(_ size: CGSize) -> some View { + layoutValue(key: ContentIdealSizeKey.self, value: size) + } +} + +extension LayoutSubview { + /// True for content that never declared it. + nonisolated var isContentReady: Bool { + self[ContentReadyKey.self] + } + + /// Asking such a subview its ideal size runs a nested AppKit layout. + nonisolated var isContentUnbounded: Bool { + self[ContentUnboundedKey.self] + } + + nonisolated var contentIdealSize: CGSize { + self[ContentIdealSizeKey.self] + } +} + +private struct ContentReadyKey: LayoutValueKey { + nonisolated static let defaultValue = true +} + +private struct ContentUnboundedKey: LayoutValueKey { + nonisolated static let defaultValue = false +} + +private struct ContentIdealSizeKey: LayoutValueKey { + nonisolated static let defaultValue: CGSize = .zero +} diff --git a/Containers/Extensions/SwiftUI/View+DefaultAction.swift b/Containers/Extensions/SwiftUI/View+DefaultAction.swift new file mode 100644 index 0000000..7576a92 --- /dev/null +++ b/Containers/Extensions/SwiftUI/View+DefaultAction.swift @@ -0,0 +1,20 @@ +// +// View+DefaultAction.swift +// Containers +// +// Created by Axel Martinez on 09/08/2026. +// + +import SwiftUI + +extension View { + /// Disabled, it drops to a plain button, as AppKit's default button does. + @ViewBuilder + func defaultAction(enabled: Bool) -> some View { + if enabled { + buttonStyle(.borderedProminent) + } else { + buttonStyle(.bordered).disabled(true) + } + } +} diff --git a/Containers/Extensions/SwiftUI/View+Foreground.swift b/Containers/Extensions/SwiftUI/View+Foreground.swift new file mode 100644 index 0000000..9ab47d3 --- /dev/null +++ b/Containers/Extensions/SwiftUI/View+Foreground.swift @@ -0,0 +1,15 @@ +// +// View+Foreground.swift +// Containers +// +// Created by Axel Martinez on 12/10/2026. +// + +import SwiftUI + +extension View { + /// Shows a cell's content as secondary while nothing can be done with its row, or while `isDimmed` holds. + func rowForeground(for row: some ActivityRow, isDimmed: Bool = false) -> some View { + foregroundStyle(row.isDisabled || isDimmed ? .secondary : .primary) + } +} diff --git a/Containers/Extensions/SwiftUI/View+PopoverTip.swift b/Containers/Extensions/SwiftUI/View+PopoverTip.swift new file mode 100644 index 0000000..cee4cfa --- /dev/null +++ b/Containers/Extensions/SwiftUI/View+PopoverTip.swift @@ -0,0 +1,36 @@ +// +// View+PopoverTip.swift +// Containers +// +// Created by Axel Martinez on 01/08/2026. +// + +import SwiftUI +import TipKit + +extension View { + @ViewBuilder + func popoverTipIfPresent( + _ tip: T?, + arrowEdge: Edge? = nil + ) -> some View { + if let tip { + self.popoverTip(tip, arrowEdge: arrowEdge) + } else { + self + } + } + + @ViewBuilder + func popoverTip( + _ tip: T, + when condition: Bool, + arrowEdge: Edge? = nil + ) -> some View { + if condition { + self.popoverTip(tip, arrowEdge: arrowEdge) + } else { + self + } + } +} diff --git a/Containers/Extensions/SwiftUI/View+RowTint.swift b/Containers/Extensions/SwiftUI/View+RowTint.swift new file mode 100644 index 0000000..87ba13a --- /dev/null +++ b/Containers/Extensions/SwiftUI/View+RowTint.swift @@ -0,0 +1,29 @@ +// +// View+RowTint.swift +// Containers +// +// Created by Axel Martinez on 15/09/2026. +// + +import SwiftUI + +extension View { + /// On a selected row, takes the row's foreground instead, as Finder's marks turn white. + func rowTint(_ color: Color) -> some View { + modifier(RowTint(color: color)) + } +} + +private struct RowTint: ViewModifier { + let color: Color + + @Environment(\.backgroundProminence) private var backgroundProminence + + func body(content: Content) -> some View { + content.foregroundStyle( + backgroundProminence == .increased + ? AnyShapeStyle(HierarchicalShapeStyle.primary) + : AnyShapeStyle(color) + ) + } +} diff --git a/Containers/Extensions/UserDefaults+Settings.swift b/Containers/Extensions/UserDefaults+Settings.swift deleted file mode 100644 index 9839b0a..0000000 --- a/Containers/Extensions/UserDefaults+Settings.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// SettingsManager.swift -// Containers -// -// Created by Axel Martinez on 02/02/26. -// - -import SwiftUI - -@propertyWrapper -struct UserDefault { - let key: String - let defaultValue: Value - var container: UserDefaults = .standard - - var wrappedValue: Value { - get { - return container.object(forKey: key) as? Value ?? defaultValue - } - set { - container.set(newValue, forKey: key) - } - } -} - -extension UserDefaults { - /// Returns the app root following Apple's containerization pattern - /// Uses Application Support directory with app-specific namespace - static var defaultAppRoot: URL { - FileManager.default.urls( - for: .applicationSupportDirectory, - in: .userDomainMask - ).first! - .appendingPathComponent("app.containers") - } - - @UserDefault( - key: "applicationDataRoot", - defaultValue: UserDefaults.defaultAppRoot - ) - static var applicationDataRoot: URL - - @UserDefault(key: "startSystemTimeoutSeconds", defaultValue: 10) - static var startSystemTimeoutSeconds: Int32 - - @UserDefault(key: "stopContainerTimeoutSeconds", defaultValue: 5) - static var stopContainerTimeoutSeconds: Int32 - - @UserDefault(key: "shutdownSystemTimeoutSeconds", defaultValue: 20) - static var shutdownSystemTimeoutSeconds: Int32 -} diff --git a/Containers/Helpers/ContainerConfigurationProvider.swift b/Containers/Helpers/ContainerConfigurationProvider.swift deleted file mode 100644 index 00052c2..0000000 --- a/Containers/Helpers/ContainerConfigurationProvider.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// ContainerConfigurationProvider.swift -// Containers -// -// Protocol for types that provide container configuration - -// Created by Axel Martinez on 2026/02/08. -// - -import Foundation -import ContainerAPIClient -import ContainerizationOCI -import ContainerResource - -/// Protocol for types that provide access to container configuration -protocol ContainerConfigurationProvider { - var configuration: ContainerConfiguration { get } -} - -extension ContainerConfigurationProvider { - - var imageName: String { - return self.configuration.image.reference - } - - var portsString: String? { - if self.configuration.publishedPorts.isEmpty { - return nil - } - - return self.configuration.publishedPorts.map(\.description).joined(separator: "\n") - } - - var volumeFSs: [Filesystem] { - let fileSystems = self.configuration.mounts - let volumes = fileSystems.filter({ $0.isVolume }) - - return volumes - } - - var volumeNames: [String] { - let volumeNames = self.volumeFSs.map(\.volumeName).filter({$0 != nil}).map({$0!}) - - return volumeNames - } -} - -extension ClientContainer: ContainerConfigurationProvider {} -extension ContainerSnapshot: ContainerConfigurationProvider {} diff --git a/Containers/Models/Containers/Capability.swift b/Containers/Models/Containers/Capability.swift new file mode 100644 index 0000000..775ddb9 --- /dev/null +++ b/Containers/Models/Containers/Capability.swift @@ -0,0 +1,23 @@ +// +// Capability.swift +// Containers +// +// Created by Axel Martinez on 03/08/2026. +// + +import Foundation + +struct Capability: Identifiable { + let id: UUID = UUID() + var name: String = "" + + var summary: String { + name.trimmingCharacters(in: .whitespacesAndNewlines) + } +} + +extension [Capability] { + var names: [String] { + map(\.summary).filter { !$0.isEmpty } + } +} diff --git a/Containers/Models/Containers/ContainerItem.swift b/Containers/Models/Containers/ContainerItem.swift new file mode 100644 index 0000000..c66cd16 --- /dev/null +++ b/Containers/Models/Containers/ContainerItem.swift @@ -0,0 +1,137 @@ +// +// ContainerItem.swift +// Containers +// +// Created by Axel Martinez on 2026/02/05. +// + +import ContainerSystem +import Containerization +import ContainerizationExtras +import ContainerizationOCI +import Foundation + +/// Nonisolated so that a column can sort by one of its fields: the target +/// takes its types as main-actor by default, and a key path into one of those +/// is not the sendable key path a sort comparator asks for. +nonisolated struct ContainerItem: Identifiable, Hashable, Equatable, Sendable { + let id: String + let imageName: String + let status: ContainerStatus + let ports: String + let ipAddress: String? + let os: String + let arch: String + let startedDate: Date? + + /// Whether the container exists yet, rather than the row standing in for one still being made. + private(set) var exists = true + + /// Set while work on the container is under way or has failed: its + /// making, which the row stands in for until it is made, or a start. + var activity: ActivitySnapshot? + + /// A container is known by its id once it exists; until then it is known + /// by what it was asked to be called. + var name: String { activity?.title ?? id } + + /// A row that only stands for the work of making a container. + var isPending: Bool { activity != nil && !exists } + + /// A row for a container that is still being made, which has none of what + /// a made one is described by. + init(pending activity: ActivitySnapshot) { + self.id = activity.id + self.imageName = activity.subtitle + self.status = .unknown + self.ports = "" + self.ipAddress = nil + self.os = Platform.current.os + self.arch = Platform.current.architecture + self.startedDate = nil + self.activity = activity + self.exists = false + } + + init(_ snapshot: ContainerSnapshot) { + self.id = snapshot.configuration.id + self.imageName = snapshot.configuration.image.reference + self.status = snapshot.status + self.ports = snapshot.configuration.publishedPorts.map { + "\($0.hostAddress):\($0.hostPort)\u{2192}\($0.containerPort)/\($0.proto.rawValue)" + }.joined(separator: "\n") + self.ipAddress = snapshot.networks.first.map { network in + let addressString = network.ipv4Address.description + return String( + addressString.split(separator: "/").first + ?? Substring(addressString) + ) + } + self.os = snapshot.configuration.platform.os + self.arch = snapshot.configuration.platform.architecture + self.startedDate = snapshot.startedDate + self.activity = nil + } + + func hash(into hasher: inout Hasher) { + hasher.combine(id) + hasher.combine(status) + hasher.combine(activity) + } + + static func == (lhs: ContainerItem, rhs: ContainerItem) -> Bool { + lhs.id == rhs.id && lhs.status == rhs.status && lhs.activity == rhs.activity + } +} + +// MARK: - Display Formatting + +extension ContainerItem { + var formattedPorts: String { + ports.isEmpty ? "-" : ports + } + + var hasIPAddress: Bool { + ipAddress != nil + } + + var formattedIPAddress: String { + ipAddress ?? "-" + } + + var formattedOS: String { + os.localizedCapitalized + } + + /// What the Uptime column sorts by: one never started sorts oldest. + var startedSort: Date { + startedDate ?? .distantPast + } + + var formattedState: String { + status.rawValue.localizedCapitalized + } + + var formattedStarted: String { + guard let startedDate else { + return "" + } + let formatter = DateFormatter() + formatter.dateStyle = .short + formatter.timeStyle = .medium + return formatter.string(from: startedDate) + } + + func formattedUptime(at date: Date = Date()) -> String { + guard status == .running, let startedDate else { + return "-" + } + + let interval = max(0, date.timeIntervalSince(startedDate)) + let formatter = DateComponentsFormatter() + formatter.allowedUnits = [.day, .hour, .minute] + formatter.maximumUnitCount = 2 + formatter.unitsStyle = .abbreviated + return formatter.string(from: interval) ?? "-" + } +} diff --git a/Containers/Models/Containers/Mount.swift b/Containers/Models/Containers/Mount.swift new file mode 100644 index 0000000..576a99c --- /dev/null +++ b/Containers/Models/Containers/Mount.swift @@ -0,0 +1,61 @@ +// +// Mount.swift +// Containers +// +// Created by Axel Martinez on 03/08/2026. +// + +import Foundation + +enum MountError: LocalizedError { + case targetMissing + case targetNotAbsolute + case sourceNotAbsolute + case duplicateTarget(String) + + var errorDescription: String? { + switch self { + case .targetMissing: + "Mounts require a target." + case .targetNotAbsolute: + "Mount target must be absolute." + case .sourceNotAbsolute: + "Mount source must be an absolute host path." + case .duplicateTarget(let target): + "A mount already exists at \(target)." + } + } +} + +struct Mount: Identifiable { + let id: UUID = UUID() + var hostURL: URL? + var containerPath: String = "" + /// An in-memory mount, which has no host path to share. + var isTemporary: Bool = false + + var summary: String { + if !isTemporary && hostURL == nil && trimmedTarget.isEmpty { + return "New Mount" + } + + return trimmedTarget.isEmpty + ? sourceLabel : "\(sourceLabel) -> \(trimmedTarget)" + } + + var columns: [String] { + [sourceLabel, trimmedTarget] + } + + var sourceLabel: String { + if isTemporary { + return "Temporary Mount" + } + + return hostURL?.path ?? "No Source" + } + + var trimmedTarget: String { + containerPath.trimmingCharacters(in: .whitespacesAndNewlines) + } +} diff --git a/Containers/Models/Containers/PortMapping.swift b/Containers/Models/Containers/PortMapping.swift new file mode 100644 index 0000000..6d015e9 --- /dev/null +++ b/Containers/Models/Containers/PortMapping.swift @@ -0,0 +1,61 @@ +// +// PortMapping.swift +// Containers +// +// Created by Axel Martinez on 03/08/2026. +// + +import ContainerSystem +import Containerization +import ContainerizationExtras +import ContainerizationOCI +import Foundation + +struct PortMapping: Identifiable { + /// The numbers a TCP or UDP port can carry. + static let range = 1...65535 + + let id: UUID = UUID() + var hostAddress: String = "127.0.0.1" + var host: Int = 0 + var container: Int = 0 + var publishProtocol: PublishProtocol = .tcp + + /// The port to publish, or nil for a row that cannot make one: the zeroes + /// it starts life with, or a number no port can take. + /// + /// The range is checked before the conversion rather than after, because + /// `UInt16` traps on what it cannot hold instead of reporting it. + var publishedPort: PublishPort? { + guard Self.range.contains(self.host), + Self.range.contains(self.container), + let fallbackAddress = try? IPAddress("127.0.0.1") + else { + return nil + } + + let address = try? IPAddress( + hostAddress.trimmingCharacters(in: .whitespacesAndNewlines) + ) + + return .init( + hostAddress: address ?? fallbackAddress, + hostPort: UInt16(self.host), + containerPort: UInt16(self.container), + proto: self.publishProtocol, + count: 1 + ) + } + + var summary: String { + "\(hostAddress):\(host):\(container)/\(publishProtocol.rawValue.uppercased())" + } + + var columns: [String] { + [ + "\(hostAddress):\(host)", + "\(container)", + publishProtocol.rawValue.uppercased(), + ] + } +} diff --git a/Containers/Models/Containers/ResolvedMounts.swift b/Containers/Models/Containers/ResolvedMounts.swift new file mode 100644 index 0000000..ae7079b --- /dev/null +++ b/Containers/Models/Containers/ResolvedMounts.swift @@ -0,0 +1,122 @@ +// +// ResolvedMounts.swift +// Containers +// +// Created by Axel Martinez on 03/08/2026. +// + +import ContainerSystem +import Containerization +import Foundation + +/// The mounts a container is created with, resolved from what the create +/// sheet drafted. The volumes are only named here: whoever creates the +/// container finds or makes them, since some may not exist yet. +struct ResolvedMounts { + /// A volume to mount. An empty name asks for a fresh anonymous one. + struct VolumeRequest { + let name: String + let destination: String + } + + let volumes: [VolumeRequest] + + private let bindMounts: [Filesystem] + private let temporaryFileSystems: [Filesystem] + private let options: [String] = [] + + init(mounts: [Mount], volumes: [VolumeMount]) throws { + var bindMounts: [Filesystem] = [] + var temporaryFileSystems: [Filesystem] = [] + var volumeRequests: [VolumeRequest] = [] + + var takenTargets = Set() + + func reserve(_ target: String) throws { + guard takenTargets.insert(target).inserted else { + throw MountError.duplicateTarget(target) + } + } + + for mount in mounts { + let target = mount.trimmedTarget + + // A row added and then left alone is not a mount. + guard mount.isTemporary || mount.hostURL != nil || !target.isEmpty + else { + continue + } + + guard !target.isEmpty else { + throw MountError.targetMissing + } + guard target.hasPrefix("/") else { + throw MountError.targetNotAbsolute + } + try reserve(target) + + guard !mount.isTemporary else { + temporaryFileSystems.append( + .tmpfs(destination: target, options: options) + ) + continue + } + + guard let source = mount.hostURL, source.path.hasPrefix("/") else { + throw MountError.sourceNotAbsolute + } + + bindMounts.append( + .virtiofs( + source: source.path, + destination: target, + options: options + ) + ) + } + + for draft in volumes { + let target = draft.trimmedTarget + + guard !draft.trimmedVolumeName.isEmpty || !target.isEmpty else { + continue + } + + guard target.hasPrefix("/") else { + throw MountError.targetNotAbsolute + } + try reserve(target) + + volumeRequests.append( + VolumeRequest( + name: draft.source == .anonymousVolume + ? "" : draft.trimmedVolumeName, + destination: target + ) + ) + } + + self.bindMounts = bindMounts + self.temporaryFileSystems = temporaryFileSystems + self.volumes = volumeRequests + } + + /// The mounts in the order the guest takes them: what the host binds in, + /// then the temporary filesystems, then the volumes. A volume nested under + /// a bind mount has to follow it, or the bind covers it over. + /// + /// `found` holds the volume for each of ``volumes``, in the same order. + func filesystems(with found: [Volume]) -> [Filesystem] { + let resolvedVolumes = zip(volumes, found).map { request, volume in + Filesystem.volume( + name: volume.name, + format: volume.format, + source: volume.source, + destination: request.destination, + options: options + ) + } + + return bindMounts + temporaryFileSystems + resolvedVolumes + } +} diff --git a/Containers/Models/Containers/VolumeMount.swift b/Containers/Models/Containers/VolumeMount.swift new file mode 100644 index 0000000..f7be643 --- /dev/null +++ b/Containers/Models/Containers/VolumeMount.swift @@ -0,0 +1,48 @@ +// +// VolumeMount.swift +// Containers +// +// Created by Axel Martinez on 03/08/2026. +// + +import Foundation + +struct VolumeMount: Identifiable { + enum Source: String, CaseIterable, Hashable, CustomStringConvertible { + case volume = "Volume" + case anonymousVolume = "Anonymous Volume" + + var description: String { rawValue } + } + + let id: UUID = UUID() + var source: Source = .volume + var volumeName: String = "" + var target: String = "" + + var summary: String { + trimmedTarget.isEmpty + ? sourceLabel : "\(sourceLabel) -> \(trimmedTarget)" + } + + var columns: [String] { + [sourceLabel, trimmedTarget] + } + + var sourceLabel: String { + switch source { + case .volume: + trimmedVolumeName.isEmpty ? "No Volume" : trimmedVolumeName + case .anonymousVolume: + "Anonymous Volume" + } + } + + var trimmedVolumeName: String { + volumeName.trimmingCharacters(in: .whitespacesAndNewlines) + } + + var trimmedTarget: String { + target.trimmingCharacters(in: .whitespacesAndNewlines) + } +} diff --git a/Containers/Models/Dashboard/NavigationTab.swift b/Containers/Models/Dashboard/NavigationTab.swift new file mode 100644 index 0000000..67c3622 --- /dev/null +++ b/Containers/Models/Dashboard/NavigationTab.swift @@ -0,0 +1,71 @@ +// +// NavigationTab.swift +// Containers +// +// Created by Axel Martinez on 2026/02/05. +// + +import ContainerSystem + +enum NavigationTab: String, Identifiable, Equatable { + case containers + case images + case volumes + case reports + + var displayTitle: String { + switch self { + case .containers: + "Containers" + case .images: + "Images" + case .volumes: + "Volumes" + case .reports: + "Reports" + } + } + + var icon: String { + switch self { + case .containers: + "shippingbox" + case .images: + "cube.transparent" + case .volumes: + "internaldrive" + case .reports: + "list.clipboard" + } + } + + /// Reports have no work of their own. + var activityKind: ActivityCenter.Kind? { + switch self { + case .containers: .container + case .images: .image + case .volumes: .volume + case .reports: nil + } + } + + var id: String { + self.rawValue + } + + /// The toolbar buttons that act on the section's selected rows. + var selectionItems: [SelectionToolbarItem] { + switch self { + case .containers: [.start, .stop, .details, .delete] + case .images: [.run, .details, .delete] + case .volumes: [.details, .delete] + case .reports: [.details, .delete] + } + } + + static let allCases: [NavigationTab] = resources + records + + static let resources: [NavigationTab] = [.containers, .images, .volumes] + + static let records: [NavigationTab] = [.reports] +} diff --git a/Containers/Models/Dashboard/ResourceUsage.swift b/Containers/Models/Dashboard/ResourceUsage.swift new file mode 100644 index 0000000..62e1f93 --- /dev/null +++ b/Containers/Models/Dashboard/ResourceUsage.swift @@ -0,0 +1,14 @@ +// +// ResourceUsage.swift +// Containers +// +// Created by Axel Martinez on 10/2/26. +// + +struct ResourceUsage { + static let zero = ResourceUsage(memoryUsage: 0, cpuUsage: 0, diskUsage: 0) + + let memoryUsage: Double // in GB + let cpuUsage: Double // percentage + let diskUsage: Double // in GB +} diff --git a/Containers/Models/Dashboard/SelectionToolbarItem.swift b/Containers/Models/Dashboard/SelectionToolbarItem.swift new file mode 100644 index 0000000..c3f5e59 --- /dev/null +++ b/Containers/Models/Dashboard/SelectionToolbarItem.swift @@ -0,0 +1,65 @@ +// +// SelectionToolbarItem.swift +// Containers +// +// Created by Axel Martinez on 02/08/2026. +// + +/// A toolbar button that acts on the rows selected in the dashboard's table. +enum SelectionToolbarItem: String { + case details + case run + case start + case stop + case delete + + var label: String { + switch self { + case .details: "Details" + case .run: "Run" + case .start: "Start" + case .stop: "Stop" + case .delete: "Delete" + } + } + + var toolTip: String { + switch self { + case .details: "Show details" + case .run: "Run container from image" + default: label + } + } + + var symbolName: String { + switch self { + case .details: "info.circle" + case .run, .start: "play" + case .stop: "stop" + case .delete: "trash" + } + } + + var command: SelectionCommand { + switch self { + case .run, .start: .start + case .details: .showDetails + case .stop: .stop + case .delete: .delete + } + } +} + +extension SelectionActions { + /// The toolbar buttons the selection can use. + var enabledItems: Set { + var items: Set = [] + + if canStart { items.formUnion([.run, .start]) } + if canShowDetails { items.insert(.details) } + if canStop { items.insert(.stop) } + if canDelete { items.insert(.delete) } + + return items + } +} diff --git a/Containers/Models/Images/ImageBuildRequest.swift b/Containers/Models/Images/ImageBuildRequest.swift new file mode 100644 index 0000000..d778fe9 --- /dev/null +++ b/Containers/Models/Images/ImageBuildRequest.swift @@ -0,0 +1,37 @@ +// +// ImageBuildRequest.swift +// Containers +// + +import ContainerSystem +import ContainerizationOCI +import Foundation + +/// What the Create Image sheet builds. +struct ImageBuildRequest { + var contextDirectory: URL? + var dockerFile: URL? + var tag = "" + var platform: PlatformSelection = .platform(.current) + var arguments: [KeyValue] = [] + var targetStage = "" + + var isComplete: Bool { + contextDirectory != nil && dockerFile != nil + } + + /// The tag, or a generated one when it's empty, so the row has a title. + func resolvedTag() -> String { + tag.isEmpty ? UUID().uuidString.lowercased() : tag + } + + var targetPlatform: Platform { + platform.platform ?? .current + } + + var namedArguments: [KeyValue] { + arguments.filter { + !$0.key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + } +} diff --git a/Containers/Models/Images/ImageItem.swift b/Containers/Models/Images/ImageItem.swift new file mode 100644 index 0000000..9c1f100 --- /dev/null +++ b/Containers/Models/Images/ImageItem.swift @@ -0,0 +1,187 @@ +// +// ImageItem.swift +// Containers +// +// Created by Axel Martinez on 2026/02/05. +// + +import ContainerSystem +import Containerization +import ContainerizationOCI +import Foundation + +nonisolated struct ImageItem: Identifiable, Hashable, Equatable, Sendable { + let name: String + let tag: String + let os: String + let arch: String + let variant: String + let sizeInBytes: Int64 + let createdDate: Date + let indexDigest: String + /// One per platform in the image's index, as apple/container's + /// `ImageResource.variants`. + let variants: [Variant] + let isInUse: Bool + let imageDescription: ImageDescription + var activity: ActivitySnapshot? + /// Whether the image has landed, rather than the row standing in for one + /// still on its way. + private(set) var exists = true + + /// A row that only stands for the work of fetching an image. + var isPending: Bool { + activity != nil && !exists + } + + var id: String { + if let activity { + return activity.id + } + + // The reference is what the work that fetches an image knows it by, + // so the row it arrives in is the row it was being fetched in. What + // has no reference to be known by — an image left behind by a build + // that has been retagged — keeps to its digest. + return Self.identity(for: imageDescription.reference) + ?? indexDigest + createdDate.description + } + + /// The reference as the registry knows it, which is how an image arriving + /// is recognised as the one that was asked for. + static func identity(for reference: String) -> String? { + guard !reference.isEmpty, !reference.contains("") else { + return nil + } + + return (try? Reference.normalized(reference).description) ?? reference + } + + init(_ summary: ImageSummary) { + self.init( + summary.description, + variant: summary.platform?.variant, + created: summary.platform?.created, + os: summary.platform?.os, + architecture: summary.platform?.architecture, + isInUse: summary.isInUse, + sizeInBytes: summary.platform?.size, + variants: summary.variants.map(Variant.init) + ) + } + + /// Initialize from ImageDescription (simplified, without full image details) + init( + _ description: ImageDescription, + variant: String? = nil, + created: Date? = nil, + os: String? = nil, + architecture: String? = nil, + isInUse: Bool, + sizeInBytes: Int64? = nil, + variants: [Variant] = [] + ) { + self.imageDescription = description + + let (name, tag) = Self.nameAndTag(from: description.reference) + self.name = name + self.tag = tag + + self.indexDigest = description.digest + self.variants = variants + self.os = os ?? Platform.current.os + self.arch = architecture ?? Platform.current.architecture + self.variant = variant ?? "" + self.sizeInBytes = sizeInBytes ?? description.descriptor.size + self.createdDate = created ?? ImageSummary.unknownCreationDate + self.isInUse = isInUse + } + + /// A row for an image that is still arriving, which has no digest of its + /// own to be known by until it has. + init(pending activity: ActivitySnapshot) { + self.imageDescription = ImageDescription( + reference: activity.title, + descriptor: Descriptor(mediaType: "", digest: "", size: 0) + ) + + let (name, tag) = Self.nameAndTag(from: activity.title) + + self.name = name + self.tag = tag + self.indexDigest = "" + self.variants = [] + self.os = Platform.current.os + self.arch = Platform.current.architecture + self.variant = "" + self.sizeInBytes = 0 + self.createdDate = ImageSummary.unknownCreationDate + self.isInUse = false + self.activity = activity + self.exists = false + } + + /// What an image with no tag is shown as wherever it is named in full. + private static let noTag = "" + + var hasTag: Bool { tag != Self.noTag } + + /// The name with its tag, where it has one. + var displayName: String { hasTag ? "\(name):\(tag)" : name } + + private static func nameAndTag(from reference: String) -> (String, String) { + guard + let parsed = try? ContainerizationOCI.Reference.parse(reference) + else { + return (reference, noTag) + } + + return (parsed.name, parsed.tag ?? noTag) + } + + // Hashable conformance + func hash(into hasher: inout Hasher) { + hasher.combine(indexDigest) + hasher.combine(activity) + } + + // Equatable conformance + static func == (lhs: ImageItem, rhs: ImageItem) -> Bool { + lhs.indexDigest == rhs.indexDigest + && lhs.variants == rhs.variants + && lhs.activity == rhs.activity + } +} + +extension ImageItem { + nonisolated struct Variant: Hashable, Sendable { + let platform: Platform + let digest: String + let size: Int64 + + init(_ variant: ImageResource.Variant) { + self.platform = variant.platform + self.digest = variant.digest + self.size = variant.size + } + } +} + +// MARK: - Display Formatting + +extension ImageItem { + var formattedSize: String { + ByteCountFormatter.string(fromByteCount: sizeInBytes, countStyle: .file) + } + + var formattedOS: String { + os.localizedCapitalized + } + + var formattedCreated: String { + let formatter = DateFormatter() + formatter.dateStyle = .medium + formatter.timeStyle = .short + return formatter.string(from: createdDate) + } +} diff --git a/Containers/Models/Images/ImageLoadRequest.swift b/Containers/Models/Images/ImageLoadRequest.swift new file mode 100644 index 0000000..144ca8d --- /dev/null +++ b/Containers/Models/Images/ImageLoadRequest.swift @@ -0,0 +1,16 @@ +// +// ImageLoadRequest.swift +// Containers +// + +import Foundation + +/// What the Create Image sheet loads. +struct ImageLoadRequest { + var tarFile: URL? + var force = false + + var isComplete: Bool { + tarFile != nil + } +} diff --git a/Containers/Models/Images/ImagePullRequest.swift b/Containers/Models/Images/ImagePullRequest.swift new file mode 100644 index 0000000..0f74a63 --- /dev/null +++ b/Containers/Models/Images/ImagePullRequest.swift @@ -0,0 +1,21 @@ +// +// ImagePullRequest.swift +// Containers +// + +import Foundation + +/// What the Create Image sheet pulls. +struct ImagePullRequest { + var imageName = "" + var tag = "latest" + var platform: PlatformSelection = .any + + var isComplete: Bool { + !imageName.isEmpty + } + + var reference: String { + tag.isEmpty ? imageName : "\(imageName):\(tag)" + } +} diff --git a/Containers/Models/Images/PlatformSelection.swift b/Containers/Models/Images/PlatformSelection.swift new file mode 100644 index 0000000..dfb413f --- /dev/null +++ b/Containers/Models/Images/PlatformSelection.swift @@ -0,0 +1,32 @@ +// +// PlatformSelection.swift +// Containers +// +// Created by Axel Martinez on 28/06/2026. +// + +import ContainerizationOCI +import Foundation + +enum PlatformSelection: Hashable, CustomStringConvertible { + case any + case platform(Platform) + + var platform: Platform? { + switch self { + case .any: + return nil + case .platform(let platform): + return platform + } + } + + var description: String { + switch self { + case .any: + return "Any" + case .platform(let platform): + return platform.description + } + } +} diff --git a/Containers/Models/Images/Registries/DockerHub.swift b/Containers/Models/Images/Registries/DockerHub.swift new file mode 100644 index 0000000..69c4288 --- /dev/null +++ b/Containers/Models/Images/Registries/DockerHub.swift @@ -0,0 +1,340 @@ +// +// DockerHub.swift +// Containers +// +// Created by Axel Martinez on 27/06/2026. +// + +import Foundation + +nonisolated struct DockerHub: RegistryProvider { + private static let cacheLifetime: Duration = .seconds(30 * 60) + + /// Docker Official Images are published under `library`, which reads as + /// nothing to anyone who doesn't already know that. + private static let officialPublisher = "library" + + private struct PopularResponse: Decodable { + let results: [PopularImage] + } + + private struct PopularImage: Decodable { + let slug: String + let shortDescription: String? + let publisher: Publisher? + let logoURL: Logo? + + struct Publisher: Decodable { + let name: String? + } + + struct Logo: Decodable { + let large: String? + let small: String? + } + + enum CodingKeys: String, CodingKey { + case slug + case shortDescription = "short_description" + case publisher + case logoURL = "logo_url" + } + + var suggestion: ImageSuggestion { + let publisherName = publisher?.name.map { + $0 == DockerHub.officialPublisher ? "Docker Official Image" : $0 + } + + return ImageSuggestion( + name: slug, + publisher: publisherName, + description: shortDescription, + imageURL: [logoURL?.large, logoURL?.small] + .compactMap { + $0?.trimmingCharacters(in: .whitespacesAndNewlines) + } + .first { !$0.isEmpty } + .flatMap(URL.init(string:)) + ) + } + } + + private struct ImageSearchResponse: Decodable { + let results: [ImageSearchResult] + } + + private struct ImageSearchResult: Decodable { + let repoName: String + + enum CodingKeys: String, CodingKey { + case repoName = "repo_name" + } + } + + private struct TagResponse: Decodable { + let results: [Tag] + } + + private struct Tag: Decodable { + let name: String + } + + private struct RepositoryDetail: Decodable { + let fullDescription: String? + + enum CodingKeys: String, CodingKey { + case fullDescription = "full_description" + } + } + + private func hubURL(path: String, query: [URLQueryItem] = []) -> URL? { + var components = URLComponents() + components.scheme = "https" + components.host = "hub.docker.com" + components.path = path + + // An empty list would still leave a `?` on the end. + if !query.isEmpty { + components.queryItems = query + } + + return components.url + } + + private func pathComponents(of imageName: String) -> [String] { + imageName + .trimmingCharacters(in: .whitespacesAndNewlines) + .split(separator: "/", omittingEmptySubsequences: true) + .map(String.init) + } + + var featuredImages: RegistryRequest<[ImageSuggestion]>? { + guard + let url = hubURL( + path: "/api/search/v4", + query: [ + URLQueryItem(name: "query", value: ""), + URLQueryItem(name: "from", value: "0"), + URLQueryItem(name: "size", value: "25"), + URLQueryItem(name: "type", value: "image"), + URLQueryItem(name: "badges", value: "official,verified_publisher"), + ] + ) + else { + return nil + } + + return RegistryRequest(url: url, lifetime: Self.cacheLifetime) { + data in + let decoded = try JSONDecoder().decode( + PopularResponse.self, + from: data + ) + let suggestions = decoded.results.map(\.suggestion) + + guard !suggestions.isEmpty else { throw RegistryError.unavailable } + + return suggestions + } + } + + /// Docker Hub addresses a repository as `namespace/name`, defaulting the + /// namespace to `library`. Nothing outside this type needs to know that. + private func repository(from imageName: String) -> Repository? { + let components = pathComponents(of: imageName) + + let namespace: String + let name: String + switch components.count { + case 1: + namespace = "library" + name = components[0] + case 2: + namespace = components[0] + name = components[1] + default: + return nil + } + + // The tag has a field of its own, but a pasted name may carry one. + let repositoryName = + name + .split( + separator: ":", + maxSplits: 1, + omittingEmptySubsequences: false + ) + .first + .map(String.init) ?? name + + guard !namespace.isEmpty, !repositoryName.isEmpty else { + return nil + } + + return Repository(namespace: namespace, name: repositoryName) + } + + func imageSearch(matching text: String) -> RegistryRequest<[String]>? { + // The registry is picked in its own field, so a name is + // `[namespace/]name`; anything deeper is not a Docker Hub repository. + let query = text.trimmingCharacters(in: .whitespacesAndNewlines) + let path = pathComponents(of: query) + + guard !path.isEmpty, path.count <= 2 else { + return nil + } + + guard + let url = hubURL( + path: "/v2/search/repositories/", + query: [ + URLQueryItem(name: "query", value: query), + URLQueryItem(name: "page_size", value: "10"), + ] + ) + else { + return nil + } + + return RegistryRequest(url: url) { data in + let decoded = try JSONDecoder().decode( + ImageSearchResponse.self, + from: data + ) + return ranked( + decoded.results.map(\.repoName), + matching: query.lowercased() + ) + } + } + + func tagSearch( + for imageName: String, + matching text: String + ) -> RegistryRequest<[String]>? { + guard let repository = repository(from: imageName) else { + return nil + } + + let prefix = text.trimmingCharacters(in: .whitespacesAndNewlines) + + var query = [URLQueryItem(name: "page_size", value: "20")] + + if !prefix.isEmpty { + query.append(URLQueryItem(name: "name", value: prefix)) + } + + guard + let url = hubURL( + path: + "/v2/repositories/\(repository.namespace)/\(repository.name)/tags/", + query: query + ) + else { + return nil + } + + return RegistryRequest(url: url) { data in + let decoded = try JSONDecoder().decode(TagResponse.self, from: data) + return ranked( + decoded.results.map(\.name), + matching: prefix, + pinning: "latest" + ) + } + } + + /// Docker Hub has no logo field for a repository, so the first image in its description stands in for one. + func logo(for imageName: String) -> RegistryRequest? { + guard let repository = repository(from: imageName) else { + return nil + } + + guard + let url = hubURL( + path: + "/v2/repositories/\(repository.namespace)/\(repository.name)/" + ) + else { + return nil + } + + return RegistryRequest(url: url, lifetime: Self.cacheLifetime) { + data in + let detail = try JSONDecoder().decode( + RepositoryDetail.self, + from: data + ) + return firstMarkdownImageURL(in: detail.fullDescription) + } + } + + /// Docker Hub returns search hits in its own relevance order and tags by last push. + /// Keep that order, but float what the user is most likely reaching for, and never list the same thing twice. + private func ranked( + _ values: [String], + matching text: String, + pinning pinned: String? = nil + ) -> [String] { + var seen = Set() + + return + values + .filter { seen.insert($0).inserted } + .enumerated() + .sorted { lhs, rhs in + let lhsRank = rank(lhs.element, matching: text, pinned: pinned) + let rhsRank = rank(rhs.element, matching: text, pinned: pinned) + + return lhsRank == rhsRank ? lhs.offset < rhs.offset : lhsRank < rhsRank + } + .map(\.element) + } + + private func rank( + _ value: String, + matching text: String, + pinned: String? + ) -> Int { + if value == pinned { return 0 } + if value == text { return 1 } + guard !text.isEmpty else { return 4 } + + // Official images have no namespace, and are what a bare name means. + let isOfficial = !value.contains("/") + if isOfficial, value.hasPrefix(text) { return 2 } + + let name = value.split(separator: "/").last.map(String.init) ?? value + if value.hasPrefix(text) || name.hasPrefix(text) { return 3 } + return 4 + } + + private func firstMarkdownImageURL(in markdown: String?) -> URL? { + guard let markdown else { return nil } + + let pattern = #"!\[[^\]]*\]\(([^\s)]+)(?:\s+\"[^\"]*\")?\)"# + guard let regex = try? NSRegularExpression(pattern: pattern) else { + return nil + } + + let range = NSRange( + markdown.startIndex.. 1, + let urlRange = Range(match.range(at: 1), in: markdown) + else { + return nil + } + + let value = String(markdown[urlRange]) + .trimmingCharacters(in: .whitespacesAndNewlines) + return URL(string: value) + } + + private struct Repository { + let namespace: String + let name: String + } +} diff --git a/Containers/Models/Images/Registries/ImageSuggestion.swift b/Containers/Models/Images/Registries/ImageSuggestion.swift new file mode 100644 index 0000000..06ee646 --- /dev/null +++ b/Containers/Models/Images/Registries/ImageSuggestion.swift @@ -0,0 +1,17 @@ +// +// ImageSuggestion.swift +// Containers +// +// Created by Axel Martinez on 01/08/2026. +// + +import Foundation + +/// An image a registry suggests, as the trending cards show it. +nonisolated struct ImageSuggestion: Identifiable, Sendable { + var id: String { name } + let name: String + let publisher: String? + let description: String? + let imageURL: URL? +} diff --git a/Containers/Models/Images/Registries/Registry.swift b/Containers/Models/Images/Registries/Registry.swift new file mode 100644 index 0000000..f838c17 --- /dev/null +++ b/Containers/Models/Images/Registries/Registry.swift @@ -0,0 +1,27 @@ +// +// Registry.swift +// Containers +// +// Created by Axel Martinez on 01/08/2026. +// + +import Foundation + +/// The registries offered in the Registry field. +enum Registry: Hashable, CaseIterable, CustomStringConvertible, Sendable { + case dockerHub + + var description: String { + switch self { + case .dockerHub: + "Docker Hub" + } + } + + var provider: any RegistryProvider { + switch self { + case .dockerHub: + DockerHub() + } + } +} diff --git a/Containers/Models/Images/Registries/RegistryProvider.swift b/Containers/Models/Images/Registries/RegistryProvider.swift new file mode 100644 index 0000000..5d34b13 --- /dev/null +++ b/Containers/Models/Images/Registries/RegistryProvider.swift @@ -0,0 +1,55 @@ +// +// RegistryProvider.swift +// Containers +// +// Created by Axel Martinez on 01/08/2026. +// + +import Foundation + +/// A call to a registry's API and how to read what comes back, described +/// without being made, as a `FetchDescriptor` describes a SwiftData fetch. +nonisolated struct RegistryRequest: Sendable { + let url: URL + let lifetime: Duration? + let decode: @Sendable (Data) throws -> Response + + init( + url: URL, + lifetime: Duration? = nil, + decode: @escaping @Sendable (Data) throws -> Response + ) { + self.url = url + self.lifetime = lifetime + self.decode = decode + } +} + +/// Creates the requests a registry answers while the image and tag fields are +/// typed into. How a name maps onto its API is the provider's business; making +/// the calls is ``RegistryLookup``'s. +/// +/// A request is nil where the registry has nothing to ask for it. +nonisolated protocol RegistryProvider: Sendable { + var featuredImages: RegistryRequest<[ImageSuggestion]>? { get } + + func imageSearch(matching text: String) -> RegistryRequest<[String]>? + func tagSearch(for imageName: String, matching text: String) -> RegistryRequest<[String]>? + func logo(for imageName: String) -> RegistryRequest? +} + +/// Why a lookup could not be answered. Distinguishes a registry that would not +/// talk to us from one that simply had nothing to suggest. +nonisolated enum RegistryError: LocalizedError { + case rateLimited + case unavailable + + var errorDescription: String? { + switch self { + case .rateLimited: + "The registry is rate limiting requests. Suggestions will come back shortly." + case .unavailable: + "Couldn't reach the registry." + } + } +} diff --git a/Containers/Models/Reports/ReportFilter.swift b/Containers/Models/Reports/ReportFilter.swift new file mode 100644 index 0000000..110cc3c --- /dev/null +++ b/Containers/Models/Reports/ReportFilter.swift @@ -0,0 +1,157 @@ +// +// ReportSearch.swift +// Containers +// +// Created by Axel Martinez on 25/09/2026. +// + +import ContainerSystem +import Foundation + +/// A search kept under a name, which the bar over the reports offers beside +/// the kinds of work. +struct SavedReportSearch: Codable, Hashable, Identifiable, Sendable { + var id = UUID() + let name: String + let filters: [ReportFilter] +} + +/// One thing a search of the reports is narrowed by, which the search field +/// carries as a token: a part of the report, how it is to compare, and with +/// what. +struct ReportFilter: Codable, Hashable, Sendable { + var field: Field + var match: Match = .contains + let value: String + + /// Which part of a report is looked at, after the table's columns. + enum Field: String, Codable, CaseIterable, Sendable { + case any + case type + case date + case kind + case name + case message + + var title: String { + switch self { + case .any: "Any" + case .type: "Type" + case .date: "Date" + case .kind: "Kind" + case .name: "Name" + case .message: "Message" + } + } + + /// What of the report is compared, as the table shows it. + func texts(of report: Report) -> [String] { + switch self { + case .any: + [Field.type, .date, .kind, .name, .message].flatMap { + $0.texts(of: report) + } + case .type: [report.level.title] + case .date: [report.dateText] + case .kind: [report.kind.title] + case .name: [report.name] + case .message: [report.message] + } + } + } + + /// How what is looked at has to compare, as Console asks it. + enum Match: String, Codable, CaseIterable, Sendable { + case contains + case doesNotContain + case equals + case doesNotEqual + + var title: String { + switch self { + case .contains: "Contains" + case .doesNotContain: "Does Not Contain" + case .equals: "Equals" + case .doesNotEqual: "Does Not Equal" + } + } + + /// What the token says after the field, where it says anything: the + /// usual way goes without saying. + var tokenTitle: String? { + switch self { + case .contains: nil + case .doesNotContain: "Not" + case .equals: "Is" + case .doesNotEqual: "Is Not" + } + } + } + + func matches(_ report: Report) -> Bool { + let texts = field.texts(of: report) + + switch match { + case .contains: + return texts.contains { $0.localizedCaseInsensitiveContains(value) } + case .doesNotContain: + return !texts.contains { $0.localizedCaseInsensitiveContains(value) } + case .equals: + return texts.contains(where: equalsValue) + case .doesNotEqual: + return !texts.contains(where: equalsValue) + } + } + + /// The kind of work a tab of the bar stands for, compared the usual way, + /// as Console's own tabs are: no kind's name holds another's. + static func kind(_ kind: Report.Kind) -> ReportFilter { + ReportFilter(field: .kind, value: kind.title) + } + + /// The one thing a window is about, compared the whole way: another's + /// name may hold this one's, and a window asking for its own reports is + /// asking for exactly those. + static func name(_ name: String) -> ReportFilter { + ReportFilter(field: .name, match: .equals, value: name) + } + + private func equalsValue(_ text: String) -> Bool { + text.localizedCaseInsensitiveCompare(value) == .orderedSame + } +} + +extension ReportFilter { + /// How the search field shows the filter, and what its menu offers: the + /// part of the report, then the way of comparing. + var token: SearchToken { + SearchToken( + category: [field.title, match.tokenTitle] + .compactMap { $0 } + .joined(separator: " "), + value: value, + menu: [ + Field.allCases.map { + SearchToken.Choice(title: $0.title, isOn: $0 == field) + }, + Match.allCases.map { + SearchToken.Choice(title: $0.title, isOn: $0 == match) + }, + ] + ) + } + + /// The filter with a choice from its menu made, told apart by title: + /// none of the parts of a report is called what a way of comparing is. + func choosing(_ title: String) -> ReportFilter { + var filter = self + + if let field = Field.allCases.first(where: { $0.title == title }) { + filter.field = field + } else if let match = Match.allCases.first(where: { $0.title == title }) { + filter.match = match + } + + return filter + } +} diff --git a/Containers/Models/Shared/ActivitySnapshot.swift b/Containers/Models/Shared/ActivitySnapshot.swift new file mode 100644 index 0000000..942adca --- /dev/null +++ b/Containers/Models/Shared/ActivitySnapshot.swift @@ -0,0 +1,134 @@ +// +// ActivitySnapshot.swift +// Containers +// +// Created by Axel Martinez on 12/09/2026. +// + +import ContainerSystem +import Foundation + +nonisolated struct ActivitySnapshot: Hashable, Sendable { + enum Phase: Hashable, Sendable { + case executing + case stopped + case failed(reportID: String?) + } + + enum Source: Sendable { + case work(ActivityCenter.Activity) + case report(Report) + } + + let id: String + let title: String + let subtitle: String + let phase: Phase + let source: Source + + /// `id` can differ from `report.name`: an image is reported under the + /// reference asked for, but its row is known by the resolved one. + init(report: Report, id: String? = nil) { + self.id = id ?? report.name + self.title = report.name + self.subtitle = "" + self.phase = .failed(reportID: report.id) + self.source = .report(report) + } + + @MainActor + init(_ activity: ActivityCenter.Activity) { + self.id = activity.id + self.title = activity.title + self.subtitle = activity.subtitle + self.source = .work(activity) + + if activity.error != nil { + self.phase = .failed(reportID: activity.reportID) + } else if activity.isStopped { + self.phase = .stopped + } else { + self.phase = .executing + } + } + + var isExecuting: Bool { phase == .executing } + var isStopped: Bool { phase == .stopped } + + var reportID: String? { + guard case .failed(let reportID) = phase else { return nil } + + return reportID + } + + var isReported: Bool { + guard case .report = source else { return false } + + return true + } + + static func == (lhs: ActivitySnapshot, rhs: ActivitySnapshot) -> Bool { + lhs.id == rhs.id && lhs.title == rhs.title + && lhs.subtitle == rhs.subtitle && lhs.phase == rhs.phase + && lhs.source.isSame(as: rhs.source) + } + + func hash(into hasher: inout Hasher) { + hasher.combine(id) + hasher.combine(phase) + } +} + +@MainActor +extension ActivitySnapshot { + var canRetry: Bool { + guard case .work(let activity) = source else { return false } + + return activity.canRetry + } + + var failureTitle: String? { + switch source { + case .work(let activity): failure(of: activity)?.title + case .report(let report): report.message + } + } + + var failureMessage: String? { + switch source { + case .work(let activity): failure(of: activity)?.message + case .report(let report): report.message + } + } + + private func failure(of activity: ActivityCenter.Activity) -> ErrorAlert? { + activity.error.map { ErrorAlert(activity.failureTitle, error: $0) } + } + + /// A failure or a stop always shows, so it can be read or run again. + var showsProgress: Bool { + guard isExecuting, case .work(let activity) = source else { return true } + + return activity.showsProgress + } + + var step: String { progress?.localizedDescription ?? "" } + var detail: String { progress?.localizedAdditionalDescription ?? "" } + var fraction: Double? { progress?.fractionCompleted } + + private var progress: ProgressObserver? { + guard case .work(let activity) = source else { return nil } + + return activity.progress + } +} + +extension ActivitySnapshot.Source { + nonisolated fileprivate func isSame(as other: Self) -> Bool { + switch (self, other) { + case (.work(let lhs), .work(let rhs)): lhs === rhs + case (.report(let lhs), .report(let rhs)): lhs.id == rhs.id + default: false + } + } +} diff --git a/Containers/Models/Shared/AppInfo.swift b/Containers/Models/Shared/AppInfo.swift new file mode 100644 index 0000000..f80fb23 --- /dev/null +++ b/Containers/Models/Shared/AppInfo.swift @@ -0,0 +1,52 @@ +// +// Release.swift +// Containers +// +// Created by Axel Martinez on 10/10/2026. +// + +import Foundation + +/// What the What's New sheet lists: the app's features on first launch, or +/// what changed in this release after an update. +enum AppInfo { + struct Feature { + let icon: String + let title: String + let description: String + } + + /// The title and features the sheet shows. + /// + /// Worked out once, at launch: dismissing the sheet marks the version seen, + /// which mustn't change what the closing sheet shows. + static let release: (title: String, features: [Feature]) = + UserDefaults.isFirstLaunch + ? ("Welcome to", welcomeFeatures) + : ("What's New in", updateFeatures) + + /// Whether an update to the version in the Info.plist shows `updateFeatures`. + /// Set it for releases worth announcing; leave it off for small fixes. + static let showsUpdateFeatures = false + + /// What changed in the version in the Info.plist. Replace it with each release. + private static let updateFeatures: [Feature] = [] + + private static let welcomeFeatures: [Feature] = [ + Feature( + icon: "shippingbox", + title: "Run Linux containers", + description: "Create and run Linux containers as lightweight virtual machines on your Mac." + ), + Feature( + icon: "cube.transparent", + title: "OCI-compatible images support", + description: "Pull and run images from container registries, build from a Dockerfile, or load from a local archive." + ), + Feature( + icon: "cpu", + title: "Optimized for Apple Silicon", + description: "Written in Swift and designed to get the most out of Apple Silicon." + ), + ] +} diff --git a/Containers/Models/Shared/AppLink.swift b/Containers/Models/Shared/AppLink.swift new file mode 100644 index 0000000..31c4422 --- /dev/null +++ b/Containers/Models/Shared/AppLink.swift @@ -0,0 +1,51 @@ +// +// AppLink.swift +// Containers +// +// Created by Axel Martinez on 27/09/2026. +// + +import Foundation + +/// A link into the app, such as `containers://reports?name=redis-test`, which +/// the dashboard opens: from a detail window, or from outside the app. +enum AppLink: Equatable { + /// The Reports section, narrowed to what was reported against `name`. + case reports(name: String) + + static let scheme = "containers" + + var url: URL { + var components = URLComponents() + components.scheme = Self.scheme + + switch self { + case .reports(let name): + components.host = "reports" + components.queryItems = [URLQueryItem(name: "name", value: name)] + } + + // Only fails for a malformed path, which is never built here. + return components.url ?? URL(fileURLWithPath: "/") + } + + /// Anything not recognised is ignored: any app can open these. + init?(_ url: URL) { + guard url.scheme == Self.scheme, let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { + return nil + } + + let query = components.queryItems ?? [] + + switch components.host { + case "reports": + guard let name = query.first(where: { $0.name == "name" })?.value, !name.isEmpty else { + return nil + } + + self = .reports(name: name) + default: + return nil + } + } +} diff --git a/Containers/Models/Shared/AppVersion.swift b/Containers/Models/Shared/AppVersion.swift new file mode 100644 index 0000000..ddb6104 --- /dev/null +++ b/Containers/Models/Shared/AppVersion.swift @@ -0,0 +1,43 @@ +// +// AppVersion.swift +// Containers +// +// Created by Axel Martinez on 10/10/2026. +// + +import Foundation + +/// A marketing version such as `1.2.3`, in the format `CFBundleShortVersionString` +/// requires: one to three period-separated integers. Missing parts are zero. +nonisolated struct AppVersion: Hashable, Comparable, Sendable { + let major: Int + let minor: Int + let patch: Int + + static func < (lhs: Self, rhs: Self) -> Bool { + (lhs.major, lhs.minor, lhs.patch) < (rhs.major, rhs.minor, rhs.patch) + } +} + +extension AppVersion: LosslessStringConvertible { + /// Fails for anything but digits between the periods: `Int` alone would + /// accept a sign, letting `1.-2` through. + init?(_ description: String) { + let components = description.split(separator: ".", omittingEmptySubsequences: false) + let numbers = components.compactMap { component in + component.allSatisfy { $0.isASCII && $0.isNumber } ? Int(component) : nil + } + + guard (1...3).contains(components.count), numbers.count == components.count else { + return nil + } + + self.init( + major: numbers[0], + minor: numbers.count > 1 ? numbers[1] : 0, + patch: numbers.count > 2 ? numbers[2] : 0 + ) + } + + var description: String { "\(major).\(minor).\(patch)" } +} diff --git a/Containers/Models/Shared/Tips.swift b/Containers/Models/Shared/Tips.swift new file mode 100644 index 0000000..ac46129 --- /dev/null +++ b/Containers/Models/Shared/Tips.swift @@ -0,0 +1,28 @@ +// +// Tips.swift +// Containers +// +// Created by Axel Martinez on 26/07/2026. +// + +import TipKit + +struct AddFirstImageTip: Tip { + @Parameter static var shouldShow: Bool = false + + var title: Text { Text("Start with an image") } + var message: Text? { + Text( + "Add your first image to get started. Images are the foundation for running containers." + ) + } + + var rules: [Rule] { + #Rule(Self.$shouldShow) { $0 == true } + } +} + +struct RunContainerTip: Tip { + var title: Text { Text("Run a container") } + var message: Text? { Text("Create and run a new container from this image.") } +} diff --git a/Containers/Models/Volumes/VolumeItem.swift b/Containers/Models/Volumes/VolumeItem.swift new file mode 100644 index 0000000..d502c8c --- /dev/null +++ b/Containers/Models/Volumes/VolumeItem.swift @@ -0,0 +1,95 @@ +// +// VolumeItem.swift +// Containers +// +// Created by Axel Martinez on 2026/02/05. +// + +import ContainerSystem +import Foundation + +enum VolumeType: String, CaseIterable, Identifiable { + case named = "Named" + case anonymous = "Anonymous" + + var id: String { rawValue } +} + +@dynamicMemberLookup +nonisolated struct VolumeItem: Identifiable, Hashable, Equatable, Sendable { + let volume: Volume + let isInUse: Bool + var activity: ActivitySnapshot? + var id: String { volume.id } + var name: String { volume.name } + var createdAt: Date { volume.createdAt } + var sizeSort: UInt64 { volume.sizeInBytes ?? 0 } + var typeText: String { volumeType.rawValue } + var stateText: String { isInUse ? "In use" : "Unused" } + + var volumeType: VolumeType { + self.volume.isAnonymous ? .anonymous : .named + } + + var labels: [String: String] { + self.volume.labels.filter({ $0.key != Volume.anonymousLabel }) + } + + var options: [String: String] { + self.volume.options.filter({ $0.key != "KB" }) + } + + init(_ item: VolumeSummary) { + self.volume = item.volume + self.isInUse = item.isInUse + } + + init(_ volume: Volume, isInUse: Bool = false) { + self.volume = volume + self.isInUse = isInUse + } + + func hash(into hasher: inout Hasher) { + hasher.combine(volume.id) + hasher.combine(volume.name) + hasher.combine(isInUse) + hasher.combine(activity) + } + + static func == (lhs: VolumeItem, rhs: VolumeItem) -> Bool { + lhs.volume.id == rhs.volume.id && lhs.volume.name == rhs.volume.name + && lhs.isInUse == rhs.isInUse && lhs.activity == rhs.activity + } + +} + +extension VolumeItem { + subscript(dynamicMember keyPath: KeyPath) -> T { + volume[keyPath: keyPath] + } +} + +// MARK: - Display Formatting + +extension VolumeItem { + var formattedCreated: String { + let formatter = DateFormatter() + formatter.dateStyle = .medium + formatter.timeStyle = .short + + return formatter.string(from: volume.createdAt) + } + + var formattedSize: String? { + guard let volumeSize = volume.sizeInBytes else { + return nil + } + + let formattedSize = ByteCountFormatter.string( + fromByteCount: Int64(volumeSize), + countStyle: .file + ) + + return formattedSize + } +} diff --git a/Containers/Supporting Files/Assets.xcassets/server.play.symbolset/Contents.json b/Containers/Supporting Files/Assets.xcassets/container.stack.fill.symbolset/Contents.json similarity index 68% rename from Containers/Supporting Files/Assets.xcassets/server.play.symbolset/Contents.json rename to Containers/Supporting Files/Assets.xcassets/container.stack.fill.symbolset/Contents.json index e44df6b..e47ef87 100644 --- a/Containers/Supporting Files/Assets.xcassets/server.play.symbolset/Contents.json +++ b/Containers/Supporting Files/Assets.xcassets/container.stack.fill.symbolset/Contents.json @@ -5,7 +5,7 @@ }, "symbols" : [ { - "filename" : "custom.server.rack.badge.play.svg", + "filename" : "container.stack.filled.svg", "idiom" : "universal" } ] diff --git a/Containers/Supporting Files/Assets.xcassets/server.play.symbolset/custom.server.rack.badge.play.svg b/Containers/Supporting Files/Assets.xcassets/container.stack.fill.symbolset/container.stack.filled.svg similarity index 60% rename from Containers/Supporting Files/Assets.xcassets/server.play.symbolset/custom.server.rack.badge.play.svg rename to Containers/Supporting Files/Assets.xcassets/container.stack.fill.symbolset/container.stack.filled.svg index 840209f..63d25bf 100644 --- a/Containers/Supporting Files/Assets.xcassets/server.play.symbolset/custom.server.rack.badge.play.svg +++ b/Containers/Supporting Files/Assets.xcassets/container.stack.fill.symbolset/container.stack.filled.svg @@ -7,20 +7,11 @@ PUBLIC "-//W3C//DTD SVG 1.1//EN" @@ -91,31 +82,22 @@ PUBLIC "-//W3C//DTD SVG 1.1//EN" - + - + - + - - - - + - - - - + - - - - + diff --git a/Containers/Supporting Files/Assets.xcassets/server.pause.symbolset/Contents.json b/Containers/Supporting Files/Assets.xcassets/container.stack.symbolset/Contents.json similarity index 68% rename from Containers/Supporting Files/Assets.xcassets/server.pause.symbolset/Contents.json rename to Containers/Supporting Files/Assets.xcassets/container.stack.symbolset/Contents.json index a08d04a..63ef3dd 100644 --- a/Containers/Supporting Files/Assets.xcassets/server.pause.symbolset/Contents.json +++ b/Containers/Supporting Files/Assets.xcassets/container.stack.symbolset/Contents.json @@ -5,7 +5,7 @@ }, "symbols" : [ { - "filename" : "custom.server.rack.badge.pause.svg", + "filename" : "container.stack.svg", "idiom" : "universal" } ] diff --git a/Containers/Supporting Files/Assets.xcassets/server.pause.symbolset/custom.server.rack.badge.pause.svg b/Containers/Supporting Files/Assets.xcassets/container.stack.symbolset/container.stack.svg similarity index 58% rename from Containers/Supporting Files/Assets.xcassets/server.pause.symbolset/custom.server.rack.badge.pause.svg rename to Containers/Supporting Files/Assets.xcassets/container.stack.symbolset/container.stack.svg index af60410..9f19759 100644 --- a/Containers/Supporting Files/Assets.xcassets/server.pause.symbolset/custom.server.rack.badge.pause.svg +++ b/Containers/Supporting Files/Assets.xcassets/container.stack.symbolset/container.stack.svg @@ -7,20 +7,11 @@ PUBLIC "-//W3C//DTD SVG 1.1//EN" @@ -91,31 +82,22 @@ PUBLIC "-//W3C//DTD SVG 1.1//EN" - + - + - + - - - - + - - - - + - - - - + diff --git a/Containers/Supporting Files/Assets.xcassets/list.clipboard.badge.symbolset/Contents.json b/Containers/Supporting Files/Assets.xcassets/list.clipboard.badge.symbolset/Contents.json new file mode 100644 index 0000000..4510842 --- /dev/null +++ b/Containers/Supporting Files/Assets.xcassets/list.clipboard.badge.symbolset/Contents.json @@ -0,0 +1,12 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "symbols" : [ + { + "filename" : "list.clipboard.badge.svg", + "idiom" : "universal" + } + ] +} diff --git a/Containers/Supporting Files/Assets.xcassets/list.clipboard.badge.symbolset/list.clipboard.badge.svg b/Containers/Supporting Files/Assets.xcassets/list.clipboard.badge.symbolset/list.clipboard.badge.svg new file mode 100644 index 0000000..9671980 --- /dev/null +++ b/Containers/Supporting Files/Assets.xcassets/list.clipboard.badge.symbolset/list.clipboard.badge.svg @@ -0,0 +1,133 @@ + + + + + + + + + + Weight/Scale Variations + Ultralight + Thin + Light + Regular + Medium + Semibold + Bold + Heavy + Black + + + + + + + + + + + Design Variations + Symbols are supported in up to nine weights and three scales. + For optimal layout with text and other symbols, vertically align + symbols with the adjacent text. + + + + + + Margins + Leading and trailing margins on the left and right side of each symbol + can be adjusted by modifying the x-location of the margin guidelines. + Modifications are automatically applied proportionally to all + scales and weights. + + + + Exporting + Symbols should be outlined when exporting to ensure the + design is preserved when submitting to Xcode. + Template v.7.0 + Requires Xcode 26 or greater + Generated from + Typeset at 100.0 points + Small + Medium + Large + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Containers/Supporting Files/Containers.entitlements b/Containers/Supporting Files/Containers.entitlements index efaf2cd..47d9075 100644 --- a/Containers/Supporting Files/Containers.entitlements +++ b/Containers/Supporting Files/Containers.entitlements @@ -2,19 +2,15 @@ - com.apple.security.temporary-exception.files.absolute-path.read-only - - /etc/resolver/ - - com.apple.security.temporary-exception.files.absolute-path.read-write - - /Users/ - + com.apple.security.app-sandbox + + com.apple.security.files.user-selected.read-write + + com.apple.security.network.client + + com.apple.security.network.server + com.apple.security.virtualization - com.apple.security.temporary-exception.apple-events - - com.apple.systemevents - diff --git a/Containers/Supporting Files/Containers.icon/Assets/Layer.png b/Containers/Supporting Files/Containers.icon/Assets/Layer.png deleted file mode 100644 index 5e449f1..0000000 Binary files a/Containers/Supporting Files/Containers.icon/Assets/Layer.png and /dev/null differ diff --git a/Containers/Supporting Files/Containers.icon/Assets/server-stack-new.png b/Containers/Supporting Files/Containers.icon/Assets/server-stack-new.png new file mode 100644 index 0000000..c5209fd Binary files /dev/null and b/Containers/Supporting Files/Containers.icon/Assets/server-stack-new.png differ diff --git a/Containers/Supporting Files/Containers.icon/icon.json b/Containers/Supporting Files/Containers.icon/icon.json index c9b5eaf..3ec53c5 100644 --- a/Containers/Supporting Files/Containers.icon/icon.json +++ b/Containers/Supporting Files/Containers.icon/icon.json @@ -17,12 +17,14 @@ }, "groups" : [ { + "blur-material" : null, "hidden" : false, "layers" : [ { "glass" : true, - "image-name" : "Layer.png", - "name" : "Layer", + "hidden" : false, + "image-name" : "server-stack-new.png", + "name" : "server-stack-new", "position" : { "scale" : 1, "translation-in-points" : [ @@ -32,6 +34,7 @@ } } ], + "lighting" : "individual", "shadow" : { "kind" : "neutral", "opacity" : 0.5 diff --git a/Containers/Supporting Files/Info.plist b/Containers/Supporting Files/Info.plist new file mode 100644 index 0000000..ff6f3b4 --- /dev/null +++ b/Containers/Supporting Files/Info.plist @@ -0,0 +1,19 @@ + + + + + CFBundleURLTypes + + + CFBundleURLName + app.containers.Containers + CFBundleTypeRole + Viewer + CFBundleURLSchemes + + containers + + + + + diff --git a/Containers/Utilities/ActivityCenter.swift b/Containers/Utilities/ActivityCenter.swift new file mode 100644 index 0000000..3e0aedf --- /dev/null +++ b/Containers/Utilities/ActivityCenter.swift @@ -0,0 +1,328 @@ +// +// ActivityCenter.swift +// Containers +// +// Created by Axel Martinez on 12/09/2026. +// + +import ContainerSystem +import Foundation +import Observation + +@Observable +@MainActor +final class ActivityCenter { + enum Kind: Hashable { + case image + case container + case volume + } + + /// An action the user took anywhere in the app. It executes until its + /// work is done and the lists showing its items have read the outcome. + @Observable + @MainActor + final class Activity: Identifiable { + /// Can change once the work reveals it, as loading an archive does. + fileprivate(set) var id: String + fileprivate(set) var title: String + fileprivate(set) var error: (any Error)? + fileprivate(set) var reportID: String? + fileprivate(set) var isStopped = false + fileprivate(set) var startedAt: Date? + /// A new one for every run, so a retry starts from nothing. + fileprivate(set) var progress: ProgressObserver? + + fileprivate var task: Task? + + /// A stopped run can take a moment to wind down, and must not speak + /// for a retry begun since. + @ObservationIgnored fileprivate var attempt = 0 + + fileprivate let work: (Progress) async throws -> String? + + let kind: Kind + let subtitle: String + let canRetry: Bool + let failureTitle: String + /// Off where the item's own state already shows the work under way. + let showsProgress: Bool + + /// One that succeeded is dropped, so only a failure or a stop ends it. + var isExecuting: Bool { + error == nil && !isStopped + } + + fileprivate init( + id: String, + kind: Kind, + title: String, + subtitle: String, + failureTitle: String, + canRetry: Bool, + showsProgress: Bool, + work: @escaping (Progress) async throws -> String? + ) { + self.id = id + self.kind = kind + self.title = title + self.subtitle = subtitle + self.failureTitle = failureTitle + self.canRetry = canRetry + self.showsProgress = showsProgress + self.work = work + } + + fileprivate func reportKind(for error: any Error) -> Report.Kind { + if error is BuildFailure { return .build } + + switch kind { + case .image: return .image + case .container: return .container + case .volume: return .volume + } + } + } + + private(set) var activities: [Activity] = [] + + /// The lists on screen, so an activity can wait for them to read its + /// outcome before it stops executing. + @ObservationIgnored private var listReloaders: [Kind: [UUID: () async -> Void]] = [:] + + private let reports: ReportManager + + init(reports: ReportManager) { + self.reports = reports + } + + func activities(ofKind kind: Kind) -> [Activity] { + activities.filter { $0.kind == kind && !isSpent($0) } + } + + /// Does nothing if the same work is already under way. `work` answers + /// with what it made, where that isn't known in advance. + func start( + id: String, + kind: Kind, + title: String, + subtitle: String = "", + failureTitle: String, + canRetry: Bool = true, + showsProgress: Bool = true, + work: @escaping (Progress) async throws -> String? + ) { + guard !activities.contains(where: { $0.id == id && $0.kind == kind }) else { + return + } + + let activity = Activity( + id: id, + kind: kind, + title: title, + subtitle: subtitle, + failureTitle: failureTitle, + canRetry: canRetry, + showsProgress: showsProgress, + work: work + ) + + activities.append(activity) + run(activity) + } + + func stop(_ id: String) { + guard let activity = activity(id), activity.isExecuting else { return } + + activity.isStopped = true + activity.task?.cancel() + } + + func retry(_ id: String) { + guard let activity = activity(id), activity.canRetry, + !activity.isExecuting + else { + return + } + + activity.error = nil + activity.reportID = nil + activity.isStopped = false + + run(activity) + } + + func run( + on id: String, + kind: Kind, + subtitle: String = "", + failureTitle: String, + showsProgress: Bool = true, + work: @escaping () async throws -> Void + ) { + if let earlier = activity(id), !earlier.isExecuting { + drop(earlier) + } + + start( + id: id, + kind: kind, + title: id, + subtitle: subtitle, + failureTitle: failureTitle, + showsProgress: showsProgress + ) { _ in + try await work() + return nil + } + } + + func isWorking(on id: String) -> Bool { + activities.contains { $0.id == id && $0.isExecuting } + } + + /// Registers a list on screen that shows items of `kind`. Remove it + /// with `removeListReloader(_:ofKind:)` once the list goes. + func addListReloader(_ id: UUID, ofKind kind: Kind, reload: @escaping () async -> Void) { + listReloaders[kind, default: [:]][id] = reload + } + + func removeListReloader(_ id: UUID, ofKind kind: Kind) { + listReloaders[kind]?[id] = nil + } + + func remove(_ id: String) { + guard let activity = activity(id) else { return } + + activity.task?.cancel() + drop(activity) + } + + func forgetFailures(reportedAs reportIDs: Set) { + activities.removeAll { activity in + !activity.isExecuting && activity.reportID.map(reportIDs.contains) == true + } + } + + /// A failure's mark leads to its report, so once that is read it goes. + private func isSpent(_ activity: Activity) -> Bool { + guard activity.error != nil, let reportID = activity.reportID else { + return false + } + + return reports.isRead(reportID) + } + + private func activity(_ id: String) -> Activity? { + activities.first { $0.id == id } + } + + private func run(_ activity: Activity) { + activity.attempt += 1 + activity.startedAt = Date() + + let attempt = activity.attempt + let reports = reports + let progress = Progress.discreteProgress(totalUnitCount: 0) + + activity.progress = ProgressObserver(progress) + activity.task = Task { [weak self] in + do { + let made = try await activity.work(progress) + + guard activity.attempt == attempt else { return } + + if let made, made != activity.id { + activity.id = made + activity.title = made + } + + await self?.reloadLists(ofKind: activity.kind) + + self?.drop(activity) + } catch { + guard activity.attempt == attempt, !activity.isStopped else { return } + + // A failed action can still have changed its item. + await self?.reloadLists(ofKind: activity.kind) + + guard activity.attempt == attempt, !activity.isStopped else { return } + + activity.error = error + + let entry = await reports.record( + kind: activity.reportKind(for: error), + name: activity.title, + message: activity.failureTitle, + error: error, + startedAt: activity.startedAt + ) + + activity.reportID = entry?.id + } + } + } + + /// A list that isn't on screen reads everything again when it appears. + /// Unstructured, so stopping the activity can't cancel a list's load + /// and have it report a failure. + private func reloadLists(ofKind kind: Kind) async { + let reloaders = listReloaders[kind, default: [:]].values + + await Task { + for reload in reloaders { + await reload() + } + }.value + } + + private func drop(_ activity: Activity) { + activities.removeAll { $0 === activity } + } +} + +// MARK: - Rows + +extension ActivityCenter { + /// Attaches each row's work, or else an unread failure reported under the + /// name `reportName` gives it, where it gives one. + /// + /// Given `pendingRow`, work of `kind` with no row yet gets one, keyed by + /// the item it will make, so it becomes that item's row in place. + func marked( + _ rows: [Row], + ofKind kind: Kind, + reportName: (Row) -> String?, + reportKinds: Set, + pendingRow: ((ActivitySnapshot) -> Row)? = nil + ) -> [Row] { + let working = activities(ofKind: kind) + + let marked = rows.map { row in + var row = row + + if let activity = working.first(where: { $0.id == row.id }) { + row.activity = ActivitySnapshot(activity) + } else if let name = reportName(row), + let report = reports.latestReport(named: name, ofKind: reportKinds), + !report.isRead + { + // Keyed by the row: an image is reported under the reference + // asked for, but its row is known by the resolved one. + row.activity = ActivitySnapshot(report: report, id: row.id) + } + + return row + } + + guard let pendingRow else { return marked } + + let markedIDs = Set(marked.map(\.id)) + let pending = + working + .filter { !markedIDs.contains($0.id) } + .map { pendingRow(ActivitySnapshot($0)) } + + return pending + marked + } +} diff --git a/Containers/Utilities/ProgressObserver.swift b/Containers/Utilities/ProgressObserver.swift new file mode 100644 index 0000000..3a7c18e --- /dev/null +++ b/Containers/Utilities/ProgressObserver.swift @@ -0,0 +1,76 @@ +// +// ProgressObserver.swift +// Containers +// +// Created by Axel Martinez on 2026/10/02. +// + +import Foundation +import Observation +import os + +/// A `Progress` as SwiftUI can watch it. +/// +/// `Progress` reports changes through key-value observing, on whichever thread +/// made them; this repeats what it says on the main actor, at most once for +/// each turn of it however many changes arrive in between. +@Observable +@MainActor +final class ProgressObserver { + let progress: Progress + + /// `nil` while nobody knows how much there is to do. + private(set) var fractionCompleted: Double? + private(set) var localizedDescription = "" + private(set) var localizedAdditionalDescription = "" + + @ObservationIgnored private var observations: [NSKeyValueObservation] = [] + + init(_ progress: Progress) { + self.progress = progress + refresh() + observations = Self.observe(progress) { [weak self] in + self?.refresh() + } + } + + private func refresh() { + // TODO: Review this implementation + // A step's handler sets its total and then its count, in two writes, on whichever thread + // reports progress. This runs on the main actor whenever it's scheduled, without taking + // the handler's lock, so it can read between the two: the new, larger total against the + // old count, which shows less done than before. A run only moves forward, so keep the + // highest fraction seen. + fractionCompleted = progress.isIndeterminate ? nil : max(fractionCompleted ?? 0, progress.fractionCompleted) + localizedDescription = progress.localizedDescription ?? "" + localizedAdditionalDescription = progress.localizedAdditionalDescription ?? "" + } + + private nonisolated static func observe( + _ progress: Progress, + onChange: @escaping @MainActor () -> Void + ) -> [NSKeyValueObservation] { + let isScheduled = OSAllocatedUnfairLock(initialState: false) + + let changed: @Sendable () -> Void = { + let schedule = isScheduled.withLock { isScheduled in + defer { isScheduled = true } + return !isScheduled + } + + guard schedule else { return } + + Task { @MainActor in + isScheduled.withLock { $0 = false } + onChange() + } + } + + return [ + progress.observe(\.fractionCompleted) { _, _ in changed() }, + progress.observe(\.isIndeterminate) { _, _ in changed() }, + progress.observe(\.localizedDescription) { _, _ in changed() }, + progress.observe(\.localizedAdditionalDescription) { _, _ in changed() }, + ] + } +} diff --git a/Containers/Utilities/WindowResizer.swift b/Containers/Utilities/WindowResizer.swift new file mode 100644 index 0000000..a6d222e --- /dev/null +++ b/Containers/Utilities/WindowResizer.swift @@ -0,0 +1,206 @@ +// +// WindowResizer.swift +// Containers +// +// Created by Axel Martinez on 23/5/26. +// + +import AppKit + +final class ResizeConstrainer: NSObject, NSWindowDelegate { + var constraints = WindowConstraints() + /// Nonisolated for the forwarding below; delegate calls arrive on main. + nonisolated(unsafe) weak var next: NSWindowDelegate? + + func windowWillResize(_ sender: NSWindow, to frameSize: NSSize) -> NSSize { + var size = + next?.windowWillResize?(sender, to: frameSize) ?? frameSize + + if constraints.widthIsFixed { + size.width = sender.frame.width + } else { + size.width = min( + max(size.width, constraints.minWidth), + constraints.maxWidth + ) + } + + if constraints.heightIsFixed { + size.height = sender.frame.height + } + + return size + } + + func windowWillUseStandardFrame(_ window: NSWindow, defaultFrame: NSRect) + -> NSRect + { + var frame = window.frame + + if !constraints.widthIsFixed { + frame.size.width = min(defaultFrame.width, constraints.maxWidth) + } + + if !constraints.heightIsFixed { + frame.size.height = defaultFrame.height + } + frame.origin.y = window.frame.maxY - frame.height + + return frame + } + + // AppKit checks `responds(to:)` before sending an optional delegate + // method, so both are needed to forward the rest to SwiftUI. + nonisolated override func responds(to aSelector: Selector!) -> Bool { + super.responds(to: aSelector) || next?.responds(to: aSelector) == true + } + + nonisolated override func forwardingTarget(for aSelector: Selector!) -> Any? { + next + } +} + +struct WindowConstraints: Equatable { + /// Set per axis when the window already shows everything on that axis: + /// there is nothing a drag could reveal, so it is refused. + var heightIsFixed = true + var widthIsFixed = true + var minWidth: CGFloat = 0 + var maxWidth: CGFloat = .greatestFiniteMagnitude + + var isFixed: Bool { heightIsFixed && widthIsFixed } +} + +/// Animates the window height — the one step SwiftUI has no hook for. +@MainActor +final class WindowResizer { + private weak var window: NSWindow? + private var requestedSize: CGSize? + private var requestedDuration: TimeInterval = 0 + private var constraints = WindowConstraints() + private let constrainer = ResizeConstrainer() + + /// Deferred a turn: this runs inside the render pass mutating the + /// window reenters. Replays a fit that lost the race to the window. + func bind(to window: NSWindow?) { + guard let window, window !== self.window else { return } + self.window = window + + Task { @MainActor in + guard self.window === window else { return } + + attachConstrainer(to: window) + apply(constraints, to: window) + + if let size = requestedSize { + await fit(size: size, duration: requestedDuration) + } + } + } + + var visibleScreenHeight: CGFloat? { + (window?.screen ?? NSScreen.main)?.visibleFrame.height + } + + var visibleScreenWidth: CGFloat? { + (window?.screen ?? NSScreen.main)?.visibleFrame.width + } + + func setConstraints(_ constraints: WindowConstraints) { + self.constraints = constraints + constrainer.constraints = constraints + + Task { @MainActor in + guard let window, self.constraints == constraints else { + return + } + apply(constraints, to: window) + } + } + + private func apply( + _ constraints: WindowConstraints, + to window: NSWindow + ) { + // The style mask covers both axes at once, so a window resizable on + // one of them keeps it and the delegate holds the other. A window + // showing all of its content on both loses it, handle and all. + if constraints.isFixed { + window.styleMask.remove(.resizable) + } else { + window.styleMask.insert(.resizable) + } + + window.collectionBehavior.remove(.fullScreenPrimary) + window.collectionBehavior.insert(.fullScreenNone) + + } + + private func attachConstrainer(to window: NSWindow) { + guard window.delegate !== constrainer else { return } + + constrainer.next = window.delegate + window.delegate = constrainer + } + + private func waitUntilOnScreen(_ window: NSWindow) async { + let deadline = ContinuousClock.now.advanced(by: .milliseconds(300)) + + while !window.isVisible, ContinuousClock.now < deadline { + await Task.yield() + try? await Task.sleep(for: .milliseconds(8)) + } + } + + /// Returns once the window has settled. Zero duration skips the animation. + func fit(size: CGSize, duration: TimeInterval) async { + guard size.height > 0 else { return } + requestedSize = size + requestedDuration = duration + + guard let window else { return } + + // An off-screen window has nothing to animate, so it would snap. + if duration > 0, !window.isVisible { + await waitUntilOnScreen(window) + } + + // Convert through the window: contentView and frame disagree while an + // earlier resize is still animating. + var contentRect = window.contentRect(forFrameRect: window.frame) + + // Only contentLayoutRect is the view's, so add the toolbar strip. + let chrome = contentRect.height - window.contentLayoutRect.height + let target = CGSize(width: size.width, height: size.height + chrome) + + guard + abs(contentRect.height - target.height) > 0.5 + || abs(contentRect.width - target.width) > 0.5 + else { return } + + contentRect.size = target + var frame = window.frameRect(forContentRect: contentRect) + + frame.origin.y = window.frame.maxY - frame.height + frame.origin.x = window.frame.midX - frame.width / 2 + + guard window.isVisible, duration > 0 else { + window.setFrame(frame, display: false) + return + } + + // TODO: A web-view tab logs "NSHostingView is being laid out + // reentrantly" each tick — harmless; duration 0 silences it. + await withCheckedContinuation { continuation in + NSAnimationContext.runAnimationGroup { context in + context.duration = duration + context.timingFunction = CAMediaTimingFunction( + name: .easeInEaseOut + ) + window.animator().setFrame(frame, display: true) + } completionHandler: { + continuation.resume() + } + } + } +} diff --git a/Containers/ViewModels/ContainerViewModel.swift b/Containers/ViewModels/ContainerViewModel.swift deleted file mode 100644 index 0244fa7..0000000 --- a/Containers/ViewModels/ContainerViewModel.swift +++ /dev/null @@ -1,98 +0,0 @@ -// -// ContainerViewModel.swift -// Containers -// -// Created by Axel Martinez on 2026/02/05. -// - -import Foundation -import ContainerizationOCI -import ContainerNetworkService -import ContainerResource -import ContainerizationExtras - -struct ContainerViewModel: Identifiable, Hashable, Equatable { - var id: String - var image: ImageDescription - var status: RuntimeStatus - var snapshot: ContainerSnapshot - - var imageName: String { - return self.image.reference - } - - init(_ snapshot: ContainerSnapshot) { - self.id = snapshot.configuration.id - self.image = snapshot.configuration.image - self.status = snapshot.status - self.snapshot = snapshot - } - - // Hashable conformance - func hash(into hasher: inout Hasher) { - hasher.combine(id) - hasher.combine(status) - hasher.combine(snapshot.configuration.image.digest) - } - - // Equatable conformance - static func == (lhs: ContainerViewModel, rhs: ContainerViewModel) -> Bool { - return lhs.id == rhs.id && - lhs.status == rhs.status && - lhs.snapshot.configuration.image.digest == rhs.snapshot.configuration.image.digest - } -} - -// MARK: - Display Formatting - -extension ContainerViewModel { - var formattedPorts: String { - let ports = snapshot.configuration.publishedPorts.map { - "\($0.hostAddress):\($0.hostPort)\u{2192}\($0.containerPort)/\($0.proto.rawValue)" - }.joined(separator: "\n") - return ports.isEmpty ? "-" : ports - } - - var hasIPAddress: Bool { - return !snapshot.networks.isEmpty - } - - var formattedIPAddress: String { - if let network = snapshot.networks.first { - let addressString = network.ipv4Address.description - return String(addressString.split(separator: "/").first ?? Substring(addressString)) - } else { - return "-" - } - } - - var formattedOS: String { - snapshot.configuration.platform.os.localizedCapitalized - } - - var formattedArch: String { - snapshot.configuration.platform.architecture.localizedCapitalized - } - - var formattedCPUs: String { - "\(snapshot.configuration.resources.cpus)" - } - - var formattedMemory: String { - "\(snapshot.configuration.resources.memoryInBytes / (1024 * 1024)) MB" - } - - var formattedState: String { - status.rawValue.localizedCapitalized - } - - var formattedStarted: String { - guard let startedDate = snapshot.startedDate else { - return "" - } - let formatter = DateFormatter() - formatter.dateStyle = .short - formatter.timeStyle = .medium - return formatter.string(from: startedDate) - } -} diff --git a/Containers/ViewModels/ImageViewModel.swift b/Containers/ViewModels/ImageViewModel.swift deleted file mode 100644 index e14fe3c..0000000 --- a/Containers/ViewModels/ImageViewModel.swift +++ /dev/null @@ -1,116 +0,0 @@ -// -// ImageViewModel.swift -// Containers -// -// Created by Axel Martinez on 2026/02/05. -// - -import Foundation -import ContainerAPIService -import ContainerizationOCI -import ContainerResource - -/// Represents the type of container volume -enum VolumeType: String, CaseIterable, Identifiable { - /// Named volume with persistent identifier - case named = "Named" - - /// Anonymous volume created automatically - case anonymous = "Anonymous" - - var id: String { rawValue } -} - -struct ImageViewModel: Identifiable, Hashable, Equatable { - var name: String - var tag: String - var indexDigest: String - var rawOS: String - var rawArch: String - var variant: String - var sizeInBytes: Int64 - var createdDate: Date? - var manifestDigest: String - var inUseContainers: [ContainerSnapshot] - var imageDescription: ImageDescription - - var inUse: Bool { - return !inUseContainers.isEmpty - } - - var id: String { - return indexDigest + manifestDigest + (createdDate?.description ?? "") - } - - /// Initialize from ImageDescription (simplified, without full image details) - init(_ description: ImageDescription, containers: [ContainerSnapshot], variant: String? = nil, created: Date? = nil, os: String? = nil, architecture: String? = nil) { - self.imageDescription = description - - // Parse reference to get name and tag - if let reference = try? ContainerizationOCI.Reference.parse(description.reference) { - self.name = reference.name - self.tag = reference.tag ?? "" - } else { - self.name = description.reference - self.tag = "" - } - - self.indexDigest = description.digest - self.manifestDigest = description.digest - self.rawOS = os ?? "Linux" - self.rawArch = architecture ?? Platform.current.architecture - self.variant = variant ?? "" - self.sizeInBytes = description.descriptor.size - self.createdDate = created - - self.inUseContainers = containers.filter { $0.configuration.image.digest == description.digest } - } - - // Hashable conformance - func hash(into hasher: inout Hasher) { - hasher.combine(indexDigest) - hasher.combine(manifestDigest) - hasher.combine(inUseContainers.count) - } - - // Equatable conformance - static func == (lhs: ImageViewModel, rhs: ImageViewModel) -> Bool { - return lhs.indexDigest == rhs.indexDigest && - lhs.manifestDigest == rhs.manifestDigest && - lhs.inUseContainers.count == rhs.inUseContainers.count - } -} - -// MARK: - Display Formatting - -extension ImageViewModel { - var formattedDigest: String { - var d = indexDigest - if d.hasPrefix("sha256:") { - d = String(d.dropFirst("sha256:".count)) - } - return d - } - - var formattedSize: String { - ByteCountFormatter.string(fromByteCount: sizeInBytes, countStyle: .file) - } - - var formattedOS: String { - rawOS.localizedCapitalized - } - - var formattedArch: String { - rawArch.localizedCapitalized - } - - var formattedCreated: String { - guard let date = createdDate else { - return "" - } - let formatter = DateFormatter() - formatter.dateStyle = .medium - formatter.timeStyle = .short - return formatter.string(from: date) - } -} diff --git a/Containers/ViewModels/RegistryLookup.swift b/Containers/ViewModels/RegistryLookup.swift new file mode 100644 index 0000000..3c3054f --- /dev/null +++ b/Containers/ViewModels/RegistryLookup.swift @@ -0,0 +1,171 @@ +// +// RegistryLookup.swift +// Containers +// +// Created by Axel Martinez on 29/09/2026. +// + +import Foundation +import Observation + +/// Asks a registry what the Pull sheet offers: what is trending, and what matches the image and tag being typed. +@Observable +@MainActor +final class RegistryLookup { + private(set) var trendingImages: [ImageSuggestion] = [] + private(set) var isLoading = false + + @ObservationIgnored private var trendingRegistry: Registry? + + func loadTrendingImages(on registry: Registry) async { + if registry != trendingRegistry { + trendingRegistry = registry + trendingImages = [] + } + + isLoading = true + + let provider = registry.provider + var images: [ImageSuggestion] = [] + + if let request = provider.featuredImages, let current = try? await Self.perform(request) { + images = current + } + + images = await Self.withLogos(images, from: provider) + + // A newer load has taken over. + guard !Task.isCancelled else { return } + + trendingImages = withoutSharedArtwork(images) + isLoading = false + } + + func images(matching text: String, on registry: Registry) async throws -> [String] { + guard let request = registry.provider.imageSearch(matching: text) else { + return [] + } + + return try await Self.perform(request) + } + + func tags( + for imageName: String, + matching text: String, + on registry: Registry + ) async throws -> [String] { + guard + let request = registry.provider.tagSearch(for: imageName, matching: text) + else { + return [] + } + + return try await Self.perform(request) + } + + private nonisolated static let fetchedAtKey = "fetchedAt" + + /// Reuses an answer kept in the URL cache while the request says it is + /// still good. The registry's own cache headers aren't what decides that, + /// so the cache is read and written here rather than left to the session. + private static func perform( + _ request: RegistryRequest + ) async throws -> Response { + var urlRequest = URLRequest(url: request.url) + urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") + urlRequest.cachePolicy = .reloadIgnoringLocalCacheData + + if let lifetime = request.lifetime, + let cached = URLCache.shared.cachedResponse(for: urlRequest), + let fetchedAt = cached.userInfo?[fetchedAtKey] as? Date, + .seconds(Date.now.timeIntervalSince(fetchedAt)) < lifetime, + let response = try? request.decode(cached.data) + { + return response + } + + let (data, response) = try await URLSession.shared.data(for: urlRequest) + + guard let httpResponse = response as? HTTPURLResponse else { + throw RegistryError.unavailable + } + + guard httpResponse.statusCode == 200 else { + throw httpResponse.statusCode == 429 + ? RegistryError.rateLimited : RegistryError.unavailable + } + + let decoded = try request.decode(data) + + if request.lifetime != nil { + URLCache.shared.storeCachedResponse( + CachedURLResponse( + response: response, + data: data, + userInfo: [fetchedAtKey: Date.now], + storagePolicy: .allowed + ), + for: urlRequest + ) + } + + return decoded + } + + private nonisolated static func withLogos( + _ images: [ImageSuggestion], + from provider: any RegistryProvider + ) async -> [ImageSuggestion] { + await withTaskGroup(of: (Int, URL?).self) { group in + for (index, image) in images.enumerated() where image.imageURL == nil { + guard let request = provider.logo(for: image.name) else { continue } + + group.addTask { + (index, (try? await perform(request)) ?? nil) + } + } + + var withLogos = images + + for await (index, logo) in group { + guard let logo else { continue } + + let image = withLogos[index] + withLogos[index] = ImageSuggestion( + name: image.name, + publisher: image.publisher, + description: image.description, + imageURL: logo + ) + } + + return withLogos + } + } + + /// A publisher's repositories often scrape the same logo, and a row of + /// identical icons reads as a bug. Drop the artwork they share so those + /// fall back to initials, keeping the ones that are actually distinct. + private func withoutSharedArtwork( + _ images: [ImageSuggestion] + ) -> [ImageSuggestion] { + let counts = images.reduce(into: [URL: Int]()) { counts, image in + if let url = image.imageURL { + counts[url, default: 0] += 1 + } + } + + return images.map { image in + guard let url = image.imageURL, counts[url, default: 0] > 1 else { + return image + } + + return ImageSuggestion( + name: image.name, + publisher: image.publisher, + description: image.description, + imageURL: nil + ) + } + } +} diff --git a/Containers/ViewModels/ResourcesViewModel.swift b/Containers/ViewModels/ResourcesViewModel.swift deleted file mode 100644 index c8cdf23..0000000 --- a/Containers/ViewModels/ResourcesViewModel.swift +++ /dev/null @@ -1,13 +0,0 @@ -// -// ResourcesViewModel.swift -// Containers -// -// Created by Axel Martinez on 10/2/26. -// - -struct ResourcesViewModel { - var memoryUsage: Double = 0.0 // in GB - var cpuUsage: Double = 0.0 // percentage - var diskUsage: Double = 0.0 // in GB - var diskLimit: Double = 50.0 // in GB -} diff --git a/Containers/ViewModels/SystemActions.swift b/Containers/ViewModels/SystemActions.swift new file mode 100644 index 0000000..76ca556 --- /dev/null +++ b/Containers/ViewModels/SystemActions.swift @@ -0,0 +1,106 @@ +// +// SystemActions.swift +// Containers +// +// Created by Axel Martinez on 27/09/2026. +// + +import AppKit +import ContainerSystem +import Foundation +import Observation + +/// What can be asked of the container system. +@Observable +@MainActor +final class SystemActions { + enum Action { + case toggle + case reload + case quit + } + + struct Failure: Error { + let title: String + let underlying: any Error + } + + /// The action under way, if any. + private(set) var working: Action? + + private let manager: SystemManager + + init(manager: SystemManager) { + self.manager = manager + } + + var isRunning: Bool { + manager.status == .running + } + + func title(for action: Action) -> String { + switch action { + case .toggle: isRunning ? "Stop" : "Start" + case .reload: "Reload" + case .quit: "Quit" + } + } + + func symbol(for action: Action) -> String { + switch action { + case .toggle: isRunning ? "stop" : "play.fill" + case .reload: "arrow.clockwise" + case .quit: "power" + } + } + + func isEnabled(_ action: Action) -> Bool { + let isSettled = + working == nil && manager.status != .starting + && manager.status != .stopping + + switch action { + case .toggle: return isSettled + case .reload: return isSettled && isRunning + case .quit: return working == nil + } + } + + func perform(_ action: Action) async throws(Failure) { + let title = failureTitle(for: action) + working = action + + defer { working = nil } + + do { + switch action { + case .toggle where isRunning: + try await manager.stop() + case .toggle: + try await start() + case .reload: + try await manager.stop() + try await start() + case .quit: + // Left running, the system would outlive the app. + try? await manager.stop() + NSApplication.shared.terminate(nil) + } + } catch { + throw Failure(title: title, underlying: error) + } + } + + private func start() async throws { + try await manager.start(appRoot: UserDefaults.applicationDataRoot) + } + + private func failureTitle(for action: Action) -> String { + switch action { + case .toggle where isRunning: "The container system couldn’t stop." + case .toggle: "The container system couldn’t start." + case .reload: "The container system couldn’t reload." + case .quit: "The container system couldn’t stop." + } + } +} diff --git a/Containers/ViewModels/VolumeViewModel.swift b/Containers/ViewModels/VolumeViewModel.swift deleted file mode 100644 index 81e115c..0000000 --- a/Containers/ViewModels/VolumeViewModel.swift +++ /dev/null @@ -1,85 +0,0 @@ -// -// VolumeViewModel.swift -// Containers -// -// Created by Axel Martinez on 2026/02/05. -// - -import Foundation -import ContainerResource - -@dynamicMemberLookup -struct VolumeViewModel: Identifiable, Hashable, Equatable { - var volume: Volume - var inUseContainers: [ContainerSnapshot] - - var inUse: Bool { - return !inUseContainers.isEmpty - } - - var volumeType: VolumeType { - self.volume.isAnonymous ? .anonymous : .named - } - - var labels: [String : String] { - self.volume.labels.filter({$0.key != Volume.anonymousLabel}) - } - - var options: [String : String] { - self.volume.options.filter({$0.key != "KB"}) - } - - var id: String { - return volume.id - } - - init(_ volume: Volume, containers: [ContainerSnapshot]) { - self.volume = volume - self.inUseContainers = containers.filter({ container in - container.volumeNames.contains(volume.name) - }) - } - - // Hashable conformance - func hash(into hasher: inout Hasher) { - hasher.combine(volume.id) - hasher.combine(volume.name) - hasher.combine(inUseContainers.count) - } - - // Equatable conformance - static func == (lhs: VolumeViewModel, rhs: VolumeViewModel) -> Bool { - return lhs.volume.id == rhs.volume.id && - lhs.volume.name == rhs.volume.name && - lhs.inUseContainers.count == rhs.inUseContainers.count - } - -} - -extension VolumeViewModel { - subscript(dynamicMember keyPath: KeyPath) -> T { - return volume[keyPath: keyPath] - } -} - -// MARK: - Display Formatting - -extension VolumeViewModel { - var formattedCreated: String { - let formatter = DateFormatter() - formatter.dateStyle = .medium - formatter.timeStyle = .short - - return formatter.string(from: volume.createdAt) - } - - var formattedSize: String? { - guard let volumeSize = volume.sizeInBytes else { - return nil - } - - let formattedSize = ByteCountFormatter.string(fromByteCount: Int64(volumeSize), countStyle: .file) - - return formattedSize - } -} diff --git a/Containers/Views/Components/ActionButton.swift b/Containers/Views/Components/ActionButton.swift new file mode 100644 index 0000000..a7af977 --- /dev/null +++ b/Containers/Views/Components/ActionButton.swift @@ -0,0 +1,45 @@ +// +// ActionButton.swift +// Containers +// +// Created by Axel Martinez on 24/5/26. +// + +import SwiftUI + +struct ActionButton: View { + let label: String + let icon: String + let help: String + let action: () -> Void + let role: ButtonRole? = nil + + init( + label: String, + icon: String, + help: String, + role: ButtonRole? = nil, + action: @escaping () -> Void + ) { + self.label = label + self.icon = icon + self.help = help + self.action = action + } + + var body: some View { + Button(role: role) { + action() + } label: { + Label(label, systemImage: icon) + } + .help(help) + } +} + +extension ActionButton: Equatable { + static func == (lhs: ActionButton, rhs: ActionButton) -> Bool { + lhs.help == rhs.help && lhs.label == rhs.label && lhs.icon == rhs.icon + && lhs.role == rhs.role + } +} diff --git a/Containers/Views/Components/BarToggle.swift b/Containers/Views/Components/BarToggle.swift new file mode 100644 index 0000000..cbd5ca0 --- /dev/null +++ b/Containers/Views/Components/BarToggle.swift @@ -0,0 +1,147 @@ +// +// BarToggle.swift +// Containers +// +// Created by Axel Martinez on 21/09/2026. +// + +import SwiftUI + +/// A toggle for bars: one of several choices, or a standalone switch. +/// Shared by every bar so their padding and fills stay identical. +struct BarToggle: View { + enum Manner { + /// Secondary until selected or hovered. + case choice + /// Picks what's shown below the bar; the selected one is filled with the accent colour. + case tab + /// A standalone on/off button. + case control + /// A sheet's tabs: the selected one is tinted rather than filled. + case segment + } + + let title: String + var manner: Manner = .choice + + @Binding var isOn: Bool + + @State private var isHovered = false + + var body: some View { + Group { + switch manner { + case .choice, .tab, .segment: word + case .control: control + } + } + .font(.callout) + } + + private static let cornerRadius: CGFloat = 5 + + private var word: some View { + Button { + isOn = true + } label: { + Text(title) + } + .buttonStyle( + WordStyle( + foreground: foreground, + background: background, + pressed: pressed, + cornerRadius: Self.cornerRadius + ) + ) + .onHover { isHovered = $0 } + } + + private var pressed: Color { + isOn ? background : Color(nsColor: .tertiaryLabelColor).opacity(0.6) + } + + /// A custom style, since the plain style doesn't expose the pressed state. + private struct WordStyle: ButtonStyle { + let foreground: AnyShapeStyle + let background: Color + let pressed: Color + let cornerRadius: CGFloat + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .foregroundStyle(foreground) + .padding(.horizontal, 10) + .padding(.vertical, 3) + .background( + RoundedRectangle(cornerRadius: cornerRadius) + .fill(configuration.isPressed ? pressed : background) + ) + .contentShape(Rectangle()) + } + } + + private var control: some View { + Toggle(title, isOn: $isOn) + .toggleStyle(.button) + .buttonStyle(.accessoryBar) + .controlSize(.small) + } + + private var foreground: AnyShapeStyle { + switch manner { + case .tab where isOn: + AnyShapeStyle(Color(nsColor: .alternateSelectedControlTextColor)) + case .segment where isOn: + AnyShapeStyle(Color(nsColor: .controlAccentColor)) + case .choice where !isOn && !isHovered: + AnyShapeStyle(.secondary) + default: + AnyShapeStyle(.primary) + } + } + + private var background: Color { + if isOn { + // `Color.accentColor` desaturates when SwiftUI reads the control as + // inactive; the system accent keeps its colour. + switch manner { + case .tab: + return Color(nsColor: .controlAccentColor) + case .segment: + return Color(nsColor: .controlAccentColor).opacity(0.15) + default: + return Color( + nsColor: .unemphasizedSelectedContentBackgroundColor + ) + } + } + + guard manner != .tab else { return Color(nsColor: .quinaryLabel) } + + return isHovered ? Color(nsColor: .quaternaryLabelColor) : .clear + } +} + +extension BarToggle { + /// On while `selection` equals `value`. It can't be turned off, since one is always selected. + init( + _ title: String, + selection: Binding, + value: Value, + manner: Manner = .choice + ) { + self.init( + title: title, + manner: manner, + isOn: Binding( + get: { selection.wrappedValue == value }, + set: { isOn in + guard isOn else { return } + + selection.wrappedValue = value + } + ) + ) + } +} diff --git a/Containers/Views/Components/FileSelection.swift b/Containers/Views/Components/FileSelection.swift new file mode 100644 index 0000000..74b1eb4 --- /dev/null +++ b/Containers/Views/Components/FileSelection.swift @@ -0,0 +1,404 @@ +// +// FileSelection.swift +// Containers +// +// Created by Axel Martinez on 2026/02/08. +// + +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +struct FileSelection: View { + /// How the choice is presented. + enum Style { + /// A pop-up of places to choose among, and nothing else: the path is + /// picked, never written. + case popUp + /// The path itself, editable, beside a button that opens the panel — + /// what suits a field whose answer can be written or made, not only + /// found. + case field + } + + /// How the pop-up writes a location out. + enum Label { + /// The name Finder gives it, localised and without the path. + case name + /// The whole path, so two locations sharing a name stay apart. + case path + } + + /// Which places picked before the pop-up offers again. + enum Recents: String { + case tarArchive + case mountSource + } + + /// A place the pop-up can offer. + struct Location: Hashable, CustomStringConvertible { + let url: URL? + + var description: String { + url?.path ?? "" + } + + var icon: NSImage? { + guard let url else { return nil } + + let icon = NSWorkspace.shared.icon(forFile: url.path) + icon.size = NSSize(width: 16, height: 16) + return icon + } + } + + let placeholder: String + let fileURL: Binding + let allowedContentTypes: [UTType] + let canChooseDirectories: Bool + let canCreateDirectories: Bool + let defaultDirectory: URL? + let locations: [URL] + let style: Style + let label: Label + let recents: Recents? + let suggestedSaveFilename: String? + let onSelection: (() -> Void)? + let isPresented: Binding? + + @Environment(\.isEnabled) private var isEnabled + @SwiftUI.State private var recentURLs: [URL] = [] + + init( + placeholder: String, + fileURL: Binding, + allowedContentTypes: [UTType] = [], + canChooseDirectories: Bool = false, + canCreateDirectories: Bool = false, + defaultDirectory: URL? = nil, + locations: [URL] = [], + style: Style = .popUp, + label: Label = .name, + recents: Recents? = nil, + suggestedSaveFilename: String? = nil, + onSelection: (() -> Void)? = nil, + isPresented: Binding? = nil + ) { + self.placeholder = placeholder + self.fileURL = fileURL + self.allowedContentTypes = allowedContentTypes + self.canChooseDirectories = canChooseDirectories + self.canCreateDirectories = canCreateDirectories + self.defaultDirectory = defaultDirectory + self.locations = locations + self.style = style + self.label = label + self.recents = recents + self.suggestedSaveFilename = suggestedSaveFilename + self.onSelection = onSelection + self.isPresented = isPresented + } + + /// Files a picker can offer in place of the standard folders, gathered + /// from `directories` without descending into them. + static func files( + in directories: [URL?], + matching matches: (URL) -> Bool + ) -> [URL] { + var seen = Set() + + return + directories + .compactMap { $0 } + .filter { seen.insert($0.standardizedFileURL.path).inserted } + .flatMap { directory in + (try? FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: [ + .contentTypeKey, .contentModificationDateKey, + ], + options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants] + )) ?? [] + } + .filter(matches) + .sorted { modificationDate(of: $0) > modificationDate(of: $1) } + } + + private static func modificationDate(of url: URL) -> Date { + (try? url.resourceValues(forKeys: [.contentModificationDateKey]) + .contentModificationDate) ?? .distantPast + } + + static var userHomeDirectory: URL { + guard let entry = getpwuid(getuid()), let path = entry.pointee.pw_dir + else { + return .homeDirectory + } + + return URL( + fileURLWithFileSystemRepresentation: path, + isDirectory: true, + relativeTo: nil + ) + } + + private static var standardDirectories: [URL] { + let home = userHomeDirectory + + return [ + home, + home.appending(path: "Desktop"), + home.appending(path: "Documents"), + home.appending(path: "Downloads"), + ] + } + + /// The offered places, led by whatever is currently selected so the button + /// has a titled entry to show for it. + private var options: [Location] { + var urls: [URL] = [] + + if let current = fileURL.wrappedValue { + urls.append(current) + } + + urls += recentURLs + + if !locations.isEmpty { + urls += locations + } else if canChooseDirectories { + urls += [defaultDirectory].compactMap { $0 } + urls += Self.standardDirectories + } + + var seen = Set() + return urls.compactMap { url in + seen.insert(url.standardizedFileURL.path).inserted + ? Location(url: url) : nil + } + } + + private var actionTitle: String { + options.isEmpty ? "Choose..." : "Other..." + } + + private var selection: Binding { + Binding { + Location(url: fileURL.wrappedValue) + } set: { location in + fileURL.wrappedValue = location.url + onSelection?() + + if let url = location.url { + remember(url) + } + } + } + + private func remember(_ url: URL) { + guard let recents else { return } + + RecentLocations.remember(url, for: recents) + recentURLs = RecentLocations.urls(for: recents) + } + + private func title(for location: Location) -> String { + guard let url = location.url else { return "" } + + switch label { + case .name: + let name = FileManager.default.displayName(atPath: url.path) + return name.isEmpty ? url.lastPathComponent : name + case .path: + return location.description + } + } + + private var popUp: some View { + FormPicker( + placeholder: placeholder, + options: options, + selection: selection, + actionTitle: actionTitle, + onAction: selectFile, + title: title(for:), + icon: \.icon + ) + } + + private var path: Binding { + Binding { + fileURL.wrappedValue?.path ?? "" + } set: { typed in + let typed = typed.trimmingCharacters(in: .whitespacesAndNewlines) + + fileURL.wrappedValue = + typed.isEmpty ? nil : URL(filePath: expanding(typed)) + onSelection?() + } + } + + /// A leading `~` means the person's home, which is not what + /// `expandingTildeInPath` resolves to from inside the sandbox. + private func expanding(_ path: String) -> String { + guard path == "~" || path.hasPrefix("~/") else { return path } + + return Self.userHomeDirectory.path + path.dropFirst() + } + + private var field: some View { + FormField( + placeholder: placeholder, + value: path, + actionIcon: "folder", + actionTitle: "Choose", + action: selectFile + ) + } + + var body: some View { + Group { + switch style { + case .popUp: + popUp + case .field: + field + } + } + .onChange(of: isPresented?.wrappedValue ?? false) { _, isPresented in + guard isPresented else { return } + selectFile() + self.isPresented?.wrappedValue = false + } + .task { + guard style == .popUp, let recents else { return } + recentURLs = RecentLocations.urls(for: recents) + } + .task(id: options.first) { + guard style == .popUp, isEnabled, fileURL.wrappedValue == nil, + let first = options.first?.url + else { return } + + fileURL.wrappedValue = first + } + } + + private func selectFile() { + if let suggestedSaveFilename { + let panel = NSSavePanel() + panel.canCreateDirectories = true + panel.showsHiddenFiles = true + panel.directoryURL = + fileURL.wrappedValue?.parent ?? defaultDirectory + panel.nameFieldStringValue = + fileURL.wrappedValue?.lastPathComponent + ?? suggestedSaveFilename + + if !allowedContentTypes.isEmpty { + panel.allowedContentTypes = allowedContentTypes + } + + guard panel.runModal() == .OK, let url = panel.url else { + return + } + + fileURL.wrappedValue = url + onSelection?() + remember(url) + return + } + + let panel = NSOpenPanel() + panel.allowsMultipleSelection = false + panel.canChooseFiles = !canChooseDirectories + panel.canChooseDirectories = canChooseDirectories + panel.canCreateDirectories = canCreateDirectories + panel.showsHiddenFiles = true + panel.directoryURL = fileURL.wrappedValue?.parent ?? defaultDirectory + + if !allowedContentTypes.isEmpty { + panel.allowedContentTypes = allowedContentTypes + } + + guard panel.runModal() == .OK, let url = panel.url else { + return + } + + fileURL.wrappedValue = url + onSelection?() + remember(url) + } +} + +/// The places already picked through an open panel, kept as security-scoped bookmarks. +private enum RecentLocations { + static let limit = 8 + + static func urls(for kind: FileSelection.Recents) -> [URL] { + var urls: [URL] = [] + var kept: [Data] = [] + + for data in stored(for: kind) { + guard let resolved = resolve(data) else { continue } + + urls.append(resolved.url) + kept.append(resolved.isStale ? renew(resolved.url) ?? data : data) + } + + if kept != stored(for: kind) { + UserDefaults.standard.set(kept, forKey: key(for: kind)) + } + + return urls + } + + static func remember(_ url: URL, for kind: FileSelection.Recents) { + guard let data = renew(url) else { return } + + var bookmarks = stored(for: kind).filter { existing in + resolve(existing)?.url.standardizedFileURL != url.standardizedFileURL + } + + bookmarks.insert(data, at: 0) + + UserDefaults.standard.set( + Array(bookmarks.prefix(limit)), + forKey: key(for: kind) + ) + } + + private static func key(for kind: FileSelection.Recents) -> String { + "recentLocations.\(kind.rawValue)" + } + + private static func stored(for kind: FileSelection.Recents) -> [Data] { + UserDefaults.standard.array(forKey: key(for: kind)) as? [Data] ?? [] + } + + private static func resolve(_ data: Data) -> (url: URL, isStale: Bool)? { + var isStale = false + + guard + let url = try? URL( + resolvingBookmarkData: data, + options: [.withSecurityScope], + relativeTo: nil, + bookmarkDataIsStale: &isStale + ) + else { + // A bookmark that no longer resolves is dropped rather than kept + // around to fail again. + return nil + } + + return (url, isStale) + } + + private static func renew(_ url: URL) -> Data? { + try? url.bookmarkData( + options: [.withSecurityScope], + includingResourceValuesForKeys: nil, + relativeTo: nil + ) + } +} diff --git a/Containers/Views/Components/FilterField.swift b/Containers/Views/Components/FilterField.swift new file mode 100644 index 0000000..295abf2 --- /dev/null +++ b/Containers/Views/Components/FilterField.swift @@ -0,0 +1,75 @@ +// +// FilterField.swift +// Containers +// +// Created by Axel Martinez on 02/08/2026. +// + +import AppKit +import SwiftUI + +/// The filter bar AppKit puts at the top of its lists and menus: a flat grey +/// field that takes on a text field's face once it has focus. +struct FilterField: View { + @Binding var text: String + var cornerRadius: CGFloat = 6 + var horizontalPadding: CGFloat = 6 + var verticalPadding: CGFloat = 3 + var highlightsActiveFilter: Bool = true + + @FocusState private var isFocused: Bool + + private var isFiltering: Bool { + highlightsActiveFilter && !text.isEmpty + } + + var body: some View { + HStack(spacing: 4) { + Image( + systemName: isFiltering + ? "line.3.horizontal.decrease.circle.fill" + : "line.3.horizontal.decrease.circle" + ) + // `Color.accentColor` desaturates wherever SwiftUI reads the + // control state as inactive, which is what a popover's own window + // reports; the raw system accent keeps its colour there. + .foregroundStyle( + isFiltering + ? Color(nsColor: .controlAccentColor) : Color.secondary + ) + .font(.system(size: 12)) + + TextField("Filter", text: $text) + .textFieldStyle(.plain) + .focused($isFocused) + + if !text.isEmpty { + Button { + text = "" + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.tertiary) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, horizontalPadding) + .padding(.vertical, verticalPadding) + .background( + Color( + nsColor: isFocused + ? .textBackgroundColor : .quaternaryLabelColor + ) + ) + .clipShape(RoundedRectangle(cornerRadius: cornerRadius)) + .overlay { + if isFocused { + RoundedRectangle(cornerRadius: cornerRadius) + .strokeBorder( + Color(nsColor: .separatorColor), + lineWidth: 1 + ) + } + } + } +} diff --git a/Containers/Views/Components/Forms/FormField.swift b/Containers/Views/Components/Forms/FormField.swift new file mode 100644 index 0000000..eae1073 --- /dev/null +++ b/Containers/Views/Components/Forms/FormField.swift @@ -0,0 +1,182 @@ +// +// FormField.swift +// Containers +// +// Created by Axel Martinez on 30/05/2026. +// + +import AppKit +import SwiftUI + +/// A text field in a form. The placeholder is a prompt rather than a title, so +/// the enclosing `Form` does not promote it to the row's label. +struct FormField: View { + /// The gap the button sits in, wide enough for a template image and the + /// margin the bezel already keeps on that side. + private static let actionWidth: CGFloat = 20 + + let placeholder: String + + @Binding var value: String + + var isEditable: Bool = true + var filter: ((String) -> String)? + var actionIcon: String? + var actionTitle: String? + var action: (() -> Void)? + + var body: some View { + field + .overlay(alignment: .trailing) { + if let actionIcon, let actionTitle, let action { + Button(action: action) { + Label(actionTitle, systemImage: actionIcon) + .labelStyle(.iconOnly) + } + .buttonStyle(.borderless) + .help(actionTitle) + .padding(.trailing, 5) + } + } + } + + /// A filtered field has to correct the text being edited, which only the + /// AppKit one can do: writing a rejected keystroke back through a binding + /// leaves the value it started at, so SwiftUI never redraws and the field + /// goes on showing what was refused. + @ViewBuilder + private var field: some View { + if action == nil, filter == nil { + TextField(text: $value, prompt: Text(placeholder)) { + EmptyView() + } + .textFieldStyle(.roundedBorder) + .labelsHidden() + .disabled(!isEditable) + } else { + InsetField( + value: $value, + placeholder: placeholder, + isEditable: isEditable, + filter: filter, + trailingInset: action == nil ? 0 : Self.actionWidth + ) + } + } +} + +/// A field that keeps its trailing edge clear, so a button can sit inside the +/// bezel without the value running underneath it. +/// +/// SwiftUI has no way to inset a text field's text, and an overlaid button only +/// covers it. `NSTextFieldCell` draws where it is told, which leaves the bezel +/// and its focus ring the system's own. +private struct InsetField: NSViewRepresentable { + @Binding var value: String + let placeholder: String + let isEditable: Bool + let filter: ((String) -> String)? + let trailingInset: CGFloat + + func makeNSView(context: Context) -> NSTextField { + let cell = InsetCell(textCell: "") + cell.isBezeled = true + cell.bezelStyle = .roundedBezel + cell.isEditable = true + cell.isSelectable = true + cell.isScrollable = true + cell.usesSingleLineMode = true + cell.lineBreakMode = .byTruncatingTail + + let field = NSTextField() + field.cell = cell + field.delegate = context.coordinator + return field + } + + func updateNSView(_ field: NSTextField, context: Context) { + context.coordinator.value = $value + context.coordinator.filter = filter + + let cell = field.cell as? InsetCell + cell?.trailingInset = trailingInset + cell?.lineBreakMode = context.environment.isEnabled ? .byClipping : .byTruncatingTail + field.placeholderString = placeholder + field.isEnabled = context.environment.isEnabled + field.isEditable = isEditable && context.environment.isEnabled + field.isSelectable = true + + if field.stringValue != value { + field.stringValue = value + } + } + + func sizeThatFits( + _ proposal: ProposedViewSize, + nsView: NSTextField, + context: Context + ) -> CGSize? { + let intrinsic = nsView.intrinsicContentSize + + guard let width = proposal.width, width.isFinite else { + return intrinsic + } + + return CGSize(width: width, height: intrinsic.height) + } + + func makeCoordinator() -> Coordinator { + Coordinator() + } + + final class Coordinator: NSObject, NSTextFieldDelegate { + var value: Binding? + var filter: ((String) -> String)? + + func controlTextDidChange(_ notification: Notification) { + guard let field = notification.object as? NSTextField else { + return + } + + if let filter { + let filtered = filter(field.stringValue) + + if filtered != field.stringValue { + NSSound.beep() + replace(field.stringValue, with: filtered, in: field) + } + } + + value?.wrappedValue = field.stringValue + } + + /// Puts the accepted text back into the field being edited, keeping the + /// insertion point where the typing left it rather than at the end. + private func replace( + _ text: String, + with filtered: String, + in field: NSTextField + ) { + let editor = field.currentEditor() + let caret = editor?.selectedRange.location ?? 0 + let dropped = text.count - filtered.count + + field.stringValue = filtered + + editor?.selectedRange = NSRange( + location: min(max(0, caret - dropped), filtered.count), + length: 0 + ) + } + } + + private final class InsetCell: NSTextFieldCell { + var trailingInset: CGFloat = 0 + + override func drawingRect(forBounds rect: NSRect) -> NSRect { + var rect = super.drawingRect(forBounds: rect) + rect.size.width = max(0, rect.width - trailingInset) + return rect + } + } +} diff --git a/Containers/Views/Components/Forms/FormList/FormList+Editor.swift b/Containers/Views/Components/Forms/FormList/FormList+Editor.swift new file mode 100644 index 0000000..46ded52 --- /dev/null +++ b/Containers/Views/Components/Forms/FormList/FormList+Editor.swift @@ -0,0 +1,102 @@ +// +// FormList+Editor.swift +// Containers +// +// Created by Axel Martinez on 2026/08/09. +// + +import SwiftUI + +// MARK: - Editor sheet + +extension FormList { + var editorPresentation: Binding { + Binding( + get: { selection.editorTarget != nil }, + set: { isPresented in + if !isPresented { + closeEditor() + } + } + ) + } + + @ViewBuilder + var editor: some View { + if let binding = editorItemBinding { + FormSheet( + title: editorTitle, + description: editorDescription, + primaryButtonTitle: editorPrimaryButtonTitle, + showsCancelButton: isEditingNewItem, + isPrimaryButtonDisabled: !canSave(binding.wrappedValue), + onSave: editorSaveAction + ) { + editorContent(binding) + } + } + } + + var isEditingNewItem: Bool { + if case .new = selection.editorTarget { + return true + } + + return false + } + + var editorPrimaryButtonTitle: String { + isEditingNewItem ? "Save" : "Done" + } + + var editorTitle: String { + isEditingNewItem ? addLabel : (title ?? addLabel) + } + + var editorSaveAction: (() -> Void)? { + guard isEditingNewItem else { + return nil + } + + return saveNewEditingItem + } + + var editorItemBinding: Binding? { + guard let target = selection.editorTarget else { + return nil + } + + switch target { + case .new: + return Binding( + get: { + guard case .new(let item) = self.selection.editorTarget else { + return newItem() + } + + return item + }, + set: { selection.editorTarget = .new($0) } + ) + case .existing(let id): + return itemBinding(for: id) + } + } + + func openEditor(for id: Item.ID) { + selection.edit(id) + } + + func closeEditor() { + selection.closeEditor() + } + + func saveNewEditingItem() { + guard case .new(let item) = selection.editorTarget else { + return + } + + selection.append(item, to: &items) + selection.closeEditor() + } +} diff --git a/Containers/Views/Components/Forms/FormList/FormList+Selection.swift b/Containers/Views/Components/Forms/FormList/FormList+Selection.swift new file mode 100644 index 0000000..c6c0f78 --- /dev/null +++ b/Containers/Views/Components/Forms/FormList/FormList+Selection.swift @@ -0,0 +1,98 @@ +// +// FormList+Selection.swift +// Containers +// +// Created by Axel Martinez on 2026/08/09. +// + +import SwiftUI + +// MARK: - Selection + +extension FormList { + /// Which item is selected, which one is being edited, and where both + /// land when an item is added or removed. The items themselves stay in + /// the caller's binding. + struct Selection { + /// A new item is carried here rather than looked up, because some lists + /// only append it once the editor is saved. + enum EditorTarget { + case existing(Item.ID) + case new(Item) + } + + var selectedItemID: Item.ID? + var editorTarget: EditorTarget? + + nonisolated init() {} + + var isEditingNewItem: Bool { + if case .new = editorTarget { + return true + } + + return false + } + + func selectedIndex(in items: [Item]) -> [Item].Index? { + guard let selectedItemID else { + return nil + } + + return items.firstIndex { $0.id == selectedItemID } + } + + mutating func select(_ id: Item.ID?) { + selectedItemID = id + } + + mutating func edit(_ id: Item.ID) { + selectedItemID = id + editorTarget = .existing(id) + } + + mutating func closeEditor() { + editorTarget = nil + } + + mutating func append(_ item: Item, to items: inout [Item]) { + items.append(item) + selectedItemID = item.id + } + + mutating func remove(at index: [Item].Index, from items: inout [Item]) { + let removedID = items[index].id + items.remove(at: index) + + if items.isEmpty { + selectedItemID = nil + } else { + // The row that moved up into the gap inherits the selection. + selectedItemID = items[min(index, items.endIndex - 1)].id + } + + if case .existing(removedID) = editorTarget { + closeEditor() + } + } + + /// Drops a selection or an editor left pointing at an item that no longer + /// exists, and closes the editor once a new item has been appended. + mutating func discardStale(in items: [Item]) { + if let selectedItemID, + !items.contains(where: { $0.id == selectedItemID }) + { + self.selectedItemID = nil + } + + switch editorTarget { + case .existing(let id) where !items.contains(where: { $0.id == id }): + closeEditor() + case .new(let item) where items.contains(where: { $0.id == item.id }): + closeEditor() + case .existing, .new, nil: + break + } + } + } +} diff --git a/Containers/Views/Components/Forms/FormList/FormList.swift b/Containers/Views/Components/Forms/FormList/FormList.swift new file mode 100644 index 0000000..7096152 --- /dev/null +++ b/Containers/Views/Components/Forms/FormList/FormList.swift @@ -0,0 +1,562 @@ +// +// FormList.swift +// Containers +// +// Created by Axel Martinez on 2026/02/08. +// + +import SwiftUI + +private let cellPadding: CGFloat = 8 +private let sectionSpacing: CGFloat = 8 + +/// A table of items that are either edited in place — pass `rowFields` — or +/// displayed as text and edited in a sheet — pass `editorContent`. +struct FormList: View +where Item.ID: Hashable { + + // MARK: - Properties + + @Environment(\.formListStyle) private var style + + @State var selection = Selection() + @State private var storedIsExpanded: Bool = true + @State private var pendingFocusItemID: Item.ID? + + @Binding var items: [Item] + + var title: String? + var expansion: Binding? + var description: String? = nil + var editorDescription: String? = nil + var columnTitles: [String] = ["Value"] + var addLabel: String + var emptyMessage: String + var hasContentBelow: Bool + var newItem: () -> Item + var rowFields: ((Binding) -> [Field])? + var rowSummary: ((Item) -> String)? + var rowValues: ((Item) -> [String])? + var canSave: (Item) -> Bool = { _ in true } + + @ViewBuilder var editorContent: (Binding) -> EditorContent + + private var usesModalEditor: Bool { + rowFields == nil + } + + // Held by the caller when given, so the section survives being rebuilt. + private var isExpanded: Bool { + get { expansion?.wrappedValue ?? storedIsExpanded } + nonmutating set { + if let expansion { + expansion.wrappedValue = newValue + } else { + storedIsExpanded = newValue + } + } + } + + // MARK: - Types + + /// One editable cell of a row: where its text lives, and what to call it + /// when it is read aloud. Callers build these, so it cannot be private. + struct Field: Identifiable { + let id = UUID() + var placeholder: String + var text: Binding + var isMonospaced: Bool = false + } + + // MARK: - Initializers + + private init( + items: Binding<[Item]>, + title: String?, + isExpanded: Binding?, + description: String?, + editorDescription: String?, + columnTitles: [String], + addLabel: String, + emptyMessage: String, + hasContentBelow: Bool, + newItem: @escaping () -> Item, + rowFields: ((Binding) -> [Field])?, + rowSummary: ((Item) -> String)?, + rowValues: ((Item) -> [String])?, + canSave: @escaping (Item) -> Bool, + @ViewBuilder editorContent: @escaping (Binding) -> EditorContent + ) { + self._items = items + self.title = title + self.expansion = isExpanded + self.description = description + self.editorDescription = editorDescription + self.columnTitles = columnTitles + self.addLabel = addLabel + self.emptyMessage = emptyMessage + self.hasContentBelow = hasContentBelow + self.newItem = newItem + self.rowFields = rowFields + self.rowSummary = rowSummary + self.rowValues = rowValues + self.canSave = canSave + self.editorContent = editorContent + } + + /// Rows are displayed as text and edited in a sheet built by `editorContent`. + init( + items: Binding<[Item]>, + title: String? = nil, + isExpanded: Binding? = nil, + description: String? = nil, + editorDescription: String? = nil, + columnTitles: [String] = ["Value"], + addLabel: String, + emptyMessage: String, + hasContentBelow: Bool = false, + newItem: @escaping () -> Item, + rowSummary: @escaping (Item) -> String, + rowValues: ((Item) -> [String])? = nil, + canSave: @escaping (Item) -> Bool = { _ in true }, + @ViewBuilder editorContent: @escaping (Binding) -> EditorContent + ) { + self.init( + items: items, + title: title, + isExpanded: isExpanded, + description: description, + editorDescription: editorDescription, + columnTitles: columnTitles, + addLabel: addLabel, + emptyMessage: emptyMessage, + hasContentBelow: hasContentBelow, + newItem: newItem, + rowFields: nil, + rowSummary: rowSummary, + rowValues: rowValues, + canSave: canSave, + editorContent: editorContent + ) + } + + // MARK: - Body + + var body: some View { + content + .sheet(isPresented: editorPresentation) { + editor + } + .onChange(of: items.endIndex) { _, _ in + removeStaleSelection() + } + } + + @ViewBuilder + private var content: some View { + switch style { + case .table: + tableContent + case .grouped: + groupedContent + } + } + + // MARK: - Layout + + private var groupedContent: some View { + GroupBox { + VStack(spacing: 0) { + VStack(alignment: .leading, spacing: 3) { + if let title { + Text(title) + .font(.headline) + .fontWeight(.bold) + } + + if let description { + Text(description) + .font(.subheadline) + .foregroundStyle(.secondary) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 12) + .padding(.vertical, 10) + + Divider() + + rows + .frame(minHeight: 80) + + Divider() + + controls(backgroundColor: Color(nsColor: .quaternarySystemFill)) + } + } + .groupBoxStyle(BoxStyle()) + } + + private var tableContent: some View { + VStack(alignment: .leading, spacing: 0) { + if let title { + disclosureHeader(title: title) + .padding(.vertical, sectionSpacing) + } + + if isExpanded || title == nil { + VStack(spacing: 0) { + table + + if title != nil { + Divider() + } + + controls() + .padding(.leading, title == nil ? 4 : 0) + } + .frame(maxHeight: title == nil ? .infinity : nil) + .padding(.leading, title != nil ? 18 : 0) + + if let description { + Text(description) + .font(.caption) + .foregroundStyle(.secondary) + } + } + + if (title != nil && !isExpanded) || hasContentBelow { + Divider() + .padding( + .top, + isExpanded && title != nil ? sectionSpacing : 0 + ) + // Last in its container, the rule takes no room: scrolled + // to the end it falls just past the clip, and the edge's + // own rule is left in its place instead of a point below. + .frame(height: hasContentBelow ? nil : 0, alignment: .top) + } + } + .frame(maxWidth: .infinity, maxHeight: title == nil ? .infinity : nil, alignment: .leading) + } + + private func disclosureHeader(title: String) -> some View { + Button { + isExpanded.toggle() + } label: { + HStack(spacing: 6) { + Image( + systemName: isExpanded ? "chevron.down" : "chevron.right" + ) + .fontWeight(.semibold) + .foregroundStyle(.secondary) + .frame(width: 12) + + Text(title) + .font(.headline) + + Spacer() + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + private var table: some View { + VStack(spacing: 0) { + HStack(spacing: 0) { + ForEach(Array(columnTitles.enumerated()), id: \.offset) { + index, + columnTitle in + Text(columnTitle) + .font(.caption) + .foregroundStyle(.primary) + .padding(.leading, title == nil ? 12 : 8) + .padding(.trailing, 8) + .frame(maxWidth: .infinity, alignment: .leading) + + if index < columnTitles.count - 1 { + Divider() + .padding(.vertical, 4) + } + } + } + .frame(height: 22) + .background(Color(nsColor: .controlBackgroundColor)) + + Divider() + + rows + } + .background(Color(nsColor: .textBackgroundColor)) + .frame(minHeight: 120) + } + + @ViewBuilder + private var rows: some View { + if items.isEmpty { + Text(emptyMessage) + .font(.subheadline) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + List(items, selection: $selection.selectedItemID) { item in + selectableRow(for: item.id) + .tag(item.id) + .contentShape(Rectangle()) + } + .listStyle(.plain) + } + } + + private func controls(backgroundColor: Color? = nil) -> some View { + Controls( + addLabel: addLabel, + isRemoveDisabled: selection.selectedItemID == nil, + backgroundColor: backgroundColor, + add: addItem, + remove: removeSelectedItem + ) + } + + @ViewBuilder + private func selectableRow(for id: Item.ID) -> some View { + if usesModalEditor { + row(for: id) + .onTapGesture(count: 2) { + openEditor(for: id) + } + } else { + row(for: id) + } + } + + @ViewBuilder + private func row(for id: Item.ID) -> some View { + if let rowFields, let binding = itemBinding(for: id) { + FieldRow( + fields: rowFields(binding), + isSelected: selection.selectedItemID == id, + autofocus: pendingFocusItemID == id, + focusHandled: { pendingFocusItemID = nil } + ) + } else if let item = items.first(where: { $0.id == id }) { + Row(values: rowValues(for: item)) + } + } + + private func rowValues(for item: Item) -> [String] { + let values = rowValues?(item) ?? rowSummary.map { [$0(item)] } ?? [] + + return columnTitles.indices.map { index in + guard index < values.count else { + return "" + } + + return values[index] + } + } + + /// An index-based binding outlives the row it was built for: after a removal + /// SwiftUI can still evaluate the old row, and the index then reads past the + /// end of the array. Looking the item up by id keeps that harmless, falling + /// back to the value the row was built with. + func itemBinding(for id: Item.ID) -> Binding? { + guard let current = items.first(where: { $0.id == id }) else { + return nil + } + + return Binding( + get: { items.first { $0.id == id } ?? current }, + set: { updated in + guard let index = items.firstIndex(where: { $0.id == id }) + else { + return + } + + items[index] = updated + } + ) + } + + // MARK: - Actions + + private func addItem() { + let item = newItem() + + if usesModalEditor { + selection.editorTarget = .new(item) + } else { + selection.append(item, to: &items) + pendingFocusItemID = item.id + } + } + + private func removeSelectedItem() { + guard let index = selection.selectedIndex(in: items) else { + return + } + + selection.remove(at: index, from: &items) + } + + private func removeStaleSelection() { + selection.discardStale(in: items) + } + + // MARK: - Subviews + + /// The add and remove buttons under the rows. + private struct Controls: View { + var addLabel: String + var removeLabel: String = "Remove selected row" + var isRemoveDisabled: Bool + var backgroundColor: Color? = nil + var add: () -> Void + var remove: () -> Void + + var body: some View { + HStack(spacing: 0) { + Button(action: add) { + icon("plus") + } + .buttonStyle(.plain) + .help(addLabel) + + Button(action: remove) { + icon("minus") + } + .buttonStyle(.plain) + .disabled(isRemoveDisabled) + .help(removeLabel) + + Spacer() + } + .frame(height: 22) + .background(backgroundColor ?? Color.clear) + } + + private func icon(_ systemName: String) -> some View { + Image(systemName: systemName) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + .frame(width: 24, height: 20) + .contentShape(Rectangle()) + } + } + + // Strips the default GroupBox padding so the rows meet its edges. + private struct BoxStyle: GroupBoxStyle { + func makeBody(configuration: Configuration) -> some View { + VStack(spacing: 0) { + configuration.content + } + .background(Color(nsColor: .quaternarySystemFill)) + .clipShape(RoundedRectangle(cornerRadius: 10)) + } + } + + /// Columns of plain text; the values are edited in the editor sheet. + private struct Row: View { + var values: [String] + + var body: some View { + HStack(spacing: 0) { + ForEach(Array(values.enumerated()), id: \.offset) { + index, + value in + // An item saved with nothing in it would otherwise leave a + // blank row with no way to tell it is there. + Text(value.isEmpty && index == 0 ? "New Item" : value) + // A hierarchical style turns white on the selected row + // by itself, in step with the highlight the table draws. + .foregroundStyle(value.isEmpty ? .tertiary : .primary) + .lineLimit(1) + .truncationMode(.middle) + .padding(.horizontal, cellPadding) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + } + } + + /// Columns of text fields, edited in place. + private struct FieldRow: View { + var fields: [Field] + var isSelected: Bool + var autofocus: Bool + var focusHandled: () -> Void + + @FocusState private var focusedFieldIndex: Int? + + var body: some View { + HStack(spacing: 0) { + ForEach(Array(fields.enumerated()), id: \.offset) { + index, + field in + // Empty rows stay blank — the column header says what goes + // in them — so the field name is left to VoiceOver. + TextField("", text: field.text) + .textFieldStyle(.plain) + .font(font(for: field)) + .accessibilityLabel(field.placeholder) + .focused($focusedFieldIndex, equals: index) + .padding(.horizontal, cellPadding) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + // An unselected row's fields would swallow the mouse down in their + // own tracking loop, leaving the table to select only on mouse up. + // Letting the click through means the first click selects and the + // second edits, which is what an AppKit table does anyway. + .allowsHitTesting(isSelected) + // Runs both when a freshly inserted row appears and when an existing + // row is asked to take focus, once the row is in the hierarchy. + .task(id: autofocus) { + guard autofocus else { return } + + focusedFieldIndex = 0 + focusHandled() + } + } + + private func font(for field: Field) -> Font { + field.isMonospaced ? .system(.body, design: .monospaced) : .body + } + } +} + +extension FormList where EditorContent == EmptyView { + /// Rows are edited in place through the fields `rowFields` describes, so + /// there is no editor sheet. + init( + items: Binding<[Item]>, + title: String? = nil, + isExpanded: Binding? = nil, + description: String? = nil, + columnTitles: [String] = ["Value"], + addLabel: String, + emptyMessage: String, + hasContentBelow: Bool = false, + newItem: @escaping () -> Item, + rowFields: @escaping (Binding) -> [Field] + ) { + self.init( + items: items, + title: title, + isExpanded: isExpanded, + description: description, + editorDescription: nil, + columnTitles: columnTitles, + addLabel: addLabel, + emptyMessage: emptyMessage, + hasContentBelow: hasContentBelow, + newItem: newItem, + rowFields: rowFields, + rowSummary: nil, + rowValues: nil, + canSave: { _ in true }, + editorContent: { _ in EmptyView() } + ) + } +} diff --git a/Containers/Views/Components/Forms/FormList/FormListStyle.swift b/Containers/Views/Components/Forms/FormList/FormListStyle.swift new file mode 100644 index 0000000..1335e39 --- /dev/null +++ b/Containers/Views/Components/Forms/FormList/FormListStyle.swift @@ -0,0 +1,35 @@ +// +// FormListStyle.swift +// Containers +// +// Created by Axel Martinez on 2026/08/09. +// + +import SwiftUI + +/// How an ``FormList`` draws itself. The rows, the selection and the +/// add and remove controls behave the same either way. +enum FormListStyle { + /// Column headers over a full-height table, for wider layouts. + case table + + /// A titled box sized to its rows, for settings panes. + case grouped +} + +private struct FormListStyleKey: EnvironmentKey { + static let defaultValue: FormListStyle = .table +} + +extension EnvironmentValues { + var formListStyle: FormListStyle { + get { self[FormListStyleKey.self] } + set { self[FormListStyleKey.self] = newValue } + } +} + +extension View { + func formListStyle(_ style: FormListStyle) -> some View { + environment(\.formListStyle, style) + } +} diff --git a/Containers/Views/Components/Forms/FormPicker.swift b/Containers/Views/Components/Forms/FormPicker.swift new file mode 100644 index 0000000..2a18c5a --- /dev/null +++ b/Containers/Views/Components/Forms/FormPicker.swift @@ -0,0 +1,184 @@ +// +// FormPicker.swift +// Containers +// +// Created by Axel Martinez on 02/08/2026. +// + +import AppKit +import Foundation +import SwiftUI + +/// A dropdown that fills the width it is given. +/// +/// SwiftUI's menu `Picker` wraps an `NSPopUpButton` but reports its intrinsic +/// width whatever the layout proposes, so it renders visibly narrower than the +/// text fields it shares a column with. Driving the button directly lets +/// `sizeThatFits` accept the proposal instead. +struct FormPicker: NSViewRepresentable { + fileprivate enum Item { + /// The selection when it is none of the options. It titles the button + /// but stays out of the menu, since it is not something to pick. + case placeholder(Option, title: String) + case option(Option, title: String) + case separator + /// A trailing command such as "Other…". + case action(String) + } + + let placeholder: String + let options: [Option] + + @Binding var selection: Option + + var fillsAvailableWidth: Bool = true + var actionTitle: String? + var onAction: (() -> Void)? + var title: ((Option) -> String)? + var icon: ((Option) -> NSImage?)? + + private var items: [Item] { + var items: [Item] = [] + + if !options.contains(selection) { + items.append(.placeholder(selection, title: placeholder)) + } + + items += options.map { option in + .option( + option, + title: title?(option) + ?? (option as? Unit)?.symbol + ?? option.description + ) + } + + if let actionTitle { + items.append(.separator) + items.append(.action(actionTitle)) + } + + return items + } + + func makeNSView(context: Context) -> NSPopUpButton { + let button = NSPopUpButton(frame: .zero, pullsDown: false) + button.target = context.coordinator + button.action = #selector(Coordinator.selectionChanged(_:)) + button.setContentHuggingPriority(.defaultLow, for: .horizontal) + button.setContentCompressionResistancePriority( + .defaultLow, + for: .horizontal + ) + return button + } + + func updateNSView(_ button: NSPopUpButton, context: Context) { + context.coordinator.items = items + context.coordinator.selection = $selection + context.coordinator.onAction = onAction + + let menu = NSMenu() + menu.autoenablesItems = false + + for (index, item) in items.enumerated() { + switch item { + case .separator: + menu.addItem(.separator()) + case .option(let option, let title): + let menuItem = NSMenuItem( + title: title, + action: nil, + keyEquivalent: "" + ) + menuItem.tag = index + menuItem.image = icon?(option) + menu.addItem(menuItem) + case .placeholder(_, let title): + let menuItem = NSMenuItem( + title: title, + action: nil, + keyEquivalent: "" + ) + menuItem.tag = index + // Hidden rather than absent: the button reads its title from + // the item it has selected. + menuItem.isHidden = true + menu.addItem(menuItem) + case .action(let title): + let menuItem = NSMenuItem( + title: title, + action: nil, + keyEquivalent: "" + ) + menuItem.tag = index + menu.addItem(menuItem) + } + } + + button.menu = menu + + if let index = context.coordinator.index(of: selection) { + button.selectItem(withTag: index) + } + } + + func sizeThatFits( + _ proposal: ProposedViewSize, + nsView: NSPopUpButton, + context: Context + ) -> CGSize? { + let intrinsic = nsView.intrinsicContentSize + + guard fillsAvailableWidth, + let width = proposal.width, + width.isFinite + else { + return intrinsic + } + + return CGSize(width: width, height: intrinsic.height) + } + + func makeCoordinator() -> Coordinator { + Coordinator() + } + + final class Coordinator: NSObject { + fileprivate var items: [Item] = [] + var selection: Binding