JavaScriptWorker.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import Foundation
  2. import JavaScriptCore
  3. private let contextLock = NSRecursiveLock()
  4. extension String {
  5. var lowercasingFirst: String { prefix(1).lowercased() + dropFirst() }
  6. var uppercasingFirst: String { prefix(1).uppercased() + dropFirst() }
  7. var camelCased: String {
  8. guard !isEmpty else { return "" }
  9. let parts = components(separatedBy: .alphanumerics.inverted)
  10. let first = parts.first!.lowercasingFirst
  11. let rest = parts.dropFirst().map(\.uppercasingFirst)
  12. return ([first] + rest).joined()
  13. }
  14. var pascalCased: String {
  15. guard !isEmpty else { return "" }
  16. let parts = components(separatedBy: .alphanumerics.inverted)
  17. let first = parts.first!.uppercasingFirst
  18. let rest = parts.dropFirst().map(\.uppercasingFirst)
  19. return ([first] + rest).joined()
  20. }
  21. }
  22. final class JavaScriptWorker {
  23. private let processQueue = DispatchQueue(label: "DispatchQueue.JavaScriptWorker", attributes: .concurrent)
  24. private let virtualMachine: JSVirtualMachine
  25. private var contextPool: [JSContext] = []
  26. private let contextPoolLock = NSLock()
  27. @SyncAccess(lock: contextLock) private var commonContext: JSContext? = nil
  28. private var consoleLogs: [String] = []
  29. private var logContext: String = ""
  30. init(poolSize: Int = 5) {
  31. virtualMachine = JSVirtualMachine()!
  32. // Pre-create a pool of JSContext instances
  33. for _ in 0 ..< poolSize {
  34. contextPool.append(createContext())
  35. }
  36. }
  37. private func createContext() -> JSContext {
  38. let context = JSContext(virtualMachine: virtualMachine)!
  39. context.exceptionHandler = { _, exception in
  40. if let error = exception?.toString() {
  41. warning(.openAPS, "JavaScript Error: \(error)")
  42. }
  43. }
  44. let consoleLog: @convention(block) (String) -> Void = { message in
  45. let trimmedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
  46. if !trimmedMessage.isEmpty {
  47. self.consoleLogs.append("\(trimmedMessage)")
  48. }
  49. }
  50. context.setObject(consoleLog, forKeyedSubscript: "_consoleLog" as NSString)
  51. return context
  52. }
  53. private func getContext() -> JSContext {
  54. contextPoolLock.lock()
  55. let context = contextPool.popLast() ?? createContext()
  56. contextPoolLock.unlock()
  57. return context
  58. }
  59. private func returnContext(_ context: JSContext) {
  60. contextPoolLock.lock()
  61. contextPool.append(context)
  62. contextPoolLock.unlock()
  63. }
  64. // New method to flush aggregated logs
  65. private func outputLogs() {
  66. var outputLogs = consoleLogs.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
  67. consoleLogs.removeAll()
  68. if outputLogs.isEmpty { return }
  69. if logContext == "autosens.js" {
  70. outputLogs = outputLogs.split(separator: "\n").map { logLine in
  71. logLine.replacingOccurrences(
  72. of: "^[-+=x!]|u\\(|\\)|\\d{1,2}h$",
  73. with: "",
  74. options: .regularExpression
  75. )
  76. }.joined(separator: "\n")
  77. }
  78. if !outputLogs.isEmpty {
  79. outputLogs.split(separator: "\n").forEach { logLine in
  80. if !"\(logLine)".trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
  81. debug(.openAPS, "\(logContext): \(logLine)")
  82. }
  83. }
  84. }
  85. }
  86. @discardableResult func evaluate(script: Script) -> JSValue! {
  87. logContext = URL(fileURLWithPath: script.name).lastPathComponent
  88. let result = evaluate(string: script.body)
  89. outputLogs()
  90. return result
  91. }
  92. private func evaluate(string: String) -> JSValue! {
  93. let context = getContext()
  94. defer { returnContext(context) }
  95. return context.evaluateScript(string)
  96. }
  97. private func json(for string: String) -> RawJSON {
  98. evaluate(string: "JSON.stringify(\(string), null, 4);")!.toString()!
  99. }
  100. func call(function: String, with arguments: [JSON]) -> RawJSON {
  101. let joined = arguments.map(\.rawJSON).joined(separator: ",")
  102. return json(for: "\(function)(\(joined))")
  103. }
  104. func inCommonContext<Value>(execute: (JavaScriptWorker) -> Value) -> Value {
  105. let context = getContext()
  106. defer {
  107. returnContext(context)
  108. outputLogs()
  109. }
  110. return execute(self)
  111. }
  112. func evaluateBatch(scripts: [Script]) {
  113. let context = getContext()
  114. defer {
  115. // Ensure the context is returned to the pool
  116. returnContext(context)
  117. }
  118. scripts.forEach { script in
  119. logContext = URL(fileURLWithPath: script.name).lastPathComponent
  120. context.evaluateScript(script.body)
  121. outputLogs()
  122. }
  123. }
  124. }