Skip to content

Commit

Permalink
feat: add Register function to DA registry (cosmos#721)
Browse files Browse the repository at this point in the history
Resolves cosmos#715.
  • Loading branch information
tzdybal authored Feb 3, 2023
1 parent 1ba8c3a commit 9f954d6
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
22 changes: 22 additions & 0 deletions da/registry/registry.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
package registry

import (
"fmt"

"github.com/rollkit/rollkit/da"
"github.com/rollkit/rollkit/da/celestia"
"github.com/rollkit/rollkit/da/grpc"
"github.com/rollkit/rollkit/da/mock"
)

// ErrAlreadyRegistered is used when user tries to register DA using a name already used in registry.
type ErrAlreadyRegistered struct {
name string
}

func (e *ErrAlreadyRegistered) Error() string {
return fmt.Sprintf("Data Availability Layer '%s' already registered", e.name)
}

// this is a central registry for all Data Availability Layer Clients
var clients = map[string]func() da.DataAvailabilityLayerClient{
"mock": func() da.DataAvailabilityLayerClient { return &mock.DataAvailabilityLayerClient{} },
Expand All @@ -23,6 +34,17 @@ func GetClient(name string) da.DataAvailabilityLayerClient {
return f()
}

// Register adds a Data Availability Layer Client to registry.
//
// If name was previously used in the registry, error is returned.
func Register(name string, constructor func() da.DataAvailabilityLayerClient) error {
if _, found := clients[name]; !found {
clients[name] = constructor
return nil
}
return &ErrAlreadyRegistered{name: name}
}

// RegisteredClients returns names of all DA clients in registry.
func RegisteredClients() []string {
registered := make([]string, 0, len(clients))
Expand Down
19 changes: 18 additions & 1 deletion da/registry/registry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/rollkit/rollkit/da"
"github.com/rollkit/rollkit/da/mock"
)

func TestRegistery(t *testing.T) {
Expand All @@ -14,7 +17,21 @@ func TestRegistery(t *testing.T) {

assert.ElementsMatch(expected, actual)

for _, e := range expected {
constructor := func() da.DataAvailabilityLayerClient {
return &mock.DataAvailabilityLayerClient{} // cheating, only for tests :D
}
err := Register("testDA", constructor)
assert.NoError(err)

// re-registration should fail
err = Register("celestia", constructor)
regErr := &ErrAlreadyRegistered{}
assert.ErrorAs(err, &regErr)
assert.Equal("celestia", regErr.name)

assert.Contains(RegisteredClients(), "testDA")

for _, e := range RegisteredClients() {
dalc := GetClient(e)
assert.NotNil(dalc)
}
Expand Down

0 comments on commit 9f954d6

Please sign in to comment.