文件
dayu-color/大鱼调色/Shared/DYBetaDiagnostics.mm
T

317 行
28 KiB
Plaintext

#import "DYBetaDiagnostics.h"
#import <AppKit/AppKit.h>
#include <atomic>
#include <cmath>
#include <sys/sysctl.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <libproc.h>
#include <sys/resource.h>
NSString *const DYBetaDiagnosticsChanged = @"DYBetaDiagnosticsChanged";
static NSString *const DYBetaPreferenceDomain = @"com.dayu.color.preferences";
static std::atomic_bool gEnabled(true);
static std::atomic_uint_fast64_t gSpan(0);
static std::atomic<double> gMainReply(0);
static NSObject *gSpanLock, *gStatusLock;
static NSMutableDictionary *gActive, *gMetrics;
static void mainPulse(CFRunLoopTimerRef timer,void *context){gMainReply.store(NSProcessInfo.processInfo.systemUptime);}
static NSDictionary *gStatus;
static BOOL gProduct;
BOOL DYBetaAllowedURL(NSURL *url, BOOL download) {
if (![url.scheme.lowercaseString isEqual:@"https"] || ![url.host.lowercaseString isEqual:@"dayu.media"] ||
url.user.length || url.password.length || (url.port && url.port.integerValue!=443)) return NO;
NSString *prefix=download?@"/wp-content/uploads/dayu-color-beta/updates/":@"/wp-json/dayu-color/v1/";
return [url.path hasPrefix:prefix] && ![url.path.pathComponents containsObject:@".."];
}
NSDictionary *DYBetaSafeFields(NSDictionary *fields) {
static NSSet *allowed; static dispatch_once_t once;
dispatch_once(&once,^{allowed=[[NSSet alloc]initWithArray:@[@"phase",@"stage",@"pipeline",@"duration_ms",@"status",@"error_domain",@"error_code",@"exception",@"signal",@"frames",@"report_time",@"count",@"pending",@"model",@"os_version",@"fcp_version",@"cpu_cores",@"memory_gb",@"gpu",@"main_delay_ms",@"active_stages",@"source_version",@"source_build",@"process_role",@"termination_namespace",@"termination_code",@"pid",@"resource_kind",@"memory_mb",@"cpu_percent",@"thread_count",@"uptime_s",@"max_duration_ms",@"average_ms",@"width",@"height",@"layer_count",@"mask_count",@"sample_status"]];});
NSMutableDictionary *out=[NSMutableDictionary dictionary];
if(![fields isKindOfClass:NSDictionary.class])return @{};
for (NSString *key in fields) {
if (![allowed containsObject:key]) continue;
id value=fields[key];
if ([value isKindOfClass:NSNumber.class]) { if (std::isfinite([value doubleValue])) out[key]=value; continue; }
if (![value isKindOfClass:NSString.class]) continue;
NSString *text=value;
for (NSString *pattern in @[@"(?:https?://\\S+|(?:/Users/|/Volumes/|/private/|/var/)[^\\r\\n]*)",@"(?i)(?:bearer\\s+\\S+|(?:token|api[_-]?key|secret|password)\\s*[=:]\\s*\\S+)"])
text=[text stringByReplacingOccurrencesOfString:pattern withString:@"[REDACTED]" options:NSRegularExpressionSearch range:NSMakeRange(0,text.length)];
NSUInteger limit=[key isEqual:@"frames"]?6000:[key isEqual:@"active_stages"]?1000:200;
out[key]=text.length>limit?[text substringToIndex:limit]:text;
}
return out;
}
#include "DYBetaEvidence.inc.h"
@interface DYBetaTransport : NSObject <NSURLSessionTaskDelegate> {
@public
dispatch_queue_t queue, evidenceQueue;
dispatch_source_t timer;
NSMutableArray *pending;
NSMutableSet *seenCrashes;
NSMutableDictionary *lastEvents;
NSURLSession *session;
NSURLSessionDataTask *sending;
NSString *sessionID, *installationID, *source, *version;
NSNumber *build;
NSURL *folder, *journal;
NSDictionary *environment;
NSTimeInterval nextAttempt, lastTick, lastStall, lastMaintenance, lastSample, sampleWindow, previousCPU, previousResourceTime, startedAt;
NSUInteger sampleCount;
BOOL sampling;
BOOL ready;
}
- (void)enqueue:(NSString *)event fields:(NSDictionary *)fields;
- (void)drain;
- (void)persist;
- (void)scanCrashSummaries;
- (NSUInteger)recoverPending;
- (NSDictionary *)resources:(double)now;
- (void)captureSample:(NSString *)stage;
@end
static DYBetaTransport *transport;
static void publishStatus(NSDictionary *values) {
@synchronized(gStatusLock) { [gStatus release]; gStatus=[values copy]; }
dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYBetaDiagnosticsChanged object:nil];});
}
static NSDictionary *statusSnapshot(void) { @synchronized(gStatusLock) { return [[gStatus copy]autorelease]?:@{}; } }
static NSUserDefaults *preferences(void) { return [[[NSUserDefaults alloc]initWithSuiteName:DYBetaPreferenceDomain]autorelease]; }
static NSString *sysctlString(const char *key) {
char buffer[256]={};size_t size=sizeof(buffer);if(sysctlbyname(key,buffer,&size,NULL,0))return @"unknown";
return [NSString stringWithUTF8String:buffer]?:@"unknown";
}
@implementation DYBetaTransport
- (instancetype)init {
if((self=[super init])) {
queue=dispatch_queue_create("com.dayu.color.beta-diagnostics",DISPATCH_QUEUE_SERIAL);
evidenceQueue=dispatch_queue_create("com.dayu.color.beta-evidence",DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(evidenceQueue,dispatch_get_global_queue(QOS_CLASS_UTILITY,0));
pending=[NSMutableArray new];seenCrashes=[NSMutableSet new];lastEvents=[NSMutableDictionary new];sessionID=[NSUUID.UUID.UUIDString.lowercaseString copy];
source=[([NSBundle.mainBundle.bundleIdentifier isEqual:@"com.dayu.color.XPC"]?@"plugin":@"app")copy];
version=[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]copy];build=@([[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue]);[build retain];
dispatch_async(queue,^{@autoreleasepool{[self prepare];}});
}return self;
}
- (void)prepare {
NSUserDefaults *prefs=preferences();[prefs registerDefaults:@{@"betaDiagnosticsEnabled":@YES}];gEnabled.store([prefs boolForKey:@"betaDiagnosticsEnabled"]);
folder=[[[NSFileManager.defaultManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask].firstObject URLByAppendingPathComponent:@"com.dayu.color/Beta" isDirectory:YES]retain];
[NSFileManager.defaultManager createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions:@0700} error:nil];
// O_EXCL gives the APP and XPC one random installation ID without hardware UUIDs.
NSURL *identity=[folder URLByAppendingPathComponent:@"installation.txt"];
NSString *newID=NSUUID.UUID.UUIDString.lowercaseString;
int fd=open(identity.fileSystemRepresentation,O_WRONLY|O_CREAT|O_EXCL,0600);
if(fd>=0){NSData *data=[newID dataUsingEncoding:NSUTF8StringEncoding];write(fd,data.bytes,data.length);close(fd);}
for(int attempt=0;attempt<20;attempt++) {
[installationID release];installationID=[[[NSString stringWithContentsOfURL:identity encoding:NSUTF8StringEncoding error:nil]stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]copy];
if([[[NSUUID alloc]initWithUUIDString:installationID]autorelease])break;
[NSThread sleepForTimeInterval:.01];
}
if(![[[NSUUID alloc]initWithUUIDString:installationID]autorelease]){gEnabled.store(false);return;}
NSURLSessionConfiguration *config=NSURLSessionConfiguration.ephemeralSessionConfiguration;
config.timeoutIntervalForRequest=8;config.timeoutIntervalForResource=12;config.HTTPShouldSetCookies=NO;config.URLCache=nil;
session=[[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]retain];
uint64_t memory=0;size_t length=sizeof(memory);sysctlbyname("hw.memsize",&memory,&length,NULL,0);
NSString *fcp=@"not-installed";
for(NSString *ID in @[@"com.apple.FinalCut",@"com.apple.FinalCutApp"]){NSURL *url=[NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:ID];if(url){fcp=[[NSBundle bundleWithURL:url]objectForInfoDictionaryKey:@"CFBundleShortVersionString"]?:@"unknown";break;}}
environment=[@{@"model":sysctlString("hw.model"),@"os_version":NSProcessInfo.processInfo.operatingSystemVersionString,@"fcp_version":fcp,@"cpu_cores":@(NSProcessInfo.processInfo.processorCount),@"memory_gb":@(double(memory)/(1024*1024*1024))}copy];
journal=[[folder URLByAppendingPathComponent:[NSString stringWithFormat:@"pending-%d-%@.json",getpid(),sessionID]]retain];
NSArray *seen=[NSArray arrayWithContentsOfURL:[folder URLByAppendingPathComponent:@"seen-crashes.plist"]];
for(id key in seen)if([key isKindOfClass:NSString.class]&&[[[NSUUID alloc]initWithUUIDString:key]autorelease])[seenCrashes addObject:key];
NSUInteger recovered=[self recoverPending];
ready=YES;gMainReply.store(NSProcessInfo.processInfo.systemUptime);lastTick=gMainReply.load();startedAt=lastTick;
NSMutableDictionary *start=[[environment mutableCopy]autorelease];start[@"pid"]=@(getpid());[self enqueue:@"process_start" fields:start];if(recovered)[self enqueue:@"previous_session_pending" fields:@{@"count":@(recovered)}];
publishStatus(@{@"installation_id":installationID,@"enabled":@(gEnabled.load()),@"pending":@(pending.count)});
timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
dispatch_source_set_timer(timer,dispatch_time(DISPATCH_TIME_NOW,2*NSEC_PER_SEC),3*NSEC_PER_SEC,NSEC_PER_SEC/4);
dispatch_source_set_event_handler(timer,^{@autoreleasepool{[self tick];}});dispatch_resume(timer);
[NSDistributedNotificationCenter.defaultCenter addObserver:self selector:@selector(settingsChanged:) name:@"com.dayu.color.beta.preferences" object:nil];
if([source isEqual:@"app"])[self scanCrashSummaries];
}
- (NSUInteger)recoverPending {
NSArray *files=[NSFileManager.defaultManager contentsOfDirectoryAtURL:folder includingPropertiesForKeys:@[NSURLContentModificationDateKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
NSUInteger recovered=0;
for(NSURL *url in files){if(![url.lastPathComponent hasPrefix:@"pending-"]||![url.pathExtension isEqual:@"json"])continue;
NSNumber *bytes=nil;[url getResourceValue:&bytes forKey:NSURLFileSizeKey error:nil];if(bytes.unsignedLongLongValue>384*1024)continue;
NSDictionary *old=[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:url]?:[NSData data] options:0 error:nil];if(![old isKindOfClass:NSDictionary.class])continue;
if(![old[@"pid"]isKindOfClass:NSNumber.class])continue;int pid=[old[@"pid"]intValue];if(pid==getpid()||pid<=0||kill(pid,0)==0||errno!=ESRCH)continue;
NSDate *date=nil;[url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil];
if(gEnabled.load()&&date.timeIntervalSinceNow> -7*86400&&[old[@"events"]isKindOfClass:NSArray.class])for(NSDictionary *event in old[@"events"]){if(pending.count>=256)break;
if(![event isKindOfClass:NSDictionary.class]||![event[@"event_id"]isKindOfClass:NSString.class]||![event[@"session_id"]isKindOfClass:NSString.class]||
![[[NSUUID alloc]initWithUUIDString:event[@"event_id"]]autorelease]||![[[NSUUID alloc]initWithUUIDString:event[@"session_id"]]autorelease]||
![event[@"version"]isKindOfClass:NSString.class]||![event[@"build"]isKindOfClass:NSNumber.class]||![event[@"event"]isKindOfClass:NSString.class]||
![@[@"app",@"plugin"]containsObject:event[@"source"]]||![event[@"fields"]isKindOfClass:NSDictionary.class]||![event[@"occurred_at"]isKindOfClass:NSNumber.class])continue;
NSMutableDictionary *safe=[[event mutableCopy]autorelease];safe[@"fields"]=DYBetaSafeFields(event[@"fields"]);[pending addObject:safe];recovered++;}
[NSFileManager.defaultManager removeItemAtURL:url error:nil];
}
return recovered;
}
- (void)enqueue:(NSString *)event fields:(NSDictionary *)fields {
if(!ready||!gEnabled.load())return;
// A bad render must not turn diagnostics into per-frame disk writes.
if([@[@"render_error",@"inspector_refresh",@"render",@"plugin_state",@"tracking_frame"]containsObject:event]){
double now=NSProcessInfo.processInfo.systemUptime;if(now-[lastEvents[event]doubleValue]<([event isEqual:@"render_error"]?5:30))return;lastEvents[event]=@(now);
}
if(pending.count>=256)[pending removeObjectsInRange:NSMakeRange(0,32)];
NSMutableDictionary *context=[[DYBetaSafeFields(fields?:@{})mutableCopy]autorelease];if(!context[@"pid"])context[@"pid"]=@(getpid());
if([NSProcessInfo.processInfo.arguments containsObject:@"--diagnostics-probe"])context[@"phase"]=@"verification";
[pending addObject:@{@"event_id":NSUUID.UUID.UUIDString.lowercaseString,@"session_id":sessionID,@"source":source,@"version":version?:@"0.0",@"build":build?:@1,@"event":event,@"occurred_at":@(NSDate.date.timeIntervalSince1970),@"fields":context}];
[self persist];
}
- (void)persist {
if(!journal)return;
NSData *data=[NSJSONSerialization dataWithJSONObject:@{@"pid":@(getpid()),@"events":pending} options:0 error:nil];
while(data.length>384*1024&&pending.count>1){[pending removeObjectAtIndex:0];data=[NSJSONSerialization dataWithJSONObject:@{@"pid":@(getpid()),@"events":pending} options:0 error:nil];}
[data writeToURL:journal options:NSDataWritingAtomic error:nil];chmod(journal.fileSystemRepresentation,0600);
}
- (void)drain {
if(!ready||!gEnabled.load()||sending||!pending.count||NSDate.date.timeIntervalSince1970<nextAttempt)return;
NSArray *batch=[[pending subarrayWithRange:NSMakeRange(0,MIN((NSUInteger)16,pending.count))]copy];
NSData *data=[NSJSONSerialization dataWithJSONObject:@{@"bundle_id":@"com.dayu.color",@"installation_id":installationID,@"events":batch} options:0 error:nil];
while(data.length>98304&&batch.count>1){NSArray *smaller=[[batch subarrayWithRange:NSMakeRange(0,batch.count-1)]copy];[batch release];batch=smaller;data=[NSJSONSerialization dataWithJSONObject:@{@"bundle_id":@"com.dayu.color",@"installation_id":installationID,@"events":batch} options:0 error:nil];}
if(!data||data.length>98304){[pending removeObjectAtIndex:0];[batch release];[self persist];return;}
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://dayu.media/wp-json/dayu-color/v1/diagnostics"]];request.HTTPMethod=@"POST";request.HTTPBody=data;[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
sending=[[session dataTaskWithRequest:request completionHandler:^(NSData *body,NSURLResponse *response,NSError *error){
dispatch_async(self->queue,^{@autoreleasepool{
NSDictionary *reply=body?[NSJSONSerialization JSONObjectWithData:body options:0 error:nil]:nil;if(![reply isKindOfClass:NSDictionary.class])reply=nil;
NSSet *accepted=[reply[@"event_ids"]isKindOfClass:NSArray.class]?[NSSet setWithArray:reply[@"event_ids"]]:[NSSet set];
NSSet *expected=[NSSet setWithArray:[batch valueForKey:@"event_id"]];
BOOL ok=!error&&[(NSHTTPURLResponse*)response statusCode]==200&&[reply[@"accepted"]isKindOfClass:NSNumber.class]&&[reply[@"accepted"]boolValue]&&[accepted isEqualToSet:expected];
if(ok){
BOOL acknowledgedCrash=NO;
for(NSDictionary *event in batch)if([event[@"event"]isEqual:@"crash_summary"]){[self->seenCrashes addObject:event[@"event_id"]];acknowledgedCrash=YES;}
if(acknowledgedCrash){NSArray *seen=self->seenCrashes.allObjects;if(seen.count>1024){seen=[seen subarrayWithRange:NSMakeRange(seen.count-1024,1024)];[self->seenCrashes setSet:[NSSet setWithArray:seen]];}
NSURL *seenURL=[self->folder URLByAppendingPathComponent:@"seen-crashes.plist"];[seen writeToURL:seenURL atomically:YES];chmod(seenURL.fileSystemRepresentation,0600);}
NSIndexSet *remove=[self->pending indexesOfObjectsPassingTest:^BOOL(NSDictionary *event,NSUInteger i,BOOL *stop){return [accepted containsObject:event[@"event_id"]];}];[self->pending removeObjectsAtIndexes:remove];self->nextAttempt=0;
publishStatus(@{@"installation_id":self->installationID,@"enabled":@(gEnabled.load()),@"pending":@(self->pending.count),@"last_upload":@([NSDate.date timeIntervalSince1970])});
}else self->nextAttempt=NSDate.date.timeIntervalSince1970+30;
[self->sending release];self->sending=nil;[batch release];[self persist];
}});
}]retain];[sending resume];
}
- (NSDictionary *)resources:(double)now {
struct proc_taskinfo info={};NSMutableDictionary *result=[NSMutableDictionary dictionaryWithDictionary:@{@"pid":@(getpid()),@"uptime_s":@(now-startedAt)}];
if(proc_pidinfo(getpid(),PROC_PIDTASKINFO,0,&info,sizeof(info))==sizeof(info)) {
result[@"memory_mb"]=@(double(info.pti_resident_size)/(1024*1024));result[@"thread_count"]=@(info.pti_threadnum);
double cpu=(info.pti_total_user+info.pti_total_system)/1e9;
if(previousResourceTime>0&&now>previousResourceTime)result[@"cpu_percent"]=@(MAX(0.,(cpu-previousCPU)/(now-previousResourceTime)*100));
previousCPU=cpu;previousResourceTime=now;
}return result;
}
- (void)captureSample:(NSString *)stage {
double now=NSProcessInfo.processInfo.systemUptime;
if(sampling||now-lastSample<120)return;
if(now-sampleWindow>3600){sampleWindow=now;sampleCount=0;}if(sampleCount>=6)return;
sampling=YES;lastSample=now;sampleCount++;
dispatch_async(evidenceQueue,^{@autoreleasepool{
NSURL *output=[self->folder URLByAppendingPathComponent:[@"sample-" stringByAppendingString:NSUUID.UUID.UUIDString]];
NSTask *task=[[[NSTask alloc]init]autorelease];task.executableURL=[NSURL fileURLWithPath:@"/usr/bin/sample"];
task.arguments=@[[@(getpid())stringValue],@"1",@"10",@"-mayDie",@"-file",output.path];
task.standardOutput=[NSFileHandle fileHandleWithNullDevice];task.standardError=[NSFileHandle fileHandleWithNullDevice];
NSString *result=@"unavailable",*frames=@"";NSError *error=nil;
if(gEnabled.load()&&[task launchAndReturnError:&error]) {
double deadline=NSProcessInfo.processInfo.systemUptime+8;
while(task.running&&gEnabled.load()&&NSProcessInfo.processInfo.systemUptime<deadline)[NSThread sleepForTimeInterval:.05];
if(task.running){[task terminate];[NSThread sleepForTimeInterval:.1];if(task.running)kill(task.processIdentifier,SIGKILL);result=@"timeout_or_disabled";}
else if(task.terminationStatus==0){NSNumber *size=nil;[output getResourceValue:&size forKey:NSURLFileSizeKey error:nil];if(size.unsignedLongLongValue<=4*1024*1024)frames=DYBetaSampleFrames([NSString stringWithContentsOfURL:output encoding:NSUTF8StringEncoding error:nil]);result=frames.length?@"captured":@"no_frames";}
}
[NSFileManager.defaultManager removeItemAtURL:output error:nil];
dispatch_async(self->queue,^{@autoreleasepool{self->sampling=NO;[self enqueue:@"hang_sample" fields:@{@"stage":stage,@"sample_status":result,@"frames":frames,@"pid":@(getpid())}];[self drain];}});
}});
}
- (void)tick {
double now=NSProcessInfo.processInfo.systemUptime;
BOOL suspended=now-lastTick>15;lastTick=now;
if(suspended)gMainReply.store(now); // Sleep/wake or process suspension isn't a measured hang.
if(gEnabled.load()) {
NSString *stages=[self activeStages:now];double delay=now-gMainReply.load();
if((delay>6||stages.length)&&now-lastStall>30){lastStall=now;NSMutableDictionary *fields=[[[self resources:now]mutableCopy]autorelease];
fields[@"status"]=@"suspected";fields[@"main_delay_ms"]=@(delay*1000);fields[@"active_stages"]=stages;
NSString *event=delay>6?@"main_thread_stall":@"operation_stall";[self enqueue:event fields:fields];[self captureSample:event];
}
if(now-lastMaintenance>=60){lastMaintenance=now;
[self enqueue:@"process_health" fields:[self resources:now]];
NSDictionary *metrics;@synchronized(gSpanLock){metrics=[[gMetrics copy]autorelease];[gMetrics removeAllObjects];}
for(NSString *stage in metrics){NSMutableDictionary *fields=[[metrics[stage]mutableCopy]autorelease];fields[@"stage"]=stage;fields[@"average_ms"]=@([fields[@"duration_ms"]doubleValue]/MAX(1,[fields[@"count"]integerValue]));[self enqueue:@"performance_summary" fields:fields];}
if([source isEqual:@"app"]){NSUInteger recovered=[self recoverPending];if(recovered)[self enqueue:@"previous_session_pending" fields:@{@"count":@(recovered)}];[self scanCrashSummaries];}
}
}
[self drain];
}
- (NSString *)activeStages:(double)now {
NSArray *values;@synchronized(gSpanLock){values=[[gActive.allValues copy]autorelease];}
NSMutableArray *slow=[NSMutableArray array];for(NSDictionary *span in values)if(now-[span[@"start"]doubleValue]>6)[slow addObject:[NSString stringWithFormat:@"%@: %.0fms",span[@"stage"],(now-[span[@"start"]doubleValue])*1000]];
return [slow componentsJoinedByString:@"; "];
}
- (void)settingsChanged:(NSNotification *)note {
dispatch_async(queue,^{@autoreleasepool{NSUserDefaults *prefs=preferences();[prefs synchronize];gEnabled.store([prefs objectForKey:@"betaDiagnosticsEnabled"]?[prefs boolForKey:@"betaDiagnosticsEnabled"]:YES);
if(!gEnabled.load()){[self->sending cancel];[self->pending removeAllObjects];[self persist];@synchronized(gSpanLock){[gActive removeAllObjects];[gMetrics removeAllObjects];}}
publishStatus(@{@"installation_id":self->installationID?:@"",@"enabled":@(gEnabled.load()),@"pending":@(self->pending.count)});
}});
}
- (void)URLSession:(NSURLSession *)s task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler {
completionHandler(DYBetaAllowedURL(request.URL,NO)?request:nil);
}
- (void)scanCrashSummaries {
if(!gEnabled.load()||![source isEqual:@"app"])return;
NSURL *reports=[NSFileManager.defaultManager.homeDirectoryForCurrentUser URLByAppendingPathComponent:@"Library/Logs/DiagnosticReports"];
NSArray *files=[NSFileManager.defaultManager contentsOfDirectoryAtURL:reports includingPropertiesForKeys:@[NSURLContentModificationDateKey,NSURLFileSizeKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
files=[files sortedArrayUsingComparator:^NSComparisonResult(NSURL *a,NSURL *b){NSDate *ad=nil,*bd=nil;[a getResourceValue:&ad forKey:NSURLContentModificationDateKey error:nil];[b getResourceValue:&bd forKey:NSURLContentModificationDateKey error:nil];return [(bd?:NSDate.distantPast) compare:ad?:NSDate.distantPast];}];
NSUInteger count=0,examined=0;
NSMutableSet *queued=[NSMutableSet setWithArray:[pending valueForKey:@"event_id"]];
for(NSURL *url in files){if(count>=12||examined++>=512||pending.count>=240)break;
if(![url.pathExtension isEqual:@"ips"]||![url.lastPathComponent hasPrefix:@"大鱼调色"])continue;
NSNumber *size=nil;[url getResourceValue:&size forKey:NSURLFileSizeKey error:nil];if(size.unsignedLongLongValue>8*1024*1024)continue;
NSDate *date=nil;[url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil];if(!date||date.timeIntervalSinceNow< -7*86400)continue;
NSData *data=[NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:nil];if(!data.length)continue;
NSString *text=[[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease];if(!text)continue;
NSRange newline=[text rangeOfString:@"\n"];if(newline.location==NSNotFound)continue;
NSDictionary *header=DYBetaDictionary([NSJSONSerialization JSONObjectWithData:[[text substringToIndex:newline.location]dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]);
NSString *key=DYBetaString(header[@"incident_id"]).lowercaseString;
if(![[[NSUUID alloc]initWithUUIDString:key]autorelease]||[seenCrashes containsObject:key]||[queued containsObject:key])continue;
NSDictionary *body=DYBetaDictionary([NSJSONSerialization JSONObjectWithData:[[text substringFromIndex:newline.location+1]dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]);
if(!body.count)continue;NSDictionary *fields=DYBetaCrashEvidence(header,body);if(!fields)continue;
NSUInteger before=pending.count;[self enqueue:@"crash_summary" fields:fields];
if(pending.count==before+1){NSMutableDictionary *event=[[pending.lastObject mutableCopy]autorelease];event[@"event_id"]=key;[pending replaceObjectAtIndex:pending.count-1 withObject:event];[queued addObject:key];[self persist];count++;}
}
}
@end
void DYBetaStart(void) {
static dispatch_once_t once;dispatch_once(&once,^{
NSString *ID=NSBundle.mainBundle.bundleIdentifier;
gProduct=([ID isEqual:@"com.dayu.color"]||[ID isEqual:@"com.dayu.color.XPC"])&&![NSProcessInfo.processInfo.arguments containsObject:@"--self-test"];
gSpanLock=[NSObject new];gStatusLock=[NSObject new];gActive=[NSMutableDictionary new];gMetrics=[NSMutableDictionary new];
if(gProduct){
NSUserDefaults *prefs=preferences();gEnabled.store([prefs objectForKey:@"betaDiagnosticsEnabled"]?[prefs boolForKey:@"betaDiagnosticsEnabled"]:YES);
gMainReply.store(NSProcessInfo.processInfo.systemUptime);
// Common modes continue to pulse while menus / file panels run nested loops.
CFRunLoopTimerRef pulse=CFRunLoopTimerCreate(NULL,CFAbsoluteTimeGetCurrent()+1,1,0,0,mainPulse,NULL);
CFRunLoopAddTimer(CFRunLoopGetMain(),pulse,kCFRunLoopCommonModes);CFRelease(pulse);
transport=[DYBetaTransport new];
}
});
}
BOOL DYBetaEnabled(void){DYBetaStart();return gEnabled.load();}
void DYBetaSetEnabled(BOOL enabled){DYBetaStart();gEnabled.store(enabled);NSUserDefaults *prefs=preferences();[prefs setBool:enabled forKey:@"betaDiagnosticsEnabled"];[prefs synchronize];[NSDistributedNotificationCenter.defaultCenter postNotificationName:@"com.dayu.color.beta.preferences" object:nil userInfo:nil deliverImmediately:YES];}
NSDictionary *DYBetaStatus(void){DYBetaStart();return statusSnapshot();}
void DYBetaEvent(NSString *event,NSDictionary *fields){DYBetaStart();if(!gProduct||!gEnabled.load())return;NSDictionary *safe=DYBetaSafeFields(fields?:@{});dispatch_async(transport->queue,^{@autoreleasepool{[transport enqueue:event fields:safe];}});}
uint64_t DYBetaSpanBegin(NSString *stage,NSDictionary *fields){DYBetaStart();if(!gProduct||!gEnabled.load())return 0;uint64_t token=++gSpan;NSDictionary *value=@{@"stage":stage,@"start":@(NSProcessInfo.processInfo.systemUptime),@"fields":DYBetaSafeFields(fields?:@{})};@synchronized(gSpanLock){if(gActive.count>=128)return 0;gActive[@(token)]=value;}
if(![@[@"inspector_refresh",@"render",@"tracking_frame",@"plugin_state"]containsObject:stage]){NSMutableDictionary *begin=[[value[@"fields"]mutableCopy]autorelease];begin[@"phase"]=@"begin";DYBetaEvent(stage,begin);}return token;
}
void DYBetaSpanEnd(uint64_t token,NSDictionary *fields){
if(!token)return;NSDictionary *span;
@synchronized(gSpanLock){span=[[gActive[@(token)]retain]autorelease];[gActive removeObjectForKey:@(token)];}
if(!span||!gEnabled.load())return;double elapsed=(NSProcessInfo.processInfo.systemUptime-[span[@"start"]doubleValue])*1000;
NSString *stage=span[@"stage"];BOOL frequent=[@[@"inspector_refresh",@"render",@"tracking_frame",@"plugin_state"]containsObject:stage];
if(frequent){@synchronized(gSpanLock){NSDictionary *old=gMetrics[stage];gMetrics[stage]=@{@"count":@([old[@"count"]integerValue]+1),@"duration_ms":@([old[@"duration_ms"]doubleValue]+elapsed),@"max_duration_ms":@(MAX([old[@"max_duration_ms"]doubleValue],elapsed))};}if(elapsed<100)return;}
NSMutableDictionary *result=[[span[@"fields"]mutableCopy]autorelease];[result addEntriesFromDictionary:fields?:@{}];result[@"duration_ms"]=@(elapsed);result[@"phase"]=@"end";DYBetaEvent(stage,result);
}
void DYBetaStop(void){DYBetaStart();if(!gProduct)return;dispatch_group_t group=dispatch_group_create();dispatch_group_async(group,transport->queue,^{@autoreleasepool{[transport enqueue:@"process_exit" fields:@{@"status":@"normal"}];[transport persist];[transport drain];}});dispatch_group_wait(group,dispatch_time(DISPATCH_TIME_NOW,NSEC_PER_SEC/2));dispatch_release(group);}
void DYBetaSendSummary(void){DYBetaStart();if(!gProduct)return;dispatch_async(transport->queue,^{@autoreleasepool{[transport enqueue:@"diagnostic_summary" fields:transport->environment];[transport scanCrashSummaries];[transport drain];}});}