summaryrefslogtreecommitdiff
path: root/tests/plugins/broadcast/plugins/plugin1.go
blob: 01ad147946f96d1d37e31546ea7bf66969e47fc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package plugins

import (
	"fmt"

	"github.com/spiral/roadrunner/v2/common/pubsub"
	"github.com/spiral/roadrunner/v2/plugins/broadcast"
	"github.com/spiral/roadrunner/v2/plugins/logger"
)

const Plugin1Name = "plugin1"

type Plugin1 struct {
	log    logger.Logger
	b      broadcast.Broadcaster
	driver pubsub.SubReader

	exit chan struct{}
}

func (p *Plugin1) Init(log logger.Logger, b broadcast.Broadcaster) error {
	p.log = log
	p.b = b
	p.exit = make(chan struct{}, 1)
	return nil
}

func (p *Plugin1) Serve() chan error {
	errCh := make(chan error, 1)

	var err error
	p.driver, err = p.b.GetDriver("test")
	if err != nil {
		errCh <- err
		return errCh
	}

	err = p.driver.Subscribe("1", "foo", "foo2", "foo3")
	if err != nil {
		panic(err)
	}

	go func() {
		for {
			select {
			case <-p.exit:
				return
			default:
				msg, err := p.driver.Next()
				if err != nil {
					errCh <- err
					return
				}

				if msg == nil {
					continue
				}

				p.log.Info(fmt.Sprintf("%s: %s", Plugin1Name, *msg))
			}
		}
	}()

	return errCh
}

func (p *Plugin1) Stop() error {
	_ = p.driver.Unsubscribe("1", "foo")
	_ = p.driver.Unsubscribe("1", "foo2")
	_ = p.driver.Unsubscribe("1", "foo3")

	p.exit <- struct{}{}
	return nil
}

func (p *Plugin1) Name() string {
	return Plugin1Name
}