Skip to content

Commit 7df6890

Browse files
committed
fix: [SDK-5181] accept a create-subscription success with no subscription object (#1748)
(cherry picked from commit 90ada2a)
1 parent 809d6ad commit 7df6890

3 files changed

Lines changed: 212 additions & 11 deletions

File tree

‎iOS_SDK/OneSignalSDK/OneSignal.xcodeproj/project.pbxproj‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@
199199
3CA8B8822BEC2FCB0010ADA1 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3C7A39D42B7C18EE0082665E /* XCTest.framework */; };
200200
3CA8B8832BEC2FCB0010ADA1 /* XCTest.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 3C7A39D42B7C18EE0082665E /* XCTest.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
201201
3CA93BC4300AEFFA000724B3 /* SubscriptionUpdateRaceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CA93BC3300AEFFA000724B3 /* SubscriptionUpdateRaceTests.swift */; };
202+
3C5181A1B2C3D4E5F6A7B802 /* SubscriptionCreateResponseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C5181A1B2C3D4E5F6A7B801 /* SubscriptionCreateResponseTests.swift */; };
202203
3CA93BC7300B0100000724B3 /* SubscriptionModelConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CA93BC6300B0100000724B3 /* SubscriptionModelConcurrencyTests.swift */; };
203204
3CAA4BB72F0BAFBA00A16682 /* TriggerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CAA4BB62F0BAFBA00A16682 /* TriggerTests.swift */; };
204205
3CB331682F281679000E1801 /* CustomEventsIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CB331672F281679000E1801 /* CustomEventsIntegrationTests.swift */; };
@@ -1480,6 +1481,7 @@
14801481
3C9AD6D22B228BB000BC1540 /* OSRequestUpdateProperties.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSRequestUpdateProperties.swift; sourceTree = "<group>"; };
14811482
3CA6CE0928E4F19B00CA0585 /* OSUserRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSUserRequest.swift; sourceTree = "<group>"; };
14821483
3CA93BC3300AEFFA000724B3 /* SubscriptionUpdateRaceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubscriptionUpdateRaceTests.swift; sourceTree = "<group>"; };
1484+
3C5181A1B2C3D4E5F6A7B801 /* SubscriptionCreateResponseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubscriptionCreateResponseTests.swift; sourceTree = "<group>"; };
14831485
3CA93BC6300B0100000724B3 /* SubscriptionModelConcurrencyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubscriptionModelConcurrencyTests.swift; sourceTree = "<group>"; };
14841486
3CAA4BB62F0BAFBA00A16682 /* TriggerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TriggerTests.swift; sourceTree = "<group>"; };
14851487
3CB331672F281679000E1801 /* CustomEventsIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomEventsIntegrationTests.swift; sourceTree = "<group>"; };
@@ -2550,6 +2552,7 @@
25502552
children = (
25512553
3CF11E3C2C6D6155002856F5 /* UserExecutorTests.swift */,
25522554
3CA93BC3300AEFFA000724B3 /* SubscriptionUpdateRaceTests.swift */,
2555+
3C5181A1B2C3D4E5F6A7B801 /* SubscriptionCreateResponseTests.swift */,
25532556
3CB331692F281692000E1801 /* OSCustomEventsExecutorTests.swift */,
25542557
FE740F9E6B87D215510B5982 /* ExecutorAnonymousPurgeTests.swift */,
25552558
);
@@ -4711,6 +4714,7 @@
47114714
3CC890352C5BF9A7002CB4CC /* UserConcurrencyTests.swift in Sources */,
47124715
3CB3316A2F281692000E1801 /* OSCustomEventsExecutorTests.swift in Sources */,
47134716
3CA93BC4300AEFFA000724B3 /* SubscriptionUpdateRaceTests.swift in Sources */,
4717+
3C5181A1B2C3D4E5F6A7B802 /* SubscriptionCreateResponseTests.swift in Sources */,
47144718
3CDE664C2BFC2A56006DA114 /* OneSignalUserObjcTests.m in Sources */,
47154719
D465D9B81F58B242ADF14874 /* OSIdentityModelRepoTests.swift in Sources */,
47164720
B5FBED8247288744EB484CB5 /* OSIdentityModelTests.swift in Sources */,

‎iOS_SDK/OneSignalSDK/OneSignalUser/Source/Executors/OSSubscriptionOperationExecutor.swift‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -357,18 +357,11 @@ extension OSSubscriptionOperationExecutor {
357357
self.addRequestQueue.removeAll(where: { $0 == request})
358358
OneSignalUserDefaults.initShared().saveCodeableData(forKey: OS_SUBSCRIPTION_EXECUTOR_ADD_REQUEST_QUEUE_KEY, withValue: self.addRequestQueue)
359359

360-
guard let response = response?["subscription"] as? [String: Any] else {
361-
OneSignalLog.onesignalLog(.LL_ERROR, message: "Unabled to parse response to create subscription request")
362-
if inBackground {
363-
OSBackgroundTaskManager.endBackgroundTask(backgroundTaskIdentifier)
364-
}
365-
return
366-
}
367-
368360
if let onesignalId = request.identityModel.onesignalId {
369-
if let rywToken = response["ryw_token"] as? String
361+
// ryw_token and ryw_delay are top-level fields, siblings of "subscription".
362+
if let rywToken = response?["ryw_token"] as? String
370363
{
371-
let rywDelay = response["ryw_delay"] as? NSNumber
364+
let rywDelay = response?["ryw_delay"] as? NSNumber
372365
OSConsistencyManager.shared.setRywTokenAndDelay(
373366
id: onesignalId,
374367
key: OSIamFetchOffsetKey.subscriptionUpdate,
@@ -380,7 +373,13 @@ extension OSSubscriptionOperationExecutor {
380373
}
381374
}
382375

383-
request.subscriptionModel.hydrate(response)
376+
// A 2xx with no subscription object is the server's no-op for a subscription that already exists on this user.
377+
if let subscription = response?["subscription"] as? [String: Any] {
378+
request.subscriptionModel.hydrate(subscription)
379+
} else {
380+
let type = request.subscriptionModel.type.rawValue
381+
OneSignalLog.onesignalLog(.LL_INFO, message: "Create \(type) subscription response has no subscription object to hydrate")
382+
}
384383
if inBackground {
385384
OSBackgroundTaskManager.endBackgroundTask(backgroundTaskIdentifier)
386385
}
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
/*
2+
Modified MIT License
3+
4+
Copyright 2026 OneSignal
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
1. The above copyright notice and this permission notice shall be included in
14+
all copies or substantial portions of the Software.
15+
16+
2. All copies of substantial portions of the Software may only be used in connection
17+
with services provided by OneSignal.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
*/
27+
28+
import XCTest
29+
import OneSignalCore
30+
import OneSignalCoreMocks
31+
import OneSignalUserMocks
32+
@testable import OneSignalOSCore
33+
@testable import OneSignalUser
34+
35+
/**
36+
How the subscription executor handles a CreateSubscription success response.
37+
*/
38+
final class SubscriptionCreateResponseTests: XCTestCase {
39+
40+
private let email = "test@example.com"
41+
private let onesignalId = "test-onesignal-id"
42+
43+
override func setUpWithError() throws {
44+
OneSignalCoreMocks.clearUserDefaults()
45+
OneSignalUserMocks.reset()
46+
OSConsistencyManager.shared.reset()
47+
OneSignalIdentifiers.currentAppId = "test-app-id"
48+
OneSignalLog.setLogLevel(.LL_VERBOSE)
49+
}
50+
51+
override func tearDownWithError() throws { }
52+
53+
/**
54+
The server answers a create for a subscription that already exists on the user with a 2xx and no
55+
subscription object. The request is finished, not retried, the model is left as it was, and a
56+
fetch waiting on this user's read-your-write token is released because none is coming.
57+
*/
58+
func testResponseWithoutSubscription_completesWithoutHydratingAndReleasesWaiters() throws {
59+
let client = MockOneSignalClient()
60+
OneSignalCoreImpl.setSharedClient(client)
61+
client.setMockResponseForRequest(request: createRequestKey, response: [:])
62+
63+
let executor = OSSubscriptionOperationExecutor(newRecordsState: OSNewRecordsState(), auth: OneSignalUserManagerImpl.sharedInstance.requestAuth)
64+
let user = OneSignalUserMocks.setUserManagerInternalUser(onesignalId: onesignalId)
65+
let model = makeEmailSubscriptionModel()
66+
67+
// Only a resolve can release this waiter, so it stays blocked if the response is dropped instead of handled.
68+
let released = expectation(description: "IAM fetch waiter was not released")
69+
DispatchQueue.global().async {
70+
_ = OSConsistencyManager.shared.getRywTokenFromAwaitableCondition(UnmetIamFetchCondition(), forId: self.onesignalId)
71+
released.fulfill()
72+
}
73+
OneSignalCoreMocks.waitUntil("Waiter was not registered") { self.waiterCount(forId: self.onesignalId) == 1 }
74+
75+
executor.enqueueDelta(addDelta(for: model, identityModel: user.identityModel))
76+
executor.processDeltaQueue(inBackground: false)
77+
OneSignalCoreMocks.waitUntil("Create subscription request did not complete") {
78+
client.hasCompletedRequestOfType(OSRequestCreateSubscription.self)
79+
}
80+
waitForAddRequestQueueToDrain()
81+
82+
XCTAssertTrue(client.allRequestsHandled)
83+
XCTAssertTrue(client.hasExecutedRequestOfType(OSRequestCreateSubscription.self, expectedCount: 1))
84+
XCTAssertNil(model.subscriptionId)
85+
wait(for: [released], timeout: 3.0)
86+
}
87+
88+
/**
89+
`ryw_token` and `ryw_delay` are siblings of the subscription object, not fields of it.
90+
*/
91+
func testResponseWithSubscription_hydratesModelAndRecordsTopLevelRywToken() throws {
92+
let client = MockOneSignalClient()
93+
OneSignalCoreImpl.setSharedClient(client)
94+
client.setMockResponseForRequest(
95+
request: createRequestKey,
96+
response: [
97+
"subscription": ["id": "email-subscription-id", "type": "Email", "token": email],
98+
"ryw_token": "ryw-token-1",
99+
"ryw_delay": 250
100+
]
101+
)
102+
103+
let executor = OSSubscriptionOperationExecutor(newRecordsState: OSNewRecordsState(), auth: OneSignalUserManagerImpl.sharedInstance.requestAuth)
104+
let user = OneSignalUserMocks.setUserManagerInternalUser(onesignalId: onesignalId)
105+
let model = makeEmailSubscriptionModel()
106+
107+
executor.enqueueDelta(addDelta(for: model, identityModel: user.identityModel))
108+
executor.processDeltaQueue(inBackground: false)
109+
// Hydration is the last step of the success handler, after the token is recorded.
110+
OneSignalCoreMocks.waitUntil("Subscription model was not hydrated") {
111+
model.subscriptionId == "email-subscription-id"
112+
}
113+
114+
XCTAssertTrue(client.allRequestsHandled)
115+
let recorded = OSConsistencyManager.shared.getRywTokenFromAwaitableCondition(
116+
SubscriptionUpdateTokenCondition(id: onesignalId),
117+
forId: onesignalId
118+
)
119+
XCTAssertEqual(recorded?.rywToken, "ryw-token-1")
120+
XCTAssertEqual(recorded?.rywDelay?.intValue, 250)
121+
}
122+
123+
// MARK: - Helpers
124+
125+
private var createRequestKey: String {
126+
"<OSRequestCreateSubscription with token: \(email)>"
127+
}
128+
129+
private func makeEmailSubscriptionModel() -> OSSubscriptionModel {
130+
OSSubscriptionModel(
131+
type: .email,
132+
address: email,
133+
subscriptionId: nil,
134+
reachable: true,
135+
isDisabled: false,
136+
changeNotifier: OSEventProducer()
137+
)
138+
}
139+
140+
private func addDelta(for model: OSSubscriptionModel, identityModel: OSIdentityModel) -> OSDelta {
141+
OSDelta(
142+
name: OS_ADD_SUBSCRIPTION_DELTA,
143+
identityModelId: identityModel.modelId,
144+
externalId: identityModel.externalId,
145+
model: model,
146+
property: model.type.rawValue,
147+
value: model.address ?? ""
148+
)
149+
}
150+
151+
private func waiterCount(forId id: String) -> Int {
152+
OSConsistencyManager.shared.queue.sync {
153+
OSConsistencyManager.shared.indexedConditions[id]?.count ?? 0
154+
}
155+
}
156+
157+
private func waitForAddRequestQueueToDrain() {
158+
OneSignalCoreMocks.waitUntil("Create subscription request was not removed from the cache") {
159+
let requests = OneSignalUserDefaults.initShared().getSavedCodeableData(
160+
forKey: OS_SUBSCRIPTION_EXECUTOR_ADD_REQUEST_QUEUE_KEY,
161+
defaultValue: []
162+
) as? [OSRequestCreateSubscription]
163+
return requests?.isEmpty == true
164+
}
165+
}
166+
}
167+
168+
/// Reads back the subscription-update token recorded for an id without waiting on anything.
169+
private final class SubscriptionUpdateTokenCondition: NSObject, OSCondition {
170+
private let id: String
171+
172+
init(id: String) {
173+
self.id = id
174+
}
175+
176+
var conditionId: String { "SubscriptionUpdateTokenCondition" }
177+
178+
func isMet(indexedTokens: [String: [NSNumber: OSReadYourWriteData]]) -> Bool {
179+
true
180+
}
181+
182+
func getNewestToken(indexedTokens: [String: [NSNumber: OSReadYourWriteData]]) -> OSReadYourWriteData? {
183+
indexedTokens[id]?[NSNumber(value: OSIamFetchOffsetKey.subscriptionUpdate.rawValue)]
184+
}
185+
}
186+
187+
/// Never met on its own and carries the IAM fetch condition id, so only the executor's resolve releases it.
188+
private final class UnmetIamFetchCondition: NSObject, OSCondition {
189+
var conditionId: String { OSIamFetchReadyCondition.CONDITIONID }
190+
191+
func isMet(indexedTokens: [String: [NSNumber: OSReadYourWriteData]]) -> Bool {
192+
false
193+
}
194+
195+
func getNewestToken(indexedTokens: [String: [NSNumber: OSReadYourWriteData]]) -> OSReadYourWriteData? {
196+
nil
197+
}
198+
}

0 commit comments

Comments
 (0)