summaryrefslogtreecommitdiff
path: root/workhorse/cable_test.go
blob: 7320837541a244630938bf41df23311bec1a33c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"regexp"
	"testing"

	"github.com/gorilla/websocket"
	"github.com/stretchr/testify/require"

	"gitlab.com/gitlab-org/gitlab-workhorse/internal/config"
	"gitlab.com/gitlab-org/gitlab-workhorse/internal/helper"
	"gitlab.com/gitlab-org/gitlab-workhorse/internal/testhelper"
)

const cablePath = "/-/cable"

func TestSingleBackend(t *testing.T) {
	cableServerConns, cableBackendServer := startCableServer()
	defer cableBackendServer.Close()

	config := newUpstreamWithCableConfig(cableBackendServer.URL, "")
	workhorse := startWorkhorseServerWithConfig(config)
	defer workhorse.Close()

	cableURL := websocketURL(workhorse.URL, cablePath)

	client, _, err := dialWebsocket(cableURL, nil)
	require.NoError(t, err)
	defer client.Close()

	server := (<-cableServerConns).conn
	defer server.Close()

	require.NoError(t, say(client, "hello"))
	requireReadMessage(t, server, websocket.TextMessage, "hello")

	require.NoError(t, say(server, "world"))
	requireReadMessage(t, client, websocket.TextMessage, "world")
}

func TestSeparateCableBackend(t *testing.T) {
	authBackendServer := testhelper.TestServerWithHandler(regexp.MustCompile(`.`), http.HandlerFunc(http.NotFound))
	defer authBackendServer.Close()

	cableServerConns, cableBackendServer := startCableServer()
	defer cableBackendServer.Close()

	config := newUpstreamWithCableConfig(authBackendServer.URL, cableBackendServer.URL)
	workhorse := startWorkhorseServerWithConfig(config)
	defer workhorse.Close()

	cableURL := websocketURL(workhorse.URL, cablePath)

	client, _, err := dialWebsocket(cableURL, nil)
	require.NoError(t, err)
	defer client.Close()

	server := (<-cableServerConns).conn
	defer server.Close()

	require.NoError(t, say(client, "hello"))
	requireReadMessage(t, server, websocket.TextMessage, "hello")

	require.NoError(t, say(server, "world"))
	requireReadMessage(t, client, websocket.TextMessage, "world")
}

func startCableServer() (chan connWithReq, *httptest.Server) {
	upgrader := &websocket.Upgrader{}

	connCh := make(chan connWithReq, 1)
	server := testhelper.TestServerWithHandler(regexp.MustCompile(cablePath), webSocketHandler(upgrader, connCh))

	return connCh, server
}

func newUpstreamWithCableConfig(authBackend string, cableBackend string) *config.Config {
	var cableBackendURL *url.URL

	if cableBackend != "" {
		cableBackendURL = helper.URLMustParse(cableBackend)
	}

	return &config.Config{
		Version:      "123",
		DocumentRoot: testDocumentRoot,
		Backend:      helper.URLMustParse(authBackend),
		CableBackend: cableBackendURL,
	}
}