Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Another approach for fixing subscription leak #35

Open
wants to merge 4 commits into
base: issue-26
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion client/bus/bus.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ func New(prefix string, nc *nats.EncodedConn, log log15.Logger) *Bus {
type subBus struct {
bus ari.Bus
subs []ari.Subscription
mu sync.Mutex
}

func (b *subBus) Close() {
Expand All @@ -97,14 +98,30 @@ func (b *subBus) Close() {
// TODO: Ultimately, we will need to derive a way to check to see if the parent bus is then unused, in which case, the NATS subscription(s) should then be closed.
}

// Used as callback from stdbus
func (b *subBus) Cancel(s interface{}) {
b.mu.Lock()
for i, si := range b.subs {
if s == si {
b.subs[i] = b.subs[len(b.subs)-1] // replace the current with the end
b.subs[len(b.subs)-1] = nil // remove the end
b.subs = b.subs[:len(b.subs)-1] // lop off the end
break
}
}
b.mu.Unlock()
}

func (b *subBus) Send(e ari.Event) {
b.bus.Send(e)
}

func (b *subBus) Subscribe(key *ari.Key, eTypes ...string) ari.Subscription {
sub := b.bus.Subscribe(key, eTypes...)

sub.AddCancelCallback(b.Cancel)
b.mu.Lock()
b.subs = append(b.subs, sub)
b.mu.Unlock()

return sub
}
Expand Down
6 changes: 3 additions & 3 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,15 +229,15 @@ func New(ctx context.Context, opts ...OptionFunc) (*Client, error) {
opt(c)
}

// Create the core bus
c.core.bus = bus.New(c.core.prefix, c.core.nc, c.core.log)

// Start the core, if it is not already started
err := c.core.Start()
if err != nil {
return nil, errors.Wrap(err, "failed to start core")
}

// Create the core bus
c.core.bus = bus.New(c.core.prefix, c.core.nc, c.core.log)

// Extract a SubBus from that core bus (NOTE: must come after core is started so that NATS connection exists)
c.bus = c.core.bus.SubBus()

Expand Down