forked from getsentry/sentry-cocoa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSentryCoreDataTracker.m
More file actions
227 lines (186 loc) · 8.55 KB
/
SentryCoreDataTracker.m
File metadata and controls
227 lines (186 loc) · 8.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#import "SentryCoreDataTracker.h"
#import "SentryDefaultThreadInspector.h"
#import "SentryFrame.h"
#import "SentryHub+Private.h"
#import "SentryInternalDefines.h"
#import "SentryLogC.h"
#import "SentryPredicateDescriptor.h"
#import "SentrySDK+Private.h"
#import "SentryScope+Private.h"
#import "SentrySpan.h"
#import "SentrySpanOperation.h"
#import "SentrySpanProtocol.h"
#import "SentryStacktrace.h"
#import "SentrySwift.h"
#import "SentryTraceOrigin.h"
@implementation SentryCoreDataTracker {
SentryPredicateDescriptor *predicateDescriptor;
SentryDefaultThreadInspector *_threadInspector;
id<SentryProcessInfoSource> _processInfoWrapper;
}
- (instancetype)initWithThreadInspector:(SentryDefaultThreadInspector *)threadInspector
processInfoWrapper:(id<SentryProcessInfoSource>)processInfoWrapper;
{
if (self = [super init]) {
predicateDescriptor = [[SentryPredicateDescriptor alloc] init];
_threadInspector = threadInspector;
_processInfoWrapper = processInfoWrapper;
}
return self;
}
- (NSArray *)managedObjectContext:(NSManagedObjectContext *)context
executeFetchRequest:(NSFetchRequest *)request
error:(NSError **)error
originalImp:(NSArray *(NS_NOESCAPE ^)(NSFetchRequest *, NSError **))original
{
id<SentrySpan> _Nullable currentSpan = [SentrySDKInternal.currentHub.scope span];
id<SentrySpan> _Nullable fetchSpan;
if (currentSpan) {
NSString *spanDescription = [self descriptionFromRequest:request];
fetchSpan = [currentSpan startChildWithOperation:SentrySpanOperationCoredataFetchOperation
description:spanDescription];
}
if (fetchSpan) {
fetchSpan.origin = SentryTraceOriginAutoDBCoreData;
SENTRY_LOG_DEBUG(@"SentryCoreDataTracker automatically started a new span with "
@"description: %@, operation: %@, origin: %@",
fetchSpan.description, fetchSpan.operation, fetchSpan.origin);
}
NSArray *result = original(request, error);
if (fetchSpan) {
[self addExtraInfoToSpan:(SentrySpan *)fetchSpan withContext:context];
[fetchSpan setDataValue:[NSNumber numberWithInteger:result.count] forKey:@"read_count"];
[fetchSpan
finishWithStatus:result == nil ? kSentrySpanStatusInternalError : kSentrySpanStatusOk];
SENTRY_LOG_DEBUG(@"SentryCoreDataTracker automatically finished span with status: %@",
result == nil ? @"error" : @"ok");
}
return result;
}
- (BOOL)managedObjectContext:(NSManagedObjectContext *)context
save:(NSError **)error
originalImp:(BOOL(NS_NOESCAPE ^)(NSError **))original
{
__block id<SentrySpan> _Nullable saveSpan = nil;
if (context.hasChanges) {
__block NSDictionary<NSString *, NSDictionary *> *operations =
[self groupEntitiesOperations:context];
id<SentrySpan> _Nullable currentSpan = [SentrySDKInternal.currentHub.scope span];
if (currentSpan) {
NSString *spanDescription = [self descriptionForOperations:operations
inContext:context];
saveSpan = [currentSpan startChildWithOperation:SentrySpanOperationCoredataSaveOperation
description:spanDescription];
}
if (saveSpan) {
saveSpan.origin = SentryTraceOriginAutoDBCoreData;
SENTRY_LOG_DEBUG(@"SentryCoreDataTracker automatically started a new span with "
@"description: %@, operation: %@, origin: %@",
saveSpan.description, saveSpan.operation, saveSpan.origin);
[saveSpan setDataValue:operations forKey:@"operations"];
} else {
SENTRY_LOG_ERROR(@"managedObjectContext:save:originalImp: saveSpan is nil");
}
}
BOOL result = original(error);
if (saveSpan) {
[self addExtraInfoToSpan:(SentrySpan *)saveSpan withContext:context];
[saveSpan finishWithStatus:result ? kSentrySpanStatusOk : kSentrySpanStatusInternalError];
SENTRY_LOG_DEBUG(@"SentryCoreDataTracker automatically finished span with status: %@",
result ? @"ok" : @"error");
}
return result;
}
- (void)addExtraInfoToSpan:(SentrySpan *)span withContext:(NSManagedObjectContext *)context
{
BOOL isMainThread = [NSThread isMainThread];
[span setDataValue:@(isMainThread) forKey:SPAN_DATA_BLOCKED_MAIN_THREAD];
NSMutableArray<NSString *> *systems = [NSMutableArray<NSString *> array];
NSMutableArray<NSString *> *names = [NSMutableArray<NSString *> array];
[context.persistentStoreCoordinator.persistentStores enumerateObjectsUsingBlock:^(
__kindof NSPersistentStore *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
[systems addObject:obj.type];
if (obj.URL != nil) {
[names addObject:SENTRY_UNWRAP_NULLABLE(NSString, obj.URL.path)];
} else {
[names addObject:@"(null)"];
}
}];
[span setDataValue:[systems componentsJoinedByString:@";"] forKey:@"db.system"];
[span setDataValue:[names componentsJoinedByString:@";"] forKey:@"db.name"];
if (!isMainThread) {
return;
}
SentryStacktrace *stackTrace = [_threadInspector stacktraceForCurrentThreadAsyncUnsafe];
[span setFrames:stackTrace.frames];
}
- (NSString *)descriptionForOperations:
(NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)operations
inContext:(NSManagedObjectContext *)context
{
__block NSMutableArray *resultParts = [NSMutableArray new];
void (^operationInfo)(NSUInteger, NSString *) = ^void(NSUInteger total, NSString *op) {
NSDictionary *items = operations[op];
if (items && items.count > 0) {
if (items.count == 1) {
[resultParts addObject:[NSString stringWithFormat:@"%@ %@ '%@'", op,
items.allValues[0], items.allKeys[0]]];
} else {
[resultParts addObject:[NSString stringWithFormat:@"%@ %lu items", op,
(unsigned long)total]];
}
}
};
operationInfo(context.insertedObjects.count, @"INSERTED");
operationInfo(context.updatedObjects.count, @"UPDATED");
operationInfo(context.deletedObjects.count, @"DELETED");
return [resultParts componentsJoinedByString:@", "];
}
- (NSDictionary<NSString *, NSDictionary *> *)groupEntitiesOperations:
(NSManagedObjectContext *)context
{
NSMutableDictionary<NSString *, NSDictionary *> *operations =
[[NSMutableDictionary alloc] initWithCapacity:3];
if (context.insertedObjects.count > 0)
[operations setValue:[self countEntities:context.insertedObjects] forKey:@"INSERTED"];
if (context.updatedObjects.count > 0)
[operations setValue:[self countEntities:context.updatedObjects] forKey:@"UPDATED"];
if (context.deletedObjects.count > 0)
[operations setValue:[self countEntities:context.deletedObjects] forKey:@"DELETED"];
return operations;
}
- (NSDictionary<NSString *, NSNumber *> *)countEntities:(NSSet *)entities
{
NSMutableDictionary<NSString *, NSNumber *> *result = [NSMutableDictionary new];
for (id item in entities) {
NSString *cl
= ((NSManagedObject *)item).entity.name ?: [SwiftDescriptor getObjectClassName:item];
NSNumber *count = result[cl];
result[cl] = [NSNumber numberWithInt:count.intValue + 1];
}
return result;
}
- (NSString *)descriptionFromRequest:(NSFetchRequest *)request
{
NSMutableString *result =
[[NSMutableString alloc] initWithFormat:@"SELECT '%@'", request.entityName];
if (request.predicate) {
[result appendFormat:@" WHERE %@",
[predicateDescriptor
predicateDescription:SENTRY_UNWRAP_NULLABLE(NSPredicate, request.predicate)]];
}
if (request.sortDescriptors.count > 0) {
[result appendFormat:@" SORT BY %@", [self sortDescription:request.sortDescriptors]];
}
return result;
}
- (NSString *)sortDescription:(NSArray<NSSortDescriptor *> *)sortList
{
NSMutableArray<NSString *> *fields = [[NSMutableArray alloc] initWithCapacity:sortList.count];
for (NSSortDescriptor *descriptor in sortList) {
NSString *direction = descriptor.ascending ? @"" : @" DESCENDING";
[fields addObject:[NSString stringWithFormat:@"%@%@", descriptor.key, direction]];
}
return [fields componentsJoinedByString:@", "];
}
@end