summaryrefslogtreecommitdiff
path: root/plugins/jobs/protocol.go
blob: 9d769fdf1111cbbc04ef3c4742ab791e3ba50cc0 (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 jobs

import (
	json "github.com/json-iterator/go"
	"github.com/spiral/errors"
	pq "github.com/spiral/roadrunner/v2/pkg/priority_queue"
	"github.com/spiral/roadrunner/v2/plugins/logger"
)

type Type uint32

const (
	NoError Type = iota
	Error
)

// internal worker protocol (jobs mode)
type protocol struct {
	// message type, see Type
	T Type `json:"type"`
	// Payload
	Data json.RawMessage `json:"data"`
}

type errorResp struct {
	Msg     string              `json:"message"`
	Requeue bool                `json:"requeue"`
	Delay   int64               `json:"delay_seconds"`
	Headers map[string][]string `json:"headers"`
}

func handleResponse(resp []byte, jb pq.Item, log logger.Logger) error {
	const op = errors.Op("jobs_handle_response")
	// TODO(rustatian) to sync.Pool
	p := &protocol{}

	err := json.Unmarshal(resp, p)
	if err != nil {
		return errors.E(op, err)
	}

	switch p.T {
	// likely case
	case NoError:
		err = jb.Ack()
		if err != nil {
			return errors.E(op, err)
		}
	case Error:
		// TODO(rustatian) to sync.Pool
		er := &errorResp{}

		err = json.Unmarshal(p.Data, er)
		if err != nil {
			return errors.E(op, err)
		}

		log.Error("jobs protocol error", "error", er.Msg, "delay", er.Delay, "requeue", er.Requeue)

		if er.Requeue {
			err = jb.Requeue(er.Headers, er.Delay)
			if err != nil {
				return errors.E(op, err)
			}
			return nil
		}

		return errors.E(op, errors.Errorf("jobs response error: %v", er.Msg))

	default:
		err = jb.Ack()
		if err != nil {
			return errors.E(op, err)
		}
	}

	return nil
}