Skip to content

Commit

Permalink
feat(sdk): Add MakeItStop (#613)
Browse files Browse the repository at this point in the history
Store reference on the sdk to a CancelFunc created in MakeItRun and
expose to enable clean programmatic exits.

Signed-off-by: Alex Ullrich <[email protected]>
  • Loading branch information
Alex Ullrich authored Jan 8, 2021
1 parent 8220514 commit baae3ee
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
19 changes: 19 additions & 0 deletions appsdk/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ type AppFunctionsSDK struct {
serviceKeyOverride string
backgroundChannel <-chan types.MessageEnvelope
customTriggerFactories map[string]func(sdk *AppFunctionsSDK) (Trigger, error)
stop context.CancelFunc
}

// AddRoute allows you to leverage the existing webserver to add routes.
Expand All @@ -148,10 +149,23 @@ func (sdk *AppFunctionsSDK) AddBackgroundPublisher(capacity int) BackgroundPubli
return pub
}

// MakeItStop will force the service loop to exit in the same fashion as SIGINT/SIGTERM received from the OS
func (sdk *AppFunctionsSDK) MakeItStop() {
if sdk.stop != nil {
sdk.stop()
} else {
sdk.LoggingClient.Warn("MakeItStop called but no stop handler set on SDK - is the service running?")
}
}

// MakeItRun will initialize and start the trigger as specified in the
// configuration. It will also configure the webserver and start listening on
// the specified port.
func (sdk *AppFunctionsSDK) MakeItRun() error {
runCtx, stop := context.WithCancel(context.Background())

sdk.stop = stop

httpErrors := make(chan error)
defer close(httpErrors)

Expand Down Expand Up @@ -199,8 +213,13 @@ func (sdk *AppFunctionsSDK) MakeItRun() error {

case signalReceived := <-signals:
sdk.LoggingClient.Info("Terminating: " + signalReceived.String())

case <-runCtx.Done():
sdk.LoggingClient.Info("Terminating: sdk.MakeItStop called")
}

sdk.stop = nil

if sdk.config.Writable.StoreAndForward.Enabled {
sdk.storeForwardCancelCtx()
sdk.storeForwardWg.Wait()
Expand Down
17 changes: 17 additions & 0 deletions appsdk/sdk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -462,3 +462,20 @@ func TestSetServiceKey(t *testing.T) {
})
}
}

func TestMakeItStop(t *testing.T) {
stopCalled := false

sdk := AppFunctionsSDK{
stop: func() {
stopCalled = true
},
LoggingClient: logger.NewMockClient(),
}

sdk.MakeItStop()
require.True(t, stopCalled, "Cancel function set at sdk.stop should be called if set")

sdk.stop = nil
sdk.MakeItStop() //should avoid nil pointer
}

0 comments on commit baae3ee

Please sign in to comment.