Sha256: 4c2f10d47f748e342584c9deafceb4d79add8b6ec58ae61d7b22e711287a54da
Contents?: true
Size: 1.69 KB
Versions: 48
Compression:
Stored size: 1.69 KB
Contents
require 'execjs' require 'weakref' module Sqreen module Js class ExecjsAdapter < JsServiceAdapter def preprocess(rule_name, code) if thread_safe? ExecJsRunnable.new(ExecJS.compile(code)) else ThreadLocalExecJsRunnable.new(code) end end def variant_name ExecJS.runtime.name + ' (ExecJS)' end private def thread_safe? ExecJS.runtime.name != 'therubyrhino (Rhino)' end end class ExecJsRunnable < ExecutableJs def initialize(compiled) @compiled = compiled end def run_js_cb(cbname, _budget, arguments) @compiled.call(cbname, *arguments) end end class ThreadLocalExecJsRunnable < ExecutableJs def initialize(code) @code = code @tl_key = "SQREEN_EXECJS_CONTEXT_#{object_id}".freeze @runtimes = [] # place where to keep strong references @runtimes_mutex = Mutex.new end def run_js_cb(cbname, _budget, arguments) tl_exec_js_runnable.call(cbname, *arguments) end def with_runtimes_mutex @runtimes_mutex.synchronize { yield } end private def dispose_from_dead_threads with_runtimes_mutex do @runtimes.delete_if { |th, _runtime| !th.alive? } end end def tl_exec_js_runnable runnable = Thread.current[@tl_key] return runnable if runnable && runnable.weakref_alive? dispose_from_dead_threads runtime = ExecJS.compile(@code) with_runtimes_mutex do @runtimes << [Thread.current, runtime] end Thread.current[@tl_key] = WeakRef.new(runtime) end end end end
Version data entries
48 entries across 48 versions & 1 rubygems