Skip to main content

A cross-platform IPC (Inter-Process Communication) library powered by Rust

Project description

ipckit

Crates.io PyPI Documentation CI License Python Versions Rust Version Downloads

A high-performance, cross-platform IPC (Inter-Process Communication) library for Rust and Python, powered by Rust.

中文文档

✨ Features

  • 🚀 High Performance - Written in Rust, with zero-copy where possible
  • 🔀 Cross-Platform - Works on Windows, Linux, and macOS
  • 🐍 Python Bindings - First-class Python support via PyO3
  • 📦 Multiple IPC Methods - Pipes, Shared Memory, Channels, and File-based IPC
  • 🔒 Thread-Safe - Safe concurrent access across processes
  • Native JSON - Built-in fast JSON serialization using Rust's serde_json
  • 🛡️ Graceful Shutdown - Built-in support for graceful channel shutdown
  • 🔌 Local Socket - Unix Domain Socket / Named Pipe abstraction for cross-platform socket communication
  • 🧵 Thread Channel - High-performance intra-process thread communication
  • 📡 Event Stream - Real-time publish-subscribe event system
  • 📋 Task Manager - Task lifecycle management with progress tracking
  • 🌐 Socket Server - Multi-client socket server (like Docker's socket)

📦 Installation

Python

pip install ipckit

Rust

[dependencies]
ipckit = "0.1"

🚀 Quick Start

Anonymous Pipe (Parent-Child Communication)

Python:

import ipckit
import subprocess

# Create pipe pair
pipe = ipckit.AnonymousPipe()

# Write to pipe
pipe.write(b"Hello from parent!")

# Read from pipe
data = pipe.read(1024)
print(data)

Rust:

use ipckit::AnonymousPipe;

fn main() -> ipckit::Result<()> {
    let pipe = AnonymousPipe::new()?;
    
    pipe.write_all(b"Hello from Rust!")?;
    
    let mut buf = [0u8; 1024];
    let n = pipe.read(&mut buf)?;
    println!("{}", String::from_utf8_lossy(&buf[..n]));
    
    Ok(())
}

Named Pipe (Unrelated Process Communication)

Python Server:

import ipckit

# Create server
server = ipckit.NamedPipe.create("my_pipe")
print("Waiting for client...")
server.wait_for_client()

# Communicate
data = server.read(1024)
server.write(b"Response from server")

Python Client:

import ipckit

# Connect to server
client = ipckit.NamedPipe.connect("my_pipe")

# Communicate
client.write(b"Hello from client")
response = client.read(1024)
print(response)

Shared Memory (Fast Data Exchange)

Python:

import ipckit

# Create shared memory (owner)
shm = ipckit.SharedMemory.create("my_shm", 4096)
shm.write(0, b"Shared data here!")

# In another process, open existing
shm2 = ipckit.SharedMemory.open("my_shm")
data = shm2.read(0, 17)
print(data)  # b"Shared data here!"

Rust:

use ipckit::SharedMemory;

fn main() -> ipckit::Result<()> {
    // Create
    let shm = SharedMemory::create("my_shm", 4096)?;
    shm.write(0, b"Hello from Rust!")?;
    
    // Open in another process
    let shm2 = SharedMemory::open("my_shm")?;
    let data = shm2.read(0, 16)?;
    
    Ok(())
}

IPC Channel (High-Level Message Passing)

Python:

import ipckit

# Server
channel = ipckit.IpcChannel.create("my_channel")
channel.wait_for_client()

# Send/receive JSON
channel.send_json({"type": "greeting", "message": "Hello!"})
response = channel.recv_json()
print(response)

File Channel (Frontend-Backend Communication)

Perfect for desktop applications where Python backend communicates with web frontend.

Python Backend:

import ipckit

# Create backend channel
channel = ipckit.FileChannel.backend("./ipc_channel")

# Send request to frontend
request_id = channel.send_request("getData", {"key": "user_info"})

# Wait for response
response = channel.wait_response(request_id, timeout_ms=5000)
print(response)

# Send events
channel.send_event("status_update", {"status": "ready"})

JavaScript Frontend:

// Read from: ./ipc_channel/backend_to_frontend.json
// Write to:  ./ipc_channel/frontend_to_backend.json

async function pollMessages() {
    const response = await fetch('./ipc_channel/backend_to_frontend.json');
    const messages = await response.json();
    // Process new messages...
}

Native JSON Functions

ipckit provides Rust-native JSON functions that are faster than Python's built-in json module:

import ipckit

# Serialize (1.2x faster than json.dumps)
data = {"name": "test", "values": [1, 2, 3]}
json_str = ipckit.json_dumps(data)

# Pretty print
pretty_str = ipckit.json_dumps_pretty(data)

# Deserialize
obj = ipckit.json_loads('{"key": "value"}')

Graceful Shutdown

When using IPC channels with event loops (like WebView, GUI frameworks), background threads may continue sending messages after the main event loop has closed, causing errors. The GracefulChannel feature solves this problem.

Python:

import ipckit

# Create channel with graceful shutdown support
channel = ipckit.GracefulIpcChannel.create("my_channel")
channel.wait_for_client()

# ... use channel normally ...
data = channel.recv()
channel.send(b"response")

# Graceful shutdown - prevents new operations and waits for pending ones
channel.shutdown()
channel.drain()  # Wait for all pending operations to complete

# Or use shutdown with timeout (in milliseconds)
channel.shutdown_timeout(5000)  # 5 second timeout

Rust:

use ipckit::{GracefulIpcChannel, GracefulChannel};
use std::time::Duration;

fn main() -> ipckit::Result<()> {
    let mut channel = GracefulIpcChannel::<Vec<u8>>::create("my_channel")?;
    channel.wait_for_client()?;
    
    // ... use channel ...
    
    // Graceful shutdown
    channel.shutdown();
    channel.drain()?;
    
    // Or with timeout
    channel.shutdown_timeout(Duration::from_secs(5))?;
    
    Ok(())
}

Key Benefits:

  • Prevents EventLoopClosed and similar errors
  • Thread-safe shutdown signaling
  • Tracks pending operations with RAII guards
  • Configurable drain timeout

Local Socket (Cross-Platform Socket Communication)

Local sockets provide a unified API for Unix Domain Sockets (Unix/macOS) and Named Pipes (Windows).

Python Server:

import ipckit

# Create server
server = ipckit.LocalSocketListener.bind("my_socket")
print("Waiting for client...")

# Accept connection
stream = server.accept()

# Receive and send data
data = stream.read(1024)
print(f"Received: {data}")
stream.write(b"Hello from server!")

# JSON communication
json_data = stream.recv_json()
stream.send_json({"status": "ok", "message": "received"})

Python Client:

import ipckit

# Connect to server
stream = ipckit.LocalSocketStream.connect("my_socket")

# Send and receive data
stream.write(b"Hello from client!")
response = stream.read(1024)
print(f"Response: {response}")

# JSON communication
stream.send_json({"action": "getData", "key": "user"})
result = stream.recv_json()
print(result)

Key Benefits:

  • Cross-platform: Works on Windows, Linux, and macOS
  • Bidirectional communication
  • Built-in JSON serialization with length prefix
  • Simple client-server model

Thread Channel (Intra-Process Communication)

High-performance channel for communication between threads within the same process.

Rust:

use ipckit::ThreadChannel;
use std::thread;

fn main() {
    // Create an unbounded channel
    let (tx, rx) = ThreadChannel::<String>::unbounded();

    // Spawn producer thread
    let tx_clone = tx.clone();
    thread::spawn(move || {
        tx_clone.send("Hello from thread!".to_string()).unwrap();
    });

    // Receive in main thread
    let msg = rx.recv().unwrap();
    println!("Received: {}", msg);
}

Event Stream (Publish-Subscribe)

Real-time event system for task progress, logs, and notifications.

Rust:

use ipckit::{EventBus, Event, EventFilter};

fn main() {
    let bus = EventBus::new(Default::default());
    let publisher = bus.publisher();

    // Subscribe to task events
    let subscriber = bus.subscribe(
        EventFilter::new().event_type("task.*")
    );

    // Publish events
    publisher.progress("task-123", 50, 100, "Half done");
    publisher.log("task-123", "info", "Processing...");

    // Receive events
    while let Some(event) = subscriber.try_recv() {
        println!("[{}] {:?}", event.event_type, event.data);
    }
}

Task Manager (Task Lifecycle)

Manage long-running tasks with progress tracking and cancellation support.

Rust:

use ipckit::{TaskManager, TaskBuilder, TaskFilter};
use std::time::Duration;

fn main() {
    let manager = TaskManager::new(Default::default());

    // Spawn a task
    let handle = manager.spawn("Upload files", "upload", |task| {
        for i in 0..100 {
            if task.is_cancelled() {
                return;
            }
            task.set_progress(i + 1, Some(&format!("Step {}/100", i + 1)));
            std::thread::sleep(Duration::from_millis(50));
        }
        task.complete(serde_json::json!({"uploaded": 100}));
    });

    // List active tasks
    let active = manager.list(&TaskFilter::new().active());
    println!("Active tasks: {}", active.len());

    // Cancel if needed
    // manager.cancel(handle.id()).unwrap();
}

Socket Server (Multi-Client Server)

Docker-style socket server for handling multiple client connections.

Rust:

use ipckit::{SocketServer, SocketServerConfig, Message, FnHandler};

fn main() -> ipckit::Result<()> {
    let server = SocketServer::new(SocketServerConfig::with_path("my_server"))?;

    // Handle connections with a simple function
    let handler = FnHandler::new(|conn, msg| {
        if msg.method() == Some("ping") {
            Ok(Some(Message::response(serde_json::json!({"pong": true}))))
        } else {
            Ok(None)
        }
    });

    // Run server (blocking)
    server.run(handler)?;
    Ok(())
}

Client:

use ipckit::SocketClient;

fn main() -> ipckit::Result<()> {
    let mut client = SocketClient::connect("my_server")?;

    // Send request and get response
    let result = client.request("ping", serde_json::json!({}))?;
    println!("Response: {:?}", result);

    Ok(())
}

📖 IPC Methods Comparison

Method Use Case Performance Complexity
Anonymous Pipe Parent-child processes Fast Low
Named Pipe Unrelated processes Fast Medium
Shared Memory Large data, frequent access Fastest High
IPC Channel Message passing Fast Low
File Channel Frontend-backend Moderate Low
Graceful Channel Event loop integration Fast Low
Local Socket Cross-platform sockets Fast Low
Thread Channel Intra-process threads Fastest Low
Event Stream Publish-subscribe events Fast Low
Task Manager Task lifecycle Fast Medium
Socket Server Multi-client server Fast Medium

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│                     Python Application                       │
├─────────────────────────────────────────────────────────────┤
│                    ipckit Python Bindings                    │
│                         (PyO3)                               │
├─────────────────────────────────────────────────────────────┤
│                     ipckit Rust Core                         │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────────────────┐│
│  │  Pipes  │ │   SHM   │ │ Channel │ │    File Channel     ││
│  └─────────┘ └─────────┘ └─────────┘ └─────────────────────┘│
│  ┌─────────────────────────────────────────────────────────┐│
│  │              Graceful Shutdown Layer                    ││
│  │  (GracefulNamedPipe, GracefulIpcChannel, ShutdownState) ││
│  └─────────────────────────────────────────────────────────┘│
│  ┌─────────────────────────────────────────────────────────┐│
│  │                  Local Socket Layer                     ││
│  │     (LocalSocketListener, LocalSocketStream)            ││
│  └─────────────────────────────────────────────────────────┘│
│  ┌─────────────────────────────────────────────────────────┐│
│  │                  High-Level Services                    ││
│  │  (ThreadChannel, EventStream, TaskManager, SocketServer)││
│  └─────────────────────────────────────────────────────────┘│
├─────────────────────────────────────────────────────────────┤
│              Platform Abstraction Layer                      │
│         (Windows / Linux / macOS)                            │
└─────────────────────────────────────────────────────────────┘

🔧 Building from Source

Prerequisites

  • Rust 1.70+
  • Python 3.7+
  • maturin (pip install maturin)

Build

# Clone repository
git clone https://github.com/loonghao/ipckit.git
cd ipckit

# Build Python package
maturin develop --release

# Run tests
pytest tests/
cargo test

📝 License

This project is dual-licensed under:

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📚 Documentation

🙏 Acknowledgments

  • PyO3 - Rust bindings for Python
  • maturin - Build and publish Rust-based Python packages
  • serde - Serialization framework for Rust

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

ipckit-0.1.2-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (380.8 kB view details)

Uploaded PyPymanylinux: glibc 2.17+ ARM64

ipckit-0.1.2-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (382.6 kB view details)

Uploaded PyPymanylinux: glibc 2.17+ ARM64

ipckit-0.1.2-cp38-abi3-win_amd64.whl (327.2 kB view details)

Uploaded CPython 3.8+Windows x86-64

ipckit-0.1.2-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (404.6 kB view details)

Uploaded CPython 3.8+manylinux: glibc 2.17+ x86-64

ipckit-0.1.2-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (382.2 kB view details)

Uploaded CPython 3.8+manylinux: glibc 2.17+ ARM64

ipckit-0.1.2-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl (745.6 kB view details)

Uploaded CPython 3.8+macOS 10.12+ universal2 (ARM64, x86-64)macOS 10.12+ x86-64macOS 11.0+ ARM64

File details

Details for the file ipckit-0.1.2-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for ipckit-0.1.2-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 c979512b9f716259ec8b5d6791fd643061e33feace4eacaef9465d8646504792
MD5 af5454a6327c156a34c958a17c7133c3
BLAKE2b-256 dc715594d64fb601129e2ad1934836b9568b5e377bbcd0d0d9cc464d95e0c4b3

See more details on using hashes here.

Provenance

The following attestation bundles were made for ipckit-0.1.2-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: release.yml on loonghao/ipckit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ipckit-0.1.2-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for ipckit-0.1.2-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 fd57934e6f2079ef01422b003b635c1a13493479830075f0f519479dfc536220
MD5 00d5824d7ec44b2d0ea630e71c8fe773
BLAKE2b-256 7ddd1faefc25ca837860e3c29bf4e1c3dbea847a3ecc8a9ff232897d9edc8418

See more details on using hashes here.

Provenance

The following attestation bundles were made for ipckit-0.1.2-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: release.yml on loonghao/ipckit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ipckit-0.1.2-cp38-abi3-win_amd64.whl.

File metadata

  • Download URL: ipckit-0.1.2-cp38-abi3-win_amd64.whl
  • Upload date:
  • Size: 327.2 kB
  • Tags: CPython 3.8+, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ipckit-0.1.2-cp38-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 2f0c720708bae7bfd5a3d35a86cf844c914f11e305788760e78c4a154ab5183d
MD5 0970f5d27e62481fba31c5d26e64eea3
BLAKE2b-256 c56ddb7a134aa552dfe803c3efa05d37cb0b9e6373b9aaade6d884f83d8a12cd

See more details on using hashes here.

Provenance

The following attestation bundles were made for ipckit-0.1.2-cp38-abi3-win_amd64.whl:

Publisher: release.yml on loonghao/ipckit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ipckit-0.1.2-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for ipckit-0.1.2-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 d6a7895295c158a1a6514dbbe4546045e1868f768345aa18e08f3d710a44cd60
MD5 600ea84e02eeee393f27c7aeaf042bdf
BLAKE2b-256 a6049afda0499f3b5878fcf540c729cf67b2bb809ecc4896cf35bfef3db4d8bf

See more details on using hashes here.

Provenance

The following attestation bundles were made for ipckit-0.1.2-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: release.yml on loonghao/ipckit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ipckit-0.1.2-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for ipckit-0.1.2-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 2562288bcb7d8965338dd46a7ed563806e88480b70d2b47ccf39d92d02939e82
MD5 a14f698e2cca260e6ee1f998ffb1c1d0
BLAKE2b-256 db939d6db076d313945b4d1daa92fb9fbd66ab0df1b7e1374537168c3962d435

See more details on using hashes here.

Provenance

The following attestation bundles were made for ipckit-0.1.2-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: release.yml on loonghao/ipckit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ipckit-0.1.2-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl.

File metadata

File hashes

Hashes for ipckit-0.1.2-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl
Algorithm Hash digest
SHA256 9b81623b3380f5b0f15fbe1749ba7bbb63f2aef4da5f385898783355adb0812a
MD5 b2f10a1717c31f039f399d13f1e9d191
BLAKE2b-256 cf75f236aa61c95124cb90e2be9f7e2b8908893fde712f581dd30839eedffede

See more details on using hashes here.

Provenance

The following attestation bundles were made for ipckit-0.1.2-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl:

Publisher: release.yml on loonghao/ipckit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page