| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package mcp |
| 9 |
|
| 10 |
import ( |
| 11 |
"bufio" |
| 12 |
"bytes" |
| 13 |
"context" |
| 14 |
"errors" |
| 15 |
"fmt" |
| 16 |
"io" |
| 17 |
"iter" |
| 18 |
"maps" |
| 19 |
"net/http" |
| 20 |
"slices" |
| 21 |
"strings" |
| 22 |
"sync" |
| 23 |
) |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
const validateMemoryEventStore = false |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
type Event struct { |
| 32 |
Name string |
| 33 |
ID string |
| 34 |
Data []byte |
| 35 |
Retry string |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
func (e Event) Empty() bool { |
| 40 |
return e.Name == "" && e.ID == "" && len(e.Data) == 0 && e.Retry == "" |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
func writeEvent(w http.ResponseWriter, evt Event) (int, error) { |
| 45 |
var b bytes.Buffer |
| 46 |
if evt.Name != "" { |
| 47 |
fmt.Fprintf(&b, "event: %s\n", evt.Name) |
| 48 |
} |
| 49 |
if evt.ID != "" { |
| 50 |
fmt.Fprintf(&b, "id: %s\n", evt.ID) |
| 51 |
} |
| 52 |
if evt.Retry != "" { |
| 53 |
fmt.Fprintf(&b, "retry: %s\n", evt.Retry) |
| 54 |
} |
| 55 |
fmt.Fprintf(&b, "data: %s\n\n", string(evt.Data)) |
| 56 |
n, err := w.Write(b.Bytes()) |
| 57 |
rc := http.NewResponseController(w) |
| 58 |
|
| 59 |
_ = rc.Flush() |
| 60 |
return n, err |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
func scanEvents(r io.Reader) iter.Seq2[Event, error] { |
| 70 |
reader := bufio.NewReader(r) |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
var ( |
| 75 |
eventKey = []byte("event") |
| 76 |
idKey = []byte("id") |
| 77 |
dataKey = []byte("data") |
| 78 |
retryKey = []byte("retry") |
| 79 |
) |
| 80 |
|
| 81 |
return func(yield func(Event, error) bool) { |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
var ( |
| 92 |
evt Event |
| 93 |
dataBuf *bytes.Buffer |
| 94 |
) |
| 95 |
yieldEvent := func() bool { |
| 96 |
if dataBuf != nil { |
| 97 |
evt.Data = dataBuf.Bytes() |
| 98 |
dataBuf = nil |
| 99 |
} |
| 100 |
if evt.Empty() { |
| 101 |
return true |
| 102 |
} |
| 103 |
if !yield(evt, nil) { |
| 104 |
return false |
| 105 |
} |
| 106 |
evt = Event{} |
| 107 |
return true |
| 108 |
} |
| 109 |
for { |
| 110 |
line, err := reader.ReadBytes('\n') |
| 111 |
if err != nil && !errors.Is(err, io.EOF) { |
| 112 |
yield(Event{}, fmt.Errorf("error reading event: %v", err)) |
| 113 |
return |
| 114 |
} |
| 115 |
line = bytes.TrimRight(line, "\r\n") |
| 116 |
isEOF := errors.Is(err, io.EOF) |
| 117 |
|
| 118 |
if len(line) == 0 { |
| 119 |
if !yieldEvent() { |
| 120 |
return |
| 121 |
} |
| 122 |
if isEOF { |
| 123 |
return |
| 124 |
} |
| 125 |
continue |
| 126 |
} |
| 127 |
before, after, found := bytes.Cut(line, []byte{':'}) |
| 128 |
if !found { |
| 129 |
yield(Event{}, fmt.Errorf("%w: malformed line in SSE stream: %q", errMalformedEvent, string(line))) |
| 130 |
return |
| 131 |
} |
| 132 |
switch { |
| 133 |
case bytes.Equal(before, eventKey): |
| 134 |
evt.Name = strings.TrimSpace(string(after)) |
| 135 |
case bytes.Equal(before, idKey): |
| 136 |
evt.ID = strings.TrimSpace(string(after)) |
| 137 |
case bytes.Equal(before, retryKey): |
| 138 |
evt.Retry = strings.TrimSpace(string(after)) |
| 139 |
case bytes.Equal(before, dataKey): |
| 140 |
data := bytes.TrimSpace(after) |
| 141 |
if dataBuf == nil { |
| 142 |
dataBuf = new(bytes.Buffer) |
| 143 |
} else { |
| 144 |
dataBuf.WriteByte('\n') |
| 145 |
} |
| 146 |
dataBuf.Write(data) |
| 147 |
} |
| 148 |
|
| 149 |
if isEOF { |
| 150 |
yieldEvent() |
| 151 |
return |
| 152 |
} |
| 153 |
} |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
type EventStore interface { |
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
Open(_ context.Context, sessionID, streamID string) error |
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
Append(_ context.Context, sessionID, streamID string, data []byte) error |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
After(_ context.Context, sessionID, streamID string, index int) iter.Seq2[[]byte, error] |
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
SessionClosed(_ context.Context, sessionID string) error |
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
} |
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
type dataList struct { |
| 197 |
size int |
| 198 |
first int |
| 199 |
data [][]byte |
| 200 |
} |
| 201 |
|
| 202 |
func (dl *dataList) appendData(d []byte) { |
| 203 |
|
| 204 |
|
| 205 |
dl.data = append(dl.data, d) |
| 206 |
dl.size += len(d) |
| 207 |
} |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
func (dl *dataList) removeFirst() int { |
| 212 |
if len(dl.data) == 0 { |
| 213 |
panic("empty dataList") |
| 214 |
} |
| 215 |
r := len(dl.data[0]) |
| 216 |
dl.size -= r |
| 217 |
dl.data[0] = nil |
| 218 |
dl.data = dl.data[1:] |
| 219 |
dl.first++ |
| 220 |
return r |
| 221 |
} |
| 222 |
|
| 223 |
|
| 224 |
type MemoryEventStore struct { |
| 225 |
mu sync.Mutex |
| 226 |
maxBytes int |
| 227 |
nBytes int |
| 228 |
store map[string]map[string]*dataList |
| 229 |
} |
| 230 |
|
| 231 |
|
| 232 |
type MemoryEventStoreOptions struct{} |
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
func (s *MemoryEventStore) MaxBytes() int { |
| 237 |
s.mu.Lock() |
| 238 |
defer s.mu.Unlock() |
| 239 |
return s.maxBytes |
| 240 |
} |
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
func (s *MemoryEventStore) SetMaxBytes(n int) { |
| 247 |
s.mu.Lock() |
| 248 |
defer s.mu.Unlock() |
| 249 |
switch { |
| 250 |
case n < 0: |
| 251 |
panic("negative argument") |
| 252 |
case n == 0: |
| 253 |
s.maxBytes = defaultMaxBytes |
| 254 |
default: |
| 255 |
s.maxBytes = n |
| 256 |
} |
| 257 |
s.purge() |
| 258 |
} |
| 259 |
|
| 260 |
const defaultMaxBytes = 10 << 20 |
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
func NewMemoryEventStore(opts *MemoryEventStoreOptions) *MemoryEventStore { |
| 265 |
return &MemoryEventStore{ |
| 266 |
maxBytes: defaultMaxBytes, |
| 267 |
store: make(map[string]map[string]*dataList), |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
func (s *MemoryEventStore) Open(_ context.Context, sessionID, streamID string) error { |
| 274 |
s.mu.Lock() |
| 275 |
defer s.mu.Unlock() |
| 276 |
s.init(sessionID, streamID) |
| 277 |
return nil |
| 278 |
} |
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
func (s *MemoryEventStore) init(sessionID, streamID string) *dataList { |
| 285 |
streamMap, ok := s.store[sessionID] |
| 286 |
if !ok { |
| 287 |
streamMap = make(map[string]*dataList) |
| 288 |
s.store[sessionID] = streamMap |
| 289 |
} |
| 290 |
dl, ok := streamMap[streamID] |
| 291 |
if !ok { |
| 292 |
dl = &dataList{} |
| 293 |
streamMap[streamID] = dl |
| 294 |
} |
| 295 |
return dl |
| 296 |
} |
| 297 |
|
| 298 |
|
| 299 |
func (s *MemoryEventStore) Append(_ context.Context, sessionID, streamID string, data []byte) error { |
| 300 |
s.mu.Lock() |
| 301 |
defer s.mu.Unlock() |
| 302 |
dl := s.init(sessionID, streamID) |
| 303 |
|
| 304 |
|
| 305 |
s.purge() |
| 306 |
dl.appendData(data) |
| 307 |
s.nBytes += len(data) |
| 308 |
return nil |
| 309 |
} |
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
var ErrEventsPurged = errors.New("data purged") |
| 314 |
|
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
var errMalformedEvent = errors.New("malformed event") |
| 319 |
|
| 320 |
|
| 321 |
func (s *MemoryEventStore) After(_ context.Context, sessionID, streamID string, index int) iter.Seq2[[]byte, error] { |
| 322 |
|
| 323 |
|
| 324 |
copyData := func() ([][]byte, error) { |
| 325 |
s.mu.Lock() |
| 326 |
defer s.mu.Unlock() |
| 327 |
streamMap, ok := s.store[sessionID] |
| 328 |
if !ok { |
| 329 |
return nil, fmt.Errorf("MemoryEventStore.After: unknown session ID %q", sessionID) |
| 330 |
} |
| 331 |
dl, ok := streamMap[streamID] |
| 332 |
if !ok { |
| 333 |
return nil, fmt.Errorf("MemoryEventStore.After: unknown stream ID %v in session %q", streamID, sessionID) |
| 334 |
} |
| 335 |
start := index + 1 |
| 336 |
if dl.first > start { |
| 337 |
return nil, fmt.Errorf("MemoryEventStore.After: index %d, stream ID %v, session %q: %w", |
| 338 |
index, streamID, sessionID, ErrEventsPurged) |
| 339 |
} |
| 340 |
return slices.Clone(dl.data[start-dl.first:]), nil |
| 341 |
} |
| 342 |
|
| 343 |
return func(yield func([]byte, error) bool) { |
| 344 |
ds, err := copyData() |
| 345 |
if err != nil { |
| 346 |
yield(nil, err) |
| 347 |
return |
| 348 |
} |
| 349 |
for _, d := range ds { |
| 350 |
if !yield(d, nil) { |
| 351 |
return |
| 352 |
} |
| 353 |
} |
| 354 |
} |
| 355 |
} |
| 356 |
|
| 357 |
|
| 358 |
func (s *MemoryEventStore) SessionClosed(_ context.Context, sessionID string) error { |
| 359 |
s.mu.Lock() |
| 360 |
defer s.mu.Unlock() |
| 361 |
for _, dl := range s.store[sessionID] { |
| 362 |
s.nBytes -= dl.size |
| 363 |
} |
| 364 |
delete(s.store, sessionID) |
| 365 |
s.validate() |
| 366 |
return nil |
| 367 |
} |
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
func (s *MemoryEventStore) purge() { |
| 372 |
|
| 373 |
for s.nBytes > s.maxBytes { |
| 374 |
changed := false |
| 375 |
for _, sm := range s.store { |
| 376 |
for _, dl := range sm { |
| 377 |
if dl.size > 0 { |
| 378 |
r := dl.removeFirst() |
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
changed = true |
| 383 |
s.nBytes -= r |
| 384 |
} |
| 385 |
} |
| 386 |
} |
| 387 |
if !changed { |
| 388 |
panic("no progress during purge") |
| 389 |
} |
| 390 |
} |
| 391 |
s.validate() |
| 392 |
} |
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
func (s *MemoryEventStore) validate() { |
| 397 |
if !validateMemoryEventStore { |
| 398 |
return |
| 399 |
} |
| 400 |
|
| 401 |
n := 0 |
| 402 |
for _, sm := range s.store { |
| 403 |
for _, dl := range sm { |
| 404 |
for _, d := range dl.data { |
| 405 |
n += len(d) |
| 406 |
} |
| 407 |
} |
| 408 |
} |
| 409 |
if n != s.nBytes { |
| 410 |
panic("sizes don't add up") |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
func (s *MemoryEventStore) debugString() string { |
| 417 |
s.mu.Lock() |
| 418 |
defer s.mu.Unlock() |
| 419 |
var b strings.Builder |
| 420 |
for i, sess := range slices.Sorted(maps.Keys(s.store)) { |
| 421 |
if i > 0 { |
| 422 |
fmt.Fprintf(&b, "; ") |
| 423 |
} |
| 424 |
sm := s.store[sess] |
| 425 |
for i, sid := range slices.Sorted(maps.Keys(sm)) { |
| 426 |
if i > 0 { |
| 427 |
fmt.Fprintf(&b, "; ") |
| 428 |
} |
| 429 |
dl := sm[sid] |
| 430 |
fmt.Fprintf(&b, "%s %s first=%d", sess, sid, dl.first) |
| 431 |
for _, d := range dl.data { |
| 432 |
fmt.Fprintf(&b, " %s", d) |
| 433 |
} |
| 434 |
} |
| 435 |
} |
| 436 |
return b.String() |
| 437 |
} |