Files
coder/aibridge/intercept/apidump/streaming.go
T
Paweł Banaszewski e00e85765b chore: move aibridge library code into coder repo (#24190)
This PR merges code from `coder/aibridge` repository into `coder/coder`.
It was split into 4 PRs for easier review but stacked PRs will need to
be merged into this PR so all checks pass.

* https://github.com/coder/coder/pull/24190 -> raw code copy (this PR,
before merging PRs on top of it, it was just 1 commit:
https://github.com/coder/coder/commit/70d33f33200c7e77df910957595715f81f9bec24)
* https://github.com/coder/coder/pull/24570 -> update imports in
`coder/coder` to use copied code
* https://github.com/coder/coder/pull/24586 -> linter fixes and CI
integration (also added README.md)
* https://github.com/coder/coder/pull/24571 -> added exclude to
scripts/check_emdash.sh check

Original PR message (before PR squash):
Moves coder/aibridge code into coder/coder repository.

Omitted files:

- `go.mod`, `go.sum`, `.gitignore`, `.github/workflows/ci.yml,`
`Makefile`, `LICENSE`, `README.md` (modified README.md is added later)
- `.github`, `example`, `buildinfo,` `scripts` directories

Simple verification script (will list omitted files)

```
tmp=$(mktemp -d)
echo "$tmp"
git clone --depth=1 https://github.com/coder/aibridge "$tmp/aibridge"
git clone --depth=1 --branch pb/aibridge-code-move https://github.com/coder/coder "$tmp/coder"
diff -rq --exclude=.git "$tmp/aibridge" "$tmp/coder/aibridge"
# rm -rf "$tmp"
```
2026-04-22 17:01:01 +02:00

74 lines
1.5 KiB
Go

package apidump
import (
"io"
"os"
"path/filepath"
"sync"
"golang.org/x/xerrors"
)
// streamingBodyDumper wraps an io.ReadCloser and writes all data to a dump file
// as it's read, preserving streaming behavior.
type streamingBodyDumper struct {
body io.ReadCloser
dumpPath string
headerData []byte
logger func(err error)
once sync.Once
file *os.File
initErr error
}
func (s *streamingBodyDumper) init() {
s.once.Do(func() {
if err := os.MkdirAll(filepath.Dir(s.dumpPath), 0o755); err != nil {
s.initErr = xerrors.Errorf("create dump dir: %w", err)
return
}
f, err := os.Create(s.dumpPath)
if err != nil {
s.initErr = xerrors.Errorf("create dump file: %w", err)
return
}
s.file = f
// Write headers first.
if _, err := s.file.Write(s.headerData); err != nil {
s.initErr = xerrors.Errorf("write headers: %w", err)
_ = s.file.Close() // best-effort cleanup on header write failure
s.file = nil
}
})
}
func (s *streamingBodyDumper) Read(p []byte) (int, error) {
n, err := s.body.Read(p)
if n > 0 {
s.init()
if s.initErr != nil && s.logger != nil {
s.logger(s.initErr)
}
if s.file != nil {
// Write raw bytes as they stream through.
_, _ = s.file.Write(p[:n])
}
}
return n, err
}
func (s *streamingBodyDumper) Close() error {
// Ensure init() has completed to avoid racing with Read().
s.init()
var closeErr error
if s.file != nil {
closeErr = s.file.Close()
}
bodyErr := s.body.Close()
if bodyErr != nil {
return bodyErr
}
return closeErr
}