Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 18e8273

Browse files
committed
feat: Compile the codersdk for wasm
``` GOOS=js GOARCH=wasm go build -o main.wasm ./codersdk ``` This enables the sdk to be build for WebAssembly. It also adds a few functions to the tailnet conn that will be used for integration into a VS Code extension.
1 parent e04877a commit 18e8273

File tree

9 files changed

+84
-46
lines changed

9 files changed

+84
-46
lines changed

cli/speedtest.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ func speedtest() *cobra.Command {
7171
return ctx.Err()
7272
case <-ticker.C:
7373
}
74-
dur, err := conn.Ping(ctx)
74+
dur, p2p, err := conn.Ping(ctx)
7575
if err != nil {
7676
continue
7777
}
@@ -80,7 +80,7 @@ func speedtest() *cobra.Command {
8080
continue
8181
}
8282
peer := status.Peer[status.Peers()[0]]
83-
if peer.CurAddr == "" && direct {
83+
if !p2p && direct {
8484
cmd.Printf("Waiting for a direct connection... (%dms via %s)\n", dur.Milliseconds(), peer.Relay)
8585
continue
8686
}

codersdk/agentconn.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ func (c *AgentConn) AwaitReachable(ctx context.Context) bool {
139139
return c.Conn.AwaitReachable(ctx, TailnetIP)
140140
}
141141

142-
func (c *AgentConn) Ping(ctx context.Context) (time.Duration, error) {
142+
func (c *AgentConn) Ping(ctx context.Context) (time.Duration, bool, error) {
143143
ctx, span := tracing.StartSpan(ctx)
144144
defer span.End()
145145

codersdk/provisionerdaemons.go

+2-9
Original file line numberDiff line numberDiff line change
@@ -130,10 +130,7 @@ func (c *Client) provisionerJobLogsAfter(ctx context.Context, path string, after
130130
httpClient := &http.Client{
131131
Jar: jar,
132132
}
133-
conn, res, err := websocket.Dial(ctx, followURL.String(), &websocket.DialOptions{
134-
HTTPClient: httpClient,
135-
CompressionMode: websocket.CompressionDisabled,
136-
})
133+
conn, res, err := websocket.Dial(ctx, followURL.String(), websocketOptions(httpClient, 0))
137134
if err != nil {
138135
if res == nil {
139136
return nil, nil, err
@@ -192,11 +189,7 @@ func (c *Client) ServeProvisionerDaemon(ctx context.Context, organization uuid.U
192189
httpClient := &http.Client{
193190
Jar: jar,
194191
}
195-
conn, res, err := websocket.Dial(ctx, serverURL.String(), &websocket.DialOptions{
196-
HTTPClient: httpClient,
197-
// Need to disable compression to avoid a data-race.
198-
CompressionMode: websocket.CompressionDisabled,
199-
})
192+
conn, res, err := websocket.Dial(ctx, serverURL.String(), websocketOptions(httpClient, 0))
200193
if err != nil {
201194
if res == nil {
202195
return nil, err

codersdk/websocket_js.go

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
//go:build js
2+
3+
package codersdk
4+
5+
import (
6+
"net/http"
7+
8+
"nhooyr.io/websocket"
9+
)
10+
11+
func websocketOptions(_ *http.Client, _ websocket.CompressionMode) *websocket.DialOptions {
12+
return &websocket.DialOptions{}
13+
}

codersdk/websocket_notjs.go

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
//go:build !js
2+
3+
package codersdk
4+
5+
import (
6+
"net/http"
7+
8+
"nhooyr.io/websocket"
9+
)
10+
11+
func websocketOptions(httpClient *http.Client, compression websocket.CompressionMode) *websocket.DialOptions {
12+
return &websocket.DialOptions{
13+
HTTPClient: httpClient,
14+
CompressionMode: compression,
15+
}
16+
}

codersdk/workspaceagents.go

+4-11
Original file line numberDiff line numberDiff line change
@@ -329,9 +329,7 @@ func (c *Client) ListenWorkspaceAgent(ctx context.Context) (net.Conn, error) {
329329
Transport: c.HTTPClient.Transport,
330330
}
331331
// nolint:bodyclose
332-
conn, res, err := websocket.Dial(ctx, coordinateURL.String(), &websocket.DialOptions{
333-
HTTPClient: httpClient,
334-
})
332+
conn, res, err := websocket.Dial(ctx, coordinateURL.String(), websocketOptions(httpClient, 0))
335333
if err != nil {
336334
if res == nil {
337335
return nil, err
@@ -403,11 +401,8 @@ func (c *Client) DialWorkspaceAgent(ctx context.Context, agentID uuid.UUID, opti
403401
for retrier := retry.New(50*time.Millisecond, 10*time.Second); retrier.Wait(ctx); {
404402
options.Logger.Debug(ctx, "connecting")
405403
// nolint:bodyclose
406-
ws, res, err := websocket.Dial(ctx, coordinateURL.String(), &websocket.DialOptions{
407-
HTTPClient: httpClient,
408-
// Need to disable compression to avoid a data-race.
409-
CompressionMode: websocket.CompressionDisabled,
410-
})
404+
// Need to disable compression to avoid a data-race.
405+
ws, res, err := websocket.Dial(ctx, coordinateURL.String(), websocketOptions(httpClient, websocket.CompressionDisabled))
411406
if isFirst {
412407
if res != nil && res.StatusCode == http.StatusConflict {
413408
first <- readBodyAsError(res)
@@ -524,9 +519,7 @@ func (c *Client) WorkspaceAgentReconnectingPTY(ctx context.Context, agentID, rec
524519
httpClient := &http.Client{
525520
Jar: jar,
526521
}
527-
conn, res, err := websocket.Dial(ctx, serverURL.String(), &websocket.DialOptions{
528-
HTTPClient: httpClient,
529-
})
522+
conn, res, err := websocket.Dial(ctx, serverURL.String(), websocketOptions(httpClient, 0))
530523
if err != nil {
531524
if res == nil {
532525
return nil, err

enterprise/coderd/replicas_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ func TestReplicas(t *testing.T) {
8181
require.Eventually(t, func() bool {
8282
ctx, cancelFunc := context.WithTimeout(context.Background(), testutil.WaitShort)
8383
defer cancelFunc()
84-
_, err = conn.Ping(ctx)
84+
_, _, err = conn.Ping(ctx)
8585
return err == nil
8686
}, testutil.WaitLong, testutil.IntervalFast)
8787
_ = conn.Close()
@@ -124,7 +124,7 @@ func TestReplicas(t *testing.T) {
124124
require.Eventually(t, func() bool {
125125
ctx, cancelFunc := context.WithTimeout(context.Background(), testutil.IntervalSlow)
126126
defer cancelFunc()
127-
_, err = conn.Ping(ctx)
127+
_, _, err = conn.Ping(ctx)
128128
return err == nil
129129
}, testutil.WaitLong, testutil.IntervalFast)
130130
_ = conn.Close()

loadtest/agentconn/run.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ func waitForDisco(ctx context.Context, logs io.Writer, conn *codersdk.AgentConn)
141141
for i := 0; i < pingAttempts; i++ {
142142
_, _ = fmt.Fprintf(logs, "\tDisco ping attempt %d/%d...\n", i+1, pingAttempts)
143143
pingCtx, cancel := context.WithTimeout(ctx, defaultRequestTimeout)
144-
_, err := conn.Ping(pingCtx)
144+
_, _, err := conn.Ping(pingCtx)
145145
cancel()
146146
if err == nil {
147147
break

tailnet/conn.go

+43-20
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ func NewConn(options *Options) (*Conn, error) {
7777
nodePublicKey := nodePrivateKey.Public()
7878

7979
netMap := &netmap.NetworkMap{
80+
DERPMap: options.DERPMap,
8081
NodeKey: nodePublicKey,
8182
PrivateKey: nodePrivateKey,
8283
Addresses: options.Addresses,
@@ -172,7 +173,6 @@ func NewConn(options *Options) (*Conn, error) {
172173
if err != nil {
173174
return nil, xerrors.Errorf("start netstack: %w", err)
174175
}
175-
wireguardEngine = wgengine.NewWatchdog(wireguardEngine)
176176
wireguardEngine.SetDERPMap(options.DERPMap)
177177
netMapCopy := *netMap
178178
wireguardEngine.SetNetworkMap(&netMapCopy)
@@ -246,6 +246,13 @@ func NewConn(options *Options) (*Conn, error) {
246246
return server, nil
247247
}
248248

249+
// DERPMap returns the currently set DERP mapping.
250+
func (c *Conn) DERPMap() *tailcfg.DERPMap {
251+
c.mutex.Lock()
252+
defer c.mutex.Unlock()
253+
return c.netMap.DERPMap
254+
}
255+
249256
// IP generates a new IP with a static service prefix.
250257
func IP() netip.Addr {
251258
// This is Tailscale's ephemeral service prefix.
@@ -407,23 +414,24 @@ func (c *Conn) Status() *ipnstate.Status {
407414
}
408415

409416
// Ping sends a Disco ping to the Wireguard engine.
410-
func (c *Conn) Ping(ctx context.Context, ip netip.Addr) (time.Duration, error) {
417+
// The bool returns true if the ping was made P2P.
418+
func (c *Conn) Ping(ctx context.Context, ip netip.Addr) (time.Duration, bool, error) {
411419
errCh := make(chan error, 1)
412-
durCh := make(chan time.Duration, 1)
420+
prChan := make(chan *ipnstate.PingResult, 1)
413421
go c.wireguardEngine.Ping(ip, tailcfg.PingDisco, func(pr *ipnstate.PingResult) {
414422
if pr.Err != "" {
415423
errCh <- xerrors.New(pr.Err)
416424
return
417425
}
418-
durCh <- time.Duration(pr.LatencySeconds * float64(time.Second))
426+
prChan <- pr
419427
})
420428
select {
421429
case err := <-errCh:
422-
return 0, err
430+
return 0, false, err
423431
case <-ctx.Done():
424-
return 0, ctx.Err()
425-
case dur := <-durCh:
426-
return dur, nil
432+
return 0, false, ctx.Err()
433+
case pr := <-prChan:
434+
return time.Duration(pr.LatencySeconds * float64(time.Second)), pr.Endpoint != "", nil
427435
}
428436
}
429437

@@ -445,7 +453,7 @@ func (c *Conn) AwaitReachable(ctx context.Context, ip netip.Addr) bool {
445453
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
446454
defer cancel()
447455

448-
_, err := c.Ping(ctx, ip)
456+
_, _, err := c.Ping(ctx, ip)
449457
if err == nil {
450458
completed()
451459
}
@@ -523,17 +531,7 @@ func (c *Conn) sendNode() {
523531
c.nodeChanged = true
524532
return
525533
}
526-
node := &Node{
527-
ID: c.netMap.SelfNode.ID,
528-
AsOf: database.Now(),
529-
Key: c.netMap.SelfNode.Key,
530-
Addresses: c.netMap.SelfNode.Addresses,
531-
AllowedIPs: c.netMap.SelfNode.AllowedIPs,
532-
DiscoKey: c.magicConn.DiscoPublicKey(),
533-
Endpoints: c.lastEndpoints,
534-
PreferredDERP: c.lastPreferredDERP,
535-
DERPLatency: c.lastDERPLatency,
536-
}
534+
node := c.selfNode()
537535
if c.blockEndpoints {
538536
node.Endpoints = nil
539537
}
@@ -557,6 +555,31 @@ func (c *Conn) sendNode() {
557555
}()
558556
}
559557

558+
// Node returns the last node that was sent to the node callback.
559+
func (c *Conn) Node() *Node {
560+
c.lastMutex.Lock()
561+
defer c.lastMutex.Unlock()
562+
return c.selfNode()
563+
}
564+
565+
func (c *Conn) selfNode() *Node {
566+
node := &Node{
567+
ID: c.netMap.SelfNode.ID,
568+
AsOf: database.Now(),
569+
Key: c.netMap.SelfNode.Key,
570+
Addresses: c.netMap.SelfNode.Addresses,
571+
AllowedIPs: c.netMap.SelfNode.AllowedIPs,
572+
DiscoKey: c.magicConn.DiscoPublicKey(),
573+
Endpoints: c.lastEndpoints,
574+
PreferredDERP: c.lastPreferredDERP,
575+
DERPLatency: c.lastDERPLatency,
576+
}
577+
if c.blockEndpoints {
578+
node.Endpoints = nil
579+
}
580+
return node
581+
}
582+
560583
// This and below is taken _mostly_ verbatim from Tailscale:
561584
// https://github.com/tailscale/tailscale/blob/c88bd53b1b7b2fcf7ba302f2e53dd1ce8c32dad4/tsnet/tsnet.go#L459-L494
562585

0 commit comments

Comments
 (0)