File size: 5,108 Bytes
8d3471e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package devcapture

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"ds2api/internal/util"

	"github.com/google/uuid"
)

const (
	defaultLimit        = 20
	defaultMaxBodyBytes = 5 * 1024 * 1024
	maxLimit            = 50
)

type Entry struct {
	ID                string `json:"id"`
	CreatedAt         int64  `json:"created_at"`
	Label             string `json:"label"`
	URL               string `json:"url"`
	AccountID         string `json:"account_id,omitempty"`
	StatusCode        int    `json:"status_code"`
	RequestBody       string `json:"request_body"`
	ResponseBody      string `json:"response_body"`
	ResponseTruncated bool   `json:"response_truncated"`
}

type Store struct {
	mu           sync.Mutex
	enabled      bool
	limit        int
	maxBodyBytes int
	items        []Entry
}

type Session struct {
	store      *Store
	id         string
	createdAt  int64
	label      string
	url        string
	accountID  string
	requestRaw string
}

type captureBody struct {
	rc         io.ReadCloser
	s          *Session
	statusCode int
	buf        strings.Builder
	truncated  bool
	finalized  bool
}

var (
	globalOnce sync.Once
	globalInst *Store
)

func Global() *Store {
	globalOnce.Do(func() {
		globalInst = NewFromEnv()
	})
	return globalInst
}

func NewFromEnv() *Store {
	enabled := !isVercelRuntime()
	if raw, ok := os.LookupEnv("DS2API_DEV_PACKET_CAPTURE"); ok {
		enabled = parseBool(raw)
	}
	limit := parseIntWithDefault(os.Getenv("DS2API_DEV_PACKET_CAPTURE_LIMIT"), defaultLimit)
	if limit < 1 {
		limit = defaultLimit
	}
	if limit > maxLimit {
		limit = maxLimit
	}
	maxBodyBytes := parseIntWithDefault(os.Getenv("DS2API_DEV_PACKET_CAPTURE_MAX_BODY_BYTES"), defaultMaxBodyBytes)
	if maxBodyBytes < 1024 {
		maxBodyBytes = defaultMaxBodyBytes
	}
	return &Store{
		enabled:      enabled,
		limit:        limit,
		maxBodyBytes: maxBodyBytes,
		items:        make([]Entry, 0, limit),
	}
}

func isVercelRuntime() bool {
	return strings.TrimSpace(os.Getenv("VERCEL")) != "" || strings.TrimSpace(os.Getenv("NOW_REGION")) != ""
}

func (s *Store) Enabled() bool {
	if s == nil {
		return false
	}
	return s.enabled
}

func (s *Store) Limit() int {
	if s == nil {
		return defaultLimit
	}
	return s.limit
}

func (s *Store) MaxBodyBytes() int {
	if s == nil {
		return defaultMaxBodyBytes
	}
	return s.maxBodyBytes
}

func (s *Store) Snapshot() []Entry {
	if s == nil {
		return nil
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	out := make([]Entry, len(s.items))
	copy(out, s.items)
	return out
}

func (s *Store) Clear() {
	if s == nil {
		return
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	s.items = s.items[:0]
}

func (s *Store) Start(label, url, accountID string, requestPayload any) *Session {
	if s == nil || !s.enabled {
		return nil
	}
	return &Session{
		store:      s,
		id:         "cap_" + strings.ReplaceAll(uuid.NewString(), "-", ""),
		createdAt:  time.Now().Unix(),
		label:      strings.TrimSpace(label),
		url:        strings.TrimSpace(url),
		accountID:  strings.TrimSpace(accountID),
		requestRaw: marshalPayload(requestPayload),
	}
}

func (s *Session) WrapBody(rc io.ReadCloser, statusCode int) io.ReadCloser {
	if s == nil || rc == nil {
		return rc
	}
	return &captureBody{
		rc:         rc,
		s:          s,
		statusCode: statusCode,
	}
}

func (c *captureBody) Read(p []byte) (int, error) {
	n, err := c.rc.Read(p)
	if n > 0 {
		c.append(string(p[:n]))
	}
	if err == io.EOF {
		c.finalize()
	}
	return n, err
}

func (c *captureBody) Close() error {
	err := c.rc.Close()
	c.finalize()
	return err
}

func (c *captureBody) append(chunk string) {
	if chunk == "" || c.s == nil || c.s.store == nil {
		return
	}
	maxLen := c.s.store.maxBodyBytes
	current := c.buf.Len()
	if current >= maxLen {
		c.truncated = true
		return
	}
	remain := maxLen - current
	if len(chunk) > remain {
		truncated, _ := util.TruncateUTF8Bytes(chunk, remain)
		c.buf.WriteString(truncated)
		c.truncated = true
		return
	}
	c.buf.WriteString(chunk)
}

func (c *captureBody) finalize() {
	if c.finalized || c.s == nil || c.s.store == nil {
		return
	}
	c.finalized = true
	entry := Entry{
		ID:                c.s.id,
		CreatedAt:         c.s.createdAt,
		Label:             c.s.label,
		URL:               c.s.url,
		AccountID:         c.s.accountID,
		StatusCode:        c.statusCode,
		RequestBody:       c.s.requestRaw,
		ResponseBody:      c.buf.String(),
		ResponseTruncated: c.truncated,
	}
	c.s.store.push(entry)
}

func (s *Store) push(entry Entry) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.items = append([]Entry{entry}, s.items...)
	if len(s.items) > s.limit {
		s.items = s.items[:s.limit]
	}
}

func marshalPayload(v any) string {
	b, err := json.Marshal(v)
	if err != nil {
		return fmt.Sprintf("%v", v)
	}
	return string(b)
}

func parseBool(v string) bool {
	switch strings.ToLower(strings.TrimSpace(v)) {
	case "1", "true", "yes", "on":
		return true
	default:
		return false
	}
}

func parseIntWithDefault(raw string, d int) int {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return d
	}
	n, err := strconv.Atoi(raw)
	if err != nil {
		return d
	}
	return n
}