dynamolock

package module
v0.0.0-...-4b3f3b7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2024 License: MIT Imports: 10 Imported by: 1

README

Go Reference

go-dynamolock

why

locking around dynamodb should be simple and easy.

what

a minimal go library for locking around dynamodb.

compared to alternatives it has less code and fewer features.

how

a record in dynamodb uses a uuid and a timetamp to coordinate callers.

to lock, a caller finds the uuid missing and adds it.

while locked, the caller heartbeats the timestamp.

to unlock, the caller removes the uuid.

arbitrary data can be stored atomically in the lock record. it is read via lock, written via unlock, and can be written without unlocking via update.

manipulation of external state while the lock is held is subject to concurrent updates depending on maxAge, heartbeatInterval, and caller clock drift.

in practice, a small heartbeatInterval, a large maxAge, and reasonable clock drift should be safe.

prefer to store data within the lock when possible, since those updates compare and swap with the uuid.

install

go get github.com/nathants/go-dynamolock

usage

package main

import (
	"context"
	"time"
	"github.com/nathants/go-dynamolock"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)


type Data struct {
    Value string
}

func main() {
	ctx := context.Background()

	// dynamodb table
	table := "table"

	// dynamodb key
	id := "lock1"

	// after a failure to unlock/heartbeat, this much time must pass before lock is available
	maxAge := time.Second * 30

	// how often to heartbeat lock timestamp
	heartbeat := time.Second * 1

	// lock and read data
	unlock, _, data, err := dynamolock.Lock[Data](ctx, table, id, maxAge, heartbeat)
	if err != nil {
		// TODO handle lock contention
		panic(err)
	}

	// do work with the lock
	time.Sleep(time.Second * 1)
	data.Value = "updated"

	// unlock and write data
	err = unlock(data)
	if err != nil {
		panic(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Lock

func Lock[T any](ctx context.Context, table, id string, maxAge, heartbeatInterval time.Duration) (UnlockFn[T], UpdateFn[T], T, error)

func Read

func Read[T any](ctx context.Context, table, id string) (*T, error)

Types

type LockData

type LockData struct {
	Unix int64  `json:"unix"` // timestamp of lock holder
	Uid  string `json:"uid"`  // uuid of lock holder
}

type LockKey

type LockKey struct {
	ID string `json:"id"` // unique id per lock
}

type LockRecord

type LockRecord struct {
	LockKey
	LockData
}

type UnlockFn

type UnlockFn[T any] func(T) error

type UpdateFn

type UpdateFn[T any] func(T) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL