<commit_before>/* Copyright 2015 Realm Inc - All Rights Reserved
 * Proprietary and Confidential
 */

extern "C" {
#import "RealmReact.h"
#import "Base/RCTBridge.h"

#import <RealmJS/RealmJS.h>
#import <objc/runtime.h>
#import <dlfcn.h>

#if DEBUG
#import <GCDWebServers/GCDWebServers.h>
#endif

@interface NSObject ()
- (instancetype)initWithJSContext:(void *)context;
- (JSGlobalContextRef)ctx;
@end

JSGlobalContextRef RealmReactGetJSGlobalContextForExecutor(id executor, bool create) {
    Ivar contextIvar = class_getInstanceVariable([executor class], "_context");
    if (!contextIvar) {
        return NULL;
    }

    id rctJSContext = object_getIvar(executor, contextIvar);
    if (!rctJSContext && create) {
        Class RCTJavaScriptContext = NSClassFromString(@"RCTJavaScriptContext");
        NSMethodSignature *signature = [RCTJavaScriptContext instanceMethodSignatureForSelector:@selector(initWithJSContext:)];
        assert(signature);

        // React Native 0.14+ expects a JSContext here, but we also support 0.13.x, which takes a JSGlobalContextRef.
        if (!strcmp([signature getArgumentTypeAtIndex:2], "@")) {
            JSContext *context = [[JSContext alloc] init];
            rctJSContext = [[RCTJavaScriptContext alloc] initWithJSContext:(void *)context];
        }
        else {
            JSGlobalContextRef ctx = JSGlobalContextCreate(NULL);
            rctJSContext = [[RCTJavaScriptContext alloc] initWithJSContext:ctx];
        }

        object_setIvar(executor, contextIvar, rctJSContext);
    }

    return [rctJSContext ctx];
}
}

#if DEBUG
#import <GCDWebServers/GCDWebServers.h>
#import <RealmJS/RealmRPC.hpp>
@interface RealmReact () {
    GCDWebServer *_webServer;
    std::unique_ptr<realm_js::RPCServer> _rpcServer;
    std::mutex _rpcMutex;
}
@end

static __weak RealmReact *s_currentRealmModule = nil;
#endif


@interface RealmReact () <RCTBridgeModule>
@end

@implementation RealmReact

@synthesize bridge = _bridge;

+ (void)load {
    void (*RCTRegisterModule)(Class) = (void (*)(Class))dlsym(RTLD_DEFAULT, "RCTRegisterModule");

    if (RCTRegisterModule) {
        RCTRegisterModule(self);
    }
    else {
        NSLog(@"Failed to load RCTRegisterModule symbol - %s", dlerror());
    }
}

+ (NSString *)moduleName {
    return @"Realm";
}

#if DEBUG
- (void)startRPC {
    std::lock_guard<std::mutex> lock(_rpcMutex);

    [GCDWebServer setLogLevel:3];
    _webServer = [[GCDWebServer alloc] init];
    _rpcServer = std::make_unique<realm_js::RPCServer>();
    __weak __typeof__(self) weakSelf = self;

    // Add a handler to respond to POST requests on any URL
    [_webServer addDefaultHandlerForMethod:@"POST"
                              requestClass:[GCDWebServerDataRequest class]
                              processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
        GCDWebServerResponse *response;
        try {
            // perform all realm ops on the main thread
            __block NSData *responseData;
            dispatch_sync(dispatch_get_main_queue(), ^{
                RealmReact *self = weakSelf;
                if (self) {
                    std::lock_guard<std::mutex> lock(_rpcMutex);
                    if (_rpcServer) {
                        realm_js::json args = realm_js::json::parse([[(GCDWebServerDataRequest *)request text] UTF8String]);
                        std::string responseText = _rpcServer->perform_request(request.path.UTF8String, args).dump();
                        responseData = [NSData dataWithBytes:responseText.c_str() length:responseText.length()];
                        return;
                    }
                }
                // we have been deallocated
                responseData = [NSData data];
            });
            response = [[GCDWebServerDataResponse alloc] initWithData:responseData contentType:@"application/json"];
        }
        catch(std::exception &ex) {
            NSLog(@"Invalid RPC request - %@", [(GCDWebServerDataRequest *)request text]);
            response = [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_UnprocessableEntity
                                                          underlyingError:nil
                                                                  message:@"Invalid RPC request"];
        }

        [response setValue:@"http://localhost:8081" forAdditionalHeader:@"Access-Control-Allow-Origin"];
        return response;
    }];

    [_webServer startWithPort:8082 bonjourName:nil];
    return;
}

- (void)shutdownRPC {
    std::lock_guard<std::mutex> lock(_rpcMutex);
    [_webServer stop];
    [_webServer removeAllHandlers];<commit_msg>lock should be global<commit_after>/* Copyright 2015 Realm Inc - All Rights Reserved
 * Proprietary and Confidential
 */

extern "C" {
#import "RealmReact.h"
#import "Base/RCTBridge.h"

#import <RealmJS/RealmJS.h>
#import <objc/runtime.h>
#import <dlfcn.h>

#if DEBUG
#import <GCDWebServers/GCDWebServers.h>
#endif

@interface NSObject ()
- (instancetype)initWithJSContext:(void *)context;
- (JSGlobalContextRef)ctx;
@end

JSGlobalContextRef RealmReactGetJSGlobalContextForExecutor(id executor, bool create) {
    Ivar contextIvar = class_getInstanceVariable([executor class], "_context");
    if (!contextIvar) {
        return NULL;
    }

    id rctJSContext = object_getIvar(executor, contextIvar);
    if (!rctJSContext && create) {
        Class RCTJavaScriptContext = NSClassFromString(@"RCTJavaScriptContext");
        NSMethodSignature *signature = [RCTJavaScriptContext instanceMethodSignatureForSelector:@selector(initWithJSContext:)];
        assert(signature);

        // React Native 0.14+ expects a JSContext here, but we also support 0.13.x, which takes a JSGlobalContextRef.
        if (!strcmp([signature getArgumentTypeAtIndex:2], "@")) {
            JSContext *context = [[JSContext alloc] init];
            rctJSContext = [[RCTJavaScriptContext alloc] initWithJSContext:(void *)context];
        }
        else {
            JSGlobalContextRef ctx = JSGlobalContextCreate(NULL);
            rctJSContext = [[RCTJavaScriptContext alloc] initWithJSContext:ctx];
        }

        object_setIvar(executor, contextIvar, rctJSContext);
    }

    return [rctJSContext ctx];
}
}

#if DEBUG
#import <GCDWebServers/GCDWebServers.h>
#import <RealmJS/RealmRPC.hpp>
@interface RealmReact () {
    GCDWebServer *_webServer;
    std::unique_ptr<realm_js::RPCServer> _rpcServer;
}
@end

static std::mutex s_rpcMutex;
static __weak RealmReact *s_currentRealmModule = nil;
#endif


@interface RealmReact () <RCTBridgeModule>
@end

@implementation RealmReact

@synthesize bridge = _bridge;

+ (void)load {
    void (*RCTRegisterModule)(Class) = (void (*)(Class))dlsym(RTLD_DEFAULT, "RCTRegisterModule");

    if (RCTRegisterModule) {
        RCTRegisterModule(self);
    }
    else {
        NSLog(@"Failed to load RCTRegisterModule symbol - %s", dlerror());
    }
}

+ (NSString *)moduleName {
    return @"Realm";
}

#if DEBUG
- (void)startRPC {
    std::lock_guard<std::mutex> lock(s_rpcMutex);

    [GCDWebServer setLogLevel:3];
    _webServer = [[GCDWebServer alloc] init];
    _rpcServer = std::make_unique<realm_js::RPCServer>();
    __weak __typeof__(self) weakSelf = self;

    // Add a handler to respond to POST requests on any URL
    [_webServer addDefaultHandlerForMethod:@"POST"
                              requestClass:[GCDWebServerDataRequest class]
                              processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
        GCDWebServerResponse *response;
        try {
            // perform all realm ops on the main thread
            __block NSData *responseData;
            dispatch_sync(dispatch_get_main_queue(), ^{
                RealmReact *self = weakSelf;
                if (self) {
                    std::lock_guard<std::mutex> lock(s_rpcMutex);
                    if (_rpcServer) {
                        realm_js::json args = realm_js::json::parse([[(GCDWebServerDataRequest *)request text] UTF8String]);
                        std::string responseText = _rpcServer->perform_request(request.path.UTF8String, args).dump();
                        responseData = [NSData dataWithBytes:responseText.c_str() length:responseText.length()];
                        return;
                    }
                }
                // we have been deallocated
                responseData = [NSData data];
            });
            response = [[GCDWebServerDataResponse alloc] initWithData:responseData contentType:@"application/json"];
        }
        catch(std::exception &ex) {
            NSLog(@"Invalid RPC request - %@", [(GCDWebServerDataRequest *)request text]);
            response = [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_UnprocessableEntity
                                                          underlyingError:nil
                                                                  message:@"Invalid RPC request"];
        }

        [response setValue:@"http://localhost:8081" forAdditionalHeader:@"Access-Control-Allow-Origin"];
        return response;
    }];

    [_webServer startWithPort:8082 bonjourName:nil];
    return;
}

- (void)shutdownRPC {
    std::lock_guard<std::mutex> lock(s_rpcMutex);
    [_webServer stop];
    [_webServer removeAllHandlers];
{'fraction_non_alphanumeric': 0.10730666666666666, 'fraction_numerical': 0.004693333333333333, 'mean_word_length': 2.7639502207948614, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '86526', 'n_tokens_mistral': 2765, 'n_tokens_neox': 2630, 'n_words': 551}