## Overview
The DAP IO module provides comprehensive input/output operations and event-driven communication infrastructure for the DAP ecosystem. This module implements high-performance networking, asynchronous I/O handling, worker thread management, and server functionality, serving as the foundation for all data exchange and concurrent operations within DAP applications.
**Based on:** `dap-sdk/io/include/dap_*.h`, `dap-sdk/io/dap_*.c`
## Submodules
- **[[#DAP Context|DAP Context]]** - Core I/O context and operation management (2137 lines)
- **[[#DAP Events Socket|DAP Events Socket]]** - Event-driven socket operations (2148 lines)
- **[[#DAP Worker|DAP Worker]]** - Worker thread pool management (551 lines)
- **[[#DAP Events|DAP Events]]** - Event system and callbacks (534 lines)
- **[[#DAP Server|DAP Server]]** - Server infrastructure and connections (417 lines)
- **[[#DAP Timer FD|DAP Timer FD]]** - Timer operations and scheduling (340 lines)
- **[[#DAP Proc Thread|DAP Proc Thread]]** - Process thread coordination (280 lines)
- **[[#DAP Net|DAP Net]]** - Network operations abstraction (149 lines)
---
## DAP Context
### Overview
DAP Context provides the core I/O context management and centralized coordination for all I/O operations within the DAP ecosystem. As the largest submodule (2137 lines), it handles initialization, resource management, event loop processing, and serves as the central hub for all I/O activities.
### Document Structure
- [[#Overview|Overview]]
- [[#Module Structures|Module Structures]]
- [[#dap_context_t|dap_context_t - I/O Context]]
- [[#dap_context_msg_t|dap_context_msg_t - Context Messages]]
- [[#Module Functions|Module Functions]]
- [[#Context Initialization Functions|Context Initialization Functions]]
- [[#Context Management Functions|Context Management Functions]]
- [[#Message Processing Functions|Message Processing Functions]]
- [[#Error Codes|Error Codes]]
- [[#Typical Examples|Typical Examples]]
### Module Structures
#### dap_context_t
Core I/O context manager handling all input/output operations and resource coordination.
```c
typedef struct dap_context {
struct {
int epoll_fd; // Epoll file descriptor (Linux)
int kqueue_fd; // Kqueue file descriptor (BSD/macOS)
dap_events_socket_t **sockets; // Active socket array
uint32_t sockets_count; // Number of active sockets
dap_worker_t **workers; // Worker thread pool
uint32_t workers_count; // Number of worker threads
bool is_running; // Context running status
pthread_mutex_t context_mutex; // Thread synchronization
uint64_t operations_processed; // Total operations completed
} pub;
struct {
dap_list_t *pending_operations; // Queued I/O operations
dap_htable_t *socket_table; // Socket hash table
dap_context_stats_t *statistics; // Performance statistics
dap_time_t startup_time; // Context initialization time
uint32_t max_connections; // Maximum allowed connections
dap_buffer_pool_t *buffer_pool; // Shared buffer pool
} priv;
} dap_context_t;
```
**Public Fields:**
- `epoll_fd` - Linux epoll file descriptor for event monitoring
- `kqueue_fd` - BSD/macOS kqueue descriptor for event monitoring
- `sockets` - Array of active event sockets
- `sockets_count` - Current number of monitored sockets
- `workers` - Array of worker threads for processing
- `workers_count` - Number of active worker threads
- `is_running` - Context operational status flag
- `context_mutex` - Mutex for thread-safe operations
- `operations_processed` - Counter of completed I/O operations
#### dap_context_msg_t
Inter-context message structure for communication between components.
```c
typedef struct dap_context_msg {
struct {
dap_context_msg_type_t type; // Message type
void *data; // Message data pointer
size_t data_size; // Data size in bytes
dap_context_t *source_context; // Source context
dap_context_t *target_context; // Target context
uint64_t message_id; // Unique message identifier
dap_time_t timestamp; // Message creation time
} pub;
struct {
uint32_t priority; // Message priority level
dap_context_callback_t callback; // Completion callback
void *callback_arg; // Callback argument
bool is_processed; // Processing status flag
dap_context_msg_t *next; // Next message in queue
} priv;
} dap_context_msg_t;
```
### Module Functions
#### Context Initialization Functions
##### `dap_context_init()`
Initializes the main I/O context with specified worker count and connection limits.
```c
int dap_context_init(uint32_t a_workers_count, uint32_t a_max_connections);
```
**Parameters:**
- `a_workers_count` (uint32_t) - Number of worker threads to create
- `a_max_connections` (uint32_t) - Maximum concurrent connections allowed
**Returns:**
- `0` - Context initialized successfully
- `-1` - Invalid parameters provided
- `-2` - Memory allocation failed
- `-3` - System resource creation failed (epoll/kqueue)
- `-4` - Worker thread creation failed
**Error Conditions:**
- Returns `-1` if worker count is 0 or exceeds system limits
- Returns `-2` if memory allocation for context structures fails
- Returns `-3` if epoll_create() or kqueue() system calls fail
- Returns `-4` if pthread_create() fails for worker threads
**Description:** Initializes the core I/O context system with platform-specific event handling (epoll on Linux, kqueue on BSD/macOS). Creates worker thread pool and sets up internal data structures for efficient I/O operation management.
##### `dap_context_deinit()`
Cleanup and shutdown the I/O context, freeing all resources.
```c
void dap_context_deinit(void);
```
**Description:** Gracefully shuts down the I/O context by stopping all worker threads, closing all sockets, and freeing allocated memory. Ensures proper cleanup of system resources.
#### Context Management Functions
##### `dap_context_add_socket()`
Adds socket to the context for event monitoring.
```c
int dap_context_add_socket(dap_context_t *a_context, dap_events_socket_t *a_socket);
```
**Parameters:**
- `a_context` (dap_context_t*) - Target I/O context
- `a_socket` (dap_events_socket_t*) - Socket to add for monitoring
**Returns:**
- `0` - Socket added successfully
- `-1` - Invalid parameters
- `-2` - Socket limit exceeded
- `-3` - System call failed
##### `dap_context_remove_socket()`
Removes socket from context monitoring.
```c
int dap_context_remove_socket(dap_context_t *a_context, dap_events_socket_t *a_socket);
```
#### Message Processing Functions
##### `dap_context_send_msg()`
Sends message between contexts.
```c
int dap_context_send_msg(dap_context_msg_t *a_message);
```
### Error Codes
```c
typedef enum dap_context_error {
DAP_CONTEXT_SUCCESS = 0, // Operation successful
DAP_CONTEXT_ERROR_INVALID_PARAM = -1, // Invalid parameter provided
DAP_CONTEXT_ERROR_MEMORY = -2, // Memory allocation failed
DAP_CONTEXT_ERROR_SYSTEM = -3, // System call failed
DAP_CONTEXT_ERROR_SOCKET_LIMIT = -4, // Socket limit exceeded
DAP_CONTEXT_ERROR_NOT_RUNNING = -5, // Context not running
DAP_CONTEXT_ERROR_WORKER_FAILED = -6, // Worker thread error
DAP_CONTEXT_ERROR_TIMEOUT = -7 // Operation timed out
} dap_context_error_t;
```
### Typical Examples
```c
#include "dap_common.h"
#include "dap_context.h"
int example_context_initialization() {
log_it(L_INFO, "=== DAP Context Initialization ===");
// Step 1: Initialize context with 4 workers, max 1000 connections
int result = dap_context_init(4, 1000);
if (result != 0) {
log_it(L_ERROR, "Failed to initialize context: %d", result);
return -1;
}
log_it(L_INFO, "✓ Context initialized successfully");
// Step 2: Verify context is running
dap_context_t *context = dap_context_get_default();
if (!context || !context->pub.is_running) {
log_it(L_ERROR, "Context is not running");
dap_context_deinit();
return -2;
}
log_it(L_INFO, "✓ Context is running with %u workers", context->pub.workers_count);
// Step 3: Cleanup
dap_context_deinit();
log_it(L_INFO, "✓ Context cleanup completed");
return 0;
}
```
---
## DAP Events Socket
### Overview
DAP Events Socket implements high-performance event-driven socket operations with comprehensive support for TCP, UDP, and other network protocols. As one of the largest submodules (2148 lines), it provides the core networking infrastructure for all DAP applications with asynchronous I/O, buffering, and callback-based event handling.
### Document Structure
- [[#Overview|Overview]]
- [[#Module Structures|Module Structures]]
- [[#dap_events_socket_t|dap_events_socket_t - Event Socket]]
- [[#dap_events_socket_callbacks_t|dap_events_socket_callbacks_t - Socket Callbacks]]
- [[#Module Functions|Module Functions]]
- [[#Socket Creation Functions|Socket Creation Functions]]
- [[#Socket I/O Functions|Socket I/O Functions]]
- [[#Socket Management Functions|Socket Management Functions]]
- [[#Error Codes|Error Codes]]
- [[#Typical Examples|Typical Examples]]
### Module Structures
#### dap_events_socket_t
Comprehensive event-driven socket structure for network operations.
```c
typedef struct dap_events_socket {
struct {
int socket; // Socket file descriptor
dap_events_socket_type_t type; // Socket type (TCP, UDP, etc.)
struct sockaddr_storage remote_addr; // Remote address
struct sockaddr_storage local_addr; // Local address
dap_events_socket_state_t state; // Current socket state
uint64_t bytes_read; // Total bytes read
uint64_t bytes_written; // Total bytes written
bool is_connected; // Connection status
bool is_listening; // Listening status
uint32_t flags; // Socket operation flags
} pub;
struct {
dap_events_t *events; // Parent events context
dap_events_socket_callbacks_t *callbacks; // Event callbacks
void *callbacks_arg; // Callback arguments
char *read_buffer; // Read buffer
size_t read_buffer_size; // Read buffer size
char *write_buffer; // Write buffer
size_t write_buffer_size; // Write buffer size
dap_time_t last_activity; // Last activity time
bool is_encrypted; // Encryption status
dap_events_socket_t *next; // Next socket in list
} priv;
} dap_events_socket_t;
```
**Public Fields:**
- `socket` - System socket file descriptor
- `type` - Socket type (TCP, UDP, Unix domain, etc.)
- `remote_addr` - Remote endpoint address information
- `local_addr` - Local endpoint address information
- `state` - Current socket state (connecting, connected, error, etc.)
- `bytes_read` - Total bytes received through this socket
- `bytes_written` - Total bytes sent through this socket
- `is_connected` - Connection establishment status
- `is_listening` - Server listening socket flag
#### dap_events_socket_callbacks_t
Socket event callback structure for handling various socket events.
```c
typedef struct dap_events_socket_callbacks {
dap_events_socket_callback_t new_callback; // New connection callback
dap_events_socket_callback_t delete_callback; // Connection close callback
dap_events_socket_callback_t read_callback; // Data read callback
dap_events_socket_callback_t write_callback; // Data write callback
dap_events_socket_callback_t error_callback; // Error handling callback
dap_events_socket_callback_t connected_callback; // Connection established callback
dap_events_socket_callback_t accept_callback; // Accept connection callback
dap_events_socket_callback_t timer_callback; // Timer event callback
} dap_events_socket_callbacks_t;
```
### Module Functions
#### Socket Creation Functions
##### `dap_events_socket_create()`
Creates new event socket for network operations.
```c
dap_events_socket_t* dap_events_socket_create(dap_events_socket_type_t a_type, dap_events_socket_callbacks_t *a_callbacks);
```
**Parameters:**
- `a_type` (dap_events_socket_type_t) - Socket type (TCP, UDP, etc.)
- `a_callbacks` (dap_events_socket_callbacks_t*) - Event callbacks structure
**Returns:**
- `dap_events_socket_t*` - Created socket structure
- `NULL` - Creation failed
**Error Conditions:**
- Returns `NULL` if socket() system call fails
- Returns `NULL` if memory allocation fails
- Returns `NULL` if event registration fails
##### `dap_events_socket_create_tcp()`
Creates TCP socket with event handling.
```c
dap_events_socket_t* dap_events_socket_create_tcp(dap_events_socket_callbacks_t *a_callbacks);
```
##### `dap_events_socket_create_udp()`
Creates UDP socket with event handling.
```c
dap_events_socket_t* dap_events_socket_create_udp(dap_events_socket_callbacks_t *a_callbacks);
```
#### Socket I/O Functions
##### `dap_events_socket_write()`
Writes data to socket with buffering and event handling.
```c
ssize_t dap_events_socket_write(dap_events_socket_t *a_socket, const void *a_data, size_t a_data_size);
```
**Parameters:**
- `a_socket` (dap_events_socket_t*) - Target socket
- `a_data` (const void*) - Data to write
- `a_data_size` (size_t) - Size of data in bytes
**Returns:**
- `>= 0` - Number of bytes written
- `-1` - Write operation failed
##### `dap_events_socket_read()`
Reads data from socket buffer.
```c
ssize_t dap_events_socket_read(dap_events_socket_t *a_socket, void *a_data, size_t a_data_size);
```
#### Socket Management Functions
##### `dap_events_socket_listen()`
Sets socket to listening state for incoming connections.
```c
int dap_events_socket_listen(dap_events_socket_t *a_socket, int a_backlog);
```
##### `dap_events_socket_connect()`
Connects socket to remote address.
```c
int dap_events_socket_connect(dap_events_socket_t *a_socket, struct sockaddr *a_addr, socklen_t a_addr_len);
```
### Error Codes
```c
typedef enum dap_events_socket_error {
DAP_EVENTS_SOCKET_SUCCESS = 0, // Operation successful
DAP_EVENTS_SOCKET_ERROR_CREATE = -1, // Socket creation failed
DAP_EVENTS_SOCKET_ERROR_CONNECT = -2, // Connection failed
DAP_EVENTS_SOCKET_ERROR_READ = -3, // Read operation failed
DAP_EVENTS_SOCKET_ERROR_WRITE = -4, // Write operation failed
DAP_EVENTS_SOCKET_ERROR_CLOSED = -5, // Socket is closed
DAP_EVENTS_SOCKET_ERROR_BUFFER = -6, // Buffer operation failed
DAP_EVENTS_SOCKET_ERROR_TIMEOUT = -7 // Operation timed out
} dap_events_socket_error_t;
```
### Typical Examples
```c
#include "dap_common.h"
#include "dap_events_socket.h"
// Callback function for handling received data
void on_data_received(dap_events_socket_t *a_socket, void *a_arg) {
char buffer[1024];
ssize_t bytes_read = dap_events_socket_read(a_socket, buffer, sizeof(buffer));
if (bytes_read > 0) {
log_it(L_INFO, "Received %zd bytes", bytes_read);
}
}
// Callback function for handling socket errors
void on_socket_error(dap_events_socket_t *a_socket, int a_error, void *a_arg) {
log_it(L_ERROR, "Socket error occurred: %d", a_error);
}
int example_tcp_socket() {
log_it(L_INFO, "=== TCP Socket Example ===");
// Step 1: Set up callbacks
dap_events_socket_callbacks_t callbacks = {
.read_callback = on_data_received,
.error_callback = on_socket_error
};
// Step 2: Create TCP socket
dap_events_socket_t *socket = dap_events_socket_create_tcp(&callbacks);
if (!socket) {
log_it(L_ERROR, "Failed to create TCP socket");
return -1;
}
log_it(L_INFO, "✓ TCP socket created successfully");
// Step 3: Connect to remote server
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
int result = dap_events_socket_connect(socket, (struct sockaddr*)&addr, sizeof(addr));
if (result != 0) {
log_it(L_ERROR, "Failed to connect: %d", result);
dap_events_socket_delete(socket);
return -2;
}
log_it(L_INFO, "✓ Socket connected successfully");
return 0;
}
```
---
## DAP Worker
### Overview
DAP Worker implements the worker thread pool management system, providing efficient task distribution and parallel processing capabilities. This submodule (551 lines) handles thread lifecycle, work queue management, load balancing across multiple worker threads, and coordination with the main I/O context.
### Document Structure
- [[#Overview|Overview]]
- [[#Module Structures|Module Structures]]
- [[#dap_worker_t|dap_worker_t - Worker Thread]]
- [[#dap_worker_msg_reassign_t|dap_worker_msg_reassign_t - Worker Reassignment]]
- [[#dap_worker_msg_io_t|dap_worker_msg_io_t - Worker I/O Message]]
- [[#dap_proc_queue_item_t|dap_proc_queue_item_t - Process Queue Item]]
- [[#dap_proc_thread_t|dap_proc_thread_t - Process Thread]]
- [[#Module Functions|Module Functions]]
- [[#Worker Management Functions|Worker Management Functions]]
- [[#Task Processing Functions|Task Processing Functions]]
- [[#Error Codes|Error Codes]]
- [[#Typical Examples|Typical Examples]]
### Module Structures
#### dap_worker_t
Worker thread structure for handling concurrent operations and task processing.
```c
typedef struct dap_worker {
struct {
uint32_t id; // Worker thread identifier
pthread_t thread; // Thread handle
bool is_running; // Worker running status
uint64_t tasks_processed; // Total tasks completed
dap_time_t last_activity; // Last task processing time
uint32_t queue_size; // Current queue size
dap_worker_state_t state; // Worker state
} pub;
struct {
dap_queue_t *task_queue; // Task queue
pthread_mutex_t worker_mutex; // Worker synchronization
pthread_cond_t worker_cond; // Worker condition variable
dap_context_t *context; // Parent context
dap_worker_stats_t *stats; // Worker statistics
bool shutdown_requested; // Shutdown flag
} priv;
} dap_worker_t;
```
**Public Fields:**
- `id` - Unique worker thread identifier
- `thread` - POSIX thread handle for the worker
- `is_running` - Worker thread operational status
- `tasks_processed` - Counter of completed tasks
- `last_activity` - Timestamp of last task processing
- `queue_size` - Number of tasks currently queued
- `state` - Current worker state (idle, busy, stopping)
#### dap_worker_msg_reassign_t
Worker message structure for task reassignment.
```c
typedef struct dap_worker_msg_reassign {
struct {
dap_worker_msg_type_t type; // Message type
void *data; // Task data
size_t data_size; // Data size
dap_worker_callback_t callback; // Completion callback
void *callback_arg; // Callback argument
uint32_t priority; // Task priority
} pub;
struct {
dap_time_t created_time; // Task creation time
dap_worker_t *assigned_worker; // Assigned worker
bool is_processed; // Processing status
dap_worker_msg_reassign_t *next; // Next message in queue
} priv;
} dap_worker_msg_reassign_t;
```
#### dap_worker_msg_io_t
Worker message structure for I/O operations.
```c
typedef struct dap_worker_msg_io {
struct {
dap_worker_msg_type_t type; // Message type
void *data; // Task data
size_t data_size; // Data size
dap_worker_callback_t callback; // Completion callback
void *callback_arg; // Callback argument
uint32_t priority; // Task priority
} pub;
struct {
dap_time_t created_time; // Task creation time
dap_worker_t *assigned_worker; // Assigned worker
bool is_processed; // Processing status
dap_worker_msg_io_t *next; // Next message in queue
} priv;
} dap_worker_msg_io_t;
```
#### dap_proc_queue_item_t
Process queue item structure for task management.
```c
typedef struct dap_proc_queue_item {
struct {
dap_worker_msg_type_t type; // Message type
void *data; // Task data
size_t data_size; // Data size
dap_worker_callback_t callback; // Completion callback
void *callback_arg; // Callback argument
uint32_t priority; // Task priority
} pub;
struct {
dap_time_t created_time; // Task creation time
dap_worker_t *assigned_worker; // Assigned worker
bool is_processed; // Processing status
dap_proc_queue_item_t *next; // Next message in queue
} priv;
} dap_proc_queue_item_t;
```
#### dap_proc_thread_t
Process thread structure for coordinated thread operations and inter-thread communication.
```c
typedef struct dap_proc_thread {
struct {
pthread_t thread; // Thread handle
uint32_t thread_id; // Thread identifier
bool is_running; // Thread running status
dap_proc_thread_type_t type; // Thread type/purpose
uint64_t operations_count; // Operations processed
dap_time_t start_time; // Thread start time
} pub;
struct {
dap_queue_t *message_queue; // Inter-thread message queue
pthread_mutex_t thread_mutex; // Thread synchronization
pthread_cond_t thread_cond; // Thread condition variable
dap_proc_thread_callback_t callback; // Thread processing callback
void *callback_arg; // Callback argument
bool shutdown_requested; // Shutdown flag
} priv;
} dap_proc_thread_t;
```
### Module Functions
#### Worker Management Functions
##### `dap_worker_create()`
Creates new worker thread with specified configuration.
```c
dap_worker_t* dap_worker_create(uint32_t a_worker_id, dap_context_t *a_context);
```
**Parameters:**
- `a_worker_id` (uint32_t) - Unique identifier for the worker
- `a_context` (dap_context_t*) - Parent I/O context
**Returns:**
- `dap_worker_t*` - Created worker structure
- `NULL` - Worker creation failed
**Error Conditions:**
- Returns `NULL` if pthread_create() fails
- Returns `NULL` if memory allocation fails
- Returns `NULL` if mutex/condition variable initialization fails
**Description:** Creates and initializes a new worker thread with its own task queue and synchronization primitives. The worker automatically starts processing tasks from its queue.
##### `dap_worker_destroy()`
Destroys worker thread and frees resources.
```c
void dap_worker_destroy(dap_worker_t *a_worker);
```
##### `dap_worker_start()`
Starts worker thread processing.
```c
int dap_worker_start(dap_worker_t *a_worker);
```
##### `dap_worker_stop()`
Stops worker thread gracefully.
```c
int dap_worker_stop(dap_worker_t *a_worker);
```
#### Task Processing Functions
##### `dap_worker_add_task()`
Adds task to worker's processing queue.
```c
int dap_worker_add_task(dap_worker_t *a_worker, dap_worker_msg_t *a_task);
```
**Parameters:**
- `a_worker` (dap_worker_t*) - Target worker thread
- `a_task` (dap_worker_msg_t*) - Task to be processed
**Returns:**
- `0` - Task added successfully
- `-1` - Invalid parameters
- `-2` - Queue is full
- `-3` - Worker is not running
##### `dap_worker_get_stats()`
Retrieves worker performance statistics.
```c
dap_worker_stats_t* dap_worker_get_stats(dap_worker_t *a_worker);
```
### Error Codes
```c
typedef enum dap_worker_error {
DAP_WORKER_SUCCESS = 0, // Operation successful
DAP_WORKER_ERROR_CREATE = -1, // Worker creation failed
DAP_WORKER_ERROR_QUEUE_FULL = -2, // Task queue is full
DAP_WORKER_ERROR_NOT_RUNNING = -3, // Worker is not running
DAP_WORKER_ERROR_INVALID_TASK = -4, // Invalid task provided
DAP_WORKER_ERROR_THREAD = -5, // Thread operation failed
DAP_WORKER_ERROR_TIMEOUT = -6 // Operation timed out
} dap_worker_error_t;
```
### Typical Examples
```c
#include "dap_common.h"
#include "dap_worker.h"
// Task callback function
void process_task(dap_worker_msg_t *a_msg, void *a_arg) {
log_it(L_INFO, "Processing task of type %d", a_msg->pub.type);
// Process task data here
log_it(L_INFO, "✓ Task completed");
}
int example_worker_creation() {
log_it(L_INFO, "=== Worker Creation Example ===");
// Step 1: Get context
dap_context_t *context = dap_context_get_default();
if (!context) {
log_it(L_ERROR, "Context not initialized");
return -1;
}
// Step 2: Create worker
dap_worker_t *worker = dap_worker_create(1, context);
if (!worker) {
log_it(L_ERROR, "Failed to create worker");
return -1;
}
log_it(L_INFO, "✓ Worker created successfully with ID %u", worker->pub.id);
// Step 3: Start worker
int result = dap_worker_start(worker);
if (result != 0) {
log_it(L_ERROR, "Failed to start worker: %d", result);
dap_worker_destroy(worker);
return -2;
}
log_it(L_INFO, "✓ Worker started successfully");
// Step 4: Create and add task
dap_worker_msg_t *task = DAP_NEW_Z(dap_worker_msg_t);
task->pub.type = DAP_WORKER_MSG_TYPE_CUSTOM;
task->pub.callback = process_task;
task->pub.priority = 1;
result = dap_worker_add_task(worker, task);
if (result != 0) {
log_it(L_ERROR, "Failed to add task: %d", result);
} else {
log_it(L_INFO, "✓ Task added to worker queue");
}
// Step 5: Stop and cleanup
dap_worker_stop(worker);
dap_worker_destroy(worker);
log_it(L_INFO, "✓ Worker cleanup completed");
return 0;
}
```
---
## DAP Events
### Overview
DAP Events provides the core event system infrastructure, handling event registration, callback management, and event loop processing for asynchronous operations throughout the DAP ecosystem. This submodule (534 lines) manages the fundamental event-driven architecture.
### Document Structure
- [[#Overview|Overview]]
- [[#Module Structures|Module Structures]]
- [[#dap_events_t|dap_events_t - Event System]]
- [[#Module Functions|Module Functions]]
- [[#Event Management Functions|Event Management Functions]]
- [[#Error Codes|Error Codes]]
- [[#Typical Examples|Typical Examples]]
### Module Structures
#### dap_events_t
Core event system management structure for handling asynchronous operations.
```c
typedef struct dap_events {
struct {
int epoll_fd; // Epoll descriptor (Linux)
int kqueue_fd; // Kqueue descriptor (BSD/macOS)
bool is_running; // Event loop status
uint32_t active_events; // Number of active events
pthread_t event_thread; // Event processing thread
uint64_t events_processed; // Total events processed
} pub;
struct {
dap_list_t *timer_list; // Active timers list
dap_htable_t *event_table; // Event hash table
pthread_mutex_t events_mutex; // Event system mutex
bool shutdown_requested; // Shutdown flag
dap_events_stats_t *statistics; // Performance statistics
} priv;
} dap_events_t;
```
### Module Functions
#### Event Management Functions
##### `dap_events_init()`
Initializes the event system with platform-specific event handling.
```c
int dap_events_init(uint32_t a_threads_count, size_t a_conn_timeout);
```
**Returns:**
- `0` - Event system initialized successfully
- `-1` - Initialization failed
- `-2` - System resource creation failed
**Parameters:**
- `a_threads_count` (uint32_t) - Number of worker threads to create
- `a_conn_timeout` (size_t) - Connection timeout in milliseconds
**Description:** Initializes the event-driven I/O system with specified number of worker threads and connection timeout.
##### `dap_events_deinit()`
Cleanup and shutdown the event system.
```c
void dap_events_deinit();
```
**Parameters:** None
**Returns:** None (void function)
**Description:** Performs complete cleanup of the event system including stopping all worker threads and freeing resources.
##### `dap_events_start()`
Starts the event processing loop.
```c
int32_t dap_events_start();
```
**Parameters:** None
**Returns:**
- `0` - Event processing started successfully
- `-1` - Start operation failed
**Description:** Starts the main event processing loop that handles all I/O operations and callbacks.
##### `dap_events_stop_all()`
Stops all event processing.
```c
void dap_events_stop_all();
```
**Parameters:** None
**Returns:** None (void function)
**Description:** Gracefully stops all event processing and worker threads.
##### `dap_events_wait()`
Waits for event processing to complete.
```c
int32_t dap_events_wait();
```
**Parameters:** None
**Returns:**
- `0` - Event processing completed successfully
- `-1` - Wait operation failed
**Description:** Blocks until all event processing has completed.
##### `dap_worker_print_all()`
Prints information about all worker threads.
```c
void dap_worker_print_all();
```
**Parameters:** None
**Returns:** None (void function)
**Description:** Debug function to print status information about all worker threads.
##### `dap_events_thread_get_index_min()`
Gets the minimum thread index.
```c
uint32_t dap_events_thread_get_index_min();
```
**Parameters:** None
**Returns:**
- `uint32_t` - Minimum thread index
##### `dap_events_thread_get_count()`
Gets the total number of event threads.
```c
uint32_t dap_events_thread_get_count();
```
**Parameters:** None
**Returns:**
- `uint32_t` - Number of event threads
##### `dap_events_worker_get_auto()`
Gets an automatically selected worker thread.
```c
dap_worker_t* dap_events_worker_get_auto();
```
**Parameters:** None
**Returns:**
- `dap_worker_t*` - Selected worker thread
- `NULL` - No worker available
##### `dap_events_workers_init_status()`
Checks if workers are initialized.
```c
bool dap_events_workers_init_status();
```
**Parameters:** None
**Returns:**
- `true` - Workers are initialized
- `false` - Workers are not initialized
##### `dap_events_worker_get()`
Gets worker thread by index.
```c
dap_worker_t* dap_events_worker_get(uint8_t a_index);
```
**Parameters:**
- `a_index` (uint8_t) - Worker thread index
**Returns:**
- `dap_worker_t*` - Worker thread at specified index
- `NULL` - Invalid index
##### `dap_get_cpu_count()`
Gets the number of CPU cores.
```c
uint32_t dap_get_cpu_count();
```
**Parameters:** None
**Returns:**
- `uint32_t` - Number of CPU cores
##### `dap_cpu_assign_thread_on()`
Assigns thread to specific CPU core.
```c
void dap_cpu_assign_thread_on(uint32_t a_cpu_id);
```
**Parameters:**
- `a_cpu_id` (uint32_t) - CPU core ID
**Returns:** None (void function)
### Worker Management Functions
##### `dap_worker_init()`
Initializes the worker thread system.
```c
int dap_worker_init(size_t a_conn_timeout);
```
**Parameters:**
- `a_conn_timeout` (size_t) - Connection timeout in milliseconds
**Returns:**
- `0` - Worker system initialized successfully
- `-1` - Initialization failed
##### `dap_worker_deinit()`
Deinitializes the worker thread system.
```c
void dap_worker_deinit();
```
**Parameters:** None
**Returns:** None (void function)
##### `dap_worker_add_events_socket_unsafe()`
Adds event socket to worker thread (unsafe version).
```c
int dap_worker_add_events_socket_unsafe(dap_worker_t *a_worker, dap_events_socket_t *a_esocket);
```
**Parameters:**
- `a_worker` (dap_worker_t*) - Target worker thread
- `a_esocket` (dap_events_socket_t*) - Event socket to add
**Returns:**
- `0` - Socket added successfully
- `-1` - Addition failed
##### `dap_worker_add_events_socket()`
Adds event socket to worker thread (thread-safe version).
```c
void dap_worker_add_events_socket(dap_worker_t *a_worker, dap_events_socket_t *a_events_socket);
```
**Parameters:**
- `a_worker` (dap_worker_t*) - Target worker thread
- `a_events_socket` (dap_events_socket_t*) - Event socket to add
**Returns:** None (void function)
##### `dap_worker_exec_callback_on()`
Executes callback function on specific worker thread.
```c
void dap_worker_exec_callback_on(dap_worker_t *a_worker, dap_worker_callback_t a_callback, void *a_arg);
```
**Parameters:**
- `a_worker` (dap_worker_t*) - Target worker thread
- `a_callback` (dap_worker_callback_t) - Callback function to execute
- `a_arg` (void*) - Callback argument
**Returns:** None (void function)
##### `dap_worker_add_events_socket_inter()`
Adds event socket to worker thread via inter-thread communication.
```c
void dap_worker_add_events_socket_inter(dap_events_socket_t *a_es_input, dap_events_socket_t *a_events_socket);
```
**Parameters:**
- `a_es_input` (dap_events_socket_t*) - Input event socket
- `a_events_socket` (dap_events_socket_t*) - Event socket to add
**Returns:** None (void function)
##### `dap_worker_exec_callback_inter()`
Executes callback via inter-thread communication.
```c
void dap_worker_exec_callback_inter(dap_events_socket_t *a_es_input, dap_worker_callback_t a_callback, void *a_arg);
```
**Parameters:**
- `a_es_input` (dap_events_socket_t*) - Input event socket
- `a_callback` (dap_worker_callback_t) - Callback function to execute
- `a_arg` (void*) - Callback argument
**Returns:** None (void function)
##### `dap_worker_check_esocket_polled_now()`
Checks if event socket is currently being polled.
```c
bool dap_worker_check_esocket_polled_now();
```
**Parameters:** None
**Returns:**
- `true` - Event socket is being polled
- `false` - Event socket is not being polled
##### `dap_worker_context_callback_started()`
Callback for context start event.
```c
int dap_worker_context_callback_started(dap_context_t *a_context, void *a_arg);
```
**Parameters:**
- `a_context` (dap_context_t*) - Context that started
- `a_arg` (void*) - Callback argument
**Returns:**
- `0` - Callback executed successfully
- `-1` - Callback failed
##### `dap_worker_context_callback_stopped()`
Callback for context stop event.
```c
int dap_worker_context_callback_stopped(dap_context_t *a_context, void *a_arg);
```
**Parameters:**
- `a_context` (dap_context_t*) - Context that stopped
- `a_arg` (void*) - Callback argument
**Returns:**
- `0` - Callback executed successfully
- `-1` - Callback failed
##### `dap_worker_thread_loop()`
Main worker thread processing loop.
```c
int dap_worker_thread_loop(dap_context_t *a_context);
```
**Parameters:**
- `a_context` (dap_context_t*) - I/O context
**Returns:**
- `0` - Thread loop completed successfully
- `-1` - Thread loop failed
### Timer Functions
##### `dap_timerfd_init()`
Initializes the timer file descriptor system.
```c
int dap_timerfd_init();
```
**Parameters:** None
**Returns:**
- `0` - Timer system initialized successfully
- `-1` - Initialization failed
##### `dap_timerfd_delete_mt()`
Deletes timer file descriptor (multi-threaded version).
```c
void dap_timerfd_delete_mt(dap_worker_t *a_worker, dap_events_socket_uuid_t a_uuid);
```
**Parameters:**
- `a_worker` (dap_worker_t*) - Worker thread
- `a_uuid` (dap_events_socket_uuid_t) - Timer UUID
**Returns:** None (void function)
##### `dap_timerfd_reset_mt()`
Resets timer file descriptor (multi-threaded version).
```c
void dap_timerfd_reset_mt(dap_worker_t *a_worker, dap_events_socket_uuid_t a_uuid);
```
**Parameters:**
- `a_worker` (dap_worker_t*) - Worker thread
- `a_uuid` (dap_events_socket_uuid_t) - Timer UUID
**Returns:** None (void function)
##### `dap_timerfd_delete_unsafe()`
Deletes timer file descriptor (unsafe version).
```c
void dap_timerfd_delete_unsafe(dap_timerfd_t *a_timerfd);
```
**Parameters:**
- `a_timerfd` (dap_timerfd_t*) - Timer file descriptor to delete
**Returns:** None (void function)
##### `dap_timerfd_reset_unsafe()`
Resets timer file descriptor (unsafe version).
```c
void dap_timerfd_reset_unsafe(dap_timerfd_t *a_timerfd);
```
**Parameters:**
- `a_timerfd` (dap_timerfd_t*) - Timer file descriptor to reset
**Returns:** None (void function)
### Server Functions
##### `dap_server_init()`
Initializes the server module.
```c
int dap_server_init();
```
**Parameters:** None
**Returns:**
- `0` - Server module initialized successfully
- `-1` - Initialization failed
##### `dap_server_deinit()`
Deinitializes the server module.
```c
void dap_server_deinit();
```
**Parameters:** None
**Returns:** None (void function)
##### `dap_server_set_default()`
Sets the default server instance.
```c
void dap_server_set_default(dap_server_t* a_server);
```
**Parameters:**
- `a_server` (dap_server_t*) - Server instance to set as default
**Returns:** None (void function)
##### `dap_server_listen_addr_add()`
Adds listening address to server.
```c
int dap_server_listen_addr_add(dap_server_t *a_server, const char *a_addr, uint16_t a_port, dap_events_socket_callbacks_t *a_callbacks);
```
**Parameters:**
- `a_server` (dap_server_t*) - Server instance
- `a_addr` (const char*) - Address to listen on
- `a_port` (uint16_t) - Port to listen on
- `a_callbacks` (dap_events_socket_callbacks_t*) - Socket callbacks
**Returns:**
- `0` - Address added successfully
- `-1` - Addition failed
##### `dap_server_callbacks_set()`
Sets server callbacks.
```c
int dap_server_callbacks_set(dap_server_t* a_server, dap_events_socket_callbacks_t* a_callbacks, dap_events_socket_callbacks_t* a_callbacks_udp);
```
**Parameters:**
- `a_server` (dap_server_t*) - Server instance
- `a_callbacks` (dap_events_socket_callbacks_t*) - TCP callbacks
- `a_callbacks_udp` (dap_events_socket_callbacks_t*) - UDP callbacks
**Returns:**
- `0` - Callbacks set successfully
- `-1` - Setting failed
##### `dap_server_delete()`
Deletes server instance.
```c
void dap_server_delete(dap_server_t *a_server);
```
**Parameters:**
- `a_server` (dap_server_t*) - Server instance to delete
**Returns:** None (void function)
### Process Thread Functions
##### `dap_proc_thread_create()`
Creates new process thread.
```c
int dap_proc_thread_create(dap_proc_thread_t *a_thread, int a_cpu_id);
```
**Parameters:**
- `a_thread` (dap_proc_thread_t*) - Thread structure to initialize
- `a_cpu_id` (int) - CPU ID to bind thread to
**Returns:**
- `0` - Thread created successfully
- `-1` - Creation failed
##### `dap_proc_thread_init()`
Initializes the process thread system.
```c
int dap_proc_thread_init(uint32_t a_threads_count);
```
**Parameters:**
- `a_threads_count` (uint32_t) - Number of threads to create
**Returns:**
- `0` - System initialized successfully
- `-1` - Initialization failed
##### `dap_proc_thread_deinit()`
Deinitializes the process thread system.
```c
void dap_proc_thread_deinit();
```
**Parameters:** None
**Returns:** None (void function)
##### `dap_proc_thread_loop()`
Main process thread loop.
```c
int dap_proc_thread_loop(dap_context_t *a_context);
```
**Parameters:**
- `a_context` (dap_context_t*) - I/O context
**Returns:**
- `0` - Thread loop completed successfully
- `-1` - Thread loop failed
##### `dap_proc_thread_callback_add_pri()`
Adds callback to process thread with priority.
```c
int dap_proc_thread_callback_add_pri(dap_proc_thread_t *a_thread, dap_proc_queue_callback_t a_callback, void *a_callback_arg, dap_queue_msg_priority_t a_priority);
```
**Parameters:**
- `a_thread` (dap_proc_thread_t*) - Target thread
- `a_callback` (dap_proc_queue_callback_t) - Callback function
- `a_callback_arg` (void*) - Callback argument
- `a_priority` (dap_queue_msg_priority_t) - Message priority
**Returns:**
- `0` - Callback added successfully
- `-1` - Addition failed
##### `dap_proc_thread_timer_add_pri()`
Adds timer to process thread with priority.
```c
int dap_proc_thread_timer_add_pri(dap_proc_thread_t *a_thread, dap_thread_timer_callback_t a_callback, void *a_callback_arg, uint64_t a_timeout_ms, bool a_oneshot, dap_queue_msg_priority_t a_priority);
```
**Parameters:**
- `a_thread` (dap_proc_thread_t*) - Target thread
- `a_callback` (dap_thread_timer_callback_t) - Timer callback
- `a_callback_arg` (void*) - Callback argument
- `a_timeout_ms` (uint64_t) - Timeout in milliseconds
- `a_oneshot` (bool) - One-shot timer flag
- `a_priority` (dap_queue_msg_priority_t) - Message priority
**Returns:**
- `0` - Timer added successfully
- `-1` - Addition failed
##### `dap_proc_thread_get_avg_queue_size()`
Gets average queue size across all process threads.
```c
size_t dap_proc_thread_get_avg_queue_size();
```
**Parameters:** None
**Returns:**
- `size_t` - Average queue size
##### `dap_proc_thread_get_count()`
Gets the number of process threads.
```c
uint32_t dap_proc_thread_get_count();
```
**Parameters:** None
**Returns:**
- `uint32_t` - Number of process threads
### Network Functions
##### `dap_net_resolve_host()`
Resolves hostname to address.
```c
int dap_net_resolve_host(const char *a_host, const char *a_port, bool a_numeric_only, struct sockaddr_storage *a_addr_out, int *a_family);
```
**Parameters:**
- `a_host` (const char*) - Hostname to resolve
- `a_port` (const char*) - Port number
- `a_numeric_only` (bool) - Numeric resolution only flag
- `a_addr_out` (struct sockaddr_storage*) - Output address structure
- `a_family` (int*) - Output address family
**Returns:**
- `0` - Resolution successful
- `-1` - Resolution failed
##### `dap_net_parse_config_address()`
Parses configuration address string.
```c
int dap_net_parse_config_address(const char *a_src, char *a_addr, uint16_t *a_port, struct sockaddr_storage *a_saddr, int *a_family);
```
**Parameters:**
- `a_src` (const char*) - Source address string
- `a_addr` (char*) - Output address string
- `a_port` (uint16_t*) - Output port number
- `a_saddr` (struct sockaddr_storage*) - Output socket address
- `a_family` (int*) - Output address family
**Returns:**
- `0` - Parsing successful
- `-1` - Parsing failed
##### `dap_net_recv()`
Receives data from socket with timeout.
```c
long dap_net_recv(SOCKET sd, unsigned char *buf, size_t bufsize, int timeout);
```
**Parameters:**
- `sd` (SOCKET) - Socket descriptor
- `buf` (unsigned char*) - Receive buffer
- `bufsize` (size_t) - Buffer size
- `timeout` (int) - Timeout in milliseconds
**Returns:**
- `> 0` - Number of bytes received
- `0` - Connection closed
- `-1` - Receive failed
---
**See also:** [[Module DAP Core|Module DAP Core]], [[Module DAP Net|Module DAP Net]]
---
*Based on: `dap-sdk/io/include/dap_*.h`, `dap-sdk/io/dap_*.c`*