libws.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package playground
  2. import (
  3. "errors"
  4. "sync"
  5. "time"
  6. "github.com/robertkrimen/otto"
  7. )
  8. // WSMock is the browser side of websocket.upgrade(): frames it sends on a
  9. // schedule, and whether it accepts the upgrade at all.
  10. type WSMock struct {
  11. Refuse bool `json:"refuse"` // answer like a plain HTTP request
  12. Script []WSScripted `json:"script"`
  13. CloseAfterMs int `json:"closeAfterMs"` // 0: stay open until the script ends
  14. }
  15. type WSScripted struct {
  16. AfterMs int `json:"afterMs"` // after the previous frame
  17. Text string `json:"text"`
  18. }
  19. // WSIn is a frame typed in the page during a run; Close closes the socket.
  20. type WSIn struct {
  21. Text string
  22. Close bool
  23. }
  24. // WSFrame is one line of the WebSocket transcript.
  25. type WSFrame struct {
  26. T int64 `json:"t"`
  27. Dir string `json:"dir"` // "out" (script to browser), "in", "open", "close"
  28. Text string `json:"text"`
  29. }
  30. type wsConn struct {
  31. r *run
  32. mu sync.Mutex
  33. queue []string
  34. closed bool
  35. notify chan struct{}
  36. stop chan struct{}
  37. once sync.Once
  38. vm *otto.Otto
  39. }
  40. func (r *run) frame(dir, text string) {
  41. f := WSFrame{T: r.ms(), Dir: dir, Text: text}
  42. r.mu.Lock()
  43. r.res.WS = append(r.res.WS, f)
  44. r.mu.Unlock()
  45. if r.hooks.WS != nil {
  46. r.hooks.WS(f)
  47. }
  48. }
  49. func (c *wsConn) push(text string) {
  50. c.mu.Lock()
  51. if c.closed {
  52. c.mu.Unlock()
  53. return
  54. }
  55. c.queue = append(c.queue, text)
  56. c.mu.Unlock()
  57. c.r.frame("in", text)
  58. select {
  59. case c.notify <- struct{}{}:
  60. default:
  61. }
  62. }
  63. func (c *wsConn) close(reason string) {
  64. c.mu.Lock()
  65. was := c.closed
  66. c.closed = true
  67. c.mu.Unlock()
  68. if !was {
  69. c.r.frame("close", reason)
  70. select {
  71. case c.notify <- struct{}{}:
  72. default:
  73. }
  74. }
  75. }
  76. func (c *wsConn) shutdown() {
  77. c.once.Do(func() { close(c.stop) })
  78. c.close("script ended")
  79. }
  80. // feed delivers the scripted frames and the page's live frames.
  81. func (c *wsConn) feed(m WSMock, live <-chan WSIn) {
  82. if live != nil {
  83. go func() {
  84. for {
  85. select {
  86. case <-c.stop:
  87. return
  88. case in, ok := <-live:
  89. if !ok {
  90. return
  91. }
  92. if in.Close {
  93. c.close("closed by the browser")
  94. } else {
  95. c.push(in.Text)
  96. }
  97. }
  98. }
  99. }()
  100. }
  101. go func() {
  102. for _, s := range m.Script {
  103. select {
  104. case <-c.stop:
  105. return
  106. case <-time.After(time.Duration(s.AfterMs) * time.Millisecond):
  107. c.push(s.Text)
  108. }
  109. }
  110. if m.CloseAfterMs > 0 {
  111. select {
  112. case <-c.stop:
  113. case <-time.After(time.Duration(m.CloseAfterMs) * time.Millisecond):
  114. c.close("closed by the browser")
  115. }
  116. }
  117. }()
  118. }
  119. // next waits up to d (forever when d < 0) for a frame: the text, or ok
  120. // false with closed telling a closed socket from a timeout.
  121. func (c *wsConn) next(d time.Duration) (text string, ok bool, closed bool) {
  122. var deadline <-chan time.Time
  123. if d >= 0 {
  124. t := time.NewTimer(d)
  125. defer t.Stop()
  126. deadline = t.C
  127. }
  128. for {
  129. c.mu.Lock()
  130. if len(c.queue) > 0 {
  131. text = c.queue[0]
  132. c.queue = c.queue[1:]
  133. c.mu.Unlock()
  134. return text, true, false
  135. }
  136. if c.closed {
  137. c.mu.Unlock()
  138. return "", false, true
  139. }
  140. c.mu.Unlock()
  141. select {
  142. case <-c.notify:
  143. case <-deadline:
  144. return "", false, false
  145. }
  146. }
  147. }
  148. // pumps reports whether delay() should deliver frames to onMessage.
  149. func (c *wsConn) pumps(vm *otto.Otto) bool {
  150. if c == nil || vm != c.vm {
  151. return false
  152. }
  153. v, err := vm.Run(`typeof websocket !== "undefined" && typeof websocket.onMessage === "function"`)
  154. if err != nil {
  155. return false
  156. }
  157. b, _ := v.ToBoolean()
  158. return b
  159. }
  160. // pump is delay() with an onMessage handler: it sleeps d, firing the
  161. // handler for every frame that arrives meanwhile.
  162. func (c *wsConn) pump(vm *otto.Otto, d time.Duration) {
  163. end := time.Now().Add(d)
  164. for {
  165. left := time.Until(end)
  166. if left <= 0 {
  167. return
  168. }
  169. text, ok, _ := c.next(left)
  170. if !ok {
  171. // closed: just finish the sleep
  172. time.Sleep(time.Until(end))
  173. return
  174. }
  175. fn, _ := vm.Get("websocket")
  176. h, _ := fn.Object().Get("onMessage")
  177. arg, _ := vm.ToValue(text)
  178. if _, err := h.Call(fn, arg); err != nil {
  179. panic(err)
  180. }
  181. }
  182. }
  183. func (r *run) injectWebsocket(vm *otto.Otto) {
  184. m := r.req.Mocks.WS
  185. vm.Set("_ws_upgrade", func(call otto.FunctionCall) otto.Value {
  186. if m.Refuse {
  187. return r.raise(vm, "WebSocketError", errors.New("websocket: the client did not ask for a WebSocket upgrade"))
  188. }
  189. r.mu.Lock()
  190. if r.ws != nil {
  191. r.mu.Unlock()
  192. return otto.TrueValue()
  193. }
  194. c := &wsConn{r: r, notify: make(chan struct{}, 1), stop: make(chan struct{}), vm: vm}
  195. r.ws = c
  196. r.res.Upgraded = true
  197. r.mu.Unlock()
  198. r.frame("open", "connection upgraded")
  199. c.feed(m, r.req.Live)
  200. return otto.TrueValue()
  201. })
  202. conn := func() *wsConn {
  203. r.mu.Lock()
  204. defer r.mu.Unlock()
  205. return r.ws
  206. }
  207. vm.Set("_ws_send", func(call otto.FunctionCall) otto.Value {
  208. c := conn()
  209. //As on ArozOS, send before upgrade answers false like a closed
  210. //connection; the log says why
  211. if c == nil {
  212. r.log("agi", "warn", "websocket.send: call websocket.upgrade() first")
  213. return otto.FalseValue()
  214. }
  215. c.mu.Lock()
  216. closed := c.closed
  217. c.mu.Unlock()
  218. if closed {
  219. return otto.FalseValue()
  220. }
  221. s, _ := call.Argument(0).ToString()
  222. r.frame("out", s)
  223. return otto.TrueValue()
  224. })
  225. vm.Set("_ws_read", func(call otto.FunctionCall) otto.Value {
  226. c := conn()
  227. if c == nil {
  228. return otto.FalseValue()
  229. }
  230. d := time.Duration(-1)
  231. if a := call.Argument(0); !a.IsUndefined() && !a.IsNull() {
  232. ms, _ := a.ToInteger()
  233. if ms > 0 {
  234. d = time.Duration(ms) * time.Millisecond
  235. }
  236. }
  237. text, ok, closed := c.next(d)
  238. switch {
  239. case ok:
  240. v, _ := vm.ToValue(text)
  241. return v
  242. case closed:
  243. return otto.FalseValue()
  244. }
  245. return otto.NullValue()
  246. })
  247. vm.Set("_ws_available", func(call otto.FunctionCall) otto.Value {
  248. c := conn()
  249. n := 0
  250. if c != nil {
  251. c.mu.Lock()
  252. n = len(c.queue)
  253. c.mu.Unlock()
  254. }
  255. v, _ := vm.ToValue(n)
  256. return v
  257. })
  258. vm.Set("_ws_isClosed", func(call otto.FunctionCall) otto.Value {
  259. c := conn()
  260. if c == nil {
  261. return otto.TrueValue()
  262. }
  263. c.mu.Lock()
  264. defer c.mu.Unlock()
  265. return boolValue(c.closed)
  266. })
  267. vm.Set("_ws_close", func(call otto.FunctionCall) otto.Value {
  268. if c := conn(); c != nil {
  269. c.close("closed by the script")
  270. }
  271. return otto.TrueValue()
  272. })
  273. vm.Run(`
  274. var websocket = {};
  275. websocket.onMessage = null;
  276. websocket.upgrade = _ws_upgrade;
  277. websocket.send = _ws_send;
  278. websocket.read = _ws_read;
  279. websocket.available = _ws_available;
  280. websocket.isClosed = _ws_isClosed;
  281. websocket.close = _ws_close;
  282. `)
  283. }