diff --git a/internal/redis/namespace.go b/internal/redis/namespace.go new file mode 100644 index 0000000..59596e7 --- /dev/null +++ b/internal/redis/namespace.go @@ -0,0 +1,40 @@ +package redis + +import ( + "strings" +) + +const ( + // Default prefix to use when none is set. + defaultPrefix = "ship" + + // We need to have some chain_id, so if no one is specified. + // we use a "null" id that is all zeros. + nullChain = "0000000000000000000000000000000000000000000000000000000000000000" +) + +// Namespace type. +// +// Contains a prefix and chain_id to guard keys against collision. +// Prefix should be sufficient to not collide with other application using the same redis database. +// chain_id should be ok to not let multiple reader with different chains to write to the same channels. + +type Namespace struct { + Prefix string + ChainID string +} + +func (ns Namespace) String() string { + // No Chain id, set to "nullChain" + if len(ns.ChainID) < 1 { + ns.ChainID = nullChain + } + + // Set default prefix if empty. + if len(ns.Prefix) < 1 { + ns.Prefix = defaultPrefix + } + + // Otherwise. return both. + return strings.Join([]string{ns.Prefix, ns.ChainID}, ".") +} diff --git a/internal/redis/namespace_test.go b/internal/redis/namespace_test.go new file mode 100644 index 0000000..1890c0e --- /dev/null +++ b/internal/redis/namespace_test.go @@ -0,0 +1,23 @@ +package redis + +import "testing" + +func TestNamespace_String(t *testing.T) { + tests := []struct { + name string + ns Namespace + want string + }{ + {"Empty", Namespace{}, "ship.0000000000000000000000000000000000000000000000000000000000000000"}, + {"Prefix Only", Namespace{Prefix: "some.prefix"}, "some.prefix.0000000000000000000000000000000000000000000000000000000000000000"}, + {"ChainID Only", Namespace{ChainID: "1234"}, "ship.1234"}, + {"Both", Namespace{Prefix: "my.prefix", ChainID: "1234"}, "my.prefix.1234"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.ns.String(); got != tt.want { + t.Errorf("Namespace.String() = %v, want %v", got, tt.want) + } + }) + } +}