Go アプリケーション内蔵型 NATS サーバーの構成とインプロセス通信の構造

はじめに
NATS について
ソフトウェアのアプリケーションやサービスは、データを交換する必要があります。NATS は、そのようなデータ交換をメッセージの形式で分割して行えるようにするインフラストラクチャです。これを「メッセージ指向ミドルウェア (message oriented middleware)」と呼びます。
NATS を使うことで、アプリケーション開発者は次のことができます。
- 分散型でスケーラブルなクライアント・サーバーアプリケーションを容易に構築できる。
- データをリアルタイムで、汎用的な方法で保存および配布できる。これは、さまざまな環境、言語、クラウドプロバイダー、オンプレミスのシステムにまたがって柔軟に実現できる。
- NATS は Go で構成されたメッセージブローカーである。
埋め込み型 NATS (Embedded NATS)
お使いのアプリケーションが Go で書かれており、その利用ケースやデプロイメントのシナリオに適合する場合、NATS サーバーをアプリケーション内部に埋め込むことさえできます。
- そして NATS の特異な点として、Go で構成されたアプリケーションの場合、embedded mode をサポートしているということである。
- つまり、メッセージブローカーの一般的な方式である、別途ブローカーサーバーを起動し、そのサーバーとアプリケーションのクライアントを通じて通信する構造ではなく、ブローカー自体を Go で作られたアプリケーションに内蔵 (embed) できるという話である。
埋め込み型 NATS の利点とユースケース
- よく説明された Youtube 動画があるため、その動画のリンクで代えさせていただく。
- 別途のメッセージブローカーサーバーをデプロイしなくても、modular monolith アプリケーションを作成して関心の分離 (separate of concern) を達成することもでき、NATS を embedded として組み込める利点を活用できる。加えて、single binary deployment も可能になる。
- platform with no network (wasm) だけでなく、offline-first アプリケーションでも有用に使用できる。
公式ドキュメントの例
1package main
2
3import (
4 "fmt"
5 "time"
6
7 "github.com/nats-io/nats-server/v2/server"
8 "github.com/nats-io/nats.go"
9)
10
11func main() {
12 opts := &server.Options{}
13
14 // オプションを指定して新しいサーバーを初期化する
15 ns, err := server.NewServer(opts)
16
17 if err != nil {
18 panic(err)
19 }
20
21 // goroutine を介してサーバーを起動する
22 go ns.Start()
23
24 // サーバーが接続を受け付ける準備になるまで待機する
25 if !ns.ReadyForConnections(4 * time.Second) {
26 panic("not ready for connection")
27 }
28
29 // サーバーに接続する
30 nc, err := nats.Connect(ns.ClientURL())
31
32 if err != nil {
33 panic(err)
34 }
35
36 subject := "my-subject"
37
38 // subject をサブスクライブする
39 nc.Subscribe(subject, func(msg *nats.Msg) {
40 // メッセージデータを出力する
41 data := string(msg.Data)
42 fmt.Println(data)
43
44 // サーバーをシャットダウンする (任意)
45 ns.Shutdown()
46 })
47
48 // subject にデータをパブリッシュする
49 nc.Publish(subject, []byte("Hello embedded NATS!"))
50
51 // サーバーのシャットダウンを待機する
52 ns.WaitForShutdown()
53}
- NATS 公式ドキュメントに掲載されている Embedded NATS の例 であるが、そのサンプルコードどおりに進めると、embedding mode で通信が行われない。
1Every 2.0s: netstat -an | grep 127.0.0.1 pravdalaptop-home.local: 02:34:20
2 in 0.017s (0)
3...
4tcp4 0 0 127.0.0.1.4222 127.0.0.1.63769 TIME_WAIT
watch 'netstat -an | grep 127.0.0.1'コマンドを使って localhost (127.0.0.1) へ行き来するネットワークを確認しながら、go run .でその Go ファイルを実行すると、NATS のデフォルトポートである4222から出発する新しいネットワークリクエストが追加されていくのを確認できる。
embedding mode のための正しい設定
意図したとおり embedded mode で通信するためには、次の二つのオプションが必要である。
- Client:
InProcessServerオプションを渡さなければならない。 - Server:
Server.OptionsでDontListenというフラグをtrueに明示しなければならない。
- Client:
これらの部分は公式にドキュメント化されてはおらず、この機能の始まりは該当の PR を通じて把握できる。
This PR adds three things:
InProcessConn()function toServerwhich builds anet.Pipeto get a connection to the NATS server without using TCP socketsDontListenoption which tells the NATS server not to listen on the usual TCP listenerstartupCompletechannel, which is closed right before we startAcceptLoop, andreadyForConnectionswill wait for it
The main motivation for this is that we have an application that can run either in a monolith (single-process) mode or a polylith (multi-process) mode. We'd like to be able to use NATS for both modes for simplicity, but the monolith mode has to be able to cater for a variety of platforms where opening socket connections either doesn't make sense (mobile) or just isn't possible (WASM). These changes will allow us to use NATS entirely in-process instead.
An accompanying PR nats-io/nats.go#774 adds support to the client side.
This is my first PR to this project so apologies in advance if I've missed anything obvious anywhere.
/cc @nats-io/core
embedded mode の動作例
1package main
2
3import (
4 "fmt"
5 "time"
6
7 "github.com/nats-io/nats-server/v2/server"
8 "github.com/nats-io/nats.go"
9)
10
11func main() {
12 opts := &server.Options{
13 // 埋め込みの NATS サーバーを設定するために
14 // DontListen を true に設定する
15 DontListen: true,
16 }
17
18 // オプションを指定して新しいサーバーを初期化する
19 ns, err := server.NewServer(opts)
20
21 if err != nil {
22 panic(err)
23 }
24
25 // goroutine を介してサーバーを起動する
26 go ns.Start()
27
28 // サーバーが接続を受け付ける準備になるまで待機する
29 if !ns.ReadyForConnections(10 * time.Second) {
30 panic("not ready for connection")
31 }
32
33 // in-process 接続を介してサーバーに接続する
34 nc, err := nats.Connect(ns.ClientURL(), nats.InProcessServer(ns))
35
36 if err != nil {
37 panic(err)
38 }
39
40 subject := "my-subject"
41
42 // subject をサブスクライブする
43 nc.Subscribe(subject, func(msg *nats.Msg) {
44 // メッセージデータを出力する
45 data := string(msg.Data)
46 fmt.Println(data)
47
48 // サーバーをシャットダウンする (任意)
49 ns.Shutdown()
50 })
51
52 // subject にデータをパブリッシュする
53 nc.Publish(subject, []byte("Hello embedded NATS!"))
54
55 // サーバーのシャットダウンを待機する
56 ns.WaitForShutdown()
57}
58
1Every 2.0s: netstat -an | grep 127.0.0.1 pravdalaptop-home.local: 02:37:50
2 in 0.023s (0)
3...no additional logs
4
- これで、意図したとおり追加のネットワークホップが発生しないことを確認できる。
内部の仕組み
TL;DR
- このコードを
main.goで実行したときに、内部でどの関数がどのように動作するかを示したシーケンス図であり、要点を説明すると以下のとおりである。DontListen: trueにより、サーバーはAcceptLoopというクライアント待ち受けフェーズを省略する。- クライアントの Connect オプションのうち
InProcessServerが有効になると、インメモリ接続を生成し、net.Pipeを通じてパイプを作成した後、パイプの一方の端をnet.Conn型としてクライアントに返す。 - クライアントとサーバーは、この接続を通じて in-process 通信を行う。
サーバー
AcceptLoop
1// nats-server/server/server.go
2
3// Wait for clients.
4if !opts.DontListen {
5 s.AcceptLoop(clientListenReady)
6}
- まず
DontListenが true の場合、AcceptLoopというクライアント待ち受けフェーズを省略する。
1// nats-server/server/server.go
2
3// AcceptLoop is exported for easier testing.
4func (s *Server) AcceptLoop(clr chan struct{}) {
5 // If we were to exit before the listener is setup properly,
6 // make sure we close the channel.
7 defer func() {
8 if clr != nil {
9 close(clr)
10 }
11 }()
12
13 if s.isShuttingDown() {
14 return
15 }
16
17 // Snapshot server options.
18 opts := s.getOpts()
19
20 // Setup state that can enable shutdown
21 s.mu.Lock()
22 hp := net.JoinHostPort(opts.Host, strconv.Itoa(opts.Port))
23 l, e := natsListen("tcp", hp)
24 s.listenerErr = e
25 if e != nil {
26 s.mu.Unlock()
27 s.Fatalf("Error listening on port: %s, %q", hp, e)
28 return
29 }
30 s.Noticef("Listening for client connections on %s",
31 net.JoinHostPort(opts.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
32
33 // Alert of TLS enabled.
34 if opts.TLSConfig != nil {
35 s.Noticef("TLS required for client connections")
36 if opts.TLSHandshakeFirst && opts.TLSHandshakeFirstFallback == 0 {
37 s.Warnf("Clients that are not using \"TLS Handshake First\" option will fail to connect")
38 }
39 }
40
41 // If server was started with RANDOM_PORT (-1), opts.Port would be equal
42 // to 0 at the beginning this function. So we need to get the actual port
43 if opts.Port == 0 {
44 // Write resolved port back to options.
45 opts.Port = l.Addr().(*net.TCPAddr).Port
46 }
47
48 // Now that port has been set (if it was set to RANDOM), set the
49 // server's info Host/Port with either values from Options or
50 // ClientAdvertise.
51 if err := s.setInfoHostPort(); err != nil {
52 s.Fatalf("Error setting server INFO with ClientAdvertise value of %s, err=%v", opts.ClientAdvertise, err)
53 l.Close()
54 s.mu.Unlock()
55 return
56 }
57 // Keep track of client connect URLs. We may need them later.
58 s.clientConnectURLs = s.getClientConnectURLs()
59 s.listener = l
60
61 go s.acceptConnections(l, "Client", func(conn net.Conn) { s.createClient(conn) },
62 func(_ error) bool {
63 if s.isLameDuckMode() {
64 // Signal that we are not accepting new clients
65 s.ldmCh <- true
66 // Now wait for the Shutdown...
67 <-s.quitCh
68 return true
69 }
70 return false
71 })
72 s.mu.Unlock()
73
74 // Let the caller know that we are ready
75 close(clr)
76 clr = nil
77}
- 参考までに、AcceptLoop 関数は次のような過程を進める。
TLSやhostPortのように network 通信に関係する部分であり、in-process 通信を行う場合には不要な部分なので、省略しても差し支えない部分である。
クライアント
InProcessServer
1
2// nats-go/nats.go
3
4// Connect will attempt to connect to the NATS system.
5// The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222
6// Comma separated arrays are also supported, e.g. urlA, urlB.
7// Options start with the defaults but can be overridden.
8// To connect to a NATS Server's websocket port, use the `ws` or `wss` scheme, such as
9// `ws://localhost:8080`. Note that websocket schemes cannot be mixed with others (nats/tls).
10func Connect(url string, options ...Option) (*Conn, error) {
11 opts := GetDefaultOptions()
12 opts.Servers = processUrlString(url)
13 for _, opt := range options {
14 if opt != nil {
15 if err := opt(&opts); err != nil {
16 return nil, err
17 }
18 }
19 }
20 return opts.Connect()
21}
1// nats-go/nats.go
2
3// Options can be used to create a customized connection.
4type Options struct {
5 // Url represents a single NATS server url to which the client
6 // will be connecting. If the Servers option is also set, it
7 // then becomes the first server in the Servers array.
8 Url string
9
10 // InProcessServer represents a NATS server running within the
11 // same process. If this is set then we will attempt to connect
12 // to the server directly rather than using external TCP conns.
13 InProcessServer InProcessConnProvider
14
15 //...
16}
1// nats-go/nats.go
2
3type InProcessConnProvider interface {
4 InProcessConn() (net.Conn, error)
5}
- nats server と nats client の接続を行う
Connect関数は、client URL と connect Option を設定でき、それらの Option をまとめた Options struct にはInProcesConnProviderinterface 型のInProcessServerというフィールドが存在する。
1// main.go of example code
2
3// Initialize new server with options
4ns, err := server.NewServer(opts)
5
6//...
7
8// Connect to server via in-process connection
9nc, err := nats.Connect(ns.ClientURL(), nats.InProcessServer(ns))
- nats client で Connect を行う際、
InProcessServerフィールドとしてnats.InProcessServer(ns)を渡すと、
1// nats-go/nats.go
2
3// InProcessServer is an Option that will try to establish a direction to a NATS server
4// running within the process instead of dialing via TCP.
5func InProcessServer(server InProcessConnProvider) Option {
6 return func(o *Options) error {
7 o.InProcessServer = server
8 return nil
9 }
10}
- Option の InProcessServer が embedded nats server に置き換えられ、
1// nats-go/nats.go
2
3// createConn will connect to the server and wrap the appropriate
4// bufio structures. It will do the right thing when an existing
5// connection is in place.
6func (nc *Conn) createConn() (err error) {
7 if nc.Opts.Timeout < 0 {
8 return ErrBadTimeout
9 }
10 if _, cur := nc.currentServer(); cur == nil {
11 return ErrNoServers
12 }
13
14 // If we have a reference to an in-process server then establish a
15 // connection using that.
16 if nc.Opts.InProcessServer != nil {
17 conn, err := nc.Opts.InProcessServer.InProcessConn()
18 if err != nil {
19 return fmt.Errorf("failed to get in-process connection: %w", err)
20 }
21 nc.conn = conn
22 nc.bindToNewConn()
23 return nil
24 }
25
26 //...
27}
- この interface は、connection を生成する
createConn関数において、InProcessServerOption が nil でない (有効な) 場合に、Option の InProcessServer が持つInProcesConnを実行しながら、
1// nats-server/server/server.go
2
3// InProcessConn returns an in-process connection to the server,
4// avoiding the need to use a TCP listener for local connectivity
5// within the same process. This can be used regardless of the
6// state of the DontListen option.
7func (s *Server) InProcessConn() (net.Conn, error) {
8 pl, pr := net.Pipe()
9 if !s.startGoRoutine(func() {
10 s.createClientInProcess(pl)
11 s.grWG.Done()
12 }) {
13 pl.Close()
14 pr.Close()
15 return nil, fmt.Errorf("failed to create connection")
16 }
17 return pr, nil
18}
- server に実装された
InProcessConnを呼び出して実行する。 - この関数は、nats の go client である
nats.goにおいて nc (nats connection) のInProcessServerが nil でない場合に呼び出され、connection (net.Conn) を作成し、それを server の connection に bind させる。
Go の consumer driven interface
A type implements an interface by implementing its methods. There is no explicit declaration of intent, no "implements" keyword. Implicit interfaces decouple the definition of an interface from its implementation, which could then appear in any package without prearrangement.
Interfaces are implemented implicitly, A Tour of Go
If a type exists only to implement an interface and will never have exported methods beyond that interface, there is no need to export the type itself.
- この interface の設計は、Go でよく言われる consumer defined interface と structural typing (duck typing) をよく表しているため、このテーマについても併せて紹介したいと思う。
1// nats-go/nats.go
2
3// Options can be used to create a customized connection.
4type Options struct {
5 // Url represents a single NATS server url to which the client
6 // will be connecting. If the Servers option is also set, it
7 // then becomes the first server in the Servers array.
8 Url string
9
10 // InProcessServer represents a NATS server running within the
11 // same process. If this is set then we will attempt to connect
12 // to the server directly rather than using external TCP conns.
13 InProcessServer InProcessConnProvider
14
15 //...
16}
1// nats-go/nats.go
2
3type InProcessConnProvider interface {
4 InProcessConn() (net.Conn, error)
5}
- 再びコードに戻ろう。nats.go client において
InProcessServerOption の struct フィールドは、InProcessConnのみを実行するInProcessConnProviderinterface として定義されている。
1// nats-server/server/server.go
2
3// InProcessConn returns an in-process connection to the server,
4// avoiding the need to use a TCP listener for local connectivity
5// within the same process. This can be used regardless of the
6// state of the DontListen option.
7func (s *Server) InProcessConn() (net.Conn, error) {
8 pl, pr := net.Pipe()
9 if !s.startGoRoutine(func() {
10 s.createClientInProcess(pl)
11 s.grWG.Done()
12 }) {
13 pl.Close()
14 pr.Close()
15 return nil, fmt.Errorf("failed to create connection")
16 }
17 return pr, nil
18}
- しかし、そこに入る型は nats-server の
Serverであり、InProcessConn だけでなく、さまざまな機能を担っている。 - なぜなら、この状況における client の関心事は、
InProcessConnという interface を提供しているかどうかだけであり、ほかの要素はあまり重要ではないからである。 - したがって、nats.go client は
InProcessConn() (net.Conn, error)という機能のみを定義したInProcessConnProviderという consumer defined interface だけを作成して利用している。
結論
- NATS の embedded mode とその動作方式、そして NATS のコードを通じて確認できる Go の consumer defined interface について、簡単に扱ってみた。
- この情報が、上記のような目的で NATS を使用する人々に役立つことを願い、この記事を終えたいと思う。