github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/transporter/mqtt/mqtt_channels.go (about) 1 package mqtt 2 3 import ( 4 "context" 5 "strconv" 6 7 "github.com/machinefi/w3bstream/pkg/depends/kit/logr" 8 "github.com/machinefi/w3bstream/pkg/depends/x/mapx" 9 "github.com/machinefi/w3bstream/pkg/errors/status" 10 "github.com/machinefi/w3bstream/pkg/types" 11 ) 12 13 var topics = mapx.New[string, *subscriber]() 14 15 func Subscribe(ctx context.Context, topic string) error { 16 ctx, l := logr.Start(ctx, "transporter.mqtt.Subscribe") 17 defer l.End() 18 19 broker := types.MustMqttBrokerFromContext(ctx) 20 21 cli, err := broker.Client(strconv.Itoa(topics.Len() + 1)) 22 if err != nil { 23 l.Error(err) 24 return status.MqttConnectFailed.StatusErr().WithDesc(err.Error()) 25 } 26 cli.WithTopic(topic) 27 28 sub := &subscriber{topic: topic, cli: cli} 29 if err = sub.subscribing(ctx); err != nil { 30 l.Error(err) 31 broker.Close(cli) 32 return status.MqttSubscribeFailed.StatusErr().WithDesc(err.Error()) 33 } 34 if !topics.StoreNX(topic, sub) { 35 l.Error(err) 36 broker.Close(cli) 37 return status.TopicAlreadySubscribed.StatusErr().WithDesc(topic) 38 } 39 return nil 40 } 41 42 func Stop(ctx context.Context, topic string) { 43 ctx, l := logr.Start(ctx, "transporter.mqtt.Stop") 44 defer l.End() 45 46 broker := types.MustMqttBrokerFromContext(ctx) 47 48 sub, ok := topics.LoadAndRemove(topic) 49 if ok { 50 broker.Close(sub.cli) 51 } 52 l.Debug("stopped") 53 }