diff options
author | Valery Piashchynski <[email protected]> | 2020-12-17 12:13:55 +0300 |
---|---|---|
committer | GitHub <[email protected]> | 2020-12-17 12:13:55 +0300 |
commit | ee0cb478c74c393a35155c2bf51e1ef260e0e5e2 (patch) | |
tree | 2c99d4c6e2b2e9e3fa155d5d68a9d471c9aeeb9b /internal/protocol.go | |
parent | a1dc59cabb6e63eab232922f4eb5a19dbd168f44 (diff) | |
parent | edf924b37bcdad14eb31014c571ab58720aa178f (diff) |
Merge pull request #452 from spiral/refactor/splitv2.0.0-alpha23
Refactor/split
Diffstat (limited to 'internal/protocol.go')
-rwxr-xr-x | internal/protocol.go | 93 |
1 files changed, 93 insertions, 0 deletions
diff --git a/internal/protocol.go b/internal/protocol.go new file mode 100755 index 00000000..5aa681eb --- /dev/null +++ b/internal/protocol.go @@ -0,0 +1,93 @@ +package internal + +import ( + "os" + + j "github.com/json-iterator/go" + "github.com/spiral/errors" + "github.com/spiral/goridge/v3" +) + +var json = j.ConfigCompatibleWithStandardLibrary + +type StopCommand struct { + Stop bool `json:"stop"` +} + +type pidCommand struct { + Pid int `json:"pid"` +} + +func SendControl(rl goridge.Relay, v interface{}) error { + const op = errors.Op("send control frame") + frame := goridge.NewFrame() + frame.WriteVersion(goridge.VERSION_1) + frame.WriteFlags(goridge.CONTROL) + + if data, ok := v.([]byte); ok { + // check if payload no more that 4Gb + if uint32(len(data)) > ^uint32(0) { + return errors.E(op, errors.Str("payload is more that 4gb")) + } + + frame.WritePayloadLen(uint32(len(data))) + frame.WritePayload(data) + frame.WriteCRC() + + err := rl.Send(frame) + if err != nil { + return errors.E(op, err) + } + return nil + } + + data, err := json.Marshal(v) + if err != nil { + return errors.E(op, errors.Errorf("invalid payload: %s", err)) + } + + frame.WritePayloadLen(uint32(len(data))) + frame.WritePayload(data) + frame.WriteCRC() + + err = rl.Send(frame) + if err != nil { + return errors.E(op, err) + } + + return nil +} + +func FetchPID(rl goridge.Relay) (int64, error) { + const op = errors.Op("fetchPID") + err := SendControl(rl, pidCommand{Pid: os.Getpid()}) + if err != nil { + return 0, errors.E(op, err) + } + + frameR := goridge.NewFrame() + err = rl.Receive(frameR) + if !frameR.VerifyCRC() { + return 0, errors.E(op, errors.Str("CRC mismatch")) + } + if err != nil { + return 0, errors.E(op, err) + } + if frameR == nil { + return 0, errors.E(op, errors.Str("nil frame received")) + } + + flags := frameR.ReadFlags() + + if flags&(byte(goridge.CONTROL)) == 0 { + return 0, errors.E(op, errors.Str("unexpected response, header is missing, no CONTROL flag")) + } + + link := &pidCommand{} + err = json.Unmarshal(frameR.Payload(), link) + if err != nil { + return 0, errors.E(op, err) + } + + return int64(link.Pid), nil +} |