|
| 1 | +// |
| 2 | +// CountlyHealthTracker.m |
| 3 | +// CountlyTestApp-iOS |
| 4 | +// |
| 5 | +// Created by Arif Burak Demiray on 20.05.2025. |
| 6 | +// Copyright © 2025 Countly. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +#import <Foundation/Foundation.h> |
| 10 | +#import "CountlyHealthTracker.h" |
| 11 | +#import "CountlyCommon.h" |
| 12 | + |
| 13 | +@interface CountlyHealthTracker () |
| 14 | + |
| 15 | +@property (nonatomic, assign) long countLogWarning; |
| 16 | +@property (nonatomic, assign) long countLogError; |
| 17 | +@property (nonatomic, assign) long countBackoffRequest; |
| 18 | +@property (nonatomic, assign) NSInteger statusCode; |
| 19 | +@property (nonatomic, strong) NSString *errorMessage; |
| 20 | +@property (nonatomic, assign) BOOL healthCheckEnabled; |
| 21 | +@property (nonatomic, assign) BOOL healthCheckSent; |
| 22 | + |
| 23 | +@end |
| 24 | + |
| 25 | +@implementation CountlyHealthTracker |
| 26 | + |
| 27 | +NSString * const keyLogError = @"LErr"; |
| 28 | +NSString * const keyLogWarning = @"LWar"; |
| 29 | +NSString * const keyStatusCode = @"RStatC"; |
| 30 | +NSString * const keyErrorMessage = @"REMsg"; |
| 31 | +NSString * const keyBackoffRequest = @"BReq"; |
| 32 | + |
| 33 | +NSString * const requestKeyErrorCount = @"el"; |
| 34 | +NSString * const requestKeyWarningCount = @"wl"; |
| 35 | +NSString * const requestKeyStatusCode = @"sc"; |
| 36 | +NSString * const requestKeyRequestError = @"em"; |
| 37 | +NSString * const requestKeyBackoffRequest = @"br"; |
| 38 | + |
| 39 | ++ (instancetype)sharedInstance { |
| 40 | + static CountlyHealthTracker *instance = nil; |
| 41 | + static dispatch_once_t onceToken; |
| 42 | + dispatch_once(&onceToken, ^{ |
| 43 | + instance = [[self alloc] init]; |
| 44 | + }); |
| 45 | + return instance; |
| 46 | +} |
| 47 | + |
| 48 | +- (instancetype)init{ |
| 49 | + self = [super init]; |
| 50 | + if (self) { |
| 51 | + _errorMessage = @""; |
| 52 | + _statusCode = -1; |
| 53 | + _healthCheckSent = NO; |
| 54 | + _healthCheckEnabled = YES; |
| 55 | + |
| 56 | + NSDictionary *initialState = [CountlyPersistency.sharedInstance retrieveHealthCheckTrackerState]; |
| 57 | + [self setupInitialCounters:initialState]; |
| 58 | + } |
| 59 | + return self; |
| 60 | +} |
| 61 | + |
| 62 | +- (void)setupInitialCounters:(NSDictionary *)initialState { |
| 63 | + if (initialState == nil || [initialState count] == 0) { |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + self.countLogWarning = [initialState[keyLogWarning] longValue]; |
| 68 | + self.countLogError = [initialState[keyLogError] longValue]; |
| 69 | + self.statusCode = [initialState[keyStatusCode] integerValue]; |
| 70 | + self.errorMessage = initialState[keyErrorMessage] ?: @""; |
| 71 | + self.countBackoffRequest = [initialState[keyBackoffRequest] longValue]; |
| 72 | + |
| 73 | + CLY_LOG_D(@"%s, Loaded initial health check state: [%@]", __FUNCTION__, initialState); |
| 74 | +} |
| 75 | + |
| 76 | +- (void)logWarning { |
| 77 | + self.countLogWarning++; |
| 78 | +} |
| 79 | + |
| 80 | +- (void)logError { |
| 81 | + self.countLogError++; |
| 82 | +} |
| 83 | + |
| 84 | +- (void)logFailedNetworkRequestWithStatusCode:(NSInteger)statusCode |
| 85 | + errorResponse:(NSString *)errorResponse { |
| 86 | + if (statusCode <= 0 || statusCode >= 1000 || errorResponse == nil) { |
| 87 | + return; |
| 88 | + } |
| 89 | + |
| 90 | + self.statusCode = statusCode; |
| 91 | + if (errorResponse.length > 1000) { |
| 92 | + self.errorMessage = [errorResponse substringToIndex:1000]; |
| 93 | + } else { |
| 94 | + self.errorMessage = errorResponse; |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +- (void)logBackoffRequest { |
| 99 | + self.countBackoffRequest++; |
| 100 | +} |
| 101 | + |
| 102 | +- (void)clearAndSave { |
| 103 | + [self clearValues]; |
| 104 | + [CountlyPersistency.sharedInstance storeHealthCheckTrackerState:@{}]; |
| 105 | +} |
| 106 | + |
| 107 | +- (void)saveState { |
| 108 | + NSDictionary *healthCheckState = @{ |
| 109 | + keyLogWarning: @(self.countLogWarning), |
| 110 | + keyLogError: @(self.countLogError), |
| 111 | + keyStatusCode: @(self.statusCode), |
| 112 | + keyErrorMessage: self.errorMessage ?: @"", |
| 113 | + keyBackoffRequest: @(self.countBackoffRequest) |
| 114 | + }; |
| 115 | + |
| 116 | + [CountlyPersistency.sharedInstance storeHealthCheckTrackerState:healthCheckState]; |
| 117 | +} |
| 118 | + |
| 119 | +- (void)clearValues { |
| 120 | + CLY_LOG_W(@"%s, Clearing counters", __FUNCTION__); |
| 121 | + |
| 122 | + self.countLogWarning = 0; |
| 123 | + self.countLogError = 0; |
| 124 | + self.statusCode = -1; |
| 125 | + self.errorMessage = @""; |
| 126 | + self.countBackoffRequest = 0; |
| 127 | +} |
| 128 | + |
| 129 | +- (void)sendHealthCheck { |
| 130 | + if (CountlyDeviceInfo.sharedInstance.isDeviceIDTemporary) { |
| 131 | + CLY_LOG_W(@"%s, currently in temporary id mode, omitting", __FUNCTION__); |
| 132 | + } |
| 133 | + |
| 134 | + if (!_healthCheckEnabled || _healthCheckSent) { |
| 135 | + CLY_LOG_D(@"%s, health check status, sent: %d, not_enabled: %d", __FUNCTION__, _healthCheckSent, _healthCheckEnabled); |
| 136 | + } |
| 137 | + |
| 138 | + NSURLSessionTask* task = [CountlyCommon.sharedInstance.URLSession dataTaskWithRequest:[self healthCheckRequest] completionHandler:^(NSData* data, NSURLResponse* response, NSError* error) |
| 139 | + { |
| 140 | + if (error) |
| 141 | + { |
| 142 | + CLY_LOG_W(@"%s, error while sending health checks error: %@", __FUNCTION__, error); |
| 143 | + return; |
| 144 | + } |
| 145 | + |
| 146 | + NSError *jsonError; |
| 147 | + NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError]; |
| 148 | + |
| 149 | + if (jsonError || !jsonResponse) { |
| 150 | + CLY_LOG_I(@"%s, error while sending health checks, Failed to parse JSON response: %@", __FUNCTION__, jsonError); |
| 151 | + return; |
| 152 | + } |
| 153 | + |
| 154 | + if (!jsonResponse[@"result"]) { |
| 155 | + CLY_LOG_D(@"%s, Retrieved request response does not match expected pattern %@", __FUNCTION__, jsonResponse); |
| 156 | + return; |
| 157 | + } |
| 158 | + |
| 159 | + [self clearAndSave]; |
| 160 | + self->_healthCheckSent = YES; |
| 161 | + }]; |
| 162 | + |
| 163 | + [task resume]; |
| 164 | +} |
| 165 | + |
| 166 | +- (NSString *)dictionaryToJsonString:(NSDictionary *)json { |
| 167 | + NSError *error; |
| 168 | + NSData *data = [NSJSONSerialization dataWithJSONObject:json options:0 error:&error]; |
| 169 | + NSString *encodedData = @""; |
| 170 | + |
| 171 | + if (!error && data) { |
| 172 | + NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; |
| 173 | + encodedData = [jsonString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; |
| 174 | + } else { |
| 175 | + CLY_LOG_W(@"%s, Failed to create json for hc request, %@", __FUNCTION__, error); |
| 176 | + } |
| 177 | + |
| 178 | + return encodedData; |
| 179 | +} |
| 180 | + |
| 181 | +- (NSURLRequest *)healthCheckRequest { |
| 182 | + NSString *queryString = [CountlyConnectionManager.sharedInstance queryEssentials]; |
| 183 | + |
| 184 | + queryString = [queryString stringByAppendingFormat:@"&%@=%@", @"hc", [self dictionaryToJsonString:@{ |
| 185 | + requestKeyErrorCount: @(self.countLogError), |
| 186 | + requestKeyWarningCount: @(self.countLogWarning), |
| 187 | + requestKeyStatusCode: @(self.statusCode), |
| 188 | + requestKeyRequestError: self.errorMessage ?: @"", |
| 189 | + requestKeyBackoffRequest: @(self.countBackoffRequest) |
| 190 | + }]]; |
| 191 | + |
| 192 | + queryString = [queryString stringByAppendingFormat:@"&%@=%@", @"metrics", [self dictionaryToJsonString:@{ |
| 193 | + kCountlyAppVersionKey: CountlyDeviceInfo.appVersion |
| 194 | + }]]; |
| 195 | + |
| 196 | + queryString = [CountlyConnectionManager.sharedInstance appendChecksum:queryString]; |
| 197 | + NSString* hcSendURL = [CountlyConnectionManager.sharedInstance.host stringByAppendingFormat:@"%@",kCountlyEndpointI]; |
| 198 | + |
| 199 | + CLY_LOG_D(@"%s, generated health check request: %@", __FUNCTION__, queryString); |
| 200 | + |
| 201 | + if (queryString.length > kCountlyGETRequestMaxLength || CountlyConnectionManager.sharedInstance.alwaysUsePOST) |
| 202 | + { |
| 203 | + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:hcSendURL]]; |
| 204 | + request.HTTPMethod = @"POST"; |
| 205 | + request.HTTPBody = [queryString cly_dataUTF8]; |
| 206 | + return request.copy; |
| 207 | + } |
| 208 | + else |
| 209 | + { |
| 210 | + NSString* withQueryString = [hcSendURL stringByAppendingFormat:@"?%@", queryString]; |
| 211 | + NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:withQueryString]]; |
| 212 | + return request; |
| 213 | + } |
| 214 | +} |
| 215 | +@end |
0 commit comments