|
| 1 | +//go:build ignore |
| 2 | + |
| 3 | +// Usage: go run parse_eventstream.go <file.resp.bin> |
| 4 | +// |
| 5 | +// Decodes an AWS EventStream binary file and prints each frame's |
| 6 | +// decoded JSON body. Use this to inspect captured Bedrock responses |
| 7 | +// and verify fixture contents. |
| 8 | +package main |
| 9 | + |
| 10 | +import ( |
| 11 | + "bytes" |
| 12 | + "encoding/base64" |
| 13 | + "encoding/json" |
| 14 | + "fmt" |
| 15 | + "os" |
| 16 | + |
| 17 | + "github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream" |
| 18 | + "github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream/eventstreamapi" |
| 19 | +) |
| 20 | + |
| 21 | +func main() { |
| 22 | + if len(os.Args) < 2 { |
| 23 | + fmt.Fprintf(os.Stderr, "usage: go run parse_eventstream.go <file.resp.bin>\n") |
| 24 | + os.Exit(1) |
| 25 | + } |
| 26 | + |
| 27 | + data, err := os.ReadFile(os.Args[1]) |
| 28 | + if err != nil { |
| 29 | + fmt.Fprintf(os.Stderr, "read file: %v\n", err) |
| 30 | + os.Exit(1) |
| 31 | + } |
| 32 | + |
| 33 | + decoder := eventstream.NewDecoder() |
| 34 | + reader := bytes.NewReader(data) |
| 35 | + frameNum := 0 |
| 36 | + |
| 37 | + for { |
| 38 | + msg, err := decoder.Decode(reader, nil) |
| 39 | + if err != nil { |
| 40 | + break |
| 41 | + } |
| 42 | + frameNum++ |
| 43 | + |
| 44 | + messageType := msg.Headers.Get(eventstreamapi.MessageTypeHeader) |
| 45 | + eventType := msg.Headers.Get(eventstreamapi.EventTypeHeader) |
| 46 | + |
| 47 | + fmt.Printf("=== Frame %d ===\n", frameNum) |
| 48 | + fmt.Printf(" message-type: %s\n", headerStr(messageType)) |
| 49 | + fmt.Printf(" event-type: %s\n", headerStr(eventType)) |
| 50 | + |
| 51 | + if headerStr(eventType) != "chunk" { |
| 52 | + fmt.Printf(" payload: %s\n\n", string(msg.Payload)) |
| 53 | + continue |
| 54 | + } |
| 55 | + |
| 56 | + var chunk struct { |
| 57 | + Bytes string `json:"bytes"` |
| 58 | + } |
| 59 | + if err := json.Unmarshal(msg.Payload, &chunk); err != nil { |
| 60 | + fmt.Printf(" unmarshal error: %v\n\n", err) |
| 61 | + continue |
| 62 | + } |
| 63 | + |
| 64 | + decoded, err := base64.StdEncoding.DecodeString(chunk.Bytes) |
| 65 | + if err != nil { |
| 66 | + fmt.Printf(" base64 decode error: %v\n\n", err) |
| 67 | + continue |
| 68 | + } |
| 69 | + |
| 70 | + var pretty json.RawMessage |
| 71 | + if err := json.Unmarshal(decoded, &pretty); err != nil { |
| 72 | + fmt.Printf(" json: %s\n\n", string(decoded)) |
| 73 | + continue |
| 74 | + } |
| 75 | + |
| 76 | + indented, _ := json.MarshalIndent(pretty, " ", " ") |
| 77 | + fmt.Printf(" body:\n %s\n\n", string(indented)) |
| 78 | + } |
| 79 | + |
| 80 | + fmt.Printf("Total frames: %d\n", frameNum) |
| 81 | +} |
| 82 | + |
| 83 | +func headerStr(h eventstream.Value) string { |
| 84 | + if h == nil { |
| 85 | + return "<nil>" |
| 86 | + } |
| 87 | + return h.String() |
| 88 | +} |
0 commit comments