store.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package store
  14. import (
  15. "fmt"
  16. "regexp"
  17. )
  18. const (
  19. keyMaxLength = 250
  20. keyCharFmt string = "[A-Za-z0-9]"
  21. keyExtCharFmt string = "[-A-Za-z0-9_.]"
  22. qualifiedKeyFmt string = "(" + keyCharFmt + keyExtCharFmt + "*)?" + keyCharFmt
  23. )
  24. var (
  25. // Key must consist of alphanumeric characters, '-', '_' or '.', and must start
  26. // and end with an alphanumeric character.
  27. keyRegex = regexp.MustCompile("^" + qualifiedKeyFmt + "$")
  28. // ErrKeyNotFound is the error returned if key is not found in Store.
  29. ErrKeyNotFound = fmt.Errorf("key is not found")
  30. )
  31. // Store provides the interface for storing keyed data.
  32. // Store must be thread-safe
  33. type Store interface {
  34. // key must contain one or more characters in [A-Za-z0-9]
  35. // Write writes data with key.
  36. Write(key string, data []byte) error
  37. // Read retrieves data with key
  38. // Read must return ErrKeyNotFound if key is not found.
  39. Read(key string) ([]byte, error)
  40. // Delete deletes data by key
  41. // Delete must not return error if key does not exist
  42. Delete(key string) error
  43. // List lists all existing keys.
  44. List() ([]string, error)
  45. }
  46. // ValidateKey returns an error if the given key does not meet the requirement
  47. // of the key format and length.
  48. func ValidateKey(key string) error {
  49. if len(key) <= keyMaxLength && keyRegex.MatchString(key) {
  50. return nil
  51. }
  52. return fmt.Errorf("invalid key: %q", key)
  53. }