Commit 872583eca8

872583eca8b4e7ae6ef85917604d4a5257b9d125

parent: d3af0e7d51

Unsigned

cmc <hello@cleberg.net> · 2026-07-23 02:43 UTC

fix: adopt Swift 6 language mode; resolve all concurrency issues (#27)

All three product targets (app, widget, share extension) now build under
SWIFT_VERSION = 6.0 with zero errors and zero warnings. The UITests
target stays on 5.0: XCTestCase's nonisolated setUp/init overrides
conflict with the target's MainActor default isolation under 6, and test
tooling is not shipping code.

The original seven diagnostics, plus the layers Swift 6 mode surfaced
once those cleared:

- SMTPChannel is an actor. It was implicitly MainActor while running its
  receive loop on a background queue, so parsedLines/lineWaiters/
  receiveBuffer were declared main-actor-protected and mutated off it —
  concurrent mutation while resuming a CheckedContinuation can
  double-resume, which traps. The actor serialises all state; Network
  callbacks hop in via Task. The start() continuation also gains an
  OSAllocatedUnfairLock resume-once guard: the state handler can fire
  .ready and later .failed, and resuming twice was a pre-existing trap of
  the same family.
- CachedLookupResult is nonisolated (a value pair built inside actor
  LookupRuntime cannot have a MainActor-bound memberwise init) with
  conditional Sendable — opting out of MainActor isolation also opted out
  of the implicit Sendable that globally-isolated types get.
- PortScanService.printableBanner is nonisolated: a pure transformation
  called from the connection's queue.
- SweepActivityController stores the activity's Sendable id instead of
  the non-Sendable Activity, re-resolving via Activity.activities inside
  each fire-and-forget task, so nothing non-Sendable crosses isolation.
- App Intents' static title/description/openAppWhenRun become lets
  (get-only protocol requirements; static var is shared mutable global
  state), and the summary helpers are @MainActor to match the model
  properties they read and the perform() implementations that call them.
- ExternalDataService's ISO8601DateFormatter is nonisolated(unsafe),
  citing Apple's documented thread-safety, rather than risking a parser
  behaviour change by switching APIs with no test coverage.
- TaskMetricsDelegate.metrics is nonisolated(unsafe): written on the
  session's delegate queue, read only after the request completes, and
  URLSession guarantees didFinishCollecting precedes task completion.
- The share extension extracts the host via async/withCheckedContinuation
  instead of sending a non-Sendable completion into loadItem's @Sendable
  handler; Task inherits the view controller's MainActor so the manual
  DispatchQueue.main hop goes too.

Validated: clean Swift 6 build of all product targets, and the full
enforced 11-test audit suite green on the floor runtime — Swift 6's
runtime isolation checks ran the app through every screen without a
trap.

Layout: unified · split

DomainDig.xcodeproj/project.pbxproj +6 −6
@@ -591,7 +591,7 @@
591591 SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
592592 SWIFT_EMIT_LOC_STRINGS = YES;
593593 SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
594 SWIFT_VERSION = 5.0;
594 SWIFT_VERSION = 6.0;
595595 TARGETED_DEVICE_FAMILY = "1,2";
596596 };
597597 name = Debug;
@@ -628,7 +628,7 @@
628628 SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
629629 SWIFT_EMIT_LOC_STRINGS = YES;
630630 SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
631 SWIFT_VERSION = 5.0;
631 SWIFT_VERSION = 6.0;
632632 TARGETED_DEVICE_FAMILY = "1,2";
633633 };
634634 name = Release;
@@ -657,7 +657,7 @@
657657 SWIFT_APPROACHABLE_CONCURRENCY = YES;
658658 SWIFT_EMIT_LOC_STRINGS = YES;
659659 SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
660 SWIFT_VERSION = 5.0;
660 SWIFT_VERSION = 6.0;
661661 TARGETED_DEVICE_FAMILY = "1,2";
662662 };
663663 name = Debug;
@@ -686,7 +686,7 @@
686686 SWIFT_APPROACHABLE_CONCURRENCY = YES;
687687 SWIFT_EMIT_LOC_STRINGS = YES;
688688 SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
689 SWIFT_VERSION = 5.0;
689 SWIFT_VERSION = 6.0;
690690 TARGETED_DEVICE_FAMILY = "1,2";
691691 };
692692 name = Release;
@@ -715,7 +715,7 @@
715715 SWIFT_APPROACHABLE_CONCURRENCY = YES;
716716 SWIFT_EMIT_LOC_STRINGS = YES;
717717 SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
718 SWIFT_VERSION = 5.0;
718 SWIFT_VERSION = 6.0;
719719 TARGETED_DEVICE_FAMILY = "1,2";
720720 };
721721 name = Debug;
@@ -744,7 +744,7 @@
744744 SWIFT_APPROACHABLE_CONCURRENCY = YES;
745745 SWIFT_EMIT_LOC_STRINGS = YES;
746746 SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
747 SWIFT_VERSION = 5.0;
747 SWIFT_VERSION = 6.0;
748748 TARGETED_DEVICE_FAMILY = "1,2";
749749 };
750750 name = Release;
DomainDig/DomainDigIntents.swift +11 −9
@@ -6,13 +6,13 @@ import Foundation
66/// `DomainReportBuilder`) and returns a concise summary. Usable from
77/// Shortcuts, Spotlight, the Action button, and Siri.
88struct InspectDomainIntent: AppIntent {
9 static var title: LocalizedStringResource = "Inspect Domain"
10 static var description = IntentDescription(
9 static let title: LocalizedStringResource = "Inspect Domain"
10 static let description = IntentDescription(
1111 "Run a DomainDig inspection and return a summary of availability, risk, TLS, email security, and certificate health."
1212 )
1313
1414 // Read-only inspection; no need to foreground the app.
15 static var openAppWhenRun = false
15 static let openAppWhenRun = false
1616
1717 @Parameter(
1818 title: "Domain",
@@ -44,6 +44,7 @@ struct InspectDomainIntent: AppIntent {
4444 }
4545
4646 /// Multi-line summary suitable for a returned Shortcuts text value.
47 @MainActor
4748 static func summaryText(for report: DomainReport) -> String {
4849 let dnssec: String
4950 switch report.dns.dnssecSigned {
@@ -68,6 +69,7 @@ struct InspectDomainIntent: AppIntent {
6869 }
6970
7071 /// Short spoken/dialog line for Siri and the Shortcuts result banner.
72 @MainActor
7173 static func spokenSummary(for report: DomainReport) -> String {
7274 "\(report.domain) is \(report.availability.rawValue). Risk \(report.riskAssessment.level.title.lowercased()), health \(report.health.title.lowercased())."
7375 }
@@ -89,12 +91,12 @@ enum InspectDomainError: Error, CustomLocalizedStringResourceConvertible {
8991/// existing view-model path (premium limits, monitoring, history linking,
9092/// cloud-sync recording, and the paywall when over the free limit).
9193struct AddToWatchlistIntent: AppIntent {
92 static var title: LocalizedStringResource = "Add Domain to Watchlist"
93 static var description = IntentDescription(
94 static let title: LocalizedStringResource = "Add Domain to Watchlist"
95 static let description = IntentDescription(
9496 "Open DomainDig and add a domain to your watchlist."
9597 )
9698
97 static var openAppWhenRun = true
99 static let openAppWhenRun = true
98100
99101 @Parameter(
100102 title: "Domain",
@@ -128,12 +130,12 @@ struct AddToWatchlistIntent: AppIntent {
128130/// through the existing view-model batch path (`refreshAllTrackedDomains`), which
129131/// enforces the batch feature gate and surfaces the paywall when needed.
130132struct RunSweepIntent: AppIntent {
131 static var title: LocalizedStringResource = "Run Watchlist Sweep"
132 static var description = IntentDescription(
133 static let title: LocalizedStringResource = "Run Watchlist Sweep"
134 static let description = IntentDescription(
133135 "Open DomainDig and re-inspect every domain on your watchlist."
134136 )
135137
136 static var openAppWhenRun = true
138 static let openAppWhenRun = true
137139
138140 @MainActor
139141 func perform() async throws -> some IntentResult {
DomainDig/ExternalDataService.swift +4 −1
@@ -738,7 +738,10 @@ actor ExternalDataService {
738738 }
739739 }
740740
741 private static let iso8601DateFormatter: ISO8601DateFormatter = {
741 // ISO8601DateFormatter is documented thread-safe ("ISO8601DateFormatter is
742 // thread-safe" — Apple docs), so sharing one instance across contexts is
743 // sound; the annotation records that the compiler cannot see it. (#27)
744 private nonisolated(unsafe) static let iso8601DateFormatter: ISO8601DateFormatter = {
742745 let formatter = ISO8601DateFormatter()
743746 formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
744747 return formatter
DomainDig/HTTPHeadersService.swift +4 −1
@@ -103,7 +103,10 @@ struct HTTPHeadersService {
103103}
104104
105105private final class TaskMetricsDelegate: NSObject, URLSessionTaskDelegate {
106 private(set) var metrics: URLSessionTaskMetrics?
106 // Written from the session's delegate queue, read only after the request
107 // has completed — URLSession guarantees didFinishCollecting is delivered
108 // before the task finishes, so the accesses are sequenced. (#27)
109 nonisolated(unsafe) private(set) var metrics: URLSessionTaskMetrics?
107110
108111 func urlSession(
109112 _ _: URLSession,
DomainDig/IntegrationService.swift +49 −25
@@ -1,5 +1,6 @@
11import Foundation
22import Network
3import os
34import Observation
45import Security
56
@@ -749,11 +750,17 @@ private enum SMTPClient {
749750 try await channel.sendRaw(body + "\r\n.\r\n")
750751 _ = try await channel.readResponse(expecting: [250])
751752 _ = try await channel.sendCommand("QUIT", expecting: [221])
752 channel.cancel()
753 await channel.cancel()
753754 }
754755}
755756
756private final class SMTPChannel {
757/// An actor, not a MainActor class. The previous shape inherited the project's
758/// MainActor default while running its receive loop on a background dispatch
759/// queue, so `parsedLines`/`lineWaiters`/`receiveBuffer` were declared
760/// main-actor-protected and mutated off it — concurrent mutation while resuming
761/// a `CheckedContinuation` can double-resume, which traps. The actor serialises
762/// all of it and forces the Network callbacks to hop in explicitly. (Issue #27.)
763private actor SMTPChannel {
757764 private let connection: NWConnection
758765 private var parsedLines: [String] = []
759766 private var lineWaiters: [CheckedContinuation<String, Error>] = []
@@ -765,25 +772,35 @@ private final class SMTPChannel {
765772
766773 func start() async throws {
767774 try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
768 connection.stateUpdateHandler = { [weak self] state in
775 // The state handler can fire `.ready` and later `.failed` (or
776 // `.failed` twice); resuming a continuation twice traps. The lock
777 // also keeps the closure Sendable-clean without touching actor state
778 // from the connection's queue.
779 let hasResumed = OSAllocatedUnfairLock(initialState: false)
780 connection.stateUpdateHandler = { state in
781 let isFirst: () -> Bool = {
782 hasResumed.withLock { resumed in
783 if resumed { return false }
784 resumed = true
785 return true
786 }
787 }
769788 switch state {
770789 case .ready:
771 self?.scheduleReceiveLoop()
772 continuation.resume()
790 if isFirst() { continuation.resume() }
773791 case .failed(let error):
774 continuation.resume(throwing: error)
792 if isFirst() { continuation.resume(throwing: error) }
793 case .cancelled:
794 if isFirst() { continuation.resume(throwing: IntegrationError.streamClosed) }
775795 default:
776796 break
777797 }
778798 }
779799 connection.start(queue: .global(qos: .utility))
780800 }
781 }
782
783 private func scheduleReceiveLoop() {
784 DispatchQueue.global(qos: .utility).async { [weak self] in
785 self?.startReceiveLoop()
786 }
801 // Started from the actor once the connection is ready, replacing the old
802 // dispatch-queue hop. TCP buffers anything that arrives in the gap.
803 startReceiveLoop()
787804 }
788805
789806 func cancel() {
@@ -845,26 +862,33 @@ private final class SMTPChannel {
845862 }
846863
847864 private func startReceiveLoop() {
865 // The completion runs on the connection's queue; hop back onto the
866 // actor before touching any state.
848867 connection.receive(minimumIncompleteLength: 1, maximumLength: 4096) { [weak self] data, _, isComplete, error in
849868 guard let self else { return }
850
851 if let error {
852 self.failWaiters(with: error)
853 return
869 Task {
870 await self.handleReceive(data: data, isComplete: isComplete, error: error)
854871 }
872 }
873 }
855874
856 if let data, !data.isEmpty {
857 self.receiveBuffer.append(data)
858 self.flushBuffer()
859 }
875 private func handleReceive(data: Data?, isComplete: Bool, error: Error?) {
876 if let error {
877 failWaiters(with: error)
878 return
879 }
860880
861 if isComplete {
862 self.failWaiters(with: IntegrationError.streamClosed)
863 return
864 }
881 if let data, !data.isEmpty {
882 receiveBuffer.append(data)
883 flushBuffer()
884 }
865885
866 self.startReceiveLoop()
886 if isComplete {
887 failWaiters(with: IntegrationError.streamClosed)
888 return
867889 }
890
891 startReceiveLoop()
868892 }
869893
870894 private func flushBuffer() {
DomainDig/LookupRuntime.swift +9 −1
@@ -1,10 +1,18 @@
11import Foundation
22
3struct CachedLookupResult<Value> {
3/// Opted out of the project's MainActor default isolation: this is a plain
4/// value pair constructed inside `actor LookupRuntime`, and a MainActor-bound
5/// memberwise init cannot be called from there under Swift 6.
6nonisolated struct CachedLookupResult<Value> {
47 let value: Value
58 let source: LookupResultSource
69}
710
11/// Opting out of MainActor isolation also opted out of the implicit
12/// Sendable that globally-isolated types get, which is what lets this cross
13/// from `actor LookupRuntime` back to its callers.
14extension CachedLookupResult: Sendable where Value: Sendable {}
15
816actor LookupRuntime {
917 static let shared = LookupRuntime()
1018
DomainDig/PortScanService.swift +4 −1
@@ -106,7 +106,10 @@ struct PortScanService {
106106 }
107107 }
108108
109 private static func printableBanner(from data: Data?, error: Error?) -> String? {
109 /// Pure data transformation, called from the connection's background queue —
110 /// `nonisolated` opts it out of the project's MainActor default, which would
111 /// otherwise make this call a data-race diagnostic under Swift 6.
112 private nonisolated static func printableBanner(from data: Data?, error: Error?) -> String? {
110113 guard error == nil,
111114 let data,
112115 !data.isEmpty,
DomainDig/SweepActivityController.swift +27 −12
@@ -2,11 +2,18 @@ import ActivityKit
22import Foundation
33
44/// Starts, updates, and ends the sweep Live Activity around a batch run.
5///
6/// Holds the activity's `id` (a Sendable `String`) rather than the
7/// `Activity` object itself. `Activity` is not Sendable, and sending the
8/// stored reference into the fire-and-forget update task while `self` still
9/// held it was a Swift 6 region-isolation violation (issue #27). Each task
10/// re-resolves the activity via `Activity.activities`, ActivityKit's
11/// sanctioned lookup, so nothing non-Sendable crosses an isolation boundary.
512@MainActor
613final class SweepActivityController {
714 static let shared = SweepActivityController()
815
9 private var activity: Activity<SweepActivityAttributes>?
16 private var activityID: String?
1017
1118 private init() { /* Singleton; use the shared instance. */ }
1219
@@ -23,14 +30,15 @@ final class SweepActivityController {
2330 changed: 0,
2431 warnings: 0
2532 )
26 activity = try? Activity.request(
33 let activity = try? Activity.request(
2734 attributes: SweepActivityAttributes(title: title, startedAt: Date()),
2835 content: ActivityContent(state: state, staleDate: nil)
2936 )
37 activityID = activity?.id
3038 }
3139
3240 func update(completed: Int, total: Int, currentDomain: String?) {
33 guard let activity else { return }
41 guard let activityID else { return }
3442 let state = SweepActivityAttributes.ContentState(
3543 completed: completed,
3644 total: total,
@@ -39,25 +47,32 @@ final class SweepActivityController {
3947 warnings: 0
4048 )
4149 Task {
50 guard let activity = Self.activity(withID: activityID) else { return }
4251 await activity.update(ActivityContent(state: state, staleDate: nil))
4352 }
4453 }
4554
4655 func end(changed: Int, warnings: Int, immediately: Bool = false) {
47 guard let activity else { return }
48 self.activity = nil
49 let state = SweepActivityAttributes.ContentState(
50 completed: activity.content.state.total,
51 total: activity.content.state.total,
52 currentDomain: nil,
53 changed: changed,
54 warnings: warnings
55 )
56 guard let activityID else { return }
57 self.activityID = nil
5658 Task {
59 guard let activity = Self.activity(withID: activityID) else { return }
60 let total = activity.content.state.total
61 let state = SweepActivityAttributes.ContentState(
62 completed: total,
63 total: total,
64 currentDomain: nil,
65 changed: changed,
66 warnings: warnings
67 )
5768 await activity.end(
5869 ActivityContent(state: state, staleDate: nil),
5970 dismissalPolicy: immediately ? .immediate : .after(Date().addingTimeInterval(60))
6071 )
6172 }
6273 }
74
75 private nonisolated static func activity(withID id: String) -> Activity<SweepActivityAttributes>? {
76 Activity<SweepActivityAttributes>.activities.first { $0.id == id }
77 }
6378}
DomainDigShareExtension/ShareViewController.swift +15 −11
@@ -24,14 +24,17 @@ final class ShareViewController: UIViewController {
2424 label.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -24)
2525 ])
2626
27 extractSharedDomain { [weak self] domain in
28 DispatchQueue.main.async {
29 self?.finish(domain: domain)
30 }
27 // Task inherits this view controller's MainActor context, so finish()
28 // lands back on main without a manual dispatch. The continuation form
29 // also avoids sending a non-Sendable completion into loadItem's
30 // @Sendable handler. (#27)
31 Task { [weak self] in
32 let domain = await self?.extractSharedDomain()
33 self?.finish(domain: domain ?? nil)
3134 }
3235 }
3336
34 private func extractSharedDomain(completion: @escaping (String?) -> Void) {
37 private func extractSharedDomain() async -> String? {
3538 let providers = (extensionContext?.inputItems ?? [])
3639 .compactMap { $0 as? NSExtensionItem }
3740 .flatMap { $0.attachments ?? [] }
@@ -39,14 +42,15 @@ final class ShareViewController: UIViewController {
3942 guard let provider = providers.first(where: {
4043 $0.hasItemConformingToTypeIdentifier(UTType.url.identifier)
4144 }) else {
42 completion(nil)
43 return
45 return nil
4446 }
4547
46 provider.loadItem(forTypeIdentifier: UTType.url.identifier) { item, _ in
47 let url = item as? URL ?? (item as? Data).flatMap { URL(dataRepresentation: $0, relativeTo: nil) }
48 let host = url?.host?.trimmingCharacters(in: .whitespacesAndNewlines)
49 completion(host?.isEmpty == false ? host : nil)
48 return await withCheckedContinuation { continuation in
49 provider.loadItem(forTypeIdentifier: UTType.url.identifier) { item, _ in
50 let url = item as? URL ?? (item as? Data).flatMap { URL(dataRepresentation: $0, relativeTo: nil) }
51 let host = url?.host?.trimmingCharacters(in: .whitespacesAndNewlines)
52 continuation.resume(returning: host?.isEmpty == false ? host : nil)
53 }
5054 }
5155 }
5256