Skip to content

Commit

Permalink
Merge pull request #774 from neilalexander/neilalexander/inprocessconn
Browse files Browse the repository at this point in the history
In-process connections
  • Loading branch information
kozlovic committed Jul 31, 2022
2 parents fcc7c44 + 92c5e2e commit 87bbea8
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
30 changes: 30 additions & 0 deletions nats.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,10 @@ type CustomDialer interface {
Dial(network, address string) (net.Conn, error)
}

type InProcessConnProvider interface {
InProcessConn() (net.Conn, error)
}

// Options can be used to create a customized connection.
type Options struct {

Expand All @@ -291,6 +295,11 @@ type Options struct {
// then becomes the first server in the Servers array.
Url string

// InProcessServer represents a NATS server running within the
// same process. If this is set then we will attempt to connect
// to the server directly rather than using external TCP conns.
InProcessServer InProcessConnProvider

// Servers is a configured set of servers which this client
// will use when attempting to connect.
Servers []string
Expand Down Expand Up @@ -783,6 +792,15 @@ func Name(name string) Option {
}
}

// InProcessServer is an Option that will try to establish a direction to a NATS server
// running within the process instead of dialing via TCP.
func InProcessServer(server InProcessConnProvider) Option {
return func(o *Options) error {
o.InProcessServer = server
return nil
}
}

// Secure is an Option to enable TLS secure connections that skip server verification by default.
// Pass a TLS Configuration for proper TLS.
// NOTE: This should NOT be used in a production setting.
Expand Down Expand Up @@ -1749,6 +1767,18 @@ func (nc *Conn) createConn() (err error) {
return ErrNoServers
}

// If we have a reference to an in-process server then establish a
// connection using that.
if nc.Opts.InProcessServer != nil {
conn, err := nc.Opts.InProcessServer.InProcessConn()
if err != nil {
return fmt.Errorf("failed to get in-process connection: %w", err)
}
nc.conn = conn
nc.bindToNewConn()
return nil
}

// We will auto-expand host names if they resolve to multiple IPs
hosts := []string{}
u := nc.current.url
Expand Down
22 changes: 22 additions & 0 deletions nats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2883,3 +2883,25 @@ func TestRespInbox(t *testing.T) {
t.Fatalf("Error: %s", resp.Data)
}
}

func TestInProcessConn(t *testing.T) {
s := RunServerOnPort(-1)
defer s.Shutdown()

nc, err := Connect("", InProcessServer(s))
if err != nil {
t.Fatal(err)
}

defer nc.Close()

// Status should be connected.
if nc.Status() != CONNECTED {
t.Fatal("should be status CONNECTED")
}

// The server should respond to a request.
if _, err := nc.RTT(); err != nil {
t.Fatal(err)
}
}

0 comments on commit 87bbea8

Please sign in to comment.