package playground import ( "errors" "sync" "time" "github.com/robertkrimen/otto" ) // WSMock is the browser side of websocket.upgrade(): frames it sends on a // schedule, and whether it accepts the upgrade at all. type WSMock struct { Refuse bool `json:"refuse"` // answer like a plain HTTP request Script []WSScripted `json:"script"` CloseAfterMs int `json:"closeAfterMs"` // 0: stay open until the script ends } type WSScripted struct { AfterMs int `json:"afterMs"` // after the previous frame Text string `json:"text"` } // WSIn is a frame typed in the page during a run; Close closes the socket. type WSIn struct { Text string Close bool } // WSFrame is one line of the WebSocket transcript. type WSFrame struct { T int64 `json:"t"` Dir string `json:"dir"` // "out" (script to browser), "in", "open", "close" Text string `json:"text"` } type wsConn struct { r *run mu sync.Mutex queue []string closed bool notify chan struct{} stop chan struct{} once sync.Once vm *otto.Otto } func (r *run) frame(dir, text string) { f := WSFrame{T: r.ms(), Dir: dir, Text: text} r.mu.Lock() r.res.WS = append(r.res.WS, f) r.mu.Unlock() if r.hooks.WS != nil { r.hooks.WS(f) } } func (c *wsConn) push(text string) { c.mu.Lock() if c.closed { c.mu.Unlock() return } c.queue = append(c.queue, text) c.mu.Unlock() c.r.frame("in", text) select { case c.notify <- struct{}{}: default: } } func (c *wsConn) close(reason string) { c.mu.Lock() was := c.closed c.closed = true c.mu.Unlock() if !was { c.r.frame("close", reason) select { case c.notify <- struct{}{}: default: } } } func (c *wsConn) shutdown() { c.once.Do(func() { close(c.stop) }) c.close("script ended") } // feed delivers the scripted frames and the page's live frames. func (c *wsConn) feed(m WSMock, live <-chan WSIn) { if live != nil { go func() { for { select { case <-c.stop: return case in, ok := <-live: if !ok { return } if in.Close { c.close("closed by the browser") } else { c.push(in.Text) } } } }() } go func() { for _, s := range m.Script { select { case <-c.stop: return case <-time.After(time.Duration(s.AfterMs) * time.Millisecond): c.push(s.Text) } } if m.CloseAfterMs > 0 { select { case <-c.stop: case <-time.After(time.Duration(m.CloseAfterMs) * time.Millisecond): c.close("closed by the browser") } } }() } // next waits up to d (forever when d < 0) for a frame: the text, or ok // false with closed telling a closed socket from a timeout. func (c *wsConn) next(d time.Duration) (text string, ok bool, closed bool) { var deadline <-chan time.Time if d >= 0 { t := time.NewTimer(d) defer t.Stop() deadline = t.C } for { c.mu.Lock() if len(c.queue) > 0 { text = c.queue[0] c.queue = c.queue[1:] c.mu.Unlock() return text, true, false } if c.closed { c.mu.Unlock() return "", false, true } c.mu.Unlock() select { case <-c.notify: case <-deadline: return "", false, false } } } // pumps reports whether delay() should deliver frames to onMessage. func (c *wsConn) pumps(vm *otto.Otto) bool { if c == nil || vm != c.vm { return false } v, err := vm.Run(`typeof websocket !== "undefined" && typeof websocket.onMessage === "function"`) if err != nil { return false } b, _ := v.ToBoolean() return b } // pump is delay() with an onMessage handler: it sleeps d, firing the // handler for every frame that arrives meanwhile. func (c *wsConn) pump(vm *otto.Otto, d time.Duration) { end := time.Now().Add(d) for { left := time.Until(end) if left <= 0 { return } text, ok, _ := c.next(left) if !ok { // closed: just finish the sleep time.Sleep(time.Until(end)) return } fn, _ := vm.Get("websocket") h, _ := fn.Object().Get("onMessage") arg, _ := vm.ToValue(text) if _, err := h.Call(fn, arg); err != nil { panic(err) } } } func (r *run) injectWebsocket(vm *otto.Otto) { m := r.req.Mocks.WS vm.Set("_ws_upgrade", func(call otto.FunctionCall) otto.Value { if m.Refuse { return r.raise(vm, "WebSocketError", errors.New("websocket: the client did not ask for a WebSocket upgrade")) } r.mu.Lock() if r.ws != nil { r.mu.Unlock() return otto.TrueValue() } c := &wsConn{r: r, notify: make(chan struct{}, 1), stop: make(chan struct{}), vm: vm} r.ws = c r.res.Upgraded = true r.mu.Unlock() r.frame("open", "connection upgraded") c.feed(m, r.req.Live) return otto.TrueValue() }) conn := func() *wsConn { r.mu.Lock() defer r.mu.Unlock() return r.ws } vm.Set("_ws_send", func(call otto.FunctionCall) otto.Value { c := conn() //As on ArozOS, send before upgrade answers false like a closed //connection; the log says why if c == nil { r.log("agi", "warn", "websocket.send: call websocket.upgrade() first") return otto.FalseValue() } c.mu.Lock() closed := c.closed c.mu.Unlock() if closed { return otto.FalseValue() } s, _ := call.Argument(0).ToString() r.frame("out", s) return otto.TrueValue() }) vm.Set("_ws_read", func(call otto.FunctionCall) otto.Value { c := conn() if c == nil { return otto.FalseValue() } d := time.Duration(-1) if a := call.Argument(0); !a.IsUndefined() && !a.IsNull() { ms, _ := a.ToInteger() if ms > 0 { d = time.Duration(ms) * time.Millisecond } } text, ok, closed := c.next(d) switch { case ok: v, _ := vm.ToValue(text) return v case closed: return otto.FalseValue() } return otto.NullValue() }) vm.Set("_ws_available", func(call otto.FunctionCall) otto.Value { c := conn() n := 0 if c != nil { c.mu.Lock() n = len(c.queue) c.mu.Unlock() } v, _ := vm.ToValue(n) return v }) vm.Set("_ws_isClosed", func(call otto.FunctionCall) otto.Value { c := conn() if c == nil { return otto.TrueValue() } c.mu.Lock() defer c.mu.Unlock() return boolValue(c.closed) }) vm.Set("_ws_close", func(call otto.FunctionCall) otto.Value { if c := conn(); c != nil { c.close("closed by the script") } return otto.TrueValue() }) vm.Run(` var websocket = {}; websocket.onMessage = null; websocket.upgrade = _ws_upgrade; websocket.send = _ws_send; websocket.read = _ws_read; websocket.available = _ws_available; websocket.isClosed = _ws_isClosed; websocket.close = _ws_close; `) }