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 {
430430 } else {
431431 IntegrationService.shared.enqueue(events: outboundEvents)
432432 }
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 )
433439
434440 return MonitoringRunOutcome(
435441 success: errors.count < results.count,
DomainDig/DomainViewModel.swift +9
@@ -1466,6 +1466,9 @@ final class DomainViewModel {
14661466 let saveStartedAt = DomainDebugLog.signpostStart("DomainViewModel.saveHistoryEntry", domain: domain)
14671467 let entry = saveHistoryEntry(replaceLatest: false, reuseCurrentAnalysis: true)
14681468 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)
14691472 DomainDebugLog.signpostEnd("DomainViewModel.performLookup", start: lookupStartedAt, domain: domain)
14701473 return entry
14711474 }
@@ -2255,6 +2258,12 @@ final class DomainViewModel {
22552258 generatedAt: Date()
22562259 )
22572260 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 )
22582267 SweepActivityController.shared.end(changed: changedCount, warnings: warningCount)
22592268 AppAccessibility.announce(
22602269 "Sweep complete. \(summary.results.count) domains, \(changedCount) changed, \(warningCount) warnings."
DomainDig/IntegrationService.swift +92 −19
@@ -112,6 +112,55 @@ final class IntegrationService {
112112 .sorted { $0.timestamp > $1.timestamp }
113113 }
114114
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
115164 func enqueue(events: [MonitoringEvent]) {
116165 guard !events.isEmpty else { return }
117166 for event in events {
@@ -328,7 +377,7 @@ final class IntegrationService {
328377 }
329378
330379 do {
331 try await deliver(item.event, to: target)
380 try await deliver(item, to: target)
332381 queue.remove(at: index)
333382 persistQueue()
334383 appendRecord(
@@ -382,7 +431,8 @@ final class IntegrationService {
382431 }
383432 }
384433
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
386436 switch target.configuration {
387437 case .webhook(let configuration):
388438 guard let reference = configuration.credentialReference else {
@@ -411,7 +461,7 @@ final class IntegrationService {
411461 throw IntegrationError.missingSecret
412462 }
413463 let secretAccessKey = try IntegrationSecretStore.secret(reference: reference)
414 let object = Self.s3Object(for: event)
464 let object = try Self.s3Object(for: item, configuration: configuration)
415465 let request = try S3UploadClient.request(
416466 for: object,
417467 configuration: configuration,
@@ -457,36 +507,59 @@ final class IntegrationService {
457507 Self.save(queue, key: StorageKey.queue, defaults: defaults)
458508 }
459509
460 /// What an event uploads: the domain's latest stored report when there is
461 /// one, and the event itself otherwise.
510 /// The object to upload.
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.
462517 ///
463 /// A test delivery takes the second path, which is the point of it — it
464 /// proves the endpoint, the signature and the bucket policy without
465 /// needing a lookup to have happened first.
466 private static func s3Object(for event: MonitoringEvent) -> S3UploadClient.Object {
518 /// The key is `{prefix}/{domain}/{iso8601}.{ext}`, the prefix coming from
519 /// the configuration.
520 private static func s3Object(
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
467537 let encoder = JSONEncoder()
468538 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
469539 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
476540 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) {
478542 body = encoded
479543 } else {
480544 body = (try? encoder.encode(IntegrationEventPayload(event: event))) ?? Data()
481545 }
482
483546 return S3UploadClient.Object(
484 key: "\(domain)/\(Self.objectTimestampFormatter.string(from: event.timestamp)).json",
547 key: "\(domain)/\(timestamp).json",
485548 body: body,
486 contentType: "application/json"
549 contentType: DomainExportFormat.json.mimeType
487550 )
488551 }
489552
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
490563 private static let objectTimestampFormatter: ISO8601DateFormatter = {
491564 let formatter = ISO8601DateFormatter()
492565 formatter.timeZone = TimeZone(identifier: "UTC")
DomainDig/IntegrationsView.swift +57 −3
@@ -201,7 +201,7 @@ private struct IntegrationEditorView: View {
201201 @State private var name: String = ""
202202 @State private var isEnabled = true
203203 @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)
205205 @State private var s3Endpoint = ""
206206 @State private var s3Region = "us-east-1"
207207 @State private var s3Bucket = ""
@@ -209,6 +209,8 @@ private struct IntegrationEditorView: View {
209209 @State private var s3UsesPathStyle = false
210210 @State private var s3AccessKeyID = ""
211211 @State private var s3SecretAccessKey = ""
212 @State private var s3Triggers: Set<S3ExportTrigger> = S3ExportTrigger.defaults
213 @State private var s3ExtraFormats: Set<DomainExportFormat> = []
212214 @State private var domainsText = ""
213215
214216 @State private var webhookURL = ""
@@ -254,7 +256,7 @@ private struct IntegrationEditorView: View {
254256 .textInputAutocapitalization(.never)
255257 .autocorrectionDisabled()
256258
257 ForEach(MonitoringEventType.allCases.filter { $0 != .test }, id: \.self) { eventType in
259 ForEach(MonitoringEventType.filterable, id: \.self) { eventType in
258260 Toggle(
259261 eventType.title,
260262 isOn: Binding(
@@ -385,6 +387,54 @@ private struct IntegrationEditorView: View {
385387 .foregroundStyle(Color(.appTextSecondary))
386388 }
387389 }
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 }
388438 }
389439
390440 if let validationMessage {
@@ -442,6 +492,8 @@ private struct IntegrationEditorView: View {
442492 s3KeyPrefix = configuration.keyPrefix
443493 s3UsesPathStyle = configuration.usesPathStyle
444494 s3AccessKeyID = configuration.accessKeyID
495 s3Triggers = configuration.triggers
496 s3ExtraFormats = configuration.extraFormats
445497 }
446498 }
447499
@@ -608,7 +660,9 @@ private struct IntegrationEditorView: View {
608660 keyPrefix: s3KeyPrefix.trimmingCharacters(in: .whitespacesAndNewlines),
609661 usesPathStyle: s3UsesPathStyle,
610662 accessKeyID: trimmedAccessKeyID,
611 credentialReference: existingReference
663 credentialReference: existingReference,
664 triggers: s3Triggers,
665 extraFormats: s3ExtraFormats
612666 )
613667 ),
614668 filters: filters
DomainDig/Models.swift +91 −3
@@ -1676,9 +1676,17 @@ enum MonitoringEventType: String, Codable, CaseIterable, Identifiable, Sendable
16761676 case monitoringFailure
16771677 case changeDetected
16781678 case test
1679 case reportExported
16791680
16801681 var id: String { rawValue }
16811682
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
16821690 var title: String {
16831691 switch self {
16841692 case .dnsChanged:
@@ -1699,6 +1707,8 @@ enum MonitoringEventType: String, Codable, CaseIterable, Identifiable, Sendable
16991707 return "Change Detected"
17001708 case .test:
17011709 return "Test Event"
1710 case .reportExported:
1711 return "Report Exported"
17021712 }
17031713 }
17041714}
@@ -1820,6 +1830,59 @@ struct EmailIntegrationConfiguration: Codable, Equatable, Sendable {
18201830 }
18211831}
18221832
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
18231886/// An S3-compatible bucket the user owns: S3 itself, R2, B2, MinIO, Wasabi or
18241887/// Spaces.
18251888///
@@ -1840,6 +1903,10 @@ struct S3IntegrationConfiguration: Codable, Equatable, Sendable {
18401903 var usesPathStyle: Bool
18411904 var accessKeyID: String
18421905 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>
18431910
18441911 init(
18451912 endpoint: String = "",
@@ -1848,7 +1915,9 @@ struct S3IntegrationConfiguration: Codable, Equatable, Sendable {
18481915 keyPrefix: String = "domaindig",
18491916 usesPathStyle: Bool = false,
18501917 accessKeyID: String = "",
1851 credentialReference: String? = nil
1918 credentialReference: String? = nil,
1919 triggers: Set<S3ExportTrigger> = S3ExportTrigger.defaults,
1920 extraFormats: Set<DomainExportFormat> = []
18521921 ) {
18531922 self.endpoint = endpoint
18541923 self.region = region
@@ -1857,6 +1926,20 @@ struct S3IntegrationConfiguration: Codable, Equatable, Sendable {
18571926 self.usesPathStyle = usesPathStyle
18581927 self.accessKeyID = accessKeyID
18591928 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)
18601943 }
18611944}
18621945
@@ -1928,7 +2011,7 @@ struct IntegrationFilterSet: Codable, Equatable, Sendable {
19282011
19292012 init(
19302013 minimumSeverity: EventSeverity = .warning,
1931 eventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.allCases.filter { $0 != .test }),
2014 eventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.filterable),
19322015 domains: [String] = []
19332016 ) {
19342017 self.minimumSeverity = minimumSeverity
@@ -2033,6 +2116,9 @@ struct QueuedDelivery: Codable, Identifiable, Equatable, Sendable {
20332116 var nextAttemptAt: Date
20342117 var lastError: String?
20352118 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?
20362122
20372123 init(
20382124 id: UUID = UUID(),
@@ -2042,7 +2128,8 @@ struct QueuedDelivery: Codable, Identifiable, Equatable, Sendable {
20422128 attemptCount: Int = 0,
20432129 nextAttemptAt: Date = Date(),
20442130 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
20462133 ) {
20472134 self.id = id
20482135 self.integrationID = integrationID
@@ -2052,6 +2139,7 @@ struct QueuedDelivery: Codable, Identifiable, Equatable, Sendable {
20522139 self.nextAttemptAt = nextAttemptAt
20532140 self.lastError = lastError
20542141 self.expiresAt = expiresAt
2142 self.export = export
20552143 }
20562144}
20572145
DomainDig/ScheduledReportService.swift +4
@@ -156,6 +156,10 @@ final class ScheduledReportService {
156156 ScheduledReportStorage.saveSettings(settings)
157157
158158 await LocalNotificationService.shared.notifyScheduledReportReady(domainCount: reports.count)
159 IntegrationService.shared.enqueueExports(
160 domains: reports.map(\.domain),
161 trigger: .scheduled
162 )
159163
160164 return ScheduledReportOutcome(success: true, message: "Report generated for \(reports.count) domains.", log: log)
161165 }
DomainDigTests/S3UploadClientTests.swift +129
@@ -292,6 +292,135 @@ final class S3UploadClientTests: XCTestCase {
292292 XCTAssertEqual(configuration.bucket, "my-bucket")
293293 }
294294
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
295424 /// The secret is never part of the configuration — it lives in the
296425 /// Keychain and only the reference is stored.
297426 func testTheConfigurationCarriesNoSecret() throws {
DomainReportExporter.swift +12
@@ -23,6 +23,18 @@ enum DomainExportFormat: String, CaseIterable, Identifiable, Codable {
2323 case .pdf: return "PDF"
2424 }
2525 }
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 }
2638}
2739
2840enum DomainReportExporter {