// creates and initializes a broker. func openBroker(path string, u *url.URL, initializing bool, joinURLs []*url.URL) *messaging.Broker { // Ignore if there's no existing broker and we're not initializing or joining. if !fileExists(path) && !initializing && len(joinURLs) == 0 { return nil } // Create broker. b := messaging.NewBroker() if err := b.Open(path, u); err != nil { log.Fatalf("failed to open broker: %s", err) } // If this is a new broker then we can initialie two ways: // 1) Start a brand new cluster. // 2) Join an existing cluster. if initializing { if len(joinURLs) == 0 { initializeBroker(b) } else { joinBroker(b, joinURLs) } } return b }
// Ensure the broker can reopen and recover correctly. func TestBroker_Reopen(t *testing.T) { b := NewBroker(nil) defer b.Close() b.MustCreateReplica(2000, &url.URL{Host: "localhost"}) b.MustSubscribe(2000, 20) b.MustSubscribe(2000, 21) b.MustPublishSync(&messaging.Message{TopicID: 20, Data: []byte("0000")}) b.MustPublishSync(&messaging.Message{TopicID: 20, Data: []byte("0000")}) b.MustPublishSync(&messaging.Message{TopicID: 21, Data: []byte("0000")}) index := b.MustPublishSync(&messaging.Message{TopicID: 20, Data: []byte("0000")}) time.Sleep(100 * time.Millisecond) // Close broker and reopen with a new broker instance. path, u := b.Path(), b.URL() b.Broker.Close() b.Broker = messaging.NewBroker() if err := b.Broker.Open(path, u); err != nil { t.Fatal(err) } // Verify the broker is up to date. newIndex := b.Index() if newIndex != index { t.Fatalf("index mismatch: exp=%d, got=%d", index, newIndex) } }
// NewBroker returns a new instance of a Broker with default values. func NewBroker() *Broker { b := &Broker{ TriggerInterval: 5 * time.Second, TriggerTimeout: 20 * time.Second, TriggerFailurePause: 1 * time.Second, } b.Broker = messaging.NewBroker() return b }
// Ensure that opening a broker without a connection address returns an error. func TestBroker_Open_ErrAddressRequired(t *testing.T) { b := messaging.NewBroker() f := tempfile() defer os.Remove(f) if err := b.Open(f, nil); err != messaging.ErrConnectionAddressRequired { t.Fatalf("unexpected error: %s", err) } }
// NewUninitializedBroker returns a new broker that has not been initialized. func NewUninitializedBroker(u *url.URL) *Broker { // Default the broker URL if not passed in. if u == nil { u = &url.URL{Scheme: "http", Host: "127.0.0.1:8080"} } // Open a new broker. b := messaging.NewBroker() if err := b.Open(tempfile(), u); err != nil { panic("open: " + err.Error()) } return &Broker{b} }
// Ensure that opening a broker without a path returns an error. func TestBroker_Open_ErrPathRequired(t *testing.T) { b := messaging.NewBroker() if err := b.Open("", &url.URL{Host: "127.0.0.1:8080"}); err != messaging.ErrPathRequired { t.Fatalf("unexpected error: %s", err) } }