Repository: edgexfoundry/device-sdk-go (go)

Issue:
Remove UseMessageBus config in 3.0
<!--🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅

Oh hi there! 😄 

To expedite issue processing please search open and closed issues before submitting a new one.
Existing issues often contain information about workarounds, resolution, or progress updates.

Please do not remove sections of this template when submitting your issue.  If the section is not relevant to your issue, leave the section but enter "n/a" for not applicable.

Note some sections are marked "REQUIRED" and must be provided.  Never mark required sections "n/a".

🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅-->


# 🚀 Feature Request

### Relevant Package [**REQUIRED**]
<!-- Can you pin-point one or more EdgeX services the are relevant for this feature request? -->
<!-- ✍️edit: --> This feature request is for...
all device services

### Description [**REQUIRED**]
<!-- ✍️--> 
The message bus is always used after 3.0

### Describe the solution you'd like
<!-- ✍️--> 
remove the config `UseMessageBus`


### Describe alternatives you've considered
<!-- ✍️--> Have you considered any alternative solutions or workarounds?


Pull request:
feat!: remove UseMessageBus config in 3.0
BREAKING CHANGE: Removed the 'Device.UseMessageBus' config, the code for sending event via core-data REST client and the 'Clients.core-data' dependency

MessageBus is always enabled in 3.0 for sending events and receiving system events for callbacks.

closes #1296

Signed-off-by: Chris Hung <chris@iotechsys.com>

<!-- Expected Commit Message Description (imported automatically by GitHub) -->
<!-- Must conform to [conventional commits guidelines](https://github.com/edgexfoundry/device-sdk-go/blob/main/.github/Contributing.md) -->
<!-- Expected Commit message must contain Closes/Fixes #IssueNumber statement when there is a related issue -->

<!-- Add additional detailed description of need for change if no related issue -->

**If your build fails** due to your commit message not passing the build checks, please review the guidelines here: https://github.com/edgexfoundry/device-sdk-go/blob/main/.github/Contributing.md

## PR Checklist
Please check if your PR fulfills the following requirements:

- [ ] I am not introducing a breaking change (if you are, flag in conventional commit message with `BREAKING CHANGE:` describing the break)
- [x] I am not introducing a new dependency (add notes below if you are)
- [ ] I have added unit tests for the new feature or bug fix (if not, why?)
- [x] I have fully tested (add details below) this the new feature or bug fix (if not, why?)
- [ ] I have opened a PR for the related docs change (if not, why?)
  <link to docs PR>

## Testing Instructions
<!-- How can the reviewers test your change? -->
1. Run device-simple from this branch
2. Run `PSUBSCRIBE edgex.events.device.*` in redis container to subscribe to the auto event messages
3. Check the autoevent messages are received by `redis` container:
```shell
127.0.0.1:6379> PSUBSCRIBE edgex.events.device.*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "edgex.events.device.*"
3) (integer) 1
1) "pmessage"
2) "edgex.events.device.*"
3) "edgex.events.device.Simple-Device.Simple-Device01.Switch"
4) "{\"ReceivedTopic\":\"\",\"CorrelationID\":\"8421be6f-b4cb-4a3f-9d28-bce7f7701ff4\",\"ApiVersion\":\"v2\",\"RequestID\":\"\",\"ErrorCode\":0,\"Payload\":\"eyJhcGlWZXJzaW9uIjoidjIiLCJyZXF1ZXN0SWQiOiJiODhmOTQ3My0wMzZkLTRhODgtYmIyMi04MmU4ZjU0Y2RhNDQiLCJldmVudCI6eyJhcGlWZXJzaW9uIjoidjIiLCJpZCI6IjdiYWQxM2MzLWZiMmEtNDM2ZS1hYjQ3LTQxOTY5NWM1YmFiZSIsImRldmljZU5hbWUiOiJTaW1wbGUtRGV2aWNlMDEiLCJwcm9maWxlTmFtZSI6IlNpbXBsZS1EZXZpY2UiLCJzb3VyY2VOYW1lIjoiU3dpdGNoIiwib3JpZ2luIjoxNjc1MzE4MDcxOTQyOTE3MDAwLCJyZWFkaW5ncyI6W3siaWQiOiJjOGQ0OWE5NC1iOTQ1LTQ5NjQtYmVhYi0zMDY3MWNlMzExYTgiLCJvcmlnaW4iOjE2NzUzMTgwNzE5NDI5MTcwMDAsImRldmljZU5hbWUiOiJTaW1wbGUtRGV2aWNlMDEiLCJyZXNvdXJjZU5hbWUiOiJTd2l0Y2hCdXR0b24iLCJwcm9maWxlTmFtZSI6IlNpbXBsZS1EZXZpY2UiLCJ2YWx1ZVR5cGUiOiJCb29sIiwidmFsdWUiOiJmYWxzZSJ9XX19\",\"ContentType\":\"application/json\",\"QueryParams\":{}}"

```

## New Dependency Instructions (If applicable)
<!-- Please follow [vetting instructions](https://wiki.edgexfoundry.org/display/FA/Vetting+Process+for+3rd+Party+Dependencies) and place results here -->

Patch:
diff --git a/example/cmd/device-simple/res/configuration.toml b/example/cmd/device-simple/res/configuration.toml
index c6a120f1..961a94c2 100644
--- a/example/cmd/device-simple/res/configuration.toml
+++ b/example/cmd/device-simple/res/configuration.toml
@@ -53,11 +53,6 @@ Port = 8500
 Type = "consul"
 
 [Clients]
-  [Clients.core-data]
-  Protocol = "http"
-  Host = "localhost"
-  Port = 59880
-
   [Clients.core-metadata]
   Protocol = "http"
   Host = "localhost"
@@ -98,7 +93,6 @@ SecretName = "redisdb"
   AsyncBufferSize = 1
   EnableAsyncReadings = true
   Labels = []
-  UseMessageBus = true
   [Device.Discovery]
     Enabled = false
     Interval = "30s"
diff --git a/internal/common/utils.go b/internal/common/utils.go
index ea1424e4..00f50134 100644
--- a/internal/common/utils.go
+++ b/internal/common/utils.go
@@ -1,7 +1,7 @@
 // -*- Mode: Go; indent-tabs-mode: t -*-
 //
 // Copyright (C) 2017-2018 Canonical Ltd
-// Copyright (C) 2018-2022 IOTech Ltd
+// Copyright (C) 2018-2023 IOTech Ltd
 //
 // SPDX-License-Identifier: Apache-2.0
 
@@ -12,11 +12,12 @@ import (
 	"fmt"
 	"time"
 
-	"github.com/edgexfoundry/device-sdk-go/v3/internal/container"
 	bootstrapInterfaces "github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/interfaces"
 	"github.com/edgexfoundry/go-mod-bootstrap/v3/config"
 	gometrics "github.com/rcrowley/go-metrics"
 
+	"github.com/edgexfoundry/device-sdk-go/v3/internal/container"
+
 	bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/container"
 	"github.com/edgexfoundry/go-mod-bootstrap/v3/di"
 	"github.com/edgexfoundry/go-mod-core-contracts/v3/clients/interfaces"
@@ -76,34 +77,23 @@ func SendEvent(event *dtos.Event, correlationID string, dic *di.Container) {
 
 	// Check event size in kilobytes
 	if configuration.MaxEventSize > 0 && int64(len(bytes)) > configuration.MaxEventSize*1024 {
-		lc.Error(fmt.Sprintf("event size exceed MaxEventSize(%d KB)", configuration.MaxEventSize))
+		lc.Errorf("event size exceed MaxEventSize(%d KB)", configuration.MaxEventSize)
 		return
 	}
 
 	sent := false
-
-	if configuration.Device.UseMessageBus {
-		mc := bootstrapContainer.MessagingClientFrom(dic.Get)
-		ctx = context.WithValue(ctx, common.ContentType, encoding) // nolint: staticcheck
-		envelope := types.NewMessageEnvelope(bytes, ctx)
-		prefix := configuration.MessageBus.Topics[config.MessageBusPublishTopicPrefix]
-		publishTopic := fmt.Sprintf("%s/%s/%s/%s", prefix, event.ProfileName, event.DeviceName, event.SourceName)
-		err = mc.Publish(envelope, publishTopic)
-		if err != nil {
-			lc.Errorf("Failed to publish event to MessageBus: %s", err)
-		}
-		lc.Debugf("Event(profileName: %s, deviceName: %s, sourceName: %s, id: %s) published to MessageBus", event.ProfileName, event.DeviceName, event.SourceName, event.Id)
-		sent = true
-	} else {
-		ec := bootstrapContainer.EventClientFrom(dic.Get)
-		_, err := ec.Add(ctx, req)
-		if err != nil {
-			lc.Errorf("Failed to push event to Coredata: %s", err)
-		} else {
-			lc.Debugf("Event(profileName: %s, deviceName: %s, sourceName: %s, id: %s) pushed to Coredata", event.ProfileName, event.DeviceName, event.SourceName, event.Id)
-		}
-		sent = true
+	mc := bootstrapContainer.MessagingClientFrom(dic.Get)
+	ctx = context.WithValue(ctx, common.ContentType, encoding) // nolint: staticcheck
+	envelope := types.NewMessageEnvelope(bytes, ctx)
+	prefix := configuration.MessageBus.Topics[config.MessageBusPublishTopicPrefix]
+	publishTopic := fmt.Sprintf("%s/%s/%s/%s", prefix, event.ProfileName, event.DeviceName, event.SourceName)
+	err = mc.Publish(envelope, publishTopic)
+	if err != nil {
+		lc.Errorf("Failed to publish event to MessageBus: %s", err)
+		return
 	}
+	lc.Debugf("Event(profileName: %s, deviceName: %s, sourceName: %s, id: %s) published to MessageBus", event.ProfileName, event.DeviceName, event.SourceName, event.Id)
+	sent = true
 
 	if sent {
 		eventsSent.Inc(1)
diff --git a/internal/config/types.go b/internal/config/types.go
index 56130024..2645d3a2 100644
--- a/internal/config/types.go
+++ b/internal/config/types.go
@@ -57,8 +57,6 @@ type DeviceInfo struct {
 	EnableAsyncReadings bool
 	// Labels are properties applied to the device service to help with searching
 	Labels []string
-	// UseMessageBus indicates whether or not the Event are published directly to the MessageBus
-	UseMessageBus bool
 }
 
 // DiscoveryInfo is a struct which contains configuration of device auto discovery.
diff --git a/pkg/service/main.go b/pkg/service/main.go
index e6881736..dfa9286e 100644
--- a/pkg/service/main.go
+++ b/pkg/service/main.go
@@ -83,7 +83,7 @@ func Main(serviceName string, serviceVersion string, proto interface{}, ctx cont
 			httpServer.BootstrapHandler,
 			messageBusBootstrapHandler,
 			handlers.NewServiceMetrics(ds.ServiceName).BootstrapHandler, // Must be after Messaging
-			clientBootstrapHandler,
+			handlers.NewClientsBootstrap().BootstrapHandler,
 			autoevent.BootstrapHandler,
 			NewBootstrap(router).BootstrapHandler,
 			autodiscovery.BootstrapHandler,
@@ -93,39 +93,22 @@ func Main(serviceName string, serviceVersion string, proto interface{}, ctx cont
 	ds.Stop(false)
 }
 
-func clientBootstrapHandler(ctx context.Context, wg *sync.WaitGroup, startupTimer startup.Timer, dic *di.Container) bool {
-	configuration := container.ConfigurationFrom(dic.Get)
-	if configuration.Device.UseMessageBus {
-		delete(configuration.Clients, common.CoreDataServiceKey)
+func messageBusBootstrapHandler(ctx context.Context, wg *sync.WaitGroup, startupTimer startup.Timer, dic *di.Container) bool {
+	if !handlers.MessagingBootstrapHandler(ctx, wg, startupTimer, dic) {
+		return false
 	}
 
-	if !handlers.NewClientsBootstrap().BootstrapHandler(ctx, wg, startupTimer, dic) {
+	lc := bootstrapContainer.LoggingClientFrom(dic.Get)
+	err := messaging.SubscribeCommands(ctx, dic)
+	if err != nil {
+		lc.Errorf("Failed to subscribe internal command request: %v", err)
 		return false
 	}
 
-	return true
-}
-
-func messageBusBootstrapHandler(ctx context.Context, wg *sync.WaitGroup, startupTimer startup.Timer, dic *di.Container) bool {
-	configuration := container.ConfigurationFrom(dic.Get)
-	if configuration.Device.UseMessageBus {
-		if !handlers.MessagingBootstrapHandler(ctx, wg, startupTimer, dic) {
-			return false
-		}
-
-		lc := bootstrapContainer.LoggingClientFrom(dic.Get)
-
-		err := messaging.SubscribeCommands(ctx, dic)
-		if err != nil {
-			lc.Errorf("Failed to subscribe internal command request: %v", err)
-			return false
-		}
-
-		err = messaging.DeviceCallback(ctx, dic)
-		if err != nil {
-			lc.Errorf("Failed to subscribe Metadata system event: %v", err)
-			return false
-		}
+	err = messaging.DeviceCallback(ctx, dic)
+	if err != nil {
+		lc.Errorf("Failed to subscribe Metadata system event: %v", err)
+		return false
 	}
 
 	return true


Test patch:
diff --git a/internal/common/utils_test.go b/internal/common/utils_test.go
index 0b1ef044..70a0f38d 100644
--- a/internal/common/utils_test.go
+++ b/internal/common/utils_test.go
@@ -1,5 +1,5 @@
 //
-// Copyright (C) 2022 IOTech Ltd
+// Copyright (C) 2022-2023 IOTech Ltd
 //
 // SPDX-License-Identifier: Apache-2.0
 
@@ -12,12 +12,10 @@ import (
 	bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/container"
 	"github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/interfaces/mocks"
 	"github.com/edgexfoundry/go-mod-bootstrap/v3/di"
-	clientMocks "github.com/edgexfoundry/go-mod-core-contracts/v3/clients/interfaces/mocks"
 	"github.com/edgexfoundry/go-mod-core-contracts/v3/clients/logger"
 	mocks2 "github.com/edgexfoundry/go-mod-core-contracts/v3/clients/logger/mocks"
 	"github.com/edgexfoundry/go-mod-core-contracts/v3/common"
 	"github.com/edgexfoundry/go-mod-core-contracts/v3/dtos"
-	dtoCommon "github.com/edgexfoundry/go-mod-core-contracts/v3/dtos/common"
 	"github.com/edgexfoundry/go-mod-core-contracts/v3/dtos/requests"
 	msgMocks "github.com/edgexfoundry/go-mod-messaging/v3/messaging/mocks"
 	"github.com/stretchr/testify/assert"
@@ -63,7 +61,6 @@ func NewMockDIC() *di.Container {
 }
 
 func TestSendEvent(t *testing.T) {
-
 	event := buildEvent()
 	req := requests.NewAddEventRequest(event)
 	bytes, _, err := req.Encode()
@@ -74,20 +71,16 @@ func TestSendEvent(t *testing.T) {
 		name          string
 		event         *dtos.Event
 		maxEventSize  int64
-		useMessageBus bool
 		eventTooLarge bool
 	}{
-		{"Valid, unlimited max event size", &event, 0, false, false},
-		{"Valid, publish to message bus", &event, int64(eventSize + 1), true, false},
-		{"Valid, push to core data ", &event, int64(eventSize + 1), false, false},
-		{"Invalid, over max event size", &event, int64(eventSize - 1), false, true},
+		{"Valid, unlimited max event size", &event, 0, false},
+		{"Valid, publish to message bus", &event, int64(eventSize + 1), false},
+		{"Invalid, over max event size", &event, int64(eventSize - 1), true},
 	}
 
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
 			dic := NewMockDIC()
-			ecMock := &clientMocks.EventClient{}
-			ecMock.On("Add", mock.Anything, mock.Anything).Return(dtoCommon.BaseWithIdResponse{}, nil)
 			mcMock := &msgMocks.MessageClient{}
 			mcMock.On("Publish", mock.Anything, mock.Anything).Return(nil)
 
@@ -95,36 +88,22 @@ func TestSendEvent(t *testing.T) {
 				container.ConfigurationName: func(get di.Get) interface{} {
 					return &config.ConfigurationStruct{
 						MaxEventSize: tt.maxEventSize,
-						Device: config.DeviceInfo{
-							UseMessageBus: tt.useMessageBus,
-						},
 					}
 				},
 				bootstrapContainer.MessagingClientName: func(get di.Get) interface{} {
 					return mcMock
 				},
-				bootstrapContainer.EventClientName: func(get di.Get) interface{} {
-					return ecMock
-				},
 			})
 
 			InitializeSentMetrics(logger.NewMockClient(), dic)
 
 			SendEvent(tt.event, testUUIDString, dic)
 			if tt.eventTooLarge {
-				ecMock.AssertNumberOfCalls(t, "Add", 0)
 				mcMock.AssertNumberOfCalls(t, "Publish", 0)
 				assert.Equal(t, int64(0), eventsSent.Count())
 				assert.Equal(t, int64(0), readingsSent.Count())
-			} else if tt.useMessageBus {
-				ecMock.AssertNumberOfCalls(t, "Add", 0)
-				mcMock.AssertNumberOfCalls(t, "Publish", 1)
 			} else {
-				ecMock.AssertNumberOfCalls(t, "Add", 1)
-				mcMock.AssertNumberOfCalls(t, "Publish", 0)
-			}
-
-			if !tt.eventTooLarge {
+				mcMock.AssertNumberOfCalls(t, "Publish", 1)
 				assert.Equal(t, int64(1), eventsSent.Count())
 				assert.Equal(t, int64(1), readingsSent.Count())
 			}