MCPcopy Index your code
hub / github.com/AlexStocks/getty

github.com/AlexStocks/getty @v1.5.2

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.5.2 ↗ · + Follow
876 symbols 2,803 edges 71 files 265 documented · 30%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

getty 中文

a netty like asynchronous network I/O library

Build Status codecov go.dev reference Go Report Card license

INTRO

Getty is an asynchronous network I/O library developed in Golang. It operates on TCP, UDP, and WebSocket network protocols, providing a consistent interface EventListener.

Within Getty, each connection (session) involves two separate goroutines. One handles the reading of TCP streams, UDP packets, or WebSocket packages, while the other manages the logic processing and writes responses into the network write buffer. If your logic processing might take a considerable amount of time, it's recommended to start a new logic process goroutine yourself within codec.go's (Codec)OnMessage method.

Additionally, you can manage heartbeat logic within the (Codec)OnCron method in codec.go. If you're using TCP or UDP, you should send heartbeat packages yourself and then call session.go's (Session)UpdateActive method to update the session's activity timestamp. You can verify if a TCP session has timed out or not in codec.go's (Codec)OnCron method using session.go's (Session)GetActive method.

If you're using WebSocket, you don't need to worry about heartbeat request/response, as Getty handles this task within session.go's (Session)handleLoop method by sending and receiving WebSocket ping/pong frames. Your responsibility is to check whether the WebSocket session has timed out or not within codec.go's (Codec)OnCron method using session.go's (Session)GetActive method.

For code examples, you can refer to getty-examples.

Callback System

Getty provides a robust callback system that allows you to register and manage callback functions for session lifecycle events. This is particularly useful for cleanup operations, resource management, and custom event handling.

Key Features

  • Thread-safe operations: All callback operations are protected by mutex locks
  • Replace semantics: Adding with the same (handler, key) replaces the existing callback in place (position preserved)
  • Panic safety: During session close, callbacks run in a dedicated goroutine with defer/recover; panics are logged with stack traces and do not escape the close path
  • Ordered execution: Callbacks are executed in the order they were added

Usage Example

// Add a close callback
session.AddCloseCallback("cleanup", "resources", func() {
    // Cleanup resources when session closes
    cleanupResources()
})

// Remove a specific callback
// Safe to call even if the pair was never added (no-op)
session.RemoveCloseCallback("cleanup", "resources")

// Callbacks are automatically executed when the session closes

Note: During session shutdown, callbacks are executed sequentially in a dedicated goroutine to preserve add-order, with defer/recover to log panics without letting them escape the close path.

Callback Management

  • AddCloseCallback: Register a callback to be executed when the session closes
  • RemoveCloseCallback: Remove a previously registered callback (no-op if not found; safe to call multiple times)
  • Thread Safety: All operations are thread-safe and can be called concurrently

Type Requirements

The handler and key parameters must be comparable types that support the == operator:

✅ Supported types: - Basic types: string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64, bool, complex64, complex128 - ⚠️ Avoid float*/complex* as keys due to NaN and precision semantics; prefer strings/ints - Pointer types: Pointers to any type (e.g., *int, *string, *MyStruct) - Interface types: Interface types are comparable only when their dynamic values are comparable types; using "==" with non-comparable dynamic values will be safely ignored with error log - Channel types: Channel types (compared by channel identity) - Array types: Arrays of comparable elements (e.g., [3]int, [2]string) - Struct types: Structs where all fields are comparable types

⚠️ Non-comparable types (will be safely ignored with error log): - map types (e.g., map[string]int) - slice types (e.g., []int, []string) - func types (e.g., func(), func(int) string) - Structs containing non-comparable fields (maps, slices, functions)

Examples:

// ✅ Valid usage
session.AddCloseCallback("user", "cleanup", callback)
session.AddCloseCallback(123, "cleanup", callback)
session.AddCloseCallback(true, false, callback)

// ⚠️ Non-comparable types (safely ignored with error log)
session.AddCloseCallback(map[string]int{"a": 1}, "key", callback)  // Logged and ignored
session.AddCloseCallback([]int{1, 2, 3}, "key", callback)          // Logged and ignored

About network transmission in getty

In network communication, the data transmission interface of getty does not guarantee that data will be sent successfully; it lacks an internal retry mechanism. Instead, getty delegates the outcome of data transmission to the underlying operating system mechanism. Under this mechanism, if data is successfully transmitted, it is considered a success; if transmission fails, it is regarded as a failure. These outcomes are then communicated back to the upper-layer caller.

Upper-layer callers need to determine whether to incorporate a retry mechanism based on these outcomes. This implies that when data transmission fails, upper-layer callers must handle the situation differently depending on the circumstances. For instance, if the failure is due to a disconnect in the connection, upper-layer callers can attempt to resend the data based on the result of getty's automatic reconnection. Alternatively, if the failure is caused by the sending buffer of the underlying operating system being full, the sender can implement its own retry mechanism to wait for the sending buffer to become available before attempting another transmission.

In summary, the data transmission interface of getty does not come with an inherent retry mechanism; instead, it is up to upper-layer callers to decide whether to implement retry logic based on specific situations. This design approach provides developers with greater flexibility in controlling the behavior of data transmission.

LICENCE

Apache License 2.0

Extension points exported contracts — how you extend this code

Reader (Interface)
Reader is used to unmarshal a complete pkg from buffer [9 implementers]
transport/getty.go
PackageHandler (Interface)
(no doc) [6 implementers]
examples/echo/udp-echo/server/app/handler.go
TlsConfigBuilder (Interface)
TlsConfigBuilder tls config builder interface [2 implementers]
transport/tls.go
StreamServer (Interface)
StreamServer is like tcp/websocket/wss server [1 implementers]
transport/server.go
Session (Interface)
Session wrap connection between the server and the client [1 implementers]
transport/session.go
ClientOption (FuncType)
Client Options
transport/options.go
Connection (Interface)
Connection wrap some connection params and operations
transport/connection.go
CallBackFunc (FuncType)
CallBackFunc defines the callback function type when Session closes Usage notes: - Callback function accepts no paramet
transport/session_callback.go

Core symbols most depended-on inside this repo

Info
called by 92
util/logger.go
Stat
called by 73
transport/session.go
inRange
called by 67
examples/echo/wss-echo/js-client/encoding.js
inRange
called by 67
examples/echo/ws-echo/js-client/encoding.js
Add
called by 61
transport/callback.go
Warnf
called by 61
util/logger.go
Errorf
called by 56
util/logger.go
Len
called by 54
transport/callback.go

Shape

Function 441
Method 318
Struct 85
Interface 17
TypeAlias 11
FuncType 4

Languages

Go68%
TypeScript32%

Modules by API surface

examples/echo/wss-echo/js-client/jquery-1.10.2.min.js74 symbols
examples/echo/ws-echo/js-client/jquery-1.10.2.min.js74 symbols
transport/session.go70 symbols
transport/connection.go58 symbols
examples/echo/wss-echo/js-client/encoding.js41 symbols
examples/echo/ws-echo/js-client/encoding.js41 symbols
transport/server.go32 symbols
util/logger.go23 symbols
transport/client.go23 symbols
transport/options.go20 symbols
transport/client_test.go20 symbols
transport/getty.go19 symbols

For agents

$ claude mcp add getty \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact