| @@ -36,11 +36,15 @@ public enum JavaScriptBlocks { |
| 36 | } |
36 | } |
| 37 | } |
37 | } |
| 38 | |
38 | |
| 39 | /// Runs a js `job` without a session on the calling thread, as `org-sbe` in a table |
39 | /// Runs a js `job` without a session, as `org-sbe` in a table formula needs, waiting on the |
| 40 | /// formula needs; nil for other jobs. |
40 | /// calling thread at most `timeout`; nil for other jobs. |
| 41 | public static func runHere(_ job: BabelJob) throws -> BabelOutput? { |
41 | public static func runHere(_ job: BabelJob, timeout: Duration = .seconds(5)) throws -> BabelOutput? { |
| 42 | guard job.language == "js" || job.language == "javascript", case .process = job.runner else { return nil } |
42 | guard job.language == "js" || job.language == "javascript", case .process = job.runner else { return nil } |
| 43 | return try Engine().main(job.input, run: Run()) |
43 | let run = Run() |
| |
44 | let thread = Thread { run.end(Result { try Engine().main(job.input, run: run) }) } |
| |
45 | thread.stackSize = 8 << 20 |
| |
46 | thread.start() |
| |
47 | return try run.result(within: timeout) |
| 44 | } |
48 | } |
| 45 | |
49 | |
| 46 | struct Stopped: Error, CustomStringConvertible { |
50 | struct Stopped: Error, CustomStringConvertible { |
| @@ -71,6 +75,7 @@ public enum JavaScriptBlocks { |
| 71 | private var result: Result<BabelOutput, Error>? |
75 | private var result: Result<BabelOutput, Error>? |
| 72 | private var continuation: CheckedContinuation<BabelOutput, Error>? |
76 | private var continuation: CheckedContinuation<BabelOutput, Error>? |
| 73 | private let wake = DispatchSemaphore(value: 0) |
77 | private let wake = DispatchSemaphore(value: 0) |
| |
78 | private let done = DispatchSemaphore(value: 0) |
| 74 | |
79 | |
| 75 | var stopped: Bool { lock.withLock { result != nil } } |
80 | var stopped: Bool { lock.withLock { result != nil } } |
| 76 | |
81 | |
| @@ -84,6 +89,16 @@ public enum JavaScriptBlocks { |
| 84 | guard first else { return } |
89 | guard first else { return } |
| 85 | waiting?.resume(with: outcome) |
90 | waiting?.resume(with: outcome) |
| 86 | wake.signal() |
91 | wake.signal() |
| |
92 | done.signal() |
| |
93 | } |
| |
94 | |
| |
95 | /// Blocks until the run ends, ending it when `timeout` passes first. |
| |
96 | func result(within timeout: Duration) throws -> BabelOutput { |
| |
97 | let (seconds, attoseconds) = timeout.components |
| |
98 | if done.wait(timeout: .now() + .nanoseconds(Int(seconds) * 1_000_000_000 + Int(attoseconds / 1_000_000_000))) == .timedOut { |
| |
99 | end(.failure(Stopped(description: "The block took longer than \(timeout) and was stopped."))) |
| |
100 | } |
| |
101 | return try lock.withLock { result! }.get() |
| 87 | } |
102 | } |
| 88 | |
103 | |
| 89 | func wait(_ continuation: CheckedContinuation<BabelOutput, Error>) { |
104 | func wait(_ continuation: CheckedContinuation<BabelOutput, Error>) { |