package rex_test import ( "context" "errors" "sync" "testing" "time" "100gex/internal/rex" "100gex/internal/rex/rextest" ) func TestParseEndpoint(t *testing.T) { for _, tt := range []struct { in string want rex.Endpoint }{ {"unix:///run/user/1000/rex/server.sock", rex.Endpoint{Socket: "/run/user/1000/rex/server.sock"}}, {"unix:///a%20b/server.sock", rex.Endpoint{Socket: "/a b/server.sock"}}, {"/tmp/rex.sock", rex.Endpoint{Socket: "/tmp/rex.sock"}}, {"tcp://example.com:7000", rex.Endpoint{Host: "example.com", Port: 7000}}, {"ws://[::1]:7000/", rex.Endpoint{Host: "::1", Port: 7000}}, } { got, err := rex.ParseEndpoint(tt.in) if err != nil || got != tt.want { t.Errorf("ParseEndpoint(%q) = %+v, %v; want %+v", tt.in, got, err, tt.want) } } for _, bad := range []string{"", "unix://", "tcp://host", "tcp://:80", "tcp://host:port", "rex"} { if got, err := rex.ParseEndpoint(bad); err == nil { t.Errorf("ParseEndpoint(%q) = %+v, want an error", bad, got) } } } // dial connects to srv, closing the connection when the test ends. func dial(t *testing.T, srv *rextest.Server) *rex.Conn { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c, err := rex.Dial(ctx, srv.Endpoint, rex.ClientInfo{Kind: "other", Name: "100gex-test"}) if err != nil { t.Fatal(err) } t.Cleanup(func() { c.Close() }) return c } // createSession creates a session whose one window runs sh, and returns its // ID. func createSession(t *testing.T, c *rex.Conn, label string) string { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var created struct { SessionID string `json:"session_id"` } _, err := c.Call(ctx, "session.create", map[string]any{ "label": label, "initial_windows": []any{map[string]any{ "layout": map[string]any{"block": map[string]any{ "flavor": "com.superlogical.terminal.shell", "options": map[string]any{"shell": "/bin/sh", "login": false}, }}, }}, }, &created) if err != nil { t.Fatal(err) } return created.SessionID } // waitEvent returns the first event from c with the given name. func waitEvent(t *testing.T, c *rex.Conn, name string) rex.Event { t.Helper() timeout := time.After(10 * time.Second) for { select { case ev, ok := <-c.Events(): if !ok { t.Fatalf("connection ended waiting for %s: %v", name, c.Err()) } if ev.Name == name { return ev } case <-timeout: t.Fatalf("no %s event", name) } } } func TestControl(t *testing.T) { srv := rextest.Start(t) c := dial(t, srv) ctx := context.Background() w := c.Welcome() if w.APIRevision != rex.APIRevision || w.ClientID() == "" { t.Errorf("welcome: revision %d, client %q; want revision %d and a client ID", w.APIRevision, w.ClientID(), rex.APIRevision) } v, err := c.ServerVersion(ctx) if err != nil || v.RexVersion == "" { t.Errorf("ServerVersion = %+v, %v", v, err) } // Errors come back typed, and leave the connection usable. if _, err := c.Call(ctx, "no.such_method", nil, nil); !rex.IsCode(err, "method_not_found") { t.Errorf("unknown method: err = %v, want method_not_found", err) } // A server with no sessions selects none. boot, _, err := c.Bootstrap(ctx, rex.BootstrapArgs{EventScope: "session"}) if err != nil { t.Fatal(err) } if boot.SelectedSession != nil || len(boot.AttachAll.Sessions) != 0 { t.Errorf("empty server: selected %+v, sessions %+v", boot.SelectedSession, boot.AttachAll.Sessions) } if boot.ClientID != w.ClientID() { t.Errorf("bootstrap client %q, welcome client %q", boot.ClientID, w.ClientID()) } // Events reach a bootstrapped connection, unwrapped from session_event // where they happened in a session. id := createSession(t, c, "work") var created struct { Session rex.Session `json:"session"` } if err := waitEvent(t, c, "session_created").Decode(&created); err != nil || created.Session.SessionID != id { t.Errorf("session_created = %+v, %v; want session %s", created, err, id) } // A second client is handed the session, its layout, and a data ticket // for its terminal. c2 := dial(t, srv) boot, seq, err := c2.Bootstrap(ctx, rex.BootstrapArgs{ EventScope: "session", DataTickets: []rex.DataTicketRequest{{CreatorName: "com.superlogical.terminal", DataRefID: "terminal", Subprotocol: "rex.data.terminal.v1"}}, }) if err != nil { t.Fatal(err) } sel := boot.SelectedSession if sel == nil || sel.Session.SessionID != id || sel.Session.Label != "work" { t.Fatalf("selected session = %+v, want %s", sel, id) } win := sel.View.ActiveWindow() if win == nil || win.FocusedBlockID == "" { t.Fatalf("view has no active window with a focused block: %+v", sel.View) } block := win.Block(win.FocusedBlockID) if block == nil || block.CreatorName != "com.superlogical.terminal" { t.Errorf("focused block = %+v, want a terminal", block) } if root := win.Layers[0].Layout; root == nil || root.BlockID != win.FocusedBlockID { t.Errorf("layout = %+v, want the one block", root) } if len(boot.DataTickets) != 1 || boot.DataTickets[0].BlockID != win.FocusedBlockID || boot.DataTickets[0].Ticket == "" { t.Errorf("data tickets = %+v, want one for %s", boot.DataTickets, win.FocusedBlockID) } t.Logf("bootstrap seq %d, view revision %d", seq, sel.View.Revision) } func TestConcurrentCalls(t *testing.T) { c := dial(t, rextest.Start(t)) var wg sync.WaitGroup errs := make(chan error, 50) for range 50 { wg.Go(func() { if _, err := c.ServerVersion(context.Background()); err != nil { errs <- err } }) } wg.Wait() close(errs) for err := range errs { t.Error(err) } } func TestClose(t *testing.T) { srv := rextest.Start(t) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c, err := rex.Dial(ctx, srv.Endpoint, rex.ClientInfo{Name: "100gex-test"}) if err != nil { t.Fatal(err) } if err := c.Close(); err != nil { t.Errorf("Close: %v", err) } if _, err := c.ServerVersion(ctx); !errors.Is(err, rex.ErrClosed) { t.Errorf("call after Close: err = %v, want ErrClosed", err) } if _, ok := <-c.Events(); ok { t.Error("Events still open after Close") } } func TestServerGone(t *testing.T) { // A call fails, rather than hangs, when there's no server. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _, err := rex.Dial(ctx, rex.Endpoint{Socket: "/nonexistent/rex.sock"}, rex.ClientInfo{}) if err == nil { t.Fatal("Dial succeeded with no server") } } func TestFindSession(t *testing.T) { sessions := []rex.Session{ {SessionID: "session:01a1f94f-3dc3-7ebe-8e27-51759bca3718", Label: "demo"}, {SessionID: "session:01a1f94f-3dc3-7ebe-8e27-51759bc00001", Label: "ca3718"}, {SessionID: "session:01a1f94f-3dc3-7ebe-8e27-51759bc00002", Label: "other"}, } for _, tt := range []struct{ query, want string }{ {"session:01a1f94f-3dc3-7ebe-8e27-51759bc00002", "other"}, {"demo", "demo"}, {"ca3718", "ca3718"}, // a label wins over the end of an ID {"00002", "other"}, } { got, err := rex.FindSession(sessions, tt.query) if err != nil || got.Label != tt.want { t.Errorf("FindSession(%q) = %+v, %v; want %s", tt.query, got, err, tt.want) } } for _, bad := range []string{"nope", "0000"} { if got, err := rex.FindSession(sessions, bad); err == nil { t.Errorf("FindSession(%q) = %+v, want an error", bad, got) } } }