npm package: @signageos/lock-lmx
Description: This library provides a distributed locking mechanism using [live-mutex](https://github.com/ORESoftware/live-mutex) (LMX), a high-performance mutex implementation optimized for Node.js applications.
Author: signageOS
Latest version: 1.1.0

# Lock LMX Library

This library provides a distributed locking mechanism using [live-mutex](https://github.com/ORESoftware/live-mutex) (LMX), a high-performance mutex implementation optimized for Node.js applications.

## Overview

`@signageos/lock-lmx` is a TypeScript wrapper around the live-mutex library, providing a simple and type-safe API for distributed locking across multiple service instances. It ensures mutual exclusion for critical sections of code that need to be executed atomically across different processes or servers.

## Why Live Mutex?

Live-mutex is a purpose-built solution for distributed locking in Node.js environments that offers several advantages:

### Advantages over Redis-based locks

1. **Optimized for Node.js**: Live-mutex is specifically designed for Node.js event loop, providing better performance and lower overhead compared to Redis-based locking mechanisms.

2. **Simpler architecture**: No need for complex Redis Redlock algorithms or managing multiple Redis instances for high availability. Live-mutex uses a dedicated TCP broker that's lightweight and efficient.

3. **Better deadlock prevention**: Built-in safeguards and TTL (time-to-live) mechanisms that automatically release locks, preventing common deadlock scenarios.

4. **Lower latency**: Direct TCP communication with the broker results in faster lock acquisition and release compared to Redis protocol overhead.

5. **Resource efficiency**: Dedicated mutex broker uses fewer resources than a full Redis instance, especially when locking is the primary use case.

6. **Process crash handling**: Automatic lock release when the holding process crashes or disconnects, ensuring system resilience.

### Limitations

- **Maximum TTL**: Lock TTL is limited to approximately 13.3 minutes (800,000 ms) due to LMX implementation constraints.
- **Single point of failure**: The LMX broker is a single point of failure (though it's lightweight and can be easily monitored/restarted).
- **Specialized use case**: Best suited for short-lived locks in high-throughput scenarios rather than long-running distributed transactions.

## Installation

```bash
npm install @signageos/lock-lmx
```

## Usage

### Basic Example

```typescript
import { createSimpleLock } from '@signageos/lock-lmx';

// Create a lock instance
const acquireLock = createSimpleLock({
	lmxDsn: 'tcp://localhost:6379',
});

// Use the lock
async function criticalOperation() {
	const release = await acquireLock('my-resource-key');
	try {
		// Your critical section code here
		await doSomethingImportant();
	} finally {
		await release();
	}
}
```

### Configuration Options

```typescript
const acquireLock = createSimpleLock({
	// Required: Live Mutex DSN connection string
	lmxDsn: 'tcp://localhost:6379',
	
	// Optional: Time to wait for acquiring the lock (default: 1 minute)
	lockRequestTimeout: 60_000,
	
	// Optional: Time to wait for releasing the lock (default: 1 minute)
	unlockRequestTimeout: 60_000,
	
	// Optional: Time to live for the lock (default: 5 minutes, max: ~13.3 minutes)
	ttl: 300_000,
});
```

### Multiple Locks

```typescript
// You can acquire multiple locks with different keys
const release1 = await acquireLock('resource-1');
const release2 = await acquireLock('resource-2');

try {
	// Work with both resources
} finally {
	await release1();
	await release2();
}
```

## Use Cases

- **Database operations**: Ensure only one instance processes a specific record at a time
- **Job queue processing**: Prevent duplicate processing of the same job across multiple workers
- **Cache updates**: Coordinate cache invalidation across multiple application instances
- **Resource allocation**: Manage access to limited shared resources
- **Rate limiting**: Implement distributed rate limiting across services

## References

- [Live-mutex GitHub Repository](https://github.com/ORESoftware/live-mutex)
- [A Better Mutex for Node.js (Medium Article)](https://medium.com/@oresoftware/a-better-mutex-for-node-js-ca5ba16ce7b5)

## Development

### Running Tests

The project includes both unit and integration tests.

#### Unit Tests
Unit tests mock the LMX client and test the library logic in isolation:
```bash
docker compose exec app npm test -- --grep "unit."
```

#### Integration Tests
Integration tests run against a real LMX broker running in Docker:
```bash
# Start all services (including the LMX broker)
docker compose up -d

# Run integration tests
docker compose exec app npm test -- --grep "integration."
```

#### All Tests
To run all tests (unit + integration):
```bash
docker compose exec app npm test
```