Overview
This crate implements distributed locking using Cloud Spanner. It relies on Spanner's TrueTime and transactions support to achieve its locking mechanism. It's a port of the original spindle, which is written in Go.
Use cases
One use case for this library is leader election. If you want one host/node/pod to be the leader within a cluster/group, you can achieve that with this crate. When the leader fails, it will fail over to another host/node/pod within a specific timeout. That said, you might want to check out hedge-rs, which is a memberlist tracking library built on top of this crate.
Usage
At the moment, the table needs to be created beforehand using the following DDL (locktable is just an example):
(
name STRING(MAX) NOT NULL,
heartbeat TIMESTAMP OPTIONS (allow_commit_timestamp=true),
token TIMESTAMP OPTIONS (allow_commit_timestamp=true),
writer STRING(MAX),
) PRIMARY KEY (name)
After creating the lock object, you will call the run() function which will attempt to acquire a named lock at a regular interval (lease duration). A has_lock() function is provided which returns true (along with the lock token) if the lock is successfully acquired. Something like:
use *;
...
Example
A sample code is provided to demonstrate the mechanism through logs. You can try running multiple processes in multiple terminals.
# Update args with your actual values:
# args[1] = database string
# args[2] = table name
The leader process should output something like leader active (me). You can then try to stop (Ctrl+C) that process and observe another one taking over as leader.
License
This library is licensed under the Apache 2.0 License.