jsre.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package jsre provides execution environment for JavaScript.
  17. package jsre
  18. import (
  19. "fmt"
  20. "io/ioutil"
  21. "sync"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/robertkrimen/otto"
  25. )
  26. /*
  27. JSRE is a generic JS runtime environment embedding the otto JS interpreter.
  28. It provides some helper functions to
  29. - load code from files
  30. - run code snippets
  31. - require libraries
  32. - bind native go objects
  33. */
  34. type JSRE struct {
  35. assetPath string
  36. evalQueue chan *evalReq
  37. stopEventLoop chan bool
  38. loopWg sync.WaitGroup
  39. }
  40. // jsTimer is a single timer instance with a callback function
  41. type jsTimer struct {
  42. timer *time.Timer
  43. duration time.Duration
  44. interval bool
  45. call otto.FunctionCall
  46. }
  47. // evalReq is a serialized vm execution request processed by runEventLoop.
  48. type evalReq struct {
  49. fn func(vm *otto.Otto)
  50. done chan bool
  51. }
  52. // runtime must be stopped with Stop() after use and cannot be used after stopping
  53. func New(assetPath string) *JSRE {
  54. re := &JSRE{
  55. assetPath: assetPath,
  56. evalQueue: make(chan *evalReq),
  57. stopEventLoop: make(chan bool),
  58. }
  59. re.loopWg.Add(1)
  60. go re.runEventLoop()
  61. re.Set("loadScript", re.loadScript)
  62. re.Set("inspect", prettyPrintJS)
  63. return re
  64. }
  65. // This function runs the main event loop from a goroutine that is started
  66. // when JSRE is created. Use Stop() before exiting to properly stop it.
  67. // The event loop processes vm access requests from the evalQueue in a
  68. // serialized way and calls timer callback functions at the appropriate time.
  69. // Exported functions always access the vm through the event queue. You can
  70. // call the functions of the otto vm directly to circumvent the queue. These
  71. // functions should be used if and only if running a routine that was already
  72. // called from JS through an RPC call.
  73. func (self *JSRE) runEventLoop() {
  74. vm := otto.New()
  75. registry := map[*jsTimer]*jsTimer{}
  76. ready := make(chan *jsTimer)
  77. newTimer := func(call otto.FunctionCall, interval bool) (*jsTimer, otto.Value) {
  78. delay, _ := call.Argument(1).ToInteger()
  79. if 0 >= delay {
  80. delay = 1
  81. }
  82. timer := &jsTimer{
  83. duration: time.Duration(delay) * time.Millisecond,
  84. call: call,
  85. interval: interval,
  86. }
  87. registry[timer] = timer
  88. timer.timer = time.AfterFunc(timer.duration, func() {
  89. ready <- timer
  90. })
  91. value, err := call.Otto.ToValue(timer)
  92. if err != nil {
  93. panic(err)
  94. }
  95. return timer, value
  96. }
  97. setTimeout := func(call otto.FunctionCall) otto.Value {
  98. _, value := newTimer(call, false)
  99. return value
  100. }
  101. setInterval := func(call otto.FunctionCall) otto.Value {
  102. _, value := newTimer(call, true)
  103. return value
  104. }
  105. clearTimeout := func(call otto.FunctionCall) otto.Value {
  106. timer, _ := call.Argument(0).Export()
  107. if timer, ok := timer.(*jsTimer); ok {
  108. timer.timer.Stop()
  109. delete(registry, timer)
  110. }
  111. return otto.UndefinedValue()
  112. }
  113. vm.Set("setTimeout", setTimeout)
  114. vm.Set("setInterval", setInterval)
  115. vm.Set("clearTimeout", clearTimeout)
  116. vm.Set("clearInterval", clearTimeout)
  117. var waitForCallbacks bool
  118. loop:
  119. for {
  120. select {
  121. case timer := <-ready:
  122. // execute callback, remove/reschedule the timer
  123. var arguments []interface{}
  124. if len(timer.call.ArgumentList) > 2 {
  125. tmp := timer.call.ArgumentList[2:]
  126. arguments = make([]interface{}, 2+len(tmp))
  127. for i, value := range tmp {
  128. arguments[i+2] = value
  129. }
  130. } else {
  131. arguments = make([]interface{}, 1)
  132. }
  133. arguments[0] = timer.call.ArgumentList[0]
  134. _, err := vm.Call(`Function.call.call`, nil, arguments...)
  135. if err != nil {
  136. fmt.Println("js error:", err, arguments)
  137. }
  138. _, inreg := registry[timer] // when clearInterval is called from within the callback don't reset it
  139. if timer.interval && inreg {
  140. timer.timer.Reset(timer.duration)
  141. } else {
  142. delete(registry, timer)
  143. if waitForCallbacks && (len(registry) == 0) {
  144. break loop
  145. }
  146. }
  147. case req := <-self.evalQueue:
  148. // run the code, send the result back
  149. req.fn(vm)
  150. close(req.done)
  151. if waitForCallbacks && (len(registry) == 0) {
  152. break loop
  153. }
  154. case waitForCallbacks = <-self.stopEventLoop:
  155. if !waitForCallbacks || (len(registry) == 0) {
  156. break loop
  157. }
  158. }
  159. }
  160. for _, timer := range registry {
  161. timer.timer.Stop()
  162. delete(registry, timer)
  163. }
  164. self.loopWg.Done()
  165. }
  166. // do schedules the given function on the event loop.
  167. func (self *JSRE) do(fn func(*otto.Otto)) {
  168. done := make(chan bool)
  169. req := &evalReq{fn, done}
  170. self.evalQueue <- req
  171. <-done
  172. }
  173. // stops the event loop before exit, optionally waits for all timers to expire
  174. func (self *JSRE) Stop(waitForCallbacks bool) {
  175. self.stopEventLoop <- waitForCallbacks
  176. self.loopWg.Wait()
  177. }
  178. // Exec(file) loads and runs the contents of a file
  179. // if a relative path is given, the jsre's assetPath is used
  180. func (self *JSRE) Exec(file string) error {
  181. code, err := ioutil.ReadFile(common.AbsolutePath(self.assetPath, file))
  182. if err != nil {
  183. return err
  184. }
  185. self.do(func(vm *otto.Otto) { _, err = vm.Run(code) })
  186. return err
  187. }
  188. // Bind assigns value v to a variable in the JS environment
  189. // This method is deprecated, use Set.
  190. func (self *JSRE) Bind(name string, v interface{}) error {
  191. return self.Set(name, v)
  192. }
  193. // Run runs a piece of JS code.
  194. func (self *JSRE) Run(code string) (v otto.Value, err error) {
  195. self.do(func(vm *otto.Otto) { v, err = vm.Run(code) })
  196. return v, err
  197. }
  198. // Get returns the value of a variable in the JS environment.
  199. func (self *JSRE) Get(ns string) (v otto.Value, err error) {
  200. self.do(func(vm *otto.Otto) { v, err = vm.Get(ns) })
  201. return v, err
  202. }
  203. // Set assigns value v to a variable in the JS environment.
  204. func (self *JSRE) Set(ns string, v interface{}) (err error) {
  205. self.do(func(vm *otto.Otto) { err = vm.Set(ns, v) })
  206. return err
  207. }
  208. // loadScript executes a JS script from inside the currently executing JS code.
  209. func (self *JSRE) loadScript(call otto.FunctionCall) otto.Value {
  210. file, err := call.Argument(0).ToString()
  211. if err != nil {
  212. // TODO: throw exception
  213. return otto.FalseValue()
  214. }
  215. file = common.AbsolutePath(self.assetPath, file)
  216. source, err := ioutil.ReadFile(file)
  217. if err != nil {
  218. // TODO: throw exception
  219. return otto.FalseValue()
  220. }
  221. if _, err := compileAndRun(call.Otto, file, source); err != nil {
  222. // TODO: throw exception
  223. fmt.Println("err:", err)
  224. return otto.FalseValue()
  225. }
  226. // TODO: return evaluation result
  227. return otto.TrueValue()
  228. }
  229. // EvalAndPrettyPrint evaluates code and pretty prints the result to
  230. // standard output.
  231. func (self *JSRE) EvalAndPrettyPrint(code string) (err error) {
  232. self.do(func(vm *otto.Otto) {
  233. var val otto.Value
  234. val, err = vm.Run(code)
  235. if err != nil {
  236. return
  237. }
  238. prettyPrint(vm, val)
  239. fmt.Println()
  240. })
  241. return err
  242. }
  243. // Compile compiles and then runs a piece of JS code.
  244. func (self *JSRE) Compile(filename string, src interface{}) (err error) {
  245. self.do(func(vm *otto.Otto) { _, err = compileAndRun(vm, filename, src) })
  246. return err
  247. }
  248. func compileAndRun(vm *otto.Otto, filename string, src interface{}) (otto.Value, error) {
  249. script, err := vm.Compile(filename, src)
  250. if err != nil {
  251. return otto.Value{}, err
  252. }
  253. return vm.Run(script)
  254. }