This commit is contained in:
+34
-5
@@ -6,14 +6,43 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ID is a transport-neutral opaque identifier primitive. Domain packages wrap it
|
||||
// in strong semantic ID types; do not pass bare ID across semantic boundaries.
|
||||
type ID string
|
||||
// StableID is a transport-neutral opaque identifier primitive. Domain packages
|
||||
// wrap it in strong semantic ID types; do not pass bare StableID across
|
||||
// semantic boundaries.
|
||||
type StableID string
|
||||
|
||||
func New() (ID, error) {
|
||||
// ID is retained as a compatibility name for the V1 primitive.
|
||||
type ID = StableID
|
||||
|
||||
// Revision is the optimistic version of a versioned semantic record.
|
||||
type Revision uint64
|
||||
|
||||
const InitialRevision Revision = 1
|
||||
|
||||
func (r Revision) Valid() bool { return r >= InitialRevision }
|
||||
|
||||
// SemanticRef is a technical cross-owner reference envelope. It identifies a
|
||||
// record but does not grant storage ownership or provide generic CRUD.
|
||||
type SemanticRef struct {
|
||||
OwnerNamespace string
|
||||
SemanticKind string
|
||||
StableID StableID
|
||||
Revision *Revision
|
||||
}
|
||||
|
||||
func (r SemanticRef) Valid() bool {
|
||||
return r.OwnerNamespace != "" && r.SemanticKind != "" && r.StableID != "" &&
|
||||
(r.Revision == nil || r.Revision.Valid())
|
||||
}
|
||||
|
||||
func NewStableID() (StableID, error) {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", fmt.Errorf("generate id: %w", err)
|
||||
}
|
||||
return ID(hex.EncodeToString(b[:])), nil
|
||||
return StableID(hex.EncodeToString(b[:])), nil
|
||||
}
|
||||
|
||||
func New() (ID, error) {
|
||||
return NewStableID()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package ids
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewStableIDIsOpaque128BitHex(t *testing.T) {
|
||||
id, err := NewStableID()
|
||||
if err != nil || len(id) != 32 {
|
||||
t.Fatalf("NewStableID() = %q, %v", id, err)
|
||||
}
|
||||
if !(SemanticRef{OwnerNamespace: "world", SemanticKind: "object", StableID: id}.Valid()) {
|
||||
t.Fatal("stable id was not accepted by semantic reference")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSemanticRefRejectsInvalidRevision(t *testing.T) {
|
||||
revision := Revision(0)
|
||||
ref := SemanticRef{OwnerNamespace: "world", SemanticKind: "object", StableID: "id", Revision: &revision}
|
||||
if ref.Valid() {
|
||||
t.Fatal("semantic reference accepted invalid revision")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user