command_factory.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package store
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/coreos/go-raft"
  6. )
  7. // A lookup of factories by version.
  8. var factories = make(map[int]CommandFactory)
  9. var minVersion, maxVersion int
  10. // The CommandFactory provides a way to create different types of commands
  11. // depending on the current version of the store.
  12. type CommandFactory interface {
  13. Version() int
  14. CreateSetCommand(key string, value string, expireTime time.Time) raft.Command
  15. CreateCreateCommand(key string, value string, expireTime time.Time, unique bool) raft.Command
  16. CreateUpdateCommand(key string, value string, expireTime time.Time) raft.Command
  17. CreateDeleteCommand(key string, recursive bool) raft.Command
  18. CreateCompareAndSwapCommand(key string, value string, prevValue string, prevIndex uint64, expireTime time.Time) raft.Command
  19. }
  20. // RegisterCommandFactory adds a command factory to the global registry.
  21. func RegisterCommandFactory(factory CommandFactory) {
  22. version := factory.Version()
  23. if GetCommandFactory(version) != nil {
  24. panic(fmt.Sprintf("Command factory already registered for version: %d", factory.Version()))
  25. }
  26. factories[version] = factory
  27. // Update compatibility versions.
  28. if minVersion == 0 || version > minVersion {
  29. minVersion = version
  30. }
  31. if maxVersion == 0 || version > maxVersion {
  32. maxVersion = version
  33. }
  34. }
  35. // GetCommandFactory retrieves a command factory for a given command version.
  36. func GetCommandFactory(version int) CommandFactory {
  37. return factories[version]
  38. }
  39. // MinVersion returns the minimum compatible store version.
  40. func MinVersion() int {
  41. return minVersion
  42. }
  43. // MaxVersion returns the maximum compatible store version.
  44. func MaxVersion() int {
  45. return maxVersion
  46. }