Documentation
¶
Overview ¶
Package session provides a session manager with TTL cleanup.
Package session provides session management with pluggable storage backends.
Index ¶
- Constants
- Variables
- func HasJSONRPCID(requestID any) bool
- func NotFoundBody(requestID any) []byte
- func NotFoundResponse(req *http.Request, requestID any) *http.Response
- func SerializeSession(s Session) ([]byte, error)
- func SerializedMetadata(data []byte) (map[string]string, error)
- func WriteNotFound(w http.ResponseWriter, requestID any)
- type DataStorage
- type Factory
- type LegacyFactory
- type LocalSessionDataStorage
- func (s *LocalSessionDataStorage) Close() error
- func (s *LocalSessionDataStorage) Create(_ context.Context, id string, metadata map[string]string) (bool, error)
- func (s *LocalSessionDataStorage) Delete(_ context.Context, id string) error
- func (s *LocalSessionDataStorage) Load(_ context.Context, id string) (map[string]string, error)
- func (s *LocalSessionDataStorage) LoadMetadata(_ context.Context, id string) (map[string]string, error)
- func (s *LocalSessionDataStorage) Update(_ context.Context, id string, metadata map[string]string) (bool, error)
- type LocalStorage
- func (s *LocalStorage) Close() error
- func (s *LocalStorage) Count() int
- func (s *LocalStorage) Create(_ context.Context, session Session) error
- func (s *LocalStorage) Delete(_ context.Context, id string) error
- func (s *LocalStorage) DeleteExpired(ctx context.Context, before time.Time) error
- func (s *LocalStorage) DeleteIfOwner(_ context.Context, id, expectedOwner string) (bool, error)
- func (s *LocalStorage) Load(_ context.Context, id string) (Session, error)
- func (s *LocalStorage) LoadIfOwner(_ context.Context, id, expectedOwner string) (Session, error)
- func (s *LocalStorage) LoadMetadata(_ context.Context, id string) (map[string]string, error)
- func (s *LocalStorage) Range(f func(key, value interface{}) bool)
- func (s *LocalStorage) Store(_ context.Context, session Session) error
- func (s *LocalStorage) StoreIfOwner(_ context.Context, session Session, expectedOwner string) (bool, error)
- type Manager
- func (m *Manager) AddSession(session Session) error
- func (m *Manager) AddWithID(id string) error
- func (m *Manager) Count() int
- func (m *Manager) Delete(id string) error
- func (m *Manager) DeleteIfOwner(id, expectedOwner string) error
- func (m *Manager) Get(id string) (Session, bool)
- func (m *Manager) GetWithError(id string) (Session, error)
- func (m *Manager) LoadIfOwner(id, expectedOwner string) (Session, error)
- func (m *Manager) LookupOwner(ctx context.Context, id string) (string, error)
- func (m *Manager) Stop() error
- func (m *Manager) UpsertSession(session Session) error
- func (m *Manager) UpsertSessionIfOwner(session Session, expectedOwner string) error
- type ProxySession
- func (s *ProxySession) CreatedAt() time.Time
- func (s *ProxySession) DeleteMetadata(key string)
- func (s *ProxySession) GetData() interface{}
- func (s *ProxySession) GetMetadata() map[string]string
- func (s *ProxySession) GetMetadataValue(key string) (string, bool)
- func (s *ProxySession) ID() string
- func (s *ProxySession) SetData(data interface{})
- func (s *ProxySession) SetMetadata(key, value string)
- func (s *ProxySession) Touch()
- func (s *ProxySession) Type() SessionType
- func (s *ProxySession) UpdatedAt() time.Time
- type SSESession
- func (s *SSESession) Disconnect()
- func (s *SSESession) GetClientInfo() *ssecommon.SSEClient
- func (s *SSESession) GetConnectionStatus() bool
- func (s *SSESession) GetCreatedAt() time.Time
- func (s *SSESession) SendMessage(msg string) error
- func (s *SSESession) SetClientInfo(client *ssecommon.SSEClient)
- type Session
- type SessionType
- type Storage
- type StreamableSession
Constants ¶
const ( // CodeSessionNotFound is the JSON-RPC error code for expired or unknown sessions. // This matches the MCP TypeScript SDK reference server convention and falls within // the JSON-RPC 2.0 implementation-defined server-errors range (-32000 to -32099). // MCP clients use this code to trigger automatic session recovery. CodeSessionNotFound int64 = -32001 // MessageSessionNotFound is the JSON-RPC error message for session-not-found. MessageSessionNotFound = "Session not found" )
const ( SessionTypeMCP = sessiontypes.SessionTypeMCP SessionTypeSSE = sessiontypes.SessionTypeSSE SessionTypeStreamable = sessiontypes.SessionTypeStreamable DefaultSessionTTL = sessiontypes.DefaultSessionTTL )
Re-exported from sessiontypes.
const MetadataKeyIdentityBinding = "vmcp.identity.binding"
MetadataKeyIdentityBinding is the canonical persisted ownership key.
const RedisPasswordEnvVar = "THV_SESSION_REDIS_PASSWORD"
RedisPasswordEnvVar is the environment variable name for the Redis session storage password. The operator injects this as a SecretKeyRef when sessionStorage.provider is "redis" and passwordRef is set. #nosec G101 -- This is an environment variable name, not a hardcoded credential
Variables ¶
var ( // ErrSessionDisconnected is returned when trying to send to a disconnected session ErrSessionDisconnected = httperr.WithCode( errors.New("session is disconnected"), http.StatusServiceUnavailable, ) // ErrMessageChannelFull is returned when the message channel is full ErrMessageChannelFull = httperr.WithCode( errors.New("message channel is full"), http.StatusServiceUnavailable, ) // ErrSessionNotFound is returned when a session cannot be found ErrSessionNotFound = httperr.WithCode( errors.New("session not found"), http.StatusNotFound, ) // ErrSessionAlreadyExists is returned when trying to create a session with an existing ID ErrSessionAlreadyExists = httperr.WithCode( errors.New("session already exists"), http.StatusConflict, ) // ErrInvalidSessionType is returned when an invalid session type is provided ErrInvalidSessionType = httperr.WithCode( errors.New("invalid session type"), http.StatusBadRequest, ) )
Common session errors
var ErrUndecodableSessionData = errors.New("failed to deserialize session metadata")
ErrUndecodableSessionData reports a value under the session key prefix that is not session metadata. Other features keep keys under the same prefix, so an ID naming one of them reads a value of another kind.
Functions ¶
func HasJSONRPCID ¶ added in v0.41.0
HasJSONRPCID reports whether requestID is a usable JSON-RPC id, i.e. whether callers should emit an "id" key at all.
MCP narrows base JSON-RPC here: schema/2025-11-25 types the error response as `id?: RequestId` where RequestId = string | number, so an absent id is encoded by omitting the key, never as null. The reference TypeScript SDK enforces this with a .strict() schema and a throwing parse(), so "id":null crashes a conformant client's transport.
A json.RawMessage holding literal null -- or nothing -- is an absent id even though the interface value is non-nil.
Do not pass a typed jsonrpc2.ID here: its zero value is a non-nil interface holding an empty struct, so this predicate would (wrongly) report it as present and callers would emit "id":{}. Use id.IsValid() instead.
func NotFoundBody ¶ added in v0.14.1
NotFoundBody returns the JSON-encoded body for a session-not-found JSON-RPC error response. The requestID is the "id" from the incoming JSON-RPC request, echoed so a client correlating by id can match this error to the request that caused it.
MCP narrows base JSON-RPC 2.0 here: schema/2025-11-25 types the error response as `id?: RequestId` where RequestId = string | number, so an absent id is encoded by omitting the "id" key entirely, never as null. The reference TypeScript SDK enforces this with a .strict() schema and a throwing parse(), so an "id":null response crashes a conformant client's transport. See HasJSONRPCID.
Pass nil only when the request genuinely carries no id: a bodiless GET (standalone SSE) or DELETE, a notification, or a batch. Do NOT pass nil merely because threading the id to the call site is inconvenient — that was the asymmetry fixed in #5945.
func NotFoundResponse ¶ added in v0.14.1
NotFoundResponse constructs an *http.Response with HTTP 404 and a JSON-RPC error body. Use this in httputil.ReverseProxy.ModifyResponse (transparent proxy) where no http.ResponseWriter is available.
requestID follows NotFoundBody: pass the incoming request's JSON-RPC id so the error echoes it, or nil when the request has none. Callers that reject a request before parsing a body (GET/DELETE) pass nil.
func SerializeSession ¶ added in v0.77.0
SerializeSession converts a Session to its JSON representation.
func SerializedMetadata ¶ added in v0.77.0
SerializedMetadata returns the metadata of a session serialized by SerializeSession.
func WriteNotFound ¶ added in v0.14.1
func WriteNotFound(w http.ResponseWriter, requestID any)
WriteNotFound writes an HTTP 404 response with a JSON-RPC error body for session-not-found. Use this with http.ResponseWriter in the streamable HTTP and SSE proxies.
Types ¶
type DataStorage ¶ added in v0.15.0
type DataStorage interface {
// Create atomically creates session metadata only if the session ID
// does not already exist. Returns (true, nil) if the entry was created,
// (false, nil) if it already existed, or (false, err) on storage errors.
Create(ctx context.Context, id string, metadata map[string]string) (bool, error)
// Update overwrites session metadata only if the session ID already exists
// (conditional write, equivalent to Redis SET XX). Returns (true, nil) if
// the entry was updated, (false, nil) if it was not found, or (false, err)
// on storage errors. Use this (SET XX) for writes that must not recreate a
// key that was concurrently deleted — an unconditional write would silently
// resurrect a session the caller intentionally terminated.
Update(ctx context.Context, id string, metadata map[string]string) (bool, error)
// Load retrieves session metadata and refreshes its TTL.
// Returns ErrSessionNotFound if the session does not exist.
Load(ctx context.Context, id string) (map[string]string, error)
// LoadMetadata retrieves session metadata without refreshing its TTL, for
// checks (such as ownership) that must not keep a session alive on behalf
// of a caller that may be rejected. Returns ErrSessionNotFound if the
// session does not exist.
LoadMetadata(ctx context.Context, id string) (map[string]string, error)
// Delete removes session metadata. Not an error if absent.
Delete(ctx context.Context, id string) error
// Close releases resources (connections, background goroutines).
Close() error
}
DataStorage stores session metadata as plain key-value pairs.
Unlike the Session-based Storage interface, DataStorage never attempts to round-trip live session objects (MultiSession, StreamableSession, etc.). It stores only serializable metadata, keeping data storage and live-object lifecycle as separate concerns.
This separation avoids the type-assertion bug where a Redis round-trip deserializes a MultiSession as a plain *StreamableSession, losing all backend connections and routing state.
Contract ¶
- Create atomically creates metadata for id only if it does not already exist. Returns (true, nil) if created, (false, nil) if the key already existed.
- Update overwrites metadata only if the key already exists (SET XX semantics). Returns (true, nil) if updated, (false, nil) if the session was not found. Use this instead of Load→mutate→unconditional-write to avoid TOCTOU resurrection races (a concurrent Delete between Load and write would be silently undone by an unconditional write).
- Load retrieves metadata and refreshes the TTL (sliding-window expiry). Returns ErrSessionNotFound if the session does not exist.
- Delete removes the session. It is not an error if the session is absent.
- Close releases any resources held by the backend (connections, goroutines).
Implementations ¶
Two concrete implementations are provided:
- LocalSessionDataStorage (in-memory, single-process)
- RedisSessionDataStorage (Redis/Valkey, multi-process)
type Factory ¶
Factory defines a function type for creating new sessions. It now returns the Session interface to support different session types.
type LegacyFactory ¶ added in v0.2.17
type LegacyFactory func(id string) *ProxySession
LegacyFactory is the old factory type for backward compatibility
type LocalSessionDataStorage ¶ added in v0.15.0
type LocalSessionDataStorage struct {
// contains filtered or unexported fields
}
LocalSessionDataStorage implements DataStorage using an in-memory map with TTL-based eviction.
Sessions are evicted if they have not been accessed within the configured TTL. A background goroutine runs until Close is called.
func NewLocalSessionDataStorage ¶ added in v0.15.0
func NewLocalSessionDataStorage(ttl time.Duration) (*LocalSessionDataStorage, error)
NewLocalSessionDataStorage creates a LocalSessionDataStorage with the given TTL. ttl must be positive; a zero or negative value returns an error. A background cleanup goroutine is started and runs until Close is called.
func (*LocalSessionDataStorage) Close ¶ added in v0.15.0
func (s *LocalSessionDataStorage) Close() error
Close stops the background cleanup goroutine and clears all stored metadata.
func (*LocalSessionDataStorage) Create ¶ added in v0.15.0
func (s *LocalSessionDataStorage) Create(_ context.Context, id string, metadata map[string]string) (bool, error)
Create creates session metadata only if the session ID does not already exist. Returns (true, nil) if created, (false, nil) if the key already existed.
func (*LocalSessionDataStorage) Delete ¶ added in v0.15.0
func (s *LocalSessionDataStorage) Delete(_ context.Context, id string) error
Delete removes session metadata. Not an error if absent.
func (*LocalSessionDataStorage) Load ¶ added in v0.15.0
Load retrieves session metadata and refreshes its last-access timestamp. Returns ErrSessionNotFound if the session does not exist.
func (*LocalSessionDataStorage) LoadMetadata ¶ added in v0.57.0
func (s *LocalSessionDataStorage) LoadMetadata(_ context.Context, id string) (map[string]string, error)
LoadMetadata retrieves session metadata without refreshing its last-access timestamp. Returns ErrSessionNotFound if the session does not exist.
func (*LocalSessionDataStorage) Update ¶ added in v0.19.0
func (s *LocalSessionDataStorage) Update(_ context.Context, id string, metadata map[string]string) (bool, error)
Update overwrites session metadata only if the session ID already exists. Returns (true, nil) if updated, (false, nil) if not found.
type LocalStorage ¶ added in v0.3.8
type LocalStorage struct {
// contains filtered or unexported fields
}
LocalStorage implements the Storage interface using an in-memory sync.Map. This is the default storage backend for single-instance deployments.
func NewLocalStorage ¶ added in v0.3.8
func NewLocalStorage() *LocalStorage
NewLocalStorage creates a new local in-memory storage backend.
func (*LocalStorage) Close ¶ added in v0.3.8
func (s *LocalStorage) Close() error
Close clears all sessions from local storage.
func (*LocalStorage) Count ¶ added in v0.3.8
func (s *LocalStorage) Count() int
Count returns the number of sessions in storage. This is a helper method not part of the Storage interface.
func (*LocalStorage) Create ¶ added in v0.51.0
func (s *LocalStorage) Create(_ context.Context, session Session) error
Create inserts a session without replacing an existing owner.
func (*LocalStorage) Delete ¶ added in v0.3.8
func (s *LocalStorage) Delete(_ context.Context, id string) error
Delete removes a session from local storage.
func (*LocalStorage) DeleteExpired ¶ added in v0.3.8
DeleteExpired removes all sessions whose last-access time is before the given cutoff.
func (*LocalStorage) DeleteIfOwner ¶ added in v0.51.0
DeleteIfOwner atomically removes a session only while its ownership binding matches.
func (*LocalStorage) Load ¶ added in v0.3.8
Load retrieves a session from local storage and refreshes its last-access timestamp. The timestamp update happens inside LocalStorage so that eviction is correct for all session types, not just those that implement a Touch() method.
func (*LocalStorage) LoadIfOwner ¶ added in v0.51.0
LoadIfOwner atomically validates ownership and refreshes last access for the validated entry.
func (*LocalStorage) LoadMetadata ¶ added in v0.51.0
LoadMetadata returns a copy of authoritative metadata without refreshing last access.
func (*LocalStorage) Range ¶ added in v0.3.8
func (s *LocalStorage) Range(f func(key, value interface{}) bool)
Range iterates over all sessions in storage, passing the session (not the internal wrapper) to f. This is a helper method not part of the Storage interface.
func (*LocalStorage) Store ¶ added in v0.3.8
func (s *LocalStorage) Store(_ context.Context, session Session) error
Store saves a session to the local storage. For local storage, we store the session object directly without serialization.
func (*LocalStorage) StoreIfOwner ¶ added in v0.51.0
func (s *LocalStorage) StoreIfOwner(_ context.Context, session Session, expectedOwner string) (bool, error)
StoreIfOwner atomically replaces a session only while its ownership binding matches.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager holds sessions with TTL cleanup.
func NewManager ¶
NewManager creates a session manager with TTL and starts cleanup worker. It accepts either the new Factory or the legacy factory for backward compatibility.
func NewManagerWithStorage ¶ added in v0.3.8
NewManagerWithStorage creates a session manager with a custom storage backend.
func (*Manager) AddSession ¶ added in v0.2.17
AddSession adds an existing session to the manager. This is useful when you need to create a session with specific properties.
func (*Manager) AddWithID ¶
AddWithID creates (and adds) a new session with the provided ID. Returns error if ID is empty, not a valid UUID, or already exists.
func (*Manager) Count ¶ added in v0.2.17
Count returns the number of active sessions.
Note: This method only works with LocalStorage backend and returns 0 for other storage backends. Count is not part of the Storage interface because it's not feasible for distributed storage backends like Redis where counting all keys can be prohibitively expensive.
For distributed storage, consider maintaining a counter or using approximate count mechanisms provided by the storage backend.
func (*Manager) Delete ¶
Delete removes a session by ID. Returns an error if the ID is invalid or the deletion fails.
func (*Manager) DeleteIfOwner ¶ added in v0.51.0
DeleteIfOwner removes a session only if the current record still has expectedOwner.
func (*Manager) Get ¶
Get retrieves a session by ID. Returns (session, true) if found. For LocalStorage, the storage backend updates the session's last-access timestamp on Load.
func (*Manager) GetWithError ¶ added in v0.13.0
GetWithError retrieves a session by ID and returns the underlying storage error when the lookup fails. Callers that need to distinguish between ErrSessionNotFound (session absent or expired) and other storage errors (e.g. Redis connectivity failures) should use this method so they can return an appropriate HTTP status code (400 vs 503) to the client.
func (*Manager) LoadIfOwner ¶ added in v0.51.0
LoadIfOwner returns the session only if its current ownership binding matches expectedOwner.
func (*Manager) LookupOwner ¶ added in v0.51.0
LookupOwner loads authoritative metadata, not a live stream or backend session. Redis shares ownership but does not provide cross-replica stream delivery.
func (*Manager) Stop ¶
Stop stops the cleanup worker and closes the storage backend. Returns an error if closing the storage backend fails.
func (*Manager) UpsertSession ¶ added in v0.11.0
UpsertSession inserts or updates a session in storage, replacing any existing session with the same ID. Used by SessionManager to replace placeholder sessions with fully-formed MultiSession objects after phase-2 construction.
type ProxySession ¶
type ProxySession struct {
// contains filtered or unexported fields
}
ProxySession implements the Session interface for proxy sessions. It now includes support for session types, metadata, and custom data.
func NewProxySession ¶
func NewProxySession(id string) *ProxySession
NewProxySession creates a new ProxySession with the given ID. It defaults to SessionTypeMCP for backward compatibility.
func NewTypedProxySession ¶ added in v0.2.17
func NewTypedProxySession(id string, sessType SessionType) *ProxySession
NewTypedProxySession creates a new ProxySession with the given ID and type.
func (*ProxySession) CreatedAt ¶
func (s *ProxySession) CreatedAt() time.Time
CreatedAt returns the creation time of the session.
func (*ProxySession) DeleteMetadata ¶ added in v0.2.17
func (s *ProxySession) DeleteMetadata(key string)
DeleteMetadata removes a metadata key.
func (*ProxySession) GetData ¶ added in v0.2.17
func (s *ProxySession) GetData() interface{}
GetData returns the session-specific data.
func (*ProxySession) GetMetadata ¶ added in v0.2.17
func (s *ProxySession) GetMetadata() map[string]string
GetMetadata returns all metadata as a map.
func (*ProxySession) GetMetadataValue ¶ added in v0.2.17
func (s *ProxySession) GetMetadataValue(key string) (string, bool)
GetMetadataValue gets a specific metadata value.
func (*ProxySession) SetData ¶ added in v0.2.17
func (s *ProxySession) SetData(data interface{})
SetData sets the session-specific data.
func (*ProxySession) SetMetadata ¶ added in v0.2.17
func (s *ProxySession) SetMetadata(key, value string)
SetMetadata sets a metadata key-value pair.
func (*ProxySession) Touch ¶
func (s *ProxySession) Touch()
Touch updates the session's last updated time to the current time.
func (*ProxySession) Type ¶ added in v0.2.17
func (s *ProxySession) Type() SessionType
Type returns the session type.
func (*ProxySession) UpdatedAt ¶
func (s *ProxySession) UpdatedAt() time.Time
UpdatedAt returns the last updated time of the session.
type SSESession ¶ added in v0.2.17
type SSESession struct {
*ProxySession
// SSE-specific fields
MessageCh chan string
ClientInfo *ssecommon.SSEClient
IsConnected bool
}
SSESession represents an SSE (Server-Sent Events) session. It embeds ProxySession and adds SSE-specific functionality.
func NewSSESession ¶ added in v0.2.17
func NewSSESession(id string) *SSESession
NewSSESession creates a new SSE session with the given ID.
func NewSSESessionWithClient ¶ added in v0.2.17
func NewSSESessionWithClient(id string, client *ssecommon.SSEClient) *SSESession
NewSSESessionWithClient creates a new SSE session with the given ID and client info.
func (*SSESession) Disconnect ¶ added in v0.2.17
func (s *SSESession) Disconnect()
Disconnect marks the session as disconnected and closes the message channel.
func (*SSESession) GetClientInfo ¶ added in v0.2.17
func (s *SSESession) GetClientInfo() *ssecommon.SSEClient
GetClientInfo returns the SSE client information.
func (*SSESession) GetConnectionStatus ¶ added in v0.2.17
func (s *SSESession) GetConnectionStatus() bool
GetConnectionStatus returns whether the SSE session is connected.
func (*SSESession) GetCreatedAt ¶ added in v0.2.17
func (s *SSESession) GetCreatedAt() time.Time
GetCreatedAt returns when the SSE session was created. This is useful for tracking connection duration.
func (*SSESession) SendMessage ¶ added in v0.2.17
func (s *SSESession) SendMessage(msg string) error
SendMessage sends a message to the SSE client if connected.
func (*SSESession) SetClientInfo ¶ added in v0.2.17
func (s *SSESession) SetClientInfo(client *ssecommon.SSEClient)
SetClientInfo sets the SSE client information.
type Session ¶
type Session = sessiontypes.Session
Session is sessiontypes.Session.
func DeserializeSession ¶ added in v0.77.0
DeserializeSession reconstructs a Session from its JSON representation. It creates the appropriate session type based on the Type field.
func NewStreamableSession ¶ added in v0.2.17
NewStreamableSession constructs a new streamable session.
type SessionType ¶ added in v0.2.17
type SessionType = sessiontypes.SessionType
SessionType is sessiontypes.SessionType.
type StreamableSession ¶ added in v0.2.17
type StreamableSession struct {
*ProxySession
// contains filtered or unexported fields
}
StreamableSession represents a Streamable HTTP session
func (*StreamableSession) Disconnect ¶ added in v0.2.17
func (s *StreamableSession) Disconnect()
Disconnect marks session as disconnected.
func (*StreamableSession) GetData ¶ added in v0.2.17
func (*StreamableSession) GetData() interface{}
GetData returns nil for StreamableSession.
func (*StreamableSession) SetData ¶ added in v0.2.17
func (*StreamableSession) SetData(interface{})
SetData is a no-op for StreamableSession.
func (*StreamableSession) Type ¶ added in v0.2.17
func (*StreamableSession) Type() SessionType
Type identifies this as a streamable session
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package types holds the session contracts.
|
Package types holds the session contracts. |