diff --git a/CLAUDE.md b/CLAUDE.md index efe8d1084..50cf652f6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ ably-cocoa is the Ably pub/sub SDK for iOS, macOS, and tvOS. It is written in Ob **ably-cocoa is device-side only**: it serves apps running on an end user's device. Per [PDR-091](https://ably.atlassian.net/wiki/spaces/product/pages/5220106242), such a client declares that to Ably, which is what determines how its traffic counts toward an account's monthly active users. The decision records cover all nine Pub/Sub SDKs and describe a device/server pair, but the server half belongs to the server-capable SDKs; do not add a server package, a server factory, or the `ably-pubsub-server` agent identifier here, and do not document this SDK as a choice between two sides. Server-side Swift is tracked separately as `ably-swift`. -The SPM products are **`AblyPubSubCore`** (the core SDK, an internal implementation product for Ably's own packages rather than for direct use by applications) and `AblyLiveObjects`. The core's **module is `Ably` and its class prefix is `ART`**, independently of the product name — do not rename ObjC symbols, headers or the module. +The SPM products are **`AblyPubSubDevice`** (what applications depend on: `PubSubDevice.createClient(options:)`, which declares the device runtime), **`AblyPubSubCore`** (the core SDK, an internal implementation product for Ably's own packages rather than for direct use by applications) and `AblyLiveObjects`. The core's **module is `Ably` and its class prefix is `ART`**, independently of the product name — do not rename ObjC symbols, headers or the module. ## Build and Test diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dd5386a18..a6ab8b4bc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,6 +30,8 @@ Changes made to dependencies in the [Cartfile](Cartfile) need to be reflected in ## Adding new Objective-C files to the SDK +The steps below are for the core SDK — the `Ably` target, whose sources live in `Source/`. The `AblyPubSubDevice` target (`PubSubDevice/`) is laid out differently: its public headers go in `PubSubDevice/include/AblyPubSubDevice/` and its implementations directly in `PubSubDevice/`, there is no umbrella header to add an `#import` to, and it is absent from `Ably.xcodeproj`. SwiftPM globs the directory and generates the module map, so a new file there needs no other change. + ### Public header (`.h`) files These are the header files that form the public interface of the SDK. @@ -127,19 +129,19 @@ If you add another `xcodebuild`-based path that compiles a test target linking ` ### Distribution -`AblyLiveObjects` is available **via Swift Package Manager only**. CocoaPods and Carthage consumers receive the core SDK alone, so a release tag does not deliver the same set of products to every channel: +`AblyPubSubDevice` and `AblyLiveObjects` are available **via Swift Package Manager only**. CocoaPods and Carthage consumers receive the core SDK alone, so a release tag does not deliver the same set of products to every channel: -| Channel | `AblyPubSubCore` | `AblyLiveObjects` | -| --- | --- | --- | -| Swift Package Manager | yes | yes | -| CocoaPods | yes (as the `Ably` pod) | no | -| Carthage | yes | no | +| Channel | `AblyPubSubCore` | `AblyPubSubDevice` | `AblyLiveObjects` | +| --- | --- | --- | --- | +| Swift Package Manager | yes | yes | yes | +| CocoaPods | yes (as the `Ably` pod) | no | no | +| Carthage | yes | no | no | > The `AblyPubSubCore` product's module is named `Ably` and its classes carry the `ART` prefix, so > consumers reach the core as `import Ably` / `#import ` whichever channel they install it > from — which is why the CocoaPods pod and the Carthage framework are both named `Ably`. -This is a deliberate decision rather than an omission. Four separate things would each have to change to lift it: +The two are SPM-only for different reasons. Nothing about `AblyPubSubDevice` resists the other channels: it is a plain Objective-C target over the core, with the same platform floor and no plugin machinery, so shipping it as a pod would mean adding a podspec and Carthage targets rather than removing an obstacle. `AblyLiveObjects` is the constrained one, and deliberately so rather than by omission — four separate things would each have to change to lift it: - [`Ably.podspec`](Ably.podspec)'s `source_files` covers `Source/` only, so neither `LiveObjects/` nor `_AblyPluginSupportPrivate/` ships in the pod; and `Ably.xcodeproj`, which Carthage builds, contains no LiveObjects or plugin-support targets. - `ABLY_SUPPORTS_PLUGINS` is defined only in `Package.swift`. Without it the plugin hook points — `ARTClientOptions.plugins` and the plumbing in `ARTRealtimeChannel.m`, `ARTRealtime.m` and `ARTJsonLikeEncoder.m` — are compiled out. It is a compile-time define on the core target, so enabling it would enable it for every CocoaPods and Carthage consumer, in a configuration that has never been built or tested. @@ -209,4 +211,4 @@ For each release, the following needs to be done: * Checkout `main` locally, pulling in changes using `git checkout main && git pull`. Make sure the new tag you need was created on publish * Release an update for CocoaPods using `pod trunk push Ably.podspec --allow-warnings`. Details on this command, as well as instructions for adding other contributors as maintainers, are at [Getting setup with Trunk](https://guides.cocoapods.org/making/getting-setup-with-trunk.html) in the [CocoaPods Guides](https://guides.cocoapods.org/). This publishes the core SDK only — there is no LiveObjects pod * Test the integration of the library in a Xcode project using Carthage and CocoaPods using the [installation guide](https://github.com/ably/ably-cocoa#installation-guide) -* Test that Swift Package Manager resolves the new tag, selecting both the `AblyPubSubCore` and `AblyLiveObjects` products +* Test that Swift Package Manager resolves the new tag, selecting the `AblyPubSubCore`, `AblyPubSubDevice` and `AblyLiveObjects` products diff --git a/Examples/SPM/Package.swift b/Examples/SPM/Package.swift index aacfaf0af..9b7886687 100644 --- a/Examples/SPM/Package.swift +++ b/Examples/SPM/Package.swift @@ -19,7 +19,8 @@ let package = Package( dependencies: [ // `package:` is the dependency's identity, which for a path // dependency is the directory name, not the manifest's `name`. - .product(name: "AblyPubSubCore", package: "ably-cocoa") + .product(name: "AblyPubSubCore", package: "ably-cocoa"), + .product(name: "AblyPubSubDevice", package: "ably-cocoa") ], swiftSettings: [ .unsafeFlags(["-warnings-as-errors"]) diff --git a/Examples/SPM/Sources/SPMIntegration/main.swift b/Examples/SPM/Sources/SPMIntegration/main.swift index 20332f031..01c3f30cd 100644 --- a/Examples/SPM/Sources/SPMIntegration/main.swift +++ b/Examples/SPM/Sources/SPMIntegration/main.swift @@ -1 +1,9 @@ -import Ably +import AblyPubSubDevice + +// `import AblyPubSubDevice` alone reaches the core's types too. +let options = ARTClientOptions() +options.autoConnect = false +options.key = "xxxx:xxxx" +options.clientId = "me" + +let _ = PubSubDevice.createClient(options: options) diff --git a/Examples/SPM/Tests/SPMTests/SPMTests.swift b/Examples/SPM/Tests/SPMTests/SPMTests.swift index 98c2ac8c2..1dd65a666 100644 --- a/Examples/SPM/Tests/SPMTests/SPMTests.swift +++ b/Examples/SPM/Tests/SPMTests/SPMTests.swift @@ -1,5 +1,6 @@ import XCTest import Ably + import AblyPubSubDevice final class SPMTests: XCTestCase { func ablyInitTest() { @@ -7,4 +8,11 @@ let _ = ARTRest(options: clientOptions) let _ = ARTRealtime(options: clientOptions) } + + func pubSubDeviceInitTest() { + let clientOptions = ARTClientOptions() + let _ = PubSubDevice.createClient(options: clientOptions) + let _ = PubSubDevice.createClient(key: "xxxx:xxxx") + let _ = PubSubDevice.createClient(token: "xxxx") + } } diff --git a/Package.swift b/Package.swift index ed14b3e14..0f351bbe2 100644 --- a/Package.swift +++ b/Package.swift @@ -18,6 +18,12 @@ let package = Package( name: "AblyPubSubCore", targets: ["Ably"] ), + // The entry point for apps: creates clients that declare they are + // running on an end user's device. + .library( + name: "AblyPubSubDevice", + targets: ["AblyPubSubDevice"] + ), .library( name: "AblyLiveObjects", targets: ["AblyLiveObjects"] @@ -84,6 +90,16 @@ let package = Package( name: "_AblyPluginSupportPrivate", path: "_AblyPluginSupportPrivate" ), + // Creates clients that declare they are running on an end user's + // device, by stamping the agent entry Ably classifies on. + .target( + name: "AblyPubSubDevice", + dependencies: [ + .target(name: "Ably"), + ], + path: "PubSubDevice", + publicHeadersPath: "include" + ), // The core SDK. Vended as the AblyPubSubCore product; its module is // named `Ably`. .target( @@ -120,6 +136,7 @@ let package = Package( name: "AblyTests", dependencies: [ .byName(name: "Ably"), + .target(name: "AblyPubSubDevice"), .byName(name: "AblyTesting"), .byName(name: "AblyTestingObjC"), .product(name: "Nimble", package: "nimble"), @@ -167,6 +184,7 @@ let package = Package( name: "AblyTestsObjC", dependencies: [ .byName(name: "Ably"), + .target(name: "AblyPubSubDevice"), .byName(name: "AblyTesting"), .byName(name: "AblyTestingObjC"), ], diff --git a/PubSubDevice/ARTPubSubDevice.m b/PubSubDevice/ARTPubSubDevice.m new file mode 100644 index 000000000..5c3627af2 --- /dev/null +++ b/PubSubDevice/ARTPubSubDevice.m @@ -0,0 +1,41 @@ +#import + +/** + * The agent entry that declares a client is running on an end user's device. + * + * Ably matches this exact string to classify a connection for monthly active user counting, so + * changing it reclassifies every client this package creates. It is sent without a version: it + * states which kind of runtime the client is on, and the SDK's own entry alongside it carries the + * version. + */ +static NSString *const ARTPubSubDeviceAgentName = @"ably-pubsub-device"; + +@implementation ARTPubSubDevice + +/// Returns a copy of `options` carrying the device declaration. +/// +/// The caller's options object and its `agents` dictionary are both left untouched. The +/// declaration is applied last, so it wins if the caller set an entry under the same name. ++ (ARTClientOptions *)optionsDeclaringDevice:(ARTClientOptions *)options { + ARTClientOptions *const newOptions = [options copy]; + + NSMutableDictionary *const agents = options.agents ? [options.agents mutableCopy] : [NSMutableDictionary dictionary]; + agents[ARTPubSubDeviceAgentName] = ARTClientInformationAgentNotVersioned; + newOptions.agents = agents; + + return newOptions; +} + ++ (ARTRealtime *)createClientWithOptions:(ARTClientOptions *)options { + return [[ARTRealtime alloc] initWithOptions:[self optionsDeclaringDevice:options]]; +} + ++ (ARTRealtime *)createClientWithKey:(NSString *)key { + return [self createClientWithOptions:[[ARTClientOptions alloc] initWithKey:key]]; +} + ++ (ARTRealtime *)createClientWithToken:(NSString *)token { + return [self createClientWithOptions:[[ARTClientOptions alloc] initWithToken:token]]; +} + +@end diff --git a/PubSubDevice/include/AblyPubSubDevice/ARTPubSubDevice.h b/PubSubDevice/include/AblyPubSubDevice/ARTPubSubDevice.h new file mode 100644 index 000000000..135dfa606 --- /dev/null +++ b/PubSubDevice/include/AblyPubSubDevice/ARTPubSubDevice.h @@ -0,0 +1,58 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * Creates Pub/Sub clients for apps running on an end user's device. + * + * A client created here tells Ably that it is running on an end user's device. That declaration + * determines how the connection is counted: on an account billed by monthly active users, device + * traffic counts toward the total, the connection must carry a `clientId`, and that `clientId` is + * subject to a concurrency limit. + * + * The returned object is an `ARTRealtime` and behaves exactly as one built with + * `-[ARTRealtime initWithOptions:]`, so all of the Ably Pub/Sub documentation applies to it + * unchanged. + */ +NS_SWIFT_NAME(PubSubDevice) +@interface ARTPubSubDevice : NSObject + +- (instancetype)init NS_UNAVAILABLE; + +/** + * Creates a client with the given options. + * + * The options are not modified; any `agents` entries they carry are preserved alongside the + * device declaration. + * + * @param options The client options. Set `clientId` on them, or use token authentication that + * supplies one. + * + * @return A realtime client that declares it is running on an end user's device. + */ ++ (ARTRealtime *)createClientWithOptions:(ARTClientOptions *)options NS_SWIFT_NAME(createClient(options:)); + +/** + * Creates a client that authenticates with an API key. + * + * Prefer token authentication in code that ships to a device; an API key embedded in an app is + * readable by anyone who has the app. + * + * @param key A full Ably API key. + * + * @return A realtime client that declares it is running on an end user's device. + */ ++ (ARTRealtime *)createClientWithKey:(NSString *)key NS_SWIFT_NAME(createClient(key:)); + +/** + * Creates a client that authenticates with an existing token. + * + * @param token An Ably authentication token. + * + * @return A realtime client that declares it is running on an end user's device. + */ ++ (ARTRealtime *)createClientWithToken:(NSString *)token NS_SWIFT_NAME(createClient(token:)); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Test/AblyTests/Tests/PubSubDeviceTests.swift b/Test/AblyTests/Tests/PubSubDeviceTests.swift new file mode 100644 index 000000000..ebd4dd8bc --- /dev/null +++ b/Test/AblyTests/Tests/PubSubDeviceTests.swift @@ -0,0 +1,177 @@ +import Ably +import Ably.Private +import AblyPubSubDevice +import Nimble +import XCTest + +private let deviceAgentName = "ably-pubsub-device" + +class PubSubDeviceTests: XCTestCase { + + // MARK: - The declaration the client carries + + func test__001__createClient__declares_the_device_agent_without_a_version() throws { + let test = Test() + let options = try AblyTests.commonAppSetup(for: test) + options.autoConnect = false + + let client = PubSubDevice.createClient(options: options) + defer { client.dispose(); client.close() } + + let agents = try XCTUnwrap(client.internal.options.agents) + XCTAssertEqual(agents[deviceAgentName], ARTClientInformationAgentNotVersioned) + + // The identifier is emitted as a bare token; a version on it would say + // nothing, since the SDK entry beside it already carries one. + let identifier = ARTClientInformation.agentIdentifier(withAdditionalAgents: agents) + XCTAssertTrue(identifier.contains(" \(deviceAgentName)") || identifier.hasPrefix("\(deviceAgentName) ")) + XCTAssertFalse(identifier.contains("\(deviceAgentName)/")) + } + + func test__002__createClient__leaves_the_callers_options_untouched() throws { + let test = Test() + let options = try AblyTests.commonAppSetup(for: test) + options.autoConnect = false + options.agents = ["some-wrapper": "1.2.3"] + + let client = PubSubDevice.createClient(options: options) + defer { client.dispose(); client.close() } + + XCTAssertEqual(options.agents, ["some-wrapper": "1.2.3"]) + XCTAssertNil(options.agents?[deviceAgentName]) + } + + func test__003__createClient__preserves_agents_supplied_by_the_caller() throws { + let test = Test() + let options = try AblyTests.commonAppSetup(for: test) + options.autoConnect = false + options.agents = ["some-wrapper": "1.2.3"] + + let client = PubSubDevice.createClient(options: options) + defer { client.dispose(); client.close() } + + let agents = try XCTUnwrap(client.internal.options.agents) + XCTAssertEqual(agents["some-wrapper"], "1.2.3") + XCTAssertEqual(agents[deviceAgentName], ARTClientInformationAgentNotVersioned) + } + + func test__004__createClient__the_declaration_wins_over_a_caller_entry_of_the_same_name() throws { + let test = Test() + let options = try AblyTests.commonAppSetup(for: test) + options.autoConnect = false + options.agents = [deviceAgentName: "9.9.9"] + + let client = PubSubDevice.createClient(options: options) + defer { client.dispose(); client.close() } + + let agents = try XCTUnwrap(client.internal.options.agents) + XCTAssertEqual(agents[deviceAgentName], ARTClientInformationAgentNotVersioned) + } + + func test__005__createClient__carries_over_the_rest_of_the_options() throws { + let test = Test() + let options = try AblyTests.commonAppSetup(for: test) + options.autoConnect = false + options.clientId = "device-client" + options.idempotentRestPublishing = true + + let client = PubSubDevice.createClient(options: options) + defer { client.dispose(); client.close() } + + XCTAssertEqual(client.internal.options.clientId, "device-client") + XCTAssertTrue(client.internal.options.idempotentRestPublishing) + } + + // MARK: - The other doors + + func test__006__createClient__accepts_a_key() throws { + let client = PubSubDevice.createClient(key: "fake:key") + defer { client.dispose(); client.close() } + + XCTAssertEqual(client.internal.options.key, "fake:key") + XCTAssertEqual(client.internal.options.agents?[deviceAgentName], ARTClientInformationAgentNotVersioned) + } + + func test__007__createClient__accepts_a_token() throws { + let client = PubSubDevice.createClient(token: "fake_token") + defer { client.dispose(); client.close() } + + XCTAssertEqual(client.internal.options.token, "fake_token") + XCTAssertEqual(client.internal.options.agents?[deviceAgentName], ARTClientInformationAgentNotVersioned) + } + + // MARK: - What reaches the wire + // + // Billing reads the agent off the wire, so these assert on what is actually + // sent rather than on the options the client holds. + + func test__008__createClient__sends_the_declaration_on_the_realtime_connection() throws { + let test = Test() + let options = try AblyTests.commonAppSetup(for: test) + options.autoConnect = false + options.testOptions.transportFactory = TestProxyTransportFactory() + + let client = PubSubDevice.createClient(options: options) + defer { client.dispose(); client.close() } + client.connect() + + waitUntil(timeout: testTimeout) { done in + client.connection.on { stateChange in + switch stateChange.current { + case .failed: + AblyTests.checkError(stateChange.reason, withAlternative: "Failed state") + done() + case .connected: + guard let transport = client.internal.transport as? TestProxyTransport, + let query = transport.lastUrl?.query else { + XCTFail("MockTransport isn't working") + done() + return + } + expect(query).to(haveParam("agent", hasPrefix: "ably-cocoa/")) + XCTAssertTrue(query.contains(deviceAgentName)) + XCTAssertFalse(query.contains("\(deviceAgentName)%2F")) + done() + default: + break + } + } + } + } + + func test__009__createClient__sends_the_declaration_on_http_requests() throws { + let test = Test() + let options = try AblyTests.commonAppSetup(for: test) + options.autoConnect = false + + let client = PubSubDevice.createClient(options: options) + defer { client.dispose(); client.close() } + + let testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options)) + client.internal.rest.httpExecutor = testHTTPExecutor + + waitUntil(timeout: testTimeout) { done in + client.time { _, error in + XCTAssertNil(error) + let headerAgent = testHTTPExecutor.requests.first?.allHTTPHeaderFields?["Ably-Agent"] + XCTAssertNotNil(headerAgent) + XCTAssertTrue(headerAgent?.contains(deviceAgentName) ?? false) + XCTAssertFalse(headerAgent?.contains("\(deviceAgentName)/") ?? true) + done() + } + } + } + + // MARK: - A client built from the core alone + + func test__010__the_core_constructor__declares_nothing() throws { + let test = Test() + let options = try AblyTests.commonAppSetup(for: test) + options.autoConnect = false + + let client = ARTRealtime(options: options) + defer { client.dispose(); client.close() } + + XCTAssertNil(client.internal.options.agents?[deviceAgentName]) + } +} diff --git a/Test/AblyTestsObjC/ARTPubSubDeviceTests.m b/Test/AblyTestsObjC/ARTPubSubDeviceTests.m new file mode 100644 index 000000000..a4ba3d316 --- /dev/null +++ b/Test/AblyTestsObjC/ARTPubSubDeviceTests.m @@ -0,0 +1,35 @@ +@import XCTest; +@import AblyPubSubDevice; +// For ARTRealtime.internal, to read back the options the client was built with. +@import Ably.Private; + +@interface ARTPubSubDeviceTests : XCTestCase +@end + +@implementation ARTPubSubDeviceTests + +// Importing AblyPubSubDevice alone has to be enough to reach the core's types, +// otherwise every caller needs a second import to use what the door returns. +- (void)test_createClient_returns_a_realtime_client_declaring_the_device_agent { + ARTClientOptions *const options = [[ARTClientOptions alloc] initWithKey:@"xxxx:xxxx"]; + options.autoConnect = NO; + + ARTRealtime *const client = [ARTPubSubDevice createClientWithOptions:options]; + + XCTAssertTrue([client isKindOfClass:[ARTRealtime class]]); + XCTAssertEqual(client.internal.options.agents[@"ably-pubsub-device"], ARTClientInformationAgentNotVersioned); + XCTAssertNil(options.agents); + + [client close]; +} + +- (void)test_createClientWithKey_declares_the_device_agent { + ARTRealtime *const client = [ARTPubSubDevice createClientWithKey:@"xxxx:xxxx"]; + + XCTAssertEqualObjects(client.internal.options.key, @"xxxx:xxxx"); + XCTAssertEqual(client.internal.options.agents[@"ably-pubsub-device"], ARTClientInformationAgentNotVersioned); + + [client close]; +} + +@end