libws.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. r.raise(errors.New("websocket: the client did not ask for a WebSocket upgrade"))
  188. return otto.FalseValue()
  189. }
  190. r.mu.Lock()
  191. if r.ws != nil {
  192. r.mu.Unlock()
  193. return otto.TrueValue()
  194. }
  195. c := &wsConn{r: r, notify: make(chan struct{}, 1), stop: make(chan struct{}), vm: vm}
  196. r.ws = c
  197. r.res.Upgraded = true
  198. r.mu.Unlock()
  199. r.frame("open", "connection upgraded")
  200. c.feed(m, r.req.Live)
  201. return otto.TrueValue()
  202. })
  203. conn := func() *wsConn {
  204. r.mu.Lock()
  205. defer r.mu.Unlock()
  206. return r.ws
  207. }
  208. vm.Set("_ws_send", func(call otto.FunctionCall) otto.Value {
  209. c := conn()
  210. if c == nil {
  211. r.raise(errors.New("websocket: call websocket.upgrade() first"))
  212. return otto.FalseValue()
  213. }
  214. c.mu.Lock()
  215. closed := c.closed
  216. c.mu.Unlock()
  217. if closed {
  218. return otto.FalseValue()
  219. }
  220. s, _ := call.Argument(0).ToString()
  221. r.frame("out", s)
  222. return otto.TrueValue()
  223. })
  224. vm.Set("_ws_read", func(call otto.FunctionCall) otto.Value {
  225. c := conn()
  226. if c == nil {
  227. return otto.FalseValue()
  228. }
  229. d := time.Duration(-1)
  230. if a := call.Argument(0); !a.IsUndefined() && !a.IsNull() {
  231. ms, _ := a.ToInteger()
  232. if ms > 0 {
  233. d = time.Duration(ms) * time.Millisecond
  234. }
  235. }
  236. text, ok, closed := c.next(d)
  237. switch {
  238. case ok:
  239. v, _ := vm.ToValue(text)
  240. return v
  241. case closed:
  242. return otto.FalseValue()
  243. }
  244. return otto.NullValue()
  245. })
  246. vm.Set("_ws_available", func(call otto.FunctionCall) otto.Value {
  247. c := conn()
  248. n := 0
  249. if c != nil {
  250. c.mu.Lock()
  251. n = len(c.queue)
  252. c.mu.Unlock()
  253. }
  254. v, _ := vm.ToValue(n)
  255. return v
  256. })
  257. vm.Set("_ws_isClosed", func(call otto.FunctionCall) otto.Value {
  258. c := conn()
  259. if c == nil {
  260. return otto.TrueValue()
  261. }
  262. c.mu.Lock()
  263. defer c.mu.Unlock()
  264. return boolValue(c.closed)
  265. })
  266. vm.Set("_ws_close", func(call otto.FunctionCall) otto.Value {
  267. if c := conn(); c != nil {
  268. c.close("closed by the script")
  269. }
  270. return otto.TrueValue()
  271. })
  272. vm.Run(`
  273. var websocket = {};
  274. websocket.onMessage = null;
  275. websocket.upgrade = _ws_upgrade;
  276. websocket.send = _ws_send;
  277. websocket.read = _ws_read;
  278. websocket.available = _ws_available;
  279. websocket.isClosed = _ws_isClosed;
  280. websocket.close = _ws_close;
  281. `)
  282. }