socketlock


Namesocketlock JSON
Version 0.1.0 PyPI version JSON
download
home_pageNone
SummaryA robust, secure, and async-friendly process lock using TCP sockets with handshake protocol
upload_time2025-10-22 04:15:01
maintainerNone
docs_urlNone
authorJoe Huck
requires_python>=3.8
licenseMIT
keywords lock process socket async asyncio mutex synchronization handshake
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # socketlock

A robust, secure, and async-friendly process lock using TCP sockets with handshake protocol verification.

[![CI](https://github.com/comput3/socketlock/actions/workflows/ci.yml/badge.svg)](https://github.com/comput3/socketlock/actions/workflows/ci.yml)
[![PyPI version](https://badge.fury.io/py/socketlock.svg)](https://badge.fury.io/py/socketlock)
[![Python Support](https://img.shields.io/pypi/pyversions/socketlock.svg)](https://pypi.org/project/socketlock/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- **🔒 Atomic Lock Acquisition**: Prevents race conditions with atomic file operations
- **🛡️ Security Handshake**: Application-level protocol prevents imposter processes
- **⚡ Async-First**: Built on asyncio with synchronous wrapper available
- **🔄 Self-Healing**: Automatic detection and cleanup of stale locks
- **📊 Rich Diagnostics**: Lock info includes PID and port for easy troubleshooting
- **🚀 High Performance**: Sub-millisecond lock operations
- **💥 Crash-Safe**: OS automatically releases sockets on process termination
- **🌍 Cross-Platform**: Works on Linux, macOS, and Windows

## Why socketlock?

Traditional process locks suffer from various problems:
- **PID files**: Process IDs can be recycled, causing false positives
- **File locks**: Often platform-specific, may not release on crash
- **Semaphores**: Require cleanup, complex API, platform differences

`socketlock` solves these issues by using TCP sockets with a verification handshake, ensuring that only legitimate processes can hold locks and that locks are always released on process termination.

## Installation

```bash
pip install socketlock
```

## Quick Start

### Async Interface

```python
import asyncio
from socketlock import AsyncSocketLock

async def critical_section():
    async with AsyncSocketLock(name="myapp") as lock:
        print(f"Lock acquired (PID: {lock.pid}, Port: {lock.port})")
        # Your protected code here
        await asyncio.sleep(1)
    # Lock automatically released

asyncio.run(critical_section())
```

### Sync Interface

```python
from socketlock import SocketLock

with SocketLock(name="myapp") as lock:
    print(f"Lock acquired (PID: {lock.pid}, Port: {lock.port})")
    # Your protected code here
# Lock automatically released
```

### Manual Lock Management

```python
import asyncio
from socketlock import AsyncSocketLock

async def manual_lock():
    lock = AsyncSocketLock(name="myapp")
    try:
        await lock.acquire()
        print("Lock acquired!")
        # Your protected code here
    except RuntimeError as e:
        print(f"Could not acquire lock: {e}")
        # Error includes PID and port of lock holder
    finally:
        await lock.release()

asyncio.run(manual_lock())
```

## Advanced Usage

### Custom Configuration

```python
from socketlock import AsyncSocketLock

lock = AsyncSocketLock(
    name="myapp",
    timeout=7200,  # Stale lock timeout (seconds)
    lock_dir="/var/run/myapp",  # Custom lock directory
    signature_seed="custom_seed",  # Custom handshake seed
)
```

### Checking Lock Status

```python
import asyncio
from socketlock import AsyncSocketLock

async def check_status():
    lock = AsyncSocketLock(name="myapp")
    info = await lock.get_lock_info()

    if info:
        print(f"Lock is held by PID {info['pid']} on port {info['port']}")
        print(f"Lock acquired at: {info['timestamp']}")
    else:
        print("Lock is available")

asyncio.run(check_status())
```

### Non-Blocking Acquisition

```python
import asyncio
from socketlock import AsyncSocketLock

async def try_lock():
    lock = AsyncSocketLock(name="myapp")

    if await lock.try_acquire():
        print("Got the lock!")
        # Do work...
        await lock.release()
    else:
        print("Lock is busy, will try again later")

asyncio.run(try_lock())
```

## How It Works

1. **Lock Acquisition**: Process attempts to bind to a TCP socket on localhost
2. **Port Discovery**: Dynamic port allocation (OS-assigned) is written to a lock file
3. **Verification**: Other processes can verify lock validity through handshake protocol
4. **Automatic Release**: OS releases socket when process terminates (any reason)

The handshake protocol prevents denial-of-service attacks where a rogue process could bind to a port and pretend to hold the lock.

## Performance

Typical operation times (Intel i7, Python 3.11):

- **Uncontested acquisition**: ~0.5ms
- **Contested detection**: ~0.7ms (including handshake verification)
- **Lock release**: ~0.06ms
- **Full context manager cycle**: ~0.6ms

## Contributing

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

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "socketlock",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "lock, process, socket, async, asyncio, mutex, synchronization, handshake",
    "author": "Joe Huck",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/b6/7b/7ec05272214811be8213b85bfd19ce39f3165e38a80c62f2b6c0488fd976/socketlock-0.1.0.tar.gz",
    "platform": null,
    "description": "# socketlock\n\nA robust, secure, and async-friendly process lock using TCP sockets with handshake protocol verification.\n\n[![CI](https://github.com/comput3/socketlock/actions/workflows/ci.yml/badge.svg)](https://github.com/comput3/socketlock/actions/workflows/ci.yml)\n[![PyPI version](https://badge.fury.io/py/socketlock.svg)](https://badge.fury.io/py/socketlock)\n[![Python Support](https://img.shields.io/pypi/pyversions/socketlock.svg)](https://pypi.org/project/socketlock/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n## Features\n\n- **\ud83d\udd12 Atomic Lock Acquisition**: Prevents race conditions with atomic file operations\n- **\ud83d\udee1\ufe0f Security Handshake**: Application-level protocol prevents imposter processes\n- **\u26a1 Async-First**: Built on asyncio with synchronous wrapper available\n- **\ud83d\udd04 Self-Healing**: Automatic detection and cleanup of stale locks\n- **\ud83d\udcca Rich Diagnostics**: Lock info includes PID and port for easy troubleshooting\n- **\ud83d\ude80 High Performance**: Sub-millisecond lock operations\n- **\ud83d\udca5 Crash-Safe**: OS automatically releases sockets on process termination\n- **\ud83c\udf0d Cross-Platform**: Works on Linux, macOS, and Windows\n\n## Why socketlock?\n\nTraditional process locks suffer from various problems:\n- **PID files**: Process IDs can be recycled, causing false positives\n- **File locks**: Often platform-specific, may not release on crash\n- **Semaphores**: Require cleanup, complex API, platform differences\n\n`socketlock` solves these issues by using TCP sockets with a verification handshake, ensuring that only legitimate processes can hold locks and that locks are always released on process termination.\n\n## Installation\n\n```bash\npip install socketlock\n```\n\n## Quick Start\n\n### Async Interface\n\n```python\nimport asyncio\nfrom socketlock import AsyncSocketLock\n\nasync def critical_section():\n    async with AsyncSocketLock(name=\"myapp\") as lock:\n        print(f\"Lock acquired (PID: {lock.pid}, Port: {lock.port})\")\n        # Your protected code here\n        await asyncio.sleep(1)\n    # Lock automatically released\n\nasyncio.run(critical_section())\n```\n\n### Sync Interface\n\n```python\nfrom socketlock import SocketLock\n\nwith SocketLock(name=\"myapp\") as lock:\n    print(f\"Lock acquired (PID: {lock.pid}, Port: {lock.port})\")\n    # Your protected code here\n# Lock automatically released\n```\n\n### Manual Lock Management\n\n```python\nimport asyncio\nfrom socketlock import AsyncSocketLock\n\nasync def manual_lock():\n    lock = AsyncSocketLock(name=\"myapp\")\n    try:\n        await lock.acquire()\n        print(\"Lock acquired!\")\n        # Your protected code here\n    except RuntimeError as e:\n        print(f\"Could not acquire lock: {e}\")\n        # Error includes PID and port of lock holder\n    finally:\n        await lock.release()\n\nasyncio.run(manual_lock())\n```\n\n## Advanced Usage\n\n### Custom Configuration\n\n```python\nfrom socketlock import AsyncSocketLock\n\nlock = AsyncSocketLock(\n    name=\"myapp\",\n    timeout=7200,  # Stale lock timeout (seconds)\n    lock_dir=\"/var/run/myapp\",  # Custom lock directory\n    signature_seed=\"custom_seed\",  # Custom handshake seed\n)\n```\n\n### Checking Lock Status\n\n```python\nimport asyncio\nfrom socketlock import AsyncSocketLock\n\nasync def check_status():\n    lock = AsyncSocketLock(name=\"myapp\")\n    info = await lock.get_lock_info()\n\n    if info:\n        print(f\"Lock is held by PID {info['pid']} on port {info['port']}\")\n        print(f\"Lock acquired at: {info['timestamp']}\")\n    else:\n        print(\"Lock is available\")\n\nasyncio.run(check_status())\n```\n\n### Non-Blocking Acquisition\n\n```python\nimport asyncio\nfrom socketlock import AsyncSocketLock\n\nasync def try_lock():\n    lock = AsyncSocketLock(name=\"myapp\")\n\n    if await lock.try_acquire():\n        print(\"Got the lock!\")\n        # Do work...\n        await lock.release()\n    else:\n        print(\"Lock is busy, will try again later\")\n\nasyncio.run(try_lock())\n```\n\n## How It Works\n\n1. **Lock Acquisition**: Process attempts to bind to a TCP socket on localhost\n2. **Port Discovery**: Dynamic port allocation (OS-assigned) is written to a lock file\n3. **Verification**: Other processes can verify lock validity through handshake protocol\n4. **Automatic Release**: OS releases socket when process terminates (any reason)\n\nThe handshake protocol prevents denial-of-service attacks where a rogue process could bind to a port and pretend to hold the lock.\n\n## Performance\n\nTypical operation times (Intel i7, Python 3.11):\n\n- **Uncontested acquisition**: ~0.5ms\n- **Contested detection**: ~0.7ms (including handshake verification)\n- **Lock release**: ~0.06ms\n- **Full context manager cycle**: ~0.6ms\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A robust, secure, and async-friendly process lock using TCP sockets with handshake protocol",
    "version": "0.1.0",
    "project_urls": {
        "Documentation": "https://github.com/comput3/socketlock#readme",
        "Homepage": "https://github.com/comput3/socketlock",
        "Issues": "https://github.com/comput3/socketlock/issues",
        "Repository": "https://github.com/comput3/socketlock.git"
    },
    "split_keywords": [
        "lock",
        " process",
        " socket",
        " async",
        " asyncio",
        " mutex",
        " synchronization",
        " handshake"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "08f18e0ccc74f96447629024f64b5c1ce90abf167886a95f7f8ee27ebe66bbfe",
                "md5": "a59e261b98b7dc16a0839dd1cfb0d736",
                "sha256": "f4be8fac2d474577fdd7895cc984f3fd9bcc0ef6bef1a188ced86c85ec2f95da"
            },
            "downloads": -1,
            "filename": "socketlock-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "a59e261b98b7dc16a0839dd1cfb0d736",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 9829,
            "upload_time": "2025-10-22T04:15:00",
            "upload_time_iso_8601": "2025-10-22T04:15:00.572293Z",
            "url": "https://files.pythonhosted.org/packages/08/f1/8e0ccc74f96447629024f64b5c1ce90abf167886a95f7f8ee27ebe66bbfe/socketlock-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "b67b7ec05272214811be8213b85bfd19ce39f3165e38a80c62f2b6c0488fd976",
                "md5": "d662be42d894b33e47f7d2b23e2137a9",
                "sha256": "fdce0357ad3d77429fdec370fd79f4b5143a51a2bd73ab4284fc367109d6dc04"
            },
            "downloads": -1,
            "filename": "socketlock-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "d662be42d894b33e47f7d2b23e2137a9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 14760,
            "upload_time": "2025-10-22T04:15:01",
            "upload_time_iso_8601": "2025-10-22T04:15:01.781795Z",
            "url": "https://files.pythonhosted.org/packages/b6/7b/7ec05272214811be8213b85bfd19ce39f3165e38a80c62f2b6c0488fd976/socketlock-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-22 04:15:01",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "comput3",
    "github_project": "socketlock#readme",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "socketlock"
}
        
Elapsed time: 1.11287s