File size: 6,815 Bytes
feccc69 33b8f8e feccc69 33b8f8e feccc69 33b8f8e feccc69 33b8f8e feccc69 33b8f8e | 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 | package rawsample
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/google/uuid"
)
const DefaultMaxSamples = 50
var referenceMarkerRe = regexp.MustCompile(`(?i)\[reference:\s*\d+\]`)
type CaptureRound struct {
Label string `json:"label,omitempty"`
URL string `json:"url,omitempty"`
StatusCode int `json:"status_code"`
ResponseBytes int `json:"response_bytes"`
}
type CaptureSummary struct {
Label string `json:"label,omitempty"`
URL string `json:"url,omitempty"`
StatusCode int `json:"status_code"`
ResponseBytes int `json:"response_bytes"`
Rounds []CaptureRound `json:"rounds,omitempty"`
ContainsReferenceMarkers bool `json:"contains_reference_markers,omitempty"`
ReferenceMarkerCount int `json:"reference_marker_count,omitempty"`
ContainsFinishedToken bool `json:"contains_finished_token,omitempty"`
FinishedTokenCount int `json:"finished_token_count,omitempty"`
}
type Meta struct {
SampleID string `json:"sample_id"`
CapturedAtUTC string `json:"captured_at_utc"`
Source string `json:"source,omitempty"`
Request any `json:"request"`
Capture CaptureSummary `json:"capture"`
}
type PersistOptions struct {
RootDir string
SampleID string
Source string
Request any
Capture CaptureSummary
UpstreamBody []byte
// MaxSamples limits how many sample directories are retained in RootDir.
// If <= 0, DefaultMaxSamples is used. Excess samples (oldest first) are pruned after persist.
MaxSamples int
}
type SavedSample struct {
SampleID string
Dir string
MetaPath string
UpstreamPath string
Meta Meta
}
func Persist(opts PersistOptions) (SavedSample, error) {
root := strings.TrimSpace(opts.RootDir)
if root == "" {
return SavedSample{}, errors.New("root dir is required")
}
if len(opts.UpstreamBody) == 0 {
return SavedSample{}, errors.New("upstream body is required")
}
if err := os.MkdirAll(root, 0o755); err != nil {
return SavedSample{}, fmt.Errorf("create root dir: %w", err)
}
baseID := NormalizeSampleID(opts.SampleID)
if baseID == "" {
baseID = DefaultSampleID("capture")
}
sampleID, err := uniqueSampleID(root, baseID)
if err != nil {
return SavedSample{}, err
}
tempID := ".tmp-" + sampleID + "-" + strings.ToLower(strings.ReplaceAll(uuid.NewString(), "-", ""))
tempDir := filepath.Join(root, tempID)
finalDir := filepath.Join(root, sampleID)
if err := os.MkdirAll(tempDir, 0o755); err != nil {
return SavedSample{}, fmt.Errorf("create temp dir: %w", err)
}
cleanup := func() {
_ = os.RemoveAll(tempDir)
}
upstreamPath := filepath.Join(tempDir, "upstream.stream.sse")
if err := os.WriteFile(upstreamPath, opts.UpstreamBody, 0o644); err != nil {
cleanup()
return SavedSample{}, fmt.Errorf("write upstream stream: %w", err)
}
now := time.Now().UTC()
capture := opts.Capture
capture.ResponseBytes = len(opts.UpstreamBody)
capture.ContainsReferenceMarkers, capture.ReferenceMarkerCount, capture.ContainsFinishedToken, capture.FinishedTokenCount = analyzeBytes(opts.UpstreamBody)
meta := Meta{
SampleID: sampleID,
CapturedAtUTC: now.Format(time.RFC3339),
Source: strings.TrimSpace(opts.Source),
Request: opts.Request,
Capture: capture,
}
metaBytes, err := json.MarshalIndent(meta, "", " ")
if err != nil {
cleanup()
return SavedSample{}, fmt.Errorf("marshal meta: %w", err)
}
metaPath := filepath.Join(tempDir, "meta.json")
if err := os.WriteFile(metaPath, append(metaBytes, '\n'), 0o644); err != nil {
cleanup()
return SavedSample{}, fmt.Errorf("write meta: %w", err)
}
if err := os.Rename(tempDir, finalDir); err != nil {
cleanup()
return SavedSample{}, fmt.Errorf("promote sample dir: %w", err)
}
maxKeep := opts.MaxSamples
if maxKeep <= 0 {
maxKeep = DefaultMaxSamples
}
pruneExcessSamples(root, maxKeep)
return SavedSample{
SampleID: sampleID,
Dir: finalDir,
MetaPath: filepath.Join(finalDir, "meta.json"),
UpstreamPath: filepath.Join(finalDir, "upstream.stream.sse"),
Meta: meta,
}, nil
}
func NormalizeSampleID(raw string) string {
raw = strings.TrimSpace(strings.ToLower(raw))
if raw == "" {
return ""
}
var b strings.Builder
prevDash := false
for _, r := range raw {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '-', r == '_', r == '.':
b.WriteRune(r)
prevDash = false
default:
if !prevDash {
b.WriteRune('-')
prevDash = true
}
}
}
out := strings.Trim(b.String(), "-_.")
if out == "" {
return ""
}
return out
}
func DefaultSampleID(prefix string) string {
prefix = NormalizeSampleID(prefix)
if prefix == "" {
prefix = "capture"
}
return fmt.Sprintf("%s-%s", prefix, time.Now().UTC().Format("20060102T150405Z"))
}
func uniqueSampleID(root, base string) (string, error) {
if base == "" {
base = DefaultSampleID("capture")
}
candidate := base
for i := 2; ; i++ {
finalDir := filepath.Join(root, candidate)
if _, err := os.Stat(finalDir); err != nil {
if os.IsNotExist(err) {
return candidate, nil
}
return "", fmt.Errorf("stat sample dir: %w", err)
}
candidate = fmt.Sprintf("%s-%d", base, i)
}
}
func analyzeBytes(raw []byte) (containsReferenceMarkers bool, referenceMarkerCount int, containsFinishedToken bool, finishedTokenCount int) {
if len(raw) == 0 {
return false, 0, false, 0
}
text := string(raw)
referenceMarkerCount = len(referenceMarkerRe.FindAllStringIndex(text, -1))
containsReferenceMarkers = referenceMarkerCount > 0
upper := strings.ToUpper(text)
finishedTokenCount = strings.Count(upper, "FINISHED")
containsFinishedToken = finishedTokenCount > 0
return
}
// pruneExcessSamples removes the oldest sample directories beyond maxKeep.
// Errors during individual removals are ignored (best-effort cleanup).
func pruneExcessSamples(rootDir string, maxKeep int) {
if maxKeep <= 0 {
return
}
entries, err := os.ReadDir(rootDir)
if err != nil {
return
}
type sampleInfo struct {
name string
mtime time.Time
}
var samples []sampleInfo
for _, entry := range entries {
if !entry.IsDir() {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
samples = append(samples, sampleInfo{
name: entry.Name(),
mtime: info.ModTime(),
})
}
if len(samples) <= maxKeep {
return
}
sort.Slice(samples, func(i, j int) bool {
return samples[i].mtime.After(samples[j].mtime)
})
for _, s := range samples[maxKeep:] {
_ = os.RemoveAll(filepath.Join(rootDir, s.name))
}
}
|