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

Add RPC Timout request and prevent blocking while waiting response #107

Closed
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
bin/
autopaho/cmd/rpc/.env
autopaho/cmd/rpc/.env
.idea
17 changes: 13 additions & 4 deletions paho/extensions/rpc/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ package rpc

import (
"context"
"errors"
"fmt"
"sync"
"time"

"github.com/eclipse/paho.golang/paho"
)

const defaultRequestTimeout = time.Second * 10
yogihardi marked this conversation as resolved.
Show resolved Hide resolved

// Handler is the struct providing a request/response functionality for the paho
// MQTT v5 client
type Handler struct {
Expand Down Expand Up @@ -54,7 +57,7 @@ func (h *Handler) getCorrelIDChan(cID string) chan *paho.Publish {
return rChan
}

func (h *Handler) Request(ctx context.Context, pb *paho.Publish) (*paho.Publish, error) {
func (h *Handler) Request(ctx context.Context, pb *paho.Publish) (resp *paho.Publish, err error) {
cID := fmt.Sprintf("%d", time.Now().UnixNano())
rChan := make(chan *paho.Publish)

Expand All @@ -68,13 +71,19 @@ func (h *Handler) Request(ctx context.Context, pb *paho.Publish) (*paho.Publish,
pb.Properties.ResponseTopic = fmt.Sprintf("%s/responses", h.c.ClientID)
pb.Retain = false

_, err := h.c.Publish(ctx, pb)
_, err = h.c.Publish(ctx, pb)
if err != nil {
return nil, err
}

resp := <-rChan
return resp, nil
select {
case <-time.After(defaultRequestTimeout):
yogihardi marked this conversation as resolved.
Show resolved Hide resolved
return nil, errors.New("request timeout")
case <-ctx.Done():
return nil, ctx.Err()
case resp = <-rChan:
return resp, nil
}
}

func (h *Handler) responseHandler(pb *paho.Publish) {
Expand Down