~tsileo/blobstash

ref: b178995e346d blobstash/pkg/client/oplog/oplog.go -rw-r--r-- 2.1 KiB
b178995eThomas Sileo vendor: update deps 2 years ago
                                                                                
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package oplog // import "a4.io/blobstash/pkg/client/oplog"

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"net/http"

	"a4.io/blobstash/pkg/client/clientutil"
)

var (
	headerEvent = []byte("event:")
	headerData  = []byte("data:")
)

type Oplog struct {
	client *clientutil.ClientUtil
}

type Op struct {
	Event string
	Data  string
}

func New(client *clientutil.ClientUtil) *Oplog {
	return &Oplog{client}
}

// Get fetch the given blob from the remote BlobStash instance.
func (o *Oplog) GetBlob(ctx context.Context, hash string) ([]byte, error) {
	resp, err := o.client.Get(fmt.Sprintf("/api/blobstore/blob/%s", hash))
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if err := clientutil.ExpectStatusCode(resp, http.StatusOK); err != nil {
		if err.IsNotFound() {
			return nil, clientutil.ErrBlobNotFound
		}
		return nil, err
	}

	return clientutil.Decode(resp)
}

// FIXME(tsileo): use a ctx and support cancelation
func (o *Oplog) Notify(ctx context.Context, ops chan<- *Op, connCallback func()) error {
	resp, err := o.client.Get("/_oplog/")
	if err != nil {
		return err
	}

	if err := clientutil.ExpectStatusCode(resp, http.StatusOK); err != nil {
		return err
	}

	if connCallback != nil {
		connCallback()
	}

	reader := bufio.NewReader(resp.Body)

	defer resp.Body.Close()
	// TODO(tsileo): a select with ctx cancel?
	var op *Op
	for {
		// Read each new line and process the type of event
		line, err := reader.ReadBytes('\n')
		if err != nil {
			return err
		}
		switch {
		case bytes.HasPrefix(line, headerEvent):
			if op == nil {
				op = &Op{}
			}
			// Remove header
			event := bytes.Replace(line, headerEvent, []byte(""), 1)
			op.Event = string(event[1 : len(event)-1]) // Remove initial space and newline
		case bytes.HasPrefix(line, headerData):
			if op == nil {
				op = &Op{}
			}
			// Remove header
			data := bytes.Replace(line, headerData, []byte(""), 1)
			op.Data = string(data[1 : len(data)-1]) // Remove initial space and newline
		default:
			if op != nil {
				// Skip the heartbeat
				if op.Event != "heartbeat" {
					ops <- op
				}
				op = nil
			}
		}
	}
}