|
| 1 | +# SDK Architecture |
| 2 | + |
| 3 | +## Module Structure |
| 4 | + |
| 5 | +The SDK is a **modular monorepo**: |
| 6 | + |
| 7 | +``` |
| 8 | +DatadogInternal (shared protocols, types — Foundation only, no external deps) |
| 9 | + ├── DatadogCore (initialization, storage, upload) |
| 10 | + ├── DatadogLogs |
| 11 | + ├── DatadogTrace |
| 12 | + ├── DatadogRUM |
| 13 | + ├── DatadogSessionReplay |
| 14 | + ├── DatadogCrashReporting |
| 15 | + ├── DatadogWebViewTracking |
| 16 | + ├── DatadogFlags |
| 17 | + ├── DatadogProfiling |
| 18 | + └── TestUtilities (test-only, shared mocks/matchers) |
| 19 | +``` |
| 20 | + |
| 21 | +### Module Boundaries |
| 22 | + |
| 23 | +- Feature modules MUST NOT import each other |
| 24 | +- Only `DatadogCore` orchestrates feature lifecycles |
| 25 | +- `DatadogInternal` is the ONLY allowed place for shared types — it defines interfaces; `DatadogCore` provides concrete implementations |
| 26 | +- Platform support: iOS 12.0+, tvOS 12.0+, macOS 12.6+, watchOS 7.0+ (limited modules), visionOS |
| 27 | + |
| 28 | +### Call Site Synchronization |
| 29 | + |
| 30 | +**When modifying code in feature modules (Logs, Trace, RUM, etc.), you MUST check if any corresponding call sites in `DatadogCore` and `DatadogInternal` need to be updated.** |
| 31 | + |
| 32 | +Common oversights: |
| 33 | +- Forgetting to update how `DatadogCore` registers the feature |
| 34 | +- Forgetting to update shared types in `DatadogInternal` |
| 35 | +- Forgetting to update manual data encoders (`SpanEventEncoder`, `LogEventEncoder`, ...) — new attributes won't be reported |
| 36 | +- Forgetting to update ObjC bridges |
| 37 | +- Forgetting to update `.pbxproj` files when adding, removing, or moving files |
| 38 | + |
| 39 | +**Always search for usages across the entire codebase before considering a change complete.** |
| 40 | + |
| 41 | +## Data Flow |
| 42 | + |
| 43 | +### RUM Event Emission Pipeline |
| 44 | + |
| 45 | +1. App calls public API (e.g., `RUMMonitor.shared().startView(...)`) |
| 46 | +2. `Monitor` (concrete `RUMMonitorProtocol` implementation) creates a `RUMCommand` with timestamp, attributes, user ID |
| 47 | +3. Command is enqueued to `FeatureScope` (async serial queue in `DatadogCore`) |
| 48 | +4. `FeatureScope` invokes scope hierarchy: `RUMApplicationScope.process()` → `RUMSessionScope.process()` → `RUMViewScope.process()` |
| 49 | +5. Each scope decides whether to accept, transform, or reject the command (returns `Bool` — `true` = scope stays open, `false` = scope is closed and removed from parent) |
| 50 | +6. If valid, scope serializes to RUM event JSON and calls `writer.write(data:)` |
| 51 | +7. `Writer` appends data to in-memory buffer or disk file |
| 52 | +8. `DataUploadWorker` periodically reads batches of events from disk |
| 53 | +9. `RequestBuilder` wraps batch in HTTP POST to Datadog intake |
| 54 | +10. `HTTPClient` sends request; on success files are deleted; on failure backoff/retry applies |
| 55 | + |
| 56 | +### Storage Pipeline |
| 57 | + |
| 58 | +``` |
| 59 | +Feature writes event → AsyncWriter → FileWriter → FilesOrchestrator → disk file |
| 60 | + ↓ |
| 61 | +DataUploadWorker (periodic) → DataReader → RequestBuilder → HTTPClient → Datadog backend |
| 62 | +``` |
| 63 | + |
| 64 | +- File-based storage in Application Support sandbox — no database |
| 65 | +- Directory structure: `[AppSupport]/Datadog/[site]/[feature]/` |
| 66 | +- Format: JSON for events, binary TLV encoding for compact storage |
| 67 | +- Optional encryption via `DataEncryption` protocol |
| 68 | +- Caching explicitly disabled at URLSession level (ephemeral config, `urlCache = nil`) |
| 69 | +- Key-value storage: `FeatureDataStore` for feature-specific persistent data |
| 70 | + |
| 71 | +### Feature Registration Lifecycle |
| 72 | + |
| 73 | +1. App calls `Datadog.initialize(with:trackingConsent:)` — creates `DatadogCore` instance |
| 74 | +2. `DatadogCore` is registered in `CoreRegistry` (singleton lookup) |
| 75 | +3. App calls feature-specific `enable()` (e.g., `RUM.enable(with:in:)`) |
| 76 | +4. Feature creates its plugin (e.g., `RUMFeature`) and registers with core |
| 77 | +5. Core allocates storage directory and upload worker for the feature |
| 78 | +6. Feature can now write events and receive messages via the bus |
| 79 | + |
| 80 | +### State Management (Context) |
| 81 | + |
| 82 | +`DatadogContext` is the central context object containing device info, app state, user info, network state, etc. It is built by `DatadogContextProvider` from multiple `ContextValuePublisher` instances that subscribe to system notifications and update context in real-time. Context is passed to every scope during command processing and attached to events before writing. |
| 83 | + |
| 84 | +## Key Abstractions |
| 85 | + |
| 86 | +| Abstraction | Purpose | Examples | |
| 87 | +|-------------|---------|----------| |
| 88 | +| **Feature** | Represents a module (RUM, Logs, Trace). Conforms to `DatadogFeature` or `DatadogRemoteFeature`. | `RUMFeature`, `LogsFeature` | |
| 89 | +| **Scope** | Hierarchical state container. Implements `process(command:context:writer:)` returning `Bool` (`true` = scope stays open, `false` = scope is closed and removed). | `RUMApplicationScope`, `RUMSessionScope`, `RUMViewScope` | |
| 90 | +| **Command** | User action or system event triggering state changes. Struct with timestamp, attributes. | `RUMStartViewCommand`, `RUMAddUserActionCommand` | |
| 91 | +| **Storage & Upload** | Persist events and batch-transmit to backend. | `FeatureStorage`, `FileWriter`, `DataUploadWorker` | |
| 92 | +| **Context Provider** | Publishes system/app state changes. Implements `ContextValuePublisher`. | `UserInfoPublisher`, `NetworkConnectionInfoPublisher` | |
| 93 | +| **Message Bus** | Inter-feature pub/sub communication. Protocol (`FeatureMessageReceiver`) in `DatadogInternal/Sources/MessageBus/`; concrete `MessageBus` in `DatadogCore`. | `MessageBus`, `FeatureMessageReceiver` | |
| 94 | + |
| 95 | +## Key Protocols |
| 96 | + |
| 97 | +| Protocol | Purpose | Location | |
| 98 | +|----------|---------|----------| |
| 99 | +| `DatadogCoreProtocol` | Central injectable core interface | `DatadogInternal/Sources/DatadogCoreProtocol.swift` | |
| 100 | +| `DatadogFeature` | Base protocol for feature modules | `DatadogInternal/Sources/DatadogFeature.swift` | |
| 101 | +| `DatadogRemoteFeature` | Extension adding `requestBuilder` for features that upload data | `DatadogInternal/Sources/DatadogFeature.swift` | |
| 102 | +| `FeatureScope` | Provides features with event writing, context, and storage | `DatadogInternal/Sources/DatadogCoreProtocol.swift` | |
| 103 | +| `FeatureMessageReceiver` | Receives inter-feature messages via the bus | `DatadogInternal/Sources/MessageBus/` | |
| 104 | +| `ContextValuePublisher` | Publishes context value changes | `DatadogCore/Sources/Core/Context/ContextValuePublisher.swift` | |
| 105 | +| `DataEncryption` | Optional encryption for on-disk data | `DatadogCore/Sources/Core/Storage/DataEncryption.swift` | |
| 106 | + |
| 107 | +## Error Handling Strategy |
| 108 | + |
| 109 | +The SDK must **never throw exceptions** to customer code: |
| 110 | + |
| 111 | +- **NOP implementations**: `NOPMonitor`, `NOPDatadogCore` silently accept all API calls when SDK is not initialized or a feature is disabled. |
| 112 | +- **Validation at boundaries**: Invalid input is logged via `DD.logger` and ignored. |
| 113 | +- **Upload backoff**: Upload failures trigger exponential backoff and retry. Network errors are logged but never crash. |
| 114 | +- **User callback safety**: Exceptions in user-provided callbacks (e.g., event mappers) are caught and logged — original event is sent. |
| 115 | +- **Event mappers**: View events cannot be dropped (mapper must return a value). All other event types can be dropped by returning `nil`. |
| 116 | + |
| 117 | +## Thread Safety Rules |
| 118 | + |
| 119 | +- **`@ReadWriteLock`**: Property wrapper for concurrent read, exclusive write access. Use for shared mutable state. |
| 120 | +- **Serial queues**: Scope processing uses serial dispatch queues (`FeatureScope` is serial). |
| 121 | +- **No `DispatchQueue.main.sync`**: Forbidden — prevents deadlocks. |
| 122 | +- **NSLock exception**: `NSLock` is used in method swizzling code (`DatadogInternal/Sources/Swizzling/`, `DatadogInternal/Sources/NetworkInstrumentation/`) where low-level synchronization is required — do not refactor those. |
| 123 | +- **No thread spawning**: SDK uses system background queues (`qos: .utility`), never creates threads. |
| 124 | + |
| 125 | +## HTTP Upload Details |
| 126 | + |
| 127 | +- **Auth**: Client token passed as `DD-API-KEY` header |
| 128 | +- **Custom headers**: `DD-EVP-ORIGIN`, `DD-EVP-ORIGIN-VERSION`, `DD-REQUEST-ID` |
| 129 | +- **Formats**: JSON, NDJSON (batches), multipart/form-data (Session Replay, crashes) |
| 130 | +- **Compression**: Gzip (`Content-Encoding: gzip`) |
| 131 | +- **Endpoints by site**: `.us1` → `browser-intake-datadoghq.com`, `.eu1` → `browser-intake-datadoghq.eu`, etc. |
| 132 | +- **Header builder**: `DatadogInternal/Sources/Upload/URLRequestBuilder.swift` |
| 133 | +- **Site definitions**: `DatadogInternal/Sources/Context/DatadogSite.swift` |
| 134 | + |
| 135 | +## Dependencies |
| 136 | + |
| 137 | +- **KSCrash 2.5.0**: Crash detection and reporting (`DatadogCrashReporting`) |
| 138 | +- **opentelemetry-swift-core 2.3.0+**: OpenTelemetry API for distributed tracing (`DatadogTrace`). |
| 139 | + |
| 140 | +Avoid adding new dependencies unless absolutely necessary (small footprint principle). |
| 141 | + |
| 142 | +## Extension Libraries |
| 143 | + |
| 144 | +- **Datadog Integration for Apollo iOS**: https://github.com/DataDog/dd-sdk-ios-apollo-interceptor — extracts GraphQL Operation information from requests to let DatadogRUM enrich GraphQL RUM Resources |
0 commit comments