feat(distlock): refactor into a standalone package

This commit is contained in:
Pasha Sviderski
2026-08-27 15:49:59 +10:00
parent 7a7a313426
commit 613cd6e418
10 changed files with 148 additions and 142 deletions
+7
View File
@@ -0,0 +1,7 @@
// Package distlock provides distributed, automatically renewed leases across independent nodes.
//
// A Cluster must return every node in the lock group, including temporarily unavailable nodes, because every node
// counts toward quorum. Changing the node set is unsafe if a new quorum can be disjoint from an earlier quorum while
// leases acquired from the earlier node set may still be valid. Callers must stop protected work when the context
// returned by Lease.Context is done.
package distlock
+547
View File
@@ -0,0 +1,547 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.34.2
// protoc v5.27.3
// source: pkg/distlock/grpc/lease.proto
package grpc
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
durationpb "google.golang.org/protobuf/types/known/durationpb"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type AcquireLeaseRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
// Token uniquely identifies the lease owner.
Token []byte `protobuf:"bytes,2,opt,name=token,proto3" json:"token,omitempty"`
// TTL sets how long the lease remains valid without renewal.
Ttl *durationpb.Duration `protobuf:"bytes,3,opt,name=ttl,proto3" json:"ttl,omitempty"`
}
func (x *AcquireLeaseRequest) Reset() {
*x = AcquireLeaseRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AcquireLeaseRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AcquireLeaseRequest) ProtoMessage() {}
func (x *AcquireLeaseRequest) ProtoReflect() protoreflect.Message {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AcquireLeaseRequest.ProtoReflect.Descriptor instead.
func (*AcquireLeaseRequest) Descriptor() ([]byte, []int) {
return file_pkg_distlock_grpc_lease_proto_rawDescGZIP(), []int{0}
}
func (x *AcquireLeaseRequest) GetResource() string {
if x != nil {
return x.Resource
}
return ""
}
func (x *AcquireLeaseRequest) GetToken() []byte {
if x != nil {
return x.Token
}
return nil
}
func (x *AcquireLeaseRequest) GetTtl() *durationpb.Duration {
if x != nil {
return x.Ttl
}
return nil
}
type AcquireLeaseResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Acquired is true when this request successfully created the lease.
Acquired bool `protobuf:"varint,1,opt,name=acquired,proto3" json:"acquired,omitempty"`
}
func (x *AcquireLeaseResponse) Reset() {
*x = AcquireLeaseResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AcquireLeaseResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AcquireLeaseResponse) ProtoMessage() {}
func (x *AcquireLeaseResponse) ProtoReflect() protoreflect.Message {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AcquireLeaseResponse.ProtoReflect.Descriptor instead.
func (*AcquireLeaseResponse) Descriptor() ([]byte, []int) {
return file_pkg_distlock_grpc_lease_proto_rawDescGZIP(), []int{1}
}
func (x *AcquireLeaseResponse) GetAcquired() bool {
if x != nil {
return x.Acquired
}
return false
}
type RenewLeaseRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
// Token identifies the owner of the existing lease.
Token []byte `protobuf:"bytes,2,opt,name=token,proto3" json:"token,omitempty"`
// TTL sets how long the renewed lease remains valid.
Ttl *durationpb.Duration `protobuf:"bytes,3,opt,name=ttl,proto3" json:"ttl,omitempty"`
}
func (x *RenewLeaseRequest) Reset() {
*x = RenewLeaseRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RenewLeaseRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RenewLeaseRequest) ProtoMessage() {}
func (x *RenewLeaseRequest) ProtoReflect() protoreflect.Message {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RenewLeaseRequest.ProtoReflect.Descriptor instead.
func (*RenewLeaseRequest) Descriptor() ([]byte, []int) {
return file_pkg_distlock_grpc_lease_proto_rawDescGZIP(), []int{2}
}
func (x *RenewLeaseRequest) GetResource() string {
if x != nil {
return x.Resource
}
return ""
}
func (x *RenewLeaseRequest) GetToken() []byte {
if x != nil {
return x.Token
}
return nil
}
func (x *RenewLeaseRequest) GetTtl() *durationpb.Duration {
if x != nil {
return x.Ttl
}
return nil
}
type RenewLeaseResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Renewed is true when an unexpired lease matched the ownership token and was successfully renewed.
Renewed bool `protobuf:"varint,1,opt,name=renewed,proto3" json:"renewed,omitempty"`
}
func (x *RenewLeaseResponse) Reset() {
*x = RenewLeaseResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RenewLeaseResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RenewLeaseResponse) ProtoMessage() {}
func (x *RenewLeaseResponse) ProtoReflect() protoreflect.Message {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RenewLeaseResponse.ProtoReflect.Descriptor instead.
func (*RenewLeaseResponse) Descriptor() ([]byte, []int) {
return file_pkg_distlock_grpc_lease_proto_rawDescGZIP(), []int{3}
}
func (x *RenewLeaseResponse) GetRenewed() bool {
if x != nil {
return x.Renewed
}
return false
}
type ReleaseLeaseRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
// Token identifies the owner of the existing lease.
Token []byte `protobuf:"bytes,2,opt,name=token,proto3" json:"token,omitempty"`
}
func (x *ReleaseLeaseRequest) Reset() {
*x = ReleaseLeaseRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ReleaseLeaseRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ReleaseLeaseRequest) ProtoMessage() {}
func (x *ReleaseLeaseRequest) ProtoReflect() protoreflect.Message {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[4]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ReleaseLeaseRequest.ProtoReflect.Descriptor instead.
func (*ReleaseLeaseRequest) Descriptor() ([]byte, []int) {
return file_pkg_distlock_grpc_lease_proto_rawDescGZIP(), []int{4}
}
func (x *ReleaseLeaseRequest) GetResource() string {
if x != nil {
return x.Resource
}
return ""
}
func (x *ReleaseLeaseRequest) GetToken() []byte {
if x != nil {
return x.Token
}
return nil
}
type ReleaseLeaseResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Released is true when an unexpired lease existed, matched the ownership token, and was successfully released.
Released bool `protobuf:"varint,1,opt,name=released,proto3" json:"released,omitempty"`
}
func (x *ReleaseLeaseResponse) Reset() {
*x = ReleaseLeaseResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ReleaseLeaseResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ReleaseLeaseResponse) ProtoMessage() {}
func (x *ReleaseLeaseResponse) ProtoReflect() protoreflect.Message {
mi := &file_pkg_distlock_grpc_lease_proto_msgTypes[5]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ReleaseLeaseResponse.ProtoReflect.Descriptor instead.
func (*ReleaseLeaseResponse) Descriptor() ([]byte, []int) {
return file_pkg_distlock_grpc_lease_proto_rawDescGZIP(), []int{5}
}
func (x *ReleaseLeaseResponse) GetReleased() bool {
if x != nil {
return x.Released
}
return false
}
var File_pkg_distlock_grpc_lease_proto protoreflect.FileDescriptor
var file_pkg_distlock_grpc_lease_proto_rawDesc = []byte{
0x0a, 0x1d, 0x70, 0x6b, 0x67, 0x2f, 0x64, 0x69, 0x73, 0x74, 0x6c, 0x6f, 0x63, 0x6b, 0x2f, 0x67,
0x72, 0x70, 0x63, 0x2f, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12,
0x0b, 0x64, 0x69, 0x73, 0x74, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x76, 0x31, 0x1a, 0x1e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75,
0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x74, 0x0a, 0x13,
0x41, 0x63, 0x71, 0x75, 0x69, 0x72, 0x65, 0x4c, 0x65, 0x61, 0x73, 0x65, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18,
0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12,
0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05,
0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x2b, 0x0a, 0x03, 0x74, 0x74, 0x6c, 0x18, 0x03, 0x20, 0x01,
0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x03, 0x74,
0x74, 0x6c, 0x22, 0x32, 0x0a, 0x14, 0x41, 0x63, 0x71, 0x75, 0x69, 0x72, 0x65, 0x4c, 0x65, 0x61,
0x73, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x61, 0x63,
0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x61, 0x63,
0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x22, 0x72, 0x0a, 0x11, 0x52, 0x65, 0x6e, 0x65, 0x77, 0x4c,
0x65, 0x61, 0x73, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x72,
0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72,
0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e,
0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x2b, 0x0a,
0x03, 0x74, 0x74, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x03, 0x74, 0x74, 0x6c, 0x22, 0x2e, 0x0a, 0x12, 0x52, 0x65,
0x6e, 0x65, 0x77, 0x4c, 0x65, 0x61, 0x73, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65,
0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x6e, 0x65, 0x77, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28,
0x08, 0x52, 0x07, 0x72, 0x65, 0x6e, 0x65, 0x77, 0x65, 0x64, 0x22, 0x47, 0x0a, 0x13, 0x52, 0x65,
0x6c, 0x65, 0x61, 0x73, 0x65, 0x4c, 0x65, 0x61, 0x73, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x01, 0x20,
0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x14, 0x0a,
0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x74, 0x6f,
0x6b, 0x65, 0x6e, 0x22, 0x32, 0x0a, 0x14, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x4c, 0x65,
0x61, 0x73, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x72,
0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x72,
0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x32, 0xf1, 0x01, 0x0a, 0x05, 0x4c, 0x65, 0x61, 0x73,
0x65, 0x12, 0x4e, 0x0a, 0x07, 0x41, 0x63, 0x71, 0x75, 0x69, 0x72, 0x65, 0x12, 0x20, 0x2e, 0x64,
0x69, 0x73, 0x74, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x63, 0x71, 0x75, 0x69,
0x72, 0x65, 0x4c, 0x65, 0x61, 0x73, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x21,
0x2e, 0x64, 0x69, 0x73, 0x74, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x63, 0x71,
0x75, 0x69, 0x72, 0x65, 0x4c, 0x65, 0x61, 0x73, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73,
0x65, 0x12, 0x48, 0x0a, 0x05, 0x52, 0x65, 0x6e, 0x65, 0x77, 0x12, 0x1e, 0x2e, 0x64, 0x69, 0x73,
0x74, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x6e, 0x65, 0x77, 0x4c, 0x65,
0x61, 0x73, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1f, 0x2e, 0x64, 0x69, 0x73,
0x74, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x6e, 0x65, 0x77, 0x4c, 0x65,
0x61, 0x73, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4e, 0x0a, 0x07, 0x52,
0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x12, 0x20, 0x2e, 0x64, 0x69, 0x73, 0x74, 0x6c, 0x6f, 0x63,
0x6b, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x4c, 0x65, 0x61, 0x73,
0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x21, 0x2e, 0x64, 0x69, 0x73, 0x74, 0x6c,
0x6f, 0x63, 0x6b, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x4c, 0x65,
0x61, 0x73, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x31, 0x5a, 0x2f, 0x67,
0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x70, 0x73, 0x76, 0x69, 0x64, 0x65,
0x72, 0x73, 0x6b, 0x69, 0x2f, 0x75, 0x6e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x70, 0x6b, 0x67,
0x2f, 0x64, 0x69, 0x73, 0x74, 0x6c, 0x6f, 0x63, 0x6b, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x62, 0x06,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_pkg_distlock_grpc_lease_proto_rawDescOnce sync.Once
file_pkg_distlock_grpc_lease_proto_rawDescData = file_pkg_distlock_grpc_lease_proto_rawDesc
)
func file_pkg_distlock_grpc_lease_proto_rawDescGZIP() []byte {
file_pkg_distlock_grpc_lease_proto_rawDescOnce.Do(func() {
file_pkg_distlock_grpc_lease_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_distlock_grpc_lease_proto_rawDescData)
})
return file_pkg_distlock_grpc_lease_proto_rawDescData
}
var file_pkg_distlock_grpc_lease_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_pkg_distlock_grpc_lease_proto_goTypes = []any{
(*AcquireLeaseRequest)(nil), // 0: distlock.v1.AcquireLeaseRequest
(*AcquireLeaseResponse)(nil), // 1: distlock.v1.AcquireLeaseResponse
(*RenewLeaseRequest)(nil), // 2: distlock.v1.RenewLeaseRequest
(*RenewLeaseResponse)(nil), // 3: distlock.v1.RenewLeaseResponse
(*ReleaseLeaseRequest)(nil), // 4: distlock.v1.ReleaseLeaseRequest
(*ReleaseLeaseResponse)(nil), // 5: distlock.v1.ReleaseLeaseResponse
(*durationpb.Duration)(nil), // 6: google.protobuf.Duration
}
var file_pkg_distlock_grpc_lease_proto_depIdxs = []int32{
6, // 0: distlock.v1.AcquireLeaseRequest.ttl:type_name -> google.protobuf.Duration
6, // 1: distlock.v1.RenewLeaseRequest.ttl:type_name -> google.protobuf.Duration
0, // 2: distlock.v1.Lease.Acquire:input_type -> distlock.v1.AcquireLeaseRequest
2, // 3: distlock.v1.Lease.Renew:input_type -> distlock.v1.RenewLeaseRequest
4, // 4: distlock.v1.Lease.Release:input_type -> distlock.v1.ReleaseLeaseRequest
1, // 5: distlock.v1.Lease.Acquire:output_type -> distlock.v1.AcquireLeaseResponse
3, // 6: distlock.v1.Lease.Renew:output_type -> distlock.v1.RenewLeaseResponse
5, // 7: distlock.v1.Lease.Release:output_type -> distlock.v1.ReleaseLeaseResponse
5, // [5:8] is the sub-list for method output_type
2, // [2:5] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_pkg_distlock_grpc_lease_proto_init() }
func file_pkg_distlock_grpc_lease_proto_init() {
if File_pkg_distlock_grpc_lease_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_pkg_distlock_grpc_lease_proto_msgTypes[0].Exporter = func(v any, i int) any {
switch v := v.(*AcquireLeaseRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_pkg_distlock_grpc_lease_proto_msgTypes[1].Exporter = func(v any, i int) any {
switch v := v.(*AcquireLeaseResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_pkg_distlock_grpc_lease_proto_msgTypes[2].Exporter = func(v any, i int) any {
switch v := v.(*RenewLeaseRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_pkg_distlock_grpc_lease_proto_msgTypes[3].Exporter = func(v any, i int) any {
switch v := v.(*RenewLeaseResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_pkg_distlock_grpc_lease_proto_msgTypes[4].Exporter = func(v any, i int) any {
switch v := v.(*ReleaseLeaseRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_pkg_distlock_grpc_lease_proto_msgTypes[5].Exporter = func(v any, i int) any {
switch v := v.(*ReleaseLeaseResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_pkg_distlock_grpc_lease_proto_rawDesc,
NumEnums: 0,
NumMessages: 6,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_pkg_distlock_grpc_lease_proto_goTypes,
DependencyIndexes: file_pkg_distlock_grpc_lease_proto_depIdxs,
MessageInfos: file_pkg_distlock_grpc_lease_proto_msgTypes,
}.Build()
File_pkg_distlock_grpc_lease_proto = out.File
file_pkg_distlock_grpc_lease_proto_rawDesc = nil
file_pkg_distlock_grpc_lease_proto_goTypes = nil
file_pkg_distlock_grpc_lease_proto_depIdxs = nil
}
+54
View File
@@ -0,0 +1,54 @@
syntax = "proto3";
package distlock.v1;
option go_package = "github.com/psviderski/uncloud/pkg/distlock/grpc";
import "google/protobuf/duration.proto";
// Lease provides atomic operations for time-bound ownership of resources on one node.
service Lease {
// Acquire creates a lease when the resource has no unexpired lease.
rpc Acquire(AcquireLeaseRequest) returns (AcquireLeaseResponse);
// Renew extends an unexpired lease when its ownership token matches.
rpc Renew(RenewLeaseRequest) returns (RenewLeaseResponse);
// Release removes an unexpired lease when its ownership token matches.
rpc Release(ReleaseLeaseRequest) returns (ReleaseLeaseResponse);
}
message AcquireLeaseRequest {
string resource = 1;
// Token uniquely identifies the lease owner.
bytes token = 2;
// TTL sets how long the lease remains valid without renewal.
google.protobuf.Duration ttl = 3;
}
message AcquireLeaseResponse {
// Acquired is true when this request successfully created the lease.
bool acquired = 1;
}
message RenewLeaseRequest {
string resource = 1;
// Token identifies the owner of the existing lease.
bytes token = 2;
// TTL sets how long the renewed lease remains valid.
google.protobuf.Duration ttl = 3;
}
message RenewLeaseResponse {
// Renewed is true when an unexpired lease matched the ownership token and was successfully renewed.
bool renewed = 1;
}
message ReleaseLeaseRequest {
string resource = 1;
// Token identifies the owner of the existing lease.
bytes token = 2;
}
message ReleaseLeaseResponse {
// Released is true when an unexpired lease existed, matched the ownership token, and was successfully released.
bool released = 1;
}
+207
View File
@@ -0,0 +1,207 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v5.27.3
// source: pkg/distlock/grpc/lease.proto
package grpc
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
Lease_Acquire_FullMethodName = "/distlock.v1.Lease/Acquire"
Lease_Renew_FullMethodName = "/distlock.v1.Lease/Renew"
Lease_Release_FullMethodName = "/distlock.v1.Lease/Release"
)
// LeaseClient is the client API for Lease service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
//
// Lease provides atomic operations for time-bound ownership of resources on one node.
type LeaseClient interface {
// Acquire creates a lease when the resource has no unexpired lease.
Acquire(ctx context.Context, in *AcquireLeaseRequest, opts ...grpc.CallOption) (*AcquireLeaseResponse, error)
// Renew extends an unexpired lease when its ownership token matches.
Renew(ctx context.Context, in *RenewLeaseRequest, opts ...grpc.CallOption) (*RenewLeaseResponse, error)
// Release removes an unexpired lease when its ownership token matches.
Release(ctx context.Context, in *ReleaseLeaseRequest, opts ...grpc.CallOption) (*ReleaseLeaseResponse, error)
}
type leaseClient struct {
cc grpc.ClientConnInterface
}
func NewLeaseClient(cc grpc.ClientConnInterface) LeaseClient {
return &leaseClient{cc}
}
func (c *leaseClient) Acquire(ctx context.Context, in *AcquireLeaseRequest, opts ...grpc.CallOption) (*AcquireLeaseResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AcquireLeaseResponse)
err := c.cc.Invoke(ctx, Lease_Acquire_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *leaseClient) Renew(ctx context.Context, in *RenewLeaseRequest, opts ...grpc.CallOption) (*RenewLeaseResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RenewLeaseResponse)
err := c.cc.Invoke(ctx, Lease_Renew_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *leaseClient) Release(ctx context.Context, in *ReleaseLeaseRequest, opts ...grpc.CallOption) (*ReleaseLeaseResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ReleaseLeaseResponse)
err := c.cc.Invoke(ctx, Lease_Release_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// LeaseServer is the server API for Lease service.
// All implementations must embed UnimplementedLeaseServer
// for forward compatibility.
//
// Lease provides atomic operations for time-bound ownership of resources on one node.
type LeaseServer interface {
// Acquire creates a lease when the resource has no unexpired lease.
Acquire(context.Context, *AcquireLeaseRequest) (*AcquireLeaseResponse, error)
// Renew extends an unexpired lease when its ownership token matches.
Renew(context.Context, *RenewLeaseRequest) (*RenewLeaseResponse, error)
// Release removes an unexpired lease when its ownership token matches.
Release(context.Context, *ReleaseLeaseRequest) (*ReleaseLeaseResponse, error)
mustEmbedUnimplementedLeaseServer()
}
// UnimplementedLeaseServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedLeaseServer struct{}
func (UnimplementedLeaseServer) Acquire(context.Context, *AcquireLeaseRequest) (*AcquireLeaseResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Acquire not implemented")
}
func (UnimplementedLeaseServer) Renew(context.Context, *RenewLeaseRequest) (*RenewLeaseResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Renew not implemented")
}
func (UnimplementedLeaseServer) Release(context.Context, *ReleaseLeaseRequest) (*ReleaseLeaseResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Release not implemented")
}
func (UnimplementedLeaseServer) mustEmbedUnimplementedLeaseServer() {}
func (UnimplementedLeaseServer) testEmbeddedByValue() {}
// UnsafeLeaseServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to LeaseServer will
// result in compilation errors.
type UnsafeLeaseServer interface {
mustEmbedUnimplementedLeaseServer()
}
func RegisterLeaseServer(s grpc.ServiceRegistrar, srv LeaseServer) {
// If the following call pancis, it indicates UnimplementedLeaseServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&Lease_ServiceDesc, srv)
}
func _Lease_Acquire_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AcquireLeaseRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LeaseServer).Acquire(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Lease_Acquire_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LeaseServer).Acquire(ctx, req.(*AcquireLeaseRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Lease_Renew_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RenewLeaseRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LeaseServer).Renew(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Lease_Renew_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LeaseServer).Renew(ctx, req.(*RenewLeaseRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Lease_Release_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ReleaseLeaseRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LeaseServer).Release(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Lease_Release_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LeaseServer).Release(ctx, req.(*ReleaseLeaseRequest))
}
return interceptor(ctx, in, info, handler)
}
// Lease_ServiceDesc is the grpc.ServiceDesc for Lease service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Lease_ServiceDesc = grpc.ServiceDesc{
ServiceName: "distlock.v1.Lease",
HandlerType: (*LeaseServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Acquire",
Handler: _Lease_Acquire_Handler,
},
{
MethodName: "Renew",
Handler: _Lease_Renew_Handler,
},
{
MethodName: "Release",
Handler: _Lease_Release_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "pkg/distlock/grpc/lease.proto",
}
+99
View File
@@ -0,0 +1,99 @@
// Package grpc provides a gRPC transport for distlock node-local lease operations.
package grpc
import (
"context"
"fmt"
"time"
"github.com/psviderski/uncloud/pkg/distlock"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/durationpb"
)
// Server adapts a node-local distlock.Store to the Lease gRPC service.
type Server struct {
UnimplementedLeaseServer
store distlock.Store
}
// NewServer creates a node-local lease server.
func NewServer(store distlock.Store) *Server {
return &Server{store: store}
}
// Acquire creates a lease when the resource has no unexpired lease.
func (s *Server) Acquire(ctx context.Context, req *AcquireLeaseRequest) (*AcquireLeaseResponse, error) {
ttl, err := validateLeaseRequest(req.Resource, req.Token, req.Ttl)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
acquired, err := s.store.Acquire(ctx, req.Resource, req.Token, ttl)
if err != nil {
return nil, storeStatusError(ctx, "acquire lease", err)
}
return &AcquireLeaseResponse{Acquired: acquired}, nil
}
// Renew extends an unexpired lease when its ownership token matches.
func (s *Server) Renew(ctx context.Context, req *RenewLeaseRequest) (*RenewLeaseResponse, error) {
ttl, err := validateLeaseRequest(req.Resource, req.Token, req.Ttl)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
renewed, err := s.store.Renew(ctx, req.Resource, req.Token, ttl)
if err != nil {
return nil, storeStatusError(ctx, "renew lease", err)
}
return &RenewLeaseResponse{Renewed: renewed}, nil
}
// Release removes an unexpired lease when its ownership token matches.
func (s *Server) Release(ctx context.Context, req *ReleaseLeaseRequest) (*ReleaseLeaseResponse, error) {
if err := validateResourceToken(req.Resource, req.Token); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
released, err := s.store.Release(ctx, req.Resource, req.Token)
if err != nil {
return nil, storeStatusError(ctx, "release lease", err)
}
return &ReleaseLeaseResponse{Released: released}, nil
}
func validateLeaseRequest(resource string, token []byte, ttl *durationpb.Duration) (time.Duration, error) {
if err := validateResourceToken(resource, token); err != nil {
return 0, err
}
if ttl == nil {
return 0, fmt.Errorf("TTL is not set")
}
if err := ttl.CheckValid(); err != nil {
return 0, fmt.Errorf("invalid TTL: %w", err)
}
duration := ttl.AsDuration()
if duration <= 0 {
return 0, fmt.Errorf("TTL must be positive")
}
return duration, nil
}
func validateResourceToken(resource string, token []byte) error {
if resource == "" {
return fmt.Errorf("resource is empty")
}
if len(token) == 0 {
return fmt.Errorf("token is empty")
}
return nil
}
func storeStatusError(ctx context.Context, operation string, err error) error {
if ctxErr := ctx.Err(); ctxErr != nil {
return status.FromContextError(ctxErr).Err()
}
return status.Error(codes.Internal, fmt.Sprintf("%s: %v", operation, err))
}
+139
View File
@@ -0,0 +1,139 @@
package distlock
import (
"bytes"
"context"
"fmt"
"sync"
"time"
)
type memoryLease struct {
token []byte
expiresAt time.Time
}
// MemoryStore stores leases in memory. Its contents are lost when the process exits.
type MemoryStore struct {
mu sync.Mutex
leases map[string]memoryLease
now func() time.Time
}
// NewMemoryStore creates an empty in-memory lease store.
func NewMemoryStore() *MemoryStore {
return &MemoryStore{
leases: make(map[string]memoryLease),
now: time.Now,
}
}
// Acquire creates a lease when the resource does not have an unexpired lease.
func (s *MemoryStore) Acquire(
ctx context.Context, resource string, token []byte, ttl time.Duration,
) (bool, error) {
if err := validateStoreInput(ctx, resource, token, ttl); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
if err := ctx.Err(); err != nil {
return false, err
}
now := s.now()
if lease, ok := s.leases[resource]; ok && now.Before(lease.expiresAt) {
return false, nil
}
s.leases[resource] = memoryLease{
token: bytes.Clone(token),
expiresAt: now.Add(ttl),
}
return true, nil
}
// Renew extends an unexpired lease when its ownership token matches.
func (s *MemoryStore) Renew(
ctx context.Context, resource string, token []byte, ttl time.Duration,
) (bool, error) {
if err := validateStoreInput(ctx, resource, token, ttl); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
if err := ctx.Err(); err != nil {
return false, err
}
now := s.now()
lease, ok := s.leases[resource]
if !ok {
return false, nil
}
if !now.Before(lease.expiresAt) {
delete(s.leases, resource)
return false, nil
}
if !bytes.Equal(lease.token, token) {
return false, nil
}
lease.expiresAt = now.Add(ttl)
s.leases[resource] = lease
return true, nil
}
// Release removes an unexpired lease when its ownership token matches.
func (s *MemoryStore) Release(ctx context.Context, resource string, token []byte) (bool, error) {
if err := validateStoreResourceToken(ctx, resource, token); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
if err := ctx.Err(); err != nil {
return false, err
}
now := s.now()
lease, ok := s.leases[resource]
if !ok {
return false, nil
}
if !now.Before(lease.expiresAt) {
delete(s.leases, resource)
return false, nil
}
if !bytes.Equal(lease.token, token) {
return false, nil
}
delete(s.leases, resource)
return true, nil
}
func validateStoreInput(ctx context.Context, resource string, token []byte, ttl time.Duration) error {
if err := validateStoreResourceToken(ctx, resource, token); err != nil {
return err
}
if ttl <= 0 {
return fmt.Errorf("TTL must be positive")
}
return nil
}
func validateStoreResourceToken(ctx context.Context, resource string, token []byte) error {
if err := ctx.Err(); err != nil {
return err
}
if resource == "" {
return fmt.Errorf("resource is empty")
}
if len(token) == 0 {
return fmt.Errorf("token is empty")
}
return nil
}
+243
View File
@@ -0,0 +1,243 @@
package distlock
import (
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestMemoryStoreAcquire(t *testing.T) {
store := newTestMemoryStore()
ctx := context.Background()
acquired, err := store.Acquire(ctx, "resource-a", []byte("owner-a"), time.Minute)
require.NoError(t, err)
require.True(t, acquired)
acquired, err = store.Acquire(ctx, "resource-a", []byte("owner-b"), time.Minute)
require.NoError(t, err)
require.False(t, acquired)
acquired, err = store.Acquire(ctx, "resource-b", []byte("owner-b"), time.Minute)
require.NoError(t, err)
require.True(t, acquired)
}
func TestMemoryStoreExpirationAndStaleOwner(t *testing.T) {
now := time.Date(2026, time.August, 26, 12, 0, 0, 0, time.UTC)
store := newTestMemoryStore()
store.now = func() time.Time { return now }
ctx := context.Background()
oldToken := []byte("old-owner")
newToken := []byte("new-owner")
acquired, err := store.Acquire(ctx, "resource", oldToken, time.Minute)
require.NoError(t, err)
require.True(t, acquired)
// A lease is expired at its expiration time, not only after it.
now = now.Add(time.Minute)
acquired, err = store.Acquire(ctx, "resource", newToken, time.Minute)
require.NoError(t, err)
require.True(t, acquired)
released, err := store.Release(ctx, "resource", oldToken)
require.NoError(t, err)
require.False(t, released)
renewed, err := store.Renew(ctx, "resource", oldToken, time.Minute)
require.NoError(t, err)
require.False(t, renewed)
released, err = store.Release(ctx, "resource", newToken)
require.NoError(t, err)
require.True(t, released)
}
func TestMemoryStoreRenew(t *testing.T) {
now := time.Date(2026, time.August, 26, 12, 0, 0, 0, time.UTC)
store := newTestMemoryStore()
store.now = func() time.Time { return now }
ctx := context.Background()
token := []byte("owner")
acquired, err := store.Acquire(ctx, "resource", token, time.Minute)
require.NoError(t, err)
require.True(t, acquired)
now = now.Add(30 * time.Second)
renewed, err := store.Renew(ctx, "resource", []byte("another-owner"), time.Minute)
require.NoError(t, err)
require.False(t, renewed)
renewed, err = store.Renew(ctx, "resource", token, time.Minute)
require.NoError(t, err)
require.True(t, renewed)
// The renewal extends the lease from the renewal time.
now = now.Add(30 * time.Second)
acquired, err = store.Acquire(ctx, "resource", []byte("another-owner"), time.Minute)
require.NoError(t, err)
require.False(t, acquired)
now = now.Add(30 * time.Second)
renewed, err = store.Renew(ctx, "resource", token, time.Minute)
require.NoError(t, err)
require.False(t, renewed)
}
func TestMemoryStoreRelease(t *testing.T) {
store := newTestMemoryStore()
ctx := context.Background()
token := []byte("owner")
released, err := store.Release(ctx, "resource", token)
require.NoError(t, err)
require.False(t, released)
acquired, err := store.Acquire(ctx, "resource", token, time.Minute)
require.NoError(t, err)
require.True(t, acquired)
released, err = store.Release(ctx, "resource", []byte("another-owner"))
require.NoError(t, err)
require.False(t, released)
released, err = store.Release(ctx, "resource", token)
require.NoError(t, err)
require.True(t, released)
released, err = store.Release(ctx, "resource", token)
require.NoError(t, err)
require.False(t, released)
}
func TestMemoryStoreCopiesToken(t *testing.T) {
store := newTestMemoryStore()
ctx := context.Background()
token := []byte("owner")
originalToken := append([]byte(nil), token...)
acquired, err := store.Acquire(ctx, "resource", token, time.Minute)
require.NoError(t, err)
require.True(t, acquired)
token[0] = 'x'
released, err := store.Release(ctx, "resource", originalToken)
require.NoError(t, err)
require.True(t, released)
}
func TestMemoryStoreValidation(t *testing.T) {
tests := []struct {
name string
run func(*MemoryStore) error
}{
{
name: "acquire with empty resource",
run: func(store *MemoryStore) error {
_, err := store.Acquire(context.Background(), "", []byte("owner"), time.Minute)
return err
},
},
{
name: "acquire with empty token",
run: func(store *MemoryStore) error {
_, err := store.Acquire(context.Background(), "resource", nil, time.Minute)
return err
},
},
{
name: "acquire with zero TTL",
run: func(store *MemoryStore) error {
_, err := store.Acquire(context.Background(), "resource", []byte("owner"), 0)
return err
},
},
{
name: "renew with negative TTL",
run: func(store *MemoryStore) error {
_, err := store.Renew(context.Background(), "resource", []byte("owner"), -time.Second)
return err
},
},
{
name: "release with empty token",
run: func(store *MemoryStore) error {
_, err := store.Release(context.Background(), "resource", nil)
return err
},
},
{
name: "cancelled context",
run: func(store *MemoryStore) error {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := store.Acquire(ctx, "resource", []byte("owner"), time.Minute)
return err
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
store := newTestMemoryStore()
require.Error(t, test.run(store))
// Invalid operations must not create or replace a lease.
acquired, err := store.Acquire(context.Background(), "resource", []byte("valid-owner"), time.Minute)
require.NoError(t, err)
require.True(t, acquired)
})
}
}
func TestMemoryStoreConcurrentAcquire(t *testing.T) {
const attempts = 100
store := newTestMemoryStore()
ctx := context.Background()
start := make(chan struct{})
errCh := make(chan error, attempts)
var acquired atomic.Int64
var wg sync.WaitGroup
for i := range attempts {
wg.Add(1)
go func() {
defer wg.Done()
<-start
ok, err := store.Acquire(ctx, "resource", []byte(fmt.Sprintf("owner-%d", i)), time.Minute)
if err != nil {
errCh <- err
return
}
if ok {
acquired.Add(1)
}
}()
}
close(start)
wg.Wait()
close(errCh)
for err := range errCh {
require.NoError(t, err)
}
require.EqualValues(t, 1, acquired.Load())
}
func newTestMemoryStore() *MemoryStore {
store := NewMemoryStore()
store.now = func() time.Time {
return time.Date(2026, time.August, 26, 12, 0, 0, 0, time.UTC)
}
return store
}
+16
View File
@@ -0,0 +1,16 @@
package distlock
import (
"context"
"time"
)
// Store holds node-local lease state and provides atomic operations over it.
type Store interface {
// Acquire creates a lease when the resource does not have an unexpired lease.
Acquire(ctx context.Context, resource string, token []byte, ttl time.Duration) (bool, error)
// Renew extends an unexpired lease when its ownership token matches.
Renew(ctx context.Context, resource string, token []byte, ttl time.Duration) (bool, error)
// Release removes a lease when its ownership token matches.
Release(ctx context.Context, resource string, token []byte) (bool, error)
}