From dabc25669275c4f08a55eb6699f95a927d009288 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 13 Jun 2022 18:59:51 -0700 Subject: [PATCH 001/127] refactor: RollbarLogger with RollbarInfrastructure --- .../DTOs/RollbarDeveloperOptions.m | 5 ++- .../RollbarNotifier/RollbarInfrastructure.m | 12 +++++ .../RollbarNotifier/RollbarNotifierFiles.h | 16 +++++++ .../RollbarNotifier/RollbarNotifierFiles.m | 12 +++++ .../RollbarNotifier/RollbarPayloadPostReply.h | 16 +++++++ .../RollbarNotifier/RollbarPayloadPostReply.m | 12 +++++ .../Sources/RollbarNotifier/RollbarSender.h | 16 +++++++ .../Sources/RollbarNotifier/RollbarSender.m | 12 +++++ .../include/RollbarInfrastructure.h | 45 +++++++++++++++++++ 9 files changed, 144 insertions(+), 2 deletions(-) create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m create mode 100644 RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m index 968b8fac..1181c94f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m @@ -1,4 +1,5 @@ #import "RollbarDeveloperOptions.h" +#import "../RollbarNotifierFiles.h" #pragma mark - constants @@ -6,7 +7,6 @@ static BOOL const DEFAULT_TRANSMIT_FLAG = YES; static BOOL const DEFAULT_SUPPRESS_SDK_INFO_LOGGING_FLAG = NO; static BOOL const DEFAULT_LOG_PAYLOADS_FLAG = NO; -static NSString * const DEFAULT_PAYLOAD_LOG_FILE = @"rollbar.payloads"; #pragma mark - data field keys @@ -44,7 +44,8 @@ - (instancetype)initWithEnabled:(BOOL)enabled return [self initWithEnabled:enabled transmit:transmit logPayload:logPayload - payloadLogFile:DEFAULT_PAYLOAD_LOG_FILE]; + payloadLogFile:[RollbarNotifierFiles payoadsLog] + ]; } - (instancetype)initWithEnabled:(BOOL)enabled { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m new file mode 100644 index 00000000..c4c85087 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -0,0 +1,12 @@ +// +// RollbarInfrastructure.m +// +// +// Created by Andrey Kornich on 2022-06-09. +// + +#import "RollbarInfrastructure.h" + +@implementation RollbarInfrastructure + +@end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h new file mode 100644 index 00000000..cd46cb16 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h @@ -0,0 +1,16 @@ +// +// RollbarNotifierFiles.h +// +// +// Created by Andrey Kornich on 2022-06-06. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarNotifierFiles : NSObject + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m new file mode 100644 index 00000000..ed69f362 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m @@ -0,0 +1,12 @@ +// +// RollbarNotifierFiles.m +// +// +// Created by Andrey Kornich on 2022-06-06. +// + +#import "RollbarNotifierFiles.h" + +@implementation RollbarNotifierFiles + +@end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h new file mode 100644 index 00000000..23457901 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h @@ -0,0 +1,16 @@ +// +// RollbarPayloadPostReply.h +// +// +// Created by Andrey Kornich on 2022-06-13. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarPayloadPostReply : NSObject + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m new file mode 100644 index 00000000..e12894d5 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m @@ -0,0 +1,12 @@ +// +// RollbarPayloadPostReply.m +// +// +// Created by Andrey Kornich on 2022-06-13. +// + +#import "RollbarPayloadPostReply.h" + +@implementation RollbarPayloadPostReply + +@end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h new file mode 100644 index 00000000..eeb4aab8 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h @@ -0,0 +1,16 @@ +// +// RollbarSender.h +// +// +// Created by Andrey Kornich on 2022-06-10. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarSender : NSObject + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m new file mode 100644 index 00000000..cb264ef1 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m @@ -0,0 +1,12 @@ +// +// RollbarSender.m +// +// +// Created by Andrey Kornich on 2022-06-10. +// + +#import "RollbarSender.h" + +@implementation RollbarSender + +@end diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h new file mode 100644 index 00000000..042031a6 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h @@ -0,0 +1,45 @@ +// +// RollbarInfrastructure.h +// +// +// Created by Andrey Kornich on 2022-06-09. +// + +#ifndef RollbarInfrastructure_h +#define RollbarInfrastructure_h + +#import + +@class RollbarConfig; + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarInfrastructure : NSObject + +/// Current config object. +@property(readonly) RollbarConfig *config; + +- (nonnull instancetype)configureWith:(RollbarConfig *)rollbarConfig; + +/// Hides the initializer. +- (instancetype)init NS_UNAVAILABLE; + +#pragma mark - Sigleton pattern + ++ (nonnull instancetype)sharedInstance; + ++ (instancetype)new NS_UNAVAILABLE; ++ (instancetype)allocWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; ++ (instancetype)alloc NS_UNAVAILABLE; ++ (id)copyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; ++ (id)mutableCopyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; + +- (void)dealloc NS_UNAVAILABLE; +- (id)copy NS_UNAVAILABLE; +- (id)mutableCopy NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END + +#endif //RollbarInfrastructure_h From d997e73d5a7b1e9fd6401ee1bb150cecad2240aa Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 13 Jun 2022 19:00:48 -0700 Subject: [PATCH 002/127] refactor: RollbarSession --- .../Sources/RollbarNotifier/RollbarSession.h | 7 ++++--- .../Sources/RollbarNotifier/RollbarSession.m | 10 ++++------ 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarSession.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarSession.h index 03d01d7c..3c9c4b36 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarSession.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarSession.h @@ -31,13 +31,14 @@ NS_ASSUME_NONNULL_BEGIN + (id)copyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; + (id)mutableCopyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; +- (void)dealloc NS_UNAVAILABLE; +- (id)copy NS_UNAVAILABLE; +- (id)mutableCopy NS_UNAVAILABLE; + - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument NS_UNAVAILABLE; - (instancetype)initWithBlock:(void (^)(void))block NS_UNAVAILABLE; -- (void)dealloc NS_UNAVAILABLE; -- (id)copy NS_UNAVAILABLE; -- (id)mutableCopy NS_UNAVAILABLE; @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarSession.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarSession.m index fd22485f..605aef66 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarSession.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarSession.m @@ -8,6 +8,7 @@ #import "RollbarSession.h" #import "RollbarSessionState.h" #import "RollbarLogger.h" +#import "RollbarNotifierFiles.h" #import "Rollbar.h" #import @@ -29,9 +30,6 @@ #pragma mark - constants -static NSString * const SESSION_FILE_NAME = @"rollbar.session"; -static NSString * const APP_QUIT_FILE_NAME = @"rollbar.appquit"; - static char *appQuitFilePath; #pragma mark - RollbarSession (Protected) @@ -107,7 +105,7 @@ - (void)enableOomMonitoring:(BOOL)enableOomDetection crashCheck ? crashCheck : [self registerDefaultCrashCheck]; if (YES == [RollbarCachesDirectory ensureCachesDirectoryExists]) { - appQuitFilePath = strdup([[RollbarCachesDirectory getCacheFilePath:APP_QUIT_FILE_NAME] UTF8String]); + appQuitFilePath = strdup([[RollbarCachesDirectory getCacheFilePath:[RollbarNotifierFiles appQuit]] UTF8String]); } [self deduceOomTermination]; @@ -444,7 +442,7 @@ - (instancetype)init { self = [super init]; if (self) { - self->_stateFilePath = [RollbarCachesDirectory getCacheFilePath:SESSION_FILE_NAME]; + self->_stateFilePath = [RollbarCachesDirectory getCacheFilePath:[RollbarNotifierFiles runtimeSession]]; if (NO == [RollbarCachesDirectory ensureCachesDirectoryExists]) { @@ -452,7 +450,7 @@ - (instancetype)init { return self; } - if (YES == [RollbarCachesDirectory checkCacheFileExists:SESSION_FILE_NAME]) { + if (YES == [RollbarCachesDirectory checkCacheFileExists:[RollbarNotifierFiles runtimeSession]]) { self->_state = [self loadSessionState]; } From fe686d660907c02b9c16d18d35c1624e225934ba Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 13 Jun 2022 19:01:53 -0700 Subject: [PATCH 003/127] refactor: RollbarNotifierFiles --- .../RollbarNotifier/RollbarNotifierFiles.h | 23 ++++++++ .../RollbarNotifier/RollbarNotifierFiles.m | 55 ++++++++++++++++--- 2 files changed, 71 insertions(+), 7 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h index cd46cb16..64025479 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h @@ -11,6 +11,29 @@ NS_ASSUME_NONNULL_BEGIN @interface RollbarNotifierFiles : NSObject +#pragma mark - notifier files + ++ (nonnull NSString * const)itemsQueue; ++ (nonnull NSString * const)itemsQueueState; + ++ (nonnull NSString * const)telemetryQueue; + ++ (nonnull NSString * const)runtimeSession; + ++ (nonnull NSString * const)appQuit; + ++ (nonnull NSString * const)payoadsLog; + ++ (nonnull NSString * const)config; + +#pragma mark - static utility nature + ++ (instancetype)new NS_UNAVAILABLE; ++ (instancetype)allocWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; ++ (instancetype)alloc NS_UNAVAILABLE; ++ (id)copyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; ++ (id)mutableCopyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m index ed69f362..bc8bd775 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m @@ -1,12 +1,53 @@ -// -// RollbarNotifierFiles.m -// -// -// Created by Andrey Kornich on 2022-06-06. -// - #import "RollbarNotifierFiles.h" +static NSString * const PAYLOADS_FILE_NAME = @"rollbar.payloads"; + +static NSString * const QUEUED_ITEMS_FILE_NAME = @"rollbar.items"; +static NSString * const QUEUED_ITEMS_STATE_FILE_NAME = @"rollbar.state"; + +static NSString * const QUEUED_TELEMETRY_ITEMS_FILE_NAME = @"rollbar.telemetry"; + +static NSString * const SESSION_FILE_NAME = @"rollbar.session"; +static NSString * const APP_QUIT_FILE_NAME = @"rollbar.appquit"; + +static NSString * const CONFIG_FILE_NAME = @"rollbar.config"; + @implementation RollbarNotifierFiles ++ (nonnull NSString * const)itemsQueue { + + return QUEUED_ITEMS_FILE_NAME; +} + ++ (nonnull NSString * const)itemsQueueState { + + return QUEUED_ITEMS_STATE_FILE_NAME; +} + ++ (nonnull NSString * const)telemetryQueue { + + return QUEUED_TELEMETRY_ITEMS_FILE_NAME; +} + ++ (nonnull NSString * const)runtimeSession { + + return SESSION_FILE_NAME; +} + ++ (nonnull NSString * const)appQuit { + + return APP_QUIT_FILE_NAME; +} + ++ (nonnull NSString * const)payoadsLog { + + return PAYLOADS_FILE_NAME; +} + ++ (nonnull NSString * const)config { + + return CONFIG_FILE_NAME; +} + + @end From 9bac164a3a6a7ce9a571c770c1017a8448cabdf3 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 13 Jun 2022 19:02:37 -0700 Subject: [PATCH 004/127] refactor: RollbarPayloadPostReply --- .../RollbarNotifier/RollbarPayloadPostReply.h | 11 ++++ .../RollbarNotifier/RollbarPayloadPostReply.m | 56 ++++++++++++++++--- 2 files changed, 60 insertions(+), 7 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h index 23457901..e5e5eec1 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h @@ -11,6 +11,17 @@ NS_ASSUME_NONNULL_BEGIN @interface RollbarPayloadPostReply : NSObject +@property (readonly) NSInteger statusCode; +@property (readonly) NSUInteger rateLimit; +@property (readonly) NSUInteger remainingCount; +@property (readonly) NSUInteger remainingSeconds; +@property (readonly) NSDate *nextPostTime; + +- (instancetype)init NS_UNAVAILABLE; + ++ (nullable RollbarPayloadPostReply *)replyFromHttpResponse:(nonnull NSHTTPURLResponse *)httpResponse; ++ (nonnull RollbarPayloadPostReply *)greenReply; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m index e12894d5..8ed63261 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m @@ -1,12 +1,54 @@ -// -// RollbarPayloadPostReply.m -// -// -// Created by Andrey Kornich on 2022-06-13. -// - #import "RollbarPayloadPostReply.h" +/// Rollbar API Service enforced payload rate limit: +static NSString * const RESPONSE_HEADER_RATE_LIMIT = @"x-rate-limit-limit"; +/// Rollbar API Service enforced remaining payload count until the limit is reached: +static NSString * const RESPONSE_HEADER_REMAINING_COUNT = @"x-rate-limit-remaining"; +/// Rollbar API Service enforced rate limit reset time for the current limit window: +static NSString * const RESPONSE_HEADER_RESET_TIME = @"x-rate-limit-reset"; +/// Rollbar API Service enforced rate limit remaining seconds of the current limit window: +static NSString * const RESPONSE_HEADER_REMAINING_SECONDS = @"x-rate-limit-remaining-seconds"; + @implementation RollbarPayloadPostReply ++ (nullable RollbarPayloadPostReply *)replyFromHttpResponse:(nonnull NSHTTPURLResponse *)httpResponse { + + return [[RollbarPayloadPostReply alloc] initWithStatusCode:httpResponse.statusCode + rateLimit:(NSUInteger)[[httpResponse valueForHTTPHeaderField:RESPONSE_HEADER_RATE_LIMIT]integerValue] + remainingCount:(NSUInteger)[[httpResponse valueForHTTPHeaderField:RESPONSE_HEADER_REMAINING_COUNT] integerValue] + remainingSeconds:(NSUInteger)[[httpResponse valueForHTTPHeaderField:RESPONSE_HEADER_REMAINING_SECONDS] integerValue] + ]; +} + +- (instancetype)initWithStatusCode:(NSUInteger)statusCode + rateLimit:(NSUInteger)rateLimit + remainingCount:(NSUInteger)remainingCount + remainingSeconds:(NSUInteger)remainingSeconds { + + if (self = [super init]) { + self->_statusCode = statusCode; + self->_rateLimit = rateLimit; + self->_remainingCount = remainingCount; + self->_remainingSeconds = remainingSeconds; + + if (self->_remainingCount > 0) { + self->_nextPostTime = [[NSDate alloc] init]; + } + else { + self->_nextPostTime = [[NSDate alloc] initWithTimeIntervalSinceNow:self->_remainingSeconds]; + } + } + + return self; +} + ++ (nonnull RollbarPayloadPostReply *)greenReply { + + return [[RollbarPayloadPostReply alloc] initWithStatusCode:200 + rateLimit:1 + remainingCount:1 + remainingSeconds:1 + ]; +} + @end From 6b5a2c7e57dd05da8e30fd95f57fe672439a4d8b Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 13 Jun 2022 19:03:02 -0700 Subject: [PATCH 005/127] refactor: RollbarSender --- .../Sources/RollbarNotifier/RollbarSender.h | 5 + .../Sources/RollbarNotifier/RollbarSender.m | 215 +++++++++++++++++- 2 files changed, 213 insertions(+), 7 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h index eeb4aab8..d81bd9b2 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h @@ -7,10 +7,15 @@ #import +@class RollbarConfig; +@class RollbarPayloadPostReply; + NS_ASSUME_NONNULL_BEGIN @interface RollbarSender : NSObject +- (nullable RollbarPayloadPostReply *)sendPayload:(nonnull NSData *)payload + usingConfig:(nonnull RollbarConfig *)config; @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m index cb264ef1..65d06cc0 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m @@ -1,12 +1,213 @@ -// -// RollbarSender.m -// -// -// Created by Andrey Kornich on 2022-06-10. -// - #import "RollbarSender.h" +#import "RollbarConfig.h" +#import "RollbarDestination.h" +#import "RollbarProxy.h" +#import "RollbarDeveloperOptions.h" +#import "RollbarPayloadPostReply.h" +#import "RollbarNotifierFiles.h" @implementation RollbarSender ++ (void)trace:(nonnull NSString *)message + withOptions:(nullable RollbarDeveloperOptions *)developerOptions { + + if (!developerOptions) { + // then, let's use default developer options: + developerOptions = [RollbarDeveloperOptions new]; + } + + if (NO == developerOptions.suppressSdkInfoLogging) { + RollbarSdkLog(message); + } +} + ++ (void)assertError:(nonnull NSString *)error + withOptions:(nullable RollbarDeveloperOptions *)developerOptions { + + [RollbarSender trace:error withOptions:developerOptions]; + + NSAssert(false, error); +} + +- (nullable RollbarPayloadPostReply *)sendPayload:(nonnull NSData *)payload + usingConfig:(nonnull RollbarConfig *)config { + + RollbarPayloadPostReply *reply = nil; + + if (YES == config.developerOptions.transmit) { + reply = [self transmitPayload:payload + toDestination:config.destination + usingDeveloperOptions:config.developerOptions + andHttpProxySettings:config.httpProxy + andHttpsProxySettings:config.httpsProxy + ]; + } + else { + reply = [RollbarPayloadPostReply greenReply]; // we just successfully short-circuit here... + } + + NSString *payloadString = [[NSString alloc] initWithData:payload + encoding:NSUTF8StringEncoding]; + if (reply && (200 == reply.statusCode)) { + [RollbarSender trace:[NSString stringWithFormat:@"Transmitted payload: %@", payloadString] + withOptions:config.developerOptions]; + if ((YES == config.developerOptions.logPayload) && config.developerOptions.payloadLogFile) { + [RollbarFileWriter appendSafelyData:payload toFile:config.developerOptions.payloadLogFile]; + //TODO: complete implementation (log into payloads log file)... + } + } + else if (reply) { + [RollbarSender trace:[NSString stringWithFormat:@"Failed to transmit payload (%li status code): %@", (long)reply.statusCode, payloadString] + withOptions:config.developerOptions]; + } + else { + [RollbarSender trace:[NSString stringWithFormat:@"Failed to transmit payload (no reply): %@", payloadString] + withOptions:config.developerOptions]; + } + + return reply; +} + +- (nullable RollbarPayloadPostReply *)transmitPayload:(nonnull NSData *)payload + toDestination:(nonnull RollbarDestination *)destination + usingDeveloperOptions:(nullable RollbarDeveloperOptions *)developerOptions + andHttpProxySettings:(nullable RollbarProxy *)httpProxySettings + andHttpsProxySettings:(nullable RollbarProxy *)httpsProxySettings { + + NSAssert(payload, @"The payload must be initialized!"); + + NSAssert(destination, @"The destination must be initialized!"); + NSAssert(destination.endpoint, @"The destination endpoint must be initialized!"); + NSAssert(destination.accessToken, @"The destination access token must be initialized!"); + + if (!developerOptions) { + // then, let's use default developer options: + developerOptions = [RollbarDeveloperOptions new]; + } + + if (!httpProxySettings) { + // then, let's use default proxy settingd: + httpProxySettings = [RollbarProxy new]; + } + + if (!httpsProxySettings) { + // then, let's use default proxy settingd: + httpsProxySettings = [RollbarProxy new]; + } + + NSHTTPURLResponse *response = [self postPayload:payload + toDestination:destination + usingDeveloperOptions:developerOptions + andHttpProxySettings:httpProxySettings + andHttpsProxySettings:httpsProxySettings]; + + RollbarPayloadPostReply *reply = [RollbarPayloadPostReply replyFromHttpResponse:response]; + + return reply; +} + +- (nullable NSHTTPURLResponse *)postPayload:(nonnull NSData *)payload + toDestination:(nonnull RollbarDestination *)destination + usingDeveloperOptions:(nonnull RollbarDeveloperOptions *)developerOptions + andHttpProxySettings:(nonnull RollbarProxy *)httpProxySettings + andHttpsProxySettings:(nonnull RollbarProxy *)httpsProxySettings { + + + NSURL *url = [NSURL URLWithString:destination.endpoint]; + if (nil == url) { + NSString *message = + [NSString stringWithFormat:@"The destination endpoint URL is malformed: %@", destination.endpoint]; + [RollbarSender assertError:message + withOptions:developerOptions]; + return nil; + } + + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request setHTTPMethod:@"POST"]; + [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + [request setValue:destination.accessToken forHTTPHeaderField:@"X-Rollbar-Access-Token"]; + [request setHTTPBody:payload]; + + //__block BOOL result = NO; + __block NSHTTPURLResponse *httpResponse = nil; + + // This requires iOS 7.0+ + dispatch_semaphore_t sem = dispatch_semaphore_create(0); + + NSURLSession *session = [NSURLSession sharedSession]; + + if (httpProxySettings.enabled + || httpsProxySettings.enabled) { + + NSDictionary *connectionProxyDictionary = + @{ + @"HTTPEnable" : [NSNumber numberWithBool:httpProxySettings.enabled], + @"HTTPProxy" : httpProxySettings.proxyUrl, + @"HTTPPort" : [NSNumber numberWithUnsignedInteger:httpProxySettings.proxyPort], + @"HTTPSEnable" : [NSNumber numberWithBool:httpsProxySettings.enabled], + @"HTTPSProxy" : httpsProxySettings.proxyUrl, + @"HTTPSPort" : [NSNumber numberWithUnsignedInteger:httpsProxySettings.proxyPort] + }; + + NSURLSessionConfiguration *sessionConfig = + [NSURLSessionConfiguration ephemeralSessionConfiguration]; + sessionConfig.connectionProxyDictionary = connectionProxyDictionary; + session = [NSURLSession sessionWithConfiguration:sessionConfig]; + } + + NSURLSessionDataTask *dataTask = + [session dataTaskWithRequest:request + completionHandler:^( + NSData * _Nullable data, + NSURLResponse * _Nullable response, + NSError * _Nullable error) { + httpResponse = [self checkPayloadResponse:response + error:error + data:data + usingDeveloperOptions:developerOptions]; + dispatch_semaphore_signal(sem); + }]; + [dataTask resume]; + + dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); + + return httpResponse; +} + +- (nullable NSHTTPURLResponse *)checkPayloadResponse:(NSURLResponse *)response + error:(NSError *)error + data:(NSData *)data + usingDeveloperOptions:(nonnull RollbarDeveloperOptions *)developerOptions { + + if (error) { + [RollbarSender trace:@"There was an error reporting to Rollbar:" + withOptions:developerOptions]; + [RollbarSender trace:[NSString stringWithFormat:@" Error: %@", [error localizedDescription]] + withOptions:developerOptions]; + return nil; + } + + NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; + if (httpResponse && (200 == [httpResponse statusCode])) { + [RollbarSender trace:[NSString stringWithFormat:@"OK response from Rollar: %@", httpResponse] + withOptions:developerOptions]; + return httpResponse; + } + + [RollbarSender trace:@"There was a problem reporting to Rollbar:" + withOptions:developerOptions]; + [RollbarSender trace:[NSString stringWithFormat:@" Response: %@", response] + withOptions:developerOptions]; + [RollbarSender trace:[NSString stringWithFormat:@" Response data: %@", data] + withOptions:developerOptions]; + // [RollbarSender trace:[NSString stringWithFormat:@" Response data: %@", + // [NSJSONSerialization JSONObjectWithData:data + // options:0 + // error:nil] + // ] + // withOptions:developerOptions]; + + return nil; +} + @end From d3fad44b6fd8bdfd3de9662a4234657cb58f61b7 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 13 Jun 2022 19:03:33 -0700 Subject: [PATCH 006/127] refactor: RollbarInfrastructure --- .../RollbarNotifier/RollbarInfrastructure.m | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index c4c85087..7660ce29 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -9,4 +9,26 @@ @implementation RollbarInfrastructure +- (nonnull instancetype)configureWith:(RollbarConfig *)rollbarConfig { + + self->_config = rollbarConfig; + + return self; +} + +#pragma mark - Sigleton pattern + ++ (nonnull instancetype)sharedInstance { + + static id singleton; + static dispatch_once_t onceToken; + + dispatch_once(&onceToken, ^{ + + singleton = [self new]; + }); + + return singleton; +} + @end From e60ac375887f308c3f36e17401285e5c8d3983ba Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 13 Jun 2022 19:04:27 -0700 Subject: [PATCH 007/127] refactor: RollbarConfigUtil --- RollbarNotifier/Sources/RollbarNotifier/RollbarConfigUtil.m | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarConfigUtil.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarConfigUtil.m index 7539bd4e..0c709c53 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarConfigUtil.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarConfigUtil.m @@ -2,10 +2,10 @@ #import "RollbarConfigUtil.h" #import "RollbarConfig.h" +#import "RollbarNotifierFiles.h" #pragma mark - constants -static NSString * const CONFIGURATION_FILENAME = @"rollbar.config"; static NSString *configurationDirectory = nil; static NSString *configurationFilePath = nil; @@ -18,13 +18,13 @@ + (void)initialize { if (self == [RollbarConfigUtil class]) { configurationDirectory = [RollbarCachesDirectory directory]; - configurationFilePath = [configurationDirectory stringByAppendingPathComponent:CONFIGURATION_FILENAME]; + configurationFilePath = [configurationDirectory stringByAppendingPathComponent:[RollbarNotifierFiles config]]; } } + (nonnull NSString *)getDefaultConfigFileName { - return CONFIGURATION_FILENAME; + return [RollbarNotifierFiles config]; } + (nonnull NSString *)getDefaultConfigDirectory { From f2fed5702cac309e516da38408c2b7a86a94f6dc Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 14 Jun 2022 12:47:34 -0700 Subject: [PATCH 008/127] test: RollbarPayloadPostReplyTests --- .../RollbarPayloadPostReplyTests.m | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m new file mode 100644 index 00000000..a1a8966d --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m @@ -0,0 +1,36 @@ +// +// RollbarPayloadPostReplyTests.m +// +// +// Created by Andrey Kornich on 2022-06-14. +// + +#import + +@interface RollbarPayloadPostReplyTests : XCTestCase + +@end + +@implementation RollbarPayloadPostReplyTests + +- (void)setUp { + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. +} + +- (void)testExample { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end From 72b56976d82dc9246fe37f5c7ea66636e4ac9107 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 14 Jun 2022 12:47:46 -0700 Subject: [PATCH 009/127] test: RollbarPayloadPostReplyTests --- .../RollbarPayloadPostReplyTests.m | 43 +++++++++++++++++-- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m index a1a8966d..92282a34 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m @@ -6,6 +6,7 @@ // #import +#import "../../Sources/RollbarNotifier/RollbarPayloadPostReply.h" @interface RollbarPayloadPostReplyTests : XCTestCase @@ -21,15 +22,49 @@ - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. } -- (void)testExample { - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct results. +- (void)testCanPostNowReply { + + RollbarPayloadPostReply *reply = [[RollbarPayloadPostReply alloc] initWithStatusCode:200 + rateLimit:60 + remainingCount:10 + remainingSeconds:20]; + NSDate *now = [NSDate date]; + XCTAssertEqual([now earlierDate:reply.nextPostTime], reply.nextPostTime); +} + +- (void)testWillPostLaterReply { + + RollbarPayloadPostReply *reply = [[RollbarPayloadPostReply alloc] initWithStatusCode:200 + rateLimit:60 + remainingCount:0 + remainingSeconds:20]; + NSDate *now = [NSDate date]; + XCTAssertEqual([now earlierDate:reply.nextPostTime], now); + XCTAssertTrue([reply.nextPostTime timeIntervalSinceDate:now] < 20); +} + +- (void)testGreenReply { + + RollbarPayloadPostReply *reply = [RollbarPayloadPostReply greenReply]; + NSDate *now = [NSDate date]; + XCTAssertEqual([now earlierDate:reply.nextPostTime], reply.nextPostTime); +} + +- (void)testRedReply { + + RollbarPayloadPostReply *reply = [RollbarPayloadPostReply redReply]; + NSDate *now = [NSDate date]; + XCTAssertEqual([now earlierDate:reply.nextPostTime], now); + XCTAssertTrue([reply.nextPostTime timeIntervalSinceDate:now] < 1); } - (void)testPerformanceExample { // This is an example of a performance test case. [self measureBlock:^{ - // Put the code you want to measure the time of here. + RollbarPayloadPostReply *reply = [[RollbarPayloadPostReply alloc] initWithStatusCode:200 + rateLimit:60 + remainingCount:10 + remainingSeconds:20]; }]; } From c26026ddf94e472f3a4a8770e2d407bd16964471 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 14 Jun 2022 12:48:47 -0700 Subject: [PATCH 010/127] test: RollbarPayloadPostReplyTests --- .../RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m index 92282a34..f4eb9481 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m @@ -59,7 +59,7 @@ - (void)testRedReply { } - (void)testPerformanceExample { - // This is an example of a performance test case. + [self measureBlock:^{ RollbarPayloadPostReply *reply = [[RollbarPayloadPostReply alloc] initWithStatusCode:200 rateLimit:60 From 485e53101f6a53ebfd679e5073c23fbccb3f4dcc Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 14 Jun 2022 22:26:55 -0700 Subject: [PATCH 011/127] refactor: added RollbarPayloadFactory --- .../RollbarNotifier/RollbarPayloadFactory.h | 16 +++++++++ .../RollbarNotifier/RollbarPayloadFactory.m | 12 +++++++ .../RollbarSenderTests.m | 36 +++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.h create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.h new file mode 100644 index 00000000..f6e9bad6 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.h @@ -0,0 +1,16 @@ +// +// RollbarPayloadFactory.h +// +// +// Created by Andrey Kornich on 2022-06-14. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarPayloadFactory : NSObject + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m new file mode 100644 index 00000000..6d0bd803 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m @@ -0,0 +1,12 @@ +// +// RollbarPayloadFactory.m +// +// +// Created by Andrey Kornich on 2022-06-14. +// + +#import "RollbarPayloadFactory.h" + +@implementation RollbarPayloadFactory + +@end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m new file mode 100644 index 00000000..0877736f --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m @@ -0,0 +1,36 @@ +// +// RollbarSenderTests.m +// +// +// Created by Andrey Kornich on 2022-06-14. +// + +#import + +@interface RollbarSenderTests : XCTestCase + +@end + +@implementation RollbarSenderTests + +- (void)setUp { + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. +} + +- (void)testExample { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end From 9e6b27d3cf4df744f746d6146148eacb80d229ab Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 14 Jun 2022 22:27:51 -0700 Subject: [PATCH 012/127] test: RollbarSenderTests --- .../Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m | 2 ++ 1 file changed, 2 insertions(+) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m index 0877736f..1769f93a 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m @@ -6,6 +6,7 @@ // #import +#import "../../Sources/RollbarNotifier/RollbarSender.h" @interface RollbarSenderTests : XCTestCase @@ -30,6 +31,7 @@ - (void)testPerformanceExample { // This is an example of a performance test case. [self measureBlock:^{ // Put the code you want to measure the time of here. + RollbarSender *sender = [RollbarSender new]; }]; } From 35c295efa610c39fa387a855b41ff0783925fbd7 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 14 Jun 2022 22:29:53 -0700 Subject: [PATCH 013/127] refactor: RollbarOsUtil --- .../Sources/RollbarCommon/include/RollbarOsUtil.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/RollbarCommon/Sources/RollbarCommon/include/RollbarOsUtil.h b/RollbarCommon/Sources/RollbarCommon/include/RollbarOsUtil.h index 56b7eeba..841c0a7a 100644 --- a/RollbarCommon/Sources/RollbarCommon/include/RollbarOsUtil.h +++ b/RollbarCommon/Sources/RollbarCommon/include/RollbarOsUtil.h @@ -21,9 +21,13 @@ NS_ASSUME_NONNULL_BEGIN + (NSTimeInterval)detectOsUptimeInterval; -#pragma mark - utility +#pragma mark - static utility nature -- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; ++ (instancetype)allocWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; ++ (instancetype)alloc NS_UNAVAILABLE; ++ (id)copyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; ++ (id)mutableCopyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; @end From ed6603085bbe76f2df04f7cf74ebb831a37b5990 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 14 Jun 2022 22:32:13 -0700 Subject: [PATCH 014/127] refactor: RollbarPayloadFactory --- .../RollbarNotifier/RollbarPayloadFactory.h | 28 ++ .../RollbarNotifier/RollbarPayloadFactory.m | 433 +++++++++++++++++- 2 files changed, 460 insertions(+), 1 deletion(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.h index f6e9bad6..a71f64c1 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.h @@ -7,10 +7,38 @@ #import +#import "RollbarLevel.h" + +@class RollbarConfig; +@class RollbarPayload; + NS_ASSUME_NONNULL_BEGIN @interface RollbarPayloadFactory : NSObject +- (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level + crashReport:(nonnull NSString *)crashReport; + +- (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level + message:(nonnull NSString *)message + data:(nullable NSDictionary *)data + context:(nullable NSString *)context; + +- (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level + exception:(nonnull NSException *)exception + data:(nullable NSDictionary *)data + context:(nullable NSString *)context; + +- (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level + error:(nonnull NSError *)error + data:(nullable NSDictionary *)data + context:(nullable NSString *)context; + +- (instancetype)initWithConfig:(nonnull RollbarConfig *)config NS_DESIGNATED_INITIALIZER; +- (instancetype)init NS_UNAVAILABLE; + ++ (instancetype)factoryWithConfig:(nonnull RollbarConfig *)config; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m index 6d0bd803..43263824 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m @@ -7,6 +7,437 @@ #import "RollbarPayloadFactory.h" -@implementation RollbarPayloadFactory +#import "RollbarConfig.h" +#import "RollbarLoggingOptions.h" +#import "RollbarScrubbingOptions.h" +#import "RollbarDestination.h" + +#import "RollbarPayload.h" +#import "RollbarBody.h" +#import "RollbarMessage.h" +#import "RollbarData.h" +#import "RollbarPerson.h" +#import "RollbarServer.h" +#import "RollbarClient.h" +#import "RollbarModule.h" + +#import + +@implementation RollbarPayloadFactory { + + @private + RollbarConfig *_config; // expected to be nonnull... + NSDictionary *_osData; +} + ++ (instancetype)factoryWithConfig:(nonnull RollbarConfig *)config { + + RollbarPayloadFactory *factory = [[RollbarPayloadFactory alloc] initWithConfig:config]; + return factory; +} + +- (instancetype)initWithConfig:(nonnull RollbarConfig *)config { + + NSAssert(config, @"The config must be initialized!"); + + if (self = [super init]) { + + self->_config = config; + } + + return self; +} + +#pragma mark - Patload factory methods + +- (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level + crashReport:(nonnull NSString *)crashReport { + + RollbarPayload *payload = [self buildRollbarPayloadWithLevel:level + message:nil + exception:nil + error:nil + extra:nil + crashReport:crashReport + context:nil]; + return payload; +} + +- (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level + message:(nonnull NSString *)message + data:(nullable NSDictionary *)data + context:(nullable NSString *)context { + + RollbarPayload *payload = [self buildRollbarPayloadWithLevel:level + message:message + exception:nil + error:nil + extra:data + crashReport:nil + context:context]; + return payload; +} + +- (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level + exception:(nonnull NSException *)exception + data:(nullable NSDictionary *)data + context:(nullable NSString *)context { + + RollbarPayload *payload = [self buildRollbarPayloadWithLevel:level + message:nil + exception:exception + error:nil + extra:data + crashReport:nil + context:context]; + return payload; +} + +- (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level + error:(nonnull NSError *)error + data:(nullable NSDictionary *)data + context:(nullable NSString *)context { + + RollbarPayload *payload = [self buildRollbarPayloadWithLevel:level + message:nil + exception:nil + error:error + extra:data + crashReport:nil + context:context]; + return payload; +} + +#pragma mark - Payload custom modifiers based on the current config + +-(BOOL)shouldIgnoreRollbarData:(nonnull RollbarData *)incomingData { + + BOOL shouldIgnore = NO; + if (self->_config.checkIgnoreRollbarData) { + @try { + shouldIgnore = self->_config.checkIgnoreRollbarData(incomingData); + return shouldIgnore; + } @catch(NSException *e) { + RollbarSdkLog(@"checkIgnore error: %@", e.reason); + + // Remove checkIgnore to prevent future exceptions + self->_config.checkIgnoreRollbarData = nil; + return NO; + } + } + + return shouldIgnore; +} + +-(RollbarData *)modifyRollbarData:(nonnull RollbarData *)incomingData { + + if (self->_config.modifyRollbarData) { + return self->_config.modifyRollbarData(incomingData); + } + return incomingData; +} + +-(RollbarData *)scrubRollbarData:(nonnull RollbarData *)incomingData { + + NSSet *scrubFieldsSet = [self getScrubFields]; + if (!scrubFieldsSet || scrubFieldsSet.count == 0) { + return incomingData; + } + + NSMutableDictionary *mutableJsonFriendlyData = incomingData.jsonFriendlyData.mutableCopy; + for (NSString *key in scrubFieldsSet) { + if ([mutableJsonFriendlyData valueForKeyPath:key]) { + [self createMutablePayloadWithData:mutableJsonFriendlyData forPath:key]; + [mutableJsonFriendlyData setValue:@"*****" forKeyPath:key]; + } + } + + return [[RollbarData alloc] initWithDictionary:mutableJsonFriendlyData]; +} + +-(NSSet *)getScrubFields { + + if (!self->_config.dataScrubber + || self->_config.dataScrubber.isEmpty + || !self->_config.dataScrubber.enabled + || !self->_config.dataScrubber.scrubFields + || self->_config.dataScrubber.scrubFields.count == 0) { + + return [NSSet set]; + } + + NSMutableSet *actualFieldsToScrub = self->_config.dataScrubber.scrubFields.mutableCopy; + if (self->_config.dataScrubber.safeListFields.count > 0) { + // actualFieldsToScrub = + // config.dataScrubber.scrubFields - config.dataScrubber.whitelistFields + // while using case insensitive field name comparison: + actualFieldsToScrub = [NSMutableSet new]; + for(NSString *key in self->_config.dataScrubber.scrubFields) { + BOOL isWhitelisted = false; + for (NSString *whiteKey in self->_config.dataScrubber.safeListFields) { + if (NSOrderedSame == [key caseInsensitiveCompare:whiteKey]) { + isWhitelisted = true; + } + } + if (!isWhitelisted) { + [actualFieldsToScrub addObject:key]; + } + } + } + + return actualFieldsToScrub; +} + +- (void)createMutablePayloadWithData:(NSMutableDictionary *)data + forPath:(NSString *)path { + + NSArray *pathComponents = [path componentsSeparatedByString:@"."]; + NSString *currentPath = @""; + + for (int i=0; i_config.destination + || !self->_config.destination.environment + || self->_config.destination.environment.length == 0) { + + return nil; + } + + // compile payload data proper body: + RollbarBody *body = [RollbarBody alloc]; + if (crashReport) { + body = [body initWithCrashReport:crashReport]; + } + else if (error) { + body = [body initWithError:error]; + } + else if (exception) { + body = [body initWithException:exception]; + } + else if (message) { + body = [body initWithMessage:message]; + } + else { + return nil; + } + + if (!body) { + return nil; + } + + // this is done only for backward compatibility for customers that used to rely on this undocumented + // extra data with a message: + if (message && extra) { + [body.message setData:extra byKey:@"extra"]; + } + + // compile payload data: + RollbarData *data = [[RollbarData alloc] initWithEnvironment:self->_config.destination.environment + body:body]; + if (!data) { + return nil; + } + + NSMutableDictionary *customData = + [NSMutableDictionary dictionaryWithDictionary:self->_config.customData]; + if (crashReport || exception) { + // neither crash report no exception payload objects have placeholders for any extra data + // or an extra message, let's preserve them as the custom data: + if (extra) { + customData[@"error.extra"] = extra; + } + if (message && message.length > 0) { + customData[@"error.message"] = message; + } + } + + data.level = level; + data.language = RollbarAppLanguage_ObjectiveC; + data.platform = @"client"; + data.uuid = [NSUUID UUID]; + data.custom = [[RollbarDTO alloc] initWithDictionary:customData]; + data.notifier = [self buildRollbarNotifierModule]; + data.person = [self buildRollbarPerson]; + data.server = [self buildRollbarServer]; + data.client = [self buildRollbarClient]; + if (context && context.length > 0) { + data.context = context; + } + if (self->_config.loggingOptions) { + data.framework = self->_config.loggingOptions.framework; + if (self->_config.loggingOptions.requestId + && (self->_config.loggingOptions.requestId.length > 0)) { + + [data setData:self->_config.loggingOptions.requestId byKey:@"requestId"]; + } + } + + // Transform payload data, if necessary + if ([self shouldIgnoreRollbarData:data]) { + return nil; + } + data = [self modifyRollbarData:data]; + data = [self scrubRollbarData:data]; + + RollbarPayload *payload = [[RollbarPayload alloc] initWithAccessToken:self->_config.destination.accessToken + data:data]; + + return payload; +} + +-(RollbarModule *)buildRollbarNotifierModule { + + if (self->_config.notifier && !self->_config.notifier.isEmpty) { + + RollbarModule *notifierModule = + [[RollbarModule alloc] initWithDictionary:self->_config.notifier.jsonFriendlyData.copy]; + [notifierModule setData:self->_config.jsonFriendlyData byKey:@"configured_options"]; + return notifierModule; + } + + return nil; +} + +-(RollbarClient *)buildRollbarClient { + + NSNumber *timestamp = [NSNumber numberWithInteger:[[NSDate date] timeIntervalSince1970]]; + + if (self->_config.loggingOptions) { + switch(self->_config.loggingOptions.captureIp) { + case RollbarCaptureIpType_Full: + return [[RollbarClient alloc] initWithDictionary:@{ + @"timestamp": timestamp, + @"ios": [self buildOSData], + @"user_ip": @"$remote_ip" + }]; + case RollbarCaptureIpType_Anonymize: + return [[RollbarClient alloc] initWithDictionary:@{ + @"timestamp": timestamp, + @"ios": [self buildOSData], + @"user_ip": @"$remote_ip_anonymize" + }]; + case RollbarCaptureIpType_None: + //no op + break; + } + } + + return [[RollbarClient alloc] initWithDictionary:@{ + @"timestamp": timestamp, + @"ios": [self buildOSData], + }]; +} + +-(RollbarPerson *)buildRollbarPerson { + + if (self->_config.person && self->_config.person.ID) { + return self->_config.person; + } + else { + return nil; + } +} + +-(RollbarServer *)buildRollbarServer { + + if (self->_config.server && !self->_config.server.isEmpty) { + return [[RollbarServer alloc] initWithCpu:nil + serverConfig:self->_config.server]; + } + else { + return nil; + } +} + +-(NSDictionary *)buildOSData { + + //TODO: redo this implementation based on the helper utils used by RollbarSession or on RollbarSession itself... + + if (self->_osData) { + return self->_osData; + } + + NSBundle *mainBundle = [NSBundle mainBundle]; + + NSString *version = nil; + if (self->_config.loggingOptions + && self->_config.loggingOptions.codeVersion + && self->_config.loggingOptions.codeVersion.length > 0) { + + version = self->_config.loggingOptions.codeVersion; + } + else { + version = [mainBundle objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey]; + } + + NSString *shortVersion = [mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; + NSString *bundleName = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey]; + NSString *bundleIdentifier = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleIdentifierKey]; + + struct utsname systemInfo; + uname(&systemInfo); + NSString *deviceCode = [NSString stringWithCString:systemInfo.machine + encoding:NSUTF8StringEncoding]; + +#if TARGET_OS_IOS | TARGET_OS_TV | TARGET_OS_MACCATALYST + self->_osData = @{ + @"os": @"iOS", + @"os_version": [[UIDevice currentDevice] systemVersion], + @"device_code": deviceCode, + @"code_version": version ? version : @"", + @"short_version": shortVersion ? shortVersion : @"", + @"bundle_identifier": bundleIdentifier ? bundleIdentifier : @"", + @"app_name": bundleName ? bundleName : @"" + }; +#else + NSOperatingSystemVersion osVer = [[NSProcessInfo processInfo] operatingSystemVersion]; + self->_osData = @{ + @"os": @"macOS", + @"os_version": [NSString stringWithFormat:@" %tu.%tu.%tu", + osVer.majorVersion, + osVer.minorVersion, + osVer.patchVersion + ], + @"device_code": deviceCode, + @"code_version": version ? version : @"", + @"short_version": shortVersion ? shortVersion : @"", + @"bundle_identifier": bundleIdentifier ? bundleIdentifier : @"", + @"app_name": bundleName ? bundleName : [[NSProcessInfo processInfo] processName] + }; +#endif + + return self->_osData; +} @end From f741059967df7fb8fcd38da1d9cee822cc6f40a3 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 14 Jun 2022 22:33:04 -0700 Subject: [PATCH 015/127] refactor: RollbarPayloadPostReply --- .../RollbarNotifier/RollbarPayloadPostReply.h | 8 +++++- .../RollbarNotifier/RollbarPayloadPostReply.m | 28 +++++++++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h index e5e5eec1..58299d04 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h @@ -17,10 +17,16 @@ NS_ASSUME_NONNULL_BEGIN @property (readonly) NSUInteger remainingSeconds; @property (readonly) NSDate *nextPostTime; -- (instancetype)init NS_UNAVAILABLE; +- (instancetype)initWithStatusCode:(NSUInteger)statusCode + rateLimit:(NSUInteger)rateLimit + remainingCount:(NSUInteger)remainingCount + remainingSeconds:(NSUInteger)remainingSeconds; + + - (instancetype)init NS_UNAVAILABLE; + (nullable RollbarPayloadPostReply *)replyFromHttpResponse:(nonnull NSHTTPURLResponse *)httpResponse; + (nonnull RollbarPayloadPostReply *)greenReply; ++ (nonnull RollbarPayloadPostReply *)redReply; @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m index 8ed63261..759b581f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m @@ -13,10 +13,22 @@ @implementation RollbarPayloadPostReply + (nullable RollbarPayloadPostReply *)replyFromHttpResponse:(nonnull NSHTTPURLResponse *)httpResponse { + NSUInteger rateLimit = + [NSNumber numberWithLongLong:[httpResponse valueForHTTPHeaderField:RESPONSE_HEADER_RATE_LIMIT]] + .unsignedIntegerValue; + + NSUInteger remainingCount = + [NSNumber numberWithLongLong:[httpResponse valueForHTTPHeaderField:RESPONSE_HEADER_REMAINING_COUNT]] + .unsignedIntegerValue; + + NSUInteger remainingSeconds = + [NSNumber numberWithLongLong:[httpResponse valueForHTTPHeaderField:RESPONSE_HEADER_REMAINING_SECONDS]] + .unsignedIntegerValue; + return [[RollbarPayloadPostReply alloc] initWithStatusCode:httpResponse.statusCode - rateLimit:(NSUInteger)[[httpResponse valueForHTTPHeaderField:RESPONSE_HEADER_RATE_LIMIT]integerValue] - remainingCount:(NSUInteger)[[httpResponse valueForHTTPHeaderField:RESPONSE_HEADER_REMAINING_COUNT] integerValue] - remainingSeconds:(NSUInteger)[[httpResponse valueForHTTPHeaderField:RESPONSE_HEADER_REMAINING_SECONDS] integerValue] + rateLimit:rateLimit + remainingCount:remainingCount + remainingSeconds:remainingSeconds ]; } @@ -51,4 +63,14 @@ + (nonnull RollbarPayloadPostReply *)greenReply { ]; } ++ (nonnull RollbarPayloadPostReply *)redReply { + + return [[RollbarPayloadPostReply alloc] initWithStatusCode:200 + rateLimit:1 + remainingCount:0 + remainingSeconds:1 + ]; +} + + @end From eb9a2f7e2e993c62c404ef10f40a04611dfd85e2 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 15 Jun 2022 12:36:04 -0700 Subject: [PATCH 016/127] test: RollbarPayloadFactoryTests --- .../RollbarPayloadFactoryTests.m | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m new file mode 100644 index 00000000..736ca792 --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m @@ -0,0 +1,36 @@ +// +// RollbarPayloadFactoryTests.m +// +// +// Created by Andrey Kornich on 2022-06-15. +// + +#import + +@interface RollbarPayloadFactoryTests : XCTestCase + +@end + +@implementation RollbarPayloadFactoryTests + +- (void)setUp { + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. +} + +- (void)testExample { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end From b2508f91dc9eacd5932f1df3140be6d83d71b946 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 15 Jun 2022 12:36:38 -0700 Subject: [PATCH 017/127] test: RollbarPayloadFactoryTests --- .../RollbarNotifier/DTOs/RollbarConfig.m | 24 +++ .../RollbarNotifier/include/RollbarConfig.h | 5 +- .../RollbarPayloadFactoryTests.m | 162 +++++++++++++++++- 3 files changed, 184 insertions(+), 7 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m index ae9f578e..3aede7f4 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m @@ -52,6 +52,30 @@ @implementation RollbarConfig +#pragma mark - factory methods + ++ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token { + + NSAssert(token, @"Access token must be initialized!"); + NSAssert(token.length > 0, @"Access token must not be empty string!"); + + RollbarConfig *config = [RollbarConfig new]; + config.destination.accessToken = token; + + return config; +} + ++ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token environment:(nonnull NSString *)env { + + NSAssert(env, @"Environment must be initialized!"); + NSAssert(env.length > 0, @"Environment must not be empty string!"); + + RollbarConfig *config = [RollbarConfig configWithAccessToken:token]; + config.destination.environment = env; + + return config; +} + #pragma mark - initializers - (instancetype)init { diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h index 077aed3e..e8797a2c 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h @@ -66,7 +66,6 @@ NS_ASSUME_NONNULL_BEGIN /// Modifies payload data before sending @property (nullable, nonatomic, copy) RollbarData *(^modifyRollbarData)(RollbarData *rollbarData); - #pragma mark - Convenience Methods /// Sets person/user related information to be sent with each payload @@ -94,6 +93,10 @@ NS_ASSUME_NONNULL_BEGIN - (void)setNotifierName:(nullable NSString *)name version:(nullable NSString *)version; +#pragma mark - Factory Methods + ++ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token; ++ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token environment:(nonnull NSString *)env; @end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m index 736ca792..69e5f1b2 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m @@ -6,6 +6,10 @@ // #import +#import "../../Sources/RollbarNotifier/RollbarPayloadFactory.h" + +@import UnitTesting; +@import RollbarNotifier; @interface RollbarPayloadFactoryTests : XCTestCase @@ -21,16 +25,162 @@ - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. } -- (void)testExample { - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct results. +- (void)testCrashReportPayload { + + NSString *crashReport = @"Fake crash report!"; + RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical + crashReport:crashReport]; + + [self assertCommonComponentsOfPayload:payload]; + + XCTAssertNotNil(payload.data.body.crashReport); + XCTAssertNil(payload.data.body.trace); + XCTAssertNil(payload.data.body.traceChain); + XCTAssertNil(payload.data.body.message); + + XCTAssertTrue([payload.data.body.crashReport.rawCrashReport containsString:crashReport]); + XCTAssertTrue([[payload serializeToJSONString] containsString:crashReport]); +} + +- (void)testMessagePayload { + + NSString *message = @"MessageMock"; + RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical + message:message + data:nil + context:@"MockContext"]; + + [self assertCommonComponentsOfPayload:payload]; + + XCTAssertNil(payload.data.body.crashReport); + XCTAssertNil(payload.data.body.trace); + XCTAssertNil(payload.data.body.traceChain); + XCTAssertNotNil(payload.data.body.message); + + XCTAssertTrue([payload.data.body.message.description containsString:message]); + XCTAssertTrue([[payload serializeToJSONString] containsString:message]); + XCTAssertTrue([[payload serializeToJSONString] containsString:@"MockContext"]); +} + + +- (void)testErrorPayload { + + NSError *error = [NSError errorWithDomain:@"NSErrorDomain" code:1001 userInfo:nil]; + RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical + error:error + data:nil + context:@"MockContext"]; + + [self assertCommonComponentsOfPayload:payload]; + + XCTAssertNil(payload.data.body.crashReport); + XCTAssertNil(payload.data.body.trace); + XCTAssertNil(payload.data.body.traceChain); + XCTAssertNotNil(payload.data.body.message); + + XCTAssertTrue([payload.data.body.message.description containsString:@"NSErrorDomain"]); + XCTAssertTrue([payload.data.body.message.description containsString:@"1001"]); + XCTAssertTrue([[payload serializeToJSONString] containsString:@"NSErrorDomain"]); + XCTAssertTrue([[payload serializeToJSONString] containsString:@"1001"]); + XCTAssertTrue([[payload serializeToJSONString] containsString:@"MockContext"]); +} + +- (void)testExceptionPayload { + + NSException *exception = [NSException exceptionWithName:@"Oy vey!" reason:@"Don't ask!" userInfo:nil]; + RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical + exception:exception + data:nil + context:@"MockContext"]; + + [self assertCommonComponentsOfPayload:payload]; + + XCTAssertNil(payload.data.body.crashReport); + XCTAssertNotNil(payload.data.body.trace); + XCTAssertNil(payload.data.body.traceChain); + XCTAssertNil(payload.data.body.message); + + XCTAssertTrue([[payload serializeToJSONString] containsString:@"NSException"]); + XCTAssertTrue([[payload serializeToJSONString] containsString:@"Don't ask!"]); + XCTAssertTrue([[payload serializeToJSONString] containsString:@"MockContext"]); } -- (void)testPerformanceExample { - // This is an example of a performance test case. +- (void)testPerformanceCrashReportPayload { + + NSString *crashReport = @"Fake crash report!"; + [self measureBlock:^{ - // Put the code you want to measure the time of here. + + RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical + crashReport:crashReport]; + [payload serializeToJSONString]; + }]; +} + +- (void)testPerformanceMessagePayload { + + NSString *message = @"MessageMock"; + + [self measureBlock:^{ + + RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical + message:message + data:nil + context:@"MockContext"]; + [payload serializeToJSONString]; }]; } +- (void)testPerformanceErrorPayload { + + NSError *error = [NSError errorWithDomain:@"NSErrorDomain" code:1001 userInfo:nil]; + + [self measureBlock:^{ + + RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical + error:error + data:nil + context:@"MockContext"]; + [payload serializeToJSONString]; + }]; +} + +- (void)testPerformanceExceptionPayload { + + NSException *exception = [NSException exceptionWithName:@"Oy vey!" reason:@"Don't ask!" userInfo:nil]; + + [self measureBlock:^{ + + RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical + exception:exception + data:nil + context:@"MockContext"]; + [payload serializeToJSONString]; + }]; +} + +- (void)assertCommonComponentsOfPayload:(nullable RollbarPayload *)payload { + + XCTAssertNotNil(payload); + XCTAssertNotNil(payload.data); + XCTAssertNotNil(payload.data.body); + XCTAssertNotNil(payload.data.notifier); + //TODO: continue asserting presence and values of other expected common components of every payload... +} + +- (nonnull RollbarPayloadFactory *)getPayloadFactory { + + RollbarPayloadFactory *factory = [RollbarPayloadFactory factoryWithConfig:[self getConfig]]; + return factory; +} + +- (nonnull RollbarConfig*) getConfig { + + RollbarConfig *config = + [RollbarConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; + + return config; +} + @end From 8fe442ae969bf86b0bf061ea0645941c2f627a93 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 15 Jun 2022 22:16:56 -0700 Subject: [PATCH 018/127] test: added common test helpers --- .../XCTestCase+RollbarNotifierTest.h | 16 ++++++++++++++++ .../XCTestCase+RollbarNotifierTest.m | 12 ++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h new file mode 100644 index 00000000..56675ef8 --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h @@ -0,0 +1,16 @@ +// +// XCTestCase+RollbarNotifierTest.h +// +// +// Created by Andrey Kornich on 2022-06-15. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface XCTestCase (RollbarNotifierTest) + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m new file mode 100644 index 00000000..5bfe9e76 --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m @@ -0,0 +1,12 @@ +// +// XCTestCase+RollbarNotifierTest.m +// +// +// Created by Andrey Kornich on 2022-06-15. +// + +#import "XCTestCase+RollbarNotifierTest.h" + +@implementation XCTestCase (RollbarNotifierTest) + +@end From 8606e405ede8a62e8fa7741ea14d7d556177e6f5 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 15 Jun 2022 22:17:37 -0700 Subject: [PATCH 019/127] test: RollbarSenderTests --- .../RollbarPayloadFactoryTests.m | 72 ++++++------- .../RollbarSenderTests.m | 102 +++++++++++++++++- .../XCTestCase+RollbarNotifierTest.h | 16 +++ .../XCTestCase+RollbarNotifierTest.m | 64 +++++++++++ 4 files changed, 207 insertions(+), 47 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m index 69e5f1b2..441450f9 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadFactoryTests.m @@ -6,6 +6,8 @@ // #import +#import "XCTestCase+RollbarNotifierTest.h" + #import "../../Sources/RollbarNotifier/RollbarPayloadFactory.h" @import UnitTesting; @@ -28,8 +30,8 @@ - (void)tearDown { - (void)testCrashReportPayload { NSString *crashReport = @"Fake crash report!"; - RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical - crashReport:crashReport]; + RollbarPayload *payload = [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical + crashReport:crashReport]; [self assertCommonComponentsOfPayload:payload]; @@ -45,10 +47,10 @@ - (void)testCrashReportPayload { - (void)testMessagePayload { NSString *message = @"MessageMock"; - RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical - message:message - data:nil - context:@"MockContext"]; + RollbarPayload *payload = [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical + message:message + data:nil + context:@"MockContext"]; [self assertCommonComponentsOfPayload:payload]; @@ -66,10 +68,10 @@ - (void)testMessagePayload { - (void)testErrorPayload { NSError *error = [NSError errorWithDomain:@"NSErrorDomain" code:1001 userInfo:nil]; - RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical - error:error - data:nil - context:@"MockContext"]; + RollbarPayload *payload = [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical + error:error + data:nil + context:@"MockContext"]; [self assertCommonComponentsOfPayload:payload]; @@ -88,10 +90,10 @@ - (void)testErrorPayload { - (void)testExceptionPayload { NSException *exception = [NSException exceptionWithName:@"Oy vey!" reason:@"Don't ask!" userInfo:nil]; - RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical - exception:exception - data:nil - context:@"MockContext"]; + RollbarPayload *payload = [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical + exception:exception + data:nil + context:@"MockContext"]; [self assertCommonComponentsOfPayload:payload]; @@ -111,8 +113,8 @@ - (void)testPerformanceCrashReportPayload { [self measureBlock:^{ - RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical - crashReport:crashReport]; + RollbarPayload *payload = [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical + crashReport:crashReport]; [payload serializeToJSONString]; }]; } @@ -123,10 +125,10 @@ - (void)testPerformanceMessagePayload { [self measureBlock:^{ - RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical - message:message - data:nil - context:@"MockContext"]; + RollbarPayload *payload = [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical + message:message + data:nil + context:@"MockContext"]; [payload serializeToJSONString]; }]; } @@ -137,10 +139,10 @@ - (void)testPerformanceErrorPayload { [self measureBlock:^{ - RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical - error:error - data:nil - context:@"MockContext"]; + RollbarPayload *payload = [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical + error:error + data:nil + context:@"MockContext"]; [payload serializeToJSONString]; }]; } @@ -151,10 +153,10 @@ - (void)testPerformanceExceptionPayload { [self measureBlock:^{ - RollbarPayload *payload = [[self getPayloadFactory] payloadWithLevel:RollbarLevel_Critical - exception:exception - data:nil - context:@"MockContext"]; + RollbarPayload *payload = [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical + exception:exception + data:nil + context:@"MockContext"]; [payload serializeToJSONString]; }]; } @@ -168,19 +170,5 @@ - (void)assertCommonComponentsOfPayload:(nullable RollbarPayload *)payload { //TODO: continue asserting presence and values of other expected common components of every payload... } -- (nonnull RollbarPayloadFactory *)getPayloadFactory { - - RollbarPayloadFactory *factory = [RollbarPayloadFactory factoryWithConfig:[self getConfig]]; - return factory; -} - -- (nonnull RollbarConfig*) getConfig { - - RollbarConfig *config = - [RollbarConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment]]; - - return config; -} @end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m index 1769f93a..3291e6eb 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m @@ -6,7 +6,12 @@ // #import +#import "XCTestCase+RollbarNotifierTest.h" + #import "../../Sources/RollbarNotifier/RollbarSender.h" +#import "../../Sources/RollbarNotifier/RollbarPayloadFactory.h" + +@import RollbarNotifier; @interface RollbarSenderTests : XCTestCase @@ -22,13 +27,100 @@ - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. } -- (void)testExample { - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct results. +- (void)testSendingCrashReport { + + RollbarPayload *payload =[self getPayload_CrashReport]; + NSData *payloadData = [payload serializeToJSONData]; + RollbarSender *sender = [RollbarSender new]; + RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; + + XCTAssertNotNil(reply); +} + +- (void)testPerformanceSendingCrashReport { + + RollbarPayload *payload =[self getPayload_CrashReport]; + NSData *payloadData = [payload serializeToJSONData]; + RollbarSender *sender = [RollbarSender new]; + + [self measureBlock:^{ + // Put the code you want to measure the time of here. + RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; + }]; +} + +- (void)testSendingMessage { + + RollbarPayload *payload =[self getPayload_Message]; + NSData *payloadData = [payload serializeToJSONData]; + RollbarSender *sender = [RollbarSender new]; + RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; + + XCTAssertNotNil(reply); } -- (void)testPerformanceExample { - // This is an example of a performance test case. +- (void)testPerformanceSendingMessage { + + RollbarPayload *payload =[self getPayload_Message]; + NSData *payloadData = [payload serializeToJSONData]; + RollbarSender *sender = [RollbarSender new]; + + [self measureBlock:^{ + // Put the code you want to measure the time of here. + RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; + }]; +} + +- (void)testSendingError { + +//TODO: implement... +// RollbarPayload *payload =[self getPayload_Message]; +// NSData *payloadData = [payload serializeToJSONData]; +// RollbarSender *sender = [RollbarSender new]; +// RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; +// +// XCTAssertNotNil(reply); +} + +- (void)testPerformanceSendingError { + + //TODO: implement... +// RollbarPayload *payload =[self getPayload_Message]; +// NSData *payloadData = [payload serializeToJSONData]; +// RollbarSender *sender = [RollbarSender new]; +// +// [self measureBlock:^{ +// // Put the code you want to measure the time of here. +// RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; +// }]; +} + +- (void)testSendingException { + + //TODO: implement... + // RollbarPayload *payload =[self getPayload_Message]; + // NSData *payloadData = [payload serializeToJSONData]; + // RollbarSender *sender = [RollbarSender new]; + // RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; + // + // XCTAssertNotNil(reply); +} + +- (void)testPerformanceSendingException { + + //TODO: implement... + // RollbarPayload *payload =[self getPayload_Message]; + // NSData *payloadData = [payload serializeToJSONData]; + // RollbarSender *sender = [RollbarSender new]; + // + // [self measureBlock:^{ + // // Put the code you want to measure the time of here. + // RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; + // }]; +} + +- (void)testPerformanceRollbarSenderInstantiation{ + [self measureBlock:^{ // Put the code you want to measure the time of here. RollbarSender *sender = [RollbarSender new]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h index 56675ef8..7fdf8e76 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h @@ -7,10 +7,26 @@ #import +@class RollbarConfig; +@class RollbarPayloadFactory; +@class RollbarPayload; + NS_ASSUME_NONNULL_BEGIN @interface XCTestCase (RollbarNotifierTest) +- (nonnull RollbarPayloadFactory *)getPayloadFactory_Live_Default; + +- (nonnull RollbarConfig*) getConfig_Live_Default; + +- (nonnull NSString *)getCrashReport_PLCrashReporter_Symbolicated; +- (nonnull NSString *)getMessageMock; + +- (nonnull RollbarPayload *)getPayload_CrashReport; +- (nonnull RollbarPayload *)getPayload_Message; + + + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m index 5bfe9e76..d4ab343f 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m @@ -6,7 +6,71 @@ // #import "XCTestCase+RollbarNotifierTest.h" +#import "TestData/CrashReports.h" + +#import "../../Sources/RollbarNotifier/RollbarPayloadFactory.h" + +@import RollbarNotifier; +@import UnitTesting; @implementation XCTestCase (RollbarNotifierTest) +- (nonnull RollbarPayloadFactory *)getPayloadFactory_Live_Default { + + RollbarPayloadFactory *factory = [RollbarPayloadFactory factoryWithConfig:[self getConfig_Live_Default]]; + return factory; +} + +- (nonnull RollbarConfig*) getConfig_Live_Default { + + RollbarConfig *config = + [RollbarConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; + + return config; +} + +- (nonnull NSString *)getContextMock { + + return @"Unit test context mock..."; +} + +- (nonnull NSDictionary *)getDataMock { + + return @{ + @"data1": @"data 1", + @"data2": @200, + }; +} + +- (nonnull NSString *)getCrashReport_PLCrashReporter_Symbolicated { + + return CRASH_REPORT_PLCRASH_SYMBOLICATED; +} + +- (nonnull NSString *)getMessageMock { + + return @"Unit test message mock..."; +} + + +- (nonnull RollbarPayload *)getPayload_CrashReport { + + RollbarPayload *payload = + [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical + crashReport:[self getCrashReport_PLCrashReporter_Symbolicated]]; + return payload; +} + +- (nonnull RollbarPayload *)getPayload_Message { + + RollbarPayload *payload = + [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Warning + message:[self getMessageMock] + data:[self getDataMock] + context:[self getContextMock] + ]; + return payload; +} + @end From bc055e18af5c053c3a92436ec101204725ced90d Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 16 Jun 2022 17:00:06 -0700 Subject: [PATCH 020/127] test: completed basic RollbarSenderTests --- .../RollbarSenderTests.m | 114 +++++++++--------- .../XCTestCase+RollbarNotifierTest.h | 6 +- .../XCTestCase+RollbarNotifierTest.m | 73 ++++++++++- 3 files changed, 132 insertions(+), 61 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m index 3291e6eb..8a13527a 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarSenderTests.m @@ -27,9 +27,34 @@ - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. } +#pragma mark - tests of live-sending of different payload types + - (void)testSendingCrashReport { - RollbarPayload *payload =[self getPayload_CrashReport]; + RollbarPayload *payload = [self getPayload_CrashReport]; + [self sendAndAssertPayload:payload]; +} + +- (void)testSendingMessage { + + RollbarPayload *payload = [self getPayload_Message]; + [self sendAndAssertPayload:payload]; +} + +- (void)testSendingError { + + RollbarPayload *payload = [self getPayload_Error]; + [self sendAndAssertPayload:payload]; +} + +- (void)testSendingException { + + RollbarPayload *payload = [self getPayload_Exception]; + [self sendAndAssertPayload:payload]; +} + +- (void)sendAndAssertPayload:(RollbarPayload *)payload { + NSData *payloadData = [payload serializeToJSONData]; RollbarSender *sender = [RollbarSender new]; RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; @@ -37,9 +62,19 @@ - (void)testSendingCrashReport { XCTAssertNotNil(reply); } +#pragma mark - performance tests + +- (void)testPerformanceRollbarSenderInstantiation{ + + [self measureBlock:^{ + // Put the code you want to measure the time of here. + RollbarSender *sender = [RollbarSender new]; + }]; +} + - (void)testPerformanceSendingCrashReport { - RollbarPayload *payload =[self getPayload_CrashReport]; + RollbarPayload *payload = [self getPayload_CrashReport]; NSData *payloadData = [payload serializeToJSONData]; RollbarSender *sender = [RollbarSender new]; @@ -49,19 +84,21 @@ - (void)testPerformanceSendingCrashReport { }]; } -- (void)testSendingMessage { +- (void)testPerformanceSendingMessage { - RollbarPayload *payload =[self getPayload_Message]; + RollbarPayload *payload = [self getPayload_Message]; NSData *payloadData = [payload serializeToJSONData]; RollbarSender *sender = [RollbarSender new]; - RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; - XCTAssertNotNil(reply); + [self measureBlock:^{ + // Put the code you want to measure the time of here. + RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; + }]; } -- (void)testPerformanceSendingMessage { +- (void)testPerformanceSendingError { - RollbarPayload *payload =[self getPayload_Message]; + RollbarPayload *payload = [self getPayload_Error]; NSData *payloadData = [payload serializeToJSONData]; RollbarSender *sender = [RollbarSender new]; @@ -71,60 +108,27 @@ - (void)testPerformanceSendingMessage { }]; } -- (void)testSendingError { - -//TODO: implement... -// RollbarPayload *payload =[self getPayload_Message]; -// NSData *payloadData = [payload serializeToJSONData]; -// RollbarSender *sender = [RollbarSender new]; -// RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; -// -// XCTAssertNotNil(reply); -} - -- (void)testPerformanceSendingError { +- (void)testPerformanceSendingException { - //TODO: implement... -// RollbarPayload *payload =[self getPayload_Message]; -// NSData *payloadData = [payload serializeToJSONData]; -// RollbarSender *sender = [RollbarSender new]; -// -// [self measureBlock:^{ -// // Put the code you want to measure the time of here. -// RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; -// }]; -} - -- (void)testSendingException { + RollbarPayload *payload = [self getPayload_Exception]; + //[self measureSendingPerformanceOfPayload:payload]; + NSData *payloadData = [payload serializeToJSONData]; + RollbarSender *sender = [RollbarSender new]; - //TODO: implement... - // RollbarPayload *payload =[self getPayload_Message]; - // NSData *payloadData = [payload serializeToJSONData]; - // RollbarSender *sender = [RollbarSender new]; - // RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; - // - // XCTAssertNotNil(reply); + [self measureBlock:^{ + // Put the code you want to measure the time of here. + RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; + }]; } -- (void)testPerformanceSendingException { +- (void)measureSendingPerformanceOfPayload:(RollbarPayload *)payload { + + NSData *payloadData = [payload serializeToJSONData]; + RollbarSender *sender = [RollbarSender new]; - //TODO: implement... - // RollbarPayload *payload =[self getPayload_Message]; - // NSData *payloadData = [payload serializeToJSONData]; - // RollbarSender *sender = [RollbarSender new]; - // - // [self measureBlock:^{ - // // Put the code you want to measure the time of here. - // RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; - // }]; -} - -- (void)testPerformanceRollbarSenderInstantiation{ - [self measureBlock:^{ // Put the code you want to measure the time of here. - RollbarSender *sender = [RollbarSender new]; + RollbarPayloadPostReply *reply = [sender sendPayload:payloadData usingConfig:[self getConfig_Live_Default]]; }]; } - @end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h index 7fdf8e76..1e597137 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h @@ -19,13 +19,13 @@ NS_ASSUME_NONNULL_BEGIN - (nonnull RollbarConfig*) getConfig_Live_Default; -- (nonnull NSString *)getCrashReport_PLCrashReporter_Symbolicated; +- (nonnull NSString *)getCrashReportMock; - (nonnull NSString *)getMessageMock; - (nonnull RollbarPayload *)getPayload_CrashReport; - (nonnull RollbarPayload *)getPayload_Message; - - +- (nonnull RollbarPayload *)getPayload_Error; +- (nonnull RollbarPayload *)getPayload_Exception; @end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m index d4ab343f..0b42fa04 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m @@ -30,6 +30,12 @@ - (nonnull RollbarConfig*) getConfig_Live_Default { return config; } +- (nonnull NSString *)getCrashReport_PLCrashReporter_Symbolicated { + + return CRASH_REPORT_PLCRASH_SYMBOLICATED; +} + + - (nonnull NSString *)getContextMock { return @"Unit test context mock..."; @@ -43,9 +49,9 @@ - (nonnull NSString *)getContextMock { }; } -- (nonnull NSString *)getCrashReport_PLCrashReporter_Symbolicated { +- (nonnull NSString *)getCrashReportMock { - return CRASH_REPORT_PLCRASH_SYMBOLICATED; + return [self getCrashReport_PLCrashReporter_Symbolicated]; } - (nonnull NSString *)getMessageMock { @@ -53,12 +59,51 @@ - (nonnull NSString *)getMessageMock { return @"Unit test message mock..."; } +- (nonnull NSError *)getErrorMock { + + NSError *error = [NSError errorWithDomain:@"NSErrorDomain" + code:101 + userInfo:@{ + @"Arror attribute 1":@"attr 1", + @"Arror attribute 2":@202, + }]; + + return error; +} + +- (nonnull NSException *)getExceptionMock { + + NSException *simulatedException = nil; + @try { + [self callWithTrouble]; + } @catch (NSException *exception) { + simulatedException = exception; + } @finally { + return simulatedException; + } +} + +- (void)callWithTrouble { + + [self simulateException]; +} + +- (void)simulateException { + + @throw [NSException exceptionWithName:NSGenericException //@"UnitTestException" + reason:@"simulation for a unit test" + userInfo:@{ + + }]; +} + +#pragma mark - different types of payloads - (nonnull RollbarPayload *)getPayload_CrashReport { RollbarPayload *payload = [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Critical - crashReport:[self getCrashReport_PLCrashReporter_Symbolicated]]; + crashReport:[self getCrashReportMock]]; return payload; } @@ -73,4 +118,26 @@ - (nonnull RollbarPayload *)getPayload_Message { return payload; } +- (nonnull RollbarPayload *)getPayload_Error { + + RollbarPayload *payload = + [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Warning + error:[self getErrorMock] + data:[self getDataMock] + context:[self getContextMock] + ]; + return payload; +} + +- (nonnull RollbarPayload *)getPayload_Exception { + + RollbarPayload *payload = + [[self getPayloadFactory_Live_Default] payloadWithLevel:RollbarLevel_Warning + exception:[self getExceptionMock] + data:[self getDataMock] + context:[self getContextMock] + ]; + return payload; +} + @end From 41871cbb2b1355de281bd4b845681edecc4515d5 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 21 Jun 2022 18:14:20 -0700 Subject: [PATCH 021/127] refactor: exception helpers --- .../Sources/RollbarNotifier/Rollbar.m | 28 ++++++++++++++++++- .../Sources/RollbarNotifier/include/Rollbar.h | 13 +++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m index b997b00e..18012343 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m +++ b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m @@ -11,6 +11,27 @@ #import "RollbarScrubbingOptions.h" #import "RollbarCrashProcessor.h" #import "RollbarSession.h" +#import "RollbarThread.h" +#import "RollbarLoggingOptions.h" + +static void uncaughtExceptionHandler(NSException * _Nonnull exception) { + NSArray *backtrace = [exception callStackSymbols]; + // NSString *platform = [[UIDevice currentDevice] platform]; + // NSString *version = [[UIDevice currentDevice] systemVersion]; + // NSString *message = [NSString stringWithFormat:@"Device: %@. OS: %@. Backtrace:\n%@", + // platform, + // version, + // backtrace]; + NSString *message = [NSString stringWithFormat:@"Backtrace:\n%@", + backtrace]; + + //TODO: complete implementation by calling RollbarInfrastructure logging method to capture the exception... + [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical + exception:exception + data:nil + context:message + ]; +} @implementation Rollbar @@ -75,6 +96,9 @@ + (void)initWithAccessToken:(nullable NSString *)accessToken config.destination.accessToken = accessToken; } + + //[[RollbarThread sharedInstance] setReportingRate:config.loggingOptions.maximumReportsPerMinute]; + [Rollbar updateConfiguration:config]; if (crashCollector) { @@ -472,7 +496,9 @@ + (void)criticalError:(NSError *)error data:(NSDictionary *)data + (void)sendJsonPayload:(NSData *)payload { - [logger sendPayload:payload]; + [[RollbarThread sharedInstance] sendPayload:payload + usingConfig:[Rollbar currentConfiguration] + ]; } #pragma mark - Telemetry API diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h index c25923bb..5f5d46b7 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h @@ -3,6 +3,7 @@ @import Foundation; +#import "RollbarInfrastructure.h" #import "RollbarLevel.h" #import "RollbarTelemetry.h" #import "RollbarTelemetryType.h" @@ -11,6 +12,18 @@ @class RollbarLogger; @protocol RollbarCrashCollector; +// Macros that help in throwing an exception with its source location metadata included: +#define __ThrowException(name, reason, class, function, file, line, info) [NSException exceptionWithName:name reason:[NSString stringWithFormat:@"%s:%i (%@:%s) %@", file, line, class, function, reason] userInfo:info]; +#define ThrowException(name, reason, info) __ThrowException(name, reason, [self class], _cmd, __FILE__, __LINE__, info) + +/// Globa;l uncaught exception handler that sends provided exception data to Rollbar via preconfigured RollbarInfrastructure's shared instnace. +/// @param exception an exception to report to Rolbar +// Add a call to the: NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler); +// to the end of your: -(BOOL)application:didFinishLaunchingWithOptions: method in AppDelegate. +// Make sure that the [RollbarInfrastructure sharedInstance] was already configured as early as possible within the: +// -(BOOL)application:didFinishLaunchingWithOptions: method in AppDelegate. +static void uncaughtExceptionHandler(NSException * _Nonnull exception); + @interface Rollbar : NSObject #pragma mark - Class Initializers From 20ecd993ea90acd0a79d13504032650d9c98f29b Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 21 Jun 2022 18:15:00 -0700 Subject: [PATCH 022/127] refactor: RollbarInfrastructure --- .../RollbarNotifier/RollbarInfrastructure.m | 102 +++++++++++++++++- .../include/RollbarInfrastructure.h | 11 +- 2 files changed, 102 insertions(+), 11 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index 7660ce29..cbb6b92d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -6,14 +6,20 @@ // #import "RollbarInfrastructure.h" +#import "RollbarConfig.h" +#import "RollbarLogger.h" -@implementation RollbarInfrastructure +const NSExceptionName RollbarInfrastructureNotConfiguredException; + +@implementation RollbarInfrastructure { + @private + RollbarConfig *_configuration; + RollbarLogger *_logger; + NSString *_oomDetectionFilePath; + NSString *_queuedItemsFilePath; + NSString *_stateFilePath; -- (nonnull instancetype)configureWith:(RollbarConfig *)rollbarConfig { - - self->_config = rollbarConfig; - return self; } #pragma mark - Sigleton pattern @@ -31,4 +37,90 @@ + (nonnull instancetype)sharedInstance { return singleton; } +#pragma mark - configuration + +- (nonnull instancetype)configureWith:(nonnull RollbarConfig *)rollbarConfig { + + [self assertValidConfiguration:rollbarConfig]; + + if (self->_configuration + && (NSOrderedSame == [[rollbarConfig serializeToJSONString] compare:[self->_configuration serializeToJSONString]]) + ) { + return self; // no need to reconfigure with an identical configuration... + } + + self->_configuration = rollbarConfig; + self->_logger = [RollbarLogger loggerWithConfiguration:rollbarConfig]; + return self; +} + +#pragma mark - properties + +- (nonnull RollbarConfig *)configuration { + + [self assertValidConfiguration:self->_configuration]; + if (YES == [self hasValidConfiguration]) { + return self->_configuration; + } + else { + [self raiseNotConfiguredException]; + return nil; + } +} + +- (nonnull RollbarLogger *)logger { + + if (self->_logger) { + return self->_logger; + } + else { + [self assertValidConfiguration:self->_configuration]; + [self raiseNotConfiguredException]; + return nil; + } +} + +#pragma mark - internal methods + +- (void)raiseNotConfiguredException { + [NSException raise:RollbarInfrastructureNotConfiguredException + format:@"Make sure the [[RollbarInfrastructure sharedInstance] configureWith:...] is called " + "providing a valid RollbarConfig instance!" + ]; +} + +- (BOOL)hasValidConfiguration { + + if (!self->_configuration) { + return NO; + } + + //TODO: complete full validation implementation... + + return YES; +} + +- (void)assertValidConfiguration:(nullable RollbarConfig *)config { + + NSAssert(config, + @"Provide valid configuration via [[RollbarInfrastructure sharedInstance] configureWith:...]!"); + + //TODO: complete full validation implementation... +} + +- (void)setupInternalStorage { + + //TODO: implement... +} + +- (void)setupConfigurableStorage { + + //TODO: implement... +} + +- (void)configureInfrastructure { + + //TODO: implement... +} + @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h index 042031a6..bb7da85d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h @@ -11,18 +11,16 @@ #import @class RollbarConfig; +@class RollbarLogger; NS_ASSUME_NONNULL_BEGIN @interface RollbarInfrastructure : NSObject -/// Current config object. -@property(readonly) RollbarConfig *config; +- (nonnull instancetype)configureWith:(nonnull RollbarConfig *)rollbarConfig; -- (nonnull instancetype)configureWith:(RollbarConfig *)rollbarConfig; - -/// Hides the initializer. -- (instancetype)init NS_UNAVAILABLE; +@property(readonly, nonnull) RollbarConfig *configuration; +@property(readonly, nonnull) RollbarLogger *logger; #pragma mark - Sigleton pattern @@ -34,6 +32,7 @@ NS_ASSUME_NONNULL_BEGIN + (id)copyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; + (id)mutableCopyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; +- (instancetype)init NS_UNAVAILABLE; - (void)dealloc NS_UNAVAILABLE; - (id)copy NS_UNAVAILABLE; - (id)mutableCopy NS_UNAVAILABLE; From 00b5479bf48d9517923ee2cab7118305c6046041 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 22 Jun 2022 00:11:40 -0700 Subject: [PATCH 023/127] refactor: RollbarInfrastructure --- .../DTOs/RollbarDeveloperOptions.m | 2 +- .../RollbarNotifier/RollbarInfrastructure.m | 74 +- .../Sources/RollbarNotifier/RollbarLogger.m | 1144 +---------------- .../RollbarNotifier/RollbarNotifierFiles.h | 2 +- .../RollbarNotifier/RollbarNotifierFiles.m | 2 +- .../RollbarNotifier/include/RollbarLogger.h | 54 +- 6 files changed, 168 insertions(+), 1110 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m index 1181c94f..8d56206f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m @@ -44,7 +44,7 @@ - (instancetype)initWithEnabled:(BOOL)enabled return [self initWithEnabled:enabled transmit:transmit logPayload:logPayload - payloadLogFile:[RollbarNotifierFiles payoadsLog] + payloadLogFile:[RollbarNotifierFiles payloadsLog] ]; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index cbb6b92d..a3804b9a 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -8,6 +8,7 @@ #import "RollbarInfrastructure.h" #import "RollbarConfig.h" #import "RollbarLogger.h" +#import "RollbarNotifierFiles.h" const NSExceptionName RollbarInfrastructureNotConfiguredException; @@ -18,8 +19,8 @@ @implementation RollbarInfrastructure { NSString *_oomDetectionFilePath; NSString *_queuedItemsFilePath; NSString *_stateFilePath; - - + NSString *_payloadsFilePath; + NSMutableDictionary *_queueState; } #pragma mark - Sigleton pattern @@ -51,6 +52,10 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)rollbarConfig { self->_configuration = rollbarConfig; self->_logger = [RollbarLogger loggerWithConfiguration:rollbarConfig]; + + [self setupInternalStorage]; + [self setupConfigurableStorage]; + return self; } @@ -110,12 +115,61 @@ - (void)assertValidConfiguration:(nullable RollbarConfig *)config { - (void)setupInternalStorage { - //TODO: implement... + // create working cache directory: + [RollbarCachesDirectory ensureCachesDirectoryExists]; + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + + // make sure we have all the data files set: + self->_queuedItemsFilePath = + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueue]]; + self->_stateFilePath = + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueueState]]; + + // create the queued items file if does not exist already: + if (![[NSFileManager defaultManager] fileExistsAtPath:self->_queuedItemsFilePath]) { + [[NSFileManager defaultManager] createFileAtPath:self->_queuedItemsFilePath + contents:nil + attributes:nil]; + } + + // create state tracking file if does not exist already: + if ([[NSFileManager defaultManager] fileExistsAtPath:self->_stateFilePath]) { + NSData *stateData = [NSData dataWithContentsOfFile:self->_stateFilePath]; + if (stateData) { + NSDictionary *state = [NSJSONSerialization JSONObjectWithData:stateData + options:0 + error:nil]; + self->_queueState = [state mutableCopy]; + } else { + RollbarSdkLog(@"There was an error restoring saved queue state"); + } + } + + // let's make sure we always recover into a good state if applicable: + if (!self->_queueState) { + self->_queueState = [@{ + @"offset": [NSNumber numberWithUnsignedInt:0], + @"retry_count": [NSNumber numberWithUnsignedInt:0] + } mutableCopy]; + [self saveQueueState]; + } } +//TODO: this method should go into RollbarLogger creation/initialization: - (void)setupConfigurableStorage { - //TODO: implement... + // create working cache directory: + [RollbarCachesDirectory ensureCachesDirectoryExists]; + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + + // make sure we have all the data files set: + self->_payloadsFilePath = + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsLog]]; + + // either create or overwrite the payloads log file: + [[NSFileManager defaultManager] createFileAtPath:self->_payloadsFilePath + contents:nil + attributes:nil]; } - (void)configureInfrastructure { @@ -123,4 +177,16 @@ - (void)configureInfrastructure { //TODO: implement... } +- (void)saveQueueState { + NSError *error; + NSData *data = [NSJSONSerialization rollbar_dataWithJSONObject:self->_queueState + options:0 + error:&error + safe:true]; + if (error) { + RollbarSdkLog(@"Error: %@", [error localizedDescription]); + } + [data writeToFile:self->_stateFilePath atomically:YES]; +} + @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index c2a67291..2ddff561 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -7,154 +7,66 @@ @import RollbarCommon; #import "RollbarLogger.h" -#import "RollbarLogger+Test.h" #import "RollbarThread.h" #import "RollbarTelemetryThread.h" #import "RollbarReachability.h" -#import +#import "RollbarPayloadFactory.h" #import "RollbarTelemetry.h" #import "RollbarPayloadTruncator.h" #import "RollbarConfig.h" +#import "RollbarNotifierFiles.h" #import "RollbarPayloadDTOs.h" #define MAX_PAYLOAD_SIZE 128 // The maximum payload size in kb -static NSString * const PAYLOADS_FILE_NAME = @"rollbar.payloads"; -static NSString * const QUEUED_ITEMS_FILE_NAME = @"rollbar.items"; -static NSString * const QUEUED_ITEMS_STATE_FILE_NAME = @"rollbar.state"; - -/// Rollbar API Service enforced payload rate limit: -static NSString * const RESPONSE_HEADER_RATE_LIMIT = @"x-rate-limit-limit"; -/// Rollbar API Service enforced remaining payload count until the limit is reached: -static NSString * const RESPONSE_HEADER_REMAINING_COUNT = @"x-rate-limit-remaining"; -/// Rollbar API Service enforced rate limit reset time for the current limit window: -static NSString * const RESPONSE_HEADER_RESET_TIME = @"x-rate-limit-reset"; -/// Rollbar API Service enforced rate limit remaining seconds of the current limit window: -static NSString * const RESPONSE_HEADER_REMAINING_SECONDS = @"x-rate-limit-remaining-seconds"; - -static NSUInteger MAX_RETRY_COUNT = 5; - static NSString *payloadsFilePath = nil; -static NSString *oomDetectionFilePath = nil; static NSString *queuedItemsFilePath = nil; -static NSString *stateFilePath = nil; -static NSMutableDictionary *queueState = nil; - -static RollbarThread *rollbarThread = nil; - -#if !TARGET_OS_WATCH -static RollbarReachability *reachability = nil; -static BOOL isNetworkReachable = YES; -#endif @implementation RollbarLogger { - NSDate *nextSendTime; @private NSDictionary *m_osData; } -static RollbarLogger *sharedSingleton = nil; - -/// This is essentially a static constructor for the type. -+ (void)initialize { - - if (self == [RollbarLogger class]) { - - // create working cache directory: - [RollbarCachesDirectory ensureCachesDirectoryExists]; - NSString *cachesDirectory = [RollbarCachesDirectory directory]; - - // make sure we have all the data files set: - queuedItemsFilePath = - [cachesDirectory stringByAppendingPathComponent:QUEUED_ITEMS_FILE_NAME]; - stateFilePath = - [cachesDirectory stringByAppendingPathComponent:QUEUED_ITEMS_STATE_FILE_NAME]; - payloadsFilePath = - [cachesDirectory stringByAppendingPathComponent:PAYLOADS_FILE_NAME]; +#pragma mark - factory methods - // either create or overwrite the payloads log file: - [[NSFileManager defaultManager] createFileAtPath:payloadsFilePath - contents:nil - attributes:nil]; - - // create the queued items file if does not exist already: - if (![[NSFileManager defaultManager] fileExistsAtPath:queuedItemsFilePath]) { - [[NSFileManager defaultManager] createFileAtPath:queuedItemsFilePath - contents:nil - attributes:nil]; - } - - // create state tracking file if does not exist already: - if ([[NSFileManager defaultManager] fileExistsAtPath:stateFilePath]) { - NSData *stateData = [NSData dataWithContentsOfFile:stateFilePath]; - if (stateData) { - NSDictionary *state = [NSJSONSerialization JSONObjectWithData:stateData - options:0 - error:nil]; - queueState = [state mutableCopy]; - } else { - RollbarSdkLog(@"There was an error restoring saved queue state"); - } - } - if (!queueState) { - queueState = [@{@"offset": [NSNumber numberWithUnsignedInt:0], - @"retry_count": [NSNumber numberWithUnsignedInt:0]} mutableCopy]; - [self saveQueueState]; - } - - RollbarConfig *config = [RollbarConfig new]; - - // Setup the worker thread that sends the items that have been queued up in the item file set above: - // TODO: !!! this needs to be redesigned taking in account multiple access tokens and endpoints !!! - RollbarLogger *logger = [[RollbarLogger alloc] initWithConfiguration:config]; - rollbarThread = - [[RollbarThread alloc] initWithNotifier:logger - reportingRate:config.loggingOptions.maximumReportsPerMinute]; - [rollbarThread start]; - -#if !TARGET_OS_WATCH - // Listen for reachability status so that the items are only sent when the internet is available: - reachability = [RollbarReachability reachabilityForInternetConnection]; - isNetworkReachable = [reachability isReachable]; - reachability.reachableBlock = ^(RollbarReachability*reach) { - [logger captureTelemetryDataForNetwork:true]; - isNetworkReachable = YES; - }; - reachability.unreachableBlock = ^(RollbarReachability*reach) { - [logger captureTelemetryDataForNetwork:false]; - isNetworkReachable = NO; - }; - - [reachability startNotifier]; -#endif - } +/// Logger factory method +/// @param accessToken a Rollbar project's access token ++ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken { + return [[RollbarLogger alloc] initWithAccessToken:accessToken]; } -+ (nonnull RollbarLogger *)sharedInstance { - @synchronized (self) { - if (sharedSingleton == nil) { - sharedSingleton = [[self alloc] init]; - } - return sharedSingleton; - } +/// Logger factory method +/// @param accessToken a Rollbar project's access token +/// @param environment a Rollbar project's environment ++ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken + andEnvironment:(nonnull NSString *)environment { + return [[RollbarLogger alloc] initWithAccessToken:accessToken andEnvironment:environment]; } -+ (nonnull RollbarLogger *)createLoggerWithConfig:(nonnull RollbarConfig *)config { - return [[self alloc] initWithConfiguration:config]; +/// Logger factory method +/// @param configuration the config object ++ (instancetype)loggerWithConfiguration:(nonnull RollbarConfig *)configuration { + return [[RollbarLogger alloc] initWithConfiguration:configuration]; } -/// Designated notifier initializer -/// @param accessToken the access token +#pragma mark - initializers + - (instancetype)initWithAccessToken:(NSString *)accessToken { RollbarConfig *config = [RollbarConfig new]; config.destination.accessToken = accessToken; return [self initWithConfiguration:config]; } -/// Designated notifier initializer -/// @param configuration the config object +- (instancetype)initWithAccessToken:(nonnull NSString *)accessToken + andEnvironment:(nonnull NSString *)environment { + RollbarConfig *config = [RollbarConfig new]; + config.destination.accessToken = accessToken; + config.destination.environment = environment; + return [self initWithConfiguration:config]; +} + - (instancetype)initWithConfiguration:(RollbarConfig *)configuration { if ((self = [super init])) { @@ -171,30 +83,25 @@ - (instancetype)initWithConfiguration:(RollbarConfig *)configuration { else { payloadsFilePath = - [cachesDirectory stringByAppendingPathComponent:PAYLOADS_FILE_NAME]; + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsLog]]; } - - self->nextSendTime = [[NSDate alloc] init]; } return self; } +#pragma mark - logging methods + - (void)logCrashReport:(NSString *)crashReport { - RollbarConfig *config = self.configuration; - - if (YES == [self shouldSkipReporting:config.loggingOptions.crashLevel]) { + if (YES == [self shouldSkipReporting:self.configuration.loggingOptions.crashLevel]) { return; } - RollbarPayload *payload = [self buildRollbarPayloadWithLevel:config.loggingOptions.crashLevel - message:nil - exception:nil - error:nil - extra:nil - crashReport:crashReport - context:nil]; + RollbarPayloadFactory *payloadFactory = [RollbarPayloadFactory factoryWithConfig:self.configuration]; + + RollbarPayload *payload = [payloadFactory payloadWithLevel:self.configuration.loggingOptions.crashLevel + crashReport:crashReport]; [self report:payload]; } @@ -207,14 +114,12 @@ - (void)log:(RollbarLevel)level return; } - RollbarPayload *payload = [self buildRollbarPayloadWithLevel:level - message:message - exception:nil - error:nil - extra:data - crashReport:nil - context:context - ]; + RollbarPayloadFactory *payloadFactory = [RollbarPayloadFactory factoryWithConfig:self.configuration]; + + RollbarPayload *payload = [payloadFactory payloadWithLevel:level + message:message + data:data + context:context]; [self report:payload]; } @@ -227,14 +132,12 @@ - (void)log:(RollbarLevel)level return; } - RollbarPayload *payload = [self buildRollbarPayloadWithLevel:level - message:nil - exception:exception - error:nil - extra:data - crashReport:nil - context:context - ]; + RollbarPayloadFactory *payloadFactory = [RollbarPayloadFactory factoryWithConfig:self.configuration]; + + RollbarPayload *payload = [payloadFactory payloadWithLevel:level + exception:exception + data:data + context:context]; [self report:payload]; } @@ -247,14 +150,12 @@ - (void)log:(RollbarLevel)level return; } - RollbarPayload *payload = [self buildRollbarPayloadWithLevel:level - message:nil - exception:nil - error:error - extra:data - crashReport:nil - context:context - ]; + RollbarPayloadFactory *payloadFactory = [RollbarPayloadFactory factoryWithConfig:self.configuration]; + + RollbarPayload *payload = [payloadFactory payloadWithLevel:level + error:error + data:data + context:context]; [self report:payload]; } @@ -273,432 +174,18 @@ - (BOOL)shouldSkipReporting:(RollbarLevel)level { return NO; } +#pragma mark - Payload queueing/reporting + - (void)report:(RollbarPayload *)payload { if (payload) { [self queuePayload:payload.jsonFriendlyData]; } } -+ (void)saveQueueState { - NSError *error; - NSData *data = [NSJSONSerialization rollbar_dataWithJSONObject:queueState - options:0 - error:&error - safe:true]; - if (error) { - RollbarSdkLog(@"Error: %@", [error localizedDescription]); - } - [data writeToFile:stateFilePath atomically:YES]; -} - -- (void)processSavedItems { - -#if !TARGET_OS_WATCH - if (!isNetworkReachable) { - RollbarSdkLog(@"Processing saved items: no network!"); - // Don't attempt sending if the network is known to be not reachable - return; - } -#endif - - NSUInteger startOffset = [queueState[@"offset"] unsignedIntegerValue]; - - NSFileHandle *fileHandle = - [NSFileHandle fileHandleForReadingAtPath:queuedItemsFilePath]; - [fileHandle seekToEndOfFile]; - __block unsigned long long fileLength = [fileHandle offsetInFile]; - [fileHandle closeFile]; - - if (!fileLength) { - if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { - RollbarSdkLog(@"Processing saved items: no queued items in the file!"); - } - return; - } - - // Empty out the queued item file if all items have been processed already - if (startOffset == fileLength) { - [@"" writeToFile:queuedItemsFilePath - atomically:YES - encoding:NSUTF8StringEncoding - error:nil]; - - queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:0]; - queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; - [RollbarLogger saveQueueState]; - if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { - RollbarSdkLog(@"Processing saved items: emptied the queued items file."); - } - - return; - } - - // Iterate through the items file and send the items in batches. - RollbarFileReader *reader = - [[RollbarFileReader alloc] initWithFilePath:queuedItemsFilePath - andOffset:startOffset]; - [reader enumerateLinesUsingBlock:^(NSString *line, NSUInteger nextOffset, BOOL *stop) { - NSData *lineData = [line dataUsingEncoding:NSUTF8StringEncoding]; - if (!lineData) { - // All we can do is ignore this line - RollbarSdkLog(@"Error converting file line to NSData: %@", line); - return; - } - NSError *error; - NSJSONReadingOptions serializationOptions = (NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves); - NSDictionary *payload = [NSJSONSerialization JSONObjectWithData:lineData - options:serializationOptions - error:&error]; - - if (!payload) { - // Ignore this line if it isn't valid json and proceed to the next line - RollbarSdkLog(@"Error restoring data from file to JSON: %@", error); - RollbarSdkLog(@"Raw data from file failed conversion to JSON:"); - RollbarSdkLog(@"%@", lineData); -// RollbarSdkLog(@" error code: %@", error.code); -// RollbarSdkLog(@" error domain: %@", error.domain); -// RollbarSdkLog(@" error description: %@", error.description); -// RollbarSdkLog(@" error localized description: %@", error.localizedDescription); -// RollbarSdkLog(@" error failure reason: %@", error.localizedFailureReason); -// RollbarSdkLog(@" error recovery option: %@", error.localizedRecoveryOptions); -// RollbarSdkLog(@" error recovery suggestion: %@", error.localizedRecoverySuggestion); - return; - } - - BOOL shouldContinue = [self sendItem:payload nextOffset:nextOffset]; - - if (!shouldContinue) { - // Stop processing the file so that the current file offset will be - // retried next time the file is processed - *stop = YES; - return; - } - - // The file has had items added since we started iterating through it, - // update the known file length to equal the next offset - if (nextOffset > fileLength) { - fileLength = nextOffset; - } - - }]; -} - -#pragma mark - Payload DTO builders - --(RollbarPerson *)buildRollbarPerson { - - RollbarConfig *config = self.configuration; - if (config && config.person && config.person.ID) { - return config.person; - } - else { - return nil; - } -} - --(RollbarServer *)buildRollbarServer { - - RollbarConfig *config = self.configuration; - if (config && config.server && !config.server.isEmpty) { - return [[RollbarServer alloc] initWithCpu:nil - serverConfig:config.server]; - } - else { - return nil; - } -} - --(NSDictionary *)buildOSData { - - if (self->m_osData) { - return self->m_osData; - } - - NSBundle *mainBundle = [NSBundle mainBundle]; - - NSString *version = nil; - RollbarConfig *config = self.configuration; - if (config - && config.loggingOptions - && config.loggingOptions.codeVersion - && config.loggingOptions.codeVersion.length > 0) { - - version = config.loggingOptions.codeVersion; - } - else { - version = [mainBundle objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey]; - } - - NSString *shortVersion = [mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; - NSString *bundleName = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey]; - NSString *bundleIdentifier = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleIdentifierKey]; - - struct utsname systemInfo; - uname(&systemInfo); - NSString *deviceCode = [NSString stringWithCString:systemInfo.machine - encoding:NSUTF8StringEncoding]; - -#if TARGET_OS_IOS | TARGET_OS_TV | TARGET_OS_MACCATALYST - self->m_osData = @{ - @"os": @"iOS", - @"os_version": [[UIDevice currentDevice] systemVersion], - @"device_code": deviceCode, - @"code_version": version ? version : @"", - @"short_version": shortVersion ? shortVersion : @"", - @"bundle_identifier": bundleIdentifier ? bundleIdentifier : @"", - @"app_name": bundleName ? bundleName : @"" - }; -#else - NSOperatingSystemVersion osVer = [[NSProcessInfo processInfo] operatingSystemVersion]; - self->m_osData = @{ - @"os": @"macOS", - @"os_version": [NSString stringWithFormat:@" %tu.%tu.%tu", - osVer.majorVersion, - osVer.minorVersion, - osVer.patchVersion - ], - @"device_code": deviceCode, - @"code_version": version ? version : @"", - @"short_version": shortVersion ? shortVersion : @"", - @"bundle_identifier": bundleIdentifier ? bundleIdentifier : @"", - @"app_name": bundleName ? bundleName : [[NSProcessInfo processInfo] processName] - }; -#endif - - return self->m_osData; -} - --(RollbarClient *)buildRollbarClient { - - NSNumber *timestamp = [NSNumber numberWithInteger:[[NSDate date] timeIntervalSince1970]]; - - RollbarConfig *config = self.configuration; - if (config && config.loggingOptions) { - switch(config.loggingOptions.captureIp) { - case RollbarCaptureIpType_Full: - return [[RollbarClient alloc] initWithDictionary:@{ - @"timestamp": timestamp, - @"ios": [self buildOSData], - @"user_ip": @"$remote_ip" - }]; - case RollbarCaptureIpType_Anonymize: - return [[RollbarClient alloc] initWithDictionary:@{ - @"timestamp": timestamp, - @"ios": [self buildOSData], - @"user_ip": @"$remote_ip_anonymize" - }]; - case RollbarCaptureIpType_None: - //no op - break; - } - } - - return [[RollbarClient alloc] initWithDictionary:@{ - @"timestamp": timestamp, - @"ios": [self buildOSData], - }]; -} - --(RollbarModule *)buildRollbarNotifierModule { - - RollbarConfig *config = self.configuration; - if (config && config.notifier && !config.notifier.isEmpty) { - - RollbarModule *notifierModule = - [[RollbarModule alloc] initWithDictionary:config.notifier.jsonFriendlyData.copy]; - [notifierModule setData:config.jsonFriendlyData byKey:@"configured_options"]; - return notifierModule; - } - - return nil; -} - --(RollbarPayload *)buildRollbarPayloadWithLevel:(RollbarLevel)level - message:(NSString *)message - exception:(NSException *)exception - error:(NSError *)error - extra:(NSDictionary *)extra - crashReport:(NSString *)crashReport - context:(NSString *)context { - - // check critical config settings: - RollbarConfig *config = self.configuration; - if (!config - || !config.destination - || !config.destination.environment - || config.destination.environment.length == 0) { - - return nil; - } - - // compile payload data proper body: - RollbarBody *body = [RollbarBody alloc]; - if (crashReport) { - body = [body initWithCrashReport:crashReport]; - } - else if (error) { - body = [body initWithError:error]; - } - else if (exception) { - body = [body initWithException:exception]; - } - else if (message) { - body = [body initWithMessage:message]; - } - else { - return nil; - } - - if (!body) { - return nil; - } - - // this is done only for backward compatibility for customers that used to rely on this undocumented - // extra data with a message: - if (message && extra) { - [body.message setData:extra byKey:@"extra"]; - } - - // compile payload data: - RollbarData *data = [[RollbarData alloc] initWithEnvironment:config.destination.environment - body:body]; - if (!data) { - return nil; - } - - NSMutableDictionary *customData = - [NSMutableDictionary dictionaryWithDictionary:self.configuration.customData]; - if (crashReport || exception) { - // neither crash report no exception payload objects have placeholders for any extra data - // or an extra message, let's preserve them as the custom data: - if (extra) { - customData[@"error.extra"] = extra; - } - if (message && message.length > 0) { - customData[@"error.message"] = message; - } - } - - data.level = level; - data.language = RollbarAppLanguage_ObjectiveC; - data.platform = @"client"; - data.uuid = [NSUUID UUID]; - data.custom = [[RollbarDTO alloc] initWithDictionary:customData]; - data.notifier = [self buildRollbarNotifierModule]; - data.person = [self buildRollbarPerson]; - data.server = [self buildRollbarServer]; - data.client = [self buildRollbarClient]; - if (context && context.length > 0) { - data.context = context; - } - if (config.loggingOptions) { - data.framework = config.loggingOptions.framework; - if (config.loggingOptions.requestId - && (config.loggingOptions.requestId.length > 0)) { - - [data setData:config.loggingOptions.requestId byKey:@"requestId"]; - } - } - - // Transform payload data, if necessary - if ([self shouldIgnoreRollbarData:data]) { - return nil; - } - data = [self modifyRollbarData:data]; - data = [self scrubRollbarData:data]; - - RollbarPayload *payload = [[RollbarPayload alloc] initWithAccessToken:config.destination.accessToken - data:data]; - - return payload; -} - --(BOOL)shouldIgnoreRollbarData:(nonnull RollbarData *)incomingData { - - BOOL shouldIgnore = NO; - if (self.configuration.checkIgnoreRollbarData) { - @try { - shouldIgnore = self.configuration.checkIgnoreRollbarData(incomingData); - return shouldIgnore; - } @catch(NSException *e) { - RollbarSdkLog(@"checkIgnore error: %@", e.reason); - - // Remove checkIgnore to prevent future exceptions - self.configuration.checkIgnoreRollbarData = nil; - return NO; - } - } - - return shouldIgnore; -} - --(RollbarData *)modifyRollbarData:(nonnull RollbarData *)incomingData { - - if (self.configuration.modifyRollbarData) { - return self.configuration.modifyRollbarData(incomingData); - } - return incomingData; -} - --(RollbarData *)scrubRollbarData:(nonnull RollbarData *)incomingData { - - NSSet *scrubFieldsSet = [self getScrubFields]; - if (!scrubFieldsSet || scrubFieldsSet.count == 0) { - return incomingData; - } - - NSMutableDictionary *mutableJsonFriendlyData = incomingData.jsonFriendlyData.mutableCopy; - for (NSString *key in scrubFieldsSet) { - if ([mutableJsonFriendlyData valueForKeyPath:key]) { - [self createMutablePayloadWithData:mutableJsonFriendlyData forPath:key]; - [mutableJsonFriendlyData setValue:@"*****" forKeyPath:key]; - } - } - - return [[RollbarData alloc] initWithDictionary:mutableJsonFriendlyData]; -} - --(NSSet *)getScrubFields { - - RollbarConfig *config = self.configuration; - if (!config - || !config.dataScrubber - || config.dataScrubber.isEmpty - || !config.dataScrubber.enabled - || !config.dataScrubber.scrubFields - || config.dataScrubber.scrubFields.count == 0) { - - return [NSSet set]; - } - - NSMutableSet *actualFieldsToScrub = config.dataScrubber.scrubFields.mutableCopy; - if (config.dataScrubber.safeListFields.count > 0) { - // actualFieldsToScrub = - // config.dataScrubber.scrubFields - config.dataScrubber.whitelistFields - // while using case insensitive field name comparison: - actualFieldsToScrub = [NSMutableSet new]; - for(NSString *key in config.dataScrubber.scrubFields) { - BOOL isWhitelisted = false; - for (NSString *whiteKey in config.dataScrubber.safeListFields) { - if (NSOrderedSame == [key caseInsensitiveCompare:whiteKey]) { - isWhitelisted = true; - } - } - if (!isWhitelisted) { - [actualFieldsToScrub addObject:key]; - } - } - } - - return actualFieldsToScrub; -} - -#pragma mark - LEGACY payload data builders - - (void)queuePayload:(NSDictionary *)payload { [self performSelector:@selector(queuePayload_OnlyCallOnThread:) - onThread:rollbarThread + onThread:[RollbarThread sharedInstance] withObject:payload waitUntilDone:NO ]; @@ -726,363 +213,6 @@ - (void)queuePayload_OnlyCallOnThread:(NSDictionary *)payload { [[RollbarTelemetry sharedInstance] clearAllData]; } -- (BOOL)sendItem:(NSDictionary *)payload - nextOffset:(NSUInteger)nextOffset { - - RollbarPayload *rollbarPayload = - [[RollbarPayload alloc] initWithDictionary:[payload copy]]; - if (nil == rollbarPayload) { - - RollbarSdkLog( - @"Couldn't init and send RollbarPayload with data: %@", - payload - ); -// queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; -// queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; -// [RollbarLogger saveQueueState]; - return YES; // no retry needed - } - - NSMutableDictionary *newPayload = - [NSMutableDictionary dictionaryWithDictionary:payload]; - [RollbarPayloadTruncator truncatePayload:newPayload]; - if (nil == newPayload) { - - RollbarSdkLog( - @"Couldn't send truncated payload that is nil" - ); -// queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; -// queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; -// [RollbarLogger saveQueueState]; - return YES; // no retry needed - } - - NSError *error; - NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:newPayload - options:0 - error:&error - safe:true]; - if (nil == jsonPayload) { - - RollbarSdkLog( - @"Couldn't send jsonPayload that is nil" - ); - if (nil != error) { - - RollbarSdkLog( - @" DETAILS: an error while generating JSON data: %@", - error - ); - } -// queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; -// queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; -// [RollbarLogger saveQueueState]; - return YES; // no retry needed - } - - if (NSOrderedDescending != [nextSendTime compare: [[NSDate alloc] init] ]) { - - NSUInteger retryCount = - [queueState[@"retry_count"] unsignedIntegerValue]; - - RollbarConfig *rollbarConfig = - [[RollbarConfig alloc] initWithDictionary:rollbarPayload.data.notifier.jsonFriendlyData[@"configured_options"]]; - - if (0 == retryCount && YES == rollbarConfig.developerOptions.logPayload) { - if (NO == rollbarConfig.developerOptions.suppressSdkInfoLogging) { - RollbarSdkLog(@"About to send payload: %@", - [[NSString alloc] initWithData:jsonPayload - encoding:NSUTF8StringEncoding] - ); - } - - // - save this payload into a proper payloads log file: - //***************************************************** - - // compose the payloads log file path: - NSString *cachesDirectory = [RollbarCachesDirectory directory]; - NSString *payloadsLogFilePath = - [cachesDirectory stringByAppendingPathComponent:rollbarConfig.developerOptions.payloadLogFile]; - - [RollbarFileWriter appendSafelyData:jsonPayload toFile:payloadsLogFilePath]; - } - - BOOL success = - rollbarConfig ? [self sendPayload:jsonPayload usingConfig:rollbarConfig] - : [self sendPayload:jsonPayload]; // backward compatibility with just upgraded very old SDKs... - - if (!success) { - - if (retryCount < MAX_RETRY_COUNT) { - - queueState[@"retry_count"] = - [NSNumber numberWithUnsignedInteger:retryCount + 1]; - - [RollbarLogger saveQueueState]; - - // Return NO so that the current batch will be retried next time - return NO; - } - } - } - else { - - RollbarSdkLog( - @"Omitting payload until nextSendTime is reached: %@", - [[NSString alloc] initWithData:jsonPayload encoding:NSUTF8StringEncoding] - ); - } - - queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; - queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; - [RollbarLogger saveQueueState]; - - return YES; -} - -- (BOOL)sendPayload:(nonnull NSData *)payload - usingConfig:(nonnull RollbarConfig *)config { - - if ((nil == payload) - || (nil == self.configuration) - || (nil == self.configuration.destination) - || (nil == self.configuration.destination.endpoint) - || (nil == self.configuration.destination.accessToken) - || (0 == self.configuration.destination.endpoint.length) - || (0 == self.configuration.destination.accessToken.length) - ) { - - return NO; - } - - NSURL *url = [NSURL URLWithString:config.destination.endpoint]; - if (nil == url) { - return NO; - } - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - - [request setHTTPMethod:@"POST"]; - [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - [request setValue:config.destination.accessToken forHTTPHeaderField:@"X-Rollbar-Access-Token"]; - [request setHTTPBody:payload]; - - if (YES == config.developerOptions.logPayload) { - NSString *payloadString = [[NSString alloc]initWithData:payload - encoding:NSUTF8StringEncoding - ]; - NSLog(@"%@", payloadString); - //TODO: if config.developerOptions.logPayloadFile is defined, save the payload into the file... - } - - if (NO == config.developerOptions.transmit) { - return YES; // we just successfully short-circuit here... - } - - __block BOOL result = NO; - - // This requires iOS 7.0+ - dispatch_semaphore_t sem = dispatch_semaphore_create(0); - - NSURLSession *session = [NSURLSession sharedSession]; - - if (config.httpProxy.enabled - || config.httpsProxy.enabled) { - - NSDictionary *connectionProxyDictionary = - @{ - @"HTTPEnable" : [NSNumber numberWithBool:config.httpProxy.enabled], - @"HTTPProxy" : config.httpProxy.proxyUrl, - @"HTTPPort" : [NSNumber numberWithUnsignedInteger:config.httpProxy.proxyPort], - @"HTTPSEnable" : [NSNumber numberWithBool:config.httpsProxy.enabled], - @"HTTPSProxy" : config.httpsProxy.proxyUrl, - @"HTTPSPort" : [NSNumber numberWithUnsignedInteger:config.httpsProxy.proxyPort] - }; - - NSURLSessionConfiguration *sessionConfig = - [NSURLSessionConfiguration ephemeralSessionConfiguration]; - sessionConfig.connectionProxyDictionary = connectionProxyDictionary; - session = [NSURLSession sessionWithConfiguration:sessionConfig]; - } - - NSURLSessionDataTask *dataTask = - [session dataTaskWithRequest:request - completionHandler:^( - NSData * _Nullable data, - NSURLResponse * _Nullable response, - NSError * _Nullable error) { - result = [self checkPayloadResponse:response - error:error - data:data]; - dispatch_semaphore_signal(sem); - }]; - [dataTask resume]; - - dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); - - return result; -} - -/// This is a DEPRECATED method left for some backward compatibility for very old clients eventually moving to this more recent implementation. -/// Use/maintain sendPayload:usingConfig: instead! -- (BOOL)sendPayload:(NSData *)payload { - - if ((nil == payload) - || (nil == self.configuration) - || (nil == self.configuration.destination) - || (nil == self.configuration.destination.endpoint) - || (nil == self.configuration.destination.accessToken) - || (0 == self.configuration.destination.endpoint.length) - || (0 == self.configuration.destination.accessToken.length) - ) { - - return NO; - } - - NSURL *url = [NSURL URLWithString:self.configuration.destination.endpoint]; - if (nil == url) { - return NO; - } - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - - [request setHTTPMethod:@"POST"]; - [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - [request setValue:self.configuration.destination.accessToken forHTTPHeaderField:@"X-Rollbar-Access-Token"]; - [request setHTTPBody:payload]; - - if (YES == self.configuration.developerOptions.logPayload) { - NSString *payloadString = [[NSString alloc]initWithData:payload - encoding:NSUTF8StringEncoding - ]; - NSLog(@"%@", payloadString); - //TODO: if self.configuration.logPayloadFile is defined, save the payload into the file... - } - - if (NO == self.configuration.developerOptions.transmit) { - return YES; // we just successfully short-circuit here... - } - - __block BOOL result = NO; - - // This requires iOS 7.0+ - dispatch_semaphore_t sem = dispatch_semaphore_create(0); - - NSURLSession *session = [NSURLSession sharedSession]; - - if (self.configuration.httpProxy.enabled - || self.configuration.httpsProxy.enabled) { - - NSDictionary *connectionProxyDictionary = - @{ - @"HTTPEnable" : [NSNumber numberWithInt:self.configuration.httpProxy.enabled], - @"HTTPProxy" : self.configuration.httpProxy.proxyUrl, - @"HTTPPort" : @(self.configuration.httpProxy.proxyPort), - @"HTTPSEnable" : [NSNumber numberWithInt:self.configuration.httpsProxy.enabled], - @"HTTPSProxy" : self.configuration.httpsProxy.proxyUrl, - @"HTTPSPort" : @(self.configuration.httpsProxy.proxyPort) - }; - - NSURLSessionConfiguration *sessionConfig = - [NSURLSessionConfiguration ephemeralSessionConfiguration]; - sessionConfig.connectionProxyDictionary = connectionProxyDictionary; - session = [NSURLSession sessionWithConfiguration:sessionConfig]; - } - - NSURLSessionDataTask *dataTask = - [session dataTaskWithRequest:request - completionHandler:^( - NSData * _Nullable data, - NSURLResponse * _Nullable response, - NSError * _Nullable error) { - result = [self checkPayloadResponse:response - error:error - data:data]; - dispatch_semaphore_signal(sem); - }]; - [dataTask resume]; - - dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); - - return result; -} - -- (BOOL)checkPayloadResponse:(NSURLResponse *)response - error:(NSError *)error - data:(NSData *)data { - - if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { - - RollbarSdkLog(@"HTTP response from Rollbar: %@", response); - } - - // Lookup rate limiting headers and adjust reporting rate accordingly: - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; - NSDictionary *httpHeaders = [httpResponse allHeaderFields]; - //int rateLimit = [[httpHeaders valueForKey:RESPONSE_HEADER_RATE_LIMIT] intValue]; - int rateLimitLeft = - [[httpHeaders valueForKey:RESPONSE_HEADER_REMAINING_COUNT] intValue]; - int rateLimitSeconds = - [[httpHeaders valueForKey:RESPONSE_HEADER_REMAINING_SECONDS] intValue]; - if (rateLimitLeft > 0) { - nextSendTime = [[NSDate alloc] init]; - } - else { - nextSendTime = - [[NSDate alloc] initWithTimeIntervalSinceNow:rateLimitSeconds]; - } - - if (error) { - RollbarSdkLog(@"There was an error reporting to Rollbar"); - RollbarSdkLog(@"Error: %@", [error localizedDescription]); - } else { - NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; - if ([httpResponse statusCode] == 200) { - if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { - RollbarSdkLog(@"Success"); - } - return YES; - } else { - RollbarSdkLog(@"There was a problem reporting to Rollbar"); - if (data) { - RollbarSdkLog( - @"Response: %@", - [NSJSONSerialization JSONObjectWithData:data - options:0 - error:nil]); - } - } - } - return NO; -} - -#pragma mark - Payload truncate - -- (void)createMutablePayloadWithData:(NSMutableDictionary *)data - forPath:(NSString *)path { - - NSArray *pathComponents = [path componentsSeparatedByString:@"."]; - NSString *currentPath = @""; - - for (int i=0; i *)readLogItemsFromStore { - - NSString *filePath = [RollbarLogger _logItemsStorePath]; - return [RollbarLogger readPayloadsDataFromFile:filePath]; -} - -+ (nonnull NSArray *)readPayloadsFromSdkLog { - - NSString *filePath = [RollbarLogger _payloadsLogStorePath]; - return [RollbarLogger readPayloadsDataFromFile:filePath]; -} - -+ (nonnull NSArray *)readPayloadsDataFromFile:(nonnull NSString *)filePath { - - RollbarFileReader *reader = [[RollbarFileReader alloc] initWithFilePath:filePath - andOffset:0]; - - NSMutableArray *items = [NSMutableArray array]; - [reader enumerateLinesUsingBlock:^(NSString *line, NSUInteger nextOffset, BOOL *stop) { - NSError *error = nil; - NSMutableDictionary *payload = - [NSJSONSerialization JSONObjectWithData:[line dataUsingEncoding:NSUTF8StringEncoding] - options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) - error:&error - ]; - if ((nil == payload) && (nil != error)) { - RollbarSdkLog(@"Error serializing log item from the store: %@", [error localizedDescription]); - return; - } - else if (nil == payload) { - RollbarSdkLog(@"Error serializing log item from the store!"); - return; - } - - NSMutableDictionary *data = payload[@"data"]; - [items addObject:data]; - }]; - - return items; -} - -+ (void)flushRollbarThread { - - [RollbarLogger performSelector:@selector(_test_doNothing) - onThread:[RollbarLogger _test_rollbarThread] - withObject:nil - waitUntilDone:YES - ]; -} - -+ (void)_clearFile:(nonnull NSString *)filePath { - - NSFileManager *fileManager = [NSFileManager defaultManager]; - NSError *error; - BOOL fileExists = [fileManager fileExistsAtPath:filePath]; - - if (fileExists) { - BOOL success = [fileManager removeItemAtPath:filePath - error:&error]; - if (!success) { - NSLog(@"Error: %@", [error localizedDescription]); - } - [[NSFileManager defaultManager] createFileAtPath:filePath - contents:nil - attributes:nil]; - } -} -+ (nonnull NSString *)_logItemsStorePath { - - return [RollbarLogger _getSDKDataFilePath:QUEUED_ITEMS_FILE_NAME]; + //[[RollbarThread sharedInstance] cancel]; + //[[RollbarThread sharedInstance] setReportingRate:maximumReportsPerMinute]; + //[[RollbarThread sharedInstance] start]; } - -+ (nonnull NSString *)_logItemsStoreStatePath { - return [RollbarLogger _getSDKDataFilePath:QUEUED_ITEMS_STATE_FILE_NAME]; -} - -+ (nonnull NSString *)_telemetryItemsStorePath { - - return [RollbarLogger _getSDKDataFilePath:QUEUED_TELEMETRY_ITEMS_FILE_NAME]; -} - -+ (nonnull NSString *)_payloadsLogStorePath { - - return [RollbarLogger _getSDKDataFilePath:PAYLOADS_FILE_NAME]; -} - -+ (nonnull NSString *)_getSDKDataFilePath:(nonnull NSString *)sdkFileName { - - NSString *cachesDirectory = [RollbarCachesDirectory directory]; - return [cachesDirectory stringByAppendingPathComponent:sdkFileName]; -} - -+ (NSThread *)_test_rollbarThread { - - return rollbarThread; -} - -+ (void)_test_doNothing { - - // no-Op simulation... -} - @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h index 64025479..148ccf2e 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h @@ -22,7 +22,7 @@ NS_ASSUME_NONNULL_BEGIN + (nonnull NSString * const)appQuit; -+ (nonnull NSString * const)payoadsLog; ++ (nonnull NSString * const)payloadsLog; + (nonnull NSString * const)config; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m index bc8bd775..284ad229 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m @@ -39,7 +39,7 @@ + (nonnull NSString * const)appQuit { return APP_QUIT_FILE_NAME; } -+ (nonnull NSString * const)payoadsLog { ++ (nonnull NSString * const)payloadsLog { return PAYLOADS_FILE_NAME; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h index c724ddb1..088868db 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h @@ -12,31 +12,49 @@ NS_ASSUME_NONNULL_BEGIN /// Models interface of a Rollbar logger @interface RollbarLogger : NSObject -/// The shared instance of the logger -+ (nonnull RollbarLogger *)sharedInstance; +#pragma mark - factory methods -/// Creates new instance of the logger using provided configuration instance -/// @param config configuration to be used by the new instance of the logger -+ (nonnull RollbarLogger *)createLoggerWithConfig:(nonnull RollbarConfig *)config; +/// Logger factory method +/// @param accessToken a Rollbar project's access token ++ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken; -/// Notifier's config object -@property (nullable, atomic, strong) RollbarConfig *configuration; +/// Logger factory method +/// @param accessToken a Rollbar project's access token +/// @param environment a Rollbar project's environment ++ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken + andEnvironment:(nonnull NSString *)environment; -/// Disallowed initializer -- (instancetype)init -NS_UNAVAILABLE; +/// Logger factory method +/// @param configuration the config object ++ (instancetype)loggerWithConfiguration:(nonnull RollbarConfig *)configuration; -/// Designated notifier initializer -/// @param accessToken the access token +#pragma mark - initializers + +/// Logger initializer +/// @param accessToken a Rollbar project's access token - (instancetype)initWithAccessToken:(nonnull NSString *)accessToken; -/// Designated notifier initializer +/// Logger initializer +/// @param accessToken a Rollbar project's access token +/// @param environment a Rollbar project's environment +- (instancetype)initWithAccessToken:(nonnull NSString *)accessToken + andEnvironment:(nonnull NSString *)environment; + +/// Designated logger initializer /// @param configuration the config object - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration NS_DESIGNATED_INITIALIZER; -/// Processes persisted payloads -- (void)processSavedItems; +/// Disallowed initializer +- (instancetype)init +NS_UNAVAILABLE; + +#pragma mark - properties + +/// Notifier's config object +@property (nullable, atomic, strong) RollbarConfig *configuration; + +#pragma mark - logging methods /// Captures a crash report /// @param crashReport the crash report @@ -77,14 +95,14 @@ NS_DESIGNATED_INITIALIZER; /// @param nextOffset the offset in the item queue file of the item immediately after this batch. /// If the send is successful or the retry limit is hit, nextOffset will be saved to the queueState as the offset to use for the next batch /// @return YES if this batch should be discarded if it was successful or a retry limit was hit. Otherwise NO is returned if this batch should be retried. -- (BOOL)sendItem:(nonnull NSDictionary *)payload - nextOffset:(NSUInteger)nextOffset; +//- (BOOL)sendItem:(nonnull NSDictionary *)payload +// nextOffset:(NSUInteger)nextOffset; /// Sends a fully composed JSON payload. /// @param payload complete Rollbar payload as JSON string /// @return YES if successful. NO if not. -- (BOOL)sendPayload:(nonnull NSData *)payload; +//- (BOOL)sendPayload:(nonnull NSData *)payload; /// Updates key configuration elements /// @param configuration the Rollbar configuration object From e2a9a2c9bce6c5714a1fbc8875c228ff00caec25 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 22 Jun 2022 11:27:22 -0700 Subject: [PATCH 024/127] refactor: RollbarInfrastructure --- .../RollbarNotifier/RollbarInfrastructure.m | 38 +++---------------- 1 file changed, 5 insertions(+), 33 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index a3804b9a..b68b71d7 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -1,10 +1,3 @@ -// -// RollbarInfrastructure.m -// -// -// Created by Andrey Kornich on 2022-06-09. -// - #import "RollbarInfrastructure.h" #import "RollbarConfig.h" #import "RollbarLogger.h" @@ -51,10 +44,9 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)rollbarConfig { } self->_configuration = rollbarConfig; - self->_logger = [RollbarLogger loggerWithConfiguration:rollbarConfig]; + self->_logger = nil; [self setupInternalStorage]; - [self setupConfigurableStorage]; return self; } @@ -75,14 +67,11 @@ - (nonnull RollbarConfig *)configuration { - (nonnull RollbarLogger *)logger { - if (self->_logger) { - return self->_logger; - } - else { - [self assertValidConfiguration:self->_configuration]; - [self raiseNotConfiguredException]; - return nil; + if (!self->_logger) { + self->_logger = [RollbarLogger loggerWithConfiguration:self.configuration]; } + + return self->_logger; } #pragma mark - internal methods @@ -155,23 +144,6 @@ - (void)setupInternalStorage { } } -//TODO: this method should go into RollbarLogger creation/initialization: -- (void)setupConfigurableStorage { - - // create working cache directory: - [RollbarCachesDirectory ensureCachesDirectoryExists]; - NSString *cachesDirectory = [RollbarCachesDirectory directory]; - - // make sure we have all the data files set: - self->_payloadsFilePath = - [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsLog]]; - - // either create or overwrite the payloads log file: - [[NSFileManager defaultManager] createFileAtPath:self->_payloadsFilePath - contents:nil - attributes:nil]; -} - - (void)configureInfrastructure { //TODO: implement... From ac15ad993b19c6904b1c777814b8e2edbc393d09 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 22 Jun 2022 11:28:42 -0700 Subject: [PATCH 025/127] refactor: RollbarInfrastructure --- .../RollbarInfrastructureTests.m | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m new file mode 100644 index 00000000..27cd1aac --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -0,0 +1,36 @@ +// +// RollbarInfrastructureTests.m +// +// +// Created by Andrey Kornich on 2022-06-22. +// + +#import + +@interface RollbarInfrastructureTests : XCTestCase + +@end + +@implementation RollbarInfrastructureTests + +- (void)setUp { + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. +} + +- (void)testExample { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end From b0538d0998d8c544d3f268053a2791064fc48b71 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 23 Jun 2022 00:22:25 -0700 Subject: [PATCH 026/127] test: RollbarInfrastructure --- .../RollbarInfrastructureTests.m | 37 ++++++++++++++----- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index 27cd1aac..e76dc568 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -1,12 +1,7 @@ -// -// RollbarInfrastructureTests.m -// -// -// Created by Andrey Kornich on 2022-06-22. -// - #import +@import RollbarNotifier; + @interface RollbarInfrastructureTests : XCTestCase @end @@ -21,9 +16,31 @@ - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. } -- (void)testExample { - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct results. +- (void)testRollbarInfrastructureNotConfiguredException { + +// XCTAssertThrowsSpecificNamed([RollbarInfrastructure sharedInstance].configuration, +// NSException, +// @"RollbarInfrastructureNotConfiguredException", +// @"An RollbarInfrastructureNotConfiguredException is expected!"); +// XCTAssertThrowsSpecificNamed([RollbarInfrastructure sharedInstance].logger, +// NSException, +// @"RollbarInfrastructureNotConfiguredException", +// @"An RollbarInfrastructureNotConfiguredException is expected!"); + XCTAssertThrows([RollbarInfrastructure sharedInstance].configuration, + @"An RollbarInfrastructureNotConfiguredException is expected!" + ); + XCTAssertThrows([RollbarInfrastructure sharedInstance].logger, + @"An RollbarInfrastructureNotConfiguredException is expected!" + ); + + [[RollbarInfrastructure sharedInstance] configureWith:[RollbarConfig new]]; + + XCTAssertNoThrow([RollbarInfrastructure sharedInstance].configuration, + @"An RollbarInfrastructureNotConfiguredException is NOT expected!" + ); + XCTAssertNoThrow([RollbarInfrastructure sharedInstance].logger, + @"An RollbarInfrastructureNotConfiguredException is NOT expected!" + ); } - (void)testPerformanceExample { From 5fd0ff858f507fede7166c91cf9258f692646eb8 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 23 Jun 2022 22:34:50 -0700 Subject: [PATCH 027/127] test: RollbarInfrastructureTests --- .../RollbarInfrastructureTests.m | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index e76dc568..db55ad5c 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -43,11 +43,11 @@ - (void)testRollbarInfrastructureNotConfiguredException { ); } -- (void)testPerformanceExample { - // This is an example of a performance test case. - [self measureBlock:^{ - // Put the code you want to measure the time of here. - }]; -} +//- (void)testPerformanceExample { +// // This is an example of a performance test case. +// [self measureBlock:^{ +// // Put the code you want to measure the time of here. +// }]; +//} @end From ea1c8b5f488eedc9cf01aa5c4a0dd2c7b060675e Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 23 Jun 2022 22:35:41 -0700 Subject: [PATCH 028/127] refactor: RollbarThread --- .../Sources/RollbarNotifier/RollbarThread.h | 41 +- .../Sources/RollbarNotifier/RollbarThread.m | 654 +++++++++++++++++- 2 files changed, 667 insertions(+), 28 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h index 38f12483..9a6d3147 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h @@ -1,20 +1,43 @@ @import Foundation; -@class RollbarLogger; +@class RollbarConfig; + +NS_ASSUME_NONNULL_BEGIN @interface RollbarThread : NSThread +/// Signifies that the thread is active or not. +@property(atomic) BOOL active; + +- (BOOL)sendPayload:(nonnull NSData *)payload + usingConfig:(nonnull RollbarConfig *)config; + +/// Hides the initializer. +- (instancetype)init NS_UNAVAILABLE; + /// Hides the initializer. -- (instancetype)init +- (instancetype)initWithTarget:(id)target + selector:(SEL)selector + object:(nullable id)argument NS_UNAVAILABLE; -/// Initializer -/// @param logger a Rollbar logger to use. -/// @param reportsPerMinute maximum allowed reporting rate. -- (instancetype)initWithNotifier:(RollbarLogger*)logger - reportingRate:(NSUInteger)reportsPerMinute; +- (instancetype)initWithBlock:(void (^)(void))block NS_UNAVAILABLE; -/// Signifies that the thread is active or not. -@property(atomic) BOOL active; + +#pragma mark - Sigleton pattern + ++ (nonnull instancetype)sharedInstance; + ++ (instancetype)new NS_UNAVAILABLE; ++ (instancetype)allocWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; ++ (instancetype)alloc NS_UNAVAILABLE; ++ (id)copyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; ++ (id)mutableCopyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE; + +- (void)dealloc NS_UNAVAILABLE; +- (id)copy NS_UNAVAILABLE; +- (id)mutableCopy NS_UNAVAILABLE; @end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 6ae5e250..a83bf162 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -4,35 +4,179 @@ #import "RollbarLogger.h" #import "RollbarConfig.h" #import "RollbarDeveloperOptions.h" +#import "RollbarReachability.h" +#import "RollbarTelemetry.h" +#import "RollbarTelemetryOptions.h" +#import "RollbarNotifierFiles.h" +#import "RollbarPayload.h" +#import "RollbarPayloadTruncator.h" +#import "RollbarData.h" +#import "RollbarModule.h" +#import "RollbarDestination.h" +#import "RollbarProxy.h" + +static NSUInteger MAX_RETRY_COUNT = 5; + +/// Rollbar API Service enforced payload rate limit: +static NSString * const RESPONSE_HEADER_RATE_LIMIT = @"x-rate-limit-limit"; +/// Rollbar API Service enforced remaining payload count until the limit is reached: +static NSString * const RESPONSE_HEADER_REMAINING_COUNT = @"x-rate-limit-remaining"; +/// Rollbar API Service enforced rate limit reset time for the current limit window: +static NSString * const RESPONSE_HEADER_RESET_TIME = @"x-rate-limit-reset"; +/// Rollbar API Service enforced rate limit remaining seconds of the current limit window: +static NSString * const RESPONSE_HEADER_REMAINING_SECONDS = @"x-rate-limit-remaining-seconds"; @implementation RollbarThread { - @private RollbarLogger *_logger; - @private NSUInteger _maxReportsPerMinute; - @private NSTimer *_timer; -} -- (instancetype)initWithNotifier:(RollbarLogger*)logger - reportingRate:(NSUInteger)reportsPerMinute { +@private + //RollbarLogger *_logger; + NSUInteger _maxReportsPerMinute; + NSTimer *_timer; + + NSString *_queuedItemsFilePath; + NSString *_stateFilePath; + NSMutableDictionary *_queueState; + NSDate *_nextSendTime; + +#if !TARGET_OS_WATCH + RollbarReachability *_reachability; + BOOL _isNetworkReachable; +#endif +} + +- (instancetype)initWithTarget:(id)target + selector:(SEL)selector + object:(nullable id)argument { + if ((self = [super initWithTarget:self selector:@selector(run) object:nil])) { - self.name = @"RollbarThread"; - _logger = logger; - - if(reportsPerMinute > 0) { - _maxReportsPerMinute = reportsPerMinute; - } else { - _maxReportsPerMinute = 60; - } + [self setupDataStorage]; + self->_maxReportsPerMinute = 60; + self->_reachability = nil; + self->_isNetworkReachable = YES; + self->_nextSendTime = [[NSDate alloc] init]; + + self.name = [RollbarThread rollbar_objectClassName];//NSStringFromClass([RollbarThread class]); self.active = YES; + + +#if !TARGET_OS_WATCH + // Listen for reachability status so that the items are only sent when the internet is available: + self->_reachability = [RollbarReachability reachabilityForInternetConnection]; + self->_isNetworkReachable = [self->_reachability isReachable]; + + __weak typeof(self) weakSelf = self; + //OR __unsafe_unretained typeof(self) weakSelf = self; + self->_reachability.reachableBlock = ^(RollbarReachability*reach) { + [weakSelf captureTelemetryDataForNetwork:true]; + self->_isNetworkReachable = YES; + }; + self->_reachability.unreachableBlock = ^(RollbarReachability*reach) { + [weakSelf captureTelemetryDataForNetwork:false]; + self->_isNetworkReachable = NO; + }; + + [self->_reachability startNotifier]; +#endif + } return self; } +- (void)setupDataStorage { + + // create working cache directory: + [RollbarCachesDirectory ensureCachesDirectoryExists]; + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + + // make sure we have all the data files set: + self->_queuedItemsFilePath = + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueue]]; + self->_stateFilePath = + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueueState]]; +// payloadsFilePath = +// [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payoadsLog]]; + + // either create or overwrite the payloads log file: +// [[NSFileManager defaultManager] createFileAtPath:payloadsFilePath +// contents:nil +// attributes:nil]; + + // create the queued items file if does not exist already: + if (![[NSFileManager defaultManager] fileExistsAtPath:self->_queuedItemsFilePath]) { + [[NSFileManager defaultManager] createFileAtPath:self->_queuedItemsFilePath + contents:nil + attributes:nil]; + } + + // create state tracking file if does not exist already: + if ([[NSFileManager defaultManager] fileExistsAtPath:self->_stateFilePath]) { + NSData *stateData = [NSData dataWithContentsOfFile:self->_stateFilePath]; + if (stateData) { + + NSDictionary *state = [NSJSONSerialization JSONObjectWithData:stateData + options:0 + error:nil]; + self->_queueState = [state mutableCopy]; + } else { + + RollbarSdkLog(@"There was an error restoring saved queue state"); + } + } + if (!self->_queueState) { + + self->_queueState = [@{ + @"offset": [NSNumber numberWithUnsignedInt:0], + @"retry_count": [NSNumber numberWithUnsignedInt:0] + } mutableCopy]; + + [self saveQueueState]; + } +} + +- (void)saveQueueState { + + NSError *error; + NSData *data = [NSJSONSerialization rollbar_dataWithJSONObject:self->_queueState + options:0 + error:&error + safe:true]; + if (error) { + + RollbarSdkLog(@"Error: %@", [error localizedDescription]); + } + [data writeToFile:self->_stateFilePath atomically:YES]; +} + +- (void)setReportingRate:(NSUInteger)reportsPerMinute { + +// NSAssert(reportsPerMinute > 0, @"reportsPerMinute must be greater than zero!"); +// +// BOOL wasExecuting = self.isExecuting; +// if (wasExecuting) { +// +// [self cancel]; +// } +// +// if(reportsPerMinute > 0) { +// _maxReportsPerMinute = reportsPerMinute; +// } else { +// _maxReportsPerMinute = 60; +// } +// +// self.active = YES; +// +// if (wasExecuting) { +// +// [self start]; +// } +} + - (void)checkItems { if (self.cancelled) { @@ -45,12 +189,12 @@ - (void)checkItems { @autoreleasepool { - if ((nil != _logger) && (NO == _logger.configuration.developerOptions.suppressSdkInfoLogging)) { +// if ((nil != _logger) && (NO == _logger.configuration.developerOptions.suppressSdkInfoLogging)) { +// +// RollbarSdkLog(@"Checking items..."); +// } - RollbarSdkLog(@"Checking items..."); - } - - [_logger processSavedItems]; + [self processSavedItems]; } } @@ -76,4 +220,476 @@ - (void)run { } } +- (void)processSavedItems { + +#if !TARGET_OS_WATCH + if (!self->_isNetworkReachable) { + RollbarSdkLog(@"Processing saved items: no network!"); + // Don't attempt sending if the network is known to be not reachable + return; + } +#endif + + NSUInteger startOffset = [self->_queueState[@"offset"] unsignedIntegerValue]; + + NSFileHandle *fileHandle = + [NSFileHandle fileHandleForReadingAtPath:self->_queuedItemsFilePath]; + [fileHandle seekToEndOfFile]; + __block unsigned long long fileLength = [fileHandle offsetInFile]; + [fileHandle closeFile]; + + if (!fileLength) { + +// if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { +// +// RollbarSdkLog(@"Processing saved items: no queued items in the file!"); +// } + return; + } + + // Empty out the queued item file if all items have been processed already + if (startOffset == fileLength) { + [@"" writeToFile:self->_queuedItemsFilePath + atomically:YES + encoding:NSUTF8StringEncoding + error:nil]; + + self->_queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:0]; + self->_queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; + [self saveQueueState]; +// if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { +// +// RollbarSdkLog(@"Processing saved items: emptied the queued items file."); +// } + + return; + } + + // Iterate through the items file and send the items in batches. + RollbarFileReader *reader = + [[RollbarFileReader alloc] initWithFilePath:self->_queuedItemsFilePath + andOffset:startOffset]; + [reader enumerateLinesUsingBlock:^(NSString *line, NSUInteger nextOffset, BOOL *stop) { + + NSData *lineData = [line dataUsingEncoding:NSUTF8StringEncoding]; + if (!lineData) { + // All we can do is ignore this line + RollbarSdkLog(@"Error converting file line to NSData: %@", line); + return; + } + NSError *error; + NSJSONReadingOptions serializationOptions = (NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves); + NSDictionary *payload = [NSJSONSerialization JSONObjectWithData:lineData + options:serializationOptions + error:&error]; + + if (!payload) { + // Ignore this line if it isn't valid json and proceed to the next line + RollbarSdkLog(@"Error restoring data from file to JSON: %@", error); + RollbarSdkLog(@"Raw data from file failed conversion to JSON:"); + RollbarSdkLog(@"%@", lineData); + // RollbarSdkLog(@" error code: %@", error.code); + // RollbarSdkLog(@" error domain: %@", error.domain); + // RollbarSdkLog(@" error description: %@", error.description); + // RollbarSdkLog(@" error localized description: %@", error.localizedDescription); + // RollbarSdkLog(@" error failure reason: %@", error.localizedFailureReason); + // RollbarSdkLog(@" error recovery option: %@", error.localizedRecoveryOptions); + // RollbarSdkLog(@" error recovery suggestion: %@", error.localizedRecoverySuggestion); + return; + } + + BOOL shouldContinue = [self sendItem:payload nextOffset:nextOffset]; + + if (!shouldContinue) { + // Stop processing the file so that the current file offset will be + // retried next time the file is processed + *stop = YES; + return; + } + + // The file has had items added since we started iterating through it, + // update the known file length to equal the next offset + if (nextOffset > fileLength) { + fileLength = nextOffset; + } + + }]; +} + +- (BOOL)sendItem:(NSDictionary *)payload + nextOffset:(NSUInteger)nextOffset { + + RollbarPayload *rollbarPayload = + [[RollbarPayload alloc] initWithDictionary:[payload copy]]; + if (nil == rollbarPayload) { + + RollbarSdkLog( + @"Couldn't init and send RollbarPayload with data: %@", + payload + ); + // queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; + // queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; + // [RollbarLogger saveQueueState]; + return YES; // no retry needed + } + + NSMutableDictionary *newPayload = + [NSMutableDictionary dictionaryWithDictionary:payload]; + [RollbarPayloadTruncator truncatePayload:newPayload]; + if (nil == newPayload) { + + RollbarSdkLog( + @"Couldn't send truncated payload that is nil" + ); + // queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; + // queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; + // [RollbarLogger saveQueueState]; + return YES; // no retry needed + } + + NSError *error; + NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:newPayload + options:0 + error:&error + safe:true]; + if (nil == jsonPayload) { + + RollbarSdkLog( + @"Couldn't send jsonPayload that is nil" + ); + if (nil != error) { + + RollbarSdkLog( + @" DETAILS: an error while generating JSON data: %@", + error + ); + } + // queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; + // queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; + // [RollbarLogger saveQueueState]; + return YES; // no retry needed + } + + if (NSOrderedDescending != [self->_nextSendTime compare: [[NSDate alloc] init] ]) { + + NSUInteger retryCount = + [self->_queueState[@"retry_count"] unsignedIntegerValue]; + + RollbarConfig *rollbarConfig = + [[RollbarConfig alloc] initWithDictionary:rollbarPayload.data.notifier.jsonFriendlyData[@"configured_options"]]; + + if (0 == retryCount && YES == rollbarConfig.developerOptions.logPayload) { + + if (NO == rollbarConfig.developerOptions.suppressSdkInfoLogging) { + + RollbarSdkLog(@"About to send payload: %@", + [[NSString alloc] initWithData:jsonPayload + encoding:NSUTF8StringEncoding] + ); + } + + // - save this payload into a proper payloads log file: + //***************************************************** + + // compose the payloads log file path: + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + NSString *payloadsLogFilePath = + [cachesDirectory stringByAppendingPathComponent:rollbarConfig.developerOptions.payloadLogFile]; + + [RollbarFileWriter appendSafelyData:jsonPayload toFile:payloadsLogFilePath]; + } + + BOOL success = + rollbarConfig ? [self sendPayload:jsonPayload usingConfig:rollbarConfig] + : [self sendPayload:jsonPayload]; // backward compatibility with just upgraded very old SDKs... + + if (!success) { + + if (retryCount < MAX_RETRY_COUNT) { + + self->_queueState[@"retry_count"] = + [NSNumber numberWithUnsignedInteger:retryCount + 1]; + + [self saveQueueState]; + + // Return NO so that the current batch will be retried next time + return NO; + } + } + } + else { + + RollbarSdkLog( + @"Omitting payload until nextSendTime is reached: %@", + [[NSString alloc] initWithData:jsonPayload encoding:NSUTF8StringEncoding] + ); + } + + self->_queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; + self->_queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; + [self saveQueueState]; + + return YES; +} + +- (BOOL)sendPayload:(nonnull NSData *)payload + usingConfig:(nonnull RollbarConfig *)config { + + if (!payload || !config) { + + return NO; + } + + NSURL *url = [NSURL URLWithString:config.destination.endpoint]; + if (nil == url) { + return NO; + } + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + + [request setHTTPMethod:@"POST"]; + [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + [request setValue:config.destination.accessToken forHTTPHeaderField:@"X-Rollbar-Access-Token"]; + [request setHTTPBody:payload]; + + if (YES == config.developerOptions.logPayload) { + NSString *payloadString = [[NSString alloc]initWithData:payload + encoding:NSUTF8StringEncoding + ]; + NSLog(@"%@", payloadString); + //TODO: if config.developerOptions.logPayloadFile is defined, save the payload into the file... + } + + if (NO == config.developerOptions.transmit) { + return YES; // we just successfully short-circuit here... + } + + __block BOOL result = NO; + + // This requires iOS 7.0+ + dispatch_semaphore_t sem = dispatch_semaphore_create(0); + + NSURLSession *session = [NSURLSession sharedSession]; + + if (config.httpProxy.enabled + || config.httpsProxy.enabled) { + + NSDictionary *connectionProxyDictionary = + @{ + @"HTTPEnable" : [NSNumber numberWithBool:config.httpProxy.enabled], + @"HTTPProxy" : config.httpProxy.proxyUrl, + @"HTTPPort" : [NSNumber numberWithUnsignedInteger:config.httpProxy.proxyPort], + @"HTTPSEnable" : [NSNumber numberWithBool:config.httpsProxy.enabled], + @"HTTPSProxy" : config.httpsProxy.proxyUrl, + @"HTTPSPort" : [NSNumber numberWithUnsignedInteger:config.httpsProxy.proxyPort] + }; + + NSURLSessionConfiguration *sessionConfig = + [NSURLSessionConfiguration ephemeralSessionConfiguration]; + sessionConfig.connectionProxyDictionary = connectionProxyDictionary; + session = [NSURLSession sessionWithConfiguration:sessionConfig]; + } + + NSURLSessionDataTask *dataTask = + [session dataTaskWithRequest:request + completionHandler:^( + NSData * _Nullable data, + NSURLResponse * _Nullable response, + NSError * _Nullable error) { + result = [self checkPayloadResponse:response + error:error + data:data]; + dispatch_semaphore_signal(sem); + }]; + [dataTask resume]; + + dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); + + return result; +} + +/// This is a DEPRECATED method left for some backward compatibility for very old clients eventually moving to this more recent implementation. +/// Use/maintain sendPayload:usingConfig: instead! +- (BOOL)sendPayload:(NSData *)payload { + + return NO; +// if ((nil == payload) +// || (nil == self.configuration) +// || (nil == self.configuration.destination) +// || (nil == self.configuration.destination.endpoint) +// || (nil == self.configuration.destination.accessToken) +// || (0 == self.configuration.destination.endpoint.length) +// || (0 == self.configuration.destination.accessToken.length) +// ) { +// +// return NO; +// } +// +// NSURL *url = [NSURL URLWithString:self.configuration.destination.endpoint]; +// if (nil == url) { +// return NO; +// } +// NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; +// +// [request setHTTPMethod:@"POST"]; +// [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; +// [request setValue:self.configuration.destination.accessToken forHTTPHeaderField:@"X-Rollbar-Access-Token"]; +// [request setHTTPBody:payload]; +// +// if (YES == self.configuration.developerOptions.logPayload) { +// NSString *payloadString = [[NSString alloc]initWithData:payload +// encoding:NSUTF8StringEncoding +// ]; +// NSLog(@"%@", payloadString); +// //TODO: if self.configuration.logPayloadFile is defined, save the payload into the file... +// } +// +// if (NO == self.configuration.developerOptions.transmit) { +// return YES; // we just successfully short-circuit here... +// } +// +// __block BOOL result = NO; +// +// // This requires iOS 7.0+ +// dispatch_semaphore_t sem = dispatch_semaphore_create(0); +// +// NSURLSession *session = [NSURLSession sharedSession]; +// +// if (self.configuration.httpProxy.enabled +// || self.configuration.httpsProxy.enabled) { +// +// NSDictionary *connectionProxyDictionary = +// @{ +// @"HTTPEnable" : [NSNumber numberWithInt:self.configuration.httpProxy.enabled], +// @"HTTPProxy" : self.configuration.httpProxy.proxyUrl, +// @"HTTPPort" : @(self.configuration.httpProxy.proxyPort), +// @"HTTPSEnable" : [NSNumber numberWithInt:self.configuration.httpsProxy.enabled], +// @"HTTPSProxy" : self.configuration.httpsProxy.proxyUrl, +// @"HTTPSPort" : @(self.configuration.httpsProxy.proxyPort) +// }; +// +// NSURLSessionConfiguration *sessionConfig = +// [NSURLSessionConfiguration ephemeralSessionConfiguration]; +// sessionConfig.connectionProxyDictionary = connectionProxyDictionary; +// session = [NSURLSession sessionWithConfiguration:sessionConfig]; +// } +// +// NSURLSessionDataTask *dataTask = +// [session dataTaskWithRequest:request +// completionHandler:^( +// NSData * _Nullable data, +// NSURLResponse * _Nullable response, +// NSError * _Nullable error) { +// result = [self checkPayloadResponse:response +// error:error +// data:data]; +// dispatch_semaphore_signal(sem); +// }]; +// [dataTask resume]; +// +// dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); +// +// return result; +} + +- (BOOL)checkPayloadResponse:(NSURLResponse *)response + error:(NSError *)error + data:(NSData *)data { + +// if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { +// +// RollbarSdkLog(@"HTTP response from Rollbar: %@", response); +// } + + // Lookup rate limiting headers and adjust reporting rate accordingly: + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; + NSDictionary *httpHeaders = [httpResponse allHeaderFields]; + //int rateLimit = [[httpHeaders valueForKey:RESPONSE_HEADER_RATE_LIMIT] intValue]; + int rateLimitLeft = + [[httpHeaders valueForKey:RESPONSE_HEADER_REMAINING_COUNT] intValue]; + int rateLimitSeconds = + [[httpHeaders valueForKey:RESPONSE_HEADER_REMAINING_SECONDS] intValue]; + if (rateLimitLeft > 0) { + + self->_nextSendTime = [[NSDate alloc] init]; + } + else { + + self->_nextSendTime = + [[NSDate alloc] initWithTimeIntervalSinceNow:rateLimitSeconds]; + } + + if (error) { + RollbarSdkLog(@"There was an error reporting to Rollbar"); + RollbarSdkLog(@"Error: %@", [error localizedDescription]); + } else { + NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; + if ([httpResponse statusCode] == 200) { + +// if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { +// +// RollbarSdkLog(@"Success"); +// } + return YES; + } else { + + RollbarSdkLog(@"There was a problem reporting to Rollbar"); + if (data) { + RollbarSdkLog( + @"Response: %@", + [NSJSONSerialization JSONObjectWithData:data + options:0 + error:nil]); + } + } + } + return NO; +} + +#pragma mark - Network telemetry data + +- (void)captureTelemetryDataForNetwork:(BOOL)reachable { + +#if !TARGET_OS_WATCH + if ([RollbarTelemetry sharedInstance].telemetryOptions.captureConnectivity + && self->_isNetworkReachable != reachable) { + + NSString *status = reachable ? @"Connected" : @"Disconnected"; + NSString *networkType = @"Unknown"; + NetworkStatus networkStatus = [self->_reachability currentReachabilityStatus]; + switch(networkStatus) { + case ReachableViaWiFi: + networkType = @"WiFi"; + break; + case ReachableViaWWAN: + networkType = @"Cellular"; + break; + default: + // no-op... + break; + } + [[RollbarTelemetry sharedInstance] recordConnectivityEventForLevel:RollbarLevel_Warning + status:status + extraData:@{@"network": networkType} + ]; + } +#endif +} + +#pragma mark - Sigleton pattern + ++ (nonnull instancetype)sharedInstance { + + static id singleton; + static dispatch_once_t onceToken; + + dispatch_once(&onceToken, ^{ + + singleton = [[self alloc] initWithTarget:self + selector:@selector(run) + object:nil]; + }); + + return singleton; +} + @end From 3efe1dc43884a8f48d80c06b7ac20e06ca403ede Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 23 Jun 2022 22:36:28 -0700 Subject: [PATCH 029/127] feat: RollbarInfrastrucure --- .../Sources/RollbarNotifier/RollbarInfrastructure.m | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index b68b71d7..a566e194 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -3,8 +3,6 @@ #import "RollbarLogger.h" #import "RollbarNotifierFiles.h" -const NSExceptionName RollbarInfrastructureNotConfiguredException; - @implementation RollbarInfrastructure { @private RollbarConfig *_configuration; @@ -77,7 +75,7 @@ - (nonnull RollbarLogger *)logger { #pragma mark - internal methods - (void)raiseNotConfiguredException { - [NSException raise:RollbarInfrastructureNotConfiguredException + [NSException raise:@"RollbarInfrastructureNotConfiguredException" format:@"Make sure the [[RollbarInfrastructure sharedInstance] configureWith:...] is called " "providing a valid RollbarConfig instance!" ]; From f390b716a3d72485884a1df199f829bdd513af6c Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 23 Jun 2022 22:37:12 -0700 Subject: [PATCH 030/127] refactor: RollbarLogger --- .../RollbarNotifier/RollbarLogger+Test.m | 131 ++++++++++++++++++ .../Sources/RollbarNotifier/RollbarLogger.m | 2 +- 2 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m new file mode 100644 index 00000000..40359e31 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m @@ -0,0 +1,131 @@ +#import "RollbarLogger+Test.h" +#import "RollbarNotifierFiles.h" +#import "RollbarThread.h" + +@import RollbarCommon; + +@implementation RollbarLogger (Test) + ++ (void)clearSdkDataStore { + + [RollbarLogger clearLogItemsStore]; + [RollbarLogger _clearFile:[RollbarLogger _telemetryItemsStorePath]]; + [RollbarLogger _clearFile:[RollbarLogger _payloadsLogStorePath]]; +} + ++ (void)clearLogItemsStore { + + [RollbarLogger _clearFile:[RollbarLogger _logItemsStoreStatePath]]; + [RollbarLogger _clearFile:[RollbarLogger _logItemsStorePath]]; +} + ++ (void)clearSdkFile:(nonnull NSString *)sdkFileName { + + [RollbarLogger _clearFile:[RollbarLogger _getSDKDataFilePath:sdkFileName]]; +} + ++ (nonnull NSArray *)readLogItemsFromStore { + + NSString *filePath = [RollbarLogger _logItemsStorePath]; + return [RollbarLogger readPayloadsDataFromFile:filePath]; +} + ++ (nonnull NSArray *)readPayloadsFromSdkLog { + + NSString *filePath = [RollbarLogger _payloadsLogStorePath]; + return [RollbarLogger readPayloadsDataFromFile:filePath]; +} + ++ (nonnull NSArray *)readPayloadsDataFromFile:(nonnull NSString *)filePath { + + RollbarFileReader *reader = [[RollbarFileReader alloc] initWithFilePath:filePath + andOffset:0]; + + NSMutableArray *items = [NSMutableArray array]; + [reader enumerateLinesUsingBlock:^(NSString *line, NSUInteger nextOffset, BOOL *stop) { + NSError *error = nil; + NSMutableDictionary *payload = + [NSJSONSerialization JSONObjectWithData:[line dataUsingEncoding:NSUTF8StringEncoding] + options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) + error:&error + ]; + if ((nil == payload) && (nil != error)) { + RollbarSdkLog(@"Error serializing log item from the store: %@", [error localizedDescription]); + return; + } + else if (nil == payload) { + RollbarSdkLog(@"Error serializing log item from the store!"); + return; + } + + NSMutableDictionary *data = payload[@"data"]; + [items addObject:data]; + }]; + + return items; +} + ++ (void)flushRollbarThread { + + [RollbarLogger performSelector:@selector(_test_doNothing) + onThread:[RollbarLogger _test_rollbarThread] + withObject:nil + waitUntilDone:YES + ]; +} + ++ (void)_clearFile:(nonnull NSString *)filePath { + + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSError *error; + BOOL fileExists = [fileManager fileExistsAtPath:filePath]; + + if (fileExists) { + BOOL success = [fileManager removeItemAtPath:filePath + error:&error]; + if (!success) { + NSLog(@"Error: %@", [error localizedDescription]); + } + [[NSFileManager defaultManager] createFileAtPath:filePath + contents:nil + attributes:nil]; + } +} + ++ (nonnull NSString *)_logItemsStorePath { + + return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles itemsQueue]]; +} + ++ (nonnull NSString *)_logItemsStoreStatePath { + + return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles itemsQueueState]]; +} + ++ (nonnull NSString *)_telemetryItemsStorePath { + + return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles telemetryQueue]]; +} + ++ (nonnull NSString *)_payloadsLogStorePath { + + return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles payloadsLog]]; +} + ++ (nonnull NSString *)_getSDKDataFilePath:(nonnull NSString *)sdkFileName { + + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + return [cachesDirectory stringByAppendingPathComponent:sdkFileName]; +} + ++ (NSThread *)_test_rollbarThread { + + return [RollbarThread sharedInstance]; +} + ++ (void)_test_doNothing { + + // no-Op simulation... +} + +@end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index 2ddff561..e6f0765d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -67,7 +67,7 @@ - (instancetype)initWithAccessToken:(nonnull NSString *)accessToken return [self initWithConfiguration:config]; } -- (instancetype)initWithConfiguration:(RollbarConfig *)configuration { +- (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration { if ((self = [super init])) { From 14a9b6ebe79dbcca529bc1cf8477e406e263d566 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 23 Jun 2022 23:22:18 -0700 Subject: [PATCH 031/127] refactor: RollbarInfrastructure --- .../RollbarNotifier/RollbarInfrastructure.m | 67 +++---------------- 1 file changed, 8 insertions(+), 59 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index a566e194..93f1a230 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -7,11 +7,6 @@ @implementation RollbarInfrastructure { @private RollbarConfig *_configuration; RollbarLogger *_logger; - NSString *_oomDetectionFilePath; - NSString *_queuedItemsFilePath; - NSString *_stateFilePath; - NSString *_payloadsFilePath; - NSMutableDictionary *_queueState; } #pragma mark - Sigleton pattern @@ -24,6 +19,10 @@ + (nonnull instancetype)sharedInstance { dispatch_once(&onceToken, ^{ singleton = [self new]; + + RollbarSdkLog(@"%@ singleton created!", + [RollbarInfrastructure className] + ); }); return singleton; @@ -44,7 +43,10 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)rollbarConfig { self->_configuration = rollbarConfig; self->_logger = nil; - [self setupInternalStorage]; + RollbarSdkLog(@"%@ is configured with this RollbarConfig instance: \n%@", + [RollbarInfrastructure className], + rollbarConfig + ); return self; } @@ -100,63 +102,10 @@ - (void)assertValidConfiguration:(nullable RollbarConfig *)config { //TODO: complete full validation implementation... } -- (void)setupInternalStorage { - - // create working cache directory: - [RollbarCachesDirectory ensureCachesDirectoryExists]; - NSString *cachesDirectory = [RollbarCachesDirectory directory]; - - // make sure we have all the data files set: - self->_queuedItemsFilePath = - [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueue]]; - self->_stateFilePath = - [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueueState]]; - - // create the queued items file if does not exist already: - if (![[NSFileManager defaultManager] fileExistsAtPath:self->_queuedItemsFilePath]) { - [[NSFileManager defaultManager] createFileAtPath:self->_queuedItemsFilePath - contents:nil - attributes:nil]; - } - - // create state tracking file if does not exist already: - if ([[NSFileManager defaultManager] fileExistsAtPath:self->_stateFilePath]) { - NSData *stateData = [NSData dataWithContentsOfFile:self->_stateFilePath]; - if (stateData) { - NSDictionary *state = [NSJSONSerialization JSONObjectWithData:stateData - options:0 - error:nil]; - self->_queueState = [state mutableCopy]; - } else { - RollbarSdkLog(@"There was an error restoring saved queue state"); - } - } - - // let's make sure we always recover into a good state if applicable: - if (!self->_queueState) { - self->_queueState = [@{ - @"offset": [NSNumber numberWithUnsignedInt:0], - @"retry_count": [NSNumber numberWithUnsignedInt:0] - } mutableCopy]; - [self saveQueueState]; - } -} - (void)configureInfrastructure { //TODO: implement... } -- (void)saveQueueState { - NSError *error; - NSData *data = [NSJSONSerialization rollbar_dataWithJSONObject:self->_queueState - options:0 - error:&error - safe:true]; - if (error) { - RollbarSdkLog(@"Error: %@", [error localizedDescription]); - } - [data writeToFile:self->_stateFilePath atomically:YES]; -} - @end From 83bbae05fa884233ca2001b04727b60ce729d68f Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 23 Jun 2022 23:23:03 -0700 Subject: [PATCH 032/127] refactor: RollbarThread --- .../Sources/RollbarNotifier/RollbarThread.m | 225 +----------------- 1 file changed, 9 insertions(+), 216 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index a83bf162..f943b136 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -14,18 +14,11 @@ #import "RollbarModule.h" #import "RollbarDestination.h" #import "RollbarProxy.h" +#import "RollbarSender.h" +#import "RollbarPayloadPostReply.h" static NSUInteger MAX_RETRY_COUNT = 5; -/// Rollbar API Service enforced payload rate limit: -static NSString * const RESPONSE_HEADER_RATE_LIMIT = @"x-rate-limit-limit"; -/// Rollbar API Service enforced remaining payload count until the limit is reached: -static NSString * const RESPONSE_HEADER_REMAINING_COUNT = @"x-rate-limit-remaining"; -/// Rollbar API Service enforced rate limit reset time for the current limit window: -static NSString * const RESPONSE_HEADER_RESET_TIME = @"x-rate-limit-reset"; -/// Rollbar API Service enforced rate limit remaining seconds of the current limit window: -static NSString * const RESPONSE_HEADER_REMAINING_SECONDS = @"x-rate-limit-remaining-seconds"; - @implementation RollbarThread { @private @@ -99,13 +92,6 @@ - (void)setupDataStorage { [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueue]]; self->_stateFilePath = [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueueState]]; -// payloadsFilePath = -// [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payoadsLog]]; - - // either create or overwrite the payloads log file: -// [[NSFileManager defaultManager] createFileAtPath:payloadsFilePath -// contents:nil -// attributes:nil]; // create the queued items file if does not exist already: if (![[NSFileManager defaultManager] fileExistsAtPath:self->_queuedItemsFilePath]) { @@ -118,26 +104,23 @@ - (void)setupDataStorage { if ([[NSFileManager defaultManager] fileExistsAtPath:self->_stateFilePath]) { NSData *stateData = [NSData dataWithContentsOfFile:self->_stateFilePath]; if (stateData) { - NSDictionary *state = [NSJSONSerialization JSONObjectWithData:stateData options:0 error:nil]; self->_queueState = [state mutableCopy]; } else { - RollbarSdkLog(@"There was an error restoring saved queue state"); } } + + // let's make sure we always recover into a good state if applicable: if (!self->_queueState) { - self->_queueState = [@{ @"offset": [NSNumber numberWithUnsignedInt:0], @"retry_count": [NSNumber numberWithUnsignedInt:0] } mutableCopy]; - [self saveQueueState]; - } -} + }} - (void)saveQueueState { @@ -440,208 +423,18 @@ - (BOOL)sendPayload:(nonnull NSData *)payload return NO; } - NSURL *url = [NSURL URLWithString:config.destination.endpoint]; - if (nil == url) { - return NO; - } - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - - [request setHTTPMethod:@"POST"]; - [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - [request setValue:config.destination.accessToken forHTTPHeaderField:@"X-Rollbar-Access-Token"]; - [request setHTTPBody:payload]; - - if (YES == config.developerOptions.logPayload) { - NSString *payloadString = [[NSString alloc]initWithData:payload - encoding:NSUTF8StringEncoding - ]; - NSLog(@"%@", payloadString); - //TODO: if config.developerOptions.logPayloadFile is defined, save the payload into the file... - } - - if (NO == config.developerOptions.transmit) { - return YES; // we just successfully short-circuit here... - } - - __block BOOL result = NO; - - // This requires iOS 7.0+ - dispatch_semaphore_t sem = dispatch_semaphore_create(0); - - NSURLSession *session = [NSURLSession sharedSession]; - - if (config.httpProxy.enabled - || config.httpsProxy.enabled) { - - NSDictionary *connectionProxyDictionary = - @{ - @"HTTPEnable" : [NSNumber numberWithBool:config.httpProxy.enabled], - @"HTTPProxy" : config.httpProxy.proxyUrl, - @"HTTPPort" : [NSNumber numberWithUnsignedInteger:config.httpProxy.proxyPort], - @"HTTPSEnable" : [NSNumber numberWithBool:config.httpsProxy.enabled], - @"HTTPSProxy" : config.httpsProxy.proxyUrl, - @"HTTPSPort" : [NSNumber numberWithUnsignedInteger:config.httpsProxy.proxyPort] - }; - - NSURLSessionConfiguration *sessionConfig = - [NSURLSessionConfiguration ephemeralSessionConfiguration]; - sessionConfig.connectionProxyDictionary = connectionProxyDictionary; - session = [NSURLSession sessionWithConfiguration:sessionConfig]; + RollbarPayloadPostReply *reply = [[RollbarSender new] sendPayload:payload usingConfig:config]; + if (reply && (0 == reply.statusCode)) { + return YES; } - NSURLSessionDataTask *dataTask = - [session dataTaskWithRequest:request - completionHandler:^( - NSData * _Nullable data, - NSURLResponse * _Nullable response, - NSError * _Nullable error) { - result = [self checkPayloadResponse:response - error:error - data:data]; - dispatch_semaphore_signal(sem); - }]; - [dataTask resume]; - - dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); - - return result; + return NO; } /// This is a DEPRECATED method left for some backward compatibility for very old clients eventually moving to this more recent implementation. /// Use/maintain sendPayload:usingConfig: instead! - (BOOL)sendPayload:(NSData *)payload { - return NO; -// if ((nil == payload) -// || (nil == self.configuration) -// || (nil == self.configuration.destination) -// || (nil == self.configuration.destination.endpoint) -// || (nil == self.configuration.destination.accessToken) -// || (0 == self.configuration.destination.endpoint.length) -// || (0 == self.configuration.destination.accessToken.length) -// ) { -// -// return NO; -// } -// -// NSURL *url = [NSURL URLWithString:self.configuration.destination.endpoint]; -// if (nil == url) { -// return NO; -// } -// NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; -// -// [request setHTTPMethod:@"POST"]; -// [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; -// [request setValue:self.configuration.destination.accessToken forHTTPHeaderField:@"X-Rollbar-Access-Token"]; -// [request setHTTPBody:payload]; -// -// if (YES == self.configuration.developerOptions.logPayload) { -// NSString *payloadString = [[NSString alloc]initWithData:payload -// encoding:NSUTF8StringEncoding -// ]; -// NSLog(@"%@", payloadString); -// //TODO: if self.configuration.logPayloadFile is defined, save the payload into the file... -// } -// -// if (NO == self.configuration.developerOptions.transmit) { -// return YES; // we just successfully short-circuit here... -// } -// -// __block BOOL result = NO; -// -// // This requires iOS 7.0+ -// dispatch_semaphore_t sem = dispatch_semaphore_create(0); -// -// NSURLSession *session = [NSURLSession sharedSession]; -// -// if (self.configuration.httpProxy.enabled -// || self.configuration.httpsProxy.enabled) { -// -// NSDictionary *connectionProxyDictionary = -// @{ -// @"HTTPEnable" : [NSNumber numberWithInt:self.configuration.httpProxy.enabled], -// @"HTTPProxy" : self.configuration.httpProxy.proxyUrl, -// @"HTTPPort" : @(self.configuration.httpProxy.proxyPort), -// @"HTTPSEnable" : [NSNumber numberWithInt:self.configuration.httpsProxy.enabled], -// @"HTTPSProxy" : self.configuration.httpsProxy.proxyUrl, -// @"HTTPSPort" : @(self.configuration.httpsProxy.proxyPort) -// }; -// -// NSURLSessionConfiguration *sessionConfig = -// [NSURLSessionConfiguration ephemeralSessionConfiguration]; -// sessionConfig.connectionProxyDictionary = connectionProxyDictionary; -// session = [NSURLSession sessionWithConfiguration:sessionConfig]; -// } -// -// NSURLSessionDataTask *dataTask = -// [session dataTaskWithRequest:request -// completionHandler:^( -// NSData * _Nullable data, -// NSURLResponse * _Nullable response, -// NSError * _Nullable error) { -// result = [self checkPayloadResponse:response -// error:error -// data:data]; -// dispatch_semaphore_signal(sem); -// }]; -// [dataTask resume]; -// -// dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); -// -// return result; -} - -- (BOOL)checkPayloadResponse:(NSURLResponse *)response - error:(NSError *)error - data:(NSData *)data { - -// if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { -// -// RollbarSdkLog(@"HTTP response from Rollbar: %@", response); -// } - - // Lookup rate limiting headers and adjust reporting rate accordingly: - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; - NSDictionary *httpHeaders = [httpResponse allHeaderFields]; - //int rateLimit = [[httpHeaders valueForKey:RESPONSE_HEADER_RATE_LIMIT] intValue]; - int rateLimitLeft = - [[httpHeaders valueForKey:RESPONSE_HEADER_REMAINING_COUNT] intValue]; - int rateLimitSeconds = - [[httpHeaders valueForKey:RESPONSE_HEADER_REMAINING_SECONDS] intValue]; - if (rateLimitLeft > 0) { - - self->_nextSendTime = [[NSDate alloc] init]; - } - else { - - self->_nextSendTime = - [[NSDate alloc] initWithTimeIntervalSinceNow:rateLimitSeconds]; - } - - if (error) { - RollbarSdkLog(@"There was an error reporting to Rollbar"); - RollbarSdkLog(@"Error: %@", [error localizedDescription]); - } else { - NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; - if ([httpResponse statusCode] == 200) { - -// if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { -// -// RollbarSdkLog(@"Success"); -// } - return YES; - } else { - - RollbarSdkLog(@"There was a problem reporting to Rollbar"); - if (data) { - RollbarSdkLog( - @"Response: %@", - [NSJSONSerialization JSONObjectWithData:data - options:0 - error:nil]); - } - } - } return NO; } From 566bde84c05a45d9942d3502ef1efd23d3a87df9 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 24 Jun 2022 14:35:57 -0700 Subject: [PATCH 033/127] refactor: RollbarThread --- .../Sources/RollbarNotifier/RollbarThread.h | 2 + .../Sources/RollbarNotifier/RollbarThread.m | 82 ++++++++++++++----- 2 files changed, 62 insertions(+), 22 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h index 9a6d3147..cd3df703 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h @@ -9,6 +9,8 @@ NS_ASSUME_NONNULL_BEGIN /// Signifies that the thread is active or not. @property(atomic) BOOL active; +- (void)persistPayload:(nonnull NSDictionary *)payload; + - (BOOL)sendPayload:(nonnull NSData *)payload usingConfig:(nonnull RollbarConfig *)config; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index f943b136..ed77ebe8 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -78,6 +78,8 @@ - (instancetype)initWithTarget:(id)target } + [self start]; + return self; } @@ -160,27 +162,6 @@ - (void)setReportingRate:(NSUInteger)reportsPerMinute { // } } -- (void)checkItems { - - if (self.cancelled) { - if (_timer) { - [_timer invalidate]; - _timer = nil; - } - [NSThread exit]; - } - - @autoreleasepool { - -// if ((nil != _logger) && (NO == _logger.configuration.developerOptions.suppressSdkInfoLogging)) { -// -// RollbarSdkLog(@"Checking items..."); -// } - - [self processSavedItems]; - } -} - - (void)run { @autoreleasepool { @@ -203,6 +184,63 @@ - (void)run { } } +#pragma mark - persisting payload items + +- (void)persistPayload:(nonnull NSDictionary *)payload { + + [self performSelector:@selector(queuePayload_OnlyCallOnThread:) + onThread:[RollbarThread sharedInstance] + withObject:payload + waitUntilDone:NO + ]; +} + + +- (void)queuePayload_OnlyCallOnThread:(NSDictionary *)payload { + + NSError *error = nil; + NSData *data = [NSJSONSerialization rollbar_dataWithJSONObject:payload + options:0 + error:&error + safe:true]; + if (nil == data) { + + RollbarSdkLog(@"Couldn't generate and save JSON data from: %@", payload); + if (error) { + + RollbarSdkLog(@" Error: %@", [error localizedDescription]); + } + return; + } + + [RollbarFileWriter appendSafelyData:data toFile:self->_queuedItemsFilePath]; + + [[RollbarTelemetry sharedInstance] clearAllData]; +} + +#pragma mark - processing persisted payload items + +- (void)checkItems { + + if (self.cancelled) { + if (_timer) { + [_timer invalidate]; + _timer = nil; + } + [NSThread exit]; + } + + @autoreleasepool { + + // if ((nil != _logger) && (NO == _logger.configuration.developerOptions.suppressSdkInfoLogging)) { + // + // RollbarSdkLog(@"Checking items..."); + // } + + [self processSavedItems]; + } +} + - (void)processSavedItems { #if !TARGET_OS_WATCH @@ -424,7 +462,7 @@ - (BOOL)sendPayload:(nonnull NSData *)payload } RollbarPayloadPostReply *reply = [[RollbarSender new] sendPayload:payload usingConfig:config]; - if (reply && (0 == reply.statusCode)) { + if (reply && (200 == reply.statusCode)) { return YES; } From 3d19bbff3c0f62b328f0c7a18be2a35c7854c113 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 24 Jun 2022 14:36:27 -0700 Subject: [PATCH 034/127] refactor: RollbarLogger --- .../Sources/RollbarNotifier/RollbarLogger.m | 35 +++---------------- 1 file changed, 4 insertions(+), 31 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index e6f0765d..e60dfcb8 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -177,40 +177,13 @@ - (BOOL)shouldSkipReporting:(RollbarLevel)level { #pragma mark - Payload queueing/reporting - (void)report:(RollbarPayload *)payload { - if (payload) { - [self queuePayload:payload.jsonFriendlyData]; - } -} -- (void)queuePayload:(NSDictionary *)payload { - - [self performSelector:@selector(queuePayload_OnlyCallOnThread:) - onThread:[RollbarThread sharedInstance] - withObject:payload - waitUntilDone:NO - ]; -} - -- (void)queuePayload_OnlyCallOnThread:(NSDictionary *)payload { - - NSError *error = nil; - NSData *data = [NSJSONSerialization rollbar_dataWithJSONObject:payload - options:0 - error:&error - safe:true]; - if (nil == data) { - - RollbarSdkLog(@"Couldn't generate and save JSON data from: %@", payload); - if (error) { - - RollbarSdkLog(@" Error: %@", [error localizedDescription]); + if (payload) { + NSDictionary *payloadJsonData = payload.jsonFriendlyData; + if (payloadJsonData) { + [[RollbarThread sharedInstance] persistPayload:payloadJsonData]; } - return; } - - [RollbarFileWriter appendSafelyData:data toFile:queuedItemsFilePath]; - - [[RollbarTelemetry sharedInstance] clearAllData]; } #pragma mark - Update configuration methods From 93e1818a5c074f03e9b14f34555e2ac95cd0f660 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 24 Jun 2022 14:36:50 -0700 Subject: [PATCH 035/127] refactor: RollbarInfrastructure --- RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index 93f1a230..ef3917f2 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -41,7 +41,7 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)rollbarConfig { } self->_configuration = rollbarConfig; - self->_logger = nil; + self->_logger = nil; //will be created as needed using the new config... RollbarSdkLog(@"%@ is configured with this RollbarConfig instance: \n%@", [RollbarInfrastructure className], From 3137fb13845bdebbb14fabf3d83aeb1c7e8108a6 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 24 Jun 2022 16:35:58 -0700 Subject: [PATCH 036/127] refactor: RollbarThread --- RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index ed77ebe8..3175cc92 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -48,7 +48,7 @@ - (instancetype)initWithTarget:(id)target [self setupDataStorage]; - self->_maxReportsPerMinute = 60; + self->_maxReportsPerMinute = 240;//60; self->_reachability = nil; self->_isNetworkReachable = YES; self->_nextSendTime = [[NSDate alloc] init]; From e1f4ceaacfa6e54e21d6b0955865c2bb63ee0026 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 24 Jun 2022 16:36:38 -0700 Subject: [PATCH 037/127] test: RollbarInfrastructureTests --- .../RollbarInfrastructureTests.m | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index db55ad5c..d6ccebbe 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -1,6 +1,7 @@ #import @import RollbarNotifier; +@import UnitTesting; @interface RollbarInfrastructureTests : XCTestCase @@ -43,6 +44,89 @@ - (void)testRollbarInfrastructureNotConfiguredException { ); } +- (void)testBasics { + + [RollbarLogger clearSdkDataStore]; + NSArray *items = [RollbarLogger readLogItemsFromStore]; + XCTAssertNotNil(items); + XCTAssertEqual(0, items.count); + items = [RollbarLogger readPayloadsFromSdkLog]; + XCTAssertNotNil(items); + XCTAssertEqual(0, items.count); + + RollbarConfig *config = [RollbarConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment] + ]; + config.developerOptions.transmit = NO; + config.developerOptions.logPayload = YES; + config.loggingOptions.maximumReportsPerMinute = 180; + [[RollbarInfrastructure sharedInstance] configureWith:config]; + [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical + message:@"RollbarInfrastructure basics test!" + data:nil + context:nil + ]; + + + [NSThread sleepForTimeInterval:0.30f]; + +// items = [RollbarLogger readLogItemsFromStore]; +// XCTAssertNotNil(items); +// XCTAssertEqual(0, items.count); + items = [RollbarLogger readPayloadsFromSdkLog]; + XCTAssertNotNil(items); + XCTAssertEqual(1, items.count); + + [RollbarLogger clearSdkDataStore]; + items = [RollbarLogger readLogItemsFromStore]; + XCTAssertNotNil(items); + XCTAssertEqual(0, items.count); + items = [RollbarLogger readPayloadsFromSdkLog]; + XCTAssertNotNil(items); + XCTAssertEqual(0, items.count); +} + +- (void)testLive { + + [RollbarLogger clearSdkDataStore]; + NSArray *items = [RollbarLogger readLogItemsFromStore]; + XCTAssertNotNil(items); + XCTAssertEqual(0, items.count); + items = [RollbarLogger readPayloadsFromSdkLog]; + XCTAssertNotNil(items); + XCTAssertEqual(0, items.count); + + RollbarConfig *config = [RollbarConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment] + ]; + config.developerOptions.transmit = YES; + config.developerOptions.logPayload = YES; + [[RollbarInfrastructure sharedInstance] configureWith:config]; + [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical + message:@"RollbarInfrastructure basics test!" + data:nil + context:nil + ]; + + + [NSThread sleepForTimeInterval:5.0f]; + + // items = [RollbarLogger readLogItemsFromStore]; + // XCTAssertNotNil(items); + // XCTAssertEqual(0, items.count); + items = [RollbarLogger readPayloadsFromSdkLog]; + XCTAssertNotNil(items); + XCTAssertEqual(1, items.count); + + [RollbarLogger clearSdkDataStore]; + items = [RollbarLogger readLogItemsFromStore]; + XCTAssertNotNil(items); + XCTAssertEqual(0, items.count); + items = [RollbarLogger readPayloadsFromSdkLog]; + XCTAssertNotNil(items); + XCTAssertEqual(0, items.count); +} + //- (void)testPerformanceExample { // // This is an example of a performance test case. // [self measureBlock:^{ From d26d9903de9a5a91b7ee88b8e0c9adb02c95586c Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 27 Jun 2022 23:32:00 -0700 Subject: [PATCH 038/127] feat: cloneable DTO --- .../Sources/RollbarCommon/DTOs/RollbarDTO.m | 8 ++++++++ .../RollbarConfigurationTests.m | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m index 313cff18..0ec2f397 100644 --- a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m +++ b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m @@ -318,6 +318,14 @@ -(BOOL)isEmpty { return NO; } +#pragma mark - NSCopying protocol + +-(id) copyWithZone: (NSZone *) zone { + + RollbarDTO *clone = [[[self class] allocWithZone:zone] initWithJSONString:[self serializeToJSONString]]; + return clone; +} + #pragma mark - Initializers - (instancetype)initWithJSONString: (NSString *)jsonString { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index 31de609a..ed06cb27 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -29,6 +29,21 @@ - (void)tearDown { [super tearDown]; } +- (void)testConfigCloning { + + RollbarConfig *rc = [RollbarConfig new]; + NSString *customEnv = @"CUSTOM_ENV"; + + XCTAssertNotEqual(rc.destination.environment, customEnv); + XCTAssertFalse(NSOrderedSame == [rc.destination.environment compare: customEnv]); + rc.destination.environment = customEnv; + XCTAssertTrue(NSOrderedSame == [rc.destination.environment compare: customEnv]); + + RollbarConfig *rcClone = (RollbarConfig *)[rc copy]; + XCTAssertNotEqual(rc.destination, rcClone.destination); + XCTAssertTrue(NSOrderedSame == [rcClone.destination.environment compare: customEnv]); +} + - (void)testDefaultRollbarConfiguration { RollbarConfig *rc = [RollbarConfig new]; From b323926db143f04654b27a79599796e947d03003 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 30 Jun 2022 00:24:54 -0700 Subject: [PATCH 039/127] feat: RollbarLoggerRegistry --- .../RollbarNotifier/RollbarLogger+Extension.h | 22 +++++++++++++++++++ .../RollbarNotifier/RollbarLoggerRecord.h | 16 ++++++++++++++ .../RollbarNotifier/RollbarLoggerRecord.m | 12 ++++++++++ .../RollbarNotifier/RollbarLoggerRegistry.h | 16 ++++++++++++++ .../RollbarNotifier/RollbarLoggerRegistry.m | 12 ++++++++++ .../RollbarLoggerRegistryRecord.h | 16 ++++++++++++++ .../RollbarLoggerRegistryRecord.m | 12 ++++++++++ 7 files changed, 106 insertions(+) create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h new file mode 100644 index 00000000..eda14e69 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h @@ -0,0 +1,22 @@ +// +// RollbarLogger+Internal.h +// +// +// Created by Andrey Kornich on 2022-06-28. +// + +#import "RollbarLogger.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarLogger () + +#pragma mark - initializers + +- (instancetype)initWithConfiguration:(nonnull RollbarConfig *)config + andRegistry:(nonnull RollbarLoggerRegistry *)registry +NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h new file mode 100644 index 00000000..ca8bdc4a --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h @@ -0,0 +1,16 @@ +// +// RollbarLoggerRecord.h +// +// +// Created by Andrey Kornich on 2022-06-28. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarLoggerRecord : NSObject + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m new file mode 100644 index 00000000..5ed62357 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m @@ -0,0 +1,12 @@ +// +// RollbarLoggerRecord.m +// +// +// Created by Andrey Kornich on 2022-06-28. +// + +#import "RollbarLoggerRecord.h" + +@implementation RollbarLoggerRecord + +@end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h new file mode 100644 index 00000000..a2f47297 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h @@ -0,0 +1,16 @@ +// +// RollbarLoggerRegistry.h +// +// +// Created by Andrey Kornich on 2022-06-28. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarLoggerRegistry : NSObject + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m new file mode 100644 index 00000000..a728f9e4 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m @@ -0,0 +1,12 @@ +// +// RollbarLoggerRegistry.m +// +// +// Created by Andrey Kornich on 2022-06-28. +// + +#import "RollbarLoggerRegistry.h" + +@implementation RollbarLoggerRegistry + +@end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h new file mode 100644 index 00000000..105553d9 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h @@ -0,0 +1,16 @@ +// +// RollbarLoggerRegistryRecord.h +// +// +// Created by Andrey Kornich on 2022-06-28. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarLoggerRegistryRecord : NSObject + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m new file mode 100644 index 00000000..52a52b0f --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m @@ -0,0 +1,12 @@ +// +// RollbarLoggerRegistryRecord.m +// +// +// Created by Andrey Kornich on 2022-06-28. +// + +#import "RollbarLoggerRegistryRecord.h" + +@implementation RollbarLoggerRegistryRecord + +@end From c74d12f19eddf8aa2ee109a9e6e9865614bf2849 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 30 Jun 2022 00:25:55 -0700 Subject: [PATCH 040/127] feat: RollbarLoggerRegistry --- .../RollbarNotifier/RollbarLogger+Extension.h | 14 +++- .../Sources/RollbarNotifier/RollbarLogger.m | 61 +++++++++++---- .../RollbarNotifier/RollbarLoggerRecord.h | 11 +++ .../RollbarNotifier/RollbarLoggerRecord.m | 14 ++++ .../RollbarNotifier/RollbarLoggerRegistry.h | 10 +++ .../RollbarNotifier/RollbarLoggerRegistry.m | 61 ++++++++++++++- .../RollbarLoggerRegistryRecord.h | 20 +++++ .../RollbarLoggerRegistryRecord.m | 77 ++++++++++++++++++- .../RollbarNotifier/include/RollbarLogger.h | 65 ++++------------ 9 files changed, 264 insertions(+), 69 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h index eda14e69..f02920e1 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h @@ -7,14 +7,24 @@ #import "RollbarLogger.h" +@import Foundation; + +@class RollbarConfig; +@class RollbarLoggerRecord; + NS_ASSUME_NONNULL_BEGIN -@interface RollbarLogger () +@interface RollbarLogger () { +} + +#pragma mark - properties + +@property (readonly)RollbarLoggerRecord *loggerRecord; #pragma mark - initializers - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)config - andRegistry:(nonnull RollbarLoggerRegistry *)registry + andLoggerRecord:(nonnull RollbarLoggerRecord *)loggerRecord NS_DESIGNATED_INITIALIZER; @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index e60dfcb8..86cf3b34 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -7,6 +7,7 @@ @import RollbarCommon; #import "RollbarLogger.h" +#import "RollbarLogger+Extension.h" #import "RollbarThread.h" #import "RollbarTelemetryThread.h" #import "RollbarReachability.h" @@ -15,6 +16,7 @@ #import "RollbarPayloadTruncator.h" #import "RollbarConfig.h" #import "RollbarNotifierFiles.h" +#import "RollbarLoggerRegistry.h" #import "RollbarPayloadDTOs.h" @@ -29,36 +31,23 @@ @implementation RollbarLogger { NSDictionary *m_osData; } -#pragma mark - factory methods +#pragma mark - //TODO: to be removed -/// Logger factory method -/// @param accessToken a Rollbar project's access token + (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken { return [[RollbarLogger alloc] initWithAccessToken:accessToken]; } - -/// Logger factory method -/// @param accessToken a Rollbar project's access token -/// @param environment a Rollbar project's environment + (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken andEnvironment:(nonnull NSString *)environment { return [[RollbarLogger alloc] initWithAccessToken:accessToken andEnvironment:environment]; } - -/// Logger factory method -/// @param configuration the config object + (instancetype)loggerWithConfiguration:(nonnull RollbarConfig *)configuration { return [[RollbarLogger alloc] initWithConfiguration:configuration]; } - -#pragma mark - initializers - - (instancetype)initWithAccessToken:(NSString *)accessToken { RollbarConfig *config = [RollbarConfig new]; config.destination.accessToken = accessToken; return [self initWithConfiguration:config]; } - - (instancetype)initWithAccessToken:(nonnull NSString *)accessToken andEnvironment:(nonnull NSString *)environment { RollbarConfig *config = [RollbarConfig new]; @@ -66,13 +55,51 @@ - (instancetype)initWithAccessToken:(nonnull NSString *)accessToken config.destination.environment = environment; return [self initWithConfiguration:config]; } - - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration { if ((self = [super init])) { - + [self updateConfiguration:configuration]; + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + if (nil != self.configuration.developerOptions.payloadLogFile + && self.configuration.developerOptions.payloadLogFile.length > 0) { + + payloadsFilePath = + [cachesDirectory stringByAppendingPathComponent:self.configuration.developerOptions.payloadLogFile]; + } + else { + + payloadsFilePath = + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsLog]]; + } + } + + return self; +} + + + + + + + + + +#pragma mark - initializers + +- (instancetype)initWithConfiguration:(nonnull RollbarConfig *)config + andLoggerRecord:(nonnull RollbarLoggerRecord *)loggerRecord { + + NSAssert(config, @"Config must not be null!"); + NSAssert(loggerRecord, @"LoggerRecord must not be null!"); + + if ((self = [super init])) { + + self->_loggerRecord = loggerRecord; + + [self updateConfiguration:config]; + NSString *cachesDirectory = [RollbarCachesDirectory directory]; if (nil != self.configuration.developerOptions.payloadLogFile && self.configuration.developerOptions.payloadLogFile.length > 0) { @@ -86,7 +113,7 @@ - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration { [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsLog]]; } } - + return self; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h index ca8bdc4a..1c61c004 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h @@ -7,10 +7,21 @@ #import +@class RollbarConfig; +@class RollbarLogger; +@class RollbarLoggerRegistryRecord; + NS_ASSUME_NONNULL_BEGIN @interface RollbarLoggerRecord : NSObject +@property (readonly, nonnull) RollbarLogger *logger; +@property (readonly, nonnull) RollbarLoggerRegistryRecord *registryRecord; + +- (instancetype)initWithConfig:(nonnull RollbarConfig *)config + andRegistryRecord:(nonnull RollbarLoggerRegistryRecord *)registryRecord; +- (instancetype)init NS_UNAVAILABLE; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m index 5ed62357..3b138542 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m @@ -6,7 +6,21 @@ // #import "RollbarLoggerRecord.h" +#import "RollbarLogger.h" +#import "RollbarLogger+Extension.h" @implementation RollbarLoggerRecord +- (instancetype)initWithConfig:(nonnull RollbarConfig *)config + andRegistryRecord:(nonnull RollbarLoggerRegistryRecord *)registryRecord { + + if (self = [super init]) { + + self->_logger = [[RollbarLogger alloc] initWithConfiguration:config andLoggerRecord:self]; + self->_registryRecord = registryRecord; + } + + return self; +} + @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h index a2f47297..bce3d2e5 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h @@ -7,10 +7,20 @@ #import +@class RollbarLogger; +@class RollbarConfig; +@class RollbarDestination; + NS_ASSUME_NONNULL_BEGIN @interface RollbarLoggerRegistry : NSObject +- (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)config; +- (void)unregisterLogger:(nonnull RollbarLogger *)logger; +- (NSUInteger)totalRegistryRecords; + ++ (nonnull NSString *)destinationID:(nonnull RollbarDestination *)destination; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m index a728f9e4..4b72bad5 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m @@ -6,7 +6,66 @@ // #import "RollbarLoggerRegistry.h" +#import "RollbarLoggerRegistryRecord.h" +#import "RollbarLoggerRecord.h" -@implementation RollbarLoggerRegistry +#import "RollbarLogger.h" +#import "RollbarLogger+Extension.h" + +#import "RollbarConfig.h" +#import "RollbarDestination.h" + +const NSUInteger DEFAULT_RegistryCapacity = 10; + +@implementation RollbarLoggerRegistry { + @private + NSMutableDictionary *_registryRecords; +} +- (instancetype)init { + + if (self = [super init]) { + self->_registryRecords = [NSMutableDictionary dictionaryWithCapacity:DEFAULT_RegistryCapacity]; + } +} +- (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)config { + + NSAssert(config, @"Config must not be null!"); + + NSString *destinationID = [RollbarLoggerRegistry destinationID:config.destination]; + + RollbarLoggerRegistryRecord *registryRecord = self->_registryRecords[destinationID]; + if (!registryRecord) { + registryRecord = [[RollbarLoggerRegistryRecord alloc] initWithDestinationID:destinationID + andRegistry:self + ]; + } + + RollbarLogger *logger = [registryRecord addLoggerWithConfig:config]; + return logger; +} + +- (void)unregisterLogger:(nonnull RollbarLogger *)logger { + [logger.loggerRecord.registryRecord removeLoggerRecord:logger.loggerRecord]; +} + +- (NSUInteger)totalRegistryRecords { + return self->_registryRecords.count; +} + +- (NSString *)debugDescription { + NSString *description = [NSString stringWithFormat:@"totalRegistryRecords: %lu, record keys: %@", + (unsigned long)[self totalRegistryRecords], + self->_registryRecords.allKeys.description + ]; + return description; +} + ++ (nonnull NSString *)destinationID:(nonnull RollbarDestination *)destination { + + NSString *destinationID = [NSString stringWithFormat:@"%@|%@", + destination.endpoint, + destination.accessToken]; + return destinationID; +} @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h index 105553d9..94b7388d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h @@ -7,10 +7,30 @@ #import +@class RollbarConfig; +@class RollbarLoggerRecord; +@class RollbarLoggerRegistry; +@class RollbarLogger; + NS_ASSUME_NONNULL_BEGIN @interface RollbarLoggerRegistryRecord : NSObject +@property (readonly, nonnull) NSString *destinationID; +@property (readonly, nonnull) NSSet *loggerRecords; +@property (readonly, nonnull) RollbarLoggerRegistry *registry; + +- (nonnull RollbarLogger *)addLoggerWithConfig:(nonnull RollbarConfig *)loggerConfig; +//- (void)removeLogger:(nonnull RollbarLogger *)logger; +- (void)removeLoggerRecord:(nonnull RollbarLoggerRecord *)loggerRecord; +- (NSUInteger)totalLoggerRecords; + + +- (instancetype)initWithDestinationID:(nonnull NSString *)destinationID + andRegistry:(RollbarLoggerRegistry *)registry +NS_DESIGNATED_INITIALIZER; +- (instancetype)init NS_UNAVAILABLE; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m index 52a52b0f..90abf416 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m @@ -6,7 +6,82 @@ // #import "RollbarLoggerRegistryRecord.h" +#import "RollbarLoggerRecord.h" +#import "RollbarLogger.h" +#import "RollbarConfig.h" +#import "RollbarDestination.h" -@implementation RollbarLoggerRegistryRecord +const NSUInteger DEFAULT_RegistryRecordCapacity = 10; + +@implementation RollbarLoggerRegistryRecord { + @private + NSMutableSet *_loggerRecords; +} + +#pragma mark - property accessors + +- (NSSet *)loggerRecords { + + return [_loggerRecords copy]; +} + +#pragma mark - initializers + +- (instancetype)initWithDestinationID:(nonnull NSString *)destinationID + andRegistry:(RollbarLoggerRegistry *)registry { + + if (self = [super init]) { + + self->_registry = registry; + self->_destinationID = destinationID; + self->_loggerRecords = [NSMutableSet setWithCapacity:DEFAULT_RegistryRecordCapacity]; + } + return self; +} + +#pragma mark - de/registration of loggers + +- (nonnull RollbarLogger *)addLoggerWithConfig:(nonnull RollbarConfig *)loggerConfig { + + RollbarLoggerRecord *loggerRecord = [[RollbarLoggerRecord alloc] initWithConfig:loggerConfig + andRegistryRecord:self]; + [self->_loggerRecords addObject:loggerRecord]; + return loggerRecord.logger; +} + +//- (void)removeLogger:(nonnull RollbarLogger *)logger { +// +// RollbarLoggerRecord *loggerRecord = nil; +// for (RollbarLoggerRecord *record in self->_loggerRecords) { +// if (logger == record.logger) { +// loggerRecord = record; +// break; +// } +// } +// +// if (loggerRecord) { +// [self removeLoggerRecord:loggerRecord]; +// } +// else { +// NSAssert(NO, @"Something wrong removing logger record from the registry!"); +// } +//} + +- (void)removeLoggerRecord:(nonnull RollbarLoggerRecord *)loggerRecord { + + [self->_loggerRecords removeObject:loggerRecord]; +} + +- (NSUInteger)totalLoggerRecords { + + return self->_loggerRecords.count; +} + +- (NSString *)debugDescription { + NSString *description = [NSString stringWithFormat:@"totalLoggerRecords: %lu", + (unsigned long)[self totalLoggerRecords] + ]; + return description; +} @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h index 088868db..174ce58b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h @@ -12,43 +12,39 @@ NS_ASSUME_NONNULL_BEGIN /// Models interface of a Rollbar logger @interface RollbarLogger : NSObject -#pragma mark - factory methods -/// Logger factory method -/// @param accessToken a Rollbar project's access token -+ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken; +#pragma mark - //TODO: to be removed -/// Logger factory method -/// @param accessToken a Rollbar project's access token -/// @param environment a Rollbar project's environment ++ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken; + (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken andEnvironment:(nonnull NSString *)environment; - -/// Logger factory method -/// @param configuration the config object + (instancetype)loggerWithConfiguration:(nonnull RollbarConfig *)configuration; -#pragma mark - initializers - -/// Logger initializer -/// @param accessToken a Rollbar project's access token - (instancetype)initWithAccessToken:(nonnull NSString *)accessToken; - -/// Logger initializer -/// @param accessToken a Rollbar project's access token -/// @param environment a Rollbar project's environment - (instancetype)initWithAccessToken:(nonnull NSString *)accessToken andEnvironment:(nonnull NSString *)environment; - -/// Designated logger initializer -/// @param configuration the config object - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration NS_DESIGNATED_INITIALIZER; +- (void)updateConfiguration:(nonnull RollbarConfig *)configuration; +- (void)updateAccessToken:(nonnull NSString *)accessToken; +- (void)updateReportingRate:(NSUInteger)maximumReportsPerMinute; + +//- (BOOL)sendItem:(nonnull NSDictionary *)payload +// nextOffset:(NSUInteger)nextOffset; +//- (BOOL)sendPayload:(nonnull NSData *)payload; + + + + + +#pragma mark - initializers + /// Disallowed initializer - (instancetype)init NS_UNAVAILABLE; + #pragma mark - properties /// Notifier's config object @@ -90,33 +86,6 @@ NS_UNAVAILABLE; data:(nullable NSDictionary *)data context:(nullable NSString *)context; -/// Sends an item batch in a blocking manner. -/// @param payload an item to send -/// @param nextOffset the offset in the item queue file of the item immediately after this batch. -/// If the send is successful or the retry limit is hit, nextOffset will be saved to the queueState as the offset to use for the next batch -/// @return YES if this batch should be discarded if it was successful or a retry limit was hit. Otherwise NO is returned if this batch should be retried. -//- (BOOL)sendItem:(nonnull NSDictionary *)payload -// nextOffset:(NSUInteger)nextOffset; - - -/// Sends a fully composed JSON payload. -/// @param payload complete Rollbar payload as JSON string -/// @return YES if successful. NO if not. -//- (BOOL)sendPayload:(nonnull NSData *)payload; - -/// Updates key configuration elements -/// @param configuration the Rollbar configuration object -- (void)updateConfiguration:(nonnull RollbarConfig *)configuration; -// isRoot:(BOOL)isRoot; - -/// Updates the Rollbar project access token -/// @param accessToken the Rollbar project access token -- (void)updateAccessToken:(nonnull NSString *)accessToken; - -/// Updates allowed reporting rate -/// @param maximumReportsPerMinute the maximum allowed reports transmission rate -- (void)updateReportingRate:(NSUInteger)maximumReportsPerMinute; - @end NS_ASSUME_NONNULL_END From 66e9fd82d58e2b9d83271e2ff5b40adf3e1ed379 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 1 Jul 2022 18:46:38 -0700 Subject: [PATCH 041/127] test: RollbarLoggerRegistryTests --- .../RollbarLoggerRegistryTests.m | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m new file mode 100644 index 00000000..e033b283 --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m @@ -0,0 +1,36 @@ +// +// RollbarLoggerRegistryTests.m +// +// +// Created by Andrey Kornich on 2022-06-30. +// + +#import + +@interface RollbarLoggerRegistryTests : XCTestCase + +@end + +@implementation RollbarLoggerRegistryTests + +- (void)setUp { + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. +} + +- (void)testExample { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end From 9f44378107dfc5839e1b75aaf133c8cafdb35f8a Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 1 Jul 2022 18:46:52 -0700 Subject: [PATCH 042/127] test: RollbarLoggerRegistryTests --- .../RollbarLoggerRegistryTests.m | 51 +++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m index e033b283..29abda39 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m @@ -7,6 +7,14 @@ #import +@import Foundation; +@import RollbarNotifier; + +#import "../../Sources/RollbarNotifier/RollbarLoggerRegistry.h" +#import "../../Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h" +#import "../../Sources/RollbarNotifier/RollbarLoggerRecord.h" +#import "../../Sources/RollbarNotifier/RollbarLogger+Extension.h" + @interface RollbarLoggerRegistryTests : XCTestCase @end @@ -21,9 +29,46 @@ - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. } -- (void)testExample { - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct results. +- (void)testBasics { + + RollbarLoggerRegistry *registry = [RollbarLoggerRegistry new]; + XCTAssertNotNil(registry); + XCTAssertEqual(0, [registry totalDestinationRecords]); + + RollbarConfig *config = [RollbarConfig configWithAccessToken:@"Token_A"]; + + RollbarLogger *loggerA = [registry loggerWithConfiguration:config]; + XCTAssertNotNil(loggerA); + XCTAssertEqual(1, [registry totalDestinationRecords]); + XCTAssertEqual(1, [registry totalLoggerRecords]); + XCTAssertEqual(1, loggerA.loggerRecord.registryRecord.totalLoggerRecords); + + RollbarLogger *loggerA1 = [registry loggerWithConfiguration:config]; + XCTAssertNotNil(loggerA1); + XCTAssertEqual(1, [registry totalDestinationRecords]); + XCTAssertEqual(2, [registry totalLoggerRecords]); + XCTAssertEqual(2, loggerA1.loggerRecord.registryRecord.totalLoggerRecords); + + config = [RollbarConfig configWithAccessToken:@"Token_B"]; + RollbarLogger *loggerB = [registry loggerWithConfiguration:config]; + XCTAssertNotNil(loggerB); + XCTAssertEqual(2, [registry totalDestinationRecords]); + XCTAssertEqual(3, [registry totalLoggerRecords]); + XCTAssertEqual(1, loggerB.loggerRecord.registryRecord.totalLoggerRecords); + + [registry unregisterLogger:loggerA]; + XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); + XCTAssertEqual(2, [registry totalLoggerRecords]); + XCTAssertEqual(1, loggerA1.loggerRecord.registryRecord.totalLoggerRecords); + + [registry unregisterLogger:loggerA1]; + XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); + XCTAssertEqual(1, [registry totalLoggerRecords]); + XCTAssertEqual(1, loggerB.loggerRecord.registryRecord.totalLoggerRecords); + + [registry unregisterLogger:loggerB]; + XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); + XCTAssertEqual(0, [registry totalLoggerRecords]); } - (void)testPerformanceExample { From 27109f73001b1c439dc72a174f5d3d5e6ff21668 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 1 Jul 2022 18:47:11 -0700 Subject: [PATCH 043/127] feat: RollbarLoggerRegistry --- .../RollbarNotifier/RollbarLoggerRegistry.h | 3 ++- .../RollbarNotifier/RollbarLoggerRegistry.m | 21 +++++++++++++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h index bce3d2e5..9ce1a6a2 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h @@ -17,7 +17,8 @@ NS_ASSUME_NONNULL_BEGIN - (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)config; - (void)unregisterLogger:(nonnull RollbarLogger *)logger; -- (NSUInteger)totalRegistryRecords; +- (NSUInteger)totalDestinationRecords; +- (NSUInteger)totalLoggerRecords; + (nonnull NSString *)destinationID:(nonnull RollbarDestination *)destination; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m index 4b72bad5..fe00a3c9 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m @@ -21,12 +21,15 @@ @implementation RollbarLoggerRegistry { @private NSMutableDictionary *_registryRecords; } + - (instancetype)init { if (self = [super init]) { self->_registryRecords = [NSMutableDictionary dictionaryWithCapacity:DEFAULT_RegistryCapacity]; } + return self; } + - (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)config { NSAssert(config, @"Config must not be null!"); @@ -38,6 +41,7 @@ - (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)conf registryRecord = [[RollbarLoggerRegistryRecord alloc] initWithDestinationID:destinationID andRegistry:self ]; + self->_registryRecords[destinationID] = registryRecord; } RollbarLogger *logger = [registryRecord addLoggerWithConfig:config]; @@ -48,13 +52,22 @@ - (void)unregisterLogger:(nonnull RollbarLogger *)logger { [logger.loggerRecord.registryRecord removeLoggerRecord:logger.loggerRecord]; } -- (NSUInteger)totalRegistryRecords { +- (NSUInteger)totalDestinationRecords { return self->_registryRecords.count; } -- (NSString *)debugDescription { - NSString *description = [NSString stringWithFormat:@"totalRegistryRecords: %lu, record keys: %@", - (unsigned long)[self totalRegistryRecords], +- (NSUInteger)totalLoggerRecords { + NSUInteger total = 0; + for (RollbarLoggerRegistryRecord *destinationRecord in self->_registryRecords.allValues) { + total += destinationRecord.totalLoggerRecords; + } + return total; +} + +- (nonnull NSString *)description { + NSString *description = [NSString stringWithFormat:@"%@ - totalDestinationRecords: %lu, record keys: %@", + super.description, + (unsigned long)[self totalDestinationRecords], self->_registryRecords.allKeys.description ]; return description; From dc9eebf8743f97e9e0a47ceb411890e9a3ecad1a Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 1 Jul 2022 21:17:46 -0700 Subject: [PATCH 044/127] refactor: logger registry --- .../{RollbarLoggerRegistryRecord.h => RollbarDestinationRecord.h} | 0 .../{RollbarLoggerRegistryRecord.m => RollbarDestinationRecord.m} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename RollbarNotifier/Sources/RollbarNotifier/{RollbarLoggerRegistryRecord.h => RollbarDestinationRecord.h} (100%) rename RollbarNotifier/Sources/RollbarNotifier/{RollbarLoggerRegistryRecord.m => RollbarDestinationRecord.m} (100%) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h similarity index 100% rename from RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h rename to RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m similarity index 100% rename from RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistryRecord.m rename to RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m From f8ad66ad3c84f0d3d7f3d657ff083d19b6945d97 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 1 Jul 2022 21:18:18 -0700 Subject: [PATCH 045/127] refactor: logger registry --- .../RollbarDestinationRecord.h | 4 ++-- .../RollbarDestinationRecord.m | 12 +++++----- .../RollbarNotifier/RollbarLoggerRecord.h | 6 ++--- .../RollbarNotifier/RollbarLoggerRecord.m | 7 +++--- .../RollbarNotifier/RollbarLoggerRegistry.m | 24 +++++++++---------- .../RollbarLoggerRegistryTests.m | 14 ++++++----- 6 files changed, 35 insertions(+), 32 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h index 94b7388d..77c163ca 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h @@ -1,5 +1,5 @@ // -// RollbarLoggerRegistryRecord.h +// RollbarDestinationRecord.h // // // Created by Andrey Kornich on 2022-06-28. @@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface RollbarLoggerRegistryRecord : NSObject +@interface RollbarDestinationRecord : NSObject @property (readonly, nonnull) NSString *destinationID; @property (readonly, nonnull) NSSet *loggerRecords; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m index 90abf416..25787548 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m @@ -1,19 +1,19 @@ // -// RollbarLoggerRegistryRecord.m +// RollbarDestinationRecord.m // // // Created by Andrey Kornich on 2022-06-28. // -#import "RollbarLoggerRegistryRecord.h" +#import "RollbarDestinationRecord.h" #import "RollbarLoggerRecord.h" #import "RollbarLogger.h" #import "RollbarConfig.h" #import "RollbarDestination.h" -const NSUInteger DEFAULT_RegistryRecordCapacity = 10; +const NSUInteger DEFAULT_DestinationRecordCapacity = 10; -@implementation RollbarLoggerRegistryRecord { +@implementation RollbarDestinationRecord { @private NSMutableSet *_loggerRecords; } @@ -34,7 +34,7 @@ - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID self->_registry = registry; self->_destinationID = destinationID; - self->_loggerRecords = [NSMutableSet setWithCapacity:DEFAULT_RegistryRecordCapacity]; + self->_loggerRecords = [NSMutableSet setWithCapacity:DEFAULT_DestinationRecordCapacity]; } return self; } @@ -44,7 +44,7 @@ - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID - (nonnull RollbarLogger *)addLoggerWithConfig:(nonnull RollbarConfig *)loggerConfig { RollbarLoggerRecord *loggerRecord = [[RollbarLoggerRecord alloc] initWithConfig:loggerConfig - andRegistryRecord:self]; + andDestinationRecord:self]; [self->_loggerRecords addObject:loggerRecord]; return loggerRecord.logger; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h index 1c61c004..c959d08d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h @@ -9,17 +9,17 @@ @class RollbarConfig; @class RollbarLogger; -@class RollbarLoggerRegistryRecord; +@class RollbarDestinationRecord; NS_ASSUME_NONNULL_BEGIN @interface RollbarLoggerRecord : NSObject @property (readonly, nonnull) RollbarLogger *logger; -@property (readonly, nonnull) RollbarLoggerRegistryRecord *registryRecord; +@property (readonly, nonnull) RollbarDestinationRecord *destinationRecord; - (instancetype)initWithConfig:(nonnull RollbarConfig *)config - andRegistryRecord:(nonnull RollbarLoggerRegistryRecord *)registryRecord; + andDestinationRecord:(nonnull RollbarDestinationRecord *)destinationRecord; - (instancetype)init NS_UNAVAILABLE; @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m index 3b138542..262d15c3 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m @@ -12,12 +12,13 @@ @implementation RollbarLoggerRecord - (instancetype)initWithConfig:(nonnull RollbarConfig *)config - andRegistryRecord:(nonnull RollbarLoggerRegistryRecord *)registryRecord { + andDestinationRecord:(nonnull RollbarDestinationRecord *)destinationRecord { if (self = [super init]) { - self->_logger = [[RollbarLogger alloc] initWithConfiguration:config andLoggerRecord:self]; - self->_registryRecord = registryRecord; + self->_logger = [[RollbarLogger alloc] initWithConfiguration:config + andLoggerRecord:self]; + self->_destinationRecord = destinationRecord; } return self; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m index fe00a3c9..730af51b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m @@ -6,7 +6,7 @@ // #import "RollbarLoggerRegistry.h" -#import "RollbarLoggerRegistryRecord.h" +#import "RollbarDestinationRecord.h" #import "RollbarLoggerRecord.h" #import "RollbarLogger.h" @@ -19,13 +19,13 @@ @implementation RollbarLoggerRegistry { @private - NSMutableDictionary *_registryRecords; + NSMutableDictionary *_destinationRecords; } - (instancetype)init { if (self = [super init]) { - self->_registryRecords = [NSMutableDictionary dictionaryWithCapacity:DEFAULT_RegistryCapacity]; + self->_destinationRecords = [NSMutableDictionary dictionaryWithCapacity:DEFAULT_RegistryCapacity]; } return self; } @@ -36,29 +36,29 @@ - (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)conf NSString *destinationID = [RollbarLoggerRegistry destinationID:config.destination]; - RollbarLoggerRegistryRecord *registryRecord = self->_registryRecords[destinationID]; - if (!registryRecord) { - registryRecord = [[RollbarLoggerRegistryRecord alloc] initWithDestinationID:destinationID + RollbarDestinationRecord *destinationRecord = self->_destinationRecords[destinationID]; + if (!destinationRecord) { + destinationRecord = [[RollbarDestinationRecord alloc] initWithDestinationID:destinationID andRegistry:self ]; - self->_registryRecords[destinationID] = registryRecord; + self->_destinationRecords[destinationID] = destinationRecord; } - RollbarLogger *logger = [registryRecord addLoggerWithConfig:config]; + RollbarLogger *logger = [destinationRecord addLoggerWithConfig:config]; return logger; } - (void)unregisterLogger:(nonnull RollbarLogger *)logger { - [logger.loggerRecord.registryRecord removeLoggerRecord:logger.loggerRecord]; + [logger.loggerRecord.destinationRecord removeLoggerRecord:logger.loggerRecord]; } - (NSUInteger)totalDestinationRecords { - return self->_registryRecords.count; + return self->_destinationRecords.count; } - (NSUInteger)totalLoggerRecords { NSUInteger total = 0; - for (RollbarLoggerRegistryRecord *destinationRecord in self->_registryRecords.allValues) { + for (RollbarDestinationRecord *destinationRecord in self->_destinationRecords.allValues) { total += destinationRecord.totalLoggerRecords; } return total; @@ -68,7 +68,7 @@ - (nonnull NSString *)description { NSString *description = [NSString stringWithFormat:@"%@ - totalDestinationRecords: %lu, record keys: %@", super.description, (unsigned long)[self totalDestinationRecords], - self->_registryRecords.allKeys.description + self->_destinationRecords.allKeys.description ]; return description; } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m index 29abda39..0bfc7484 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m @@ -11,7 +11,7 @@ @import RollbarNotifier; #import "../../Sources/RollbarNotifier/RollbarLoggerRegistry.h" -#import "../../Sources/RollbarNotifier/RollbarLoggerRegistryRecord.h" +#import "../../Sources/RollbarNotifier/RollbarDestinationRecord.h" #import "../../Sources/RollbarNotifier/RollbarLoggerRecord.h" #import "../../Sources/RollbarNotifier/RollbarLogger+Extension.h" @@ -41,30 +41,32 @@ - (void)testBasics { XCTAssertNotNil(loggerA); XCTAssertEqual(1, [registry totalDestinationRecords]); XCTAssertEqual(1, [registry totalLoggerRecords]); - XCTAssertEqual(1, loggerA.loggerRecord.registryRecord.totalLoggerRecords); + XCTAssertEqual(1, loggerA.loggerRecord.destinationRecord.totalLoggerRecords); RollbarLogger *loggerA1 = [registry loggerWithConfiguration:config]; XCTAssertNotNil(loggerA1); XCTAssertEqual(1, [registry totalDestinationRecords]); XCTAssertEqual(2, [registry totalLoggerRecords]); - XCTAssertEqual(2, loggerA1.loggerRecord.registryRecord.totalLoggerRecords); + XCTAssertEqual(2, loggerA1.loggerRecord.destinationRecord.totalLoggerRecords); config = [RollbarConfig configWithAccessToken:@"Token_B"]; + RollbarLogger *loggerB = [registry loggerWithConfiguration:config]; XCTAssertNotNil(loggerB); XCTAssertEqual(2, [registry totalDestinationRecords]); XCTAssertEqual(3, [registry totalLoggerRecords]); - XCTAssertEqual(1, loggerB.loggerRecord.registryRecord.totalLoggerRecords); + XCTAssertEqual(1, loggerB.loggerRecord.destinationRecord.totalLoggerRecords); + [registry unregisterLogger:loggerA]; XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); XCTAssertEqual(2, [registry totalLoggerRecords]); - XCTAssertEqual(1, loggerA1.loggerRecord.registryRecord.totalLoggerRecords); + XCTAssertEqual(1, loggerA1.loggerRecord.destinationRecord.totalLoggerRecords); [registry unregisterLogger:loggerA1]; XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); XCTAssertEqual(1, [registry totalLoggerRecords]); - XCTAssertEqual(1, loggerB.loggerRecord.registryRecord.totalLoggerRecords); + XCTAssertEqual(1, loggerB.loggerRecord.destinationRecord.totalLoggerRecords); [registry unregisterLogger:loggerB]; XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); From c4a92d180481972f3d57d39983fd9da8859101e8 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Sat, 2 Jul 2022 12:23:12 -0700 Subject: [PATCH 046/127] feat: logger registry --- .../Sources/RollbarNotifier/RollbarDestinationRecord.m | 10 ++++++++++ .../Sources/RollbarNotifier/RollbarLoggerRegistry.m | 8 ++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m index 25787548..ded70d23 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m @@ -39,6 +39,16 @@ - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID return self; } +#pragma mark - overrides + +- (nonnull NSString *)description { + NSString *description = [NSString stringWithFormat:@"%@ - totalLoggerRecords: %lu", + super.description, + (unsigned long)[self totalLoggerRecords] + ]; + return description; +} + #pragma mark - de/registration of loggers - (nonnull RollbarLogger *)addLoggerWithConfig:(nonnull RollbarConfig *)loggerConfig { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m index 730af51b..1ed0a187 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m @@ -64,15 +64,19 @@ - (NSUInteger)totalLoggerRecords { return total; } +#pragma mark - overrides + - (nonnull NSString *)description { - NSString *description = [NSString stringWithFormat:@"%@ - totalDestinationRecords: %lu, record keys: %@", + NSString *description = [NSString stringWithFormat:@"%@ - totalDestinationRecords: %lu, records: %@", super.description, (unsigned long)[self totalDestinationRecords], - self->_destinationRecords.allKeys.description + self->_destinationRecords ]; return description; } +#pragma mark - class methods + + (nonnull NSString *)destinationID:(nonnull RollbarDestination *)destination { NSString *destinationID = [NSString stringWithFormat:@"%@|%@", From 470f11d54912b95a6615cb6a2590036679fc37be Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 6 Jul 2022 12:13:04 -0700 Subject: [PATCH 047/127] fix: payload factory --- .../Sources/RollbarNotifier/RollbarPayloadFactory.m | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m index 43263824..aa1eb517 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m @@ -23,6 +23,10 @@ #import +#if TARGET_OS_IOS | TARGET_OS_TV | TARGET_OS_MACCATALYST +@import UIKit; +#endif + @implementation RollbarPayloadFactory { @private From 59d8cdccce2a27697ef90cc5e6c727fc6f0c83f7 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 6 Jul 2022 12:14:05 -0700 Subject: [PATCH 048/127] feat: logger registry --- .../RollbarDestinationRecord.m | 7 ----- .../RollbarNotifier/RollbarLoggerRecord.h | 3 ++ .../RollbarNotifier/RollbarLoggerRecord.m | 30 ++++++++++++++----- .../RollbarNotifier/RollbarLoggerRegistry.m | 7 ----- 4 files changed, 25 insertions(+), 22 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m index ded70d23..67bbfd0e 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m @@ -1,10 +1,3 @@ -// -// RollbarDestinationRecord.m -// -// -// Created by Andrey Kornich on 2022-06-28. -// - #import "RollbarDestinationRecord.h" #import "RollbarLoggerRecord.h" #import "RollbarLogger.h" diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h index c959d08d..44cfe68b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h @@ -15,9 +15,12 @@ NS_ASSUME_NONNULL_BEGIN @interface RollbarLoggerRecord : NSObject +@property (readonly) BOOL isInScope; @property (readonly, nonnull) RollbarLogger *logger; @property (readonly, nonnull) RollbarDestinationRecord *destinationRecord; +- (void)markAsOutOfScope; + - (instancetype)initWithConfig:(nonnull RollbarConfig *)config andDestinationRecord:(nonnull RollbarDestinationRecord *)destinationRecord; - (instancetype)init NS_UNAVAILABLE; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m index 262d15c3..1de593dc 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m @@ -1,21 +1,35 @@ -// -// RollbarLoggerRecord.m -// -// -// Created by Andrey Kornich on 2022-06-28. -// - #import "RollbarLoggerRecord.h" #import "RollbarLogger.h" #import "RollbarLogger+Extension.h" +#import "RollbarInfrastructure.h" -@implementation RollbarLoggerRecord +@implementation RollbarLoggerRecord { + @private + BOOL _isInScope; +} + +//- (BOOL)isInScope { +// +// if (self->_logger == [RollbarInfrastructure sharedInstance].logger) { +// return NO; +// } +// else { +// return self->_isInScope; +// } +//} + +- (void)markAsOutOfScope { + + self->_isInScope = NO; +} - (instancetype)initWithConfig:(nonnull RollbarConfig *)config andDestinationRecord:(nonnull RollbarDestinationRecord *)destinationRecord { if (self = [super init]) { + self->_isInScope = YES; + self->_logger = [[RollbarLogger alloc] initWithConfiguration:config andLoggerRecord:self]; self->_destinationRecord = destinationRecord; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m index 1ed0a187..bad59c27 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m @@ -1,10 +1,3 @@ -// -// RollbarLoggerRegistry.m -// -// -// Created by Andrey Kornich on 2022-06-28. -// - #import "RollbarLoggerRegistry.h" #import "RollbarDestinationRecord.h" #import "RollbarLoggerRecord.h" From a188387252606a189d2205d4066a5472da768c19 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 6 Jul 2022 12:15:15 -0700 Subject: [PATCH 049/127] feat: infrastructure --- .../RollbarNotifier/RollbarInfrastructure.m | 59 +++++++++++++++---- .../Sources/RollbarNotifier/RollbarLogger.m | 9 +++ .../include/RollbarInfrastructure.h | 14 ++++- .../RollbarInfrastructureTests.m | 6 +- .../RollbarLoggerRegistryTests.m | 25 ++++++++ 5 files changed, 99 insertions(+), 14 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index ef3917f2..7bf8f1a8 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -2,11 +2,13 @@ #import "RollbarConfig.h" #import "RollbarLogger.h" #import "RollbarNotifierFiles.h" +#import "RollbarLoggerRegistry.h" @implementation RollbarInfrastructure { @private RollbarConfig *_configuration; RollbarLogger *_logger; + RollbarLoggerRegistry *_loggerRegistry; } #pragma mark - Sigleton pattern @@ -18,39 +20,76 @@ + (nonnull instancetype)sharedInstance { dispatch_once(&onceToken, ^{ - singleton = [self new]; + singleton = [RollbarInfrastructure new]; RollbarSdkLog(@"%@ singleton created!", - [RollbarInfrastructure className] + [RollbarInfrastructure rollbar_objectClassName] ); }); return singleton; } -#pragma mark - configuration +- (instancetype)init { + + if (self = [super init]) { + + self->_loggerRegistry = [RollbarLoggerRegistry new]; + } + return self; +} + +#pragma mark - instance methods -- (nonnull instancetype)configureWith:(nonnull RollbarConfig *)rollbarConfig { +- (nonnull instancetype)configure:(nonnull RollbarConfig *)config { - [self assertValidConfiguration:rollbarConfig]; + [self assertValidConfiguration:config]; if (self->_configuration - && (NSOrderedSame == [[rollbarConfig serializeToJSONString] compare:[self->_configuration serializeToJSONString]]) + && (NSOrderedSame == [[config serializeToJSONString] compare:[self->_configuration serializeToJSONString]]) ) { return self; // no need to reconfigure with an identical configuration... } - self->_configuration = rollbarConfig; + self->_configuration = config; self->_logger = nil; //will be created as needed using the new config... RollbarSdkLog(@"%@ is configured with this RollbarConfig instance: \n%@", - [RollbarInfrastructure className], - rollbarConfig + [RollbarInfrastructure rollbar_objectClassName], + config ); return self; } +- (nonnull RollbarLogger *)createLogger { + + return [self createLoggerWithConfig:self.configuration]; +} + +- (nonnull RollbarLogger *)createLoggerWithConfig:(nonnull RollbarConfig *)config { + + RollbarLogger *logger = [self->_loggerRegistry loggerWithConfiguration:config]; + return logger; +} + +#pragma mark - class methods + ++ (nonnull RollbarLogger *)sharedLogger { + + return [RollbarInfrastructure sharedInstance].logger; +} + ++ (nonnull RollbarLogger *)logger { + + return [[RollbarInfrastructure sharedInstance] createLogger]; +} + ++ (nonnull RollbarLogger *)loggerWithConfig:(nonnull RollbarConfig *)config { + + return [[RollbarInfrastructure sharedInstance] createLoggerWithConfig:config]; +} + #pragma mark - properties - (nonnull RollbarConfig *)configuration { @@ -68,7 +107,7 @@ - (nonnull RollbarConfig *)configuration { - (nonnull RollbarLogger *)logger { if (!self->_logger) { - self->_logger = [RollbarLogger loggerWithConfiguration:self.configuration]; + self->_logger = [self->_loggerRegistry loggerWithConfiguration:self.configuration]; } return self->_logger; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index 86cf3b34..7f98d899 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -17,6 +17,8 @@ #import "RollbarConfig.h" #import "RollbarNotifierFiles.h" #import "RollbarLoggerRegistry.h" +#import "RollbarLoggerRecord.h" +#import "RollbarDestinationRecord.h" #import "RollbarPayloadDTOs.h" @@ -117,6 +119,13 @@ - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)config return self; } +#pragma mark - finalizers + +- (void)dealloc { + + [self.loggerRecord markAsOutOfScope]; +} + #pragma mark - logging methods - (void)logCrashReport:(NSString *)crashReport { diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h index bb7da85d..3f2421dd 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h @@ -17,11 +17,23 @@ NS_ASSUME_NONNULL_BEGIN @interface RollbarInfrastructure : NSObject -- (nonnull instancetype)configureWith:(nonnull RollbarConfig *)rollbarConfig; +#pragma mark - propeties @property(readonly, nonnull) RollbarConfig *configuration; @property(readonly, nonnull) RollbarLogger *logger; +#pragma mark - instance methods + +- (nonnull instancetype)configure:(nonnull RollbarConfig *)config; +- (nonnull RollbarLogger *)createLogger; +- (nonnull RollbarLogger *)createLoggerWithConfig:(nonnull RollbarConfig *)config; + +#pragma mark - class methods + ++ (nonnull RollbarLogger *)sharedLogger; ++ (nonnull RollbarLogger *)logger; ++ (nonnull RollbarLogger *)loggerWithConfig:(nonnull RollbarConfig *)config; + #pragma mark - Sigleton pattern + (nonnull instancetype)sharedInstance; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index d6ccebbe..b15b8dac 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -34,7 +34,7 @@ - (void)testRollbarInfrastructureNotConfiguredException { @"An RollbarInfrastructureNotConfiguredException is expected!" ); - [[RollbarInfrastructure sharedInstance] configureWith:[RollbarConfig new]]; + [[RollbarInfrastructure sharedInstance] configure:[RollbarConfig new]]; XCTAssertNoThrow([RollbarInfrastructure sharedInstance].configuration, @"An RollbarInfrastructureNotConfiguredException is NOT expected!" @@ -60,7 +60,7 @@ - (void)testBasics { config.developerOptions.transmit = NO; config.developerOptions.logPayload = YES; config.loggingOptions.maximumReportsPerMinute = 180; - [[RollbarInfrastructure sharedInstance] configureWith:config]; + [[RollbarInfrastructure sharedInstance] configure:config]; [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical message:@"RollbarInfrastructure basics test!" data:nil @@ -101,7 +101,7 @@ - (void)testLive { ]; config.developerOptions.transmit = YES; config.developerOptions.logPayload = YES; - [[RollbarInfrastructure sharedInstance] configureWith:config]; + [[RollbarInfrastructure sharedInstance] configure:config]; [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical message:@"RollbarInfrastructure basics test!" data:nil diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m index 0bfc7484..1ac984bf 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m @@ -73,6 +73,31 @@ - (void)testBasics { XCTAssertEqual(0, [registry totalLoggerRecords]); } +- (void)testLoggerScope { + + RollbarConfig *config = [RollbarConfig configWithAccessToken:@"Token"]; + [[RollbarInfrastructure sharedInstance] configure:config]; + + RollbarLoggerRegistry *registry = [RollbarLoggerRegistry new]; + + XCTAssertNotNil(registry); + XCTAssertEqual(0, [registry totalDestinationRecords]); + + [self useLoggerWithinLimitedScope:registry]; +} + +- (void)useLoggerWithinLimitedScope:(nonnull RollbarLoggerRegistry *)registry { + + @autoreleasepool { + RollbarLogger *logger = [registry loggerWithConfiguration:[RollbarConfig new]]; //[[RollbarInfrastructure sharedInstance] createLogger]; + XCTAssertNotNil(logger); + XCTAssertEqual(1, [registry totalDestinationRecords]); + XCTAssertEqual(1, [registry totalLoggerRecords]); + XCTAssertEqual(1, logger.loggerRecord.destinationRecord.totalLoggerRecords); + XCTAssertTrue(logger.loggerRecord.isInScope); + } +} + - (void)testPerformanceExample { // This is an example of a performance test case. [self measureBlock:^{ From caee1fab7255bd0110444134809a48ef7e184fa2 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 6 Jul 2022 15:03:46 -0700 Subject: [PATCH 050/127] refactor: logger and infrastructure --- .../RollbarNotifier/RollbarInfrastructure.m | 66 ++++++++--- .../Sources/RollbarNotifier/RollbarLogger.m | 6 + .../include/RollbarInfrastructure.h | 20 ++-- .../RollbarNotifier/include/RollbarLogger.h | 104 +++++++++--------- .../include/RollbarLoggerProtocol.h | 57 ++++++++++ 5 files changed, 178 insertions(+), 75 deletions(-) create mode 100644 RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggerProtocol.h diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index 7bf8f1a8..97a2c628 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -1,14 +1,15 @@ #import "RollbarInfrastructure.h" #import "RollbarConfig.h" +#import "RollbarDestination.h" #import "RollbarLogger.h" #import "RollbarNotifierFiles.h" -#import "RollbarLoggerRegistry.h" +//#import "RollbarLoggerRegistry.h" @implementation RollbarInfrastructure { @private RollbarConfig *_configuration; RollbarLogger *_logger; - RollbarLoggerRegistry *_loggerRegistry; +// RollbarLoggerRegistry *_loggerRegistry; } #pragma mark - Sigleton pattern @@ -30,14 +31,14 @@ + (nonnull instancetype)sharedInstance { return singleton; } -- (instancetype)init { - - if (self = [super init]) { - - self->_loggerRegistry = [RollbarLoggerRegistry new]; - } - return self; -} +//- (instancetype)init { +// +// if (self = [super init]) { +// +//// self->_loggerRegistry = [RollbarLoggerRegistry new]; +// } +// return self; +//} #pragma mark - instance methods @@ -62,34 +63,65 @@ - (nonnull instancetype)configure:(nonnull RollbarConfig *)config { return self; } -- (nonnull RollbarLogger *)createLogger { +- (nonnull id)createLogger { return [self createLoggerWithConfig:self.configuration]; } - (nonnull RollbarLogger *)createLoggerWithConfig:(nonnull RollbarConfig *)config { - RollbarLogger *logger = [self->_loggerRegistry loggerWithConfiguration:config]; + RollbarLogger *logger = [RollbarLogger loggerWithConfiguration:config]; + //RollbarLogger *logger = [self->_loggerRegistry loggerWithConfiguration:config]; + return logger; +} + +- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token { + + RollbarConfig *config = [self.configuration copy]; + config.destination.accessToken = token; + id logger = [self createLoggerWithConfig:config]; + return logger; +} + +- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token + andEnvironment:(nonnull NSString *)env { + + RollbarConfig *config = [self.configuration copy]; + config.destination.accessToken = token; + config.destination.environment = env; + id logger = [self createLoggerWithConfig:config]; return logger; } #pragma mark - class methods -+ (nonnull RollbarLogger *)sharedLogger { ++ (nonnull id)sharedLogger { return [RollbarInfrastructure sharedInstance].logger; } -+ (nonnull RollbarLogger *)logger { ++ (nonnull id)logger { return [[RollbarInfrastructure sharedInstance] createLogger]; } -+ (nonnull RollbarLogger *)loggerWithConfig:(nonnull RollbarConfig *)config { ++ (nonnull id)loggerWithConfig:(nonnull RollbarConfig *)config { return [[RollbarInfrastructure sharedInstance] createLoggerWithConfig:config]; } ++ (nonnull id)loggerWithAccessToken:(nonnull NSString *)token { + + return [[RollbarInfrastructure sharedInstance] createLoggerWithAccessToken:token]; +} + ++ (nonnull id)loggerWithAccessToken:(nonnull NSString *)token + andEnvironment:(nonnull NSString *)env { + + return [[RollbarInfrastructure sharedInstance] createLoggerWithAccessToken:token + andEnvironment:env]; +} + #pragma mark - properties - (nonnull RollbarConfig *)configuration { @@ -104,10 +136,10 @@ - (nonnull RollbarConfig *)configuration { } } -- (nonnull RollbarLogger *)logger { +- (nonnull id)logger { if (!self->_logger) { - self->_logger = [self->_loggerRegistry loggerWithConfiguration:self.configuration]; + self->_logger = [RollbarLogger loggerWithConfiguration:self.configuration]; } return self->_logger; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index 7f98d899..b9908d6d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -33,6 +33,12 @@ @implementation RollbarLogger { NSDictionary *m_osData; } +@synthesize configuration; + + + + + #pragma mark - //TODO: to be removed + (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken { diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h index 3f2421dd..5b81f94f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h @@ -11,7 +11,7 @@ #import @class RollbarConfig; -@class RollbarLogger; +@protocol RollbarLogger; NS_ASSUME_NONNULL_BEGIN @@ -20,19 +20,25 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - propeties @property(readonly, nonnull) RollbarConfig *configuration; -@property(readonly, nonnull) RollbarLogger *logger; +@property(readonly, nonnull) id logger; #pragma mark - instance methods - (nonnull instancetype)configure:(nonnull RollbarConfig *)config; -- (nonnull RollbarLogger *)createLogger; -- (nonnull RollbarLogger *)createLoggerWithConfig:(nonnull RollbarConfig *)config; +- (nonnull id)createLogger; +- (nonnull id)createLoggerWithConfig:(nonnull RollbarConfig *)config; +- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token; +- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token + andEnvironment:(nonnull NSString *)env; #pragma mark - class methods -+ (nonnull RollbarLogger *)sharedLogger; -+ (nonnull RollbarLogger *)logger; -+ (nonnull RollbarLogger *)loggerWithConfig:(nonnull RollbarConfig *)config; ++ (nonnull id)sharedLogger; ++ (nonnull id)logger; ++ (nonnull id)loggerWithConfig:(nonnull RollbarConfig *)config; ++ (nonnull id)loggerWithAccessToken:(nonnull NSString *)token + andEnvironment:(nonnull NSString *)env; ++ (nonnull id)loggerWithAccessToken:(nonnull NSString *)token; #pragma mark - Sigleton pattern diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h index 174ce58b..140e2eb4 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h @@ -6,25 +6,17 @@ @class RollbarConfig; #import "RollbarLevel.h" +#import "RollbarLoggerProtocol.h" NS_ASSUME_NONNULL_BEGIN /// Models interface of a Rollbar logger -@interface RollbarLogger : NSObject +@interface RollbarLogger : NSObject #pragma mark - //TODO: to be removed -+ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken; -+ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken - andEnvironment:(nonnull NSString *)environment; -+ (instancetype)loggerWithConfiguration:(nonnull RollbarConfig *)configuration; -- (instancetype)initWithAccessToken:(nonnull NSString *)accessToken; -- (instancetype)initWithAccessToken:(nonnull NSString *)accessToken - andEnvironment:(nonnull NSString *)environment; -- (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration -NS_DESIGNATED_INITIALIZER; - (void)updateConfiguration:(nonnull RollbarConfig *)configuration; - (void)updateAccessToken:(nonnull NSString *)accessToken; @@ -36,55 +28,65 @@ NS_DESIGNATED_INITIALIZER; +#pragma mark - factory methods ++ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken; ++ (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken + andEnvironment:(nonnull NSString *)environment; ++ (instancetype)loggerWithConfiguration:(nonnull RollbarConfig *)configuration; #pragma mark - initializers +- (instancetype)initWithAccessToken:(nonnull NSString *)accessToken; +- (instancetype)initWithAccessToken:(nonnull NSString *)accessToken + andEnvironment:(nonnull NSString *)environment; +- (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration +NS_DESIGNATED_INITIALIZER; + /// Disallowed initializer - (instancetype)init NS_UNAVAILABLE; - -#pragma mark - properties - -/// Notifier's config object -@property (nullable, atomic, strong) RollbarConfig *configuration; - -#pragma mark - logging methods - -/// Captures a crash report -/// @param crashReport the crash report -- (void)logCrashReport:(nonnull NSString *)crashReport; - -/// Captures a log entry -/// @param level Rollbar error/log level -/// @param message message -/// @param data extra data -/// @param context extra context -- (void)log:(RollbarLevel)level - message:(nonnull NSString *)message - data:(nullable NSDictionary *)data - context:(nullable NSString *)context; - -/// Captures a log entry -/// @param level Rollbar error/log level -/// @param exception exception -/// @param data extra data -/// @param context extra context -- (void)log:(RollbarLevel)level - exception:(nonnull NSException *)exception - data:(nullable NSDictionary *)data - context:(nullable NSString *)context; - -/// Capture a log entry based on an NSError -/// @param level Rollbar error/log level -/// @param error an NSError -/// @param data extra data -/// @param context extra context -- (void)log:(RollbarLevel)level - error:(nonnull NSError *)error - data:(nullable NSDictionary *)data - context:(nullable NSString *)context; +//#pragma mark - properties +// +///// Notifier's config object +//@property (nullable, atomic, strong) RollbarConfig *configuration; +// +//#pragma mark - logging methods +// +///// Captures a crash report +///// @param crashReport the crash report +//- (void)logCrashReport:(nonnull NSString *)crashReport; +// +///// Captures a log entry +///// @param level Rollbar error/log level +///// @param message message +///// @param data extra data +///// @param context extra context +//- (void)log:(RollbarLevel)level +// message:(nonnull NSString *)message +// data:(nullable NSDictionary *)data +// context:(nullable NSString *)context; +// +///// Captures a log entry +///// @param level Rollbar error/log level +///// @param exception exception +///// @param data extra data +///// @param context extra context +//- (void)log:(RollbarLevel)level +// exception:(nonnull NSException *)exception +// data:(nullable NSDictionary *)data +// context:(nullable NSString *)context; +// +///// Capture a log entry based on an NSError +///// @param level Rollbar error/log level +///// @param error an NSError +///// @param data extra data +///// @param context extra context +//- (void)log:(RollbarLevel)level +// error:(nonnull NSError *)error +// data:(nullable NSDictionary *)data +// context:(nullable NSString *)context; @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggerProtocol.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggerProtocol.h new file mode 100644 index 00000000..2f6687d2 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggerProtocol.h @@ -0,0 +1,57 @@ +// +// RollbarLoggerProtocol.h +// +// +// Created by Andrey Kornich on 2022-07-06. +// + +#ifndef RollbarLoggerProtocol_h +#define RollbarLoggerProtocol_h + +@protocol RollbarLogger + +#pragma mark - properties + +/// Notifier's config object +@property (nullable, atomic, strong) RollbarConfig *configuration; + +#pragma mark - logging methods + +/// Captures a crash report +/// @param crashReport the crash report +- (void)logCrashReport:(nonnull NSString *)crashReport; + +/// Captures a log entry +/// @param level Rollbar error/log level +/// @param message message +/// @param data extra data +/// @param context extra context +- (void)log:(RollbarLevel)level + message:(nonnull NSString *)message + data:(nullable NSDictionary *)data + context:(nullable NSString *)context; + +/// Captures a log entry +/// @param level Rollbar error/log level +/// @param exception exception +/// @param data extra data +/// @param context extra context +- (void)log:(RollbarLevel)level + exception:(nonnull NSException *)exception + data:(nullable NSDictionary *)data + context:(nullable NSString *)context; + +/// Capture a log entry based on an NSError +/// @param level Rollbar error/log level +/// @param error an NSError +/// @param data extra data +/// @param context extra context +- (void)log:(RollbarLevel)level + error:(nonnull NSError *)error + data:(nullable NSDictionary *)data + context:(nullable NSString *)context; + + +@end + +#endif /* RollbarLoggerProtocol_h */ From 39bb531c9c353fc037978219a1e729a025013511 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 6 Jul 2022 15:07:09 -0700 Subject: [PATCH 051/127] refactor: Rollbar telemetry and telemetry thread --- .../Sources/RollbarNotifier/RollbarTelemetry.m | 9 +++++++-- .../Sources/RollbarNotifier/RollbarTelemetryThread.h | 2 ++ .../Sources/RollbarNotifier/RollbarTelemetryThread.m | 5 +++++ .../Sources/RollbarNotifier/include/RollbarTelemetry.h | 2 ++ 4 files changed, 16 insertions(+), 2 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetry.m index 9037b1ad..6544a2e7 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetry.m @@ -2,6 +2,7 @@ #import "RollbarTelemetry.h" #import "RollbarCachesDirectory.h" +#import "RollbarNotifierFiles.h" #import "RollbarTelemetryOptions.h" #import "RollbarScrubbingOptions.h" @@ -17,7 +18,6 @@ #import "RollbarTelemetryManualBody.h" static NSUInteger const DEFAULT_DATA_LIMIT = 10; -static NSString * const TELEMETRY_FILE_NAME = @"rollbar.telemetry"; static BOOL captureLog = false; @@ -87,7 +87,7 @@ - (instancetype)init { // Create cache file NSString *cachesDirectory = [RollbarCachesDirectory directory]; - _dataFilePath = [cachesDirectory stringByAppendingPathComponent:TELEMETRY_FILE_NAME]; + _dataFilePath = [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles telemetryQueue]]; _viewInputsToScrub = [NSMutableSet new]; @@ -116,6 +116,11 @@ - (nonnull instancetype)configureWithOptions:(nonnull RollbarTelemetryOptions *) return self; } +- (nonnull RollbarTelemetryOptions *)telemetryOptions { + + return [RollbarTelemetryThread sharedInstance].telemetryOptions; +} + - (void)setCaptureLog:(BOOL)shouldCapture { dispatch_async(queue, ^{ diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetryThread.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetryThread.h index cc7053fc..57db5069 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetryThread.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetryThread.h @@ -17,6 +17,8 @@ NS_ASSUME_NONNULL_BEGIN /// @param telemetryOptions desired Telemetry options - (instancetype)configureWithOptions:(nonnull RollbarTelemetryOptions *)telemetryOptions; +@property (readonly, nonnull) RollbarTelemetryOptions *telemetryOptions; + /// Signifies that the thread is active or not. @property(atomic) BOOL active; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetryThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetryThread.m index 9e6c14b5..98db8c5c 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetryThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarTelemetryThread.m @@ -86,6 +86,11 @@ - (instancetype)configureWithOptions:(nonnull RollbarTelemetryOptions *)telemetr return self; } +- (nonnull RollbarTelemetryOptions *)telemetryOptions { + + return self->_telemetryOptions; +} + - (BOOL)setupTimer { self->_collectionTimeInterval = [RollbarTelemetryThread calculateCollectionTimeInterval:self->_telemetryOptions]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetry.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetry.h index 2c51f4e8..c89320b2 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetry.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetry.h @@ -52,6 +52,8 @@ /// @param telemetryOptions desired Telemetry options - (nonnull instancetype)configureWithOptions:(nonnull RollbarTelemetryOptions *)telemetryOptions; +@property (readonly, nonnull) RollbarTelemetryOptions *telemetryOptions; + /// Telemetry collection enable/disable switch @property (readwrite, atomic) BOOL enabled; From 2f713eb99d8dc327486e344c78c1a4b5a9a5fc0f Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 6 Jul 2022 23:10:02 -0700 Subject: [PATCH 052/127] refactor: infrastructure, logger and their dependencies --- .../RollbarNotifier/RollbarInfrastructure.m | 69 ++++++++++--------- .../RollbarNotifier/RollbarLogger+Extension.h | 32 --------- .../Sources/RollbarNotifier/RollbarLogger.m | 60 ++-------------- .../RollbarNotifier/RollbarLoggerRecord.m | 5 +- .../RollbarNotifier/RollbarLoggerRegistry.h | 8 +-- .../RollbarNotifier/RollbarLoggerRegistry.m | 7 +- .../RollbarNotifier/include/RollbarConfig.h | 22 +++--- .../include/RollbarInfrastructure.h | 20 +++--- .../RollbarNotifier/include/RollbarLogger.h | 8 +-- .../include/RollbarLoggerProtocol.h | 6 +- .../RollbarInfrastructureTests.m | 3 + .../RollbarLoggerRegistryTests.m | 21 +++--- 12 files changed, 91 insertions(+), 170 deletions(-) delete mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index 97a2c628..35d630f5 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -1,6 +1,7 @@ #import "RollbarInfrastructure.h" #import "RollbarConfig.h" -#import "RollbarDestination.h" +//#import "RollbarDestination.h" +#import "RollbarLoggerProtocol.h" #import "RollbarLogger.h" #import "RollbarNotifierFiles.h" //#import "RollbarLoggerRegistry.h" @@ -32,9 +33,9 @@ + (nonnull instancetype)sharedInstance { } //- (instancetype)init { -// +// // if (self = [super init]) { -// +// //// self->_loggerRegistry = [RollbarLoggerRegistry new]; // } // return self; @@ -68,59 +69,59 @@ - (nonnull instancetype)configure:(nonnull RollbarConfig *)config { return [self createLoggerWithConfig:self.configuration]; } -- (nonnull RollbarLogger *)createLoggerWithConfig:(nonnull RollbarConfig *)config { +- (nonnull id)createLoggerWithConfig:(nonnull RollbarConfig *)config { RollbarLogger *logger = [RollbarLogger loggerWithConfiguration:config]; //RollbarLogger *logger = [self->_loggerRegistry loggerWithConfiguration:config]; return logger; } -- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token { +- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token + andEnvironment:(nonnull NSString *)env { RollbarConfig *config = [self.configuration copy]; config.destination.accessToken = token; + config.destination.environment = env; id logger = [self createLoggerWithConfig:config]; return logger; } -- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token - andEnvironment:(nonnull NSString *)env { +- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token { RollbarConfig *config = [self.configuration copy]; config.destination.accessToken = token; - config.destination.environment = env; id logger = [self createLoggerWithConfig:config]; return logger; } #pragma mark - class methods -+ (nonnull id)sharedLogger { - - return [RollbarInfrastructure sharedInstance].logger; -} - -+ (nonnull id)logger { - - return [[RollbarInfrastructure sharedInstance] createLogger]; -} - -+ (nonnull id)loggerWithConfig:(nonnull RollbarConfig *)config { - - return [[RollbarInfrastructure sharedInstance] createLoggerWithConfig:config]; -} - -+ (nonnull id)loggerWithAccessToken:(nonnull NSString *)token { - - return [[RollbarInfrastructure sharedInstance] createLoggerWithAccessToken:token]; -} - -+ (nonnull id)loggerWithAccessToken:(nonnull NSString *)token - andEnvironment:(nonnull NSString *)env { - - return [[RollbarInfrastructure sharedInstance] createLoggerWithAccessToken:token - andEnvironment:env]; -} +//+ (nonnull id)sharedLogger { +// +// return [RollbarInfrastructure sharedInstance].logger; +//} +// +//+ (nonnull id)newLogger { +// +// return [[RollbarInfrastructure sharedInstance] createLogger]; +//} +// +//+ (nonnull id)newLoggerWithConfig:(nonnull RollbarConfig *)config { +// +// return [[RollbarInfrastructure sharedInstance] createLoggerWithConfig:config]; +//} +// +//+ (nonnull id)newLoggerWithAccessToken:(nonnull NSString *)token { +// +// return [[RollbarInfrastructure sharedInstance] createLoggerWithAccessToken:token]; +//} +// +//+ (nonnull id)newLoggerWithAccessToken:(nonnull NSString *)token +// andEnvironment:(nonnull NSString *)env { +// +// return [[RollbarInfrastructure sharedInstance] createLoggerWithAccessToken:token +// andEnvironment:env]; +//} #pragma mark - properties diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h deleted file mode 100644 index f02920e1..00000000 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Extension.h +++ /dev/null @@ -1,32 +0,0 @@ -// -// RollbarLogger+Internal.h -// -// -// Created by Andrey Kornich on 2022-06-28. -// - -#import "RollbarLogger.h" - -@import Foundation; - -@class RollbarConfig; -@class RollbarLoggerRecord; - -NS_ASSUME_NONNULL_BEGIN - -@interface RollbarLogger () { -} - -#pragma mark - properties - -@property (readonly)RollbarLoggerRecord *loggerRecord; - -#pragma mark - initializers - -- (instancetype)initWithConfiguration:(nonnull RollbarConfig *)config - andLoggerRecord:(nonnull RollbarLoggerRecord *)loggerRecord -NS_DESIGNATED_INITIALIZER; - -@end - -NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index b9908d6d..d736a44d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -7,7 +7,6 @@ @import RollbarCommon; #import "RollbarLogger.h" -#import "RollbarLogger+Extension.h" #import "RollbarThread.h" #import "RollbarTelemetryThread.h" #import "RollbarReachability.h" @@ -35,22 +34,23 @@ @implementation RollbarLogger { @synthesize configuration; - - - - -#pragma mark - //TODO: to be removed +#pragma mark - factory methods + (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken { return [[RollbarLogger alloc] initWithAccessToken:accessToken]; } + + (instancetype)loggerWithAccessToken:(nonnull NSString *)accessToken andEnvironment:(nonnull NSString *)environment { return [[RollbarLogger alloc] initWithAccessToken:accessToken andEnvironment:environment]; } + + (instancetype)loggerWithConfiguration:(nonnull RollbarConfig *)configuration { return [[RollbarLogger alloc] initWithConfiguration:configuration]; } + +#pragma mark - initializers + - (instancetype)initWithAccessToken:(NSString *)accessToken { RollbarConfig *config = [RollbarConfig new]; config.destination.accessToken = accessToken; @@ -64,49 +64,10 @@ - (instancetype)initWithAccessToken:(nonnull NSString *)accessToken return [self initWithConfiguration:config]; } - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration { - - if ((self = [super init])) { - - [self updateConfiguration:configuration]; - - NSString *cachesDirectory = [RollbarCachesDirectory directory]; - if (nil != self.configuration.developerOptions.payloadLogFile - && self.configuration.developerOptions.payloadLogFile.length > 0) { - - payloadsFilePath = - [cachesDirectory stringByAppendingPathComponent:self.configuration.developerOptions.payloadLogFile]; - } - else { - - payloadsFilePath = - [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsLog]]; - } - } - - return self; -} - - - - - - - - - -#pragma mark - initializers - -- (instancetype)initWithConfiguration:(nonnull RollbarConfig *)config - andLoggerRecord:(nonnull RollbarLoggerRecord *)loggerRecord { - NSAssert(config, @"Config must not be null!"); - NSAssert(loggerRecord, @"LoggerRecord must not be null!"); - if ((self = [super init])) { - self->_loggerRecord = loggerRecord; - - [self updateConfiguration:config]; + [self updateConfiguration:configuration]; NSString *cachesDirectory = [RollbarCachesDirectory directory]; if (nil != self.configuration.developerOptions.payloadLogFile @@ -125,13 +86,6 @@ - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)config return self; } -#pragma mark - finalizers - -- (void)dealloc { - - [self.loggerRecord markAsOutOfScope]; -} - #pragma mark - logging methods - (void)logCrashReport:(NSString *)crashReport { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m index 1de593dc..46fc31f4 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m @@ -1,6 +1,5 @@ #import "RollbarLoggerRecord.h" #import "RollbarLogger.h" -#import "RollbarLogger+Extension.h" #import "RollbarInfrastructure.h" @implementation RollbarLoggerRecord { @@ -30,8 +29,8 @@ - (instancetype)initWithConfig:(nonnull RollbarConfig *)config self->_isInScope = YES; - self->_logger = [[RollbarLogger alloc] initWithConfiguration:config - andLoggerRecord:self]; +// self->_logger = [[RollbarLogger alloc] initWithConfiguration:config +// andLoggerRecord:self]; self->_destinationRecord = destinationRecord; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h index 9ce1a6a2..d7200866 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h @@ -7,16 +7,16 @@ #import -@class RollbarLogger; -@class RollbarConfig; -@class RollbarDestination; +#import "RollbarConfig.h" +#import "RollbarLogger.h" +#import "RollbarDestinationRecord.h" NS_ASSUME_NONNULL_BEGIN @interface RollbarLoggerRegistry : NSObject - (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)config; -- (void)unregisterLogger:(nonnull RollbarLogger *)logger; +//- (void)unregisterLogger:(nonnull RollbarLogger *)logger; - (NSUInteger)totalDestinationRecords; - (NSUInteger)totalLoggerRecords; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m index bad59c27..7bcdffa5 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m @@ -3,7 +3,6 @@ #import "RollbarLoggerRecord.h" #import "RollbarLogger.h" -#import "RollbarLogger+Extension.h" #import "RollbarConfig.h" #import "RollbarDestination.h" @@ -41,9 +40,9 @@ - (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)conf return logger; } -- (void)unregisterLogger:(nonnull RollbarLogger *)logger { - [logger.loggerRecord.destinationRecord removeLoggerRecord:logger.loggerRecord]; -} +//- (void)unregisterLogger:(nonnull RollbarLogger *)logger { +// [logger.loggerRecord.destinationRecord removeLoggerRecord:logger.loggerRecord]; +//} - (NSUInteger)totalDestinationRecords { return self->_destinationRecords.count; diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h index e8797a2c..bbe0ddfc 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h @@ -1,22 +1,22 @@ #ifndef RollbarConfig_h #define RollbarConfig_h +#import "RollbarDestination.h" +#import "RollbarDeveloperOptions.h" +#import "RollbarProxy.h" +#import "RollbarScrubbingOptions.h" +#import "RollbarServerConfig.h" +#import "RollbarPerson.h" +#import "RollbarModule.h" +#import "RollbarTelemetryOptions.h" +#import "RollbarLoggingOptions.h" +#import "RollbarData.h" + #import "RollbarCaptureIpType.h" #import "RollbarLevel.h" @import RollbarCommon; -@class RollbarDestination; -@class RollbarDeveloperOptions; -@class RollbarProxy; -@class RollbarScrubbingOptions; -@class RollbarServerConfig; -@class RollbarPerson; -@class RollbarModule; -@class RollbarTelemetryOptions; -@class RollbarLoggingOptions; -@class RollbarData; - NS_ASSUME_NONNULL_BEGIN /// Rollbar configuration structured model diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h index 5b81f94f..225d58f0 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h @@ -10,8 +10,8 @@ #import -@class RollbarConfig; -@protocol RollbarLogger; +#import "RollbarLoggerProtocol.h" +#import "RollbarConfig.h" NS_ASSUME_NONNULL_BEGIN @@ -27,18 +27,18 @@ NS_ASSUME_NONNULL_BEGIN - (nonnull instancetype)configure:(nonnull RollbarConfig *)config; - (nonnull id)createLogger; - (nonnull id)createLoggerWithConfig:(nonnull RollbarConfig *)config; -- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token; - (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token - andEnvironment:(nonnull NSString *)env; + andEnvironment:(nonnull NSString *)env; +- (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token; #pragma mark - class methods -+ (nonnull id)sharedLogger; -+ (nonnull id)logger; -+ (nonnull id)loggerWithConfig:(nonnull RollbarConfig *)config; -+ (nonnull id)loggerWithAccessToken:(nonnull NSString *)token - andEnvironment:(nonnull NSString *)env; -+ (nonnull id)loggerWithAccessToken:(nonnull NSString *)token; +//+ (nonnull id)sharedLogger; +//+ (nonnull id)newLogger; +//+ (nonnull id)newLoggerWithConfig:(nonnull RollbarConfig *)config; +//+ (nonnull id)newLoggerWithAccessToken:(nonnull NSString *)token +// andEnvironment:(nonnull NSString *)env; +//+ (nonnull id)newLoggerWithAccessToken:(nonnull NSString *)token; #pragma mark - Sigleton pattern diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h index 140e2eb4..84d9a84c 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h @@ -1,12 +1,8 @@ #ifndef RollbarLogger_h #define RollbarLogger_h -@import Foundation; - -@class RollbarConfig; - -#import "RollbarLevel.h" #import "RollbarLoggerProtocol.h" +@import Foundation; NS_ASSUME_NONNULL_BEGIN @@ -16,8 +12,6 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - //TODO: to be removed - - - (void)updateConfiguration:(nonnull RollbarConfig *)configuration; - (void)updateAccessToken:(nonnull NSString *)accessToken; - (void)updateReportingRate:(NSUInteger)maximumReportsPerMinute; diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggerProtocol.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggerProtocol.h index 2f6687d2..dea3969f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggerProtocol.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggerProtocol.h @@ -8,6 +8,11 @@ #ifndef RollbarLoggerProtocol_h #define RollbarLoggerProtocol_h +#import + +#import "RollbarLevel.h" +#import "RollbarConfig.h" + @protocol RollbarLogger #pragma mark - properties @@ -51,7 +56,6 @@ data:(nullable NSDictionary *)data context:(nullable NSString *)context; - @end #endif /* RollbarLoggerProtocol_h */ diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index b15b8dac..c270be02 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -109,6 +109,9 @@ - (void)testLive { ]; +// id logger = [RollbarInfrastructure newLogger]; +// [logger log:RollbarLevel_Critical message:@"From Logger!" data:nil context:nil]; + [NSThread sleepForTimeInterval:5.0f]; // items = [RollbarLogger readLogItemsFromStore]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m index 1ac984bf..c385880c 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m @@ -13,7 +13,6 @@ #import "../../Sources/RollbarNotifier/RollbarLoggerRegistry.h" #import "../../Sources/RollbarNotifier/RollbarDestinationRecord.h" #import "../../Sources/RollbarNotifier/RollbarLoggerRecord.h" -#import "../../Sources/RollbarNotifier/RollbarLogger+Extension.h" @interface RollbarLoggerRegistryTests : XCTestCase @@ -41,13 +40,13 @@ - (void)testBasics { XCTAssertNotNil(loggerA); XCTAssertEqual(1, [registry totalDestinationRecords]); XCTAssertEqual(1, [registry totalLoggerRecords]); - XCTAssertEqual(1, loggerA.loggerRecord.destinationRecord.totalLoggerRecords); +// XCTAssertEqual(1, loggerA.loggerRecord.destinationRecord.totalLoggerRecords); RollbarLogger *loggerA1 = [registry loggerWithConfiguration:config]; XCTAssertNotNil(loggerA1); XCTAssertEqual(1, [registry totalDestinationRecords]); XCTAssertEqual(2, [registry totalLoggerRecords]); - XCTAssertEqual(2, loggerA1.loggerRecord.destinationRecord.totalLoggerRecords); +// XCTAssertEqual(2, loggerA1.loggerRecord.destinationRecord.totalLoggerRecords); config = [RollbarConfig configWithAccessToken:@"Token_B"]; @@ -55,20 +54,20 @@ - (void)testBasics { XCTAssertNotNil(loggerB); XCTAssertEqual(2, [registry totalDestinationRecords]); XCTAssertEqual(3, [registry totalLoggerRecords]); - XCTAssertEqual(1, loggerB.loggerRecord.destinationRecord.totalLoggerRecords); +// XCTAssertEqual(1, loggerB.loggerRecord.destinationRecord.totalLoggerRecords); - [registry unregisterLogger:loggerA]; +// [registry unregisterLogger:loggerA]; XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); XCTAssertEqual(2, [registry totalLoggerRecords]); - XCTAssertEqual(1, loggerA1.loggerRecord.destinationRecord.totalLoggerRecords); +// XCTAssertEqual(1, loggerA1.loggerRecord.destinationRecord.totalLoggerRecords); - [registry unregisterLogger:loggerA1]; +// [registry unregisterLogger:loggerA1]; XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); XCTAssertEqual(1, [registry totalLoggerRecords]); - XCTAssertEqual(1, loggerB.loggerRecord.destinationRecord.totalLoggerRecords); +// XCTAssertEqual(1, loggerB.loggerRecord.destinationRecord.totalLoggerRecords); - [registry unregisterLogger:loggerB]; +// [registry unregisterLogger:loggerB]; XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); XCTAssertEqual(0, [registry totalLoggerRecords]); } @@ -93,8 +92,8 @@ - (void)useLoggerWithinLimitedScope:(nonnull RollbarLoggerRegistry *)registry { XCTAssertNotNil(logger); XCTAssertEqual(1, [registry totalDestinationRecords]); XCTAssertEqual(1, [registry totalLoggerRecords]); - XCTAssertEqual(1, logger.loggerRecord.destinationRecord.totalLoggerRecords); - XCTAssertTrue(logger.loggerRecord.isInScope); +// XCTAssertEqual(1, logger.loggerRecord.destinationRecord.totalLoggerRecords); +// XCTAssertTrue(logger.loggerRecord.isInScope); } } From c54184ca3afa73652b2b14be5adf5e8fdd908cc3 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 7 Jul 2022 17:45:39 -0700 Subject: [PATCH 053/127] feat: integrated infrastructure with crash report collection and Rollbar session --- .../RollbarNotifier/RollbarInfrastructure.m | 38 +++++++++++++++++-- .../include/RollbarInfrastructure.h | 5 ++- .../RollbarInfrastructureTests.m | 6 +-- .../RollbarLoggerRegistryTests.m | 2 +- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index 35d630f5..d3899b93 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -4,12 +4,15 @@ #import "RollbarLoggerProtocol.h" #import "RollbarLogger.h" #import "RollbarNotifierFiles.h" +#import "RollbarCrashProcessor.h" +#import "RollbarSession.h" //#import "RollbarLoggerRegistry.h" @implementation RollbarInfrastructure { @private RollbarConfig *_configuration; RollbarLogger *_logger; + RollbarCrashProcessor *_crashProcessor; // RollbarLoggerRegistry *_loggerRegistry; } @@ -43,7 +46,14 @@ + (nonnull instancetype)sharedInstance { #pragma mark - instance methods -- (nonnull instancetype)configure:(nonnull RollbarConfig *)config { +- (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config { + + return [self configureWith:config + andCrashCollector:nil]; +} + +- (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config + andCrashCollector:(nullable id)crashCollector { [self assertValidConfiguration:config]; @@ -54,11 +64,31 @@ - (nonnull instancetype)configure:(nonnull RollbarConfig *)config { } self->_configuration = config; - self->_logger = nil; //will be created as needed using the new config... + self->_logger = nil; //will be created as needed using the current self->_configuration... + + RollbarCrashReportCheck crashReportCheck = nil; + if (crashCollector) { + + self->_crashProcessor = [RollbarCrashProcessor new]; + [crashCollector collectCrashReportsWithObserver:self->_crashProcessor]; + crashReportCheck = ^() { + + BOOL result = NO; + if (self->_crashProcessor.totalProcessedReports > 0) { + + result = YES; + } + return result; + }; + } + + [[RollbarSession sharedInstance] enableOomMonitoring:config.loggingOptions.enableOomDetection + withCrashCheck:crashReportCheck]; - RollbarSdkLog(@"%@ is configured with this RollbarConfig instance: \n%@", + RollbarSdkLog(@"%@ is configured with this RollbarConfig instance: \n%@ \nand crash collector %@", [RollbarInfrastructure rollbar_objectClassName], - config + config, + crashCollector ); return self; diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h index 225d58f0..c464b56f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarInfrastructure.h @@ -12,6 +12,7 @@ #import "RollbarLoggerProtocol.h" #import "RollbarConfig.h" +#import "RollbarCrashCollectorProtocol.h" NS_ASSUME_NONNULL_BEGIN @@ -24,7 +25,9 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - instance methods -- (nonnull instancetype)configure:(nonnull RollbarConfig *)config; +- (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config; +- (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config + andCrashCollector:(nullable id)crashCollector; - (nonnull id)createLogger; - (nonnull id)createLoggerWithConfig:(nonnull RollbarConfig *)config; - (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index c270be02..ab1e4986 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -34,7 +34,7 @@ - (void)testRollbarInfrastructureNotConfiguredException { @"An RollbarInfrastructureNotConfiguredException is expected!" ); - [[RollbarInfrastructure sharedInstance] configure:[RollbarConfig new]]; + [[RollbarInfrastructure sharedInstance] configureWith:[RollbarConfig new]]; XCTAssertNoThrow([RollbarInfrastructure sharedInstance].configuration, @"An RollbarInfrastructureNotConfiguredException is NOT expected!" @@ -60,7 +60,7 @@ - (void)testBasics { config.developerOptions.transmit = NO; config.developerOptions.logPayload = YES; config.loggingOptions.maximumReportsPerMinute = 180; - [[RollbarInfrastructure sharedInstance] configure:config]; + [[RollbarInfrastructure sharedInstance] configureWith:config]; [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical message:@"RollbarInfrastructure basics test!" data:nil @@ -101,7 +101,7 @@ - (void)testLive { ]; config.developerOptions.transmit = YES; config.developerOptions.logPayload = YES; - [[RollbarInfrastructure sharedInstance] configure:config]; + [[RollbarInfrastructure sharedInstance] configureWith:config]; [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical message:@"RollbarInfrastructure basics test!" data:nil diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m index c385880c..a1004944 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m @@ -75,7 +75,7 @@ - (void)testBasics { - (void)testLoggerScope { RollbarConfig *config = [RollbarConfig configWithAccessToken:@"Token"]; - [[RollbarInfrastructure sharedInstance] configure:config]; + [[RollbarInfrastructure sharedInstance] configureWith:config]; RollbarLoggerRegistry *registry = [RollbarLoggerRegistry new]; From 4e5febbf41987718cfe10468c16baac7b31c3339 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 7 Jul 2022 23:25:39 -0700 Subject: [PATCH 054/127] reafctor: Rollbar registry --- .../RollbarDestinationRecord.h | 15 +-- .../RollbarDestinationRecord.m | 68 ++--------- .../Sources/RollbarNotifier/RollbarLogger.m | 3 - .../RollbarNotifier/RollbarLoggerRecord.h | 30 ----- .../RollbarNotifier/RollbarLoggerRecord.m | 40 ------- ...lbarLoggerRegistry.h => RollbarRegistry.h} | 11 +- ...lbarLoggerRegistry.m => RollbarRegistry.m} | 36 ++---- .../Sources/RollbarNotifier/RollbarSender.h | 2 +- .../RollbarLoggerRegistryTests.m | 107 ------------------ .../RollbarRegistryTests.m | 50 ++++++++ 10 files changed, 74 insertions(+), 288 deletions(-) delete mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h delete mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m rename RollbarNotifier/Sources/RollbarNotifier/{RollbarLoggerRegistry.h => RollbarRegistry.h} (50%) rename RollbarNotifier/Sources/RollbarNotifier/{RollbarLoggerRegistry.m => RollbarRegistry.m} (63%) delete mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h index 77c163ca..134a1ee6 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h @@ -8,26 +8,17 @@ #import @class RollbarConfig; -@class RollbarLoggerRecord; -@class RollbarLoggerRegistry; -@class RollbarLogger; +@class RollbarRegistry; NS_ASSUME_NONNULL_BEGIN @interface RollbarDestinationRecord : NSObject @property (readonly, nonnull) NSString *destinationID; -@property (readonly, nonnull) NSSet *loggerRecords; -@property (readonly, nonnull) RollbarLoggerRegistry *registry; - -- (nonnull RollbarLogger *)addLoggerWithConfig:(nonnull RollbarConfig *)loggerConfig; -//- (void)removeLogger:(nonnull RollbarLogger *)logger; -- (void)removeLoggerRecord:(nonnull RollbarLoggerRecord *)loggerRecord; -- (NSUInteger)totalLoggerRecords; - +@property (readonly, nonnull) RollbarRegistry *registry; - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID - andRegistry:(RollbarLoggerRegistry *)registry + andRegistry:(nonnull RollbarRegistry *)registry NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m index 67bbfd0e..08e78ad2 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m @@ -1,33 +1,20 @@ #import "RollbarDestinationRecord.h" -#import "RollbarLoggerRecord.h" -#import "RollbarLogger.h" -#import "RollbarConfig.h" -#import "RollbarDestination.h" - -const NSUInteger DEFAULT_DestinationRecordCapacity = 10; @implementation RollbarDestinationRecord { @private - NSMutableSet *_loggerRecords; } #pragma mark - property accessors -- (NSSet *)loggerRecords { - - return [_loggerRecords copy]; -} - #pragma mark - initializers - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID - andRegistry:(RollbarLoggerRegistry *)registry { + andRegistry:(nonnull RollbarRegistry *)registry { if (self = [super init]) { self->_registry = registry; self->_destinationID = destinationID; - self->_loggerRecords = [NSMutableSet setWithCapacity:DEFAULT_DestinationRecordCapacity]; } return self; } @@ -35,56 +22,17 @@ - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID #pragma mark - overrides - (nonnull NSString *)description { - NSString *description = [NSString stringWithFormat:@"%@ - totalLoggerRecords: %lu", - super.description, - (unsigned long)[self totalLoggerRecords] + NSString *description = [NSString stringWithFormat:@"%@", + super.description ]; return description; } -#pragma mark - de/registration of loggers - -- (nonnull RollbarLogger *)addLoggerWithConfig:(nonnull RollbarConfig *)loggerConfig { - - RollbarLoggerRecord *loggerRecord = [[RollbarLoggerRecord alloc] initWithConfig:loggerConfig - andDestinationRecord:self]; - [self->_loggerRecords addObject:loggerRecord]; - return loggerRecord.logger; -} - -//- (void)removeLogger:(nonnull RollbarLogger *)logger { -// -// RollbarLoggerRecord *loggerRecord = nil; -// for (RollbarLoggerRecord *record in self->_loggerRecords) { -// if (logger == record.logger) { -// loggerRecord = record; -// break; -// } -// } -// -// if (loggerRecord) { -// [self removeLoggerRecord:loggerRecord]; -// } -// else { -// NSAssert(NO, @"Something wrong removing logger record from the registry!"); -// } +//- (NSString *)debugDescription { +// NSString *description = [NSString stringWithFormat:@"totalLoggerRecords: %lu", +// (unsigned long)[self totalLoggerRecords] +// ]; +// return description; //} -- (void)removeLoggerRecord:(nonnull RollbarLoggerRecord *)loggerRecord { - - [self->_loggerRecords removeObject:loggerRecord]; -} - -- (NSUInteger)totalLoggerRecords { - - return self->_loggerRecords.count; -} - -- (NSString *)debugDescription { - NSString *description = [NSString stringWithFormat:@"totalLoggerRecords: %lu", - (unsigned long)[self totalLoggerRecords] - ]; - return description; -} - @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index d736a44d..49a24f1c 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -15,9 +15,6 @@ #import "RollbarPayloadTruncator.h" #import "RollbarConfig.h" #import "RollbarNotifierFiles.h" -#import "RollbarLoggerRegistry.h" -#import "RollbarLoggerRecord.h" -#import "RollbarDestinationRecord.h" #import "RollbarPayloadDTOs.h" diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h deleted file mode 100644 index 44cfe68b..00000000 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.h +++ /dev/null @@ -1,30 +0,0 @@ -// -// RollbarLoggerRecord.h -// -// -// Created by Andrey Kornich on 2022-06-28. -// - -#import - -@class RollbarConfig; -@class RollbarLogger; -@class RollbarDestinationRecord; - -NS_ASSUME_NONNULL_BEGIN - -@interface RollbarLoggerRecord : NSObject - -@property (readonly) BOOL isInScope; -@property (readonly, nonnull) RollbarLogger *logger; -@property (readonly, nonnull) RollbarDestinationRecord *destinationRecord; - -- (void)markAsOutOfScope; - -- (instancetype)initWithConfig:(nonnull RollbarConfig *)config - andDestinationRecord:(nonnull RollbarDestinationRecord *)destinationRecord; -- (instancetype)init NS_UNAVAILABLE; - -@end - -NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m deleted file mode 100644 index 46fc31f4..00000000 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRecord.m +++ /dev/null @@ -1,40 +0,0 @@ -#import "RollbarLoggerRecord.h" -#import "RollbarLogger.h" -#import "RollbarInfrastructure.h" - -@implementation RollbarLoggerRecord { - @private - BOOL _isInScope; -} - -//- (BOOL)isInScope { -// -// if (self->_logger == [RollbarInfrastructure sharedInstance].logger) { -// return NO; -// } -// else { -// return self->_isInScope; -// } -//} - -- (void)markAsOutOfScope { - - self->_isInScope = NO; -} - -- (instancetype)initWithConfig:(nonnull RollbarConfig *)config - andDestinationRecord:(nonnull RollbarDestinationRecord *)destinationRecord { - - if (self = [super init]) { - - self->_isInScope = YES; - -// self->_logger = [[RollbarLogger alloc] initWithConfiguration:config -// andLoggerRecord:self]; - self->_destinationRecord = destinationRecord; - } - - return self; -} - -@end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h similarity index 50% rename from RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h rename to RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h index d7200866..3584c147 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h @@ -1,5 +1,5 @@ // -// RollbarLoggerRegistry.h +// RollbarRegistry.h // // // Created by Andrey Kornich on 2022-06-28. @@ -7,18 +7,15 @@ #import -#import "RollbarConfig.h" -#import "RollbarLogger.h" +#import "RollbarDestination.h" #import "RollbarDestinationRecord.h" NS_ASSUME_NONNULL_BEGIN -@interface RollbarLoggerRegistry : NSObject +@interface RollbarRegistry : NSObject -- (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)config; -//- (void)unregisterLogger:(nonnull RollbarLogger *)logger; +- (nonnull RollbarDestinationRecord *)getRecordForDestination:(nonnull RollbarDestination *)destination; - (NSUInteger)totalDestinationRecords; -- (NSUInteger)totalLoggerRecords; + (nonnull NSString *)destinationID:(nonnull RollbarDestination *)destination; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m similarity index 63% rename from RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m rename to RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m index 7bcdffa5..1cdf66d8 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLoggerRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m @@ -1,15 +1,9 @@ -#import "RollbarLoggerRegistry.h" +#import "RollbarRegistry.h" #import "RollbarDestinationRecord.h" -#import "RollbarLoggerRecord.h" - -#import "RollbarLogger.h" - -#import "RollbarConfig.h" -#import "RollbarDestination.h" const NSUInteger DEFAULT_RegistryCapacity = 10; -@implementation RollbarLoggerRegistry { +@implementation RollbarRegistry { @private NSMutableDictionary *_destinationRecords; } @@ -22,12 +16,11 @@ - (instancetype)init { return self; } -- (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)config { - - NSAssert(config, @"Config must not be null!"); - - NSString *destinationID = [RollbarLoggerRegistry destinationID:config.destination]; +- (nonnull RollbarDestinationRecord *)getRecordForDestination:(nonnull RollbarDestination *)destination { + + NSAssert(destination, @"Destination must not be null!"); + NSString *destinationID = [RollbarRegistry destinationID:destination]; RollbarDestinationRecord *destinationRecord = self->_destinationRecords[destinationID]; if (!destinationRecord) { destinationRecord = [[RollbarDestinationRecord alloc] initWithDestinationID:destinationID @@ -35,27 +28,14 @@ - (nonnull RollbarLogger *)loggerWithConfiguration:(nonnull RollbarConfig *)conf ]; self->_destinationRecords[destinationID] = destinationRecord; } - - RollbarLogger *logger = [destinationRecord addLoggerWithConfig:config]; - return logger; -} -//- (void)unregisterLogger:(nonnull RollbarLogger *)logger { -// [logger.loggerRecord.destinationRecord removeLoggerRecord:logger.loggerRecord]; -//} + return destinationRecord; +} - (NSUInteger)totalDestinationRecords { return self->_destinationRecords.count; } -- (NSUInteger)totalLoggerRecords { - NSUInteger total = 0; - for (RollbarDestinationRecord *destinationRecord in self->_destinationRecords.allValues) { - total += destinationRecord.totalLoggerRecords; - } - return total; -} - #pragma mark - overrides - (nonnull NSString *)description { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h index d81bd9b2..ae11e523 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.h @@ -15,7 +15,7 @@ NS_ASSUME_NONNULL_BEGIN @interface RollbarSender : NSObject - (nullable RollbarPayloadPostReply *)sendPayload:(nonnull NSData *)payload - usingConfig:(nonnull RollbarConfig *)config; + usingConfig:(nonnull RollbarConfig *)config; @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m deleted file mode 100644 index a1004944..00000000 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarLoggerRegistryTests.m +++ /dev/null @@ -1,107 +0,0 @@ -// -// RollbarLoggerRegistryTests.m -// -// -// Created by Andrey Kornich on 2022-06-30. -// - -#import - -@import Foundation; -@import RollbarNotifier; - -#import "../../Sources/RollbarNotifier/RollbarLoggerRegistry.h" -#import "../../Sources/RollbarNotifier/RollbarDestinationRecord.h" -#import "../../Sources/RollbarNotifier/RollbarLoggerRecord.h" - -@interface RollbarLoggerRegistryTests : XCTestCase - -@end - -@implementation RollbarLoggerRegistryTests - -- (void)setUp { - // Put setup code here. This method is called before the invocation of each test method in the class. -} - -- (void)tearDown { - // Put teardown code here. This method is called after the invocation of each test method in the class. -} - -- (void)testBasics { - - RollbarLoggerRegistry *registry = [RollbarLoggerRegistry new]; - XCTAssertNotNil(registry); - XCTAssertEqual(0, [registry totalDestinationRecords]); - - RollbarConfig *config = [RollbarConfig configWithAccessToken:@"Token_A"]; - - RollbarLogger *loggerA = [registry loggerWithConfiguration:config]; - XCTAssertNotNil(loggerA); - XCTAssertEqual(1, [registry totalDestinationRecords]); - XCTAssertEqual(1, [registry totalLoggerRecords]); -// XCTAssertEqual(1, loggerA.loggerRecord.destinationRecord.totalLoggerRecords); - - RollbarLogger *loggerA1 = [registry loggerWithConfiguration:config]; - XCTAssertNotNil(loggerA1); - XCTAssertEqual(1, [registry totalDestinationRecords]); - XCTAssertEqual(2, [registry totalLoggerRecords]); -// XCTAssertEqual(2, loggerA1.loggerRecord.destinationRecord.totalLoggerRecords); - - config = [RollbarConfig configWithAccessToken:@"Token_B"]; - - RollbarLogger *loggerB = [registry loggerWithConfiguration:config]; - XCTAssertNotNil(loggerB); - XCTAssertEqual(2, [registry totalDestinationRecords]); - XCTAssertEqual(3, [registry totalLoggerRecords]); -// XCTAssertEqual(1, loggerB.loggerRecord.destinationRecord.totalLoggerRecords); - - -// [registry unregisterLogger:loggerA]; - XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); - XCTAssertEqual(2, [registry totalLoggerRecords]); -// XCTAssertEqual(1, loggerA1.loggerRecord.destinationRecord.totalLoggerRecords); - -// [registry unregisterLogger:loggerA1]; - XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); - XCTAssertEqual(1, [registry totalLoggerRecords]); -// XCTAssertEqual(1, loggerB.loggerRecord.destinationRecord.totalLoggerRecords); - -// [registry unregisterLogger:loggerB]; - XCTAssertEqual(2, [registry totalDestinationRecords], @"All registry records stay!"); - XCTAssertEqual(0, [registry totalLoggerRecords]); -} - -- (void)testLoggerScope { - - RollbarConfig *config = [RollbarConfig configWithAccessToken:@"Token"]; - [[RollbarInfrastructure sharedInstance] configureWith:config]; - - RollbarLoggerRegistry *registry = [RollbarLoggerRegistry new]; - - XCTAssertNotNil(registry); - XCTAssertEqual(0, [registry totalDestinationRecords]); - - [self useLoggerWithinLimitedScope:registry]; -} - -- (void)useLoggerWithinLimitedScope:(nonnull RollbarLoggerRegistry *)registry { - - @autoreleasepool { - RollbarLogger *logger = [registry loggerWithConfiguration:[RollbarConfig new]]; //[[RollbarInfrastructure sharedInstance] createLogger]; - XCTAssertNotNil(logger); - XCTAssertEqual(1, [registry totalDestinationRecords]); - XCTAssertEqual(1, [registry totalLoggerRecords]); -// XCTAssertEqual(1, logger.loggerRecord.destinationRecord.totalLoggerRecords); -// XCTAssertTrue(logger.loggerRecord.isInScope); - } -} - -- (void)testPerformanceExample { - // This is an example of a performance test case. - [self measureBlock:^{ - // Put the code you want to measure the time of here. - }]; -} - -@end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m new file mode 100644 index 00000000..c6ddeaff --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m @@ -0,0 +1,50 @@ +// +// RollbarLoggerRegistryTests.m +// +// +// Created by Andrey Kornich on 2022-06-30. +// + +#import + +@import Foundation; +@import RollbarNotifier; + +#import "../../Sources/RollbarNotifier/RollbarRegistry.h" +#import "../../Sources/RollbarNotifier/RollbarDestinationRecord.h" + +@interface RollbarLoggerRegistryTests : XCTestCase + +@end + +@implementation RollbarLoggerRegistryTests + +- (void)setUp { + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. +} + +- (void)testDestinationID { + + RollbarDestination *destination = [[RollbarDestination alloc] initWithEndpoint:@"End_Point" + accessToken:@"Access_Token" + environment:@"ENV" + ]; + + NSString *destinationID = [RollbarRegistry destinationID:destination]; + XCTAssertTrue([destinationID containsString:@"End_Point"]); + XCTAssertTrue([destinationID containsString:@"Access_Token"]); + XCTAssertFalse([destinationID containsString:@"ENV"]); +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end From 2ea93307e3bb0a7c1612524eff578e03cb4ba86c Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 7 Jul 2022 23:57:10 -0700 Subject: [PATCH 055/127] refactor: rollbar registry --- .../RollbarDestinationRecord.h | 15 ++++++++++-- .../RollbarDestinationRecord.m | 24 +++++++++++++++++++ .../Sources/RollbarNotifier/RollbarRegistry.h | 7 +++--- .../Sources/RollbarNotifier/RollbarRegistry.m | 13 +++++++--- 4 files changed, 51 insertions(+), 8 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h index 134a1ee6..042f88ae 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h @@ -7,16 +7,27 @@ #import -@class RollbarConfig; -@class RollbarRegistry; +#import "RollbarConfig.h" +#import "RollbarRegistry.h" NS_ASSUME_NONNULL_BEGIN @interface RollbarDestinationRecord : NSObject @property (readonly, nonnull) NSString *destinationID; + +@property (readwrite) NSUInteger localWindowLimit; + +@property (readonly) NSUInteger localWindowCount; +@property (readonly) NSUInteger serverWindowCount; +@property (readonly, nullable) NSDate *nextLocalWindowStart; +@property (readonly, nullable) NSDate *nextServerWindowStart; + @property (readonly, nonnull) RollbarRegistry *registry; +- (instancetype)initWithConfig:(nonnull RollbarConfig *)config + andRegistry:(nonnull RollbarRegistry *)registry +NS_DESIGNATED_INITIALIZER; - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID andRegistry:(nonnull RollbarRegistry *)registry NS_DESIGNATED_INITIALIZER; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m index 08e78ad2..48abfbba 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m @@ -8,6 +8,25 @@ @implementation RollbarDestinationRecord { #pragma mark - initializers +- (instancetype)initWithConfig:(nonnull RollbarConfig *)config + andRegistry:(nonnull RollbarRegistry *)registry { + + NSAssert(config, @"Config can not be nil!"); + NSAssert(config.destination, @"Config destination can not be nil!"); + NSAssert(registry, @"Registry can not be nil!"); + + if (self = [super init]) { + + self->_registry = registry; + self->_destinationID = [RollbarRegistry destinationID:config.destination]; + self->_localWindowLimit = config.loggingOptions.maximumReportsPerMinute; + self->_localWindowCount = 0; + self->_serverWindowCount =0; + self->_nextLocalWindowStart = nil; + self->_nextServerWindowStart = nil; + } +} + - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID andRegistry:(nonnull RollbarRegistry *)registry { @@ -15,6 +34,11 @@ - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID self->_registry = registry; self->_destinationID = destinationID; + self->_localWindowLimit = 0; + self->_localWindowCount = 0; + self->_serverWindowCount =0; + self->_nextLocalWindowStart = nil; + self->_nextServerWindowStart = nil; } return self; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h index 3584c147..fe5776fc 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h @@ -7,14 +7,15 @@ #import -#import "RollbarDestination.h" -#import "RollbarDestinationRecord.h" +#import "RollbarConfig.h" + +@class RollbarDestinationRecord; NS_ASSUME_NONNULL_BEGIN @interface RollbarRegistry : NSObject -- (nonnull RollbarDestinationRecord *)getRecordForDestination:(nonnull RollbarDestination *)destination; +- (nonnull RollbarDestinationRecord *)getRecordForConfig:(nonnull RollbarConfig *)config; - (NSUInteger)totalDestinationRecords; + (nonnull NSString *)destinationID:(nonnull RollbarDestination *)destination; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m index 1cdf66d8..cfe3cd75 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m @@ -16,11 +16,12 @@ - (instancetype)init { return self; } -- (nonnull RollbarDestinationRecord *)getRecordForDestination:(nonnull RollbarDestination *)destination { +- (nonnull RollbarDestinationRecord *)getRecordForConfig:(nonnull RollbarConfig *)config { - NSAssert(destination, @"Destination must not be null!"); + NSAssert(config, @"Config must not be null!"); + NSAssert(config.destination, @"Destination must not be null!"); - NSString *destinationID = [RollbarRegistry destinationID:destination]; + NSString *destinationID = [RollbarRegistry destinationID:config.destination]; RollbarDestinationRecord *destinationRecord = self->_destinationRecords[destinationID]; if (!destinationRecord) { destinationRecord = [[RollbarDestinationRecord alloc] initWithDestinationID:destinationID @@ -29,6 +30,12 @@ - (nonnull RollbarDestinationRecord *)getRecordForDestination:(nonnull RollbarDe self->_destinationRecords[destinationID] = destinationRecord; } + if (destinationRecord.localWindowLimit < config.loggingOptions.maximumReportsPerMinute) { + + // we use lagest configured limit per destination: + destinationRecord.localWindowLimit = config.loggingOptions.maximumReportsPerMinute; + } + return destinationRecord; } From ba1a4432b7b8c2607e902c2aa3be8dfd39c747f4 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 8 Jul 2022 21:06:59 -0700 Subject: [PATCH 056/127] feat: integrating the registry --- .../RollbarNotifier/RollbarDestinationRecord.h | 7 ++++++- .../RollbarNotifier/RollbarDestinationRecord.m | 15 +++++++++++++++ .../Sources/RollbarNotifier/RollbarRegistry.h | 3 +-- .../Sources/RollbarNotifier/RollbarThread.m | 14 +++++++++++++- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h index 042f88ae..914b7c42 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h @@ -8,7 +8,9 @@ #import #import "RollbarConfig.h" -#import "RollbarRegistry.h" +#import "RollbarPayloadPostReply.h" + +@class RollbarRegistry; NS_ASSUME_NONNULL_BEGIN @@ -25,6 +27,9 @@ NS_ASSUME_NONNULL_BEGIN @property (readonly, nonnull) RollbarRegistry *registry; +- (BOOL)canPost; +- (void)recordPostReply:(nullable RollbarPayloadPostReply *)reply; + - (instancetype)initWithConfig:(nonnull RollbarConfig *)config andRegistry:(nonnull RollbarRegistry *)registry NS_DESIGNATED_INITIALIZER; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m index 48abfbba..b87658e1 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m @@ -1,4 +1,5 @@ #import "RollbarDestinationRecord.h" +#import "RollbarRegistry.h" @implementation RollbarDestinationRecord { @private @@ -43,6 +44,20 @@ - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID return self; } +#pragma mark - methods + +- (BOOL)canPost { + + //TODO: implement... + return YES; +} + +- (void)recordPostReply:(nullable RollbarPayloadPostReply *)reply { + + //TODO: implement... + // should be able to process nil as reply! +} + #pragma mark - overrides - (nonnull NSString *)description { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h index fe5776fc..72332a9b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h @@ -7,10 +7,9 @@ #import +#import "RollbarDestinationRecord.h" #import "RollbarConfig.h" -@class RollbarDestinationRecord; - NS_ASSUME_NONNULL_BEGIN @interface RollbarRegistry : NSObject diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 3175cc92..2248aa1a 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -16,6 +16,7 @@ #import "RollbarProxy.h" #import "RollbarSender.h" #import "RollbarPayloadPostReply.h" +#import "RollbarRegistry.h" static NSUInteger MAX_RETRY_COUNT = 5; @@ -24,6 +25,7 @@ @implementation RollbarThread { @private //RollbarLogger *_logger; NSUInteger _maxReportsPerMinute; + RollbarRegistry *_registry; NSTimer *_timer; NSString *_queuedItemsFilePath; @@ -49,6 +51,8 @@ - (instancetype)initWithTarget:(id)target [self setupDataStorage]; self->_maxReportsPerMinute = 240;//60; + self->_registry = [RollbarRegistry new]; + self->_reachability = nil; self->_isNetworkReachable = YES; self->_nextSendTime = [[NSDate alloc] init]; @@ -461,7 +465,15 @@ - (BOOL)sendPayload:(nonnull NSData *)payload return NO; } - RollbarPayloadPostReply *reply = [[RollbarSender new] sendPayload:payload usingConfig:config]; + RollbarDestinationRecord *record = [self->_registry getRecordForConfig:config]; + if (![record canPost]) { + return NO; + } + + RollbarPayloadPostReply *reply = [[RollbarSender new] sendPayload:payload + usingConfig:config + ]; + [record recordPostReply:reply]; if (reply && (200 == reply.statusCode)) { return YES; } From 23f13eff68ebd8bdc7732f633fddd4efd8a194bd Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 12 Jul 2022 17:10:37 -0700 Subject: [PATCH 057/127] feat: integrated the Rollbar registry --- .../RollbarDestinationRecord.h | 3 +- .../RollbarDestinationRecord.m | 100 ++++++++++++++++-- .../RollbarNotifier/RollbarPayloadPostReply.h | 4 +- .../RollbarNotifier/RollbarPayloadPostReply.m | 43 +++++++- .../RollbarPayloadPostReplyTests.m | 4 +- .../RollbarRegistryTests.m | 95 ++++++++++++++++- 6 files changed, 229 insertions(+), 20 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h index 914b7c42..01423a2f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h @@ -21,9 +21,10 @@ NS_ASSUME_NONNULL_BEGIN @property (readwrite) NSUInteger localWindowLimit; @property (readonly) NSUInteger localWindowCount; -@property (readonly) NSUInteger serverWindowCount; +@property (readonly) NSUInteger serverWindowRemainingCount; @property (readonly, nullable) NSDate *nextLocalWindowStart; @property (readonly, nullable) NSDate *nextServerWindowStart; +@property (readonly, nonnull) NSDate *nextEarliestPost; @property (readonly, nonnull) RollbarRegistry *registry; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m index b87658e1..fcfdda7a 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m @@ -22,9 +22,10 @@ - (instancetype)initWithConfig:(nonnull RollbarConfig *)config self->_destinationID = [RollbarRegistry destinationID:config.destination]; self->_localWindowLimit = config.loggingOptions.maximumReportsPerMinute; self->_localWindowCount = 0; - self->_serverWindowCount =0; + self->_serverWindowRemainingCount = 0; self->_nextLocalWindowStart = nil; self->_nextServerWindowStart = nil; + self->_nextEarliestPost = [NSDate date]; } } @@ -37,9 +38,10 @@ - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID self->_destinationID = destinationID; self->_localWindowLimit = 0; self->_localWindowCount = 0; - self->_serverWindowCount =0; + self->_serverWindowRemainingCount = 0; self->_nextLocalWindowStart = nil; self->_nextServerWindowStart = nil; + self->_nextEarliestPost = [NSDate date]; } return self; } @@ -48,21 +50,103 @@ - (instancetype)initWithDestinationID:(nonnull NSString *)destinationID - (BOOL)canPost { - //TODO: implement... - return YES; + if (!self->_nextEarliestPost) { + return NO; + } + + if (NSOrderedDescending == [self->_nextEarliestPost compare:[NSDate date]]) { + return NO; + } + else { + return YES; + } } - (void)recordPostReply:(nullable RollbarPayloadPostReply *)reply { - //TODO: implement... - // should be able to process nil as reply! + if (!reply) { + //no response from the server to our lates POST of a payload, + //let's hold on on posting to the destination for 1 minute: + self->_nextEarliestPost = [NSDate dateWithTimeIntervalSinceNow:60]; + self->_localWindowCount = 0; + self->_serverWindowRemainingCount = 0; + self->_nextLocalWindowStart = self->_nextEarliestPost; + self->_nextServerWindowStart = nil; + return; // nothing else to do... + } + + switch(reply.statusCode) { + case 429: // too many requests + self->_nextLocalWindowStart = [NSDate dateWithTimeIntervalSinceNow:reply.remainingSeconds];; + self->_serverWindowRemainingCount = 0; + break; + case 403: // access denied + case 404: // not found + //let's hold on on posting to the destination for 1 minute: + self->_nextEarliestPost = [NSDate dateWithTimeIntervalSinceNow:60]; + self->_localWindowCount = 0; + self->_serverWindowRemainingCount = 0; + self->_nextLocalWindowStart = self->_nextEarliestPost; + self->_nextServerWindowStart = nil; + return; // nothing else to do... + case 200: // OK + case 400: // bad request + case 413: // request entity too large + case 422: // unprocessable entity + default: + self->_nextServerWindowStart = [NSDate dateWithTimeIntervalSinceNow:reply.remainingSeconds];; + self->_serverWindowRemainingCount = reply.remainingCount; + if (self->_nextLocalWindowStart ) { + self->_localWindowCount = 0; + self->_nextLocalWindowStart = [NSDate dateWithTimeIntervalSinceNow:60]; + } + else { + self->_localWindowCount += 1; + } + break; + } + + // since we got here, let's calculate value for self->_nextEarliestPost: + + if (self->_nextServerWindowStart && (0 == self->_serverWindowRemainingCount)) { + // server told us to wait until next rate limiting window: + self->_nextEarliestPost = self->_nextServerWindowStart; + return; + } + + if (self->_nextLocalWindowStart && (self->_localWindowCount >= self->_localWindowLimit)) { + // we already exceeded local rate limits, let's wait till the next local rate limiting window: + self->_nextEarliestPost = self->_nextLocalWindowStart; + return; + } + + // looks like no limits are in force now, keep sending ASAP: + self->_nextEarliestPost = [NSDate date]; + return; } #pragma mark - overrides - (nonnull NSString *)description { - NSString *description = [NSString stringWithFormat:@"%@", - super.description + NSString *description = [NSString stringWithFormat:@"%@:\n" + " destinationID: %@\n" + " localWindowLimit: %lu\n" + " localWindowCount: %lu\n" + " serverWindowRemainingCount: %lu\n" + " nextLocalWindowStart: %@\n" + " nextServerWindowStart: %@\n" + " nextEarliestPost: %@\n" + " canPost: %@\n" + , + super.description, + self->_destinationID, + self->_localWindowLimit, + self->_localWindowCount, + self->_serverWindowRemainingCount, + self->_nextLocalWindowStart, + self->_nextServerWindowStart, + self->_nextEarliestPost, + [self canPost] ? @"YES" : @"NO" ]; return description; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h index 58299d04..cf36b9c6 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.h @@ -22,10 +22,12 @@ NS_ASSUME_NONNULL_BEGIN remainingCount:(NSUInteger)remainingCount remainingSeconds:(NSUInteger)remainingSeconds; - - (instancetype)init NS_UNAVAILABLE; +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; + (nullable RollbarPayloadPostReply *)replyFromHttpResponse:(nonnull NSHTTPURLResponse *)httpResponse; + (nonnull RollbarPayloadPostReply *)greenReply; ++ (nonnull RollbarPayloadPostReply *)yellowReply; + (nonnull RollbarPayloadPostReply *)redReply; @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m index 759b581f..9f0ae7d1 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadPostReply.m @@ -54,23 +54,56 @@ - (instancetype)initWithStatusCode:(NSUInteger)statusCode return self; } -+ (nonnull RollbarPayloadPostReply *)greenReply { +#pragma mark - overrides + +- (nonnull NSString *)description { + NSString *description = [NSString stringWithFormat:@"%@:\n" + " statusCode: %li\n" + " rateLimit: %lu\n" + " remainingCount: %lu\n" + " remainingSeconds: %lu\n" + " nextPostTime: %@\n" + , + super.description, + self->_statusCode, + self->_rateLimit, + self->_remainingCount, + self->_remainingSeconds, + self->_nextPostTime + ]; + return description; +} - return [[RollbarPayloadPostReply alloc] initWithStatusCode:200 +#pragma mark - factory methods + ++ (nonnull RollbarPayloadPostReply *)greenReply { + + // the last POST was OK and can continue POSTing: + return [[RollbarPayloadPostReply alloc] initWithStatusCode:200 // OK rateLimit:1 remainingCount:1 remainingSeconds:1 ]; } -+ (nonnull RollbarPayloadPostReply *)redReply { ++ (nonnull RollbarPayloadPostReply *)yellowReply { - return [[RollbarPayloadPostReply alloc] initWithStatusCode:200 + // the last POST was OK but can not continue POSTing for another 10 [sec]: + return [[RollbarPayloadPostReply alloc] initWithStatusCode:200 // OK rateLimit:1 remainingCount:0 - remainingSeconds:1 + remainingSeconds:10 ]; } ++ (nonnull RollbarPayloadPostReply *)redReply { + + // the last POST failed due too many requests and can not continue POSTing for another 10 [sec]: + return [[RollbarPayloadPostReply alloc] initWithStatusCode:429 // too many requests... + rateLimit:1 + remainingCount:0 + remainingSeconds:10 + ]; +} @end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m index f4eb9481..f7e495a5 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m @@ -40,7 +40,7 @@ - (void)testWillPostLaterReply { remainingSeconds:20]; NSDate *now = [NSDate date]; XCTAssertEqual([now earlierDate:reply.nextPostTime], now); - XCTAssertTrue([reply.nextPostTime timeIntervalSinceDate:now] < 20); + XCTAssertTrue([reply.nextPostTime timeIntervalSinceDate:now] <= 20); } - (void)testGreenReply { @@ -55,7 +55,7 @@ - (void)testRedReply { RollbarPayloadPostReply *reply = [RollbarPayloadPostReply redReply]; NSDate *now = [NSDate date]; XCTAssertEqual([now earlierDate:reply.nextPostTime], now); - XCTAssertTrue([reply.nextPostTime timeIntervalSinceDate:now] < 1); + XCTAssertTrue([reply.nextPostTime timeIntervalSinceDate:now] <= 1); } - (void)testPerformanceExample { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m index c6ddeaff..79e9446c 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m @@ -12,6 +12,7 @@ #import "../../Sources/RollbarNotifier/RollbarRegistry.h" #import "../../Sources/RollbarNotifier/RollbarDestinationRecord.h" +#import "../../Sources/RollbarNotifier/RollbarPayloadPostReply.h" @interface RollbarLoggerRegistryTests : XCTestCase @@ -27,6 +28,90 @@ - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. } +#pragma mark - registry destination record tests + +- (void)testDestinationRecord { + + RollbarRegistry *registry = [RollbarRegistry new]; + XCTAssertEqual(0, registry.totalDestinationRecords); + + RollbarConfig *config = [RollbarConfig configWithAccessToken:@"AT1" + environment:@"Env1"]; + + RollbarDestinationRecord *record = [registry getRecordForConfig:config]; + XCTAssertEqual(1, registry.totalDestinationRecords); + XCTAssertEqual(YES, [record canPost]); + XCTAssertNotNil(record.nextEarliestPost); + XCTAssertNil(record.nextLocalWindowStart); + XCTAssertNil(record.nextServerWindowStart); + + RollbarPayloadPostReply *reply = [RollbarPayloadPostReply greenReply]; + [record recordPostReply:reply]; + XCTAssertTrue([record canPost]); + + reply = [RollbarPayloadPostReply yellowReply]; + [record recordPostReply:reply]; + XCTAssertFalse([record canPost]); + + reply = [RollbarPayloadPostReply redReply]; + [record recordPostReply:reply]; + XCTAssertFalse([record canPost]); +} + +#pragma mark - registry records tests + +- (void)testRegistryRecords { + + RollbarRegistry *registry = [RollbarRegistry new]; + XCTAssertEqual(0, registry.totalDestinationRecords); + + RollbarConfig *config = [RollbarConfig configWithAccessToken:@"AT1" + environment:@"Env1"]; + + RollbarDestinationRecord *record = [registry getRecordForConfig:config]; + XCTAssertEqual(1, registry.totalDestinationRecords); + XCTAssertTrue([record.destinationID containsString:@"https://api.rollbar.com/api/1/item/"]); + XCTAssertTrue([record.destinationID containsString:@"AT1"]); + XCTAssertFalse([record.destinationID containsString:@"Env1"]); + + RollbarConfig *config1 = [config copy]; + RollbarDestinationRecord *record1 = [registry getRecordForConfig:config1]; + XCTAssertEqual(1, registry.totalDestinationRecords); + XCTAssertTrue([record1.destinationID containsString:@"https://api.rollbar.com/api/1/item/"]); + XCTAssertTrue([record1.destinationID containsString:@"AT1"]); + XCTAssertFalse([record1.destinationID containsString:@"Env1"]); + XCTAssertEqualObjects(record, record1); + XCTAssertEqual(record, record1); + XCTAssertIdentical(record, record1); + XCTAssertTrue(record == record1); + + RollbarConfig *config2 = [RollbarConfig configWithAccessToken:@"AT2" + environment:@"Env2"]; + RollbarDestinationRecord *record2 = [registry getRecordForConfig:config2]; + XCTAssertEqual(2, registry.totalDestinationRecords); + XCTAssertTrue([record2.destinationID containsString:@"https://api.rollbar.com/api/1/item/"]); + XCTAssertTrue([record2.destinationID containsString:@"AT2"]); + XCTAssertFalse([record2.destinationID containsString:@"Env2"]); + XCTAssertNotEqualObjects(record2, record1); + XCTAssertNotEqual(record2, record1); + XCTAssertNotIdentical(record2, record1); + XCTAssertFalse(record2 == record1); +} + +- (void)testPerformanceOfNewDestinationRecord { + + RollbarRegistry *registry = [RollbarRegistry new]; + XCTAssertEqual(0, registry.totalDestinationRecords); + + RollbarConfig *config = [RollbarConfig configWithAccessToken:@"AT1" + environment:@"Env1"]; + [self measureBlock:^{ + RollbarDestinationRecord *record = [registry getRecordForConfig:config]; + }]; +} + +#pragma mark - destination ID tests + - (void)testDestinationID { RollbarDestination *destination = [[RollbarDestination alloc] initWithEndpoint:@"End_Point" @@ -40,10 +125,14 @@ - (void)testDestinationID { XCTAssertFalse([destinationID containsString:@"ENV"]); } -- (void)testPerformanceExample { - // This is an example of a performance test case. +- (void)testPerformanceDestinationID { + + RollbarDestination *destination = [[RollbarDestination alloc] initWithEndpoint:@"End_Point" + accessToken:@"Access_Token" + environment:@"ENV" + ]; [self measureBlock:^{ - // Put the code you want to measure the time of here. + NSString *destinationID = [RollbarRegistry destinationID:destination]; }]; } From 67a9fb26921ab3d8e8981687874c5630f545ddfd Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 15 Jul 2022 23:01:48 -0700 Subject: [PATCH 058/127] feat: refactor RollbarConfig related classes into im/mutable cass clusters --- .../Sources/RollbarCommon/DTOs/RollbarDTO.m | 73 ++- .../RollbarCommon/include/RollbarDTO.h | 2 +- .../RollbarNotifier/DTOs/RollbarConfig.m | 237 ++++++-- .../RollbarNotifier/DTOs/RollbarDestination.m | 36 +- .../DTOs/RollbarDeveloperOptions.m | 49 +- .../DTOs/RollbarLoggingOptions.m | 97 ++- .../RollbarNotifier/DTOs/RollbarModule.m | 37 +- .../RollbarNotifier/DTOs/RollbarPerson.m | 37 +- .../RollbarNotifier/DTOs/RollbarProxy.m | 31 +- .../DTOs/RollbarScrubbingOptions.m | 75 ++- .../DTOs/RollbarServerConfig.m | 46 +- .../DTOs/RollbarTelemetryOptions.m | 83 ++- .../Sources/RollbarNotifier/Rollbar.m | 8 +- .../RollbarNotifier/RollbarInfrastructure.m | 4 +- .../Sources/RollbarNotifier/RollbarLogger.m | 30 +- .../RollbarNotifier/RollbarPayloadFactory.m | 4 +- .../Sources/RollbarNotifier/include/Rollbar.h | 2 +- .../RollbarNotifier/include/RollbarConfig.h | 101 +++- .../include/RollbarDestination.h | 46 +- .../include/RollbarDeveloperOptions.h | 31 +- .../RollbarNotifier/include/RollbarLogger.h | 4 +- .../include/RollbarLoggingOptions.h | 51 +- .../RollbarNotifier/include/RollbarModule.h | 43 +- .../RollbarNotifier/include/RollbarPerson.h | 75 ++- .../RollbarNotifier/include/RollbarProxy.h | 21 +- .../include/RollbarScrubbingOptions.h | 74 ++- .../include/RollbarServerConfig.h | 48 +- .../include/RollbarTelemetryOptions.h | 74 ++- .../RollbarNotifierTests-ObjC/DTOsTests.m | 48 +- .../RollbarConfigTests.m | 562 ++++++++++++++++++ .../RollbarConfigurationTests.m | 4 +- .../RollbarInfrastructureTests.m | 10 +- .../RollbarNotifierTests-ObjC/RollbarTests.m | 13 +- .../RollbarNotifierConfigUtilTests.swift | 2 +- .../RollbarNotifierConfigurationTests.swift | 14 +- .../RollbarNotifierDTOsTests.swift | 28 +- .../RollbarNotifierLoggerTests.swift | 8 +- .../RollbarNotifierTelemetryTests.swift | 10 +- .../RollbarNotifierTruncationTests.swift | 2 +- 39 files changed, 1714 insertions(+), 406 deletions(-) create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m diff --git a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m index 0ec2f397..9f97f995 100644 --- a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m +++ b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m @@ -1,6 +1,7 @@ #import "RollbarDTO.h" #import "RollbarSdkLog.h" #import "NSJSONSerialization+Rollbar.h" +#import "NSObject+Rollbar.h" @import ObjectiveC.runtime; @@ -318,14 +319,6 @@ -(BOOL)isEmpty { return NO; } -#pragma mark - NSCopying protocol - --(id) copyWithZone: (NSZone *) zone { - - RollbarDTO *clone = [[[self class] allocWithZone:zone] initWithJSONString:[self serializeToJSONString]]; - return clone; -} - #pragma mark - Initializers - (instancetype)initWithJSONString: (NSString *)jsonString { @@ -433,4 +426,68 @@ - (instancetype)init { return self; } +//-(instancetype)init { +// +// if (self = [self initWithDictionary:@{}]) { +// return self; +// } +// return nil; +//} + + +#pragma mark - NSCopying protocol + +-(id) copyWithZone: (NSZone *) zone { + + NSString *thisClassName = [self rollbar_objectClassName]; + + if (YES == [thisClassName hasPrefix:@"RollbarMutable"]) { + NSBundle *classBundle = [NSBundle bundleForClass:[self class]]; + NSString *immutableClassName = [thisClassName stringByReplacingOccurrencesOfString:@"RollbarMutable" + withString:@"Rollbar"]; + Class immutableClass = [classBundle classNamed:immutableClassName]; + if (immutableClass) { + RollbarDTO *clone = [[immutableClass allocWithZone:zone] initWithJSONString:[self serializeToJSONString]]; + return clone; + } + } + else if ((YES == [thisClassName hasPrefix:@"Rollbar"]) && (NO == [thisClassName hasPrefix:@"RollbarMutable"])) { + NSBundle *classBundle = [NSBundle bundleForClass:[self class]]; + NSString *mutableClassName = [thisClassName stringByReplacingOccurrencesOfString:@"Rollbar" + withString:@"RollbarMutable"]; + Class mutableClass = [classBundle classNamed:mutableClassName]; + if (mutableClass) { + // OPTIMIZATION: + // Since we have a mutable alternative to ths class, + // it means this is an instance of an immutable class. + // Hence, there is no need to clone an immutable object. + return self; + } + } + + RollbarDTO *clone = [[[self class] allocWithZone:zone] initWithJSONString:[self serializeToJSONString]]; + return clone; +} + +#pragma mark - NSMutableCopying protocol + +-(id) mutableCopyWithZone: (NSZone *) zone { + + NSString *thisClassName = [self rollbar_objectClassName]; + + if ((NO == [thisClassName hasPrefix:@"RollbarMutable"]) && (YES == [thisClassName hasPrefix:@"Rollbar"])) { + NSBundle *classBundle = [NSBundle bundleForClass:[self class]]; + NSString *mutableClassName = [thisClassName stringByReplacingOccurrencesOfString:@"Rollbar" + withString:@"RollbarMutable"]; + Class mutableClass = [classBundle classNamed:mutableClassName]; + if (mutableClass) { + RollbarDTO *clone = [[mutableClass allocWithZone:zone] initWithJSONString:[self serializeToJSONString]]; + return clone; + } + } + + RollbarDTO *clone = [[[self class] allocWithZone:zone] initWithJSONString:[self serializeToJSONString]]; + return clone; +} + @end diff --git a/RollbarCommon/Sources/RollbarCommon/include/RollbarDTO.h b/RollbarCommon/Sources/RollbarCommon/include/RollbarDTO.h index 9cb445d4..2aedacdc 100644 --- a/RollbarCommon/Sources/RollbarCommon/include/RollbarDTO.h +++ b/RollbarCommon/Sources/RollbarCommon/include/RollbarDTO.h @@ -8,7 +8,7 @@ NS_ASSUME_NONNULL_BEGIN /// The foundation for defining Rollbar Data Transfer Objects (DTOs). -@interface RollbarDTO : NSObject { +@interface RollbarDTO : NSObject { @private id _data; //... diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m index 3aede7f4..fe9ac849 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m @@ -59,9 +59,9 @@ + (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token { NSAssert(token, @"Access token must be initialized!"); NSAssert(token.length > 0, @"Access token must not be empty string!"); - RollbarConfig *config = [RollbarConfig new]; - config.destination.accessToken = token; - + RollbarConfig *config = [[RollbarConfig alloc] initWithAccessToken:token + environment:nil]; + return config; } @@ -70,16 +70,54 @@ + (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token environm NSAssert(env, @"Environment must be initialized!"); NSAssert(env.length > 0, @"Environment must not be empty string!"); - RollbarConfig *config = [RollbarConfig configWithAccessToken:token]; - config.destination.environment = env; + RollbarConfig *config = [[RollbarConfig alloc] initWithAccessToken:token + environment:env]; return config; } #pragma mark - initializers -- (instancetype)init { +- (instancetype)initWithAccessToken:(nullable NSString *)token environment:(nullable NSString *)env { + + RollbarDestination *destination = nil; + if (token && env) { + destination = [[RollbarDestination alloc] initWithAccessToken:token environment:env]; + } + else if (token) { + destination = [[RollbarDestination alloc] initWithAccessToken:token]; + } + else { + destination = [[RollbarMutableDestination alloc] init]; + } + + if (!destination) { + return nil; + } + + if (self = [super initWithDictionary:@{ + DFK_DESTINATION:destination.jsonFriendlyData, + DFK_DEVELOPER_OPTIONS:[RollbarDeveloperOptions new].jsonFriendlyData, + DFK_LOGGING_OPTIONS:[RollbarLoggingOptions new].jsonFriendlyData, + DFK_HTTP_PROXY:[RollbarProxy new].jsonFriendlyData, + DFK_HTTPS_PROXY:[RollbarProxy new].jsonFriendlyData, + DFK_DATA_SCRUBBER:[RollbarScrubbingOptions new].jsonFriendlyData, + DFK_TELEMETRY:[RollbarTelemetryOptions new].jsonFriendlyData, + DFK_NOTIFIER:[[RollbarModule alloc] initWithName:NOTIFIER_NAME version:NOTIFIER_VERSION].jsonFriendlyData, + DFK_SERVER:[RollbarServerConfig new].jsonFriendlyData, + DFK_PERSON: [NSMutableDictionary new], + DFK_CUSTOM: [NSMutableDictionary new] + }]) { + + return self; + } + + return nil; +} + +- (instancetype)init { + self = [super initWithDictionary:@{ DFK_DESTINATION:[RollbarDestination new].jsonFriendlyData, DFK_DEVELOPER_OPTIONS:[RollbarDeveloperOptions new].jsonFriendlyData, @@ -96,7 +134,6 @@ - (instancetype)init { return self; } - #pragma mark - Rollbar destination - (RollbarDestination *)destination { @@ -105,37 +142,157 @@ - (RollbarDestination *)destination { return dto; } +#pragma mark - Developer options + +- (RollbarDeveloperOptions *)developerOptions { + id data = [self safelyGetDictionaryByKey:DFK_DEVELOPER_OPTIONS]; + return [[RollbarDeveloperOptions alloc] initWithDictionary:data]; +} + +#pragma mark - Logging options + +- (RollbarLoggingOptions *)loggingOptions { + id data = [self safelyGetDictionaryByKey:DFK_LOGGING_OPTIONS]; + return [[RollbarLoggingOptions alloc] initWithDictionary:data]; +} + +#pragma mark - Notifier + +- (RollbarModule *)notifier { + id data = [self safelyGetDictionaryByKey:DFK_NOTIFIER]; + return [[RollbarModule alloc] initWithDictionary:data]; +} + +#pragma mark - Data scrubber + +- (RollbarScrubbingOptions *)dataScrubber { + id data = [self safelyGetDictionaryByKey:DFK_DATA_SCRUBBER]; + return [[RollbarScrubbingOptions alloc] initWithDictionary:data]; +} + +#pragma mark - Server + +- (RollbarServerConfig *)server { + id data = [self safelyGetDictionaryByKey:DFK_SERVER]; + return [[RollbarServerConfig alloc] initWithDictionary:data]; +} + +#pragma mark - Person + +- (RollbarPerson *)person { + id data = [self safelyGetDictionaryByKey:DFK_PERSON]; + return [[RollbarPerson alloc] initWithDictionary:data]; +} + +#pragma mark - HTTP Proxy Settings + +- (RollbarProxy *)httpProxy { + id data = [self safelyGetDictionaryByKey:DFK_HTTP_PROXY]; + return [[RollbarProxy alloc] initWithDictionary:data]; +} + +#pragma mark - HTTPS Proxy Settings + +- (RollbarProxy *)httpsProxy { + id data = [self safelyGetDictionaryByKey:DFK_HTTPS_PROXY]; + return [[RollbarProxy alloc] initWithDictionary:data]; +} + +#pragma mark - Telemetry + +- (RollbarTelemetryOptions *)telemetry { + id data = [self safelyGetDictionaryByKey:DFK_TELEMETRY]; + return [[RollbarTelemetryOptions alloc] initWithDictionary:data]; +} + +#pragma mark - Custom data + +- (NSDictionary *)customData { + NSMutableDictionary *result = [self safelyGetDictionaryByKey:DFK_CUSTOM]; + return result; +} + +#pragma mark - Payload Content Related + +@synthesize checkIgnoreRollbarData = _checkIgnoreRollbarData; + +@synthesize modifyRollbarData = _modifyRollbarData; + + +//#pragma mark - RollbarPersistent protocol +// +//- (BOOL)loadFromFile:(nonnull NSString *)filePath { +//} +// +//- (BOOL)saveToFile:(nonnull NSString *)filePath { +//} + +@end + +@implementation RollbarMutableConfig + +#pragma mark - initializers + +-(instancetype)init { + + if (self = [super initWithDictionary:@{}]) { + return self; + } + return nil; +} + +#pragma mark - Payload Content Related + +@dynamic checkIgnoreRollbarData; +@dynamic modifyRollbarData; + +- (void)setCheckIgnoreRollbarData:(BOOL (^)(RollbarData * _Nonnull))checkIgnoreRollbarData { + self->_checkIgnoreRollbarData = checkIgnoreRollbarData; +} + +- (void)setModifyRollbarData:(RollbarData * _Nonnull (^)(RollbarData * _Nonnull))modifyRollbarData { + self->_modifyRollbarData = modifyRollbarData; +} + +#pragma mark - Rollbar destination + +- (RollbarMutableDestination *)destination { + id data = [self safelyGetDictionaryByKey:DFK_DESTINATION]; + id dto = [[RollbarMutableDestination alloc] initWithDictionary:data]; + return dto; +} + - (void)setDestination:(RollbarDestination *)destination { - [self setDataTransferObject:destination forKey:DFK_DESTINATION]; + [self setDataTransferObject:[destination mutableCopy] forKey:DFK_DESTINATION]; } #pragma mark - Developer options -- (RollbarDeveloperOptions *)developerOptions { +- (RollbarMutableDeveloperOptions *)developerOptions { id data = [self safelyGetDictionaryByKey:DFK_DEVELOPER_OPTIONS]; - return [[RollbarDeveloperOptions alloc] initWithDictionary:data]; + return [[RollbarMutableDeveloperOptions alloc] initWithDictionary:data]; } - (void)setDeveloperOptions:(RollbarDeveloperOptions *)developerOptions { - [self setDataTransferObject:developerOptions forKey:DFK_DEVELOPER_OPTIONS]; + [self setDataTransferObject:[developerOptions mutableCopy] forKey:DFK_DEVELOPER_OPTIONS]; } #pragma mark - Logging options -- (RollbarLoggingOptions *)loggingOptions { +- (RollbarMutableLoggingOptions *)loggingOptions { id data = [self safelyGetDictionaryByKey:DFK_LOGGING_OPTIONS]; - return [[RollbarLoggingOptions alloc] initWithDictionary:data]; + return [[RollbarMutableLoggingOptions alloc] initWithDictionary:data]; } -- (void)setLoggingOptions:(RollbarLoggingOptions *)developerOptions { - [self setDataTransferObject:developerOptions forKey:DFK_LOGGING_OPTIONS]; +- (void)setLoggingOptions:(RollbarLoggingOptions *)loggingOptions { + [self setDataTransferObject:[loggingOptions mutableCopy] forKey:DFK_LOGGING_OPTIONS]; } #pragma mark - Notifier -- (RollbarModule *)notifier { +- (RollbarMutableModule *)notifier { id data = [self safelyGetDictionaryByKey:DFK_NOTIFIER]; - return [[RollbarModule alloc] initWithDictionary:data]; + return [[RollbarMutableModule alloc] initWithDictionary:data]; } - (void)setNotifier:(RollbarModule *)developerOptions { @@ -144,31 +301,31 @@ - (void)setNotifier:(RollbarModule *)developerOptions { #pragma mark - Data scrubber -- (RollbarScrubbingOptions *)dataScrubber { +- (RollbarMutableScrubbingOptions *)dataScrubber { id data = [self safelyGetDictionaryByKey:DFK_DATA_SCRUBBER]; - return [[RollbarScrubbingOptions alloc] initWithDictionary:data]; + return [[RollbarMutableScrubbingOptions alloc] initWithDictionary:data]; } - (void)setDataScrubber:(RollbarScrubbingOptions *)value { - [self setDataTransferObject:value forKey:DFK_DATA_SCRUBBER]; + [self setDataTransferObject:[value mutableCopy] forKey:DFK_DATA_SCRUBBER]; } #pragma mark - Server -- (RollbarServerConfig *)server { +- (RollbarMutableServerConfig *)server { id data = [self safelyGetDictionaryByKey:DFK_SERVER]; - return [[RollbarServerConfig alloc] initWithDictionary:data]; + return [[RollbarMutableServerConfig alloc] initWithDictionary:data]; } - (void)setServer:(RollbarServerConfig *)value { - [self setDataTransferObject:value forKey:DFK_SERVER]; + [self setDataTransferObject:[value mutableCopy] forKey:DFK_SERVER]; } #pragma mark - Person -- (RollbarPerson *)person { +- (RollbarMutablePerson *)person { id data = [self safelyGetDictionaryByKey:DFK_PERSON]; - return [[RollbarPerson alloc] initWithDictionary:data]; + return [[RollbarMutablePerson alloc] initWithDictionary:data]; } - (void)setPerson:(RollbarPerson *)value { @@ -177,35 +334,35 @@ - (void)setPerson:(RollbarPerson *)value { #pragma mark - HTTP Proxy Settings -- (RollbarProxy *)httpProxy { +- (RollbarMutableProxy *)httpProxy { id data = [self safelyGetDictionaryByKey:DFK_HTTP_PROXY]; - return [[RollbarProxy alloc] initWithDictionary:data]; + return [[RollbarMutableProxy alloc] initWithDictionary:data]; } - (void)setHttpProxy:(RollbarProxy *)value { - [self setDataTransferObject:value forKey:DFK_HTTP_PROXY]; + [self setDataTransferObject:[value mutableCopy] forKey:DFK_HTTP_PROXY]; } #pragma mark - HTTPS Proxy Settings -- (RollbarProxy *)httpsProxy { +- (RollbarMutableProxy *)httpsProxy { id data = [self safelyGetDictionaryByKey:DFK_HTTPS_PROXY]; - return [[RollbarProxy alloc] initWithDictionary:data]; + return [[RollbarMutableProxy alloc] initWithDictionary:data]; } - (void)setHttpsProxy:(RollbarProxy *)value { - [self setDataTransferObject:value forKey:DFK_HTTPS_PROXY]; + [self setDataTransferObject:[value mutableCopy] forKey:DFK_HTTPS_PROXY]; } #pragma mark - Telemetry -- (RollbarTelemetryOptions *)telemetry { +- (RollbarMutableTelemetryOptions *)telemetry { id data = [self safelyGetDictionaryByKey:DFK_TELEMETRY]; - return [[RollbarTelemetryOptions alloc] initWithDictionary:data]; + return [[RollbarMutableTelemetryOptions alloc] initWithDictionary:data]; } - (void)setTelemetry:(RollbarTelemetryOptions *)value { - [self setDataTransferObject:value forKey:DFK_TELEMETRY]; + [self setDataTransferObject:[value mutableCopy] forKey:DFK_TELEMETRY]; } #pragma mark - Convenience Methods @@ -236,21 +393,13 @@ - (void)setNotifierName:(nullable NSString *)name #pragma mark - Custom data -- (NSDictionary *)customData { +- (NSMutableDictionary *)customData { NSMutableDictionary *result = [self safelyGetDictionaryByKey:DFK_CUSTOM]; return result; } -- (void)setCustomData:(NSDictionary *)value { +- (void)setCustomData:(NSMutableDictionary *)value { [self setDictionary:value forKey:DFK_CUSTOM]; } -//#pragma mark - RollbarPersistent protocol -// -//- (BOOL)loadFromFile:(nonnull NSString *)filePath { -//} -// -//- (BOOL)saveToFile:(nonnull NSString *)filePath { -//} - @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDestination.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDestination.m index fe259455..2fa20104 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDestination.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDestination.m @@ -60,24 +60,44 @@ - (NSString *)endpoint { return result; } -- (void)setEndpoint:(NSString *)value { - [self setString:value forKey:DFK_ENDPOINT]; -} - - (NSString *)accessToken { NSString *result = [self safelyGetStringByKey:DFK_ACCESS_TOKEN]; return result; } -- (void)setAccessToken:(NSString *)value { - [self setString:value forKey:DFK_ACCESS_TOKEN]; -} - - (NSString *)environment { NSString *result = [self safelyGetStringByKey:DFK_ENVIRONMENT]; return result; } +@end + +@implementation RollbarMutableDestination + +#pragma mark - initializers + +-(instancetype)init { + + if (self = [super initWithDictionary:@{}]) { + return self; + } + return nil; +} + +#pragma mark - property accessors + +@dynamic endpoint; +@dynamic accessToken; +@dynamic environment; + +- (void)setEndpoint:(NSString *)value { + [self setString:value forKey:DFK_ENDPOINT]; +} + +- (void)setAccessToken:(NSString *)value { + [self setString:value forKey:DFK_ACCESS_TOKEN]; +} + - (void)setEnvironment:(NSString *)value { [self setString:value forKey:DFK_ENVIRONMENT]; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m index 8d56206f..d8bac73d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m @@ -66,42 +66,59 @@ - (BOOL)enabled { return [result boolValue]; } -- (void)setEnabled:(BOOL)value { - [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_ENABLED]; -} - - (BOOL)transmit { NSNumber *result = [self safelyGetNumberByKey:DFK_TRANSMIT]; return [result boolValue]; } -- (void)setTransmit:(BOOL)value { - [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_TRANSMIT]; -} - - (BOOL)suppressSdkInfoLogging { NSNumber *result = [self safelyGetNumberByKey:DFK_SUPPRESS_SDK_INFO_LOGGING]; return [result boolValue]; } -- (void)setSuppressSdkInfoLogging:(BOOL)value { - [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_SUPPRESS_SDK_INFO_LOGGING]; -} - - (BOOL)logPayload { NSNumber *result = [self safelyGetNumberByKey:DFK_LOG_PAYLOAD]; return [result boolValue]; } -- (void)setLogPayload:(BOOL)value { - [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_LOG_PAYLOAD]; -} - - (NSString *)payloadLogFile { NSString *result = [self safelyGetStringByKey:DFK_LOG_PAYLOAD_FILE]; return result; } +@end + +@implementation RollbarMutableDeveloperOptions + +@dynamic enabled; +@dynamic transmit; +@dynamic suppressSdkInfoLogging; +@dynamic logPayload; +@dynamic payloadLogFile; + +#pragma mark - property accessors + +- (void)setEnabled:(BOOL)value { + [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_ENABLED]; +} + +- (void)setTransmit:(BOOL)value { + [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_TRANSMIT]; +} + +- (void)setSuppressSdkInfoLogging:(BOOL)value { + [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_SUPPRESS_SDK_INFO_LOGGING]; +} + +- (void)setLogPayload:(BOOL)value { + [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_LOG_PAYLOAD]; +} + +//- (NSString *)payloadLogFile { +// NSString *result = [self safelyGetStringByKey:DFK_LOG_PAYLOAD_FILE]; +// return result; +//} + - (void)setPayloadLogFile:(NSString *)value { [self setString:value forKey:DFK_LOG_PAYLOAD_FILE]; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarLoggingOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarLoggingOptions.m index fc81ac21..76cefa16 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarLoggingOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarLoggingOptions.m @@ -158,71 +158,108 @@ - (RollbarLevel)logLevel { return [RollbarLevelUtil RollbarLevelFromString:logLevelString]; } -- (void)setLogLevel:(RollbarLevel)level { - NSString *levelString = [RollbarLevelUtil RollbarLevelToString:level]; - [self setString:levelString forKey:DFK_LOG_LEVEL]; -} - - (RollbarLevel)crashLevel { NSString *logLevelString = [self safelyGetStringByKey:DFK_CRASH_LEVEL]; return [RollbarLevelUtil RollbarLevelFromString:logLevelString]; } -- (void)setCrashLevel:(RollbarLevel)level { - NSString *levelString = [RollbarLevelUtil RollbarLevelToString:level]; - [self setString:levelString forKey:DFK_CRASH_LEVEL]; -} - - (NSUInteger)maximumReportsPerMinute { return [self safelyGetUIntegerByKey:DFK_MAX_REPORTS_PER_MINUTE withDefault:DEFAULT_MAX_REPORTS_PER_MINUTE]; } -- (void)setMaximumReportsPerMinute:(NSUInteger)value { - [self setUInteger:value forKey:DFK_MAX_REPORTS_PER_MINUTE]; -} - - (RollbarCaptureIpType)captureIp { NSString *valueString = [self safelyGetStringByKey:DFK_IP_CAPTURE_TYPE]; return [RollbarCaptureIpTypeUtil CaptureIpTypeFromString:valueString]; } +- (nullable NSString *)codeVersion { + return [self getDataByKey:DFK_CODE_VERSION]; +} + +- (nullable NSString *)framework; { + return [self getDataByKey:DFK_FRAMEWORK]; +} + +- (nullable NSString *)requestId { + return [self getDataByKey:DFK_REQUEST_ID]; +} + +- (BOOL)enableOomDetection { + + BOOL result = [self safelyGetBoolByKey:DFK_OOM_DETECTION + withDefault:DEFAULT_OOM_DETECTION]; + return result; +} + +@end + +@implementation RollbarMutableLoggingOptions + +#pragma mark - initializers + +-(instancetype)init { + + if (self = [super initWithDictionary:@{}]) { + return self; + } + return nil; +} + +#pragma mark - property accessors + +@dynamic logLevel; +@dynamic crashLevel; +@dynamic maximumReportsPerMinute; +@dynamic captureIp; +@dynamic codeVersion; +@dynamic framework; +@dynamic requestId; +@dynamic enableOomDetection; + +- (void)setLogLevel:(RollbarLevel)level { + NSString *levelString = [RollbarLevelUtil RollbarLevelToString:level]; + [self setString:levelString forKey:DFK_LOG_LEVEL]; +} + +- (void)setCrashLevel:(RollbarLevel)level { + NSString *levelString = [RollbarLevelUtil RollbarLevelToString:level]; + [self setString:levelString forKey:DFK_CRASH_LEVEL]; +} + +- (void)setMaximumReportsPerMinute:(NSUInteger)value { + [self setUInteger:value forKey:DFK_MAX_REPORTS_PER_MINUTE]; +} + - (void)setCaptureIp:(RollbarCaptureIpType)value { NSString *valueString = [RollbarCaptureIpTypeUtil CaptureIpTypeToString:value]; [self setString:valueString forKey:DFK_IP_CAPTURE_TYPE]; } -- (nullable NSString *)codeVersion { - return [self getDataByKey:DFK_CODE_VERSION]; -} +//- (nullable NSString *)codeVersion { +// return [self getDataByKey:DFK_CODE_VERSION]; +//} - (void)setCodeVersion:(nullable NSString *)value { [self setData:value byKey:DFK_CODE_VERSION]; } -- (nullable NSString *)framework; { - return [self getDataByKey:DFK_FRAMEWORK]; -} +//- (nullable NSString *)framework; { +// return [self getDataByKey:DFK_FRAMEWORK]; +//} - (void)setFramework:(nullable NSString *)value { [self setData:value byKey:DFK_FRAMEWORK]; } -- (nullable NSString *)requestId { - return [self getDataByKey:DFK_REQUEST_ID]; -} +//- (nullable NSString *)requestId { +// return [self getDataByKey:DFK_REQUEST_ID]; +//} - (void)setRequestId:(nullable NSString *)value { [self setData:value byKey:DFK_REQUEST_ID]; } -- (BOOL)enableOomDetection { - - BOOL result = [self safelyGetBoolByKey:DFK_OOM_DETECTION - withDefault:DEFAULT_OOM_DETECTION]; - return result; -} - - (void)setEnableOomDetection:(BOOL)value { [self setBool:value diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarModule.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarModule.m index 9acf0f3a..1428ed68 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarModule.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarModule.m @@ -18,11 +18,14 @@ @implementation RollbarModule - (instancetype)initWithName:(nullable NSString *)name version:(nullable NSString *)version { - self = [super initWithDictionary:@{ + if (self = [super initWithDictionary:@{ DFK_NAME:name ? name : [NSNull null], DFK_VERSION:version ? version : [NSNull null] - }]; - return self; + }]) { + return self; + } + + return nil;; } - (instancetype)initWithName:(nullable NSString *)name { @@ -36,14 +39,34 @@ - (nullable NSString *)name { return [self getDataByKey:DFK_NAME]; } -- (void)setName:(nullable NSString *)value { - [self setData:value byKey:DFK_NAME]; -} - - (nullable NSString *)version { return [self getDataByKey:DFK_VERSION]; } +@end + + +@implementation RollbarMutableModule + +#pragma mark - initializers + +-(instancetype)init { + + if (self = [super initWithDictionary:@{}]) { + return self; + } + return nil; +} + +#pragma mark - property accessors + +@dynamic name; +@dynamic version; + +- (void)setName:(nullable NSString *)value { + [self setData:value byKey:DFK_NAME]; +} + - (void)setVersion:(nullable NSString *)value { [self setData:value byKey:DFK_VERSION]; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarPerson.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarPerson.m index 4208154c..9768dba0 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarPerson.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarPerson.m @@ -63,24 +63,45 @@ - (NSString *)ID { return (nil != result) ? result : @""; } -- (void)setID:(NSString *)value { +- (NSString *)username { - [self setData:value byKey:DFK_ID]; + return [self getDataByKey:DFK_USERNAME]; } -- (NSString *)username { +- (NSString *)email { - return [self getDataByKey:DFK_USERNAME]; + return [self getDataByKey:DFK_EMAIL]; } -- (void)setUsername:(NSString *)value { +@end + + +@implementation RollbarMutablePerson + +#pragma mark - initializers + +-(instancetype)init { - [self setData:value byKey:DFK_USERNAME]; + if (self = [super initWithDictionary:@{}]) { + return self; + } + return nil; } -- (NSString *)email { +#pragma mark - property accessors + +@dynamic ID; +@dynamic username; +@dynamic email; + +- (void)setID:(NSString *)value { - return [self getDataByKey:DFK_EMAIL]; + [self setData:value byKey:DFK_ID]; +} + +- (void)setUsername:(NSString *)value { + + [self setData:value byKey:DFK_USERNAME]; } - (void)setEmail:(NSString *)value { diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarProxy.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarProxy.m index dc54804a..a63e8ef4 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarProxy.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarProxy.m @@ -47,25 +47,40 @@ - (BOOL)enabled { return [result boolValue]; } -- (void)setEnabled:(BOOL)value { - [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_ENABLED]; -} - - (NSString *)proxyUrl { NSString *result = [self safelyGetStringByKey:DFK_PROXY_URL]; return result; } -- (void)setProxyUrl:(NSString *)value { - [self setString:value forKey:DFK_PROXY_URL]; -} - - (NSUInteger)proxyPort { NSUInteger result = [self safelyGetUIntegerByKey:DFK_PROXY_PORT withDefault:DEFAULT_PROXY_PORT]; return result; } +@end + +@implementation RollbarMutableProxy + +@dynamic enabled; +@dynamic proxyUrl; +@dynamic proxyPort; + +#pragma mark - property accessors + +- (void)setEnabled:(BOOL)value { + [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_ENABLED]; +} + +//- (NSString *)proxyUrl { +// NSString *result = [self safelyGetStringByKey:DFK_PROXY_URL]; +// return result; +//} + +- (void)setProxyUrl:(NSString *)value { + [self setString:value forKey:DFK_PROXY_URL]; +} + - (void)setProxyPort:(NSUInteger)value { [self setUInteger:value forKey:DFK_PROXY_PORT]; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarScrubbingOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarScrubbingOptions.m index 10417026..ef8f50ef 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarScrubbingOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarScrubbingOptions.m @@ -65,46 +65,83 @@ - (BOOL)enabled { return [result boolValue]; } +- (NSArray *)scrubFields { + NSArray *result = [self safelyGetArrayByKey:DFK_SCRUB_FIELDS]; + return result; +} + +- (NSArray *)safeListFields { + NSArray *result = [self safelyGetArrayByKey:DFK_SAFELIST_FIELDS]; + return result; +} + +@end + + +@implementation RollbarMutableScrubbingOptions + +#pragma mark - initializers + +-(instancetype)init { + + if (self = [super initWithDictionary:@{}]) { + return self; + } + return nil; +} + +#pragma mark - property accessors + +@dynamic enabled; + - (void)setEnabled:(BOOL)value { [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_ENABLED]; } -- (NSArray *)scrubFields { - NSArray *result = [self safelyGetArrayByKey:DFK_SCRUB_FIELDS]; +- (NSMutableArray *)scrubFields { + NSMutableArray *result = [self safelyGetArrayByKey:DFK_SCRUB_FIELDS]; return result; } - (void)setScrubFields:(NSArray *)scrubFields { - [self setArray:scrubFields forKey:DFK_SCRUB_FIELDS]; + [self setArray:[scrubFields mutableCopy] forKey:DFK_SCRUB_FIELDS]; } -- (void)addScrubField:(NSString *)field { - self.scrubFields = - [self.scrubFields arrayByAddingObject:field]; +- (NSMutableArray *)safeListFields { + NSMutableArray *result = [self safelyGetArrayByKey:DFK_SAFELIST_FIELDS]; + return result; } -- (void)removeScrubField:(NSString *)field { - NSMutableArray *mutableCopy = self.scrubFields.mutableCopy; - [mutableCopy removeObject:field]; - self.scrubFields = mutableCopy.copy; +- (void)setSafeListFields:(NSArray *)whitelistFields { + [self setArray:[whitelistFields mutableCopy] forKey:DFK_SAFELIST_FIELDS]; } -- (NSArray *)safeListFields { - NSArray *result = [self safelyGetArrayByKey:DFK_SAFELIST_FIELDS]; - return result; + +#pragma mark - methods + +- (void)addScrubField:(NSString *)field { +// self.scrubFields = +// [self.scrubFields arrayByAddingObject:field]; + [self.scrubFields addObject:field]; } -- (void)setSafeListFields:(NSArray *)whitelistFields { - [self setArray:whitelistFields forKey:DFK_SAFELIST_FIELDS]; +- (void)removeScrubField:(NSString *)field { +// NSMutableArray *mutableCopy = self.scrubFields.mutableCopy; +// [mutableCopy removeObject:field]; +// self.scrubFields = mutableCopy.copy; + [self.scrubFields removeObject:field]; } - (void)addScrubSafeListField:(NSString *)field { - self.safeListFields = [self.safeListFields arrayByAddingObject:field]; +// self.safeListFields = [self.safeListFields arrayByAddingObject:field]; + [self.safeListFields addObject:field]; } - (void)removeScrubSafeListField:(NSString *)field { - NSMutableArray *mutableCopy = self.safeListFields.mutableCopy; - [mutableCopy removeObject:field]; - self.safeListFields = mutableCopy.copy; +// NSMutableArray *mutableCopy = self.safeListFields.mutableCopy; +// [mutableCopy removeObject:field]; +// self.safeListFields = mutableCopy.copy; + [self.safeListFields removeObject:field]; } + @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarServerConfig.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarServerConfig.m index e0ecf296..1219bc6b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarServerConfig.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarServerConfig.m @@ -46,29 +46,57 @@ - (nullable NSString *)host { return [self getDataByKey:DFK_HOST]; } +- (nullable NSString *)root { + return [self getDataByKey:DFK_ROOT]; +} + +- (nullable NSString *)branch { + return [self getDataByKey:DFK_BRANCH]; +} + +- (nullable NSString *)codeVersion { + return [self getDataByKey:DFK_CODE_VERSION]; +} + +@end + + +@implementation RollbarMutableServerConfig + +@dynamic host; +@dynamic root; +@dynamic branch; +@dynamic codeVersion; + +#pragma mark - property accessors + +//- (nullable NSString *)host { +// return [self getDataByKey:DFK_HOST]; +//} + - (void)setHost:(nullable NSString *)value { [self setData:value byKey:DFK_HOST]; } -- (nullable NSString *)root { - return [self getDataByKey:DFK_ROOT]; -} +//- (nullable NSString *)root { +// return [self getDataByKey:DFK_ROOT]; +//} - (void)setRoot:(nullable NSString *)value { [self setData:value byKey:DFK_ROOT]; } -- (nullable NSString *)branch { - return [self getDataByKey:DFK_BRANCH]; -} +//- (nullable NSString *)branch { +// return [self getDataByKey:DFK_BRANCH]; +//} - (void)setBranch:(nullable NSString *)value { [self setData:value byKey:DFK_BRANCH]; } -- (nullable NSString *)codeVersion { - return [self getDataByKey:DFK_CODE_VERSION]; -} +//- (nullable NSString *)codeVersion { +// return [self getDataByKey:DFK_CODE_VERSION]; +//} - (void)setCodeVersion:(nullable NSString *)value { [self setData:value byKey:DFK_CODE_VERSION]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarTelemetryOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarTelemetryOptions.m index 33d6eb87..13fd7c7c 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarTelemetryOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarTelemetryOptions.m @@ -73,63 +73,92 @@ - (BOOL)enabled { return result.boolValue; } -- (void)setEnabled:(BOOL)value { - - [self setNumber:[NSNumber numberWithBool:value] - forKey:DFK_ENABLED_FLAG - ]; -} - - (BOOL)captureLog { NSNumber *result = [self safelyGetNumberByKey:DFK_CAPTURE_LOG_FLAG]; return result.boolValue; } -- (void)setCaptureLog:(BOOL)value { - [self setNumber:[NSNumber numberWithBool:value] - forKey:DFK_CAPTURE_LOG_FLAG - ]; -} - - (BOOL)captureConnectivity { NSNumber *result = [self safelyGetNumberByKey:DFK_CAPTURE_CONNECTIVITY_FLAG]; return result.boolValue; } -- (void)setCaptureConnectivity:(BOOL)value { - [self setNumber:[NSNumber numberWithBool:value] - forKey:DFK_CAPTURE_CONNECTIVITY_FLAG - ]; -} - - (NSUInteger)maximumTelemetryData { NSUInteger result = [self safelyGetUIntegerByKey:DFK_MAX_TELEMETRY_DATA withDefault:DEFAULT_MAX_TELEMETRY_DATA]; return result; } -- (void)setMaximumTelemetryData:(NSUInteger)value { - [self setUInteger:value forKey:DFK_MAX_TELEMETRY_DATA]; -} - - (RollbarScrubbingOptions *)viewInputsScrubber { id data = [self safelyGetDictionaryByKey:DFK_VIEW_INPUTS_SCRUBBER]; id dto = [[RollbarScrubbingOptions alloc] initWithDictionary:data]; return dto; } -- (void)setViewInputsScrubber:(RollbarScrubbingOptions *)scrubber { - [self setDataTransferObject:scrubber forKey:DFK_VIEW_INPUTS_SCRUBBER]; -} - - (NSTimeInterval)memoryStatsAutocollectionInterval { NSTimeInterval result = [self safelyGetTimeIntervalByKey:DFK_AUTOCOLLECTION_INTERVAL_MEM_STATS withDefault:DEFAULT_AUTOCOLLECTION_INTERVAL_MEM_STATS]; return result; } +@end + + +@implementation RollbarMutableTelemetryOptions + +#pragma mark - initializers + +-(instancetype)init { + + if (self = [super initWithDictionary:@{}]) { + return self; + } + return nil; +} + +#pragma mark - property accessors + +@dynamic enabled; +@dynamic captureLog; +@dynamic captureConnectivity; +@dynamic maximumTelemetryData; +@dynamic memoryStatsAutocollectionInterval; + +- (void)setEnabled:(BOOL)value { + + [self setNumber:[NSNumber numberWithBool:value] + forKey:DFK_ENABLED_FLAG + ]; +} + +- (void)setCaptureLog:(BOOL)value { + [self setNumber:[NSNumber numberWithBool:value] + forKey:DFK_CAPTURE_LOG_FLAG + ]; +} + +- (void)setCaptureConnectivity:(BOOL)value { + [self setNumber:[NSNumber numberWithBool:value] + forKey:DFK_CAPTURE_CONNECTIVITY_FLAG + ]; +} + +- (void)setMaximumTelemetryData:(NSUInteger)value { + [self setUInteger:value forKey:DFK_MAX_TELEMETRY_DATA]; +} + - (void)setMemoryStatsAutocollectionInterval:(NSTimeInterval)value { [self setTimeInterval:value forKey:DFK_AUTOCOLLECTION_INTERVAL_MEM_STATS]; } +- (RollbarMutableScrubbingOptions *)viewInputsScrubber { + id data = [self safelyGetDictionaryByKey:DFK_VIEW_INPUTS_SCRUBBER]; + id dto = [[RollbarMutableScrubbingOptions alloc] initWithDictionary:data]; + return dto; +} + +- (void)setViewInputsScrubber:(RollbarScrubbingOptions *)scrubber { + [self setDataTransferObject:[scrubber mutableCopy] forKey:DFK_VIEW_INPUTS_SCRUBBER]; +} + @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m index 18012343..ab0faea7 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m +++ b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m @@ -91,7 +91,7 @@ + (void)initWithAccessToken:(nullable NSString *)accessToken RollbarSdkLog(@"Rollbar has already been initialized."); } else { - RollbarConfig *config = configuration ? configuration : [RollbarConfig new]; + RollbarMutableConfig *config = configuration ? [configuration mutableCopy] : [RollbarMutableConfig new]; if (accessToken && accessToken.length > 0) { config.destination.accessToken = accessToken; @@ -143,9 +143,9 @@ + (void)updateConfiguration:(RollbarConfig *)configuration { logger = [[RollbarLogger alloc] initWithConfiguration:configuration]; } - if (oldReportingRate != configuration.loggingOptions.maximumReportsPerMinute) { - [logger updateReportingRate:configuration.loggingOptions.maximumReportsPerMinute]; - } +// if (oldReportingRate != configuration.loggingOptions.maximumReportsPerMinute) { +// [logger updateReportingRate:configuration.loggingOptions.maximumReportsPerMinute]; +// } if (configuration && configuration.telemetry) { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index d3899b93..fade0533 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -109,7 +109,7 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config - (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token andEnvironment:(nonnull NSString *)env { - RollbarConfig *config = [self.configuration copy]; + RollbarMutableConfig *config = [self.configuration mutableCopy]; config.destination.accessToken = token; config.destination.environment = env; id logger = [self createLoggerWithConfig:config]; @@ -118,7 +118,7 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config - (nonnull id)createLoggerWithAccessToken:(nonnull NSString *)token { - RollbarConfig *config = [self.configuration copy]; + RollbarMutableConfig *config = [self.configuration mutableCopy]; config.destination.accessToken = token; id logger = [self createLoggerWithConfig:config]; return logger; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index 49a24f1c..9df62f88 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -49,17 +49,19 @@ + (instancetype)loggerWithConfiguration:(nonnull RollbarConfig *)configuration { #pragma mark - initializers - (instancetype)initWithAccessToken:(NSString *)accessToken { - RollbarConfig *config = [RollbarConfig new]; + RollbarMutableConfig *config = [RollbarMutableConfig new]; config.destination.accessToken = accessToken; return [self initWithConfiguration:config]; } + - (instancetype)initWithAccessToken:(nonnull NSString *)accessToken andEnvironment:(nonnull NSString *)environment { - RollbarConfig *config = [RollbarConfig new]; + RollbarMutableConfig *config = [RollbarMutableConfig new]; config.destination.accessToken = accessToken; config.destination.environment = environment; return [self initWithConfiguration:config]; } + - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration { if ((self = [super init])) { @@ -186,18 +188,18 @@ - (void)updateConfiguration:(RollbarConfig *)configuration { self.configuration = configuration; } -- (void)updateAccessToken:(NSString *)accessToken { - self.configuration.destination.accessToken = accessToken; -} - -- (void)updateReportingRate:(NSUInteger)maximumReportsPerMinute { - if (nil != self.configuration) { - self.configuration.loggingOptions.maximumReportsPerMinute = maximumReportsPerMinute; - } +//- (void)updateAccessToken:(NSString *)accessToken { +// self.configuration.destination.accessToken = accessToken; +//} - //[[RollbarThread sharedInstance] cancel]; - //[[RollbarThread sharedInstance] setReportingRate:maximumReportsPerMinute]; - //[[RollbarThread sharedInstance] start]; -} +//- (void)updateReportingRate:(NSUInteger)maximumReportsPerMinute { +// if (nil != self.configuration) { +// self.configuration.loggingOptions.maximumReportsPerMinute = maximumReportsPerMinute; +// } +// +// //[[RollbarThread sharedInstance] cancel]; +// //[[RollbarThread sharedInstance] setReportingRate:maximumReportsPerMinute]; +// //[[RollbarThread sharedInstance] start]; +//} @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m index aa1eb517..9f9e554e 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m @@ -125,7 +125,9 @@ -(BOOL)shouldIgnoreRollbarData:(nonnull RollbarData *)incomingData { RollbarSdkLog(@"checkIgnore error: %@", e.reason); // Remove checkIgnore to prevent future exceptions - self->_config.checkIgnoreRollbarData = nil; + //self->_config.checkIgnoreRollbarData = nil; + NSAssert(false, @"Provided checkIgnore implementation throws an exception!"); + return NO; } } diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h index 5f5d46b7..38f4a74a 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h @@ -56,7 +56,7 @@ static void uncaughtExceptionHandler(NSException * _Nonnull exception); #pragma mark - Configuration /// The shared Rollbar master configuration. -+ (nullable RollbarConfig *)currentConfiguration; ++ (nullable RollbarMutableConfig *)currentConfiguration; /// Updates with a shared configuration. /// @param configuration a new Rollbar configuration diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h index bbe0ddfc..bd20c1c3 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h @@ -11,7 +11,6 @@ #import "RollbarTelemetryOptions.h" #import "RollbarLoggingOptions.h" #import "RollbarData.h" - #import "RollbarCaptureIpType.h" #import "RollbarLevel.h" @@ -19,52 +18,119 @@ NS_ASSUME_NONNULL_BEGIN -/// Rollbar configuration structured model +/// Immutable Rollbar configuration structured model @interface RollbarConfig : RollbarDTO { + + BOOL (^_checkIgnoreRollbarData)(RollbarData *rollbarData); + RollbarData *(^_modifyRollbarData)(RollbarData *rollbarData); + + //TODO: to be removed: BOOL _isRootConfiguration; } +#pragma mark - Factory Methods + ++ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token; + ++ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token environment:(nonnull NSString *)env; + #pragma mark - properties /// Destination related settings -@property (nonnull, nonatomic, strong) RollbarDestination *destination; +@property (nonnull, nonatomic, readonly, strong) RollbarDestination *destination; /// Developer related settings -@property (nonnull, nonatomic, strong) RollbarDeveloperOptions *developerOptions; +@property (nonnull, nonatomic, readonly, strong) RollbarDeveloperOptions *developerOptions; /// Logging related settings -@property (nonnull, nonatomic, strong) RollbarLoggingOptions *loggingOptions; +@property (nonnull, nonatomic, readonly, strong) RollbarLoggingOptions *loggingOptions; /// HTTP proxy related settings -@property (nonnull, nonatomic, strong) RollbarProxy *httpProxy; +@property (nonnull, nonatomic, readonly, strong) RollbarProxy *httpProxy; /// HTTPS proxy related settings -@property (nonnull, nonatomic, strong) RollbarProxy *httpsProxy; +@property (nonnull, nonatomic, readonly, strong) RollbarProxy *httpsProxy; /// Data scrubbing related settings -@property (nonnull, nonatomic, strong) RollbarScrubbingOptions *dataScrubber; +@property (nonnull, nonatomic, readonly, strong) RollbarScrubbingOptions *dataScrubber; /// Server related settings -@property (nonnull, nonatomic, strong) RollbarServerConfig *server; +@property (nonnull, nonatomic, readonly, strong) RollbarServerConfig *server; /// Person/user related settings -@property (nonnull, nonatomic, strong) RollbarPerson *person; +@property (nonnull, nonatomic, readonly, strong) RollbarPerson *person; /// Notifier related settings -@property (nonnull, nonatomic, strong) RollbarModule *notifier; +@property (nonnull, nonatomic, readonly, strong) RollbarModule *notifier; /// Telemetry related settings -@property (nonnull, nonatomic, strong) RollbarTelemetryOptions *telemetry; +@property (nonnull, nonatomic, readonly, strong) RollbarTelemetryOptions *telemetry; #pragma mark - Custom data -@property (nonatomic, strong) NSDictionary *customData; +@property (nonatomic, readonly, strong) NSDictionary *customData; #pragma mark - Payload Content Related /// Decides whether or not to send provided payload data. Returns true to ignore, false to send -@property (nullable, nonatomic, copy) BOOL (^checkIgnoreRollbarData)(RollbarData *rollbarData); +@property (nullable, atomic, readonly, copy) BOOL (^checkIgnoreRollbarData)(RollbarData *rollbarData); + /// Modifies payload data before sending -@property (nullable, nonatomic, copy) RollbarData *(^modifyRollbarData)(RollbarData *rollbarData); +@property (nullable, atomic, readonly, copy) RollbarData *(^modifyRollbarData)(RollbarData *rollbarData); + +@end + + +/// Mutable Rollbar configuration structured model +@interface RollbarMutableConfig : RollbarConfig + +#pragma mark - initializers + +- (instancetype)init +NS_DESIGNATED_INITIALIZER; + +#pragma mark - properties + +/// Destination related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutableDestination *destination; + +/// Developer related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutableDeveloperOptions *developerOptions; + +/// Logging related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutableLoggingOptions *loggingOptions; + +/// HTTP proxy related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutableProxy *httpProxy; + +/// HTTPS proxy related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutableProxy *httpsProxy; + +/// Data scrubbing related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutableScrubbingOptions *dataScrubber; + +/// Server related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutableServerConfig *server; + +/// Person/user related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutablePerson *person; + +/// Notifier related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutableModule *notifier; + +/// Telemetry related settings +@property (nonnull, nonatomic, readwrite, strong) RollbarMutableTelemetryOptions *telemetry; + +#pragma mark - Custom data + +@property (nonatomic, readwrite, strong) NSMutableDictionary *customData; + +#pragma mark - Payload Content Related + +/// Decides whether or not to send provided payload data. Returns true to ignore, false to send +@property (nullable, atomic, readwrite, copy) BOOL (^checkIgnoreRollbarData)(RollbarData *rollbarData); + +/// Modifies payload data before sending +@property (nullable, atomic, readwrite, copy) RollbarData *(^modifyRollbarData)(RollbarData *rollbarData); #pragma mark - Convenience Methods @@ -93,11 +159,6 @@ NS_ASSUME_NONNULL_BEGIN - (void)setNotifierName:(nullable NSString *)name version:(nullable NSString *)version; -#pragma mark - Factory Methods - -+ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token; -+ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token environment:(nonnull NSString *)env; - @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDestination.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDestination.h index 94f3594f..0a39de03 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDestination.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDestination.h @@ -11,13 +11,13 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - properties /// Endpoint URI -@property (nonatomic, copy) NSString *endpoint; +@property (nonatomic, readonly, copy) NSString *endpoint; /// Project access token -@property (nonatomic, copy) NSString *accessToken; +@property (nonatomic, readonly, copy) NSString *accessToken; /// Environment name -@property (nonatomic, copy) NSString *environment; +@property (nonatomic, readonly, copy) NSString *environment; #pragma mark - initializers @@ -41,6 +41,46 @@ NS_ASSUME_NONNULL_BEGIN @end +@interface RollbarMutableDestination : RollbarDestination + +#pragma mark - initializers + +- (instancetype)init +NS_DESIGNATED_INITIALIZER; + +#pragma mark - properties + +/// Endpoint URI +@property (nonatomic, readwrite, copy) NSString *endpoint; + +/// Project access token +@property (nonatomic, readwrite, copy) NSString *accessToken; + +/// Environment name +@property (nonatomic, readwrite, copy) NSString *environment; + +//#pragma mark - initializers +// +///// Initializer +///// @param endpoint endpoint URI +///// @param accessToken Rollbar project access token +///// @param environment environment name +//- (instancetype)initWithEndpoint:(NSString *)endpoint +// accessToken:(NSString *)accessToken +// environment:(NSString *)environment; +// +///// Initializer +///// @param accessToken Rollbar project access token +///// @param environment environment name +//- (instancetype)initWithAccessToken:(NSString *)accessToken +// environment:(NSString *)environment; +// +///// Initializer +///// @param accessToken Rollbar project access token +//- (instancetype)initWithAccessToken:(NSString *)accessToken; + +@end + NS_ASSUME_NONNULL_END #endif //RollbarDestination_h diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h index 0ecff82b..0489cf26 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h @@ -11,19 +11,19 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - properties /// Rollbar operation enabled flag -@property (nonatomic) BOOL enabled; +@property (nonatomic, readonly) BOOL enabled; /// Enables/disables actual transmission of the payloads -@property (nonatomic) BOOL transmit; +@property (nonatomic, readonly) BOOL transmit; /// A flag to suppress internal SDK's informational logging -@property (nonatomic) BOOL suppressSdkInfoLogging; +@property (nonatomic, readonly) BOOL suppressSdkInfoLogging; /// Flags if the processed payloads to be logged locally -@property (nonatomic) BOOL logPayload; +@property (nonatomic, readonly) BOOL logPayload; /// Log file to use for local logged payloads -@property (nonatomic, copy) NSString *payloadLogFile; +@property (nonatomic, readonly, copy) NSString *payloadLogFile; #pragma mark - initializers @@ -48,6 +48,27 @@ NS_ASSUME_NONNULL_BEGIN @end +@interface RollbarMutableDeveloperOptions : RollbarDeveloperOptions + +#pragma mark - properties + +/// Rollbar operation enabled flag +@property (nonatomic, readwrite) BOOL enabled; + +/// Enables/disables actual transmission of the payloads +@property (nonatomic, readwrite) BOOL transmit; + +/// A flag to suppress internal SDK's informational logging +@property (nonatomic, readwrite) BOOL suppressSdkInfoLogging; + +/// Flags if the processed payloads to be logged locally +@property (nonatomic, readwrite) BOOL logPayload; + +/// Log file to use for local logged payloads +@property (nonatomic, readwrite, copy) NSString *payloadLogFile; + +@end + NS_ASSUME_NONNULL_END #endif //RollbarDeveloperOptions_h diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h index 84d9a84c..3b48e453 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger.h @@ -13,8 +13,8 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - //TODO: to be removed - (void)updateConfiguration:(nonnull RollbarConfig *)configuration; -- (void)updateAccessToken:(nonnull NSString *)accessToken; -- (void)updateReportingRate:(NSUInteger)maximumReportsPerMinute; +//- (void)updateAccessToken:(nonnull NSString *)accessToken; +//- (void)updateReportingRate:(NSUInteger)maximumReportsPerMinute; //- (BOOL)sendItem:(nonnull NSDictionary *)payload // nextOffset:(NSUInteger)nextOffset; diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggingOptions.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggingOptions.h index 3094129c..bddecb36 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggingOptions.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLoggingOptions.h @@ -13,28 +13,28 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - Properties /// A minimum threshold level to log from -@property (nonatomic) RollbarLevel logLevel; +@property (nonatomic, readonly) RollbarLevel logLevel; /// A log level to use for crsh reports -@property (nonatomic) RollbarLevel crashLevel; +@property (nonatomic, readonly) RollbarLevel crashLevel; /// Reporting rate limit -@property (nonatomic) NSUInteger maximumReportsPerMinute; +@property (nonatomic, readonly) NSUInteger maximumReportsPerMinute; /// A way of capturing IP addresses -@property (nonatomic) RollbarCaptureIpType captureIp; +@property (nonatomic, readonly) RollbarCaptureIpType captureIp; /// A code version to mark payloads with -@property (nonatomic, copy, nullable) NSString *codeVersion; +@property (nonatomic, copy, nullable, readonly) NSString *codeVersion; /// A framework tag to mark payloads with -@property (nonatomic, copy, nullable) NSString *framework; +@property (nonatomic, copy, nullable, readonly, readonly) NSString *framework; /// A request ID to mark payloads with -@property (nonatomic, copy, nullable) NSString *requestId; +@property (nonatomic, copy, nullable, readonly) NSString *requestId; /// A flag enabling potential OOM (Out-of-Memory) detection -@property (nonatomic) BOOL enableOomDetection; +@property (nonatomic, readonly) BOOL enableOomDetection; #pragma mark - Initializers @@ -129,6 +129,41 @@ NS_ASSUME_NONNULL_BEGIN @end +@interface RollbarMutableLoggingOptions : RollbarLoggingOptions + +#pragma mark - initializers + +- (instancetype)init +NS_DESIGNATED_INITIALIZER; + +#pragma mark - Properties + +/// A minimum threshold level to log from +@property (nonatomic, readwrite) RollbarLevel logLevel; + +/// A log level to use for crsh reports +@property (nonatomic, readwrite) RollbarLevel crashLevel; + +/// Reporting rate limit +@property (nonatomic, readwrite) NSUInteger maximumReportsPerMinute; + +/// A way of capturing IP addresses +@property (nonatomic, readwrite) RollbarCaptureIpType captureIp; + +/// A code version to mark payloads with +@property (nonatomic, copy, nullable, readwrite) NSString *codeVersion; + +/// A framework tag to mark payloads with +@property (nonatomic, copy, nullable, readwrite) NSString *framework; + +/// A request ID to mark payloads with +@property (nonatomic, copy, nullable, readwrite) NSString *requestId; + +/// A flag enabling potential OOM (Out-of-Memory) detection +@property (nonatomic, readwrite) BOOL enableOomDetection; + +@end + NS_ASSUME_NONNULL_END #endif //RollbarLoggingOptions_h diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarModule.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarModule.h index fe400e9d..07907f65 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarModule.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarModule.h @@ -8,16 +8,6 @@ NS_ASSUME_NONNULL_BEGIN /// Module element of a payload @interface RollbarModule : RollbarDTO -#pragma mark - properties - -/// Optional: name -/// Name of the library -@property (nonatomic, copy, nullable) NSString *name; - -/// Optional: version -/// Library version string -@property (nonatomic, copy, nullable) NSString *version; - #pragma mark - initializers /// Initializer @@ -30,6 +20,39 @@ NS_ASSUME_NONNULL_BEGIN /// @param name module name - (instancetype)initWithName:(nullable NSString *)name; +- (instancetype)init +NS_UNAVAILABLE; + +#pragma mark - properties + +/// Optional: name +/// Name of the library +@property (nonatomic, copy, nullable, readonly) NSString *name; + +/// Optional: version +/// Library version string +@property (nonatomic, copy, nullable, readonly) NSString *version; + +@end + + +/// Mutable Module element of a payload +@interface RollbarMutableModule : RollbarModule + +#pragma mark - initializers + +- (instancetype)init; + +#pragma mark - properties + +/// Optional: name +/// Name of the library +@property (nonatomic, copy, nullable, readwrite) NSString *name; + +/// Optional: version +/// Library version string +@property (nonatomic, copy, nullable, readwrite) NSString *version; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarPerson.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarPerson.h index 381b77c3..02603a05 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarPerson.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarPerson.h @@ -9,27 +9,6 @@ NS_ASSUME_NONNULL_BEGIN /// Models a monitored system user. @interface RollbarPerson : RollbarDTO -#pragma mark - properties - -/// Required: id. -/// -/// A string up to 40 characters identifying this user in your system. -/// -/// The user affected by this event. Will be indexed by ID, username, and email. -/// People are stored in Rollbar keyed by ID. If you send a multiple different usernames/emails for the -/// same ID, the last received values will overwrite earlier ones. -@property (nonatomic, copy, nonnull) NSString *ID; - -/// Optional: username. -/// -/// A string up to 255 characters -@property (nonatomic, copy, nullable) NSString *username; - -/// Optional: email. -/// -/// A string up to 255 characters -@property (nonatomic, copy, nullable) NSString *email; - #pragma mark - initializers /// Initialiazes a RollbarPerson. @@ -59,6 +38,60 @@ NS_ASSUME_NONNULL_BEGIN - (instancetype)init NS_UNAVAILABLE; +#pragma mark - properties + +/// Required: id. +/// +/// A string up to 40 characters identifying this user in your system. +/// +/// The user affected by this event. Will be indexed by ID, username, and email. +/// People are stored in Rollbar keyed by ID. If you send a multiple different usernames/emails for the +/// same ID, the last received values will overwrite earlier ones. +@property (nonatomic, copy, nonnull, readonly) NSString *ID; + +/// Optional: username. +/// +/// A string up to 255 characters +@property (nonatomic, copy, nullable, readonly) NSString *username; + +/// Optional: email. +/// +/// A string up to 255 characters +@property (nonatomic, copy, nullable, readonly) NSString *email; + +@end + + +/// Mutable RollbarPerson DTO. +/// Models a monitored system user. +@interface RollbarMutablePerson : RollbarPerson + +#pragma mark - initializers + +/// Hides perameterless initializer. +- (instancetype)init; + +#pragma mark - properties + +/// Required: id. +/// +/// A string up to 40 characters identifying this user in your system. +/// +/// The user affected by this event. Will be indexed by ID, username, and email. +/// People are stored in Rollbar keyed by ID. If you send a multiple different usernames/emails for the +/// same ID, the last received values will overwrite earlier ones. +@property (nonatomic, copy, nonnull, readwrite) NSString *ID; + +/// Optional: username. +/// +/// A string up to 255 characters +@property (nonatomic, copy, nullable, readwrite) NSString *username; + +/// Optional: email. +/// +/// A string up to 255 characters +@property (nonatomic, copy, nullable, readwrite) NSString *email; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarProxy.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarProxy.h index 0ee782a1..39de2097 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarProxy.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarProxy.h @@ -11,13 +11,13 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - properties /// Enables/disables usage of these proxy settings -@property (nonatomic) BOOL enabled; +@property (nonatomic, readonly) BOOL enabled; /// Proxy URI to use -@property (nonatomic, copy) NSString *proxyUrl; +@property (nonatomic, readonly, copy) NSString *proxyUrl; /// Proxy port to use -@property (nonatomic) NSUInteger proxyPort; +@property (nonatomic, readonly) NSUInteger proxyPort; #pragma mark - initializers @@ -31,6 +31,21 @@ NS_ASSUME_NONNULL_BEGIN @end +@interface RollbarMutableProxy : RollbarProxy + +#pragma mark - properties + +/// Enables/disables usage of these proxy settings +@property (nonatomic, readwrite) BOOL enabled; + +/// Proxy URI to use +@property (nonatomic, readwrite, copy) NSString *proxyUrl; + +/// Proxy port to use +@property (nonatomic, readwrite) NSUInteger proxyPort; + +@end + NS_ASSUME_NONNULL_END #endif //RollbarProxy_h diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarScrubbingOptions.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarScrubbingOptions.h index c67f28b2..5558d6d2 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarScrubbingOptions.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarScrubbingOptions.h @@ -8,13 +8,60 @@ NS_ASSUME_NONNULL_BEGIN /// Scrubbing setting of a configuration @interface RollbarScrubbingOptions : RollbarDTO +#pragma mark - initializers + +/// Initializer +/// @param enabled scrubbing enabling flag +/// @param scrubFields scrubbing fields +/// @param safeListFields safe list of fields (to never scrub) +- (instancetype)initWithEnabled:(BOOL)enabled + scrubFields:(NSArray *)scrubFields + safeListFields:(NSArray *)safeListFields; + +/// Initializer +/// @param scrubFields scrubbing fields +/// @param safeListFields safe list of fields (to never scrub) +- (instancetype)initWithScrubFields:(NSArray *)scrubFields + safeListFields:(NSArray *)safeListFields; + +/// Initializer +/// @param scrubFields scrubbing fields +- (instancetype)initWithScrubFields:(NSArray *)scrubFields; + +#pragma mark - properties + +/// Enables scrubbing +@property (nonatomic, readonly) BOOL enabled; + +/// Fields to scrub from the payload +@property (nonatomic, nonnull, readonly, strong) NSArray *scrubFields; + +/// Fields to not scrub from the payload even if they mention among scrubFields +@property (nonatomic, nonnull, readonly, strong) NSArray *safeListFields; + +@end + + +/// Mutable scrubbing setting of a configuration +@interface RollbarMutableScrubbingOptions : RollbarScrubbingOptions + +#pragma mark - initializers + +- (instancetype)init +NS_DESIGNATED_INITIALIZER; + #pragma mark - properties /// Enables scrubbing -@property (nonatomic) BOOL enabled; +@property (nonatomic, readwrite) BOOL enabled; /// Fields to scrub from the payload -@property (nonnull, nonatomic, strong) NSArray *scrubFields; +@property (nonatomic, nonnull, readwrite, strong) NSMutableArray *scrubFields; + +/// Fields to not scrub from the payload even if they mention among scrubFields +@property (nonatomic, nonnull, readwrite, strong) NSMutableArray *safeListFields; + +#pragma mark - methods /// Adds a scrubbing field to use /// @param field a scrubbing field @@ -24,9 +71,6 @@ NS_ASSUME_NONNULL_BEGIN /// @param field a scrubbing field - (void)removeScrubField:(NSString *)field; -/// Fields to not scrub from the payload even if they mention among scrubFields -@property (nonnull, nonatomic, strong) NSArray *safeListFields; - /// Adds a scrubbing field to the safe list /// @param field a scrubbing field - (void)addScrubSafeListField:(NSString *)field; @@ -35,26 +79,6 @@ NS_ASSUME_NONNULL_BEGIN /// @param field a scrubbing field - (void)removeScrubSafeListField:(NSString *)field; -#pragma mark - initializers - -/// Initializer -/// @param enabled scrubbing enabling flag -/// @param scrubFields scrubbing fields -/// @param safeListFields safe list of fields (to never scrub) -- (instancetype)initWithEnabled:(BOOL)enabled - scrubFields:(NSArray *)scrubFields - safeListFields:(NSArray *)safeListFields; - -/// Initializer -/// @param scrubFields scrubbing fields -/// @param safeListFields safe list of fields (to never scrub) -- (instancetype)initWithScrubFields:(NSArray *)scrubFields - safeListFields:(NSArray *)safeListFields; - -/// Initializer -/// @param scrubFields scrubbing fields -- (instancetype)initWithScrubFields:(NSArray *)scrubFields; - @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarServerConfig.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarServerConfig.h index d981ef5b..5f512fab 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarServerConfig.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarServerConfig.h @@ -8,20 +8,6 @@ NS_ASSUME_NONNULL_BEGIN /// Server config setting of a configuration @interface RollbarServerConfig : RollbarDTO -#pragma mark - properties - -/// Servef host -@property (nonatomic, copy, nullable) NSString *host; - -/// Server code root -@property (nonatomic, copy, nullable) NSString *root; - -/// Server code branch -@property (nonatomic, copy, nullable) NSString *branch; - -/// Server code version -@property (nonatomic, copy, nullable) NSString *codeVersion; - #pragma mark - initializers /// Initializer @@ -34,6 +20,40 @@ NS_ASSUME_NONNULL_BEGIN branch:(nullable NSString *)branch codeVersion:(nullable NSString *)codeVersion; +#pragma mark - properties + +/// Servef host +@property (nonatomic, copy, nullable, readonly) NSString *host; + +/// Server code root +@property (nonatomic, copy, nullable, readonly) NSString *root; + +/// Server code branch, readonly +@property (nonatomic, copy, nullable, readonly) NSString *branch; + +/// Server code version, readonly +@property (nonatomic, copy, nullable, readonly) NSString *codeVersion; + +@end + + +/// Mutable Server config setting of a configuration +@interface RollbarMutableServerConfig : RollbarServerConfig + +#pragma mark - properties + +/// Servef host +@property (nonatomic, copy, nullable, readwrite) NSString *host; + +/// Server code root +@property (nonatomic, copy, nullable, readwrite) NSString *root; + +/// Server code branch +@property (nonatomic, copy, nullable, readwrite) NSString *branch; + +/// Server code version +@property (nonatomic, copy, nullable, readwrite) NSString *codeVersion; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetryOptions.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetryOptions.h index 63b8d7d8..dbdeab5c 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetryOptions.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetryOptions.h @@ -1,35 +1,16 @@ #ifndef RollbarTelemetryOptions_h #define RollbarTelemetryOptions_h +#import "RollbarScrubbingOptions.h" + @import RollbarCommon; -@class RollbarScrubbingOptions; NS_ASSUME_NONNULL_BEGIN /// Telemetry related settings of a configuration @interface RollbarTelemetryOptions : RollbarDTO -#pragma mark - properties -/// Telemetry enabled flag -@property (nonatomic) BOOL enabled; - -/// Capture OS log as Telemetry events flag -@property (nonatomic) BOOL captureLog; - -/// Capture connectivity flag -@property (nonatomic) BOOL captureConnectivity; - -/// Telemtry events buffer limit -@property (nonatomic) NSUInteger maximumTelemetryData; - -/// Telemetry scrubbing options -@property (nonatomic, strong) RollbarScrubbingOptions *viewInputsScrubber; - -/// Time interval for auto-collecting memtory stats -/// @note 0.0 means no collection! -@property (atomic) NSTimeInterval memoryStatsAutocollectionInterval; //[sec] - #pragma mark - initializers /// Initializer @@ -54,6 +35,57 @@ NS_ASSUME_NONNULL_BEGIN /// @param enabled telemetry enabled - (instancetype)initWithEnabled:(BOOL)enabled; +#pragma mark - properties +/// Telemetry enabled flag +@property (nonatomic, readonly) BOOL enabled; + +/// Capture OS log as Telemetry events flag +@property (nonatomic, readonly) BOOL captureLog; + +/// Capture connectivity flag +@property (nonatomic, readonly) BOOL captureConnectivity; + +/// Telemtry events buffer limit +@property (nonatomic, readonly) NSUInteger maximumTelemetryData; + +/// Telemetry scrubbing options +@property (nonatomic, strong, readonly) RollbarScrubbingOptions *viewInputsScrubber; + +/// Time interval for auto-collecting memtory stats +/// @note 0.0 means no collection! +@property (atomic, readonly) NSTimeInterval memoryStatsAutocollectionInterval; //[sec] + +@end + + +/// Mutable Telemetry related settings of a configuration +@interface RollbarMutableTelemetryOptions : RollbarTelemetryOptions + +#pragma mark - initializers + +- (instancetype)init +NS_DESIGNATED_INITIALIZER; + +#pragma mark - properties +/// Telemetry enabled flag +@property (nonatomic, readwrite) BOOL enabled; + +/// Capture OS log as Telemetry events flag +@property (nonatomic, readwrite) BOOL captureLog; + +/// Capture connectivity flag +@property (nonatomic, readwrite) BOOL captureConnectivity; + +/// Telemtry events buffer limit +@property (nonatomic, readwrite) NSUInteger maximumTelemetryData; + +/// Telemetry scrubbing options +@property (nonatomic, strong, readwrite) RollbarMutableScrubbingOptions *viewInputsScrubber; + +/// Time interval for auto-collecting memtory stats +/// @note 0.0 means no collection! +@property (atomic, readwrite) NSTimeInterval memoryStatsAutocollectionInterval; //[sec] + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/DTOsTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/DTOsTests.m index 591d79e3..3e9280dc 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/DTOsTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/DTOsTests.m @@ -149,7 +149,7 @@ -(void)testRollbarProxyDTO { } - (void)testRollbarScrubbingOptionsDTO { - RollbarScrubbingOptions *dto = [[RollbarScrubbingOptions alloc] initWithScrubFields:@[@"field1", @"field2"]]; + RollbarMutableScrubbingOptions *dto = [[RollbarMutableScrubbingOptions alloc] initWithScrubFields:@[@"field1", @"field2"]]; XCTAssertTrue(dto.enabled, @"Enabled by default" ); @@ -160,7 +160,7 @@ - (void)testRollbarScrubbingOptionsDTO { @"Has NO whitelist fields" ); - dto.safeListFields = @[@"tf1", @"tf2", @"tf3"]; + dto.safeListFields = [@[@"tf1", @"tf2", @"tf3"] mutableCopy]; XCTAssertTrue(dto.safeListFields.count == 3, @"Has some whitelist fields" ); @@ -172,11 +172,11 @@ - (void)testRollbarScrubbingOptionsDTO { } - (void)testRollbarServerConfigDTO { - RollbarServerConfig *dto = [[RollbarServerConfig alloc] initWithHost:@"HOST" - root:@"ROOT" - branch:@"BRANCH" - codeVersion:@"1.2.3" - ]; + RollbarMutableServerConfig *dto = [[RollbarMutableServerConfig alloc] initWithHost:@"HOST" + root:@"ROOT" + branch:@"BRANCH" + codeVersion:@"1.2.3" + ]; XCTAssertTrue(NSOrderedSame == [dto.host compare:@"HOST"], @"Proper host" ); @@ -208,7 +208,7 @@ - (void)testRollbarServerConfigDTO { ); - RollbarConfig *rc = [RollbarConfig new]; + RollbarMutableConfig *rc = [RollbarMutableConfig new]; rc.destination.accessToken = @"ACCESSTOKEN"; rc.destination.environment = @"ENVIRONMENT"; rc.destination.endpoint = @"ENDPOINT"; @@ -225,9 +225,9 @@ - (void)testRollbarServerConfigDTO { } - (void)testRollbarPersonDTO { - RollbarPerson *dto = [[RollbarPerson alloc] initWithID:@"ID" - username:@"USERNAME" - email:@"EMAIL" + RollbarMutablePerson *dto = [[RollbarMutablePerson alloc] initWithID:@"ID" + username:@"USERNAME" + email:@"EMAIL" ]; XCTAssertTrue(NSOrderedSame == [dto.ID compare:@"ID"], @"Proper ID" @@ -252,7 +252,7 @@ - (void)testRollbarPersonDTO { @"Proper email" ); - dto = [[RollbarPerson alloc] initWithID:@"ID007"]; + dto = [[RollbarMutablePerson alloc] initWithID:@"ID007"]; XCTAssertTrue(NSOrderedSame == [dto.ID compare:@"ID007"], @"Proper ID" ); @@ -265,9 +265,9 @@ - (void)testRollbarPersonDTO { } - (void)testRollbarModuleDTO { - RollbarModule *dto = [[RollbarModule alloc] initWithName:@"ModuleName" - version:@"v1.2.3" - ]; + RollbarMutableModule *dto = [[RollbarMutableModule alloc] initWithName:@"ModuleName" + version:@"v1.2.3" + ]; XCTAssertTrue([dto.name isEqualToString:@"ModuleName"], @"Proper name" ); @@ -284,7 +284,7 @@ - (void)testRollbarModuleDTO { @"Proper version" ); - dto = [[RollbarModule alloc] initWithName:@"Module"]; + dto = [[RollbarMutableModule alloc] initWithName:@"Module"]; XCTAssertTrue([dto.name isEqualToString:@"Module"], @"Proper name" ); @@ -323,7 +323,7 @@ - (void)testRollbarTelemetryOptionsDTO { @"Proper view inputs scrubber white list fields count" ); - dto = [[RollbarTelemetryOptions alloc] init]; + dto = [[RollbarMutableTelemetryOptions alloc] init]; XCTAssertTrue(!dto.enabled, @"Proper enabled" ); @@ -346,9 +346,9 @@ - (void)testRollbarTelemetryOptionsDTO { } - (void)testRollbarLoggingOptionsDTO { - RollbarLoggingOptions *dto = [[RollbarLoggingOptions alloc] initWithLogLevel:RollbarLevel_Error - crashLevel:RollbarLevel_Info - maximumReportsPerMinute:45]; + RollbarMutableLoggingOptions *dto = [[RollbarMutableLoggingOptions alloc] initWithLogLevel:RollbarLevel_Error + crashLevel:RollbarLevel_Info + maximumReportsPerMinute:45]; dto.captureIp = RollbarCaptureIpType_Anonymize; dto.codeVersion = @"CODEVERSION"; dto.framework = @"FRAMEWORK"; @@ -376,7 +376,7 @@ - (void)testRollbarLoggingOptionsDTO { @"Proper request ID" ); - dto = [[RollbarLoggingOptions alloc] init]; + dto = [[RollbarMutableLoggingOptions alloc] init]; XCTAssertTrue(dto.logLevel == RollbarLevel_Info, @"Proper default log level" ); @@ -402,7 +402,7 @@ - (void)testRollbarLoggingOptionsDTO { - (void)testRollbarConfigDTO { - RollbarConfig *rc = [RollbarConfig new]; + RollbarMutableConfig *rc = [RollbarMutableConfig new]; //id destination = rc.destination; rc.destination.accessToken = @"ACCESSTOKEN"; rc.destination.environment = @"ENVIRONMENT"; @@ -413,7 +413,7 @@ - (void)testRollbarConfigDTO { [rc setServerHost:@"SERVERHOST" root:@"SERVERROOT" branch:@"SERVERBRANCH" codeVersion:@"SERVERCODEVERSION"]; [rc setNotifierName:@"NOTIFIERNAME" version:@"NOTIFIERVERSION"]; - RollbarConfig *rcClone = [[RollbarConfig alloc] initWithJSONString:[rc serializeToJSONString]]; + RollbarMutableConfig *rcClone = [[RollbarMutableConfig alloc] initWithJSONString:[rc serializeToJSONString]]; // id scrubList = rc.scrubFields; // id scrubListClone = rcClone.scrubFields; @@ -437,7 +437,7 @@ - (void)testRollbarConfigDTO { // [rcClone serializeToJSONString] // ); - rcClone = [[RollbarConfig alloc] initWithJSONString:[rc serializeToJSONString]]; + rcClone = [[RollbarMutableConfig alloc] initWithJSONString:[rc serializeToJSONString]]; rcClone.httpProxy.proxyUrl = @"SOME_OTHER_ONE"; XCTAssertTrue(![rc isEqual:rcClone], @"Two DTOs are NOT expected to be equal" diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m new file mode 100644 index 00000000..556415eb --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m @@ -0,0 +1,562 @@ +// +// RollbarConfigTests.m +// +// +// Created by Andrey Kornich on 2022-07-14. +// + +#import + +@import RollbarCommon; +@import RollbarNotifier; + +@interface RollbarConfigTests : XCTestCase + +@end + +@implementation RollbarConfigTests + +- (void)setUp { + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. +} + +- (void)testRollbarDestination { + + RollbarMutableDestination *mutable = [RollbarMutableDestination new]; + mutable.endpoint = @"test_EP"; + mutable.accessToken = @"test_AC"; + mutable.environment = @"test_ENV"; + XCTAssertTrue([mutable.endpoint isEqualToString:@"test_EP"]); + XCTAssertTrue([mutable.accessToken isEqualToString:@"test_AC"]); + XCTAssertTrue([mutable.environment isEqualToString:@"test_ENV"]); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_EP"]); + XCTAssertTrue([content containsString:@"test_AC"]); + XCTAssertTrue([content containsString:@"test_ENV"]); + + RollbarDestination *immutable = [mutable copy]; + XCTAssertNotNil(immutable); + XCTAssertTrue([immutable.endpoint isEqualToString:@"test_EP"]); + XCTAssertTrue([immutable.accessToken isEqualToString:@"test_AC"]); + XCTAssertTrue([immutable.environment isEqualToString:@"test_ENV"]); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_EP"]); + XCTAssertTrue([content containsString:@"test_AC"]); + XCTAssertTrue([content containsString:@"test_ENV"]); + + XCTAssertEqualObjects(immutable, mutable); + XCTAssertNotIdentical(immutable, mutable); + + XCTAssertEqualObjects(immutable, [immutable copy]); + XCTAssertIdentical (immutable, [immutable copy]); + XCTAssertEqualObjects(immutable, [immutable mutableCopy]); + XCTAssertNotIdentical(immutable, [immutable mutableCopy]); + + XCTAssertEqualObjects(mutable, [mutable copy]); + XCTAssertNotIdentical(mutable, [mutable copy]); + XCTAssertEqualObjects(mutable, [mutable mutableCopy]); + XCTAssertNotIdentical(mutable, [mutable mutableCopy]); +} + +- (void)testRollbarDeveloperOptions { + + RollbarMutableDeveloperOptions *mutable = [RollbarMutableDeveloperOptions new]; + mutable.enabled = NO; + mutable.transmit = NO; + mutable.suppressSdkInfoLogging = NO; + mutable.logPayload = NO; + mutable.payloadLogFile = @"test_PAYLOADS.LOG_old"; + XCTAssertFalse(mutable.enabled); + XCTAssertFalse(mutable.transmit); + XCTAssertFalse(mutable.suppressSdkInfoLogging); + XCTAssertFalse(mutable.logPayload); + XCTAssertTrue([mutable.payloadLogFile isEqualToString:@"test_PAYLOADS.LOG_old"]); + + mutable.enabled = YES; + mutable.transmit = YES; + mutable.suppressSdkInfoLogging = YES; + mutable.logPayload = YES; + mutable.payloadLogFile = @"test_PAYLOADS.LOG"; + XCTAssertTrue(mutable.enabled); + XCTAssertTrue(mutable.transmit); + XCTAssertTrue(mutable.suppressSdkInfoLogging); + XCTAssertTrue(mutable.logPayload); + XCTAssertTrue([mutable.payloadLogFile isEqualToString:@"test_PAYLOADS.LOG"]); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_PAYLOADS.LOG"]); + + RollbarDeveloperOptions *immutable = [mutable copy]; + XCTAssertNotNil(immutable); + XCTAssertTrue(immutable.enabled); + XCTAssertTrue(immutable.transmit); + XCTAssertTrue(immutable.suppressSdkInfoLogging); + XCTAssertTrue(immutable.logPayload); + XCTAssertTrue([immutable.payloadLogFile isEqualToString:@"test_PAYLOADS.LOG"]); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_PAYLOADS.LOG"]); + + XCTAssertEqualObjects(immutable, mutable); + XCTAssertNotIdentical(immutable, mutable); + + XCTAssertEqualObjects(immutable, [immutable copy]); + XCTAssertIdentical (immutable, [immutable copy]); + XCTAssertEqualObjects(immutable, [immutable mutableCopy]); + XCTAssertNotIdentical(immutable, [immutable mutableCopy]); + + XCTAssertEqualObjects(mutable, [mutable copy]); + XCTAssertNotIdentical(mutable, [mutable copy]); + XCTAssertEqualObjects(mutable, [mutable mutableCopy]); + XCTAssertNotIdentical(mutable, [mutable mutableCopy]); +} + +- (void)testRollbarLoggingOptions { + + RollbarMutableLoggingOptions *mutable = [RollbarMutableLoggingOptions new]; + mutable.logLevel = RollbarLevel_Info; + mutable.crashLevel = RollbarLevel_Error; + mutable.maximumReportsPerMinute = 10; + mutable.captureIp = RollbarCaptureIpType_Anonymize; + mutable.codeVersion = @"test_CV_old"; + mutable.framework = @"test_FW_old"; + mutable.requestId = @"test_RID_old"; + mutable.enableOomDetection = NO; + XCTAssertEqual(mutable.logLevel, RollbarLevel_Info); + XCTAssertEqual(mutable.crashLevel, RollbarLevel_Error); + XCTAssertEqual(mutable.maximumReportsPerMinute, 10); + XCTAssertEqual(mutable.captureIp, RollbarCaptureIpType_Anonymize); + XCTAssertTrue([mutable.codeVersion isEqualToString:@"test_CV_old"]); + XCTAssertTrue([mutable.framework isEqualToString:@"test_FW_old"]); + XCTAssertTrue([mutable.requestId isEqualToString:@"test_RID_old"]); + XCTAssertFalse(mutable.enableOomDetection); + + mutable.logLevel = RollbarLevel_Debug; + mutable.crashLevel = RollbarLevel_Critical; + mutable.maximumReportsPerMinute = 25; + mutable.captureIp = RollbarCaptureIpType_Full; + mutable.codeVersion = @"test_CV"; + mutable.framework = @"test_FW"; + mutable.requestId = @"test_RID"; + mutable.enableOomDetection = YES; + XCTAssertEqual(mutable.logLevel, RollbarLevel_Debug); + XCTAssertEqual(mutable.crashLevel, RollbarLevel_Critical); + XCTAssertEqual(mutable.maximumReportsPerMinute, 25); + XCTAssertEqual(mutable.captureIp, RollbarCaptureIpType_Full); + XCTAssertTrue([mutable.codeVersion isEqualToString:@"test_CV"]); + XCTAssertTrue([mutable.framework isEqualToString:@"test_FW"]); + XCTAssertTrue([mutable.requestId isEqualToString:@"test_RID"]); + XCTAssertTrue(mutable.enableOomDetection); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"debug"]); + XCTAssertTrue([content containsString:@"critical"]); + XCTAssertTrue([content containsString:@"25"]); + XCTAssertTrue([content containsString:@"Full"]); + XCTAssertTrue([content containsString:@"test_CV"]); + XCTAssertTrue([content containsString:@"test_FW"]); + XCTAssertTrue([content containsString:@"test_RID"]); + + RollbarLoggingOptions *immutable = [mutable copy]; + XCTAssertNotNil(immutable); + XCTAssertEqual(immutable.logLevel, RollbarLevel_Debug); + XCTAssertEqual(immutable.crashLevel, RollbarLevel_Critical); + XCTAssertEqual(immutable.maximumReportsPerMinute, 25); + XCTAssertEqual(immutable.captureIp, RollbarCaptureIpType_Full); + XCTAssertTrue([immutable.codeVersion isEqualToString:@"test_CV"]); + XCTAssertTrue([immutable.framework isEqualToString:@"test_FW"]); + XCTAssertTrue([immutable.requestId isEqualToString:@"test_RID"]); + XCTAssertTrue(immutable.enableOomDetection); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"debug"]); + XCTAssertTrue([content containsString:@"critical"]); + XCTAssertTrue([content containsString:@"25"]); + XCTAssertTrue([content containsString:@"Full"]); + XCTAssertTrue([content containsString:@"test_CV"]); + XCTAssertTrue([content containsString:@"test_FW"]); + XCTAssertTrue([content containsString:@"test_RID"]); + + XCTAssertEqualObjects(immutable, mutable); + XCTAssertNotIdentical(immutable, mutable); + + XCTAssertEqualObjects(immutable, [immutable copy]); + XCTAssertIdentical (immutable, [immutable copy]); + XCTAssertEqualObjects(immutable, [immutable mutableCopy]); + XCTAssertNotIdentical(immutable, [immutable mutableCopy]); + + XCTAssertEqualObjects(mutable, [mutable copy]); + XCTAssertNotIdentical(mutable, [mutable copy]); + XCTAssertEqualObjects(mutable, [mutable mutableCopy]); + XCTAssertNotIdentical(mutable, [mutable mutableCopy]); +} + +- (void)testRollbarModule { + + RollbarMutableModule *mutable = [RollbarMutableModule new]; + mutable.name = @"test_N_old"; + mutable.version = @"test_V_old"; + XCTAssertTrue([mutable.name isEqualToString:@"test_N_old"]); + XCTAssertTrue([mutable.version isEqualToString:@"test_V_old"]); + + mutable.name = @"test_N"; + mutable.version = @"test_V"; + XCTAssertTrue([mutable.name isEqualToString:@"test_N"]); + XCTAssertTrue([mutable.version isEqualToString:@"test_V"]); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_N"]); + XCTAssertTrue([content containsString:@"test_V"]); + + RollbarModule *immutable = [mutable copy]; + XCTAssertNotNil(immutable); + XCTAssertTrue([immutable.name isEqualToString:@"test_N"]); + XCTAssertTrue([immutable.version isEqualToString:@"test_V"]); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_N"]); + XCTAssertTrue([content containsString:@"test_V"]); + + XCTAssertEqualObjects(immutable, mutable); + XCTAssertNotIdentical(immutable, mutable); + + XCTAssertEqualObjects(immutable, [immutable copy]); + XCTAssertIdentical (immutable, [immutable copy]); + XCTAssertEqualObjects(immutable, [immutable mutableCopy]); + XCTAssertNotIdentical(immutable, [immutable mutableCopy]); + + XCTAssertEqualObjects(mutable, [mutable copy]); + XCTAssertNotIdentical(mutable, [mutable copy]); + XCTAssertEqualObjects(mutable, [mutable mutableCopy]); + XCTAssertNotIdentical(mutable, [mutable mutableCopy]); +} + +- (void)testRollbarPerson { + + RollbarMutablePerson *mutable = [RollbarMutablePerson new]; + mutable.ID = @"test_ID_old"; + mutable.username = @"test_UN_old"; + mutable.email = @"test_EM_old"; + XCTAssertTrue([mutable.ID isEqualToString:@"test_ID_old"]); + XCTAssertTrue([mutable.username isEqualToString:@"test_UN_old"]); + XCTAssertTrue([mutable.email isEqualToString:@"test_EM_old"]); + + mutable.ID = @"test_ID"; + mutable.username = @"test_UN"; + mutable.email = @"test_EM"; + XCTAssertTrue([mutable.ID isEqualToString:@"test_ID"]); + XCTAssertTrue([mutable.username isEqualToString:@"test_UN"]); + XCTAssertTrue([mutable.email isEqualToString:@"test_EM"]); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_ID"]); + XCTAssertTrue([content containsString:@"test_UN"]); + XCTAssertTrue([content containsString:@"test_EM"]); + + RollbarPerson *immutable = [mutable copy]; + XCTAssertNotNil(immutable); + XCTAssertTrue([immutable.ID isEqualToString:@"test_ID"]); + XCTAssertTrue([immutable.username isEqualToString:@"test_UN"]); + XCTAssertTrue([immutable.email isEqualToString:@"test_EM"]); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_ID"]); + XCTAssertTrue([content containsString:@"test_UN"]); + XCTAssertTrue([content containsString:@"test_EM"]); + + XCTAssertEqualObjects(immutable, mutable); + XCTAssertNotIdentical(immutable, mutable); + + XCTAssertEqualObjects(immutable, [immutable copy]); + XCTAssertIdentical (immutable, [immutable copy]); + XCTAssertEqualObjects(immutable, [immutable mutableCopy]); + XCTAssertNotIdentical(immutable, [immutable mutableCopy]); + + XCTAssertEqualObjects(mutable, [mutable copy]); + XCTAssertNotIdentical(mutable, [mutable copy]); + XCTAssertEqualObjects(mutable, [mutable mutableCopy]); + XCTAssertNotIdentical(mutable, [mutable mutableCopy]); +} + +- (void)testRollbarProxy { + + RollbarMutableProxy *mutable = [RollbarMutableProxy new]; + mutable.enabled = NO; + mutable.proxyUrl = @"test_URL_old"; + mutable.proxyPort = 100; + XCTAssertTrue(!mutable.enabled); + XCTAssertTrue([mutable.proxyUrl isEqualToString:@"test_URL_old"]); + XCTAssertEqual(mutable.proxyPort, 100); + + mutable.enabled = YES; + mutable.proxyUrl = @"test_URL"; + mutable.proxyPort = 199; + XCTAssertTrue(mutable.enabled); + XCTAssertTrue([mutable.proxyUrl isEqualToString:@"test_URL"]); + XCTAssertEqual(mutable.proxyPort, 199); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_URL"]); + XCTAssertTrue([content containsString:@"199"]); + + RollbarProxy *immutable = [mutable copy]; + XCTAssertNotNil(immutable); + XCTAssertTrue(immutable.enabled); + XCTAssertTrue([immutable.proxyUrl isEqualToString:@"test_URL"]); + XCTAssertEqual(immutable.proxyPort, 199); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_URL"]); + XCTAssertTrue([content containsString:@"199"]); + + XCTAssertEqualObjects(immutable, mutable); + XCTAssertNotIdentical(immutable, mutable); + + XCTAssertEqualObjects(immutable, [immutable copy]); + XCTAssertIdentical (immutable, [immutable copy]); + XCTAssertEqualObjects(immutable, [immutable mutableCopy]); + XCTAssertNotIdentical(immutable, [immutable mutableCopy]); + + XCTAssertEqualObjects(mutable, [mutable copy]); + XCTAssertNotIdentical(mutable, [mutable copy]); + XCTAssertEqualObjects(mutable, [mutable mutableCopy]); + XCTAssertNotIdentical(mutable, [mutable mutableCopy]); +} + +- (void)testRollbarServerConfig { + + RollbarMutableServerConfig *mutable = [RollbarMutableServerConfig new]; + mutable.host = @"test_H_old"; + mutable.root = @"test_R_old"; + mutable.branch = @"test_B_old"; + mutable.codeVersion = @"test_CV_old"; + XCTAssertTrue([mutable.host isEqualToString:@"test_H_old"]); + XCTAssertTrue([mutable.root isEqualToString:@"test_R_old"]); + XCTAssertTrue([mutable.branch isEqualToString:@"test_B_old"]); + XCTAssertTrue([mutable.codeVersion isEqualToString:@"test_CV_old"]); + + mutable.host = @"test_H"; + mutable.root = @"test_R"; + mutable.branch = @"test_B"; + mutable.codeVersion = @"test_CV"; + XCTAssertTrue([mutable.host isEqualToString:@"test_H"]); + XCTAssertTrue([mutable.root isEqualToString:@"test_R"]); + XCTAssertTrue([mutable.branch isEqualToString:@"test_B"]); + XCTAssertTrue([mutable.codeVersion isEqualToString:@"test_CV"]); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_H"]); + XCTAssertTrue([content containsString:@"test_R"]); + XCTAssertTrue([content containsString:@"test_B"]); + XCTAssertTrue([content containsString:@"test_CV"]); + + RollbarServerConfig *immutable = [mutable copy]; + XCTAssertNotNil(immutable); + XCTAssertTrue([immutable.host isEqualToString:@"test_H"]); + XCTAssertTrue([immutable.root isEqualToString:@"test_R"]); + XCTAssertTrue([immutable.branch isEqualToString:@"test_B"]); + XCTAssertTrue([immutable.codeVersion isEqualToString:@"test_CV"]); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_H"]); + XCTAssertTrue([content containsString:@"test_R"]); + XCTAssertTrue([content containsString:@"test_B"]); + XCTAssertTrue([content containsString:@"test_CV"]); + + XCTAssertEqualObjects(immutable, mutable); + XCTAssertNotIdentical(immutable, mutable); + + XCTAssertEqualObjects(immutable, [immutable copy]); + XCTAssertIdentical (immutable, [immutable copy]); + XCTAssertEqualObjects(immutable, [immutable mutableCopy]); + XCTAssertNotIdentical(immutable, [immutable mutableCopy]); + + XCTAssertEqualObjects(mutable, [mutable copy]); + XCTAssertNotIdentical(mutable, [mutable copy]); + XCTAssertEqualObjects(mutable, [mutable mutableCopy]); + XCTAssertNotIdentical(mutable, [mutable mutableCopy]); +} + +- (void)testRollbarScrubbingOptions { + + RollbarMutableScrubbingOptions *mutable = [RollbarMutableScrubbingOptions new]; + mutable.enabled = NO; + mutable.scrubFields = [@[@"F1"] mutableCopy]; + mutable.safeListFields = [@[@"S1"] mutableCopy]; + XCTAssertTrue(!mutable.enabled); + XCTAssertTrue([mutable.scrubFields containsObject:@"F1"]); + XCTAssertTrue(![mutable.scrubFields containsObject:@"F2"]); + XCTAssertTrue([mutable.safeListFields containsObject:@"S1"]); + XCTAssertTrue(![mutable.safeListFields containsObject:@"S2"]); + + mutable.enabled = YES; + [mutable addScrubField:@"F2"]; + [mutable addScrubSafeListField:@"S2"]; + XCTAssertTrue(mutable.enabled); + XCTAssertTrue([mutable.scrubFields containsObject:@"F1"]); + XCTAssertTrue([mutable.scrubFields containsObject:@"F2"]); + XCTAssertTrue([mutable.safeListFields containsObject:@"S1"]); + XCTAssertTrue([mutable.safeListFields containsObject:@"S2"]); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"F1"]); + XCTAssertTrue([content containsString:@"F2"]); + XCTAssertTrue([content containsString:@"S1"]); + XCTAssertTrue([content containsString:@"S2"]); + + RollbarScrubbingOptions *immutable = [mutable copy]; + XCTAssertNotNil(immutable); + XCTAssertTrue(immutable.enabled); + XCTAssertTrue([immutable.scrubFields containsObject:@"F1"]); + XCTAssertTrue([immutable.scrubFields containsObject:@"F2"]); + XCTAssertTrue([immutable.safeListFields containsObject:@"S1"]); + XCTAssertTrue([immutable.safeListFields containsObject:@"S2"]); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"F1"]); + XCTAssertTrue([content containsString:@"F2"]); + XCTAssertTrue([content containsString:@"S1"]); + XCTAssertTrue([content containsString:@"S2"]); + + XCTAssertEqualObjects(immutable, mutable); + XCTAssertNotIdentical(immutable, mutable); + + XCTAssertEqualObjects(immutable, [immutable copy]); + XCTAssertIdentical (immutable, [immutable copy]); + XCTAssertEqualObjects(immutable, [immutable mutableCopy]); + XCTAssertNotIdentical(immutable, [immutable mutableCopy]); + + XCTAssertEqualObjects(mutable, [mutable copy]); + XCTAssertNotIdentical(mutable, [mutable copy]); + XCTAssertEqualObjects(mutable, [mutable mutableCopy]); + XCTAssertNotIdentical(mutable, [mutable mutableCopy]); +} + +- (void)testRollbarTelemetryOptions { + + RollbarMutableTelemetryOptions *mutable = [RollbarMutableTelemetryOptions new]; + mutable.enabled = NO; + mutable.captureLog = NO; + mutable.captureConnectivity = NO; + mutable.maximumTelemetryData = 10; + mutable.memoryStatsAutocollectionInterval = 11; + [mutable.viewInputsScrubber addScrubField:@"F1"]; + [mutable.viewInputsScrubber addScrubSafeListField:@"S1"]; + XCTAssertTrue(!mutable.enabled); + XCTAssertTrue(!mutable.captureLog); + XCTAssertTrue(!mutable.captureConnectivity); + XCTAssertEqual(mutable.maximumTelemetryData, 10); + XCTAssertEqual(mutable.memoryStatsAutocollectionInterval, 11); + XCTAssertNotNil(mutable.viewInputsScrubber); + XCTAssertNotNil(mutable.viewInputsScrubber.scrubFields); + XCTAssertNotNil(mutable.viewInputsScrubber.safeListFields); + XCTAssertEqual(mutable.viewInputsScrubber.scrubFields.count, 1); + XCTAssertEqual(mutable.viewInputsScrubber.safeListFields.count, 1); + XCTAssertEqual(mutable.viewInputsScrubber.scrubFields[0], @"F1"); + XCTAssertEqual(mutable.viewInputsScrubber.safeListFields[0], @"S1"); + + mutable.enabled = YES; + mutable.captureLog = YES; + mutable.captureConnectivity = YES; + mutable.maximumTelemetryData = 19; + mutable.memoryStatsAutocollectionInterval = 21; + [mutable.viewInputsScrubber addScrubField:@"F2"]; + [mutable.viewInputsScrubber addScrubSafeListField:@"S2"]; + XCTAssertTrue(mutable.enabled); + XCTAssertTrue(mutable.captureLog); + XCTAssertTrue(mutable.captureConnectivity); + XCTAssertEqual(mutable.maximumTelemetryData, 19); + XCTAssertEqual(mutable.memoryStatsAutocollectionInterval, 21); + XCTAssertNotNil(mutable.viewInputsScrubber); + XCTAssertNotNil(mutable.viewInputsScrubber.scrubFields); + XCTAssertNotNil(mutable.viewInputsScrubber.safeListFields); + XCTAssertEqual(mutable.viewInputsScrubber.scrubFields.count, 2); + XCTAssertEqual(mutable.viewInputsScrubber.safeListFields.count, 2); + XCTAssertEqual(mutable.viewInputsScrubber.scrubFields[0], @"F1"); + XCTAssertEqual(mutable.viewInputsScrubber.safeListFields[0], @"S1"); + XCTAssertEqual(mutable.viewInputsScrubber.scrubFields[1], @"F2"); + XCTAssertEqual(mutable.viewInputsScrubber.safeListFields[1], @"S2"); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"19"]); + XCTAssertTrue([content containsString:@"21"]); + XCTAssertTrue([content containsString:@"F1"]); + XCTAssertTrue([content containsString:@"F2"]); + XCTAssertTrue([content containsString:@"S1"]); + XCTAssertTrue([content containsString:@"S2"]); + + RollbarTelemetryOptions *immutable = [mutable copy]; + XCTAssertNotNil(immutable); + XCTAssertTrue(immutable.enabled); + XCTAssertTrue(immutable.captureLog); + XCTAssertTrue(immutable.captureConnectivity); + XCTAssertEqual(immutable.maximumTelemetryData, 19); + XCTAssertEqual(immutable.memoryStatsAutocollectionInterval, 21); + XCTAssertNotNil(immutable.viewInputsScrubber); + XCTAssertNotNil(immutable.viewInputsScrubber.scrubFields); + XCTAssertNotNil(immutable.viewInputsScrubber.safeListFields); + XCTAssertEqual(immutable.viewInputsScrubber.scrubFields.count, 2); + XCTAssertEqual(immutable.viewInputsScrubber.safeListFields.count, 2); + XCTAssertEqual(immutable.viewInputsScrubber.scrubFields[0], @"F1"); + XCTAssertEqual(immutable.viewInputsScrubber.safeListFields[0], @"S1"); + XCTAssertEqual(immutable.viewInputsScrubber.scrubFields[1], @"F2"); + XCTAssertEqual(immutable.viewInputsScrubber.safeListFields[1], @"S2"); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"19"]); + XCTAssertTrue([content containsString:@"21"]); + XCTAssertTrue([content containsString:@"F1"]); + XCTAssertTrue([content containsString:@"F2"]); + XCTAssertTrue([content containsString:@"S1"]); + XCTAssertTrue([content containsString:@"S2"]); + + XCTAssertEqualObjects(immutable, mutable); + XCTAssertNotIdentical(immutable, mutable); + + XCTAssertEqualObjects(immutable, [immutable copy]); + XCTAssertIdentical (immutable, [immutable copy]); + XCTAssertEqualObjects(immutable, [immutable mutableCopy]); + XCTAssertNotIdentical(immutable, [immutable mutableCopy]); + + XCTAssertEqualObjects(mutable, [mutable copy]); + XCTAssertNotIdentical(mutable, [mutable copy]); + XCTAssertEqualObjects(mutable, [mutable mutableCopy]); + XCTAssertNotIdentical(mutable, [mutable mutableCopy]); +} + +- (void)testRollbarConfig { + +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index ed06cb27..a94d97c0 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -31,7 +31,7 @@ - (void)tearDown { - (void)testConfigCloning { - RollbarConfig *rc = [RollbarConfig new]; + RollbarMutableConfig *rc = [RollbarMutableConfig new]; NSString *customEnv = @"CUSTOM_ENV"; XCTAssertNotEqual(rc.destination.environment, customEnv); @@ -209,7 +209,7 @@ - (void)testEnabled { Rollbar.currentConfiguration.developerOptions.enabled = NO; - Rollbar.currentLogger.configuration.developerOptions.enabled = NO; + //Rollbar.currentLogger.configuration.developerOptions.enabled = NO; [Rollbar debugMessage:@"Test1"]; [RollbarLogger flushRollbarThread]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index ab1e4986..02c0fe70 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -54,8 +54,8 @@ - (void)testBasics { XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - RollbarConfig *config = [RollbarConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment] + RollbarMutableConfig *config = [RollbarMutableConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment] ]; config.developerOptions.transmit = NO; config.developerOptions.logPayload = YES; @@ -96,9 +96,9 @@ - (void)testLive { XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - RollbarConfig *config = [RollbarConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment] - ]; + RollbarMutableConfig *config = + [RollbarMutableConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; config.developerOptions.transmit = YES; config.developerOptions.logPayload = YES; [[RollbarInfrastructure sharedInstance] configureWith:config]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m index db7e8dba..d78a3421 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m @@ -20,7 +20,7 @@ - (void)setUp { if (!Rollbar.currentConfiguration) { - RollbarConfig *config = [[RollbarConfig alloc] init]; + RollbarMutableConfig *config = [[RollbarMutableConfig alloc] init]; config.destination.accessToken = [RollbarTestHelper getRollbarPayloadsAccessToken]; config.destination.environment = [RollbarTestHelper getRollbarEnvironment]; config.developerOptions.transmit = YES; @@ -45,8 +45,9 @@ - (void)testMultithreadedStressCase { for( int i = 0; i < 20; i++) { dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY,0), ^(){ - RollbarLogger *logger = [[RollbarLogger alloc] initWithAccessToken:Rollbar.currentConfiguration.destination.accessToken]; - logger.configuration.destination.environment = [RollbarTestHelper getRollbarEnvironment]; + RollbarMutableConfig *config = [Rollbar.currentConfiguration mutableCopy]; + config.destination.environment = [RollbarTestHelper getRollbarEnvironment]; + RollbarLogger *logger = [[RollbarLogger alloc] initWithConfiguration:config]; for (int j = 0; j < 20; j++) { [logger log:RollbarLevel_Error message:@"error" @@ -83,8 +84,10 @@ - (void)testRollbarNotifiersIndependentConfiguration { Rollbar.currentConfiguration.destination.environment); // create and configure another notifier: - RollbarLogger *notifier = [[RollbarLogger alloc] initWithAccessToken:@"AT_1"]; - notifier.configuration.destination.environment = @"ENV_1"; + RollbarMutableConfig *config = [RollbarMutableConfig new]; + config.destination.accessToken = @"AT_1"; + config.destination.environment = @"ENV_1"; + RollbarLogger *notifier = [[RollbarLogger alloc] initWithConfiguration:config]; XCTAssertTrue([notifier.configuration.destination.accessToken compare:@"AT_1"] == NSOrderedSame); XCTAssertTrue([notifier.configuration.destination.environment compare:@"ENV_1"] == NSOrderedSame); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigUtilTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigUtilTests.swift index 5fde124e..0e36074e 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigUtilTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigUtilTests.swift @@ -61,7 +61,7 @@ final class RolllbarNotifierConfigUtilTests: XCTestCase { } func testWithConfigFile() { - var config : RollbarConfig = RollbarConfig(); + var config : RollbarConfig = RollbarMutableConfig(); XCTAssertNotNil(config); do { _ = try RollbarConfigUtil.save(config); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift index 2e207850..39057bba 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift @@ -22,12 +22,12 @@ final class RollbarNotifierConfigurationTests: XCTestCase { } override func tearDown() { - Rollbar.updateConfiguration(RollbarConfig()); + Rollbar.updateConfiguration(RollbarMutableConfig()); super.tearDown(); } func testDefaultRollbarConfiguration() { - let rc = RollbarConfig(); + let rc = RollbarMutableConfig(); NSLog("%@", rc); } @@ -130,13 +130,13 @@ final class RollbarNotifierConfigurationTests: XCTestCase { let element1 = "password"; let element2 = "pin"; - Rollbar.currentConfiguration()?.telemetry.viewInputsScrubber.scrubFields.append(element1); - Rollbar.currentConfiguration()?.telemetry.viewInputsScrubber.scrubFields.append(element2); + Rollbar.currentConfiguration()?.telemetry.viewInputsScrubber.scrubFields.add(element1); + Rollbar.currentConfiguration()?.telemetry.viewInputsScrubber.scrubFields.add(element2); Rollbar.updateConfiguration(Rollbar.currentConfiguration()!); XCTAssertTrue( - RollbarTelemetry.sharedInstance().viewInputsToScrub!.count == (RollbarScrubbingOptions().scrubFields.count + 2), + RollbarTelemetry.sharedInstance().viewInputsToScrub!.count == (RollbarMutableScrubbingOptions().scrubFields.count + 2), "RollbarTelemetry.sharedInstance.viewInputsToScrub is expected to count = 2" ); XCTAssertTrue( @@ -154,7 +154,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.updateConfiguration(Rollbar.currentConfiguration()!); XCTAssertTrue( - RollbarTelemetry.sharedInstance().viewInputsToScrub!.count == RollbarScrubbingOptions().scrubFields.count, + RollbarTelemetry.sharedInstance().viewInputsToScrub!.count == RollbarMutableScrubbingOptions().scrubFields.count, "RollbarTelemetry.sharedInstance.viewInputsToScrub is expected to count = 0" ); } @@ -170,7 +170,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.currentConfiguration()?.developerOptions.enabled = false; - Rollbar.currentLogger().configuration!.developerOptions.enabled = false; + //Rollbar.currentLogger().configuration!.developerOptions.enabled = false; Rollbar.debugMessage("Test1"); RollbarTestUtil.waitForPesistenceToComplete(); logItems = RollbarTestUtil.readItemStringsFromLogFile(); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierDTOsTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierDTOsTests.swift index 565aaacc..f17ccb35 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierDTOsTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierDTOsTests.swift @@ -76,7 +76,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { func testRollbarScrubbingOptionsDTO() { - let dto = RollbarScrubbingOptions(scrubFields: ["field1", "field2"]); + let dto = RollbarMutableScrubbingOptions(scrubFields: ["field1", "field2"]); XCTAssertTrue(dto.enabled, "Enabled by default" ); @@ -100,7 +100,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { func testRollbarServerConfigDTO() { - var dto = RollbarServerConfig(host: "HOST", root: "ROOT", branch: "BRANCH", codeVersion: "1.2.3"); + var dto = RollbarMutableServerConfig(host: "HOST", root: "ROOT", branch: "BRANCH", codeVersion: "1.2.3"); XCTAssertTrue(.orderedSame == dto.host!.compare("HOST"), "Proper host" @@ -133,7 +133,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { ); - let rc = RollbarConfig(); + let rc = RollbarMutableConfig(); rc.destination.accessToken = "ACCESSTOKEN"; rc.destination.environment = "ENVIRONMENT"; rc.destination.endpoint = "ENDPOINT"; @@ -151,7 +151,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { func testRollbarPersonDTO() { - var dto = RollbarPerson(id: "ID", username: "USERNAME", email: "EMAIL"); + var dto = RollbarMutablePerson(id: "ID", username: "USERNAME", email: "EMAIL"); XCTAssertTrue(.orderedSame == dto.id.compare("ID"), "Proper ID" @@ -176,7 +176,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { "Proper email" ); - dto = RollbarPerson(id: "ID007"); + dto = RollbarMutablePerson(id: "ID007"); XCTAssertTrue(.orderedSame == dto.id.compare("ID007"), "Proper ID" ); @@ -187,7 +187,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { "Proper default email" ); - dto = RollbarPerson(id: "nil", username: "USERNAME", email: "EMAIL"); + dto = RollbarMutablePerson(id: "nil", username: "USERNAME", email: "EMAIL"); XCTAssertTrue(.orderedSame == dto.id.compare("nil"), "Proper initial ID" ); @@ -205,7 +205,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { func testRollbarModuleDTO() { - var dto = RollbarModule(name: "ModuleName", version: "v1.2.3"); + var dto = RollbarMutableModule(name: "ModuleName", version: "v1.2.3"); XCTAssertTrue(.orderedSame == dto.name!.compare("ModuleName"), "Proper name" @@ -223,7 +223,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { "Proper version" ); - dto = RollbarModule(name: "Module"); + dto = RollbarMutableModule(name: "Module"); XCTAssertTrue(.orderedSame == dto.name!.compare("Module"), "Proper name" ); @@ -265,7 +265,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { "Proper view inputs scrubber white list fields count" ); - dto = RollbarTelemetryOptions(); + dto = RollbarMutableTelemetryOptions(); XCTAssertTrue(!dto.enabled, "Proper enabled" ); @@ -289,7 +289,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { func testRollbarLoggingOptionsDTO() { - var dto = RollbarLoggingOptions( + var dto = RollbarMutableLoggingOptions( logLevel: .error, crash: .info, maximumReportsPerMinute: UInt(45) @@ -321,7 +321,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { "Proper request ID" ); - dto = RollbarLoggingOptions(); + dto = RollbarMutableLoggingOptions(); XCTAssertTrue(dto.logLevel == .info, "Proper default log level" ); @@ -350,7 +350,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { func testRollbarConfigDTO() { - let rc = RollbarConfig(); + let rc = RollbarMutableConfig(); //id destination = rc.destination; rc.destination.accessToken = "ACCESSTOKEN"; rc.destination.environment = "ENVIRONMENT"; @@ -361,7 +361,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { rc.setServerHost("SERVERHOST", root:"SERVERROOT", branch: "SERVERBRANCH", codeVersion: "SERVERCODEVERSION"); rc.setNotifierName("NOTIFIERNAME", version: "NOTIFIERVERSION"); - var rcClone = RollbarConfig(jsonString: rc.serializeToJSONString()!); + var rcClone = RollbarMutableConfig(jsonString: rc.serializeToJSONString()!); // id scrubList = rc.scrubFields; // id scrubListClone = rcClone.scrubFields; @@ -385,7 +385,7 @@ final class RollbarNotifierDTOsTests: XCTestCase { // [rcClone serializeToJSONString] // ); - rcClone = RollbarConfig(jsonString: rc.serializeToJSONString()!); + rcClone = RollbarMutableConfig(jsonString: rc.serializeToJSONString()!); rcClone.httpProxy.proxyUrl = "SOME_OTHER_ONE"; XCTAssertTrue(!rc.isEqual(rcClone), "Two DTOs are NOT expected to be equal" diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift index 0d81396a..ab53e1f7 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift @@ -31,7 +31,7 @@ final class RollbarNotifierLoggerTests: XCTestCase { RollbarTestUtil.waitForPesistenceToComplete(waitTimeInSeconds: 2.0); - Rollbar.updateConfiguration(RollbarConfig()); + Rollbar.updateConfiguration(RollbarMutableConfig()); super.tearDown(); } @@ -62,8 +62,10 @@ final class RollbarNotifierLoggerTests: XCTestCase { Rollbar.currentConfiguration()?.destination.environment); // create and configure another notifier: - let notifier = RollbarLogger(accessToken: "AT_1"); - notifier.configuration!.destination.environment = "ENV_1"; + let config = Rollbar.currentConfiguration()!; + config.destination.accessToken = "AT_1"; + config.destination.environment = "ENV_1"; + let notifier = RollbarLogger(configuration: config); XCTAssertTrue(notifier.configuration!.destination.accessToken.compare("AT_1") == .orderedSame); XCTAssertTrue(notifier.configuration!.destination.environment.compare("ENV_1") == .orderedSame); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift index 4684081a..abcc6a48 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift @@ -23,7 +23,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { } override func tearDown() { - Rollbar.updateConfiguration(RollbarConfig()); + Rollbar.updateConfiguration(RollbarMutableConfig()); super.tearDown(); } @@ -32,7 +32,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { RollbarTestUtil.clearLogFile(); RollbarTestUtil.clearTelemetryFile(); - let config = RollbarConfig(); + let config = RollbarMutableConfig(); config.destination.accessToken = RollbarTestHelper.getRollbarPayloadsAccessToken(); config.destination.environment = RollbarTestHelper.getRollbarEnvironment(); config.developerOptions.transmit = false; @@ -66,7 +66,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { RollbarTestUtil.clearLogFile(); RollbarTestUtil.clearTelemetryFile(); - let config = RollbarConfig(); + let config = RollbarMutableConfig(); config.destination.accessToken = RollbarTestHelper.getRollbarPayloadsAccessToken(); config.destination.environment = RollbarTestHelper.getRollbarEnvironment(); config.telemetry.enabled = true; @@ -269,8 +269,8 @@ final class RollbarNotifierTelemetryTests: XCTestCase { Rollbar.currentConfiguration()?.telemetry.enabled = true; Rollbar.currentConfiguration()?.telemetry.viewInputsScrubber.enabled = true; - Rollbar.currentConfiguration()?.telemetry.viewInputsScrubber.scrubFields.append("password"); - Rollbar.currentConfiguration()?.telemetry.viewInputsScrubber.scrubFields.append("pin"); + Rollbar.currentConfiguration()?.telemetry.viewInputsScrubber.scrubFields.add("password"); + Rollbar.currentConfiguration()?.telemetry.viewInputsScrubber.scrubFields.add("pin"); Rollbar.updateConfiguration(Rollbar.currentConfiguration()!); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift index 71016c7e..995f70ac 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift @@ -21,7 +21,7 @@ final class RollbarNotifierTruncationTests: XCTestCase { } override func tearDown() { - Rollbar.updateConfiguration(RollbarConfig()); + Rollbar.updateConfiguration(RollbarMutableConfig()); super.tearDown(); } From a85ed79269634e381c85cd9f3c69a02f9cad7b3a Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 15 Jul 2022 23:08:17 -0700 Subject: [PATCH 059/127] test: fixed RollbarConfigTests --- .../RollbarConfigTests.m | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m index 556415eb..66e55b16 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m @@ -494,10 +494,10 @@ - (void)testRollbarTelemetryOptions { XCTAssertNotNil(mutable.viewInputsScrubber.safeListFields); XCTAssertEqual(mutable.viewInputsScrubber.scrubFields.count, 2); XCTAssertEqual(mutable.viewInputsScrubber.safeListFields.count, 2); - XCTAssertEqual(mutable.viewInputsScrubber.scrubFields[0], @"F1"); - XCTAssertEqual(mutable.viewInputsScrubber.safeListFields[0], @"S1"); - XCTAssertEqual(mutable.viewInputsScrubber.scrubFields[1], @"F2"); - XCTAssertEqual(mutable.viewInputsScrubber.safeListFields[1], @"S2"); + XCTAssertTrue([mutable.viewInputsScrubber.scrubFields[0] isEqualToString:@"F1"]); + XCTAssertTrue([mutable.viewInputsScrubber.safeListFields[0] isEqualToString:@"S1"]); + XCTAssertTrue([mutable.viewInputsScrubber.scrubFields[1] isEqualToString:@"F2"]); + XCTAssertTrue([mutable.viewInputsScrubber.safeListFields[1] isEqualToString:@"S2"]); NSString *content = [mutable serializeToJSONString]; XCTAssertNotNil(content); @@ -520,10 +520,10 @@ - (void)testRollbarTelemetryOptions { XCTAssertNotNil(immutable.viewInputsScrubber.safeListFields); XCTAssertEqual(immutable.viewInputsScrubber.scrubFields.count, 2); XCTAssertEqual(immutable.viewInputsScrubber.safeListFields.count, 2); - XCTAssertEqual(immutable.viewInputsScrubber.scrubFields[0], @"F1"); - XCTAssertEqual(immutable.viewInputsScrubber.safeListFields[0], @"S1"); - XCTAssertEqual(immutable.viewInputsScrubber.scrubFields[1], @"F2"); - XCTAssertEqual(immutable.viewInputsScrubber.safeListFields[1], @"S2"); + XCTAssertTrue([immutable.viewInputsScrubber.scrubFields[0] isEqualToString:@"F1"]); + XCTAssertTrue([immutable.viewInputsScrubber.safeListFields[0] isEqualToString:@"S1"]); + XCTAssertTrue([immutable.viewInputsScrubber.scrubFields[1] isEqualToString:@"F2"]); + XCTAssertTrue([immutable.viewInputsScrubber.safeListFields[1] isEqualToString:@"S2"]); content = [immutable serializeToJSONString]; XCTAssertNotNil(content); From 524b03079a8c6c56a940caec6e64b6d261ab533b Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 18 Jul 2022 22:35:50 -0700 Subject: [PATCH 060/127] test: improving RollbarConfig unit tests --- .../RollbarNotifier/DTOs/RollbarConfig.m | 2 +- .../RollbarNotifier/DTOs/RollbarDestination.m | 2 +- .../DTOs/RollbarLoggingOptions.m | 2 +- .../DTOs/RollbarScrubbingOptions.m | 6 +- .../DTOs/RollbarTelemetryOptions.m | 7 +- .../RollbarNotifier/include/RollbarModule.h | 3 + .../RollbarNotifier/include/RollbarPerson.h | 3 + .../RollbarNotifierTests-ObjC/DTOsTests.m | 2 +- .../RollbarConfigTests.m | 94 +++++++++++++++++-- 9 files changed, 105 insertions(+), 16 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m index fe9ac849..f638a5ea 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m @@ -235,7 +235,7 @@ @implementation RollbarMutableConfig -(instancetype)init { - if (self = [super initWithDictionary:@{}]) { + if (self = [super init]) { return self; } return nil; diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDestination.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDestination.m index 2fa20104..ff3ffc22 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDestination.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDestination.m @@ -78,7 +78,7 @@ @implementation RollbarMutableDestination -(instancetype)init { - if (self = [super initWithDictionary:@{}]) { + if (self = [super init]) { return self; } return nil; diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarLoggingOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarLoggingOptions.m index 76cefa16..d69ad029 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarLoggingOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarLoggingOptions.m @@ -200,7 +200,7 @@ @implementation RollbarMutableLoggingOptions -(instancetype)init { - if (self = [super initWithDictionary:@{}]) { + if (self = [super init]) { return self; } return nil; diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarScrubbingOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarScrubbingOptions.m index ef8f50ef..4a2439d7 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarScrubbingOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarScrubbingOptions.m @@ -33,8 +33,8 @@ - (instancetype)initWithScrubFields:(NSArray *)scrubFields safeListFields:(NSArray *)safeListFields { return [self initWithEnabled:DEFAULT_ENABLED_FLAG - scrubFields:scrubFields - safeListFields:safeListFields + scrubFields:[scrubFields mutableCopy] + safeListFields:[safeListFields mutableCopy] ]; } @@ -84,7 +84,7 @@ @implementation RollbarMutableScrubbingOptions -(instancetype)init { - if (self = [super initWithDictionary:@{}]) { + if (self = [super init]) { return self; } return nil; diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarTelemetryOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarTelemetryOptions.m index 13fd7c7c..48627c88 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarTelemetryOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarTelemetryOptions.m @@ -110,9 +110,14 @@ @implementation RollbarMutableTelemetryOptions -(instancetype)init { - if (self = [super initWithDictionary:@{}]) { + if (self = [super initWithEnabled:DEFAULT_ENABLED_FLAG + captureLog:DEFAULT_CAPTURE_LOG_FLAG + captureConnectivity:DEFAULT_CAPTURE_CONNECTIVITY_FLAG + viewInputsScrubber:[RollbarMutableScrubbingOptions new] + ]) { return self; } + return nil; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarModule.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarModule.h index 07907f65..77d42b81 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarModule.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarModule.h @@ -23,6 +23,9 @@ NS_ASSUME_NONNULL_BEGIN - (instancetype)init NS_UNAVAILABLE; +- (instancetype)new +NS_UNAVAILABLE; + #pragma mark - properties /// Optional: name diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarPerson.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarPerson.h index 02603a05..98af25c1 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarPerson.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarPerson.h @@ -38,6 +38,9 @@ NS_ASSUME_NONNULL_BEGIN - (instancetype)init NS_UNAVAILABLE; +- (instancetype)new +NS_UNAVAILABLE; + #pragma mark - properties /// Required: id. diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/DTOsTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/DTOsTests.m index 3e9280dc..619c3d5d 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/DTOsTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/DTOsTests.m @@ -298,7 +298,7 @@ - (void)testRollbarTelemetryOptionsDTO { [[RollbarScrubbingOptions alloc] initWithEnabled:YES scrubFields:@[@"one", @"two"] safeListFields:@[@"two", @"three", @"four"] - ]; + ]; RollbarTelemetryOptions *dto = [[RollbarTelemetryOptions alloc] initWithEnabled:YES captureLog:YES captureConnectivity:YES diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m index 66e55b16..145524cd 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m @@ -25,6 +25,10 @@ - (void)tearDown { } - (void)testRollbarDestination { + + NSString *defaultMutable = [[RollbarMutableDestination new] serializeToJSONString]; + NSString *defaultImmutable = [[RollbarDestination new] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); RollbarMutableDestination *mutable = [RollbarMutableDestination new]; mutable.endpoint = @"test_EP"; @@ -68,6 +72,10 @@ - (void)testRollbarDestination { - (void)testRollbarDeveloperOptions { + NSString *defaultMutable = [[RollbarMutableDeveloperOptions new] serializeToJSONString]; + NSString *defaultImmutable = [[RollbarDeveloperOptions new] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); + RollbarMutableDeveloperOptions *mutable = [RollbarMutableDeveloperOptions new]; mutable.enabled = NO; mutable.transmit = NO; @@ -123,6 +131,10 @@ - (void)testRollbarDeveloperOptions { - (void)testRollbarLoggingOptions { + NSString *defaultMutable = [[RollbarMutableLoggingOptions new] serializeToJSONString]; + NSString *defaultImmutable = [[RollbarLoggingOptions new] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); + RollbarMutableLoggingOptions *mutable = [RollbarMutableLoggingOptions new]; mutable.logLevel = RollbarLevel_Info; mutable.crashLevel = RollbarLevel_Error; @@ -205,6 +217,10 @@ - (void)testRollbarLoggingOptions { - (void)testRollbarModule { + NSString *defaultMutable = [[RollbarMutableModule new] serializeToJSONString]; + NSString *defaultImmutable = [[[RollbarModule alloc] initWithName:nil] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); + RollbarMutableModule *mutable = [RollbarMutableModule new]; mutable.name = @"test_N_old"; mutable.version = @"test_V_old"; @@ -247,6 +263,10 @@ - (void)testRollbarModule { - (void)testRollbarPerson { + NSString *defaultMutable = [[[RollbarMutablePerson alloc] initWithID:@"ID"] serializeToJSONString]; + NSString *defaultImmutable = [[[RollbarPerson alloc] initWithID:@"ID"] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); + RollbarMutablePerson *mutable = [RollbarMutablePerson new]; mutable.ID = @"test_ID_old"; mutable.username = @"test_UN_old"; @@ -296,6 +316,10 @@ - (void)testRollbarPerson { - (void)testRollbarProxy { + NSString *defaultMutable = [[RollbarMutableProxy new] serializeToJSONString]; + NSString *defaultImmutable = [[RollbarProxy new] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); + RollbarMutableProxy *mutable = [RollbarMutableProxy new]; mutable.enabled = NO; mutable.proxyUrl = @"test_URL_old"; @@ -343,6 +367,10 @@ - (void)testRollbarProxy { - (void)testRollbarServerConfig { + NSString *defaultMutable = [[RollbarMutableServerConfig new] serializeToJSONString]; + NSString *defaultImmutable = [[RollbarServerConfig new] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); + RollbarMutableServerConfig *mutable = [RollbarMutableServerConfig new]; mutable.host = @"test_H_old"; mutable.root = @"test_R_old"; @@ -399,6 +427,10 @@ - (void)testRollbarServerConfig { - (void)testRollbarScrubbingOptions { + NSString *defaultMutable = [[RollbarMutableScrubbingOptions new] serializeToJSONString]; + NSString *defaultImmutable = [[RollbarScrubbingOptions new] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); + RollbarMutableScrubbingOptions *mutable = [RollbarMutableScrubbingOptions new]; mutable.enabled = NO; mutable.scrubFields = [@[@"F1"] mutableCopy]; @@ -456,6 +488,10 @@ - (void)testRollbarScrubbingOptions { - (void)testRollbarTelemetryOptions { + NSString *defaultMutable = [[RollbarMutableTelemetryOptions new] serializeToJSONString]; + NSString *defaultImmutable = [[RollbarTelemetryOptions new] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); + RollbarMutableTelemetryOptions *mutable = [RollbarMutableTelemetryOptions new]; mutable.enabled = NO; mutable.captureLog = NO; @@ -472,9 +508,9 @@ - (void)testRollbarTelemetryOptions { XCTAssertNotNil(mutable.viewInputsScrubber); XCTAssertNotNil(mutable.viewInputsScrubber.scrubFields); XCTAssertNotNil(mutable.viewInputsScrubber.safeListFields); - XCTAssertEqual(mutable.viewInputsScrubber.scrubFields.count, 1); + XCTAssertEqual(mutable.viewInputsScrubber.scrubFields.count, 9); XCTAssertEqual(mutable.viewInputsScrubber.safeListFields.count, 1); - XCTAssertEqual(mutable.viewInputsScrubber.scrubFields[0], @"F1"); + XCTAssertEqual(mutable.viewInputsScrubber.scrubFields[8], @"F1"); XCTAssertEqual(mutable.viewInputsScrubber.safeListFields[0], @"S1"); mutable.enabled = YES; @@ -492,11 +528,11 @@ - (void)testRollbarTelemetryOptions { XCTAssertNotNil(mutable.viewInputsScrubber); XCTAssertNotNil(mutable.viewInputsScrubber.scrubFields); XCTAssertNotNil(mutable.viewInputsScrubber.safeListFields); - XCTAssertEqual(mutable.viewInputsScrubber.scrubFields.count, 2); + XCTAssertEqual(mutable.viewInputsScrubber.scrubFields.count, 10); XCTAssertEqual(mutable.viewInputsScrubber.safeListFields.count, 2); - XCTAssertTrue([mutable.viewInputsScrubber.scrubFields[0] isEqualToString:@"F1"]); + XCTAssertTrue([mutable.viewInputsScrubber.scrubFields[8] isEqualToString:@"F1"]); XCTAssertTrue([mutable.viewInputsScrubber.safeListFields[0] isEqualToString:@"S1"]); - XCTAssertTrue([mutable.viewInputsScrubber.scrubFields[1] isEqualToString:@"F2"]); + XCTAssertTrue([mutable.viewInputsScrubber.scrubFields[9] isEqualToString:@"F2"]); XCTAssertTrue([mutable.viewInputsScrubber.safeListFields[1] isEqualToString:@"S2"]); NSString *content = [mutable serializeToJSONString]; @@ -518,11 +554,11 @@ - (void)testRollbarTelemetryOptions { XCTAssertNotNil(immutable.viewInputsScrubber); XCTAssertNotNil(immutable.viewInputsScrubber.scrubFields); XCTAssertNotNil(immutable.viewInputsScrubber.safeListFields); - XCTAssertEqual(immutable.viewInputsScrubber.scrubFields.count, 2); + XCTAssertEqual(immutable.viewInputsScrubber.scrubFields.count, 10); XCTAssertEqual(immutable.viewInputsScrubber.safeListFields.count, 2); - XCTAssertTrue([immutable.viewInputsScrubber.scrubFields[0] isEqualToString:@"F1"]); + XCTAssertTrue([immutable.viewInputsScrubber.scrubFields[8] isEqualToString:@"F1"]); XCTAssertTrue([immutable.viewInputsScrubber.safeListFields[0] isEqualToString:@"S1"]); - XCTAssertTrue([immutable.viewInputsScrubber.scrubFields[1] isEqualToString:@"F2"]); + XCTAssertTrue([immutable.viewInputsScrubber.scrubFields[9] isEqualToString:@"F2"]); XCTAssertTrue([immutable.viewInputsScrubber.safeListFields[1] isEqualToString:@"S2"]); content = [immutable serializeToJSONString]; @@ -550,6 +586,48 @@ - (void)testRollbarTelemetryOptions { - (void)testRollbarConfig { + NSString *defaultMutable = [[RollbarMutableConfig new] serializeToJSONString]; + NSString *defaultImmutable = [[RollbarConfig new] serializeToJSONString]; + XCTAssertTrue([defaultMutable isEqualToString:defaultImmutable]); + + RollbarMutableConfig *mutable = [RollbarMutableConfig new]; + mutable.destination.accessToken = @"test_AT_old"; + RollbarMutableDeveloperOptions *devOptions = [RollbarMutableDeveloperOptions new]; + devOptions.payloadLogFile = @"test_PL_old"; + mutable.developerOptions = devOptions; + + XCTAssertTrue([mutable.destination.accessToken isEqualToString:@"test_AT_old"]); + XCTAssertTrue([mutable.developerOptions.payloadLogFile isEqualToString:@"test_PL_old"]); + + NSString *content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_AT_old"]); + XCTAssertTrue([content containsString:@"test_PL_old"]); + + mutable.destination.accessToken = @"test_AT"; + mutable.developerOptions.payloadLogFile = @"test_PL"; + + XCTAssertTrue([mutable.destination.accessToken isEqualToString:@"test_AT"]); + XCTAssertTrue([mutable.developerOptions.payloadLogFile isEqualToString:@"test_PL"]); + + content = [mutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_AT"]); + XCTAssertTrue([content containsString:@"test_PL"]); + XCTAssertTrue(![content containsString:@"test_AT_old"]); + XCTAssertTrue(![content containsString:@"test_PL_old"]); + + RollbarConfig *immutable = [mutable copy]; + + XCTAssertTrue([immutable.destination.accessToken isEqualToString:@"test_AT"]); + XCTAssertTrue([immutable.developerOptions.payloadLogFile isEqualToString:@"test_PL"]); + + content = [immutable serializeToJSONString]; + XCTAssertNotNil(content); + XCTAssertTrue([content containsString:@"test_AT"]); + XCTAssertTrue([content containsString:@"test_PL"]); + XCTAssertTrue(![content containsString:@"test_AT_old"]); + XCTAssertTrue(![content containsString:@"test_PL_old"]); } - (void)testPerformanceExample { From b78646ac429576918c53b446937ee4b9c3a6cc28 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 19 Jul 2022 14:48:30 -0700 Subject: [PATCH 061/127] refactor: Rollbar facade component --- .../Sources/RollbarNotifier/Rollbar.m | 220 +++++++++--------- .../RollbarNotifier/RollbarInfrastructure.m | 5 +- .../Sources/RollbarNotifier/include/Rollbar.h | 24 +- 3 files changed, 125 insertions(+), 124 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m index ab0faea7..1434784d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m +++ b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m @@ -35,21 +35,21 @@ static void uncaughtExceptionHandler(NSException * _Nonnull exception) { @implementation Rollbar -static RollbarLogger *logger = nil; -static RollbarTelemetryOptionsObserver *telemetryOptionsObserver = nil; -static id crashCollector = nil; -static RollbarCrashProcessor *crashProcessor = nil; - -+ (void)initialize { - - if (self == [Rollbar class]) { - - telemetryOptionsObserver = [RollbarTelemetryOptionsObserver new]; - } - - //[[RollbarSession sharedInstance] registerApplicationHooks]; - -} +//static RollbarLogger *logger = nil; +//static RollbarTelemetryOptionsObserver *telemetryOptionsObserver = nil; +//static id crashCollector = nil; +//static RollbarCrashProcessor *crashProcessor = nil; + +//+ (void)initialize { +// +// if (self == [Rollbar class]) { +// +// telemetryOptionsObserver = [RollbarTelemetryOptionsObserver new]; +// } +// +// //[[RollbarSession sharedInstance] registerApplicationHooks]; +// +//} + (void)initWithAccessToken:(NSString *)accessToken { @@ -86,143 +86,131 @@ + (void)initWithAccessToken:(nullable NSString *)accessToken configuration:(nullable RollbarConfig *)configuration crashCollector:(nullable id)crashCollector { - if (logger) { - - RollbarSdkLog(@"Rollbar has already been initialized."); - } else { - - RollbarMutableConfig *config = configuration ? [configuration mutableCopy] : [RollbarMutableConfig new]; - if (accessToken && accessToken.length > 0) { - - config.destination.accessToken = accessToken; - } - - //[[RollbarThread sharedInstance] setReportingRate:config.loggingOptions.maximumReportsPerMinute]; + RollbarMutableConfig *config = configuration ? [configuration mutableCopy] : [RollbarMutableConfig new]; + if (accessToken && accessToken.length > 0) { - [Rollbar updateConfiguration:config]; - - if (crashCollector) { - - crashProcessor = [[RollbarCrashProcessor alloc] init]; - [crashCollector collectCrashReportsWithObserver:crashProcessor]; - } - - RollbarCrashReportCheck crashRepoertCheck = ^() { - - BOOL result = NO; - if (crashProcessor.totalProcessedReports > 0) { - - result = YES; - } - return result; - }; - [[RollbarSession sharedInstance] enableOomMonitoring:config.loggingOptions.enableOomDetection - withCrashCheck:crashRepoertCheck]; + config.destination.accessToken = accessToken; } -} -+ (RollbarConfig *)currentConfiguration { - - return logger.configuration; + [[RollbarInfrastructure sharedInstance] configureWith:config + andCrashCollector:crashCollector]; } -+ (RollbarLogger *)currentLogger { ++ (RollbarConfig *)configuration { - return logger; + return [RollbarInfrastructure sharedInstance].configuration; } + (void)updateConfiguration:(RollbarConfig *)configuration { - - NSUInteger oldReportingRate = 0; - - if (logger) { - oldReportingRate = logger.configuration.loggingOptions.maximumReportsPerMinute; - [logger updateConfiguration:configuration]; - } - else { - logger = [[RollbarLogger alloc] initWithConfiguration:configuration]; - } - -// if (oldReportingRate != configuration.loggingOptions.maximumReportsPerMinute) { -// [logger updateReportingRate:configuration.loggingOptions.maximumReportsPerMinute]; + + [[RollbarInfrastructure sharedInstance] configureWith:configuration + andCrashCollector:nil]; + +// NSUInteger oldReportingRate = 0; +// +// if (logger) { +// oldReportingRate = logger.configuration.loggingOptions.maximumReportsPerMinute; +// [logger updateConfiguration:configuration]; +// } +// else { +// logger = [[RollbarLogger alloc] initWithConfiguration:configuration]; +// } +// +//// if (oldReportingRate != configuration.loggingOptions.maximumReportsPerMinute) { +//// [logger updateReportingRate:configuration.loggingOptions.maximumReportsPerMinute]; +//// } +// +// if (configuration && configuration.telemetry) { +// +// [[RollbarTelemetry sharedInstance] configureWithOptions:configuration.telemetry]; // } - - if (configuration && configuration.telemetry) { - - [[RollbarTelemetry sharedInstance] configureWithOptions:configuration.telemetry]; - } } -+ (void)reapplyConfiguration { - - RollbarConfig *config = Rollbar.currentConfiguration; - if (nil != config) { - [Rollbar updateConfiguration:config]; - } -} +#pragma mark - Legacy methods to remove + +// TODO: remove this method... +//+ (RollbarConfig *)currentConfiguration { +// +// return logger.configuration; +//} + +// TODO: remove this method... +//+ (RollbarLogger *)currentLogger { +// +// return logger; +//} + +// TODO: remove this method... +//+ (void)reapplyConfiguration { +// +// RollbarConfig *config = Rollbar.currentConfiguration; +// if (nil != config) { +// [Rollbar updateConfiguration:config]; +// } +//} #pragma mark - Logging methods + (void)logCrashReport:(NSString *)crashReport { - [logger logCrashReport:crashReport]; + [[RollbarInfrastructure sharedInstance].logger logCrashReport:crashReport]; } + (void)log:(RollbarLevel)level message:(NSString *)message { - [logger log:level - message:message - data:nil - context:nil]; + [[RollbarInfrastructure sharedInstance].logger log:level + message:message + data:nil + context:nil]; } + (void)log:(RollbarLevel)level exception:(NSException *)exception { - [logger log:level - exception:exception - data:nil - context:nil]; + [[RollbarInfrastructure sharedInstance].logger log:level + exception:exception + data:nil + context:nil]; } + (void)log:(RollbarLevel)level error:(NSError *)error { - [logger log:level - error:error - data:nil - context:nil]; + [[RollbarInfrastructure sharedInstance].logger log:level + error:error + data:nil + context:nil]; } + (void)log:(RollbarLevel)level message:(NSString *)message data:(NSDictionary *)data { - [logger log:level - message:message - data:data - context:nil]; + [[RollbarInfrastructure sharedInstance].logger log:level + message:message + data:data + context:nil]; } + (void)log:(RollbarLevel)level exception:(NSException *)exception data:(NSDictionary *)data { - [logger log:level - exception:exception - data:data - context:nil]; + [[RollbarInfrastructure sharedInstance].logger log:level + exception:exception + data:data + context:nil]; } + (void)log:(RollbarLevel)level error:(NSError *)error data:(NSDictionary *)data { - [logger log:level - error:error - data:data - context:nil]; + [[RollbarInfrastructure sharedInstance].logger log:level + error:error + data:data + context:nil]; } + (void)log:(RollbarLevel)level @@ -230,10 +218,10 @@ + (void)log:(RollbarLevel)level data:(NSDictionary *)data context:(NSString *)context { - [logger log:level - message:message - data:data - context:context]; + [[RollbarInfrastructure sharedInstance].logger log:level + message:message + data:data + context:context]; } + (void)log:(RollbarLevel)level @@ -241,10 +229,10 @@ + (void)log:(RollbarLevel)level data:(NSDictionary *)data context:(NSString *)context { - [logger log:level - exception:exception - data:data - context:context]; + [[RollbarInfrastructure sharedInstance].logger log:level + exception:exception + data:data + context:context]; } + (void)log:(RollbarLevel)level @@ -252,10 +240,10 @@ + (void)log:(RollbarLevel)level data:(NSDictionary *)data context:(NSString *)context { - [logger log:level - error:error - data:data - context:context]; + [[RollbarInfrastructure sharedInstance].logger log:level + error:error + data:data + context:context]; } #pragma mark - Convenience logging methods @@ -497,12 +485,14 @@ + (void)criticalError:(NSError *)error data:(NSDictionary *)data + (void)sendJsonPayload:(NSData *)payload { [[RollbarThread sharedInstance] sendPayload:payload - usingConfig:[Rollbar currentConfiguration] + usingConfig:[Rollbar configuration] ]; } + #pragma mark - Telemetry API + #pragma mark - Dom + (void)recordViewEventForLevel:(RollbarLevel)level diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index fade0533..932ccb6c 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -6,6 +6,7 @@ #import "RollbarNotifierFiles.h" #import "RollbarCrashProcessor.h" #import "RollbarSession.h" +#import "RollbarTelemetry.h" //#import "RollbarLoggerRegistry.h" @implementation RollbarInfrastructure { @@ -84,7 +85,9 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config [[RollbarSession sharedInstance] enableOomMonitoring:config.loggingOptions.enableOomDetection withCrashCheck:crashReportCheck]; - + + [[RollbarTelemetry sharedInstance] configureWithOptions:config.telemetry]; + RollbarSdkLog(@"%@ is configured with this RollbarConfig instance: \n%@ \nand crash collector %@", [RollbarInfrastructure rollbar_objectClassName], config, diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h index 38f4a74a..00e7132e 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h @@ -48,22 +48,30 @@ static void uncaughtExceptionHandler(NSException * _Nonnull exception); + (void)initWithConfiguration:(nonnull RollbarConfig *)configuration crashCollector:(nullable id)crashCollector; -#pragma mark - Shared/global notifier - -/// The shared singleton logger. -+ (nonnull RollbarLogger *)currentLogger; - #pragma mark - Configuration /// The shared Rollbar master configuration. -+ (nullable RollbarMutableConfig *)currentConfiguration; ++ (nullable RollbarConfig *)configuration; /// Updates with a shared configuration. /// @param configuration a new Rollbar configuration + (void)updateConfiguration:(nonnull RollbarConfig *)configuration; -/// Forces fundamental configuration update -+ (void)reapplyConfiguration; + +// TODO: remove this method... +//+ (nullable RollbarMutableConfig *)currentConfiguration; + + +// TODO: remove this method... +//+ (void)reapplyConfiguration; + +#pragma mark - Shared/global notifier + +// TODO: remove this method... +//+ (nonnull RollbarLogger *)currentLogger; + + + #pragma mark - Logging methods From dc491c602d9cd1a46869b286cfe4d3657b38b5e6 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 19 Jul 2022 18:11:13 -0700 Subject: [PATCH 062/127] test: fixed build issues of the RollbarNotifier unit tests --- .../Sources/RollbarNotifier/include/Rollbar.h | 2 +- .../RollbarNotifier/include/RollbarConfig.h | 10 ++ .../PayloadTruncationTests.m | 9 +- .../RollbarConfigurationTests.m | 88 ++++++++++------- .../RollbarTelemetryTests.m | 38 +++---- .../RollbarNotifierTests-ObjC/RollbarTests.m | 63 +++++++----- .../RollbarNotifierConfigurationTests.swift | 98 +++++++++++-------- .../RollbarNotifierLoggerTests.swift | 80 ++++++++------- .../RollbarNotifierTelemetryTests.swift | 32 +++--- .../RollbarNotifierTruncationTests.swift | 9 +- 10 files changed, 247 insertions(+), 182 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h index 00e7132e..1977c1b8 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h @@ -51,7 +51,7 @@ static void uncaughtExceptionHandler(NSException * _Nonnull exception); #pragma mark - Configuration /// The shared Rollbar master configuration. -+ (nullable RollbarConfig *)configuration; ++ (nonnull RollbarConfig *)configuration; /// Updates with a shared configuration. /// @param configuration a new Rollbar configuration diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h index bd20c1c3..366805b8 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h @@ -18,6 +18,8 @@ NS_ASSUME_NONNULL_BEGIN +@class RollbarMutableConfig; + /// Immutable Rollbar configuration structured model @interface RollbarConfig : RollbarDTO { @@ -77,6 +79,10 @@ NS_ASSUME_NONNULL_BEGIN /// Modifies payload data before sending @property (nullable, atomic, readonly, copy) RollbarData *(^modifyRollbarData)(RollbarData *rollbarData); +#pragma mark - overrides + +- (nonnull RollbarMutableConfig *) mutableCopy; + @end @@ -159,6 +165,10 @@ NS_DESIGNATED_INITIALIZER; - (void)setNotifierName:(nullable NSString *)name version:(nullable NSString *)version; +#pragma mark - overrides + +- (nonnull RollbarConfig *) copy; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m index 735c9abc..9a0eaa7c 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m @@ -18,9 +18,12 @@ - (void)setUp { [RollbarLogger clearSdkDataStore]; - if (!Rollbar.currentConfiguration) { - [Rollbar initWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken]]; - Rollbar.currentConfiguration.destination.environment = [RollbarTestHelper getRollbarEnvironment]; + if (![Rollbar configuration]) { + RollbarMutableConfig *config = + [RollbarMutableConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; + + [Rollbar initWithConfiguration:config]; } } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index a94d97c0..e382a9ad 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -18,7 +18,7 @@ - (void)setUp { [RollbarLogger clearSdkDataStore]; - if (!Rollbar.currentConfiguration) { + if (!Rollbar.configuration) { [Rollbar initWithAccessToken:@""]; } } @@ -55,10 +55,12 @@ - (void)testScrubSafeListFields { NSString *scrubedContent = @"*****"; NSArray *keys = @[@"client.ios.app_name", @"client.ios.os_version", @"body.message.body"]; + RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; // define scrub fields: for (NSString *key in keys) { - [Rollbar.currentConfiguration.dataScrubber addScrubField:key]; + [config.dataScrubber addScrubField:key]; } + [Rollbar updateConfiguration:config]; [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; @@ -79,8 +81,9 @@ - (void)testScrubSafeListFields { // define scrub whitelist fields (the same as the scrub fields - to counterbalance them): for (NSString *key in keys) { - [Rollbar.currentConfiguration.dataScrubber addScrubSafeListField:key]; + [config.dataScrubber addScrubSafeListField:key]; } + [Rollbar updateConfiguration:config]; [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; @@ -103,8 +106,9 @@ - (void)testTelemetryEnabled { [RollbarLogger clearSdkDataStore]; BOOL expectedFlag = NO; - Rollbar.currentConfiguration.telemetry.enabled = expectedFlag; - [Rollbar reapplyConfiguration]; + RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; + config.telemetry.enabled = expectedFlag; + [Rollbar updateConfiguration:config]; XCTAssertTrue(RollbarTelemetry.sharedInstance.enabled == expectedFlag, @"RollbarTelemetry.sharedInstance.enabled is expected to be NO." @@ -115,7 +119,7 @@ - (void)testTelemetryEnabled { [Rollbar recordErrorEventForLevel:RollbarLevel_Debug message:@"test"]; } - Rollbar.currentConfiguration.loggingOptions.maximumReportsPerMinute = max; + config.loggingOptions.maximumReportsPerMinute = max; NSArray *telemetryCollection = [[RollbarTelemetry sharedInstance] getAllData]; XCTAssertTrue(telemetryCollection.count == 0, @"Telemetry count is expected to be %i. Actual is %lu", @@ -124,8 +128,8 @@ - (void)testTelemetryEnabled { ); expectedFlag = YES; - Rollbar.currentConfiguration.telemetry.enabled = expectedFlag; - [Rollbar reapplyConfiguration]; + config.telemetry.enabled = expectedFlag; + [Rollbar updateConfiguration:config]; XCTAssertTrue(RollbarTelemetry.sharedInstance.enabled == expectedFlag, @"RollbarTelemetry.sharedInstance.enabled is expected to be YES." @@ -133,7 +137,7 @@ - (void)testTelemetryEnabled { for (int i=0; i Date: Wed, 20 Jul 2022 15:28:14 -0700 Subject: [PATCH 063/127] test: correcting failing unit tests --- .../RollbarNotifier/DTOs/RollbarConfig.m | 42 ++++++++++++++++++- .../RollbarNotifier/include/RollbarConfig.h | 10 ++++- .../include/RollbarTelemetryOptions.h | 4 +- .../PayloadTruncationTests.m | 32 +++++++------- .../RollbarConfigurationTests.m | 23 ++++++++-- .../RollbarInfrastructureTests.m | 9 ++-- .../RollbarRegistryTests.m | 2 +- .../RollbarTelemetryTests.m | 4 +- .../RollbarNotifierTests-ObjC/RollbarTests.m | 27 ++++++------ .../XCTestCase+RollbarNotifierTest.h | 4 +- .../XCTestCase+RollbarNotifierTest.m | 8 ++-- .../RollbarNotifierLoggerTests.swift | 6 ++- .../RollbarNotifierTelemetryTests.swift | 6 ++- .../RollbarNotifierTruncationTests.swift | 6 ++- 14 files changed, 126 insertions(+), 57 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m index f638a5ea..e144c0e9 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m @@ -54,7 +54,7 @@ @implementation RollbarConfig #pragma mark - factory methods -+ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token { ++ (nonnull RollbarConfig *)configWithAccessToken:(nonnull NSString *)token { NSAssert(token, @"Access token must be initialized!"); NSAssert(token.length > 0, @"Access token must not be empty string!"); @@ -65,7 +65,8 @@ + (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token { return config; } -+ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token environment:(nonnull NSString *)env { ++ (nonnull RollbarConfig *)configWithAccessToken:(nonnull NSString *)token + environment:(nonnull NSString *)env { NSAssert(env, @"Environment must be initialized!"); NSAssert(env.length > 0, @"Environment must not be empty string!"); @@ -76,6 +77,29 @@ + (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token environm return config; } ++ (nonnull RollbarMutableConfig *)mutableConfigWithAccessToken:(nonnull NSString *)token { + + NSAssert(token, @"Access token must be initialized!"); + NSAssert(token.length > 0, @"Access token must not be empty string!"); + + RollbarMutableConfig *config = [[RollbarMutableConfig alloc] initWithAccessToken:token + environment:nil]; + + return config; +} + ++ (nonnull RollbarMutableConfig *)mutableConfigWithAccessToken:(nonnull NSString *)token + environment:(nonnull NSString *)env { + + NSAssert(env, @"Environment must be initialized!"); + NSAssert(env.length > 0, @"Environment must not be empty string!"); + + RollbarMutableConfig *config = [[RollbarMutableConfig alloc] initWithAccessToken:token + environment:env]; + + return config; +} + #pragma mark - initializers @@ -218,6 +242,12 @@ - (RollbarTelemetryOptions *)telemetry { @synthesize modifyRollbarData = _modifyRollbarData; +#pragma mark - overrides + +- (nonnull RollbarMutableConfig *) mutableCopy { + + return [self mutableCopyWithZone:nil]; +} //#pragma mark - RollbarPersistent protocol // @@ -402,4 +432,12 @@ - (void)setCustomData:(NSMutableDictionary *)value { [self setDictionary:value forKey:DFK_CUSTOM]; } +#pragma mark - overrides + +- (nonnull RollbarConfig *) copy { + + return [self copyWithZone:nil]; +} + + @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h index 366805b8..23b864c6 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h @@ -32,9 +32,15 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - Factory Methods -+ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token; ++ (nonnull RollbarConfig *)configWithAccessToken:(nonnull NSString *)token; -+ (nonnull instancetype)configWithAccessToken:(nonnull NSString *)token environment:(nonnull NSString *)env; ++ (nonnull RollbarConfig *)configWithAccessToken:(nonnull NSString *)token + environment:(nonnull NSString *)env; + ++ (nonnull RollbarMutableConfig *)mutableConfigWithAccessToken:(nonnull NSString *)token; + ++ (nonnull RollbarMutableConfig *)mutableConfigWithAccessToken:(nonnull NSString *)token + environment:(nonnull NSString *)env; #pragma mark - properties /// Destination related settings diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetryOptions.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetryOptions.h index dbdeab5c..edc866b8 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetryOptions.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarTelemetryOptions.h @@ -53,7 +53,7 @@ NS_ASSUME_NONNULL_BEGIN /// Time interval for auto-collecting memtory stats /// @note 0.0 means no collection! -@property (atomic, readonly) NSTimeInterval memoryStatsAutocollectionInterval; //[sec] +@property (nonatomic, readonly) NSTimeInterval memoryStatsAutocollectionInterval; //[sec] @end @@ -84,7 +84,7 @@ NS_DESIGNATED_INITIALIZER; /// Time interval for auto-collecting memtory stats /// @note 0.0 means no collection! -@property (atomic, readwrite) NSTimeInterval memoryStatsAutocollectionInterval; //[sec] +@property (nonatomic, readwrite) NSTimeInterval memoryStatsAutocollectionInterval; //[sec] @end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m index 9a0eaa7c..87e2e212 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m @@ -18,13 +18,15 @@ - (void)setUp { [RollbarLogger clearSdkDataStore]; - if (![Rollbar configuration]) { - RollbarMutableConfig *config = - [RollbarMutableConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment]]; + RollbarMutableConfig *config = + [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; + + [Rollbar initWithConfiguration:config]; - [Rollbar initWithConfiguration:config]; - } + [NSThread sleepForTimeInterval:5.0f]; + NSArray *items = [RollbarLogger readLogItemsFromStore]; + XCTAssertEqual(items.count, 0); } - (void)tearDown { @@ -184,6 +186,10 @@ - (void)testVisuallyTruncateStringToTotalBytesUnicode { - (void)testPayloadTruncation { + //[NSThread sleepForTimeInterval:5.0f]; + NSArray *items = [RollbarLogger readLogItemsFromStore]; + XCTAssertEqual(items.count, 0); + @try { NSArray *crew = [NSArray arrayWithObjects: @"Dave", @@ -198,7 +204,7 @@ - (void)testPayloadTruncation { [RollbarLogger flushRollbarThread]; - NSArray *items = [RollbarLogger readLogItemsFromStore]; + items = [RollbarLogger readLogItemsFromStore]; for (id payload in items) { NSMutableArray *frames = [payload mutableArrayValueForKeyPath:@"body.trace.frames"]; @@ -242,14 +248,12 @@ - (void)testErrorReportingWithTruncation { [Rollbar criticalMessage:simulatedLongString data:@{@"extra_truncatable_data": simulatedLongString} ]; + NSArray *items = [RollbarLogger readLogItemsFromStore]; + XCTAssertTrue(items.count > 0); - [NSThread sleepForTimeInterval:1.0f]; - - // What is this doing? -// [Rollbar.currentNotifier updateReportingRate:10]; -// [Rollbar.currentNotifier updateReportingRate:60]; -// [Rollbar.currentNotifier updateReportingRate:20]; -// [Rollbar.currentNotifier updateReportingRate:60]; + [NSThread sleepForTimeInterval:5.0f]; + items = [RollbarLogger readLogItemsFromStore]; + XCTAssertEqual(items.count, 0); } } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index e382a9ad..a2785bb2 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -16,11 +16,28 @@ - (void)setUp { [super setUp]; +// [RollbarLogger clearSdkDataStore]; +// +// if (!Rollbar.configuration) { +// [Rollbar initWithAccessToken:@""]; +// } + + + + [RollbarLogger clearSdkDataStore]; - if (!Rollbar.configuration) { - [Rollbar initWithAccessToken:@""]; - } + RollbarMutableConfig *config = + [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; + //config.telemetry.memoryStatsAutocollectionInterval = 0.0; + + [Rollbar initWithConfiguration:config]; + + //[NSThread sleepForTimeInterval:10.0f]; + NSArray *items = [RollbarLogger readLogItemsFromStore]; + XCTAssertEqual(items.count, 0); + } - (void)tearDown { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index 02c0fe70..0a2e2e54 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -54,8 +54,9 @@ - (void)testBasics { XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - RollbarMutableConfig *config = [RollbarMutableConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment] + RollbarMutableConfig *config = + [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment] ]; config.developerOptions.transmit = NO; config.developerOptions.logPayload = YES; @@ -97,8 +98,8 @@ - (void)testLive { XCTAssertEqual(0, items.count); RollbarMutableConfig *config = - [RollbarMutableConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment]]; + [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; config.developerOptions.transmit = YES; config.developerOptions.logPayload = YES; [[RollbarInfrastructure sharedInstance] configureWith:config]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m index 79e9446c..b1da9799 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarRegistryTests.m @@ -35,7 +35,7 @@ - (void)testDestinationRecord { RollbarRegistry *registry = [RollbarRegistry new]; XCTAssertEqual(0, registry.totalDestinationRecords); - RollbarConfig *config = [RollbarConfig configWithAccessToken:@"AT1" + RollbarConfig *config = [RollbarConfig mutableConfigWithAccessToken:@"AT1" environment:@"Env1"]; RollbarDestinationRecord *record = [registry getRecordForConfig:config]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m index ce00d7f1..fe74b079 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m @@ -19,8 +19,8 @@ - (void)setUp { [RollbarLogger clearSdkDataStore]; RollbarMutableConfig *config = - [RollbarMutableConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment]]; + [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; [Rollbar updateConfiguration:config]; } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m index 93d7b9b9..218244e7 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m @@ -18,21 +18,18 @@ - (void)setUp { [RollbarLogger clearSdkDataStore]; - if (!Rollbar.configuration) { - - RollbarMutableConfig *config = [[RollbarMutableConfig alloc] init]; - config.destination.accessToken = [RollbarTestHelper getRollbarPayloadsAccessToken]; - config.destination.environment = [RollbarTestHelper getRollbarEnvironment]; - config.developerOptions.transmit = YES; - config.developerOptions.logPayload = YES; - config.loggingOptions.maximumReportsPerMinute = 5000; - // for the stress test specifically: - config.telemetry.enabled = YES; - config.loggingOptions.captureIp = RollbarCaptureIpType_Full; - NSLog(@"%@", config) - - [Rollbar initWithConfiguration:config]; - } + RollbarMutableConfig *config = [[RollbarMutableConfig alloc] init]; + config.destination.accessToken = [RollbarTestHelper getRollbarPayloadsAccessToken]; + config.destination.environment = [RollbarTestHelper getRollbarEnvironment]; + config.developerOptions.transmit = YES; + config.developerOptions.logPayload = YES; + config.loggingOptions.maximumReportsPerMinute = 5000; + // for the stress test specifically: + config.telemetry.enabled = YES; + config.loggingOptions.captureIp = RollbarCaptureIpType_Full; + NSLog(@"%@", config) + + [Rollbar initWithConfiguration:config]; } - (void)tearDown { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h index 1e597137..bfb1d506 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.h @@ -7,7 +7,7 @@ #import -@class RollbarConfig; +@class RollbarMutableConfig; @class RollbarPayloadFactory; @class RollbarPayload; @@ -17,7 +17,7 @@ NS_ASSUME_NONNULL_BEGIN - (nonnull RollbarPayloadFactory *)getPayloadFactory_Live_Default; -- (nonnull RollbarConfig*) getConfig_Live_Default; +- (nonnull RollbarMutableConfig*) getConfig_Live_Default; - (nonnull NSString *)getCrashReportMock; - (nonnull NSString *)getMessageMock; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m index 0b42fa04..703b434a 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/XCTestCase+RollbarNotifierTest.m @@ -21,11 +21,11 @@ - (nonnull RollbarPayloadFactory *)getPayloadFactory_Live_Default { return factory; } -- (nonnull RollbarConfig*) getConfig_Live_Default { +- (nonnull RollbarMutableConfig*) getConfig_Live_Default { - RollbarConfig *config = - [RollbarConfig configWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment]]; + RollbarMutableConfig *config = + [RollbarConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; return config; } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift index 1834f248..c0022454 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift @@ -15,8 +15,10 @@ final class RollbarNotifierLoggerTests: XCTestCase { RollbarTestUtil.clearTelemetryFile(); RollbarTestUtil.waitForPesistenceToComplete(); - let config = RollbarMutableConfig(accessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), - environment: RollbarTestHelper.getRollbarEnvironment()); + let config = RollbarMutableConfig.mutableConfig( + withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), + environment: RollbarTestHelper.getRollbarEnvironment() + ); config.developerOptions.transmit = true; config.developerOptions.logPayload = true; config.loggingOptions.maximumReportsPerMinute = 5000; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift index 686995aa..adee9e4a 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift @@ -13,8 +13,10 @@ final class RollbarNotifierTelemetryTests: XCTestCase { RollbarTestUtil.clearLogFile(); RollbarTestUtil.clearTelemetryFile(); - let config = RollbarMutableConfig(accessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), - environment: RollbarTestHelper.getRollbarEnvironment()); + let config = RollbarConfig.mutableConfig( + withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), + environment: RollbarTestHelper.getRollbarEnvironment() + ); Rollbar.updateConfiguration(config); } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift index 46da6c24..47b77f90 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift @@ -14,8 +14,10 @@ final class RollbarNotifierTruncationTests: XCTestCase { RollbarTestUtil.clearLogFile(); RollbarTestUtil.clearTelemetryFile(); - let config = RollbarMutableConfig(accessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), - environment: RollbarTestHelper.getRollbarEnvironment()); + let config = RollbarConfig.mutableConfig( + withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), + environment: RollbarTestHelper.getRollbarEnvironment() + ); Rollbar.updateConfiguration(config); } From 80b80dce3c29697faebb01a29917b06973e54594 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 20 Jul 2022 18:51:20 -0700 Subject: [PATCH 064/127] test: fixing failing tests --- .../RollbarInfrastructureTests.m | 44 ++++++++++--------- .../RollbarPayloadPostReplyTests.m | 2 +- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index 0a2e2e54..55984a19 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -17,7 +17,7 @@ - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. } -- (void)testRollbarInfrastructureNotConfiguredException { +- (void)test1_RollbarInfrastructureNotConfiguredException { // XCTAssertThrowsSpecificNamed([RollbarInfrastructure sharedInstance].configuration, // NSException, @@ -44,7 +44,7 @@ - (void)testRollbarInfrastructureNotConfiguredException { ); } -- (void)testBasics { +- (void)test2_Basics { [RollbarLogger clearSdkDataStore]; NSArray *items = [RollbarLogger readLogItemsFromStore]; @@ -62,21 +62,23 @@ - (void)testBasics { config.developerOptions.logPayload = YES; config.loggingOptions.maximumReportsPerMinute = 180; [[RollbarInfrastructure sharedInstance] configureWith:config]; + + [NSThread sleepForTimeInterval:1.0f]; + items = [RollbarLogger readPayloadsFromSdkLog]; + XCTAssertNotNil(items); + int expectedCount = items.count; + [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical message:@"RollbarInfrastructure basics test!" data:nil context:nil ]; - - [NSThread sleepForTimeInterval:0.30f]; - -// items = [RollbarLogger readLogItemsFromStore]; -// XCTAssertNotNil(items); -// XCTAssertEqual(0, items.count); + [NSThread sleepForTimeInterval:1.0f]; + expectedCount++; items = [RollbarLogger readPayloadsFromSdkLog]; XCTAssertNotNil(items); - XCTAssertEqual(1, items.count); + XCTAssertEqual(expectedCount, items.count); [RollbarLogger clearSdkDataStore]; items = [RollbarLogger readLogItemsFromStore]; @@ -87,7 +89,7 @@ - (void)testBasics { XCTAssertEqual(0, items.count); } -- (void)testLive { +- (void)test3_Live { [RollbarLogger clearSdkDataStore]; NSArray *items = [RollbarLogger readLogItemsFromStore]; @@ -103,24 +105,24 @@ - (void)testLive { config.developerOptions.transmit = YES; config.developerOptions.logPayload = YES; [[RollbarInfrastructure sharedInstance] configureWith:config]; + + + [NSThread sleepForTimeInterval:3.0f]; + items = [RollbarLogger readPayloadsFromSdkLog]; + XCTAssertNotNil(items); + int expectedCount = items.count; + [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical message:@"RollbarInfrastructure basics test!" data:nil context:nil ]; - - -// id logger = [RollbarInfrastructure newLogger]; -// [logger log:RollbarLevel_Critical message:@"From Logger!" data:nil context:nil]; - - [NSThread sleepForTimeInterval:5.0f]; - - // items = [RollbarLogger readLogItemsFromStore]; - // XCTAssertNotNil(items); - // XCTAssertEqual(0, items.count); + + [NSThread sleepForTimeInterval:1.0f]; + expectedCount++; items = [RollbarLogger readPayloadsFromSdkLog]; XCTAssertNotNil(items); - XCTAssertEqual(1, items.count); + XCTAssertEqual(expectedCount, items.count); [RollbarLogger clearSdkDataStore]; items = [RollbarLogger readLogItemsFromStore]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m index f7e495a5..c8eb05ca 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadPostReplyTests.m @@ -55,7 +55,7 @@ - (void)testRedReply { RollbarPayloadPostReply *reply = [RollbarPayloadPostReply redReply]; NSDate *now = [NSDate date]; XCTAssertEqual([now earlierDate:reply.nextPostTime], now); - XCTAssertTrue([reply.nextPostTime timeIntervalSinceDate:now] <= 1); + XCTAssertTrue([reply.nextPostTime timeIntervalSinceDate:now] <= reply.remainingSeconds); } - (void)testPerformanceExample { From 823542d5aeb7c9dc9ad21e5d020a9d021a6cd423 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 20 Jul 2022 19:27:51 -0700 Subject: [PATCH 065/127] test: fixing failing tests --- .../RollbarCommon/NSJSONSerialization+Rollbar.m | 2 +- .../RollbarConfigurationTests.m | 17 +++++------------ 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m index 45c74770..02d48e72 100644 --- a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m +++ b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m @@ -57,7 +57,7 @@ + (nonnull NSMutableDictionary *)rollbar_safeDataFromJSONObject:(nullable id)obj } else if ([obj isKindOfClass:[NSArray class]]) { [safeData setObject:((NSArray *)obj).mutableCopy forKey:key]; - } else if ([NSJSONSerialization isValidJSONObject:@{key:obj}]) { + } else if ([NSJSONSerialization isValidJSONObject:obj]) { [safeData setObject:obj forKey:key]; } else if ([obj isKindOfClass:[NSNumber class]]) { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index a2785bb2..d2898f93 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -16,25 +16,15 @@ - (void)setUp { [super setUp]; -// [RollbarLogger clearSdkDataStore]; -// -// if (!Rollbar.configuration) { -// [Rollbar initWithAccessToken:@""]; -// } - - - - [RollbarLogger clearSdkDataStore]; RollbarMutableConfig *config = [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] environment:[RollbarTestHelper getRollbarEnvironment]]; - //config.telemetry.memoryStatsAutocollectionInterval = 0.0; - [Rollbar initWithConfiguration:config]; - //[NSThread sleepForTimeInterval:10.0f]; + [NSThread sleepForTimeInterval:1.0f]; + [RollbarLogger clearSdkDataStore]; NSArray *items = [RollbarLogger readLogItemsFromStore]; XCTAssertEqual(items.count, 0); @@ -425,6 +415,9 @@ - (void)testLogTelemetryAutoCapture { config.telemetry.enabled = YES; config.telemetry.captureLog = YES; [Rollbar updateConfiguration:config]; + [RollbarLogger flushRollbarThread]; + [RollbarLogger clearSdkDataStore]; + // The following line ensures the captureLogAsTelemetryData setting is flushed through the internal queue [[RollbarTelemetry sharedInstance] getAllData]; NSLog(logMsg); From c9788504bbb655504a26e28ccf484251d344fbc2 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 21 Jul 2022 16:44:45 -0700 Subject: [PATCH 066/127] test: fixing failing unit tests --- .../RollbarNotifier/RollbarInfrastructure.m | 2 ++ .../RollbarNotifier/include/RollbarConfig.h | 16 ++++++++++------ .../RollbarConfigurationTests.m | 3 ++- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index 932ccb6c..c934ba69 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -59,6 +59,8 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config [self assertValidConfiguration:config]; if (self->_configuration + && self->_configuration.modifyRollbarData == config.modifyRollbarData + && self->_configuration.checkIgnoreRollbarData == config.checkIgnoreRollbarData && (NSOrderedSame == [[config serializeToJSONString] compare:[self->_configuration serializeToJSONString]]) ) { return self; // no need to reconfigure with an identical configuration... diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h index 23b864c6..e0bd1470 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarConfig.h @@ -20,11 +20,15 @@ NS_ASSUME_NONNULL_BEGIN @class RollbarMutableConfig; +typedef BOOL (^RollbarCheckIgnoreData)(RollbarData *rollbarData); +typedef RollbarData *_Nonnull(^RollbarModifyData)(RollbarData *rollbarData); + + /// Immutable Rollbar configuration structured model @interface RollbarConfig : RollbarDTO { - BOOL (^_checkIgnoreRollbarData)(RollbarData *rollbarData); - RollbarData *(^_modifyRollbarData)(RollbarData *rollbarData); + RollbarCheckIgnoreData _checkIgnoreRollbarData; + RollbarModifyData _modifyRollbarData; //TODO: to be removed: BOOL _isRootConfiguration; @@ -80,10 +84,10 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - Payload Content Related /// Decides whether or not to send provided payload data. Returns true to ignore, false to send -@property (nullable, atomic, readonly, copy) BOOL (^checkIgnoreRollbarData)(RollbarData *rollbarData); +@property (nullable, atomic, readonly, copy) RollbarCheckIgnoreData checkIgnoreRollbarData; /// Modifies payload data before sending -@property (nullable, atomic, readonly, copy) RollbarData *(^modifyRollbarData)(RollbarData *rollbarData); +@property (nullable, atomic, readonly, copy) RollbarModifyData modifyRollbarData; #pragma mark - overrides @@ -139,10 +143,10 @@ NS_DESIGNATED_INITIALIZER; #pragma mark - Payload Content Related /// Decides whether or not to send provided payload data. Returns true to ignore, false to send -@property (nullable, atomic, readwrite, copy) BOOL (^checkIgnoreRollbarData)(RollbarData *rollbarData); +@property (nullable, atomic, readwrite, copy) RollbarCheckIgnoreData checkIgnoreRollbarData; /// Modifies payload data before sending -@property (nullable, atomic, readwrite, copy) RollbarData *(^modifyRollbarData)(RollbarData *rollbarData); +@property (nullable, atomic, readwrite, copy) RollbarModifyData modifyRollbarData; #pragma mark - Convenience Methods diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index d2898f93..a336fe90 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -4,6 +4,7 @@ #if !TARGET_OS_WATCH #import +@import RollbarCommon; @import RollbarNotifier; @interface RollbarConfigurationTests : XCTestCase @@ -352,7 +353,7 @@ - (void)testPayloadModification { NSString *newMsg = @"Modified message"; RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; - config.modifyRollbarData = ^RollbarData *(RollbarData *payloadData) { + config.modifyRollbarData = ^RollbarData *_Nonnull(RollbarData *payloadData) { // [payloadData setValue:newMsg forKeyPath:@"body.message.body"]; // [payloadData setValue:newMsg forKeyPath:@"body.message.body2"]; payloadData.body.message.body = newMsg; From 48041d82279b47841ecd842d4f0c5cdf8d600275 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 21 Jul 2022 19:20:48 -0700 Subject: [PATCH 067/127] test: fixing failing unut tests --- .../Sources/RollbarCommon/RollbarBundleUtil.m | 3 ++ .../RollbarNotifier/DTOs/RollbarConfig.m | 25 +++++++++ .../RollbarNotifier/RollbarInfrastructure.m | 4 +- .../Sources/RollbarNotifier/RollbarLogger.m | 2 +- .../RollbarConfigurationTests.m | 53 ++++++++----------- .../RollbarNotifierConfigurationTests.swift | 23 ++++---- .../RollbarNotifierTelemetryTests.swift | 4 +- .../Sources/UnitTesting/RollbarTestUtil.swift | 2 +- 8 files changed, 69 insertions(+), 47 deletions(-) diff --git a/RollbarCommon/Sources/RollbarCommon/RollbarBundleUtil.m b/RollbarCommon/Sources/RollbarCommon/RollbarBundleUtil.m index 84a5f920..9b3537ba 100644 --- a/RollbarCommon/Sources/RollbarCommon/RollbarBundleUtil.m +++ b/RollbarCommon/Sources/RollbarCommon/RollbarBundleUtil.m @@ -5,6 +5,9 @@ @implementation RollbarBundleUtil + (nonnull NSString *)detectAppBundleVersion { NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; + if (!infoDictionary) { + return @"n/a"; + } NSString *major = infoDictionary[@"CFBundleShortVersionString"]; NSString *minor = infoDictionary[@"CFBundleVersion"]; NSString *version = [NSString stringWithFormat:@"%@.%@", major, minor]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m index e144c0e9..42205f68 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m @@ -257,6 +257,31 @@ - (nonnull RollbarMutableConfig *) mutableCopy { //- (BOOL)saveToFile:(nonnull NSString *)filePath { //} + +#pragma mark - NSCopying protocol + +-(id) copyWithZone: (NSZone *) zone { + + RollbarConfig *clone = [super copyWithZone:zone]; + if (clone != self) { + clone->_checkIgnoreRollbarData = self->_checkIgnoreRollbarData; + clone->_modifyRollbarData = self->_modifyRollbarData; + } + return clone; +} + +#pragma mark - NSMutableCopying protocol + +-(id) mutableCopyWithZone: (NSZone *) zone { + + RollbarConfig *clone = [super mutableCopyWithZone:zone]; + if (clone != self) { + clone->_checkIgnoreRollbarData = self->_checkIgnoreRollbarData; + clone->_modifyRollbarData = self->_modifyRollbarData; + } + return clone; +} + @end @implementation RollbarMutableConfig diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index c934ba69..445b5546 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -61,12 +61,12 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config if (self->_configuration && self->_configuration.modifyRollbarData == config.modifyRollbarData && self->_configuration.checkIgnoreRollbarData == config.checkIgnoreRollbarData - && (NSOrderedSame == [[config serializeToJSONString] compare:[self->_configuration serializeToJSONString]]) + && [[self->_configuration serializeToJSONString] isEqualToString:[config serializeToJSONString]] ) { return self; // no need to reconfigure with an identical configuration... } - self->_configuration = config; + self->_configuration = [config copy]; self->_logger = nil; //will be created as needed using the current self->_configuration... RollbarCrashReportCheck crashReportCheck = nil; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index 9df62f88..2d3d595d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -185,7 +185,7 @@ - (void)report:(RollbarPayload *)payload { - (void)updateConfiguration:(RollbarConfig *)configuration { - self.configuration = configuration; + self.configuration = [configuration copy]; } //- (void)updateAccessToken:(NSString *)accessToken { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index a336fe90..cbcaaf0c 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -37,6 +37,19 @@ - (void)tearDown { [super tearDown]; } +- (BOOL)rollbarStoreContains:(nonnull NSString *)string { + + [RollbarLogger flushRollbarThread]; + NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + for (NSDictionary *item in logItems) { + RollbarPayload *payload = [[RollbarPayload alloc] initWithDictionary:item]; + if ([[payload serializeToJSONString] containsString:string]) { + return YES; + } + } + return NO; +} + - (void)testConfigCloning { RollbarMutableConfig *rc = [RollbarMutableConfig new]; @@ -227,36 +240,18 @@ - (void)testEnabled { //Rollbar.currentLogger.configuration.developerOptions.enabled = NO; [Rollbar updateConfiguration:config]; [Rollbar debugMessage:@"Test1"]; - [RollbarLogger flushRollbarThread]; - - logItems = [RollbarLogger readLogItemsFromStore]; - XCTAssertTrue(logItems.count == 0, - @"logItems count is expected to be 0. Actual value is %lu", - (unsigned long) logItems.count - ); - + XCTAssertTrue(![self rollbarStoreContains:@"Test1"]); + config.developerOptions.enabled = YES; [Rollbar updateConfiguration:config]; [Rollbar debugMessage:@"Test2"]; - [RollbarLogger flushRollbarThread]; - - logItems = [RollbarLogger readLogItemsFromStore]; - XCTAssertTrue(logItems.count == 1, - @"logItems count is expected to be 1. Actual value is %lu", - (unsigned long) logItems.count - ); + XCTAssertTrue([self rollbarStoreContains:@"Test2"]); config.developerOptions.enabled = NO; [Rollbar updateConfiguration:config]; [Rollbar debugMessage:@"Test3"]; - [RollbarLogger flushRollbarThread]; + XCTAssertTrue(![self rollbarStoreContains:@"Test3"]); - logItems = [RollbarLogger readLogItemsFromStore]; - XCTAssertTrue(logItems.count == 1, - @"logItems count is expected to be 1. Actual value is %lu", - (unsigned long) logItems.count - ); - [RollbarLogger clearSdkDataStore]; } @@ -279,7 +274,7 @@ - (void)testMaximumTelemetryEvents { [RollbarLogger flushRollbarThread]; NSArray *logItems = [RollbarLogger readLogItemsFromStore]; - NSDictionary *item = logItems[0]; + NSDictionary *item = logItems[logItems.count - 1]; NSArray *telemetryData = [item valueForKeyPath:@"body.telemetry"]; XCTAssertTrue(telemetryData.count == max, @"Telemetry item count is %lu, should be %lu", @@ -291,19 +286,15 @@ - (void)testMaximumTelemetryEvents { - (void)testCheckIgnore { [Rollbar debugMessage:@"Don't ignore this"]; - [RollbarLogger flushRollbarThread]; - - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; - XCTAssertTrue(logItems.count == 1, @"Log item count should be 1"); + XCTAssertTrue([self rollbarStoreContains:@"Don't ignore this"]); RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.checkIgnoreRollbarData = ^BOOL(RollbarData *payloadData) { return true; }; [Rollbar updateConfiguration:config]; - [Rollbar debugMessage:@"Ignore this"]; - logItems = [RollbarLogger readLogItemsFromStore]; - XCTAssertTrue(logItems.count == 1, @"Log item count should be 1"); + [Rollbar debugMessage:@"Must ignore this"]; + XCTAssertTrue(![self rollbarStoreContains:@"Must ignore this"]); } - (void)testServerData { @@ -434,8 +425,6 @@ - (void)testLogTelemetryAutoCapture { telemetryMsg, logMsg ); - - //[NSThread sleepForTimeInterval:3.0f]; } @end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift index 3d1f2801..e2abeca5 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift @@ -99,7 +99,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { var logItem:String?; while (nil == logItem) { - logItem = RollbarTestUtil.readFirstItemStringsFromLogFile(); + logItem = RollbarTestUtil.readFirstItemStringFromLogFile(); RollbarTestUtil.waitForPesistenceToComplete(); } let payload = RollbarPayload(jsonString: logItem!); @@ -230,12 +230,14 @@ final class RollbarNotifierConfigurationTests: XCTestCase { let branch = "testBranch"; let codeVersion = "testCodeVersion"; config.setServerHost(host, root: root, branch: branch, codeVersion: codeVersion); + Rollbar .updateConfiguration(config); Rollbar.debugMessage("test"); RollbarTestUtil.waitForPesistenceToComplete(); - let logItem = RollbarTestUtil.readFirstItemStringsFromLogFile()!; + let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let server = payload.data.server!; @@ -270,7 +272,8 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarTestUtil.waitForPesistenceToComplete(); - let logItem = RollbarTestUtil.readFirstItemStringsFromLogFile()!; + let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let msg1 = payload.data.body.message!.body; let msg2 = payload.data.body.message!.getDataByKey("body2") as! String; @@ -301,8 +304,9 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarTestUtil.waitForPesistenceToComplete(); // verify the fields were scrubbed: - var logItem = RollbarTestUtil.readFirstItemStringsFromLogFile(); - var payload = RollbarPayload(jsonString: logItem!); + var logItems = RollbarTestUtil.readItemStringsFromLogFile(); + var logItem = logItems[logItems.count - 1]; + var payload = RollbarPayload(jsonString: logItem); for key in keys { let content = payload.data.jsonFriendlyData.value(forKeyPath: key) as! String; XCTAssertTrue( @@ -321,8 +325,9 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarTestUtil.waitForPesistenceToComplete(); // verify the fields were not scrubbed: - logItem = RollbarTestUtil.readFirstItemStringsFromLogFile(); - payload = RollbarPayload(jsonString: logItem!); + logItems = RollbarTestUtil.readItemStringsFromLogFile(); + logItem = logItems[logItems.count - 1]; + payload = RollbarPayload(jsonString: logItem); for key in keys { let content = payload.data.jsonFriendlyData.value(forKeyPath: key) as! String; XCTAssertTrue( @@ -360,7 +365,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("test"); RollbarTestUtil.waitForPesistenceToComplete(); // verify the fields were scrubbed: - let logItem = RollbarTestUtil.readFirstItemStringsFromLogFile(); + let logItem = RollbarTestUtil.readFirstItemStringFromLogFile(); let payload = RollbarPayload(jsonString: logItem!); XCTAssertTrue( .orderedSame == payload.data.person!.serializeToJSONString()!.compare(expectedPersonJson), @@ -401,7 +406,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("test"); RollbarTestUtil.waitForPesistenceToComplete(); // verify the fields were scrubbed: - let logItem = RollbarTestUtil.readFirstItemStringsFromLogFile(); + let logItem = RollbarTestUtil.readFirstItemStringFromLogFile(); let payload = RollbarPayload(jsonString: logItem!); XCTAssertTrue( .orderedSame == payload.data.person!.serializeToJSONString()!.compare(expectedPersonJson), diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift index adee9e4a..9437fc0f 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift @@ -42,7 +42,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { Rollbar.criticalMessage("Must contain memory telemetry!"); RollbarTestUtil.waitForPesistenceToComplete(); - let logItem = RollbarTestUtil.readFirstItemStringsFromLogFile()!; + let logItem = RollbarTestUtil.readFirstItemStringFromLogFile()!; let payload = RollbarPayload(jsonString: logItem); let telemetryEvents = payload.data.body.telemetry!; XCTAssertTrue(telemetryEvents.count > 0); @@ -125,7 +125,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { RollbarTestUtil.waitForPesistenceToComplete(); - let logItem = RollbarTestUtil.readFirstItemStringsFromLogFile()!; + let logItem = RollbarTestUtil.readFirstItemStringFromLogFile()!; let payload = RollbarPayload(jsonString: logItem); let telemetryEvents = payload.data.body.telemetry!; XCTAssertTrue(telemetryEvents.count > 0); diff --git a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift index 76b47805..70c0326c 100644 --- a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift +++ b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift @@ -66,7 +66,7 @@ import RollbarCommon } } - @objc public static func readFirstItemStringsFromLogFile() -> String? { + @objc public static func readFirstItemStringFromLogFile() -> String? { let filePath = RollbarTestUtil.getQueuedItemsFilePath(); let fileReader = RollbarFileReader(filePath: filePath, andOffset: 0); From a39e2ce53578a3199e828f7a8e3356627c4ae707 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 22 Jul 2022 11:51:02 -0700 Subject: [PATCH 068/127] test: fixing unit tests --- .../NSJSONSerialization+Rollbar.m | 3 ++ .../RollbarNotifierTests-ObjC/RollbarTests.m | 31 ++++++++++--------- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m index 02d48e72..afe58c30 100644 --- a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m +++ b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m @@ -57,6 +57,9 @@ + (nonnull NSMutableDictionary *)rollbar_safeDataFromJSONObject:(nullable id)obj } else if ([obj isKindOfClass:[NSArray class]]) { [safeData setObject:((NSArray *)obj).mutableCopy forKey:key]; + } else if ([obj isKindOfClass:[NSNull class]]) { + + [safeData setObject:obj forKey:key]; } else if ([NSJSONSerialization isValidJSONObject:obj]) { [safeData setObject:obj forKey:key]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m index 218244e7..b28f49a1 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m @@ -74,35 +74,36 @@ - (void)testRollbarNotifiersIndependentConfiguration { [Rollbar updateConfiguration:config]; - XCTAssertEqual([Rollbar configuration].destination.accessToken, - config.destination.accessToken); - XCTAssertEqual([Rollbar configuration].destination.environment, - config.destination.environment); - - XCTAssertEqual([Rollbar configuration].destination.accessToken, - config.destination.accessToken); - XCTAssertEqual([Rollbar configuration].destination.environment, - config.destination.environment); + XCTAssertTrue([[Rollbar configuration].destination.accessToken + isEqualToString:config.destination.accessToken]); + XCTAssertTrue([[Rollbar configuration].destination.environment + isEqualToString:config.destination.environment]); // create and configure another notifier: config = [RollbarMutableConfig new]; config.destination.accessToken = @"AT_1"; config.destination.environment = @"ENV_1"; RollbarLogger *notifier = [[RollbarLogger alloc] initWithConfiguration:config]; - XCTAssertTrue([notifier.configuration.destination.accessToken compare:@"AT_1"] == NSOrderedSame); - XCTAssertTrue([notifier.configuration.destination.environment compare:@"ENV_1"] == NSOrderedSame); + XCTAssertTrue([notifier.configuration.destination.accessToken + isEqualToString:@"AT_1"]); + XCTAssertTrue([notifier.configuration.destination.environment + isEqualToString:@"ENV_1"]); // reconfigure the root notifier: config = [[Rollbar configuration] mutableCopy]; config.destination.accessToken = @"AT_N"; config.destination.environment = @"ENV_N"; [Rollbar updateConfiguration:config]; - XCTAssertTrue([[RollbarInfrastructure sharedInstance].logger.configuration.destination.accessToken compare:@"AT_N"] == NSOrderedSame); - XCTAssertTrue([[RollbarInfrastructure sharedInstance].logger.configuration.destination.environment compare:@"ENV_N"] == NSOrderedSame); + XCTAssertTrue([[RollbarInfrastructure sharedInstance].logger.configuration.destination.accessToken + isEqualToString:@"AT_N"]); + XCTAssertTrue([[RollbarInfrastructure sharedInstance].logger.configuration.destination.environment + isEqualToString:@"ENV_N"]); // make sure the other notifier is still has its original configuration: - XCTAssertTrue([notifier.configuration.destination.accessToken compare:@"AT_1"] == NSOrderedSame); - XCTAssertTrue([notifier.configuration.destination.environment compare:@"ENV_1"] == NSOrderedSame); + XCTAssertTrue([notifier.configuration.destination.accessToken + isEqualToString:@"AT_1"]); + XCTAssertTrue([notifier.configuration.destination.environment + isEqualToString:@"ENV_1"]); //TODO: to make this test even more valuable we need to make sure the other notifier's payloads // are actually sent to its intended destination. But that is something we will be able to do From 496260642087d9b5bc6b673ee9624ae9a4c1aa1a Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 22 Jul 2022 20:37:19 -0700 Subject: [PATCH 069/127] test: fixing unit tests --- .../NSJSONSerialization+Rollbar.m | 2 +- .../PayloadTruncationTests.m | 3 +- .../RollbarInfrastructureTests.m | 55 +++++++++------- .../RollbarTelemetryTests.m | 2 +- .../RollbarNotifierConfigurationTests.swift | 66 +++++++++++-------- .../RollbarNotifierLoggerTests.swift | 9 ++- .../RollbarNotifierTelemetryTests.swift | 17 ++--- 7 files changed, 93 insertions(+), 61 deletions(-) diff --git a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m index afe58c30..542d9b89 100644 --- a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m +++ b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m @@ -57,7 +57,7 @@ + (nonnull NSMutableDictionary *)rollbar_safeDataFromJSONObject:(nullable id)obj } else if ([obj isKindOfClass:[NSArray class]]) { [safeData setObject:((NSArray *)obj).mutableCopy forKey:key]; - } else if ([obj isKindOfClass:[NSNull class]]) { + } else if (obj == [NSNull null] || [obj isKindOfClass:[NSNull class]]) { [safeData setObject:obj forKey:key]; } else if ([NSJSONSerialization isValidJSONObject:obj]) { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m index 87e2e212..fb328dce 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m @@ -24,7 +24,8 @@ - (void)setUp { [Rollbar initWithConfiguration:config]; - [NSThread sleepForTimeInterval:5.0f]; + [RollbarTestUtil waitForPesistenceToCompleteWithWaitTimeInSeconds:3]; + [RollbarLogger clearSdkDataStore]; NSArray *items = [RollbarLogger readLogItemsFromStore]; XCTAssertEqual(items.count, 0); } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index 55984a19..1775c549 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -27,13 +27,15 @@ - (void)test1_RollbarInfrastructureNotConfiguredException { // NSException, // @"RollbarInfrastructureNotConfiguredException", // @"An RollbarInfrastructureNotConfiguredException is expected!"); - XCTAssertThrows([RollbarInfrastructure sharedInstance].configuration, - @"An RollbarInfrastructureNotConfiguredException is expected!" - ); - XCTAssertThrows([RollbarInfrastructure sharedInstance].logger, - @"An RollbarInfrastructureNotConfiguredException is expected!" - ); + +// XCTAssertThrows([RollbarInfrastructure sharedInstance].configuration, +// @"An RollbarInfrastructureNotConfiguredException is expected!" +// ); +// XCTAssertThrows([RollbarInfrastructure sharedInstance].logger, +// @"An RollbarInfrastructureNotConfiguredException is expected!" +// ); + [[RollbarInfrastructure sharedInstance] configureWith:[RollbarConfig new]]; XCTAssertNoThrow([RollbarInfrastructure sharedInstance].configuration, @@ -66,19 +68,23 @@ - (void)test2_Basics { [NSThread sleepForTimeInterval:1.0f]; items = [RollbarLogger readPayloadsFromSdkLog]; XCTAssertNotNil(items); - int expectedCount = items.count; [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical - message:@"RollbarInfrastructure basics test!" + message:@"RollbarInfrastructure basics test 2!" data:nil context:nil ]; - [NSThread sleepForTimeInterval:1.0f]; - expectedCount++; - items = [RollbarLogger readPayloadsFromSdkLog]; - XCTAssertNotNil(items); - XCTAssertEqual(expectedCount, items.count); + [RollbarLogger flushRollbarThread]; + items = [RollbarTestUtil readItemStringsFromLogFile]; + BOOL wasLogged = NO; + for (NSString *item in items) { + if (YES == [item containsString:@"RollbarInfrastructure basics test 2!"]) { + wasLogged = YES; + break; + } + } + XCTAssertTrue(YES == wasLogged); [RollbarLogger clearSdkDataStore]; items = [RollbarLogger readLogItemsFromStore]; @@ -107,22 +113,25 @@ - (void)test3_Live { [[RollbarInfrastructure sharedInstance] configureWith:config]; - [NSThread sleepForTimeInterval:3.0f]; - items = [RollbarLogger readPayloadsFromSdkLog]; + [RollbarLogger flushRollbarThread]; + items = [RollbarTestUtil readItemStringsFromLogFile]; XCTAssertNotNil(items); - int expectedCount = items.count; [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical - message:@"RollbarInfrastructure basics test!" + message:@"RollbarInfrastructure basics test 3!" data:nil context:nil ]; - - [NSThread sleepForTimeInterval:1.0f]; - expectedCount++; - items = [RollbarLogger readPayloadsFromSdkLog]; - XCTAssertNotNil(items); - XCTAssertEqual(expectedCount, items.count); + [RollbarLogger flushRollbarThread]; + items = [RollbarTestUtil readItemStringsFromLogFile]; + BOOL wasLogged = NO; + for (NSString *item in items) { + if (YES == [item containsString:@"RollbarInfrastructure basics test 3!"]) { + wasLogged = YES; + break; + } + } + XCTAssertTrue(YES == wasLogged); [RollbarLogger clearSdkDataStore]; items = [RollbarLogger readLogItemsFromStore]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m index fe74b079..d5b30d2e 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m @@ -46,7 +46,7 @@ - (void)testTelemetryCapture { [RollbarLogger flushRollbarThread]; NSArray *logItems = [RollbarLogger readLogItemsFromStore]; - NSDictionary *item = logItems[0]; + NSDictionary *item = logItems[logItems.count - 1]; NSArray *telemetryData = [item valueForKeyPath:@"body.telemetry"]; XCTAssertTrue(telemetryData.count > 0); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift index e2abeca5..6ad9bde8 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift @@ -96,13 +96,11 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.updateConfiguration(config); Rollbar.debugMessage("Test"); + RollbarLogger .flushRollbarThread(); - var logItem:String?; - while (nil == logItem) { - logItem = RollbarTestUtil.readFirstItemStringFromLogFile(); - RollbarTestUtil.waitForPesistenceToComplete(); - } - let payload = RollbarPayload(jsonString: logItem!); + let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItem = logItems[logItems.count - 1]; + let payload = RollbarPayload(jsonString: logItem); let telemetry = payload.data.body.telemetry!; XCTAssertTrue(telemetry.count == max, "Telemetry item count is \(telemetry.count), should be \(max)" @@ -166,7 +164,9 @@ final class RollbarNotifierConfigurationTests: XCTestCase { func testEnabled() { + RollbarLogger.flushRollbarThread(); RollbarTestUtil.clearLogFile(); + RollbarTestUtil.waitForPesistenceToComplete(waitTimeInSeconds: 5); var logItems = RollbarTestUtil.readItemStringsFromLogFile(); XCTAssertTrue(logItems.count == 0, @@ -176,29 +176,34 @@ final class RollbarNotifierConfigurationTests: XCTestCase { let config = Rollbar.configuration().mutableCopy(); config.developerOptions.enabled = false; - //Rollbar.currentLogger().configuration!.developerOptions.enabled = false; + Rollbar.updateConfiguration(config); + RollbarLogger.flushRollbarThread(); + RollbarTestUtil.clearLogFile(); + Rollbar.debugMessage("Test1"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarLogger.flushRollbarThread(); logItems = RollbarTestUtil.readItemStringsFromLogFile(); XCTAssertTrue(logItems.count == 0, "logItems count is expected to be 0. Actual value is \(logItems.count)" ); config.developerOptions.enabled = true; + Rollbar.updateConfiguration(config); + RollbarLogger.flushRollbarThread(); + Rollbar.debugMessage("Test2"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarLogger.flushRollbarThread(); logItems = RollbarTestUtil.readItemStringsFromLogFile(); - XCTAssertTrue(logItems.count == 1, - "logItems count is expected to be 1. Actual value is \(logItems.count)" - ); + XCTAssertTrue(logItems[logItems.count - 1].contains("Test2")); config.developerOptions.enabled = false; + Rollbar.updateConfiguration(config); + RollbarLogger.flushRollbarThread(); + Rollbar.debugMessage("Test3"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarLogger.flushRollbarThread(); logItems = RollbarTestUtil.readItemStringsFromLogFile(); - XCTAssertTrue(logItems.count == 1, - "logItems count is expected to be 1. Actual value is\(logItems.count)" - ); + XCTAssertTrue(!logItems[logItems.count - 1].contains("Test3")); RollbarTestUtil.clearLogFile(); } @@ -299,10 +304,12 @@ final class RollbarNotifierConfigurationTests: XCTestCase { for key in keys { config.dataScrubber.addScrubField(key); } + Rollbar.updateConfiguration(config); + RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("test"); - RollbarTestUtil.waitForPesistenceToComplete(); - + RollbarLogger.flushRollbarThread(); + // verify the fields were scrubbed: var logItems = RollbarTestUtil.readItemStringsFromLogFile(); var logItem = logItems[logItems.count - 1]; @@ -320,9 +327,11 @@ final class RollbarNotifierConfigurationTests: XCTestCase { for key in keys { config.dataScrubber.addScrubSafeListField(key); } + Rollbar.updateConfiguration(config); + RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("test"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarLogger.flushRollbarThread(); // verify the fields were not scrubbed: logItems = RollbarTestUtil.readItemStringsFromLogFile(); @@ -335,6 +344,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { "\(key) is \(content), should not be \(scrubedContent)" ); } + RollbarTestUtil.clearLogFile(); } @@ -361,12 +371,14 @@ final class RollbarNotifierConfigurationTests: XCTestCase { .orderedSame == personJson!.compare(expectedPersonJson), "Properly serialized person attributes." ); + Rollbar.updateConfiguration(config); + RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("test"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarLogger.flushRollbarThread(); // verify the fields were scrubbed: - let logItem = RollbarTestUtil.readFirstItemStringFromLogFile(); - let payload = RollbarPayload(jsonString: logItem!); + let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let payload = RollbarPayload(jsonString: logItems[logItems.count - 1]); XCTAssertTrue( .orderedSame == payload.data.person!.serializeToJSONString()!.compare(expectedPersonJson), "Properly serialized person in payload." @@ -402,12 +414,14 @@ final class RollbarNotifierConfigurationTests: XCTestCase { .orderedSame == personJson!.compare(expectedPersonJson), "Properly serialized person attributes." ); - + Rollbar.updateConfiguration(config); + RollbarLogger.flushRollbarThread(); + Rollbar.debugMessage("test"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarLogger.flushRollbarThread(); // verify the fields were scrubbed: - let logItem = RollbarTestUtil.readFirstItemStringFromLogFile(); - let payload = RollbarPayload(jsonString: logItem!); + let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let payload = RollbarPayload(jsonString: logItems[logItems.count - 1]); XCTAssertTrue( .orderedSame == payload.data.person!.serializeToJSONString()!.compare(expectedPersonJson), "Properly serialized person in payload." diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift index c0022454..ad6c3a30 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift @@ -148,16 +148,23 @@ final class RollbarNotifierLoggerTests: XCTestCase { } } - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarLogger.flushRollbarThread(); let items = RollbarTestUtil.readItemStringsFromLogFile(); + XCTAssertTrue(items.count >= notificationText.count); + var count:Int = 0; for item in items { + if (!item.contains("testing-")) { + continue; + } let payload = RollbarPayload(jsonString: item); let level = payload.data.level; let message: String? = payload.data.body.message?.body; let params = notificationText[RollbarLevelUtil.rollbarLevel(toString: level)]!; XCTAssertTrue(message!.compare(params[0] as String) == .orderedSame, "Expects '\(params[0])', got '\(message ?? "")'."); + count += 1; } + XCTAssertEqual(count, notificationText.count); } func testNSErrorReporting() { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift index 9437fc0f..2316b016 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift @@ -40,9 +40,10 @@ final class RollbarNotifierTelemetryTests: XCTestCase { Thread.sleep(forTimeInterval: 5.0); Rollbar.criticalMessage("Must contain memory telemetry!"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarLogger.flushRollbarThread(); - let logItem = RollbarTestUtil.readFirstItemStringFromLogFile()!; + let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let telemetryEvents = payload.data.body.telemetry!; XCTAssertTrue(telemetryEvents.count > 0); @@ -89,7 +90,8 @@ final class RollbarNotifierTelemetryTests: XCTestCase { let config = Rollbar.configuration().mutableCopy(); config.telemetry.enabled = true; Rollbar.updateConfiguration(config); - + RollbarLogger.flushRollbarThread(); + Rollbar.recordNavigationEvent( for: .info, from: "from", @@ -119,13 +121,12 @@ final class RollbarNotifierTelemetryTests: XCTestCase { withData: ["data" : "content"] ); - //RollbarTestUtil.waitForPesistenceToComplete(); - + RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("Test"); + RollbarLogger.flushRollbarThread(); - RollbarTestUtil.waitForPesistenceToComplete(); - - let logItem = RollbarTestUtil.readFirstItemStringFromLogFile()!; + let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let telemetryEvents = payload.data.body.telemetry!; XCTAssertTrue(telemetryEvents.count > 0); From db7a473efb3fb1c51ba88d80874867f4d4cb1c89 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 25 Jul 2022 16:48:49 -0700 Subject: [PATCH 070/127] refactor: Rollbar facade test: fixing unit tests --- .../Sources/RollbarNotifier/Rollbar.m | 2 +- .../Sources/RollbarNotifier/include/Rollbar.h | 114 ++++++++++++------ .../PayloadTruncationTests.m | 2 +- .../RollbarConfigurationTests.m | 38 +++--- .../RollbarTelemetryTests.m | 12 +- .../RollbarNotifierTests-ObjC/RollbarTests.m | 12 +- .../RollbarNotifierConfigurationTests.swift | 40 +++--- .../RollbarNotifierLoggerTests.swift | 14 +-- .../RollbarNotifierTelemetryTests.swift | 14 +-- .../RollbarNotifierTruncationTests.swift | 4 +- 10 files changed, 147 insertions(+), 105 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m index 1434784d..6b57204a 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m +++ b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m @@ -101,7 +101,7 @@ + (RollbarConfig *)configuration { return [RollbarInfrastructure sharedInstance].configuration; } -+ (void)updateConfiguration:(RollbarConfig *)configuration { ++ (void)updateWithConfiguration:(RollbarConfig *)configuration { [[RollbarInfrastructure sharedInstance] configureWith:configuration andCrashCollector:nil]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h index 1977c1b8..20eee813 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/Rollbar.h @@ -8,30 +8,24 @@ #import "RollbarTelemetry.h" #import "RollbarTelemetryType.h" -@class RollbarConfig; -@class RollbarLogger; -@protocol RollbarCrashCollector; +#import "RollbarCrashCollectorProtocol.h" +#import "RollbarConfig.h" +//#import "RollbarLogger.h" -// Macros that help in throwing an exception with its source location metadata included: -#define __ThrowException(name, reason, class, function, file, line, info) [NSException exceptionWithName:name reason:[NSString stringWithFormat:@"%s:%i (%@:%s) %@", file, line, class, function, reason] userInfo:info]; -#define ThrowException(name, reason, info) __ThrowException(name, reason, [self class], _cmd, __FILE__, __LINE__, info) -/// Globa;l uncaught exception handler that sends provided exception data to Rollbar via preconfigured RollbarInfrastructure's shared instnace. -/// @param exception an exception to report to Rolbar -// Add a call to the: NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler); -// to the end of your: -(BOOL)application:didFinishLaunchingWithOptions: method in AppDelegate. -// Make sure that the [RollbarInfrastructure sharedInstance] was already configured as early as possible within the: -// -(BOOL)application:didFinishLaunchingWithOptions: method in AppDelegate. -static void uncaughtExceptionHandler(NSException * _Nonnull exception); +#pragma mark - Initialization Facade Protocol -@interface Rollbar : NSObject +/// Rollbar facade initialization protocol +@protocol RollbarFacadeInitialization -#pragma mark - Class Initializers +@required /// Class initializer. /// @param accessToken Rollbar project access token + (void)initWithAccessToken:(nonnull NSString *)accessToken; +@optional + /// Class initializer. /// @param configuration a Rollbar configuration + (void)initWithConfiguration:(nonnull RollbarConfig *)configuration; @@ -47,33 +41,32 @@ static void uncaughtExceptionHandler(NSException * _Nonnull exception); /// @param crashCollector a crash collector + (void)initWithConfiguration:(nonnull RollbarConfig *)configuration crashCollector:(nullable id)crashCollector; + @end + -#pragma mark - Configuration +#pragma mark - Configuration Facade Protocol + +/// Rollbar facade configuration protocol +@protocol RollbarFacadeConfiguration // + +@required /// The shared Rollbar master configuration. + (nonnull RollbarConfig *)configuration; /// Updates with a shared configuration. /// @param configuration a new Rollbar configuration -+ (void)updateConfiguration:(nonnull RollbarConfig *)configuration; - ++ (void)updateWithConfiguration:(nonnull RollbarConfig *)configuration; -// TODO: remove this method... -//+ (nullable RollbarMutableConfig *)currentConfiguration; - - -// TODO: remove this method... -//+ (void)reapplyConfiguration; - -#pragma mark - Shared/global notifier - -// TODO: remove this method... -//+ (nonnull RollbarLogger *)currentLogger; +@end +#pragma mark - Logging Facade Protocol +/// Rollbar facade logging protocol +@protocol RollbarFacadeLogging // -#pragma mark - Logging methods +@required /// Logs a crash report /// @param crashReport a crash report @@ -151,7 +144,7 @@ static void uncaughtExceptionHandler(NSException * _Nonnull exception); data:(nullable NSDictionary *)data context:(nullable NSString *)context; -#pragma mark - Convenience logging methods +@optional /// Performs debug level logging /// @param message a message @@ -424,14 +417,15 @@ static void uncaughtExceptionHandler(NSException * _Nonnull exception); data:(nullable NSDictionary *)data context:(nullable NSString *)context; +@end -#pragma mark - Send manually constructed JSON payload -/// Posts a Json payload -/// @param payload a Json payload -+ (void)sendJsonPayload:(nonnull NSData *)payload; +#pragma mark - Telemetry Facade Protocol + +/// Rollbar facade telemetry protocol +@protocol RollbarFacadeTelemetry // -#pragma mark - Telemetry API +@required /// Captures a view telemetry event /// @param level Rollbar log level @@ -529,4 +523,52 @@ static void uncaughtExceptionHandler(NSException * _Nonnull exception); @end + +#pragma mark - Rollbar Facade Utility Class + +/// Rollbar facade utility class +@interface Rollbar +: NSObject + +#pragma mark - Send manually constructed JSON payload + +/// Posts a Json payload +/// @param payload a Json payload ++ (void)sendJsonPayload:(nonnull NSData *)payload; + +#pragma mark - Instantiation blockers + ++ (nonnull instancetype)new NS_UNAVAILABLE; ++ (nonnull instancetype)allocWithZone:(nullable struct _NSZone *)zone NS_UNAVAILABLE; ++ (nonnull instancetype)alloc NS_UNAVAILABLE; ++ (nullable id)copyWithZone:(nullable struct _NSZone *)zone NS_UNAVAILABLE; ++ (nullable id)mutableCopyWithZone:(nullable struct _NSZone *)zone NS_UNAVAILABLE; + +- (nonnull instancetype)init NS_UNAVAILABLE; +- (void)dealloc NS_UNAVAILABLE; +- (nonnull id)copy NS_UNAVAILABLE; +- (nonnull id)mutableCopy NS_UNAVAILABLE; + +@end + + +#pragma mark - Exception Raising + +// Macros that help in throwing an exception with its source location metadata included: +#define __ThrowException(name, reason, class, function, file, line, info) [NSException exceptionWithName:name reason:[NSString stringWithFormat:@"%s:%i (%@:%s) %@", file, line, class, function, reason] userInfo:info]; +#define ThrowException(name, reason, info) __ThrowException(name, reason, [self class], _cmd, __FILE__, __LINE__, info) + + +#pragma mark - Unhandled Exception Handler + +/// Globa;l uncaught exception handler that sends provided exception data to Rollbar via preconfigured RollbarInfrastructure's shared instnace. +/// @param exception an exception to report to Rolbar +// Add a call to the: NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler); +// to the end of your: -(BOOL)application:didFinishLaunchingWithOptions: method in AppDelegate. +// Make sure that the [RollbarInfrastructure sharedInstance] was already configured as early as possible within the: +// -(BOOL)application:didFinishLaunchingWithOptions: method in AppDelegate. +static void uncaughtExceptionHandler(NSException * _Nonnull exception); + + + #endif //Rollbar_h diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m index fb328dce..15f23e9b 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m @@ -32,7 +32,7 @@ - (void)setUp { - (void)tearDown { - [Rollbar updateConfiguration:[RollbarConfig new]]; + [Rollbar updateWithConfiguration:[RollbarConfig new]]; [super tearDown]; } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index cbcaaf0c..5b275800 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -33,7 +33,7 @@ - (void)setUp { - (void)tearDown { - [Rollbar updateConfiguration:[RollbarConfig new]]; + [Rollbar updateWithConfiguration:[RollbarConfig new]]; [super tearDown]; } @@ -81,7 +81,7 @@ - (void)testScrubSafeListFields { for (NSString *key in keys) { [config.dataScrubber addScrubField:key]; } - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; @@ -104,7 +104,7 @@ - (void)testScrubSafeListFields { for (NSString *key in keys) { [config.dataScrubber addScrubSafeListField:key]; } - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; @@ -129,7 +129,7 @@ - (void)testTelemetryEnabled { BOOL expectedFlag = NO; RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.telemetry.enabled = expectedFlag; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; XCTAssertTrue(RollbarTelemetry.sharedInstance.enabled == expectedFlag, @"RollbarTelemetry.sharedInstance.enabled is expected to be NO." @@ -150,7 +150,7 @@ - (void)testTelemetryEnabled { expectedFlag = YES; config.telemetry.enabled = expectedFlag; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; XCTAssertTrue(RollbarTelemetry.sharedInstance.enabled == expectedFlag, @"RollbarTelemetry.sharedInstance.enabled is expected to be YES." @@ -174,7 +174,7 @@ - (void)testScrubViewInputsTelemetryConfig { BOOL expectedFlag = NO; RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.telemetry.viewInputsScrubber.enabled = expectedFlag; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; XCTAssertTrue(RollbarTelemetry.sharedInstance.scrubViewInputs == expectedFlag, @"RollbarTelemetry.sharedInstance.scrubViewInputs is expected to be NO." @@ -182,7 +182,7 @@ - (void)testScrubViewInputsTelemetryConfig { expectedFlag = YES; config.telemetry.viewInputsScrubber.enabled = expectedFlag; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; XCTAssertTrue(RollbarTelemetry.sharedInstance.scrubViewInputs == expectedFlag, @"RollbarTelemetry.sharedInstance.scrubViewInputs is expected to be YES." @@ -197,7 +197,7 @@ - (void)testViewInputTelemetrScrubFieldsConfig { RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; [config.telemetry.viewInputsScrubber addScrubField:element1]; [config.telemetry.viewInputsScrubber addScrubField:element2]; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; XCTAssertTrue( RollbarTelemetry.sharedInstance.viewInputsToScrub.count == [RollbarScrubbingOptions new].scrubFields.count + 2, @@ -216,7 +216,7 @@ - (void)testViewInputTelemetrScrubFieldsConfig { [config.telemetry.viewInputsScrubber removeScrubField:element1]; [config.telemetry.viewInputsScrubber removeScrubField:element2]; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; XCTAssertTrue( RollbarTelemetry.sharedInstance.viewInputsToScrub.count == [RollbarScrubbingOptions new].scrubFields.count, @@ -238,17 +238,17 @@ - (void)testEnabled { RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.developerOptions.enabled = NO; //Rollbar.currentLogger.configuration.developerOptions.enabled = NO; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"Test1"]; XCTAssertTrue(![self rollbarStoreContains:@"Test1"]); config.developerOptions.enabled = YES; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"Test2"]; XCTAssertTrue([self rollbarStoreContains:@"Test2"]); config.developerOptions.enabled = NO; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"Test3"]; XCTAssertTrue(![self rollbarStoreContains:@"Test3"]); @@ -259,7 +259,7 @@ - (void)testMaximumTelemetryEvents { RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.telemetry.enabled = YES; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; int testCount = 10; int max = 5; @@ -268,7 +268,7 @@ - (void)testMaximumTelemetryEvents { } config.telemetry.maximumTelemetryData = max; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"Test"]; [RollbarLogger flushRollbarThread]; @@ -292,7 +292,7 @@ - (void)testCheckIgnore { config.checkIgnoreRollbarData = ^BOOL(RollbarData *payloadData) { return true; }; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"Must ignore this"]; XCTAssertTrue(![self rollbarStoreContains:@"Must ignore this"]); } @@ -309,7 +309,7 @@ - (void)testServerData { branch:branch codeVersion:codeVersion ]; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; @@ -351,7 +351,7 @@ - (void)testPayloadModification { [payloadData.body.message addKeyed:@"body2" String:newMsg]; return payloadData; }; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; @@ -381,7 +381,7 @@ - (void)testScrubField { for (NSString *key in keys) { [config.dataScrubber addScrubField:key]; } - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; @@ -406,7 +406,7 @@ - (void)testLogTelemetryAutoCapture { RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.telemetry.enabled = YES; config.telemetry.captureLog = YES; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [RollbarLogger flushRollbarThread]; [RollbarLogger clearSdkDataStore]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m index d5b30d2e..749804b9 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m @@ -21,11 +21,11 @@ - (void)setUp { RollbarMutableConfig *config = [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] environment:[RollbarTestHelper getRollbarEnvironment]]; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; } - (void)tearDown { - [Rollbar updateConfiguration:[RollbarConfig new]]; + [Rollbar updateWithConfiguration:[RollbarConfig new]]; [super tearDown]; } @@ -33,7 +33,7 @@ - (void)testTelemetryCapture { RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.telemetry.enabled = YES; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar recordNavigationEventForLevel:RollbarLevel_Info from:@"from" to:@"to"]; [Rollbar recordConnectivityEventForLevel:RollbarLevel_Info status:@"status"]; @@ -80,7 +80,7 @@ - (void)testErrorReportingWithTelemetry { RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.telemetry.enabled = YES; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar recordNavigationEventForLevel:RollbarLevel_Info from:@"SomeNavigationSource" to:@"SomeNavigationDestination"]; [Rollbar recordConnectivityEventForLevel:RollbarLevel_Info status:@"SomeConnectivityStatus"]; @@ -137,7 +137,7 @@ - (void)testTelemetryViewEventScrubbing { config.telemetry.viewInputsScrubber.enabled = YES; [config.telemetry.viewInputsScrubber addScrubField:@"password"]; [config.telemetry.viewInputsScrubber addScrubField:@"pin"]; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar recordViewEventForLevel:RollbarLevel_Debug element:@"password" @@ -160,7 +160,7 @@ - (void)testRollbarLog { RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.telemetry.enabled = YES; config.telemetry.captureLog = YES; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [RollbarTelemetry.sharedInstance clearAllData]; [NSThread sleepForTimeInterval:2.0f]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m index b28f49a1..32488c0f 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m @@ -34,7 +34,7 @@ - (void)setUp { - (void)tearDown { - [Rollbar updateConfiguration:[RollbarConfig new]]; + [Rollbar updateWithConfiguration:[RollbarConfig new]]; [super tearDown]; } @@ -72,7 +72,7 @@ - (void)testRollbarNotifiersIndependentConfiguration { config.destination.accessToken = @"AT_0"; config.destination.environment = @"ENV_0"; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; XCTAssertTrue([[Rollbar configuration].destination.accessToken isEqualToString:config.destination.accessToken]); @@ -93,7 +93,7 @@ - (void)testRollbarNotifiersIndependentConfiguration { config = [[Rollbar configuration] mutableCopy]; config.destination.accessToken = @"AT_N"; config.destination.environment = @"ENV_N"; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; XCTAssertTrue([[RollbarInfrastructure sharedInstance].logger.configuration.destination.accessToken isEqualToString:@"AT_N"]); XCTAssertTrue([[RollbarInfrastructure sharedInstance].logger.configuration.destination.environment @@ -119,18 +119,18 @@ - (void)testRollbarTransmit { config.developerOptions.transmit = YES; config.developerOptions.transmit = YES; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar criticalMessage:@"Transmission test YES"]; [NSThread sleepForTimeInterval:2.0f]; config.developerOptions.transmit = NO; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar criticalMessage:@"Transmission test NO"]; [NSThread sleepForTimeInterval:2.0f]; config.developerOptions.transmit = YES; //config.enabled = NO; - [Rollbar updateConfiguration:config]; + [Rollbar updateWithConfiguration:config]; [Rollbar criticalMessage:@"Transmission test YES2"]; [NSThread sleepForTimeInterval:2.0f]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift index 6ad9bde8..38397ad5 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift @@ -22,7 +22,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { } override func tearDown() { - Rollbar.updateConfiguration(RollbarMutableConfig()); + Rollbar.update(withConfiguration: RollbarMutableConfig()); super.tearDown(); } @@ -39,7 +39,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { let config = Rollbar.configuration().mutableCopy(); config.telemetry.enabled = expectedFlag; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); XCTAssertTrue(RollbarTelemetry.sharedInstance().enabled == expectedFlag, "RollbarTelemetry.sharedInstance.enabled is expected to be NO." @@ -51,7 +51,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { } config.loggingOptions.maximumReportsPerMinute = max; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); var telemetryCollection = RollbarTelemetry.sharedInstance().getAllData()!; XCTAssertTrue(telemetryCollection.count == 0, @@ -60,7 +60,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { expectedFlag = true; config.telemetry.enabled = expectedFlag; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); XCTAssertTrue(RollbarTelemetry.sharedInstance().enabled == expectedFlag, "RollbarTelemetry.sharedInstance.enabled is expected to be YES." @@ -70,7 +70,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { } config.loggingOptions.maximumReportsPerMinute = max; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); telemetryCollection = RollbarTelemetry.sharedInstance().getAllData()!; XCTAssertTrue(telemetryCollection.count == max, @@ -85,7 +85,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { let config = Rollbar.configuration().mutableCopy(); config.telemetry.enabled = true; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); let testCount = 10; let max:UInt = 5; @@ -93,7 +93,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.recordErrorEvent(for: .debug, message: "test"); } config.telemetry.maximumTelemetryData = max; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); Rollbar.debugMessage("Test"); RollbarLogger .flushRollbarThread(); @@ -112,14 +112,14 @@ final class RollbarNotifierConfigurationTests: XCTestCase { var expectedFlag = false; let config = Rollbar.configuration().mutableCopy(); config.telemetry.viewInputsScrubber.enabled = expectedFlag; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); XCTAssertTrue(RollbarTelemetry.sharedInstance().scrubViewInputs == expectedFlag, "RollbarTelemetry.sharedInstance.scrubViewInputs is expected to be NO." ); expectedFlag = true; config.telemetry.viewInputsScrubber.enabled = expectedFlag; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); XCTAssertTrue(RollbarTelemetry.sharedInstance().scrubViewInputs == expectedFlag, "RollbarTelemetry.sharedInstance.scrubViewInputs is expected to be YES." ); @@ -136,7 +136,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { config.telemetry.viewInputsScrubber.scrubFields.add(element1); config.telemetry.viewInputsScrubber.scrubFields.add(element2); - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); XCTAssertTrue( RollbarTelemetry.sharedInstance().viewInputsToScrub!.count == (RollbarMutableScrubbingOptions().scrubFields.count + 2), @@ -154,7 +154,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { config.telemetry.viewInputsScrubber.removeScrubField(element1); config.telemetry.viewInputsScrubber.removeScrubField(element2); - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); XCTAssertTrue( RollbarTelemetry.sharedInstance().viewInputsToScrub!.count == RollbarMutableScrubbingOptions().scrubFields.count, @@ -176,7 +176,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { let config = Rollbar.configuration().mutableCopy(); config.developerOptions.enabled = false; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); RollbarLogger.flushRollbarThread(); RollbarTestUtil.clearLogFile(); @@ -188,7 +188,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { ); config.developerOptions.enabled = true; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("Test2"); @@ -197,7 +197,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { XCTAssertTrue(logItems[logItems.count - 1].contains("Test2")); config.developerOptions.enabled = false; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("Test3"); @@ -235,7 +235,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { let branch = "testBranch"; let codeVersion = "testCodeVersion"; config.setServerHost(host, root: root, branch: branch, codeVersion: codeVersion); - Rollbar .updateConfiguration(config); + Rollbar .update(withConfiguration: config); Rollbar.debugMessage("test"); @@ -272,7 +272,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { rollbarData.body.message?.addKeyed("body2", string: newMsg) return rollbarData; }; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); Rollbar.debugMessage("test"); RollbarTestUtil.waitForPesistenceToComplete(); @@ -304,7 +304,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { for key in keys { config.dataScrubber.addScrubField(key); } - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("test"); @@ -327,7 +327,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { for key in keys { config.dataScrubber.addScrubSafeListField(key); } - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("test"); @@ -371,7 +371,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { .orderedSame == personJson!.compare(expectedPersonJson), "Properly serialized person attributes." ); - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("test"); @@ -414,7 +414,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { .orderedSame == personJson!.compare(expectedPersonJson), "Properly serialized person attributes." ); - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("test"); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift index ad6c3a30..c531be60 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift @@ -23,14 +23,14 @@ final class RollbarNotifierLoggerTests: XCTestCase { config.developerOptions.logPayload = true; config.loggingOptions.maximumReportsPerMinute = 5000; config.customData = ["someKey": "someValue", ]; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); } override func tearDown() { RollbarTestUtil.waitForPesistenceToComplete(waitTimeInSeconds: 2.0); - Rollbar.updateConfiguration(RollbarMutableConfig()); + Rollbar.update(withConfiguration: RollbarMutableConfig()); super.tearDown(); } @@ -51,7 +51,7 @@ final class RollbarNotifierLoggerTests: XCTestCase { config.destination.accessToken = "AT_0"; config.destination.environment = "ENV_0"; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); XCTAssertEqual(RollbarInfrastructure.sharedInstance().logger.configuration!.destination.accessToken, config.destination.accessToken); XCTAssertEqual(RollbarInfrastructure.sharedInstance().logger.configuration!.destination.environment, @@ -74,7 +74,7 @@ final class RollbarNotifierLoggerTests: XCTestCase { config = Rollbar.configuration().mutableCopy(); config.destination.accessToken = "AT_N"; config.destination.environment = "ENV_N"; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); XCTAssertTrue(RollbarInfrastructure.sharedInstance().logger.configuration!.destination.accessToken.compare("AT_N") == .orderedSame); XCTAssertTrue(RollbarInfrastructure.sharedInstance().logger.configuration!.destination.environment.compare("ENV_N") == .orderedSame); @@ -98,17 +98,17 @@ final class RollbarNotifierLoggerTests: XCTestCase { config.developerOptions.transmit = true; config.developerOptions.transmit = true; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); Rollbar.criticalMessage("Transmission test YES"); RollbarTestUtil.waitForPesistenceToComplete(); config.developerOptions.transmit = false; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); Rollbar.criticalMessage("Transmission test NO"); RollbarTestUtil.waitForPesistenceToComplete(); config.developerOptions.transmit = true; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); Rollbar.criticalMessage("Transmission test YES2"); RollbarTestUtil.waitForPesistenceToComplete(); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift index 2316b016..14253ac5 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift @@ -17,11 +17,11 @@ final class RollbarNotifierTelemetryTests: XCTestCase { withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), environment: RollbarTestHelper.getRollbarEnvironment() ); - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); } override func tearDown() { - Rollbar.updateConfiguration(RollbarMutableConfig()); + Rollbar.update(withConfiguration: RollbarMutableConfig()); super.tearDown(); } @@ -36,7 +36,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { config.developerOptions.transmit = false; config.telemetry.enabled = true; config.telemetry.memoryStatsAutocollectionInterval = 0.5; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); Thread.sleep(forTimeInterval: 5.0); Rollbar.criticalMessage("Must contain memory telemetry!"); @@ -71,7 +71,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { config.telemetry.enabled = true; config.telemetry.memoryStatsAutocollectionInterval = 0.5; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); //let resultingConfig = Rollbar.currentConfiguration(); Rollbar.criticalMessage("Rollbar will be testing memory telemetry!"); @@ -89,7 +89,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { let config = Rollbar.configuration().mutableCopy(); config.telemetry.enabled = true; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); RollbarLogger.flushRollbarThread(); Rollbar.recordNavigationEvent( @@ -179,7 +179,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { let config = Rollbar.configuration().mutableCopy(); config.telemetry.enabled = true; - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); Rollbar.recordNavigationEvent( for: .info, @@ -273,7 +273,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { config.telemetry.viewInputsScrubber.enabled = true; config.telemetry.viewInputsScrubber.scrubFields.add("password"); config.telemetry.viewInputsScrubber.scrubFields.add("pin"); - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); Rollbar.recordViewEvent( for: .debug, diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift index 47b77f90..beef6ac1 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift @@ -18,11 +18,11 @@ final class RollbarNotifierTruncationTests: XCTestCase { withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), environment: RollbarTestHelper.getRollbarEnvironment() ); - Rollbar.updateConfiguration(config); + Rollbar.update(withConfiguration: config); } override func tearDown() { - Rollbar.updateConfiguration(RollbarMutableConfig()); + Rollbar.update(withConfiguration: RollbarMutableConfig()); super.tearDown(); } From bb21d8109578dd9aba2140c1b71facd93cb3bb23 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 27 Jul 2022 20:15:54 -0700 Subject: [PATCH 071/127] feat: adding Sqlite based payloads store --- .../RollbarNotifier/RollbarNotifierFiles.h | 2 + .../RollbarNotifier/RollbarNotifierFiles.m | 7 ++ .../RollbarPayloadRepository.h | 29 +++++ .../RollbarPayloadRepository.m | 118 ++++++++++++++++++ .../Sources/RollbarNotifier/RollbarThread.h | 5 +- .../Sources/RollbarNotifier/RollbarThread.m | 38 +++--- 6 files changed, 184 insertions(+), 15 deletions(-) create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h create mode 100644 RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h index 148ccf2e..ca7b2267 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h @@ -13,6 +13,8 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - notifier files ++ (nonnull NSString * const)payloadsStore; + + (nonnull NSString * const)itemsQueue; + (nonnull NSString * const)itemsQueueState; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m index 284ad229..82f125c0 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m @@ -2,6 +2,8 @@ static NSString * const PAYLOADS_FILE_NAME = @"rollbar.payloads"; +static NSString * const PAYLOADS_STORE_FILE_NAME = @"rollbar.store"; + static NSString * const QUEUED_ITEMS_FILE_NAME = @"rollbar.items"; static NSString * const QUEUED_ITEMS_STATE_FILE_NAME = @"rollbar.state"; @@ -14,6 +16,11 @@ @implementation RollbarNotifierFiles ++ (nonnull NSString * const)payloadsStore { + + return PAYLOADS_STORE_FILE_NAME; +} + + (nonnull NSString * const)itemsQueue { return QUEUED_ITEMS_FILE_NAME; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h new file mode 100644 index 00000000..7863daf8 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -0,0 +1,29 @@ +// +// RollbarPayloadRepository.h +// +// +// Created by Andrey Kornich on 2022-07-27. +// + +#import + +#import "RollbarPayload.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface RollbarPayloadRepository : NSObject + +#pragma mark - repository methods + +- (void)clear; + +- (void)addPayload:(nonnull RollbarPayload *)payload; + +#pragma mark - instance initializers + +- (instancetype)initWithStore:(nonnull NSString *)storePath +NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m new file mode 100644 index 00000000..b01f0482 --- /dev/null +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -0,0 +1,118 @@ +#import "RollbarPayloadRepository.h" + +#import "RollbarNotifierFiles.h" + +@import RollbarCommon; + +#import "sqlite3.h" + + +@implementation RollbarPayloadRepository { + + @private + NSString *_storePath; + sqlite3 *_db; + char *_sqliteErrorMessage; +} + ++ (void)initialize { + +} + +#pragma mark - instance initializers + +- (instancetype)initWithStore:(nonnull NSString *)storePath { + + if (self = [super init]) { + + self->_storePath = storePath; + [self initDB]; + return self; + } + + return nil; +} + +- (instancetype)init { + + // create working cache directory: + [RollbarCachesDirectory ensureCachesDirectoryExists]; + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + NSString *storePath = [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsStore]]; + + if (self = [self initWithStore:storePath]) { + + return self; + } + + return nil; +} + +#pragma mark - repository methods + +- (void)addPayload:(nonnull RollbarPayload *)payload { + +} + +- (void)clear { + +} + +#pragma mark - internal methods + +- (void)initDB { + + [self openDB]; + [self ensureDestinationsTable]; + [self ensurePayloadsTable]; +} + +- (void)openDB { + + int result = sqlite3_open([self->_storePath UTF8String], &self->_db); + if (result != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_open: %s", sqlite3_errmsg(self->_db)); + } +} + +- (void)ensureDestinationsTable { + + NSString *sql = [NSString stringWithFormat: + @"CREATE TABLE IF NOT EXISTS destinations (id INTEGER, endpoint TEXT, access_token TEXT)"]; + [self executeSql:sql]; +} + +- (void)ensurePayloadsTable { + + NSString *sql = [NSString stringWithFormat: + @"CREATE TABLE IF NOT EXISTS payloads (id INTEGER, destination_id INTEGER, payload_json TEXT, timestamp TEXT)"]; + [self executeSql:sql]; +} + +- (void)releaseDB { + + sqlite3_close(self->_db); + self->_db = nil; +} + +- (void)clearDestinationsTable { +} + +- (void)clearPayloadsTable { +} + +- (void)clearPayloadsOlderThan:(nonnull NSDate *)cutoffTime { +} + +- (void)executeSql:(nonnull NSString *)sql { + + char *sqliteErrorMessage; + int result = sqlite3_exec(self->_db, [sql UTF8String], NULL, NULL, &sqliteErrorMessage); + if (result != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } +} +@end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h index cd3df703..ef5aac2f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h @@ -1,6 +1,7 @@ @import Foundation; -@class RollbarConfig; +#import "RollbarConfig.h" +#import "RollbarPayload.h" NS_ASSUME_NONNULL_BEGIN @@ -9,6 +10,8 @@ NS_ASSUME_NONNULL_BEGIN /// Signifies that the thread is active or not. @property(atomic) BOOL active; +- (void)persist:(nonnull RollbarPayload *)payload; + - (void)persistPayload:(nonnull NSDictionary *)payload; - (BOOL)sendPayload:(nonnull NSData *)payload diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 2248aa1a..e64d6e51 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -2,21 +2,22 @@ #import "RollbarThread.h" #import "RollbarLogger.h" -#import "RollbarConfig.h" -#import "RollbarDeveloperOptions.h" +//#import "RollbarConfig.h" +//#import "RollbarDeveloperOptions.h" #import "RollbarReachability.h" #import "RollbarTelemetry.h" -#import "RollbarTelemetryOptions.h" +//#import "RollbarTelemetryOptions.h" #import "RollbarNotifierFiles.h" -#import "RollbarPayload.h" +//#import "RollbarPayload.h" #import "RollbarPayloadTruncator.h" #import "RollbarData.h" -#import "RollbarModule.h" -#import "RollbarDestination.h" +//#import "RollbarModule.h" +//#import "RollbarDestination.h" #import "RollbarProxy.h" #import "RollbarSender.h" #import "RollbarPayloadPostReply.h" #import "RollbarRegistry.h" +#import "RollbarPayloadRepository.h" static NSUInteger MAX_RETRY_COUNT = 5; @@ -53,8 +54,10 @@ - (instancetype)initWithTarget:(id)target self->_maxReportsPerMinute = 240;//60; self->_registry = [RollbarRegistry new]; +#if !TARGET_OS_WATCH self->_reachability = nil; self->_isNetworkReachable = YES; +#endif self->_nextSendTime = [[NSDate alloc] init]; self.name = [RollbarThread rollbar_objectClassName];//NSStringFromClass([RollbarThread class]); @@ -142,13 +145,13 @@ - (void)saveQueueState { [data writeToFile:self->_stateFilePath atomically:YES]; } -- (void)setReportingRate:(NSUInteger)reportsPerMinute { - +//- (void)setReportingRate:(NSUInteger)reportsPerMinute { +// // NSAssert(reportsPerMinute > 0, @"reportsPerMinute must be greater than zero!"); -// +// // BOOL wasExecuting = self.isExecuting; // if (wasExecuting) { -// +// // [self cancel]; // } // @@ -157,14 +160,14 @@ - (void)setReportingRate:(NSUInteger)reportsPerMinute { // } else { // _maxReportsPerMinute = 60; // } -// +// // self.active = YES; -// +// // if (wasExecuting) { -// +// // [self start]; // } -} +//} - (void)run { @@ -188,6 +191,13 @@ - (void)run { } } +#pragma mark - payload store + +- (void)persist:(nonnull RollbarPayload *)payload { + +} + + #pragma mark - persisting payload items - (void)persistPayload:(nonnull NSDictionary *)payload { From b9ade7380c176e40006e385a00ad80c0b8fd2d17 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 28 Jul 2022 17:33:08 -0700 Subject: [PATCH 072/127] test: RollbarPayloadRepositoryTests --- .../RollbarPayloadRepositoryTests.m | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m new file mode 100644 index 00000000..251c3612 --- /dev/null +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -0,0 +1,36 @@ +// +// RollbarPayloadRepositoryTests.m +// +// +// Created by Andrey Kornich on 2022-07-28. +// + +#import + +@interface RollbarPayloadRepositoryTests : XCTestCase + +@end + +@implementation RollbarPayloadRepositoryTests + +- (void)setUp { + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. +} + +- (void)testExample { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end From 0432c509c4b4ca2cabededf2b4b13c124c849432 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 28 Jul 2022 17:33:45 -0700 Subject: [PATCH 073/127] test: RollbarTestUtil --- .../Sources/UnitTesting/RollbarTestUtil.swift | 70 ++++++++++++++----- 1 file changed, 54 insertions(+), 16 deletions(-) diff --git a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift index 70c0326c..625e1a7d 100644 --- a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift +++ b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift @@ -10,10 +10,17 @@ import RollbarCommon @objc public class RollbarTestUtil: NSObject { + private static let payloadsStore = "rollbar.db"; private static let queuedItemsFileName = "rollbar.items"; private static let queuedItemsStateFileName = "rollbar.state"; private static let telemetryFileName = "rollbar.telemetry"; + private static func getPayloadsStoreFilePath() -> String { + let cachesDirectory = RollbarCachesDirectory.directory() ; + let filePath = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(payloadsStore); + return filePath.path; + } + private static func getQueuedItemsFilePath() -> String { let cachesDirectory = RollbarCachesDirectory.directory() ; let filePath = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(queuedItemsFileName); @@ -25,14 +32,26 @@ import RollbarCommon let filePath = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(queuedItemsStateFileName); return filePath.path; } + private static func getTelemetryFilePath() -> String { let cachesDirectory = RollbarCachesDirectory.directory() ; let filePath = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(telemetryFileName); return filePath.path; } - @objc public static func clearTelemetryFile() { - let filePath = RollbarTestUtil.getTelemetryFilePath(); + @objc public static func checkFileExists(filePath:String!) -> Bool { + if ((filePath == nil) || filePath.isEmpty) { + return false; + } + let fileManager = FileManager.default; + let fileExists = fileManager.fileExists(atPath: filePath); + return fileExists; + } + + @objc public static func deleteFile(filePath:String!) { + if ((filePath == nil) || filePath.isEmpty) { + return; + } let fileManager = FileManager.default; let fileExists = fileManager.fileExists(atPath: filePath); if fileExists { @@ -41,28 +60,47 @@ import RollbarCommon } catch { print("Unexpected error: \(error).") } + } + } + + @objc public static func clearFile(filePath:String!) { + if ((filePath == nil) || filePath.isEmpty) { + return; + } + let fileManager = FileManager.default; + let fileExists = fileManager.fileExists(atPath: filePath); + if fileExists { + RollbarTestUtil.deleteFile(filePath: filePath); fileManager.createFile(atPath: filePath, contents: nil, attributes: nil); } } + @objc public static func checkPayloadsStoreFileExists() -> Bool { + let filePath = RollbarTestUtil.getPayloadsStoreFilePath(); + return RollbarTestUtil.checkFileExists(filePath: filePath); + } + + @objc public static func deletePayloadsStoreFile() { + let filePath = RollbarTestUtil.getPayloadsStoreFilePath(); + RollbarTestUtil.deleteFile(filePath: filePath); + } + + @objc public static func clearTelemetryFile() { + let filePath = RollbarTestUtil.getTelemetryFilePath(); + RollbarTestUtil.clearFile(filePath: filePath); + } + @objc public static func clearLogFile() { let itemsStateFilePath = RollbarTestUtil.getQueuedItemsStateFilePath(); let itemsFilePath = RollbarTestUtil.getQueuedItemsFilePath(); let fileManager = FileManager.default; - do { - if fileManager.fileExists(atPath: itemsStateFilePath) { - try fileManager.removeItem(atPath: itemsStateFilePath); - } - if fileManager.fileExists(atPath: itemsFilePath) { - try fileManager.removeItem(atPath: itemsFilePath); - fileManager.createFile( - atPath: itemsFilePath, - contents: nil, - attributes: nil - ); - } - } catch { - print("Unexpected error: \(error).") + + if fileManager.fileExists(atPath: itemsStateFilePath) { + RollbarTestUtil.deleteFile(filePath: itemsStateFilePath); + } + + if fileManager.fileExists(atPath: itemsFilePath) { + RollbarTestUtil.clearFile(filePath: itemsFilePath); } } From 1c84ec154943122aeb20f169b24272b93a052e08 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 28 Jul 2022 17:34:16 -0700 Subject: [PATCH 074/127] feat: RollbarPayloadRepository --- .../RollbarNotifier/RollbarNotifierFiles.m | 2 +- .../RollbarPayloadRepository.h | 8 +++ .../RollbarPayloadRepository.m | 70 +++++++++++++++++++ 3 files changed, 79 insertions(+), 1 deletion(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m index 82f125c0..cd24d84f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m @@ -2,7 +2,7 @@ static NSString * const PAYLOADS_FILE_NAME = @"rollbar.payloads"; -static NSString * const PAYLOADS_STORE_FILE_NAME = @"rollbar.store"; +static NSString * const PAYLOADS_STORE_FILE_NAME = @"rollbar.db"; static NSString * const QUEUED_ITEMS_FILE_NAME = @"rollbar.items"; static NSString * const QUEUED_ITEMS_STATE_FILE_NAME = @"rollbar.state"; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index 7863daf8..9c0aaa5f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -24,6 +24,14 @@ NS_ASSUME_NONNULL_BEGIN - (instancetype)initWithStore:(nonnull NSString *)storePath NS_DESIGNATED_INITIALIZER; +#pragma mark - unit testing helper methods + +- (BOOL)checkIfTableExists_Destinations; + +- (BOOL)checkIfTableExists_Payloads; + +- (BOOL)checkIfTableExists_Unknown; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index b01f0482..1c4d0c03 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -6,6 +6,22 @@ #import "sqlite3.h" +static int checkIfTableExistsCallback(void *info, int columns, char **data, char **column) +{ + RollbarSdkLog(@"Columns: %d", columns); + for (int i = 0; i < columns; i++) { + RollbarSdkLog(@"Column: %s", column[i]); + RollbarSdkLog(@"Data: %s", data[i]); + } + + BOOL *answerFlag = (BOOL *)info; + if (answerFlag) { + + *answerFlag = (columns > 0) ? YES : NO; + } + + return SQLITE_OK; +} @implementation RollbarPayloadRepository { @@ -13,6 +29,10 @@ @implementation RollbarPayloadRepository { NSString *_storePath; sqlite3 *_db; char *_sqliteErrorMessage; + + BOOL _tableExists_Destinations; + BOOL _tableExists_Payloads; + BOOL _tableExists_Unknown; } + (void)initialize { @@ -115,4 +135,54 @@ - (void)executeSql:(nonnull NSString *)sql { sqlite3_free(sqliteErrorMessage); } } + +- (BOOL)checkIfTableExists_Destinations { + + BOOL result = [self checkIfTableExists:@"destinations"]; + return result; +} + +- (BOOL)checkIfTableExists_Payloads { + + BOOL result = [self checkIfTableExists:@"payloads"]; + return result; +} + +- (BOOL)checkIfTableExists_Unknown { + + BOOL result = [self checkIfTableExists:@"unknown"]; + return result; +} + + +- (BOOL)checkIfTableExists:(nonnull NSString *)tableName { + + BOOL *answerFlag = nil; + if ([tableName isEqualToString:@"destinations"]) { + answerFlag = &(self->_tableExists_Destinations); + } + else if ([tableName isEqualToString:@"payloads"]) { + answerFlag = &(self->_tableExists_Payloads); + } + else if ([tableName isEqualToString:@"unknown"]) { + answerFlag = &(self->_tableExists_Unknown); + } + else { + return NO; + } + + NSString *sql = [NSString stringWithFormat: + @"SELECT name FROM sqlite_master WHERE type='table' AND name='%@'", tableName]; + char *sqliteErrorMessage; + int result = sqlite3_exec(self->_db, [sql UTF8String], checkIfTableExistsCallback, answerFlag, &sqliteErrorMessage); + if (result != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } + + BOOL exists = *answerFlag; + return exists; +} + @end From 04bcf862c92902b500e26d7a100246b42ce25177 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 28 Jul 2022 17:34:33 -0700 Subject: [PATCH 075/127] test: RollbarPayloadRepositoryTests --- .../RollbarPayloadRepositoryTests.m | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index 251c3612..c22ec4db 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -6,6 +6,9 @@ // #import +#import "../../Sources/RollbarNotifier/RollbarPayloadRepository.h" + +@import UnitTesting; @interface RollbarPayloadRepositoryTests : XCTestCase @@ -14,14 +17,30 @@ @interface RollbarPayloadRepositoryTests : XCTestCase @implementation RollbarPayloadRepositoryTests - (void)setUp { - // Put setup code here. This method is called before the invocation of each test method in the class. + + [super setUp]; + + [RollbarTestUtil deletePayloadsStoreFile]; + XCTAssertFalse([RollbarTestUtil checkPayloadsStoreFileExists]); } - (void)tearDown { - // Put teardown code here. This method is called after the invocation of each test method in the class. + + //[RollbarTestUtil deletePayloadsStoreFile]; + + [super tearDown]; } -- (void)testExample { +- (void)testBasics { + + XCTAssertFalse([RollbarTestUtil checkPayloadsStoreFileExists]); + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue([RollbarTestUtil checkPayloadsStoreFileExists]); + + XCTAssertFalse([repo checkIfTableExists_Unknown]); + XCTAssertTrue ([repo checkIfTableExists_Destinations]); + XCTAssertTrue ([repo checkIfTableExists_Payloads]); + // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } From 21d9ee81d592eb58977cab00cb84403e561b2ea5 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 29 Jul 2022 15:55:53 -0700 Subject: [PATCH 076/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.h | 3 ++ .../RollbarPayloadRepository.m | 51 ++++++++++++++++--- .../RollbarPayloadRepositoryTests.m | 17 +++++-- 3 files changed, 61 insertions(+), 10 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index 9c0aaa5f..100dd517 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -32,6 +32,9 @@ NS_DESIGNATED_INITIALIZER; - (BOOL)checkIfTableExists_Unknown; +- (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 1c4d0c03..3257bde0 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -23,6 +23,17 @@ static int checkIfTableExistsCallback(void *info, int columns, char **data, char return SQLITE_OK; } +static int insertDestinationCallback(void *info, int columns, char **data, char **column) +{ + RollbarSdkLog(@"Columns: %d", columns); + for (int i = 0; i < columns; i++) { + RollbarSdkLog(@"Column: %s", column[i]); + RollbarSdkLog(@"Data: %s", data[i]); + } + + return SQLITE_OK; +} + @implementation RollbarPayloadRepository { @private @@ -99,17 +110,45 @@ - (void)openDB { - (void)ensureDestinationsTable { NSString *sql = [NSString stringWithFormat: - @"CREATE TABLE IF NOT EXISTS destinations (id INTEGER, endpoint TEXT, access_token TEXT)"]; + @"CREATE TABLE IF NOT EXISTS destinations (id INTEGER NOT NULL PRIMARY KEY, endpoint TEXT NOT NULL, access_token TEXT NOT NULL, CONSTRAINT unique_destination UNIQUE(endpoint, access_token))" + ]; [self executeSql:sql]; } - (void)ensurePayloadsTable { + + NSString *sql = [NSString stringWithFormat: - @"CREATE TABLE IF NOT EXISTS payloads (id INTEGER, destination_id INTEGER, payload_json TEXT, timestamp TEXT)"]; + @"CREATE TABLE IF NOT EXISTS payloads (id INTEGER NOT NULL PRIMARY KEY, config_json TEXT NOT NULL, payload_json TEXT NOT NULL, created_at INTEGER NOT NULL, destination_key INTEGER NOT NULL, FOREIGN KEY(destination_key) REFERENCES destinations(id) ON UPDATE CASCADE ON DELETE CASCADE)" + ]; [self executeSql:sql]; } +- (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken { + + NSString *sql = [NSString stringWithFormat: + @"INSERT INTO destinations (endpoint, access_token) VALUES ('%@', '%@')", + endpoint, + accessToken + ]; + char *sqliteErrorMessage; + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], insertDestinationCallback, NULL, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } +} + + + + + + + + - (void)releaseDB { sqlite3_close(self->_db); @@ -128,8 +167,8 @@ - (void)clearPayloadsOlderThan:(nonnull NSDate *)cutoffTime { - (void)executeSql:(nonnull NSString *)sql { char *sqliteErrorMessage; - int result = sqlite3_exec(self->_db, [sql UTF8String], NULL, NULL, &sqliteErrorMessage); - if (result != SQLITE_OK) { + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], NULL, NULL, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); sqlite3_free(sqliteErrorMessage); @@ -174,8 +213,8 @@ - (BOOL)checkIfTableExists:(nonnull NSString *)tableName { NSString *sql = [NSString stringWithFormat: @"SELECT name FROM sqlite_master WHERE type='table' AND name='%@'", tableName]; char *sqliteErrorMessage; - int result = sqlite3_exec(self->_db, [sql UTF8String], checkIfTableExistsCallback, answerFlag, &sqliteErrorMessage); - if (result != SQLITE_OK) { + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], checkIfTableExistsCallback, answerFlag, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); sqlite3_free(sqliteErrorMessage); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index c22ec4db..b9e2e443 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -31,7 +31,7 @@ - (void)tearDown { [super tearDown]; } -- (void)testBasics { +- (void)testRepoInitialization { XCTAssertFalse([RollbarTestUtil checkPayloadsStoreFileExists]); RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; @@ -45,10 +45,19 @@ - (void)testBasics { // Use XCTAssert and related functions to verify your tests produce the correct results. } -- (void)testPerformanceExample { - // This is an example of a performance test case. +- (void)testInsertDestination { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + [repo insertDestinationWithEndpoint:@"EP_0011" andAccesToken:@"AC_001"]; + + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. +} + +- (void)testRepoInitializationPerformance { + [self measureBlock:^{ - // Put the code you want to measure the time of here. + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; }]; } From 722fb3ea67e1f82c0ada102a4108ea9235acc30d Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 29 Jul 2022 23:22:37 -0700 Subject: [PATCH 077/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.h | 2 + .../RollbarPayloadRepository.m | 98 ++++++++++++++----- .../RollbarPayloadRepositoryTests.m | 16 ++- 3 files changed, 87 insertions(+), 29 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index 100dd517..1487927b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -35,6 +35,8 @@ NS_DESIGNATED_INITIALIZER; - (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint andAccesToken:(nonnull NSString *)accessToken; +- (nullable NSDictionary *)selectDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken; @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 3257bde0..98536b84 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -6,7 +6,14 @@ #import "sqlite3.h" -static int checkIfTableExistsCallback(void *info, int columns, char **data, char **column) +//====================================================================================================================== +#pragma mark - Sqlite command execution callbacks +#pragma mark - +//====================================================================================================================== + +typedef int (^SqliteCallback)(void *info, int columns, char **data, char **column); + +static int defaultOnSelectCallback(void *info, int columns, char **data, char **column) { RollbarSdkLog(@"Columns: %d", columns); for (int i = 0; i < columns; i++) { @@ -14,6 +21,13 @@ static int checkIfTableExistsCallback(void *info, int columns, char **data, char RollbarSdkLog(@"Data: %s", data[i]); } + return SQLITE_OK; +} + +static int checkIfTableExistsCallback(void *info, int columns, char **data, char **column) +{ + defaultOnSelectCallback(info, columns, data, column); + BOOL *answerFlag = (BOOL *)info; if (answerFlag) { @@ -25,25 +39,48 @@ static int checkIfTableExistsCallback(void *info, int columns, char **data, char static int insertDestinationCallback(void *info, int columns, char **data, char **column) { - RollbarSdkLog(@"Columns: %d", columns); + defaultOnSelectCallback(info, columns, data, column); + + return SQLITE_OK; +} + +static int selectDestinationCallback(void *info, int columns, char **data, char **column) +{ + defaultOnSelectCallback(info, columns, data, column); + + //NSMutableDictionary *row = [NSMutableDictionary dictionaryWithCapacity:columns]; + //info = row; + NSMutableDictionary *__strong*result = (NSMutableDictionary *__strong*)info; + *result = [NSMutableDictionary dictionaryWithCapacity:columns]; + + NSMutableDictionary *row = + [NSMutableDictionary dictionaryWithCapacity:columns]; + + for (int i = 0; i < columns; i++) { - RollbarSdkLog(@"Column: %s", column[i]); - RollbarSdkLog(@"Data: %s", data[i]); + NSString *key = [NSString stringWithFormat:@"%s", column[i]]; + NSString *value = [NSString stringWithFormat:@"%s", data[i]]; + row[key] = value; } + *result = row; + return SQLITE_OK; } +//====================================================================================================================== +#pragma mark - Peyloads Repository +#pragma mark - +//====================================================================================================================== + +/// Peristent Rollbar payloads repository @implementation RollbarPayloadRepository { @private NSString *_storePath; sqlite3 *_db; char *_sqliteErrorMessage; - - BOOL _tableExists_Destinations; - BOOL _tableExists_Payloads; - BOOL _tableExists_Unknown; + } + (void)initialize { @@ -133,15 +170,38 @@ - (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint endpoint, accessToken ]; + char *sqliteErrorMessage; int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], insertDestinationCallback, NULL, &sqliteErrorMessage); if (sqlResult != SQLITE_OK) { - + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); sqlite3_free(sqliteErrorMessage); } } +- (nullable NSDictionary *)selectDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken { + + NSString *sql = [NSString stringWithFormat: + @"SELECT * FROM destinations WHERE endpoint = '%@' AND access_token = '%@'", + endpoint, + accessToken + ]; + + NSMutableDictionary *result = nil; + + char *sqliteErrorMessage; + NSDictionary *selectedRow = nil; + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], selectDestinationCallback, &result, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } + + return result; +} @@ -196,32 +256,18 @@ - (BOOL)checkIfTableExists_Unknown { - (BOOL)checkIfTableExists:(nonnull NSString *)tableName { - BOOL *answerFlag = nil; - if ([tableName isEqualToString:@"destinations"]) { - answerFlag = &(self->_tableExists_Destinations); - } - else if ([tableName isEqualToString:@"payloads"]) { - answerFlag = &(self->_tableExists_Payloads); - } - else if ([tableName isEqualToString:@"unknown"]) { - answerFlag = &(self->_tableExists_Unknown); - } - else { - return NO; - } - NSString *sql = [NSString stringWithFormat: @"SELECT name FROM sqlite_master WHERE type='table' AND name='%@'", tableName]; char *sqliteErrorMessage; - int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], checkIfTableExistsCallback, answerFlag, &sqliteErrorMessage); + BOOL answerFlag = NO; + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], checkIfTableExistsCallback, &answerFlag, &sqliteErrorMessage); if (sqlResult != SQLITE_OK) { RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); sqlite3_free(sqliteErrorMessage); } - BOOL exists = *answerFlag; - return exists; + return answerFlag; } @end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index b9e2e443..b5f0cbf8 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -48,10 +48,20 @@ - (void)testRepoInitialization { - (void)testInsertDestination { RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; - [repo insertDestinationWithEndpoint:@"EP_0011" andAccesToken:@"AC_001"]; + [repo insertDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct results. + NSDictionary * destination = + [repo selectDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + + XCTAssertTrue([destination.allKeys containsObject:@"id"]); + XCTAssertTrue([destination.allKeys containsObject:@"endpoint"]); + XCTAssertTrue([destination.allKeys containsObject:@"access_token"]); + + XCTAssertTrue([destination.allValues containsObject:@"EP_001"]); + XCTAssertTrue([destination.allValues containsObject:@"AC_001"]); + + XCTAssertTrue([destination[@"endpoint"] isEqualToString:@"EP_001"]); + XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AC_001"]); } - (void)testRepoInitializationPerformance { From 7ca130fb7a2ae6de2f0289617dddbe79d40779b9 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 2 Aug 2022 01:07:53 -0700 Subject: [PATCH 078/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.h | 10 +-- .../RollbarPayloadRepository.m | 67 +++++++++++++++---- .../RollbarPayloadRepositoryTests.m | 35 ++++++++-- 3 files changed, 89 insertions(+), 23 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index 1487927b..dee4c63b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -32,11 +32,13 @@ NS_DESIGNATED_INITIALIZER; - (BOOL)checkIfTableExists_Unknown; -- (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint - andAccesToken:(nonnull NSString *)accessToken; +- (void)addDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken; -- (nullable NSDictionary *)selectDestinationWithEndpoint:(nonnull NSString *)endpoint - andAccesToken:(nonnull NSString *)accessToken; +- (nullable NSDictionary *)getDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken; + +- (nullable NSArray *> *)getAllDestinations; @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 98536b84..48f8b87d 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -37,34 +37,59 @@ static int checkIfTableExistsCallback(void *info, int columns, char **data, char return SQLITE_OK; } -static int insertDestinationCallback(void *info, int columns, char **data, char **column) +static int addDestinationCallback(void *info, int columns, char **data, char **column) { defaultOnSelectCallback(info, columns, data, column); return SQLITE_OK; } -static int selectDestinationCallback(void *info, int columns, char **data, char **column) +static int getDestinationCallback(void *info, int columns, char **data, char **column) { defaultOnSelectCallback(info, columns, data, column); //NSMutableDictionary *row = [NSMutableDictionary dictionaryWithCapacity:columns]; //info = row; - NSMutableDictionary *__strong*result = (NSMutableDictionary *__strong*)info; - *result = [NSMutableDictionary dictionaryWithCapacity:columns]; + NSDictionary *__strong*result = (NSDictionary *__strong*)info; + //*result = [NSMutableDictionary dictionaryWithCapacity:columns]; NSMutableDictionary *row = [NSMutableDictionary dictionaryWithCapacity:columns]; - for (int i = 0; i < columns; i++) { NSString *key = [NSString stringWithFormat:@"%s", column[i]]; NSString *value = [NSString stringWithFormat:@"%s", data[i]]; row[key] = value; } - *result = row; + *result = [row copy]; + + return SQLITE_OK; +} +static int getAllDestinationsCallback(void *info, int columns, char **data, char **column) +{ + defaultOnSelectCallback(info, columns, data, column); + + //NSMutableArray *> *result = nil; + + NSMutableArray *> *__strong*result = + (NSMutableArray *> *__strong*)info; + if (!*result) { + *result = [NSMutableArray *> array]; + } + + NSMutableDictionary *row = + [NSMutableDictionary dictionaryWithCapacity:columns]; + + for (int i = 0; i < columns; i++) { + NSString *key = [NSString stringWithFormat:@"%s", column[i]]; + NSString *value = [NSString stringWithFormat:@"%s", data[i]]; + row[key] = value; + } + + [*result addObject:[row copy]]; + return SQLITE_OK; } @@ -162,7 +187,7 @@ - (void)ensurePayloadsTable { [self executeSql:sql]; } -- (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint +- (void)addDestinationWithEndpoint:(nonnull NSString *)endpoint andAccesToken:(nonnull NSString *)accessToken { NSString *sql = [NSString stringWithFormat: @@ -172,7 +197,7 @@ - (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint ]; char *sqliteErrorMessage; - int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], insertDestinationCallback, NULL, &sqliteErrorMessage); + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], addDestinationCallback, NULL, &sqliteErrorMessage); if (sqlResult != SQLITE_OK) { RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); @@ -180,8 +205,8 @@ - (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint } } -- (nullable NSDictionary *)selectDestinationWithEndpoint:(nonnull NSString *)endpoint - andAccesToken:(nonnull NSString *)accessToken { +- (nullable NSDictionary *)getDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken { NSString *sql = [NSString stringWithFormat: @"SELECT * FROM destinations WHERE endpoint = '%@' AND access_token = '%@'", @@ -189,11 +214,11 @@ - (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint accessToken ]; - NSMutableDictionary *result = nil; + NSDictionary *result = nil; char *sqliteErrorMessage; NSDictionary *selectedRow = nil; - int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], selectDestinationCallback, &result, &sqliteErrorMessage); + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], getDestinationCallback, &result, &sqliteErrorMessage); if (sqlResult != SQLITE_OK) { RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); @@ -203,6 +228,24 @@ - (void)insertDestinationWithEndpoint:(nonnull NSString *)endpoint return result; } +- (nullable NSArray *> *)getAllDestinations { + + NSString *sql = @"SELECT * FROM destinations"; + + NSMutableArray *> *result = nil; + + char *sqliteErrorMessage; + //NSDictionary *selectedRow = nil; + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], getAllDestinationsCallback, &result, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } + + return [result copy]; +} + diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index b5f0cbf8..de11da49 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -40,18 +40,15 @@ - (void)testRepoInitialization { XCTAssertFalse([repo checkIfTableExists_Unknown]); XCTAssertTrue ([repo checkIfTableExists_Destinations]); XCTAssertTrue ([repo checkIfTableExists_Payloads]); - - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct results. } -- (void)testInsertDestination { +- (void)testAddDestination { RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; - [repo insertDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; - NSDictionary * destination = - [repo selectDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + NSDictionary *destination = + [repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; XCTAssertTrue([destination.allKeys containsObject:@"id"]); XCTAssertTrue([destination.allKeys containsObject:@"endpoint"]); @@ -64,6 +61,30 @@ - (void)testInsertDestination { XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AC_001"]); } +- (void)testGetAllDestinations { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_002"]; + + NSArray *> *destinations = + [repo getAllDestinations]; + + XCTAssertEqual(destinations.count, 2); + + for(NSDictionary *destination in destinations) { + + XCTAssertTrue([destination.allKeys containsObject:@"id"]); + XCTAssertTrue([destination.allKeys containsObject:@"endpoint"]); + XCTAssertTrue([destination.allKeys containsObject:@"access_token"]); + + XCTAssertTrue([destination.allValues containsObject:@"EP_001"]); + + XCTAssertTrue([destination[@"endpoint"] isEqualToString:@"EP_001"]); + XCTAssertTrue([destination[@"access_token"] containsString:@"AC_00"]); + } +} + - (void)testRepoInitializationPerformance { [self measureBlock:^{ From 6d684e52c1a5357fa7e5460734f5c5725a956f6b Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 2 Aug 2022 15:17:27 -0700 Subject: [PATCH 079/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.h | 16 ++- .../RollbarPayloadRepository.m | 68 +++++++++++- .../RollbarPayloadRepositoryTests.m | 103 ++++++++++++++++++ 3 files changed, 180 insertions(+), 7 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index dee4c63b..088df11a 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -32,13 +32,23 @@ NS_DESIGNATED_INITIALIZER; - (BOOL)checkIfTableExists_Unknown; -- (void)addDestinationWithEndpoint:(nonnull NSString *)endpoint - andAccesToken:(nonnull NSString *)accessToken; +- (nullable NSDictionary *)addDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken; - (nullable NSDictionary *)getDestinationWithEndpoint:(nonnull NSString *)endpoint andAccesToken:(nonnull NSString *)accessToken; -- (nullable NSArray *> *)getAllDestinations; +- (nullable NSDictionary *)getDestinationByID:(nonnull NSString *)destinationID; + +- (nonnull NSArray *> *)getAllDestinations; + +- (BOOL)removeDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken; + +- (BOOL)removeDestinationByID:(nonnull NSString *)destinationID; + +- (BOOL)removeAllDestinations; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 48f8b87d..4733c2a7 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -187,8 +187,8 @@ - (void)ensurePayloadsTable { [self executeSql:sql]; } -- (void)addDestinationWithEndpoint:(nonnull NSString *)endpoint - andAccesToken:(nonnull NSString *)accessToken { +- (nullable NSDictionary *)addDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken { NSString *sql = [NSString stringWithFormat: @"INSERT INTO destinations (endpoint, access_token) VALUES ('%@', '%@')", @@ -202,7 +202,16 @@ - (void)addDestinationWithEndpoint:(nonnull NSString *)endpoint RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); sqlite3_free(sqliteErrorMessage); + return nil; } + + sqlite3_int64 destinationID = sqlite3_last_insert_rowid(self->_db); + + return @ { + @"id": [NSString stringWithFormat:@"%lli", destinationID], //[NSNumber numberWithLongLong:destinationID], + @"endpoint": endpoint, + @"access_token": accessToken + }; } - (nullable NSDictionary *)getDestinationWithEndpoint:(nonnull NSString *)endpoint @@ -228,7 +237,53 @@ - (void)addDestinationWithEndpoint:(nonnull NSString *)endpoint return result; } -- (nullable NSArray *> *)getAllDestinations { +- (nullable NSDictionary *)getDestinationByID:(nonnull NSString *)destinationID { + + NSString *sql = [NSString stringWithFormat: + @"SELECT * FROM destinations WHERE id = '%@'", + destinationID + ]; + + NSDictionary *result = nil; + + char *sqliteErrorMessage; + NSDictionary *selectedRow = nil; + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], getDestinationCallback, &result, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } + + return result; +} + + + +//int (*callback)(void*,int,char**,char**) +- (NSDictionary *)selectSingleRowWithSql:(NSString *)sql + andCallback:(int(*)(void*,int,char**,char**))callback { + + NSDictionary *result = nil; + char *sqliteErrorMessage; + NSDictionary *selectedRow = nil; + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], callback, &result, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } + + return result; +} + + + + + + + +- (nonnull NSArray *> *)getAllDestinations { NSString *sql = @"SELECT * FROM destinations"; @@ -243,7 +298,12 @@ - (void)addDestinationWithEndpoint:(nonnull NSString *)endpoint sqlite3_free(sqliteErrorMessage); } - return [result copy]; + if (result) { + return [result copy]; + } + else { + return [NSArray *> array]; + } } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index de11da49..1628b1dc 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -31,6 +31,8 @@ - (void)tearDown { [super tearDown]; } +#pragma mark - unit tests + - (void)testRepoInitialization { XCTAssertFalse([RollbarTestUtil checkPayloadsStoreFileExists]); @@ -45,18 +47,57 @@ - (void)testRepoInitialization { - (void)testAddDestination { RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + NSDictionary *destination = [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + + XCTAssertTrue([destination.allKeys containsObject:@"id"]); + XCTAssertTrue([destination.allKeys containsObject:@"endpoint"]); + XCTAssertTrue([destination.allKeys containsObject:@"access_token"]); + + XCTAssertTrue([destination.allValues containsObject:@"EP_001"]); + XCTAssertTrue([destination.allValues containsObject:@"AC_001"]); + + XCTAssertNotNil(destination[@"id"]); + XCTAssertTrue([destination[@"endpoint"] isEqualToString:@"EP_001"]); + XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AC_001"]); +} + +- (void)testGetDestination { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + [self insertDestinationMocks:repo]; NSDictionary *destination = [repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + XCTAssertNotNil(destination); + XCTAssertTrue([destination.allKeys containsObject:@"id"]); XCTAssertTrue([destination.allKeys containsObject:@"endpoint"]); XCTAssertTrue([destination.allKeys containsObject:@"access_token"]); XCTAssertTrue([destination.allValues containsObject:@"EP_001"]); XCTAssertTrue([destination.allValues containsObject:@"AC_001"]); + + XCTAssertTrue([destination[@"endpoint"] isEqualToString:@"EP_001"]); + XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AC_001"]); +} +- (void)testGetDestinationByID { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + [self insertDestinationMocks:repo]; + + NSDictionary *destination = + [repo getDestinationByID:@"0000000000001"]; + + XCTAssertNotNil(destination); + + XCTAssertTrue([destination.allKeys containsObject:@"id"]); + XCTAssertTrue([destination.allKeys containsObject:@"endpoint"]); + XCTAssertTrue([destination.allKeys containsObject:@"access_token"]); + + XCTAssertTrue([destination[@"id"] isEqualToString:@"1"]); XCTAssertTrue([destination[@"endpoint"] isEqualToString:@"EP_001"]); XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AC_001"]); } @@ -70,6 +111,8 @@ - (void)testGetAllDestinations { NSArray *> *destinations = [repo getAllDestinations]; + XCTAssertNotNil(destinations); + XCTAssertEqual(destinations.count, 2); for(NSDictionary *destination in destinations) { @@ -85,6 +128,8 @@ - (void)testGetAllDestinations { } } +#pragma mark - performance tests + - (void)testRepoInitializationPerformance { [self measureBlock:^{ @@ -92,4 +137,62 @@ - (void)testRepoInitializationPerformance { }]; } +- (void)testAddDestinationPerformance { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + + [self measureBlock:^{ + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + }]; +} + +- (void)testGetDestinationPerformance { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + [self insertDestinationMocks:repo]; + XCTAssertNotNil([repo getAllDestinations]); + XCTAssertTrue([repo getAllDestinations].count > 0); + + [self measureBlock:^{ + id result = [repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_009"]; + }]; +} + +- (void)testGetAllDestinationsPerformance { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + [self insertDestinationMocks:repo]; + + NSArray __block *result = nil; + [self measureBlock:^{ + result = [repo getAllDestinations]; + }]; + + XCTAssertNotNil(result); + XCTAssertTrue(result.count > 0); +} + +#pragma mark - mocking helpers + +- (void)insertDestinationMocks:(RollbarPayloadRepository *)repo { + + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_002"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_003"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_004"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_005"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_006"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_007"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_008"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_009"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_010"]; + + [repo addDestinationWithEndpoint:@"EP_002" andAccesToken:@"AC_001"]; + [repo addDestinationWithEndpoint:@"EP_003" andAccesToken:@"AC_001"]; + [repo addDestinationWithEndpoint:@"EP_004" andAccesToken:@"AC_001"]; + [repo addDestinationWithEndpoint:@"EP_005" andAccesToken:@"AC_001"]; +} + @end From bf00b979846807fc823a318a70d075a39740b18b Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 2 Aug 2022 16:23:44 -0700 Subject: [PATCH 080/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.m | 128 ++++++++---------- .../RollbarPayloadRepositoryTests.m | 3 + 2 files changed, 58 insertions(+), 73 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 4733c2a7..2bfbac5e 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -223,16 +223,8 @@ - (void)ensurePayloadsTable { accessToken ]; - NSDictionary *result = nil; - - char *sqliteErrorMessage; - NSDictionary *selectedRow = nil; - int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], getDestinationCallback, &result, &sqliteErrorMessage); - if (sqlResult != SQLITE_OK) { - - RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); - sqlite3_free(sqliteErrorMessage); - } + NSDictionary *result = + [self selectSingleRowWithSql:sql andCallback:getDestinationCallback]; return result; } @@ -244,66 +236,19 @@ - (void)ensurePayloadsTable { destinationID ]; - NSDictionary *result = nil; - - char *sqliteErrorMessage; - NSDictionary *selectedRow = nil; - int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], getDestinationCallback, &result, &sqliteErrorMessage); - if (sqlResult != SQLITE_OK) { - - RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); - sqlite3_free(sqliteErrorMessage); - } - - return result; -} - - - -//int (*callback)(void*,int,char**,char**) -- (NSDictionary *)selectSingleRowWithSql:(NSString *)sql - andCallback:(int(*)(void*,int,char**,char**))callback { - - NSDictionary *result = nil; - char *sqliteErrorMessage; - NSDictionary *selectedRow = nil; - int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], callback, &result, &sqliteErrorMessage); - if (sqlResult != SQLITE_OK) { - - RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); - sqlite3_free(sqliteErrorMessage); - } + NSDictionary *result = + [self selectSingleRowWithSql:sql andCallback:getDestinationCallback]; return result; } - - - - - - - (nonnull NSArray *> *)getAllDestinations { NSString *sql = @"SELECT * FROM destinations"; - NSMutableArray *> *result = nil; - - char *sqliteErrorMessage; - //NSDictionary *selectedRow = nil; - int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], getAllDestinationsCallback, &result, &sqliteErrorMessage); - if (sqlResult != SQLITE_OK) { - - RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); - sqlite3_free(sqliteErrorMessage); - } - - if (result) { - return [result copy]; - } - else { - return [NSArray *> array]; - } + NSArray *> *result = + [self selectMultipleRowsWithSql:sql andCallback:getAllDestinationsCallback]; + return result; } @@ -327,17 +272,6 @@ - (void)clearPayloadsTable { - (void)clearPayloadsOlderThan:(nonnull NSDate *)cutoffTime { } -- (void)executeSql:(nonnull NSString *)sql { - - char *sqliteErrorMessage; - int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], NULL, NULL, &sqliteErrorMessage); - if (sqlResult != SQLITE_OK) { - - RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); - sqlite3_free(sqliteErrorMessage); - } -} - - (BOOL)checkIfTableExists_Destinations { BOOL result = [self checkIfTableExists:@"destinations"]; @@ -373,4 +307,52 @@ - (BOOL)checkIfTableExists:(nonnull NSString *)tableName { return answerFlag; } +- (void)executeSql:(nonnull NSString *)sql { + + char *sqliteErrorMessage; + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], NULL, NULL, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } +} + +- (nullable NSDictionary *)selectSingleRowWithSql:(NSString *)sql + andCallback:(int(*)(void*,int,char**,char**))callback { + + NSDictionary *result = nil; + char *sqliteErrorMessage; + NSDictionary *selectedRow = nil; + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], callback, &result, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } + + return result; +} + +- (nonnull NSArray *> *)selectMultipleRowsWithSql:(NSString *)sql + andCallback:(int(*)(void*,int,char**,char**))callback { + + NSMutableArray *> *result = nil; + + char *sqliteErrorMessage; + int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], callback, &result, &sqliteErrorMessage); + if (sqlResult != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); + sqlite3_free(sqliteErrorMessage); + } + + if (result) { + return [result copy]; + } + else { + return [NSArray *> array]; + } +} + @end diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index 1628b1dc..acfa283b 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -140,9 +140,12 @@ - (void)testRepoInitializationPerformance { - (void)testAddDestinationPerformance { RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); [self measureBlock:^{ [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + + //TODO: clear the destinations table... }]; } From 200f74b88872403cf05a5060d80b1c48b08e3ebf Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 2 Aug 2022 16:30:43 -0700 Subject: [PATCH 081/127] feat: RollbarPayloadRepository --- .../RollbarNotifier/RollbarPayloadRepository.m | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 2bfbac5e..e03bd23e 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -44,14 +44,11 @@ static int addDestinationCallback(void *info, int columns, char **data, char **c return SQLITE_OK; } -static int getDestinationCallback(void *info, int columns, char **data, char **column) +static int selectSingleRowCallback(void *info, int columns, char **data, char **column) { defaultOnSelectCallback(info, columns, data, column); - //NSMutableDictionary *row = [NSMutableDictionary dictionaryWithCapacity:columns]; - //info = row; NSDictionary *__strong*result = (NSDictionary *__strong*)info; - //*result = [NSMutableDictionary dictionaryWithCapacity:columns]; NSMutableDictionary *row = [NSMutableDictionary dictionaryWithCapacity:columns]; @@ -67,12 +64,10 @@ static int getDestinationCallback(void *info, int columns, char **data, char **c return SQLITE_OK; } -static int getAllDestinationsCallback(void *info, int columns, char **data, char **column) +static int selectMultipleRowsCallback(void *info, int columns, char **data, char **column) { defaultOnSelectCallback(info, columns, data, column); - //NSMutableArray *> *result = nil; - NSMutableArray *> *__strong*result = (NSMutableArray *> *__strong*)info; if (!*result) { @@ -224,7 +219,7 @@ - (void)ensurePayloadsTable { ]; NSDictionary *result = - [self selectSingleRowWithSql:sql andCallback:getDestinationCallback]; + [self selectSingleRowWithSql:sql andCallback:selectSingleRowCallback]; return result; } @@ -237,7 +232,7 @@ - (void)ensurePayloadsTable { ]; NSDictionary *result = - [self selectSingleRowWithSql:sql andCallback:getDestinationCallback]; + [self selectSingleRowWithSql:sql andCallback:selectSingleRowCallback]; return result; } @@ -247,7 +242,7 @@ - (void)ensurePayloadsTable { NSString *sql = @"SELECT * FROM destinations"; NSArray *> *result = - [self selectMultipleRowsWithSql:sql andCallback:getAllDestinationsCallback]; + [self selectMultipleRowsWithSql:sql andCallback:selectMultipleRowsCallback]; return result; } From b8da63de41ed3344295ce8b1e6beaa9ed3fcd82a Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 2 Aug 2022 16:46:29 -0700 Subject: [PATCH 082/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.m | 58 ++++++++++++------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index e03bd23e..200a4638 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -37,13 +37,6 @@ static int checkIfTableExistsCallback(void *info, int columns, char **data, char return SQLITE_OK; } -static int addDestinationCallback(void *info, int columns, char **data, char **column) -{ - defaultOnSelectCallback(info, columns, data, column); - - return SQLITE_OK; -} - static int selectSingleRowCallback(void *info, int columns, char **data, char **column) { defaultOnSelectCallback(info, columns, data, column); @@ -155,31 +148,33 @@ - (void)initDB { [self ensurePayloadsTable]; } -- (void)openDB { +- (BOOL)openDB { int result = sqlite3_open([self->_storePath UTF8String], &self->_db); if (result != SQLITE_OK) { RollbarSdkLog(@"sqlite3_open: %s", sqlite3_errmsg(self->_db)); + return NO; } + return YES; } -- (void)ensureDestinationsTable { +- (BOOL)ensureDestinationsTable { NSString *sql = [NSString stringWithFormat: @"CREATE TABLE IF NOT EXISTS destinations (id INTEGER NOT NULL PRIMARY KEY, endpoint TEXT NOT NULL, access_token TEXT NOT NULL, CONSTRAINT unique_destination UNIQUE(endpoint, access_token))" ]; - [self executeSql:sql]; + return [self executeSql:sql]; } -- (void)ensurePayloadsTable { +- (BOOL)ensurePayloadsTable { NSString *sql = [NSString stringWithFormat: @"CREATE TABLE IF NOT EXISTS payloads (id INTEGER NOT NULL PRIMARY KEY, config_json TEXT NOT NULL, payload_json TEXT NOT NULL, created_at INTEGER NOT NULL, destination_key INTEGER NOT NULL, FOREIGN KEY(destination_key) REFERENCES destinations(id) ON UPDATE CASCADE ON DELETE CASCADE)" ]; - [self executeSql:sql]; + return [self executeSql:sql]; } - (nullable NSDictionary *)addDestinationWithEndpoint:(nonnull NSString *)endpoint @@ -190,13 +185,8 @@ - (void)ensurePayloadsTable { endpoint, accessToken ]; - - char *sqliteErrorMessage; - int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], addDestinationCallback, NULL, &sqliteErrorMessage); - if (sqlResult != SQLITE_OK) { - - RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); - sqlite3_free(sqliteErrorMessage); + + if (NO == [self executeSql:sql]) { return nil; } @@ -249,6 +239,32 @@ - (void)ensurePayloadsTable { +- (BOOL)removeDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken { + + //TODO: implement... + NSString *sql = [NSString stringWithFormat: + @"CREATE TABLE IF NOT EXISTS destinations (id INTEGER NOT NULL PRIMARY KEY, endpoint TEXT NOT NULL, access_token TEXT NOT NULL, CONSTRAINT unique_destination UNIQUE(endpoint, access_token))" + ]; + return [self executeSql:sql]; +} + +- (BOOL)removeDestinationByID:(nonnull NSString *)destinationID { + + //TODO: implement... + return NO; +} + +- (BOOL)removeAllDestinations { + + //TODO: implement... + return NO; +} + + + + + @@ -302,7 +318,7 @@ - (BOOL)checkIfTableExists:(nonnull NSString *)tableName { return answerFlag; } -- (void)executeSql:(nonnull NSString *)sql { +- (BOOL)executeSql:(nonnull NSString *)sql { char *sqliteErrorMessage; int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], NULL, NULL, &sqliteErrorMessage); @@ -310,7 +326,9 @@ - (void)executeSql:(nonnull NSString *)sql { RollbarSdkLog(@"sqlite3_exec: %s during %@", sqliteErrorMessage, sql); sqlite3_free(sqliteErrorMessage); + return NO; } + return YES; } - (nullable NSDictionary *)selectSingleRowWithSql:(NSString *)sql From f711c0f602b25ec9fb655ff9fb7e67db8a11c0c3 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 3 Aug 2022 16:52:43 -0700 Subject: [PATCH 083/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.h | 2 + .../RollbarPayloadRepository.m | 26 +++-- .../RollbarPayloadRepositoryTests.m | 108 +++++++++++++----- 3 files changed, 97 insertions(+), 39 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index 088df11a..ef95e0cd 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -47,6 +47,8 @@ NS_DESIGNATED_INITIALIZER; - (BOOL)removeDestinationByID:(nonnull NSString *)destinationID; +- (BOOL)removeUnusedDestinations; + - (BOOL)removeAllDestinations; @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 200a4638..39875c18 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -236,29 +236,35 @@ - (BOOL)ensurePayloadsTable { return result; } - - - - (BOOL)removeDestinationWithEndpoint:(nonnull NSString *)endpoint andAccesToken:(nonnull NSString *)accessToken { - //TODO: implement... - NSString *sql = [NSString stringWithFormat: - @"CREATE TABLE IF NOT EXISTS destinations (id INTEGER NOT NULL PRIMARY KEY, endpoint TEXT NOT NULL, access_token TEXT NOT NULL, CONSTRAINT unique_destination UNIQUE(endpoint, access_token))" + NSString *sql = + [NSString stringWithFormat: @"DELETE FROM destinations WHERE endpoint = '%@' AND access_token = '%@'", + endpoint, + accessToken ]; return [self executeSql:sql]; } - (BOOL)removeDestinationByID:(nonnull NSString *)destinationID { - //TODO: implement... - return NO; + NSString *sql = + [NSString stringWithFormat: @"DELETE FROM destinations WHERE id = '%@'", destinationID]; + return [self executeSql:sql]; +} + +- (BOOL)removeUnusedDestinations { + + NSString *sql = + @"DELETE FROM destinations WHERE NOT EXISTS (SELECT 1 FROM payloads WHERE payloads.destination_key = destinations.id)"; + return [self executeSql:sql]; } - (BOOL)removeAllDestinations { - //TODO: implement... - return NO; + NSString *sql = @"DELETE FROM destinations"; + return [self executeSql:sql]; } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index acfa283b..c1f59e21 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -48,18 +48,18 @@ - (void)testAddDestination { RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; NSDictionary *destination = - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_001"]; XCTAssertTrue([destination.allKeys containsObject:@"id"]); XCTAssertTrue([destination.allKeys containsObject:@"endpoint"]); XCTAssertTrue([destination.allKeys containsObject:@"access_token"]); XCTAssertTrue([destination.allValues containsObject:@"EP_001"]); - XCTAssertTrue([destination.allValues containsObject:@"AC_001"]); + XCTAssertTrue([destination.allValues containsObject:@"AT_001"]); XCTAssertNotNil(destination[@"id"]); XCTAssertTrue([destination[@"endpoint"] isEqualToString:@"EP_001"]); - XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AC_001"]); + XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AT_001"]); } - (void)testGetDestination { @@ -68,7 +68,7 @@ - (void)testGetDestination { [self insertDestinationMocks:repo]; NSDictionary *destination = - [repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + [repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_001"]; XCTAssertNotNil(destination); @@ -77,10 +77,10 @@ - (void)testGetDestination { XCTAssertTrue([destination.allKeys containsObject:@"access_token"]); XCTAssertTrue([destination.allValues containsObject:@"EP_001"]); - XCTAssertTrue([destination.allValues containsObject:@"AC_001"]); + XCTAssertTrue([destination.allValues containsObject:@"AT_001"]); XCTAssertTrue([destination[@"endpoint"] isEqualToString:@"EP_001"]); - XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AC_001"]); + XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AT_001"]); } - (void)testGetDestinationByID { @@ -99,14 +99,14 @@ - (void)testGetDestinationByID { XCTAssertTrue([destination[@"id"] isEqualToString:@"1"]); XCTAssertTrue([destination[@"endpoint"] isEqualToString:@"EP_001"]); - XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AC_001"]); + XCTAssertTrue([destination[@"access_token"] isEqualToString:@"AT_001"]); } - (void)testGetAllDestinations { RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_002"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_001"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_002"]; NSArray *> *destinations = [repo getAllDestinations]; @@ -124,28 +124,76 @@ - (void)testGetAllDestinations { XCTAssertTrue([destination.allValues containsObject:@"EP_001"]); XCTAssertTrue([destination[@"endpoint"] isEqualToString:@"EP_001"]); - XCTAssertTrue([destination[@"access_token"] containsString:@"AC_00"]); + XCTAssertTrue([destination[@"access_token"] containsString:@"AT_00"]); } } +- (void)testDestinationRemovals { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + [self insertDestinationMocks:repo]; + + int removedCount = 0; + int initialCount = [repo getAllDestinations].count; + + XCTAssertEqual(YES, [repo removeDestinationByID:@"0001"]); + removedCount++; + XCTAssertEqual(initialCount - removedCount, [repo getAllDestinations].count); + + XCTAssertEqual(YES, [repo removeDestinationByID:@"0001"]); + //removedCount++; + XCTAssertEqual(initialCount - removedCount, [repo getAllDestinations].count); + + XCTAssertEqual(YES, [repo removeDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_007"]); + removedCount++; + XCTAssertEqual(initialCount - removedCount, [repo getAllDestinations].count); + + XCTAssertEqual(YES, [repo removeDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_007"]); + //removedCount++; + XCTAssertEqual(initialCount - removedCount, [repo getAllDestinations].count); + + XCTAssertEqual(YES, [repo removeUnusedDestinations]); + removedCount = initialCount; + XCTAssertEqual(initialCount - removedCount, [repo getAllDestinations].count); + + XCTAssertEqual(YES, [repo removeAllDestinations]); + removedCount = initialCount; + XCTAssertEqual(initialCount - removedCount, [repo getAllDestinations].count); +} + #pragma mark - performance tests - (void)testRepoInitializationPerformance { [self measureBlock:^{ + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; }]; } -- (void)testAddDestinationPerformance { +- (void)testAddRemoveDestinationPerformance { RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; XCTAssertTrue(0 == [repo getAllDestinations].count); [self measureBlock:^{ - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; + + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_001"]; - //TODO: clear the destinations table... + [repo removeDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_001"]; + }]; +} + +- (void)testAddRemoveDestinationByIDPerformance { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + + [self measureBlock:^{ + + NSDictionary *destinationRow = [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_001"]; + + [repo removeDestinationByID:destinationRow[@"id"]]; }]; } @@ -158,7 +206,8 @@ - (void)testGetDestinationPerformance { XCTAssertTrue([repo getAllDestinations].count > 0); [self measureBlock:^{ - id result = [repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_009"]; + + id result = [repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_009"]; }]; } @@ -170,6 +219,7 @@ - (void)testGetAllDestinationsPerformance { NSArray __block *result = nil; [self measureBlock:^{ + result = [repo getAllDestinations]; }]; @@ -181,21 +231,21 @@ - (void)testGetAllDestinationsPerformance { - (void)insertDestinationMocks:(RollbarPayloadRepository *)repo { - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_001"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_002"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_003"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_004"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_005"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_006"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_007"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_008"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_009"]; - [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AC_010"]; - - [repo addDestinationWithEndpoint:@"EP_002" andAccesToken:@"AC_001"]; - [repo addDestinationWithEndpoint:@"EP_003" andAccesToken:@"AC_001"]; - [repo addDestinationWithEndpoint:@"EP_004" andAccesToken:@"AC_001"]; - [repo addDestinationWithEndpoint:@"EP_005" andAccesToken:@"AC_001"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_001"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_002"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_003"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_004"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_005"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_006"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_007"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_008"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_009"]; + [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_010"]; + + [repo addDestinationWithEndpoint:@"EP_002" andAccesToken:@"AT_001"]; + [repo addDestinationWithEndpoint:@"EP_003" andAccesToken:@"AT_001"]; + [repo addDestinationWithEndpoint:@"EP_004" andAccesToken:@"AT_001"]; + [repo addDestinationWithEndpoint:@"EP_005" andAccesToken:@"AT_001"]; } @end From 7a17d2b0d6e431a5d77965a2783f16f8727cb168 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 3 Aug 2022 20:39:39 -0700 Subject: [PATCH 084/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.h | 51 +++-- .../RollbarPayloadRepository.m | 212 +++++++++++++----- .../RollbarPayloadRepositoryTests.m | 31 ++- 3 files changed, 227 insertions(+), 67 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index ef95e0cd..a8ba348c 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -13,24 +13,12 @@ NS_ASSUME_NONNULL_BEGIN @interface RollbarPayloadRepository : NSObject -#pragma mark - repository methods - -- (void)clear; - -- (void)addPayload:(nonnull RollbarPayload *)payload; - #pragma mark - instance initializers - (instancetype)initWithStore:(nonnull NSString *)storePath NS_DESIGNATED_INITIALIZER; -#pragma mark - unit testing helper methods - -- (BOOL)checkIfTableExists_Destinations; - -- (BOOL)checkIfTableExists_Payloads; - -- (BOOL)checkIfTableExists_Unknown; +#pragma mark - Destinations related methods - (nullable NSDictionary *)addDestinationWithEndpoint:(nonnull NSString *)endpoint andAccesToken:(nonnull NSString *)accessToken; @@ -51,6 +39,43 @@ NS_DESIGNATED_INITIALIZER; - (BOOL)removeAllDestinations; +#pragma mark - Payloads related methods + +- (nullable NSDictionary *)addPayload:(nonnull NSString *)payload + withConfig:(nonnull NSString *)config + andDestinationID:(nonnull NSString *)destinationID; + +- (nullable NSDictionary *)getPayloadByID:(nonnull NSString *)payloadID; + +- (nonnull NSArray *> *)getAllPayloadsWithDestinationID:(nonnull NSString *)destinationID; + +- (nonnull NSArray *> *)getPayloadsWithLimit:(NSUInteger)limit; + +- (nonnull NSArray *> *)getPayloadsWithOffset:(NSUInteger)offset + andLimit:(NSUInteger)limit; + +- (nonnull NSArray *> *)getAllPayloads; + +- (BOOL)removePayloadByID:(nonnull NSString *)payloadID; + +- (BOOL)removePayloadsOlderThan:(nonnull NSDate *)cutoffTime; + +- (BOOL)removeAllPayloads; + +#pragma mark - unit testing helper methods + +- (BOOL)checkIfTableExists_Destinations; + +- (BOOL)checkIfTableExists_Payloads; + +- (BOOL)checkIfTableExists_Unknown; + +- (BOOL)clearDestinations; + +- (BOOL)clearPayloads; + +- (BOOL)clear; + @end NS_ASSUME_NONNULL_END diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 39875c18..fa2abb06 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -129,53 +129,8 @@ - (instancetype)init { return nil; } -#pragma mark - repository methods +#pragma mark - Destinations related methods -- (void)addPayload:(nonnull RollbarPayload *)payload { - -} - -- (void)clear { - -} - -#pragma mark - internal methods - -- (void)initDB { - - [self openDB]; - [self ensureDestinationsTable]; - [self ensurePayloadsTable]; -} - -- (BOOL)openDB { - - int result = sqlite3_open([self->_storePath UTF8String], &self->_db); - if (result != SQLITE_OK) { - - RollbarSdkLog(@"sqlite3_open: %s", sqlite3_errmsg(self->_db)); - return NO; - } - return YES; -} - -- (BOOL)ensureDestinationsTable { - - NSString *sql = [NSString stringWithFormat: - @"CREATE TABLE IF NOT EXISTS destinations (id INTEGER NOT NULL PRIMARY KEY, endpoint TEXT NOT NULL, access_token TEXT NOT NULL, CONSTRAINT unique_destination UNIQUE(endpoint, access_token))" - ]; - return [self executeSql:sql]; -} - -- (BOOL)ensurePayloadsTable { - - - - NSString *sql = [NSString stringWithFormat: - @"CREATE TABLE IF NOT EXISTS payloads (id INTEGER NOT NULL PRIMARY KEY, config_json TEXT NOT NULL, payload_json TEXT NOT NULL, created_at INTEGER NOT NULL, destination_key INTEGER NOT NULL, FOREIGN KEY(destination_key) REFERENCES destinations(id) ON UPDATE CASCADE ON DELETE CASCADE)" - ]; - return [self executeSql:sql]; -} - (nullable NSDictionary *)addDestinationWithEndpoint:(nonnull NSString *)endpoint andAccesToken:(nonnull NSString *)accessToken { @@ -233,6 +188,7 @@ - (BOOL)ensurePayloadsTable { NSArray *> *result = [self selectMultipleRowsWithSql:sql andCallback:selectMultipleRowsCallback]; + return result; } @@ -244,6 +200,7 @@ - (BOOL)removeDestinationWithEndpoint:(nonnull NSString *)endpoint endpoint, accessToken ]; + return [self executeSql:sql]; } @@ -251,6 +208,7 @@ - (BOOL)removeDestinationByID:(nonnull NSString *)destinationID { NSString *sql = [NSString stringWithFormat: @"DELETE FROM destinations WHERE id = '%@'", destinationID]; + return [self executeSql:sql]; } @@ -267,28 +225,116 @@ - (BOOL)removeAllDestinations { return [self executeSql:sql]; } +#pragma mark - Payloads related methods + +- (nullable NSDictionary *)addPayload:(nonnull NSString *)payload + withConfig:(nonnull NSString *)config + andDestinationID:(nonnull NSString *)destinationID { + + NSNumber *timeStamp = [NSNumber numberWithInteger:[[NSDate date] timeIntervalSince1970]]; + + NSString *sql = [NSString stringWithFormat: + @"INSERT INTO payloads (config_json, payload_json, destination_key, created_at) VALUES ('%@', '%@', '%@', '%ld')", + config, + payload, + destinationID, + [timeStamp integerValue] + ]; + + if (NO == [self executeSql:sql]) { + return nil; + } + + sqlite3_int64 payloadID = sqlite3_last_insert_rowid(self->_db); + + return @ { + @"id": [NSString stringWithFormat:@"%lli", payloadID], //[NSNumber numberWithLongLong:destinationID], + @"config_json": config, + @"payload_json": payload, + @"destination_id": destinationID + }; +} + +- (nullable NSDictionary *)getPayloadByID:(nonnull NSString *)payloadID { + NSString *sql = [NSString stringWithFormat: + @"SELECT * FROM payloads WHERE id = '%@'", + payloadID + ]; + + NSDictionary *result = + [self selectSingleRowWithSql:sql andCallback:selectSingleRowCallback]; + + return result; +} +- (nonnull NSArray *> *)getAllPayloadsWithDestinationID:(nonnull NSString *)destinationID { + + NSString *sql = [NSString stringWithFormat: + @"SELECT * FROM payloads WHERE destination_id = '%@'", + destinationID + ]; + NSArray *> *result = + [self selectMultipleRowsWithSql:sql andCallback:selectMultipleRowsCallback]; + + return result; +} +- (nonnull NSArray *> *)getPayloadsWithLimit:(NSUInteger)limit { + return [self getPayloadsWithOffset:0 andLimit:limit]; +} +- (nonnull NSArray *> *)getPayloadsWithOffset:(NSUInteger)offset + andLimit:(NSUInteger)limit { -- (void)releaseDB { + NSString *sql = [NSString stringWithFormat: + @"SELECT * FROM payloads OFFSET '%lu' LIMIT '%lu'", + offset, + limit + ]; - sqlite3_close(self->_db); - self->_db = nil; + NSArray *> *result = + [self selectMultipleRowsWithSql:sql andCallback:selectMultipleRowsCallback]; + + return result; } -- (void)clearDestinationsTable { +- (nonnull NSArray *> *)getAllPayloads { + + NSString *sql = @"SELECT * FROM payloads"; + + NSArray *> *result = + [self selectMultipleRowsWithSql:sql andCallback:selectMultipleRowsCallback]; + + return result; } -- (void)clearPayloadsTable { +- (BOOL)removePayloadByID:(nonnull NSString *)payloadID { + + NSString *sql = + [NSString stringWithFormat: @"DELETE FROM payloads WHERE id = '%@'", payloadID]; + + return [self executeSql:sql]; } -- (void)clearPayloadsOlderThan:(nonnull NSDate *)cutoffTime { +- (BOOL)removePayloadsOlderThan:(nonnull NSDate *)cutoffTime { + + NSNumber *threshold = [NSNumber numberWithInteger:[cutoffTime timeIntervalSince1970]]; + + NSString *sql = [NSString stringWithFormat:@"DELETE FROM payloads WHERE created_at <= '%lu'", [threshold integerValue]]; + return [self executeSql:sql]; +} + +- (BOOL)removeAllPayloads { + + NSString *sql = @"DELETE FROM payloads"; + return [self executeSql:sql]; } +#pragma mark - unit testing helper methods + - (BOOL)checkIfTableExists_Destinations { BOOL result = [self checkIfTableExists:@"destinations"]; @@ -307,6 +353,68 @@ - (BOOL)checkIfTableExists_Unknown { return result; } +- (BOOL)clearDestinations; { + + return [self removeAllDestinations]; +} + +- (BOOL)clearPayloads { + + return [self removeAllPayloads]; +} + +- (BOOL)clear { + + BOOL success = [self clearPayloads]; + if (success) { + success = [self clearDestinations]; + } + return success; +} + +#pragma mark - internal methods + +- (void)initDB { + + [self openDB]; + [self ensureDestinationsTable]; + [self ensurePayloadsTable]; +} + +- (BOOL)openDB { + + int result = sqlite3_open([self->_storePath UTF8String], &self->_db); + if (result != SQLITE_OK) { + + RollbarSdkLog(@"sqlite3_open: %s", sqlite3_errmsg(self->_db)); + return NO; + } + return YES; +} + +- (BOOL)ensureDestinationsTable { + + NSString *sql = [NSString stringWithFormat: + @"CREATE TABLE IF NOT EXISTS destinations (id INTEGER NOT NULL PRIMARY KEY, endpoint TEXT NOT NULL, access_token TEXT NOT NULL, CONSTRAINT unique_destination UNIQUE(endpoint, access_token))" + ]; + return [self executeSql:sql]; +} + +- (BOOL)ensurePayloadsTable { + + + + NSString *sql = [NSString stringWithFormat: + @"CREATE TABLE IF NOT EXISTS payloads (id INTEGER NOT NULL PRIMARY KEY, config_json TEXT NOT NULL, payload_json TEXT NOT NULL, created_at INTEGER NOT NULL, destination_key INTEGER NOT NULL, FOREIGN KEY(destination_key) REFERENCES destinations(id) ON UPDATE CASCADE ON DELETE CASCADE)" + ]; + return [self executeSql:sql]; +} + +- (void)releaseDB { + + sqlite3_close(self->_db); + self->_db = nil; +} - (BOOL)checkIfTableExists:(nonnull NSString *)tableName { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index c1f59e21..4a087b26 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -31,7 +31,7 @@ - (void)tearDown { [super tearDown]; } -#pragma mark - unit tests +#pragma mark - Destinations unit tests - (void)testRepoInitialization { @@ -161,7 +161,7 @@ - (void)testDestinationRemovals { XCTAssertEqual(initialCount - removedCount, [repo getAllDestinations].count); } -#pragma mark - performance tests +#pragma mark - Destinations performance tests - (void)testRepoInitializationPerformance { @@ -227,6 +227,33 @@ - (void)testGetAllDestinationsPerformance { XCTAssertTrue(result.count > 0); } + + + +#pragma mark - Payloads unit tests + +- (void)testTimestamp { + + NSDate *cutoffTime = [NSDate date]; + NSNumber *threshold = [NSNumber numberWithInteger:[cutoffTime timeIntervalSince1970]]; + + RollbarSdkLog(@"*** Removing payloads older than: %@ (%@)", + cutoffTime, + [NSDate dateWithTimeIntervalSince1970:[threshold integerValue]] + ); + +} + +//TODO: implement... + +#pragma mark - Payloads performance tests +//TODO: implement... + + + + + + #pragma mark - mocking helpers - (void)insertDestinationMocks:(RollbarPayloadRepository *)repo { From b307b7f2c9b41fa732ae192b31899296a978f8ce Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 4 Aug 2022 14:39:59 -0700 Subject: [PATCH 085/127] fix: possible nil handling within NSJSONSerialization (Rollbar) --- .../Sources/RollbarCommon/NSJSONSerialization+Rollbar.m | 3 +++ 1 file changed, 3 insertions(+) diff --git a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m index 542d9b89..5c099be9 100644 --- a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m +++ b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m @@ -51,6 +51,9 @@ + (nonnull NSMutableDictionary *)rollbar_safeDataFromJSONObject:(nullable id)obj [obj enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { + // Defensive failsafe to avoid exceptions when trying to create dictionary literal with nil `obj` + obj = obj ?: [NSNull null]; + if ([obj isKindOfClass:[NSDictionary class]]) { [safeData setObject:[[self class] rollbar_safeDataFromJSONObject:obj] forKey:key]; From 3179590194ea956a338efe19d6bb8d771b972be7 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Sat, 6 Aug 2022 02:38:51 -0700 Subject: [PATCH 086/127] feat: RollbarPayloadRepository feat: A new feature fix: A bug fix docs: Documentation only changes style: Changes that do not affect the meaning of the code refactor: A code change that neither a bug fix nor a new feature perf: A code change that improves performance test: Adding or modifying unit test code chore: Changes to the build process or auxiliary tools and libraries such as documentation generation, etc. --- .../RollbarPayloadRepository.m | 18 +-- .../RollbarPayloadRepositoryTests.m | 132 +++++++++++++++++- 2 files changed, 138 insertions(+), 12 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index fa2abb06..7ce96024 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -251,7 +251,7 @@ - (BOOL)removeAllDestinations { @"id": [NSString stringWithFormat:@"%lli", payloadID], //[NSNumber numberWithLongLong:destinationID], @"config_json": config, @"payload_json": payload, - @"destination_id": destinationID + @"destination_key": destinationID }; } @@ -271,7 +271,7 @@ - (BOOL)removeAllDestinations { - (nonnull NSArray *> *)getAllPayloadsWithDestinationID:(nonnull NSString *)destinationID { NSString *sql = [NSString stringWithFormat: - @"SELECT * FROM payloads WHERE destination_id = '%@'", + @"SELECT * FROM payloads WHERE destination_key = '%@'", destinationID ]; @@ -289,11 +289,8 @@ - (BOOL)removeAllDestinations { - (nonnull NSArray *> *)getPayloadsWithOffset:(NSUInteger)offset andLimit:(NSUInteger)limit { - NSString *sql = [NSString stringWithFormat: - @"SELECT * FROM payloads OFFSET '%lu' LIMIT '%lu'", - offset, - limit - ]; + NSString *sql = + [NSString stringWithFormat:@"SELECT * FROM payloads LIMIT %lu OFFSET %lu", limit, offset]; NSArray *> *result = [self selectMultipleRowsWithSql:sql andCallback:selectMultipleRowsCallback]; @@ -321,9 +318,12 @@ - (BOOL)removePayloadByID:(nonnull NSString *)payloadID { - (BOOL)removePayloadsOlderThan:(nonnull NSDate *)cutoffTime { - NSNumber *threshold = [NSNumber numberWithInteger:[cutoffTime timeIntervalSince1970]]; + NSTimeInterval interval = [cutoffTime timeIntervalSince1970]; - NSString *sql = [NSString stringWithFormat:@"DELETE FROM payloads WHERE created_at <= '%lu'", [threshold integerValue]]; + NSString *sql = [NSString stringWithFormat: + @"DELETE FROM payloads WHERE created_at <= '%li'", + (long int)interval + ]; return [self executeSql:sql]; } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index 4a087b26..c0ba5616 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -232,19 +232,120 @@ - (void)testGetAllDestinationsPerformance { #pragma mark - Payloads unit tests -- (void)testTimestamp { +- (void)testTimestampCalculations { NSDate *cutoffTime = [NSDate date]; - NSNumber *threshold = [NSNumber numberWithInteger:[cutoffTime timeIntervalSince1970]]; + NSNumber *threshold = [NSNumber numberWithInteger:cutoffTime.timeIntervalSince1970]; RollbarSdkLog(@"*** Removing payloads older than: %@ (%@)", cutoffTime, [NSDate dateWithTimeIntervalSince1970:[threshold integerValue]] ); + XCTAssertTrue((cutoffTime.timeIntervalSince1970 - threshold.doubleValue) < 1.0); +} +- (void)testAddGetRemovePayload { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + [self insertDestinationMocks:repo]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + + XCTAssertEqual(0, [repo getAllPayloads].count); + + XCTAssertNil([repo getPayloadByID:@"0001"]); + NSDictionary *dataFields = + [repo addPayload:@"PL_001" + withConfig:@"C_001" + andDestinationID:[repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_005"][@"id"] + ]; + XCTAssertEqual(1, [repo getAllPayloads].count); + NSDictionary *dataFields1 = [repo getPayloadByID:dataFields[@"id"]]; + XCTAssertNotNil(dataFields1); + XCTAssertEqual(5, dataFields1.count); + XCTAssertTrue([dataFields[@"id"] isEqualToString:dataFields1[@"id"]]); + XCTAssertTrue([dataFields[@"payload_json"] isEqualToString:dataFields1[@"payload_json"]]); + XCTAssertTrue([dataFields[@"config_json"] isEqualToString:dataFields1[@"config_json"]]); + + [repo removePayloadByID:dataFields[@"id"]]; + XCTAssertNil([repo getPayloadByID:dataFields[@"id"]]); + XCTAssertEqual(0, [repo getAllPayloads].count); } -//TODO: implement... +- (void)testGetAllPayloads { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + XCTAssertTrue(0 < [repo getAllPayloads].count); +} + +- (void)testRemoveAllPayloads { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + XCTAssertTrue(0 < [repo getAllPayloads].count); + [repo removeAllPayloads]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); +} + +- (void)testRemoveOldPayloads { + + NSDate *cutoffTime = [NSDate date]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + XCTAssertTrue(0 < [repo getAllPayloads].count); + [repo removePayloadsOlderThan:[NSDate distantPast]]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + XCTAssertEqual(4, [repo getAllPayloads].count); + [repo removePayloadsOlderThan:[NSDate distantFuture]]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + XCTAssertEqual(0, [repo getAllPayloads].count); +} + +- (void)testGetPayloadsWithDestinationID { + + NSDate *cutoffTime = [NSDate date]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + NSString *destinationID = [repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_005"][@"id"]; + XCTAssertEqual(3, [repo getAllPayloadsWithDestinationID:destinationID].count); + destinationID = [repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_006"][@"id"]; + XCTAssertEqual(1, [repo getAllPayloadsWithDestinationID:destinationID].count); + destinationID = [repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_007"][@"id"]; + XCTAssertEqual(0, [repo getAllPayloadsWithDestinationID:destinationID].count); +} + +- (void)testGetPayloadsWithOffsetAndLimit { + + NSDate *cutoffTime = [NSDate date]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + XCTAssertEqual(4, [repo getAllPayloads].count); + XCTAssertEqual(2, [repo getPayloadsWithLimit:2].count); + XCTAssertEqual(2, [repo getPayloadsWithOffset:2 andLimit:4].count); + XCTAssertEqual(1, [repo getPayloadsWithOffset:3 andLimit:4].count); + XCTAssertEqual(0, [repo getPayloadsWithOffset:4 andLimit:4].count); + XCTAssertEqual(0, [repo getPayloadsWithOffset:5 andLimit:4].count); + XCTAssertEqual(0, [repo getPayloadsWithOffset:2 andLimit:0].count); +} #pragma mark - Payloads performance tests //TODO: implement... @@ -275,4 +376,29 @@ - (void)insertDestinationMocks:(RollbarPayloadRepository *)repo { [repo addDestinationWithEndpoint:@"EP_005" andAccesToken:@"AT_001"]; } +- (void)insertPayloadMocks:(RollbarPayloadRepository *)repo { + + [self insertDestinationMocks:repo]; + + //paylooads for EP_001/AT_005 destination + [repo addPayload:@"PL_001" + withConfig:@"C_001" + andDestinationID:[repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_005"][@"id"] + ]; + [repo addPayload:@"PL_002" + withConfig:@"C_002" + andDestinationID:[repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_005"][@"id"] + ]; + [repo addPayload:@"PL_003" + withConfig:@"C_003" + andDestinationID:[repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_005"][@"id"] + ]; + + //paylooads for EP_001/AT_006 destination + [repo addPayload:@"PL_004" + withConfig:@"C_004" + andDestinationID:[repo getDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_006"][@"id"] + ]; +} + @end From 9cde1225391efc523a43e0563c6b643b702f6c3d Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 8 Aug 2022 12:59:24 -0700 Subject: [PATCH 087/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.h | 7 ++++++ .../RollbarPayloadRepository.m | 24 ++++++++++++++++++ .../RollbarPayloadRepositoryTests.m | 25 +++++++++++++++++++ 3 files changed, 56 insertions(+) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index a8ba348c..114531ad 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -49,6 +49,13 @@ NS_DESIGNATED_INITIALIZER; - (nonnull NSArray *> *)getAllPayloadsWithDestinationID:(nonnull NSString *)destinationID; +- (nonnull NSArray *> *)getPayloadsWithDestinationID:(nonnull NSString *)destinationID + andLimit:(NSUInteger)limit; + +- (nonnull NSArray *> *)getPayloadsWithDestinationID:(nonnull NSString *)destinationID + andOffset:(NSUInteger)offset + andLimit:(NSUInteger)limit; + - (nonnull NSArray *> *)getPayloadsWithLimit:(NSUInteger)limit; - (nonnull NSArray *> *)getPayloadsWithOffset:(NSUInteger)offset diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 7ce96024..1797a091 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -281,6 +281,30 @@ - (BOOL)removeAllDestinations { return result; } +- (nonnull NSArray *> *)getPayloadsWithDestinationID:(nonnull NSString *)destinationID + andLimit:(NSUInteger)limit { + + return [self getPayloadsWithDestinationID:destinationID andOffset:0 andLimit:limit]; +} + +- (nonnull NSArray *> *)getPayloadsWithDestinationID:(nonnull NSString *)destinationID + andOffset:(NSUInteger)offset + andLimit:(NSUInteger)limit { + + + NSString *sql = [NSString stringWithFormat: + @"SELECT * FROM payloads WHERE destination_key = '%@' LIMIT %lu OFFSET %lu", + destinationID, + limit, + offset + ]; + + NSArray *> *result = + [self selectMultipleRowsWithSql:sql andCallback:selectMultipleRowsCallback]; + + return result; +} + - (nonnull NSArray *> *)getPayloadsWithLimit:(NSUInteger)limit { return [self getPayloadsWithOffset:0 andLimit:limit]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index c0ba5616..f5c9ee63 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -331,6 +331,31 @@ - (void)testGetPayloadsWithDestinationID { XCTAssertEqual(0, [repo getAllPayloadsWithDestinationID:destinationID].count); } + +- (void)testGetPayloadsWithDestinationIDAndOffsetAndLimit { + + NSDate *cutoffTime = [NSDate date]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + XCTAssertEqual(4, [repo getAllPayloads].count); + + NSString *destinationID = [repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_005"][@"id"]; + XCTAssertEqual(3, [repo getAllPayloadsWithDestinationID:destinationID].count); + + + XCTAssertEqual(2, [repo getPayloadsWithDestinationID:destinationID andLimit:2].count); + XCTAssertEqual(3, [repo getPayloadsWithDestinationID:destinationID andOffset:0 andLimit:3].count); + XCTAssertEqual(3, [repo getPayloadsWithDestinationID:destinationID andOffset:0 andLimit:6].count); + XCTAssertEqual(2, [repo getPayloadsWithDestinationID:destinationID andOffset:1 andLimit:2].count); + XCTAssertEqual(2, [repo getPayloadsWithDestinationID:destinationID andOffset:1 andLimit:4].count); + XCTAssertEqual(1, [repo getPayloadsWithDestinationID:destinationID andOffset:2 andLimit:2].count); + XCTAssertEqual(1, [repo getPayloadsWithDestinationID:destinationID andOffset:2 andLimit:4].count); + XCTAssertEqual(0, [repo getPayloadsWithDestinationID:destinationID andOffset:5 andLimit:2].count); +} + - (void)testGetPayloadsWithOffsetAndLimit { NSDate *cutoffTime = [NSDate date]; From 78d8ba9428abab6ec175fc66de2178c5925dfbf5 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 9 Aug 2022 15:59:55 -0700 Subject: [PATCH 088/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.h | 16 ++++- .../RollbarPayloadRepository.m | 61 +++++++++++++++++-- .../RollbarPayloadRepositoryTests.m | 46 ++++++++------ 3 files changed, 95 insertions(+), 28 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index 114531ad..f9a97246 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -13,10 +13,20 @@ NS_ASSUME_NONNULL_BEGIN @interface RollbarPayloadRepository : NSObject -#pragma mark - instance initializers +#pragma mark - factory methods -- (instancetype)initWithStore:(nonnull NSString *)storePath -NS_DESIGNATED_INITIALIZER; ++ (instancetype)repositoryWithFlag:(BOOL)inMemory; ++ (instancetype)repositoryWithPath:(nonnull NSString *)storePath; + ++ (instancetype)inMemoryRepository; ++ (instancetype)persistentRepository; ++ (instancetype)persistentRepositoryWithPath:(nonnull NSString *)storePath; + +#pragma mark - instantiation blocking + ++ (instancetype)alloc NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; +- (instancetype)init NS_UNAVAILABLE; #pragma mark - Destinations related methods diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 1797a091..c33496a9 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -96,18 +96,65 @@ @implementation RollbarPayloadRepository { } +#pragma mark - factory methods + ++ (instancetype)repositoryWithFlag:(BOOL)inMemory { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository alloc]; + if (inMemory) { + return [repo initInMemoryOnly]; + } + else { + return [repo init]; + } +} + ++ (instancetype)repositoryWithPath:(nonnull NSString *)storePath { + + return [[RollbarPayloadRepository alloc] initWithStore:storePath]; +} + ++ (instancetype)inMemoryRepository { + + return [RollbarPayloadRepository repositoryWithFlag:YES]; +} + ++ (instancetype)persistentRepository { + + return [RollbarPayloadRepository repositoryWithFlag:NO]; +} + ++ (instancetype)persistentRepositoryWithPath:(nonnull NSString *)storePath { + + return [RollbarPayloadRepository repositoryWithPath:storePath]; +} + +#pragma mark - class initializer + + (void)initialize { } #pragma mark - instance initializers +- (instancetype)initInMemoryOnly { + + if (self = [super init]) { + + [self initDB:YES]; + return self; + } + + return nil; +} + + - (instancetype)initWithStore:(nonnull NSString *)storePath { if (self = [super init]) { self->_storePath = storePath; - [self initDB]; + [self initDB:NO]; return self; } @@ -398,16 +445,20 @@ - (BOOL)clear { #pragma mark - internal methods -- (void)initDB { +- (void)initDB:(BOOL)inMemory { - [self openDB]; + [self openDB:inMemory]; [self ensureDestinationsTable]; [self ensurePayloadsTable]; } -- (BOOL)openDB { +- (BOOL)openDB:(BOOL)inMemory { + + int sqliteDbFlags = inMemory + ? (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY) + : (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); - int result = sqlite3_open([self->_storePath UTF8String], &self->_db); + int result = sqlite3_open_v2([self->_storePath UTF8String], &self->_db, sqliteDbFlags, NULL); if (result != SQLITE_OK) { RollbarSdkLog(@"sqlite3_open: %s", sqlite3_errmsg(self->_db)); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index f5c9ee63..39c48098 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -33,11 +33,11 @@ - (void)tearDown { #pragma mark - Destinations unit tests -- (void)testRepoInitialization { +- (void)testInMemoryRepoInitialization { XCTAssertFalse([RollbarTestUtil checkPayloadsStoreFileExists]); - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; - XCTAssertTrue([RollbarTestUtil checkPayloadsStoreFileExists]); + RollbarPayloadRepository *repo = [RollbarPayloadRepository inMemoryRepository]; + XCTAssertFalse([RollbarTestUtil checkPayloadsStoreFileExists]); XCTAssertFalse([repo checkIfTableExists_Unknown]); XCTAssertTrue ([repo checkIfTableExists_Destinations]); @@ -46,7 +46,7 @@ - (void)testRepoInitialization { - (void)testAddDestination { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; NSDictionary *destination = [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_001"]; @@ -64,7 +64,7 @@ - (void)testAddDestination { - (void)testGetDestination { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; [self insertDestinationMocks:repo]; NSDictionary *destination = @@ -85,7 +85,7 @@ - (void)testGetDestination { - (void)testGetDestinationByID { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; [self insertDestinationMocks:repo]; NSDictionary *destination = @@ -104,7 +104,7 @@ - (void)testGetDestinationByID { - (void)testGetAllDestinations { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_001"]; [repo addDestinationWithEndpoint:@"EP_001" andAccesToken:@"AT_002"]; @@ -130,7 +130,7 @@ - (void)testGetAllDestinations { - (void)testDestinationRemovals { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; [self insertDestinationMocks:repo]; int removedCount = 0; @@ -167,13 +167,13 @@ - (void)testRepoInitializationPerformance { [self measureBlock:^{ - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; }]; } - (void)testAddRemoveDestinationPerformance { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); [self measureBlock:^{ @@ -186,7 +186,7 @@ - (void)testAddRemoveDestinationPerformance { - (void)testAddRemoveDestinationByIDPerformance { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); [self measureBlock:^{ @@ -199,7 +199,7 @@ - (void)testAddRemoveDestinationByIDPerformance { - (void)testGetDestinationPerformance { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); [self insertDestinationMocks:repo]; XCTAssertNotNil([repo getAllDestinations]); @@ -213,7 +213,7 @@ - (void)testGetDestinationPerformance { - (void)testGetAllDestinationsPerformance { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); [self insertDestinationMocks:repo]; @@ -246,7 +246,7 @@ - (void)testTimestampCalculations { - (void)testAddGetRemovePayload { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); [self insertDestinationMocks:repo]; XCTAssertTrue(0 < [repo getAllDestinations].count); @@ -275,7 +275,7 @@ - (void)testAddGetRemovePayload { - (void)testGetAllPayloads { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); XCTAssertTrue(0 == [repo getAllPayloads].count); [self insertPayloadMocks:repo]; @@ -285,7 +285,7 @@ - (void)testGetAllPayloads { - (void)testRemoveAllPayloads { - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); XCTAssertTrue(0 == [repo getAllPayloads].count); [self insertPayloadMocks:repo]; @@ -299,7 +299,7 @@ - (void)testRemoveAllPayloads { - (void)testRemoveOldPayloads { NSDate *cutoffTime = [NSDate date]; - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); XCTAssertTrue(0 == [repo getAllPayloads].count); [self insertPayloadMocks:repo]; @@ -316,7 +316,7 @@ - (void)testRemoveOldPayloads { - (void)testGetPayloadsWithDestinationID { NSDate *cutoffTime = [NSDate date]; - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); XCTAssertTrue(0 == [repo getAllPayloads].count); [self insertPayloadMocks:repo]; @@ -335,7 +335,7 @@ - (void)testGetPayloadsWithDestinationID { - (void)testGetPayloadsWithDestinationIDAndOffsetAndLimit { NSDate *cutoffTime = [NSDate date]; - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); XCTAssertTrue(0 == [repo getAllPayloads].count); [self insertPayloadMocks:repo]; @@ -359,7 +359,7 @@ - (void)testGetPayloadsWithDestinationIDAndOffsetAndLimit { - (void)testGetPayloadsWithOffsetAndLimit { NSDate *cutoffTime = [NSDate date]; - RollbarPayloadRepository *repo = [RollbarPayloadRepository new]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; XCTAssertTrue(0 == [repo getAllDestinations].count); XCTAssertTrue(0 == [repo getAllPayloads].count); [self insertPayloadMocks:repo]; @@ -374,6 +374,12 @@ - (void)testGetPayloadsWithOffsetAndLimit { #pragma mark - Payloads performance tests //TODO: implement... +- (void)testPerformance { + + [self measureBlock:^{ + + }]; +} From 395a638661dece26fba7b6a3cd979076cc06542c Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 9 Aug 2022 16:49:41 -0700 Subject: [PATCH 089/127] test: RollbarPayloadRepository --- .../RollbarPayloadRepositoryTests.m | 99 ++++++++++++++++++- 1 file changed, 94 insertions(+), 5 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index 39c48098..0c8a238e 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -228,8 +228,6 @@ - (void)testGetAllDestinationsPerformance { } - - #pragma mark - Payloads unit tests - (void)testTimestampCalculations { @@ -373,18 +371,109 @@ - (void)testGetPayloadsWithOffsetAndLimit { } #pragma mark - Payloads performance tests -//TODO: implement... -- (void)testPerformance { + +- (void)testAddGetRemovePayloadPerformance { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + [self insertDestinationMocks:repo]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + + XCTAssertEqual(0, [repo getAllPayloads].count); + XCTAssertNil([repo getPayloadByID:@"0001"]); + [self measureBlock:^{ - + NSDictionary *dataFields = + [repo addPayload:@"PL_001" + withConfig:@"C_001" + andDestinationID:[repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_005"][@"id"] + ]; + [repo removePayloadByID:dataFields[@"id"]]; }]; } +- (void)testGetAllPayloadsPerformance { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + [self measureBlock:^{ + id result = [repo getAllPayloads]; + }]; +} +- (void)testRemoveAllPayloadsPerformance { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + XCTAssertTrue(0 < [repo getAllPayloads].count); + [self measureBlock:^{ + [repo removeAllPayloads]; + }]; +} +- (void)testRemoveOldPayloadsPerformance { + + NSDate *cutoffTime = [NSDate date]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + XCTAssertTrue(0 < [repo getAllPayloads].count); + [self measureBlock:^{ + [repo removePayloadsOlderThan:[NSDate distantPast]]; + }]; +} +- (void)testGetPayloadsWithDestinationIDPerformance { + + NSDate *cutoffTime = [NSDate date]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + NSString *destinationID = [repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_005"][@"id"]; + [self measureBlock:^{ + id result = [repo getAllPayloadsWithDestinationID:destinationID]; + }]; +} + + +- (void)testGetPayloadsWithDestinationIDAndOffsetAndLimitPerformance { + + NSDate *cutoffTime = [NSDate date]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + XCTAssertEqual(4, [repo getAllPayloads].count); + + NSString *destinationID = [repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_005"][@"id"]; + [self measureBlock:^{ + id result = [repo getPayloadsWithDestinationID:destinationID andOffset:1 andLimit:4]; + }]; +} +- (void)testGetPayloadsWithOffsetAndLimitPerformance { + + NSDate *cutoffTime = [NSDate date]; + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + XCTAssertTrue(0 == [repo getAllPayloads].count); + [self insertPayloadMocks:repo]; + [self measureBlock:^{ + id result = [repo getPayloadsWithOffset:2 andLimit:4]; + }]; +} #pragma mark - mocking helpers From 8999a1e1dfc6a46a4094619c1651b8f8bfe6b0e6 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 12 Aug 2022 17:23:53 -0700 Subject: [PATCH 090/127] feat: RollbarPayloadRepository --- .../RollbarPayloadRepository.h | 3 ++ .../RollbarPayloadRepository.m | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h index f9a97246..910208d7 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.h @@ -33,6 +33,9 @@ NS_ASSUME_NONNULL_BEGIN - (nullable NSDictionary *)addDestinationWithEndpoint:(nonnull NSString *)endpoint andAccesToken:(nonnull NSString *)accessToken; +- (nonnull NSString *)getIDofDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken; + - (nullable NSDictionary *)getDestinationWithEndpoint:(nonnull NSString *)endpoint andAccesToken:(nonnull NSString *)accessToken; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index c33496a9..9311c741 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -201,6 +201,35 @@ - (instancetype)init { }; } +- (nonnull NSString *)getIDofDestinationWithEndpoint:(nonnull NSString *)endpoint + andAccesToken:(nonnull NSString *)accessToken { + + NSString *sql = [NSString stringWithFormat: + @"SELECT id FROM destinations WHERE endpoint = '%@' AND access_token = '%@'", + endpoint, + accessToken + ]; + + NSDictionary *result = [self selectSingleRowWithSql:sql + andCallback:selectSingleRowCallback]; + + if (!result || (0 == result.count)) { + result = [self addDestinationWithEndpoint:endpoint + andAccesToken:accessToken]; + } + + NSString *destinationID = nil; + if (result) { + destinationID = result[@"id"]; + } + + if (!destinationID) { + destinationID = @""; + } + + return destinationID; +} + - (nullable NSDictionary *)getDestinationWithEndpoint:(nonnull NSString *)endpoint andAccesToken:(nonnull NSString *)accessToken { From 3b8b036057e6b3767836f41b9a7f81fdbaf61c2c Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 16 Aug 2022 20:46:17 -0700 Subject: [PATCH 091/127] feat: RollbarPayloadRepository integration - first cut. --- .../RollbarDestinationRecord.h | 1 + .../RollbarDestinationRecord.m | 21 + .../Sources/RollbarNotifier/RollbarLogger.m | 12 +- .../Sources/RollbarNotifier/RollbarRegistry.h | 4 + .../Sources/RollbarNotifier/RollbarRegistry.m | 48 ++- .../Sources/RollbarNotifier/RollbarThread.h | 5 +- .../Sources/RollbarNotifier/RollbarThread.m | 391 ++++++------------ 7 files changed, 198 insertions(+), 284 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h index 01423a2f..f0dafd3b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.h @@ -29,6 +29,7 @@ NS_ASSUME_NONNULL_BEGIN @property (readonly, nonnull) RollbarRegistry *registry; - (BOOL)canPost; +- (BOOL)canPostWithConfig:(nonnull RollbarConfig *)config; - (void)recordPostReply:(nullable RollbarPayloadPostReply *)reply; - (instancetype)initWithConfig:(nonnull RollbarConfig *)config diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m index fcfdda7a..ccd91b86 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarDestinationRecord.m @@ -62,6 +62,27 @@ - (BOOL)canPost { } } +- (BOOL)canPostWithConfig:(nonnull RollbarConfig *)config { + + + if (self->_nextLocalWindowStart && (self->_localWindowCount >= config.loggingOptions.maximumReportsPerMinute)) { + // we already exceeded local rate limits, let's wait till the next local rate limiting window: + //self->_nextEarliestPost = self->_nextLocalWindowStart; + return NO; + } + + if (!self->_nextEarliestPost) { + return NO; + } + + if (NSOrderedDescending == [self->_nextEarliestPost compare:[NSDate date]]) { + return NO; + } + else { + return YES; + } +} + - (void)recordPostReply:(nullable RollbarPayloadPostReply *)reply { if (!reply) { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index 2d3d595d..8664dec5 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -174,10 +174,14 @@ - (BOOL)shouldSkipReporting:(RollbarLevel)level { - (void)report:(RollbarPayload *)payload { if (payload) { - NSDictionary *payloadJsonData = payload.jsonFriendlyData; - if (payloadJsonData) { - [[RollbarThread sharedInstance] persistPayload:payloadJsonData]; - } + + [[RollbarThread sharedInstance] persistPayload:payload + withConfig:self.configuration]; + +// NSDictionary *payloadJsonData = payload.jsonFriendlyData; +// if (payloadJsonData) { +// [[RollbarThread sharedInstance] persistPayload:payloadJsonData]; +// } } } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h index 72332a9b..c02a16e8 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.h @@ -15,9 +15,13 @@ NS_ASSUME_NONNULL_BEGIN @interface RollbarRegistry : NSObject - (nonnull RollbarDestinationRecord *)getRecordForConfig:(nonnull RollbarConfig *)config; +- (nonnull RollbarDestinationRecord *)getRecordForEndpoint:(nonnull NSString *)endpoint + andAccessToken:(nonnull NSString *)accessToken; - (NSUInteger)totalDestinationRecords; + (nonnull NSString *)destinationID:(nonnull RollbarDestination *)destination; ++ (nonnull NSString *)destinationIDwithEndpoint:(nonnull NSString *)endpoint + andAccessToken:(nonnull NSString *)accessToken; @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m index cfe3cd75..f5302523 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m @@ -21,7 +21,26 @@ - (nonnull RollbarDestinationRecord *)getRecordForConfig:(nonnull RollbarConfig NSAssert(config, @"Config must not be null!"); NSAssert(config.destination, @"Destination must not be null!"); - NSString *destinationID = [RollbarRegistry destinationID:config.destination]; + //NSString *destinationID = [RollbarRegistry destinationID:config.destination]; + RollbarDestinationRecord *destinationRecord = [self getRecordForEndpoint:config.destination.endpoint + andAccessToken:config.destination.accessToken]; + + if (destinationRecord.localWindowLimit < config.loggingOptions.maximumReportsPerMinute) { + + // we use lagest configured limit per destination: + destinationRecord.localWindowLimit = config.loggingOptions.maximumReportsPerMinute; + } + + return destinationRecord; +} + +- (nonnull RollbarDestinationRecord *)getRecordForEndpoint:(nonnull NSString *)endpoint + andAccessToken:(nonnull NSString *)accessToken { + + NSAssert(endpoint, @"endpoint must not be null!"); + NSAssert(accessToken, @"accessToken must not be null!"); + + NSString *destinationID = [RollbarRegistry destinationIDwithEndpoint:endpoint andAccessToken:accessToken]; RollbarDestinationRecord *destinationRecord = self->_destinationRecords[destinationID]; if (!destinationRecord) { destinationRecord = [[RollbarDestinationRecord alloc] initWithDestinationID:destinationID @@ -29,16 +48,20 @@ - (nonnull RollbarDestinationRecord *)getRecordForConfig:(nonnull RollbarConfig ]; self->_destinationRecords[destinationID] = destinationRecord; } - - if (destinationRecord.localWindowLimit < config.loggingOptions.maximumReportsPerMinute) { - - // we use lagest configured limit per destination: - destinationRecord.localWindowLimit = config.loggingOptions.maximumReportsPerMinute; - } + +// if (destinationRecord.localWindowLimit < config.loggingOptions.maximumReportsPerMinute) { +// +// // we use lagest configured limit per destination: +// destinationRecord.localWindowLimit = config.loggingOptions.maximumReportsPerMinute; +// } return destinationRecord; } + + + + - (NSUInteger)totalDestinationRecords { return self->_destinationRecords.count; } @@ -58,9 +81,16 @@ - (nonnull NSString *)description { + (nonnull NSString *)destinationID:(nonnull RollbarDestination *)destination { + return [RollbarRegistry destinationIDwithEndpoint:destination.endpoint + andAccessToken:destination.accessToken]; +} + ++ (nonnull NSString *)destinationIDwithEndpoint:(nonnull NSString *)endpoint + andAccessToken:(nonnull NSString *)accessToken { + NSString *destinationID = [NSString stringWithFormat:@"%@|%@", - destination.endpoint, - destination.accessToken]; + endpoint, + accessToken]; return destinationID; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h index ef5aac2f..119340a1 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h @@ -10,9 +10,10 @@ NS_ASSUME_NONNULL_BEGIN /// Signifies that the thread is active or not. @property(atomic) BOOL active; -- (void)persist:(nonnull RollbarPayload *)payload; +//- (void)persist:(nonnull RollbarPayload *)payload; -- (void)persistPayload:(nonnull NSDictionary *)payload; +- (void)persistPayload:(nonnull RollbarPayload *)payload + withConfig:(nonnull RollbarConfig *)config; - (BOOL)sendPayload:(nonnull NSData *)payload usingConfig:(nonnull RollbarConfig *)config; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index e64d6e51..0550b309 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -1,18 +1,12 @@ @import RollbarCommon; #import "RollbarThread.h" -#import "RollbarLogger.h" -//#import "RollbarConfig.h" -//#import "RollbarDeveloperOptions.h" #import "RollbarReachability.h" #import "RollbarTelemetry.h" -//#import "RollbarTelemetryOptions.h" #import "RollbarNotifierFiles.h" -//#import "RollbarPayload.h" #import "RollbarPayloadTruncator.h" #import "RollbarData.h" -//#import "RollbarModule.h" -//#import "RollbarDestination.h" +#import "RollbarModule.h" #import "RollbarProxy.h" #import "RollbarSender.h" #import "RollbarPayloadPostReply.h" @@ -24,15 +18,16 @@ @implementation RollbarThread { @private - //RollbarLogger *_logger; NSUInteger _maxReportsPerMinute; - RollbarRegistry *_registry; NSTimer *_timer; + NSString *_payloadsRepoFilePath; + RollbarRegistry *_registry; + RollbarPayloadRepository *_payloadsRepo; - NSString *_queuedItemsFilePath; - NSString *_stateFilePath; - NSMutableDictionary *_queueState; - NSDate *_nextSendTime; +// NSDate *_nextSendTime; +// NSString *_queuedItemsFilePath; +// NSString *_stateFilePath; +// NSMutableDictionary *_queueState; #if !TARGET_OS_WATCH RollbarReachability *_reachability; @@ -58,7 +53,7 @@ - (instancetype)initWithTarget:(id)target self->_reachability = nil; self->_isNetworkReachable = YES; #endif - self->_nextSendTime = [[NSDate alloc] init]; + //self->_nextSendTime = [[NSDate alloc] init]; self.name = [RollbarThread rollbar_objectClassName];//NSStringFromClass([RollbarThread class]); self.active = YES; @@ -96,79 +91,16 @@ - (void)setupDataStorage { [RollbarCachesDirectory ensureCachesDirectoryExists]; NSString *cachesDirectory = [RollbarCachesDirectory directory]; - // make sure we have all the data files set: - self->_queuedItemsFilePath = - [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueue]]; - self->_stateFilePath = - [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles itemsQueueState]]; - - // create the queued items file if does not exist already: - if (![[NSFileManager defaultManager] fileExistsAtPath:self->_queuedItemsFilePath]) { - [[NSFileManager defaultManager] createFileAtPath:self->_queuedItemsFilePath - contents:nil - attributes:nil]; - } - - // create state tracking file if does not exist already: - if ([[NSFileManager defaultManager] fileExistsAtPath:self->_stateFilePath]) { - NSData *stateData = [NSData dataWithContentsOfFile:self->_stateFilePath]; - if (stateData) { - NSDictionary *state = [NSJSONSerialization JSONObjectWithData:stateData - options:0 - error:nil]; - self->_queueState = [state mutableCopy]; - } else { - RollbarSdkLog(@"There was an error restoring saved queue state"); - } - } - - // let's make sure we always recover into a good state if applicable: - if (!self->_queueState) { - self->_queueState = [@{ - @"offset": [NSNumber numberWithUnsignedInt:0], - @"retry_count": [NSNumber numberWithUnsignedInt:0] - } mutableCopy]; - [self saveQueueState]; - }} - -- (void)saveQueueState { - - NSError *error; - NSData *data = [NSJSONSerialization rollbar_dataWithJSONObject:self->_queueState - options:0 - error:&error - safe:true]; - if (error) { - - RollbarSdkLog(@"Error: %@", [error localizedDescription]); - } - [data writeToFile:self->_stateFilePath atomically:YES]; + // setup persistent payloads store/repo: + self->_payloadsRepoFilePath = + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsStore]]; + self->_payloadsRepo = + [RollbarPayloadRepository persistentRepositoryWithPath:self->_payloadsRepoFilePath]; + NSAssert([[NSFileManager defaultManager] fileExistsAtPath:self->_payloadsRepoFilePath], + @"Resistent payloads store was not created: %@!!!", self->_payloadsRepoFilePath + ); } -//- (void)setReportingRate:(NSUInteger)reportsPerMinute { -// -// NSAssert(reportsPerMinute > 0, @"reportsPerMinute must be greater than zero!"); -// -// BOOL wasExecuting = self.isExecuting; -// if (wasExecuting) { -// -// [self cancel]; -// } -// -// if(reportsPerMinute > 0) { -// _maxReportsPerMinute = reportsPerMinute; -// } else { -// _maxReportsPerMinute = 60; -// } -// -// self.active = YES; -// -// if (wasExecuting) { -// -// [self start]; -// } -//} - - (void)run { @autoreleasepool { @@ -200,34 +132,55 @@ - (void)persist:(nonnull RollbarPayload *)payload { #pragma mark - persisting payload items -- (void)persistPayload:(nonnull NSDictionary *)payload { +- (void)persistPayload:(nonnull RollbarPayload *)payload + withConfig:(nonnull RollbarConfig *)config { [self performSelector:@selector(queuePayload_OnlyCallOnThread:) onThread:[RollbarThread sharedInstance] - withObject:payload + withObject:@[payload, config] waitUntilDone:NO ]; } - -- (void)queuePayload_OnlyCallOnThread:(NSDictionary *)payload { - - NSError *error = nil; - NSData *data = [NSJSONSerialization rollbar_dataWithJSONObject:payload - options:0 - error:&error - safe:true]; - if (nil == data) { +- (void)queuePayload_OnlyCallOnThread:(nonnull NSArray *)data { + + NSAssert(data, @"data can not be nil"); + NSAssert(2 == data.count, @"data expected to have 2 components"); - RollbarSdkLog(@"Couldn't generate and save JSON data from: %@", payload); - if (error) { - - RollbarSdkLog(@" Error: %@", [error localizedDescription]); - } + RollbarPayload *payload = (RollbarPayload *)data[0]; + NSAssert(payload, @"payload can not be nil in data: %@", data); + RollbarConfig *config = (RollbarConfig *)data[1]; + NSAssert(config, @"config can not be nil"); + if (!(payload && config)) { + + RollbarSdkLog(@"Couldn't queue payload %@ with config %@", payload, config); + return; + } + + NSString *destinationID = [self->_payloadsRepo getIDofDestinationWithEndpoint:config.destination.endpoint + andAccesToken:config.destination.accessToken]; + + NSString *configJson = [config serializeToJSONString]; + NSAssert(configJson && configJson.length > 0, @"invalid configJson!"); + if (!configJson || (0 == configJson.length)) { + RollbarSdkLog(@"invalid configJson!"); return; } - [RollbarFileWriter appendSafelyData:data toFile:self->_queuedItemsFilePath]; + //TODO: consider moving payload modifications (scrubbing and truncation) here... + + [payload.data.notifier setData:@"configured_options" byKey:configJson]; + NSString *payloadJson = [payload serializeToJSONString]; + NSDictionary *payloadDataRow = [self->_payloadsRepo addPayload:payloadJson + withConfig:configJson + andDestinationID:destinationID]; + if (!payloadDataRow || !payloadDataRow[@"id"]) { + RollbarSdkLog(@"*** Couldn't add a payload to the repo: %@", payloadJson); + RollbarSdkLog(@"*** with config: %@", configJson); + RollbarSdkLog(@"*** with destinationID: %@", destinationID); + RollbarSdkLog(@"*** Resulting payloadDataRow: %@", payloadDataRow); + } + NSAssert(payloadDataRow && payloadDataRow[@"id"], @"Couldn't add a payload to the repo: %@", payloadJson); [[RollbarTelemetry sharedInstance] clearAllData]; } @@ -255,133 +208,44 @@ - (void)checkItems { } } -- (void)processSavedItems { - -#if !TARGET_OS_WATCH - if (!self->_isNetworkReachable) { - RollbarSdkLog(@"Processing saved items: no network!"); - // Don't attempt sending if the network is known to be not reachable - return; - } -#endif - - NSUInteger startOffset = [self->_queueState[@"offset"] unsignedIntegerValue]; +- (void)processSavedPayload:(nonnull NSDictionary *)payloadDataRow { - NSFileHandle *fileHandle = - [NSFileHandle fileHandleForReadingAtPath:self->_queuedItemsFilePath]; - [fileHandle seekToEndOfFile]; - __block unsigned long long fileLength = [fileHandle offsetInFile]; - [fileHandle closeFile]; + NSString *destinationKey = payloadDataRow[@"destination_key"]; + NSAssert(destinationKey && destinationKey.length > 0, @"destination_key is expected to be defined!"); + NSDictionary *destination = [self->_payloadsRepo getDestinationByID:destinationKey]; + RollbarDestinationRecord *destinationRecord = [self->_registry getRecordForEndpoint:destination[@"endpoint"] + andAccessToken:destination[@"access_token"]]; + NSString *configJson = payloadDataRow[@"config_json"]; + NSAssert(configJson && configJson.length > 0, @"config_json is expected to be defined!"); + RollbarConfig *config = [[RollbarConfig alloc] initWithJSONString:configJson]; + NSAssert(config, @"config is expected to be defined!"); - if (!fileLength) { - -// if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { -// -// RollbarSdkLog(@"Processing saved items: no queued items in the file!"); -// } + if (![destinationRecord canPostWithConfig:config]) { return; } - // Empty out the queued item file if all items have been processed already - if (startOffset == fileLength) { - [@"" writeToFile:self->_queuedItemsFilePath - atomically:YES - encoding:NSUTF8StringEncoding - error:nil]; - - self->_queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:0]; - self->_queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; - [self saveQueueState]; -// if (NO == self.configuration.developerOptions.suppressSdkInfoLogging) { -// -// RollbarSdkLog(@"Processing saved items: emptied the queued items file."); -// } - - return; - } + NSString *payloadJson = payloadDataRow[@"payload_json"]; + RollbarPayload *payload = [[RollbarPayload alloc] initWithJSONString:payloadJson]; + NSAssert(payload, @"payload is expected to be defined!"); - // Iterate through the items file and send the items in batches. - RollbarFileReader *reader = - [[RollbarFileReader alloc] initWithFilePath:self->_queuedItemsFilePath - andOffset:startOffset]; - [reader enumerateLinesUsingBlock:^(NSString *line, NSUInteger nextOffset, BOOL *stop) { - - NSData *lineData = [line dataUsingEncoding:NSUTF8StringEncoding]; - if (!lineData) { - // All we can do is ignore this line - RollbarSdkLog(@"Error converting file line to NSData: %@", line); - return; - } - NSError *error; - NSJSONReadingOptions serializationOptions = (NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves); - NSDictionary *payload = [NSJSONSerialization JSONObjectWithData:lineData - options:serializationOptions - error:&error]; - - if (!payload) { - // Ignore this line if it isn't valid json and proceed to the next line - RollbarSdkLog(@"Error restoring data from file to JSON: %@", error); - RollbarSdkLog(@"Raw data from file failed conversion to JSON:"); - RollbarSdkLog(@"%@", lineData); - // RollbarSdkLog(@" error code: %@", error.code); - // RollbarSdkLog(@" error domain: %@", error.domain); - // RollbarSdkLog(@" error description: %@", error.description); - // RollbarSdkLog(@" error localized description: %@", error.localizedDescription); - // RollbarSdkLog(@" error failure reason: %@", error.localizedFailureReason); - // RollbarSdkLog(@" error recovery option: %@", error.localizedRecoveryOptions); - // RollbarSdkLog(@" error recovery suggestion: %@", error.localizedRecoverySuggestion); - return; - } - - BOOL shouldContinue = [self sendItem:payload nextOffset:nextOffset]; - - if (!shouldContinue) { - // Stop processing the file so that the current file offset will be - // retried next time the file is processed - *stop = YES; - return; - } - - // The file has had items added since we started iterating through it, - // update the known file length to equal the next offset - if (nextOffset > fileLength) { - fileLength = nextOffset; - } - - }]; -} - -- (BOOL)sendItem:(NSDictionary *)payload - nextOffset:(NSUInteger)nextOffset { - - RollbarPayload *rollbarPayload = - [[RollbarPayload alloc] initWithDictionary:[payload copy]]; - if (nil == rollbarPayload) { - - RollbarSdkLog( - @"Couldn't init and send RollbarPayload with data: %@", - payload - ); - // queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; - // queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; - // [RollbarLogger saveQueueState]; - return YES; // no retry needed - } + //TODO: the following payload truncation code should eventually move to the point right before payload persistence + // into the repo: NSMutableDictionary *newPayload = - [NSMutableDictionary dictionaryWithDictionary:payload]; + [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; [RollbarPayloadTruncator truncatePayload:newPayload]; if (nil == newPayload) { RollbarSdkLog( @"Couldn't send truncated payload that is nil" ); - // queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; - // queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; - // [RollbarLogger saveQueueState]; - return YES; // no retry needed + //let's use untruncated original: + newPayload = [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; } + + + NSError *error; NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:newPayload options:0 @@ -399,72 +263,61 @@ - (BOOL)sendItem:(NSDictionary *)payload error ); } - // queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; - // queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; - // [RollbarLogger saveQueueState]; - return YES; // no retry needed + // there is nothing we can do with this payload - let's drop it: + RollbarSdkLog(@"Dropping unprocessable payload: %@", payloadJson); + if (![self->_payloadsRepo removePayloadByID:payloadDataRow[@"id"]]) { + RollbarSdkLog(@"Couldn't remove payload data row with ID: %@", payloadDataRow[@"id"]); + } + return; } - if (NSOrderedDescending != [self->_nextSendTime compare: [[NSDate alloc] init] ]) { + if (config.developerOptions.logPayload) { - NSUInteger retryCount = - [self->_queueState[@"retry_count"] unsignedIntegerValue]; - - RollbarConfig *rollbarConfig = - [[RollbarConfig alloc] initWithDictionary:rollbarPayload.data.notifier.jsonFriendlyData[@"configured_options"]]; - - if (0 == retryCount && YES == rollbarConfig.developerOptions.logPayload) { - - if (NO == rollbarConfig.developerOptions.suppressSdkInfoLogging) { - - RollbarSdkLog(@"About to send payload: %@", - [[NSString alloc] initWithData:jsonPayload - encoding:NSUTF8StringEncoding] - ); - } + if (!config.developerOptions.suppressSdkInfoLogging) { - // - save this payload into a proper payloads log file: - //***************************************************** - - // compose the payloads log file path: - NSString *cachesDirectory = [RollbarCachesDirectory directory]; - NSString *payloadsLogFilePath = - [cachesDirectory stringByAppendingPathComponent:rollbarConfig.developerOptions.payloadLogFile]; - - [RollbarFileWriter appendSafelyData:jsonPayload toFile:payloadsLogFilePath]; + RollbarSdkLog(@"About to send payload: %@", + [[NSString alloc] initWithData:jsonPayload + encoding:NSUTF8StringEncoding] + ); } - BOOL success = - rollbarConfig ? [self sendPayload:jsonPayload usingConfig:rollbarConfig] - : [self sendPayload:jsonPayload]; // backward compatibility with just upgraded very old SDKs... + // - save this payload into a proper payloads log file: + //***************************************************** - if (!success) { - - if (retryCount < MAX_RETRY_COUNT) { - - self->_queueState[@"retry_count"] = - [NSNumber numberWithUnsignedInteger:retryCount + 1]; - - [self saveQueueState]; - - // Return NO so that the current batch will be retried next time - return NO; - } - } + // compose the payloads log file path: + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + NSString *payloadsLogFilePath = + [cachesDirectory stringByAppendingPathComponent:config.developerOptions.payloadLogFile]; + [RollbarFileWriter appendSafelyData:jsonPayload toFile:payloadsLogFilePath]; } - else { - - RollbarSdkLog( - @"Omitting payload until nextSendTime is reached: %@", - [[NSString alloc] initWithData:jsonPayload encoding:NSUTF8StringEncoding] - ); + + + BOOL success = config ? [self sendPayload:jsonPayload usingConfig:config] + : [self sendPayload:jsonPayload]; // backward compatibility with just upgraded very old SDKs... + + if (success) { + // we a successful sending - can remove the repo data row: + if (![self->_payloadsRepo removePayloadByID:payloadDataRow[@"id"]]) { + RollbarSdkLog(@"Couldn't remove payload data row with ID: %@", payloadDataRow[@"id"]); + } + return; } +} + +- (void)processSavedItems { - self->_queueState[@"offset"] = [NSNumber numberWithUnsignedInteger:nextOffset]; - self->_queueState[@"retry_count"] = [NSNumber numberWithUnsignedInteger:0]; - [self saveQueueState]; +#if !TARGET_OS_WATCH + if (!self->_isNetworkReachable) { + RollbarSdkLog(@"Processing saved items: no network!"); + // Don't attempt sending if the network is known to be not reachable + return; + } +#endif - return YES; + NSArray *> *payloads = [self->_payloadsRepo getPayloadsWithOffset:0 andLimit:5]; + for(NSDictionary *payload in payloads) { + [self processSavedPayload:payload]; + } } - (BOOL)sendPayload:(nonnull NSData *)payload @@ -495,7 +348,7 @@ - (BOOL)sendPayload:(nonnull NSData *)payload /// Use/maintain sendPayload:usingConfig: instead! - (BOOL)sendPayload:(NSData *)payload { - return NO; + return YES; } #pragma mark - Network telemetry data From ecb417ef12477fa97962bc4360cfc8c5801b638b Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 17 Aug 2022 22:39:57 -0700 Subject: [PATCH 092/127] feat: RollbarPayloadRepository integration post fixes --- .../RollbarPayloadRepository.m | 7 +++- .../Sources/RollbarNotifier/RollbarRegistry.m | 4 +- .../Sources/RollbarNotifier/RollbarThread.m | 5 ++- .../RollbarPayloadRepositoryTests.m | 37 +++++++++++++++++++ 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index 9311c741..f0a95a4f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -308,11 +308,14 @@ - (BOOL)removeAllDestinations { andDestinationID:(nonnull NSString *)destinationID { NSNumber *timeStamp = [NSNumber numberWithInteger:[[NSDate date] timeIntervalSince1970]]; + + NSString *escapedPayload = [payload stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; + NSString *escapedConfig = [config stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; NSString *sql = [NSString stringWithFormat: @"INSERT INTO payloads (config_json, payload_json, destination_key, created_at) VALUES ('%@', '%@', '%@', '%ld')", - config, - payload, + escapedConfig, + escapedPayload, destinationID, [timeStamp integerValue] ]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m index f5302523..0bdc899b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarRegistry.m @@ -20,7 +20,9 @@ - (nonnull RollbarDestinationRecord *)getRecordForConfig:(nonnull RollbarConfig NSAssert(config, @"Config must not be null!"); NSAssert(config.destination, @"Destination must not be null!"); - + NSAssert(config.destination.endpoint, @"destination.endpoint must not be null!"); + NSAssert(config.destination.accessToken, @"destination.accessToken must not be null!"); + //NSString *destinationID = [RollbarRegistry destinationID:config.destination]; RollbarDestinationRecord *destinationRecord = [self getRecordForEndpoint:config.destination.endpoint andAccessToken:config.destination.accessToken]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 0550b309..7d4e16ba 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -169,7 +169,7 @@ - (void)queuePayload_OnlyCallOnThread:(nonnull NSArray *)data { //TODO: consider moving payload modifications (scrubbing and truncation) here... - [payload.data.notifier setData:@"configured_options" byKey:configJson]; + //[payload.data.notifier setData:config.jsonFriendlyData byKey:@"configured_options"]; NSString *payloadJson = [payload serializeToJSONString]; NSDictionary *payloadDataRow = [self->_payloadsRepo addPayload:payloadJson withConfig:configJson @@ -213,6 +213,9 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl NSString *destinationKey = payloadDataRow[@"destination_key"]; NSAssert(destinationKey && destinationKey.length > 0, @"destination_key is expected to be defined!"); NSDictionary *destination = [self->_payloadsRepo getDestinationByID:destinationKey]; + NSAssert(destination, @"destination can not be nil!"); + NSAssert(destination[@"endpoint"], @"destination endpoint can not be nil!"); + NSAssert(destination[@"access_token"], @"destination access_token can not be nil!"); RollbarDestinationRecord *destinationRecord = [self->_registry getRecordForEndpoint:destination[@"endpoint"] andAccessToken:destination[@"access_token"]]; NSString *configJson = payloadDataRow[@"config_json"]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m index 0c8a238e..b71e57f5 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarPayloadRepositoryTests.m @@ -271,6 +271,43 @@ - (void)testAddGetRemovePayload { XCTAssertEqual(0, [repo getAllPayloads].count); } +- (void)testAddPayloadWithOddContent { + + RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; + XCTAssertTrue(0 == [repo getAllDestinations].count); + [self insertDestinationMocks:repo]; + XCTAssertTrue(0 < [repo getAllDestinations].count); + + XCTAssertEqual(0, [repo getAllPayloads].count); + + XCTAssertNil([repo getPayloadByID:@"0001"]); + + NSDictionary *dataFields = + [repo addPayload:@"PL_001" + withConfig:@"C_001" + andDestinationID:[repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_005"][@"id"] + ]; + XCTAssertEqual(1, [repo getAllPayloads].count); + NSDictionary *dataFields1 = [repo getPayloadByID:dataFields[@"id"]]; + XCTAssertNotNil(dataFields1); + XCTAssertEqual(5, dataFields1.count); + + [repo removePayloadByID:dataFields[@"id"]]; + XCTAssertNil([repo getPayloadByID:dataFields[@"id"]]); + XCTAssertEqual(0, [repo getAllPayloads].count); + + + dataFields = + [repo addPayload:@"Don't" + withConfig:@"C_001" + andDestinationID:[repo getDestinationWithEndpoint:@"EP_001" + andAccesToken:@"AT_005"][@"id"] + ]; + XCTAssertEqual(1, [repo getAllPayloads].count); + id payloads = [repo getAllPayloads]; +} + - (void)testGetAllPayloads { RollbarPayloadRepository *repo = [RollbarPayloadRepository persistentRepository]; From 68ba92c5d0c2a2bc1697496247298d004fd76d7c Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 18 Aug 2022 18:04:05 -0700 Subject: [PATCH 093/127] feat: RollbarNotifier local logging of transmitted payloads vs dropped --- .../DTOs/RollbarDeveloperOptions.m | 76 ++++++---- .../RollbarNotifier/RollbarLogger+Test.m | 47 +++--- .../Sources/RollbarNotifier/RollbarLogger.m | 28 +++- .../RollbarNotifier/RollbarNotifierFiles.h | 7 +- .../RollbarNotifier/RollbarNotifierFiles.m | 25 ++-- .../Sources/RollbarNotifier/RollbarSender.m | 8 +- .../Sources/RollbarNotifier/RollbarThread.h | 4 +- .../Sources/RollbarNotifier/RollbarThread.m | 135 +++++++++++------- .../include/RollbarDeveloperOptions.h | 49 +++++-- .../include/RollbarLogger+Test.h | 12 +- 10 files changed, 240 insertions(+), 151 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m index d8bac73d..b8631294 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m @@ -6,15 +6,18 @@ static BOOL const DEFAULT_ENABLED_FLAG = YES; static BOOL const DEFAULT_TRANSMIT_FLAG = YES; static BOOL const DEFAULT_SUPPRESS_SDK_INFO_LOGGING_FLAG = NO; -static BOOL const DEFAULT_LOG_PAYLOADS_FLAG = NO; +static BOOL const DEFAULT_LOG_TRANSMITTED_PAYLOADS_FLAG = NO; +static BOOL const DEFAULT_LOG_DROPPED_PAYLOADS_FLAG = NO; #pragma mark - data field keys static NSString * const DFK_ENABLED = @"enabled"; static NSString * const DFK_TRANSMIT = @"transmit"; static NSString * const DFK_SUPPRESS_SDK_INFO_LOGGING = @"suppressSdkInfoLogging"; -static NSString * const DFK_LOG_PAYLOAD = @"logPayload"; -static NSString * const DFK_LOG_PAYLOAD_FILE = @"logPayloadFile"; +static NSString * const DFK_LOG_TRANSMITTED_PAYLOADS = @"logTransmittedsPayload"; +static NSString * const DFK_LOG_TRANSMITTED_PAYLOADS_FILE = @"logTransmittedPayloadsFile"; +static NSString * const DFK_LOG_DROPPED_PAYLOADS = @"logDroppedsPayload"; +static NSString * const DFK_LOG_DROPPED_PAYLOADS_FILE = @"logDroppedPayloadsFile"; #pragma mark - class implementation @@ -24,27 +27,34 @@ @implementation RollbarDeveloperOptions - (instancetype)initWithEnabled:(BOOL)enabled transmit:(BOOL)transmit - logPayload:(BOOL)logPayload - payloadLogFile:(NSString *)payloadLogFile { + logTransmittedPayloads:(BOOL)logTransmittedPayloads + logDroppedPayloads:(BOOL)logDroppedPayloads + transmittedPayloadsLogFile:(NSString *)logTransmittedPayloadsFile + droppedPayloadsLogFile:(NSString *)logDroppedPayloadsFile { self = [super initWithDictionary:@{ DFK_ENABLED:[NSNumber numberWithBool:enabled], DFK_TRANSMIT:[NSNumber numberWithBool:transmit], DFK_SUPPRESS_SDK_INFO_LOGGING:[NSNumber numberWithBool:DEFAULT_SUPPRESS_SDK_INFO_LOGGING_FLAG], - DFK_LOG_PAYLOAD:[NSNumber numberWithBool:logPayload], - DFK_LOG_PAYLOAD_FILE:payloadLogFile + DFK_LOG_TRANSMITTED_PAYLOADS:[NSNumber numberWithBool:logTransmittedPayloads], + DFK_LOG_DROPPED_PAYLOADS:[NSNumber numberWithBool:logDroppedPayloads], + DFK_LOG_TRANSMITTED_PAYLOADS_FILE:logTransmittedPayloadsFile, + DFK_LOG_DROPPED_PAYLOADS_FILE:logDroppedPayloadsFile }]; return self; } - (instancetype)initWithEnabled:(BOOL)enabled transmit:(BOOL)transmit - logPayload:(BOOL)logPayload { + logTransmittedPayloads:(BOOL)logTransmittedPayloads + logDroppedPayloads:(BOOL)logDroppedPayloads { return [self initWithEnabled:enabled transmit:transmit - logPayload:logPayload - payloadLogFile:[RollbarNotifierFiles payloadsLog] + logTransmittedPayloads:logTransmittedPayloads + logDroppedPayloads:logDroppedPayloads + transmittedPayloadsLogFile:[RollbarNotifierFiles transmittedPayloadsLog] + droppedPayloadsLogFile:[RollbarNotifierFiles droppedPayloadsLog] ]; } @@ -52,7 +62,8 @@ - (instancetype)initWithEnabled:(BOOL)enabled { return [self initWithEnabled:enabled transmit:DEFAULT_TRANSMIT_FLAG - logPayload:DEFAULT_LOG_PAYLOADS_FLAG]; + logTransmittedPayloads:DEFAULT_LOG_TRANSMITTED_PAYLOADS_FLAG + logDroppedPayloads:DEFAULT_LOG_DROPPED_PAYLOADS_FLAG]; } - (instancetype)init { @@ -76,13 +87,23 @@ - (BOOL)suppressSdkInfoLogging { return [result boolValue]; } -- (BOOL)logPayload { - NSNumber *result = [self safelyGetNumberByKey:DFK_LOG_PAYLOAD]; +- (BOOL)logTransmittedPayloads { + NSNumber *result = [self safelyGetNumberByKey:DFK_LOG_TRANSMITTED_PAYLOADS]; return [result boolValue]; } -- (NSString *)payloadLogFile { - NSString *result = [self safelyGetStringByKey:DFK_LOG_PAYLOAD_FILE]; +- (NSString *)transmittedPayloadsLogFile { + NSString *result = [self safelyGetStringByKey:DFK_LOG_TRANSMITTED_PAYLOADS_FILE]; + return result; +} + +- (BOOL)logDroppedPayloads { + NSNumber *result = [self safelyGetNumberByKey:DFK_LOG_DROPPED_PAYLOADS]; + return [result boolValue]; +} + +- (NSString *)droppedPayloadsLogFile { + NSString *result = [self safelyGetStringByKey:DFK_LOG_DROPPED_PAYLOADS_FILE]; return result; } @@ -93,8 +114,10 @@ @implementation RollbarMutableDeveloperOptions @dynamic enabled; @dynamic transmit; @dynamic suppressSdkInfoLogging; -@dynamic logPayload; -@dynamic payloadLogFile; +@dynamic logTransmittedPayloads; +@dynamic transmittedPayloadLogFile; +@dynamic logDroppedPayloads; +@dynamic droppedPayloadLogFile; #pragma mark - property accessors @@ -110,17 +133,20 @@ - (void)setSuppressSdkInfoLogging:(BOOL)value { [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_SUPPRESS_SDK_INFO_LOGGING]; } -- (void)setLogPayload:(BOOL)value { - [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_LOG_PAYLOAD]; +- (void)setLogTransmittedPayloads:(BOOL)value { + [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_LOG_TRANSMITTED_PAYLOADS]; +} + +- (void)setTransmittedPayloadsLogFile:(NSString *)value { + [self setString:value forKey:DFK_LOG_TRANSMITTED_PAYLOADS_FILE]; } -//- (NSString *)payloadLogFile { -// NSString *result = [self safelyGetStringByKey:DFK_LOG_PAYLOAD_FILE]; -// return result; -//} +- (void)setLogDroppedPayloads:(BOOL)value { + [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_LOG_DROPPED_PAYLOADS]; +} -- (void)setPayloadLogFile:(NSString *)value { - [self setString:value forKey:DFK_LOG_PAYLOAD_FILE]; +- (void)setDroppedPayloadsLogFile:(NSString *)value { + [self setString:value forKey:DFK_LOG_DROPPED_PAYLOADS_FILE]; } @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m index 40359e31..c25380af 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m @@ -8,34 +8,34 @@ @implementation RollbarLogger (Test) + (void)clearSdkDataStore { - [RollbarLogger clearLogItemsStore]; + [RollbarLogger _clearFile:[RollbarLogger _logPayloadsStorePath]]; [RollbarLogger _clearFile:[RollbarLogger _telemetryItemsStorePath]]; - [RollbarLogger _clearFile:[RollbarLogger _payloadsLogStorePath]]; + [RollbarLogger _clearFile:[RollbarLogger _transmittedPayloadsLogPath]]; + [RollbarLogger _clearFile:[RollbarLogger _droppedPayloadsLogPath]]; } -+ (void)clearLogItemsStore { - - [RollbarLogger _clearFile:[RollbarLogger _logItemsStoreStatePath]]; - [RollbarLogger _clearFile:[RollbarLogger _logItemsStorePath]]; -} + (void)clearSdkFile:(nonnull NSString *)sdkFileName { [RollbarLogger _clearFile:[RollbarLogger _getSDKDataFilePath:sdkFileName]]; } -+ (nonnull NSArray *)readLogItemsFromStore { ++ (nonnull NSArray *)readPayloadsFromSdkTransmittedLog { - NSString *filePath = [RollbarLogger _logItemsStorePath]; - return [RollbarLogger readPayloadsDataFromFile:filePath]; + [RollbarLogger readPayloadsDataFromFile:[RollbarLogger _transmittedPayloadsLogPath]]; } -+ (nonnull NSArray *)readPayloadsFromSdkLog { ++ (nonnull NSArray *)readPayloadsFromSdkDroppedLog { - NSString *filePath = [RollbarLogger _payloadsLogStorePath]; - return [RollbarLogger readPayloadsDataFromFile:filePath]; + [RollbarLogger readPayloadsDataFromFile:[RollbarLogger _droppedPayloadsLogPath]]; } +//+ (nonnull NSArray *)readPayloadsFromSdkLog { +// +// NSString *filePath = [RollbarLogger _payloadsLogPath]; +// return [RollbarLogger readPayloadsDataFromFile:filePath]; +//} + + (nonnull NSArray *)readPayloadsDataFromFile:(nonnull NSString *)filePath { RollbarFileReader *reader = [[RollbarFileReader alloc] initWithFilePath:filePath @@ -92,24 +92,29 @@ + (void)_clearFile:(nonnull NSString *)filePath { } } -+ (nonnull NSString *)_logItemsStorePath { ++ (nonnull NSString *)_logPayloadsStorePath { - return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles itemsQueue]]; + return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles payloadsStore]]; } -+ (nonnull NSString *)_logItemsStoreStatePath { - - return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles itemsQueueState]]; -} +//+ (nonnull NSString *)_logItemsStoreStatePath { +// +// return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles itemsQueueState]]; +//} + (nonnull NSString *)_telemetryItemsStorePath { return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles telemetryQueue]]; } -+ (nonnull NSString *)_payloadsLogStorePath { ++ (nonnull NSString *)_transmittedPayloadsLogPath { + + return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles transmittedPayloadsLog]]; +} + ++ (nonnull NSString *)_droppedPayloadsLogPath { - return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles payloadsLog]]; + return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles droppedPayloadsLog]]; } + (nonnull NSString *)_getSDKDataFilePath:(nonnull NSString *)sdkFileName { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index 8664dec5..189d756a 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -20,7 +20,8 @@ #define MAX_PAYLOAD_SIZE 128 // The maximum payload size in kb -static NSString *payloadsFilePath = nil; +static NSString *transmittedPayloadsFilePath = nil; +static NSString *droppedPayloadsFilePath = nil; static NSString *queuedItemsFilePath = nil; @implementation RollbarLogger { @@ -69,16 +70,29 @@ - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration { [self updateConfiguration:configuration]; NSString *cachesDirectory = [RollbarCachesDirectory directory]; - if (nil != self.configuration.developerOptions.payloadLogFile - && self.configuration.developerOptions.payloadLogFile.length > 0) { + + if (nil != self.configuration.developerOptions.transmittedPayloadLogFile + && self.configuration.developerOptions.transmittedPayloadLogFile.length > 0) { + + transmittedPayloadsFilePath = + [cachesDirectory stringByAppendingPathComponent:self.configuration.developerOptions.transmittedPayloadLogFile]; + } + else { + + transmittedPayloadsFilePath = + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles transmittedPayloadsLog]]; + } + + if (nil != self.configuration.developerOptions.droppedPayloadLogFile + && self.configuration.developerOptions.droppedPayloadLogFile.length > 0) { - payloadsFilePath = - [cachesDirectory stringByAppendingPathComponent:self.configuration.developerOptions.payloadLogFile]; + droppedPayloadsFilePath = + [cachesDirectory stringByAppendingPathComponent:self.configuration.developerOptions.droppedPayloadLogFile]; } else { - payloadsFilePath = - [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsLog]]; + droppedPayloadsFilePath = + [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles droppedPayloadsLog]]; } } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h index ca7b2267..40ed3e13 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h @@ -15,16 +15,15 @@ NS_ASSUME_NONNULL_BEGIN + (nonnull NSString * const)payloadsStore; -+ (nonnull NSString * const)itemsQueue; -+ (nonnull NSString * const)itemsQueueState; - + (nonnull NSString * const)telemetryQueue; + (nonnull NSString * const)runtimeSession; + (nonnull NSString * const)appQuit; -+ (nonnull NSString * const)payloadsLog; ++ (nonnull NSString * const)transmittedPayloadsLog ; + ++ (nonnull NSString * const)droppedPayloadsLog; + (nonnull NSString * const)config; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m index cd24d84f..df9b4f2f 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m @@ -1,11 +1,9 @@ #import "RollbarNotifierFiles.h" -static NSString * const PAYLOADS_FILE_NAME = @"rollbar.payloads"; - static NSString * const PAYLOADS_STORE_FILE_NAME = @"rollbar.db"; -static NSString * const QUEUED_ITEMS_FILE_NAME = @"rollbar.items"; -static NSString * const QUEUED_ITEMS_STATE_FILE_NAME = @"rollbar.state"; +static NSString * const TRANSMITTED_PAYLOADS_FILE_NAME = @"rollbar.transmitted"; +static NSString * const DROPPED_PAYLOADS_FILE_NAME = @"rollbar.dropped"; static NSString * const QUEUED_TELEMETRY_ITEMS_FILE_NAME = @"rollbar.telemetry"; @@ -21,16 +19,6 @@ + (nonnull NSString * const)payloadsStore { return PAYLOADS_STORE_FILE_NAME; } -+ (nonnull NSString * const)itemsQueue { - - return QUEUED_ITEMS_FILE_NAME; -} - -+ (nonnull NSString * const)itemsQueueState { - - return QUEUED_ITEMS_STATE_FILE_NAME; -} - + (nonnull NSString * const)telemetryQueue { return QUEUED_TELEMETRY_ITEMS_FILE_NAME; @@ -46,9 +34,14 @@ + (nonnull NSString * const)appQuit { return APP_QUIT_FILE_NAME; } -+ (nonnull NSString * const)payloadsLog { ++ (nonnull NSString * const)transmittedPayloadsLog { + + return TRANSMITTED_PAYLOADS_FILE_NAME; +} + ++ (nonnull NSString * const)droppedPayloadsLog { - return PAYLOADS_FILE_NAME; + return DROPPED_PAYLOADS_FILE_NAME; } + (nonnull NSString * const)config { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m index 65d06cc0..8b209ab9 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarSender.m @@ -51,10 +51,10 @@ - (nullable RollbarPayloadPostReply *)sendPayload:(nonnull NSData *)payload if (reply && (200 == reply.statusCode)) { [RollbarSender trace:[NSString stringWithFormat:@"Transmitted payload: %@", payloadString] withOptions:config.developerOptions]; - if ((YES == config.developerOptions.logPayload) && config.developerOptions.payloadLogFile) { - [RollbarFileWriter appendSafelyData:payload toFile:config.developerOptions.payloadLogFile]; - //TODO: complete implementation (log into payloads log file)... - } +// if ((YES == config.developerOptions.logTransmittedPayloads) && config.developerOptions.transmittedPayloadLogFile) { +// [RollbarFileWriter appendSafelyData:payload toFile:config.developerOptions.transmittedPayloadLogFile]; +// //TODO: complete implementation (log into payloads log file)... +// } } else if (reply) { [RollbarSender trace:[NSString stringWithFormat:@"Failed to transmit payload (%li status code): %@", (long)reply.statusCode, payloadString] diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h index 119340a1..75f580ca 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.h @@ -15,8 +15,8 @@ NS_ASSUME_NONNULL_BEGIN - (void)persistPayload:(nonnull RollbarPayload *)payload withConfig:(nonnull RollbarConfig *)config; -- (BOOL)sendPayload:(nonnull NSData *)payload - usingConfig:(nonnull RollbarConfig *)config; +- (RollbarTriStateFlag)sendPayload:(nonnull NSData *)payload + usingConfig:(nonnull RollbarConfig *)config; /// Hides the initializer. - (instancetype)init NS_UNAVAILABLE; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 7d4e16ba..8f17becf 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -210,6 +210,8 @@ - (void)checkItems { - (void)processSavedPayload:(nonnull NSDictionary *)payloadDataRow { + //TODO: implement detection of stale payload and remove from the repo if it is stale... + NSString *destinationKey = payloadDataRow[@"destination_key"]; NSAssert(destinationKey && destinationKey.length > 0, @"destination_key is expected to be defined!"); NSDictionary *destination = [self->_payloadsRepo getDestinationByID:destinationKey]; @@ -230,10 +232,10 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl NSString *payloadJson = payloadDataRow[@"payload_json"]; RollbarPayload *payload = [[RollbarPayload alloc] initWithJSONString:payloadJson]; NSAssert(payload, @"payload is expected to be defined!"); - - + //TODO: the following payload truncation code should eventually move to the point right before payload persistence // into the repo: + NSMutableDictionary *newPayload = [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; [RollbarPayloadTruncator truncatePayload:newPayload]; @@ -246,25 +248,15 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl newPayload = [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; } - - - - NSError *error; + NSError *error; NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:newPayload options:0 error:&error safe:true]; if (nil == jsonPayload) { - - RollbarSdkLog( - @"Couldn't send jsonPayload that is nil" - ); + RollbarSdkLog(@"Couldn't send jsonPayload that is nil"); if (nil != error) { - - RollbarSdkLog( - @" DETAILS: an error while generating JSON data: %@", - error - ); + RollbarSdkLog(@" DETAILS: an error while generating JSON data: %@", error); } // there is nothing we can do with this payload - let's drop it: RollbarSdkLog(@"Dropping unprocessable payload: %@", payloadJson); @@ -274,36 +266,65 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl return; } - if (config.developerOptions.logPayload) { - - if (!config.developerOptions.suppressSdkInfoLogging) { - - RollbarSdkLog(@"About to send payload: %@", - [[NSString alloc] initWithData:jsonPayload - encoding:NSUTF8StringEncoding] - ); - } - - // - save this payload into a proper payloads log file: - //***************************************************** - - // compose the payloads log file path: + RollbarTriStateFlag success = config ? [self sendPayload:jsonPayload usingConfig:config] + : [self sendPayload:jsonPayload]; // backward compatibility with just upgraded very old SDKs... + + NSString *payloadsLogFile = nil; + NSString *sdkLogTrace = (RollbarTriStateFlag_None == success) ? nil + : [NSString stringWithFormat:@"%@ payload: %@", + (RollbarTriStateFlag_On == success) ? @"Transmitted" : @"Dropped", + [[NSString alloc] initWithData:jsonPayload encoding:NSUTF8StringEncoding] + ]; + switch(success) { + case RollbarTriStateFlag_On: + // The payload is fully processed and transmitted. + // It can be removed from the repo: + if (![self->_payloadsRepo removePayloadByID:payloadDataRow[@"id"]]) { + RollbarSdkLog(@"Couldn't remove payload data row with ID: %@", payloadDataRow[@"id"]); + } + if (config.developerOptions.logTransmittedPayloads) { + payloadsLogFile = config.developerOptions.transmittedPayloadLogFile; + } + break; + case RollbarTriStateFlag_Off: + // The payload is fully processed but not accepted by the server due to some invalid content. + // It must be removed from the repo: + if (![self->_payloadsRepo removePayloadByID:payloadDataRow[@"id"]]) { + RollbarSdkLog(@"Couldn't remove payload data row with ID: %@", payloadDataRow[@"id"]); + } + if (config.developerOptions.logDroppedPayloads) { + payloadsLogFile = config.developerOptions.droppedPayloadLogFile; + } + break; + case RollbarTriStateFlag_None: + default: + // Nothing obviously wrong with the payload but it was not actually tranmitted successfully. + // Let's try again some other time. Keep it in the repo for now (unless it is already too stale)... + //TODO: implement detection of stale payload and remove from the repo if it is stale... + break; + } + + if (payloadsLogFile) { NSString *cachesDirectory = [RollbarCachesDirectory directory]; - NSString *payloadsLogFilePath = - [cachesDirectory stringByAppendingPathComponent:config.developerOptions.payloadLogFile]; + NSString *payloadsLogFilePath = [cachesDirectory stringByAppendingPathComponent:payloadsLogFile]; [RollbarFileWriter appendSafelyData:jsonPayload toFile:payloadsLogFilePath]; } - - - BOOL success = config ? [self sendPayload:jsonPayload usingConfig:config] - : [self sendPayload:jsonPayload]; // backward compatibility with just upgraded very old SDKs... - - if (success) { - // we a successful sending - can remove the repo data row: - if (![self->_payloadsRepo removePayloadByID:payloadDataRow[@"id"]]) { - RollbarSdkLog(@"Couldn't remove payload data row with ID: %@", payloadDataRow[@"id"]); + if (!config.developerOptions.suppressSdkInfoLogging) { + NSString *sdkLogTrace = nil; + switch(success) { + case RollbarTriStateFlag_On: + RollbarSdkLog(@"Transmitted payload: %@", + [[NSString alloc] initWithData:jsonPayload encoding:NSUTF8StringEncoding]); + break; + case RollbarTriStateFlag_Off: + RollbarSdkLog(@"Dropped payload: %@", + [[NSString alloc] initWithData:jsonPayload encoding:NSUTF8StringEncoding]); + break; + case RollbarTriStateFlag_None: + RollbarSdkLog(@"Couldn't transmit (and will try) payload: %@", + [[NSString alloc] initWithData:jsonPayload encoding:NSUTF8StringEncoding]); + break; } - return; } } @@ -323,35 +344,49 @@ - (void)processSavedItems { } } -- (BOOL)sendPayload:(nonnull NSData *)payload - usingConfig:(nonnull RollbarConfig *)config { +- (RollbarTriStateFlag)sendPayload:(nonnull NSData *)payload + usingConfig:(nonnull RollbarConfig *)config { if (!payload || !config) { - return NO; + return RollbarTriStateFlag_Off; //obviously invalid payload to sent or invalid destination... } RollbarDestinationRecord *record = [self->_registry getRecordForConfig:config]; if (![record canPost]) { - return NO; + return RollbarTriStateFlag_None; // nothing obviously wrong with the payload - just can not send at the moment } RollbarPayloadPostReply *reply = [[RollbarSender new] sendPayload:payload usingConfig:config ]; [record recordPostReply:reply]; - if (reply && (200 == reply.statusCode)) { - return YES; + + if (!reply) { + return RollbarTriStateFlag_None; // nothing obviously wrong with the payload - just there was no deterministic + // reply from the destination server } - return NO; + switch(reply.statusCode) { + case 200: // OK + return RollbarTriStateFlag_On; // the payload was successfully transmitted + case 400: // bad request + case 413: // request entity too large + case 422: // unprocessable entity + return RollbarTriStateFlag_Off; // unecceptable request/payload - should be dropped + case 403: // access denied + case 404: // not found + case 429: // too many requests + default: + return RollbarTriStateFlag_None; // worth retrying later + } } /// This is a DEPRECATED method left for some backward compatibility for very old clients eventually moving to this more recent implementation. /// Use/maintain sendPayload:usingConfig: instead! -- (BOOL)sendPayload:(NSData *)payload { +- (RollbarTriStateFlag)sendPayload:(NSData *)payload { - return YES; + return RollbarTriStateFlag_Off; } #pragma mark - Network telemetry data diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h index 0489cf26..38a9e7e0 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h @@ -19,31 +19,46 @@ NS_ASSUME_NONNULL_BEGIN /// A flag to suppress internal SDK's informational logging @property (nonatomic, readonly) BOOL suppressSdkInfoLogging; -/// Flags if the processed payloads to be logged locally -@property (nonatomic, readonly) BOOL logPayload; +/// Flags if the transmitted payloads to be logged locally +@property (nonatomic, readonly) BOOL logTransmittedPayloads; -/// Log file to use for local logged payloads -@property (nonatomic, readonly, copy) NSString *payloadLogFile; +/// Flags if the dropped payloads to be logged locally +@property (nonatomic, readonly) BOOL logDroppedPayloads; + +/// Log file to use for local logged transmitted payloads +@property (nonatomic, readonly, copy) NSString *transmittedPayloadLogFile; + +/// Log file to use for local logged dropped payloads +@property (nonatomic, readonly, copy) NSString *droppedPayloadLogFile; #pragma mark - initializers /// Initializer /// @param enabled enabled flag /// @param transmit payloads transmission flag -/// @param logPayload local payloads logging flag -/// @param logPayloadFile pocal payloads logging file +/// @param logTransmittedPayloads flag to log transmitted payloads locally +/// @param logDroppedPayloads flag to log dropped payloads locally +/// @param transmittedPayloadsLogFile file to log transmitted payloads to +/// @param droppedPayloadsLogFile file to log dropped payloads to - (instancetype)initWithEnabled:(BOOL)enabled transmit:(BOOL)transmit - logPayload:(BOOL)logPayload - payloadLogFile:(NSString *)logPayloadFile; + logTransmittedPayloads:(BOOL)logTransmittedPayloads + logDroppedPayloads:(BOOL)logDroppedPayloads + transmittedPayloadsLogFile:(NSString *)logTransmittedPayloadsFile + droppedPayloadsLogFile:(NSString *)logDroppedPayloadsFile; /// Initializer /// @param enabled enabled flag /// @param transmit payloads transmission flag -/// @param logPayload local payloads logging flag +/// @param logTransmittedPayloads flag to log transmitted payloads locally +/// @param logDroppedPayloads flag to log dropped payloads locally - (instancetype)initWithEnabled:(BOOL)enabled transmit:(BOOL)transmit - logPayload:(BOOL)logPayload; + logTransmittedPayloads:(BOOL)logTransmittedPayloads + logDroppedPayloads:(BOOL)logDroppedPayloads; + +/// Initializer +/// @param enabled flag enabling/suspending the SDK operation - (instancetype)initWithEnabled:(BOOL)enabled; @end @@ -61,11 +76,17 @@ NS_ASSUME_NONNULL_BEGIN /// A flag to suppress internal SDK's informational logging @property (nonatomic, readwrite) BOOL suppressSdkInfoLogging; -/// Flags if the processed payloads to be logged locally -@property (nonatomic, readwrite) BOOL logPayload; +/// Flags if the transmitted payloads to be logged locally +@property (nonatomic, readwrite) BOOL logTransmittedPayloads; + +/// Flags if the dropped payloads to be logged locally +@property (nonatomic, readwrite) BOOL logDroppedPayloads; + +/// Log file to use for local logged transmitted payloads +@property (nonatomic, readwrite, copy) NSString *transmittedPayloadLogFile; -/// Log file to use for local logged payloads -@property (nonatomic, readwrite, copy) NSString *payloadLogFile; +/// Log file to use for local logged dropped payloads +@property (nonatomic, readwrite, copy) NSString *droppedPayloadLogFile; @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger+Test.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger+Test.h index 02768c68..9b8f56e8 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger+Test.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger+Test.h @@ -14,22 +14,18 @@ NS_ASSUME_NONNULL_BEGIN ///@note THIS METHOD IS TO BE USED FOR TESTING PURPOSES ONLY. + (void)flushRollbarThread; -/// Reads all the payloads queued up in the persistent store +/// Reads all payloads from the default transmitted payloads log ///@note THIS METHOD IS TO BE USED FOR TESTING PURPOSES ONLY. -+ (nonnull NSArray *)readLogItemsFromStore; ++ (nonnull NSArray *)readPayloadsFromSdkTransmittedLog; -/// Reads all payloads from the default payloads log +/// Reads all payloads from the default dropped payloads log ///@note THIS METHOD IS TO BE USED FOR TESTING PURPOSES ONLY. -+ (nonnull NSArray *)readPayloadsFromSdkLog; ++ (nonnull NSArray *)readPayloadsFromSdkDroppedLog; /// Reads all payloads from the provided file path ///@note THIS METHOD IS TO BE USED FOR TESTING PURPOSES ONLY. + (nonnull NSArray *)readPayloadsDataFromFile:(nonnull NSString *)filePath; -/// Clears all the payloads queued up in the persistent store -///@note THIS METHOD IS TO BE USED FOR TESTING PURPOSES ONLY. -+ (void)clearLogItemsStore; - /// Clears all the SDK persisted data ///@note THIS METHOD IS TO BE USED FOR TESTING PURPOSES ONLY. + (void)clearSdkDataStore; From be4f6992e86e39b51f2bb5a841f72091394eb8e6 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 19 Aug 2022 18:09:21 -0700 Subject: [PATCH 094/127] test: refactored the unit tests to build --- .../PayloadTruncationTests.m | 10 +++---- .../RollbarConfigTests.m | 30 +++++++++---------- .../RollbarConfigurationTests.m | 20 ++++++------- .../RollbarInfrastructureTests.m | 22 +++++++------- .../RollbarTelemetryTests.m | 4 +-- .../RollbarNotifierTests-ObjC/RollbarTests.m | 6 ++-- .../RollbarNotifierLoggerTests.swift | 6 ++-- 7 files changed, 50 insertions(+), 48 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m index 15f23e9b..50790244 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m @@ -26,7 +26,7 @@ - (void)setUp { [RollbarTestUtil waitForPesistenceToCompleteWithWaitTimeInSeconds:3]; [RollbarLogger clearSdkDataStore]; - NSArray *items = [RollbarLogger readLogItemsFromStore]; + NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertEqual(items.count, 0); } @@ -188,7 +188,7 @@ - (void)testVisuallyTruncateStringToTotalBytesUnicode { - (void)testPayloadTruncation { //[NSThread sleepForTimeInterval:5.0f]; - NSArray *items = [RollbarLogger readLogItemsFromStore]; + NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertEqual(items.count, 0); @try { @@ -205,7 +205,7 @@ - (void)testPayloadTruncation { [RollbarLogger flushRollbarThread]; - items = [RollbarLogger readLogItemsFromStore]; + items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; for (id payload in items) { NSMutableArray *frames = [payload mutableArrayValueForKeyPath:@"body.trace.frames"]; @@ -249,11 +249,11 @@ - (void)testErrorReportingWithTruncation { [Rollbar criticalMessage:simulatedLongString data:@{@"extra_truncatable_data": simulatedLongString} ]; - NSArray *items = [RollbarLogger readLogItemsFromStore]; + NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertTrue(items.count > 0); [NSThread sleepForTimeInterval:5.0f]; - items = [RollbarLogger readLogItemsFromStore]; + items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertEqual(items.count, 0); } } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m index 145524cd..40ff9127 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m @@ -80,24 +80,24 @@ - (void)testRollbarDeveloperOptions { mutable.enabled = NO; mutable.transmit = NO; mutable.suppressSdkInfoLogging = NO; - mutable.logPayload = NO; - mutable.payloadLogFile = @"test_PAYLOADS.LOG_old"; + mutable.logTransmittedPayloads = NO; + mutable.transmittedPayloadLogFile = @"test_PAYLOADS.LOG_old"; XCTAssertFalse(mutable.enabled); XCTAssertFalse(mutable.transmit); XCTAssertFalse(mutable.suppressSdkInfoLogging); - XCTAssertFalse(mutable.logPayload); - XCTAssertTrue([mutable.payloadLogFile isEqualToString:@"test_PAYLOADS.LOG_old"]); + XCTAssertFalse(mutable.logTransmittedPayloads); + XCTAssertTrue([mutable.transmittedPayloadLogFile isEqualToString:@"test_PAYLOADS.LOG_old"]); mutable.enabled = YES; mutable.transmit = YES; mutable.suppressSdkInfoLogging = YES; - mutable.logPayload = YES; - mutable.payloadLogFile = @"test_PAYLOADS.LOG"; + mutable.logTransmittedPayloads = YES; + mutable.transmittedPayloadLogFile = @"test_PAYLOADS.LOG"; XCTAssertTrue(mutable.enabled); XCTAssertTrue(mutable.transmit); XCTAssertTrue(mutable.suppressSdkInfoLogging); - XCTAssertTrue(mutable.logPayload); - XCTAssertTrue([mutable.payloadLogFile isEqualToString:@"test_PAYLOADS.LOG"]); + XCTAssertTrue(mutable.logTransmittedPayloads); + XCTAssertTrue([mutable.transmittedPayloadLogFile isEqualToString:@"test_PAYLOADS.LOG"]); NSString *content = [mutable serializeToJSONString]; XCTAssertNotNil(content); @@ -108,8 +108,8 @@ - (void)testRollbarDeveloperOptions { XCTAssertTrue(immutable.enabled); XCTAssertTrue(immutable.transmit); XCTAssertTrue(immutable.suppressSdkInfoLogging); - XCTAssertTrue(immutable.logPayload); - XCTAssertTrue([immutable.payloadLogFile isEqualToString:@"test_PAYLOADS.LOG"]); + XCTAssertTrue(immutable.logTransmittedPayloads); + XCTAssertTrue([immutable.transmittedPayloadLogFile isEqualToString:@"test_PAYLOADS.LOG"]); content = [immutable serializeToJSONString]; XCTAssertNotNil(content); @@ -593,11 +593,11 @@ - (void)testRollbarConfig { RollbarMutableConfig *mutable = [RollbarMutableConfig new]; mutable.destination.accessToken = @"test_AT_old"; RollbarMutableDeveloperOptions *devOptions = [RollbarMutableDeveloperOptions new]; - devOptions.payloadLogFile = @"test_PL_old"; + devOptions.transmittedPayloadLogFile = @"test_PL_old"; mutable.developerOptions = devOptions; XCTAssertTrue([mutable.destination.accessToken isEqualToString:@"test_AT_old"]); - XCTAssertTrue([mutable.developerOptions.payloadLogFile isEqualToString:@"test_PL_old"]); + XCTAssertTrue([mutable.developerOptions.transmittedPayloadLogFile isEqualToString:@"test_PL_old"]); NSString *content = [mutable serializeToJSONString]; XCTAssertNotNil(content); @@ -605,10 +605,10 @@ - (void)testRollbarConfig { XCTAssertTrue([content containsString:@"test_PL_old"]); mutable.destination.accessToken = @"test_AT"; - mutable.developerOptions.payloadLogFile = @"test_PL"; + mutable.developerOptions.transmittedPayloadLogFile = @"test_PL"; XCTAssertTrue([mutable.destination.accessToken isEqualToString:@"test_AT"]); - XCTAssertTrue([mutable.developerOptions.payloadLogFile isEqualToString:@"test_PL"]); + XCTAssertTrue([mutable.developerOptions.transmittedPayloadLogFile isEqualToString:@"test_PL"]); content = [mutable serializeToJSONString]; XCTAssertNotNil(content); @@ -620,7 +620,7 @@ - (void)testRollbarConfig { RollbarConfig *immutable = [mutable copy]; XCTAssertTrue([immutable.destination.accessToken isEqualToString:@"test_AT"]); - XCTAssertTrue([immutable.developerOptions.payloadLogFile isEqualToString:@"test_PL"]); + XCTAssertTrue([immutable.developerOptions.transmittedPayloadLogFile isEqualToString:@"test_PL"]); content = [immutable serializeToJSONString]; XCTAssertNotNil(content); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index 5b275800..b40d502a 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -26,7 +26,7 @@ - (void)setUp { [NSThread sleepForTimeInterval:1.0f]; [RollbarLogger clearSdkDataStore]; - NSArray *items = [RollbarLogger readLogItemsFromStore]; + NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertEqual(items.count, 0); } @@ -40,7 +40,7 @@ - (void)tearDown { - (BOOL)rollbarStoreContains:(nonnull NSString *)string { [RollbarLogger flushRollbarThread]; - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; for (NSDictionary *item in logItems) { RollbarPayload *payload = [[RollbarPayload alloc] initWithDictionary:item]; if ([[payload serializeToJSONString] containsString:string]) { @@ -87,7 +87,7 @@ - (void)testScrubSafeListFields { [RollbarLogger flushRollbarThread]; // verify the fields were scrubbed: - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; for (NSString *key in keys) { NSString *content = [logItems[0] valueForKeyPath:key]; XCTAssertTrue([content isEqualToString:scrubedContent], @@ -110,7 +110,7 @@ - (void)testScrubSafeListFields { [RollbarLogger flushRollbarThread]; // verify the fields were not scrubbed: - logItems = [RollbarLogger readLogItemsFromStore]; + logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; for (NSString *key in keys) { NSString *content = [logItems[0] valueForKeyPath:key]; XCTAssertTrue(![content isEqualToString:scrubedContent], @@ -228,7 +228,7 @@ - (void)testEnabled { [RollbarLogger clearSdkDataStore]; - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertTrue(logItems.count == 0, @"logItems count is expected to be 0. Actual value is %lu", (unsigned long) logItems.count @@ -273,7 +273,7 @@ - (void)testMaximumTelemetryEvents { [Rollbar debugMessage:@"Test"]; [RollbarLogger flushRollbarThread]; - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; NSDictionary *item = logItems[logItems.count - 1]; NSArray *telemetryData = [item valueForKeyPath:@"body.telemetry"]; XCTAssertTrue(telemetryData.count == max, @@ -314,7 +314,7 @@ - (void)testServerData { [RollbarLogger flushRollbarThread]; - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; NSDictionary *item = logItems[0]; NSDictionary *server = item[@"server"]; @@ -356,7 +356,7 @@ - (void)testPayloadModification { [RollbarLogger flushRollbarThread]; - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; NSString *msg1 = [logItems[0] valueForKeyPath:@"body.message.body"]; NSString *msg2 = [logItems[0] valueForKeyPath:@"body.message.body2"]; @@ -386,7 +386,7 @@ - (void)testScrubField { [RollbarLogger flushRollbarThread]; - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; for (NSString *key in keys) { NSString *content = [logItems[0] valueForKeyPath:key]; XCTAssertTrue([content isEqualToString:scrubedContent], @@ -417,7 +417,7 @@ - (void)testLogTelemetryAutoCapture { [RollbarLogger flushRollbarThread]; - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; NSArray *telemetryData = [logItems[0] valueForKeyPath:@"body.telemetry"]; NSString *telemetryMsg = [telemetryData[0] valueForKeyPath:@"body.message"]; XCTAssertTrue([logMsg isEqualToString:telemetryMsg], diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index 1775c549..379d7146 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -49,10 +49,10 @@ - (void)test1_RollbarInfrastructureNotConfiguredException { - (void)test2_Basics { [RollbarLogger clearSdkDataStore]; - NSArray *items = [RollbarLogger readLogItemsFromStore]; + NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - items = [RollbarLogger readPayloadsFromSdkLog]; + items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); @@ -61,12 +61,12 @@ - (void)test2_Basics { environment:[RollbarTestHelper getRollbarEnvironment] ]; config.developerOptions.transmit = NO; - config.developerOptions.logPayload = YES; + config.developerOptions.logTransmittedPayloads = YES; config.loggingOptions.maximumReportsPerMinute = 180; [[RollbarInfrastructure sharedInstance] configureWith:config]; [NSThread sleepForTimeInterval:1.0f]; - items = [RollbarLogger readPayloadsFromSdkLog]; + items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertNotNil(items); [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical @@ -87,10 +87,10 @@ - (void)test2_Basics { XCTAssertTrue(YES == wasLogged); [RollbarLogger clearSdkDataStore]; - items = [RollbarLogger readLogItemsFromStore]; + items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - items = [RollbarLogger readPayloadsFromSdkLog]; + items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); } @@ -98,10 +98,10 @@ - (void)test2_Basics { - (void)test3_Live { [RollbarLogger clearSdkDataStore]; - NSArray *items = [RollbarLogger readLogItemsFromStore]; + NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - items = [RollbarLogger readPayloadsFromSdkLog]; + items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); @@ -109,7 +109,7 @@ - (void)test3_Live { [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] environment:[RollbarTestHelper getRollbarEnvironment]]; config.developerOptions.transmit = YES; - config.developerOptions.logPayload = YES; + config.developerOptions.logTransmittedPayloads = YES; [[RollbarInfrastructure sharedInstance] configureWith:config]; @@ -134,10 +134,10 @@ - (void)test3_Live { XCTAssertTrue(YES == wasLogged); [RollbarLogger clearSdkDataStore]; - items = [RollbarLogger readLogItemsFromStore]; + items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - items = [RollbarLogger readPayloadsFromSdkLog]; + items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m index 749804b9..994facd7 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m @@ -45,7 +45,7 @@ - (void)testTelemetryCapture { [RollbarLogger flushRollbarThread]; - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; NSDictionary *item = logItems[logItems.count - 1]; NSArray *telemetryData = [item valueForKeyPath:@"body.telemetry"]; XCTAssertTrue(telemetryData.count > 0); @@ -98,7 +98,7 @@ - (void)testErrorReportingWithTelemetry { //[NSThread sleepForTimeInterval:8.0f]; - NSArray *logItems = [RollbarLogger readLogItemsFromStore]; + NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; for (NSDictionary *item in logItems) { NSArray *telemetryData = [item valueForKeyPath:@"body.telemetry"]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m index 32488c0f..ca242466 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m @@ -22,7 +22,7 @@ - (void)setUp { config.destination.accessToken = [RollbarTestHelper getRollbarPayloadsAccessToken]; config.destination.environment = [RollbarTestHelper getRollbarEnvironment]; config.developerOptions.transmit = YES; - config.developerOptions.logPayload = YES; + config.developerOptions.logTransmittedPayloads = YES; config.loggingOptions.maximumReportsPerMinute = 5000; // for the stress test specifically: config.telemetry.enabled = YES; @@ -66,7 +66,7 @@ - (void)testRollbarNotifiersIndependentConfiguration { RollbarMutableConfig *config = [[RollbarMutableConfig alloc] init]; config.developerOptions.transmit = NO; - config.developerOptions.logPayload = YES; + config.developerOptions.logTransmittedPayloads = YES; // configure the root notifier: config.destination.accessToken = @"AT_0"; @@ -168,7 +168,7 @@ - (void)testNotification { [NSThread sleepForTimeInterval:3.0f]; - NSArray *items = [RollbarLogger readLogItemsFromStore]; + NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; for (id item in items) { NSString *level = [item valueForKeyPath:@"level"]; NSString *message = [item valueForKeyPath:@"body.message.body"]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift index c531be60..850781e6 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift @@ -20,7 +20,8 @@ final class RollbarNotifierLoggerTests: XCTestCase { environment: RollbarTestHelper.getRollbarEnvironment() ); config.developerOptions.transmit = true; - config.developerOptions.logPayload = true; + config.developerOptions.logTransmittedPayloads = true; + config.developerOptions.logDroppedPayloads = true; config.loggingOptions.maximumReportsPerMinute = 5000; config.customData = ["someKey": "someValue", ]; Rollbar.update(withConfiguration: config); @@ -45,7 +46,8 @@ final class RollbarNotifierLoggerTests: XCTestCase { var config = Rollbar.configuration().mutableCopy(); config.developerOptions.transmit = false; - config.developerOptions.logPayload = true; + config.developerOptions.logTransmittedPayloads = true; + config.developerOptions.logDroppedPayloads = true; // configure the shared notifier: config.destination.accessToken = "AT_0"; From 687d8094e95c372890e4b645ddec8513d30840cd Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 19 Aug 2022 22:06:47 -0700 Subject: [PATCH 095/127] feat: incoming payloads local logging and payload modifications on save feat: configurable local logging of incoming payloads and payload modifications on save only (once vs on sending attempts) --- .../DTOs/RollbarDeveloperOptions.m | 32 +++ .../RollbarNotifier/RollbarLogger+Test.m | 12 + .../RollbarNotifier/RollbarNotifierFiles.h | 2 + .../RollbarNotifier/RollbarNotifierFiles.m | 6 + .../RollbarNotifier/RollbarPayloadFactory.m | 214 +++++++++--------- .../Sources/RollbarNotifier/RollbarThread.m | 213 +++++++++++++++-- .../include/RollbarDeveloperOptions.h | 22 +- .../include/RollbarLogger+Test.h | 4 + 8 files changed, 379 insertions(+), 126 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m index b8631294..b1c853c5 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m @@ -6,6 +6,7 @@ static BOOL const DEFAULT_ENABLED_FLAG = YES; static BOOL const DEFAULT_TRANSMIT_FLAG = YES; static BOOL const DEFAULT_SUPPRESS_SDK_INFO_LOGGING_FLAG = NO; +static BOOL const DEFAULT_LOG_INCOMING_PAYLOADS_FLAG = NO; static BOOL const DEFAULT_LOG_TRANSMITTED_PAYLOADS_FLAG = NO; static BOOL const DEFAULT_LOG_DROPPED_PAYLOADS_FLAG = NO; @@ -14,6 +15,9 @@ static NSString * const DFK_ENABLED = @"enabled"; static NSString * const DFK_TRANSMIT = @"transmit"; static NSString * const DFK_SUPPRESS_SDK_INFO_LOGGING = @"suppressSdkInfoLogging"; + +static NSString * const DFK_LOG_INCOMING_PAYLOADS = @"logIncomingPayload"; +static NSString * const DFK_LOG_INCOMING_PAYLOADS_FILE = @"logIncomingPayloadsFile"; static NSString * const DFK_LOG_TRANSMITTED_PAYLOADS = @"logTransmittedsPayload"; static NSString * const DFK_LOG_TRANSMITTED_PAYLOADS_FILE = @"logTransmittedPayloadsFile"; static NSString * const DFK_LOG_DROPPED_PAYLOADS = @"logDroppedsPayload"; @@ -27,8 +31,10 @@ @implementation RollbarDeveloperOptions - (instancetype)initWithEnabled:(BOOL)enabled transmit:(BOOL)transmit + logIncomingPayloads:(BOOL)logIncomingPayloads logTransmittedPayloads:(BOOL)logTransmittedPayloads logDroppedPayloads:(BOOL)logDroppedPayloads + incomingPayloadsLogFile:(NSString *)logIncomingPayloadsFile transmittedPayloadsLogFile:(NSString *)logTransmittedPayloadsFile droppedPayloadsLogFile:(NSString *)logDroppedPayloadsFile { @@ -36,8 +42,10 @@ - (instancetype)initWithEnabled:(BOOL)enabled DFK_ENABLED:[NSNumber numberWithBool:enabled], DFK_TRANSMIT:[NSNumber numberWithBool:transmit], DFK_SUPPRESS_SDK_INFO_LOGGING:[NSNumber numberWithBool:DEFAULT_SUPPRESS_SDK_INFO_LOGGING_FLAG], + DFK_LOG_INCOMING_PAYLOADS:[NSNumber numberWithBool:logIncomingPayloads], DFK_LOG_TRANSMITTED_PAYLOADS:[NSNumber numberWithBool:logTransmittedPayloads], DFK_LOG_DROPPED_PAYLOADS:[NSNumber numberWithBool:logDroppedPayloads], + DFK_LOG_INCOMING_PAYLOADS_FILE:logIncomingPayloadsFile, DFK_LOG_TRANSMITTED_PAYLOADS_FILE:logTransmittedPayloadsFile, DFK_LOG_DROPPED_PAYLOADS_FILE:logDroppedPayloadsFile }]; @@ -46,13 +54,16 @@ - (instancetype)initWithEnabled:(BOOL)enabled - (instancetype)initWithEnabled:(BOOL)enabled transmit:(BOOL)transmit + logIncomingPayloads:(BOOL)logIncomingPayloads logTransmittedPayloads:(BOOL)logTransmittedPayloads logDroppedPayloads:(BOOL)logDroppedPayloads { return [self initWithEnabled:enabled transmit:transmit + logIncomingPayloads:logIncomingPayloads logTransmittedPayloads:logTransmittedPayloads logDroppedPayloads:logDroppedPayloads + incomingPayloadsLogFile:[RollbarNotifierFiles incomingPayloadsLog] transmittedPayloadsLogFile:[RollbarNotifierFiles transmittedPayloadsLog] droppedPayloadsLogFile:[RollbarNotifierFiles droppedPayloadsLog] ]; @@ -62,6 +73,7 @@ - (instancetype)initWithEnabled:(BOOL)enabled { return [self initWithEnabled:enabled transmit:DEFAULT_TRANSMIT_FLAG + logIncomingPayloads:DEFAULT_LOG_INCOMING_PAYLOADS_FLAG logTransmittedPayloads:DEFAULT_LOG_TRANSMITTED_PAYLOADS_FLAG logDroppedPayloads:DEFAULT_LOG_DROPPED_PAYLOADS_FLAG]; } @@ -87,6 +99,16 @@ - (BOOL)suppressSdkInfoLogging { return [result boolValue]; } +- (BOOL)logIncomingPayloads { + NSNumber *result = [self safelyGetNumberByKey:DFK_LOG_INCOMING_PAYLOADS]; + return [result boolValue]; +} + +- (NSString *)incomingPayloadsLogFile { + NSString *result = [self safelyGetStringByKey:DFK_LOG_INCOMING_PAYLOADS_FILE]; + return result; +} + - (BOOL)logTransmittedPayloads { NSNumber *result = [self safelyGetNumberByKey:DFK_LOG_TRANSMITTED_PAYLOADS]; return [result boolValue]; @@ -114,6 +136,8 @@ @implementation RollbarMutableDeveloperOptions @dynamic enabled; @dynamic transmit; @dynamic suppressSdkInfoLogging; +@dynamic logIncomingPayloads; +@dynamic incomingPayloadLogFile; @dynamic logTransmittedPayloads; @dynamic transmittedPayloadLogFile; @dynamic logDroppedPayloads; @@ -133,6 +157,14 @@ - (void)setSuppressSdkInfoLogging:(BOOL)value { [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_SUPPRESS_SDK_INFO_LOGGING]; } +- (void)setLogIncomingPayloads:(BOOL)value { + [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_LOG_INCOMING_PAYLOADS]; +} + +- (void)setIncomingPayloadsLogFile:(NSString *)value { + [self setString:value forKey:DFK_LOG_INCOMING_PAYLOADS_FILE]; +} + - (void)setLogTransmittedPayloads:(BOOL)value { [self setNumber:[[NSNumber alloc] initWithBool:value] forKey:DFK_LOG_TRANSMITTED_PAYLOADS]; } diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m index c25380af..c599ae9b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m @@ -10,6 +10,8 @@ + (void)clearSdkDataStore { [RollbarLogger _clearFile:[RollbarLogger _logPayloadsStorePath]]; [RollbarLogger _clearFile:[RollbarLogger _telemetryItemsStorePath]]; + + [RollbarLogger _clearFile:[RollbarLogger _incomingPayloadsLogPath]]; [RollbarLogger _clearFile:[RollbarLogger _transmittedPayloadsLogPath]]; [RollbarLogger _clearFile:[RollbarLogger _droppedPayloadsLogPath]]; } @@ -20,6 +22,11 @@ + (void)clearSdkFile:(nonnull NSString *)sdkFileName { [RollbarLogger _clearFile:[RollbarLogger _getSDKDataFilePath:sdkFileName]]; } ++ (nonnull NSArray *)readPayloadsFromSdkIncomingLog { + + [RollbarLogger readPayloadsDataFromFile:[RollbarLogger _incomingPayloadsLogPath]]; +} + + (nonnull NSArray *)readPayloadsFromSdkTransmittedLog { [RollbarLogger readPayloadsDataFromFile:[RollbarLogger _transmittedPayloadsLogPath]]; @@ -107,6 +114,11 @@ + (nonnull NSString *)_telemetryItemsStorePath { return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles telemetryQueue]]; } ++ (nonnull NSString *)_incomingPayloadsLogPath { + + return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles incomingPayloadsLog]]; +} + + (nonnull NSString *)_transmittedPayloadsLogPath { return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles transmittedPayloadsLog]]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h index 40ed3e13..b88c74dc 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h @@ -21,6 +21,8 @@ NS_ASSUME_NONNULL_BEGIN + (nonnull NSString * const)appQuit; ++ (nonnull NSString * const)incomingPayloadsLog ; + + (nonnull NSString * const)transmittedPayloadsLog ; + (nonnull NSString * const)droppedPayloadsLog; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m index df9b4f2f..d8b7f8cd 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.m @@ -2,6 +2,7 @@ static NSString * const PAYLOADS_STORE_FILE_NAME = @"rollbar.db"; +static NSString * const INCOMING_PAYLOADS_FILE_NAME = @"rollbar.incoming"; static NSString * const TRANSMITTED_PAYLOADS_FILE_NAME = @"rollbar.transmitted"; static NSString * const DROPPED_PAYLOADS_FILE_NAME = @"rollbar.dropped"; @@ -34,6 +35,11 @@ + (nonnull NSString * const)appQuit { return APP_QUIT_FILE_NAME; } ++ (nonnull NSString * const)incomingPayloadsLog { + + return INCOMING_PAYLOADS_FILE_NAME; +} + + (nonnull NSString * const)transmittedPayloadsLog { return TRANSMITTED_PAYLOADS_FILE_NAME; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m index 9f9e554e..d281fe9b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m @@ -114,112 +114,112 @@ - (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level #pragma mark - Payload custom modifiers based on the current config --(BOOL)shouldIgnoreRollbarData:(nonnull RollbarData *)incomingData { - - BOOL shouldIgnore = NO; - if (self->_config.checkIgnoreRollbarData) { - @try { - shouldIgnore = self->_config.checkIgnoreRollbarData(incomingData); - return shouldIgnore; - } @catch(NSException *e) { - RollbarSdkLog(@"checkIgnore error: %@", e.reason); - - // Remove checkIgnore to prevent future exceptions - //self->_config.checkIgnoreRollbarData = nil; - NSAssert(false, @"Provided checkIgnore implementation throws an exception!"); - - return NO; - } - } - - return shouldIgnore; -} +//-(BOOL)shouldIgnoreRollbarData:(nonnull RollbarData *)incomingData { +// +// BOOL shouldIgnore = NO; +// if (self->_config.checkIgnoreRollbarData) { +// @try { +// shouldIgnore = self->_config.checkIgnoreRollbarData(incomingData); +// return shouldIgnore; +// } @catch(NSException *e) { +// RollbarSdkLog(@"checkIgnore error: %@", e.reason); +// +// // Remove checkIgnore to prevent future exceptions +// //self->_config.checkIgnoreRollbarData = nil; +// NSAssert(false, @"Provided checkIgnore implementation throws an exception!"); +// +// return NO; +// } +// } +// +// return shouldIgnore; +//} --(RollbarData *)modifyRollbarData:(nonnull RollbarData *)incomingData { - - if (self->_config.modifyRollbarData) { - return self->_config.modifyRollbarData(incomingData); - } - return incomingData; -} +//-(RollbarData *)modifyRollbarData:(nonnull RollbarData *)incomingData { +// +// if (self->_config.modifyRollbarData) { +// return self->_config.modifyRollbarData(incomingData); +// } +// return incomingData; +//} --(RollbarData *)scrubRollbarData:(nonnull RollbarData *)incomingData { - - NSSet *scrubFieldsSet = [self getScrubFields]; - if (!scrubFieldsSet || scrubFieldsSet.count == 0) { - return incomingData; - } - - NSMutableDictionary *mutableJsonFriendlyData = incomingData.jsonFriendlyData.mutableCopy; - for (NSString *key in scrubFieldsSet) { - if ([mutableJsonFriendlyData valueForKeyPath:key]) { - [self createMutablePayloadWithData:mutableJsonFriendlyData forPath:key]; - [mutableJsonFriendlyData setValue:@"*****" forKeyPath:key]; - } - } - - return [[RollbarData alloc] initWithDictionary:mutableJsonFriendlyData]; -} +//-(RollbarData *)scrubRollbarData:(nonnull RollbarData *)incomingData { +// +// NSSet *scrubFieldsSet = [self getScrubFields]; +// if (!scrubFieldsSet || scrubFieldsSet.count == 0) { +// return incomingData; +// } +// +// NSMutableDictionary *mutableJsonFriendlyData = incomingData.jsonFriendlyData.mutableCopy; +// for (NSString *key in scrubFieldsSet) { +// if ([mutableJsonFriendlyData valueForKeyPath:key]) { +// [self createMutablePayloadWithData:mutableJsonFriendlyData forPath:key]; +// [mutableJsonFriendlyData setValue:@"*****" forKeyPath:key]; +// } +// } +// +// return [[RollbarData alloc] initWithDictionary:mutableJsonFriendlyData]; +//} --(NSSet *)getScrubFields { - - if (!self->_config.dataScrubber - || self->_config.dataScrubber.isEmpty - || !self->_config.dataScrubber.enabled - || !self->_config.dataScrubber.scrubFields - || self->_config.dataScrubber.scrubFields.count == 0) { - - return [NSSet set]; - } - - NSMutableSet *actualFieldsToScrub = self->_config.dataScrubber.scrubFields.mutableCopy; - if (self->_config.dataScrubber.safeListFields.count > 0) { - // actualFieldsToScrub = - // config.dataScrubber.scrubFields - config.dataScrubber.whitelistFields - // while using case insensitive field name comparison: - actualFieldsToScrub = [NSMutableSet new]; - for(NSString *key in self->_config.dataScrubber.scrubFields) { - BOOL isWhitelisted = false; - for (NSString *whiteKey in self->_config.dataScrubber.safeListFields) { - if (NSOrderedSame == [key caseInsensitiveCompare:whiteKey]) { - isWhitelisted = true; - } - } - if (!isWhitelisted) { - [actualFieldsToScrub addObject:key]; - } - } - } - - return actualFieldsToScrub; -} +//-(NSSet *)getScrubFields { +// +// if (!self->_config.dataScrubber +// || self->_config.dataScrubber.isEmpty +// || !self->_config.dataScrubber.enabled +// || !self->_config.dataScrubber.scrubFields +// || self->_config.dataScrubber.scrubFields.count == 0) { +// +// return [NSSet set]; +// } +// +// NSMutableSet *actualFieldsToScrub = self->_config.dataScrubber.scrubFields.mutableCopy; +// if (self->_config.dataScrubber.safeListFields.count > 0) { +// // actualFieldsToScrub = +// // config.dataScrubber.scrubFields - config.dataScrubber.whitelistFields +// // while using case insensitive field name comparison: +// actualFieldsToScrub = [NSMutableSet new]; +// for(NSString *key in self->_config.dataScrubber.scrubFields) { +// BOOL isWhitelisted = false; +// for (NSString *whiteKey in self->_config.dataScrubber.safeListFields) { +// if (NSOrderedSame == [key caseInsensitiveCompare:whiteKey]) { +// isWhitelisted = true; +// } +// } +// if (!isWhitelisted) { +// [actualFieldsToScrub addObject:key]; +// } +// } +// } +// +// return actualFieldsToScrub; +//} -- (void)createMutablePayloadWithData:(NSMutableDictionary *)data - forPath:(NSString *)path { - - NSArray *pathComponents = [path componentsSeparatedByString:@"."]; - NSString *currentPath = @""; - - for (int i=0; i_config.destination.accessToken data:data]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 8f17becf..7941ac52 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -142,6 +142,163 @@ - (void)persistPayload:(nonnull RollbarPayload *)payload ]; } ++ (BOOL)shouldIgnorePayload:(nonnull RollbarPayload *)payload + withConfig:(nonnull RollbarConfig *)config { + + if (config.checkIgnoreRollbarData) { + + BOOL shouldIgnore = NO; + @try { + shouldIgnore = config.checkIgnoreRollbarData(payload.data); + } + @catch(NSException *e) { + RollbarSdkLog(@"checkIgnore error: %@", e.reason); + NSAssert(false, @"Provided checkIgnore implementation throws an exception!"); + shouldIgnore = NO; + } + + if (shouldIgnore) { + + if (config.developerOptions.logDroppedPayloads + && config.developerOptions.incomingPayloadLogFile + && (config.developerOptions.incomingPayloadLogFile.length > 0) + ) { + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + NSString *payloadsLogFilePath = + [cachesDirectory stringByAppendingPathComponent:config.developerOptions.incomingPayloadLogFile]; + [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:payloadsLogFilePath]; + } + + if (!config.developerOptions.suppressSdkInfoLogging) { + RollbarSdkLog(@"Dropped payload (due to checkIgnore): %@", + [[NSString alloc] initWithData:[payload serializeToJSONData] + encoding:NSUTF8StringEncoding] + ); + } + + return YES; // ignore == nothing to queue... + } + } + + return NO; +} + ++ (nullable RollbarPayload *)modifyPayload:(nonnull RollbarPayload *)payload + withConfig:(nonnull RollbarConfig *)config { + + if (config.modifyRollbarData) { + + @try { + payload.data = config.modifyRollbarData(payload.data); + } + @catch(NSException *e) { + RollbarSdkLog(@"modifyRollbarData error: %@", e.reason); + NSAssert(false, @"Provided modifyRollbarData implementation throws an exception!"); + //return null; + } + } + return payload; +} + ++ (nullable RollbarPayload *)scrubPayload:(nonnull RollbarPayload *)payload + withConfig:(nonnull RollbarConfig *)config { + + NSSet *scrubFieldsSet = [RollbarThread getScrubFields:config.dataScrubber]; + if (scrubFieldsSet.count == 0) { + return payload; + } + + NSMutableDictionary *mutableJsonFriendlyData = payload.data.jsonFriendlyData.mutableCopy; + for (NSString *key in scrubFieldsSet) { + if ([mutableJsonFriendlyData valueForKeyPath:key]) { + [RollbarThread createMutableDataWithData:mutableJsonFriendlyData + forPath:key]; + [mutableJsonFriendlyData setValue:@"*****" + forKeyPath:key]; + } + } + + payload.data = [[RollbarData alloc] initWithDictionary:mutableJsonFriendlyData]; + + return payload; +} + ++ (nonnull NSSet *)getScrubFields:(nullable RollbarScrubbingOptions *)scrubbingOptions { + + if (!scrubbingOptions + || scrubbingOptions.isEmpty + || !scrubbingOptions.enabled + || !scrubbingOptions.scrubFields + || scrubbingOptions.scrubFields.count == 0) { + + return [NSSet set]; + } + + NSMutableSet *actualFieldsToScrub = scrubbingOptions.scrubFields.mutableCopy; + if (scrubbingOptions.safeListFields.count > 0) { + // actualFieldsToScrub = + // config.dataScrubber.scrubFields - config.dataScrubber.whitelistFields + // while using case insensitive field name comparison: + actualFieldsToScrub = [NSMutableSet new]; + for(NSString *key in scrubbingOptions.scrubFields) { + BOOL isWhitelisted = false; + for (NSString *whiteKey in scrubbingOptions.safeListFields) { + if (NSOrderedSame == [key caseInsensitiveCompare:whiteKey]) { + isWhitelisted = true; + } + } + if (!isWhitelisted) { + [actualFieldsToScrub addObject:key]; + } + } + } + + return actualFieldsToScrub; +} + ++ (void)createMutableDataWithData:(NSMutableDictionary *)data + forPath:(NSString *)path { + + NSArray *pathComponents = [path componentsSeparatedByString:@"."]; + NSString *currentPath = @""; + + for (int i=0; i_payloadsRepo getIDofDestinationWithEndpoint:config.destination.endpoint andAccesToken:config.destination.accessToken]; @@ -233,23 +407,28 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl RollbarPayload *payload = [[RollbarPayload alloc] initWithJSONString:payloadJson]; NSAssert(payload, @"payload is expected to be defined!"); - //TODO: the following payload truncation code should eventually move to the point right before payload persistence - // into the repo: - - NSMutableDictionary *newPayload = - [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; - [RollbarPayloadTruncator truncatePayload:newPayload]; - if (nil == newPayload) { - - RollbarSdkLog( - @"Couldn't send truncated payload that is nil" - ); - //let's use untruncated original: - newPayload = [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; - } - - NSError *error; - NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:newPayload +// //TODO: the following payload truncation code should eventually move to the point right before payload persistence +// // into the repo: +// NSMutableDictionary *newPayload = +// [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; +// [RollbarPayloadTruncator truncatePayload:newPayload]; +// if (nil == newPayload) { +// +// RollbarSdkLog( +// @"Couldn't send truncated payload that is nil" +// ); +// //let's use untruncated original: +// newPayload = [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; +// } +// +// NSError *error; +// NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:newPayload +// options:0 +// error:&error +// safe:true]; + + NSError *error; + NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:payload options:0 error:&error safe:true]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h index 38a9e7e0..e39595e5 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h @@ -19,12 +19,18 @@ NS_ASSUME_NONNULL_BEGIN /// A flag to suppress internal SDK's informational logging @property (nonatomic, readonly) BOOL suppressSdkInfoLogging; +/// Flags if the incoming payloads to be logged locally +@property (nonatomic, readonly) BOOL logIncomingPayloads; + /// Flags if the transmitted payloads to be logged locally @property (nonatomic, readonly) BOOL logTransmittedPayloads; /// Flags if the dropped payloads to be logged locally @property (nonatomic, readonly) BOOL logDroppedPayloads; +/// Log file to use for local logged incoming payloads +@property (nonatomic, readonly, copy) NSString *incomingPayloadLogFile; + /// Log file to use for local logged transmitted payloads @property (nonatomic, readonly, copy) NSString *transmittedPayloadLogFile; @@ -36,24 +42,30 @@ NS_ASSUME_NONNULL_BEGIN /// Initializer /// @param enabled enabled flag /// @param transmit payloads transmission flag +/// @param logIncomingPayloads flag to log incoming payloads locally /// @param logTransmittedPayloads flag to log transmitted payloads locally /// @param logDroppedPayloads flag to log dropped payloads locally -/// @param transmittedPayloadsLogFile file to log transmitted payloads to -/// @param droppedPayloadsLogFile file to log dropped payloads to +/// @param logIncomingPayloadsFile file to log incoming payloads to +/// @param logTransmittedPayloadsFile file to log transmitted payloads to +/// @param logDroppedPayloadsFile file to log dropped payloads to - (instancetype)initWithEnabled:(BOOL)enabled transmit:(BOOL)transmit + logIncomingPayloads:(BOOL)logIncomingPayloads logTransmittedPayloads:(BOOL)logTransmittedPayloads logDroppedPayloads:(BOOL)logDroppedPayloads + incomingPayloadsLogFile:(NSString *)logIncomingPayloadsFile transmittedPayloadsLogFile:(NSString *)logTransmittedPayloadsFile droppedPayloadsLogFile:(NSString *)logDroppedPayloadsFile; /// Initializer /// @param enabled enabled flag /// @param transmit payloads transmission flag +/// @param logIncomingPayloads flag to log incoming payloads locally /// @param logTransmittedPayloads flag to log transmitted payloads locally /// @param logDroppedPayloads flag to log dropped payloads locally - (instancetype)initWithEnabled:(BOOL)enabled transmit:(BOOL)transmit + logIncomingPayloads:(BOOL)logIncomingPayloads logTransmittedPayloads:(BOOL)logTransmittedPayloads logDroppedPayloads:(BOOL)logDroppedPayloads; @@ -76,12 +88,18 @@ NS_ASSUME_NONNULL_BEGIN /// A flag to suppress internal SDK's informational logging @property (nonatomic, readwrite) BOOL suppressSdkInfoLogging; +/// Flags if the incoming payloads to be logged locally +@property (nonatomic, readwrite) BOOL logIncomingPayloads; + /// Flags if the transmitted payloads to be logged locally @property (nonatomic, readwrite) BOOL logTransmittedPayloads; /// Flags if the dropped payloads to be logged locally @property (nonatomic, readwrite) BOOL logDroppedPayloads; +/// Log file to use for local logged incoming payloads +@property (nonatomic, readwrite, copy) NSString *incomingPayloadLogFile; + /// Log file to use for local logged transmitted payloads @property (nonatomic, readwrite, copy) NSString *transmittedPayloadLogFile; diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger+Test.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger+Test.h index 9b8f56e8..79e84b75 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger+Test.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarLogger+Test.h @@ -14,6 +14,10 @@ NS_ASSUME_NONNULL_BEGIN ///@note THIS METHOD IS TO BE USED FOR TESTING PURPOSES ONLY. + (void)flushRollbarThread; +/// Reads all payloads from the default incoming payloads log +///@note THIS METHOD IS TO BE USED FOR TESTING PURPOSES ONLY. ++ (nonnull NSArray *)readPayloadsFromSdkIncomingLog; + /// Reads all payloads from the default transmitted payloads log ///@note THIS METHOD IS TO BE USED FOR TESTING PURPOSES ONLY. + (nonnull NSArray *)readPayloadsFromSdkTransmittedLog; From 34fa320a2f972010feaf5101b3d7d33cfd0e2134 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 22 Aug 2022 15:28:38 -0700 Subject: [PATCH 096/127] feat: resolve #231, #232, #233 --- .../Sources/RollbarNotifier/RollbarThread.m | 101 ++++++++++++------ 1 file changed, 66 insertions(+), 35 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 7941ac52..256be712 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -13,12 +13,14 @@ #import "RollbarRegistry.h" #import "RollbarPayloadRepository.h" -static NSUInteger MAX_RETRY_COUNT = 5; +static NSTimeInterval const DEFAULT_PAYLOAD_LIFETIME_SECONDS = 24 * 60 * 60; +// hours-per day * 60 min-per-hour * 60 sec-per-min = 1 day in sec @implementation RollbarThread { @private NSUInteger _maxReportsPerMinute; + NSTimeInterval _payloadLifetimeInSeconds; NSTimer *_timer; NSString *_payloadsRepoFilePath; RollbarRegistry *_registry; @@ -47,6 +49,7 @@ - (instancetype)initWithTarget:(id)target [self setupDataStorage]; self->_maxReportsPerMinute = 240;//60; + self->_payloadLifetimeInSeconds = DEFAULT_PAYLOAD_LIFETIME_SECONDS; self->_registry = [RollbarRegistry new]; #if !TARGET_OS_WATCH @@ -135,8 +138,8 @@ - (void)persist:(nonnull RollbarPayload *)payload { - (void)persistPayload:(nonnull RollbarPayload *)payload withConfig:(nonnull RollbarConfig *)config { - [self performSelector:@selector(queuePayload_OnlyCallOnThread:) - onThread:[RollbarThread sharedInstance] + [self performSelector:@selector(queuePayload_OnlyCallOnThisThread:) + onThread:self //[RollbarThread sharedInstance] withObject:@[payload, config] waitUntilDone:NO ]; @@ -299,21 +302,31 @@ + (nonnull RollbarPayload *)truncatePayload:(nonnull RollbarPayload *)payload { } } -- (void)queuePayload_OnlyCallOnThread:(nonnull NSArray *)data { +- (void)queuePayload_OnlyCallOnThisThread:(nonnull NSArray *)data { NSAssert(data, @"data can not be nil"); NSAssert(2 == data.count, @"data expected to have 2 components"); - + RollbarPayload *payload = (RollbarPayload *)data[0]; NSAssert(payload, @"payload can not be nil in data: %@", data); RollbarConfig *config = (RollbarConfig *)data[1]; NSAssert(config, @"config can not be nil"); - if (!(payload && config)) { - + if (!(payload && config)) { RollbarSdkLog(@"Couldn't queue payload %@ with config %@", payload, config); return; } + @try { + [self savePayload:payload withConfig:config]; + } @catch (NSException *exception) { + RollbarSdkLog(@"Payload queuing EXCEPTION: %@", exception); + } @finally { + [[RollbarTelemetry sharedInstance] clearAllData]; + } +} + +- (void)savePayload:(nonnull RollbarPayload *)payload withConfig:(nonnull RollbarConfig *)config { + if ([RollbarThread shouldIgnorePayload:payload withConfig:config]) { return; @@ -341,8 +354,6 @@ - (void)queuePayload_OnlyCallOnThread:(nonnull NSArray *)data { return; } - //TODO: consider moving payload modifications (scrubbing and truncation) here... - //[payload.data.notifier setData:config.jsonFriendlyData byKey:@"configured_options"]; NSString *payloadJson = [payload serializeToJSONString]; NSDictionary *payloadDataRow = [self->_payloadsRepo addPayload:payloadJson @@ -355,8 +366,6 @@ - (void)queuePayload_OnlyCallOnThread:(nonnull NSArray *)data { RollbarSdkLog(@"*** Resulting payloadDataRow: %@", payloadDataRow); } NSAssert(payloadDataRow && payloadDataRow[@"id"], @"Couldn't add a payload to the repo: %@", payloadJson); - - [[RollbarTelemetry sharedInstance] clearAllData]; } #pragma mark - processing persisted payload items @@ -382,9 +391,47 @@ - (void)checkItems { } } +- (BOOL)checkProcessStalePayload:(nonnull NSDictionary *)payloadDataRow { + + // let's make sure we are not dealng with a stale payload: + NSString *timestampValue = payloadDataRow[@"created_at"]; + NSScanner *scanner = [NSScanner scannerWithString:timestampValue]; + double payloadTimestamp; + BOOL timestampParsingSuccess = [scanner scanDouble:&payloadTimestamp]; + if (!timestampParsingSuccess + || ((payloadTimestamp + self->_payloadLifetimeInSeconds) < [NSDate date].timeIntervalSince1970) + ) { + // we either have some sort of timestamp corruption or + // we are processing a stale payload let's just drop it and call it done: + [self->_payloadsRepo removePayloadByID:payloadDataRow[@"id"]]; + + RollbarConfig *config = [[RollbarConfig alloc] initWithJSONString:payloadDataRow[@"config_json"]]; + + if (config && config.developerOptions.logTransmittedPayloads) { + NSString *payloadsLogFile = config.developerOptions.droppedPayloadLogFile; + if (payloadsLogFile && (payloadsLogFile.length > 0)) { + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + NSString *payloadsLogFilePath = [cachesDirectory stringByAppendingPathComponent:payloadsLogFile]; + RollbarPayload *payload = [[RollbarPayload alloc] initWithJSONString:payloadDataRow[@"payload_json"]]; + [RollbarFileWriter appendSafelyData: payload.serializeToJSONData toFile:payloadsLogFilePath]; + } + } + + if (config && !config.developerOptions.suppressSdkInfoLogging) { + RollbarSdkLog(@"Dropped a stale payload: %@", payloadDataRow[@"payload_json"]); + } + + return YES; + } + + return NO; +} + - (void)processSavedPayload:(nonnull NSDictionary *)payloadDataRow { - //TODO: implement detection of stale payload and remove from the repo if it is stale... + if ([self checkProcessStalePayload:payloadDataRow]) { + return; + } NSString *destinationKey = payloadDataRow[@"destination_key"]; NSAssert(destinationKey && destinationKey.length > 0, @"destination_key is expected to be defined!"); @@ -407,26 +454,6 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl RollbarPayload *payload = [[RollbarPayload alloc] initWithJSONString:payloadJson]; NSAssert(payload, @"payload is expected to be defined!"); -// //TODO: the following payload truncation code should eventually move to the point right before payload persistence -// // into the repo: -// NSMutableDictionary *newPayload = -// [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; -// [RollbarPayloadTruncator truncatePayload:newPayload]; -// if (nil == newPayload) { -// -// RollbarSdkLog( -// @"Couldn't send truncated payload that is nil" -// ); -// //let's use untruncated original: -// newPayload = [NSMutableDictionary dictionaryWithDictionary:payload.jsonFriendlyData]; -// } -// -// NSError *error; -// NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:newPayload -// options:0 -// error:&error -// safe:true]; - NSError *error; NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:payload options:0 @@ -478,8 +505,7 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl case RollbarTriStateFlag_None: default: // Nothing obviously wrong with the payload but it was not actually tranmitted successfully. - // Let's try again some other time. Keep it in the repo for now (unless it is already too stale)... - //TODO: implement detection of stale payload and remove from the repo if it is stale... + // Let's try again some other time. Keep it in the repo for now... break; } @@ -519,7 +545,12 @@ - (void)processSavedItems { NSArray *> *payloads = [self->_payloadsRepo getPayloadsWithOffset:0 andLimit:5]; for(NSDictionary *payload in payloads) { - [self processSavedPayload:payload]; + @try { + [self processSavedPayload:payload]; + } @catch (NSException *exception) { + RollbarSdkLog(@"Payload processing EXCEPTION: %@", exception); + } @finally { + } } } From 13bf79d3c98aa552ada9528d8d64ad43252f0938 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 24 Aug 2022 23:12:17 -0700 Subject: [PATCH 097/127] test: refactoring unit tests --- .../RollbarNotifier/RollbarLogger+Test.m | 11 --- .../Sources/RollbarNotifier/RollbarThread.m | 17 +--- .../RollbarInfrastructureTests.m | 6 +- .../RollbarNotifierConfigurationTests.swift | 67 ++++++------- .../RollbarNotifierLoggerTests.swift | 9 +- .../RollbarNotifierTelemetryTests.swift | 24 ++--- .../RollbarNotifierTruncationTests.swift | 5 +- .../Sources/UnitTesting/RollbarTestUtil.swift | 95 +++++++++++++++---- 8 files changed, 123 insertions(+), 111 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m index c599ae9b..8c47b1c5 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger+Test.m @@ -37,12 +37,6 @@ + (void)clearSdkFile:(nonnull NSString *)sdkFileName { [RollbarLogger readPayloadsDataFromFile:[RollbarLogger _droppedPayloadsLogPath]]; } -//+ (nonnull NSArray *)readPayloadsFromSdkLog { -// -// NSString *filePath = [RollbarLogger _payloadsLogPath]; -// return [RollbarLogger readPayloadsDataFromFile:filePath]; -//} - + (nonnull NSArray *)readPayloadsDataFromFile:(nonnull NSString *)filePath { RollbarFileReader *reader = [[RollbarFileReader alloc] initWithFilePath:filePath @@ -104,11 +98,6 @@ + (nonnull NSString *)_logPayloadsStorePath { return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles payloadsStore]]; } -//+ (nonnull NSString *)_logItemsStoreStatePath { -// -// return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles itemsQueueState]]; -//} - + (nonnull NSString *)_telemetryItemsStorePath { return [RollbarLogger _getSDKDataFilePath:[RollbarNotifierFiles telemetryQueue]]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 256be712..63f2bf34 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -26,11 +26,6 @@ @implementation RollbarThread { RollbarRegistry *_registry; RollbarPayloadRepository *_payloadsRepo; -// NSDate *_nextSendTime; -// NSString *_queuedItemsFilePath; -// NSString *_stateFilePath; -// NSMutableDictionary *_queueState; - #if !TARGET_OS_WATCH RollbarReachability *_reachability; BOOL _isNetworkReachable; @@ -56,7 +51,6 @@ - (instancetype)initWithTarget:(id)target self->_reachability = nil; self->_isNetworkReachable = YES; #endif - //self->_nextSendTime = [[NSDate alloc] init]; self.name = [RollbarThread rollbar_objectClassName];//NSStringFromClass([RollbarThread class]); self.active = YES; @@ -126,13 +120,6 @@ - (void)run { } } -#pragma mark - payload store - -- (void)persist:(nonnull RollbarPayload *)payload { - -} - - #pragma mark - persisting payload items - (void)persistPayload:(nonnull RollbarPayload *)payload @@ -311,7 +298,7 @@ - (void)queuePayload_OnlyCallOnThisThread:(nonnull NSArray *)data { NSAssert(payload, @"payload can not be nil in data: %@", data); RollbarConfig *config = (RollbarConfig *)data[1]; NSAssert(config, @"config can not be nil"); - if (!(payload && config)) { + if (!(payload && config)) { RollbarSdkLog(@"Couldn't queue payload %@ with config %@", payload, config); return; } @@ -455,7 +442,7 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl NSAssert(payload, @"payload is expected to be defined!"); NSError *error; - NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:payload + NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:payload.jsonFriendlyData options:0 error:&error safe:true]; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index 379d7146..059e6674 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -76,7 +76,7 @@ - (void)test2_Basics { ]; [RollbarLogger flushRollbarThread]; - items = [RollbarTestUtil readItemStringsFromLogFile]; + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; BOOL wasLogged = NO; for (NSString *item in items) { if (YES == [item containsString:@"RollbarInfrastructure basics test 2!"]) { @@ -114,7 +114,7 @@ - (void)test3_Live { [RollbarLogger flushRollbarThread]; - items = [RollbarTestUtil readItemStringsFromLogFile]; + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; XCTAssertNotNil(items); [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical @@ -123,7 +123,7 @@ - (void)test3_Live { context:nil ]; [RollbarLogger flushRollbarThread]; - items = [RollbarTestUtil readItemStringsFromLogFile]; + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; BOOL wasLogged = NO; for (NSString *item in items) { if (YES == [item containsString:@"RollbarInfrastructure basics test 3!"]) { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift index 38397ad5..5ab506fd 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift @@ -11,12 +11,19 @@ final class RollbarNotifierConfigurationTests: XCTestCase { super.setUp(); - RollbarTestUtil.clearLogFile(); + RollbarTestUtil.deleteLogFiles(); + RollbarTestUtil.deletePayloadsStoreFile(); RollbarTestUtil.clearTelemetryFile(); // if Rollbar.currentConfiguration() != nil { // Rollbar.initWithAccessToken(""); // } + + let config = RollbarMutableConfig(); + config.developerOptions.logIncomingPayloads = true; + config.developerOptions.logTransmittedPayloads = true; + config.developerOptions.logDroppedPayloads = true; + Rollbar.initWithAccessToken(""); } @@ -33,8 +40,6 @@ final class RollbarNotifierConfigurationTests: XCTestCase { func testTelemetryEnabled() { - RollbarTestUtil.clearLogFile(); - var expectedFlag = false; let config = Rollbar.configuration().mutableCopy(); @@ -81,8 +86,6 @@ final class RollbarNotifierConfigurationTests: XCTestCase { func testMaximumTelemetryEvents() { - RollbarTestUtil.clearLogFile(); - let config = Rollbar.configuration().mutableCopy(); config.telemetry.enabled = true; Rollbar.update(withConfiguration: config); @@ -98,7 +101,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("Test"); RollbarLogger .flushRollbarThread(); - let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let telemetry = payload.data.body.telemetry!; @@ -127,8 +130,6 @@ final class RollbarNotifierConfigurationTests: XCTestCase { func testViewInputTelemetrScrubFieldsConfig() { - RollbarTestUtil.clearLogFile(); - let element1 = "password"; let element2 = "pin"; @@ -164,11 +165,11 @@ final class RollbarNotifierConfigurationTests: XCTestCase { func testEnabled() { - RollbarLogger.flushRollbarThread(); - RollbarTestUtil.clearLogFile(); - RollbarTestUtil.waitForPesistenceToComplete(waitTimeInSeconds: 5); +// RollbarLogger.flushRollbarThread(); +// RollbarTestUtil.deleteLogFiles(); +// RollbarTestUtil.waitForPesistenceToComplete(waitTimeInSeconds: 5); - var logItems = RollbarTestUtil.readItemStringsFromLogFile(); + var logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); XCTAssertTrue(logItems.count == 0, "logItems count is expected to be 0. Actual value is \(logItems.count)" ); @@ -178,11 +179,11 @@ final class RollbarNotifierConfigurationTests: XCTestCase { config.developerOptions.enabled = false; Rollbar.update(withConfiguration: config); RollbarLogger.flushRollbarThread(); - RollbarTestUtil.clearLogFile(); + RollbarTestUtil.deleteLogFiles(); Rollbar.debugMessage("Test1"); RollbarLogger.flushRollbarThread(); - logItems = RollbarTestUtil.readItemStringsFromLogFile(); + logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); XCTAssertTrue(logItems.count == 0, "logItems count is expected to be 0. Actual value is \(logItems.count)" ); @@ -193,7 +194,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("Test2"); RollbarLogger.flushRollbarThread(); - logItems = RollbarTestUtil.readItemStringsFromLogFile(); + logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); XCTAssertTrue(logItems[logItems.count - 1].contains("Test2")); config.developerOptions.enabled = false; @@ -202,32 +203,28 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("Test3"); RollbarLogger.flushRollbarThread(); - logItems = RollbarTestUtil.readItemStringsFromLogFile(); + logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); XCTAssertTrue(!logItems[logItems.count - 1].contains("Test3")); - RollbarTestUtil.clearLogFile(); + RollbarTestUtil.deleteLogFiles(); } func testCheckIgnore() { - RollbarTestUtil.clearLogFile(); - Rollbar.debugMessage("Don't ignore this"); RollbarTestUtil.waitForPesistenceToComplete(); - var logItems = RollbarTestUtil.readItemStringsFromLogFile(); + var logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); XCTAssertTrue(logItems.count == 1, "Log item count should be 1"); let config = Rollbar.configuration().mutableCopy(); config.checkIgnoreRollbarData = { rollbarData in return true; }; Rollbar.debugMessage("Ignore this"); - logItems = RollbarTestUtil.readItemStringsFromLogFile(); + logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); XCTAssertTrue(logItems.count == 1, "Log item count should be 1"); } func testServerData() { - RollbarTestUtil.clearLogFile(); - let config = Rollbar.configuration().mutableCopy(); let host = "testHost"; @@ -241,7 +238,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarTestUtil.waitForPesistenceToComplete(); - let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let server = payload.data.server!; @@ -262,8 +259,6 @@ final class RollbarNotifierConfigurationTests: XCTestCase { func testPayloadModification() { - RollbarTestUtil.clearLogFile(); - let config = Rollbar.configuration().mutableCopy(); let newMsg = "Modified message"; @@ -277,7 +272,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarTestUtil.waitForPesistenceToComplete(); - let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let msg1 = payload.data.body.message!.body; @@ -293,8 +288,6 @@ final class RollbarNotifierConfigurationTests: XCTestCase { func testScrublistFields() { - RollbarTestUtil.clearLogFile(); - let config = Rollbar.configuration().mutableCopy(); let scrubedContent = "*****"; @@ -311,7 +304,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarLogger.flushRollbarThread(); // verify the fields were scrubbed: - var logItems = RollbarTestUtil.readItemStringsFromLogFile(); + var logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); var logItem = logItems[logItems.count - 1]; var payload = RollbarPayload(jsonString: logItem); for key in keys { @@ -321,7 +314,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { "\(key) is \(content), should be \(scrubedContent)" ); } - RollbarTestUtil.clearLogFile(); + RollbarTestUtil.deleteLogFiles(); // define scrub whitelist fields (the same as the scrub fields - to counterbalance them): for key in keys { @@ -334,7 +327,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarLogger.flushRollbarThread(); // verify the fields were not scrubbed: - logItems = RollbarTestUtil.readItemStringsFromLogFile(); + logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); logItem = logItems[logItems.count - 1]; payload = RollbarPayload(jsonString: logItem); for key in keys { @@ -345,13 +338,11 @@ final class RollbarNotifierConfigurationTests: XCTestCase { ); } - RollbarTestUtil.clearLogFile(); + RollbarTestUtil.deleteLogFiles(); } func testPersonDataAttachment() { - RollbarTestUtil.clearLogFile(); - XCTAssertNotNil(Rollbar.configuration()); let config = Rollbar.configuration().mutableCopy(); @@ -377,7 +368,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("test"); RollbarLogger.flushRollbarThread(); // verify the fields were scrubbed: - let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); let payload = RollbarPayload(jsonString: logItems[logItems.count - 1]); XCTAssertTrue( .orderedSame == payload.data.person!.serializeToJSONString()!.compare(expectedPersonJson), @@ -392,8 +383,6 @@ final class RollbarNotifierConfigurationTests: XCTestCase { func testRollbarSetPersonDataAttachment() { - RollbarTestUtil.clearLogFile(); - XCTAssertNotNil(Rollbar.configuration()); let config = Rollbar.configuration().mutableCopy(); @@ -420,7 +409,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("test"); RollbarLogger.flushRollbarThread(); // verify the fields were scrubbed: - let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); let payload = RollbarPayload(jsonString: logItems[logItems.count - 1]); XCTAssertTrue( .orderedSame == payload.data.person!.serializeToJSONString()!.compare(expectedPersonJson), diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift index 850781e6..6414b679 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift @@ -11,10 +11,11 @@ final class RollbarNotifierLoggerTests: XCTestCase { super.setUp(); - RollbarTestUtil.clearLogFile(); - RollbarTestUtil.clearTelemetryFile(); RollbarTestUtil.waitForPesistenceToComplete(); - + RollbarTestUtil.deleteLogFiles(); + RollbarTestUtil.deletePayloadsStoreFile(); + RollbarTestUtil.clearTelemetryFile(); + let config = RollbarMutableConfig.mutableConfig( withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), environment: RollbarTestHelper.getRollbarEnvironment() @@ -152,7 +153,7 @@ final class RollbarNotifierLoggerTests: XCTestCase { RollbarLogger.flushRollbarThread(); - let items = RollbarTestUtil.readItemStringsFromLogFile(); + let items = RollbarTestUtil.readTransmittedPayloadsAsStrings(); XCTAssertTrue(items.count >= notificationText.count); var count:Int = 0; for item in items { diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift index 14253ac5..bd8a51cc 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift @@ -10,9 +10,11 @@ final class RollbarNotifierTelemetryTests: XCTestCase { override func setUp() { super.setUp(); - RollbarTestUtil.clearLogFile(); + + RollbarTestUtil.deleteLogFiles(); + RollbarTestUtil.deletePayloadsStoreFile(); RollbarTestUtil.clearTelemetryFile(); - + let config = RollbarConfig.mutableConfig( withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), environment: RollbarTestHelper.getRollbarEnvironment() @@ -27,9 +29,6 @@ final class RollbarNotifierTelemetryTests: XCTestCase { func testMemoryTelemetryAutocapture() { - RollbarTestUtil.clearLogFile(); - RollbarTestUtil.clearTelemetryFile(); - let config = RollbarMutableConfig(); config.destination.accessToken = RollbarTestHelper.getRollbarPayloadsAccessToken(); config.destination.environment = RollbarTestHelper.getRollbarEnvironment(); @@ -42,7 +41,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { Rollbar.criticalMessage("Must contain memory telemetry!"); RollbarLogger.flushRollbarThread(); - let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let telemetryEvents = payload.data.body.telemetry!; @@ -62,9 +61,6 @@ final class RollbarNotifierTelemetryTests: XCTestCase { func testMemoryTelemetryAutocapture_Live() { - RollbarTestUtil.clearLogFile(); - RollbarTestUtil.clearTelemetryFile(); - let config = RollbarMutableConfig(); config.destination.accessToken = RollbarTestHelper.getRollbarPayloadsAccessToken(); config.destination.environment = RollbarTestHelper.getRollbarEnvironment(); @@ -84,9 +80,6 @@ final class RollbarNotifierTelemetryTests: XCTestCase { func testTelemetryCapture() { - RollbarTestUtil.clearLogFile(); - RollbarTestUtil.clearTelemetryFile(); - let config = Rollbar.configuration().mutableCopy(); config.telemetry.enabled = true; Rollbar.update(withConfiguration: config); @@ -125,7 +118,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { Rollbar.debugMessage("Test"); RollbarLogger.flushRollbarThread(); - let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let telemetryEvents = payload.data.body.telemetry!; @@ -174,9 +167,6 @@ final class RollbarNotifierTelemetryTests: XCTestCase { func testErrorReportingWithTelemetry() { - RollbarTestUtil.clearLogFile(); - RollbarTestUtil.clearTelemetryFile(); - let config = Rollbar.configuration().mutableCopy(); config.telemetry.enabled = true; Rollbar.update(withConfiguration: config); @@ -222,7 +212,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { RollbarTestUtil.waitForPesistenceToComplete(); - let logItems = RollbarTestUtil.readItemStringsFromLogFile(); + let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); for item in logItems { let payload = RollbarPayload(jsonString: item); let telemetryEvents = payload.data.body.telemetry; diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift index beef6ac1..449b4d3a 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift @@ -11,9 +11,10 @@ final class RollbarNotifierTruncationTests: XCTestCase { super.setUp(); - RollbarTestUtil.clearLogFile(); + RollbarTestUtil.deleteLogFiles(); + RollbarTestUtil.deletePayloadsStoreFile(); RollbarTestUtil.clearTelemetryFile(); - + let config = RollbarConfig.mutableConfig( withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), environment: RollbarTestHelper.getRollbarEnvironment() diff --git a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift index 625e1a7d..ae02b0db 100644 --- a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift +++ b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift @@ -11,8 +11,11 @@ import RollbarCommon @objc public class RollbarTestUtil: NSObject { private static let payloadsStore = "rollbar.db"; - private static let queuedItemsFileName = "rollbar.items"; - private static let queuedItemsStateFileName = "rollbar.state"; + + private static let incomingPayloadsLog = "rollbar.incoming"; + private static let transmittedPayloadsLog = "rollbar.transmitted"; + private static let droppedPayloadsLog = "rollbar.dropped"; + private static let telemetryFileName = "rollbar.telemetry"; private static func getPayloadsStoreFilePath() -> String { @@ -21,15 +24,21 @@ import RollbarCommon return filePath.path; } - private static func getQueuedItemsFilePath() -> String { + private static func getIncomingPayloadsLogFilePath() -> String { let cachesDirectory = RollbarCachesDirectory.directory() ; - let filePath = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(queuedItemsFileName); + let filePath = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(incomingPayloadsLog); return filePath.path; } - private static func getQueuedItemsStateFilePath() -> String { + private static func getTransmittedPayloadsLogFilePath() -> String { + let cachesDirectory = RollbarCachesDirectory.directory() ; + let filePath = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(transmittedPayloadsLog); + return filePath.path; + } + + private static func getDroppedPayloadsLogFilePath() -> String { let cachesDirectory = RollbarCachesDirectory.directory() ; - let filePath = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(queuedItemsStateFileName); + let filePath = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(droppedPayloadsLog); return filePath.path; } @@ -90,31 +99,62 @@ import RollbarCommon RollbarTestUtil.clearFile(filePath: filePath); } - @objc public static func clearLogFile() { - let itemsStateFilePath = RollbarTestUtil.getQueuedItemsStateFilePath(); - let itemsFilePath = RollbarTestUtil.getQueuedItemsFilePath(); + @objc public static func deleteLogFiles() { + + let logs : [String] = [ + RollbarTestUtil.getIncomingPayloadsLogFilePath(), + RollbarTestUtil.getTransmittedPayloadsLogFilePath(), + RollbarTestUtil.getDroppedPayloadsLogFilePath(), + ]; + let fileManager = FileManager.default; - if fileManager.fileExists(atPath: itemsStateFilePath) { - RollbarTestUtil.deleteFile(filePath: itemsStateFilePath); + for log in logs { + if fileManager.fileExists(atPath: log) { + RollbarTestUtil.deleteFile(filePath: log); + } } + } + + @objc public static func readFirstIncomingPayloadAsString() -> String? { - if fileManager.fileExists(atPath: itemsFilePath) { - RollbarTestUtil.clearFile(filePath: itemsFilePath); - } + return RollbarTestUtil.readFirstItemStringFromLogFile(filePath: RollbarTestUtil.getIncomingPayloadsLogFilePath()); + } + + @objc public static func readFirstTransmittedPayloadAsString() -> String? { + + return RollbarTestUtil.readFirstItemStringFromLogFile(filePath: RollbarTestUtil.getTransmittedPayloadsLogFilePath()); + } + + @objc public static func readFirstDroppedPayloadAsString() -> String? { + + return RollbarTestUtil.readFirstItemStringFromLogFile(filePath: RollbarTestUtil.getDroppedPayloadsLogFilePath()); } - @objc public static func readFirstItemStringFromLogFile() -> String? { + @objc public static func readFirstItemStringFromLogFile(filePath: String) -> String? { - let filePath = RollbarTestUtil.getQueuedItemsFilePath(); let fileReader = RollbarFileReader(filePath: filePath, andOffset: 0); let item = fileReader.readLine(); return item; } - @objc public static func readItemStringsFromLogFile() -> [String] { + @objc public static func readIncomingPayloadsAsStrings() -> [String] { + + return RollbarTestUtil.readItemStringsFromLogFile(filePath: RollbarTestUtil.getIncomingPayloadsLogFilePath()); + } + + @objc public static func readTransmittedPayloadsAsStrings() -> [String] { + + return RollbarTestUtil.readItemStringsFromLogFile(filePath: RollbarTestUtil.getTransmittedPayloadsLogFilePath()); + } + + @objc public static func readDroppedPayloadsAsStrings() -> [String] { + + return RollbarTestUtil.readItemStringsFromLogFile(filePath: RollbarTestUtil.getDroppedPayloadsLogFilePath()); + } + + @objc public static func readItemStringsFromLogFile(filePath: String) -> [String] { - let filePath = RollbarTestUtil.getQueuedItemsFilePath(); let fileReader = RollbarFileReader(filePath: filePath, andOffset: 0); var items = [String](); fileReader.enumerateLines({ (line, nextOffset, stop) in @@ -126,8 +166,23 @@ import RollbarCommon return items; } - @objc public static func readItemsFromLogFile() -> [NSMutableDictionary] { - let filePath = RollbarTestUtil.getQueuedItemsFilePath(); + @objc public static func readIncomingPayloads() -> [NSMutableDictionary] { + + return RollbarTestUtil.readItemsFromLogFile(filePath: RollbarTestUtil.getIncomingPayloadsLogFilePath()); + } + + @objc public static func readTransmittedPayloads() -> [NSMutableDictionary] { + + return RollbarTestUtil.readItemsFromLogFile(filePath: RollbarTestUtil.getTransmittedPayloadsLogFilePath()); + } + + @objc public static func readDroppedPayloads() -> [NSMutableDictionary] { + + return RollbarTestUtil.readItemsFromLogFile(filePath: RollbarTestUtil.getDroppedPayloadsLogFilePath()); + } + + @objc public static func readItemsFromLogFile(filePath: String) -> [NSMutableDictionary] { + let fileReader = RollbarFileReader(filePath: filePath, andOffset: 0); var items = [NSMutableDictionary] (); fileReader.enumerateLines({ (line, nextOffset, stop) in From c87f4bd660898cccb53f38c6244b8df1757ff5dd Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Thu, 25 Aug 2022 17:55:01 -0700 Subject: [PATCH 098/127] test: refactoring unit tests --- .../Sources/RollbarNotifier/RollbarLogger.m | 12 +++---- .../RollbarNotifier/RollbarNotifierFiles.h | 4 +-- .../Sources/RollbarNotifier/RollbarThread.m | 34 +++++++++++++++---- .../include/RollbarDeveloperOptions.h | 6 ++-- .../RollbarConfigTests.m | 4 +-- .../RollbarNotifierConfigurationTests.swift | 11 +++--- 6 files changed, 48 insertions(+), 23 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m index 189d756a..852c8a21 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarLogger.m @@ -71,11 +71,11 @@ - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration { NSString *cachesDirectory = [RollbarCachesDirectory directory]; - if (nil != self.configuration.developerOptions.transmittedPayloadLogFile - && self.configuration.developerOptions.transmittedPayloadLogFile.length > 0) { + if (nil != self.configuration.developerOptions.transmittedPayloadsLogFile + && self.configuration.developerOptions.transmittedPayloadsLogFile.length > 0) { transmittedPayloadsFilePath = - [cachesDirectory stringByAppendingPathComponent:self.configuration.developerOptions.transmittedPayloadLogFile]; + [cachesDirectory stringByAppendingPathComponent:self.configuration.developerOptions.transmittedPayloadsLogFile]; } else { @@ -83,11 +83,11 @@ - (instancetype)initWithConfiguration:(nonnull RollbarConfig *)configuration { [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles transmittedPayloadsLog]]; } - if (nil != self.configuration.developerOptions.droppedPayloadLogFile - && self.configuration.developerOptions.droppedPayloadLogFile.length > 0) { + if (nil != self.configuration.developerOptions.droppedPayloadsLogFile + && self.configuration.developerOptions.droppedPayloadsLogFile.length > 0) { droppedPayloadsFilePath = - [cachesDirectory stringByAppendingPathComponent:self.configuration.developerOptions.droppedPayloadLogFile]; + [cachesDirectory stringByAppendingPathComponent:self.configuration.developerOptions.droppedPayloadsLogFile]; } else { diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h index b88c74dc..b4894b79 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarNotifierFiles.h @@ -21,9 +21,9 @@ NS_ASSUME_NONNULL_BEGIN + (nonnull NSString * const)appQuit; -+ (nonnull NSString * const)incomingPayloadsLog ; ++ (nonnull NSString * const)incomingPayloadsLog; -+ (nonnull NSString * const)transmittedPayloadsLog ; ++ (nonnull NSString * const)transmittedPayloadsLog; + (nonnull NSString * const)droppedPayloadsLog; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 63f2bf34..e9bce415 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -150,12 +150,12 @@ + (BOOL)shouldIgnorePayload:(nonnull RollbarPayload *)payload if (shouldIgnore) { if (config.developerOptions.logDroppedPayloads - && config.developerOptions.incomingPayloadLogFile - && (config.developerOptions.incomingPayloadLogFile.length > 0) + && config.developerOptions.incomingPayloadsLogFile + && (config.developerOptions.incomingPayloadsLogFile.length > 0) ) { NSString *cachesDirectory = [RollbarCachesDirectory directory]; NSString *payloadsLogFilePath = - [cachesDirectory stringByAppendingPathComponent:config.developerOptions.incomingPayloadLogFile]; + [cachesDirectory stringByAppendingPathComponent:config.developerOptions.incomingPayloadsLogFile]; [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:payloadsLogFilePath]; } @@ -352,6 +352,28 @@ - (void)savePayload:(nonnull RollbarPayload *)payload withConfig:(nonnull Rollba RollbarSdkLog(@"*** with destinationID: %@", destinationID); RollbarSdkLog(@"*** Resulting payloadDataRow: %@", payloadDataRow); } + else if (config.developerOptions.logIncomingPayloads) { + NSString *logFile = config.developerOptions.incomingPayloadsLogFile; + NSString *cachesDirectory = [RollbarCachesDirectory directory]; + NSString *logFilePath = [cachesDirectory stringByAppendingPathComponent:logFile]; + + + NSError *error; + NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:payload.jsonFriendlyData + options:0 + error:&error + safe:true]; + if (nil == jsonPayload) { + RollbarSdkLog(@"ERROR: Couldn't log an incoming payload locally!"); + if (nil != error) { + RollbarSdkLog(@" DETAILS: an error while generating JSON data: %@", error); + } + } + else { + [RollbarFileWriter appendSafelyData:jsonPayload toFile:logFilePath]; + } + } + NSAssert(payloadDataRow && payloadDataRow[@"id"], @"Couldn't add a payload to the repo: %@", payloadJson); } @@ -395,7 +417,7 @@ - (BOOL)checkProcessStalePayload:(nonnull NSDictionary * RollbarConfig *config = [[RollbarConfig alloc] initWithJSONString:payloadDataRow[@"config_json"]]; if (config && config.developerOptions.logTransmittedPayloads) { - NSString *payloadsLogFile = config.developerOptions.droppedPayloadLogFile; + NSString *payloadsLogFile = config.developerOptions.droppedPayloadsLogFile; if (payloadsLogFile && (payloadsLogFile.length > 0)) { NSString *cachesDirectory = [RollbarCachesDirectory directory]; NSString *payloadsLogFilePath = [cachesDirectory stringByAppendingPathComponent:payloadsLogFile]; @@ -476,7 +498,7 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl RollbarSdkLog(@"Couldn't remove payload data row with ID: %@", payloadDataRow[@"id"]); } if (config.developerOptions.logTransmittedPayloads) { - payloadsLogFile = config.developerOptions.transmittedPayloadLogFile; + payloadsLogFile = config.developerOptions.transmittedPayloadsLogFile; } break; case RollbarTriStateFlag_Off: @@ -486,7 +508,7 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl RollbarSdkLog(@"Couldn't remove payload data row with ID: %@", payloadDataRow[@"id"]); } if (config.developerOptions.logDroppedPayloads) { - payloadsLogFile = config.developerOptions.droppedPayloadLogFile; + payloadsLogFile = config.developerOptions.droppedPayloadsLogFile; } break; case RollbarTriStateFlag_None: diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h index e39595e5..17b79c81 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h @@ -29,13 +29,13 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, readonly) BOOL logDroppedPayloads; /// Log file to use for local logged incoming payloads -@property (nonatomic, readonly, copy) NSString *incomingPayloadLogFile; +@property (nonatomic, readonly, copy) NSString *incomingPayloadsLogFile; /// Log file to use for local logged transmitted payloads -@property (nonatomic, readonly, copy) NSString *transmittedPayloadLogFile; +@property (nonatomic, readonly, copy) NSString *transmittedPayloadsLogFile; /// Log file to use for local logged dropped payloads -@property (nonatomic, readonly, copy) NSString *droppedPayloadLogFile; +@property (nonatomic, readonly, copy) NSString *droppedPayloadsLogFile; #pragma mark - initializers diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m index 40ff9127..75f0a6cb 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m @@ -109,7 +109,7 @@ - (void)testRollbarDeveloperOptions { XCTAssertTrue(immutable.transmit); XCTAssertTrue(immutable.suppressSdkInfoLogging); XCTAssertTrue(immutable.logTransmittedPayloads); - XCTAssertTrue([immutable.transmittedPayloadLogFile isEqualToString:@"test_PAYLOADS.LOG"]); + XCTAssertTrue([immutable.transmittedPayloadsLogFile isEqualToString:@"test_PAYLOADS.LOG"]); content = [immutable serializeToJSONString]; XCTAssertNotNil(content); @@ -620,7 +620,7 @@ - (void)testRollbarConfig { RollbarConfig *immutable = [mutable copy]; XCTAssertTrue([immutable.destination.accessToken isEqualToString:@"test_AT"]); - XCTAssertTrue([immutable.developerOptions.transmittedPayloadLogFile isEqualToString:@"test_PL"]); + XCTAssertTrue([immutable.developerOptions.transmittedPayloadsLogFile isEqualToString:@"test_PL"]); content = [immutable serializeToJSONString]; XCTAssertNotNil(content); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift index 5ab506fd..f30576e3 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift @@ -24,16 +24,19 @@ final class RollbarNotifierConfigurationTests: XCTestCase { config.developerOptions.logTransmittedPayloads = true; config.developerOptions.logDroppedPayloads = true; - Rollbar.initWithAccessToken(""); + Rollbar.initWithConfiguration(config); } override func tearDown() { + Rollbar.update(withConfiguration: RollbarMutableConfig()); + super.tearDown(); } func testDefaultRollbarConfiguration() { + let rc = RollbarMutableConfig(); NSLog("%@", rc); } @@ -101,7 +104,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("Test"); RollbarLogger .flushRollbarThread(); - let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let telemetry = payload.data.body.telemetry!; @@ -203,10 +206,10 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("Test3"); RollbarLogger.flushRollbarThread(); - logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); XCTAssertTrue(!logItems[logItems.count - 1].contains("Test3")); - RollbarTestUtil.deleteLogFiles(); +// RollbarTestUtil.deleteLogFiles(); } func testCheckIgnore() { From 8a57e7d55041e3ddf72ba72a79c80a47794e0e88 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 26 Aug 2022 01:10:03 -0700 Subject: [PATCH 099/127] test: refactoring unit tests --- .../Sources/RollbarCommon/DTOs/RollbarDTO.m | 29 +++-- .../Sources/RollbarNotifier/RollbarThread.m | 123 ++++++++++++------ .../RollbarNotifierConfigurationTests.swift | 55 +++++--- .../Sources/UnitTesting/RollbarTestUtil.swift | 2 +- 4 files changed, 135 insertions(+), 74 deletions(-) diff --git a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m index 9f97f995..9b6ff90d 100644 --- a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m +++ b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m @@ -149,6 +149,24 @@ - (nullable NSData *)serializeToJSONData { RollbarSdkLog(@"JSON-invalid internal data."); } + NSJSONWritingOptions opt = 0; + NSError *error = nil; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self->_data options:opt error:&error]; + if ((nil == jsonData) && (nil != error)) { + + RollbarSdkLog(@"Error serializing NSData: %@", [error localizedDescription]); + } + return jsonData; +} + +- (nullable NSString *)serializeToJSONString { + + BOOL hasValidData = [NSJSONSerialization isValidJSONObject:self->_data]; + if (NO == hasValidData) { + + RollbarSdkLog(@"JSON-invalid internal data."); + } + NSJSONWritingOptions opt = 0; #ifdef DEBUG opt |= NSJSONWritingPrettyPrinted; @@ -164,18 +182,9 @@ - (nullable NSData *)serializeToJSONData { if ((nil == jsonData) && (nil != error)) { RollbarSdkLog(@"Error serializing NSData: %@", [error localizedDescription]); - } - return jsonData; -} - -- (nullable NSString *)serializeToJSONString { - - NSData *jsonData = [self serializeToJSONData]; - if (nil == jsonData) { - return nil; } - + NSString *result = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; return result; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index e9bce415..22923600 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -146,28 +146,31 @@ + (BOOL)shouldIgnorePayload:(nonnull RollbarPayload *)payload NSAssert(false, @"Provided checkIgnore implementation throws an exception!"); shouldIgnore = NO; } - - if (shouldIgnore) { - - if (config.developerOptions.logDroppedPayloads - && config.developerOptions.incomingPayloadsLogFile - && (config.developerOptions.incomingPayloadsLogFile.length > 0) - ) { - NSString *cachesDirectory = [RollbarCachesDirectory directory]; - NSString *payloadsLogFilePath = - [cachesDirectory stringByAppendingPathComponent:config.developerOptions.incomingPayloadsLogFile]; - [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:payloadsLogFilePath]; - } - - if (!config.developerOptions.suppressSdkInfoLogging) { - RollbarSdkLog(@"Dropped payload (due to checkIgnore): %@", - [[NSString alloc] initWithData:[payload serializeToJSONData] - encoding:NSUTF8StringEncoding] - ); - } - - return YES; // ignore == nothing to queue... + @finally { + return shouldIgnore; } + +// if (shouldIgnore) { +// +// if (config.developerOptions.logDroppedPayloads +// && config.developerOptions.incomingPayloadsLogFile +// && (config.developerOptions.incomingPayloadsLogFile.length > 0) +// ) { +// NSString *cachesDirectory = [RollbarCachesDirectory directory]; +// NSString *payloadsLogFilePath = +// [cachesDirectory stringByAppendingPathComponent:config.developerOptions.incomingPayloadsLogFile]; +// [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:payloadsLogFilePath]; +// } +// +// if (!config.developerOptions.suppressSdkInfoLogging) { +// RollbarSdkLog(@"Dropped payload (due to checkIgnore): %@", +// [[NSString alloc] initWithData:[payload serializeToJSONData] +// encoding:NSUTF8StringEncoding] +// ); +// } +// +// return YES; // ignore == nothing to queue... +// } } return NO; @@ -314,21 +317,78 @@ - (void)queuePayload_OnlyCallOnThisThread:(nonnull NSArray *)data { - (void)savePayload:(nonnull RollbarPayload *)payload withConfig:(nonnull RollbarConfig *)config { + if ([RollbarThread shouldIgnorePayload:payload withConfig:config]) { + if (config.developerOptions.logIncomingPayloads) { + NSString *logFilePath = + [[RollbarCachesDirectory directory] stringByAppendingPathComponent:config.developerOptions.incomingPayloadsLogFile]; + [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:logFilePath]; + } + if (config.developerOptions.logDroppedPayloads) { + NSString *logFilePath = + [[RollbarCachesDirectory directory] stringByAppendingPathComponent:config.developerOptions.droppedPayloadsLogFile]; + [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:logFilePath]; + } + if (!config.developerOptions.suppressSdkInfoLogging) { + RollbarSdkLog(@"Dropped payload (due to checkIgnore): %@", + [[NSString alloc] initWithData:[payload serializeToJSONData] + encoding:NSUTF8StringEncoding] + ); + } return; } payload = [RollbarThread modifyPayload:payload withConfig:config]; if (!payload) { + + if (config.developerOptions.logIncomingPayloads) { + NSString *logFilePath = + [[RollbarCachesDirectory directory] stringByAppendingPathComponent:config.developerOptions.incomingPayloadsLogFile]; + [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:logFilePath]; + } + if (config.developerOptions.logDroppedPayloads) { + NSString *logFilePath = + [[RollbarCachesDirectory directory] stringByAppendingPathComponent:config.developerOptions.droppedPayloadsLogFile]; + [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:logFilePath]; + } + if (!config.developerOptions.suppressSdkInfoLogging) { + RollbarSdkLog(@"Dropped payload (due to modifyPayload failure): %@", + [[NSString alloc] initWithData:[payload serializeToJSONData] + encoding:NSUTF8StringEncoding] + ); + } return; } payload = [RollbarThread scrubPayload:payload withConfig:config]; if (!payload) { + + if (config.developerOptions.logIncomingPayloads) { + NSString *logFilePath = + [[RollbarCachesDirectory directory] stringByAppendingPathComponent:config.developerOptions.incomingPayloadsLogFile]; + [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:logFilePath]; + } + if (config.developerOptions.logDroppedPayloads) { + NSString *logFilePath = + [[RollbarCachesDirectory directory] stringByAppendingPathComponent:config.developerOptions.droppedPayloadsLogFile]; + [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:logFilePath]; + } + if (!config.developerOptions.suppressSdkInfoLogging) { + RollbarSdkLog(@"Dropped payload (due to scrubPayload failure): %@", + [[NSString alloc] initWithData:[payload serializeToJSONData] + encoding:NSUTF8StringEncoding] + ); + } return; } + if (config.developerOptions.logIncomingPayloads) { + NSString *logFilePath = + [[RollbarCachesDirectory directory] stringByAppendingPathComponent:config.developerOptions.incomingPayloadsLogFile]; + [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:logFilePath]; + } + payload = [RollbarThread truncatePayload:payload]; NSString *destinationID = [self->_payloadsRepo getIDofDestinationWithEndpoint:config.destination.endpoint @@ -352,27 +412,6 @@ - (void)savePayload:(nonnull RollbarPayload *)payload withConfig:(nonnull Rollba RollbarSdkLog(@"*** with destinationID: %@", destinationID); RollbarSdkLog(@"*** Resulting payloadDataRow: %@", payloadDataRow); } - else if (config.developerOptions.logIncomingPayloads) { - NSString *logFile = config.developerOptions.incomingPayloadsLogFile; - NSString *cachesDirectory = [RollbarCachesDirectory directory]; - NSString *logFilePath = [cachesDirectory stringByAppendingPathComponent:logFile]; - - - NSError *error; - NSData *jsonPayload = [NSJSONSerialization rollbar_dataWithJSONObject:payload.jsonFriendlyData - options:0 - error:&error - safe:true]; - if (nil == jsonPayload) { - RollbarSdkLog(@"ERROR: Couldn't log an incoming payload locally!"); - if (nil != error) { - RollbarSdkLog(@" DETAILS: an error while generating JSON data: %@", error); - } - } - else { - [RollbarFileWriter appendSafelyData:jsonPayload toFile:logFilePath]; - } - } NSAssert(payloadDataRow && payloadDataRow[@"id"], @"Couldn't add a payload to the repo: %@", payloadJson); } diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift index f30576e3..46bf5efd 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift @@ -23,7 +23,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { config.developerOptions.logIncomingPayloads = true; config.developerOptions.logTransmittedPayloads = true; config.developerOptions.logDroppedPayloads = true; - + config.loggingOptions.enableOomDetection = false; Rollbar.initWithConfiguration(config); } @@ -168,10 +168,6 @@ final class RollbarNotifierConfigurationTests: XCTestCase { func testEnabled() { -// RollbarLogger.flushRollbarThread(); -// RollbarTestUtil.deleteLogFiles(); -// RollbarTestUtil.waitForPesistenceToComplete(waitTimeInSeconds: 5); - var logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); XCTAssertTrue(logItems.count == 0, "logItems count is expected to be 0. Actual value is \(logItems.count)" @@ -208,22 +204,42 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarLogger.flushRollbarThread(); logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); XCTAssertTrue(!logItems[logItems.count - 1].contains("Test3")); - -// RollbarTestUtil.deleteLogFiles(); } func testCheckIgnore() { + Rollbar.configuration(); + + RollbarTestUtil.waitForPesistenceToComplete(); + var expectedIncomingCount = RollbarTestUtil.readIncomingPayloadsAsStrings().count; + var expectedDroppedCount = RollbarTestUtil.readDroppedPayloadsAsStrings().count; + Rollbar.debugMessage("Don't ignore this"); + expectedIncomingCount+=1; RollbarTestUtil.waitForPesistenceToComplete(); - var logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); - XCTAssertTrue(logItems.count == 1, "Log item count should be 1"); + var logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); + XCTAssertTrue(logItems.count == expectedIncomingCount, + "Log item count should be \(expectedIncomingCount) but actual is \(logItems.count)" + ); let config = Rollbar.configuration().mutableCopy(); - config.checkIgnoreRollbarData = { rollbarData in return true; }; + config.checkIgnoreRollbarData = { + rollbarData in return true; + + }; + Rollbar.update(withConfiguration: config); Rollbar.debugMessage("Ignore this"); - logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); - XCTAssertTrue(logItems.count == 1, "Log item count should be 1"); + expectedIncomingCount+=1; + expectedDroppedCount+=1; + RollbarTestUtil.waitForPesistenceToComplete(); + logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); + XCTAssertTrue(logItems.count == expectedIncomingCount, + "Log item count should be \(expectedIncomingCount) but actual is \(logItems.count)" + ); + logItems = RollbarTestUtil.readDroppedPayloadsAsStrings(); + XCTAssertTrue(logItems.count == expectedDroppedCount, + "Log item count should be \(expectedIncomingCount) but actual is \(logItems.count)" + ); } func testServerData() { @@ -241,7 +257,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarTestUtil.waitForPesistenceToComplete(); - let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let server = payload.data.server!; @@ -274,8 +290,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("test"); RollbarTestUtil.waitForPesistenceToComplete(); - - let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let msg1 = payload.data.body.message!.body; @@ -307,7 +322,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarLogger.flushRollbarThread(); // verify the fields were scrubbed: - var logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + var logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); var logItem = logItems[logItems.count - 1]; var payload = RollbarPayload(jsonString: logItem); for key in keys { @@ -330,7 +345,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarLogger.flushRollbarThread(); // verify the fields were not scrubbed: - logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); logItem = logItems[logItems.count - 1]; payload = RollbarPayload(jsonString: logItem); for key in keys { @@ -340,8 +355,6 @@ final class RollbarNotifierConfigurationTests: XCTestCase { "\(key) is \(content), should not be \(scrubedContent)" ); } - - RollbarTestUtil.deleteLogFiles(); } func testPersonDataAttachment() { @@ -371,7 +384,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("test"); RollbarLogger.flushRollbarThread(); // verify the fields were scrubbed: - let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let payload = RollbarPayload(jsonString: logItems[logItems.count - 1]); XCTAssertTrue( .orderedSame == payload.data.person!.serializeToJSONString()!.compare(expectedPersonJson), @@ -412,7 +425,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("test"); RollbarLogger.flushRollbarThread(); // verify the fields were scrubbed: - let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let payload = RollbarPayload(jsonString: logItems[logItems.count - 1]); XCTAssertTrue( .orderedSame == payload.data.person!.serializeToJSONString()!.compare(expectedPersonJson), diff --git a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift index ae02b0db..1c8fa3cf 100644 --- a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift +++ b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift @@ -207,7 +207,7 @@ import RollbarCommon return items; } - @objc public static func waitForPesistenceToComplete(waitTimeInSeconds: TimeInterval = 0.5) { + @objc public static func waitForPesistenceToComplete(waitTimeInSeconds: TimeInterval = 2.0) { Thread.sleep(forTimeInterval: waitTimeInSeconds); } From 1efe548dc91203b78688af2fa930740767fa2294 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Fri, 26 Aug 2022 15:16:57 -0700 Subject: [PATCH 100/127] test: refactor RollbarNotifierTests in Swift --- .../Sources/RollbarNotifier/RollbarThread.m | 9 +++++++-- .../RollbarNotifierTelemetryTests.swift | 16 ++++++++++------ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 22923600..840bf97a 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -520,8 +520,13 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl return; } - RollbarTriStateFlag success = config ? [self sendPayload:jsonPayload usingConfig:config] - : [self sendPayload:jsonPayload]; // backward compatibility with just upgraded very old SDKs... + RollbarTriStateFlag success = RollbarTriStateFlag_On; + if (!config) { + success = [self sendPayload:jsonPayload]; // backward compatibility with just upgraded very old SDKs... + } + else if (config.developerOptions.transmit) { + success = [self sendPayload:jsonPayload usingConfig:config]; + } NSString *payloadsLogFile = nil; NSString *sdkLogTrace = (RollbarTriStateFlag_None == success) ? nil diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift index bd8a51cc..cdfaefd3 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift @@ -19,6 +19,11 @@ final class RollbarNotifierTelemetryTests: XCTestCase { withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), environment: RollbarTestHelper.getRollbarEnvironment() ); + config.developerOptions.transmit = false; + config.developerOptions.logIncomingPayloads = true; + config.developerOptions.logTransmittedPayloads = true; + config.developerOptions.logDroppedPayloads = true; + Rollbar.update(withConfiguration: config); } @@ -29,10 +34,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { func testMemoryTelemetryAutocapture() { - let config = RollbarMutableConfig(); - config.destination.accessToken = RollbarTestHelper.getRollbarPayloadsAccessToken(); - config.destination.environment = RollbarTestHelper.getRollbarEnvironment(); - config.developerOptions.transmit = false; + let config = Rollbar.configuration().mutableCopy(); config.telemetry.enabled = true; config.telemetry.memoryStatsAutocollectionInterval = 0.5; Rollbar.update(withConfiguration: config); @@ -41,7 +43,8 @@ final class RollbarNotifierTelemetryTests: XCTestCase { Rollbar.criticalMessage("Must contain memory telemetry!"); RollbarLogger.flushRollbarThread(); - let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + RollbarTestUtil.waitForPesistenceToComplete(); + let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let telemetryEvents = payload.data.body.telemetry!; @@ -118,7 +121,8 @@ final class RollbarNotifierTelemetryTests: XCTestCase { Rollbar.debugMessage("Test"); RollbarLogger.flushRollbarThread(); - let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); + RollbarTestUtil.waitForPesistenceToComplete(); + let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); let telemetryEvents = payload.data.body.telemetry!; From c770631183357c7a27579cb2989a0d96e50e85a1 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 29 Aug 2022 16:36:20 -0700 Subject: [PATCH 101/127] refactor: Rollbar infrastructure --- .../Sources/RollbarNotifier/Rollbar.m | 60 +-------- .../RollbarNotifier/RollbarInfrastructure.m | 48 ------- .../RollbarNotifier/RollbarPayloadFactory.m | 124 ------------------ .../Sources/RollbarNotifier/RollbarThread.m | 30 +---- 4 files changed, 8 insertions(+), 254 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m index 6b57204a..55aece33 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m +++ b/RollbarNotifier/Sources/RollbarNotifier/Rollbar.m @@ -35,22 +35,6 @@ static void uncaughtExceptionHandler(NSException * _Nonnull exception) { @implementation Rollbar -//static RollbarLogger *logger = nil; -//static RollbarTelemetryOptionsObserver *telemetryOptionsObserver = nil; -//static id crashCollector = nil; -//static RollbarCrashProcessor *crashProcessor = nil; - -//+ (void)initialize { -// -// if (self == [Rollbar class]) { -// -// telemetryOptionsObserver = [RollbarTelemetryOptionsObserver new]; -// } -// -// //[[RollbarSession sharedInstance] registerApplicationHooks]; -// -//} - + (void)initWithAccessToken:(NSString *)accessToken { [Rollbar initWithAccessToken:accessToken @@ -105,49 +89,7 @@ + (void)updateWithConfiguration:(RollbarConfig *)configuration { [[RollbarInfrastructure sharedInstance] configureWith:configuration andCrashCollector:nil]; - -// NSUInteger oldReportingRate = 0; -// -// if (logger) { -// oldReportingRate = logger.configuration.loggingOptions.maximumReportsPerMinute; -// [logger updateConfiguration:configuration]; -// } -// else { -// logger = [[RollbarLogger alloc] initWithConfiguration:configuration]; -// } -// -//// if (oldReportingRate != configuration.loggingOptions.maximumReportsPerMinute) { -//// [logger updateReportingRate:configuration.loggingOptions.maximumReportsPerMinute]; -//// } -// -// if (configuration && configuration.telemetry) { -// -// [[RollbarTelemetry sharedInstance] configureWithOptions:configuration.telemetry]; -// } -} - -#pragma mark - Legacy methods to remove - -// TODO: remove this method... -//+ (RollbarConfig *)currentConfiguration { -// -// return logger.configuration; -//} - -// TODO: remove this method... -//+ (RollbarLogger *)currentLogger { -// -// return logger; -//} - -// TODO: remove this method... -//+ (void)reapplyConfiguration { -// -// RollbarConfig *config = Rollbar.currentConfiguration; -// if (nil != config) { -// [Rollbar updateConfiguration:config]; -// } -//} +} #pragma mark - Logging methods diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m index 445b5546..72589e23 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarInfrastructure.m @@ -1,20 +1,17 @@ #import "RollbarInfrastructure.h" #import "RollbarConfig.h" -//#import "RollbarDestination.h" #import "RollbarLoggerProtocol.h" #import "RollbarLogger.h" #import "RollbarNotifierFiles.h" #import "RollbarCrashProcessor.h" #import "RollbarSession.h" #import "RollbarTelemetry.h" -//#import "RollbarLoggerRegistry.h" @implementation RollbarInfrastructure { @private RollbarConfig *_configuration; RollbarLogger *_logger; RollbarCrashProcessor *_crashProcessor; -// RollbarLoggerRegistry *_loggerRegistry; } #pragma mark - Sigleton pattern @@ -36,15 +33,6 @@ + (nonnull instancetype)sharedInstance { return singleton; } -//- (instancetype)init { -// -// if (self = [super init]) { -// -//// self->_loggerRegistry = [RollbarLoggerRegistry new]; -// } -// return self; -//} - #pragma mark - instance methods - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config { @@ -107,7 +95,6 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config - (nonnull id)createLoggerWithConfig:(nonnull RollbarConfig *)config { RollbarLogger *logger = [RollbarLogger loggerWithConfiguration:config]; - //RollbarLogger *logger = [self->_loggerRegistry loggerWithConfiguration:config]; return logger; } @@ -129,35 +116,6 @@ - (nonnull instancetype)configureWith:(nonnull RollbarConfig *)config return logger; } -#pragma mark - class methods - -//+ (nonnull id)sharedLogger { -// -// return [RollbarInfrastructure sharedInstance].logger; -//} -// -//+ (nonnull id)newLogger { -// -// return [[RollbarInfrastructure sharedInstance] createLogger]; -//} -// -//+ (nonnull id)newLoggerWithConfig:(nonnull RollbarConfig *)config { -// -// return [[RollbarInfrastructure sharedInstance] createLoggerWithConfig:config]; -//} -// -//+ (nonnull id)newLoggerWithAccessToken:(nonnull NSString *)token { -// -// return [[RollbarInfrastructure sharedInstance] createLoggerWithAccessToken:token]; -//} -// -//+ (nonnull id)newLoggerWithAccessToken:(nonnull NSString *)token -// andEnvironment:(nonnull NSString *)env { -// -// return [[RollbarInfrastructure sharedInstance] createLoggerWithAccessToken:token -// andEnvironment:env]; -//} - #pragma mark - properties - (nonnull RollbarConfig *)configuration { @@ -209,10 +167,4 @@ - (void)assertValidConfiguration:(nullable RollbarConfig *)config { //TODO: complete full validation implementation... } - -- (void)configureInfrastructure { - - //TODO: implement... -} - @end diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m index d281fe9b..80af64ba 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m @@ -1,10 +1,3 @@ -// -// RollbarPayloadFactory.m -// -// -// Created by Andrey Kornich on 2022-06-14. -// - #import "RollbarPayloadFactory.h" #import "RollbarConfig.h" @@ -112,116 +105,6 @@ - (nullable RollbarPayload *)payloadWithLevel:(RollbarLevel)level return payload; } -#pragma mark - Payload custom modifiers based on the current config - -//-(BOOL)shouldIgnoreRollbarData:(nonnull RollbarData *)incomingData { -// -// BOOL shouldIgnore = NO; -// if (self->_config.checkIgnoreRollbarData) { -// @try { -// shouldIgnore = self->_config.checkIgnoreRollbarData(incomingData); -// return shouldIgnore; -// } @catch(NSException *e) { -// RollbarSdkLog(@"checkIgnore error: %@", e.reason); -// -// // Remove checkIgnore to prevent future exceptions -// //self->_config.checkIgnoreRollbarData = nil; -// NSAssert(false, @"Provided checkIgnore implementation throws an exception!"); -// -// return NO; -// } -// } -// -// return shouldIgnore; -//} - -//-(RollbarData *)modifyRollbarData:(nonnull RollbarData *)incomingData { -// -// if (self->_config.modifyRollbarData) { -// return self->_config.modifyRollbarData(incomingData); -// } -// return incomingData; -//} - -//-(RollbarData *)scrubRollbarData:(nonnull RollbarData *)incomingData { -// -// NSSet *scrubFieldsSet = [self getScrubFields]; -// if (!scrubFieldsSet || scrubFieldsSet.count == 0) { -// return incomingData; -// } -// -// NSMutableDictionary *mutableJsonFriendlyData = incomingData.jsonFriendlyData.mutableCopy; -// for (NSString *key in scrubFieldsSet) { -// if ([mutableJsonFriendlyData valueForKeyPath:key]) { -// [self createMutablePayloadWithData:mutableJsonFriendlyData forPath:key]; -// [mutableJsonFriendlyData setValue:@"*****" forKeyPath:key]; -// } -// } -// -// return [[RollbarData alloc] initWithDictionary:mutableJsonFriendlyData]; -//} - -//-(NSSet *)getScrubFields { -// -// if (!self->_config.dataScrubber -// || self->_config.dataScrubber.isEmpty -// || !self->_config.dataScrubber.enabled -// || !self->_config.dataScrubber.scrubFields -// || self->_config.dataScrubber.scrubFields.count == 0) { -// -// return [NSSet set]; -// } -// -// NSMutableSet *actualFieldsToScrub = self->_config.dataScrubber.scrubFields.mutableCopy; -// if (self->_config.dataScrubber.safeListFields.count > 0) { -// // actualFieldsToScrub = -// // config.dataScrubber.scrubFields - config.dataScrubber.whitelistFields -// // while using case insensitive field name comparison: -// actualFieldsToScrub = [NSMutableSet new]; -// for(NSString *key in self->_config.dataScrubber.scrubFields) { -// BOOL isWhitelisted = false; -// for (NSString *whiteKey in self->_config.dataScrubber.safeListFields) { -// if (NSOrderedSame == [key caseInsensitiveCompare:whiteKey]) { -// isWhitelisted = true; -// } -// } -// if (!isWhitelisted) { -// [actualFieldsToScrub addObject:key]; -// } -// } -// } -// -// return actualFieldsToScrub; -//} - -//- (void)createMutablePayloadWithData:(NSMutableDictionary *)data -// forPath:(NSString *)path { -// -// NSArray *pathComponents = [path componentsSeparatedByString:@"."]; -// NSString *currentPath = @""; -// -// for (int i=0; i_config.destination.accessToken data:data]; diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index 840bf97a..aa9d9ce9 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -94,7 +94,7 @@ - (void)setupDataStorage { self->_payloadsRepo = [RollbarPayloadRepository persistentRepositoryWithPath:self->_payloadsRepoFilePath]; NSAssert([[NSFileManager defaultManager] fileExistsAtPath:self->_payloadsRepoFilePath], - @"Resistent payloads store was not created: %@!!!", self->_payloadsRepoFilePath + @"Persistent payloads store was not created: %@!!!", self->_payloadsRepoFilePath ); } @@ -149,28 +149,6 @@ + (BOOL)shouldIgnorePayload:(nonnull RollbarPayload *)payload @finally { return shouldIgnore; } - -// if (shouldIgnore) { -// -// if (config.developerOptions.logDroppedPayloads -// && config.developerOptions.incomingPayloadsLogFile -// && (config.developerOptions.incomingPayloadsLogFile.length > 0) -// ) { -// NSString *cachesDirectory = [RollbarCachesDirectory directory]; -// NSString *payloadsLogFilePath = -// [cachesDirectory stringByAppendingPathComponent:config.developerOptions.incomingPayloadsLogFile]; -// [RollbarFileWriter appendSafelyData:[payload serializeToJSONData] toFile:payloadsLogFilePath]; -// } -// -// if (!config.developerOptions.suppressSdkInfoLogging) { -// RollbarSdkLog(@"Dropped payload (due to checkIgnore): %@", -// [[NSString alloc] initWithData:[payload serializeToJSONData] -// encoding:NSUTF8StringEncoding] -// ); -// } -// -// return YES; // ignore == nothing to queue... -// } } return NO; @@ -484,6 +462,12 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl NSString *destinationKey = payloadDataRow[@"destination_key"]; NSAssert(destinationKey && destinationKey.length > 0, @"destination_key is expected to be defined!"); NSDictionary *destination = [self->_payloadsRepo getDestinationByID:destinationKey]; + + //TODO: remove this before the upcoming major release: + if (!destination) { + RollbarSdkLog(@"Aha!"); + } + NSAssert(destination, @"destination can not be nil!"); NSAssert(destination[@"endpoint"], @"destination endpoint can not be nil!"); NSAssert(destination[@"access_token"], @"destination access_token can not be nil!"); From f3ab4a32cc5a99da5b80152e44d19c41f8055f95 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 29 Aug 2022 16:37:42 -0700 Subject: [PATCH 102/127] refactor: added checkDbFile to RollbarPayloadRepository --- .../RollbarPayloadRepository.m | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index f0a95a4f..a70068bc 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -148,7 +148,6 @@ - (instancetype)initInMemoryOnly { return nil; } - - (instancetype)initWithStore:(nonnull NSString *)storePath { if (self = [super init]) { @@ -167,13 +166,8 @@ - (instancetype)init { [RollbarCachesDirectory ensureCachesDirectoryExists]; NSString *cachesDirectory = [RollbarCachesDirectory directory]; NSString *storePath = [cachesDirectory stringByAppendingPathComponent:[RollbarNotifierFiles payloadsStore]]; - - if (self = [self initWithStore:storePath]) { - - return self; - } - return nil; + return [self initWithStore:storePath]; } #pragma mark - Destinations related methods @@ -496,6 +490,8 @@ - (BOOL)openDB:(BOOL)inMemory { RollbarSdkLog(@"sqlite3_open: %s", sqlite3_errmsg(self->_db)); return NO; } + + [self checkDbFile]; return YES; } @@ -525,6 +521,8 @@ - (void)releaseDB { - (BOOL)checkIfTableExists:(nonnull NSString *)tableName { + [self checkDbFile]; + NSString *sql = [NSString stringWithFormat: @"SELECT name FROM sqlite_master WHERE type='table' AND name='%@'", tableName]; char *sqliteErrorMessage; @@ -541,6 +539,8 @@ - (BOOL)checkIfTableExists:(nonnull NSString *)tableName { - (BOOL)executeSql:(nonnull NSString *)sql { + [self checkDbFile]; + char *sqliteErrorMessage; int sqlResult = sqlite3_exec(self->_db, [sql UTF8String], NULL, NULL, &sqliteErrorMessage); if (sqlResult != SQLITE_OK) { @@ -555,6 +555,8 @@ - (BOOL)executeSql:(nonnull NSString *)sql { - (nullable NSDictionary *)selectSingleRowWithSql:(NSString *)sql andCallback:(int(*)(void*,int,char**,char**))callback { + [self checkDbFile]; + NSDictionary *result = nil; char *sqliteErrorMessage; NSDictionary *selectedRow = nil; @@ -571,6 +573,8 @@ - (BOOL)executeSql:(nonnull NSString *)sql { - (nonnull NSArray *> *)selectMultipleRowsWithSql:(NSString *)sql andCallback:(int(*)(void*,int,char**,char**))callback { + [self checkDbFile]; + NSMutableArray *> *result = nil; char *sqliteErrorMessage; @@ -589,4 +593,19 @@ - (BOOL)executeSql:(nonnull NSString *)sql { } } +- (void)checkDbFile { + + if (self->_storePath && ![[NSFileManager defaultManager] fileExistsAtPath:self->_storePath]) { + RollbarSdkLog(@"Persistent payloads store was not created: %@!!!", self->_storePath); + [self openDB:NO]; + [self ensureDestinationsTable]; + [self ensurePayloadsTable]; + return; + } + NSAssert([[NSFileManager defaultManager] fileExistsAtPath:self->_storePath], + @"Persistent payloads store was not created: %@!!!", self->_storePath + ); + +} + @end From 888e11e8416e2138e89b9dfd53e6a6e32ab97341 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 29 Aug 2022 16:38:51 -0700 Subject: [PATCH 103/127] refactor: unit tests --- .../Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m | 2 +- UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m index 50790244..979b9244 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m @@ -24,7 +24,7 @@ - (void)setUp { [Rollbar initWithConfiguration:config]; - [RollbarTestUtil waitForPesistenceToCompleteWithWaitTimeInSeconds:3]; + [RollbarTestUtil waitWithWaitTimeInSeconds:3]; [RollbarLogger clearSdkDataStore]; NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; XCTAssertEqual(items.count, 0); diff --git a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift index 1c8fa3cf..6572525f 100644 --- a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift +++ b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift @@ -207,7 +207,7 @@ import RollbarCommon return items; } - @objc public static func waitForPesistenceToComplete(waitTimeInSeconds: TimeInterval = 2.0) { + @objc public static func wait(waitTimeInSeconds: TimeInterval = 2.0) { Thread.sleep(forTimeInterval: waitTimeInSeconds); } From ad983aae9cefbc35bcc49859c26f0b46c45e7b7c Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Mon, 29 Aug 2022 16:39:32 -0700 Subject: [PATCH 104/127] test: updated RollbarNotifier unit tests in Swift --- .../RollbarNotifierConfigurationTests.swift | 18 ++--- .../RollbarNotifierLoggerTests.swift | 77 +++++++++---------- .../RollbarNotifierTelemetryTests.swift | 20 ++--- .../RollbarNotifierTruncationTests.swift | 16 +--- 4 files changed, 49 insertions(+), 82 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift index 46bf5efd..339d3bf9 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierConfigurationTests.swift @@ -15,23 +15,17 @@ final class RollbarNotifierConfigurationTests: XCTestCase { RollbarTestUtil.deletePayloadsStoreFile(); RollbarTestUtil.clearTelemetryFile(); -// if Rollbar.currentConfiguration() != nil { -// Rollbar.initWithAccessToken(""); -// } - let config = RollbarMutableConfig(); + config.developerOptions.transmit = false; config.developerOptions.logIncomingPayloads = true; config.developerOptions.logTransmittedPayloads = true; config.developerOptions.logDroppedPayloads = true; config.loggingOptions.enableOomDetection = false; Rollbar.initWithConfiguration(config); - } override func tearDown() { - Rollbar.update(withConfiguration: RollbarMutableConfig()); - super.tearDown(); } @@ -210,13 +204,13 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.configuration(); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarTestUtil.wait(); var expectedIncomingCount = RollbarTestUtil.readIncomingPayloadsAsStrings().count; var expectedDroppedCount = RollbarTestUtil.readDroppedPayloadsAsStrings().count; Rollbar.debugMessage("Don't ignore this"); expectedIncomingCount+=1; - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarTestUtil.wait(); var logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); XCTAssertTrue(logItems.count == expectedIncomingCount, "Log item count should be \(expectedIncomingCount) but actual is \(logItems.count)" @@ -231,7 +225,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("Ignore this"); expectedIncomingCount+=1; expectedDroppedCount+=1; - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarTestUtil.wait(); logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); XCTAssertTrue(logItems.count == expectedIncomingCount, "Log item count should be \(expectedIncomingCount) but actual is \(logItems.count)" @@ -255,7 +249,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.debugMessage("test"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarTestUtil.wait(); let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; @@ -289,7 +283,7 @@ final class RollbarNotifierConfigurationTests: XCTestCase { Rollbar.update(withConfiguration: config); Rollbar.debugMessage("test"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarTestUtil.wait(); let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift index 6414b679..0d469e8b 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift @@ -11,10 +11,9 @@ final class RollbarNotifierLoggerTests: XCTestCase { super.setUp(); - RollbarTestUtil.waitForPesistenceToComplete(); - RollbarTestUtil.deleteLogFiles(); RollbarTestUtil.deletePayloadsStoreFile(); RollbarTestUtil.clearTelemetryFile(); + RollbarTestUtil.deleteLogFiles(); let config = RollbarMutableConfig.mutableConfig( withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), @@ -25,14 +24,14 @@ final class RollbarNotifierLoggerTests: XCTestCase { config.developerOptions.logDroppedPayloads = true; config.loggingOptions.maximumReportsPerMinute = 5000; config.customData = ["someKey": "someValue", ]; - Rollbar.update(withConfiguration: config); + + Rollbar.initWithConfiguration(config); } override func tearDown() { - RollbarTestUtil.waitForPesistenceToComplete(waitTimeInSeconds: 2.0); - - Rollbar.update(withConfiguration: RollbarMutableConfig()); + // add custom tear down code... + super.tearDown(); } @@ -47,6 +46,7 @@ final class RollbarNotifierLoggerTests: XCTestCase { var config = Rollbar.configuration().mutableCopy(); config.developerOptions.transmit = false; + config.developerOptions.logIncomingPayloads = true; config.developerOptions.logTransmittedPayloads = true; config.developerOptions.logDroppedPayloads = true; @@ -92,9 +92,6 @@ final class RollbarNotifierLoggerTests: XCTestCase { func testRollbarTransmit() { - //RollbarTestUtil.clearLogFile(); - //RollbarTestUtil.clearTelemetryFile(); - let config = Rollbar.configuration().mutableCopy(); config.destination.accessToken = RollbarTestHelper.getRollbarPayloadsAccessToken(); config.destination.environment = RollbarTestHelper.getRollbarEnvironment(); @@ -103,31 +100,28 @@ final class RollbarNotifierLoggerTests: XCTestCase { config.developerOptions.transmit = true; Rollbar.update(withConfiguration: config); Rollbar.criticalMessage("Transmission test YES"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarTestUtil.wait(waitTimeInSeconds: 1.0); config.developerOptions.transmit = false; Rollbar.update(withConfiguration: config); Rollbar.criticalMessage("Transmission test NO"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarTestUtil.wait(waitTimeInSeconds: 1.0); config.developerOptions.transmit = true; Rollbar.update(withConfiguration: config); Rollbar.criticalMessage("Transmission test YES2"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarTestUtil.wait(waitTimeInSeconds: 1.0); var count = 50; while (count > 0) { Rollbar.criticalMessage("Rate Limit Test \(count)"); - RollbarTestUtil.waitForPesistenceToComplete(); + RollbarTestUtil.wait(waitTimeInSeconds: 1.0); count -= 1; } } func testNotification() { -// RollbarTestUtil.clearLogFile(); -// RollbarTestUtil.clearTelemetryFile(); - let notificationText = [ "error": ["testing-error"], "debug": ["testing-debug"], @@ -152,6 +146,7 @@ final class RollbarNotifierLoggerTests: XCTestCase { } RollbarLogger.flushRollbarThread(); + RollbarTestUtil.wait(waitTimeInSeconds: 6.0); let items = RollbarTestUtil.readTransmittedPayloadsAsStrings(); XCTAssertTrue(items.count >= notificationText.count); @@ -170,37 +165,37 @@ final class RollbarNotifierLoggerTests: XCTestCase { XCTAssertEqual(count, notificationText.count); } - func testNSErrorReporting() { - do { - try RollbarTestUtil.makeTroubledCall(); - //var expectedErrorCallDepth: uint = 5; - //try RollbarTestUtil.simulateError(callDepth: &expectedErrorCallDepth); - } - catch RollbarTestUtilError.simulatedException(let errorDescription, let errorCallStack) { - print("Caught an error: \(errorDescription)"); - print("Caught error's call stack:"); - errorCallStack.forEach({print($0)}); - } - catch let e as BackTracedErrorProtocol { - //print("Caught an error: \(e.localizedDescription)"); - print("Caught an error: \(e.errorDescription)"); - print("Caught error's call stack:"); - e.errorCallStack.forEach({print($0)}); - } - catch { - print("Caught an error: \(error)"); - //print("Caught an error: \(error.localizedDescription)"); - //print("Corresponding call stack trace at the catch point:"); - Thread.callStackSymbols.forEach{print($0)} - } - } +// func testNSErrorReporting() { +// do { +// try RollbarTestUtil.makeTroubledCall(); +// //var expectedErrorCallDepth: uint = 5; +// //try RollbarTestUtil.simulateError(callDepth: &expectedErrorCallDepth); +// } +// catch RollbarTestUtilError.simulatedException(let errorDescription, let errorCallStack) { +// print("Caught an error: \(errorDescription)"); +// print("Caught error's call stack:"); +// errorCallStack.forEach({print($0)}); +// } +// catch let e as BackTracedErrorProtocol { +// //print("Caught an error: \(e.localizedDescription)"); +// print("Caught an error: \(e.errorDescription)"); +// print("Caught error's call stack:"); +// e.errorCallStack.forEach({print($0)}); +// } +// catch { +// print("Caught an error: \(error)"); +// //print("Caught an error: \(error.localizedDescription)"); +// //print("Corresponding call stack trace at the catch point:"); +// Thread.callStackSymbols.forEach{print($0)} +// } +// } static var allTests = [ ("testRollbarConfiguration", testRollbarConfiguration), ("testRollbarNotifiersIndependentConfiguration", testRollbarNotifiersIndependentConfiguration), ("testRollbarTransmit", testRollbarTransmit), ("testNotification", testNotification), - ("testNSErrorReporting", testNSErrorReporting), + //("testNSErrorReporting", testNSErrorReporting), ] } #endif diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift index cdfaefd3..6ac155e4 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift @@ -28,7 +28,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { } override func tearDown() { - Rollbar.update(withConfiguration: RollbarMutableConfig()); + super.tearDown(); } @@ -39,11 +39,10 @@ final class RollbarNotifierTelemetryTests: XCTestCase { config.telemetry.memoryStatsAutocollectionInterval = 0.5; Rollbar.update(withConfiguration: config); - Thread.sleep(forTimeInterval: 5.0); + Thread.sleep(forTimeInterval: 2.0); Rollbar.criticalMessage("Must contain memory telemetry!"); RollbarLogger.flushRollbarThread(); - RollbarTestUtil.waitForPesistenceToComplete(); let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); @@ -67,18 +66,16 @@ final class RollbarNotifierTelemetryTests: XCTestCase { let config = RollbarMutableConfig(); config.destination.accessToken = RollbarTestHelper.getRollbarPayloadsAccessToken(); config.destination.environment = RollbarTestHelper.getRollbarEnvironment(); + config.developerOptions.transmit = true; config.telemetry.enabled = true; config.telemetry.memoryStatsAutocollectionInterval = 0.5; Rollbar.update(withConfiguration: config); - //let resultingConfig = Rollbar.currentConfiguration(); Rollbar.criticalMessage("Rollbar will be testing memory telemetry!"); - RollbarTestUtil.waitForPesistenceToComplete(); - Thread.sleep(forTimeInterval: 2.0); + RollbarTestUtil.wait(waitTimeInSeconds: 2.0); Rollbar.criticalMessage("Must contain memory telemetry!"); - RollbarTestUtil.waitForPesistenceToComplete(); - Thread.sleep(forTimeInterval: 3.0); + RollbarTestUtil.wait(waitTimeInSeconds: 3.0); } func testTelemetryCapture() { @@ -117,11 +114,9 @@ final class RollbarNotifierTelemetryTests: XCTestCase { withData: ["data" : "content"] ); - RollbarLogger.flushRollbarThread(); Rollbar.debugMessage("Test"); RollbarLogger.flushRollbarThread(); - RollbarTestUtil.waitForPesistenceToComplete(); let logItems = RollbarTestUtil.readIncomingPayloadsAsStrings(); let logItem = logItems[logItems.count - 1]; let payload = RollbarPayload(jsonString: logItem); @@ -208,14 +203,11 @@ final class RollbarNotifierTelemetryTests: XCTestCase { withData: ["myTelemetryParameter": "itsValue"] ); - //RollbarTestUtil.waitForPesistenceToComplete(); - Rollbar.debugMessage("Demonstrate Telemetry capture"); Rollbar.debugMessage("Demonstrate Telemetry capture once more..."); Rollbar.debugMessage("DO Demonstrate Telemetry capture once more..."); + RollbarLogger.flushRollbarThread(); - RollbarTestUtil.waitForPesistenceToComplete(); - let logItems = RollbarTestUtil.readTransmittedPayloadsAsStrings(); for item in logItems { let payload = RollbarPayload(jsonString: item); diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift index 449b4d3a..8b5e7e07 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTruncationTests.swift @@ -11,26 +11,13 @@ final class RollbarNotifierTruncationTests: XCTestCase { super.setUp(); - RollbarTestUtil.deleteLogFiles(); - RollbarTestUtil.deletePayloadsStoreFile(); - RollbarTestUtil.clearTelemetryFile(); - - let config = RollbarConfig.mutableConfig( - withAccessToken: RollbarTestHelper.getRollbarPayloadsAccessToken(), - environment: RollbarTestHelper.getRollbarEnvironment() - ); - Rollbar.update(withConfiguration: config); } override func tearDown() { - Rollbar.update(withConfiguration: RollbarMutableConfig()); + super.tearDown(); } - func testDefaultRollbarConfiguration() { - NSLog("%@", Rollbar.configuration()); - } - func testMeasureTotalEncodingBytes() { let testString1 = "ABCD"; @@ -269,7 +256,6 @@ final class RollbarNotifierTruncationTests: XCTestCase { static var allTests = [ - ("testDefaultRollbarConfiguration", testDefaultRollbarConfiguration), ("testMeasureTotalEncodingBytes", testMeasureTotalEncodingBytes), ("testTruncateStringToTotalBytes", testTruncateStringToTotalBytes), ("testTruncateStringToTotalBytesUnicode", testTruncateStringToTotalBytesUnicode), From 6e339163f410f30fb4c1bf240ece1b4d9dee9146 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 30 Aug 2022 10:21:09 -0700 Subject: [PATCH 105/127] fix: typos --- .../Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m index b1c853c5..939c94a9 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m @@ -16,11 +16,11 @@ static NSString * const DFK_TRANSMIT = @"transmit"; static NSString * const DFK_SUPPRESS_SDK_INFO_LOGGING = @"suppressSdkInfoLogging"; -static NSString * const DFK_LOG_INCOMING_PAYLOADS = @"logIncomingPayload"; +static NSString * const DFK_LOG_INCOMING_PAYLOADS = @"logIncomingPayloads"; static NSString * const DFK_LOG_INCOMING_PAYLOADS_FILE = @"logIncomingPayloadsFile"; -static NSString * const DFK_LOG_TRANSMITTED_PAYLOADS = @"logTransmittedsPayload"; +static NSString * const DFK_LOG_TRANSMITTED_PAYLOADS = @"logTransmittedPayloads"; static NSString * const DFK_LOG_TRANSMITTED_PAYLOADS_FILE = @"logTransmittedPayloadsFile"; -static NSString * const DFK_LOG_DROPPED_PAYLOADS = @"logDroppedsPayload"; +static NSString * const DFK_LOG_DROPPED_PAYLOADS = @"logDroppedPayloads"; static NSString * const DFK_LOG_DROPPED_PAYLOADS_FILE = @"logDroppedPayloadsFile"; #pragma mark - class implementation From 162f0e97c34d7b2a8c4609af9bf7ba0553250711 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 30 Aug 2022 17:11:17 -0700 Subject: [PATCH 106/127] fix: developer options properties implementation typos --- .../Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m | 6 +++--- .../RollbarNotifier/include/RollbarDeveloperOptions.h | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m index 939c94a9..8dfd570a 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarDeveloperOptions.m @@ -137,11 +137,11 @@ @implementation RollbarMutableDeveloperOptions @dynamic transmit; @dynamic suppressSdkInfoLogging; @dynamic logIncomingPayloads; -@dynamic incomingPayloadLogFile; +@dynamic incomingPayloadsLogFile; @dynamic logTransmittedPayloads; -@dynamic transmittedPayloadLogFile; +@dynamic transmittedPayloadsLogFile; @dynamic logDroppedPayloads; -@dynamic droppedPayloadLogFile; +@dynamic droppedPayloadsLogFile; #pragma mark - property accessors diff --git a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h index 17b79c81..9bd7aa9b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h +++ b/RollbarNotifier/Sources/RollbarNotifier/include/RollbarDeveloperOptions.h @@ -98,13 +98,13 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, readwrite) BOOL logDroppedPayloads; /// Log file to use for local logged incoming payloads -@property (nonatomic, readwrite, copy) NSString *incomingPayloadLogFile; +@property (nonatomic, readwrite, copy) NSString *incomingPayloadsLogFile; /// Log file to use for local logged transmitted payloads -@property (nonatomic, readwrite, copy) NSString *transmittedPayloadLogFile; +@property (nonatomic, readwrite, copy) NSString *transmittedPayloadsLogFile; /// Log file to use for local logged dropped payloads -@property (nonatomic, readwrite, copy) NSString *droppedPayloadLogFile; +@property (nonatomic, readwrite, copy) NSString *droppedPayloadsLogFile; @end From 8a41c87fed7071b7827020a4e45d733ab034afa2 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 30 Aug 2022 17:13:26 -0700 Subject: [PATCH 107/127] fix: making sure payload factory produces only mutable internal structures of a payload --- .../Sources/RollbarNotifier/RollbarPayloadFactory.m | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m index 80af64ba..551f9812 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadFactory.m @@ -24,7 +24,7 @@ @implementation RollbarPayloadFactory { @private RollbarConfig *_config; // expected to be nonnull... - NSDictionary *_osData; + NSMutableDictionary *_osData; } + (instancetype)factoryWithConfig:(nonnull RollbarConfig *)config { @@ -148,7 +148,7 @@ -(nullable RollbarPayload *)buildRollbarPayloadWithLevel:(RollbarLevel)level // this is done only for backward compatibility for customers that used to rely on this undocumented // extra data with a message: if (message && extra) { - [body.message setData:extra byKey:@"extra"]; + [body.message setData:extra.mutableCopy byKey:@"extra"]; } // compile payload data: @@ -164,7 +164,7 @@ -(nullable RollbarPayload *)buildRollbarPayloadWithLevel:(RollbarLevel)level // neither crash report no exception payload objects have placeholders for any extra data // or an extra message, let's preserve them as the custom data: if (extra) { - customData[@"error.extra"] = extra; + customData[@"error.extra"] = extra.mutableCopy; } if (message && message.length > 0) { customData[@"error.message"] = message; @@ -262,7 +262,7 @@ -(RollbarServer *)buildRollbarServer { } } --(NSDictionary *)buildOSData { +-(NSDictionary *)buildOSData { //TODO: redo this implementation based on the helper utils used by RollbarSession or on RollbarSession itself... @@ -301,7 +301,7 @@ -(NSDictionary *)buildOSData { @"short_version": shortVersion ? shortVersion : @"", @"bundle_identifier": bundleIdentifier ? bundleIdentifier : @"", @"app_name": bundleName ? bundleName : @"" - }; + }.mutableCopy; #else NSOperatingSystemVersion osVer = [[NSProcessInfo processInfo] operatingSystemVersion]; self->_osData = @{ @@ -316,7 +316,7 @@ -(NSDictionary *)buildOSData { @"short_version": shortVersion ? shortVersion : @"", @"bundle_identifier": bundleIdentifier ? bundleIdentifier : @"", @"app_name": bundleName ? bundleName : [[NSProcessInfo processInfo] processName] - }; + }.mutableCopy; #endif return self->_osData; From 6d1dbfb1709b674bc98abcbb2bab01e189f031b3 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 30 Aug 2022 17:14:25 -0700 Subject: [PATCH 108/127] feat: adding more diagnostics to the payload truncator --- .../RollbarNotifier/RollbarPayloadTruncator.m | 151 ++++++++++-------- 1 file changed, 84 insertions(+), 67 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadTruncator.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadTruncator.m index 6a698182..7c8234b0 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadTruncator.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadTruncator.m @@ -56,37 +56,55 @@ +(void)truncatePayload:(NSMutableDictionary*)payload ]; if (continueTruncation) { - continueTruncation = + @try { + continueTruncation = [RollbarPayloadTruncator truncatePayload:payload toTotalBytes:limit byReducingItems:pathToCrashThreads keepingHeadsCount:payloadHeadCrashThreadsToKeep keepingTailsCount:payloadTailCrashThreadsToKeep - ]; + ]; + } @catch (NSException *exception) { + RollbarSdkLog(@"Payload truncation EXCEPTION: %@", exception); + } + } unsigned long stringLimit = maxStringBytesLimit; while (continueTruncation && (stringLimit >= minStringBytesLimit)) { - continueTruncation = [RollbarPayloadTruncator truncatePayload:payload - toTotalBytes:limit - byLimitingStringBytes:stringLimit - ]; - stringLimit /= 2; + @try { + continueTruncation = [RollbarPayloadTruncator truncatePayload:payload + toTotalBytes:limit + byLimitingStringBytes:stringLimit + ]; + stringLimit /= 2; + } @catch (NSException *exception) { + RollbarSdkLog(@"Payload truncation EXCEPTION: %@", exception); + } } if (continueTruncation) { - continueTruncation = [RollbarPayloadTruncator truncatePayload:payload - toTotalBytes:limit - withExceptionMessageLimit:maxExceptionMessageChars - andTraceFramesLimit:maxTraceFrames - ]; + @try { + continueTruncation = [RollbarPayloadTruncator truncatePayload:payload + toTotalBytes:limit + withExceptionMessageLimit:maxExceptionMessageChars + andTraceFramesLimit:maxTraceFrames + ]; + } @catch (NSException *exception) { + RollbarSdkLog(@"Payload truncation EXCEPTION: %@", exception); + } } if (continueTruncation) { - - [RollbarPayloadTruncator limitRawCrashReportInPayload:payload]; + + @try { + [RollbarPayloadTruncator limitRawCrashReportInPayload:payload]; + } @catch (NSException *exception) { + RollbarSdkLog(@"Payload truncation EXCEPTION: %@", exception); + } + } } @@ -182,51 +200,60 @@ +(BOOL)truncatePayload:(NSMutableDictionary*)payload +(void)itereateObjectStructure:(id)obj whileTuncatingStrings:(unsigned long)stringBytesLimit { - if ([obj isKindOfClass:[NSMutableString class]] && [RollbarPayloadTruncator isMutable:obj]) { - - //truncate the string obj: - [obj setString:[RollbarPayloadTruncator truncateString:obj - toTotalBytes:stringBytesLimit] - ]; - } - else if ([obj isKindOfClass:[NSArray class]]) { - - //recurse the collection obj's items: - [obj enumerateObjectsUsingBlock: ^(id item, NSUInteger idx, BOOL *stop) { - [RollbarPayloadTruncator itereateObjectStructure:item - whileTuncatingStrings:stringBytesLimit - ]; - }]; - } - else if ([obj isKindOfClass:[NSDictionary class]]) { - - //recurse the collection obj's items: - [obj enumerateKeysAndObjectsUsingBlock: ^(id key, id item, BOOL *stop) { - if (![key isEqualToString:@"raw"]) { - if ([item isKindOfClass:[NSMutableString class]] && ![RollbarPayloadTruncator isMutable:item]) { - NSMutableString *mutableItem = [item mutableCopy]; - [obj setObject:mutableItem forKey:key]; - [RollbarPayloadTruncator itereateObjectStructure:mutableItem - whileTuncatingStrings:stringBytesLimit]; - } else { - [RollbarPayloadTruncator itereateObjectStructure:item - whileTuncatingStrings:stringBytesLimit]; + @try { + if ([obj isKindOfClass:[NSMutableString class]] && [RollbarPayloadTruncator isMutable:obj]) { + + //truncate the string obj: + [obj setString:[RollbarPayloadTruncator truncateString:obj + toTotalBytes:stringBytesLimit] + ]; + } + else if ([obj isKindOfClass:[NSArray class]]) { + + //recurse the collection obj's items: + [obj enumerateObjectsUsingBlock: ^(id item, NSUInteger idx, BOOL *stop) { + [RollbarPayloadTruncator itereateObjectStructure:item + whileTuncatingStrings:stringBytesLimit + ]; + }]; + } + else if ([obj isKindOfClass:[NSDictionary class]]) { + + //recurse the collection obj's items: + [obj enumerateKeysAndObjectsUsingBlock: ^(id key, id item, BOOL *stop) { + if (![key isEqualToString:@"raw"]) { + if ([item isKindOfClass:[NSString class]]) { + NSMutableString *strItem = ((NSString *)item).mutableCopy; + @try { + obj[key] = strItem; + } @catch (NSException *exception) { + RollbarSdkLog(@"Payload truncation EXCEPTION: %@", exception); + } + [RollbarPayloadTruncator itereateObjectStructure:strItem + whileTuncatingStrings:stringBytesLimit]; + } else { + [RollbarPayloadTruncator itereateObjectStructure:item + whileTuncatingStrings:stringBytesLimit]; + } } - } - }]; - } - else if ([obj isKindOfClass:[NSSet class]]) { - - //recurse the collection obj's items: - [obj enumerateObjectsUsingBlock: ^(id item, BOOL *stop) { - [RollbarPayloadTruncator itereateObjectStructure:item - whileTuncatingStrings:stringBytesLimit - ]; - }]; - } - else { - //nothing really... + }]; + } + else if ([obj isKindOfClass:[NSSet class]]) { + + //recurse the collection obj's items: + [obj enumerateObjectsUsingBlock: ^(id item, BOOL *stop) { + [RollbarPayloadTruncator itereateObjectStructure:item + whileTuncatingStrings:stringBytesLimit + ]; + }]; + } + else { + //nothing really... + } + } @catch (NSException *exception) { + RollbarSdkLog(@"Payload truncation EXCEPTION: %@", exception); } + } +(BOOL)isMutable:(id)str { @@ -246,16 +273,6 @@ +(BOOL)truncatePayload:(NSMutableDictionary*)payload return FALSE; //payload is small enough, no need to truncate further... } -// NSMutableArray *items = [payload mutableArrayValueForKeyPath:pathToItems]; -// if (items.count <= (headsCount + tailsCount)) { -// return TRUE; -// } -// -// unsigned long totalItemsToRemove = items.count - headsCount - tailsCount; -// [items removeObjectsInRange:NSMakeRange(headsCount, totalItemsToRemove)]; -// -// return TRUE; - id value = [payload valueForKeyPath:pathToItems]; if (value == [NSNull null] || [value isKindOfClass:[NSNull class]]) { From fe00422cd3c9dab75bbb2f5fdd7061076ce81afb Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 30 Aug 2022 17:15:20 -0700 Subject: [PATCH 109/127] refactor: RollbarDTO data seeded initializers --- .../Sources/RollbarCommon/DTOs/RollbarDTO.m | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m index 9b6ff90d..e864ca49 100644 --- a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m +++ b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m @@ -359,7 +359,7 @@ - (instancetype)initWithDictionary:(nullable NSDictionary *)data if (nil == data) { - data = [NSMutableDictionary dictionary]; + data = [NSMutableDictionary dictionary]; } if (![RollbarDTO isTransferableObject:data]) { @@ -367,14 +367,19 @@ - (instancetype)initWithDictionary:(nullable NSDictionary *)data return self; } - if ([data isKindOfClass:[NSMutableDictionary class]]) { + if ([data isKindOfClass:[NSMutableDictionary class]]) { - self->_data = (NSMutableDictionary *) data; + self->_data = (NSMutableDictionary *) data; } - else { - +// else { +// +// self->_data = data.mutableCopy; +// } + + if (!self->_data) { self->_data = data.mutableCopy; } + self->_dataArray = nil; self->_dataDictionary = (NSMutableDictionary *) self->_data; for (NSString *key in self->_dataDictionary.allKeys) { @@ -400,7 +405,8 @@ - (instancetype)initWithArray:(NSArray *)data { self->_dataDictionary = nil; if (!data) { - return self; + //return self; + data = [NSMutableArray arrayWithCapacity:5]; } if (![RollbarDTO isTransferableObject:data]) { @@ -410,9 +416,11 @@ - (instancetype)initWithArray:(NSArray *)data { if ([data isKindOfClass:[NSMutableArray class]]) { self->_data = (NSMutableArray *) data; } - else { + + if (!self->_data) { self->_data = data.mutableCopy; } + self->_dataDictionary = nil; self->_dataArray = (NSMutableArray *) self->_data; for (id item in self->_dataArray) { From 9e6b08d258f26d347a8906a3da72666203ddf7ac Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 30 Aug 2022 17:19:03 -0700 Subject: [PATCH 110/127] test: refactored Obj-C RollbarConfig unit tests --- .../RollbarConfigTests.m | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m index 75f0a6cb..d7e3199f 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigTests.m @@ -81,23 +81,23 @@ - (void)testRollbarDeveloperOptions { mutable.transmit = NO; mutable.suppressSdkInfoLogging = NO; mutable.logTransmittedPayloads = NO; - mutable.transmittedPayloadLogFile = @"test_PAYLOADS.LOG_old"; + mutable.transmittedPayloadsLogFile = @"test_PAYLOADS.LOG_old"; XCTAssertFalse(mutable.enabled); XCTAssertFalse(mutable.transmit); XCTAssertFalse(mutable.suppressSdkInfoLogging); XCTAssertFalse(mutable.logTransmittedPayloads); - XCTAssertTrue([mutable.transmittedPayloadLogFile isEqualToString:@"test_PAYLOADS.LOG_old"]); + XCTAssertTrue([mutable.transmittedPayloadsLogFile isEqualToString:@"test_PAYLOADS.LOG_old"]); mutable.enabled = YES; mutable.transmit = YES; mutable.suppressSdkInfoLogging = YES; mutable.logTransmittedPayloads = YES; - mutable.transmittedPayloadLogFile = @"test_PAYLOADS.LOG"; + mutable.transmittedPayloadsLogFile = @"test_PAYLOADS.LOG"; XCTAssertTrue(mutable.enabled); XCTAssertTrue(mutable.transmit); XCTAssertTrue(mutable.suppressSdkInfoLogging); XCTAssertTrue(mutable.logTransmittedPayloads); - XCTAssertTrue([mutable.transmittedPayloadLogFile isEqualToString:@"test_PAYLOADS.LOG"]); + XCTAssertTrue([mutable.transmittedPayloadsLogFile isEqualToString:@"test_PAYLOADS.LOG"]); NSString *content = [mutable serializeToJSONString]; XCTAssertNotNil(content); @@ -593,11 +593,11 @@ - (void)testRollbarConfig { RollbarMutableConfig *mutable = [RollbarMutableConfig new]; mutable.destination.accessToken = @"test_AT_old"; RollbarMutableDeveloperOptions *devOptions = [RollbarMutableDeveloperOptions new]; - devOptions.transmittedPayloadLogFile = @"test_PL_old"; + devOptions.transmittedPayloadsLogFile = @"test_PL_old"; mutable.developerOptions = devOptions; XCTAssertTrue([mutable.destination.accessToken isEqualToString:@"test_AT_old"]); - XCTAssertTrue([mutable.developerOptions.transmittedPayloadLogFile isEqualToString:@"test_PL_old"]); + XCTAssertTrue([mutable.developerOptions.transmittedPayloadsLogFile isEqualToString:@"test_PL_old"]); NSString *content = [mutable serializeToJSONString]; XCTAssertNotNil(content); @@ -605,10 +605,10 @@ - (void)testRollbarConfig { XCTAssertTrue([content containsString:@"test_PL_old"]); mutable.destination.accessToken = @"test_AT"; - mutable.developerOptions.transmittedPayloadLogFile = @"test_PL"; + mutable.developerOptions.transmittedPayloadsLogFile = @"test_PL"; XCTAssertTrue([mutable.destination.accessToken isEqualToString:@"test_AT"]); - XCTAssertTrue([mutable.developerOptions.transmittedPayloadLogFile isEqualToString:@"test_PL"]); + XCTAssertTrue([mutable.developerOptions.transmittedPayloadsLogFile isEqualToString:@"test_PL"]); content = [mutable serializeToJSONString]; XCTAssertNotNil(content); From 1cba0f2bd59f386bdaafc9a40948344fa02b35b2 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 30 Aug 2022 17:19:42 -0700 Subject: [PATCH 111/127] refactor: UnitTesting API --- .../Sources/UnitTesting/RollbarTestUtil.swift | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift index 6572525f..a336c6cb 100644 --- a/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift +++ b/UnitTesting/Sources/UnitTesting/RollbarTestUtil.swift @@ -166,22 +166,22 @@ import RollbarCommon return items; } - @objc public static func readIncomingPayloads() -> [NSMutableDictionary] { + @objc public static func readIncomingPayloadsAsDictionaries() -> [NSMutableDictionary] { - return RollbarTestUtil.readItemsFromLogFile(filePath: RollbarTestUtil.getIncomingPayloadsLogFilePath()); + return RollbarTestUtil.readItemDictionariesFromLogFile(filePath: RollbarTestUtil.getIncomingPayloadsLogFilePath()); } - @objc public static func readTransmittedPayloads() -> [NSMutableDictionary] { + @objc public static func readTransmittedPayloadsAsDictionaries() -> [NSMutableDictionary] { - return RollbarTestUtil.readItemsFromLogFile(filePath: RollbarTestUtil.getTransmittedPayloadsLogFilePath()); + return RollbarTestUtil.readItemDictionariesFromLogFile(filePath: RollbarTestUtil.getTransmittedPayloadsLogFilePath()); } - @objc public static func readDroppedPayloads() -> [NSMutableDictionary] { + @objc public static func readDroppedPayloadsAsDictionaries() -> [NSMutableDictionary] { - return RollbarTestUtil.readItemsFromLogFile(filePath: RollbarTestUtil.getDroppedPayloadsLogFilePath()); + return RollbarTestUtil.readItemDictionariesFromLogFile(filePath: RollbarTestUtil.getDroppedPayloadsLogFilePath()); } - @objc public static func readItemsFromLogFile(filePath: String) -> [NSMutableDictionary] { + @objc public static func readItemDictionariesFromLogFile(filePath: String) -> [NSMutableDictionary] { let fileReader = RollbarFileReader(filePath: filePath, andOffset: 0); var items = [NSMutableDictionary] (); From 49a2a69d3fd908015f1a975f6c8f27f291cec610 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 30 Aug 2022 17:20:36 -0700 Subject: [PATCH 112/127] test: refactored Obj-C payload truncation unit tests --- .../PayloadTruncationTests.m | 73 +++++++++++++------ 1 file changed, 50 insertions(+), 23 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m index 979b9244..4c783eac 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/PayloadTruncationTests.m @@ -15,24 +15,10 @@ @implementation PayloadTruncationTests - (void)setUp { [super setUp]; - - [RollbarLogger clearSdkDataStore]; - - RollbarMutableConfig *config = - [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment]]; - - [Rollbar initWithConfiguration:config]; - - [RollbarTestUtil waitWithWaitTimeInSeconds:3]; - [RollbarLogger clearSdkDataStore]; - NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; - XCTAssertEqual(items.count, 0); } - (void)tearDown { - [Rollbar updateWithConfiguration:[RollbarConfig new]]; [super tearDown]; } @@ -187,8 +173,21 @@ - (void)testVisuallyTruncateStringToTotalBytesUnicode { - (void)testPayloadTruncation { - //[NSThread sleepForTimeInterval:5.0f]; - NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + RollbarMutableConfig *config = + [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; + config.developerOptions.logIncomingPayloads = YES; + config.developerOptions.logTransmittedPayloads = YES; + config.developerOptions.logDroppedPayloads = YES; + config.developerOptions.transmit = NO; + + [Rollbar initWithConfiguration:config]; + + [RollbarTestUtil waitWithWaitTimeInSeconds:2]; + [RollbarTestUtil deleteLogFiles]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + + NSArray *items = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; XCTAssertEqual(items.count, 0); @try { @@ -203,9 +202,11 @@ - (void)testPayloadTruncation { [Rollbar errorException:exception]; } - [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:3]; - items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + items = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; + XCTAssertNotNil(items); + XCTAssertEqual(items.count, 1); for (id payload in items) { NSMutableArray *frames = [payload mutableArrayValueForKeyPath:@"body.trace.frames"]; @@ -226,6 +227,23 @@ - (void)testPayloadTruncation { - (void)testErrorReportingWithTruncation { + RollbarMutableConfig *config = + [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] + environment:[RollbarTestHelper getRollbarEnvironment]]; + config.developerOptions.logIncomingPayloads = YES; + config.developerOptions.logTransmittedPayloads = YES; + config.developerOptions.logDroppedPayloads = YES; + config.developerOptions.transmit = YES; + + [Rollbar initWithConfiguration:config]; + + [RollbarTestUtil waitWithWaitTimeInSeconds:5]; + [RollbarTestUtil deleteLogFiles]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + + NSArray *items = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; + XCTAssertEqual(items.count, 0); + NSMutableString *simulatedLongString = [[NSMutableString alloc] initWithCapacity:(512 + 1)*1024]; while (simulatedLongString.length < (512 * 1024)) { @@ -236,6 +254,14 @@ - (void)testErrorReportingWithTruncation { data:@{@"extra_truncatable_data": simulatedLongString} ]; + [RollbarTestUtil waitWithWaitTimeInSeconds:2]; + items = [RollbarTestUtil readIncomingPayloadsAsDictionaries]; + XCTAssertEqual(items.count, 1); + XCTAssertTrue([@"Message with long extra data" isEqualToString:[items[0] valueForKeyPath:@"body.message.body"]]); + [RollbarTestUtil waitWithWaitTimeInSeconds:3]; + items = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; + XCTAssertEqual(items.count, 1); + @try { NSArray *crew = [NSArray arrayWithObjects: @"Dave", @@ -249,12 +275,13 @@ - (void)testErrorReportingWithTruncation { [Rollbar criticalMessage:simulatedLongString data:@{@"extra_truncatable_data": simulatedLongString} ]; - NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; - XCTAssertTrue(items.count > 0); - [NSThread sleepForTimeInterval:5.0f]; - items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; - XCTAssertEqual(items.count, 0); + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + items = [RollbarTestUtil readIncomingPayloadsAsDictionaries]; + XCTAssertEqual(items.count, 2); + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + items = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; + XCTAssertEqual(items.count, 2); } } From 8107ed228b7e5868df5f63f31660edabe6584d2b Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Tue, 30 Aug 2022 17:21:18 -0700 Subject: [PATCH 113/127] test: refactored Swift telemetry unit tests --- .../RollbarNotifierTests/RollbarNotifierTelemetryTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift index 6ac155e4..af20fbd6 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierTelemetryTests.swift @@ -39,7 +39,7 @@ final class RollbarNotifierTelemetryTests: XCTestCase { config.telemetry.memoryStatsAutocollectionInterval = 0.5; Rollbar.update(withConfiguration: config); - Thread.sleep(forTimeInterval: 2.0); + RollbarTestUtil .wait(waitTimeInSeconds: 3); Rollbar.criticalMessage("Must contain memory telemetry!"); RollbarLogger.flushRollbarThread(); From bd8d2c08c41f482b08c14bd090a4cb4af22fffff Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 31 Aug 2022 15:06:19 -0700 Subject: [PATCH 114/127] refactor: RollbarPayloadRepository --- .../RollbarPayloadRepository.m | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m index a70068bc..c1192fa7 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarPayloadRepository.m @@ -473,9 +473,15 @@ - (BOOL)clear { - (void)initDB:(BOOL)inMemory { - [self openDB:inMemory]; - [self ensureDestinationsTable]; - [self ensurePayloadsTable]; + if ([self openDB:inMemory]) { + + [self ensureDestinationsTable]; + [self ensurePayloadsTable]; + } + else { + + RollbarSdkLog(@"Can not open database: %@!!!", inMemory ? @"in memory" : self->_storePath); + } } - (BOOL)openDB:(BOOL)inMemory { @@ -490,8 +496,9 @@ - (BOOL)openDB:(BOOL)inMemory { RollbarSdkLog(@"sqlite3_open: %s", sqlite3_errmsg(self->_db)); return NO; } - + [self checkDbFile]; + return YES; } @@ -602,7 +609,9 @@ - (void)checkDbFile { [self ensurePayloadsTable]; return; } - NSAssert([[NSFileManager defaultManager] fileExistsAtPath:self->_storePath], + NSAssert(self->_storePath ? + [[NSFileManager defaultManager] fileExistsAtPath:self->_storePath] + : YES, @"Persistent payloads store was not created: %@!!!", self->_storePath ); From 9025542501afccb44b7fc2e8ce4ec07c6d4d0c73 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 31 Aug 2022 15:06:43 -0700 Subject: [PATCH 115/127] test: refactored RollbarConfigurationTests --- .../RollbarConfigurationTests.m | 89 ++++++++++--------- 1 file changed, 48 insertions(+), 41 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m index b40d502a..3313450e 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarConfigurationTests.m @@ -17,33 +17,39 @@ - (void)setUp { [super setUp]; - [RollbarLogger clearSdkDataStore]; + [RollbarTestUtil deleteLogFiles]; + [RollbarTestUtil deletePayloadsStoreFile]; + [RollbarTestUtil clearTelemetryFile]; - RollbarMutableConfig *config = - [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] - environment:[RollbarTestHelper getRollbarEnvironment]]; + RollbarMutableConfig *config = [RollbarMutableConfig new]; + config.developerOptions.transmit = NO; + config.developerOptions.logIncomingPayloads = YES; + config.developerOptions.logTransmittedPayloads = YES; + config.developerOptions.logDroppedPayloads = YES; + config.loggingOptions.enableOomDetection = NO; + [Rollbar initWithConfiguration:config]; - - [NSThread sleepForTimeInterval:1.0f]; - [RollbarLogger clearSdkDataStore]; - NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; - XCTAssertEqual(items.count, 0); + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + [RollbarTestUtil deleteLogFiles]; + [RollbarTestUtil deletePayloadsStoreFile]; + [RollbarTestUtil clearTelemetryFile]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; } - (void)tearDown { - [Rollbar updateWithConfiguration:[RollbarConfig new]]; [super tearDown]; } -- (BOOL)rollbarStoreContains:(nonnull NSString *)string { +- (BOOL)rollbarTransmittedPayloadsLogContains:(nonnull NSString *)string { [RollbarLogger flushRollbarThread]; - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; - for (NSDictionary *item in logItems) { - RollbarPayload *payload = [[RollbarPayload alloc] initWithDictionary:item]; - if ([[payload serializeToJSONString] containsString:string]) { + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + + NSArray *logItems = [RollbarTestUtil readTransmittedPayloadsAsStrings]; + for (NSString *item in logItems) { + if ([item containsString:string]) { return YES; } } @@ -83,11 +89,12 @@ - (void)testScrubSafeListFields { } [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"test"]; - + [RollbarLogger flushRollbarThread]; - + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + // verify the fields were scrubbed: - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + NSArray *logItems = [RollbarTestUtil readIncomingPayloadsAsDictionaries]; for (NSString *key in keys) { NSString *content = [logItems[0] valueForKeyPath:key]; XCTAssertTrue([content isEqualToString:scrubedContent], @@ -98,8 +105,10 @@ - (void)testScrubSafeListFields { ); } - [RollbarLogger clearSdkDataStore]; - + [RollbarTestUtil deletePayloadsStoreFile]; + [RollbarTestUtil deleteLogFiles]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + // define scrub whitelist fields (the same as the scrub fields - to counterbalance them): for (NSString *key in keys) { [config.dataScrubber addScrubSafeListField:key]; @@ -108,9 +117,10 @@ - (void)testScrubSafeListFields { [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; - + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + // verify the fields were not scrubbed: - logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + logItems = [RollbarTestUtil readIncomingPayloadsAsDictionaries]; for (NSString *key in keys) { NSString *content = [logItems[0] valueForKeyPath:key]; XCTAssertTrue(![content isEqualToString:scrubedContent], @@ -124,8 +134,6 @@ - (void)testScrubSafeListFields { - (void)testTelemetryEnabled { - [RollbarLogger clearSdkDataStore]; - BOOL expectedFlag = NO; RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.telemetry.enabled = expectedFlag; @@ -226,9 +234,7 @@ - (void)testViewInputTelemetrScrubFieldsConfig { - (void)testEnabled { - [RollbarLogger clearSdkDataStore]; - - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + NSArray *logItems = [RollbarTestUtil readIncomingPayloadsAsDictionaries]; XCTAssertTrue(logItems.count == 0, @"logItems count is expected to be 0. Actual value is %lu", (unsigned long) logItems.count @@ -240,19 +246,17 @@ - (void)testEnabled { //Rollbar.currentLogger.configuration.developerOptions.enabled = NO; [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"Test1"]; - XCTAssertTrue(![self rollbarStoreContains:@"Test1"]); + XCTAssertTrue(![self rollbarTransmittedPayloadsLogContains:@"Test1"]); config.developerOptions.enabled = YES; [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"Test2"]; - XCTAssertTrue([self rollbarStoreContains:@"Test2"]); + XCTAssertTrue([self rollbarTransmittedPayloadsLogContains:@"Test2"]); config.developerOptions.enabled = NO; [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"Test3"]; - XCTAssertTrue(![self rollbarStoreContains:@"Test3"]); - - [RollbarLogger clearSdkDataStore]; + XCTAssertTrue(![self rollbarTransmittedPayloadsLogContains:@"Test3"]); } - (void)testMaximumTelemetryEvents { @@ -272,8 +276,9 @@ - (void)testMaximumTelemetryEvents { [Rollbar debugMessage:@"Test"]; [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + NSArray *logItems = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; NSDictionary *item = logItems[logItems.count - 1]; NSArray *telemetryData = [item valueForKeyPath:@"body.telemetry"]; XCTAssertTrue(telemetryData.count == max, @@ -286,7 +291,7 @@ - (void)testMaximumTelemetryEvents { - (void)testCheckIgnore { [Rollbar debugMessage:@"Don't ignore this"]; - XCTAssertTrue([self rollbarStoreContains:@"Don't ignore this"]); + XCTAssertTrue([self rollbarTransmittedPayloadsLogContains:@"Don't ignore this"]); RollbarMutableConfig *config = [[Rollbar configuration] mutableCopy]; config.checkIgnoreRollbarData = ^BOOL(RollbarData *payloadData) { @@ -294,7 +299,7 @@ - (void)testCheckIgnore { }; [Rollbar updateWithConfiguration:config]; [Rollbar debugMessage:@"Must ignore this"]; - XCTAssertTrue(![self rollbarStoreContains:@"Must ignore this"]); + XCTAssertTrue(![self rollbarTransmittedPayloadsLogContains:@"Must ignore this"]); } - (void)testServerData { @@ -313,8 +318,9 @@ - (void)testServerData { [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + NSArray *logItems = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; NSDictionary *item = logItems[0]; NSDictionary *server = item[@"server"]; @@ -355,8 +361,9 @@ - (void)testPayloadModification { [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + NSArray *logItems = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; NSString *msg1 = [logItems[0] valueForKeyPath:@"body.message.body"]; NSString *msg2 = [logItems[0] valueForKeyPath:@"body.message.body2"]; @@ -385,8 +392,9 @@ - (void)testScrubField { [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + NSArray *logItems = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; for (NSString *key in keys) { NSString *content = [logItems[0] valueForKeyPath:key]; XCTAssertTrue([content isEqualToString:scrubedContent], @@ -407,8 +415,6 @@ - (void)testLogTelemetryAutoCapture { config.telemetry.enabled = YES; config.telemetry.captureLog = YES; [Rollbar updateWithConfiguration:config]; - [RollbarLogger flushRollbarThread]; - [RollbarLogger clearSdkDataStore]; // The following line ensures the captureLogAsTelemetryData setting is flushed through the internal queue [[RollbarTelemetry sharedInstance] getAllData]; @@ -416,8 +422,9 @@ - (void)testLogTelemetryAutoCapture { [Rollbar debugMessage:@"test"]; [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + NSArray *logItems = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; NSArray *telemetryData = [logItems[0] valueForKeyPath:@"body.telemetry"]; NSString *telemetryMsg = [telemetryData[0] valueForKeyPath:@"body.message"]; XCTAssertTrue([logMsg isEqualToString:telemetryMsg], From 8330d537b8a59798a90b4c80d00988b526279c37 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 31 Aug 2022 15:32:06 -0700 Subject: [PATCH 116/127] test: refactored RollbarInfrastructureTests --- .../RollbarInfrastructureTests.m | 53 ++++++++++++++----- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m index 059e6674..27f1f291 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarInfrastructureTests.m @@ -48,11 +48,15 @@ - (void)test1_RollbarInfrastructureNotConfiguredException { - (void)test2_Basics { - [RollbarLogger clearSdkDataStore]; - NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + [RollbarTestUtil deleteLogFiles]; + [RollbarTestUtil deletePayloadsStoreFile]; + [RollbarTestUtil clearTelemetryFile]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + + NSArray *items = [RollbarTestUtil readIncomingPayloadsAsStrings]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); @@ -61,12 +65,16 @@ - (void)test2_Basics { environment:[RollbarTestHelper getRollbarEnvironment] ]; config.developerOptions.transmit = NO; + config.developerOptions.logIncomingPayloads = YES; config.developerOptions.logTransmittedPayloads = YES; + config.developerOptions.logDroppedPayloads = YES; config.loggingOptions.maximumReportsPerMinute = 180; [[RollbarInfrastructure sharedInstance] configureWith:config]; - [NSThread sleepForTimeInterval:1.0f]; - items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + //[NSThread sleepForTimeInterval:1.0f]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; XCTAssertNotNil(items); [[RollbarInfrastructure sharedInstance].logger log:RollbarLevel_Critical @@ -76,6 +84,8 @@ - (void)test2_Basics { ]; [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; BOOL wasLogged = NO; for (NSString *item in items) { @@ -86,22 +96,28 @@ - (void)test2_Basics { } XCTAssertTrue(YES == wasLogged); - [RollbarLogger clearSdkDataStore]; - items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + [RollbarTestUtil deletePayloadsStoreFile]; + [RollbarTestUtil deleteLogFiles]; + + items = [RollbarTestUtil readIncomingPayloadsAsStrings]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); } - (void)test3_Live { - [RollbarLogger clearSdkDataStore]; - NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + [RollbarTestUtil deleteLogFiles]; + [RollbarTestUtil deletePayloadsStoreFile]; + [RollbarTestUtil clearTelemetryFile]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + + NSArray *items = [RollbarTestUtil readIncomingPayloadsAsStrings]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); @@ -109,11 +125,16 @@ - (void)test3_Live { [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] environment:[RollbarTestHelper getRollbarEnvironment]]; config.developerOptions.transmit = YES; + config.developerOptions.logIncomingPayloads = YES; config.developerOptions.logTransmittedPayloads = YES; + config.developerOptions.logDroppedPayloads = YES; [[RollbarInfrastructure sharedInstance] configureWith:config]; [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + items = [RollbarTestUtil readIncomingPayloadsAsStrings]; + XCTAssertNotNil(items); items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; XCTAssertNotNil(items); @@ -123,6 +144,8 @@ - (void)test3_Live { context:nil ]; [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; BOOL wasLogged = NO; for (NSString *item in items) { @@ -133,11 +156,13 @@ - (void)test3_Live { } XCTAssertTrue(YES == wasLogged); - [RollbarLogger clearSdkDataStore]; - items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + [RollbarTestUtil deletePayloadsStoreFile]; + [RollbarTestUtil deleteLogFiles]; + + items = [RollbarTestUtil readIncomingPayloadsAsStrings]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); - items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + items = [RollbarTestUtil readTransmittedPayloadsAsStrings]; XCTAssertNotNil(items); XCTAssertEqual(0, items.count); } From 5dec608bc3751c41761381d8ff57eddb0b5b8193 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 31 Aug 2022 21:14:15 -0700 Subject: [PATCH 117/127] test: refactored RollbarTelemetryTests --- .../RollbarTelemetryTests.m | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m index 994facd7..a7222967 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTelemetryTests.m @@ -16,12 +16,23 @@ - (void)setUp { [super setUp]; - [RollbarLogger clearSdkDataStore]; - + [RollbarTestUtil deletePayloadsStoreFile]; + [RollbarTestUtil deleteLogFiles]; + [RollbarTestUtil clearTelemetryFile]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + RollbarMutableConfig *config = [RollbarMutableConfig mutableConfigWithAccessToken:[RollbarTestHelper getRollbarPayloadsAccessToken] environment:[RollbarTestHelper getRollbarEnvironment]]; + config.developerOptions.transmit = NO; + config.developerOptions.logIncomingPayloads = YES; + config.developerOptions.logTransmittedPayloads = YES; + config.developerOptions.logDroppedPayloads = YES; + config.loggingOptions.maximumReportsPerMinute = 180; [Rollbar updateWithConfiguration:config]; + + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + [RollbarTestUtil deleteLogFiles]; } - (void)tearDown { @@ -44,8 +55,9 @@ - (void)testTelemetryCapture { [Rollbar debugMessage:@"Test"]; [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + NSArray *logItems = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; NSDictionary *item = logItems[logItems.count - 1]; NSArray *telemetryData = [item valueForKeyPath:@"body.telemetry"]; XCTAssertTrue(telemetryData.count > 0); @@ -96,9 +108,10 @@ - (void)testErrorReportingWithTelemetry { [Rollbar debugMessage:@"Demonstrate Telemetry capture once more..."]; [Rollbar debugMessage:@"DO Demonstrate Telemetry capture once more..."]; - //[NSThread sleepForTimeInterval:8.0f]; - - NSArray *logItems = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + + NSArray *logItems = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; for (NSDictionary *item in logItems) { NSArray *telemetryData = [item valueForKeyPath:@"body.telemetry"]; From 7152f0ffb68863d0186cfcea76283918b36a461d Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 31 Aug 2022 22:20:49 -0700 Subject: [PATCH 118/127] refactor: RollbarThread --- RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m index aa9d9ce9..8b7f329b 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m +++ b/RollbarNotifier/Sources/RollbarNotifier/RollbarThread.m @@ -463,9 +463,11 @@ - (void)processSavedPayload:(nonnull NSDictionary *)payl NSAssert(destinationKey && destinationKey.length > 0, @"destination_key is expected to be defined!"); NSDictionary *destination = [self->_payloadsRepo getDestinationByID:destinationKey]; - //TODO: remove this before the upcoming major release: + //TODO: remove this code-block before the upcoming major release: if (!destination) { RollbarSdkLog(@"Aha!"); + [self->_payloadsRepo removePayloadByID:payloadDataRow[@"id"]]; + return; } NSAssert(destination, @"destination can not be nil!"); From d086e875a742b0f4f25b47b7e8b50bce09af612e Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 31 Aug 2022 22:21:25 -0700 Subject: [PATCH 119/127] test: refactored RollbarTests --- .../RollbarNotifierTests-ObjC/RollbarTests.m | 35 ++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m index ca242466..8f9c1cc2 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m +++ b/RollbarNotifier/Tests/RollbarNotifierTests-ObjC/RollbarTests.m @@ -16,25 +16,41 @@ - (void)setUp { [super setUp]; - [RollbarLogger clearSdkDataStore]; + [RollbarTestUtil deletePayloadsStoreFile]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; RollbarMutableConfig *config = [[RollbarMutableConfig alloc] init]; config.destination.accessToken = [RollbarTestHelper getRollbarPayloadsAccessToken]; config.destination.environment = [RollbarTestHelper getRollbarEnvironment]; config.developerOptions.transmit = YES; + config.developerOptions.logIncomingPayloads = YES; config.developerOptions.logTransmittedPayloads = YES; + config.developerOptions.logDroppedPayloads = YES; config.loggingOptions.maximumReportsPerMinute = 5000; + config.telemetry.memoryStatsAutocollectionInterval = 0; // for the stress test specifically: config.telemetry.enabled = YES; config.loggingOptions.captureIp = RollbarCaptureIpType_Full; NSLog(@"%@", config) [Rollbar initWithConfiguration:config]; + + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:2]; + [RollbarTestUtil deleteLogFiles]; + [RollbarTestUtil waitWithWaitTimeInSeconds:1]; + + NSArray *items = [RollbarTestUtil readIncomingPayloadsAsDictionaries]; + XCTAssertEqual(items.count, 0); + items = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; + XCTAssertEqual(items.count, 0); + items = [RollbarTestUtil readDroppedPayloadsAsDictionaries]; + XCTAssertEqual(items.count, 0); } - (void)tearDown { - [Rollbar updateWithConfiguration:[RollbarConfig new]]; [super tearDown]; } @@ -142,10 +158,19 @@ - (void)testRollbarTransmit { count--; } + + //TODO: this test will need asserts added based on content of the local log files... } - (void)testNotification { +// [RollbarLogger flushRollbarThread]; +// [RollbarTestUtil waitWithWaitTimeInSeconds:1]; +// [RollbarTestUtil deleteLogFiles]; +// NSArray *items = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; +// XCTAssertEqual(items.count, 0); + //[RollbarTestUtil waitWithWaitTimeInSeconds:1]; + NSDictionary *notificationText = @{ @"error": @[@"testing-error-with-message"], @"debug": @[@"testing-debug"], @@ -166,9 +191,11 @@ - (void)testNotification { } } - [NSThread sleepForTimeInterval:3.0f]; + [RollbarLogger flushRollbarThread]; + [RollbarTestUtil waitWithWaitTimeInSeconds:2]; - NSArray *items = [RollbarLogger readPayloadsFromSdkTransmittedLog]; + NSArray *items = [RollbarTestUtil readTransmittedPayloadsAsDictionaries]; + XCTAssertEqual(items.count, notificationText.count); for (id item in items) { NSString *level = [item valueForKeyPath:@"level"]; NSString *message = [item valueForKeyPath:@"body.message.body"]; From ababe2e3211426e69a366585b4adf7e863afff47 Mon Sep 17 00:00:00 2001 From: Andrey Kornich Date: Wed, 31 Aug 2022 22:22:09 -0700 Subject: [PATCH 120/127] test: refactored RollbarNotifierLoggerTests --- .../RollbarNotifierLoggerTests.swift | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift index 0d469e8b..621d683e 100644 --- a/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift +++ b/RollbarNotifier/Tests/RollbarNotifierTests/RollbarNotifierLoggerTests.swift @@ -26,12 +26,21 @@ final class RollbarNotifierLoggerTests: XCTestCase { config.customData = ["someKey": "someValue", ]; Rollbar.initWithConfiguration(config); + + RollbarTestUtil.wait(waitTimeInSeconds: 1); + RollbarLogger.flushRollbarThread(); + RollbarTestUtil.deleteLogFiles(); + RollbarTestUtil.wait(waitTimeInSeconds: 1); + + XCTAssertEqual(0, RollbarTestUtil.readIncomingPayloadsAsStrings().count); + XCTAssertEqual(0, RollbarTestUtil.readTransmittedPayloadsAsStrings().count); + XCTAssertEqual(0, RollbarTestUtil.readDroppedPayloadsAsStrings().count); } override func tearDown() { - // add custom tear down code... - + RollbarTestUtil.wait(waitTimeInSeconds: 1); + super.tearDown(); } @@ -41,9 +50,6 @@ final class RollbarNotifierLoggerTests: XCTestCase { func testRollbarNotifiersIndependentConfiguration() { - //RollbarTestUtil.clearLogFile(); - //RollbarTestUtil.clearTelemetryFile(); - var config = Rollbar.configuration().mutableCopy(); config.developerOptions.transmit = false; config.developerOptions.logIncomingPayloads = true; From e79aa99420e484e6e8f10935f68d06048d05106a Mon Sep 17 00:00:00 2001 From: Matias Pequeno Date: Tue, 29 Nov 2022 13:47:50 +0100 Subject: [PATCH 121/127] New iOS ObjC Demo with UI and more usage examples. --- .../iosAppObjC.xcodeproj/project.pbxproj | 48 +++++-- Demos/iosAppObjC/iosAppObjC/AppDelegate.h | 10 +- Demos/iosAppObjC/iosAppObjC/AppDelegate.m | 98 ++----------- .../iosAppObjC/Base.lproj/Main.storyboard | 136 +++++++++++++++++- Demos/iosAppObjC/iosAppObjC/Info.plist | 41 ------ Demos/iosAppObjC/iosAppObjC/SceneDelegate.h | 11 +- Demos/iosAppObjC/iosAppObjC/SceneDelegate.m | 54 ------- Demos/iosAppObjC/iosAppObjC/ViewController.h | 11 +- Demos/iosAppObjC/iosAppObjC/ViewController.m | 78 ++++++++-- Demos/iosAppObjC/iosAppObjC/main.m | 11 +- 10 files changed, 251 insertions(+), 247 deletions(-) diff --git a/Demos/iosAppObjC/iosAppObjC.xcodeproj/project.pbxproj b/Demos/iosAppObjC/iosAppObjC.xcodeproj/project.pbxproj index f1d417ec..9df839d1 100644 --- a/Demos/iosAppObjC/iosAppObjC.xcodeproj/project.pbxproj +++ b/Demos/iosAppObjC/iosAppObjC.xcodeproj/project.pbxproj @@ -7,9 +7,9 @@ objects = { /* Begin PBXBuildFile section */ + 3BDB825A292D67900093AC9D /* SceneDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 3BDB8258292D67900093AC9D /* SceneDelegate.m */; }; 5533980A2627F4670031D02C /* RollbarPLCrashReporter in Frameworks */ = {isa = PBXBuildFile; productRef = 553398092627F4670031D02C /* RollbarPLCrashReporter */; }; 55684F702553B4C400F82F34 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 55684F6F2553B4C400F82F34 /* AppDelegate.m */; }; - 55684F732553B4C400F82F34 /* SceneDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 55684F722553B4C400F82F34 /* SceneDelegate.m */; }; 55684F762553B4C400F82F34 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 55684F752553B4C400F82F34 /* ViewController.m */; }; 55684F792553B4C400F82F34 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 55684F772553B4C400F82F34 /* Main.storyboard */; }; 55684F7B2553B4C700F82F34 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 55684F7A2553B4C700F82F34 /* Assets.xcassets */; }; @@ -22,21 +22,20 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 3BDB8258292D67900093AC9D /* SceneDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SceneDelegate.m; sourceTree = ""; }; + 3BDB8259292D67900093AC9D /* SceneDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SceneDelegate.h; sourceTree = ""; }; + 3BDB825B292E34990093AC9D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = ""; }; 55684F6B2553B4C400F82F34 /* iosAppObjC.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iosAppObjC.app; sourceTree = BUILT_PRODUCTS_DIR; }; 55684F6E2553B4C400F82F34 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 55684F6F2553B4C400F82F34 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - 55684F712553B4C400F82F34 /* SceneDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SceneDelegate.h; sourceTree = ""; }; - 55684F722553B4C400F82F34 /* SceneDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SceneDelegate.m; sourceTree = ""; }; 55684F742553B4C400F82F34 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; 55684F752553B4C400F82F34 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 55684F782553B4C400F82F34 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 55684F7A2553B4C700F82F34 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 55684F7D2553B4C700F82F34 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 55684F7F2553B4C700F82F34 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 55684F802553B4C700F82F34 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 55684F9B2553BD1B00F82F34 /* iosAppObjC.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = iosAppObjC.entitlements; sourceTree = ""; }; 55684F9C2553BD1C00F82F34 /* NetworkExtension.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = NetworkExtension.framework; path = System/Library/Frameworks/NetworkExtension.framework; sourceTree = SDKROOT; }; - 55C1B42127C5C95000017B22 /* RollbarDemoSettings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RollbarDemoSettings.h; path = ../../RollbarDemoSettings.h; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -75,18 +74,17 @@ 55684F6D2553B4C400F82F34 /* iosAppObjC */ = { isa = PBXGroup; children = ( - 55C1B42127C5C95000017B22 /* RollbarDemoSettings.h */, + 3BDB825B292E34990093AC9D /* Info.plist */, 55684F9B2553BD1B00F82F34 /* iosAppObjC.entitlements */, 55684F6E2553B4C400F82F34 /* AppDelegate.h */, 55684F6F2553B4C400F82F34 /* AppDelegate.m */, - 55684F712553B4C400F82F34 /* SceneDelegate.h */, - 55684F722553B4C400F82F34 /* SceneDelegate.m */, + 3BDB8259292D67900093AC9D /* SceneDelegate.h */, + 3BDB8258292D67900093AC9D /* SceneDelegate.m */, 55684F742553B4C400F82F34 /* ViewController.h */, 55684F752553B4C400F82F34 /* ViewController.m */, 55684F772553B4C400F82F34 /* Main.storyboard */, 55684F7A2553B4C700F82F34 /* Assets.xcassets */, 55684F7C2553B4C700F82F34 /* LaunchScreen.storyboard */, - 55684F7F2553B4C700F82F34 /* Info.plist */, 55684F802553B4C700F82F34 /* main.m */, ); path = iosAppObjC; @@ -178,7 +176,7 @@ 55684F762553B4C400F82F34 /* ViewController.m in Sources */, 55684F702553B4C400F82F34 /* AppDelegate.m in Sources */, 55684F812553B4C700F82F34 /* main.m in Sources */, - 55684F732553B4C400F82F34 /* SceneDelegate.m in Sources */, + 3BDB825A292D67900093AC9D /* SceneDelegate.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -238,7 +236,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu11; @@ -255,10 +253,12 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.1; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; + PRODUCT_BUNDLE_IDENTIFIER = com.rollbar.iosAppObjC; SDKROOT = iphoneos; }; name = Debug; @@ -308,9 +308,11 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.1; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = com.rollbar.iosAppObjC; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; }; @@ -324,12 +326,20 @@ CODE_SIGN_ENTITLEMENTS = iosAppObjC/iosAppObjC.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = LDX6L68VZJ; + CURRENT_PROJECT_VERSION = 3; + DEVELOPMENT_TEAM = 6B5NER795L; INFOPLIST_FILE = iosAppObjC/Info.plist; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; + INFOPLIST_KEY_UIMainStoryboardFile = Main; + INFOPLIST_KEY_UIRequiredDeviceCapabilities = armv7; + INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); + MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.rollbar.iosAppObjC; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; @@ -345,12 +355,20 @@ CODE_SIGN_ENTITLEMENTS = iosAppObjC/iosAppObjC.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = LDX6L68VZJ; + CURRENT_PROJECT_VERSION = 3; + DEVELOPMENT_TEAM = 6B5NER795L; INFOPLIST_FILE = iosAppObjC/Info.plist; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; + INFOPLIST_KEY_UIMainStoryboardFile = Main; + INFOPLIST_KEY_UIRequiredDeviceCapabilities = armv7; + INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); + MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.rollbar.iosAppObjC; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; diff --git a/Demos/iosAppObjC/iosAppObjC/AppDelegate.h b/Demos/iosAppObjC/iosAppObjC/AppDelegate.h index 72c98f50..3254d7a6 100644 --- a/Demos/iosAppObjC/iosAppObjC/AppDelegate.h +++ b/Demos/iosAppObjC/iosAppObjC/AppDelegate.h @@ -1,14 +1,6 @@ -// -// AppDelegate.h -// iosAppObjC -// -// Created by Andrey Kornich on 2020-11-04. -// - -#import +@import UIKit; @interface AppDelegate : UIResponder - @end diff --git a/Demos/iosAppObjC/iosAppObjC/AppDelegate.m b/Demos/iosAppObjC/iosAppObjC/AppDelegate.m index a34113ed..922b27d7 100644 --- a/Demos/iosAppObjC/iosAppObjC/AppDelegate.m +++ b/Demos/iosAppObjC/iosAppObjC/AppDelegate.m @@ -1,12 +1,4 @@ -// -// AppDelegate.m -// iosAppObjC -// -// Created by Andrey Kornich on 2020-11-04. -// - #import "AppDelegate.h" -#import "RollbarDemoSettings.h" @import RollbarNotifier; @import RollbarKSCrash; @@ -14,98 +6,36 @@ @implementation AppDelegate - - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. - [self initRollbar]; - - NSData *data = [[NSData alloc] init]; - NSError *error; - NSJSONReadingOptions serializationOptions = (NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves); - NSDictionary *payload = [NSJSONSerialization JSONObjectWithData:data - options:serializationOptions - error:&error]; - if (!payload && error) { - [Rollbar log:RollbarLevel_Error - error:error - data:nil - context:nil - ]; - } + RollbarMutableConfig *config = [RollbarConfig mutableConfigWithAccessToken:@"dc0d9ce3d93c4ef5a4dbacf2434e508d" + environment:@"staging"]; + config.loggingOptions.codeVersion = @"main"; + config.developerOptions.suppressSdkInfoLogging = NO; + config.telemetry.memoryStatsAutocollectionInterval = 0.5; + config.telemetry.enabled = YES; - @try { - [self callTroublemaker]; - } @catch (NSException *exception) { - [Rollbar errorException:exception data:nil context:@"from @try-@catch"]; - } @finally { - [Rollbar infoMessage:@"Post-trouble notification!" data:nil context:@"from @try-@finally"]; - } - + //id crashCollector = [[RollbarKSCrashCollector alloc] init]; + id crashCollector = [[RollbarPLCrashCollector alloc] init]; - // now, cause a crash: - // [self callTroublemaker]; - - //@throw NSInternalInconsistencyException; - - // [self performSelector:@selector(die_die)]; - // [self performSelector:NSSelectorFromString(@"crashme:") withObject:nil afterDelay:10]; + [Rollbar initWithConfiguration:config + crashCollector:crashCollector]; + + [Rollbar infoMessage:@"Rollbar is up and running! Enjoy your remote error and log monitoring..."]; return YES; } - #pragma mark - UISceneSession lifecycle - - (UISceneConfiguration *) application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. - return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role]; -} - - -- (void) application:(UIApplication *)application -didDiscardSceneSessions:(NSSet *)sceneSessions { - // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" + sessionRole:connectingSceneSession.role]; } -- (void)initRollbar { - - // configure Rollbar: - RollbarConfig *config = [RollbarConfig new]; - - config.destination.accessToken = ROLLBAR_DEMO_PAYLOADS_ACCESS_TOKEN; - config.destination.environment = ROLLBAR_DEMO_ENVIRONMENT; - config.developerOptions.suppressSdkInfoLogging = YES; - config.telemetry.memoryStatsAutocollectionInterval = 0.5; - config.telemetry.enabled = YES; - - // init Rollbar shared instance: - //id crashCollector = [[RollbarKSCrashCollector alloc] init]; - id crashCollector = [[RollbarPLCrashCollector alloc] init]; - - [Rollbar initWithConfiguration:config crashCollector:crashCollector]; - - [Rollbar infoMessage:@"Rollbar is up and running! Enjoy your remote error and log monitoring..."]; -} - -- (void)callTroublemaker { - NSArray *items = @[@"one", @"two", @"three"]; - NSLog(@"Here is the trouble-item: %@", items[10]); -} - - //- (void)demonstrateDeployApiUsage { - // - // RollbarDeploysDemoClient * rollbarDeploysIntro = [[RollbarDeploysDemoClient new] init]; - // [rollbarDeploysIntro demoDeploymentRegistration]; - // [rollbarDeploysIntro demoGetDeploymentDetailsById]; - // [rollbarDeploysIntro demoGetDeploymentsPage]; - //} - - @end diff --git a/Demos/iosAppObjC/iosAppObjC/Base.lproj/Main.storyboard b/Demos/iosAppObjC/iosAppObjC/Base.lproj/Main.storyboard index 808a21ce..b5848e50 100644 --- a/Demos/iosAppObjC/iosAppObjC/Base.lproj/Main.storyboard +++ b/Demos/iosAppObjC/iosAppObjC/Base.lproj/Main.storyboard @@ -1,24 +1,150 @@ - + + - + + + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demos/iosAppObjC/iosAppObjC/Info.plist b/Demos/iosAppObjC/iosAppObjC/Info.plist index 72bf2c4f..81ed29b7 100644 --- a/Demos/iosAppObjC/iosAppObjC/Info.plist +++ b/Demos/iosAppObjC/iosAppObjC/Info.plist @@ -2,24 +2,6 @@ - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - LSRequiresIPhoneOS - UIApplicationSceneManifest UIApplicationSupportsMultipleScenes @@ -39,28 +21,5 @@ - UIApplicationSupportsIndirectInputEvents - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UIRequiredDeviceCapabilities - - armv7 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - diff --git a/Demos/iosAppObjC/iosAppObjC/SceneDelegate.h b/Demos/iosAppObjC/iosAppObjC/SceneDelegate.h index 1ee2ecf0..b18ed508 100644 --- a/Demos/iosAppObjC/iosAppObjC/SceneDelegate.h +++ b/Demos/iosAppObjC/iosAppObjC/SceneDelegate.h @@ -1,15 +1,8 @@ -// -// SceneDelegate.h -// iosAppObjC -// -// Created by Andrey Kornich on 2020-11-04. -// - -#import +@import UIKit; @interface SceneDelegate : UIResponder -@property (strong, nonatomic) UIWindow * window; +@property (strong, nonatomic) UIWindow *window; @end diff --git a/Demos/iosAppObjC/iosAppObjC/SceneDelegate.m b/Demos/iosAppObjC/iosAppObjC/SceneDelegate.m index 35cbd6aa..3ac0ce3d 100644 --- a/Demos/iosAppObjC/iosAppObjC/SceneDelegate.m +++ b/Demos/iosAppObjC/iosAppObjC/SceneDelegate.m @@ -1,59 +1,5 @@ -// -// SceneDelegate.m -// iosAppObjC -// -// Created by Andrey Kornich on 2020-11-04. -// - #import "SceneDelegate.h" -@interface SceneDelegate () - -@end - @implementation SceneDelegate - -- (void) scene:(UIScene *)scene - willConnectToSession:(UISceneSession *)session - options:(UISceneConnectionOptions *)connectionOptions { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). -} - - -- (void)sceneDidDisconnect:(UIScene *)scene { - // Called as the scene is being released by the system. - // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). -} - - -- (void)sceneDidBecomeActive:(UIScene *)scene { - // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. -} - - -- (void)sceneWillResignActive:(UIScene *)scene { - // Called when the scene will move from an active state to an inactive state. - // This may occur due to temporary interruptions (ex. an incoming phone call). -} - - -- (void)sceneWillEnterForeground:(UIScene *)scene { - // Called as the scene transitions from the background to the foreground. - // Use this method to undo the changes made on entering the background. -} - - -- (void)sceneDidEnterBackground:(UIScene *)scene { - // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information - // to restore the scene back to its current state. -} - - @end diff --git a/Demos/iosAppObjC/iosAppObjC/ViewController.h b/Demos/iosAppObjC/iosAppObjC/ViewController.h index a9acdcb2..29e7ff1c 100644 --- a/Demos/iosAppObjC/iosAppObjC/ViewController.h +++ b/Demos/iosAppObjC/iosAppObjC/ViewController.h @@ -1,14 +1,5 @@ -// -// ViewController.h -// iosAppObjC -// -// Created by Andrey Kornich on 2020-11-04. -// - -#import +@import UIKit; @interface ViewController : UIViewController - @end - diff --git a/Demos/iosAppObjC/iosAppObjC/ViewController.m b/Demos/iosAppObjC/iosAppObjC/ViewController.m index d3d964b1..c249fe19 100644 --- a/Demos/iosAppObjC/iosAppObjC/ViewController.m +++ b/Demos/iosAppObjC/iosAppObjC/ViewController.m @@ -1,22 +1,76 @@ -// -// ViewController.m -// iosAppObjC -// -// Created by Andrey Kornich on 2020-11-04. -// +@import RollbarNotifier; #import "ViewController.h" -@interface ViewController () +@implementation ViewController -@end +- (IBAction)interrupt:(UIButton *)sender { + raise(SIGINT); +} -@implementation ViewController +- (IBAction)trap:(UIButton *)sender { + raise(SIGTRAP); +} + +- (IBAction)abort:(UIButton *)sender { + abort(); // SIGABRT +} + +- (IBAction)exit:(UIButton *)sender { + exit(1); +} -- (void)viewDidLoad { - [super viewDidLoad]; - // Do any additional setup after loading the view. +- (IBAction)assert:(UIButton *)sender { + assert(NO); } +- (IBAction)nsassert:(UIButton *)sender { + NSAssert(NO, @"whoops"); +} + +- (IBAction)throw:(UIButton *)sender { + @throw NSInternalInconsistencyException; +} + +- (IBAction)divideByZero:(UIButton *)sender { + //int i = 1 / 0; + __unused div_t i = div(1, 0); +} + +- (IBAction)null:(UIButton *)sender { + ((char *)NULL)[1] = 0; +} + +- (IBAction)tryCatchFinally:(UIButton *)sender { + @try { + NSArray *items = @[@"one", @"two", @"three"]; + __unused NSString *item = items[4]; + } @catch (NSException *exception) { + [Rollbar errorException:exception + data:nil + context:@"from @try-@catch"]; + } @finally { + [Rollbar infoMessage:@"Finally notification" + data:nil + context:@"from @try-@finally"]; + } +} + +- (IBAction)performAbsurdSelector:(UIButton *)sender { + [self performSelector:@selector(absurd)]; +} + +- (IBAction)invalidJson:(UIButton *)sender { + NSError *error; + __unused NSDictionary *payload = + [NSJSONSerialization JSONObjectWithData:[[NSData alloc] init] + options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves + error:&error]; + + [Rollbar log:RollbarLevel_Error + error:error + data:nil + context:@"While trying to serialize data."]; +} @end diff --git a/Demos/iosAppObjC/iosAppObjC/main.m b/Demos/iosAppObjC/iosAppObjC/main.m index 81d6a600..90ce0c45 100644 --- a/Demos/iosAppObjC/iosAppObjC/main.m +++ b/Demos/iosAppObjC/iosAppObjC/main.m @@ -1,18 +1,13 @@ -// -// main.m -// iosAppObjC -// -// Created by Andrey Kornich on 2020-11-04. -// - #import #import "AppDelegate.h" int main(int argc, char * argv[]) { - NSString * appDelegateClassName; + NSString *appDelegateClassName; + @autoreleasepool { // Setup code that might create autoreleased objects goes here. appDelegateClassName = NSStringFromClass([AppDelegate class]); } + return UIApplicationMain(argc, argv, nil, appDelegateClassName); } From 10a56d282befb0e39afa45b4a6a0689c3fc3a0b0 Mon Sep 17 00:00:00 2001 From: Matias Pequeno Date: Tue, 29 Nov 2022 13:54:59 +0100 Subject: [PATCH 122/127] Created iOS Swift Demo with UI. --- .../iosAppSwift.xcodeproj/project.pbxproj | 395 ++++++++++++++++++ .../xcschemes/iosAppSwift.xcscheme | 78 ++++ .../AccentColor.colorset/Contents.json | 11 + .../AppIcon.appiconset/Contents.json | 13 + .../iosAppSwift/Assets.xcassets/Contents.json | 6 + .../iosAppSwift/iosAppSwift/ContentView.swift | 134 ++++++ .../Preview Assets.xcassets/Contents.json | 6 + .../iosAppSwift/iosAppSwiftApp.swift | 101 +++++ .../contents.xcworkspacedata | 3 + 9 files changed, 747 insertions(+) create mode 100644 Demos/iosAppSwift/iosAppSwift.xcodeproj/project.pbxproj create mode 100644 Demos/iosAppSwift/iosAppSwift.xcodeproj/xcshareddata/xcschemes/iosAppSwift.xcscheme create mode 100644 Demos/iosAppSwift/iosAppSwift/Assets.xcassets/AccentColor.colorset/Contents.json create mode 100644 Demos/iosAppSwift/iosAppSwift/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 Demos/iosAppSwift/iosAppSwift/Assets.xcassets/Contents.json create mode 100644 Demos/iosAppSwift/iosAppSwift/ContentView.swift create mode 100644 Demos/iosAppSwift/iosAppSwift/Preview Content/Preview Assets.xcassets/Contents.json create mode 100644 Demos/iosAppSwift/iosAppSwift/iosAppSwiftApp.swift diff --git a/Demos/iosAppSwift/iosAppSwift.xcodeproj/project.pbxproj b/Demos/iosAppSwift/iosAppSwift.xcodeproj/project.pbxproj new file mode 100644 index 00000000..af6422c8 --- /dev/null +++ b/Demos/iosAppSwift/iosAppSwift.xcodeproj/project.pbxproj @@ -0,0 +1,395 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + 3BDB8240292D2DCE0093AC9D /* iosAppSwiftApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BDB823F292D2DCE0093AC9D /* iosAppSwiftApp.swift */; }; + 3BDB8242292D2DCE0093AC9D /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BDB8241292D2DCE0093AC9D /* ContentView.swift */; }; + 3BDB8244292D2DCF0093AC9D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3BDB8243292D2DCF0093AC9D /* Assets.xcassets */; }; + 3BDB8247292D2DCF0093AC9D /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3BDB8246292D2DCF0093AC9D /* Preview Assets.xcassets */; }; + 3BDB824F292D2E4B0093AC9D /* RollbarAUL in Frameworks */ = {isa = PBXBuildFile; productRef = 3BDB824E292D2E4B0093AC9D /* RollbarAUL */; }; + 3BDB8251292D2E4B0093AC9D /* RollbarCommon in Frameworks */ = {isa = PBXBuildFile; productRef = 3BDB8250292D2E4B0093AC9D /* RollbarCommon */; }; + 3BDB8253292D2E4B0093AC9D /* RollbarNotifier in Frameworks */ = {isa = PBXBuildFile; productRef = 3BDB8252292D2E4B0093AC9D /* RollbarNotifier */; }; + 3BDB8255292D2E4B0093AC9D /* RollbarPLCrashReporter in Frameworks */ = {isa = PBXBuildFile; productRef = 3BDB8254292D2E4B0093AC9D /* RollbarPLCrashReporter */; }; + 3BDB8257292D2E4B0093AC9D /* RollbarSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 3BDB8256292D2E4B0093AC9D /* RollbarSwift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 3BDB823C292D2DCE0093AC9D /* iosAppSwift.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iosAppSwift.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 3BDB823F292D2DCE0093AC9D /* iosAppSwiftApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iosAppSwiftApp.swift; sourceTree = ""; }; + 3BDB8241292D2DCE0093AC9D /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + 3BDB8243292D2DCF0093AC9D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 3BDB8246292D2DCF0093AC9D /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 3BDB8239292D2DCE0093AC9D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 3BDB8255292D2E4B0093AC9D /* RollbarPLCrashReporter in Frameworks */, + 3BDB8253292D2E4B0093AC9D /* RollbarNotifier in Frameworks */, + 3BDB8257292D2E4B0093AC9D /* RollbarSwift in Frameworks */, + 3BDB8251292D2E4B0093AC9D /* RollbarCommon in Frameworks */, + 3BDB824F292D2E4B0093AC9D /* RollbarAUL in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 3BDB8233292D2DCE0093AC9D = { + isa = PBXGroup; + children = ( + 3BDB823E292D2DCE0093AC9D /* iosAppSwift */, + 3BDB823D292D2DCE0093AC9D /* Products */, + 3BDB824D292D2E4B0093AC9D /* Frameworks */, + ); + sourceTree = ""; + }; + 3BDB823D292D2DCE0093AC9D /* Products */ = { + isa = PBXGroup; + children = ( + 3BDB823C292D2DCE0093AC9D /* iosAppSwift.app */, + ); + name = Products; + sourceTree = ""; + }; + 3BDB823E292D2DCE0093AC9D /* iosAppSwift */ = { + isa = PBXGroup; + children = ( + 3BDB823F292D2DCE0093AC9D /* iosAppSwiftApp.swift */, + 3BDB8241292D2DCE0093AC9D /* ContentView.swift */, + 3BDB8243292D2DCF0093AC9D /* Assets.xcassets */, + 3BDB8245292D2DCF0093AC9D /* Preview Content */, + ); + path = iosAppSwift; + sourceTree = ""; + }; + 3BDB8245292D2DCF0093AC9D /* Preview Content */ = { + isa = PBXGroup; + children = ( + 3BDB8246292D2DCF0093AC9D /* Preview Assets.xcassets */, + ); + path = "Preview Content"; + sourceTree = ""; + }; + 3BDB824D292D2E4B0093AC9D /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 3BDB823B292D2DCE0093AC9D /* iosAppSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3BDB824A292D2DCF0093AC9D /* Build configuration list for PBXNativeTarget "iosAppSwift" */; + buildPhases = ( + 3BDB8238292D2DCE0093AC9D /* Sources */, + 3BDB8239292D2DCE0093AC9D /* Frameworks */, + 3BDB823A292D2DCE0093AC9D /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = iosAppSwift; + packageProductDependencies = ( + 3BDB824E292D2E4B0093AC9D /* RollbarAUL */, + 3BDB8250292D2E4B0093AC9D /* RollbarCommon */, + 3BDB8252292D2E4B0093AC9D /* RollbarNotifier */, + 3BDB8254292D2E4B0093AC9D /* RollbarPLCrashReporter */, + 3BDB8256292D2E4B0093AC9D /* RollbarSwift */, + ); + productName = iosAppSwift; + productReference = 3BDB823C292D2DCE0093AC9D /* iosAppSwift.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 3BDB8234292D2DCE0093AC9D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1410; + LastUpgradeCheck = 1410; + TargetAttributes = { + 3BDB823B292D2DCE0093AC9D = { + CreatedOnToolsVersion = 14.1; + }; + }; + }; + buildConfigurationList = 3BDB8237292D2DCE0093AC9D /* Build configuration list for PBXProject "iosAppSwift" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 3BDB8233292D2DCE0093AC9D; + productRefGroup = 3BDB823D292D2DCE0093AC9D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 3BDB823B292D2DCE0093AC9D /* iosAppSwift */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 3BDB823A292D2DCE0093AC9D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3BDB8247292D2DCF0093AC9D /* Preview Assets.xcassets in Resources */, + 3BDB8244292D2DCF0093AC9D /* Assets.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 3BDB8238292D2DCE0093AC9D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3BDB8242292D2DCE0093AC9D /* ContentView.swift in Sources */, + 3BDB8240292D2DCE0093AC9D /* iosAppSwiftApp.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 3BDB8248292D2DCF0093AC9D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 3BDB8249292D2DCF0093AC9D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 3BDB824B292D2DCF0093AC9D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 3; + DEVELOPMENT_ASSET_PATHS = "\"iosAppSwift/Preview Content\""; + DEVELOPMENT_TEAM = 6B5NER795L; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_CFBundleDisplayName = "Rollbar Demo"; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.matux.test.rollbarAppDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 3BDB824C292D2DCF0093AC9D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 3; + DEVELOPMENT_ASSET_PATHS = "\"iosAppSwift/Preview Content\""; + DEVELOPMENT_TEAM = 6B5NER795L; + ENABLE_PREVIEWS = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = NO; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_CFBundleDisplayName = "Rollbar Demo"; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.matux.test.rollbarAppDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 3BDB8237292D2DCE0093AC9D /* Build configuration list for PBXProject "iosAppSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 3BDB8248292D2DCF0093AC9D /* Debug */, + 3BDB8249292D2DCF0093AC9D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 3BDB824A292D2DCF0093AC9D /* Build configuration list for PBXNativeTarget "iosAppSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 3BDB824B292D2DCF0093AC9D /* Debug */, + 3BDB824C292D2DCF0093AC9D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + 3BDB824E292D2E4B0093AC9D /* RollbarAUL */ = { + isa = XCSwiftPackageProductDependency; + productName = RollbarAUL; + }; + 3BDB8250292D2E4B0093AC9D /* RollbarCommon */ = { + isa = XCSwiftPackageProductDependency; + productName = RollbarCommon; + }; + 3BDB8252292D2E4B0093AC9D /* RollbarNotifier */ = { + isa = XCSwiftPackageProductDependency; + productName = RollbarNotifier; + }; + 3BDB8254292D2E4B0093AC9D /* RollbarPLCrashReporter */ = { + isa = XCSwiftPackageProductDependency; + productName = RollbarPLCrashReporter; + }; + 3BDB8256292D2E4B0093AC9D /* RollbarSwift */ = { + isa = XCSwiftPackageProductDependency; + productName = RollbarSwift; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 3BDB8234292D2DCE0093AC9D /* Project object */; +} diff --git a/Demos/iosAppSwift/iosAppSwift.xcodeproj/xcshareddata/xcschemes/iosAppSwift.xcscheme b/Demos/iosAppSwift/iosAppSwift.xcodeproj/xcshareddata/xcschemes/iosAppSwift.xcscheme new file mode 100644 index 00000000..cf323e7d --- /dev/null +++ b/Demos/iosAppSwift/iosAppSwift.xcodeproj/xcshareddata/xcschemes/iosAppSwift.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demos/iosAppSwift/iosAppSwift/Assets.xcassets/AccentColor.colorset/Contents.json b/Demos/iosAppSwift/iosAppSwift/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/Demos/iosAppSwift/iosAppSwift/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Demos/iosAppSwift/iosAppSwift/Assets.xcassets/AppIcon.appiconset/Contents.json b/Demos/iosAppSwift/iosAppSwift/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..13613e3e --- /dev/null +++ b/Demos/iosAppSwift/iosAppSwift/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,13 @@ +{ + "images" : [ + { + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Demos/iosAppSwift/iosAppSwift/Assets.xcassets/Contents.json b/Demos/iosAppSwift/iosAppSwift/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/Demos/iosAppSwift/iosAppSwift/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Demos/iosAppSwift/iosAppSwift/ContentView.swift b/Demos/iosAppSwift/iosAppSwift/ContentView.swift new file mode 100644 index 00000000..63bf9659 --- /dev/null +++ b/Demos/iosAppSwift/iosAppSwift/ContentView.swift @@ -0,0 +1,134 @@ +import SwiftUI +import RollbarSwift +import RollbarNotifier + +enum ExampleError: Error { + case + invalidResult, + outOfBounds, + invalidInput +} + +struct ContentView: View { + let example = Example(); + + var body: some View { + VStack { + Text("Rollbar Apple SDK Example") + .font(.title) + .padding(.bottom) + + VStack { + Button("Manual Logging Example", action: example.manualLogging) + .tint(.blue) + .buttonStyle(.bordered) + + Button("Divide by zero") { _ = example.divide(by: 0) } + .tint(.blue) + .buttonStyle(.bordered) + + Button("Log invalid JSON", action: example.logInvalidJson) + .tint(.blue) + .buttonStyle(.bordered) + .padding(.bottom) + + Button("Throw an ExampleError") { try! example.throwError() } + .tint(.blue) + .buttonStyle(.bordered) + + Button("Throw an NSException", action: example.throwNSException) + .tint(.blue) + .buttonStyle(.bordered) + .padding(.bottom) + + Button("Assertion Failure", action: example.forceAssertionFailure) + .tint(.blue) + .buttonStyle(.bordered) + + Button("Precondition Failure", action: example.forcePreconditionFailure) + .tint(.blue) + .buttonStyle(.bordered) + + Button("Fatal Error", action: example.forceFatalError) + .tint(.blue) + .buttonStyle(.bordered) + } + } + .padding() + } +} + +struct ContentView_Previews: PreviewProvider { + static var previews: some View { + ContentView() + } +} + +struct Example { + let logger = RollbarLogger(configuration: Rollbar.configuration()) + + /// Some different ways to explicitly log an error to Rollbar. + func manualLogging() { + let extraInfo = ["item_1": "value_1", "item_2": "value_2"] + + Rollbar.log(.error, message: "My log message") + + Rollbar.log( + .error, + error: ExampleError.invalidInput, + data: extraInfo, + context: "Some additional information.") + + Rollbar.errorMessage("My error message", data: extraInfo) + + Rollbar.errorError(ExampleError.invalidResult, data: extraInfo) + + do { + throw ExampleError.outOfBounds + } catch { + Rollbar.errorError(error, data: extraInfo) + } + } + + /// A hard crash is captured by the crash reporter. The next time + /// the application is started, the data is sent to Rollbar. + func forceFatalError() { + fatalError("Force a crash") + } + + func forcePreconditionFailure() { + preconditionFailure("Precondition failed") + } + + func forceAssertionFailure() { + assertionFailure("Assertion failed") + } + + func divide(by y: Int) -> Int { + 1 / y + } + + func throwError() throws { + throw ExampleError.outOfBounds + } + + func throwNSException() { + RollbarExceptionGuard(logger: logger).tryExecute { + RollbarTryCatch.throw("NSException from ObjC") + } + } + + func logInvalidJson() { + Rollbar.log( + .warning, + message: "Logging with extras and context", + data: [ + "fingerprint": "targeted-mistake-recycling-incorrect-range", + "bestSolutionTokens": [51241, 42421, 32142], + "guessTokens": [22414, 89389], + // This is a (Int, Int), which can't be turned into Json + "detectedRangeStart": (1, 10), + ], + context: "Rollbar Example Logging Invalid Json") + } +} diff --git a/Demos/iosAppSwift/iosAppSwift/Preview Content/Preview Assets.xcassets/Contents.json b/Demos/iosAppSwift/iosAppSwift/Preview Content/Preview Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/Demos/iosAppSwift/iosAppSwift/Preview Content/Preview Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Demos/iosAppSwift/iosAppSwift/iosAppSwiftApp.swift b/Demos/iosAppSwift/iosAppSwift/iosAppSwiftApp.swift new file mode 100644 index 00000000..2816a71a --- /dev/null +++ b/Demos/iosAppSwift/iosAppSwift/iosAppSwiftApp.swift @@ -0,0 +1,101 @@ +import SwiftUI +import RollbarSwift +import RollbarNotifier +import RollbarPLCrashReporter + +@main +struct iosAppSwiftApp: App { + @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate + + var body: some Scene { + WindowGroup { + ContentView() + } + } +} + +class AppDelegate: NSObject, UIApplicationDelegate { + + func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil + ) -> Bool { + // Dynamically read these settings from your config settings on + // application startup. + let accessToken = "2fa95b91f38448299b5097ff11cffb23" // Rollbar post_client_item access token + let environment = "staging" + let codeVersion = "main" // Ideally codeVersion is commit SHA https://docs.rollbar.com/docs/versions + + // Initialize a configuration object and add configuration settings as + // needed. + let config = RollbarConfig.mutableConfig( + withAccessToken: accessToken, + environment: environment) + + config.loggingOptions.codeVersion = codeVersion + + // Optionally anonymize the IP address + //config.loggingOptions.captureIp = RollbarCaptureIpType.anonymize + + // Suppress Rollbar event being logged (e.g. in XCode debug logs) + //config.developerOptions.suppressSdkInfoLogging = true + + config.telemetry.enabled = true + config.telemetry.captureLog = true + config.telemetry.maximumTelemetryData = 10 + + config.modifyRollbarData = Rollbar.transform(payload:) + + // Optionally don't send certain occurrences based on some aspect of + // the payload contents + //config.checkIgnoreRollbarData = Rollbar.shouldIgnore(payload:) + + // List of fields to scrub + // Make sure to test this if you are overriding the default scrub list + //config.dataScrubber.scrubFields = ["accessToken", "cpu", "key_y"] + + // optionally add data about the user to improve error response + config.person.id = "12345" + + // additional custom data to add to every occurrence sent + config.customData = ["customer_type": "enterprise"] + + // Initialize a Rollbar shared instance with a crash collector + Rollbar.initWithConfiguration( + config, + crashCollector: RollbarPLCrashCollector()) + + // Note the ability to add aditional key/value pairs to the occurrence data for extra context + Rollbar.infoMessage( + "Rollbar is up and running! Enjoy your remote error and log monitoring...", + data: ["key_x": "value_x", "key_y": "value_y"]) + + return true + } +} + +extension Rollbar { + /// `return true` means DO NOT send the data to Rollbar (i.e. ignore) + /// `return false` means DO send the data to Rollbar + static func shouldIgnore(payload: RollbarData) -> Bool { + return false + } + + /// Transform the occurrence payload just before the data is sent. + /// + /// This allows data to be added/removed from the payload basd on some + /// aspect of the payload data. + /// + /// This method is often used to do advanced data scrubbing or to add + /// additional data to the payload that is only available at the time + /// the error occurs. + static func transform(payload: RollbarData) -> RollbarData { + // Context is an indexed fast search field in the Rollbar Web UI + // + // The items timeline view can be filtered by context + // https://docs.rollbar.com/docs/search-items#context + payload.context = "owner#ui_team" + + return payload + } +} diff --git a/RollbarSDK.xcworkspace/contents.xcworkspacedata b/RollbarSDK.xcworkspace/contents.xcworkspacedata index 0ab21587..a91fa17c 100644 --- a/RollbarSDK.xcworkspace/contents.xcworkspacedata +++ b/RollbarSDK.xcworkspace/contents.xcworkspacedata @@ -111,6 +111,9 @@ + + From 0942d41d3ca0c5e96182d0f6ba10b882df22fdba Mon Sep 17 00:00:00 2001 From: Matias Pequeno Date: Tue, 29 Nov 2022 13:58:27 +0100 Subject: [PATCH 123/127] Fixed examples that weren't compiling. --- Demos/macosAppObjC/macosAppObjC/AppDelegate.m | 16 +++++++++------- .../macosAppObjC/RollbarDeploysDemoClient.m | 7 +++++-- .../macosAppObjC/ViewController.h | 1 - .../macosAppSwift/ContentView.swift | 19 ++++--------------- Demos/tvosAppObjC/tvosAppObjC/AppDelegate.m | 6 ++---- 5 files changed, 20 insertions(+), 29 deletions(-) diff --git a/Demos/macosAppObjC/macosAppObjC/AppDelegate.m b/Demos/macosAppObjC/macosAppObjC/AppDelegate.m index 91af9330..5dc5500c 100644 --- a/Demos/macosAppObjC/macosAppObjC/AppDelegate.m +++ b/Demos/macosAppObjC/macosAppObjC/AppDelegate.m @@ -7,21 +7,24 @@ // #import "AppDelegate.h" - #import "RollbarDeploysDemoClient.h" -#import "RollbarDemoSettings.h" @import RollbarNotifier; @import RollbarAUL; @import RollbarKSCrash; @import RollbarPLCrashReporter; +static NSString * const ROLLBAR_DEMO_PAYLOADS_ACCESS_TOKEN = @"09da180aba21479e9ed3d91e0b8d58d6"; +static NSString * const ROLLBAR_DEMO_DEPLOYS_WRITE_ACCESS_TOKEN = @"efdc4b85d66045f293a7f9e99c732f61"; +static NSString * const ROLLBAR_DEMO_DEPLOYS_READ_ACCESS_TOKEN = @"595cbf76b05b45f2b3ef661a2e0078d4"; + __attribute__((noinline)) static void crashIt (void) { /* Trigger a crash */ ((char *)NULL)[1] = 0; } @interface AppDelegate () +@property (nonatomic, readonly) RollbarLogger *logger; @end @@ -77,16 +80,15 @@ - (void)applicationWillTerminate:(NSNotification *)aNotification { - (void)initRollbar { // configure Rollbar: - RollbarConfig *config = [RollbarConfig new]; - config.destination.accessToken = ROLLBAR_DEMO_PAYLOADS_ACCESS_TOKEN; - config.destination.environment = ROLLBAR_DEMO_ENVIRONMENT; + RollbarMutableConfig *config = [RollbarConfig mutableConfigWithAccessToken:ROLLBAR_DEMO_PAYLOADS_ACCESS_TOKEN + environment:@"staging"]; //config.developerOptions.suppressSdkInfoLogging = YES; - config.customData = @{ @"someKey": @"someValue", }; + config.customData = [NSMutableDictionary dictionaryWithDictionary: @{ @"someKey": @"someValue", }]; config.telemetry.enabled = YES; config.telemetry.memoryStatsAutocollectionInterval = 0.5; config.telemetry.maximumTelemetryData = 30; - [RollbarAulStoreMonitor.sharedInstance configureRollbarLogger:Rollbar.currentLogger]; + //[RollbarAulStoreMonitor.sharedInstance configureRollbarLogger:Rollbar.currentLogger]; [RollbarAulStoreMonitor.sharedInstance start]; // optional crash reporter: diff --git a/Demos/macosAppObjC/macosAppObjC/RollbarDeploysDemoClient.m b/Demos/macosAppObjC/macosAppObjC/RollbarDeploysDemoClient.m index eb090c5e..cb4de3e9 100644 --- a/Demos/macosAppObjC/macosAppObjC/RollbarDeploysDemoClient.m +++ b/Demos/macosAppObjC/macosAppObjC/RollbarDeploysDemoClient.m @@ -7,9 +7,12 @@ // #import "RollbarDeploysDemoClient.h" -#import "RollbarDemoSettings.h" @import RollbarDeploys; +static NSString * const ROLLBAR_DEMO_PAYLOADS_ACCESS_TOKEN = @"09da180aba21479e9ed3d91e0b8d58d6"; +static NSString * const ROLLBAR_DEMO_DEPLOYS_WRITE_ACCESS_TOKEN = @"efdc4b85d66045f293a7f9e99c732f61"; +static NSString * const ROLLBAR_DEMO_DEPLOYS_READ_ACCESS_TOKEN = @"595cbf76b05b45f2b3ef661a2e0078d4"; + @interface RollbarDeploysObserver : NSObject< RollbarDeploymentRegistrationObserver, @@ -58,7 +61,7 @@ - (void)demoDeploymentRegistration { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; - NSString * const environment = ROLLBAR_DEMO_ENVIRONMENT; + NSString * const environment = @"staging"; NSString * const comment = [NSString stringWithFormat:@"a new deploy at %@", [dateFormatter stringFromDate:[NSDate date]]]; NSString * const revision = @"a_revision"; diff --git a/Demos/macosAppObjC/macosAppObjC/ViewController.h b/Demos/macosAppObjC/macosAppObjC/ViewController.h index 6a98f7d5..2af7b0af 100644 --- a/Demos/macosAppObjC/macosAppObjC/ViewController.h +++ b/Demos/macosAppObjC/macosAppObjC/ViewController.h @@ -10,6 +10,5 @@ @interface ViewController : NSViewController - @end diff --git a/Demos/macosAppSwift/macosAppSwift/ContentView.swift b/Demos/macosAppSwift/macosAppSwift/ContentView.swift index d412e9b5..34ad9c4a 100644 --- a/Demos/macosAppSwift/macosAppSwift/ContentView.swift +++ b/Demos/macosAppSwift/macosAppSwift/ContentView.swift @@ -59,14 +59,7 @@ func handleSwiftError() { func handleObjCException() { - do { - - self.generateObjCException(); - } - catch { - - print("Unexpected error: \(error).") - } + self.generateObjCException(); } func generateObjCException() { @@ -90,13 +83,9 @@ func handleSwiftError() { func createGuard() -> RollbarExceptionGuard { - let config = RollbarConfig(); - - config.destination.accessToken = - RollbarDemoSettings.payloadsPostAccessToken; - - config.destination.environment = - RollbarDemoSettings.environment; + let config = RollbarConfig.mutableConfig( + withAccessToken: RollbarDemoSettings.payloadsPostAccessToken, + environment: RollbarDemoSettings.environment) // AUL capture setup: // config.developerOptions.transmit = true; diff --git a/Demos/tvosAppObjC/tvosAppObjC/AppDelegate.m b/Demos/tvosAppObjC/tvosAppObjC/AppDelegate.m index cb6dd7f5..f11aacd6 100644 --- a/Demos/tvosAppObjC/tvosAppObjC/AppDelegate.m +++ b/Demos/tvosAppObjC/tvosAppObjC/AppDelegate.m @@ -6,7 +6,6 @@ // #import "AppDelegate.h" -#import "RollbarDemoSettings.h" @import RollbarNotifier; @import RollbarKSCrash; @@ -82,10 +81,9 @@ - (void)applicationDidBecomeActive:(UIApplication *)application { - (void)initRollbar { // configure Rollbar: - RollbarConfig *config = [RollbarConfig new]; + RollbarMutableConfig *config = [RollbarConfig mutableConfigWithAccessToken:@"09da180aba21479e9ed3d91e0b8d58d6" + environment:@"staging"]; - config.destination.accessToken = ROLLBAR_DEMO_PAYLOADS_ACCESS_TOKEN; - config.destination.environment = ROLLBAR_DEMO_ENVIRONMENT; config.developerOptions.suppressSdkInfoLogging = YES; config.telemetry.memoryStatsAutocollectionInterval = 0.5; config.telemetry.enabled = YES; From 8967c163bac41b27e888eaa684f1cad8c586de97 Mon Sep 17 00:00:00 2001 From: Matias Pequeno Date: Tue, 29 Nov 2022 18:31:25 +0100 Subject: [PATCH 124/127] Removed access tokens from examples. --- Demos/RollbarDemoSettings.h | 16 ---------------- Demos/RollbarDemoSettings.swift | 8 -------- Demos/iosAppObjC/iosAppObjC/AppDelegate.m | 7 +++++-- .../iosAppSwift/iosAppSwift/iosAppSwiftApp.swift | 2 +- .../macosAppObjC.xcodeproj/project.pbxproj | 2 -- .../macosAppSwift.xcodeproj/project.pbxproj | 4 ---- .../tvosAppObjC.xcodeproj/project.pbxproj | 2 -- .../ExtensionDelegate.m | 8 ++++---- .../watchosAppObjC.xcodeproj/project.pbxproj | 2 -- RollbarSDK.xcworkspace/contents.xcworkspacedata | 6 ------ 10 files changed, 10 insertions(+), 47 deletions(-) delete mode 100644 Demos/RollbarDemoSettings.h delete mode 100644 Demos/RollbarDemoSettings.swift diff --git a/Demos/RollbarDemoSettings.h b/Demos/RollbarDemoSettings.h deleted file mode 100644 index 500f5201..00000000 --- a/Demos/RollbarDemoSettings.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef RollbarDemoSettings_h -#define RollbarDemoSettings_h - -static NSString * const ROLLBAR_DEMO_ENVIRONMENT = -@"Rollbar-Apple-Samples"; - -static NSString * const ROLLBAR_DEMO_PAYLOADS_ACCESS_TOKEN = -@"09da180aba21479e9ed3d91e0b8d58d6"; - -static NSString * const ROLLBAR_DEMO_DEPLOYS_WRITE_ACCESS_TOKEN = -@"efdc4b85d66045f293a7f9e99c732f61"; - -static NSString * const ROLLBAR_DEMO_DEPLOYS_READ_ACCESS_TOKEN = -@"595cbf76b05b45f2b3ef661a2e0078d4"; - -#endif /* RollbarDemoSettings_h */ diff --git a/Demos/RollbarDemoSettings.swift b/Demos/RollbarDemoSettings.swift deleted file mode 100644 index 870e65a3..00000000 --- a/Demos/RollbarDemoSettings.swift +++ /dev/null @@ -1,8 +0,0 @@ -import Foundation - -struct RollbarDemoSettings { - static let environment = "Rollbar-Apple-Samples"; - static let payloadsPostAccessToken = "09da180aba21479e9ed3d91e0b8d58d6"; - static let deploysWriteAccessToken = "efdc4b85d66045f293a7f9e99c732f61"; - static let deploysReadAccessToken = "595cbf76b05b45f2b3ef661a2e0078d4"; -} diff --git a/Demos/iosAppObjC/iosAppObjC/AppDelegate.m b/Demos/iosAppObjC/iosAppObjC/AppDelegate.m index 922b27d7..82f75761 100644 --- a/Demos/iosAppObjC/iosAppObjC/AppDelegate.m +++ b/Demos/iosAppObjC/iosAppObjC/AppDelegate.m @@ -9,8 +9,11 @@ @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. - RollbarMutableConfig *config = [RollbarConfig mutableConfigWithAccessToken:@"dc0d9ce3d93c4ef5a4dbacf2434e508d" - environment:@"staging"]; + RollbarMutableConfig *config = [ + // Rollbar post_client_item access token + RollbarConfig mutableConfigWithAccessToken:@"YOUR-ROLLBAR-ACCESSTOKEN" + environment:@"staging"]; + config.loggingOptions.codeVersion = @"main"; config.developerOptions.suppressSdkInfoLogging = NO; config.telemetry.memoryStatsAutocollectionInterval = 0.5; diff --git a/Demos/iosAppSwift/iosAppSwift/iosAppSwiftApp.swift b/Demos/iosAppSwift/iosAppSwift/iosAppSwiftApp.swift index 2816a71a..6c7a595c 100644 --- a/Demos/iosAppSwift/iosAppSwift/iosAppSwiftApp.swift +++ b/Demos/iosAppSwift/iosAppSwift/iosAppSwiftApp.swift @@ -22,7 +22,7 @@ class AppDelegate: NSObject, UIApplicationDelegate { ) -> Bool { // Dynamically read these settings from your config settings on // application startup. - let accessToken = "2fa95b91f38448299b5097ff11cffb23" // Rollbar post_client_item access token + let accessToken = "YOUR-ROLLBAR-ACCESSTOKEN" // Rollbar post_client_item access token let environment = "staging" let codeVersion = "main" // Ideally codeVersion is commit SHA https://docs.rollbar.com/docs/versions diff --git a/Demos/macosAppObjC/macosAppObjC.xcodeproj/project.pbxproj b/Demos/macosAppObjC/macosAppObjC.xcodeproj/project.pbxproj index b146ba04..01fd1f83 100644 --- a/Demos/macosAppObjC/macosAppObjC.xcodeproj/project.pbxproj +++ b/Demos/macosAppObjC/macosAppObjC.xcodeproj/project.pbxproj @@ -31,7 +31,6 @@ 55759A772477561100ED3F04 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 55759A782477561100ED3F04 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 55759A7A2477561100ED3F04 /* macosAppObjC.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = macosAppObjC.entitlements; sourceTree = ""; }; - 55C1B42027C5C4E800017B22 /* RollbarDemoSettings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RollbarDemoSettings.h; path = ../../RollbarDemoSettings.h; sourceTree = ""; }; 55FD07122478614B000BBC22 /* RollbarDeploysDemoClient.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RollbarDeploysDemoClient.h; sourceTree = ""; }; 55FD07132478614B000BBC22 /* RollbarDeploysDemoClient.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RollbarDeploysDemoClient.m; sourceTree = ""; }; /* End PBXFileReference section */ @@ -72,7 +71,6 @@ 55759A6B2477560D00ED3F04 /* macosAppObjC */ = { isa = PBXGroup; children = ( - 55C1B42027C5C4E800017B22 /* RollbarDemoSettings.h */, 55759A6C2477560D00ED3F04 /* AppDelegate.h */, 55759A6D2477560D00ED3F04 /* AppDelegate.m */, 55759A6F2477560D00ED3F04 /* ViewController.h */, diff --git a/Demos/macosAppSwift/macosAppSwift.xcodeproj/project.pbxproj b/Demos/macosAppSwift/macosAppSwift.xcodeproj/project.pbxproj index 5ae3ff3e..45333629 100644 --- a/Demos/macosAppSwift/macosAppSwift.xcodeproj/project.pbxproj +++ b/Demos/macosAppSwift/macosAppSwift.xcodeproj/project.pbxproj @@ -16,7 +16,6 @@ 5544A01F25FB074300C710A1 /* RollbarCommon in Frameworks */ = {isa = PBXBuildFile; productRef = 5544A01E25FB074300C710A1 /* RollbarCommon */; }; 5544A02125FB074300C710A1 /* RollbarNotifier in Frameworks */ = {isa = PBXBuildFile; productRef = 5544A02025FB074300C710A1 /* RollbarNotifier */; }; 5544A02325FB074300C710A1 /* RollbarSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 5544A02225FB074300C710A1 /* RollbarSwift */; }; - 55C1B41F27C5BDF000017B22 /* RollbarDemoSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55C1B41E27C5BDF000017B22 /* RollbarDemoSettings.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -27,7 +26,6 @@ 55098C6B25FA93110045C180 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; 55098C6D25FA93110045C180 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 55098C6E25FA93110045C180 /* macosAppSwift.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = macosAppSwift.entitlements; sourceTree = ""; }; - 55C1B41E27C5BDF000017B22 /* RollbarDemoSettings.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RollbarDemoSettings.swift; path = ../../RollbarDemoSettings.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -66,7 +64,6 @@ 55098C6325FA930D0045C180 /* macosAppSwift */ = { isa = PBXGroup; children = ( - 55C1B41E27C5BDF000017B22 /* RollbarDemoSettings.swift */, 55098C6425FA930D0045C180 /* macosAppSwiftApp.swift */, 55098C6625FA930D0045C180 /* ContentView.swift */, 55098C6825FA93110045C180 /* Assets.xcassets */, @@ -169,7 +166,6 @@ buildActionMask = 2147483647; files = ( 55098C6725FA930D0045C180 /* ContentView.swift in Sources */, - 55C1B41F27C5BDF000017B22 /* RollbarDemoSettings.swift in Sources */, 55098C6525FA930D0045C180 /* macosAppSwiftApp.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Demos/tvosAppObjC/tvosAppObjC.xcodeproj/project.pbxproj b/Demos/tvosAppObjC/tvosAppObjC.xcodeproj/project.pbxproj index e8c726b4..344c1591 100644 --- a/Demos/tvosAppObjC/tvosAppObjC.xcodeproj/project.pbxproj +++ b/Demos/tvosAppObjC/tvosAppObjC.xcodeproj/project.pbxproj @@ -19,7 +19,6 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ - 554E6728282B448E00908A64 /* RollbarDemoSettings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RollbarDemoSettings.h; path = ../../RollbarDemoSettings.h; sourceTree = ""; }; 55889E242818B83B002E0228 /* tvosAppObjC.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = tvosAppObjC.app; sourceTree = BUILT_PRODUCTS_DIR; }; 55889E272818B83B002E0228 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 55889E282818B83B002E0228 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; @@ -65,7 +64,6 @@ 55889E262818B83B002E0228 /* tvosAppObjC */ = { isa = PBXGroup; children = ( - 554E6728282B448E00908A64 /* RollbarDemoSettings.h */, 55889E272818B83B002E0228 /* AppDelegate.h */, 55889E282818B83B002E0228 /* AppDelegate.m */, 55889E2A2818B83B002E0228 /* ViewController.h */, diff --git a/Demos/watchosAppObjC/watchosAppObjC WatchKit Extension/ExtensionDelegate.m b/Demos/watchosAppObjC/watchosAppObjC WatchKit Extension/ExtensionDelegate.m index 16124a63..c2b1664f 100644 --- a/Demos/watchosAppObjC/watchosAppObjC WatchKit Extension/ExtensionDelegate.m +++ b/Demos/watchosAppObjC/watchosAppObjC WatchKit Extension/ExtensionDelegate.m @@ -6,7 +6,6 @@ // #import "ExtensionDelegate.h" -#import "RollbarDemoSettings.h" @import RollbarNotifier; @@ -97,10 +96,11 @@ - (void)handleBackgroundTasks:(NSSet *)backgroundTask - (void)initRollbar { // configure Rollbar: - RollbarConfig *config = [RollbarConfig new]; + RollbarMutableConfig *config = [ + // Rollbar post_client_item access token + RollbarMutableConfig mutableConfigWithAccessToken:@"YOUR-ROLLBAR-ACCESSTOKEN" + environment:@"staging"]; - config.destination.accessToken = ROLLBAR_DEMO_PAYLOADS_ACCESS_TOKEN; - config.destination.environment = ROLLBAR_DEMO_ENVIRONMENT; config.developerOptions.suppressSdkInfoLogging = YES; config.telemetry.memoryStatsAutocollectionInterval = 0.5; config.telemetry.enabled = YES; diff --git a/Demos/watchosAppObjC/watchosAppObjC.xcodeproj/project.pbxproj b/Demos/watchosAppObjC/watchosAppObjC.xcodeproj/project.pbxproj index c74c6969..442e8b55 100644 --- a/Demos/watchosAppObjC/watchosAppObjC.xcodeproj/project.pbxproj +++ b/Demos/watchosAppObjC/watchosAppObjC.xcodeproj/project.pbxproj @@ -62,7 +62,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 554E6731282B4C3C00908A64 /* RollbarDemoSettings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RollbarDemoSettings.h; path = ../../RollbarDemoSettings.h; sourceTree = ""; }; 55889E432818B937002E0228 /* watchosAppObjC.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = watchosAppObjC.app; sourceTree = BUILT_PRODUCTS_DIR; }; 55889E472818B937002E0228 /* watchosAppObjC WatchKit App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "watchosAppObjC WatchKit App.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 55889E4D2818B937002E0228 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = ""; }; @@ -125,7 +124,6 @@ 55889E592818B939002E0228 /* watchosAppObjC WatchKit Extension */ = { isa = PBXGroup; children = ( - 554E6731282B4C3C00908A64 /* RollbarDemoSettings.h */, 55889E5A2818B939002E0228 /* InterfaceController.h */, 55889E5B2818B939002E0228 /* InterfaceController.m */, 55889E5D2818B939002E0228 /* ExtensionDelegate.h */, diff --git a/RollbarSDK.xcworkspace/contents.xcworkspacedata b/RollbarSDK.xcworkspace/contents.xcworkspacedata index a91fa17c..51ad510b 100644 --- a/RollbarSDK.xcworkspace/contents.xcworkspacedata +++ b/RollbarSDK.xcworkspace/contents.xcworkspacedata @@ -89,12 +89,6 @@ - - - - From 8fa09879f9092361e13dc52d7c8de522f64b5264 Mon Sep 17 00:00:00 2001 From: Matias Pequeno Date: Tue, 29 Nov 2022 18:36:54 +0100 Subject: [PATCH 125/127] Fixed crash during json serialization. dsa --- .../Sources/RollbarCommon/DTOs/RollbarDTO.m | 2 +- .../NSJSONSerialization+Rollbar.m | 15 ++++-- .../NSJSONSerialization+RollbarTests.swift | 50 +++++++------------ 3 files changed, 30 insertions(+), 37 deletions(-) diff --git a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m index e864ca49..d95391ba 100644 --- a/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m +++ b/RollbarCommon/Sources/RollbarCommon/DTOs/RollbarDTO.m @@ -363,7 +363,7 @@ - (instancetype)initWithDictionary:(nullable NSDictionary *)data } if (![RollbarDTO isTransferableObject:data]) { - + RollbarSdkLog(@"JSON-invalid internal data."); return self; } diff --git a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m index 5c099be9..6252540a 100644 --- a/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m +++ b/RollbarCommon/Sources/RollbarCommon/NSJSONSerialization+Rollbar.m @@ -1,6 +1,10 @@ #import "NSJSONSerialization+Rollbar.h" #import "RollbarSdkLog.h" +#import +// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html +#define IS_NSOBJECT(_X_) (strchr("@#", @encode(typeof(_X_))[0]) != NULL) + @implementation NSJSONSerialization (Rollbar) NS_ASSUME_NONNULL_BEGIN @@ -42,7 +46,7 @@ + (nullable NSData *)rollbar_dataWithJSONObject:(id)obj } + (nonnull NSMutableDictionary *)rollbar_safeDataFromJSONObject:(nullable id)obj { - + NSMutableDictionary *safeData = [NSMutableDictionary new]; if (nil == obj) { @@ -50,10 +54,11 @@ + (nonnull NSMutableDictionary *)rollbar_safeDataFromJSONObject:(nullable id)obj } [obj enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { - - // Defensive failsafe to avoid exceptions when trying to create dictionary literal with nil `obj` - obj = obj ?: [NSNull null]; - + + if (obj == nil || !IS_NSOBJECT(obj)) { + obj = [NSNull null]; + } + if ([obj isKindOfClass:[NSDictionary class]]) { [safeData setObject:[[self class] rollbar_safeDataFromJSONObject:obj] forKey:key]; diff --git a/RollbarCommon/Tests/RollbarCommonTests/NSJSONSerialization+RollbarTests.swift b/RollbarCommon/Tests/RollbarCommonTests/NSJSONSerialization+RollbarTests.swift index f42172be..d38720ce 100644 --- a/RollbarCommon/Tests/RollbarCommonTests/NSJSONSerialization+RollbarTests.swift +++ b/RollbarCommon/Tests/RollbarCommonTests/NSJSONSerialization+RollbarTests.swift @@ -31,53 +31,41 @@ final class NSJSONSerializationRollbarTests: XCTestCase { } func testNSJSONSerializationRollbar_safeDataFromJSONObject() { - let goldenStandard = "{\"access_token\":\"321\",\"data\":{\"attribute\":\"An attribute\",\"body\":\"Message\",\"date\":\"1970-01-01 00:00:00 +0000\",\"error\":{},\"httpUrlResponse\":{\"header1\":\"Header 1\",\"header2\":\"Header 2\"},\"innerData\":{\"attribute\":\"An attribute\",\"body\":\"Message\",\"date\":\"1970-01-01 00:00:00 +0000\",\"error\":{},\"httpUrlResponse\":{\"header1\":\"Header 1\",\"header2\":\"Header 2\"},\"optionalField\":null,\"scrubFields\":\"secret,CCV,password\",\"url\":\"http:\\/\\/www.apple.com\"},\"optionalField\":null,\"scrubFields\":\"secret,CCV,password\",\"url\":\"http:\\/\\/www.apple.com\"}}"; - let optionalFieldValue: String? = nil var data = [ "body": "Message", - "optionalField": optionalFieldValue as Any, + "optionalField": (nil as String?) as Any, "attribute": "An attribute", - "date": NSDate.init(timeIntervalSince1970: TimeInterval.init()), - "url": NSURL.init(string: "http://www.apple.com")!, - "error": NSError.init(domain: "Error Domain", code: 101, userInfo: nil), - "httpUrlResponse": HTTPURLResponse.init( - url: URL.init(string: "https://www.rollbar.com")!, + "date": Date(timeIntervalSince1970: TimeInterval.init()), + "url": URL(string: "http://www.apple.com")!, + "error": NSError(domain: "Error Domain", code: 101, userInfo: nil), + "httpUrlResponse": HTTPURLResponse( + url: URL(string: "https://www.rollbar.com")!, statusCode: 500, httpVersion: "1.2", headerFields: ["header1": "Header 1", "header2": "Header 2"]) as Any, - "scrubFields": NSSet.init(array: ["password", "secret", "CCV"]), - ] as [String : Any]; - - if #available(OSX 10.13, iOS 11.0, *) { - data["innerData"] = JSONSerialization.rollbar_data( - withJSONObject: data, - options: .sortedKeys, - error: nil, - safe: true) - } else { - // Fallback on earlier versions - XCTFail("Test it on more recent OS version!"); - }; + "scrubFields": NSSet(array: ["password", "secret", "CCV"]), + ] as [String: Any]; + + data["innerData"] = JSONSerialization.rollbar_data( + withJSONObject: data, + options: .sortedKeys, + error: nil, + safe: true) let payload = [ "access_token": "321", "data": data, - ] as [String : Any]; - + ] as [String : Any]; + let safeJson = JSONSerialization.rollbar_safeData(fromJSONObject: payload); do { - if #available(OSX 10.13, iOS 11.0, *) { - let jsonData = try JSONSerialization.data(withJSONObject: safeJson, options: .sortedKeys) - let result = String.init(data: jsonData, encoding: .utf8); - XCTAssertEqual(goldenStandard, result); - } else { - // Fallback on earlier versions - XCTFail("Test it on more recent OS version!"); - }; + let jsonData = try JSONSerialization.data(withJSONObject: safeJson, options: .sortedKeys) + let result = String(data: jsonData, encoding: .utf8); + XCTAssertEqual(goldenStandard, result); } catch { XCTFail("Unexpected failure!"); From 800e20059906e524c8618c76fd1f0b97b0804afc Mon Sep 17 00:00:00 2001 From: Matias Pequeno Date: Tue, 29 Nov 2022 19:36:11 +0100 Subject: [PATCH 126/127] Updated version to 2.4.0 --- .gitignore | 2 + Package.resolved | 43 +++++++++++++++++++ RollbarAUL.podspec | 4 +- RollbarCocoaLumberjack.podspec | 4 +- RollbarCommon.podspec | 4 +- RollbarDeploys.podspec | 4 +- RollbarKSCrash.podspec | 4 +- RollbarNotifier.podspec | 4 +- .../RollbarNotifier/DTOs/RollbarConfig.m | 2 +- RollbarPLCrashReporter.podspec | 4 +- RollbarSDK.experimental_podspec | 2 +- RollbarSwift.podspec | 4 +- 12 files changed, 63 insertions(+), 18 deletions(-) create mode 100644 Package.resolved diff --git a/.gitignore b/.gitignore index ab6ef954..ab4040da 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,5 @@ build_wrapper_output_directory/ _ General AUL Entries Bulk Capture.txt _ AUL Entries Capture Samples.txt + +.build/ diff --git a/Package.resolved b/Package.resolved new file mode 100644 index 00000000..0e3de8d9 --- /dev/null +++ b/Package.resolved @@ -0,0 +1,43 @@ +{ + "object": { + "pins": [ + { + "package": "CocoaLumberjack", + "repositoryURL": "https://github.com/CocoaLumberjack/CocoaLumberjack.git", + "state": { + "branch": null, + "revision": "0188d31089b5881a269e01777be74c7316924346", + "version": "3.8.0" + } + }, + { + "package": "KSCrash", + "repositoryURL": "https://github.com/kstenerud/KSCrash.git", + "state": { + "branch": null, + "revision": "f45a917d93928b32626f3268239c58a6cdd852bb", + "version": "1.15.25" + } + }, + { + "package": "PLCrashReporter", + "repositoryURL": "https://github.com/microsoft/plcrashreporter.git", + "state": { + "branch": null, + "revision": "b1a342da19ed9b3af61ea2efa7656c2af30aeb7c", + "version": "1.11.0" + } + }, + { + "package": "swift-log", + "repositoryURL": "https://github.com/apple/swift-log.git", + "state": { + "branch": null, + "revision": "6fe203dc33195667ce1759bf0182975e4653ba1c", + "version": "1.4.4" + } + } + ] + }, + "version": 1 +} diff --git a/RollbarAUL.podspec b/RollbarAUL.podspec index 139b6733..243fd37d 100644 --- a/RollbarAUL.podspec +++ b/RollbarAUL.podspec @@ -7,7 +7,7 @@ Pod::Spec.new do |s| - s.version = "2.3.4" + s.version = "2.4.0" s.name = "RollbarAUL" s.summary = "Application or client side SDK for interacting with the Rollbar API Server." s.description = <<-DESC @@ -54,7 +54,7 @@ Pod::Spec.new do |s| # s.library = "iconv" # s.libraries = "iconv", "xml2" # s.dependency "JSONKit", "~> 1.4" - + s.requires_arc = true s.xcconfig = { "USE_HEADERMAP" => "NO", diff --git a/RollbarCocoaLumberjack.podspec b/RollbarCocoaLumberjack.podspec index 04693908..6d63b775 100644 --- a/RollbarCocoaLumberjack.podspec +++ b/RollbarCocoaLumberjack.podspec @@ -7,7 +7,7 @@ Pod::Spec.new do |s| - s.version = "2.3.4" + s.version = "2.4.0" s.name = "RollbarCocoaLumberjack" s.summary = "Application or client side SDK for interacting with the Rollbar API Server." s.description = <<-DESC @@ -56,7 +56,7 @@ Pod::Spec.new do |s| # s.library = "iconv" # s.libraries = "iconv", "xml2" # s.dependency "JSONKit", "~> 1.4" - + s.requires_arc = true # s.xcconfig = { # "USE_HEADERMAP" => "NO", diff --git a/RollbarCommon.podspec b/RollbarCommon.podspec index c235a57d..d2e250c7 100644 --- a/RollbarCommon.podspec +++ b/RollbarCommon.podspec @@ -7,7 +7,7 @@ Pod::Spec.new do |s| - s.version = "2.3.4" + s.version = "2.4.0" s.name = "RollbarCommon" s.summary = "Application or client side SDK for interacting with the Rollbar API Server." s.description = <<-DESC @@ -52,7 +52,7 @@ Pod::Spec.new do |s| # s.library = "iconv" # s.libraries = "iconv", "xml2" # s.dependency "JSONKit", "~> 1.4" - + s.requires_arc = true # s.xcconfig = { # "USE_HEADERMAP" => "NO", diff --git a/RollbarDeploys.podspec b/RollbarDeploys.podspec index bdcd7522..e287dccf 100644 --- a/RollbarDeploys.podspec +++ b/RollbarDeploys.podspec @@ -7,7 +7,7 @@ Pod::Spec.new do |s| - s.version = "2.3.4" + s.version = "2.4.0" s.name = "RollbarDeploys" s.summary = "Application or client side SDK for interacting with the Rollbar API Server." s.description = <<-DESC @@ -53,7 +53,7 @@ Pod::Spec.new do |s| # s.library = "iconv" # s.libraries = "iconv", "xml2" # s.dependency "JSONKit", "~> 1.4" - + s.requires_arc = true # s.xcconfig = { # "USE_HEADERMAP" => "NO", diff --git a/RollbarKSCrash.podspec b/RollbarKSCrash.podspec index 96765543..47f1bef5 100644 --- a/RollbarKSCrash.podspec +++ b/RollbarKSCrash.podspec @@ -7,7 +7,7 @@ Pod::Spec.new do |s| - s.version = "2.3.4" + s.version = "2.4.0" s.name = "RollbarKSCrash" s.summary = "Application or client side SDK for interacting with the Rollbar API Server." s.description = <<-DESC @@ -54,7 +54,7 @@ Pod::Spec.new do |s| # s.library = "iconv" # s.libraries = "iconv", "xml2" # s.dependency "JSONKit", "~> 1.4" - + s.requires_arc = true # s.xcconfig = { # "USE_HEADERMAP" => "NO", diff --git a/RollbarNotifier.podspec b/RollbarNotifier.podspec index 095f3992..4cc9dd05 100644 --- a/RollbarNotifier.podspec +++ b/RollbarNotifier.podspec @@ -7,7 +7,7 @@ Pod::Spec.new do |s| - s.version = "2.3.4" + s.version = "2.4.0" s.name = "RollbarNotifier" s.summary = "Application or client side SDK for interacting with the Rollbar API Server." s.description = <<-DESC @@ -53,7 +53,7 @@ Pod::Spec.new do |s| # s.library = "iconv" # s.libraries = "iconv", "xml2" # s.dependency "JSONKit", "~> 1.4" - + s.requires_arc = true # s.xcconfig = { # "USE_HEADERMAP" => "NO", diff --git a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m index d1565a86..7f483928 100644 --- a/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m +++ b/RollbarNotifier/Sources/RollbarNotifier/DTOs/RollbarConfig.m @@ -14,7 +14,7 @@ #pragma mark - constants -static NSString * const NOTIFIER_VERSION = @"2.3.4"; +static NSString * const NOTIFIER_VERSION = @"2.4.0"; static NSString * const NOTIFIER_NAME = @"rollbar-apple"; diff --git a/RollbarPLCrashReporter.podspec b/RollbarPLCrashReporter.podspec index af4fa98a..491a66e9 100644 --- a/RollbarPLCrashReporter.podspec +++ b/RollbarPLCrashReporter.podspec @@ -7,7 +7,7 @@ Pod::Spec.new do |s| - s.version = "2.3.4" + s.version = "2.4.0" s.name = "RollbarPLCrashReporter" s.summary = "Application or client side SDK for interacting with the Rollbar API Server." s.description = <<-DESC @@ -55,7 +55,7 @@ Pod::Spec.new do |s| # s.library = "iconv" # s.libraries = "iconv", "xml2" # s.dependency "JSONKit", "~> 1.4" - + s.requires_arc = true # s.xcconfig = { # "USE_HEADERMAP" => "NO", diff --git a/RollbarSDK.experimental_podspec b/RollbarSDK.experimental_podspec index 49f14cea..3ed56460 100644 --- a/RollbarSDK.experimental_podspec +++ b/RollbarSDK.experimental_podspec @@ -9,7 +9,7 @@ Pod::Spec.new do |sdk| # Rollbar SDK: # ============ - sdk.version = "2.3.4" + sdk.version = "2.4.0" sdk.name = "RollbarSDK" s.summary = "Application or client side SDK for interacting with the Rollbar API Server." sdk.description = <<-DESC diff --git a/RollbarSwift.podspec b/RollbarSwift.podspec index 37e0df2a..684936a7 100644 --- a/RollbarSwift.podspec +++ b/RollbarSwift.podspec @@ -7,7 +7,7 @@ Pod::Spec.new do |s| - s.version = "2.3.4" + s.version = "2.4.0" s.name = "RollbarSwift" s.summary = "Application or client side SDK for interacting with the Rollbar API Server." s.description = <<-DESC @@ -54,7 +54,7 @@ Pod::Spec.new do |s| # s.library = "iconv" # s.libraries = "iconv", "xml2" # s.dependency "JSONKit", "~> 1.4" - + s.requires_arc = true s.xcconfig = { "USE_HEADERMAP" => "NO", From 704b2680f97414f014b24f82a96b4e3dbd50c215 Mon Sep 17 00:00:00 2001 From: Matias Pequeno Date: Tue, 29 Nov 2022 20:09:48 +0100 Subject: [PATCH 127/127] Updated changelog --- CHANGELOG.md | 44 ++++++++++++++++++++------------------------ 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 71adf7b6..dd3c840c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,37 +2,33 @@ The change log has moved to this repo's [GitHub Releases Page](https://github.com/rollbar/rollbar-apple/releases). -## Release Notes Tagging Conventions - -1. Every entry within the PackageReleaseNotes element is expected to be started with - at least one of the tags listed: - - feat: A new feature - fix: A bug fix - docs: Documentation only changes - style: Changes that do not affect the meaning of the code - refactor: A code change that neither a bug fix nor a new feature - perf: A code change that improves performance - test: Adding or modifying unit test code - chore: Changes to the build process or auxiliary tools and libraries such as documentation generation, etc. - -2. Every entry within the PackageReleaseNotes element is expected to be tagged with - EITHER - "resolve #GITHUB_ISSUE_NUMBER:" - meaning completely addresses the GitHub issue - OR - "ref #GITHUB_ISSUE_NUMBER:" - meaning relevant to the GitHub issue - depending on what is more appropriate in each case. - ## Release Notes +### 2.4.0 +- New SDK Demos for iOS Swift and Objective-C. +- Fixed a rare crash during JSON serialization. +- More robust and more flexible SDK reconfigurability. +- Thread safety by design. +- Fully independent configurability of each individual instance of a logger. +- Flexible and standardized rate limiting control (both locally configured and server enforced). +- Structured payload storage based on Sqlite instead of a flat text file. +- Improved local payload logging based on developer options of a config object. Separately for all the incoming vs transmitted vs dropped payloads. +- Improved internal diagnostics of the SDK with reach debug build assertions. +- Ooptimized payload modification implementation. +- Improved performance of the RollbarThread. +- Improved internal SDK recovery from any unforeseen internal SDK exceptions/errors (including during processing of totally custom user-specified data within a payload). +- General codebase code quality and maintainability improvements. +- A higher level of code reuse. +- And more... + ### 2.3.4 - fix: resolve #218 - Failsafe to ensure obj is not nil when creating dict literal ### 2.3.3 -- fix: resolve #190 - Fix Cocoapods build warnings in RollbarNotifier -- fix: resolve #191 - Fix Cocoapods build warnings in RollbarCommon +- fix: resolve #190 - Fix Cocoapods build warnings in RollbarNotifier +- fix: resolve #191 - Fix Cocoapods build warnings in RollbarCommon - fix: resolve #192 - Fix SonarCloud detected bugs ### 2.3.2 @@ -76,7 +72,7 @@ The change log has moved to this repo's [GitHub Releases Page](https://github.co ### 2.1.0 -- feat: resolve #141 - Apply developer options of the persisted payload when sending the payload +- feat: resolve #141 - Apply developer options of the persisted payload when sending the payload - feat: resolve #133 - Implement RollbarCocoaLumberjack module - test: resolve #134 - Implement unit tests for RollbarCocoaLumberjack - fix: resolve #136 - RollbarPLCrashReporter.init() no longer available