Commit 3a34fe2460

3a34fe2460974227320cc486701a86d8c06e3c19

parent: 3f5274031a

Unsigned

cmc <hello@cleberg.net> · 2026-10-25 11:30 UTC

Upload reports on run completion, in the chosen formats (!39)

W14's fourth and last part, completing D1's export axis.

Scheduled, monitoring and batch completions upload by default; an interactive
Run is opt-in and off by default, because every tap would otherwise ship an
object. JSON always uploads and PDF and CSV are optional, keyed as
`{prefix}/{domain}/{iso8601}.{ext}` so each format lands at its own key instead
of overwriting the last.

**Why this is not `enqueue(events:)`.** That entry point fans one event out to
every target and applies each target's severity and event-type filters, which
exist for alerts. Whether a finished run exports is a per-target setting, and a
finished run is not an alert, so those filters must not decide it.
`enqueueExports(domains:trigger:)` is its own path for that reason, and it
checks the Pro+ gate itself rather than trusting its callers.

**One entry per format, not per report**, so a PDF that fails to upload retries
without re-sending the JSON that already landed. The entry names its format and
the report is still re-rendered from local history at upload time, so the queue
stays small enough to survive a refresh being cut off — the same reason part 3
kept reports out of it.

Two compatibility details: `QueuedDelivery.export` is optional so entries
written before exports existed still decode (there is a test that decodes a
pre-export entry), and the new `MonitoringEventType.reportExported` is excluded
from the filter list via a new `filterable`, the way `test` already was by hand.
That replaces the three scattered `$0 != .test` filters with one named thing.

Only domains that have a report to upload are queued: the batch trigger skips
results that did not complete, and a domain with no history entry falls through
to the event payload rather than uploading an empty object.

`DomainExportFormat` gains a `mimeType`, so a bucket serves each object back as
the right type rather than as a download.

The four trigger points are `ScheduledReportService.generateReport`,
`DomainMonitoringService`'s run completion, `DomainViewModel.finishBatchLookup`
and `DomainViewModel.performLookup` — the last being the interactive one, which
is why it is the opt-in.

10 new tests, 330 green on iOS 18.6 and 27.0. Ratchet unchanged at 280.

Not covered by tests: the four call sites themselves, and the upload actually
reaching a bucket. The first would need a seam into each service that does not
exist today; the second needs a real endpoint. What is tested is the trigger and
format logic, the queue entry's coding including the pre-export shape, and the
request construction from !38.

Layout: unified · split

DomainDig/DomainMonitoringService.swift +6
@@ -430,6 +430,12 @@ final class DomainMonitoringService {
430 } else { 430 } else {
431 IntegrationService.shared.enqueue(events: outboundEvents) 431 IntegrationService.shared.enqueue(events: outboundEvents)
432 } 432 }
433 // Every domain the run actually inspected, whether or not it changed:
434 // an export is a record of the run, not an alert about it.
435 IntegrationService.shared.enqueueExports(
436 domains: results.map(\.domain),
437 trigger: .monitoring
438 )
433 439
434 return MonitoringRunOutcome( 440 return MonitoringRunOutcome(
435 success: errors.count < results.count, 441 success: errors.count < results.count,
DomainDig/DomainViewModel.swift +9
@@ -1466,6 +1466,9 @@ final class DomainViewModel {
1466 let saveStartedAt = DomainDebugLog.signpostStart("DomainViewModel.saveHistoryEntry", domain: domain) 1466 let saveStartedAt = DomainDebugLog.signpostStart("DomainViewModel.saveHistoryEntry", domain: domain)
1467 let entry = saveHistoryEntry(replaceLatest: false, reuseCurrentAnalysis: true) 1467 let entry = saveHistoryEntry(replaceLatest: false, reuseCurrentAnalysis: true)
1468 DomainDebugLog.signpostEnd("DomainViewModel.saveHistoryEntry", start: saveStartedAt, domain: domain) 1468 DomainDebugLog.signpostEnd("DomainViewModel.saveHistoryEntry", start: saveStartedAt, domain: domain)
1469 // Opt-in, and off by default: this fires on every Run, so a target
1470 // that enabled it ships an object per tap.
1471 IntegrationService.shared.enqueueExports(domains: [domain], trigger: .interactiveRun)
1469 DomainDebugLog.signpostEnd("DomainViewModel.performLookup", start: lookupStartedAt, domain: domain) 1472 DomainDebugLog.signpostEnd("DomainViewModel.performLookup", start: lookupStartedAt, domain: domain)
1470 return entry 1473 return entry
1471 } 1474 }
@@ -2255,6 +2258,12 @@ final class DomainViewModel {
2255 generatedAt: Date() 2258 generatedAt: Date()
2256 ) 2259 )
2257 latestBatchSweepSummary = summary 2260 latestBatchSweepSummary = summary
2261 // Only the domains that actually completed: a failed lookup has no
2262 // report to upload.
2263 IntegrationService.shared.enqueueExports(
2264 domains: batchResults.filter { $0.status == .completed }.map(\.domain),
2265 trigger: .batch
2266 )
2258 SweepActivityController.shared.end(changed: changedCount, warnings: warningCount) 2267 SweepActivityController.shared.end(changed: changedCount, warnings: warningCount)
2259 AppAccessibility.announce( 2268 AppAccessibility.announce(
2260 "Sweep complete. \(summary.results.count) domains, \(changedCount) changed, \(warningCount) warnings." 2269 "Sweep complete. \(summary.results.count) domains, \(changedCount) changed, \(warningCount) warnings."
DomainDig/IntegrationService.swift +92 −19
@@ -112,6 +112,55 @@ final class IntegrationService {
112 .sorted { $0.timestamp > $1.timestamp } 112 .sorted { $0.timestamp > $1.timestamp }
113 } 113 }
114 114
115 /// Queues an upload of each domain's latest report to every S3 target set
116 /// to fire on `trigger`, one entry per configured format.
117 ///
118 /// Deliberately not routed through `enqueue(events:)`. That fans one event
119 /// out to every target and applies each target's severity and event-type
120 /// filters, which exist for alerts. Whether a completed run exports is a
121 /// per-target setting, and a finished run is not an alert, so the filters
122 /// must not decide it.
123 ///
124 /// One entry per format rather than one per report, so a PDF that fails to
125 /// upload retries without re-sending the JSON that already landed.
126 func enqueueExports(domains: [String], trigger: S3ExportTrigger) {
127 guard FeatureAccessService.hasAccess(to: .bucketExport) else { return }
128
129 var seen = Set<String>()
130 let normalizedDomains = domains
131 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
132 .filter { !$0.isEmpty && seen.insert($0).inserted }
133 guard !normalizedDomains.isEmpty else { return }
134
135 var queuedAny = false
136 for target in targets {
137 guard target.isEnabled, case .s3(let configuration) = target.configuration else { continue }
138 guard configuration.uploads(on: trigger) else { continue }
139
140 for domain in normalizedDomains {
141 for format in configuration.formats {
142 queue.append(
143 QueuedDelivery(
144 integrationID: target.id,
145 event: MonitoringEvent(
146 type: .reportExported,
147 severity: .info,
148 domain: domain,
149 summary: "\(trigger.title): \(domain) as \(format.title)"
150 ),
151 export: ExportDelivery(format: format, trigger: trigger)
152 )
153 )
154 queuedAny = true
155 }
156 }
157 }
158
159 guard queuedAny else { return }
160 persistQueue()
161 scheduleProcessing()
162 }
163
115 func enqueue(events: [MonitoringEvent]) { 164 func enqueue(events: [MonitoringEvent]) {
116 guard !events.isEmpty else { return } 165 guard !events.isEmpty else { return }
117 for event in events { 166 for event in events {
@@ -328,7 +377,7 @@ final class IntegrationService {
328 } 377 }
329 378
330 do { 379 do {
331 try await deliver(item.event, to: target) 380 try await deliver(item, to: target)
332 queue.remove(at: index) 381 queue.remove(at: index)
333 persistQueue() 382 persistQueue()
334 appendRecord( 383 appendRecord(
@@ -382,7 +431,8 @@ final class IntegrationService {
382 } 431 }
383 } 432 }
384 433
385 private func deliver(_ event: MonitoringEvent, to target: IntegrationTarget) async throws { 434 private func deliver(_ item: QueuedDelivery, to target: IntegrationTarget) async throws {
435 let event = item.event
386 switch target.configuration { 436 switch target.configuration {
387 case .webhook(let configuration): 437 case .webhook(let configuration):
388 guard let reference = configuration.credentialReference else { 438 guard let reference = configuration.credentialReference else {
@@ -411,7 +461,7 @@ final class IntegrationService {
411 throw IntegrationError.missingSecret 461 throw IntegrationError.missingSecret
412 } 462 }
413 let secretAccessKey = try IntegrationSecretStore.secret(reference: reference) 463 let secretAccessKey = try IntegrationSecretStore.secret(reference: reference)
414 let object = Self.s3Object(for: event) 464 let object = try Self.s3Object(for: item, configuration: configuration)
415 let request = try S3UploadClient.request( 465 let request = try S3UploadClient.request(
416 for: object, 466 for: object,
417 configuration: configuration, 467 configuration: configuration,
@@ -457,36 +507,59 @@ final class IntegrationService {
457 Self.save(queue, key: StorageKey.queue, defaults: defaults) 507 Self.save(queue, key: StorageKey.queue, defaults: defaults)
458 } 508 }
459 509
460 /// What an event uploads: the domain's latest stored report when there is 510 /// The object to upload.
461 /// one, and the event itself otherwise. 511 ///
512 /// An export entry names its format and renders the domain's latest stored
513 /// report in it. Anything else — a test delivery, or an event on a target
514 /// with no report to find — uploads the event as JSON, which is what makes
515 /// the test action prove the endpoint, the signature and the bucket policy
516 /// without needing a lookup first.
462 /// 517 ///
463 /// A test delivery takes the second path, which is the point of it — it 518 /// The key is `{prefix}/{domain}/{iso8601}.{ext}`, the prefix coming from
464 /// proves the endpoint, the signature and the bucket policy without 519 /// the configuration.
465 /// needing a lookup to have happened first. 520 private static func s3Object(
466 private static func s3Object(for event: MonitoringEvent) -> S3UploadClient.Object { 521 for item: QueuedDelivery,
522 configuration: S3IntegrationConfiguration
523 ) throws -> S3UploadClient.Object {
524 let event = item.event
525 let domain = event.domain.isEmpty ? "unknown" : event.domain
526 let timestamp = Self.objectTimestampFormatter.string(from: event.timestamp)
527 let report = Self.latestReport(for: domain)
528
529 if let export = item.export, let report {
530 return S3UploadClient.Object(
531 key: "\(domain)/\(timestamp).\(export.format.fileExtension)",
532 body: try DomainReportExporter.data(for: report, format: export.format),
533 contentType: export.format.mimeType
534 )
535 }
536
467 let encoder = JSONEncoder() 537 let encoder = JSONEncoder()
468 encoder.outputFormatting = [.prettyPrinted, .sortedKeys] 538 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
469 encoder.dateEncodingStrategy = .iso8601 539 encoder.dateEncodingStrategy = .iso8601
470
471 let domain = event.domain.isEmpty ? "unknown" : event.domain
472 let snapshot = MonitoringStorage.loadHistoryEntries()
473 .first { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }?
474 .snapshot
475
476 let body: Data 540 let body: Data
477 if let snapshot, let encoded = try? encoder.encode(DomainReportBuilder().build(from: snapshot)) { 541 if let report, let encoded = try? encoder.encode(report) {
478 body = encoded 542 body = encoded
479 } else { 543 } else {
480 body = (try? encoder.encode(IntegrationEventPayload(event: event))) ?? Data() 544 body = (try? encoder.encode(IntegrationEventPayload(event: event))) ?? Data()
481 } 545 }
482
483 return S3UploadClient.Object( 546 return S3UploadClient.Object(
484 key: "\(domain)/\(Self.objectTimestampFormatter.string(from: event.timestamp)).json", 547 key: "\(domain)/\(timestamp).json",
485 body: body, 548 body: body,
486 contentType: "application/json" 549 contentType: DomainExportFormat.json.mimeType
487 ) 550 )
488 } 551 }
489 552
553 private static func latestReport(for domain: String) -> DomainReport? {
554 guard let snapshot = MonitoringStorage.loadHistoryEntries()
555 .first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame })?
556 .snapshot
557 else {
558 return nil
559 }
560 return DomainReportBuilder().build(from: snapshot)
561 }
562
490 private static let objectTimestampFormatter: ISO8601DateFormatter = { 563 private static let objectTimestampFormatter: ISO8601DateFormatter = {
491 let formatter = ISO8601DateFormatter() 564 let formatter = ISO8601DateFormatter()
492 formatter.timeZone = TimeZone(identifier: "UTC") 565 formatter.timeZone = TimeZone(identifier: "UTC")
DomainDig/IntegrationsView.swift +57 −3
@@ -201,7 +201,7 @@ private struct IntegrationEditorView: View {
201 @State private var name: String = "" 201 @State private var name: String = ""
202 @State private var isEnabled = true 202 @State private var isEnabled = true
203 @State private var minimumSeverity: EventSeverity = .warning 203 @State private var minimumSeverity: EventSeverity = .warning
204 @State private var selectedEventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.allCases.filter { $0 != .test }) 204 @State private var selectedEventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.filterable)
205 @State private var s3Endpoint = "" 205 @State private var s3Endpoint = ""
206 @State private var s3Region = "us-east-1" 206 @State private var s3Region = "us-east-1"
207 @State private var s3Bucket = "" 207 @State private var s3Bucket = ""
@@ -209,6 +209,8 @@ private struct IntegrationEditorView: View {
209 @State private var s3UsesPathStyle = false 209 @State private var s3UsesPathStyle = false
210 @State private var s3AccessKeyID = "" 210 @State private var s3AccessKeyID = ""
211 @State private var s3SecretAccessKey = "" 211 @State private var s3SecretAccessKey = ""
212 @State private var s3Triggers: Set<S3ExportTrigger> = S3ExportTrigger.defaults
213 @State private var s3ExtraFormats: Set<DomainExportFormat> = []
212 @State private var domainsText = "" 214 @State private var domainsText = ""
213 215
214 @State private var webhookURL = "" 216 @State private var webhookURL = ""
@@ -254,7 +256,7 @@ private struct IntegrationEditorView: View {
254 .textInputAutocapitalization(.never) 256 .textInputAutocapitalization(.never)
255 .autocorrectionDisabled() 257 .autocorrectionDisabled()
256 258
257 ForEach(MonitoringEventType.allCases.filter { $0 != .test }, id: \.self) { eventType in 259 ForEach(MonitoringEventType.filterable, id: \.self) { eventType in
258 Toggle( 260 Toggle(
259 eventType.title, 261 eventType.title,
260 isOn: Binding( 262 isOn: Binding(
@@ -385,6 +387,54 @@ private struct IntegrationEditorView: View {
385 .foregroundStyle(Color(.appTextSecondary)) 387 .foregroundStyle(Color(.appTextSecondary))
386 } 388 }
387 } 389 }
390
391 Section("Upload when") {
392 ForEach(S3ExportTrigger.allCases) { trigger in
393 Toggle(
394 isOn: Binding(
395 get: { s3Triggers.contains(trigger) },
396 set: { isOn in
397 if isOn {
398 s3Triggers.insert(trigger)
399 } else {
400 s3Triggers.remove(trigger)
401 }
402 }
403 )
404 ) {
405 VStack(alignment: .leading, spacing: 2) {
406 Text(trigger.title)
407 if let detail = trigger.detail {
408 Text(detail)
409 .font(.caption)
410 .foregroundStyle(Color(.appTextSecondary))
411 }
412 }
413 }
414 }
415 }
416
417 Section("Formats") {
418 Text("JSON always uploads. The others are renderings of it.")
419 .font(.caption)
420 .foregroundStyle(Color(.appTextSecondary))
421
422 ForEach([DomainExportFormat.pdf, .csv]) { format in
423 Toggle(
424 format.title,
425 isOn: Binding(
426 get: { s3ExtraFormats.contains(format) },
427 set: { isOn in
428 if isOn {
429 s3ExtraFormats.insert(format)
430 } else {
431 s3ExtraFormats.remove(format)
432 }
433 }
434 )
435 )
436 }
437 }
388 } 438 }
389 439
390 if let validationMessage { 440 if let validationMessage {
@@ -442,6 +492,8 @@ private struct IntegrationEditorView: View {
442 s3KeyPrefix = configuration.keyPrefix 492 s3KeyPrefix = configuration.keyPrefix
443 s3UsesPathStyle = configuration.usesPathStyle 493 s3UsesPathStyle = configuration.usesPathStyle
444 s3AccessKeyID = configuration.accessKeyID 494 s3AccessKeyID = configuration.accessKeyID
495 s3Triggers = configuration.triggers
496 s3ExtraFormats = configuration.extraFormats
445 } 497 }
446 } 498 }
447 499
@@ -608,7 +660,9 @@ private struct IntegrationEditorView: View {
608 keyPrefix: s3KeyPrefix.trimmingCharacters(in: .whitespacesAndNewlines), 660 keyPrefix: s3KeyPrefix.trimmingCharacters(in: .whitespacesAndNewlines),
609 usesPathStyle: s3UsesPathStyle, 661 usesPathStyle: s3UsesPathStyle,
610 accessKeyID: trimmedAccessKeyID, 662 accessKeyID: trimmedAccessKeyID,
611 credentialReference: existingReference 663 credentialReference: existingReference,
664 triggers: s3Triggers,
665 extraFormats: s3ExtraFormats
612 ) 666 )
613 ), 667 ),
614 filters: filters 668 filters: filters
DomainDig/Models.swift +91 −3
@@ -1676,9 +1676,17 @@ enum MonitoringEventType: String, Codable, CaseIterable, Identifiable, Sendable
1676 case monitoringFailure 1676 case monitoringFailure
1677 case changeDetected 1677 case changeDetected
1678 case test 1678 case test
1679 case reportExported
1679 1680
1680 var id: String { rawValue } 1681 var id: String { rawValue }
1681 1682
1683 /// Types a user can filter an integration on. `test` and `reportExported`
1684 /// are not alerts — one is a probe, the other is the carrier for an upload
1685 /// that bypasses filters — so neither belongs in the filter list.
1686 static var filterable: [MonitoringEventType] {
1687 allCases.filter { $0 != .test && $0 != .reportExported }
1688 }
1689
1682 var title: String { 1690 var title: String {
1683 switch self { 1691 switch self {
1684 case .dnsChanged: 1692 case .dnsChanged:
@@ -1699,6 +1707,8 @@ enum MonitoringEventType: String, Codable, CaseIterable, Identifiable, Sendable
1699 return "Change Detected" 1707 return "Change Detected"
1700 case .test: 1708 case .test:
1701 return "Test Event" 1709 return "Test Event"
1710 case .reportExported:
1711 return "Report Exported"
1702 } 1712 }
1703 } 1713 }
1704} 1714}
@@ -1820,6 +1830,59 @@ struct EmailIntegrationConfiguration: Codable, Equatable, Sendable {
1820 } 1830 }
1821} 1831}
1822 1832
1833/// When a completed run uploads.
1834///
1835/// Scheduled, monitoring and batch runs upload by default. An interactive Run
1836/// does not, because every tap would otherwise ship an object (D1).
1837enum S3ExportTrigger: String, Codable, CaseIterable, Identifiable, Sendable {
1838 case scheduled
1839 case monitoring
1840 case batch
1841 case interactiveRun
1842
1843 var id: String { rawValue }
1844
1845 /// The triggers a new target starts with.
1846 static let defaults: Set<S3ExportTrigger> = [.scheduled, .monitoring, .batch]
1847
1848 var title: String {
1849 switch self {
1850 case .scheduled:
1851 return "Scheduled reports"
1852 case .monitoring:
1853 return "Monitoring runs"
1854 case .batch:
1855 return "Batch lookups"
1856 case .interactiveRun:
1857 return "Every lookup you run"
1858 }
1859 }
1860
1861 var detail: String? {
1862 switch self {
1863 case .interactiveRun:
1864 return "Off by default: every tap would upload an object."
1865 case .scheduled, .monitoring, .batch:
1866 return nil
1867 }
1868 }
1869}
1870
1871/// One object to upload: which format, and what asked for it.
1872///
1873/// The report itself is not here. It is re-rendered from local history when the
1874/// upload runs, because the queue persists to UserDefaults and has to stay
1875/// small enough to survive a refresh being cut off.
1876struct ExportDelivery: Codable, Equatable, Sendable {
1877 var format: DomainExportFormat
1878 var trigger: S3ExportTrigger
1879
1880 init(format: DomainExportFormat, trigger: S3ExportTrigger) {
1881 self.format = format
1882 self.trigger = trigger
1883 }
1884}
1885
1823/// An S3-compatible bucket the user owns: S3 itself, R2, B2, MinIO, Wasabi or 1886/// An S3-compatible bucket the user owns: S3 itself, R2, B2, MinIO, Wasabi or
1824/// Spaces. 1887/// Spaces.
1825/// 1888///
@@ -1840,6 +1903,10 @@ struct S3IntegrationConfiguration: Codable, Equatable, Sendable {
1840 var usesPathStyle: Bool 1903 var usesPathStyle: Bool
1841 var accessKeyID: String 1904 var accessKeyID: String
1842 var credentialReference: String? 1905 var credentialReference: String?
1906 /// Which completed runs upload.
1907 var triggers: Set<S3ExportTrigger>
1908 /// Formats beyond JSON. JSON always uploads, so it is not listed here.
1909 var extraFormats: Set<DomainExportFormat>
1843 1910
1844 init( 1911 init(
1845 endpoint: String = "", 1912 endpoint: String = "",
@@ -1848,7 +1915,9 @@ struct S3IntegrationConfiguration: Codable, Equatable, Sendable {
1848 keyPrefix: String = "domaindig", 1915 keyPrefix: String = "domaindig",
1849 usesPathStyle: Bool = false, 1916 usesPathStyle: Bool = false,
1850 accessKeyID: String = "", 1917 accessKeyID: String = "",
1851 credentialReference: String? = nil 1918 credentialReference: String? = nil,
1919 triggers: Set<S3ExportTrigger> = S3ExportTrigger.defaults,
1920 extraFormats: Set<DomainExportFormat> = []
1852 ) { 1921 ) {
1853 self.endpoint = endpoint 1922 self.endpoint = endpoint
1854 self.region = region 1923 self.region = region
@@ -1857,6 +1926,20 @@ struct S3IntegrationConfiguration: Codable, Equatable, Sendable {
1857 self.usesPathStyle = usesPathStyle 1926 self.usesPathStyle = usesPathStyle
1858 self.accessKeyID = accessKeyID 1927 self.accessKeyID = accessKeyID
1859 self.credentialReference = credentialReference 1928 self.credentialReference = credentialReference
1929 self.triggers = triggers
1930 self.extraFormats = extraFormats
1931 }
1932
1933 /// Every format this target uploads, JSON first.
1934 ///
1935 /// JSON is not optional: it is the only format that round-trips, and the
1936 /// others are renderings of it.
1937 var formats: [DomainExportFormat] {
1938 [.json] + extraFormats.filter { $0 != .json }.sorted { $0.rawValue < $1.rawValue }
1939 }
1940
1941 func uploads(on trigger: S3ExportTrigger) -> Bool {
1942 triggers.contains(trigger)
1860 } 1943 }
1861} 1944}
1862 1945
@@ -1928,7 +2011,7 @@ struct IntegrationFilterSet: Codable, Equatable, Sendable {
1928 2011
1929 init( 2012 init(
1930 minimumSeverity: EventSeverity = .warning, 2013 minimumSeverity: EventSeverity = .warning,
1931 eventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.allCases.filter { $0 != .test }), 2014 eventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.filterable),
1932 domains: [String] = [] 2015 domains: [String] = []
1933 ) { 2016 ) {
1934 self.minimumSeverity = minimumSeverity 2017 self.minimumSeverity = minimumSeverity
@@ -2033,6 +2116,9 @@ struct QueuedDelivery: Codable, Identifiable, Equatable, Sendable {
2033 var nextAttemptAt: Date 2116 var nextAttemptAt: Date
2034 var lastError: String? 2117 var lastError: String?
2035 var expiresAt: Date 2118 var expiresAt: Date
2119 /// Set when this entry is an export upload rather than an event delivery.
2120 /// Optional so queue entries written before exports existed still decode.
2121 var export: ExportDelivery?
2036 2122
2037 init( 2123 init(
2038 id: UUID = UUID(), 2124 id: UUID = UUID(),
@@ -2042,7 +2128,8 @@ struct QueuedDelivery: Codable, Identifiable, Equatable, Sendable {
2042 attemptCount: Int = 0, 2128 attemptCount: Int = 0,
2043 nextAttemptAt: Date = Date(), 2129 nextAttemptAt: Date = Date(),
2044 lastError: String? = nil, 2130 lastError: String? = nil,
2045 expiresAt: Date = Date().addingTimeInterval(3 * 24 * 60 * 60) 2131 expiresAt: Date = Date().addingTimeInterval(3 * 24 * 60 * 60),
2132 export: ExportDelivery? = nil
2046 ) { 2133 ) {
2047 self.id = id 2134 self.id = id
2048 self.integrationID = integrationID 2135 self.integrationID = integrationID
@@ -2052,6 +2139,7 @@ struct QueuedDelivery: Codable, Identifiable, Equatable, Sendable {
2052 self.nextAttemptAt = nextAttemptAt 2139 self.nextAttemptAt = nextAttemptAt
2053 self.lastError = lastError 2140 self.lastError = lastError
2054 self.expiresAt = expiresAt 2141 self.expiresAt = expiresAt
2142 self.export = export
2055 } 2143 }
2056} 2144}
2057 2145
DomainDig/ScheduledReportService.swift +4
@@ -156,6 +156,10 @@ final class ScheduledReportService {
156 ScheduledReportStorage.saveSettings(settings) 156 ScheduledReportStorage.saveSettings(settings)
157 157
158 await LocalNotificationService.shared.notifyScheduledReportReady(domainCount: reports.count) 158 await LocalNotificationService.shared.notifyScheduledReportReady(domainCount: reports.count)
159 IntegrationService.shared.enqueueExports(
160 domains: reports.map(\.domain),
161 trigger: .scheduled
162 )
159 163
160 return ScheduledReportOutcome(success: true, message: "Report generated for \(reports.count) domains.", log: log) 164 return ScheduledReportOutcome(success: true, message: "Report generated for \(reports.count) domains.", log: log)
161 } 165 }
DomainDigTests/S3UploadClientTests.swift +129
@@ -292,6 +292,135 @@ final class S3UploadClientTests: XCTestCase {
292 XCTAssertEqual(configuration.bucket, "my-bucket") 292 XCTAssertEqual(configuration.bucket, "my-bucket")
293 } 293 }
294 294
295 // MARK: Triggers
296
297 /// Scheduled, monitoring and batch upload by default; an interactive Run
298 /// does not, because every tap would otherwise ship an object (D1).
299 func testInteractiveRunIsTheOnlyTriggerOffByDefault() {
300 let configuration = S3IntegrationConfiguration()
301
302 XCTAssertTrue(configuration.uploads(on: .scheduled))
303 XCTAssertTrue(configuration.uploads(on: .monitoring))
304 XCTAssertTrue(configuration.uploads(on: .batch))
305 XCTAssertFalse(configuration.uploads(on: .interactiveRun))
306 }
307
308 func testTriggersAreIndependentlySettable() {
309 var configuration = S3IntegrationConfiguration(triggers: [.interactiveRun])
310
311 XCTAssertTrue(configuration.uploads(on: .interactiveRun))
312 XCTAssertFalse(configuration.uploads(on: .monitoring))
313
314 configuration.triggers = []
315 for trigger in S3ExportTrigger.allCases {
316 XCTAssertFalse(configuration.uploads(on: trigger))
317 }
318 }
319
320 // MARK: Formats
321
322 /// JSON always uploads: it is the only format that round-trips, and the
323 /// others are renderings of it.
324 func testJSONUploadsEvenWithNoExtraFormats() {
325 XCTAssertEqual(S3IntegrationConfiguration().formats, [.json])
326 }
327
328 func testExtraFormatsAreAddedAfterJSON() {
329 let configuration = S3IntegrationConfiguration(extraFormats: [.pdf, .csv])
330
331 XCTAssertEqual(configuration.formats.first, .json)
332 XCTAssertEqual(Set(configuration.formats), [.json, .csv, .pdf])
333 }
334
335 /// JSON is implicit, so selecting it as an extra must not upload it twice.
336 func testJSONAsAnExtraFormatIsNotDuplicated() {
337 XCTAssertEqual(S3IntegrationConfiguration(extraFormats: [.json]).formats, [.json])
338 }
339
340 /// The key template is `{prefix}/{domain}/{iso8601}.{ext}`, so each format
341 /// lands at its own key rather than overwriting the last one.
342 func testEachFormatHasItsOwnExtension() {
343 XCTAssertEqual(DomainExportFormat.json.fileExtension, "json")
344 XCTAssertEqual(DomainExportFormat.pdf.fileExtension, "pdf")
345 XCTAssertEqual(DomainExportFormat.csv.fileExtension, "csv")
346 XCTAssertEqual(DomainExportFormat.pdf.mimeType, "application/pdf")
347 XCTAssertEqual(DomainExportFormat.json.mimeType, "application/json")
348 }
349
350 /// The export carrier is not an alert, so it must not appear in the list a
351 /// user filters an integration on.
352 func testTheExportEventTypeIsNotFilterable() {
353 XCTAssertFalse(MonitoringEventType.filterable.contains(.reportExported))
354 XCTAssertFalse(MonitoringEventType.filterable.contains(.test))
355 XCTAssertTrue(MonitoringEventType.filterable.contains(.dnsChanged))
356 }
357
358 /// Queue entries written before exports existed have no `export` field and
359 /// still have to decode.
360 func testAQueueEntryWithoutAnExportDescriptorStillDecodes() throws {
361 let json = Data("""
362 {
363 "id": "5E7E4B0E-0000-4000-8000-000000000001",
364 "integrationID": "5E7E4B0E-0000-4000-8000-000000000002",
365 "event": {
366 "id": "5E7E4B0E-0000-4000-8000-000000000003",
367 "type": "dnsChanged",
368 "severity": "warning",
369 "domain": "example.com",
370 "timestamp": 0,
371 "summary": "changed",
372 "details": {}
373 },
374 "createdAt": 0,
375 "attemptCount": 0,
376 "nextAttemptAt": 0,
377 "expiresAt": 1
378 }
379 """.utf8)
380
381 let decoded = try JSONDecoder().decode(QueuedDelivery.self, from: json)
382
383 XCTAssertNil(decoded.export)
384 XCTAssertEqual(decoded.event.domain, "example.com")
385 }
386
387 func testAnExportQueueEntryRoundTrips() throws {
388 let entry = QueuedDelivery(
389 integrationID: UUID(),
390 event: MonitoringEvent(
391 type: .reportExported,
392 severity: .info,
393 domain: "example.com",
394 summary: "Batch lookups: example.com as PDF"
395 ),
396 export: ExportDelivery(format: .pdf, trigger: .batch)
397 )
398
399 let decoded = try JSONDecoder().decode(
400 QueuedDelivery.self,
401 from: try JSONEncoder().encode(entry)
402 )
403
404 XCTAssertEqual(decoded.export, ExportDelivery(format: .pdf, trigger: .batch))
405 XCTAssertEqual(decoded.event.type, .reportExported)
406 }
407
408 /// Triggers and formats are persisted with the target.
409 func testTriggersAndFormatsRoundTripThroughCoding() throws {
410 var configuration = configuration()
411 configuration.triggers = [.interactiveRun, .batch]
412 configuration.extraFormats = [.pdf]
413
414 let decoded = try JSONDecoder().decode(
415 S3IntegrationConfiguration.self,
416 from: try JSONEncoder().encode(configuration)
417 )
418
419 XCTAssertEqual(decoded.triggers, [.interactiveRun, .batch])
420 XCTAssertEqual(decoded.extraFormats, [.pdf])
421 XCTAssertEqual(decoded.formats, [.json, .pdf])
422 }
423
295 /// The secret is never part of the configuration — it lives in the 424 /// The secret is never part of the configuration — it lives in the
296 /// Keychain and only the reference is stored. 425 /// Keychain and only the reference is stored.
297 func testTheConfigurationCarriesNoSecret() throws { 426 func testTheConfigurationCarriesNoSecret() throws {
DomainReportExporter.swift +12
@@ -23,6 +23,18 @@ enum DomainExportFormat: String, CaseIterable, Identifiable, Codable {
23 case .pdf: return "PDF" 23 case .pdf: return "PDF"
24 } 24 }
25 } 25 }
26
27 /// Sent as `Content-Type` when a report is uploaded, so a bucket serves it
28 /// back as the right thing rather than as a download.
29 var mimeType: String {
30 switch self {
31 case .text: return "text/plain; charset=utf-8"
32 case .csv: return "text/csv; charset=utf-8"
33 case .json: return "application/json"
34 case .markdown: return "text/markdown; charset=utf-8"
35 case .pdf: return "application/pdf"
36 }
37 }
26} 38}
27 39
28enum DomainReportExporter { 40enum DomainReportExporter {