Documentation
¶
Index ¶
- Constants
- func CloseEvent(h EventHandle)
- func CloseShm(h ShmHandle, addr uintptr, size uint64)
- func SignalEvent(h EventHandle)
- func UnlinkEvent(name string)
- func UnlinkShm(name string)
- func WaitForEvent(h EventHandle, timeoutMs uint32)
- type Client
- func (c *Client) AcquireGuestSlot() (*GuestSlot, error)
- func (c *Client) Close()
- func (c *Client) Handle(h func(req []byte, respBuf []byte, msgType MsgType) (int32, MsgType))
- func (c *Client) SendGuestCall(data []byte, msgType MsgType) ([]byte, error)
- func (c *Client) SendGuestCallWithTimeout(data []byte, msgType MsgType, timeout time.Duration) ([]byte, error)
- func (c *Client) SetTimeout(d time.Duration)
- func (c *Client) Start()
- func (c *Client) Wait()
- type ClientConfig
- type DirectGuest
- func (g *DirectGuest) AcquireGuestSlot() (*GuestSlot, error)
- func (g *DirectGuest) Close()
- func (g *DirectGuest) SendGuestCall(data []byte, msgType MsgType) ([]byte, error)
- func (g *DirectGuest) SendGuestCallWithTimeout(data []byte, msgType MsgType, timeout time.Duration) ([]byte, error)
- func (g *DirectGuest) SetTimeout(d time.Duration)
- func (g *DirectGuest) Start(handler func(req []byte, resp []byte, msgType MsgType) (int32, MsgType))
- func (g *DirectGuest) Wait()
- type EventHandle
- type ExchangeHeader
- type GuestSlot
- func (s *GuestSlot) Release()
- func (s *GuestSlot) RequestBuffer() []byte
- func (s *GuestSlot) ResponseBuffer() []byte
- func (s *GuestSlot) Send(size int32, msgType MsgType) (int32, MsgType, error)
- func (s *GuestSlot) SendWithTimeout(size int32, msgType MsgType, timeout time.Duration) (int32, MsgType, error)
- type MsgType
- type ShmHandle
- type SlotHeader
- type WaitStrategy
Constants ¶
const ( // SlotFree indicates the slot is available for the Host to claim. SlotFree = 0 // SlotReqReady indicates the Host has written a request and it is ready for the Guest. SlotReqReady = 1 // SlotRespReady indicates the Guest has written a response and it is ready for the Host. SlotRespReady = 2 // SlotDone is a transient state indicating transaction completion. SlotDone = 3 // SlotBusy indicates the Host has claimed the slot and is writing data. SlotBusy = 4 // SlotGuestBusy indicates the Guest has claimed the slot and is writing data. SlotGuestBusy = 5 // MsgTypeNormal is a standard data payload message. MsgTypeNormal MsgType = 0 // MsgTypeHeartbeatReq is a keep-alive request from the Host. MsgTypeHeartbeatReq MsgType = 1 // MsgTypeHeartbeatResp is the response to a keep-alive request. MsgTypeHeartbeatResp MsgType = 2 // MsgTypeShutdown signals the Guest to terminate. MsgTypeShutdown MsgType = 3 // MsgTypeFlatbuffer indicates a Zero-Copy FlatBuffer payload. MsgTypeFlatbuffer MsgType = 10 // MsgTypeGuestCall indicates a Guest Call payload. MsgTypeGuestCall MsgType = 11 // MsgTypeAppStart is the start of Application Specific message types. // Types below 128 are reserved for internal protocol use. // Applications should define their own message types starting from this value. // // Example: // const ( // MyMsgLogin = shm.MsgTypeAppStart + 0 // MyMsgUpdate = shm.MsgTypeAppStart + 1 // ) MsgTypeAppStart MsgType = 128 // Magic is the magic number for validating shared memory ("XLL!"). Magic uint32 = 0x584C4C21 // Version is the current protocol version (v0.5.0). Version uint32 = 0x00050000 // HostStateActive indicates the Host is spinning or processing. HostStateActive = 0 // HostStateWaiting indicates the Host is sleeping on the Response Event. HostStateWaiting = 1 // GuestStateActive indicates the Guest is spinning or processing. GuestStateActive = 0 // GuestStateWaiting indicates the Guest is sleeping on the Request Event. GuestStateWaiting = 1 )
Constants defining slot states and message Types.
Variables ¶
This section is empty.
Functions ¶
func CloseEvent ¶
func CloseEvent(h EventHandle)
CloseEvent closes the event handle and releases associated resources.
h: The event handle.
func CloseShm ¶
CloseShm unmaps the shared memory and closes the handle.
h: The shared memory handle. addr: The mapped address. size: The size of the mapping.
func SignalEvent ¶
func SignalEvent(h EventHandle)
SignalEvent signals the event, waking up any waiting threads.
h: The event handle.
func UnlinkEvent ¶
func UnlinkEvent(name string)
UnlinkEvent removes the named event from the system. This is primarily relevant for POSIX semaphores which persist until unlinked.
name: The name of the event.
func UnlinkShm ¶
func UnlinkShm(name string)
UnlinkShm removes the named shared memory region from the system.
name: The name of the shared memory region.
func WaitForEvent ¶
func WaitForEvent(h EventHandle, timeoutMs uint32)
WaitForEvent blocks the current thread until the event is signaled or the timeout expires.
h: The event handle. timeoutMs: Timeout in milliseconds.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the high-level API for the Guest side of the IPC. It wraps DirectGuest and handles connection retries and lifecycle management.
func Connect ¶
func Connect(config ClientConfig) (*Client, error)
Connect attempts to establish a connection to the Host using the provided configuration. It assumes Direct Mode and retries until the timeout expires.
config: The configuration object.
Returns a Client instance or an error if connection fails after retries.
func ConnectDefault ¶
ConnectDefault is a helper for backward compatibility or simple usage. It connects with default settings (10s timeout).
func (*Client) AcquireGuestSlot ¶
AcquireGuestSlot acquires a free guest slot for Zero-Copy operations.
This allows the caller to write directly to the shared memory buffer and read the response directly, avoiding extra allocations.
Returns a GuestSlot object or an error if no slots are available. The caller must call Release() on the slot when finished.
func (*Client) Close ¶
func (c *Client) Close()
Close releases all resources associated with the client. It closes shared memory handles and event handles. Note: This does not stop background workers if they are blocked on OS events.
func (*Client) Handle ¶
Handle registers the request handler function.
h: A function that takes a request buffer, response buffer, and message Type.
It should process the request, write the response to the response buffer, and return the size of the response written (negative for End-Aligned) and the response MsgType.
The handler must be thread-safe as it may be called concurrently by multiple workers.
func (*Client) SendGuestCall ¶
SendGuestCall sends a message to the Host (Guest Call). It uses the default timeout configured via SetTimeout (default 10s).
data: The payload to send. msgType: The message type.
Returns the response payload or an error.
func (*Client) SendGuestCallWithTimeout ¶
func (c *Client) SendGuestCallWithTimeout(data []byte, msgType MsgType, timeout time.Duration) ([]byte, error)
SendGuestCallWithTimeout sends a message to the Host (Guest Call) with a custom timeout.
data: The payload to send. msgType: The message type. timeout: The custom timeout duration.
Returns the response payload or an error.
func (*Client) SetTimeout ¶
SetTimeout sets the timeout for waiting for a response (Guest Call).
d: The timeout duration.
type ClientConfig ¶
type ClientConfig struct {
// ShmName is the name of the shared memory region (e.g., "MyIPC").
ShmName string
// ConnectionTimeout is the maximum duration to wait for the Host to initialize shared memory.
// Default: 10 seconds.
ConnectionTimeout time.Duration
// RetryInterval is the interval between connection attempts.
// Default: 100 milliseconds.
RetryInterval time.Duration
}
ClientConfig holds configuration parameters for the Client connection.
type DirectGuest ¶
type DirectGuest struct {
// contains filtered or unexported fields
}
DirectGuest implements the Guest side of the Direct Mode IPC. It manages multiple workers, each attached to a specific slot.
func NewDirectGuest ¶
func NewDirectGuest(name string) (*DirectGuest, error)
NewDirectGuest initializes the DirectGuest by attaching to an existing shared memory region.
name: The name of the shared memory region.
Returns a pointer to the initialized DirectGuest or an error if attachment fails.
func (*DirectGuest) AcquireGuestSlot ¶
func (g *DirectGuest) AcquireGuestSlot() (*GuestSlot, error)
AcquireGuestSlot acquires a free guest slot for Zero-Copy operations. Returns a GuestSlot object or an error if no slots are available.
func (*DirectGuest) Close ¶
func (g *DirectGuest) Close()
Close releases shared memory resources. It signals workers to exit and cleans up resources.
func (*DirectGuest) SendGuestCall ¶
func (g *DirectGuest) SendGuestCall(data []byte, msgType MsgType) ([]byte, error)
SendGuestCall sends a request to the Host using a Guest Slot. It blocks until a response is received or the default timeout occurs.
data: The payload to send to the Host. msgType: The message type identifier.
Returns the response payload or an error if the call fails or times out.
func (*DirectGuest) SendGuestCallWithTimeout ¶
func (g *DirectGuest) SendGuestCallWithTimeout(data []byte, msgType MsgType, timeout time.Duration) ([]byte, error)
SendGuestCallWithTimeout sends a request to the Host using a Guest Slot with a custom timeout.
data: The payload to send. msgType: The message type identifier. timeout: The custom duration to wait for a response.
Returns the response payload or an error.
func (*DirectGuest) SetTimeout ¶
func (g *DirectGuest) SetTimeout(d time.Duration)
SetTimeout sets the default timeout for Guest Call responses.
d: The timeout duration. Default is 10 seconds.
func (*DirectGuest) Start ¶
func (g *DirectGuest) Start(handler func(req []byte, resp []byte, msgType MsgType) (int32, MsgType))
Start launches the worker goroutines. It spawns one goroutine per slot to handle incoming requests from the Host.
handler: The function to process requests. It receives the request buffer, response buffer, and message type.
It must return the response size (negative for end-aligned) and response message type.
func (*DirectGuest) Wait ¶
func (g *DirectGuest) Wait()
Wait blocks the calling thread until all worker goroutines have exited. Workers usually exit when the Host sends a Shutdown signal.
type EventHandle ¶
type EventHandle uintptr
EventHandle represents an OS-specific handle for a synchronization event. On Linux, it wraps a pointer to `sem_t`. On Windows, it wraps a `HANDLE`.
func CreateEvent ¶
func CreateEvent(name string) (EventHandle, error)
CreateEvent creates a new named synchronization event.
name: The name of the event.
Returns the event handle or an error if creation fails.
func OpenEvent ¶
func OpenEvent(name string) (EventHandle, error)
OpenEvent opens an existing named synchronization event.
name: The name of the event.
Returns the event handle or an error if the event does not exist or cannot be opened.
type ExchangeHeader ¶
type ExchangeHeader struct {
Magic uint32
Version uint32
NumSlots uint32
NumGuestSlots uint32
SlotSize uint32
ReqOffset uint32
RespOffset uint32
// contains filtered or unexported fields
}
ExchangeHeader represents the metadata at the start of the shared memory region. It describes the layout of the slot pool.
type GuestSlot ¶
type GuestSlot struct {
// contains filtered or unexported fields
}
GuestSlot represents an acquired slot for Zero-Copy Guest Calls. It allows the user to write directly to shared memory and read the response directly, avoiding extra allocations and copies.
func (*GuestSlot) Release ¶
func (s *GuestSlot) Release()
Release marks the slot as free for other workers to use. MUST be called after processing the response.
func (*GuestSlot) RequestBuffer ¶
RequestBuffer returns the shared memory buffer for the request. The user should write their data into this buffer. For standard messages, write at the beginning. For Zero-Copy (FlatBuffers), write at the end and use a negative size in Send().
func (*GuestSlot) ResponseBuffer ¶
ResponseBuffer returns the shared memory buffer for the response. This buffer contains the valid response data after Send() returns successfully. Note: The valid data range depends on the size returned by the Host (available in the header), but for raw access, this returns the full buffer.
func (*GuestSlot) Send ¶
Send signals the Host to process the request currently in the RequestBuffer.
size: The size of the data written.
Positive: Data starts at index 0. Negative: Data ends at the end of the buffer (End-Aligned).
msgType: The message type.
Returns:
- int32: The size of the response (Positive=Start, Negative=End).
- MsgType: The type of the response.
- error: Error if transaction fails or times out.
type MsgType ¶
type MsgType uint32
MsgType represents the type of the message (command). It is distinct from the Message ID (Sequence ID).
We use a distinct type definition (not an alias) to ensure type safety, preventing accidental mixing with other uint32 values like MsgId or sizes.
type ShmHandle ¶
type ShmHandle uintptr
ShmHandle represents an OS-specific handle for a shared memory region. On Linux, it wraps a file descriptor (int). On Windows, it wraps a `HANDLE`.
func CreateShm ¶
CreateShm creates a new named shared memory region of the specified size.
name: The name of the shared memory region. size: The size of the region in bytes.
Returns the handle, the mapped address (uintptr), and any error.
type SlotHeader ¶
type SlotHeader struct {
State uint32
HostState uint32
GuestState uint32
MsgSeq uint32
MsgType MsgType
ReqSize int32
RespSize int32
// contains filtered or unexported fields
}
SlotHeader represents the metadata for a single slot in shared memory. It must match the C++ layout exactly (128 bytes).
type WaitStrategy ¶
type WaitStrategy struct {
CurrentLimit int32
MinSpin int32
MaxSpin int32
IncStep int32
DecStep int32
YieldEnabled bool
}
WaitStrategy implements an adaptive spin-wait strategy.
func NewWaitStrategy ¶
func NewWaitStrategy(enableYield bool) *WaitStrategy
NewWaitStrategy creates a new WaitStrategy with default optimized values. enableYield: If true, calls runtime.Gosched() periodically during spinning.
Recommended for multi-threaded/oversubscribed environments. If false, performs strict busy-waiting (better for single-thread latency).
func (*WaitStrategy) Wait ¶
func (w *WaitStrategy) Wait(condition func() bool, sleepAction func()) bool
Wait executes the adaptive wait logic.
condition: A function that returns true if the wait condition is met. sleepAction: A function to execute when spinning fails (e.g. wait on semaphore).
Returns true if the condition was met.