summaryrefslogtreecommitdiff
path: root/plugins/jobs/protocol.go
blob: adfd07842cac917d0a1e794c6891647f67327fb9 (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
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 (
	Error Type = iota
	NoError
)

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

type errorResp struct {
	Msg     string `json:"message"`
	Requeue bool   `json:"requeue"`
	Delay   uint32 `json:"delay_seconds"`
}

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 {
	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("error protocol type", "error", er.Msg, "delay", er.Delay, "requeue", er.Requeue)

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

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

	return nil
}