aboutsummaryrefslogtreecommitdiff
path: root/internal/ingest/client.go
blob: 0f9ad432a12e269a785da6a567416f6f8a08c4a7 (plain) (blame)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package ingest

import (
	"bufio"
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/Fuwn/plutia/internal/types"
)

type Client struct {
	source string
	http   *http.Client
}

func NewClient(source string) *Client {
	transport := &http.Transport{
		Proxy:                 http.ProxyFromEnvironment,
		DialContext:           (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
		ForceAttemptHTTP2:     true,
		MaxIdleConns:          256,
		MaxIdleConnsPerHost:   64,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
	}
	return &Client{
		source: strings.TrimRight(source, "/"),
		http: &http.Client{
			Timeout:   60 * time.Second,
			Transport: transport,
		},
	}
}

func (c *Client) FetchExport(ctx context.Context, after uint64) ([]types.ExportRecord, error) {
	return c.FetchExportLimited(ctx, after, 0)
}

func (c *Client) FetchExportLimited(ctx context.Context, after uint64, limit uint64) ([]types.ExportRecord, error) {
	if strings.HasPrefix(c.source, "file://") || strings.HasSuffix(c.source, ".ndjson") || strings.HasSuffix(c.source, ".json") {
		return c.fetchFromFile(after, limit)
	}
	u, err := url.Parse(c.source)
	if err != nil {
		return nil, fmt.Errorf("parse plc source: %w", err)
	}
	u.Path = strings.TrimRight(u.Path, "/") + "/export"
	q := u.Query()
	q.Set("after", fmt.Sprintf("%d", after))
	u.RawQuery = q.Encode()

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
	if err != nil {
		return nil, fmt.Errorf("new request: %w", err)
	}
	resp, err := c.http.Do(req)
	if err != nil {
		return nil, fmt.Errorf("fetch export: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		b, _ := io.ReadAll(io.LimitReader(resp.Body, 4*1024))
		return nil, fmt.Errorf("export response %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
	}
	return decodeExportBody(resp.Body, limit)
}

func decodeExportBody(r io.Reader, limit uint64) ([]types.ExportRecord, error) {
	br := bufio.NewReader(r)
	first, err := peekFirstNonSpace(br)
	if err != nil {
		if err == io.EOF {
			return nil, nil
		}
		return nil, err
	}

	if first == '[' {
		b, err := io.ReadAll(br)
		if err != nil {
			return nil, fmt.Errorf("read export body: %w", err)
		}
		trimmed := bytes.TrimSpace(b)
		var records []types.ExportRecord
		if err := json.Unmarshal(trimmed, &records); err != nil {
			return nil, fmt.Errorf("decode export json array: %w", err)
		}
		if limit > 0 && uint64(len(records)) > limit {
			records = records[:limit]
		}
		return records, nil
	}
	out := make([]types.ExportRecord, 0, 1024)
	for {
		line, err := br.ReadBytes('\n')
		isEOF := errors.Is(err, io.EOF)
		if err != nil && !isEOF {
			return nil, fmt.Errorf("read ndjson line: %w", err)
		}
		if limit > 0 && uint64(len(out)) >= limit {
			return out, nil
		}
		trimmed := bytes.TrimSpace(line)
		if len(trimmed) > 0 {
			var rec types.ExportRecord
			if err := json.Unmarshal(trimmed, &rec); err != nil {
				if isEOF && isTrailingNDJSONPartial(err) {
					return out, nil
				}
				return nil, fmt.Errorf("decode ndjson line: %w", err)
			}
			out = append(out, rec)
		}
		if isEOF {
			break
		}
	}
	return out, nil
}

func isTrailingNDJSONPartial(err error) bool {
	if !errors.Is(err, io.ErrUnexpectedEOF) && !strings.Contains(err.Error(), "unexpected end of JSON input") {
		return false
	}
	return true
}

func peekFirstNonSpace(br *bufio.Reader) (byte, error) {
	for {
		b, err := br.ReadByte()
		if err != nil {
			return 0, err
		}
		if !isSpace(b) {
			if err := br.UnreadByte(); err != nil {
				return 0, fmt.Errorf("unread byte: %w", err)
			}
			return b, nil
		}
	}
}

func isSpace(b byte) bool {
	switch b {
	case ' ', '\n', '\t', '\r':
		return true
	default:
		return false
	}
}

func (c *Client) fetchFromFile(after uint64, limit uint64) ([]types.ExportRecord, error) {
	path := c.source
	if strings.HasPrefix(path, "file://") {
		path = strings.TrimPrefix(path, "file://")
	}
	path = filepath.Clean(path)
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read source file: %w", err)
	}
	recs, err := decodeExportBody(bytes.NewReader(b), 0)
	if err != nil {
		return nil, err
	}
	out := make([]types.ExportRecord, 0, len(recs))
	for _, r := range recs {
		if r.Seq <= after {
			continue
		}
		out = append(out, r)
		if limit > 0 && uint64(len(out)) >= limit {
			break
		}
	}
	return out, nil
}