Documentation
¶
Overview ¶
Package dynamolock coordinates leases and atomic payload writes on DynamoDB items with string primary keys. It does not fence external effects.
Index ¶
- Variables
- func Create[T any](ctx context.Context, client *dynamodb.Client, table Table, key Key, data *T) error
- func MarshalItem(table Table, key Key, data any) (map[string]types.AttributeValue, error)
- func Read[T any](ctx context.Context, client *dynamodb.Client, table Table, key Key, ...) (*T, error)
- func UnmarshalItem[T any](table Table, item map[string]types.AttributeValue) (*T, error)
- type CAS
- type IndexItem
- type IndexPage
- type Item
- type Key
- type Lease
- func (l *Lease[T]) Commit(ctx context.Context, data *T) error
- func (l *Lease[T]) Context() context.Context
- func (l *Lease[T]) Delete(ctx context.Context) error
- func (l *Lease[T]) Key() Key
- func (l *Lease[T]) Release(ctx context.Context) error
- func (l *Lease[T]) Update(ctx context.Context, data *T) error
- type LockInput
- type Page
- type ProjectedItem
- type ProjectedPage
- type ReadOptions
- type Table
Constants ¶
This section is empty.
Variables ¶
var ErrConflict = errors.New("CAS snapshot conflicts with current record")
ErrConflict means Create found an existing item or a CAS snapshot no longer authorizes writes. Read the current record before deciding whether to retry; CAS callers must obtain a new snapshot before recomputing application work.
var ErrInvalidPayload = errors.New("invalid lock payload")
ErrInvalidPayload reports a nil, non-map, or conflicting-ID payload.
var ErrInvalidRecord = errors.New("invalid lock record")
ErrInvalidRecord reports an item that does not use this package's record format.
var ErrLeaseLost = errors.New("lease lost")
ErrLeaseLost means the handle can no longer authorize payload writes.
var ErrLockHeld = fmt.Errorf("%w: lock is held", ErrLockUnavailable)
ErrLockHeld means the configured contention retries were exhausted.
var ErrLockNotFound = fmt.Errorf("%w: required item is missing", ErrLockUnavailable)
ErrLockNotFound means RequireExisting prevented creation of a missing item.
ErrLockUnavailable classifies expected acquisition failures.
var ErrOutcomeUnknown = errors.New("write outcome unknown")
ErrOutcomeUnknown means a write may have committed. It does not mean rollback. An ambiguous payload write permanently invalidates the handle for further writes. Release-only cleanup is still allowed with a fresh context.
var ErrReleased = errors.New("lease released")
ErrReleased means this handle has already been released or committed.
var ErrVersionExhausted = errors.New("record version exhausted")
ErrVersionExhausted means the generation's counter cannot be incremented. Counters never wrap. Hard deletion is still allowed with the current authority.
Functions ¶
func Create ¶
func Create[T any](ctx context.Context, client *dynamodb.Client, table Table, key Key, data *T) error
Create writes data only if the item is physically absent, without reading or acquiring a lease. Existing items cause ErrConflict, including those without payload or with expired ownership. Encoding, projections and revisions use the same path as CAS.Update. ErrOutcomeUnknown means creation may have succeeded; reconcile the stored record before retrying.
func MarshalItem ¶
MarshalItem encodes an unlocked envelope without writing to DynamoDB. Nil data, non-map encodings and conflicting keys are rejected. Primary keys are stored only outside data. Does not overwrite or acquire an existing item.
func Read ¶
func Read[T any](ctx context.Context, client *dynamodb.Client, table Table, key Key, options ReadOptions) (*T, error)
Read reads a payload without taking a lease. Reads are eventually consistent unless ConsistentRead is true; eventual reads can return stale data or absence. It can observe Update before Commit or Release. Nil means no payload was returned, not necessarily that the item is absent.
func UnmarshalItem ¶
UnmarshalItem decodes a full envelope into a struct or string-keyed map T. The input map is unchanged. Outer primary keys are injected before decoding; map values must accept strings. An absent item or absent data returns nil; empty data returns a non-nil value. Interface numbers use attributevalue.Number to preserve precision; typed numeric fields keep their declared Go types.
Types ¶
type CAS ¶
type CAS[T any] struct { // contains filtered or unexported fields }
CAS is a reusable optimistic writer, not a held lock. Do not copy it. Operations serialize; caller-owned values must not be mutated during a write. Successful updates advance its snapshot without another read. Conflicts and ambiguous writes permanently invalidate it; successful Delete consumes it. There is no heartbeat, Release, or background work. Each call owns its context.
func ReadCAS ¶
func ReadCAS[T any](ctx context.Context, client *dynamodb.Client, table Table, key Key, options ReadOptions) (*CAS[T], *T, error)
ReadCAS reads a complete snapshot and returns its optimistic writer and value. Reads default to eventual consistency. An observed live lease returns the inspectable value and ErrLockHeld, but no writer. Every write independently checks ownership and revision; stale reads can cause conflicts, not lost updates. An absent item returns a creation-capable writer and nil data. Existing records without revision metadata are initialized with one conditional write, using its returned payload rather than attaching a revision to the potentially stale read. All old writers must be stopped before enabling this shared versioned protocol.
func (*CAS[T]) Delete ¶
Delete physically removes the observed generation under the same CAS fence. For an absent snapshot it succeeds only if the item is still absent. Success consumes the handle; ambiguity invalidates it without retrying the deletion.
type IndexItem ¶
IndexItem is a read-only index observation, not a complete document. Value is decoded from primary keys and configured Table.Attributes present on the entry, even when only keys were returned. Missing copies do not prove that fields are absent from the document. No payload envelope or lease metadata is interpreted.
type IndexPage ¶
type IndexPage[T any] struct { Items []IndexItem[T] LastEvaluatedKey map[string]types.AttributeValue Count int32 ScannedCount int32 }
IndexPage preserves counts and the complete service cursor for one index page. An empty page may still have a cursor. Count-only pages have no Items.
func QueryIndex ¶
func QueryIndex[T any](ctx context.Context, client *dynamodb.Client, table Table, input *dynamodb.QueryInput) (IndexPage[T], error)
QueryIndex returns one page of typed index observations, decoding only primary keys and configured Table.Attributes copies. It ignores data, lease metadata and unconfigured attributes, even if the index projects them. It never reads the parent document or acquires a lease; lock and recheck before modifying it. IndexName is required. Caller projections are rejected; Select may be empty, AllProjectedAttributes or Count. Filter, ordering, limit and cursor options are preserved. ConsistentRead defaults to eventual; strong reads work only on LSIs. Input is copied, never mutated; do not mutate it during a call. Pass the full LastEvaluatedKey as ExclusiveStartKey until empty, even after an empty page. Neither strong reads nor pagination provide a collection snapshot.
type Item ¶
Item is one discovered primary key and its document. Value is nil when no data exists, including a keys-only index projection. Use Read with ConsistentRead for current state; discovery neither acquires ownership nor proves absence.
type Lease ¶
type Lease[T any] struct { // contains filtered or unexported fields }
Lease owns one acquisition. Do not copy it. Payload operations are serialized; renewal is independent, so slow marshaling or writes do not block heartbeats. Callers own their payload values and must not mutate them during a write. A lost lease never becomes usable again, even if a late renewal succeeds.
func Lock ¶
func Lock[T any](ctx context.Context, client *dynamodb.Client, input *LockInput) (lease *Lease[T], data *T, err error)
Lock atomically acquires ownership and returns the payload. The context owns the entire lease lifetime; cancellation stops renewal but does not release the item. Missing data returns nil even when RequireExisting succeeds.
T must be a struct or string-keyed map. The client's transport must honor request contexts. Custom codecs run synchronously and must return promptly; this package cannot cancel them.
func (*Lease[T]) Commit ¶
Commit atomically patches caller-visible changes and releases ownership. Nil is rejected. A repeated Commit fails with ErrReleased; it is not a new write.
func (*Lease[T]) Context ¶
Context is canceled on parent cancellation, loss, or successful completion. Protected work must stop on cancellation; context.Cause supplies the reason. Cancellation cannot undo external effects or in-flight DynamoDB requests.
func (*Lease[T]) Delete ¶
Delete removes the item under the same live-token fence as Update and Commit. An ambiguous response invalidates the handle; reconcile before another action.
func (*Lease[T]) Release ¶
Release clears only this handle's ownership, preserving the raw payload. It works after loss or parent cancellation with a fresh context. Release is idempotent: an absent/different token or a completed handle is already released. Successful completion joins the heartbeat goroutine.
func (*Lease[T]) Update ¶
Update patches caller-visible changes without extending or releasing the lease. Unknown map fields survive. Removing a previously visible field removes its subtree; a changed opaque list must not discard fields hidden by typed decoding. Nil is rejected. The last confirmed encoding is the comparison baseline.
type LockInput ¶
type LockInput struct {
Table Table
Key Key
RequireExisting bool // Check item existence, not payload presence.
// LeaseDuration is the lifetime established by acquisition and each renewal.
// Renewal is due every quarter-duration, measured from the last confirmed
// request's start. Must be at least 4ns so that interval is positive.
LeaseDuration time.Duration
Retries int // Additional attempts after ordinary contention.
RetriesSleep time.Duration // Zero uses one second.
}
LockInput configures acquisition and renewal. Lock copies it before use; callers may reuse it after Lock returns, but must not mutate it during Lock.
type Page ¶
type Page[T any] struct { Items []Item[T] LastEvaluatedKey map[string]types.AttributeValue Count int32 ScannedCount int32 }
Page preserves the full service cursor, including index keys. A page can be empty and still have a cursor. Count and ScannedCount also support SelectCount.
func Query ¶
func Query[T any](ctx context.Context, client *dynamodb.Client, table Table, input *dynamodb.QueryInput) (Page[T], error)
Query returns one typed page with ordinary SDK query/index/filter options. ConsistentRead defaults to false (eventual); true requests strong reads on tables or local secondary indexes. Global secondary indexes are eventual only. Input is copied, never mutated. No hidden rereads, leases or full collection. Pass LastEvaluatedKey as ExclusiveStartKey until the cursor is empty, even after an empty page. Strong reads do not provide a collection snapshot. Do not request partial projections; indexes without data return nil Values.
type ProjectedItem ¶
ProjectedItem is an incomplete, read-only observation, not a full document. A present item with nil Value returned none of the selected payload; it does not prove the full payload is absent or valid. HasLeaseMetadata reports a valid ownership pair, even if expired, and grants no ownership or mutation authority.
func ReadProjected ¶
func ReadProjected[T any](ctx context.Context, client *dynamodb.Client, table Table, key Key, fields [][]string, options ReadOptions) (*ProjectedItem[T], error)
ReadProjected reads one key with only the requested payload paths. Reads are eventually consistent unless ConsistentRead is true; eventual reads can return stale data, lease metadata or absence. Paths are exact attribute-name segments relative to data, not expressions or list indexes. No fields selects keys/metadata only. A nil result means no item was observed; a nil Value on a present result means no selected payload was returned. No hidden full read or lease is provided.
type ProjectedPage ¶
type ProjectedPage[T any] struct { Items []ProjectedItem[T] LastEvaluatedKey map[string]types.AttributeValue Count int32 ScannedCount int32 }
ProjectedPage preserves the full service cursor and counts for one scan page. An empty page may still have a cursor. Items contain only selected payloads.
func ScanProjected ¶
func ScanProjected[T any](ctx context.Context, client *dynamodb.Client, table Table, input *dynamodb.ScanInput, fields [][]string) (ProjectedPage[T], error)
ScanProjected returns one incomplete base-table page, selecting only explicit payload paths plus primary keys and both ownership fields. It preserves filter, consistency, limit, segment and cursor options; caller inputs are not mutated. ConsistentRead defaults to false (eventual); true requests strong reads, not a collection snapshot. Pass LastEvaluatedKey as ExclusiveStartKey until the cursor is empty, including after pages with no items. Index scans and caller projection/Select options are rejected so omitted index metadata cannot masquerade as an unleased item. No hidden reads or leases.
type ReadOptions ¶
type ReadOptions struct {
// ConsistentRead requests strong consistency. Otherwise recent creates,
// updates and deletes may not yet be visible.
ConsistentRead bool
}
ReadOptions controls non-locking single-item reads. The zero value requests eventual consistency, at half the read-unit cost of strong consistency. These options never affect acquisition or its strongly consistent reconciliation.
type Table ¶
Table describes string primary keys and optional top-level projections of data fields for indexes or application TTL. PartitionKey defaults to id. Attributes are exact stored field names, not paths; lease metadata must never be TTL. Name is required for requests, but may be omitted for pure envelope codecs.