Spaces:
Build error
Build error
File size: 15,787 Bytes
4b1daed | 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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 | // Package memory provides a client for the Rust memory service.
package memory
import (
"bufio"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net"
"sync"
"time"
lz4 "github.com/pierrec/lz4/v4"
)
const (
// Protocol constants
magicHeader uint32 = 0x4D454D41 // "MEMA"
protocolVersion uint8 = 1
// Message types
msgStore uint8 = 0x01
msgRetrieve uint8 = 0x02
msgUpdate uint8 = 0x03
msgDelete uint8 = 0x04
msgBatchStore uint8 = 0x05
msgGetContextWindow uint8 = 0x10
msgConsolidate uint8 = 0x11
msgSubscribe uint8 = 0x20
msgUnsubscribe uint8 = 0x21
msgMemoryEvent uint8 = 0x22
msgApplyTTL uint8 = 0x30
msgDetectConflicts uint8 = 0x31
msgResolveConflict uint8 = 0x32
msgSuccess uint8 = 0x80
msgError uint8 = 0x81
msgPartial uint8 = 0x82
// Flags
flagCompressed uint8 = 0x01
flagChecksum uint8 = 0x02
flagEncrypted uint8 = 0x04
)
// FrameHeader represents the binary protocol frame header
type FrameHeader struct {
Magic uint32
Version uint8
Type uint8
Flags uint8
MessageID [16]byte
BodyLength uint64
}
// RustMemoryClient connects to the Rust memory service
type RustMemoryClient struct {
mu sync.Mutex
// Connection configuration
addr string
port int
compression bool
requestTimeout time.Duration
// Connection pool
pool *connectionPool
// Fallback to local backend if Rust service unavailable
fallback MemoryManager
useFallback bool
}
// RustClientConfig configures the Rust client
type RustClientConfig struct {
Host string
Port int
Compression bool
PoolSize int
RequestTimeout time.Duration
Fallback MemoryManager
}
// NewRustMemoryClient creates a new Rust memory client
func NewRustMemoryClient(config RustClientConfig) *RustMemoryClient {
if config.PoolSize == 0 {
config.PoolSize = 10
}
if config.RequestTimeout == 0 {
config.RequestTimeout = 5 * time.Second
}
client := &RustMemoryClient{
addr: config.Host,
port: config.Port,
compression: config.Compression,
requestTimeout: config.RequestTimeout,
fallback: config.Fallback,
useFallback: false,
}
// Initialize connection pool
client.pool = newConnectionPool(config.PoolSize, func() (net.Conn, error) {
return net.DialTimeout("tcp",
fmt.Sprintf("%s:%d", config.Host, config.Port),
config.RequestTimeout)
})
// Check if Rust service is available
if err := client.healthCheck(); err != nil {
client.useFallback = true
}
return client
}
// healthCheck verifies connection to Rust service
func (c *RustMemoryClient) healthCheck() error {
conn, err := c.pool.get()
if err != nil {
return err
}
defer c.pool.put(conn)
// Simple ping/pong would go here
return nil
}
// Store persists a new memory entry
func (c *RustMemoryClient) Store(ctx context.Context, entry *MemoryEntry) error {
if c.useFallback && c.fallback != nil {
return c.fallback.Store(ctx, entry)
}
conn, err := c.pool.get()
if err != nil {
if c.fallback != nil {
return c.fallback.Store(ctx, entry)
}
return err
}
defer c.pool.put(conn)
// Serialize entry
body, err := serializeMemoryEntry(entry)
if err != nil {
return err
}
// Build and send frame
header := c.buildHeader(msgStore, body)
if err := c.writeFrame(conn, header, body); err != nil {
return err
}
// Read response
respHeader, respBody, err := c.readFrame(conn)
if err != nil {
return err
}
if respHeader.Type == msgError {
return fmt.Errorf("rust service error: %s", string(respBody))
}
return nil
}
// BatchStore stores multiple entries efficiently
func (c *RustMemoryClient) BatchStore(ctx context.Context, entries []*MemoryEntry) error {
if c.useFallback && c.fallback != nil {
return c.fallback.BatchStore(ctx, entries)
}
conn, err := c.pool.get()
if err != nil {
if c.fallback != nil {
return c.fallback.BatchStore(ctx, entries)
}
return err
}
defer c.pool.put(conn)
// Serialize entries batch
body, err := serializeMemoryEntries(entries)
if err != nil {
return err
}
header := c.buildHeader(msgBatchStore, body)
if err := c.writeFrame(conn, header, body); err != nil {
return err
}
respHeader, respBody, err := c.readFrame(conn)
if err != nil {
return err
}
if respHeader.Type == msgError {
return fmt.Errorf("rust service error: %s", string(respBody))
}
return nil
}
// Retrieve searches for relevant memories
func (c *RustMemoryClient) Retrieve(ctx context.Context, query *MemoryQuery) ([]*MemoryEntry, error) {
if c.useFallback && c.fallback != nil {
return c.fallback.Retrieve(ctx, query)
}
conn, err := c.pool.get()
if err != nil {
if c.fallback != nil {
return c.fallback.Retrieve(ctx, query)
}
return nil, err
}
defer c.pool.put(conn)
// Serialize query
body, err := serializeMemoryQuery(query)
if err != nil {
return nil, err
}
header := c.buildHeader(msgRetrieve, body)
if err := c.writeFrame(conn, header, body); err != nil {
return nil, err
}
respHeader, respBody, err := c.readFrame(conn)
if err != nil {
return nil, err
}
if respHeader.Type == msgError {
return nil, fmt.Errorf("rust service error: %s", string(respBody))
}
return deserializeMemoryEntries(respBody)
}
// Update modifies an existing memory entry
func (c *RustMemoryClient) Update(ctx context.Context, id string, updates map[string]interface{}) error {
if c.useFallback && c.fallback != nil {
return c.fallback.Update(ctx, id, updates)
}
// TODO: Implement wire protocol for updates
return fmt.Errorf("update not implemented for Rust client")
}
// Delete removes a memory entry
func (c *RustMemoryClient) Delete(ctx context.Context, id string) error {
if c.useFallback && c.fallback != nil {
return c.fallback.Delete(ctx, id)
}
conn, err := c.pool.get()
if err != nil {
if c.fallback != nil {
return c.fallback.Delete(ctx, id)
}
return err
}
defer c.pool.put(conn)
body := []byte(id)
header := c.buildHeader(msgDelete, body)
if err := c.writeFrame(conn, header, body); err != nil {
return err
}
respHeader, respBody, err := c.readFrame(conn)
if err != nil {
return err
}
if respHeader.Type == msgError {
return fmt.Errorf("rust service error: %s", string(respBody))
}
return nil
}
// DeleteUserData removes all data for a user (GDPR compliance)
func (c *RustMemoryClient) DeleteUserData(ctx context.Context, userID string) error {
if c.useFallback && c.fallback != nil {
return c.fallback.DeleteUserData(ctx, userID)
}
// TODO: Implement wire protocol for user data deletion
return fmt.Errorf("delete user data not implemented for Rust client")
}
// GetContextWindow retrieves recent conversation context
func (c *RustMemoryClient) GetContextWindow(ctx context.Context, sessionID string, maxTurns int) ([]*MemoryEntry, error) {
if c.useFallback && c.fallback != nil {
return c.fallback.GetContextWindow(ctx, sessionID, maxTurns)
}
conn, err := c.pool.get()
if err != nil {
if c.fallback != nil {
return c.fallback.GetContextWindow(ctx, sessionID, maxTurns)
}
return nil, err
}
defer c.pool.put(conn)
// Serialize request
body := make([]byte, len(sessionID)+4)
copy(body, sessionID)
binary.BigEndian.PutUint32(body[len(sessionID):], uint32(maxTurns))
header := c.buildHeader(msgGetContextWindow, body)
if err := c.writeFrame(conn, header, body); err != nil {
return nil, err
}
respHeader, respBody, err := c.readFrame(conn)
if err != nil {
return nil, err
}
if respHeader.Type == msgError {
return nil, fmt.Errorf("rust service error: %s", string(respBody))
}
return deserializeMemoryEntries(respBody)
}
// ConsolidateMemory migrates short-term to long-term memory
func (c *RustMemoryClient) ConsolidateMemory(ctx context.Context, sessionID string) error {
if c.useFallback && c.fallback != nil {
return c.fallback.ConsolidateMemory(ctx, sessionID)
}
conn, err := c.pool.get()
if err != nil {
if c.fallback != nil {
return c.fallback.ConsolidateMemory(ctx, sessionID)
}
return err
}
defer c.pool.put(conn)
body := []byte(sessionID)
header := c.buildHeader(msgConsolidate, body)
if err := c.writeFrame(conn, header, body); err != nil {
return err
}
respHeader, respBody, err := c.readFrame(conn)
if err != nil {
return err
}
if respHeader.Type == msgError {
return fmt.Errorf("rust service error: %s", string(respBody))
}
return nil
}
// ApplyTTL removes expired memories and returns count
func (c *RustMemoryClient) ApplyTTL(ctx context.Context) (int64, error) {
if c.useFallback && c.fallback != nil {
return c.fallback.ApplyTTL(ctx)
}
conn, err := c.pool.get()
if err != nil {
if c.fallback != nil {
return c.fallback.ApplyTTL(ctx)
}
return 0, err
}
defer c.pool.put(conn)
header := c.buildHeader(msgApplyTTL, nil)
if err := c.writeFrame(conn, header, nil); err != nil {
return 0, err
}
respHeader, respBody, err := c.readFrame(conn)
if err != nil {
return 0, err
}
if respHeader.Type == msgError {
return 0, fmt.Errorf("rust service error: %s", string(respBody))
}
if len(respBody) >= 8 {
return int64(binary.BigEndian.Uint64(respBody)), nil
}
return 0, nil
}
// DetectConflicts finds conflicting memories for a user
func (c *RustMemoryClient) DetectConflicts(ctx context.Context, userID string) ([]Conflict, error) {
if c.useFallback && c.fallback != nil {
return c.fallback.DetectConflicts(ctx, userID)
}
// TODO: Implement wire protocol for conflict detection
return nil, nil
}
// ResolveConflict resolves a detected conflict
func (c *RustMemoryClient) ResolveConflict(ctx context.Context, conflictID string, resolution ConflictResolution) error {
if c.useFallback && c.fallback != nil {
return c.fallback.ResolveConflict(ctx, conflictID, resolution)
}
// TODO: Implement wire protocol for conflict resolution
return nil
}
// Subscribe creates a channel for real-time memory events
func (c *RustMemoryClient) Subscribe(ctx context.Context, userID string) (<-chan MemoryEvent, error) {
if c.useFallback && c.fallback != nil {
return c.fallback.Subscribe(ctx, userID)
}
// TODO: Implement streaming subscription
ch := make(chan MemoryEvent)
return ch, nil
}
// Unsubscribe removes a subscription
func (c *RustMemoryClient) Unsubscribe(ctx context.Context, userID string) error {
if c.useFallback && c.fallback != nil {
return c.fallback.Unsubscribe(ctx, userID)
}
return nil
}
// Close cleans up resources
func (c *RustMemoryClient) Close() error {
c.pool.close()
if c.fallback != nil {
return c.fallback.Close()
}
return nil
}
// buildHeader creates a frame header
func (c *RustMemoryClient) buildHeader(msgType uint8, body []byte) FrameHeader {
header := FrameHeader{
Magic: magicHeader,
Version: protocolVersion,
Type: msgType,
Flags: 0,
BodyLength: uint64(len(body)),
}
if c.compression && len(body) > 1024 {
header.Flags |= flagCompressed
}
return header
}
// writeFrame writes a complete frame to the connection
func (c *RustMemoryClient) writeFrame(conn net.Conn, header FrameHeader, body []byte) error {
// Set deadline
conn.SetWriteDeadline(time.Now().Add(c.requestTimeout))
writer := bufio.NewWriter(conn)
// Write header (31 bytes)
if err := binary.Write(writer, binary.BigEndian, header.Magic); err != nil {
return err
}
writer.WriteByte(header.Version)
writer.WriteByte(header.Type)
writer.WriteByte(header.Flags)
writer.Write(header.MessageID[:])
binary.Write(writer, binary.BigEndian, header.BodyLength)
// Write body
if len(body) > 0 {
writer.Write(body)
}
return writer.Flush()
}
// readFrame reads a complete frame from the connection
func (c *RustMemoryClient) readFrame(conn net.Conn) (FrameHeader, []byte, error) {
// Set deadline
conn.SetReadDeadline(time.Now().Add(c.requestTimeout))
reader := bufio.NewReader(conn)
var header FrameHeader
// Read header
if err := binary.Read(reader, binary.BigEndian, &header.Magic); err != nil {
return header, nil, err
}
if header.Magic != magicHeader {
return header, nil, fmt.Errorf("invalid magic header: %x", header.Magic)
}
var err error
header.Version, err = reader.ReadByte()
if err != nil {
return header, nil, err
}
header.Type, err = reader.ReadByte()
if err != nil {
return header, nil, err
}
header.Flags, err = reader.ReadByte()
if err != nil {
return header, nil, err
}
if _, err := io.ReadFull(reader, header.MessageID[:]); err != nil {
return header, nil, err
}
if err := binary.Read(reader, binary.BigEndian, &header.BodyLength); err != nil {
return header, nil, err
}
// Read body
body := make([]byte, header.BodyLength)
if header.BodyLength > 0 {
if _, err := io.ReadFull(reader, body); err != nil {
return header, nil, err
}
}
// Decompress if needed
if header.Flags&flagCompressed != 0 {
body, err = decompressLZ4(body)
if err != nil {
return header, nil, err
}
}
return header, body, nil
}
// Connection pool
type connectionPool struct {
mu sync.Mutex
conns []net.Conn
maxConns int
factory func() (net.Conn, error)
}
func newConnectionPool(maxConns int, factory func() (net.Conn, error)) *connectionPool {
return &connectionPool{
conns: make([]net.Conn, 0, maxConns),
maxConns: maxConns,
factory: factory,
}
}
func (p *connectionPool) get() (net.Conn, error) {
p.mu.Lock()
if len(p.conns) > 0 {
conn := p.conns[len(p.conns)-1]
p.conns = p.conns[:len(p.conns)-1]
p.mu.Unlock()
return conn, nil
}
p.mu.Unlock()
return p.factory()
}
func (p *connectionPool) put(conn net.Conn) {
p.mu.Lock()
defer p.mu.Unlock()
if len(p.conns) < p.maxConns {
p.conns = append(p.conns, conn)
} else {
conn.Close()
}
}
func (p *connectionPool) close() {
p.mu.Lock()
defer p.mu.Unlock()
for _, conn := range p.conns {
conn.Close()
}
p.conns = nil
}
// Serialization helpers using JSON encoding
// serializeMemoryEntry serializes a single memory entry to JSON
func serializeMemoryEntry(entry *MemoryEntry) ([]byte, error) {
return json.Marshal(entry)
}
// serializeMemoryEntries serializes multiple entries to JSON array
func serializeMemoryEntries(entries []*MemoryEntry) ([]byte, error) {
return json.Marshal(entries)
}
// serializeMemoryQuery serializes a query to JSON
func serializeMemoryQuery(query *MemoryQuery) ([]byte, error) {
return json.Marshal(query)
}
// deserializeMemoryEntries deserializes JSON to memory entries
func deserializeMemoryEntries(data []byte) ([]*MemoryEntry, error) {
if len(data) == 0 {
return nil, nil
}
var entries []*MemoryEntry
if err := json.Unmarshal(data, &entries); err != nil {
return nil, fmt.Errorf("failed to deserialize entries: %w", err)
}
return entries, nil
}
// decompressLZ4 decompresses LZ4 data
func decompressLZ4(data []byte) ([]byte, error) {
if len(data) == 0 {
return data, nil
}
// Simple frame format: first 4 bytes = uncompressed length
if len(data) < 4 {
return data, nil // Not compressed or invalid
}
// Read uncompressed length (little-endian)
uncompressedLen := int(data[0]) | int(data[1])<<8 | int(data[2])<<16 | int(data[3])<<24
if uncompressedLen <= 0 || uncompressedLen > 100*1024*1024 { // Max 100MB
return data, nil // Invalid length, return as-is
}
result := make([]byte, uncompressedLen)
n, err := lz4.UncompressBlock(data[4:], result)
if err != nil {
return nil, fmt.Errorf("lz4 decompress failed: %w", err)
}
return result[:n], nil
}
// compressLZ4 compresses data using LZ4 (placeholder)
func compressLZ4(data []byte) ([]byte, error) {
// For now, return as-is
// In production, use: github.com/pierrec/lz4/v4
return data, nil
}
|