@@ -146,8 +146,16 @@ @interface OSMessagingController ()
146146
147147@property (nonatomic ) BOOL calledLoadTags;
148148
149- // / set when we attempt getInAppMessagesFromServer and no onesignal ID is available yet
150- @property (strong , nonatomic , nullable ) NSString *shouldFetchOnUserChangeWithSubscriptionID;
149+ /* *
150+ Set when a fetch could not go out: no onesignal ID yet, or Identity Verification has not answered what
151+ the call should be addressed and signed with. Read through `takeDeferredFetchSubscriptionId`, since a
152+ user change, a hydration and a new token can all arrive at once and only one of them should refetch.
153+ */
154+ @property (strong , nonatomic , nullable ) NSString *deferredFetchSubscriptionId;
155+
156+ // / Bumped on every login and logout. A fetch carries the value it started with, so a response that
157+ // / arrives after the user changed is discarded instead of showing one user's messages to another.
158+ @property (nonatomic ) NSUInteger userGeneration;
151159
152160// / Tracks whether the first IAM fetch has completed since this cold start
153161@property (nonatomic ) BOOL hasCompletedFirstFetch;
@@ -242,6 +250,11 @@ - (instancetype)init {
242250 _isInAppMessagingPaused = false ;
243251
244252 [[NSNotificationCenter defaultCenter ] addObserver: self selector: @selector (handleIAMPreview: ) name: ONESIGNAL_POST_PREVIEW_IAM object: nil ];
253+ // A deferred fetch waits on how to address it and what to sign it with; hydration answers the
254+ // first, a supplied token the second.
255+ [[NSNotificationCenter defaultCenter ] addObserver: self selector: @selector (retryDeferredFetch ) name: OS_ON_JWT_CONFIG_HYDRATED object: nil ];
256+ [[NSNotificationCenter defaultCenter ] addObserver: self selector: @selector (retryDeferredFetch ) name: OS_ON_USER_JWT_UPDATED object: nil ];
257+ [[NSNotificationCenter defaultCenter ] addObserver: self selector: @selector (onUserWillChange ) name: OS_ON_USER_WILL_CHANGE object: nil ];
245258 }
246259
247260 return self;
@@ -255,7 +268,15 @@ - (void)initializeTriggerController {
255268 dateFromString: timeSinceLastMessage]];
256269}
257270
271+ /* *
272+ Fetches in-app messages for `subscriptionId`, addressed as whoever is the current user.
273+
274+ Nothing checks that the server has those two paired — the subscription comes from the caller and can
275+ predate a login, while the alias is read here — so a well-formed fetch can still be refused. Pairing
276+ them would mean tracking subscription ownership, which the SDK does not do.
277+ */
258278- (void )getInAppMessagesFromServer : (NSString *)subscriptionId {
279+ NSUInteger generation = [self currentUserGeneration ];
259280 dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT , 0 ), ^{
260281 [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" getInAppMessagesFromServer" ];
261282
@@ -269,7 +290,16 @@ - (void)getInAppMessagesFromServer:(NSString *)subscriptionId {
269290 // NOTE: Check for subscription ID above first, before checking for OneSignal ID next
270291 if (!onesignalId) {
271292 [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" Failed to get in app messages due to no OneSignal ID, will reattempt" ];
272- self.shouldFetchOnUserChangeWithSubscriptionID = subscriptionId;
293+ [self deferFetchWithSubscriptionId: subscriptionId];
294+ return ;
295+ }
296+
297+ // Resolved before the read-your-write wait, which can hold this thread for as long as it takes
298+ // the user requests to come back.
299+ OSUserRequestAuthorization *authorization = [OneSignalUserManagerImpl.sharedInstance authorizationForCurrentUser ];
300+ if (!authorization) {
301+ [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" Failed to get in app messages due to Identity Verification, will reattempt" ];
302+ [self deferFetchWithSubscriptionId: subscriptionId];
273303 return ;
274304 }
275305
@@ -288,24 +318,101 @@ - (void)getInAppMessagesFromServer:(NSString *)subscriptionId {
288318
289319 // Initial request
290320 [self attemptFetchWithRetries: subscriptionId
321+ authorization: authorization
291322 rywData: rywData
292323 attempts: @0 // Starting with 0 attempts
293- retryLimit: nil ]; // Retry limit to be set dynamically on first failure
324+ retryLimit: nil // Retry limit to be set dynamically on first failure
325+ userGeneration: generation];
294326 });
295327 });
296328}
297329
330+ - (NSUInteger )currentUserGeneration {
331+ @synchronized (self) {
332+ return self.userGeneration ;
333+ }
334+ }
335+
336+ // / Whether a fetch that started in `generation` is still for the user it was addressed and signed for.
337+ - (BOOL )isCurrentUserGeneration : (NSUInteger )generation {
338+ @synchronized (self) {
339+ return self.userGeneration == generation;
340+ }
341+ }
342+
343+ /* *
344+ Drops the outgoing user's in-app messages and invalidates any fetch still in flight for them, then
345+ queues one for whoever is signing in. The new user's fetch goes out from `onUserStateDidChange`, once
346+ there is a `onesignal_id` to address it by.
347+ */
348+ - (void )onUserWillChange {
349+ @synchronized (self) {
350+ self.userGeneration += 1 ;
351+ }
352+ [self deferFetchWithSubscriptionId: OneSignalUserManagerImpl.sharedInstance.pushSubscriptionId];
353+ // On main, where every other write to `messages` happens.
354+ dispatch_async (dispatch_get_main_queue (), ^{
355+ self.messages = @[];
356+ });
357+ }
358+
359+ - (void )deferFetchWithSubscriptionId : (NSString *)subscriptionId {
360+ @synchronized (self) {
361+ self.deferredFetchSubscriptionId = subscriptionId;
362+ }
363+ }
364+
365+ // / The deferred subscription ID, if there is one, taken so that two signals arriving together refetch once.
366+ - (NSString * _Nullable)takeDeferredFetchSubscriptionId {
367+ @synchronized (self) {
368+ NSString *subscriptionId = self.deferredFetchSubscriptionId ;
369+ self.deferredFetchSubscriptionId = nil ;
370+ return subscriptionId;
371+ }
372+ }
373+
374+ - (void )retryDeferredFetch {
375+ NSString *subscriptionId = [self takeDeferredFetchSubscriptionId ];
376+ if (subscriptionId) {
377+ [self getInAppMessagesFromServer: subscriptionId];
378+ }
379+ }
380+
381+ /* *
382+ Parks the fetch for a later token to reattempt, without reporting the one it was signed with.
383+
384+ A rejection here is ambiguous: the path names a user and a subscription the server may simply not have
385+ paired, and a replacement token would not change that. Invalidating is left to the user requests, which
386+ address a user alone; the token the app supplies after one of those releases what is parked here.
387+ */
388+ - (void )handleUnauthorizedFetch : (OSUserRequestAuthorization *)authorization subscriptionId : (NSString *)subscriptionId {
389+ // An unsigned fetch has no token to replace, so there would be nothing different to reattempt with.
390+ if (!authorization.token ) {
391+ return ;
392+ }
393+ [self deferFetchWithSubscriptionId: subscriptionId];
394+ }
395+
298396
299397- (void )attemptFetchWithRetries : (NSString *)subscriptionId
398+ authorization : (OSUserRequestAuthorization *)authorization
300399 rywData : (OSReadYourWriteData *)rywData
301400 attempts : (NSNumber *)attempts
302- retryLimit : (NSNumber *)retryLimit {
401+ retryLimit : (NSNumber *)retryLimit
402+ userGeneration : (NSUInteger )generation {
403+ if (![self isCurrentUserGeneration: generation]) {
404+ [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" Abandoning an in app message fetch for a previous user" ];
405+ return ;
406+ }
407+
303408 NSNumber *sessionDuration = @([OSSessionManager.sharedSessionManager getTimeFocusedElapsed ]);
304409 NSString *rywToken = rywData.rywToken ;
305410 NSNumber *rywDelay = rywData.rywDelay ;
306411
307412 // Create the request with the current attempt count
308413 OSRequestGetInAppMessages *request = [OSRequestGetInAppMessages withSubscriptionId: subscriptionId
414+ withAlias: authorization.alias
415+ withUserHeaders: authorization.headers
309416 withSessionDuration: sessionDuration
310417 withRetryCount: attempts
311418 withRywToken: rywToken];
@@ -316,6 +423,10 @@ - (void)attemptFetchWithRetries:(NSString *)subscriptionId
316423 onSuccess: ^(NSDictionary *result) {
317424 dispatch_async (dispatch_get_main_queue (), ^{
318425 [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" getInAppMessagesFromServer success" ];
426+ if (![self isCurrentUserGeneration: generation]) {
427+ [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" Discarding in app messages fetched for a previous user" ];
428+ return ;
429+ }
319430 if (result[@" in_app_messages" ]) {
320431 NSMutableArray *messages = [NSMutableArray new ];
321432
@@ -335,7 +446,12 @@ - (void)attemptFetchWithRetries:(NSString *)subscriptionId
335446 NSDictionary * responseHeaders = error.responseHeaders ;
336447
337448 [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: [NSString stringWithFormat: @" getInAppMessagesFromServer failure: %@ " , error.description]];
338-
449+
450+ // A retry, and the token this was signed with, both belong to the user it started for.
451+ if (![self isCurrentUserGeneration: generation]) {
452+ return ;
453+ }
454+
339455 if (error.code == 425 || error.code == 429 ) { // 425 Too Early or 429 Too Many Requests
340456 NSInteger retryAfter = [responseHeaders[@" Retry-After" ] integerValue ] ?: DEFAULT_RETRY_AFTER_SECONDS ;
341457
@@ -348,13 +464,17 @@ - (void)attemptFetchWithRetries:(NSString *)subscriptionId
348464 NSInteger nextAttempt = [attempts integerValue ] + 1 ; // Increment attempts
349465 [self retryAfterDelay: retryAfter
350466 subscriptionId: subscriptionId
467+ authorization: authorization
351468 rywData: rywData
352469 attempts: @(nextAttempt)
353- retryLimit: blockRetryLimit];
470+ retryLimit: blockRetryLimit
471+ userGeneration: generation];
354472 } else {
355473 // Final attempt without rywToken
356- [self fetchInAppMessagesWithoutToken: subscriptionId];
474+ [self fetchInAppMessagesWithoutToken: subscriptionId authorization: authorization userGeneration: generation ];
357475 }
476+ } else if ([OSNetworkingUtils getResponseStatusType: error.code] == OSResponseStatusUnauthorized) {
477+ [self handleUnauthorizedFetch: authorization subscriptionId: subscriptionId];
358478 } else if (error.code >= 500 && error.code <= 599 ) {
359479 [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" Server error, skipping retries" ];
360480 }
@@ -363,23 +483,31 @@ - (void)attemptFetchWithRetries:(NSString *)subscriptionId
363483
364484- (void )retryAfterDelay : (NSInteger )retryAfter
365485 subscriptionId : (NSString *)subscriptionId
486+ authorization : (OSUserRequestAuthorization *)authorization
366487 rywData : (OSReadYourWriteData *)rywData
367488 attempts : (NSNumber *)attempts
368- retryLimit : (NSNumber *)retryLimit {
489+ retryLimit : (NSNumber *)retryLimit
490+ userGeneration : (NSUInteger )generation {
369491
370492 dispatch_after (dispatch_time (DISPATCH_TIME_NOW , (int64_t )(retryAfter * NSEC_PER_SEC )), dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT , 0 ), ^{
371493
372494 [self attemptFetchWithRetries: subscriptionId
495+ authorization: authorization
373496 rywData: rywData
374497 attempts: attempts
375- retryLimit: retryLimit];
498+ retryLimit: retryLimit
499+ userGeneration: generation];
376500 });
377501}
378502
379- - (void )fetchInAppMessagesWithoutToken : (NSString *)subscriptionId {
503+ - (void )fetchInAppMessagesWithoutToken : (NSString *)subscriptionId
504+ authorization : (OSUserRequestAuthorization *)authorization
505+ userGeneration : (NSUInteger )generation {
380506 NSNumber *sessionDuration = @([OSSessionManager.sharedSessionManager getTimeFocusedElapsed ]);
381507
382508 OSRequestGetInAppMessages *request = [OSRequestGetInAppMessages withSubscriptionId: subscriptionId
509+ withAlias: authorization.alias
510+ withUserHeaders: authorization.headers
383511 withSessionDuration: sessionDuration
384512 withRetryCount: nil
385513 withRywToken: nil ]; // No retries for the final attempt
@@ -388,6 +516,10 @@ - (void)fetchInAppMessagesWithoutToken:(NSString *)subscriptionId {
388516 onSuccess: ^(NSDictionary *result) {
389517 dispatch_async (dispatch_get_main_queue (), ^{
390518 [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" Final attempt without token success" ];
519+ if (![self isCurrentUserGeneration: generation]) {
520+ [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" Discarding in app messages fetched for a previous user" ];
521+ return ;
522+ }
391523 if (result[@" in_app_messages" ]) {
392524 NSMutableArray *messages = [NSMutableArray new ];
393525
@@ -404,6 +536,12 @@ - (void)fetchInAppMessagesWithoutToken:(NSString *)subscriptionId {
404536 });
405537 } onFailure: ^(OneSignalClientError *error) {
406538 [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: [NSString stringWithFormat: @" getInAppMessagesFromServer failure: %@ " , error.description]];
539+ if (![self isCurrentUserGeneration: generation]) {
540+ return ;
541+ }
542+ if ([OSNetworkingUtils getResponseStatusType: error.code] == OSResponseStatusUnauthorized) {
543+ [self handleUnauthorizedFetch: authorization subscriptionId: subscriptionId];
544+ }
407545 }];
408546}
409547
@@ -1237,11 +1375,9 @@ - (void)onPushSubscriptionDidChangeWithState:(OSPushSubscriptionChangedState * _
12371375}
12381376
12391377- (void )onUserStateDidChangeWithState : (OSUserChangedState * _Nonnull)state {
1240- if (state.current .onesignalId != nil && self. shouldFetchOnUserChangeWithSubscriptionID ) {
1378+ if (state.current .onesignalId != nil ) {
12411379 [OneSignalLog onesignalLog: ONE_S_LL_VERBOSE message: @" OSMessagingController onUserStateDidChangeWithState: changed to new valid onesignal id" ];
1242- NSString *subscriptionID = self.shouldFetchOnUserChangeWithSubscriptionID ;
1243- self.shouldFetchOnUserChangeWithSubscriptionID = nil ;
1244- [self getInAppMessagesFromServer: subscriptionID];
1380+ [self retryDeferredFetch ];
12451381 }
12461382}
12471383
0 commit comments