jsre.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. return re
  63. }
  64. // This function runs the main event loop from a goroutine that is started
  65. // when JSRE is created. Use Stop() before exiting to properly stop it.
  66. // The event loop processes vm access requests from the evalQueue in a
  67. // serialized way and calls timer callback functions at the appropriate time.
  68. // Exported functions always access the vm through the event queue. You can
  69. // call the functions of the otto vm directly to circumvent the queue. These
  70. // functions should be used if and only if running a routine that was already
  71. // called from JS through an RPC call.
  72. func (self *JSRE) runEventLoop() {
  73. vm := otto.New()
  74. registry := map[*jsTimer]*jsTimer{}
  75. ready := make(chan *jsTimer)
  76. newTimer := func(call otto.FunctionCall, interval bool) (*jsTimer, otto.Value) {
  77. delay, _ := call.Argument(1).ToInteger()
  78. if 0 >= delay {
  79. delay = 1
  80. }
  81. timer := &jsTimer{
  82. duration: time.Duration(delay) * time.Millisecond,
  83. call: call,
  84. interval: interval,
  85. }
  86. registry[timer] = timer
  87. timer.timer = time.AfterFunc(timer.duration, func() {
  88. ready <- timer
  89. })
  90. value, err := call.Otto.ToValue(timer)
  91. if err != nil {
  92. panic(err)
  93. }
  94. return timer, value
  95. }
  96. setTimeout := func(call otto.FunctionCall) otto.Value {
  97. _, value := newTimer(call, false)
  98. return value
  99. }
  100. setInterval := func(call otto.FunctionCall) otto.Value {
  101. _, value := newTimer(call, true)
  102. return value
  103. }
  104. clearTimeout := func(call otto.FunctionCall) otto.Value {
  105. timer, _ := call.Argument(0).Export()
  106. if timer, ok := timer.(*jsTimer); ok {
  107. timer.timer.Stop()
  108. delete(registry, timer)
  109. }
  110. return otto.UndefinedValue()
  111. }
  112. vm.Set("setTimeout", setTimeout)
  113. vm.Set("setInterval", setInterval)
  114. vm.Set("clearTimeout", clearTimeout)
  115. vm.Set("clearInterval", clearTimeout)
  116. var waitForCallbacks bool
  117. loop:
  118. for {
  119. select {
  120. case timer := <-ready:
  121. // execute callback, remove/reschedule the timer
  122. var arguments []interface{}
  123. if len(timer.call.ArgumentList) > 2 {
  124. tmp := timer.call.ArgumentList[2:]
  125. arguments = make([]interface{}, 2+len(tmp))
  126. for i, value := range tmp {
  127. arguments[i+2] = value
  128. }
  129. } else {
  130. arguments = make([]interface{}, 1)
  131. }
  132. arguments[0] = timer.call.ArgumentList[0]
  133. _, err := vm.Call(`Function.call.call`, nil, arguments...)
  134. if err != nil {
  135. fmt.Println("js error:", err, arguments)
  136. }
  137. if timer.interval {
  138. timer.timer.Reset(timer.duration)
  139. } else {
  140. delete(registry, timer)
  141. if waitForCallbacks && (len(registry) == 0) {
  142. break loop
  143. }
  144. }
  145. case req := <-self.evalQueue:
  146. // run the code, send the result back
  147. req.fn(vm)
  148. close(req.done)
  149. if waitForCallbacks && (len(registry) == 0) {
  150. break loop
  151. }
  152. case waitForCallbacks = <-self.stopEventLoop:
  153. if !waitForCallbacks || (len(registry) == 0) {
  154. break loop
  155. }
  156. }
  157. }
  158. for _, timer := range registry {
  159. timer.timer.Stop()
  160. delete(registry, timer)
  161. }
  162. self.loopWg.Done()
  163. }
  164. // do schedules the given function on the event loop.
  165. func (self *JSRE) do(fn func(*otto.Otto)) {
  166. done := make(chan bool)
  167. req := &evalReq{fn, done}
  168. self.evalQueue <- req
  169. <-done
  170. }
  171. // stops the event loop before exit, optionally waits for all timers to expire
  172. func (self *JSRE) Stop(waitForCallbacks bool) {
  173. self.stopEventLoop <- waitForCallbacks
  174. self.loopWg.Wait()
  175. }
  176. // Exec(file) loads and runs the contents of a file
  177. // if a relative path is given, the jsre's assetPath is used
  178. func (self *JSRE) Exec(file string) error {
  179. code, err := ioutil.ReadFile(common.AbsolutePath(self.assetPath, file))
  180. if err != nil {
  181. return err
  182. }
  183. self.do(func(vm *otto.Otto) { _, err = vm.Run(code) })
  184. return err
  185. }
  186. // Bind assigns value v to a variable in the JS environment
  187. // This method is deprecated, use Set.
  188. func (self *JSRE) Bind(name string, v interface{}) error {
  189. return self.Set(name, v)
  190. }
  191. // Run runs a piece of JS code.
  192. func (self *JSRE) Run(code string) (v otto.Value, err error) {
  193. self.do(func(vm *otto.Otto) { v, err = vm.Run(code) })
  194. return v, err
  195. }
  196. // Get returns the value of a variable in the JS environment.
  197. func (self *JSRE) Get(ns string) (v otto.Value, err error) {
  198. self.do(func(vm *otto.Otto) { v, err = vm.Get(ns) })
  199. return v, err
  200. }
  201. // Set assigns value v to a variable in the JS environment.
  202. func (self *JSRE) Set(ns string, v interface{}) (err error) {
  203. self.do(func(vm *otto.Otto) { err = vm.Set(ns, v) })
  204. return err
  205. }
  206. // loadScript executes a JS script from inside the currently executing JS code.
  207. func (self *JSRE) loadScript(call otto.FunctionCall) otto.Value {
  208. file, err := call.Argument(0).ToString()
  209. if err != nil {
  210. // TODO: throw exception
  211. return otto.FalseValue()
  212. }
  213. file = common.AbsolutePath(self.assetPath, file)
  214. source, err := ioutil.ReadFile(file)
  215. if err != nil {
  216. // TODO: throw exception
  217. return otto.FalseValue()
  218. }
  219. if _, err := compileAndRun(call.Otto, file, source); err != nil {
  220. // TODO: throw exception
  221. fmt.Println("err:", err)
  222. return otto.FalseValue()
  223. }
  224. // TODO: return evaluation result
  225. return otto.TrueValue()
  226. }
  227. // EvalAndPrettyPrint evaluates code and pretty prints the result to
  228. // standard output.
  229. func (self *JSRE) EvalAndPrettyPrint(code string) (err error) {
  230. self.do(func(vm *otto.Otto) {
  231. var val otto.Value
  232. val, err = vm.Run(code)
  233. if err != nil {
  234. return
  235. }
  236. prettyPrint(vm, val)
  237. fmt.Println()
  238. })
  239. return err
  240. }
  241. // Compile compiles and then runs a piece of JS code.
  242. func (self *JSRE) Compile(filename string, src interface{}) (err error) {
  243. self.do(func(vm *otto.Otto) { _, err = compileAndRun(vm, filename, src) })
  244. return err
  245. }
  246. func compileAndRun(vm *otto.Otto, filename string, src interface{}) (otto.Value, error) {
  247. script, err := vm.Compile(filename, src)
  248. if err != nil {
  249. return otto.Value{}, err
  250. }
  251. return vm.Run(script)
  252. }