command_factory.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package store
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/coreos/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. CreateUpgradeCommand() raft.Command
  15. CreateSetCommand(key string, value string, expireTime time.Time) raft.Command
  16. CreateCreateCommand(key string, value string, expireTime time.Time, unique bool) raft.Command
  17. CreateUpdateCommand(key string, value string, expireTime time.Time) raft.Command
  18. CreateDeleteCommand(key string, recursive bool) raft.Command
  19. CreateCompareAndSwapCommand(key string, value string, prevValue string, prevIndex uint64, expireTime time.Time) raft.Command
  20. CreateCompareAndDeleteCommand(key string, recursive bool, prevValue string, prevIndex uint64) raft.Command
  21. CreateSyncCommand(now time.Time) raft.Command
  22. }
  23. // RegisterCommandFactory adds a command factory to the global registry.
  24. func RegisterCommandFactory(factory CommandFactory) {
  25. version := factory.Version()
  26. if GetCommandFactory(version) != nil {
  27. panic(fmt.Sprintf("Command factory already registered for version: %d", factory.Version()))
  28. }
  29. factories[version] = factory
  30. // Update compatibility versions.
  31. if minVersion == 0 || version > minVersion {
  32. minVersion = version
  33. }
  34. if maxVersion == 0 || version > maxVersion {
  35. maxVersion = version
  36. }
  37. }
  38. // GetCommandFactory retrieves a command factory for a given command version.
  39. func GetCommandFactory(version int) CommandFactory {
  40. return factories[version]
  41. }
  42. // MinVersion returns the minimum compatible store version.
  43. func MinVersion() int {
  44. return minVersion
  45. }
  46. // MaxVersion returns the maximum compatible store version.
  47. func MaxVersion() int {
  48. return maxVersion
  49. }