ADAPT-Chase commited on
Commit
cf3ed5d
·
verified ·
1 Parent(s): e89cd08

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/anonymous/middleware.go +94 -0
  2. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/anonymous/middleware_test.go +102 -0
  3. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/client.go +112 -0
  4. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/client_test.go +186 -0
  5. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/db_user_test.go +457 -0
  6. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/db_users.go +550 -0
  7. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/keys/key_generation.go +118 -0
  8. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/keys/key_generation_test.go +69 -0
  9. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/remote.go +57 -0
  10. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/wrapper.go +77 -0
  11. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/wrapper_test.go +148 -0
  12. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/authentication.go +19 -0
  13. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/composer/token_validation.go +61 -0
  14. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/composer/token_validation_test.go +240 -0
  15. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/oidc/middleware.go +298 -0
  16. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/oidc/middleware_test.go +279 -0
  17. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/oidc/oidc_server_for_test.go +115 -0
  18. platform/dbops/binaries/weaviate-src/usecases/auth/authentication/oidc/oidc_server_with_certificate_for_test.go +79 -0
  19. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/adminlist/authorizer.go +133 -0
  20. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/adminlist/authorizer_test.go +449 -0
  21. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/adminlist/config.go +53 -0
  22. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/adminlist/config_test.go +224 -0
  23. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/authorizer.go +49 -0
  24. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/controller.go +30 -0
  25. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/conv/casbin_converter.go +107 -0
  26. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/mock_authorizer.go +249 -0
  27. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/mock_controller.go +659 -0
  28. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/types.go +606 -0
  29. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/types_test.go +287 -0
  30. platform/dbops/binaries/weaviate-src/usecases/replica/transport.go +293 -0
  31. platform/dbops/binaries/weaviate-src/usecases/replica/transport_test.go +67 -0
  32. platform/dbops/binaries/weaviate-src/usecases/schema/alias.go +144 -0
  33. platform/dbops/binaries/weaviate-src/usecases/schema/authorization_test.go +241 -0
  34. platform/dbops/binaries/weaviate-src/usecases/schema/class.go +1009 -0
  35. platform/dbops/binaries/weaviate-src/usecases/schema/class_test.go +2338 -0
  36. platform/dbops/binaries/weaviate-src/usecases/schema/executor.go +370 -0
  37. platform/dbops/binaries/weaviate-src/usecases/schema/executor_test.go +218 -0
  38. platform/dbops/binaries/weaviate-src/usecases/schema/fakes_test.go +349 -0
  39. platform/dbops/binaries/weaviate-src/usecases/schema/get_class.go +174 -0
  40. platform/dbops/binaries/weaviate-src/usecases/schema/get_class_test.go +169 -0
  41. platform/dbops/binaries/weaviate-src/usecases/schema/handler.go +302 -0
  42. platform/dbops/binaries/weaviate-src/usecases/schema/handler_test.go +403 -0
  43. platform/dbops/binaries/weaviate-src/usecases/schema/helpers_test.go +391 -0
  44. platform/dbops/binaries/weaviate-src/usecases/schema/manager.go +449 -0
  45. platform/dbops/binaries/weaviate-src/usecases/schema/migrator.go +69 -0
  46. platform/dbops/binaries/weaviate-src/usecases/schema/mock_schema_getter.go +777 -0
  47. platform/dbops/binaries/weaviate-src/usecases/schema/mock_schema_reader.go +1335 -0
  48. platform/dbops/binaries/weaviate-src/usecases/schema/parser.go +581 -0
  49. platform/dbops/binaries/weaviate-src/usecases/schema/parser_test.go +182 -0
  50. platform/dbops/binaries/weaviate-src/usecases/schema/property.go +157 -0
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/anonymous/middleware.go ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package anonymous
13
+
14
+ import (
15
+ "fmt"
16
+ "net/http"
17
+ "strings"
18
+
19
+ "github.com/go-openapi/runtime"
20
+ "github.com/weaviate/weaviate/usecases/config"
21
+ )
22
+
23
+ // Client for anonymous access
24
+ type Client struct {
25
+ config config.AnonymousAccess
26
+ apiKeyEnabled bool
27
+ oidcEnabled bool
28
+ }
29
+
30
+ // New anonymous access client. Client.Middleware can be used as a regular
31
+ // golang http-middleware
32
+ func New(cfg config.Config) *Client {
33
+ return &Client{config: cfg.Authentication.AnonymousAccess, apiKeyEnabled: cfg.Authentication.AnyApiKeyAvailable(), oidcEnabled: cfg.Authentication.OIDC.Enabled}
34
+ }
35
+
36
+ // Middleware will fail unauthenticated requests if anonymous access is
37
+ // disabled. This middleware should run after all previous middlewares.
38
+ func (c *Client) Middleware(next http.Handler) http.Handler {
39
+ if c.config.Enabled {
40
+ // Anonymous Access is allowed, this means we don't have to validate any
41
+ // further, let's just return the original middleware stack
42
+
43
+ return next
44
+ }
45
+
46
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
47
+ if hasBearerAuth(r) {
48
+ // if an OIDC-Header is present we can be sure that the OIDC
49
+ // Authenticator has already validated the token, so we don't have to do
50
+ // anything and can call the next handler.
51
+ next.ServeHTTP(w, r)
52
+ return
53
+ }
54
+
55
+ w.WriteHeader(401)
56
+ var authSchemas []string
57
+ if c.apiKeyEnabled {
58
+ authSchemas = append(authSchemas, "API-keys")
59
+ }
60
+ if c.oidcEnabled {
61
+ authSchemas = append(authSchemas, "OIDC")
62
+ }
63
+
64
+ w.Write([]byte(
65
+ fmt.Sprintf(
66
+ `{"code":401,"message": "anonymous access not enabled. Please authenticate through one of the available methods: [%s]" }`, strings.Join(authSchemas, ", "),
67
+ ),
68
+ ))
69
+ })
70
+ }
71
+
72
+ func hasBearerAuth(r *http.Request) bool {
73
+ // The following logic to decide whether OIDC information is set is taken
74
+ // straight from go-swagger to make sure the decision matches:
75
+ // https://github.com/go-openapi/runtime/blob/109737172424d8a656fd1199e28c9f5cc89b0cca/security/authenticator.go#L208-L225
76
+ const prefix = "Bearer "
77
+ var token string
78
+ hdr := r.Header.Get("Authorization")
79
+ if strings.HasPrefix(hdr, prefix) {
80
+ token = strings.TrimPrefix(hdr, prefix)
81
+ }
82
+ if token == "" {
83
+ qs := r.URL.Query()
84
+ token = qs.Get("access_token")
85
+ }
86
+ //#nosec
87
+ ct, _, _ := runtime.ContentType(r.Header)
88
+ if token == "" && (ct == "application/x-www-form-urlencoded" || ct == "multipart/form-data") {
89
+ token = r.FormValue("access_token")
90
+ }
91
+ // End of go-swagger logic
92
+
93
+ return token != ""
94
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/anonymous/middleware_test.go ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package anonymous
13
+
14
+ import (
15
+ "net/http"
16
+ "net/http/httptest"
17
+ "testing"
18
+
19
+ "github.com/stretchr/testify/assert"
20
+ "github.com/weaviate/weaviate/usecases/config"
21
+ )
22
+
23
+ func Test_AnonymousMiddleware_Enabled(t *testing.T) {
24
+ // when anonymous access is enabled, we don't need to do anything and can
25
+ // safely call the next next handler
26
+
27
+ r := httptest.NewRequest("GET", "/foo", nil)
28
+ w := httptest.NewRecorder()
29
+
30
+ next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
31
+ w.WriteHeader(900)
32
+ })
33
+
34
+ cfg := config.Config{
35
+ Authentication: config.Authentication{
36
+ AnonymousAccess: config.AnonymousAccess{
37
+ Enabled: true,
38
+ },
39
+ },
40
+ }
41
+
42
+ New(cfg).Middleware(next).ServeHTTP(w, r)
43
+ response := w.Result()
44
+ defer response.Body.Close()
45
+
46
+ assert.Equal(t, response.StatusCode, 900)
47
+ }
48
+
49
+ func Test_AnonymousMiddleware_Disabled(t *testing.T) {
50
+ t.Run("when OIDC is enabled, but no token provided", func(t *testing.T) {
51
+ r := httptest.NewRequest("GET", "/foo", nil)
52
+ w := httptest.NewRecorder()
53
+
54
+ next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
55
+ w.WriteHeader(900)
56
+ })
57
+
58
+ cfg := config.Config{
59
+ Authentication: config.Authentication{
60
+ AnonymousAccess: config.AnonymousAccess{
61
+ Enabled: false,
62
+ },
63
+ OIDC: config.OIDC{
64
+ Enabled: true,
65
+ },
66
+ },
67
+ }
68
+
69
+ New(cfg).Middleware(next).ServeHTTP(w, r)
70
+ response := w.Result()
71
+ defer response.Body.Close()
72
+
73
+ assert.Equal(t, response.StatusCode, 401)
74
+ })
75
+
76
+ t.Run("when OIDC is enabled, and a Bearer Header provided", func(t *testing.T) {
77
+ r := httptest.NewRequest("GET", "/foo", nil)
78
+ r.Header.Add("Authorization", "Bearer foo")
79
+ w := httptest.NewRecorder()
80
+
81
+ next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
82
+ w.WriteHeader(900)
83
+ })
84
+
85
+ cfg := config.Config{
86
+ Authentication: config.Authentication{
87
+ AnonymousAccess: config.AnonymousAccess{
88
+ Enabled: false,
89
+ },
90
+ OIDC: config.OIDC{
91
+ Enabled: true,
92
+ },
93
+ },
94
+ }
95
+
96
+ New(cfg).Middleware(next).ServeHTTP(w, r)
97
+ response := w.Result()
98
+ defer response.Body.Close()
99
+
100
+ assert.Equal(t, response.StatusCode, 900)
101
+ })
102
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/client.go ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package apikey
13
+
14
+ import (
15
+ "crypto/sha256"
16
+ "crypto/subtle"
17
+ "fmt"
18
+
19
+ "github.com/weaviate/weaviate/entities/models"
20
+ "github.com/weaviate/weaviate/usecases/config"
21
+ )
22
+
23
+ type StaticApiKey struct {
24
+ config config.StaticAPIKey
25
+ weakKeyStorage [][sha256.Size]byte
26
+ }
27
+
28
+ func NewStatic(cfg config.Config) (*StaticApiKey, error) {
29
+ c := &StaticApiKey{
30
+ config: cfg.Authentication.APIKey,
31
+ }
32
+
33
+ if err := c.validateConfig(); err != nil {
34
+ return nil, fmt.Errorf("invalid apikey config: %w", err)
35
+ }
36
+
37
+ c.parseKeys()
38
+
39
+ return c, nil
40
+ }
41
+
42
+ func (c *StaticApiKey) parseKeys() {
43
+ c.weakKeyStorage = make([][sha256.Size]byte, len(c.config.AllowedKeys))
44
+ for i, rawKey := range c.config.AllowedKeys {
45
+ c.weakKeyStorage[i] = sha256.Sum256([]byte(rawKey))
46
+ }
47
+ }
48
+
49
+ func (c *StaticApiKey) validateConfig() error {
50
+ if !c.config.Enabled {
51
+ // don't validate if this scheme isn't used
52
+ return nil
53
+ }
54
+
55
+ if len(c.config.AllowedKeys) < 1 {
56
+ return fmt.Errorf("need at least one valid allowed key")
57
+ }
58
+
59
+ for _, key := range c.config.AllowedKeys {
60
+ if len(key) == 0 {
61
+ return fmt.Errorf("keys cannot have length 0")
62
+ }
63
+ }
64
+
65
+ if len(c.config.Users) < 1 {
66
+ return fmt.Errorf("need at least one user")
67
+ }
68
+
69
+ for _, key := range c.config.Users {
70
+ if len(key) == 0 {
71
+ return fmt.Errorf("users cannot have length 0")
72
+ }
73
+ }
74
+
75
+ if len(c.config.Users) > 1 && len(c.config.Users) != len(c.config.AllowedKeys) {
76
+ return fmt.Errorf("length of users and keys must match, alternatively provide single user for all keys")
77
+ }
78
+
79
+ return nil
80
+ }
81
+
82
+ func (c *StaticApiKey) ValidateAndExtract(token string, scopes []string) (*models.Principal, error) {
83
+ tokenPos, ok := c.isTokenAllowed(token)
84
+ if !ok {
85
+ return nil, fmt.Errorf("invalid api key")
86
+ }
87
+
88
+ return &models.Principal{
89
+ Username: c.getUser(tokenPos), UserType: models.UserTypeInputDb,
90
+ }, nil
91
+ }
92
+
93
+ func (c *StaticApiKey) isTokenAllowed(token string) (int, bool) {
94
+ tokenHash := sha256.Sum256([]byte(token))
95
+
96
+ for i, allowed := range c.weakKeyStorage {
97
+ if subtle.ConstantTimeCompare(tokenHash[:], allowed[:]) == 1 {
98
+ return i, true
99
+ }
100
+ }
101
+
102
+ return -1, false
103
+ }
104
+
105
+ func (c *StaticApiKey) getUser(pos int) string {
106
+ // passed validation guarantees that one of those options will work
107
+ if pos >= len(c.config.Users) {
108
+ return c.config.Users[0]
109
+ }
110
+
111
+ return c.config.Users[pos]
112
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/client_test.go ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package apikey
13
+
14
+ import (
15
+ "testing"
16
+
17
+ "github.com/stretchr/testify/assert"
18
+ "github.com/stretchr/testify/require"
19
+ "github.com/weaviate/weaviate/usecases/config"
20
+ )
21
+
22
+ func Test_APIKeyClient(t *testing.T) {
23
+ type test struct {
24
+ name string
25
+ config config.StaticAPIKey
26
+ expectConfigErr bool
27
+ expectConfigErrMsg string
28
+ validate func(t *testing.T, c *StaticApiKey)
29
+ }
30
+
31
+ tests := []test{
32
+ {
33
+ name: "not enabled",
34
+ config: config.StaticAPIKey{
35
+ Enabled: false,
36
+ },
37
+ expectConfigErr: false,
38
+ },
39
+ {
40
+ name: "key, but no user",
41
+ config: config.StaticAPIKey{
42
+ Enabled: true,
43
+ AllowedKeys: []string{"secret-key"},
44
+ Users: []string{},
45
+ },
46
+ expectConfigErr: true,
47
+ expectConfigErrMsg: "need at least one user",
48
+ },
49
+ {
50
+ name: "zero length key",
51
+ config: config.StaticAPIKey{
52
+ Enabled: true,
53
+ AllowedKeys: []string{""},
54
+ Users: []string{"gooduser"},
55
+ },
56
+ expectConfigErr: true,
57
+ expectConfigErrMsg: "keys cannot have length 0",
58
+ },
59
+ {
60
+ name: "user, but no key",
61
+ config: config.StaticAPIKey{
62
+ Enabled: true,
63
+ AllowedKeys: []string{},
64
+ Users: []string{"johnnyBeAllowed"},
65
+ },
66
+ expectConfigErr: true,
67
+ expectConfigErrMsg: "need at least one valid allowed key",
68
+ },
69
+ {
70
+ name: "zero length user",
71
+ config: config.StaticAPIKey{
72
+ Enabled: true,
73
+ AllowedKeys: []string{"secret-key"},
74
+ Users: []string{""},
75
+ },
76
+ expectConfigErr: true,
77
+ expectConfigErrMsg: "users cannot have length 0",
78
+ },
79
+ {
80
+ name: "one user, one key",
81
+ config: config.StaticAPIKey{
82
+ Enabled: true,
83
+ AllowedKeys: []string{"secret-key"},
84
+ Users: []string{"mrRoboto"},
85
+ },
86
+ expectConfigErr: false,
87
+ validate: func(t *testing.T, c *StaticApiKey) {
88
+ p, err := c.ValidateAndExtract("secret-key", nil)
89
+ require.Nil(t, err)
90
+ assert.Equal(t, "mrRoboto", p.Username)
91
+
92
+ _, err = c.ValidateAndExtract("", nil)
93
+ require.NotNil(t, err)
94
+ _, err = c.ValidateAndExtract("other-key", nil)
95
+ require.NotNil(t, err)
96
+ },
97
+ },
98
+ {
99
+ // this is allowed, this means that all keys point to the same user for
100
+ // authZ purposes
101
+ name: "one user, multiple keys",
102
+ config: config.StaticAPIKey{
103
+ Enabled: true,
104
+ AllowedKeys: []string{"secret-key", "another-secret-key", "third-key"},
105
+ Users: []string{"jane"},
106
+ },
107
+ expectConfigErr: false,
108
+ validate: func(t *testing.T, c *StaticApiKey) {
109
+ p, err := c.ValidateAndExtract("secret-key", nil)
110
+ require.Nil(t, err)
111
+ assert.Equal(t, "jane", p.Username)
112
+
113
+ p, err = c.ValidateAndExtract("another-secret-key", nil)
114
+ require.Nil(t, err)
115
+ assert.Equal(t, "jane", p.Username)
116
+
117
+ p, err = c.ValidateAndExtract("third-key", nil)
118
+ require.Nil(t, err)
119
+ assert.Equal(t, "jane", p.Username)
120
+
121
+ _, err = c.ValidateAndExtract("", nil)
122
+ require.NotNil(t, err)
123
+ _, err = c.ValidateAndExtract("other-key", nil)
124
+ require.NotNil(t, err)
125
+ },
126
+ },
127
+ {
128
+ // this is allowed, this means that each key at pos i points to user at
129
+ // pos i for authZ purposes
130
+ name: "multiple user, multiple keys",
131
+ config: config.StaticAPIKey{
132
+ Enabled: true,
133
+ AllowedKeys: []string{"secret-key", "another-secret-key", "third-key"},
134
+ Users: []string{"jane", "jessica", "jennifer"},
135
+ },
136
+ expectConfigErr: false,
137
+ validate: func(t *testing.T, c *StaticApiKey) {
138
+ p, err := c.ValidateAndExtract("secret-key", nil)
139
+ require.Nil(t, err)
140
+ assert.Equal(t, "jane", p.Username)
141
+
142
+ p, err = c.ValidateAndExtract("another-secret-key", nil)
143
+ require.Nil(t, err)
144
+ assert.Equal(t, "jessica", p.Username)
145
+
146
+ p, err = c.ValidateAndExtract("third-key", nil)
147
+ require.Nil(t, err)
148
+ assert.Equal(t, "jennifer", p.Username)
149
+
150
+ _, err = c.ValidateAndExtract("", nil)
151
+ require.NotNil(t, err)
152
+ _, err = c.ValidateAndExtract("other-key", nil)
153
+ require.NotNil(t, err)
154
+ },
155
+ },
156
+ {
157
+ // this is invalid, the keys cannot be mapped to the users
158
+ name: "2 users, 3 keys",
159
+ config: config.StaticAPIKey{
160
+ Enabled: true,
161
+ AllowedKeys: []string{"secret-key", "another-secret-key", "third-key"},
162
+ Users: []string{"jane", "jessica"},
163
+ },
164
+ expectConfigErr: true,
165
+ expectConfigErrMsg: "length of users and keys must match, alternatively provide single user for all keys",
166
+ },
167
+ }
168
+
169
+ for _, test := range tests {
170
+ t.Run(test.name, func(t *testing.T) {
171
+ c, err := NewStatic(config.Config{
172
+ Authentication: config.Authentication{APIKey: test.config},
173
+ })
174
+
175
+ if test.expectConfigErr {
176
+ require.NotNil(t, err)
177
+ assert.Contains(t, err.Error(), test.expectConfigErrMsg)
178
+ return
179
+ }
180
+
181
+ if test.validate != nil {
182
+ test.validate(t, c)
183
+ }
184
+ })
185
+ }
186
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/db_user_test.go ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package apikey
13
+
14
+ import (
15
+ "crypto/sha256"
16
+ "fmt"
17
+ "strconv"
18
+ "sync"
19
+ "testing"
20
+ "time"
21
+
22
+ "github.com/weaviate/weaviate/entities/models"
23
+
24
+ "github.com/sirupsen/logrus/hooks/test"
25
+
26
+ "github.com/weaviate/weaviate/usecases/auth/authentication/apikey/keys"
27
+
28
+ "github.com/stretchr/testify/require"
29
+ )
30
+
31
+ var log, _ = test.NewNullLogger()
32
+
33
+ func TestDynUserConcurrency(t *testing.T) {
34
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
35
+ require.NoError(t, err)
36
+
37
+ numUsers := 10
38
+
39
+ wg := sync.WaitGroup{}
40
+ wg.Add(numUsers)
41
+
42
+ userNames := make([]string, 0, numUsers)
43
+ for i := 0; i < numUsers; i++ {
44
+ userName := fmt.Sprintf("user%v", i)
45
+ go func() {
46
+ err := dynUsers.CreateUser(userName, "something", userName, "", time.Now())
47
+ require.NoError(t, err)
48
+ wg.Done()
49
+ }()
50
+ userNames = append(userNames, userName)
51
+ }
52
+ wg.Wait()
53
+
54
+ users, err := dynUsers.GetUsers(userNames...)
55
+ require.NoError(t, err)
56
+ require.Equal(t, len(userNames), len(users))
57
+ }
58
+
59
+ func TestConcurrentValidate(t *testing.T) {
60
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
61
+ require.NoError(t, err)
62
+ userId1 := "id"
63
+ userId2 := "id2"
64
+
65
+ apiKey, hash, identifier, err := keys.CreateApiKeyAndHash()
66
+ require.NoError(t, err)
67
+
68
+ require.NoError(t, dynUsers.CreateUser(userId1, hash, identifier, "", time.Now()))
69
+
70
+ apiKey2, hash2, identifier2, err := keys.CreateApiKeyAndHash()
71
+ require.NoError(t, err)
72
+
73
+ require.NoError(t, dynUsers.CreateUser(userId2, hash2, identifier2, "", time.Now()))
74
+
75
+ randomKey, _, err := keys.DecodeApiKey(apiKey)
76
+ require.NoError(t, err)
77
+ randomKey2, _, err := keys.DecodeApiKey(apiKey2)
78
+ require.NoError(t, err)
79
+ start := time.Now()
80
+ wg := sync.WaitGroup{}
81
+ for i := 0; i < 10; i++ {
82
+ wg.Add(2)
83
+ go func() {
84
+ _, err := dynUsers.ValidateAndExtract(randomKey, identifier)
85
+ require.NoError(t, err)
86
+ wg.Done()
87
+ }()
88
+
89
+ go func() {
90
+ _, err := dynUsers.ValidateAndExtract(randomKey2, identifier2)
91
+ require.NoError(t, err)
92
+ wg.Done()
93
+ }()
94
+ }
95
+ wg.Wait()
96
+
97
+ users, err := dynUsers.GetUsers(userId1)
98
+ require.NoError(t, err)
99
+ user := users[userId1]
100
+ require.Less(t, start, user.LastUsedAt)
101
+ }
102
+
103
+ func TestDynUserTestSlowAfterWeakHash(t *testing.T) {
104
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
105
+ require.NoError(t, err)
106
+ userId := "id"
107
+
108
+ apiKey, hash, identifier, err := keys.CreateApiKeyAndHash()
109
+ require.NoError(t, err)
110
+
111
+ require.NoError(t, dynUsers.CreateUser(userId, hash, identifier, "", time.Now()))
112
+
113
+ randomKey, _, err := keys.DecodeApiKey(apiKey)
114
+ require.NoError(t, err)
115
+
116
+ _, ok := dynUsers.memoryOnlyData.weakKeyStorageById[userId]
117
+ require.False(t, ok)
118
+
119
+ startSlow := time.Now()
120
+ _, err = dynUsers.ValidateAndExtract(randomKey, identifier)
121
+ require.NoError(t, err)
122
+ tookSlow := time.Since(startSlow)
123
+
124
+ _, ok = dynUsers.memoryOnlyData.weakKeyStorageById[userId]
125
+ require.True(t, ok)
126
+
127
+ startFast := time.Now()
128
+ _, err = dynUsers.ValidateAndExtract(randomKey, identifier)
129
+ require.NoError(t, err)
130
+ tookFast := time.Since(startFast)
131
+ require.Less(t, tookFast, tookSlow)
132
+ }
133
+
134
+ func TestUpdateUser(t *testing.T) {
135
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
136
+ require.NoError(t, err)
137
+ userId := "id"
138
+
139
+ apiKey, hash, oldIdentifier, err := keys.CreateApiKeyAndHash()
140
+ require.NoError(t, err)
141
+
142
+ require.NoError(t, dynUsers.CreateUser(userId, hash, oldIdentifier, "", time.Now()))
143
+
144
+ // login works
145
+ randomKeyOld, _, err := keys.DecodeApiKey(apiKey)
146
+ require.NoError(t, err)
147
+
148
+ principal, err := dynUsers.ValidateAndExtract(randomKeyOld, oldIdentifier)
149
+ require.NoError(t, err)
150
+ require.NotNil(t, principal)
151
+
152
+ // update key and check that original key does not work, but new one does
153
+ apiKeyNew, hashNew, newIdentifier, err := keys.CreateApiKeyAndHash()
154
+ require.NoError(t, err)
155
+ require.NoError(t, dynUsers.RotateKey(userId, apiKeyNew[:3], hashNew, oldIdentifier, newIdentifier))
156
+
157
+ randomKeyNew, _, err := keys.DecodeApiKey(apiKeyNew)
158
+ require.NoError(t, err)
159
+
160
+ principal, err = dynUsers.ValidateAndExtract(randomKeyOld, oldIdentifier)
161
+ require.Error(t, err)
162
+ require.Nil(t, principal)
163
+
164
+ // first login with new key is slow again, second is fast
165
+ startSlow := time.Now()
166
+ principal, err = dynUsers.ValidateAndExtract(randomKeyNew, newIdentifier)
167
+ require.NoError(t, err)
168
+ require.NotNil(t, principal)
169
+ tookSlow := time.Since(startSlow)
170
+
171
+ startFast := time.Now()
172
+ _, err = dynUsers.ValidateAndExtract(randomKeyNew, newIdentifier)
173
+ require.NoError(t, err)
174
+ tookFast := time.Since(startFast)
175
+ require.Less(t, tookFast, tookSlow)
176
+ }
177
+
178
+ func TestSnapShotAndRestore(t *testing.T) {
179
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
180
+ require.NoError(t, err)
181
+
182
+ userId1 := "id-1"
183
+ userId2 := "id-2"
184
+
185
+ apiKey, hash, identifier, err := keys.CreateApiKeyAndHash()
186
+ require.NoError(t, err)
187
+
188
+ require.NoError(t, dynUsers.CreateUser(userId1, hash, identifier, "", time.Now()))
189
+ login1, _, err := keys.DecodeApiKey(apiKey)
190
+ require.NoError(t, err)
191
+
192
+ apiKey2, hash2, identifier2, err := keys.CreateApiKeyAndHash()
193
+ require.NoError(t, err)
194
+ require.NoError(t, dynUsers.CreateUser(userId2, hash2, identifier2, "", time.Now()))
195
+ login2, _, err := keys.DecodeApiKey(apiKey2)
196
+ require.NoError(t, err)
197
+
198
+ // first login is slow, second is fast
199
+ startSlow := time.Now()
200
+ principal, err := dynUsers.ValidateAndExtract(login1, identifier)
201
+ require.NoError(t, err)
202
+ require.NotNil(t, principal)
203
+ tookSlow := time.Since(startSlow)
204
+
205
+ startFast := time.Now()
206
+ _, err = dynUsers.ValidateAndExtract(login1, identifier)
207
+ require.NoError(t, err)
208
+ tookFast := time.Since(startFast)
209
+ require.Less(t, tookFast, tookSlow)
210
+
211
+ principal2, err := dynUsers.ValidateAndExtract(login2, identifier2)
212
+ require.NoError(t, err)
213
+ require.NotNil(t, principal2)
214
+
215
+ require.NoError(t, dynUsers.DeactivateUser(userId2, true))
216
+
217
+ // create snapshot and restore to an empty new DBUser struct
218
+ snapShot, err := dynUsers.Snapshot()
219
+ require.NoError(t, err)
220
+
221
+ dynUsers2, err := NewDBUser(t.TempDir(), true, log)
222
+ require.NoError(t, err)
223
+ require.NoError(t, dynUsers2.Restore(snapShot))
224
+
225
+ // content should be identical:
226
+ // - all users and their status present
227
+ // - taking a new snapshot should be identical
228
+ // - only weak hash is missing => first login should be slow again
229
+ snapshot2, err := dynUsers2.Snapshot()
230
+ require.NoError(t, err)
231
+ require.Equal(t, snapShot, snapshot2)
232
+
233
+ startAfterRestoreSlow := time.Now()
234
+ _, err = dynUsers2.ValidateAndExtract(login1, identifier)
235
+ require.NoError(t, err)
236
+ tookAfterRestore := time.Since(startAfterRestoreSlow)
237
+ require.Less(t, tookFast, tookAfterRestore)
238
+
239
+ _, err = dynUsers2.ValidateAndExtract(login2, identifier2)
240
+ require.Error(t, err)
241
+
242
+ apiKey3, hash3, identifier3, err := keys.CreateApiKeyAndHash()
243
+ require.NoError(t, err)
244
+ require.NoError(t, dynUsers2.RotateKey(userId2, apiKey3[:3], hash3, identifier2, identifier3))
245
+
246
+ login3, _, err := keys.DecodeApiKey(apiKey3)
247
+ require.NoError(t, err)
248
+ _, err = dynUsers2.ValidateAndExtract(login3, identifier3)
249
+ require.Error(t, err)
250
+ }
251
+
252
+ func TestSuspendAfterDelete(t *testing.T) {
253
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
254
+ require.NoError(t, err)
255
+ userId := "id"
256
+
257
+ _, hash, identifier, err := keys.CreateApiKeyAndHash()
258
+ require.NoError(t, err)
259
+
260
+ require.NoError(t, dynUsers.CreateUser(userId, hash, identifier, "", time.Now()))
261
+
262
+ users, err := dynUsers.GetUsers(userId)
263
+ require.NoError(t, err)
264
+ require.Contains(t, users, userId)
265
+ require.Len(t, users, 1)
266
+
267
+ require.NoError(t, dynUsers.DeleteUser(userId))
268
+
269
+ require.Error(t, dynUsers.DeactivateUser(userId, false))
270
+ require.Error(t, dynUsers.ActivateUser(userId))
271
+ require.Error(t, dynUsers.RotateKey(userId, "", "", "", ""))
272
+ require.Error(t, dynUsers.ActivateUser(userId))
273
+ }
274
+
275
+ func TestLastUsedTime(t *testing.T) {
276
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
277
+ require.NoError(t, err)
278
+ userId := "user"
279
+
280
+ start := time.Now()
281
+
282
+ apiKey, hash, identifier, err := keys.CreateApiKeyAndHash()
283
+ require.NoError(t, err)
284
+
285
+ require.NoError(t, dynUsers.CreateUser(userId, hash, identifier, "", time.Now()))
286
+
287
+ user, err := dynUsers.GetUsers(userId)
288
+ require.NoError(t, err)
289
+ require.Less(t, user[userId].LastUsedAt, start) // no usage yet
290
+
291
+ login, _, err := keys.DecodeApiKey(apiKey)
292
+ require.NoError(t, err)
293
+ _, err = dynUsers.ValidateAndExtract(login, identifier)
294
+ require.NoError(t, err)
295
+
296
+ user, err = dynUsers.GetUsers(userId)
297
+ require.NoError(t, err)
298
+ require.Less(t, start, user[userId].LastUsedAt) // was just used
299
+ require.Less(t, user[userId].LastUsedAt, time.Now())
300
+ lastUsedTime := user[userId].LastUsedAt
301
+
302
+ // try to update with older timestamp => no effect
303
+ dynUsers.UpdateLastUsedTimestamp(map[string]time.Time{userId: start})
304
+ user, err = dynUsers.GetUsers(userId)
305
+ require.NoError(t, err)
306
+
307
+ require.Equal(t, user[userId].LastUsedAt, lastUsedTime)
308
+
309
+ // update with newer timestamp (that another node has seen)
310
+ updateTime := time.Now()
311
+ dynUsers.UpdateLastUsedTimestamp(map[string]time.Time{userId: updateTime})
312
+ user, err = dynUsers.GetUsers(userId)
313
+ require.NoError(t, err)
314
+
315
+ require.Equal(t, user[userId].LastUsedAt, updateTime)
316
+ }
317
+
318
+ func TestImportingAndSuspendingStaticKeys(t *testing.T) {
319
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
320
+ require.NoError(t, err)
321
+
322
+ createdAt := time.Now()
323
+ userId := "user"
324
+ importedApiKey := "importedApiKey"
325
+ require.NoError(t, dynUsers.CreateUserWithKey(userId, importedApiKey[:3], sha256.Sum256([]byte(importedApiKey)), createdAt))
326
+
327
+ principal, err := dynUsers.ValidateImportedKey(importedApiKey)
328
+ require.NoError(t, err)
329
+ require.NotNil(t, principal)
330
+ require.Equal(t, userId, principal.Username)
331
+
332
+ require.NoError(t, dynUsers.DeactivateUser(userId, true))
333
+
334
+ principal, err = dynUsers.ValidateImportedKey(importedApiKey)
335
+ require.Error(t, err)
336
+ require.Nil(t, principal)
337
+
338
+ require.NoError(t, dynUsers.ActivateUser(userId))
339
+ principal, err = dynUsers.ValidateImportedKey(importedApiKey)
340
+ require.Error(t, err)
341
+ require.Nil(t, principal)
342
+
343
+ apiKey, hash, identifier, err := keys.CreateApiKeyAndHash()
344
+ require.NoError(t, err)
345
+ require.NoError(t, dynUsers.RotateKey(userId, apiKey[:3], hash, "imported_"+userId, identifier))
346
+
347
+ login, _, err := keys.DecodeApiKey(apiKey)
348
+ require.NoError(t, err)
349
+ _, err = dynUsers.ValidateAndExtract(login, identifier)
350
+ require.NoError(t, err)
351
+
352
+ principal, err = dynUsers.ValidateImportedKey(importedApiKey)
353
+ require.NoError(t, err) // error is only returned if key is deactivated
354
+ require.Nil(t, principal)
355
+ }
356
+
357
+ func TestImportingStaticKeys(t *testing.T) {
358
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
359
+ require.NoError(t, err)
360
+ createdAt := time.Now()
361
+ for i := 0; i < 10; i++ {
362
+ userId := "user" + strconv.Itoa(i)
363
+ importedApiKey := "importedApiKey" + strconv.Itoa(i)
364
+ require.NoError(t, dynUsers.CreateUserWithKey(userId, importedApiKey[:3], sha256.Sum256([]byte(importedApiKey)), createdAt))
365
+
366
+ principal, err := dynUsers.ValidateImportedKey(importedApiKey)
367
+ require.NoError(t, err)
368
+ require.NotNil(t, principal)
369
+ require.Equal(t, userId, principal.Username)
370
+ require.Equal(t, principal.UserType, models.UserTypeInputDb)
371
+
372
+ require.True(t, dynUsers.IsBlockedKey(importedApiKey))
373
+ }
374
+
375
+ for i := 0; i < 10; i++ {
376
+ userId := "user" + strconv.Itoa(i)
377
+ importedApiKey := "importedApiKey" + strconv.Itoa(i)
378
+
379
+ users, err := dynUsers.GetUsers(userId)
380
+ require.NoError(t, err)
381
+ require.Len(t, users, 1)
382
+ user, ok := users[userId]
383
+ require.True(t, ok)
384
+ require.Equal(t, user.Id, userId)
385
+ require.Equal(t, user.InternalIdentifier, "imported_"+userId)
386
+ require.Equal(t, user.CreatedAt, createdAt)
387
+ require.True(t, user.ImportedWithKey)
388
+
389
+ apiKey, hash, identifier, err := keys.CreateApiKeyAndHash()
390
+ require.NoError(t, err)
391
+ require.NoError(t, dynUsers.RotateKey(userId, apiKey[:3], hash, "imported_"+userId, identifier))
392
+
393
+ login, _, err := keys.DecodeApiKey(apiKey)
394
+ require.NoError(t, err)
395
+ _, err = dynUsers.ValidateAndExtract(login, identifier)
396
+ require.NoError(t, err)
397
+
398
+ users, err = dynUsers.GetUsers(userId)
399
+ require.NoError(t, err)
400
+ require.Len(t, users, 1)
401
+ user, ok = users[userId]
402
+ require.True(t, ok)
403
+ require.Equal(t, user.Id, userId)
404
+ require.Equal(t, user.InternalIdentifier, identifier)
405
+ require.Equal(t, user.CreatedAt, createdAt)
406
+ require.False(t, user.ImportedWithKey)
407
+
408
+ require.True(t, dynUsers.IsBlockedKey(importedApiKey))
409
+
410
+ }
411
+ }
412
+
413
+ func TestImportingStaticKeysWithTime(t *testing.T) {
414
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
415
+ require.NoError(t, err)
416
+ createdAt := time.Now().Add(-time.Hour)
417
+
418
+ importedApiKey := "importedApiKey"
419
+ userId := "user"
420
+ require.NoError(t, dynUsers.CreateUserWithKey(userId, importedApiKey[:3], sha256.Sum256([]byte(importedApiKey)), createdAt))
421
+
422
+ users, err := dynUsers.GetUsers(userId)
423
+ require.NoError(t, err)
424
+ require.Len(t, users, 1)
425
+ user, ok := users[userId]
426
+ require.True(t, ok)
427
+ require.Equal(t, user.CreatedAt, createdAt)
428
+ }
429
+
430
+ func TestSnapshotRestoreEmpty(t *testing.T) {
431
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
432
+ require.NoError(t, err)
433
+ userId := "user"
434
+
435
+ _, hash, identifier, err := keys.CreateApiKeyAndHash()
436
+ require.NoError(t, err)
437
+
438
+ require.NoError(t, dynUsers.CreateUser(userId, hash, identifier, "", time.Now()))
439
+ user, err := dynUsers.GetUsers(userId)
440
+ require.NoError(t, err)
441
+ require.Equal(t, user[userId].Id, userId)
442
+
443
+ err = dynUsers.Restore([]byte{})
444
+ require.NoError(t, err)
445
+
446
+ // nothing overwritten
447
+ user, err = dynUsers.GetUsers(userId)
448
+ require.NoError(t, err)
449
+ require.Equal(t, user[userId].Id, userId)
450
+ }
451
+
452
+ func TestRestoreInvalidData(t *testing.T) {
453
+ dynUsers, err := NewDBUser(t.TempDir(), true, log)
454
+ require.NoError(t, err)
455
+
456
+ require.Error(t, dynUsers.Restore([]byte("invalid json")))
457
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/db_users.go ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package apikey
13
+
14
+ import (
15
+ "crypto/sha256"
16
+ "crypto/subtle"
17
+ "encoding/json"
18
+ "errors"
19
+ "fmt"
20
+ "os"
21
+ "path/filepath"
22
+ "sync"
23
+ "time"
24
+
25
+ "github.com/sirupsen/logrus"
26
+ enterrors "github.com/weaviate/weaviate/entities/errors"
27
+
28
+ "github.com/alexedwards/argon2id"
29
+
30
+ "github.com/weaviate/weaviate/entities/models"
31
+ )
32
+
33
+ const (
34
+ SnapshotVersion = 0
35
+ FileName = "users.json"
36
+ UserNameMaxLength = 128
37
+ UserNameRegexCore = `[A-Za-z][-_0-9A-Za-z@.]{0,128}`
38
+ )
39
+
40
+ type DBUsers interface {
41
+ CreateUser(userId, secureHash, userIdentifier, apiKeyFirstLetters string, createdAt time.Time) error
42
+ CreateUserWithKey(userId, apiKeyFirstLetters string, weakHash [sha256.Size]byte, createdAt time.Time) error
43
+ DeleteUser(userId string) error
44
+ ActivateUser(userId string) error
45
+ DeactivateUser(userId string, revokeKey bool) error
46
+ GetUsers(userIds ...string) (map[string]*User, error)
47
+ RotateKey(userId, apiKeyFirstLetters, secureHash, oldIdentifier, newIdentifier string) error
48
+ CheckUserIdentifierExists(userIdentifier string) (bool, error)
49
+ }
50
+
51
+ type User struct {
52
+ sync.RWMutex
53
+ Id string
54
+ Active bool
55
+ InternalIdentifier string
56
+ ApiKeyFirstLetters string
57
+ CreatedAt time.Time
58
+ LastUsedAt time.Time
59
+ ImportedWithKey bool
60
+ }
61
+
62
+ type DBUser struct {
63
+ lock *sync.RWMutex
64
+ weakHashLock *sync.RWMutex
65
+ data dbUserdata
66
+ memoryOnlyData memoryOnlyData
67
+ path string
68
+ enabled bool
69
+ }
70
+
71
+ type DBUserSnapshot struct {
72
+ Data dbUserdata
73
+ Version int
74
+ }
75
+
76
+ type dbUserdata struct {
77
+ SecureKeyStorageById map[string]string
78
+ IdentifierToId map[string]string
79
+ IdToIdentifier map[string]string
80
+ Users map[string]*User
81
+ UserKeyRevoked map[string]struct{}
82
+ ImportedApiKeysWeakHash map[string][sha256.Size]byte
83
+ }
84
+
85
+ type memoryOnlyData struct {
86
+ weakKeyStorageById map[string][sha256.Size]byte
87
+ // imported keys from static users should not work after key rotation, eg the following scenario
88
+ // - import user with "key"
89
+ // - login works when using "key" through dynamic users
90
+ // - key rotation "key" => "new-key"
91
+ // - login works when using "new-key" through dynamic users
92
+ // - login using "key" is blocked and does not reach static user config where the old key is still present
93
+ //
94
+ // Note that this will NOT be persisted and we expect that the static user configuration does not contain "key" anymore
95
+ // on the next restart
96
+ importedApiKeysBlocked [][sha256.Size]byte
97
+ }
98
+
99
+ func NewDBUser(path string, enabled bool, logger logrus.FieldLogger) (*DBUser, error) {
100
+ fullpath := fmt.Sprintf("%s/raft/db_users/", path)
101
+ err := createStorage(fullpath + FileName)
102
+ if err != nil {
103
+ return nil, err
104
+ }
105
+ existingData, err := ReadFile(fullpath + FileName)
106
+ if err != nil {
107
+ return nil, err
108
+ }
109
+ snapshot := DBUserSnapshot{}
110
+ if len(existingData) > 0 {
111
+ if err := json.Unmarshal(existingData, &snapshot); err != nil {
112
+ return nil, err
113
+ }
114
+ }
115
+
116
+ if snapshot.Data.SecureKeyStorageById == nil {
117
+ snapshot.Data.SecureKeyStorageById = make(map[string]string)
118
+ }
119
+ if snapshot.Data.IdentifierToId == nil {
120
+ snapshot.Data.IdentifierToId = make(map[string]string)
121
+ }
122
+ if snapshot.Data.IdToIdentifier == nil {
123
+ snapshot.Data.IdToIdentifier = make(map[string]string)
124
+ }
125
+ if snapshot.Data.Users == nil {
126
+ snapshot.Data.Users = make(map[string]*User)
127
+ }
128
+ if snapshot.Data.UserKeyRevoked == nil {
129
+ snapshot.Data.UserKeyRevoked = make(map[string]struct{})
130
+ }
131
+
132
+ if snapshot.Data.ImportedApiKeysWeakHash == nil {
133
+ snapshot.Data.ImportedApiKeysWeakHash = make(map[string][sha256.Size]byte)
134
+ }
135
+
136
+ dbUsers := &DBUser{
137
+ path: fullpath,
138
+ lock: &sync.RWMutex{},
139
+ weakHashLock: &sync.RWMutex{},
140
+ data: snapshot.Data,
141
+ memoryOnlyData: memoryOnlyData{
142
+ weakKeyStorageById: make(map[string][sha256.Size]byte),
143
+ importedApiKeysBlocked: make([][sha256.Size]byte, 0),
144
+ },
145
+ enabled: enabled,
146
+ }
147
+
148
+ // we save every change to file after a request is done, EXCEPT the lastUsedAt time as we do not want to write to a
149
+ // file with every request.
150
+ // This information is not terribly important (besides WCD UX), so it does not matter much if we very rarely loose
151
+ // some information here. This info will also be written on shutdown so the only loss of information occurs with
152
+ // OOM or similar.
153
+ if enabled {
154
+ enterrors.GoWrapper(func() {
155
+ ticker := time.NewTicker(1 * time.Minute)
156
+ for range ticker.C {
157
+ func() {
158
+ dbUsers.lock.RLock()
159
+ defer dbUsers.lock.RUnlock()
160
+ err := dbUsers.storeToFile()
161
+ if err != nil {
162
+ logger.WithField("action", "db_users_write_to_file").
163
+ WithField("error", err).
164
+ Warn("db users file not written")
165
+ }
166
+ }()
167
+ }
168
+ }, logger)
169
+ }
170
+
171
+ return dbUsers, nil
172
+ }
173
+
174
+ func (c *DBUser) CreateUser(userId, secureHash, userIdentifier, apiKeyFirstLetters string, createdAt time.Time) error {
175
+ c.lock.Lock()
176
+ defer c.lock.Unlock()
177
+
178
+ if len(apiKeyFirstLetters) > 3 {
179
+ return errors.New("api key first letters too long")
180
+ }
181
+
182
+ c.data.SecureKeyStorageById[userId] = secureHash
183
+ c.data.IdentifierToId[userIdentifier] = userId
184
+ c.data.IdToIdentifier[userId] = userIdentifier
185
+ c.data.Users[userId] = &User{Id: userId, Active: true, InternalIdentifier: userIdentifier, CreatedAt: createdAt, ApiKeyFirstLetters: apiKeyFirstLetters}
186
+ return c.storeToFile()
187
+ }
188
+
189
+ func (c *DBUser) CreateUserWithKey(userId, apiKeyFirstLetters string, weakHash [sha256.Size]byte, createdAt time.Time) error {
190
+ c.lock.Lock()
191
+ defer c.lock.Unlock()
192
+
193
+ if len(apiKeyFirstLetters) > 3 {
194
+ return errors.New("api key first letters too long")
195
+ }
196
+
197
+ c.data.ImportedApiKeysWeakHash[userId] = weakHash
198
+ c.memoryOnlyData.importedApiKeysBlocked = append(c.memoryOnlyData.importedApiKeysBlocked, weakHash)
199
+ c.data.Users[userId] = &User{
200
+ Id: userId,
201
+ Active: true,
202
+ InternalIdentifier: "imported_" + userId,
203
+ CreatedAt: createdAt,
204
+ ApiKeyFirstLetters: apiKeyFirstLetters,
205
+ ImportedWithKey: true,
206
+ }
207
+ return c.storeToFile()
208
+ }
209
+
210
+ func (c *DBUser) RotateKey(userId, apiKeyFirstLetters, secureHash, oldIdentifier, newIdentifier string) error {
211
+ if len(apiKeyFirstLetters) > 3 {
212
+ return errors.New("api key first letters too long")
213
+ }
214
+
215
+ c.lock.Lock()
216
+ defer c.lock.Unlock()
217
+
218
+ if _, ok := c.data.Users[userId]; !ok {
219
+ return fmt.Errorf("user %s does not exist", userId)
220
+ }
221
+
222
+ // replay of old raft commands can have these be ""
223
+ if oldIdentifier != "" && newIdentifier != "" {
224
+ c.data.IdToIdentifier[userId] = newIdentifier
225
+ delete(c.data.IdentifierToId, oldIdentifier)
226
+ c.data.IdentifierToId[newIdentifier] = userId
227
+ c.data.Users[userId].InternalIdentifier = newIdentifier
228
+ }
229
+ if c.data.Users[userId].ImportedWithKey {
230
+ c.data.Users[userId].ImportedWithKey = false
231
+ delete(c.data.ImportedApiKeysWeakHash, userId)
232
+
233
+ }
234
+
235
+ c.data.Users[userId].ApiKeyFirstLetters = apiKeyFirstLetters
236
+ c.data.SecureKeyStorageById[userId] = secureHash
237
+ delete(c.memoryOnlyData.weakKeyStorageById, userId)
238
+ delete(c.data.UserKeyRevoked, userId)
239
+ return c.storeToFile()
240
+ }
241
+
242
+ func (c *DBUser) DeleteUser(userId string) error {
243
+ c.lock.Lock()
244
+ defer c.lock.Unlock()
245
+
246
+ delete(c.data.SecureKeyStorageById, userId)
247
+ delete(c.data.IdentifierToId, c.data.IdToIdentifier[userId])
248
+ delete(c.data.IdToIdentifier, userId)
249
+ delete(c.data.Users, userId)
250
+ delete(c.memoryOnlyData.weakKeyStorageById, userId)
251
+ delete(c.data.UserKeyRevoked, userId)
252
+ delete(c.data.ImportedApiKeysWeakHash, userId)
253
+ return c.storeToFile()
254
+ }
255
+
256
+ func (c *DBUser) ActivateUser(userId string) error {
257
+ c.lock.Lock()
258
+ defer c.lock.Unlock()
259
+
260
+ if _, ok := c.data.Users[userId]; !ok {
261
+ return fmt.Errorf("user %s does not exist", userId)
262
+ }
263
+
264
+ c.data.Users[userId].Active = true
265
+ return c.storeToFile()
266
+ }
267
+
268
+ func (c *DBUser) DeactivateUser(userId string, revokeKey bool) error {
269
+ c.lock.Lock()
270
+ defer c.lock.Unlock()
271
+ if _, ok := c.data.Users[userId]; !ok {
272
+ return fmt.Errorf("user %s does not exist", userId)
273
+ }
274
+ if revokeKey {
275
+ c.data.UserKeyRevoked[userId] = struct{}{}
276
+ }
277
+ c.data.Users[userId].Active = false
278
+
279
+ return c.storeToFile()
280
+ }
281
+
282
+ func (c *DBUser) GetUsers(userIds ...string) (map[string]*User, error) {
283
+ c.lock.RLock()
284
+ defer c.lock.RUnlock()
285
+
286
+ if len(userIds) == 0 {
287
+ return c.data.Users, nil
288
+ }
289
+
290
+ users := make(map[string]*User, len(userIds))
291
+ for _, id := range userIds {
292
+ user, ok := c.data.Users[id]
293
+ if ok {
294
+ users[id] = user
295
+ }
296
+ }
297
+ return users, nil
298
+ }
299
+
300
+ func (c *DBUser) CheckUserIdentifierExists(userIdentifier string) (bool, error) {
301
+ c.lock.RLock()
302
+ defer c.lock.RUnlock()
303
+
304
+ _, ok := c.data.Users[userIdentifier]
305
+ return ok, nil
306
+ }
307
+
308
+ func (c *DBUser) UpdateLastUsedTimestamp(users map[string]time.Time) {
309
+ // RLock is fine here, we only want to avoid that c.data.Users is being changed. LastUsed has its own
310
+ // locking mechanism
311
+ c.lock.RLock()
312
+ defer c.lock.RUnlock()
313
+
314
+ for userID, lastUsed := range users {
315
+ if c.data.Users[userID].LastUsedAt.Before(lastUsed) {
316
+ c.data.Users[userID].Lock()
317
+ c.data.Users[userID].LastUsedAt = lastUsed
318
+ c.data.Users[userID].Unlock()
319
+ }
320
+ }
321
+ }
322
+
323
+ func (c *DBUser) ValidateImportedKey(token string) (*models.Principal, error) {
324
+ c.lock.RLock()
325
+ defer c.lock.RUnlock()
326
+
327
+ keyHashGiven := sha256.Sum256([]byte(token))
328
+ for userId, keyHashStored := range c.data.ImportedApiKeysWeakHash {
329
+ if subtle.ConstantTimeCompare(keyHashGiven[:], keyHashStored[:]) != 1 {
330
+ continue
331
+ }
332
+ if c.data.Users[userId] != nil && !c.data.Users[userId].Active {
333
+ return nil, fmt.Errorf("user deactivated")
334
+ }
335
+
336
+ if _, ok := c.data.UserKeyRevoked[userId]; ok {
337
+ return nil, fmt.Errorf("key is revoked")
338
+ }
339
+
340
+ // Last used time does not have to be exact. If we have multiple concurrent requests for the same
341
+ // user, only recording one of them is good enough
342
+ if c.data.Users[userId].TryLock() {
343
+ c.data.Users[userId].LastUsedAt = time.Now()
344
+ c.data.Users[userId].Unlock()
345
+ }
346
+
347
+ return &models.Principal{Username: userId, UserType: models.UserTypeInputDb}, nil
348
+ }
349
+
350
+ return nil, nil
351
+ }
352
+
353
+ func (c *DBUser) IsBlockedKey(token string) bool {
354
+ keyHashGiven := sha256.Sum256([]byte(token))
355
+ for _, keyHashStored := range c.memoryOnlyData.importedApiKeysBlocked {
356
+ if subtle.ConstantTimeCompare(keyHashGiven[:], keyHashStored[:]) == 1 {
357
+ return true
358
+ }
359
+ }
360
+ return false
361
+ }
362
+
363
+ func (c *DBUser) ValidateAndExtract(key, userIdentifier string) (*models.Principal, error) {
364
+ c.lock.RLock()
365
+ defer c.lock.RUnlock()
366
+
367
+ userId, ok := c.data.IdentifierToId[userIdentifier]
368
+ if !ok {
369
+ return nil, fmt.Errorf("invalid token")
370
+ }
371
+
372
+ secureHash, ok := c.data.SecureKeyStorageById[userId]
373
+ if !ok {
374
+ return nil, fmt.Errorf("invalid token")
375
+ }
376
+ c.weakHashLock.RLock()
377
+ weakHash, ok := c.memoryOnlyData.weakKeyStorageById[userId]
378
+ c.weakHashLock.RUnlock()
379
+ if ok {
380
+ // use the secureHash as salt for the computation of the weaker in-memory
381
+ if err := c.validateWeakHash([]byte(key+secureHash), weakHash); err != nil {
382
+ return nil, err
383
+ }
384
+ } else {
385
+ if err := c.validateStrongHash(key, secureHash, userId); err != nil {
386
+ return nil, err
387
+ }
388
+ }
389
+
390
+ if c.data.Users[userId] != nil && !c.data.Users[userId].Active {
391
+ return nil, fmt.Errorf("user deactivated")
392
+ }
393
+ if _, ok := c.data.UserKeyRevoked[userId]; ok {
394
+ return nil, fmt.Errorf("key is revoked")
395
+ }
396
+
397
+ // Last used time does not have to be exact. If we have multiple concurrent requests for the same
398
+ // user, only recording one of them is good enough
399
+ if c.data.Users[userId].TryLock() {
400
+ c.data.Users[userId].LastUsedAt = time.Now()
401
+ c.data.Users[userId].Unlock()
402
+ }
403
+
404
+ return &models.Principal{Username: userId, UserType: models.UserTypeInputDb}, nil
405
+ }
406
+
407
+ func (c *DBUser) validateWeakHash(key []byte, weakHash [32]byte) error {
408
+ keyHash := sha256.Sum256(key)
409
+ if subtle.ConstantTimeCompare(keyHash[:], weakHash[:]) != 1 {
410
+ return fmt.Errorf("invalid token")
411
+ }
412
+
413
+ return nil
414
+ }
415
+
416
+ func (c *DBUser) validateStrongHash(key, secureHash, userId string) error {
417
+ match, err := argon2id.ComparePasswordAndHash(key, secureHash)
418
+ if err != nil {
419
+ return err
420
+ }
421
+ if !match {
422
+ return fmt.Errorf("invalid token")
423
+ }
424
+ token := []byte(key + secureHash)
425
+ // avoid concurrent writes to map
426
+ weakHash := sha256.Sum256(token)
427
+
428
+ c.weakHashLock.Lock()
429
+ c.memoryOnlyData.weakKeyStorageById[userId] = weakHash
430
+ c.weakHashLock.Unlock()
431
+
432
+ return nil
433
+ }
434
+
435
+ func (c *DBUser) Snapshot() ([]byte, error) {
436
+ c.lock.Lock()
437
+ defer c.lock.Unlock()
438
+
439
+ marshal, err := json.Marshal(DBUserSnapshot{Data: c.data, Version: SnapshotVersion})
440
+ if err != nil {
441
+ return nil, err
442
+ }
443
+ return marshal, nil
444
+ }
445
+
446
+ func (c *DBUser) Restore(snapshot []byte) error {
447
+ c.lock.Lock()
448
+ defer c.lock.Unlock()
449
+
450
+ // don't overwrite with empty snapshot to avoid overwriting recovery from file
451
+ // with a non-existent db user snapshot when coming from old versions
452
+ if len(snapshot) == 0 {
453
+ return nil
454
+ }
455
+
456
+ snapshotRestore := DBUserSnapshot{}
457
+ err := json.Unmarshal(snapshot, &snapshotRestore)
458
+ if err != nil {
459
+ return err
460
+ }
461
+
462
+ if snapshotRestore.Version != SnapshotVersion {
463
+ return fmt.Errorf("invalid snapshot version")
464
+ }
465
+ c.data = snapshotRestore.Data
466
+
467
+ return nil
468
+ }
469
+
470
+ func (c *DBUser) storeToFile() error {
471
+ data, err := json.Marshal(DBUserSnapshot{Data: c.data, Version: SnapshotVersion})
472
+ if err != nil {
473
+ return err
474
+ }
475
+
476
+ tmpFile, err := os.CreateTemp(c.path, "temp-*.tmp")
477
+ if err != nil {
478
+ return err
479
+ }
480
+ tempFilename := tmpFile.Name()
481
+
482
+ defer func() {
483
+ tmpFile.Close()
484
+ os.Remove(tempFilename) // Remove temp file if it still exists
485
+ }()
486
+
487
+ // Write data to temp file, flush and close
488
+ if _, err := tmpFile.Write(data); err != nil {
489
+ return err
490
+ }
491
+ if err := tmpFile.Sync(); err != nil {
492
+ return err
493
+ }
494
+ if err := tmpFile.Close(); err != nil {
495
+ return err
496
+ }
497
+
498
+ // Atomically rename the temp file to the target filename to not leave garbage when it crashes
499
+ return os.Rename(tempFilename, c.path+"/"+FileName)
500
+ }
501
+
502
+ func (c *DBUser) Close() error {
503
+ c.lock.Lock()
504
+ defer c.lock.Unlock()
505
+ return c.storeToFile()
506
+ }
507
+
508
+ func createStorage(filePath string) error {
509
+ if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
510
+ return fmt.Errorf("failed to create directories: %w", err)
511
+ }
512
+
513
+ _, err := os.Stat(filePath)
514
+ if err == nil { // file exists
515
+ return nil
516
+ }
517
+
518
+ if os.IsNotExist(err) {
519
+ file, err := os.Create(filePath)
520
+ if err != nil {
521
+ return fmt.Errorf("failed to create file: %w", err)
522
+ }
523
+ defer file.Close()
524
+ return nil
525
+ }
526
+
527
+ return err
528
+ }
529
+
530
+ func ReadFile(filename string) ([]byte, error) {
531
+ file, err := os.Open(filename)
532
+ if err != nil {
533
+ return nil, err
534
+ }
535
+ defer file.Close()
536
+
537
+ fileInfo, err := file.Stat()
538
+ if err != nil {
539
+ return nil, err
540
+ }
541
+
542
+ data := make([]byte, fileInfo.Size())
543
+
544
+ _, err = file.Read(data)
545
+ if err != nil {
546
+ return nil, err
547
+ }
548
+
549
+ return data, nil
550
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/keys/key_generation.go ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package keys
13
+
14
+ import (
15
+ "crypto/rand"
16
+ "encoding/base64"
17
+ "fmt"
18
+ "strings"
19
+
20
+ "github.com/alexedwards/argon2id"
21
+ )
22
+
23
+ const (
24
+ DynUserIdentifier = "v200" // has to be 4 chars so full key is divisible by 3 and Base64Encoding does not end in "="
25
+ RandomBytesLength = 32
26
+ RandomBytesBase64Length = 44
27
+ UserIdentifierBytesLength = 12
28
+ UserIdentifierBytesBase64Length = 16
29
+ )
30
+
31
+ // second recommendation from the RFC: https://www.rfc-editor.org/rfc/rfc9106.html#name-parameter-choice
32
+ // Changing ANY of these parameters will change the output and make previously generated keys invalid.
33
+ var argonParameters = &argon2id.Params{
34
+ Memory: 64 * 1024,
35
+ Parallelism: 2,
36
+ Iterations: 3,
37
+ SaltLength: 16,
38
+ KeyLength: 32,
39
+ }
40
+
41
+ // CreateApiKeyAndHash creates an api key that has three parts:
42
+ // 1) an argon hash of a random key with length 32 bytes (Base64 encoded)
43
+ // 2) a random user identifier with length 10 bytes (Base64 encoded)
44
+ // - this identifier can be used to fetch the hash later
45
+ //
46
+ // 3) a version string to identify the type of api key
47
+ //
48
+ // The different parts have "_" as separator (which is not part of Base64) and the combined string is encoded again as
49
+ // Base64 to be returned to the user. The apiKey length is divisible by 3 so the Base64Encoding does not end in "=".
50
+ //
51
+ // To verify that a user provides the correct key the following steps have to be taken:
52
+ // - decode the key into the 3 parts mentioned above using DecodeApiKey
53
+ // - fetch the saved hash based on the returned user identifier
54
+ // - compare the returned randomKey with the fetched hash using argon2id.ComparePasswordAndHash
55
+ func CreateApiKeyAndHash() (string, string, string, error) {
56
+ randomBytesKey, err := generateRandomBytes(RandomBytesLength)
57
+ if err != nil {
58
+ return "", "", "", err
59
+ }
60
+ randomKey := base64.StdEncoding.EncodeToString(randomBytesKey)
61
+
62
+ randomBytesIdentifier, err := generateRandomBytes(UserIdentifierBytesLength)
63
+ if err != nil {
64
+ return "", "", "", err
65
+ }
66
+ identifier := base64.StdEncoding.EncodeToString(randomBytesIdentifier)
67
+
68
+ fullApiKey := generateApiKey(randomKey, identifier)
69
+
70
+ hash, err := argon2id.CreateHash(randomKey, argonParameters)
71
+
72
+ return fullApiKey, hash, identifier, err
73
+ }
74
+
75
+ func generateApiKey(randomKey, userIdentifier string) string {
76
+ fullString := userIdentifier + "_" + randomKey + "_" + DynUserIdentifier
77
+ return base64.StdEncoding.EncodeToString([]byte(fullString))
78
+ }
79
+
80
+ func generateRandomBytes(length int) ([]byte, error) {
81
+ b := make([]byte, length)
82
+ _, err := rand.Read(b)
83
+ // Note that err == nil only if we read len(b) bytes.
84
+ if err != nil {
85
+ return nil, err
86
+ }
87
+
88
+ return b, nil
89
+ }
90
+
91
+ func DecodeApiKey(fullApiKey string) (string, string, error) {
92
+ decodeString, err := base64.StdEncoding.DecodeString(fullApiKey)
93
+ if err != nil {
94
+ return "", "", err
95
+ }
96
+
97
+ parts := strings.Split(string(decodeString), "_")
98
+ if len(parts) != 3 {
99
+ return "", "", fmt.Errorf("invalid token")
100
+ }
101
+
102
+ userIdentifier := parts[0]
103
+ randomKey := parts[1]
104
+ version := parts[2]
105
+ if version != DynUserIdentifier {
106
+ return "", "", fmt.Errorf("invalid token")
107
+ }
108
+
109
+ if len(userIdentifier) != UserIdentifierBytesBase64Length {
110
+ return "", "", fmt.Errorf("invalid token")
111
+ }
112
+
113
+ if len(randomKey) != RandomBytesBase64Length {
114
+ return "", "", fmt.Errorf("invalid token")
115
+ }
116
+
117
+ return randomKey, userIdentifier, nil
118
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/keys/key_generation_test.go ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package keys
13
+
14
+ import (
15
+ "encoding/base64"
16
+ "strings"
17
+ "testing"
18
+
19
+ "github.com/alexedwards/argon2id"
20
+ "github.com/stretchr/testify/require"
21
+ )
22
+
23
+ func TestKeyGeneration(t *testing.T) {
24
+ fullApiKey, hash, userIdentifier, err := CreateApiKeyAndHash()
25
+ require.NoError(t, err)
26
+
27
+ randomKey, userIdentifierDecoded, err := DecodeApiKey(fullApiKey)
28
+ require.NoError(t, err)
29
+ require.Equal(t, userIdentifier, userIdentifierDecoded)
30
+
31
+ match, err := argon2id.ComparePasswordAndHash(randomKey, hash)
32
+ require.NoError(t, err)
33
+ require.True(t, match)
34
+ }
35
+
36
+ func TestInvalidKeys(t *testing.T) {
37
+ randomKeyDummy := strings.Repeat("A", RandomBytesBase64Length)
38
+ randomIdentifierDummy := strings.Repeat("A", UserIdentifierBytesBase64Length)
39
+
40
+ combiner := func(parts ...string) string {
41
+ return strings.Join(parts, "_")
42
+ }
43
+
44
+ tests := []struct {
45
+ name string
46
+ key string
47
+ error bool
48
+ }{
49
+ {name: "valid", key: combiner(randomIdentifierDummy, randomKeyDummy, DynUserIdentifier), error: false},
50
+ {name: "invalid base64", key: "i am a string that is not base64", error: true},
51
+ {name: "invalid version", key: combiner(randomIdentifierDummy, randomKeyDummy, "v123"), error: true},
52
+ {name: "missing part", key: combiner(randomIdentifierDummy, randomKeyDummy), error: true},
53
+ {name: "invalid randomKey", key: combiner(randomIdentifierDummy, randomKeyDummy[:5], DynUserIdentifier), error: true},
54
+ {name: "invalid identifier", key: combiner(randomIdentifierDummy[:5], randomKeyDummy, DynUserIdentifier), error: true},
55
+ {name: "all wrong", key: combiner(randomIdentifierDummy[:5], randomKeyDummy[:5], "v123"), error: true},
56
+ }
57
+
58
+ for _, tt := range tests {
59
+ t.Run(tt.name, func(t *testing.T) {
60
+ encodedKey := base64.StdEncoding.EncodeToString([]byte(tt.key))
61
+ _, _, err := DecodeApiKey(encodedKey)
62
+ if tt.error {
63
+ require.Error(t, err)
64
+ } else {
65
+ require.NoError(t, err)
66
+ }
67
+ })
68
+ }
69
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/remote.go ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package apikey
13
+
14
+ import (
15
+ "context"
16
+ "time"
17
+ )
18
+
19
+ type RemoteApiKey struct {
20
+ apikey *DBUser
21
+ }
22
+
23
+ func NewRemoteApiKey(apikey *ApiKey) *RemoteApiKey {
24
+ return &RemoteApiKey{apikey: apikey.Dynamic}
25
+ }
26
+
27
+ func (r *RemoteApiKey) GetUserStatus(ctx context.Context, users UserStatusRequest) (*UserStatusResponse, error) {
28
+ r.apikey.UpdateLastUsedTimestamp(users.Users)
29
+
30
+ if !users.ReturnStatus {
31
+ return nil, nil
32
+ }
33
+
34
+ userIds := make([]string, 0, len(users.Users))
35
+ for userId := range users.Users {
36
+ userIds = append(userIds, userId)
37
+ }
38
+ userReturns, err := r.apikey.GetUsers(userIds...)
39
+ if err != nil {
40
+ return nil, err
41
+ }
42
+
43
+ ret := make(map[string]time.Time, len(userReturns))
44
+ for _, userReturn := range userReturns {
45
+ ret[userReturn.Id] = userReturn.LastUsedAt
46
+ }
47
+ return &UserStatusResponse{Users: ret}, nil
48
+ }
49
+
50
+ type UserStatusResponse struct {
51
+ Users map[string]time.Time
52
+ }
53
+
54
+ type UserStatusRequest struct {
55
+ Users map[string]time.Time
56
+ ReturnStatus bool
57
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/wrapper.go ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package apikey
13
+
14
+ import (
15
+ "fmt"
16
+
17
+ "github.com/go-openapi/errors"
18
+ "github.com/sirupsen/logrus"
19
+ "github.com/weaviate/weaviate/entities/models"
20
+ "github.com/weaviate/weaviate/usecases/auth/authentication/apikey/keys"
21
+ "github.com/weaviate/weaviate/usecases/config"
22
+ )
23
+
24
+ type ApiKey struct {
25
+ static *StaticApiKey
26
+ Dynamic *DBUser
27
+ }
28
+
29
+ func New(cfg config.Config, logger logrus.FieldLogger) (*ApiKey, error) {
30
+ static, err := NewStatic(cfg)
31
+ if err != nil {
32
+ return nil, err
33
+ }
34
+ dynamic, err := NewDBUser(cfg.Persistence.DataPath, cfg.Authentication.DBUsers.Enabled, logger)
35
+ if err != nil {
36
+ return nil, err
37
+ }
38
+
39
+ return &ApiKey{
40
+ static: static,
41
+ Dynamic: dynamic,
42
+ }, nil
43
+ }
44
+
45
+ func (a *ApiKey) ValidateAndExtract(token string, scopes []string) (*models.Principal, error) {
46
+ validate := func(token string, scopes []string) (*models.Principal, error) {
47
+ if a.Dynamic.enabled {
48
+ if randomKey, userIdentifier, err := keys.DecodeApiKey(token); err == nil {
49
+ principal, err := a.Dynamic.ValidateAndExtract(randomKey, userIdentifier)
50
+ if err != nil {
51
+ return nil, fmt.Errorf("invalid api key: %w", err)
52
+ }
53
+ return principal, nil
54
+ }
55
+ principal, err := a.Dynamic.ValidateImportedKey(token)
56
+ if err != nil {
57
+ return nil, fmt.Errorf("invalid api key: %w", err)
58
+ }
59
+ if principal != nil {
60
+ return principal, nil
61
+ } else if a.Dynamic.IsBlockedKey(token) {
62
+ // make sure static keys do not work after import and key rotation
63
+ return nil, fmt.Errorf("invalid api key")
64
+ }
65
+ }
66
+ if a.static.config.Enabled {
67
+ return a.static.ValidateAndExtract(token, scopes)
68
+ }
69
+ return nil, fmt.Errorf("invalid api key")
70
+ }
71
+
72
+ principal, err := validate(token, scopes)
73
+ if err != nil {
74
+ return nil, errors.New(401, "unauthorized: %v", err)
75
+ }
76
+ return principal, nil
77
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/apikey/wrapper_test.go ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package apikey
13
+
14
+ import (
15
+ "testing"
16
+ "time"
17
+
18
+ "github.com/stretchr/testify/require"
19
+ "github.com/weaviate/weaviate/usecases/auth/authentication/apikey/keys"
20
+ "github.com/weaviate/weaviate/usecases/config"
21
+
22
+ "github.com/sirupsen/logrus/hooks/test"
23
+ )
24
+
25
+ func TestInvalidApiKey(t *testing.T) {
26
+ t.Parallel()
27
+
28
+ logger, _ := test.NewNullLogger()
29
+
30
+ testCases := []struct {
31
+ staticEnabled bool
32
+ dbEnabled bool
33
+ }{
34
+ {staticEnabled: true, dbEnabled: false},
35
+ {staticEnabled: false, dbEnabled: true},
36
+ {staticEnabled: true, dbEnabled: true},
37
+ }
38
+
39
+ for _, testCase := range testCases {
40
+ t.Run("staticEnabled="+boolToStr(testCase.staticEnabled)+",dbEnabled="+boolToStr(testCase.dbEnabled), func(t *testing.T) {
41
+ conf := config.Config{
42
+ Persistence: config.Persistence{DataPath: t.TempDir()},
43
+ Authentication: config.Authentication{
44
+ DBUsers: config.DbUsers{Enabled: testCase.dbEnabled},
45
+ APIKey: config.StaticAPIKey{Enabled: testCase.staticEnabled, AllowedKeys: []string{"valid-key"}, Users: []string{"user1"}},
46
+ },
47
+ }
48
+ wrapper, err := New(conf, logger)
49
+ require.NoError(t, err)
50
+
51
+ _, err = wrapper.ValidateAndExtract("invalid-key", nil)
52
+ require.Error(t, err)
53
+ require.Contains(t, err.Error(), "unauthorized: invalid api key")
54
+ })
55
+ }
56
+ }
57
+
58
+ func TestValidStaticKey(t *testing.T) {
59
+ t.Parallel()
60
+
61
+ logger, _ := test.NewNullLogger()
62
+
63
+ testCases := []struct {
64
+ staticEnabled bool
65
+ dbEnabled bool
66
+ expectError bool
67
+ }{
68
+ {staticEnabled: true, dbEnabled: false, expectError: false},
69
+ {staticEnabled: false, dbEnabled: true, expectError: true},
70
+ {staticEnabled: true, dbEnabled: true, expectError: false},
71
+ }
72
+
73
+ for _, testCase := range testCases {
74
+ t.Run("staticEnabled="+boolToStr(testCase.staticEnabled)+",dbEnabled="+boolToStr(testCase.dbEnabled), func(t *testing.T) {
75
+ conf := config.Config{
76
+ Persistence: config.Persistence{DataPath: t.TempDir()},
77
+ Authentication: config.Authentication{
78
+ DBUsers: config.DbUsers{Enabled: testCase.dbEnabled},
79
+ APIKey: config.StaticAPIKey{Enabled: testCase.staticEnabled, AllowedKeys: []string{"valid-key"}, Users: []string{"user1"}},
80
+ },
81
+ }
82
+ wrapper, err := New(conf, logger)
83
+ require.NoError(t, err)
84
+
85
+ principal, err := wrapper.ValidateAndExtract("valid-key", nil)
86
+ if testCase.expectError {
87
+ require.Error(t, err)
88
+ require.Contains(t, err.Error(), "unauthorized: invalid api key")
89
+ } else {
90
+ require.NoError(t, err)
91
+ require.NotNil(t, principal)
92
+ }
93
+ })
94
+ }
95
+ }
96
+
97
+ func TestValidDynamicKey(t *testing.T) {
98
+ t.Parallel()
99
+
100
+ logger, _ := test.NewNullLogger()
101
+
102
+ testCases := []struct {
103
+ staticEnabled bool
104
+ dbEnabled bool
105
+ expectError bool
106
+ }{
107
+ {staticEnabled: true, dbEnabled: false, expectError: true},
108
+ {staticEnabled: false, dbEnabled: true, expectError: false},
109
+ {staticEnabled: true, dbEnabled: true, expectError: false},
110
+ }
111
+
112
+ for _, testCase := range testCases {
113
+ t.Run("staticEnabled="+boolToStr(testCase.staticEnabled)+",dbEnabled="+boolToStr(testCase.dbEnabled), func(t *testing.T) {
114
+ conf := config.Config{
115
+ Persistence: config.Persistence{DataPath: t.TempDir()},
116
+ Authentication: config.Authentication{
117
+ DBUsers: config.DbUsers{Enabled: testCase.dbEnabled},
118
+ APIKey: config.StaticAPIKey{Enabled: testCase.staticEnabled, AllowedKeys: []string{"valid-key"}, Users: []string{"user1"}},
119
+ },
120
+ }
121
+ wrapper, err := New(conf, logger)
122
+ require.NoError(t, err)
123
+
124
+ userId := "id"
125
+
126
+ apiKey, hash, identifier, err := keys.CreateApiKeyAndHash()
127
+ require.NoError(t, err)
128
+
129
+ require.NoError(t, wrapper.Dynamic.CreateUser(userId, hash, identifier, "", time.Now()))
130
+
131
+ principal, err := wrapper.ValidateAndExtract(apiKey, nil)
132
+ if testCase.expectError {
133
+ require.Error(t, err)
134
+ require.Contains(t, err.Error(), "unauthorized: invalid api key")
135
+ } else {
136
+ require.NoError(t, err)
137
+ require.NotNil(t, principal)
138
+ }
139
+ })
140
+ }
141
+ }
142
+
143
+ func boolToStr(enabled bool) string {
144
+ if enabled {
145
+ return "true"
146
+ }
147
+ return "false"
148
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/authentication.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package authentication
13
+
14
+ type AuthType string
15
+
16
+ const (
17
+ AuthTypeDb AuthType = "db"
18
+ AuthTypeOIDC AuthType = "oidc"
19
+ )
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/composer/token_validation.go ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package composer
13
+
14
+ import (
15
+ "github.com/golang-jwt/jwt/v4"
16
+ "github.com/pkg/errors"
17
+ "github.com/weaviate/weaviate/entities/models"
18
+ "github.com/weaviate/weaviate/usecases/config"
19
+ )
20
+
21
+ type TokenFunc func(token string, scopes []string) (*models.Principal, error)
22
+
23
+ // New provides an OpenAPI compatible token validation
24
+ // function that validates the token either as OIDC or as an StaticAPIKey token
25
+ // depending on which is configured. If both are configured, the scheme is
26
+ // figured out at runtime.
27
+ func New(config config.Authentication,
28
+ apikey authValidator, oidc authValidator,
29
+ ) TokenFunc {
30
+ if config.AnyApiKeyAvailable() && config.OIDC.Enabled {
31
+ return pickAuthSchemeDynamically(apikey, oidc)
32
+ }
33
+
34
+ if config.AnyApiKeyAvailable() {
35
+ return apikey.ValidateAndExtract
36
+ }
37
+
38
+ // default to OIDC, even if no scheme is enabled, then it can deal with this
39
+ // scenario itself. This is the backward-compatible scenario.
40
+ return oidc.ValidateAndExtract
41
+ }
42
+
43
+ func pickAuthSchemeDynamically(
44
+ apiKey authValidator, oidc authValidator,
45
+ ) TokenFunc {
46
+ return func(token string, scopes []string) (*models.Principal, error) {
47
+ _, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
48
+ return nil, nil
49
+ })
50
+
51
+ if err != nil && errors.Is(err, jwt.ErrTokenMalformed) {
52
+ return apiKey.ValidateAndExtract(token, scopes)
53
+ }
54
+
55
+ return oidc.ValidateAndExtract(token, scopes)
56
+ }
57
+ }
58
+
59
+ type authValidator interface {
60
+ ValidateAndExtract(token string, scopes []string) (*models.Principal, error)
61
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/composer/token_validation_test.go ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package composer
13
+
14
+ import (
15
+ "fmt"
16
+ "testing"
17
+
18
+ "github.com/stretchr/testify/assert"
19
+ "github.com/stretchr/testify/require"
20
+ "github.com/weaviate/weaviate/entities/models"
21
+ "github.com/weaviate/weaviate/usecases/config"
22
+ )
23
+
24
+ func Test_TokenAuthComposer(t *testing.T) {
25
+ type test struct {
26
+ name string
27
+ token string
28
+ config config.Authentication
29
+ oidc TokenFunc
30
+ apiKey TokenFunc
31
+ expectErr bool
32
+ expectErrMsg string
33
+ }
34
+
35
+ tests := []test{
36
+ {
37
+ name: "everything disabled - pass to oidc provider (backward compat)",
38
+ config: config.Authentication{
39
+ OIDC: config.OIDC{
40
+ Enabled: false,
41
+ },
42
+ APIKey: config.StaticAPIKey{
43
+ Enabled: false,
44
+ },
45
+ },
46
+ token: "does not matter",
47
+ apiKey: func(t string, s []string) (*models.Principal, error) {
48
+ panic("i should never be called")
49
+ },
50
+ oidc: func(t string, s []string) (*models.Principal, error) {
51
+ return nil, nil
52
+ },
53
+ expectErr: false,
54
+ },
55
+ {
56
+ name: "everything disabled - pass to oidc provider fail",
57
+ config: config.Authentication{
58
+ OIDC: config.OIDC{
59
+ Enabled: false,
60
+ },
61
+ APIKey: config.StaticAPIKey{
62
+ Enabled: false,
63
+ },
64
+ },
65
+ token: "does not matter",
66
+ apiKey: func(t string, s []string) (*models.Principal, error) {
67
+ panic("i should never be called")
68
+ },
69
+ oidc: func(t string, s []string) (*models.Principal, error) {
70
+ return nil, fmt.Errorf("oidc says nope!")
71
+ },
72
+ expectErr: true,
73
+ expectErrMsg: "oidc says nope!",
74
+ },
75
+ {
76
+ name: "only oidc enabled, returns success",
77
+ config: config.Authentication{
78
+ OIDC: config.OIDC{
79
+ Enabled: true,
80
+ },
81
+ APIKey: config.StaticAPIKey{
82
+ Enabled: false,
83
+ },
84
+ },
85
+ token: "does not matter",
86
+ apiKey: func(t string, s []string) (*models.Principal, error) {
87
+ panic("i should never be called")
88
+ },
89
+ oidc: func(t string, s []string) (*models.Principal, error) {
90
+ return nil, nil
91
+ },
92
+ expectErr: false,
93
+ },
94
+ {
95
+ name: "only oidc enabled, returns no success",
96
+ config: config.Authentication{
97
+ OIDC: config.OIDC{
98
+ Enabled: true,
99
+ },
100
+ APIKey: config.StaticAPIKey{
101
+ Enabled: false,
102
+ },
103
+ },
104
+ token: "does not matter",
105
+ apiKey: func(t string, s []string) (*models.Principal, error) {
106
+ panic("i should never be called")
107
+ },
108
+ oidc: func(t string, s []string) (*models.Principal, error) {
109
+ return nil, fmt.Errorf("thou shalt not pass")
110
+ },
111
+ expectErr: true,
112
+ expectErrMsg: "thou shalt not pass",
113
+ },
114
+ {
115
+ name: "only apiKey enabled, returns success",
116
+ config: config.Authentication{
117
+ OIDC: config.OIDC{
118
+ Enabled: false,
119
+ },
120
+ APIKey: config.StaticAPIKey{
121
+ Enabled: true,
122
+ },
123
+ },
124
+ token: "does not matter",
125
+ apiKey: func(t string, s []string) (*models.Principal, error) {
126
+ return nil, nil
127
+ },
128
+ oidc: func(t string, s []string) (*models.Principal, error) {
129
+ panic("i should never be called")
130
+ },
131
+ expectErr: false,
132
+ },
133
+ {
134
+ name: "only apiKey enabled, returns no success",
135
+ config: config.Authentication{
136
+ OIDC: config.OIDC{
137
+ Enabled: false,
138
+ },
139
+ APIKey: config.StaticAPIKey{
140
+ Enabled: true,
141
+ },
142
+ },
143
+ token: "does not matter",
144
+ apiKey: func(t string, s []string) (*models.Principal, error) {
145
+ return nil, fmt.Errorf("you think I let anyone through?")
146
+ },
147
+ oidc: func(t string, s []string) (*models.Principal, error) {
148
+ panic("i should never be called")
149
+ },
150
+ expectErr: true,
151
+ expectErrMsg: "you think I let anyone through?",
152
+ },
153
+ {
154
+ name: "both an enabled, with an 'obvious' api key",
155
+ config: config.Authentication{
156
+ OIDC: config.OIDC{
157
+ Enabled: true,
158
+ },
159
+ APIKey: config.StaticAPIKey{
160
+ Enabled: true,
161
+ },
162
+ },
163
+ token: "does not matter",
164
+ apiKey: func(t string, s []string) (*models.Principal, error) {
165
+ return nil, fmt.Errorf("it's a pretty key, but not good enough")
166
+ },
167
+ oidc: func(t string, s []string) (*models.Principal, error) {
168
+ panic("i should never be called")
169
+ },
170
+ expectErr: true,
171
+ expectErrMsg: "it's a pretty key, but not good enough",
172
+ },
173
+ {
174
+ name: "both an enabled, empty token",
175
+ config: config.Authentication{
176
+ OIDC: config.OIDC{
177
+ Enabled: true,
178
+ },
179
+ APIKey: config.StaticAPIKey{
180
+ Enabled: true,
181
+ },
182
+ },
183
+ token: "",
184
+ apiKey: func(t string, s []string) (*models.Principal, error) {
185
+ return nil, fmt.Errorf("really? an empty one?")
186
+ },
187
+ oidc: func(t string, s []string) (*models.Principal, error) {
188
+ panic("i should never be called")
189
+ },
190
+ expectErr: true,
191
+ expectErrMsg: "empty one",
192
+ },
193
+ {
194
+ name: "both an enabled, jwt token",
195
+ config: config.Authentication{
196
+ OIDC: config.OIDC{
197
+ Enabled: true,
198
+ },
199
+ APIKey: config.StaticAPIKey{
200
+ Enabled: true,
201
+ },
202
+ },
203
+ token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
204
+ apiKey: func(t string, s []string) (*models.Principal, error) {
205
+ panic("i should never be called")
206
+ },
207
+ oidc: func(t string, s []string) (*models.Principal, error) {
208
+ return nil, fmt.Errorf("john doe ... that sounds like a fake name!")
209
+ },
210
+ expectErr: true,
211
+ expectErrMsg: "john doe",
212
+ },
213
+ }
214
+
215
+ for _, test := range tests {
216
+ t.Run(test.name, func(t *testing.T) {
217
+ v := New(
218
+ test.config,
219
+ fakeValidator{v: test.apiKey},
220
+ fakeValidator{v: test.oidc},
221
+ )
222
+ _, err := v(test.token, nil)
223
+ if test.expectErr {
224
+ require.NotNil(t, err)
225
+ assert.Contains(t, err.Error(), test.expectErrMsg)
226
+ return
227
+ }
228
+
229
+ require.Nil(t, err)
230
+ })
231
+ }
232
+ }
233
+
234
+ type fakeValidator struct {
235
+ v TokenFunc
236
+ }
237
+
238
+ func (v fakeValidator) ValidateAndExtract(t string, s []string) (*models.Principal, error) {
239
+ return v.v(t, s)
240
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/oidc/middleware.go ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package oidc
13
+
14
+ import (
15
+ "bytes"
16
+ "context"
17
+ "crypto/tls"
18
+ "crypto/x509"
19
+ "encoding/pem"
20
+ "fmt"
21
+ "io"
22
+ "net/http"
23
+ "os"
24
+ "strings"
25
+
26
+ "github.com/coreos/go-oidc/v3/oidc"
27
+ errors "github.com/go-openapi/errors"
28
+ "github.com/minio/minio-go/v7"
29
+ "github.com/minio/minio-go/v7/pkg/credentials"
30
+ "github.com/sirupsen/logrus"
31
+ "github.com/weaviate/weaviate/entities/models"
32
+ "github.com/weaviate/weaviate/usecases/config"
33
+ )
34
+
35
+ // Client handles the OIDC setup at startup and provides a middleware to be
36
+ // used with the goswagger API
37
+ type Client struct {
38
+ Config config.OIDC
39
+ verifier *oidc.IDTokenVerifier
40
+ logger logrus.FieldLogger
41
+ }
42
+
43
+ // New OIDC Client: It tries to retrieve the JWKs at startup (or fails), it
44
+ // provides a middleware which can be used at runtime with a go-swagger style
45
+ // API
46
+ func New(cfg config.Config, logger logrus.FieldLogger) (*Client, error) {
47
+ client := &Client{
48
+ Config: cfg.Authentication.OIDC,
49
+ logger: logger.WithField("component", "oidc"),
50
+ }
51
+
52
+ if !client.Config.Enabled {
53
+ // if oidc is not enabled, we are done, no need to setup an actual client.
54
+ // The "disabled" client is however still valuable to deny any requests
55
+ // coming in with an OAuth token set.
56
+ return client, nil
57
+ }
58
+
59
+ if err := client.Init(); err != nil {
60
+ return nil, fmt.Errorf("oidc init: %w", err)
61
+ }
62
+
63
+ return client, nil
64
+ }
65
+
66
+ func (c *Client) Init() error {
67
+ if err := c.validateConfig(); err != nil {
68
+ return fmt.Errorf("invalid config: %w", err)
69
+ }
70
+ c.logger.WithField("action", "oidc_init").Info("validated OIDC configuration")
71
+
72
+ ctx := context.Background()
73
+ if c.Config.Certificate.Get() != "" {
74
+ client, err := c.useCertificate()
75
+ if err != nil {
76
+ return fmt.Errorf("could not setup client with custom certificate: %w", err)
77
+ }
78
+ ctx = oidc.ClientContext(ctx, client)
79
+ c.logger.WithField("action", "oidc_init").Info("configured OIDC client with custom certificate")
80
+ }
81
+
82
+ if c.Config.JWKSUrl.Get() != "" {
83
+ keySet := oidc.NewRemoteKeySet(ctx, c.Config.JWKSUrl.Get())
84
+ verifier := oidc.NewVerifier(c.Config.Issuer.Get(), keySet, &oidc.Config{
85
+ ClientID: c.Config.ClientID.Get(),
86
+ SkipClientIDCheck: c.Config.SkipClientIDCheck.Get(),
87
+ })
88
+ c.verifier = verifier
89
+ c.logger.WithField("action", "oidc_init").WithField("jwks_url", c.Config.JWKSUrl.Get()).Info("configured OIDC verifier")
90
+ } else {
91
+ provider, err := oidc.NewProvider(ctx, c.Config.Issuer.Get())
92
+ if err != nil {
93
+ return fmt.Errorf("could not setup provider: %w", err)
94
+ }
95
+ c.logger.WithField("action", "oidc_init").Info("configured OIDC provider")
96
+
97
+ // oauth2
98
+
99
+ verifier := provider.Verifier(&oidc.Config{
100
+ ClientID: c.Config.ClientID.Get(),
101
+ SkipClientIDCheck: c.Config.SkipClientIDCheck.Get(),
102
+ })
103
+ c.verifier = verifier
104
+ c.logger.WithField("action", "oidc_init").Info("configured OIDC verifier")
105
+ }
106
+
107
+ return nil
108
+ }
109
+
110
+ func (c *Client) validateConfig() error {
111
+ var msgs []string
112
+
113
+ if c.Config.Issuer.Get() == "" {
114
+ msgs = append(msgs, "missing required field 'issuer'")
115
+ }
116
+
117
+ if c.Config.UsernameClaim.Get() == "" {
118
+ msgs = append(msgs, "missing required field 'username_claim'")
119
+ }
120
+
121
+ if !c.Config.SkipClientIDCheck.Get() && c.Config.ClientID.Get() == "" {
122
+ msgs = append(msgs, "missing required field 'client_id': "+
123
+ "either set a client_id or explicitly disable the check with 'skip_client_id_check: true'")
124
+ }
125
+
126
+ if len(msgs) == 0 {
127
+ return nil
128
+ }
129
+
130
+ return fmt.Errorf("%v", strings.Join(msgs, ", "))
131
+ }
132
+
133
+ // ValidateAndExtract can be used as a middleware for go-swagger
134
+ func (c *Client) ValidateAndExtract(token string, scopes []string) (*models.Principal, error) {
135
+ if !c.Config.Enabled {
136
+ return nil, errors.New(401, "oidc auth is not configured, please try another auth scheme or set up weaviate with OIDC configured")
137
+ }
138
+
139
+ parsed, err := c.verifier.Verify(context.Background(), token)
140
+ if err != nil {
141
+ return nil, errors.New(401, "unauthorized: %v", err)
142
+ }
143
+
144
+ claims, err := c.extractClaims(parsed)
145
+ if err != nil {
146
+ return nil, errors.New(500, "oidc: %v", err)
147
+ }
148
+
149
+ username, err := c.extractUsername(claims)
150
+ if err != nil {
151
+ return nil, errors.New(500, "oidc: %v", err)
152
+ }
153
+
154
+ groups := c.extractGroups(claims)
155
+
156
+ return &models.Principal{
157
+ Username: username,
158
+ Groups: groups,
159
+ UserType: models.UserTypeInputOidc,
160
+ }, nil
161
+ }
162
+
163
+ func (c *Client) extractClaims(token *oidc.IDToken) (map[string]interface{}, error) {
164
+ var claims map[string]interface{}
165
+ if err := token.Claims(&claims); err != nil {
166
+ return nil, fmt.Errorf("could not extract claims from token: %w", err)
167
+ }
168
+
169
+ return claims, nil
170
+ }
171
+
172
+ func (c *Client) extractUsername(claims map[string]interface{}) (string, error) {
173
+ usernameUntyped, ok := claims[c.Config.UsernameClaim.Get()]
174
+ if !ok {
175
+ return "", fmt.Errorf("token doesn't contain required claim '%s'", c.Config.UsernameClaim.Get())
176
+ }
177
+
178
+ username, ok := usernameUntyped.(string)
179
+ if !ok {
180
+ return "", fmt.Errorf("claim '%s' is not a string, but %T", c.Config.UsernameClaim.Get(), usernameUntyped)
181
+ }
182
+
183
+ return username, nil
184
+ }
185
+
186
+ // extractGroups never errors, if groups can't be parsed an empty set of groups
187
+ // is returned. This is because groups are not a required standard in the OIDC
188
+ // spec, so we can't error if an OIDC provider does not support them.
189
+ func (c *Client) extractGroups(claims map[string]interface{}) []string {
190
+ var groups []string
191
+
192
+ groupsUntyped, ok := claims[c.Config.GroupsClaim.Get()]
193
+ if !ok {
194
+ return groups
195
+ }
196
+
197
+ groupsSlice, ok := groupsUntyped.([]interface{})
198
+ if !ok {
199
+ groupAsString, ok := groupsUntyped.(string)
200
+ if ok {
201
+ return []string{groupAsString}
202
+ }
203
+ return groups
204
+ }
205
+
206
+ for _, untyped := range groupsSlice {
207
+ if group, ok := untyped.(string); ok {
208
+ groups = append(groups, group)
209
+ }
210
+ }
211
+
212
+ return groups
213
+ }
214
+
215
+ func (c *Client) useCertificate() (*http.Client, error) {
216
+ var certificate, certificateSource string
217
+ if strings.HasPrefix(c.Config.Certificate.Get(), "http") {
218
+ resp, err := http.Get(c.Config.Certificate.Get())
219
+ if err != nil {
220
+ return nil, fmt.Errorf("failed to get certificate from %s: %w", c.Config.Certificate.Get(), err)
221
+ }
222
+ defer resp.Body.Close()
223
+ if resp.StatusCode != http.StatusOK {
224
+ return nil, fmt.Errorf("failed to download certificate from %s: http status: %v", c.Config.Certificate.Get(), resp.StatusCode)
225
+ }
226
+ certBytes, err := io.ReadAll(resp.Body)
227
+ if err != nil {
228
+ return nil, fmt.Errorf("failed to read certificate from %s: %w", c.Config.Certificate.Get(), err)
229
+ }
230
+ certificate = string(certBytes)
231
+ certificateSource = c.Config.Certificate.Get()
232
+ } else if strings.HasPrefix(c.Config.Certificate.Get(), "s3://") {
233
+ parts := strings.TrimPrefix(c.Config.Certificate.Get(), "s3://")
234
+ segments := strings.SplitN(parts, "/", 2)
235
+ if len(segments) != 2 {
236
+ return nil, fmt.Errorf("invalid S3 URI, must contain bucket and key: %s", c.Config.Certificate.Get())
237
+ }
238
+ region := os.Getenv("AWS_REGION")
239
+ if region == "" {
240
+ region = os.Getenv("AWS_DEFAULT_REGION")
241
+ }
242
+ creds := credentials.NewIAM("")
243
+ // check if we are able to get the credentials using AWS IAM
244
+ if _, err := creds.GetWithContext(nil); err != nil {
245
+ // if IAM doesn't work, check environment settings for creds, set anonymous access if none found
246
+ creds = credentials.NewEnvAWS()
247
+ }
248
+ bucketName, objectKey := segments[0], segments[1]
249
+ minioClient, err := minio.New("s3.amazonaws.com", &minio.Options{
250
+ Creds: creds,
251
+ Secure: true,
252
+ Region: region,
253
+ })
254
+ if err != nil {
255
+ return nil, fmt.Errorf("failed to create S3 client: %w", err)
256
+ }
257
+ object, err := minioClient.GetObject(context.Background(), bucketName, objectKey, minio.GetObjectOptions{})
258
+ if err != nil {
259
+ return nil, fmt.Errorf("failed to get certificate from: %s: %w", c.Config.Certificate.Get(), err)
260
+ }
261
+ defer object.Close()
262
+ var content bytes.Buffer
263
+ if _, err := io.Copy(&content, object); err != nil {
264
+ return nil, fmt.Errorf("failed to read certificate from %s: %w", c.Config.Certificate.Get(), err)
265
+ }
266
+ certificate = content.String()
267
+ certificateSource = c.Config.Certificate.Get()
268
+ } else {
269
+ certificate = c.Config.Certificate.Get()
270
+ certificateSource = "environment variable"
271
+ }
272
+
273
+ certBlock, _ := pem.Decode([]byte(certificate))
274
+ if certBlock == nil || len(certBlock.Bytes) == 0 {
275
+ return nil, fmt.Errorf("failed to decode certificate")
276
+ }
277
+ cert, err := x509.ParseCertificate(certBlock.Bytes)
278
+ if err != nil {
279
+ return nil, fmt.Errorf("failed to parse certificate: %w", err)
280
+ }
281
+
282
+ c.logger.WithField("action", "oidc_init").WithField("source", certificateSource).Info("custom certificate is valid")
283
+
284
+ certPool := x509.NewCertPool()
285
+ certPool.AddCert(cert)
286
+
287
+ // Create an HTTP client with self signed certificate
288
+ client := &http.Client{
289
+ Transport: &http.Transport{
290
+ TLSClientConfig: &tls.Config{
291
+ RootCAs: certPool,
292
+ MinVersion: tls.VersionTLS12,
293
+ },
294
+ },
295
+ }
296
+
297
+ return client, nil
298
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/oidc/middleware_test.go ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package oidc
13
+
14
+ import (
15
+ "fmt"
16
+ "testing"
17
+ "time"
18
+
19
+ errors "github.com/go-openapi/errors"
20
+ "github.com/golang-jwt/jwt/v4"
21
+ "github.com/sirupsen/logrus"
22
+ logrustest "github.com/sirupsen/logrus/hooks/test"
23
+ "github.com/stretchr/testify/assert"
24
+ "github.com/stretchr/testify/require"
25
+
26
+ "github.com/weaviate/weaviate/usecases/config"
27
+ "github.com/weaviate/weaviate/usecases/config/runtime"
28
+ )
29
+
30
+ func Test_Middleware_NotConfigured(t *testing.T) {
31
+ cfg := config.Config{
32
+ Authentication: config.Authentication{
33
+ OIDC: config.OIDC{
34
+ Enabled: false,
35
+ },
36
+ },
37
+ }
38
+ expectedErr := errors.New(401, "oidc auth is not configured, please try another auth scheme or set up weaviate with OIDC configured")
39
+
40
+ logger, _ := logrustest.NewNullLogger()
41
+ client, err := New(cfg, logger)
42
+ require.Nil(t, err)
43
+
44
+ principal, err := client.ValidateAndExtract("token-doesnt-matter", []string{})
45
+ assert.Nil(t, principal)
46
+ assert.Equal(t, expectedErr, err)
47
+ }
48
+
49
+ func Test_Middleware_IncompleteConfiguration(t *testing.T) {
50
+ cfg := config.Config{
51
+ Authentication: config.Authentication{
52
+ OIDC: config.OIDC{
53
+ Enabled: true,
54
+ },
55
+ },
56
+ }
57
+ expectedErr := fmt.Errorf("oidc init: invalid config: missing required field 'issuer', " +
58
+ "missing required field 'username_claim', missing required field 'client_id': either set a client_id or explicitly disable the check with 'skip_client_id_check: true'")
59
+
60
+ logger, _ := logrustest.NewNullLogger()
61
+ _, err := New(cfg, logger)
62
+ assert.ErrorAs(t, err, &expectedErr)
63
+ }
64
+
65
+ type claims struct {
66
+ jwt.StandardClaims
67
+ Email string `json:"email"`
68
+ Groups []string `json:"groups"`
69
+ GroupAsString string `json:"group_as_string"`
70
+ }
71
+
72
+ func Test_Middleware_WithValidToken(t *testing.T) {
73
+ t.Run("without groups set", func(t *testing.T) {
74
+ server := newOIDCServer(t)
75
+ defer server.Close()
76
+
77
+ cfg := config.Config{
78
+ Authentication: config.Authentication{
79
+ OIDC: config.OIDC{
80
+ Enabled: true,
81
+ Issuer: runtime.NewDynamicValue(server.URL),
82
+ ClientID: runtime.NewDynamicValue("best_client"),
83
+ SkipClientIDCheck: runtime.NewDynamicValue(false),
84
+ UsernameClaim: runtime.NewDynamicValue("sub"),
85
+ },
86
+ },
87
+ }
88
+
89
+ token := token(t, "best-user", server.URL, "best_client")
90
+ logger, _ := logrustest.NewNullLogger()
91
+ client, err := New(cfg, logger)
92
+ require.Nil(t, err)
93
+
94
+ principal, err := client.ValidateAndExtract(token, []string{})
95
+ require.Nil(t, err)
96
+ assert.Equal(t, "best-user", principal.Username)
97
+ })
98
+
99
+ t.Run("with a non-standard username claim", func(t *testing.T) {
100
+ server := newOIDCServer(t)
101
+ defer server.Close()
102
+
103
+ cfg := config.Config{
104
+ Authentication: config.Authentication{
105
+ OIDC: config.OIDC{
106
+ Enabled: true,
107
+ Issuer: runtime.NewDynamicValue(server.URL),
108
+ ClientID: runtime.NewDynamicValue("best_client"),
109
+ SkipClientIDCheck: runtime.NewDynamicValue(false),
110
+ UsernameClaim: runtime.NewDynamicValue("email"),
111
+ GroupsClaim: runtime.NewDynamicValue("groups"),
112
+ },
113
+ },
114
+ }
115
+
116
+ token := tokenWithEmail(t, "best-user", server.URL, "best_client", "foo@bar.com")
117
+ logger, _ := logrustest.NewNullLogger()
118
+ client, err := New(cfg, logger)
119
+ require.Nil(t, err)
120
+
121
+ principal, err := client.ValidateAndExtract(token, []string{})
122
+ require.Nil(t, err)
123
+ assert.Equal(t, "foo@bar.com", principal.Username)
124
+ })
125
+
126
+ t.Run("with groups claim", func(t *testing.T) {
127
+ server := newOIDCServer(t)
128
+ defer server.Close()
129
+
130
+ cfg := config.Config{
131
+ Authentication: config.Authentication{
132
+ OIDC: config.OIDC{
133
+ Enabled: true,
134
+ Issuer: runtime.NewDynamicValue(server.URL),
135
+ ClientID: runtime.NewDynamicValue("best_client"),
136
+ SkipClientIDCheck: runtime.NewDynamicValue(false),
137
+ UsernameClaim: runtime.NewDynamicValue("sub"),
138
+ GroupsClaim: runtime.NewDynamicValue("groups"),
139
+ },
140
+ },
141
+ }
142
+
143
+ token := tokenWithGroups(t, "best-user", server.URL, "best_client", []string{"group1", "group2"})
144
+ logger, _ := logrustest.NewNullLogger()
145
+ client, err := New(cfg, logger)
146
+ require.Nil(t, err)
147
+
148
+ principal, err := client.ValidateAndExtract(token, []string{})
149
+ require.Nil(t, err)
150
+ assert.Equal(t, "best-user", principal.Username)
151
+ assert.Equal(t, []string{"group1", "group2"}, principal.Groups)
152
+ })
153
+
154
+ t.Run("with a string groups claim", func(t *testing.T) {
155
+ server := newOIDCServer(t)
156
+ defer server.Close()
157
+
158
+ cfg := config.Config{
159
+ Authentication: config.Authentication{
160
+ OIDC: config.OIDC{
161
+ Enabled: true,
162
+ Issuer: runtime.NewDynamicValue(server.URL),
163
+ ClientID: runtime.NewDynamicValue("best_client"),
164
+ SkipClientIDCheck: runtime.NewDynamicValue(false),
165
+ UsernameClaim: runtime.NewDynamicValue("sub"),
166
+ GroupsClaim: runtime.NewDynamicValue("group_as_string"),
167
+ },
168
+ },
169
+ }
170
+
171
+ token := tokenWithStringGroups(t, "best-user", server.URL, "best_client", "group1")
172
+ logger, _ := logrustest.NewNullLogger()
173
+ client, err := New(cfg, logger)
174
+ require.Nil(t, err)
175
+
176
+ principal, err := client.ValidateAndExtract(token, []string{})
177
+ require.Nil(t, err)
178
+ assert.Equal(t, "best-user", principal.Username)
179
+ assert.Equal(t, []string{"group1"}, principal.Groups)
180
+ })
181
+ }
182
+
183
+ func token(t *testing.T, subject string, issuer string, aud string) string {
184
+ return tokenWithEmail(t, subject, issuer, aud, "")
185
+ }
186
+
187
+ func tokenWithEmail(t *testing.T, subject string, issuer string, aud string, email string) string {
188
+ claims := claims{
189
+ Email: email,
190
+ }
191
+
192
+ return tokenWithClaims(t, subject, issuer, aud, claims)
193
+ }
194
+
195
+ func tokenWithGroups(t *testing.T, subject string, issuer string, aud string, groups []string) string {
196
+ claims := claims{
197
+ Groups: groups,
198
+ }
199
+
200
+ return tokenWithClaims(t, subject, issuer, aud, claims)
201
+ }
202
+
203
+ func tokenWithStringGroups(t *testing.T, subject string, issuer string, aud string, groups string) string {
204
+ claims := claims{
205
+ GroupAsString: groups,
206
+ }
207
+
208
+ return tokenWithClaims(t, subject, issuer, aud, claims)
209
+ }
210
+
211
+ func tokenWithClaims(t *testing.T, subject string, issuer string, aud string, claims claims) string {
212
+ claims.StandardClaims = jwt.StandardClaims{
213
+ Subject: subject,
214
+ Issuer: issuer,
215
+ Audience: aud,
216
+ ExpiresAt: time.Now().Add(10 * time.Second).Unix(),
217
+ }
218
+
219
+ token, err := signToken(claims)
220
+ require.Nil(t, err, "signing token should not error")
221
+
222
+ return token
223
+ }
224
+
225
+ func Test_Middleware_CertificateDownload(t *testing.T) {
226
+ newClientWithCertificate := func(certificate string) (*Client, *logrustest.Hook) {
227
+ logger, loggerHook := logrustest.NewNullLogger()
228
+ logger.SetLevel(logrus.InfoLevel)
229
+ cfg := config.Config{
230
+ Authentication: config.Authentication{
231
+ OIDC: config.OIDC{
232
+ Enabled: true,
233
+ Certificate: runtime.NewDynamicValue(certificate),
234
+ },
235
+ },
236
+ }
237
+ client := &Client{
238
+ Config: cfg.Authentication.OIDC,
239
+ logger: logger.WithField("component", "oidc"),
240
+ }
241
+ return client, loggerHook
242
+ }
243
+
244
+ verifyLogs := func(t *testing.T, loggerHook *logrustest.Hook, certificateSource string) {
245
+ for _, logEntry := range loggerHook.AllEntries() {
246
+ assert.Contains(t, logEntry.Message, "custom certificate is valid")
247
+ assert.Contains(t, logEntry.Data["source"], certificateSource)
248
+ assert.Contains(t, logEntry.Data["action"], "oidc_init")
249
+ assert.Contains(t, logEntry.Data["component"], "oidc")
250
+ }
251
+ }
252
+
253
+ t.Run("certificate string", func(t *testing.T) {
254
+ client, loggerHook := newClientWithCertificate(testingCertificate)
255
+ clientWithCertificate, err := client.useCertificate()
256
+ require.NoError(t, err)
257
+ require.NotNil(t, clientWithCertificate)
258
+ verifyLogs(t, loggerHook, "environment variable")
259
+ })
260
+
261
+ t.Run("certificate URL", func(t *testing.T) {
262
+ certificateServer := newServerWithCertificate()
263
+ defer certificateServer.Close()
264
+ source := certificateURL(certificateServer)
265
+ client, loggerHook := newClientWithCertificate(source)
266
+ clientWithCertificate, err := client.useCertificate()
267
+ require.NoError(t, err)
268
+ require.NotNil(t, clientWithCertificate)
269
+ verifyLogs(t, loggerHook, source)
270
+ })
271
+
272
+ t.Run("unparseable string", func(t *testing.T) {
273
+ client, _ := newClientWithCertificate("unparseable")
274
+ clientWithCertificate, err := client.useCertificate()
275
+ require.Nil(t, clientWithCertificate)
276
+ require.Error(t, err)
277
+ assert.ErrorContains(t, err, "failed to decode certificate")
278
+ })
279
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/oidc/oidc_server_for_test.go ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package oidc
13
+
14
+ import (
15
+ "encoding/json"
16
+ "fmt"
17
+ "net/http"
18
+ "net/http/httptest"
19
+ "testing"
20
+
21
+ jose "github.com/go-jose/go-jose/v4"
22
+ "github.com/golang-jwt/jwt/v4"
23
+ )
24
+
25
+ func newOIDCServer(t *testing.T) *httptest.Server {
26
+ // we need to start up with an empty handler
27
+ s := httptest.NewServer(nil)
28
+
29
+ // so that we can configure it once we now the url, this is used to match the
30
+ // issue field
31
+ s.Config.Handler = oidcHandler(t, s.URL)
32
+ return s
33
+ }
34
+
35
+ type oidcDiscovery struct {
36
+ Issuer string `json:"issuer"`
37
+ JWKSUri string `json:"jwks_uri"`
38
+ }
39
+
40
+ type jwksResponse struct {
41
+ Keys []jose.JSONWebKey `json:"keys"`
42
+ }
43
+
44
+ func oidcHandler(t *testing.T, url string) http.Handler {
45
+ mux := http.NewServeMux()
46
+
47
+ publicKey, err := jwt.ParseRSAPublicKeyFromPEM([]byte(testingPublicKey))
48
+ if err != nil {
49
+ t.Fatalf("test server: couldn't parse public key: %v", err)
50
+ }
51
+
52
+ mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, req *http.Request) {
53
+ w.Header().Add("Content-Type", "application/json")
54
+ d := oidcDiscovery{
55
+ Issuer: url,
56
+ JWKSUri: fmt.Sprintf("%v/.well-known/jwks", url),
57
+ }
58
+ json.NewEncoder(w).Encode(d)
59
+ })
60
+
61
+ mux.HandleFunc("/.well-known/jwks", func(w http.ResponseWriter, req *http.Request) {
62
+ w.Header().Add("Content-Type", "application/json")
63
+ d := jwksResponse{
64
+ Keys: []jose.JSONWebKey{
65
+ {
66
+ Key: publicKey,
67
+ Use: "sig",
68
+ Algorithm: string(jose.RS256),
69
+ KeyID: "my-key",
70
+ },
71
+ },
72
+ }
73
+ if err := json.NewEncoder(w).Encode(d); err != nil {
74
+ t.Fatalf("encoding jwks in test server: %v", err)
75
+ }
76
+ })
77
+
78
+ return mux
79
+ }
80
+
81
+ // those keys are intended to make it possible to sign our own tokens in tests.
82
+ // Never use these keys for anything outside a test scenario!
83
+
84
+ var testingPrivateKey = `-----BEGIN RSA PRIVATE KEY-----
85
+ MIICXAIBAAKBgQDFRV9sD1ULVV7q1w9OXCXPTFRcrTYAZAVZwg8X9V1QyBd8eyp5
86
+ OMI4YxuL7sk+Las+PTcS6AdrHitdDZNqUjWFYOo5EQLnVBghIlu3ZWlAnM2SCPo5
87
+ e2jFD8IgAVHtkAHbFUliQtP6a6OOLMRq9GMhIv2ZWf79KyXvh5DFuM7zbwIDAQAB
88
+ AoGAXptEhghcWtEYcjutZYEfyOjsVH3lNg7B2igNIQpVNFahnNtcpUIpMu2k2lks
89
+ Phuc0n59GR4Z4K9ZUIkgN48xhuqDtHevMQLfg6KQaqf0KRwxBw4dIOhUX0aLkvcJ
90
+ WTtUPE+3hYbOuAPuXVBDB6hBZAe5mbvLPYDM3yYyRotbN7ECQQD/S3Y+shEHOMg1
91
+ ve1eQ4tjN+5Fdmq8l2JIbOPpvH6ytiEQSV2Q55u8gL+1x5Tb9vh3rAdg2OJ0LFay
92
+ VTqmCmkDAkEAxdDgvDqk7JwMbM2jxozVEcECoN07eGrshVWlXtnEpJgU4vBN8wAj
93
+ sS94WZCWu4LZRzPHp36dVDiPFS0aqGlCJQJAMGKX/Zf4HDtJzs25YEVC9MIT+bxQ
94
+ zH+QlBN3OsSL6skUCScugZkz7g0kyIoUD4CGZQAIwfU5LjV9FP2MSQ3uCwJAZxS0
95
+ t4F7xcx/cQcry+BBe7HvU7JVNifJvqVlumqSXQ7e+28rv3AYKVHKTinZUjcaUE88
96
+ QBzrkSKz9N3/ITlQfQJBAL25aXdmooBdYQUvXmNu+n10wwDAqCKtoGW75cZBJvjX
97
+ WnBQsDVlzaBcs32lr08XZIAH318OibfmAs5HKHABoFk=
98
+ -----END RSA PRIVATE KEY-----`
99
+
100
+ var testingPublicKey = `-----BEGIN PUBLIC KEY-----
101
+ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDFRV9sD1ULVV7q1w9OXCXPTFRc
102
+ rTYAZAVZwg8X9V1QyBd8eyp5OMI4YxuL7sk+Las+PTcS6AdrHitdDZNqUjWFYOo5
103
+ EQLnVBghIlu3ZWlAnM2SCPo5e2jFD8IgAVHtkAHbFUliQtP6a6OOLMRq9GMhIv2Z
104
+ Wf79KyXvh5DFuM7zbwIDAQAB
105
+ -----END PUBLIC KEY-----`
106
+
107
+ func signToken(claims jwt.Claims) (string, error) {
108
+ token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
109
+ key, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(testingPrivateKey))
110
+ if err != nil {
111
+ return "", err
112
+ }
113
+
114
+ return token.SignedString(key)
115
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authentication/oidc/oidc_server_with_certificate_for_test.go ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package oidc
13
+
14
+ import (
15
+ "bytes"
16
+ "fmt"
17
+ "net/http"
18
+ "net/http/httptest"
19
+ "time"
20
+ )
21
+
22
+ const testCertificateFilename = "certificate.crt"
23
+
24
+ func newServerWithCertificate() *httptest.Server {
25
+ mux := http.NewServeMux()
26
+ mux.HandleFunc(fmt.Sprintf("/%s", testCertificateFilename), downloadHandler)
27
+ s := httptest.NewServer(mux)
28
+ return s
29
+ }
30
+
31
+ func certificateURL(s *httptest.Server) string {
32
+ return fmt.Sprintf("%s/%s", s.URL, testCertificateFilename)
33
+ }
34
+
35
+ func downloadHandler(w http.ResponseWriter, r *http.Request) {
36
+ fileName := testCertificateFilename
37
+ // Create in-memory buffer
38
+ buffer := bytes.NewBufferString(testingCertificate)
39
+
40
+ // Set headers
41
+ w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
42
+ w.Header().Set("Content-Type", "text/plain")
43
+ w.Header().Set("Content-Length", fmt.Sprintf("%d", buffer.Len()))
44
+
45
+ // Serve file from memory
46
+ http.ServeContent(w, r, fileName, time.Now(), bytes.NewReader(buffer.Bytes()))
47
+ }
48
+
49
+ // This certificate is only intended for tests so that certificate parsing step won't fail
50
+ // Never use these certificate for anything outside a test scenario!
51
+ var testingCertificate = `-----BEGIN CERTIFICATE-----
52
+ MIIE8zCCAtugAwIBAgIUXiJ3NER2OjKPD4f4QehH+NRsujIwDQYJKoZIhvcNAQEL
53
+ BQAwFDESMBAGA1UEAwwJbW9jay1vaWRjMB4XDTI1MDYxMzE3MjEyNVoXDTI2MDYx
54
+ MzE3MjEyNVowFDESMBAGA1UEAwwJbW9jay1vaWRjMIICIjANBgkqhkiG9w0BAQEF
55
+ AAOCAg8AMIICCgKCAgEAvJ8n2h7h0ZKNO20MCQuUOn9eyA+VKtkkkoXfZFpsZ/vv
56
+ fvdOe9hNz+X9igJVugfwi9MgKhfPUnGOoWXJB8uwJl4yeHV8lzd5dXYkp3Pi6oCg
57
+ PkGsOwOL7KPQWkCcJDNY8Nj2IsaP+VsdQY2ydCaryztyUBZ8nKs6HWOFsMEPVQUt
58
+ 01SDcWT8lBet6GZ+4QxY+JTnBCZCDoQUk9VAOWucstGfJ9lrC8PBNRNjIXtq88dR
59
+ d4e78RRdTrErwZstZgsjXvfoudNuHeAq5RdCBBuc95sCzHvcbsP7qn4JMDCtk1Xn
60
+ y7Jlh2gTAdLEjqj7yZHgmcRuDTv4AGY3jHXgB2dSYu9PXGBJR0x75O9ILfF/Rvgh
61
+ xqsaqTDmC7lFp1Tc7W0LC0joG0qsmD5Co1xhHpeivsydhI0FKcjZGp0tcKLdE8Nr
62
+ O+za2Tl8IDHkMUBNn1Spf0+MXCX5gVvWkqsvegin6+zz++0ncEqSZLJ1vhUywiJO
63
+ NnNRw8N3iYNfpuFKY3SWGOECVfw57Uzl3YD7p5HNBUSRgjIV5oPtJpluWPb9/v1X
64
+ 1uYoBmerRQ48GOW/S+OeMHoTNHpGT+yFUYlooStsKUzlVg6qgDgGzciXllvSXlNP
65
+ aIk1el5LRWCQ+7NdxyIDZ7z018d5/Nvq4TGtYMxPJ1q2UslsuT8ma8kRdZDLAmcC
66
+ AwEAAaM9MDswGgYDVR0RBBMwEYIJbW9jay1vaWRjhwR/AAABMB0GA1UdDgQWBBTV
67
+ UEwK/9twnd+iP0B7eZFjR9eB3DANBgkqhkiG9w0BAQsFAAOCAgEAeAImntOcqGnN
68
+ 30Y3I36v1tyYC3U109AatLarHvMglhkwmCPjStel0GuyOyxxpnzpbe17vlxSF4Bg
69
+ u/fXoM1PrPn0As/5/MQdbxZs5mDMc1D5ykpo0T+CYlgJNzxBDjCz+lODGf4vH9Ud
70
+ 4ZKLWss0QCYCuF7psyOvwM223mWa63SvWgIBI7vBXcHwk5y4nVAb6jGZVTx0D9Xw
71
+ OTDsxeevpfndTuXQdSHQ09hZlmify7alAPC88Ef3oaudli8QjkNasQswAVKp+0V6
72
+ jKYEHe0XUWcdKX3kT0I1jynh7EKcR/eiHePJv9tR2Trn8bAdgnqvmUwgKPx8mOTp
73
+ tXpkz/72v3Rbbp7/mmg3U9XVIe9i7jroa05sRrrnoqW0j1EGft8MEqYw8gspnbEw
74
+ OI0tw+zwMZ0ikkZzxCn4kn+TRuzGEvUQMz32T++v7YiQwZMgRLOSTuCov0G3Co8F
75
+ LIZf11PYTnOSAmwBLDiONbBOP5OJLnvscZc9bYeEBjSUvFnDeuEb7JduvYuDbche
76
+ zGO07I7oRupj0lzXVtFJJ8D/lTjl9usQ6pFXoFEI8WaOKcUA+kFEHUfKQ9QPrJsP
77
+ MtlI4pJn5rg9W195YH0eMj06QXuy4qi/pPZQHLfx4V7UpVydWemWXeYxVpwy0j2j
78
+ 9CEbs0CkTGfHn/7DvYbVqIy/QMVxsMU=
79
+ -----END CERTIFICATE-----`
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/adminlist/authorizer.go ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package adminlist
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+
18
+ "github.com/weaviate/weaviate/entities/models"
19
+ "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
20
+ )
21
+
22
+ const AnonymousPrincipalUsername = "anonymous"
23
+
24
+ // Authorizer provides either full (admin) or no access
25
+ type Authorizer struct {
26
+ adminUsers map[string]int
27
+ readOnlyUsers map[string]int
28
+ adminGroups map[string]int
29
+ readOnlyGroups map[string]int
30
+ }
31
+
32
+ // New Authorizer using the AdminList method
33
+ func New(cfg Config) *Authorizer {
34
+ a := &Authorizer{}
35
+ a.addAdminUserList(cfg.Users)
36
+ a.addReadOnlyUserList(cfg.ReadOnlyUsers)
37
+ a.addAdminGroupList(cfg.Groups)
38
+ a.addReadOnlyGroupList(cfg.ReadOnlyGroups)
39
+ return a
40
+ }
41
+
42
+ // Authorize will give full access (to any resource!) if the user is part of
43
+ // the admin list or no access at all if they are not
44
+ func (a *Authorizer) Authorize(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
45
+ if principal == nil {
46
+ principal = newAnonymousPrincipal()
47
+ }
48
+
49
+ if _, ok := a.adminUsers[principal.Username]; ok {
50
+ return nil
51
+ }
52
+
53
+ for _, group := range principal.Groups {
54
+ if _, ok := a.adminGroups[group]; ok {
55
+ return nil
56
+ }
57
+ }
58
+
59
+ if verb == "R" {
60
+ if _, ok := a.readOnlyUsers[principal.Username]; ok {
61
+ return nil
62
+ }
63
+ for _, group := range principal.Groups {
64
+ if _, ok := a.readOnlyGroups[group]; ok {
65
+ return nil
66
+ }
67
+ }
68
+ }
69
+
70
+ return fmt.Errorf("adminlist: %w", errors.NewForbidden(principal, verb, resources...))
71
+ }
72
+
73
+ func (a *Authorizer) AuthorizeSilent(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
74
+ return a.Authorize(ctx, principal, verb, resources...)
75
+ }
76
+
77
+ func (a *Authorizer) FilterAuthorizedResources(ctx context.Context, principal *models.Principal, verb string, resources ...string) ([]string, error) {
78
+ if err := a.Authorize(ctx, principal, verb, resources...); err != nil {
79
+ return nil, err
80
+ }
81
+
82
+ return resources, nil
83
+ }
84
+
85
+ func (a *Authorizer) addAdminUserList(users []string) {
86
+ // build a map for more efficient lookup on long lists
87
+ if a.adminUsers == nil {
88
+ a.adminUsers = map[string]int{}
89
+ }
90
+
91
+ for _, user := range users {
92
+ a.adminUsers[user] = 1
93
+ }
94
+ }
95
+
96
+ func (a *Authorizer) addReadOnlyUserList(users []string) {
97
+ // build a map for more efficient lookup on long lists
98
+ if a.readOnlyUsers == nil {
99
+ a.readOnlyUsers = map[string]int{}
100
+ }
101
+
102
+ for _, user := range users {
103
+ a.readOnlyUsers[user] = 1
104
+ }
105
+ }
106
+
107
+ func (a *Authorizer) addAdminGroupList(groups []string) {
108
+ // build a map for more efficient lookup on long lists
109
+ if a.adminGroups == nil {
110
+ a.adminGroups = map[string]int{}
111
+ }
112
+
113
+ for _, group := range groups {
114
+ a.adminGroups[group] = 1
115
+ }
116
+ }
117
+
118
+ func (a *Authorizer) addReadOnlyGroupList(groups []string) {
119
+ // build a map for more efficient lookup on long lists
120
+ if a.readOnlyGroups == nil {
121
+ a.readOnlyGroups = map[string]int{}
122
+ }
123
+
124
+ for _, group := range groups {
125
+ a.readOnlyGroups[group] = 1
126
+ }
127
+ }
128
+
129
+ func newAnonymousPrincipal() *models.Principal {
130
+ return &models.Principal{
131
+ Username: AnonymousPrincipalUsername,
132
+ }
133
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/adminlist/authorizer_test.go ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package adminlist
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "testing"
18
+
19
+ "github.com/stretchr/testify/assert"
20
+ "github.com/weaviate/weaviate/entities/models"
21
+ authZErrors "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
22
+ )
23
+
24
+ func Test_AdminList_Authorizer(t *testing.T) {
25
+ t.Run("with read requests", func(t *testing.T) {
26
+ t.Run("with no users configured at all", func(t *testing.T) {
27
+ cfg := Config{
28
+ Enabled: true,
29
+ Users: []string{},
30
+ }
31
+
32
+ principal := &models.Principal{
33
+ Username: "johndoe",
34
+ }
35
+
36
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
37
+
38
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
39
+ assert.Contains(t, err.Error(), "forbidden")
40
+ assert.Contains(t, err.Error(), "johndoe")
41
+ })
42
+
43
+ t.Run("with a nil principal", func(t *testing.T) {
44
+ cfg := Config{
45
+ Enabled: true,
46
+ Users: []string{},
47
+ }
48
+
49
+ principal := (*models.Principal)(nil)
50
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
51
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
52
+ assert.Contains(t, err.Error(), "forbidden")
53
+ assert.Contains(t, err.Error(), "anonymous")
54
+ })
55
+
56
+ t.Run("with a non-configured user, it denies the request", func(t *testing.T) {
57
+ cfg := Config{
58
+ Enabled: true,
59
+ Users: []string{
60
+ "alice",
61
+ },
62
+ }
63
+
64
+ principal := &models.Principal{
65
+ Username: "johndoe",
66
+ }
67
+
68
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
69
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
70
+ assert.Contains(t, err.Error(), "forbidden")
71
+ assert.Contains(t, err.Error(), "johndoe")
72
+ })
73
+
74
+ t.Run("with a configured admin user, it allows the request", func(t *testing.T) {
75
+ cfg := Config{
76
+ Enabled: true,
77
+ Users: []string{
78
+ "alice",
79
+ "johndoe",
80
+ },
81
+ }
82
+
83
+ principal := &models.Principal{
84
+ Username: "johndoe",
85
+ }
86
+
87
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
88
+ assert.Nil(t, err)
89
+ })
90
+
91
+ t.Run("with a configured read-only user, it allows the request", func(t *testing.T) {
92
+ cfg := Config{
93
+ Enabled: true,
94
+ ReadOnlyUsers: []string{
95
+ "alice",
96
+ "johndoe",
97
+ },
98
+ }
99
+
100
+ principal := &models.Principal{
101
+ Username: "johndoe",
102
+ }
103
+
104
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
105
+ assert.Nil(t, err)
106
+ })
107
+
108
+ t.Run("with anonymous as read-only user and no principal, it allows the request", func(t *testing.T) {
109
+ cfg := Config{
110
+ Enabled: true,
111
+ ReadOnlyUsers: []string{
112
+ "anonymous",
113
+ },
114
+ }
115
+
116
+ principal := (*models.Principal)(nil)
117
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
118
+ assert.Nil(t, err)
119
+ })
120
+ })
121
+
122
+ t.Run("with a non-configured group, it denies the request", func(t *testing.T) {
123
+ cfg := Config{
124
+ Enabled: true,
125
+ Groups: []string{
126
+ "band",
127
+ },
128
+ }
129
+
130
+ principal := &models.Principal{
131
+ Username: "alice",
132
+ Groups: []string{
133
+ "posse",
134
+ },
135
+ }
136
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
137
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
138
+ assert.Contains(t, err.Error(), "forbidden")
139
+ assert.Contains(t, err.Error(), "posse")
140
+ assert.Contains(t, err.Error(), "alice")
141
+ })
142
+
143
+ t.Run("with a configured admin group, it allows the request", func(t *testing.T) {
144
+ cfg := Config{
145
+ Enabled: true,
146
+ Groups: []string{
147
+ "band",
148
+ "posse",
149
+ },
150
+ }
151
+
152
+ principal := &models.Principal{
153
+ Username: "alice",
154
+ Groups: []string{
155
+ "posse",
156
+ },
157
+ }
158
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
159
+ assert.Nil(t, err)
160
+ })
161
+
162
+ t.Run("with a configured read-only group, it allows the request", func(t *testing.T) {
163
+ cfg := Config{
164
+ Enabled: true,
165
+ ReadOnlyGroups: []string{
166
+ "band",
167
+ "posse",
168
+ },
169
+ }
170
+
171
+ principal := &models.Principal{
172
+ Username: "johndoe",
173
+ Groups: []string{
174
+ "posse",
175
+ },
176
+ }
177
+
178
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
179
+ assert.Nil(t, err)
180
+ })
181
+
182
+ t.Run("with a configured admin user and non-configured group, it allows the request", func(t *testing.T) {
183
+ cfg := Config{
184
+ Enabled: true,
185
+ Users: []string{
186
+ "alice",
187
+ "johndoe",
188
+ },
189
+ Groups: []string{
190
+ "band",
191
+ },
192
+ }
193
+
194
+ principal := &models.Principal{
195
+ Username: "johndoe",
196
+ Groups: []string{
197
+ "posse",
198
+ },
199
+ }
200
+
201
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
202
+ assert.Nil(t, err)
203
+ })
204
+
205
+ t.Run("with a configured read-only user and non-configured read-only group, it allows the request", func(t *testing.T) {
206
+ cfg := Config{
207
+ Enabled: true,
208
+ ReadOnlyUsers: []string{
209
+ "alice",
210
+ "johndoe",
211
+ },
212
+ ReadOnlyGroups: []string{
213
+ "band",
214
+ },
215
+ }
216
+
217
+ principal := &models.Principal{
218
+ Username: "johndoe",
219
+ Groups: []string{
220
+ "posse",
221
+ },
222
+ }
223
+
224
+ err := New(cfg).Authorize(context.Background(), principal, "R", "things")
225
+ assert.Nil(t, err)
226
+ })
227
+
228
+ t.Run("with write/delete requests", func(t *testing.T) {
229
+ t.Run("with a nil principal", func(t *testing.T) {
230
+ cfg := Config{
231
+ Enabled: true,
232
+ Users: []string{},
233
+ }
234
+
235
+ principal := (*models.Principal)(nil)
236
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
237
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
238
+ assert.Contains(t, err.Error(), "forbidden")
239
+ assert.Contains(t, err.Error(), "anonymous")
240
+ })
241
+
242
+ t.Run("with no users configured at all", func(t *testing.T) {
243
+ cfg := Config{
244
+ Enabled: true,
245
+ Users: []string{},
246
+ }
247
+
248
+ principal := &models.Principal{
249
+ Username: "johndoe",
250
+ }
251
+
252
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
253
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
254
+ assert.Contains(t, err.Error(), "forbidden")
255
+ assert.Contains(t, err.Error(), "johndoe")
256
+ })
257
+
258
+ t.Run("with a non-configured user, it denies the request", func(t *testing.T) {
259
+ cfg := Config{
260
+ Enabled: true,
261
+ Users: []string{
262
+ "alice",
263
+ },
264
+ }
265
+
266
+ principal := &models.Principal{
267
+ Username: "johndoe",
268
+ }
269
+
270
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
271
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
272
+ assert.Contains(t, err.Error(), "forbidden")
273
+ assert.Contains(t, err.Error(), "johndoe")
274
+ })
275
+
276
+ t.Run("with an empty user, it denies the request", func(t *testing.T) {
277
+ cfg := Config{
278
+ Enabled: true,
279
+ Users: []string{
280
+ "alice",
281
+ },
282
+ }
283
+
284
+ principal := &models.Principal{
285
+ Username: "",
286
+ }
287
+
288
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
289
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
290
+ assert.Contains(t, err.Error(), "forbidden")
291
+ })
292
+
293
+ t.Run("with a configured admin user, it allows the request", func(t *testing.T) {
294
+ cfg := Config{
295
+ Enabled: true,
296
+ Users: []string{
297
+ "alice",
298
+ "johndoe",
299
+ },
300
+ }
301
+
302
+ principal := &models.Principal{
303
+ Username: "johndoe",
304
+ }
305
+
306
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
307
+ assert.Nil(t, err)
308
+ })
309
+
310
+ t.Run("with a configured read-only user, it denies the request", func(t *testing.T) {
311
+ cfg := Config{
312
+ Enabled: true,
313
+ ReadOnlyUsers: []string{
314
+ "alice",
315
+ "johndoe",
316
+ },
317
+ }
318
+
319
+ principal := &models.Principal{
320
+ Username: "johndoe",
321
+ }
322
+
323
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
324
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
325
+ assert.Contains(t, err.Error(), "forbidden")
326
+ assert.Contains(t, err.Error(), "johndoe")
327
+ })
328
+
329
+ t.Run("with anonymous on the read-only list and a nil principal", func(t *testing.T) {
330
+ cfg := Config{
331
+ Enabled: true,
332
+ Users: []string{},
333
+ ReadOnlyUsers: []string{
334
+ "anonymous",
335
+ },
336
+ }
337
+
338
+ principal := (*models.Principal)(nil)
339
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
340
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
341
+ assert.Contains(t, err.Error(), "forbidden")
342
+ assert.Contains(t, err.Error(), "anonymous")
343
+ })
344
+
345
+ t.Run("with a non-configured group, it denies the request", func(t *testing.T) {
346
+ cfg := Config{
347
+ Enabled: true,
348
+ Groups: []string{
349
+ "band",
350
+ },
351
+ }
352
+
353
+ principal := &models.Principal{
354
+ Username: "johndoe",
355
+ Groups: []string{
356
+ "posse",
357
+ },
358
+ }
359
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
360
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
361
+ assert.Contains(t, err.Error(), "forbidden")
362
+ assert.Contains(t, err.Error(), "posse")
363
+ assert.Contains(t, err.Error(), "johndoe")
364
+ })
365
+
366
+ t.Run("with an empty group, it denies the request", func(t *testing.T) {
367
+ cfg := Config{
368
+ Enabled: true,
369
+ Groups: []string{
370
+ "band",
371
+ },
372
+ }
373
+
374
+ principal := &models.Principal{
375
+ Username: "johndoe",
376
+ Groups: []string{},
377
+ }
378
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
379
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
380
+ assert.Contains(t, err.Error(), "forbidden")
381
+ assert.Contains(t, err.Error(), "johndoe")
382
+ })
383
+
384
+ t.Run("with a configured admin group, it allows the request", func(t *testing.T) {
385
+ cfg := Config{
386
+ Enabled: true,
387
+ Groups: []string{
388
+ "band",
389
+ "posse",
390
+ },
391
+ }
392
+
393
+ principal := &models.Principal{
394
+ Username: "johndoe",
395
+ Groups: []string{
396
+ "band",
397
+ },
398
+ }
399
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
400
+ assert.Nil(t, err)
401
+ })
402
+
403
+ t.Run("with a configured read-only group, it denies the request", func(t *testing.T) {
404
+ cfg := Config{
405
+ Enabled: true,
406
+ ReadOnlyGroups: []string{
407
+ "band",
408
+ "posse",
409
+ },
410
+ }
411
+
412
+ principal := &models.Principal{
413
+ Username: "johndoe",
414
+ Groups: []string{
415
+ "posse",
416
+ },
417
+ }
418
+
419
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
420
+ assert.True(t, errors.As(err, &authZErrors.Forbidden{}))
421
+ assert.Contains(t, err.Error(), "forbidden")
422
+ assert.Contains(t, err.Error(), "johndoe")
423
+ assert.Contains(t, err.Error(), "posse")
424
+ })
425
+
426
+ t.Run("with a configured admin user and non-configured group, it allows the request", func(t *testing.T) {
427
+ cfg := Config{
428
+ Enabled: true,
429
+ Users: []string{
430
+ "alice",
431
+ "johndoe",
432
+ },
433
+ Groups: []string{
434
+ "band",
435
+ },
436
+ }
437
+
438
+ principal := &models.Principal{
439
+ Username: "johndoe",
440
+ Groups: []string{
441
+ "posse",
442
+ },
443
+ }
444
+
445
+ err := New(cfg).Authorize(context.Background(), principal, "create", "things")
446
+ assert.Nil(t, err)
447
+ })
448
+ })
449
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/adminlist/config.go ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package adminlist
13
+
14
+ import "fmt"
15
+
16
+ // Config makes every subject on the list an admin, whereas everyone else
17
+ // has no rights whatsoever
18
+ type Config struct {
19
+ Enabled bool `json:"enabled" yaml:"enabled"`
20
+ Users []string `json:"users" yaml:"users"`
21
+ ReadOnlyUsers []string `json:"read_only_users" yaml:"read_only_users"`
22
+ Groups []string `json:"groups" yaml:"groups"`
23
+ ReadOnlyGroups []string `json:"read_only_groups" yaml:"read_only_groups"`
24
+ }
25
+
26
+ // Validate admin list config for viability, can be called from the central
27
+ // config package
28
+ func (c Config) Validate() error {
29
+ return c.validateOverlap()
30
+ }
31
+
32
+ // we are expecting both lists to always contain few subjects and know that
33
+ // this comparison is only done once (at startup). We are therefore fine with
34
+ // the O(n^2) complexity of this very primitive overlap search in favor of very
35
+ // simple code.
36
+ func (c Config) validateOverlap() error {
37
+ for _, a := range c.Users {
38
+ for _, b := range c.ReadOnlyUsers {
39
+ if a == b {
40
+ return fmt.Errorf("admin list: subject '%s' is present on both admin and read-only list", a)
41
+ }
42
+ }
43
+ }
44
+ for _, a := range c.Groups {
45
+ for _, b := range c.ReadOnlyGroups {
46
+ if a == b {
47
+ return fmt.Errorf("admin list: subject '%s' is present on both admin and read-only list", a)
48
+ }
49
+ }
50
+ }
51
+
52
+ return nil
53
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/adminlist/config_test.go ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package adminlist
13
+
14
+ import (
15
+ "fmt"
16
+ "testing"
17
+
18
+ "github.com/stretchr/testify/assert"
19
+ )
20
+
21
+ func Test_Validation(t *testing.T) {
22
+ t.Run("with only an admin user list set", func(t *testing.T) {
23
+ cfg := Config{
24
+ Enabled: true,
25
+ Users: []string{
26
+ "alice",
27
+ "johndoe",
28
+ },
29
+ }
30
+
31
+ err := cfg.Validate()
32
+ assert.Nil(t, err)
33
+ })
34
+
35
+ t.Run("with only a read only user list set", func(t *testing.T) {
36
+ cfg := Config{
37
+ Enabled: true,
38
+ ReadOnlyUsers: []string{
39
+ "alice",
40
+ "johndoe",
41
+ },
42
+ }
43
+
44
+ err := cfg.Validate()
45
+ assert.Nil(t, err)
46
+ })
47
+
48
+ t.Run("with both user lists present, but no overlap", func(t *testing.T) {
49
+ cfg := Config{
50
+ Enabled: true,
51
+ Users: []string{
52
+ "alice",
53
+ },
54
+ ReadOnlyUsers: []string{
55
+ "johndoe",
56
+ },
57
+ }
58
+
59
+ err := cfg.Validate()
60
+ assert.Nil(t, err)
61
+ })
62
+
63
+ t.Run("with one subject part of both user lists", func(t *testing.T) {
64
+ cfg := Config{
65
+ Enabled: true,
66
+ Users: []string{
67
+ "alice",
68
+ "johndoe",
69
+ },
70
+ ReadOnlyUsers: []string{
71
+ "johndoe",
72
+ },
73
+ }
74
+
75
+ err := cfg.Validate()
76
+ assert.Equal(t, err, fmt.Errorf("admin list: subject 'johndoe' is present on both admin and read-only list"))
77
+ })
78
+
79
+ t.Run("with only an admin group list set", func(t *testing.T) {
80
+ cfg := Config{
81
+ Enabled: true,
82
+ Groups: []string{
83
+ "band",
84
+ "posse",
85
+ },
86
+ }
87
+
88
+ err := cfg.Validate()
89
+ assert.Nil(t, err)
90
+ })
91
+
92
+ t.Run("with only a read only group list set", func(t *testing.T) {
93
+ cfg := Config{
94
+ Enabled: true,
95
+ ReadOnlyGroups: []string{
96
+ "band",
97
+ "posse",
98
+ },
99
+ }
100
+
101
+ err := cfg.Validate()
102
+ assert.Nil(t, err)
103
+ })
104
+
105
+ t.Run("with both group lists present, but no overlap", func(t *testing.T) {
106
+ cfg := Config{
107
+ Enabled: true,
108
+ Groups: []string{
109
+ "band",
110
+ },
111
+ ReadOnlyGroups: []string{
112
+ "posse",
113
+ },
114
+ }
115
+
116
+ err := cfg.Validate()
117
+ assert.Nil(t, err)
118
+ })
119
+
120
+ t.Run("with one subject part of both group lists", func(t *testing.T) {
121
+ cfg := Config{
122
+ Enabled: true,
123
+ Groups: []string{
124
+ "band",
125
+ "posse",
126
+ },
127
+ ReadOnlyGroups: []string{
128
+ "posse",
129
+ },
130
+ }
131
+
132
+ err := cfg.Validate()
133
+ assert.Equal(t, err, fmt.Errorf("admin list: subject 'posse' is present on both admin and read-only list"))
134
+ })
135
+
136
+ t.Run("with both admin user and groups present", func(t *testing.T) {
137
+ cfg := Config{
138
+ Enabled: true,
139
+ Users: []string{
140
+ "alice",
141
+ "johndoe",
142
+ },
143
+ Groups: []string{
144
+ "band",
145
+ "posse",
146
+ },
147
+ }
148
+
149
+ err := cfg.Validate()
150
+ assert.Nil(t, err)
151
+ })
152
+
153
+ t.Run("with an admin user and read only group set", func(t *testing.T) {
154
+ cfg := Config{
155
+ Enabled: true,
156
+ Users: []string{
157
+ "alice",
158
+ "johndoe",
159
+ },
160
+ ReadOnlyGroups: []string{
161
+ "band",
162
+ "posse",
163
+ },
164
+ }
165
+
166
+ err := cfg.Validate()
167
+ assert.Nil(t, err)
168
+ })
169
+
170
+ t.Run("with both read only user and groups present", func(t *testing.T) {
171
+ cfg := Config{
172
+ Enabled: true,
173
+ ReadOnlyUsers: []string{
174
+ "alice",
175
+ "johndoe",
176
+ },
177
+ ReadOnlyGroups: []string{
178
+ "band",
179
+ "posse",
180
+ },
181
+ }
182
+
183
+ err := cfg.Validate()
184
+ assert.Nil(t, err)
185
+ })
186
+
187
+ t.Run("with a read only user and admin group set", func(t *testing.T) {
188
+ cfg := Config{
189
+ Enabled: true,
190
+ ReadOnlyUsers: []string{
191
+ "alice",
192
+ "johndoe",
193
+ },
194
+ Groups: []string{
195
+ "band",
196
+ "posse",
197
+ },
198
+ }
199
+
200
+ err := cfg.Validate()
201
+ assert.Nil(t, err)
202
+ })
203
+
204
+ t.Run("all user and group attributes present", func(t *testing.T) {
205
+ cfg := Config{
206
+ Enabled: true,
207
+ Users: []string{
208
+ "alice",
209
+ },
210
+ ReadOnlyUsers: []string{
211
+ "johndoe",
212
+ },
213
+ Groups: []string{
214
+ "band",
215
+ },
216
+ ReadOnlyGroups: []string{
217
+ "posse",
218
+ },
219
+ }
220
+
221
+ err := cfg.Validate()
222
+ assert.Nil(t, err)
223
+ })
224
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/authorizer.go ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package authorization
13
+
14
+ import (
15
+ "context"
16
+
17
+ "github.com/weaviate/weaviate/entities/models"
18
+ )
19
+
20
+ // Authorizer always makes a yes/no decision on a specific resource. Which
21
+ // authorization technique is used in the background (e.g. RBAC, adminlist,
22
+ // ...) is hidden through this interface
23
+ type Authorizer interface {
24
+ Authorize(ctx context.Context, principal *models.Principal, verb string, resources ...string) error
25
+ // AuthorizeSilent Silent authorization without audit logs
26
+ AuthorizeSilent(ctx context.Context, principal *models.Principal, verb string, resources ...string) error
27
+ // FilterAuthorizedResources authorize the passed resources with best effort approach, it will return
28
+ // list of allowed resources, if none, it will return an empty slice
29
+ FilterAuthorizedResources(ctx context.Context, principal *models.Principal, verb string, resources ...string) ([]string, error)
30
+ }
31
+
32
+ // DummyAuthorizer is a pluggable Authorizer which can be used if no specific
33
+ // authorizer is configured. It will allow every auth decision, i.e. it is
34
+ // effectively the same as "no authorization at all"
35
+ type DummyAuthorizer struct{}
36
+
37
+ // Authorize on the DummyAuthorizer will allow any subject access to any
38
+ // resource
39
+ func (d *DummyAuthorizer) Authorize(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
40
+ return nil
41
+ }
42
+
43
+ func (d *DummyAuthorizer) AuthorizeSilent(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
44
+ return nil
45
+ }
46
+
47
+ func (d *DummyAuthorizer) FilterAuthorizedResources(ctx context.Context, principal *models.Principal, verb string, resources ...string) ([]string, error) {
48
+ return resources, nil
49
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/controller.go ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package authorization
13
+
14
+ import (
15
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
16
+ )
17
+
18
+ type Controller interface {
19
+ UpdateRolesPermissions(roles map[string][]Policy) error
20
+ CreateRolesPermissions(roles map[string][]Policy) error
21
+ GetRoles(names ...string) (map[string][]Policy, error)
22
+ DeleteRoles(roles ...string) error
23
+ AddRolesForUser(user string, roles []string) error
24
+ GetRolesForUserOrGroup(user string, authMethod authentication.AuthType, isGroup bool) (map[string][]Policy, error)
25
+ GetUsersOrGroupForRole(role string, authMethod authentication.AuthType, IsGroup bool) ([]string, error)
26
+ RevokeRolesForUser(user string, roles ...string) error
27
+ RemovePermissions(role string, permissions []*Policy) error
28
+ HasPermission(role string, permission *Policy) (bool, error)
29
+ GetUsersOrGroupsWithRoles(isGroup bool, authMethod authentication.AuthType) ([]string, error)
30
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/conv/casbin_converter.go ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package conv
13
+
14
+ import (
15
+ "fmt"
16
+ "slices"
17
+ "strings"
18
+
19
+ "github.com/weaviate/weaviate/entities/models"
20
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
21
+ )
22
+
23
+ func RolesToPolicies(roles ...*models.Role) (map[string][]authorization.Policy, error) {
24
+ rolesmap := make(map[string][]authorization.Policy)
25
+ for idx := range roles {
26
+ rolesmap[*roles[idx].Name] = []authorization.Policy{}
27
+ for _, permission := range roles[idx].Permissions {
28
+ policy, err := policy(permission)
29
+ if err != nil {
30
+ return rolesmap, fmt.Errorf("policy: %w", err)
31
+ }
32
+ rolesmap[*roles[idx].Name] = append(rolesmap[*roles[idx].Name], *policy)
33
+ }
34
+ }
35
+
36
+ return rolesmap, nil
37
+ }
38
+
39
+ func PermissionToPolicies(permissions ...*models.Permission) ([]*authorization.Policy, error) {
40
+ policies := []*authorization.Policy{}
41
+ for idx := range permissions {
42
+ policy, err := policy(permissions[idx])
43
+ if err != nil {
44
+ return nil, fmt.Errorf("policy: %w", err)
45
+ }
46
+ policies = append(policies, policy)
47
+ }
48
+
49
+ return policies, nil
50
+ }
51
+
52
+ func PathToPermission(verb, path string) (*models.Permission, error) {
53
+ parts := strings.Split(path, "/")
54
+ if len(parts) < 1 {
55
+ return nil, fmt.Errorf("invalid path")
56
+ }
57
+
58
+ return permission([]string{"", path, verb, parts[0]}, false)
59
+ }
60
+
61
+ func PoliciesToPermission(policies ...authorization.Policy) ([]*models.Permission, error) {
62
+ permissions := []*models.Permission{}
63
+ for idx := range policies {
64
+ // 1st empty string to replace casbin pattern of having policy name as 1st place
65
+ // e.g. tester, roles/.*, (C)|(R)|(U)|(D), roles
66
+ // see newPolicy()
67
+ perm, err := permission([]string{"", policies[idx].Resource, policies[idx].Verb, policies[idx].Domain}, true)
68
+ if err != nil {
69
+ return nil, err
70
+ }
71
+ if perm.Action == nil {
72
+ continue
73
+ }
74
+ permissions = append(permissions, perm)
75
+ }
76
+ return permissions, nil
77
+ }
78
+
79
+ func CasbinPolicies(casbinPolicies ...[][]string) (map[string][]authorization.Policy, error) {
80
+ rolesPermissions := make(map[string][]authorization.Policy)
81
+ for _, p := range casbinPolicies {
82
+ for _, policyParts := range p {
83
+ name := TrimRoleNamePrefix(policyParts[0])
84
+ if slices.Contains(authorization.BuiltInRoles, name) {
85
+ perms := authorization.BuiltInPermissions[name]
86
+ for _, p := range perms {
87
+ perm, err := policy(p)
88
+ if err != nil {
89
+ return nil, fmt.Errorf("policy: %w", err)
90
+ }
91
+ rolesPermissions[name] = append(rolesPermissions[name], *perm)
92
+ }
93
+ } else {
94
+ perm, err := permission(policyParts, true)
95
+ if err != nil {
96
+ return nil, fmt.Errorf("permission: %w", err)
97
+ }
98
+ weaviatePerm, err := policy(perm)
99
+ if err != nil {
100
+ return nil, fmt.Errorf("policy: %w", err)
101
+ }
102
+ rolesPermissions[name] = append(rolesPermissions[name], *weaviatePerm)
103
+ }
104
+ }
105
+ }
106
+ return rolesPermissions, nil
107
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/mock_authorizer.go ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ // Code generated by mockery v2.53.2. DO NOT EDIT.
13
+
14
+ package authorization
15
+
16
+ import (
17
+ context "context"
18
+
19
+ mock "github.com/stretchr/testify/mock"
20
+ models "github.com/weaviate/weaviate/entities/models"
21
+ )
22
+
23
+ // MockAuthorizer is an autogenerated mock type for the Authorizer type
24
+ type MockAuthorizer struct {
25
+ mock.Mock
26
+ }
27
+
28
+ type MockAuthorizer_Expecter struct {
29
+ mock *mock.Mock
30
+ }
31
+
32
+ func (_m *MockAuthorizer) EXPECT() *MockAuthorizer_Expecter {
33
+ return &MockAuthorizer_Expecter{mock: &_m.Mock}
34
+ }
35
+
36
+ // Authorize provides a mock function with given fields: ctx, principal, verb, resources
37
+ func (_m *MockAuthorizer) Authorize(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
38
+ _va := make([]interface{}, len(resources))
39
+ for _i := range resources {
40
+ _va[_i] = resources[_i]
41
+ }
42
+ var _ca []interface{}
43
+ _ca = append(_ca, ctx, principal, verb)
44
+ _ca = append(_ca, _va...)
45
+ ret := _m.Called(_ca...)
46
+
47
+ if len(ret) == 0 {
48
+ panic("no return value specified for Authorize")
49
+ }
50
+
51
+ var r0 error
52
+ if rf, ok := ret.Get(0).(func(context.Context, *models.Principal, string, ...string) error); ok {
53
+ r0 = rf(ctx, principal, verb, resources...)
54
+ } else {
55
+ r0 = ret.Error(0)
56
+ }
57
+
58
+ return r0
59
+ }
60
+
61
+ // MockAuthorizer_Authorize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Authorize'
62
+ type MockAuthorizer_Authorize_Call struct {
63
+ *mock.Call
64
+ }
65
+
66
+ // Authorize is a helper method to define mock.On call
67
+ // - ctx context.Context
68
+ // - principal *models.Principal
69
+ // - verb string
70
+ // - resources ...string
71
+ func (_e *MockAuthorizer_Expecter) Authorize(ctx interface{}, principal interface{}, verb interface{}, resources ...interface{}) *MockAuthorizer_Authorize_Call {
72
+ return &MockAuthorizer_Authorize_Call{Call: _e.mock.On("Authorize",
73
+ append([]interface{}{ctx, principal, verb}, resources...)...)}
74
+ }
75
+
76
+ func (_c *MockAuthorizer_Authorize_Call) Run(run func(ctx context.Context, principal *models.Principal, verb string, resources ...string)) *MockAuthorizer_Authorize_Call {
77
+ _c.Call.Run(func(args mock.Arguments) {
78
+ variadicArgs := make([]string, len(args)-3)
79
+ for i, a := range args[3:] {
80
+ if a != nil {
81
+ variadicArgs[i] = a.(string)
82
+ }
83
+ }
84
+ run(args[0].(context.Context), args[1].(*models.Principal), args[2].(string), variadicArgs...)
85
+ })
86
+ return _c
87
+ }
88
+
89
+ func (_c *MockAuthorizer_Authorize_Call) Return(_a0 error) *MockAuthorizer_Authorize_Call {
90
+ _c.Call.Return(_a0)
91
+ return _c
92
+ }
93
+
94
+ func (_c *MockAuthorizer_Authorize_Call) RunAndReturn(run func(context.Context, *models.Principal, string, ...string) error) *MockAuthorizer_Authorize_Call {
95
+ _c.Call.Return(run)
96
+ return _c
97
+ }
98
+
99
+ // AuthorizeSilent provides a mock function with given fields: ctx, principal, verb, resources
100
+ func (_m *MockAuthorizer) AuthorizeSilent(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
101
+ _va := make([]interface{}, len(resources))
102
+ for _i := range resources {
103
+ _va[_i] = resources[_i]
104
+ }
105
+ var _ca []interface{}
106
+ _ca = append(_ca, ctx, principal, verb)
107
+ _ca = append(_ca, _va...)
108
+ ret := _m.Called(_ca...)
109
+
110
+ if len(ret) == 0 {
111
+ panic("no return value specified for AuthorizeSilent")
112
+ }
113
+
114
+ var r0 error
115
+ if rf, ok := ret.Get(0).(func(context.Context, *models.Principal, string, ...string) error); ok {
116
+ r0 = rf(ctx, principal, verb, resources...)
117
+ } else {
118
+ r0 = ret.Error(0)
119
+ }
120
+
121
+ return r0
122
+ }
123
+
124
+ // MockAuthorizer_AuthorizeSilent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AuthorizeSilent'
125
+ type MockAuthorizer_AuthorizeSilent_Call struct {
126
+ *mock.Call
127
+ }
128
+
129
+ // AuthorizeSilent is a helper method to define mock.On call
130
+ // - ctx context.Context
131
+ // - principal *models.Principal
132
+ // - verb string
133
+ // - resources ...string
134
+ func (_e *MockAuthorizer_Expecter) AuthorizeSilent(ctx interface{}, principal interface{}, verb interface{}, resources ...interface{}) *MockAuthorizer_AuthorizeSilent_Call {
135
+ return &MockAuthorizer_AuthorizeSilent_Call{Call: _e.mock.On("AuthorizeSilent",
136
+ append([]interface{}{ctx, principal, verb}, resources...)...)}
137
+ }
138
+
139
+ func (_c *MockAuthorizer_AuthorizeSilent_Call) Run(run func(ctx context.Context, principal *models.Principal, verb string, resources ...string)) *MockAuthorizer_AuthorizeSilent_Call {
140
+ _c.Call.Run(func(args mock.Arguments) {
141
+ variadicArgs := make([]string, len(args)-3)
142
+ for i, a := range args[3:] {
143
+ if a != nil {
144
+ variadicArgs[i] = a.(string)
145
+ }
146
+ }
147
+ run(args[0].(context.Context), args[1].(*models.Principal), args[2].(string), variadicArgs...)
148
+ })
149
+ return _c
150
+ }
151
+
152
+ func (_c *MockAuthorizer_AuthorizeSilent_Call) Return(_a0 error) *MockAuthorizer_AuthorizeSilent_Call {
153
+ _c.Call.Return(_a0)
154
+ return _c
155
+ }
156
+
157
+ func (_c *MockAuthorizer_AuthorizeSilent_Call) RunAndReturn(run func(context.Context, *models.Principal, string, ...string) error) *MockAuthorizer_AuthorizeSilent_Call {
158
+ _c.Call.Return(run)
159
+ return _c
160
+ }
161
+
162
+ // FilterAuthorizedResources provides a mock function with given fields: ctx, principal, verb, resources
163
+ func (_m *MockAuthorizer) FilterAuthorizedResources(ctx context.Context, principal *models.Principal, verb string, resources ...string) ([]string, error) {
164
+ _va := make([]interface{}, len(resources))
165
+ for _i := range resources {
166
+ _va[_i] = resources[_i]
167
+ }
168
+ var _ca []interface{}
169
+ _ca = append(_ca, ctx, principal, verb)
170
+ _ca = append(_ca, _va...)
171
+ ret := _m.Called(_ca...)
172
+
173
+ if len(ret) == 0 {
174
+ panic("no return value specified for FilterAuthorizedResources")
175
+ }
176
+
177
+ var r0 []string
178
+ var r1 error
179
+ if rf, ok := ret.Get(0).(func(context.Context, *models.Principal, string, ...string) ([]string, error)); ok {
180
+ return rf(ctx, principal, verb, resources...)
181
+ }
182
+ if rf, ok := ret.Get(0).(func(context.Context, *models.Principal, string, ...string) []string); ok {
183
+ r0 = rf(ctx, principal, verb, resources...)
184
+ } else {
185
+ if ret.Get(0) != nil {
186
+ r0 = ret.Get(0).([]string)
187
+ }
188
+ }
189
+
190
+ if rf, ok := ret.Get(1).(func(context.Context, *models.Principal, string, ...string) error); ok {
191
+ r1 = rf(ctx, principal, verb, resources...)
192
+ } else {
193
+ r1 = ret.Error(1)
194
+ }
195
+
196
+ return r0, r1
197
+ }
198
+
199
+ // MockAuthorizer_FilterAuthorizedResources_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FilterAuthorizedResources'
200
+ type MockAuthorizer_FilterAuthorizedResources_Call struct {
201
+ *mock.Call
202
+ }
203
+
204
+ // FilterAuthorizedResources is a helper method to define mock.On call
205
+ // - ctx context.Context
206
+ // - principal *models.Principal
207
+ // - verb string
208
+ // - resources ...string
209
+ func (_e *MockAuthorizer_Expecter) FilterAuthorizedResources(ctx interface{}, principal interface{}, verb interface{}, resources ...interface{}) *MockAuthorizer_FilterAuthorizedResources_Call {
210
+ return &MockAuthorizer_FilterAuthorizedResources_Call{Call: _e.mock.On("FilterAuthorizedResources",
211
+ append([]interface{}{ctx, principal, verb}, resources...)...)}
212
+ }
213
+
214
+ func (_c *MockAuthorizer_FilterAuthorizedResources_Call) Run(run func(ctx context.Context, principal *models.Principal, verb string, resources ...string)) *MockAuthorizer_FilterAuthorizedResources_Call {
215
+ _c.Call.Run(func(args mock.Arguments) {
216
+ variadicArgs := make([]string, len(args)-3)
217
+ for i, a := range args[3:] {
218
+ if a != nil {
219
+ variadicArgs[i] = a.(string)
220
+ }
221
+ }
222
+ run(args[0].(context.Context), args[1].(*models.Principal), args[2].(string), variadicArgs...)
223
+ })
224
+ return _c
225
+ }
226
+
227
+ func (_c *MockAuthorizer_FilterAuthorizedResources_Call) Return(_a0 []string, _a1 error) *MockAuthorizer_FilterAuthorizedResources_Call {
228
+ _c.Call.Return(_a0, _a1)
229
+ return _c
230
+ }
231
+
232
+ func (_c *MockAuthorizer_FilterAuthorizedResources_Call) RunAndReturn(run func(context.Context, *models.Principal, string, ...string) ([]string, error)) *MockAuthorizer_FilterAuthorizedResources_Call {
233
+ _c.Call.Return(run)
234
+ return _c
235
+ }
236
+
237
+ // NewMockAuthorizer creates a new instance of MockAuthorizer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
238
+ // The first argument is typically a *testing.T value.
239
+ func NewMockAuthorizer(t interface {
240
+ mock.TestingT
241
+ Cleanup(func())
242
+ }) *MockAuthorizer {
243
+ mock := &MockAuthorizer{}
244
+ mock.Mock.Test(t)
245
+
246
+ t.Cleanup(func() { mock.AssertExpectations(t) })
247
+
248
+ return mock
249
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/mock_controller.go ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ // Code generated by mockery v2.53.2. DO NOT EDIT.
13
+
14
+ package authorization
15
+
16
+ import (
17
+ mock "github.com/stretchr/testify/mock"
18
+ authentication "github.com/weaviate/weaviate/usecases/auth/authentication"
19
+ )
20
+
21
+ // MockController is an autogenerated mock type for the Controller type
22
+ type MockController struct {
23
+ mock.Mock
24
+ }
25
+
26
+ type MockController_Expecter struct {
27
+ mock *mock.Mock
28
+ }
29
+
30
+ func (_m *MockController) EXPECT() *MockController_Expecter {
31
+ return &MockController_Expecter{mock: &_m.Mock}
32
+ }
33
+
34
+ // AddRolesForUser provides a mock function with given fields: user, roles
35
+ func (_m *MockController) AddRolesForUser(user string, roles []string) error {
36
+ ret := _m.Called(user, roles)
37
+
38
+ if len(ret) == 0 {
39
+ panic("no return value specified for AddRolesForUser")
40
+ }
41
+
42
+ var r0 error
43
+ if rf, ok := ret.Get(0).(func(string, []string) error); ok {
44
+ r0 = rf(user, roles)
45
+ } else {
46
+ r0 = ret.Error(0)
47
+ }
48
+
49
+ return r0
50
+ }
51
+
52
+ // MockController_AddRolesForUser_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddRolesForUser'
53
+ type MockController_AddRolesForUser_Call struct {
54
+ *mock.Call
55
+ }
56
+
57
+ // AddRolesForUser is a helper method to define mock.On call
58
+ // - user string
59
+ // - roles []string
60
+ func (_e *MockController_Expecter) AddRolesForUser(user interface{}, roles interface{}) *MockController_AddRolesForUser_Call {
61
+ return &MockController_AddRolesForUser_Call{Call: _e.mock.On("AddRolesForUser", user, roles)}
62
+ }
63
+
64
+ func (_c *MockController_AddRolesForUser_Call) Run(run func(user string, roles []string)) *MockController_AddRolesForUser_Call {
65
+ _c.Call.Run(func(args mock.Arguments) {
66
+ run(args[0].(string), args[1].([]string))
67
+ })
68
+ return _c
69
+ }
70
+
71
+ func (_c *MockController_AddRolesForUser_Call) Return(_a0 error) *MockController_AddRolesForUser_Call {
72
+ _c.Call.Return(_a0)
73
+ return _c
74
+ }
75
+
76
+ func (_c *MockController_AddRolesForUser_Call) RunAndReturn(run func(string, []string) error) *MockController_AddRolesForUser_Call {
77
+ _c.Call.Return(run)
78
+ return _c
79
+ }
80
+
81
+ // CreateRolesPermissions provides a mock function with given fields: roles
82
+ func (_m *MockController) CreateRolesPermissions(roles map[string][]Policy) error {
83
+ ret := _m.Called(roles)
84
+
85
+ if len(ret) == 0 {
86
+ panic("no return value specified for CreateRolesPermissions")
87
+ }
88
+
89
+ var r0 error
90
+ if rf, ok := ret.Get(0).(func(map[string][]Policy) error); ok {
91
+ r0 = rf(roles)
92
+ } else {
93
+ r0 = ret.Error(0)
94
+ }
95
+
96
+ return r0
97
+ }
98
+
99
+ // MockController_CreateRolesPermissions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateRolesPermissions'
100
+ type MockController_CreateRolesPermissions_Call struct {
101
+ *mock.Call
102
+ }
103
+
104
+ // CreateRolesPermissions is a helper method to define mock.On call
105
+ // - roles map[string][]Policy
106
+ func (_e *MockController_Expecter) CreateRolesPermissions(roles interface{}) *MockController_CreateRolesPermissions_Call {
107
+ return &MockController_CreateRolesPermissions_Call{Call: _e.mock.On("CreateRolesPermissions", roles)}
108
+ }
109
+
110
+ func (_c *MockController_CreateRolesPermissions_Call) Run(run func(roles map[string][]Policy)) *MockController_CreateRolesPermissions_Call {
111
+ _c.Call.Run(func(args mock.Arguments) {
112
+ run(args[0].(map[string][]Policy))
113
+ })
114
+ return _c
115
+ }
116
+
117
+ func (_c *MockController_CreateRolesPermissions_Call) Return(_a0 error) *MockController_CreateRolesPermissions_Call {
118
+ _c.Call.Return(_a0)
119
+ return _c
120
+ }
121
+
122
+ func (_c *MockController_CreateRolesPermissions_Call) RunAndReturn(run func(map[string][]Policy) error) *MockController_CreateRolesPermissions_Call {
123
+ _c.Call.Return(run)
124
+ return _c
125
+ }
126
+
127
+ // DeleteRoles provides a mock function with given fields: roles
128
+ func (_m *MockController) DeleteRoles(roles ...string) error {
129
+ _va := make([]interface{}, len(roles))
130
+ for _i := range roles {
131
+ _va[_i] = roles[_i]
132
+ }
133
+ var _ca []interface{}
134
+ _ca = append(_ca, _va...)
135
+ ret := _m.Called(_ca...)
136
+
137
+ if len(ret) == 0 {
138
+ panic("no return value specified for DeleteRoles")
139
+ }
140
+
141
+ var r0 error
142
+ if rf, ok := ret.Get(0).(func(...string) error); ok {
143
+ r0 = rf(roles...)
144
+ } else {
145
+ r0 = ret.Error(0)
146
+ }
147
+
148
+ return r0
149
+ }
150
+
151
+ // MockController_DeleteRoles_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteRoles'
152
+ type MockController_DeleteRoles_Call struct {
153
+ *mock.Call
154
+ }
155
+
156
+ // DeleteRoles is a helper method to define mock.On call
157
+ // - roles ...string
158
+ func (_e *MockController_Expecter) DeleteRoles(roles ...interface{}) *MockController_DeleteRoles_Call {
159
+ return &MockController_DeleteRoles_Call{Call: _e.mock.On("DeleteRoles",
160
+ append([]interface{}{}, roles...)...)}
161
+ }
162
+
163
+ func (_c *MockController_DeleteRoles_Call) Run(run func(roles ...string)) *MockController_DeleteRoles_Call {
164
+ _c.Call.Run(func(args mock.Arguments) {
165
+ variadicArgs := make([]string, len(args)-0)
166
+ for i, a := range args[0:] {
167
+ if a != nil {
168
+ variadicArgs[i] = a.(string)
169
+ }
170
+ }
171
+ run(variadicArgs...)
172
+ })
173
+ return _c
174
+ }
175
+
176
+ func (_c *MockController_DeleteRoles_Call) Return(_a0 error) *MockController_DeleteRoles_Call {
177
+ _c.Call.Return(_a0)
178
+ return _c
179
+ }
180
+
181
+ func (_c *MockController_DeleteRoles_Call) RunAndReturn(run func(...string) error) *MockController_DeleteRoles_Call {
182
+ _c.Call.Return(run)
183
+ return _c
184
+ }
185
+
186
+ // GetRoles provides a mock function with given fields: names
187
+ func (_m *MockController) GetRoles(names ...string) (map[string][]Policy, error) {
188
+ _va := make([]interface{}, len(names))
189
+ for _i := range names {
190
+ _va[_i] = names[_i]
191
+ }
192
+ var _ca []interface{}
193
+ _ca = append(_ca, _va...)
194
+ ret := _m.Called(_ca...)
195
+
196
+ if len(ret) == 0 {
197
+ panic("no return value specified for GetRoles")
198
+ }
199
+
200
+ var r0 map[string][]Policy
201
+ var r1 error
202
+ if rf, ok := ret.Get(0).(func(...string) (map[string][]Policy, error)); ok {
203
+ return rf(names...)
204
+ }
205
+ if rf, ok := ret.Get(0).(func(...string) map[string][]Policy); ok {
206
+ r0 = rf(names...)
207
+ } else {
208
+ if ret.Get(0) != nil {
209
+ r0 = ret.Get(0).(map[string][]Policy)
210
+ }
211
+ }
212
+
213
+ if rf, ok := ret.Get(1).(func(...string) error); ok {
214
+ r1 = rf(names...)
215
+ } else {
216
+ r1 = ret.Error(1)
217
+ }
218
+
219
+ return r0, r1
220
+ }
221
+
222
+ // MockController_GetRoles_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRoles'
223
+ type MockController_GetRoles_Call struct {
224
+ *mock.Call
225
+ }
226
+
227
+ // GetRoles is a helper method to define mock.On call
228
+ // - names ...string
229
+ func (_e *MockController_Expecter) GetRoles(names ...interface{}) *MockController_GetRoles_Call {
230
+ return &MockController_GetRoles_Call{Call: _e.mock.On("GetRoles",
231
+ append([]interface{}{}, names...)...)}
232
+ }
233
+
234
+ func (_c *MockController_GetRoles_Call) Run(run func(names ...string)) *MockController_GetRoles_Call {
235
+ _c.Call.Run(func(args mock.Arguments) {
236
+ variadicArgs := make([]string, len(args)-0)
237
+ for i, a := range args[0:] {
238
+ if a != nil {
239
+ variadicArgs[i] = a.(string)
240
+ }
241
+ }
242
+ run(variadicArgs...)
243
+ })
244
+ return _c
245
+ }
246
+
247
+ func (_c *MockController_GetRoles_Call) Return(_a0 map[string][]Policy, _a1 error) *MockController_GetRoles_Call {
248
+ _c.Call.Return(_a0, _a1)
249
+ return _c
250
+ }
251
+
252
+ func (_c *MockController_GetRoles_Call) RunAndReturn(run func(...string) (map[string][]Policy, error)) *MockController_GetRoles_Call {
253
+ _c.Call.Return(run)
254
+ return _c
255
+ }
256
+
257
+ // GetRolesForUserOrGroup provides a mock function with given fields: user, authMethod, isGroup
258
+ func (_m *MockController) GetRolesForUserOrGroup(user string, authMethod authentication.AuthType, isGroup bool) (map[string][]Policy, error) {
259
+ ret := _m.Called(user, authMethod, isGroup)
260
+
261
+ if len(ret) == 0 {
262
+ panic("no return value specified for GetRolesForUserOrGroup")
263
+ }
264
+
265
+ var r0 map[string][]Policy
266
+ var r1 error
267
+ if rf, ok := ret.Get(0).(func(string, authentication.AuthType, bool) (map[string][]Policy, error)); ok {
268
+ return rf(user, authMethod, isGroup)
269
+ }
270
+ if rf, ok := ret.Get(0).(func(string, authentication.AuthType, bool) map[string][]Policy); ok {
271
+ r0 = rf(user, authMethod, isGroup)
272
+ } else {
273
+ if ret.Get(0) != nil {
274
+ r0 = ret.Get(0).(map[string][]Policy)
275
+ }
276
+ }
277
+
278
+ if rf, ok := ret.Get(1).(func(string, authentication.AuthType, bool) error); ok {
279
+ r1 = rf(user, authMethod, isGroup)
280
+ } else {
281
+ r1 = ret.Error(1)
282
+ }
283
+
284
+ return r0, r1
285
+ }
286
+
287
+ // MockController_GetRolesForUserOrGroup_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRolesForUserOrGroup'
288
+ type MockController_GetRolesForUserOrGroup_Call struct {
289
+ *mock.Call
290
+ }
291
+
292
+ // GetRolesForUserOrGroup is a helper method to define mock.On call
293
+ // - user string
294
+ // - authMethod authentication.AuthType
295
+ // - isGroup bool
296
+ func (_e *MockController_Expecter) GetRolesForUserOrGroup(user interface{}, authMethod interface{}, isGroup interface{}) *MockController_GetRolesForUserOrGroup_Call {
297
+ return &MockController_GetRolesForUserOrGroup_Call{Call: _e.mock.On("GetRolesForUserOrGroup", user, authMethod, isGroup)}
298
+ }
299
+
300
+ func (_c *MockController_GetRolesForUserOrGroup_Call) Run(run func(user string, authMethod authentication.AuthType, isGroup bool)) *MockController_GetRolesForUserOrGroup_Call {
301
+ _c.Call.Run(func(args mock.Arguments) {
302
+ run(args[0].(string), args[1].(authentication.AuthType), args[2].(bool))
303
+ })
304
+ return _c
305
+ }
306
+
307
+ func (_c *MockController_GetRolesForUserOrGroup_Call) Return(_a0 map[string][]Policy, _a1 error) *MockController_GetRolesForUserOrGroup_Call {
308
+ _c.Call.Return(_a0, _a1)
309
+ return _c
310
+ }
311
+
312
+ func (_c *MockController_GetRolesForUserOrGroup_Call) RunAndReturn(run func(string, authentication.AuthType, bool) (map[string][]Policy, error)) *MockController_GetRolesForUserOrGroup_Call {
313
+ _c.Call.Return(run)
314
+ return _c
315
+ }
316
+
317
+ // GetUsersOrGroupForRole provides a mock function with given fields: role, authMethod, IsGroup
318
+ func (_m *MockController) GetUsersOrGroupForRole(role string, authMethod authentication.AuthType, IsGroup bool) ([]string, error) {
319
+ ret := _m.Called(role, authMethod, IsGroup)
320
+
321
+ if len(ret) == 0 {
322
+ panic("no return value specified for GetUsersOrGroupForRole")
323
+ }
324
+
325
+ var r0 []string
326
+ var r1 error
327
+ if rf, ok := ret.Get(0).(func(string, authentication.AuthType, bool) ([]string, error)); ok {
328
+ return rf(role, authMethod, IsGroup)
329
+ }
330
+ if rf, ok := ret.Get(0).(func(string, authentication.AuthType, bool) []string); ok {
331
+ r0 = rf(role, authMethod, IsGroup)
332
+ } else {
333
+ if ret.Get(0) != nil {
334
+ r0 = ret.Get(0).([]string)
335
+ }
336
+ }
337
+
338
+ if rf, ok := ret.Get(1).(func(string, authentication.AuthType, bool) error); ok {
339
+ r1 = rf(role, authMethod, IsGroup)
340
+ } else {
341
+ r1 = ret.Error(1)
342
+ }
343
+
344
+ return r0, r1
345
+ }
346
+
347
+ // MockController_GetUsersOrGroupForRole_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetUsersOrGroupForRole'
348
+ type MockController_GetUsersOrGroupForRole_Call struct {
349
+ *mock.Call
350
+ }
351
+
352
+ // GetUsersOrGroupForRole is a helper method to define mock.On call
353
+ // - role string
354
+ // - authMethod authentication.AuthType
355
+ // - IsGroup bool
356
+ func (_e *MockController_Expecter) GetUsersOrGroupForRole(role interface{}, authMethod interface{}, IsGroup interface{}) *MockController_GetUsersOrGroupForRole_Call {
357
+ return &MockController_GetUsersOrGroupForRole_Call{Call: _e.mock.On("GetUsersOrGroupForRole", role, authMethod, IsGroup)}
358
+ }
359
+
360
+ func (_c *MockController_GetUsersOrGroupForRole_Call) Run(run func(role string, authMethod authentication.AuthType, IsGroup bool)) *MockController_GetUsersOrGroupForRole_Call {
361
+ _c.Call.Run(func(args mock.Arguments) {
362
+ run(args[0].(string), args[1].(authentication.AuthType), args[2].(bool))
363
+ })
364
+ return _c
365
+ }
366
+
367
+ func (_c *MockController_GetUsersOrGroupForRole_Call) Return(_a0 []string, _a1 error) *MockController_GetUsersOrGroupForRole_Call {
368
+ _c.Call.Return(_a0, _a1)
369
+ return _c
370
+ }
371
+
372
+ func (_c *MockController_GetUsersOrGroupForRole_Call) RunAndReturn(run func(string, authentication.AuthType, bool) ([]string, error)) *MockController_GetUsersOrGroupForRole_Call {
373
+ _c.Call.Return(run)
374
+ return _c
375
+ }
376
+
377
+ // GetUsersOrGroupsWithRoles provides a mock function with given fields: isGroup, authMethod
378
+ func (_m *MockController) GetUsersOrGroupsWithRoles(isGroup bool, authMethod authentication.AuthType) ([]string, error) {
379
+ ret := _m.Called(isGroup, authMethod)
380
+
381
+ if len(ret) == 0 {
382
+ panic("no return value specified for GetUsersOrGroupsWithRoles")
383
+ }
384
+
385
+ var r0 []string
386
+ var r1 error
387
+ if rf, ok := ret.Get(0).(func(bool, authentication.AuthType) ([]string, error)); ok {
388
+ return rf(isGroup, authMethod)
389
+ }
390
+ if rf, ok := ret.Get(0).(func(bool, authentication.AuthType) []string); ok {
391
+ r0 = rf(isGroup, authMethod)
392
+ } else {
393
+ if ret.Get(0) != nil {
394
+ r0 = ret.Get(0).([]string)
395
+ }
396
+ }
397
+
398
+ if rf, ok := ret.Get(1).(func(bool, authentication.AuthType) error); ok {
399
+ r1 = rf(isGroup, authMethod)
400
+ } else {
401
+ r1 = ret.Error(1)
402
+ }
403
+
404
+ return r0, r1
405
+ }
406
+
407
+ // MockController_GetUsersOrGroupsWithRoles_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetUsersOrGroupsWithRoles'
408
+ type MockController_GetUsersOrGroupsWithRoles_Call struct {
409
+ *mock.Call
410
+ }
411
+
412
+ // GetUsersOrGroupsWithRoles is a helper method to define mock.On call
413
+ // - isGroup bool
414
+ // - authMethod authentication.AuthType
415
+ func (_e *MockController_Expecter) GetUsersOrGroupsWithRoles(isGroup interface{}, authMethod interface{}) *MockController_GetUsersOrGroupsWithRoles_Call {
416
+ return &MockController_GetUsersOrGroupsWithRoles_Call{Call: _e.mock.On("GetUsersOrGroupsWithRoles", isGroup, authMethod)}
417
+ }
418
+
419
+ func (_c *MockController_GetUsersOrGroupsWithRoles_Call) Run(run func(isGroup bool, authMethod authentication.AuthType)) *MockController_GetUsersOrGroupsWithRoles_Call {
420
+ _c.Call.Run(func(args mock.Arguments) {
421
+ run(args[0].(bool), args[1].(authentication.AuthType))
422
+ })
423
+ return _c
424
+ }
425
+
426
+ func (_c *MockController_GetUsersOrGroupsWithRoles_Call) Return(_a0 []string, _a1 error) *MockController_GetUsersOrGroupsWithRoles_Call {
427
+ _c.Call.Return(_a0, _a1)
428
+ return _c
429
+ }
430
+
431
+ func (_c *MockController_GetUsersOrGroupsWithRoles_Call) RunAndReturn(run func(bool, authentication.AuthType) ([]string, error)) *MockController_GetUsersOrGroupsWithRoles_Call {
432
+ _c.Call.Return(run)
433
+ return _c
434
+ }
435
+
436
+ // HasPermission provides a mock function with given fields: role, permission
437
+ func (_m *MockController) HasPermission(role string, permission *Policy) (bool, error) {
438
+ ret := _m.Called(role, permission)
439
+
440
+ if len(ret) == 0 {
441
+ panic("no return value specified for HasPermission")
442
+ }
443
+
444
+ var r0 bool
445
+ var r1 error
446
+ if rf, ok := ret.Get(0).(func(string, *Policy) (bool, error)); ok {
447
+ return rf(role, permission)
448
+ }
449
+ if rf, ok := ret.Get(0).(func(string, *Policy) bool); ok {
450
+ r0 = rf(role, permission)
451
+ } else {
452
+ r0 = ret.Get(0).(bool)
453
+ }
454
+
455
+ if rf, ok := ret.Get(1).(func(string, *Policy) error); ok {
456
+ r1 = rf(role, permission)
457
+ } else {
458
+ r1 = ret.Error(1)
459
+ }
460
+
461
+ return r0, r1
462
+ }
463
+
464
+ // MockController_HasPermission_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasPermission'
465
+ type MockController_HasPermission_Call struct {
466
+ *mock.Call
467
+ }
468
+
469
+ // HasPermission is a helper method to define mock.On call
470
+ // - role string
471
+ // - permission *Policy
472
+ func (_e *MockController_Expecter) HasPermission(role interface{}, permission interface{}) *MockController_HasPermission_Call {
473
+ return &MockController_HasPermission_Call{Call: _e.mock.On("HasPermission", role, permission)}
474
+ }
475
+
476
+ func (_c *MockController_HasPermission_Call) Run(run func(role string, permission *Policy)) *MockController_HasPermission_Call {
477
+ _c.Call.Run(func(args mock.Arguments) {
478
+ run(args[0].(string), args[1].(*Policy))
479
+ })
480
+ return _c
481
+ }
482
+
483
+ func (_c *MockController_HasPermission_Call) Return(_a0 bool, _a1 error) *MockController_HasPermission_Call {
484
+ _c.Call.Return(_a0, _a1)
485
+ return _c
486
+ }
487
+
488
+ func (_c *MockController_HasPermission_Call) RunAndReturn(run func(string, *Policy) (bool, error)) *MockController_HasPermission_Call {
489
+ _c.Call.Return(run)
490
+ return _c
491
+ }
492
+
493
+ // RemovePermissions provides a mock function with given fields: role, permissions
494
+ func (_m *MockController) RemovePermissions(role string, permissions []*Policy) error {
495
+ ret := _m.Called(role, permissions)
496
+
497
+ if len(ret) == 0 {
498
+ panic("no return value specified for RemovePermissions")
499
+ }
500
+
501
+ var r0 error
502
+ if rf, ok := ret.Get(0).(func(string, []*Policy) error); ok {
503
+ r0 = rf(role, permissions)
504
+ } else {
505
+ r0 = ret.Error(0)
506
+ }
507
+
508
+ return r0
509
+ }
510
+
511
+ // MockController_RemovePermissions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemovePermissions'
512
+ type MockController_RemovePermissions_Call struct {
513
+ *mock.Call
514
+ }
515
+
516
+ // RemovePermissions is a helper method to define mock.On call
517
+ // - role string
518
+ // - permissions []*Policy
519
+ func (_e *MockController_Expecter) RemovePermissions(role interface{}, permissions interface{}) *MockController_RemovePermissions_Call {
520
+ return &MockController_RemovePermissions_Call{Call: _e.mock.On("RemovePermissions", role, permissions)}
521
+ }
522
+
523
+ func (_c *MockController_RemovePermissions_Call) Run(run func(role string, permissions []*Policy)) *MockController_RemovePermissions_Call {
524
+ _c.Call.Run(func(args mock.Arguments) {
525
+ run(args[0].(string), args[1].([]*Policy))
526
+ })
527
+ return _c
528
+ }
529
+
530
+ func (_c *MockController_RemovePermissions_Call) Return(_a0 error) *MockController_RemovePermissions_Call {
531
+ _c.Call.Return(_a0)
532
+ return _c
533
+ }
534
+
535
+ func (_c *MockController_RemovePermissions_Call) RunAndReturn(run func(string, []*Policy) error) *MockController_RemovePermissions_Call {
536
+ _c.Call.Return(run)
537
+ return _c
538
+ }
539
+
540
+ // RevokeRolesForUser provides a mock function with given fields: user, roles
541
+ func (_m *MockController) RevokeRolesForUser(user string, roles ...string) error {
542
+ _va := make([]interface{}, len(roles))
543
+ for _i := range roles {
544
+ _va[_i] = roles[_i]
545
+ }
546
+ var _ca []interface{}
547
+ _ca = append(_ca, user)
548
+ _ca = append(_ca, _va...)
549
+ ret := _m.Called(_ca...)
550
+
551
+ if len(ret) == 0 {
552
+ panic("no return value specified for RevokeRolesForUser")
553
+ }
554
+
555
+ var r0 error
556
+ if rf, ok := ret.Get(0).(func(string, ...string) error); ok {
557
+ r0 = rf(user, roles...)
558
+ } else {
559
+ r0 = ret.Error(0)
560
+ }
561
+
562
+ return r0
563
+ }
564
+
565
+ // MockController_RevokeRolesForUser_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RevokeRolesForUser'
566
+ type MockController_RevokeRolesForUser_Call struct {
567
+ *mock.Call
568
+ }
569
+
570
+ // RevokeRolesForUser is a helper method to define mock.On call
571
+ // - user string
572
+ // - roles ...string
573
+ func (_e *MockController_Expecter) RevokeRolesForUser(user interface{}, roles ...interface{}) *MockController_RevokeRolesForUser_Call {
574
+ return &MockController_RevokeRolesForUser_Call{Call: _e.mock.On("RevokeRolesForUser",
575
+ append([]interface{}{user}, roles...)...)}
576
+ }
577
+
578
+ func (_c *MockController_RevokeRolesForUser_Call) Run(run func(user string, roles ...string)) *MockController_RevokeRolesForUser_Call {
579
+ _c.Call.Run(func(args mock.Arguments) {
580
+ variadicArgs := make([]string, len(args)-1)
581
+ for i, a := range args[1:] {
582
+ if a != nil {
583
+ variadicArgs[i] = a.(string)
584
+ }
585
+ }
586
+ run(args[0].(string), variadicArgs...)
587
+ })
588
+ return _c
589
+ }
590
+
591
+ func (_c *MockController_RevokeRolesForUser_Call) Return(_a0 error) *MockController_RevokeRolesForUser_Call {
592
+ _c.Call.Return(_a0)
593
+ return _c
594
+ }
595
+
596
+ func (_c *MockController_RevokeRolesForUser_Call) RunAndReturn(run func(string, ...string) error) *MockController_RevokeRolesForUser_Call {
597
+ _c.Call.Return(run)
598
+ return _c
599
+ }
600
+
601
+ // UpdateRolesPermissions provides a mock function with given fields: roles
602
+ func (_m *MockController) UpdateRolesPermissions(roles map[string][]Policy) error {
603
+ ret := _m.Called(roles)
604
+
605
+ if len(ret) == 0 {
606
+ panic("no return value specified for UpdateRolesPermissions")
607
+ }
608
+
609
+ var r0 error
610
+ if rf, ok := ret.Get(0).(func(map[string][]Policy) error); ok {
611
+ r0 = rf(roles)
612
+ } else {
613
+ r0 = ret.Error(0)
614
+ }
615
+
616
+ return r0
617
+ }
618
+
619
+ // MockController_UpdateRolesPermissions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateRolesPermissions'
620
+ type MockController_UpdateRolesPermissions_Call struct {
621
+ *mock.Call
622
+ }
623
+
624
+ // UpdateRolesPermissions is a helper method to define mock.On call
625
+ // - roles map[string][]Policy
626
+ func (_e *MockController_Expecter) UpdateRolesPermissions(roles interface{}) *MockController_UpdateRolesPermissions_Call {
627
+ return &MockController_UpdateRolesPermissions_Call{Call: _e.mock.On("UpdateRolesPermissions", roles)}
628
+ }
629
+
630
+ func (_c *MockController_UpdateRolesPermissions_Call) Run(run func(roles map[string][]Policy)) *MockController_UpdateRolesPermissions_Call {
631
+ _c.Call.Run(func(args mock.Arguments) {
632
+ run(args[0].(map[string][]Policy))
633
+ })
634
+ return _c
635
+ }
636
+
637
+ func (_c *MockController_UpdateRolesPermissions_Call) Return(_a0 error) *MockController_UpdateRolesPermissions_Call {
638
+ _c.Call.Return(_a0)
639
+ return _c
640
+ }
641
+
642
+ func (_c *MockController_UpdateRolesPermissions_Call) RunAndReturn(run func(map[string][]Policy) error) *MockController_UpdateRolesPermissions_Call {
643
+ _c.Call.Return(run)
644
+ return _c
645
+ }
646
+
647
+ // NewMockController creates a new instance of MockController. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
648
+ // The first argument is typically a *testing.T value.
649
+ func NewMockController(t interface {
650
+ mock.TestingT
651
+ Cleanup(func())
652
+ }) *MockController {
653
+ mock := &MockController{}
654
+ mock.Mock.Test(t)
655
+
656
+ t.Cleanup(func() { mock.AssertExpectations(t) })
657
+
658
+ return mock
659
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/types.go ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package authorization
13
+
14
+ import (
15
+ "fmt"
16
+ "strings"
17
+
18
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
19
+
20
+ "github.com/go-openapi/strfmt"
21
+
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/entities/schema"
24
+ "github.com/weaviate/weaviate/entities/verbosity"
25
+ )
26
+
27
+ const (
28
+ // CREATE Represents the action to create a new resource.
29
+ CREATE = "C"
30
+ // READ Represents the action to retrieve a resource.
31
+ READ = "R"
32
+ // UPDATE Represents the action to update an existing resource.
33
+ UPDATE = "U"
34
+ // DELETE Represents the action to delete a resource.
35
+ DELETE = "D"
36
+
37
+ ROLE_SCOPE_ALL = "ALL"
38
+ ROLE_SCOPE_MATCH = "MATCH"
39
+
40
+ USER_AND_GROUP_ASSIGN_AND_REVOKE = "A"
41
+ )
42
+
43
+ const (
44
+ GroupsDomain = "groups"
45
+ UsersDomain = "users"
46
+ RolesDomain = "roles"
47
+ ClusterDomain = "cluster"
48
+ NodesDomain = "nodes"
49
+ BackupsDomain = "backups"
50
+ SchemaDomain = "schema"
51
+ CollectionsDomain = "collections"
52
+ TenantsDomain = "tenants"
53
+ DataDomain = "data"
54
+ ReplicateDomain = "replicate"
55
+ AliasesDomain = "aliases"
56
+ )
57
+
58
+ var (
59
+ All = String("*")
60
+
61
+ AllBackups = &models.PermissionBackups{
62
+ Collection: All,
63
+ }
64
+ AllData = &models.PermissionData{
65
+ Collection: All,
66
+ Tenant: All,
67
+ Object: All,
68
+ }
69
+ AllTenants = &models.PermissionTenants{
70
+ Collection: All,
71
+ Tenant: All,
72
+ }
73
+ AllNodes = &models.PermissionNodes{
74
+ Verbosity: String(verbosity.OutputVerbose),
75
+ Collection: All,
76
+ }
77
+ AllOIDCGroups = &models.PermissionGroups{
78
+ Group: All,
79
+ GroupType: models.GroupTypeOidc,
80
+ }
81
+ AllRoles = &models.PermissionRoles{
82
+ Role: All,
83
+ Scope: String(models.PermissionRolesScopeAll),
84
+ }
85
+ AllUsers = &models.PermissionUsers{
86
+ Users: All,
87
+ }
88
+ AllCollections = &models.PermissionCollections{
89
+ Collection: All,
90
+ }
91
+ AllReplicate = &models.PermissionReplicate{
92
+ Collection: All,
93
+ Shard: All,
94
+ }
95
+ AllAliases = &models.PermissionAliases{
96
+ Collection: All,
97
+ Alias: All,
98
+ }
99
+
100
+ ComponentName = "RBAC"
101
+
102
+ // Note: if a new action added, don't forget to add it to availableWeaviateActions
103
+ // to be added to built in roles
104
+ // any action has to contain of `{verb}_{domain}` verb: CREATE, READ, UPDATE, DELETE domain: roles, users, cluster, collections, data
105
+ ReadRoles = "read_roles"
106
+ CreateRoles = "create_roles"
107
+ UpdateRoles = "update_roles"
108
+ DeleteRoles = "delete_roles"
109
+
110
+ ReadCluster = "read_cluster"
111
+ ReadNodes = "read_nodes"
112
+
113
+ AssignAndRevokeGroups = "assign_and_revoke_groups"
114
+ ReadGroups = "read_groups"
115
+
116
+ AssignAndRevokeUsers = "assign_and_revoke_users"
117
+ CreateUsers = "create_users"
118
+ ReadUsers = "read_users"
119
+ UpdateUsers = "update_users"
120
+ DeleteUsers = "delete_users"
121
+
122
+ ManageBackups = "manage_backups"
123
+
124
+ CreateCollections = "create_collections"
125
+ ReadCollections = "read_collections"
126
+ UpdateCollections = "update_collections"
127
+ DeleteCollections = "delete_collections"
128
+
129
+ CreateData = "create_data"
130
+ ReadData = "read_data"
131
+ UpdateData = "update_data"
132
+ DeleteData = "delete_data"
133
+
134
+ CreateTenants = "create_tenants"
135
+ ReadTenants = "read_tenants"
136
+ UpdateTenants = "update_tenants"
137
+ DeleteTenants = "delete_tenants"
138
+
139
+ CreateReplicate = "create_replicate"
140
+ ReadReplicate = "read_replicate"
141
+ UpdateReplicate = "update_replicate"
142
+ DeleteReplicate = "delete_replicate"
143
+
144
+ CreateAliases = "create_aliases"
145
+ ReadAliases = "read_aliases"
146
+ UpdateAliases = "update_aliases"
147
+ DeleteAliases = "delete_aliases"
148
+
149
+ availableWeaviateActions = []string{
150
+ // Roles domain
151
+ CreateRoles,
152
+ ReadRoles,
153
+ UpdateRoles,
154
+ DeleteRoles,
155
+
156
+ // Backups domain
157
+ ManageBackups,
158
+
159
+ // Users domain
160
+ AssignAndRevokeUsers,
161
+ CreateUsers,
162
+ ReadUsers,
163
+ UpdateUsers,
164
+ DeleteUsers,
165
+
166
+ // Cluster domain
167
+ ReadCluster,
168
+
169
+ // Groups domain
170
+ AssignAndRevokeGroups,
171
+ ReadGroups,
172
+
173
+ // Nodes domain
174
+ ReadNodes,
175
+
176
+ // Collections domain
177
+ CreateCollections,
178
+ ReadCollections,
179
+ UpdateCollections,
180
+ DeleteCollections,
181
+
182
+ // Data domain
183
+ CreateData,
184
+ ReadData,
185
+ UpdateData,
186
+ DeleteData,
187
+
188
+ // Tenant domain
189
+ CreateTenants,
190
+ ReadTenants,
191
+ UpdateTenants,
192
+ DeleteTenants,
193
+
194
+ // Replicate domain
195
+ CreateReplicate,
196
+ ReadReplicate,
197
+ UpdateReplicate,
198
+ DeleteReplicate,
199
+
200
+ // Aliases domain
201
+ CreateAliases,
202
+ ReadAliases,
203
+ UpdateAliases,
204
+ DeleteAliases,
205
+ }
206
+ )
207
+
208
+ var (
209
+ // build-in roles that can be assigned via API
210
+ Viewer = "viewer"
211
+ Admin = "admin"
212
+ // build-in roles that can be assigned via env vars and cannot be changed via APIS
213
+ Root = "root"
214
+ ReadOnly = "read-only"
215
+ BuiltInRoles = []string{Viewer, Admin, Root, ReadOnly}
216
+
217
+ // viewer : can view everything , roles, users, schema, data
218
+ // editor : can create/read/update everything , roles, users, schema, data
219
+ // Admin : aka basically super Admin or root
220
+ BuiltInPermissions = map[string][]*models.Permission{
221
+ Viewer: viewerPermissions(),
222
+ Admin: adminPermissions(),
223
+ Root: adminPermissions(),
224
+ ReadOnly: viewerPermissions(),
225
+ }
226
+ EnvVarRoles = []string{ReadOnly, Root}
227
+ )
228
+
229
+ type Policy struct {
230
+ Resource string
231
+ Verb string
232
+ Domain string
233
+ }
234
+
235
+ // Cluster returns a string representing the cluster authorization scope.
236
+ // The returned string is "cluster/*", which can be used to specify that
237
+ // the authorization applies to all resources within the cluster.
238
+ func Cluster() string {
239
+ return fmt.Sprintf("%s/*", ClusterDomain)
240
+ }
241
+
242
+ func nodes(verbosity, class string) string {
243
+ if verbosity == "" {
244
+ verbosity = "minimal"
245
+ }
246
+ if verbosity == "minimal" {
247
+ return fmt.Sprintf("%s/verbosity/%s", NodesDomain, verbosity)
248
+ }
249
+ return fmt.Sprintf("%s/verbosity/%s/collections/%s", NodesDomain, verbosity, class)
250
+ }
251
+
252
+ func Nodes(verbosity string, classes ...string) []string {
253
+ classes = schema.UppercaseClassesNames(classes...)
254
+
255
+ if len(classes) == 0 || (len(classes) == 1 && (classes[0] == "" || classes[0] == "*")) {
256
+ return []string{nodes(verbosity, "*")}
257
+ }
258
+
259
+ resources := make([]string, len(classes))
260
+ for idx := range classes {
261
+ if classes[idx] == "" {
262
+ resources[idx] = nodes(verbosity, "*")
263
+ } else {
264
+ resources[idx] = nodes(verbosity, classes[idx])
265
+ }
266
+ }
267
+
268
+ return resources
269
+ }
270
+
271
+ // Groups generates a list of user resource strings based on the provided group names.
272
+ // If no group names are provided, it returns a default user resource string "groups/*".
273
+ //
274
+ // Parameters:
275
+ //
276
+ // groups - A variadic parameter representing the group names.
277
+ //
278
+ // Returns:
279
+ //
280
+ // A slice of strings where each string is a formatted user resource string.
281
+ func Groups(groupType authentication.AuthType, groups ...string) []string {
282
+ if len(groups) == 0 || (len(groups) == 1 && (groups[0] == "" || groups[0] == "*")) {
283
+ return []string{
284
+ fmt.Sprintf("%s/%s/*", GroupsDomain, groupType),
285
+ }
286
+ }
287
+
288
+ resources := make([]string, len(groups))
289
+ for idx := range groups {
290
+ resources[idx] = fmt.Sprintf("%s/%s/%s", GroupsDomain, groupType, groups[idx])
291
+ }
292
+
293
+ return resources
294
+ }
295
+
296
+ // Users generates a list of user resource strings based on the provided user names.
297
+ // If no user names are provided, it returns a default user resource string "users/*".
298
+ //
299
+ // Parameters:
300
+ //
301
+ // users - A variadic parameter representing the user names.
302
+ //
303
+ // Returns:
304
+ //
305
+ // A slice of strings where each string is a formatted user resource string.
306
+ func Users(users ...string) []string {
307
+ if len(users) == 0 || (len(users) == 1 && (users[0] == "" || users[0] == "*")) {
308
+ return []string{
309
+ fmt.Sprintf("%s/*", UsersDomain),
310
+ }
311
+ }
312
+
313
+ resources := make([]string, len(users))
314
+ for idx := range users {
315
+ resources[idx] = fmt.Sprintf("%s/%s", UsersDomain, users[idx])
316
+ }
317
+
318
+ return resources
319
+ }
320
+
321
+ // Roles generates a list of role resource strings based on the provided role names.
322
+ // If no role names are provided, it returns a default role resource string "roles/*".
323
+ //
324
+ // Parameters:
325
+ //
326
+ // roles - A variadic parameter representing the role names.
327
+ //
328
+ // Returns:
329
+ //
330
+ // A slice of strings where each string is a formatted role resource string.
331
+ func Roles(roles ...string) []string {
332
+ if len(roles) == 0 || (len(roles) == 1 && (roles[0] == "" || roles[0] == "*")) {
333
+ return []string{
334
+ fmt.Sprintf("%s/*", RolesDomain),
335
+ }
336
+ }
337
+
338
+ resources := make([]string, len(roles))
339
+ for idx := range roles {
340
+ resources[idx] = fmt.Sprintf("%s/%s", RolesDomain, roles[idx])
341
+ }
342
+
343
+ return resources
344
+ }
345
+
346
+ // CollectionsMetadata generates a list of resource strings for the given classes.
347
+ // If no classes are provided, it returns a default resource string "collections/*".
348
+ // Each class is formatted as "collection/{class}".
349
+ //
350
+ // Parameters:
351
+ //
352
+ // classes - a variadic parameter representing the class names.
353
+ //
354
+ // Returns:
355
+ //
356
+ // A slice of strings representing the resource paths.
357
+ func CollectionsMetadata(classes ...string) []string {
358
+ classes = schema.UppercaseClassesNames(classes...)
359
+
360
+ if len(classes) == 0 || (len(classes) == 1 && (classes[0] == "" || classes[0] == "*")) {
361
+ return []string{fmt.Sprintf("%s/collections/*/shards/#", SchemaDomain)}
362
+ }
363
+
364
+ resources := make([]string, len(classes))
365
+ for idx := range classes {
366
+ if classes[idx] == "" {
367
+ resources[idx] = fmt.Sprintf("%s/collections/*/shards/#", SchemaDomain)
368
+ } else {
369
+ resources[idx] = fmt.Sprintf("%s/collections/%s/shards/#", SchemaDomain, classes[idx])
370
+ }
371
+ }
372
+
373
+ return resources
374
+ }
375
+
376
+ func Aliases(class string, aliases ...string) []string {
377
+ class = schema.UppercaseClassName(class)
378
+ aliases = schema.UppercaseClassesNames(aliases...)
379
+
380
+ if class == "" {
381
+ class = "*"
382
+ }
383
+
384
+ if len(aliases) == 0 || (len(aliases) == 1 && (aliases[0] == "" || aliases[0] == "*")) {
385
+ return []string{fmt.Sprintf("%s/collections/%s/aliases/*", AliasesDomain, class)}
386
+ }
387
+
388
+ resources := make([]string, len(aliases))
389
+ for idx := range aliases {
390
+ if aliases[idx] == "" {
391
+ resources[idx] = fmt.Sprintf("%s/collections/%s/aliases/*", AliasesDomain, class)
392
+ } else {
393
+ resources[idx] = fmt.Sprintf("%s/collections/%s/aliases/%s", AliasesDomain, class, aliases[idx])
394
+ }
395
+ }
396
+
397
+ return resources
398
+ }
399
+
400
+ func CollectionsData(classes ...string) []string {
401
+ classes = schema.UppercaseClassesNames(classes...)
402
+
403
+ if len(classes) == 0 || (len(classes) == 1 && (classes[0] == "" || classes[0] == "*")) {
404
+ return []string{Objects("*", "*", "*")}
405
+ }
406
+
407
+ var paths []string
408
+ for _, class := range classes {
409
+ paths = append(paths, Objects(class, "*", "*"))
410
+ }
411
+ return paths
412
+ }
413
+
414
+ func Collections(classes ...string) []string {
415
+ classes = schema.UppercaseClassesNames(classes...)
416
+ return append(CollectionsData(classes...), CollectionsMetadata(classes...)...)
417
+ }
418
+
419
+ // ShardsMetadata generates a list of shard resource strings for a given class and shards.
420
+ // If the class is an empty string, it defaults to "*". If no shards are provided,
421
+ // it returns a single resource string with a wildcard for shards. If shards are
422
+ // provided, it returns a list of resource strings for each shard.
423
+ //
424
+ // Parameters:
425
+ // - class: The class name for the resource. If empty, defaults to "*".
426
+ // - shards: A variadic list of shard names. If empty, it will replace it with '#' to mark it as collection only check
427
+ //
428
+ // Returns:
429
+ //
430
+ // A slice of strings representing the resource paths for the given class and shards.
431
+ func ShardsMetadata(class string, shards ...string) []string {
432
+ class = schema.UppercaseClassesNames(class)[0]
433
+ if class == "" {
434
+ class = "*"
435
+ }
436
+
437
+ if len(shards) == 0 || (len(shards) == 1 && (shards[0] == "" || shards[0] == "*")) {
438
+ return []string{fmt.Sprintf("%s/collections/%s/shards/*", SchemaDomain, class)}
439
+ }
440
+
441
+ resources := make([]string, len(shards))
442
+ for idx := range shards {
443
+ if shards[idx] == "" {
444
+ resources[idx] = fmt.Sprintf("%s/collections/%s/shards/*", SchemaDomain, class)
445
+ } else {
446
+ resources[idx] = fmt.Sprintf("%s/collections/%s/shards/%s", SchemaDomain, class, shards[idx])
447
+ }
448
+ }
449
+
450
+ return resources
451
+ }
452
+
453
+ func ShardsData(class string, shards ...string) []string {
454
+ class = schema.UppercaseClassesNames(class)[0]
455
+ var paths []string
456
+ for _, shard := range shards {
457
+ paths = append(paths, Objects(class, shard, "*"))
458
+ }
459
+ return paths
460
+ }
461
+
462
+ // Objects generates a string representing a path to objects within a collection and shard.
463
+ // The path format varies based on the provided class, shard, and id parameters.
464
+ //
465
+ // Parameters:
466
+ // - class: the class of the collection (string)
467
+ // - shard: the shard identifier (string)
468
+ // - id: the unique identifier of the object (strfmt.UUID)
469
+ //
470
+ // Returns:
471
+ // - A string representing the path to the objects, with wildcards (*) used for any empty parameters.
472
+ //
473
+ // Example outputs:
474
+ // - "collections/*/shards/*/objects/*" if all parameters are empty
475
+ // - "collections/*/shards/*/objects/{id}" if only id is provided
476
+ // - "collections/{class}/shards/{shard}/objects/{id}" if all parameters are provided
477
+ func Objects(class, shard string, id strfmt.UUID) string {
478
+ class = schema.UppercaseClassesNames(class)[0]
479
+ if class == "" {
480
+ class = "*"
481
+ }
482
+ if shard == "" {
483
+ shard = "*"
484
+ }
485
+ if id == "" {
486
+ id = "*"
487
+ }
488
+ return fmt.Sprintf("%s/collections/%s/shards/%s/objects/%s", DataDomain, class, shard, id)
489
+ }
490
+
491
+ // Backups generates a resource string for the given classes.
492
+ // If the backend is an empty string, it defaults to "*".
493
+
494
+ // Parameters:
495
+ // - class: the class name (string)
496
+
497
+ // Returns:
498
+ // - A string representing the resource path for the given classes.
499
+
500
+ // Example outputs:
501
+ // - "backups/*" if the backend is an empty string
502
+ // - "backups/{backend}" for the provided backend
503
+ func Backups(classes ...string) []string {
504
+ classes = schema.UppercaseClassesNames(classes...)
505
+ if len(classes) == 0 || (len(classes) == 1 && (classes[0] == "" || classes[0] == "*")) {
506
+ return []string{fmt.Sprintf("%s/collections/*", BackupsDomain)}
507
+ }
508
+
509
+ resources := make([]string, len(classes))
510
+ for idx := range classes {
511
+ if classes[idx] == "" {
512
+ resources[idx] = fmt.Sprintf("%s/collections/*", BackupsDomain)
513
+ } else {
514
+ resources[idx] = fmt.Sprintf("%s/collections/%s", BackupsDomain, classes[idx])
515
+ }
516
+ }
517
+
518
+ return resources
519
+ }
520
+
521
+ // Replications generates a replication resource string for a given class and shard.
522
+ //
523
+ // Parameters:
524
+ // - class: The class name for the resource. If empty, defaults to "*".
525
+ // - shard: The shard name for the resource. If empty, defaults to "*".
526
+ //
527
+ // Returns:
528
+ //
529
+ // A slice of strings representing the resource paths for the given class and shards.
530
+ func Replications(class, shard string) string {
531
+ class = schema.UppercaseClassName(class)
532
+ if class == "" {
533
+ class = "*"
534
+ }
535
+ if shard == "" {
536
+ shard = "*"
537
+ }
538
+ return fmt.Sprintf("%s/collections/%s/shards/%s", ReplicateDomain, class, shard)
539
+ }
540
+
541
+ // WildcardPath returns the appropriate wildcard path based on the domain and original resource path.
542
+ // The domain is expected to be the first part of the resource path.
543
+ func WildcardPath(resource string) string {
544
+ parts := strings.Split(resource, "/")
545
+ parts[len(parts)-1] = "*"
546
+ return strings.Join(parts, "/")
547
+ }
548
+
549
+ func String(s string) *string {
550
+ return &s
551
+ }
552
+
553
+ // viewer : can view everything , roles, users, schema, data
554
+ func viewerPermissions() []*models.Permission {
555
+ perms := []*models.Permission{}
556
+ for _, action := range availableWeaviateActions {
557
+ if strings.ToUpper(action)[0] != READ[0] {
558
+ continue
559
+ }
560
+
561
+ perms = append(perms, &models.Permission{
562
+ Action: &action,
563
+ Backups: AllBackups,
564
+ Data: AllData,
565
+ Nodes: AllNodes,
566
+ Roles: AllRoles,
567
+ Collections: AllCollections,
568
+ Tenants: AllTenants,
569
+ Users: AllUsers,
570
+ Aliases: AllAliases,
571
+ Groups: AllOIDCGroups,
572
+ })
573
+ }
574
+
575
+ return perms
576
+ }
577
+
578
+ // Admin : aka basically super Admin or root
579
+ func adminPermissions() []*models.Permission {
580
+ // TODO ignore CRUD if there is manage
581
+ perms := []*models.Permission{}
582
+ for _, action := range availableWeaviateActions {
583
+ perms = append(perms, &models.Permission{
584
+ Action: &action,
585
+ Backups: AllBackups,
586
+ Data: AllData,
587
+ Nodes: AllNodes,
588
+ Roles: AllRoles,
589
+ Collections: AllCollections,
590
+ Tenants: AllTenants,
591
+ Users: AllUsers,
592
+ Aliases: AllAliases,
593
+ Groups: AllOIDCGroups,
594
+ })
595
+ }
596
+
597
+ return perms
598
+ }
599
+
600
+ func VerbWithScope(verb, scope string) string {
601
+ if strings.Contains(verb, "_") {
602
+ return verb
603
+ }
604
+
605
+ return fmt.Sprintf("%s_%s", verb, scope)
606
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/types_test.go ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package authorization
13
+
14
+ import (
15
+ "fmt"
16
+ "testing"
17
+
18
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
19
+
20
+ "github.com/go-openapi/strfmt"
21
+ "github.com/stretchr/testify/assert"
22
+ )
23
+
24
+ func TestUsers(t *testing.T) {
25
+ tests := []struct {
26
+ name string
27
+ users []string
28
+ expected []string
29
+ }{
30
+ {"No users", []string{}, []string{fmt.Sprintf("%s/*", UsersDomain)}},
31
+ {"Single user", []string{"user1"}, []string{fmt.Sprintf("%s/user1", UsersDomain)}},
32
+ {"Multiple users", []string{"user1", "user2"}, []string{fmt.Sprintf("%s/user1", UsersDomain), fmt.Sprintf("%s/user2", UsersDomain)}},
33
+ }
34
+
35
+ for _, tt := range tests {
36
+ t.Run(tt.name, func(t *testing.T) {
37
+ result := Users(tt.users...)
38
+ assert.Equal(t, tt.expected, result)
39
+ })
40
+ }
41
+ }
42
+
43
+ func TestGroups(t *testing.T) {
44
+ tests := []struct {
45
+ name string
46
+ groups []string
47
+ expected []string
48
+ }{
49
+ {"No groups", []string{}, []string{fmt.Sprintf("%s/%s/*", GroupsDomain, authentication.AuthTypeOIDC)}},
50
+ {"Single group", []string{"group1"}, []string{fmt.Sprintf("%s/%s/group1", GroupsDomain, authentication.AuthTypeOIDC)}},
51
+ {"Multiple groups", []string{"group1", "group2"}, []string{fmt.Sprintf("%s/%s/group1", GroupsDomain, authentication.AuthTypeOIDC), fmt.Sprintf("%s/%s/group2", GroupsDomain, authentication.AuthTypeOIDC)}},
52
+ }
53
+
54
+ for _, tt := range tests {
55
+ t.Run(tt.name, func(t *testing.T) {
56
+ result := Groups(authentication.AuthTypeOIDC, tt.groups...)
57
+ assert.Equal(t, tt.expected, result)
58
+ })
59
+ }
60
+ }
61
+
62
+ func TestRoles(t *testing.T) {
63
+ tests := []struct {
64
+ name string
65
+ roles []string
66
+ expected []string
67
+ }{
68
+ {"No roles", []string{}, []string{fmt.Sprintf("%s/*", RolesDomain)}},
69
+ {"Single role", []string{"admin"}, []string{fmt.Sprintf("%s/admin", RolesDomain)}},
70
+ {"Multiple roles", []string{"admin", "user"}, []string{fmt.Sprintf("%s/admin", RolesDomain), fmt.Sprintf("%s/user", RolesDomain)}},
71
+ }
72
+
73
+ for _, tt := range tests {
74
+ t.Run(tt.name, func(t *testing.T) {
75
+ result := Roles(tt.roles...)
76
+ assert.Equal(t, tt.expected, result)
77
+ })
78
+ }
79
+ }
80
+
81
+ func TestCluster(t *testing.T) {
82
+ expected := "cluster/*"
83
+ result := Cluster()
84
+ assert.Equal(t, expected, result)
85
+ }
86
+
87
+ func TestNodes(t *testing.T) {
88
+ tests := []struct {
89
+ name string
90
+ verbosity string
91
+ classes []string
92
+ expected []string
93
+ }{
94
+ {"Empty verbosity", "", []string{}, []string{fmt.Sprintf("%s/verbosity/minimal", NodesDomain)}},
95
+ {"Minimal verbosity", "minimal", []string{}, []string{fmt.Sprintf("%s/verbosity/minimal", NodesDomain)}},
96
+ {"Minimal verbosity with classes", "minimal", []string{"class1"}, []string{fmt.Sprintf("%s/verbosity/minimal", NodesDomain)}},
97
+ {"Verbose verbosity with no classes", "verbose", []string{}, []string{fmt.Sprintf("%s/verbosity/verbose/collections/*", NodesDomain)}},
98
+ {"Verbose verbosity with classes", "verbose", []string{"class1", "class2"}, []string{fmt.Sprintf("%s/verbosity/verbose/collections/Class1", NodesDomain), fmt.Sprintf("%s/verbosity/verbose/collections/Class2", NodesDomain)}},
99
+ }
100
+ for _, tt := range tests {
101
+ t.Run(tt.name, func(t *testing.T) {
102
+ result := Nodes(tt.verbosity, tt.classes...)
103
+ assert.Equal(t, tt.expected, result)
104
+ })
105
+ }
106
+ }
107
+
108
+ func TestBackups(t *testing.T) {
109
+ tests := []struct {
110
+ name string
111
+ backend string
112
+ expected []string
113
+ }{
114
+ {"No collection", "", []string{fmt.Sprintf("%s/collections/*", BackupsDomain)}},
115
+ {"Collection", "class1", []string{fmt.Sprintf("%s/collections/Class1", BackupsDomain)}},
116
+ }
117
+
118
+ for _, tt := range tests {
119
+ t.Run(tt.name, func(t *testing.T) {
120
+ result := Backups(tt.backend)
121
+ assert.Equal(t, tt.expected, result)
122
+ })
123
+ }
124
+ }
125
+
126
+ func TestCollections(t *testing.T) {
127
+ tests := []struct {
128
+ name string
129
+ classes []string
130
+ expected []string
131
+ }{
132
+ {"No classes", []string{}, []string{fmt.Sprintf("%s/collections/*/shards/#", SchemaDomain)}},
133
+ {"Single empty class", []string{""}, []string{fmt.Sprintf("%s/collections/*/shards/#", SchemaDomain)}},
134
+ {"Single class", []string{"class1"}, []string{fmt.Sprintf("%s/collections/Class1/shards/#", SchemaDomain)}},
135
+ {"Multiple classes", []string{"class1", "class2"}, []string{fmt.Sprintf("%s/collections/Class1/shards/#", SchemaDomain), fmt.Sprintf("%s/collections/Class2/shards/#", SchemaDomain)}},
136
+ }
137
+
138
+ for _, tt := range tests {
139
+ t.Run(tt.name, func(t *testing.T) {
140
+ result := CollectionsMetadata(tt.classes...)
141
+ assert.Equal(t, tt.expected, result)
142
+ })
143
+ }
144
+ }
145
+
146
+ func TestShards(t *testing.T) {
147
+ tests := []struct {
148
+ name string
149
+ class string
150
+ shards []string
151
+ expected []string
152
+ }{
153
+ {"No class, no shards", "", []string{}, []string{fmt.Sprintf("%s/collections/*/shards/*", SchemaDomain)}},
154
+ {"Class, no shards", "class1", []string{}, []string{fmt.Sprintf("%s/collections/Class1/shards/*", SchemaDomain)}},
155
+ {"No class, single shard", "", []string{"shard1"}, []string{fmt.Sprintf("%s/collections/*/shards/shard1", SchemaDomain)}},
156
+ {"Class, single shard", "class1", []string{"shard1"}, []string{fmt.Sprintf("%s/collections/Class1/shards/shard1", SchemaDomain)}},
157
+ {"Class, multiple shards", "class1", []string{"shard1", "shard2"}, []string{fmt.Sprintf("%s/collections/Class1/shards/shard1", SchemaDomain), fmt.Sprintf("%s/collections/Class1/shards/shard2", SchemaDomain)}},
158
+ {"Class, empty shard", "class1", []string{"shard1", ""}, []string{fmt.Sprintf("%s/collections/Class1/shards/shard1", SchemaDomain), fmt.Sprintf("%s/collections/Class1/shards/*", SchemaDomain)}},
159
+ }
160
+
161
+ for _, tt := range tests {
162
+ t.Run(tt.name, func(t *testing.T) {
163
+ result := ShardsMetadata(tt.class, tt.shards...)
164
+ assert.Equal(t, tt.expected, result)
165
+ })
166
+ }
167
+ }
168
+
169
+ func TestObjects(t *testing.T) {
170
+ tests := []struct {
171
+ name string
172
+ class string
173
+ shard string
174
+ id strfmt.UUID
175
+ expected string
176
+ }{
177
+ {"No class, no shard, no id", "", "", "", fmt.Sprintf("%s/collections/*/shards/*/objects/*", DataDomain)},
178
+ {"Class, no shard, no id", "class1", "", "", fmt.Sprintf("%s/collections/Class1/shards/*/objects/*", DataDomain)},
179
+ {"No class, shard, no id", "", "shard1", "", fmt.Sprintf("%s/collections/*/shards/shard1/objects/*", DataDomain)},
180
+ {"No class, no shard, id", "", "", "id1", fmt.Sprintf("%s/collections/*/shards/*/objects/id1", DataDomain)},
181
+ {"Class, shard, no id", "class1", "shard1", "", fmt.Sprintf("%s/collections/Class1/shards/shard1/objects/*", DataDomain)},
182
+ {"Class, no shard, id", "class1", "", "id1", fmt.Sprintf("%s/collections/Class1/shards/*/objects/id1", DataDomain)},
183
+ {"No class, shard, id", "", "shard1", "id1", fmt.Sprintf("%s/collections/*/shards/shard1/objects/id1", DataDomain)},
184
+ {"Class, shard, id", "class1", "shard1", "id1", fmt.Sprintf("%s/collections/Class1/shards/shard1/objects/id1", DataDomain)},
185
+ }
186
+
187
+ for _, tt := range tests {
188
+ t.Run(tt.name, func(t *testing.T) {
189
+ result := Objects(tt.class, tt.shard, tt.id)
190
+ assert.Equal(t, tt.expected, result)
191
+ })
192
+ }
193
+ }
194
+
195
+ func TestTenants(t *testing.T) {
196
+ tests := []struct {
197
+ name string
198
+ class string
199
+ shards []string
200
+ expected []string
201
+ }{
202
+ {"No class, no tenant", "", []string{}, []string{fmt.Sprintf("%s/collections/*/shards/*", SchemaDomain)}},
203
+ {"Class, no tenant", "class1", []string{}, []string{fmt.Sprintf("%s/collections/Class1/shards/*", SchemaDomain)}},
204
+ {"No class, single tenant", "", []string{"tenant1"}, []string{fmt.Sprintf("%s/collections/*/shards/tenant1", SchemaDomain)}},
205
+ {"Class, single tenants", "class1", []string{"tenant1"}, []string{fmt.Sprintf("%s/collections/Class1/shards/tenant1", SchemaDomain)}},
206
+ {"Class, multiple tenants", "class1", []string{"tenant1", "tenant2"}, []string{fmt.Sprintf("%s/collections/Class1/shards/tenant1", SchemaDomain), fmt.Sprintf("%s/collections/Class1/shards/tenant2", SchemaDomain)}},
207
+ {"Class, empty tenant", "class1", []string{"tenant1", ""}, []string{fmt.Sprintf("%s/collections/Class1/shards/tenant1", SchemaDomain), fmt.Sprintf("%s/collections/Class1/shards/*", SchemaDomain)}},
208
+ }
209
+
210
+ for _, tt := range tests {
211
+ t.Run(tt.name, func(t *testing.T) {
212
+ result := ShardsMetadata(tt.class, tt.shards...)
213
+ assert.Equal(t, tt.expected, result)
214
+ })
215
+ }
216
+ }
217
+
218
+ func TestGetWildcardPath(t *testing.T) {
219
+ tests := []struct {
220
+ name string
221
+ resource string
222
+ expected string
223
+ }{
224
+ // Data domain tests
225
+ {
226
+ name: "data domain full path",
227
+ resource: "data/collections/Class1/shards/Tenant1/objects/123",
228
+ expected: "data/collections/Class1/shards/Tenant1/objects/*",
229
+ },
230
+ {
231
+ name: "data domain incomplete path",
232
+ resource: "data/collections/Class1/shards/Tenant1",
233
+ expected: "data/collections/Class1/shards/*",
234
+ },
235
+
236
+ // Schema domain tests
237
+ {
238
+ name: "schema domain full path",
239
+ resource: "schema/collections/Class1/shards/Tenant1",
240
+ expected: "schema/collections/Class1/shards/*",
241
+ },
242
+ {
243
+ name: "schema domain full path",
244
+ resource: "schema/collections/Class1/shards/Tenant1",
245
+ expected: "schema/collections/Class1/shards/*",
246
+ },
247
+ {
248
+ name: "schema domain incomplete path",
249
+ resource: "schema/collections/Class1",
250
+ expected: "schema/collections/*",
251
+ },
252
+
253
+ // Backups domain tests
254
+ {
255
+ name: "backups domain full path",
256
+ resource: "backups/collections/Class1",
257
+ expected: "backups/collections/*",
258
+ },
259
+ {
260
+ name: "backups domain incomplete path",
261
+ resource: "backups/collections",
262
+ expected: "backups/*",
263
+ },
264
+
265
+ // Users domain tests
266
+ {
267
+ name: "users domain",
268
+ resource: "users/user1",
269
+ expected: "users/*",
270
+ },
271
+
272
+ // Roles domain tests
273
+ {
274
+ name: "roles domain",
275
+ resource: "roles/role1",
276
+ expected: "roles/*",
277
+ },
278
+ }
279
+
280
+ for _, tt := range tests {
281
+ t.Run(tt.name, func(t *testing.T) {
282
+ result := WildcardPath(tt.resource)
283
+ assert.Equal(t, tt.expected, result, "WildcardPath(%q) = %q, want %q",
284
+ tt.resource, result, tt.expected)
285
+ })
286
+ }
287
+ }
platform/dbops/binaries/weaviate-src/usecases/replica/transport.go ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package replica
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "time"
18
+
19
+ "github.com/go-openapi/strfmt"
20
+ "github.com/weaviate/weaviate/cluster/router/types"
21
+ "github.com/weaviate/weaviate/entities/additional"
22
+ "github.com/weaviate/weaviate/entities/filters"
23
+ "github.com/weaviate/weaviate/entities/search"
24
+ "github.com/weaviate/weaviate/entities/storobj"
25
+ "github.com/weaviate/weaviate/usecases/objects"
26
+ "github.com/weaviate/weaviate/usecases/replica/hashtree"
27
+ )
28
+
29
+ const (
30
+ // RequestKey is used to marshalling request IDs
31
+ RequestKey = "request_id"
32
+ SchemaVersionKey = "schema_version"
33
+ )
34
+
35
+ // Client is used to read and write objects on replicas
36
+ type Client interface {
37
+ RClient
38
+ WClient
39
+ }
40
+
41
+ // StatusCode is communicate the cause of failure during replication
42
+ type StatusCode int
43
+
44
+ const (
45
+ StatusOK = 0
46
+ StatusClassNotFound = iota + 200
47
+ StatusShardNotFound
48
+ StatusNotFound
49
+ StatusAlreadyExisted
50
+ StatusNotReady
51
+ StatusConflict = iota + 300
52
+ StatusPreconditionFailed
53
+ StatusReadOnly
54
+ StatusObjectNotFound
55
+ )
56
+
57
+ // Error reports error happening during replication
58
+ type Error struct {
59
+ Code StatusCode `json:"code"`
60
+ Msg string `json:"msg,omitempty"`
61
+ Err error `json:"-"`
62
+ }
63
+
64
+ // Empty checks whether e is an empty error which equivalent to e == nil
65
+ func (e *Error) Empty() bool {
66
+ return e.Code == StatusOK && e.Msg == "" && e.Err == nil
67
+ }
68
+
69
+ // NewError create new replication error
70
+ func NewError(code StatusCode, msg string) *Error {
71
+ return &Error{code, msg, nil}
72
+ }
73
+
74
+ func (e *Error) Clone() *Error {
75
+ return &Error{Code: e.Code, Msg: e.Msg, Err: e.Err}
76
+ }
77
+
78
+ // Unwrap underlying error
79
+ func (e *Error) Unwrap() error { return e.Err }
80
+
81
+ func (e *Error) Error() string {
82
+ return fmt.Sprintf("%s %q: %v", StatusText(e.Code), e.Msg, e.Err)
83
+ }
84
+
85
+ func (e *Error) IsStatusCode(sc StatusCode) bool {
86
+ return e.Code == sc
87
+ }
88
+
89
+ // StatusText returns a text for the status code. It returns the empty
90
+ // string if the code is unknown.
91
+ func StatusText(code StatusCode) string {
92
+ switch code {
93
+ case StatusOK:
94
+ return "ok"
95
+ case StatusNotFound:
96
+ return "not found"
97
+ case StatusClassNotFound:
98
+ return "class not found"
99
+ case StatusShardNotFound:
100
+ return "shard not found"
101
+ case StatusConflict:
102
+ return "conflict"
103
+ case StatusPreconditionFailed:
104
+ return "precondition failed"
105
+ case StatusAlreadyExisted:
106
+ return "already existed"
107
+ case StatusNotReady:
108
+ return "local index not ready"
109
+ case StatusReadOnly:
110
+ return "read only"
111
+ case StatusObjectNotFound:
112
+ return "object not found"
113
+ default:
114
+ return ""
115
+ }
116
+ }
117
+
118
+ func (e *Error) Timeout() bool {
119
+ t, ok := e.Err.(interface {
120
+ Timeout() bool
121
+ })
122
+ return ok && t.Timeout()
123
+ }
124
+
125
+ type SimpleResponse struct {
126
+ Errors []Error `json:"errors,omitempty"`
127
+ }
128
+
129
+ func (r *SimpleResponse) FirstError() error {
130
+ for i, err := range r.Errors {
131
+ if !err.Empty() {
132
+ return &r.Errors[i]
133
+ }
134
+ }
135
+ return nil
136
+ }
137
+
138
+ // DeleteBatchResponse represents the response returned by DeleteObjects
139
+ type DeleteBatchResponse struct {
140
+ Batch []UUID2Error `json:"batch,omitempty"`
141
+ }
142
+
143
+ type UUID2Error struct {
144
+ UUID string `json:"uuid,omitempty"`
145
+ Error Error `json:"error,omitempty"`
146
+ }
147
+
148
+ // FirstError returns the first found error
149
+ func (r *DeleteBatchResponse) FirstError() error {
150
+ for i, ue := range r.Batch {
151
+ if !ue.Error.Empty() {
152
+ return &r.Batch[i].Error
153
+ }
154
+ }
155
+ return nil
156
+ }
157
+
158
+ func fromReplicas(xs []Replica) []*storobj.Object {
159
+ rs := make([]*storobj.Object, len(xs))
160
+ for i := range xs {
161
+ rs[i] = xs[i].Object
162
+ }
163
+ return rs
164
+ }
165
+
166
+ type DigestObjectsInRangeReq struct {
167
+ InitialUUID strfmt.UUID `json:"initialUUID,omitempty"`
168
+ FinalUUID strfmt.UUID `json:"finalUUID,omitempty"`
169
+ Limit int `json:"limit,omitempty"`
170
+ }
171
+
172
+ type DigestObjectsInRangeResp struct {
173
+ Digests []types.RepairResponse `json:"digests,omitempty"`
174
+ }
175
+
176
+ // WClient is the client used to write to replicas
177
+ type WClient interface {
178
+ PutObject(ctx context.Context, host, index, shard, requestID string,
179
+ obj *storobj.Object, schemaVersion uint64) (SimpleResponse, error)
180
+ DeleteObject(ctx context.Context, host, index, shard, requestID string,
181
+ id strfmt.UUID, deletionTime time.Time, schemaVersion uint64) (SimpleResponse, error)
182
+ PutObjects(ctx context.Context, host, index, shard, requestID string,
183
+ objs []*storobj.Object, schemaVersion uint64) (SimpleResponse, error)
184
+ MergeObject(ctx context.Context, host, index, shard, requestID string,
185
+ mergeDoc *objects.MergeDocument, schemaVersion uint64) (SimpleResponse, error)
186
+ DeleteObjects(ctx context.Context, host, index, shard, requestID string,
187
+ uuids []strfmt.UUID, deletionTime time.Time, dryRun bool, schemaVersion uint64) (SimpleResponse, error)
188
+ AddReferences(ctx context.Context, host, index, shard, requestID string,
189
+ refs []objects.BatchReference, schemaVersion uint64) (SimpleResponse, error)
190
+ Commit(ctx context.Context, host, index, shard, requestID string, resp interface{}) error
191
+ Abort(ctx context.Context, host, index, shard, requestID string) (SimpleResponse, error)
192
+ }
193
+
194
+ // RClient is the client used to read from remote replicas
195
+ type RClient interface {
196
+ // FetchObject fetches one object
197
+ FetchObject(_ context.Context, host, index, shard string,
198
+ id strfmt.UUID, props search.SelectProperties,
199
+ additional additional.Properties, numRetries int) (Replica, error)
200
+
201
+ // FetchObjects fetches objects specified in ids list.
202
+ FetchObjects(_ context.Context, host, index, shard string,
203
+ ids []strfmt.UUID) ([]Replica, error)
204
+
205
+ // OverwriteObjects conditionally updates existing objects.
206
+ OverwriteObjects(_ context.Context, host, index, shard string,
207
+ _ []*objects.VObject) ([]types.RepairResponse, error)
208
+
209
+ // DigestObjects finds a list of objects and returns a compact representation
210
+ // of a list of the objects. This is used by the replicator to optimize the
211
+ // number of bytes transferred over the network when fetching a replicated
212
+ // object
213
+ DigestObjects(ctx context.Context, host, index, shard string,
214
+ ids []strfmt.UUID, numRetries int) ([]types.RepairResponse, error)
215
+
216
+ FindUUIDs(ctx context.Context, host, index, shard string,
217
+ filters *filters.LocalFilter) ([]strfmt.UUID, error)
218
+
219
+ DigestObjectsInRange(ctx context.Context, host, index, shard string,
220
+ initialUUID, finalUUID strfmt.UUID, limit int) ([]types.RepairResponse, error)
221
+
222
+ HashTreeLevel(ctx context.Context, host, index, shard string, level int,
223
+ discriminant *hashtree.Bitset) (digests []hashtree.Digest, err error)
224
+ }
225
+
226
+ // FinderClient extends RClient with consistency checks
227
+ type FinderClient struct {
228
+ cl RClient
229
+ }
230
+
231
+ // FullRead reads full object
232
+ func (fc FinderClient) FullRead(ctx context.Context,
233
+ host, index, shard string,
234
+ id strfmt.UUID,
235
+ props search.SelectProperties,
236
+ additional additional.Properties,
237
+ numRetries int,
238
+ ) (Replica, error) {
239
+ return fc.cl.FetchObject(ctx, host, index, shard, id, props, additional, numRetries)
240
+ }
241
+
242
+ func (fc FinderClient) HashTreeLevel(ctx context.Context,
243
+ host, index, shard string, level int, discriminant *hashtree.Bitset,
244
+ ) (digests []hashtree.Digest, err error) {
245
+ return fc.cl.HashTreeLevel(ctx, host, index, shard, level, discriminant)
246
+ }
247
+
248
+ // DigestReads reads digests of all specified objects
249
+ func (fc FinderClient) DigestReads(ctx context.Context,
250
+ host, index, shard string,
251
+ ids []strfmt.UUID, numRetries int,
252
+ ) ([]types.RepairResponse, error) {
253
+ n := len(ids)
254
+ rs, err := fc.cl.DigestObjects(ctx, host, index, shard, ids, numRetries)
255
+ if err == nil && len(rs) != n {
256
+ err = fmt.Errorf("malformed digest read response: length expected %d got %d", n, len(rs))
257
+ }
258
+ return rs, err
259
+ }
260
+
261
+ func (fc FinderClient) DigestObjectsInRange(ctx context.Context,
262
+ host, index, shard string,
263
+ initialUUID, finalUUID strfmt.UUID, limit int,
264
+ ) ([]types.RepairResponse, error) {
265
+ return fc.cl.DigestObjectsInRange(ctx, host, index, shard, initialUUID, finalUUID, limit)
266
+ }
267
+
268
+ // FullReads read full objects
269
+ func (fc FinderClient) FullReads(ctx context.Context,
270
+ host, index, shard string,
271
+ ids []strfmt.UUID,
272
+ ) ([]Replica, error) {
273
+ n := len(ids)
274
+ rs, err := fc.cl.FetchObjects(ctx, host, index, shard, ids)
275
+ if m := len(rs); err == nil && n != m {
276
+ err = fmt.Errorf("malformed full read response: length expected %d got %d", n, m)
277
+ }
278
+ return rs, err
279
+ }
280
+
281
+ // Overwrite specified object with most recent contents
282
+ func (fc FinderClient) Overwrite(ctx context.Context,
283
+ host, index, shard string,
284
+ xs []*objects.VObject,
285
+ ) ([]types.RepairResponse, error) {
286
+ return fc.cl.OverwriteObjects(ctx, host, index, shard, xs)
287
+ }
288
+
289
+ func (fc FinderClient) FindUUIDs(ctx context.Context,
290
+ host, class, shard string, filters *filters.LocalFilter,
291
+ ) ([]strfmt.UUID, error) {
292
+ return fc.cl.FindUUIDs(ctx, host, class, shard, filters)
293
+ }
platform/dbops/binaries/weaviate-src/usecases/replica/transport_test.go ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package replica_test
13
+
14
+ import (
15
+ "encoding/json"
16
+ "testing"
17
+ "time"
18
+
19
+ "github.com/weaviate/weaviate/usecases/replica"
20
+
21
+ "github.com/pkg/errors"
22
+ "github.com/stretchr/testify/assert"
23
+ "golang.org/x/net/context"
24
+ )
25
+
26
+ func TestReplicationErrorTimeout(t *testing.T) {
27
+ ctx := context.Background()
28
+ ctx, cancel := context.WithDeadline(ctx, time.Now())
29
+ defer cancel()
30
+ err := &replica.Error{Err: ctx.Err()}
31
+ assert.True(t, err.Timeout())
32
+ err = err.Clone()
33
+ assert.ErrorIs(t, err, context.DeadlineExceeded)
34
+ }
35
+
36
+ func TestReplicationErrorMarshal(t *testing.T) {
37
+ rawErr := replica.Error{Code: replica.StatusClassNotFound, Msg: "Article", Err: errors.New("error cannot be marshalled")}
38
+ bytes, err := json.Marshal(&rawErr)
39
+ assert.Nil(t, err)
40
+ got := replica.NewError(0, "")
41
+ assert.Nil(t, json.Unmarshal(bytes, got))
42
+ want := &replica.Error{Code: replica.StatusClassNotFound, Msg: "Article"}
43
+ assert.Equal(t, want, got)
44
+ }
45
+
46
+ func TestReplicationErrorStatus(t *testing.T) {
47
+ tests := []struct {
48
+ code replica.StatusCode
49
+ desc string
50
+ }{
51
+ {-1, ""},
52
+ {replica.StatusOK, "ok"},
53
+ {replica.StatusClassNotFound, "class not found"},
54
+ {replica.StatusShardNotFound, "shard not found"},
55
+ {replica.StatusNotFound, "not found"},
56
+ {replica.StatusAlreadyExisted, "already existed"},
57
+ {replica.StatusConflict, "conflict"},
58
+ {replica.StatusPreconditionFailed, "precondition failed"},
59
+ {replica.StatusReadOnly, "read only"},
60
+ }
61
+ for _, test := range tests {
62
+ got := replica.StatusText(test.code)
63
+ if got != test.desc {
64
+ t.Errorf("StatusText(%d) want %v got %v", test.code, test.desc, got)
65
+ }
66
+ }
67
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/alias.go ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+
19
+ cschema "github.com/weaviate/weaviate/cluster/schema"
20
+ "github.com/weaviate/weaviate/entities/models"
21
+ "github.com/weaviate/weaviate/entities/schema"
22
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
23
+ "github.com/weaviate/weaviate/usecases/auth/authorization/filter"
24
+ )
25
+
26
+ func (h *Handler) GetAliases(ctx context.Context, principal *models.Principal, alias, className string) ([]*models.Alias, error) {
27
+ var class *models.Class
28
+ if className != "" {
29
+ name := schema.UppercaseClassName(className)
30
+ class = h.schemaReader.ReadOnlyClass(name)
31
+ }
32
+ aliases, err := h.schemaManager.GetAliases(ctx, alias, class)
33
+ if err != nil {
34
+ return nil, err
35
+ }
36
+
37
+ filteredAliases := filter.New[*models.Alias](h.Authorizer, h.config.Authorization.Rbac).Filter(
38
+ ctx,
39
+ h.logger,
40
+ principal,
41
+ aliases,
42
+ authorization.READ,
43
+ func(alias *models.Alias) string {
44
+ return authorization.Aliases(className, alias.Alias)[0]
45
+ },
46
+ )
47
+
48
+ return filteredAliases, nil
49
+ }
50
+
51
+ func (h *Handler) GetAlias(ctx context.Context, principal *models.Principal, alias string) (*models.Alias, error) {
52
+ alias = schema.UppercaseClassName(alias)
53
+ // NOTE: We pass empty class, because this endpoint doesn't know what collection the alias belongs to
54
+ // hence if RBAC is enabled, the user has to have read permission for all the collection for api to go discover
55
+ // right collection for the alias.
56
+ if err := h.Authorizer.Authorize(ctx, principal, authorization.READ, authorization.Aliases("", alias)...); err != nil {
57
+ return nil, err
58
+ }
59
+
60
+ a, err := h.schemaManager.GetAlias(ctx, alias)
61
+ if err != nil {
62
+ if errors.Is(err, cschema.ErrAliasNotFound) {
63
+ return nil, fmt.Errorf("alias %s not found: %w", alias, ErrNotFound)
64
+ }
65
+ return nil, err
66
+ }
67
+ return a, nil
68
+ }
69
+
70
+ func (h *Handler) AddAlias(ctx context.Context, principal *models.Principal,
71
+ alias *models.Alias,
72
+ ) (*models.Alias, uint64, error) {
73
+ alias.Class = schema.UppercaseClassName(alias.Class)
74
+ alias.Alias = schema.UppercaseClassName(alias.Alias)
75
+
76
+ err := h.Authorizer.Authorize(ctx, principal, authorization.CREATE, authorization.Aliases(alias.Class, alias.Alias)...)
77
+ if err != nil {
78
+ return nil, 0, err
79
+ }
80
+
81
+ // alias should have same validation as collection.
82
+ al, err := schema.ValidateAliasName(alias.Alias)
83
+ if err != nil {
84
+ return nil, 0, err
85
+ }
86
+ alias.Alias = al
87
+
88
+ class := h.schemaReader.ReadOnlyClass(alias.Class)
89
+ version, err := h.schemaManager.CreateAlias(ctx, alias.Alias, class)
90
+ if err != nil {
91
+ return nil, 0, err
92
+ }
93
+ return &models.Alias{Alias: alias.Alias, Class: class.Class}, version, nil
94
+ }
95
+
96
+ func (h *Handler) UpdateAlias(ctx context.Context, principal *models.Principal,
97
+ aliasName, targetClassName string,
98
+ ) (*models.Alias, error) {
99
+ targetClassName = schema.UppercaseClassName(targetClassName)
100
+ aliasName = schema.UppercaseClassName(aliasName)
101
+ err := h.Authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.Aliases(targetClassName, aliasName)...)
102
+ if err != nil {
103
+ return nil, err
104
+ }
105
+ aliases, err := h.schemaManager.GetAliases(ctx, aliasName, nil)
106
+ if err != nil {
107
+ return nil, err
108
+ }
109
+
110
+ if len(aliases) != 1 {
111
+ return nil, fmt.Errorf("%w, no alias found with name: %s", ErrNotFound, aliasName)
112
+ }
113
+
114
+ alias := aliases[0]
115
+ targetClass := h.schemaReader.ReadOnlyClass(targetClassName)
116
+
117
+ _, err = h.schemaManager.ReplaceAlias(ctx, alias, targetClass)
118
+ if err != nil {
119
+ return nil, err
120
+ }
121
+
122
+ return &models.Alias{Alias: alias.Alias, Class: targetClass.Class}, nil
123
+ }
124
+
125
+ func (h *Handler) DeleteAlias(ctx context.Context, principal *models.Principal, aliasName string) error {
126
+ aliasName = schema.UppercaseClassName(aliasName)
127
+ err := h.Authorizer.Authorize(ctx, principal, authorization.DELETE, authorization.Aliases("", aliasName)...)
128
+ if err != nil {
129
+ return err
130
+ }
131
+
132
+ aliases, err := h.schemaManager.GetAliases(ctx, aliasName, nil)
133
+ if err != nil {
134
+ return err
135
+ }
136
+ if len(aliases) == 0 {
137
+ return fmt.Errorf("alias not found: %w", ErrNotFound)
138
+ }
139
+
140
+ if _, err = h.schemaManager.DeleteAlias(ctx, aliasName); err != nil {
141
+ return err
142
+ }
143
+ return nil
144
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/authorization_test.go ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+ "reflect"
19
+ "testing"
20
+
21
+ "github.com/stretchr/testify/assert"
22
+ "github.com/stretchr/testify/mock"
23
+ "github.com/stretchr/testify/require"
24
+
25
+ "github.com/weaviate/weaviate/entities/models"
26
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
27
+ "github.com/weaviate/weaviate/usecases/auth/authorization/mocks"
28
+ )
29
+
30
+ // A component-test like test suite that makes sure that every available UC is
31
+ // potentially protected with the Authorization plugin
32
+ func Test_Schema_Authorization(t *testing.T) {
33
+ type testCase struct {
34
+ methodName string
35
+ additionalArgs []interface{}
36
+ expectedVerb string
37
+ expectedResources []string
38
+ }
39
+
40
+ tests := []testCase{
41
+ {
42
+ methodName: "GetClass",
43
+ additionalArgs: []interface{}{"classname"},
44
+ expectedVerb: authorization.READ,
45
+ expectedResources: authorization.CollectionsMetadata("classname"),
46
+ },
47
+ {
48
+ methodName: "GetConsistentClass",
49
+ additionalArgs: []interface{}{"classname", false},
50
+ expectedVerb: authorization.READ,
51
+ expectedResources: authorization.CollectionsMetadata("classname"),
52
+ },
53
+ {
54
+ methodName: "GetCachedClass",
55
+ additionalArgs: []interface{}{"classname"},
56
+ expectedVerb: authorization.READ,
57
+ expectedResources: authorization.CollectionsMetadata("classname"),
58
+ },
59
+ {
60
+ methodName: "AddClass",
61
+ additionalArgs: []interface{}{&models.Class{Class: "classname"}},
62
+ expectedVerb: authorization.CREATE,
63
+ expectedResources: authorization.CollectionsMetadata("Classname"),
64
+ },
65
+ {
66
+ methodName: "UpdateClass",
67
+ additionalArgs: []interface{}{"class", &models.Class{Class: "class"}},
68
+ expectedVerb: authorization.UPDATE,
69
+ expectedResources: authorization.CollectionsMetadata("class"),
70
+ },
71
+ {
72
+ methodName: "DeleteClass",
73
+ additionalArgs: []interface{}{"somename"},
74
+ expectedVerb: authorization.DELETE,
75
+ expectedResources: authorization.CollectionsMetadata("somename"),
76
+ },
77
+ {
78
+ methodName: "AddClassProperty",
79
+ additionalArgs: []interface{}{&models.Class{Class: "classname"}, "classname", false, &models.Property{}},
80
+ expectedVerb: authorization.UPDATE,
81
+ expectedResources: authorization.CollectionsMetadata("classname"),
82
+ },
83
+ {
84
+ methodName: "DeleteClassProperty",
85
+ additionalArgs: []interface{}{"somename", "someprop"},
86
+ expectedVerb: authorization.UPDATE,
87
+ expectedResources: authorization.CollectionsMetadata("somename"),
88
+ },
89
+ {
90
+ methodName: "UpdateShardStatus",
91
+ additionalArgs: []interface{}{"className", "shardName", "targetStatus"},
92
+ expectedVerb: authorization.UPDATE,
93
+ expectedResources: authorization.ShardsMetadata("className", "shardName"),
94
+ },
95
+ {
96
+ methodName: "ShardsStatus",
97
+ additionalArgs: []interface{}{"className", "tenant"},
98
+ expectedVerb: authorization.READ,
99
+ expectedResources: authorization.ShardsMetadata("className", "tenant"),
100
+ },
101
+ {
102
+ methodName: "AddTenants",
103
+ additionalArgs: []interface{}{"className", []*models.Tenant{{Name: "P1"}}},
104
+ expectedVerb: authorization.CREATE,
105
+ expectedResources: authorization.ShardsMetadata("className", "P1"),
106
+ },
107
+ {
108
+ methodName: "UpdateTenants",
109
+ additionalArgs: []interface{}{"className", []*models.Tenant{
110
+ {Name: "P1", ActivityStatus: models.TenantActivityStatusHOT},
111
+ }},
112
+ expectedVerb: authorization.UPDATE,
113
+ expectedResources: authorization.ShardsMetadata("className", "P1"),
114
+ },
115
+ {
116
+ methodName: "DeleteTenants",
117
+ additionalArgs: []interface{}{"className", []string{"P1"}},
118
+ expectedVerb: authorization.DELETE,
119
+ expectedResources: authorization.ShardsMetadata("className", "P1"),
120
+ },
121
+ {
122
+ methodName: "ConsistentTenantExists",
123
+ additionalArgs: []interface{}{"className", false, "P1"},
124
+ expectedVerb: authorization.READ,
125
+ expectedResources: authorization.ShardsMetadata("className", "P1"),
126
+ },
127
+ {
128
+ methodName: "AddAlias",
129
+ additionalArgs: []interface{}{&models.Alias{Class: "classname", Alias: "aliasName"}},
130
+ expectedVerb: authorization.CREATE,
131
+ expectedResources: authorization.Aliases("Classname", "AliasName"),
132
+ },
133
+ {
134
+ methodName: "UpdateAlias",
135
+ additionalArgs: []interface{}{"aliasName", "class"},
136
+ expectedVerb: authorization.UPDATE,
137
+ expectedResources: authorization.Aliases("class", "aliasName"),
138
+ },
139
+ {
140
+ methodName: "DeleteAlias",
141
+ additionalArgs: []interface{}{"aliasName"},
142
+ expectedVerb: authorization.DELETE,
143
+ expectedResources: authorization.Aliases("", "aliasName"),
144
+ },
145
+ {
146
+ methodName: "GetAlias",
147
+ additionalArgs: []interface{}{"aliasName"},
148
+ expectedVerb: authorization.READ,
149
+ expectedResources: authorization.Aliases("", "aliasName"),
150
+ },
151
+ }
152
+
153
+ t.Run("verify that a test for every public method exists", func(t *testing.T) {
154
+ testedMethods := make([]string, len(tests))
155
+ for i, test := range tests {
156
+ testedMethods[i] = test.methodName
157
+ }
158
+
159
+ for _, method := range allExportedMethods(&Handler{classGetter: nil}) {
160
+ switch method {
161
+ case "RegisterSchemaUpdateCallback",
162
+ // introduced by sync.Mutex in go 1.18
163
+ "UpdateMeta", "GetSchemaSkipAuth", "IndexedInverted", "RLock", "RUnlock", "Lock", "Unlock",
164
+ "TryLock", "RLocker", "TryRLock", "TxManager", "RestoreClass",
165
+ "ShardOwner", "TenantShard", "ShardFromUUID", "LockGuard", "RLockGuard", "ShardReplicas",
166
+ "GetCachedClassNoAuth",
167
+ // internal methods to indicate readiness state
168
+ "StartServing", "Shutdown", "Statistics",
169
+ // Cluster/nodes related endpoint
170
+ "JoinNode", "RemoveNode", "Nodes", "NodeName", "ClusterHealthScore", "ClusterStatus", "ResolveParentNodes",
171
+ // revert to schema v0 (non raft),
172
+ "GetConsistentSchema", "GetConsistentTenants", "GetConsistentTenant", "GetAliases",
173
+ // ignored because it will check if schema has collections otherwise returns nothing
174
+ "StoreSchemaV1":
175
+ // don't require auth on methods which are exported because other
176
+ // packages need to call them for maintenance and other regular jobs,
177
+ // but aren't user facing
178
+ continue
179
+ }
180
+ assert.Contains(t, testedMethods, method)
181
+ }
182
+ })
183
+
184
+ t.Run("verify the tested methods require correct permissions from the Authorizer", func(t *testing.T) {
185
+ principal := &models.Principal{}
186
+ for _, test := range tests {
187
+ t.Run(test.methodName, func(t *testing.T) {
188
+ authorizer := mocks.NewMockAuthorizer()
189
+ authorizer.SetErr(errors.New("just a test fake"))
190
+ handler, fakeSchemaManager := newTestHandlerWithCustomAuthorizer(t, &fakeDB{}, authorizer)
191
+ fakeSchemaManager.On("ReadOnlySchema").Return(models.Schema{})
192
+ fakeSchemaManager.On("ReadOnlyClass", mock.Anything).Return(models.Class{})
193
+ fakeSchemaManager.On("GetAliases", mock.Anything, mock.Anything, mock.Anything).Return([]*models.Alias{{}}, nil)
194
+ fakeSchemaManager.On("GetAlias", mock.Anything, mock.Anything).Return(&models.Alias{}, nil)
195
+
196
+ var args []interface{}
197
+ if test.methodName == "GetSchema" || test.methodName == "GetConsistentSchema" {
198
+ // no context on this method
199
+ args = append([]interface{}{principal}, test.additionalArgs...)
200
+ } else {
201
+ args = append([]interface{}{context.Background(), principal}, test.additionalArgs...)
202
+ }
203
+ out, _ := callFuncByName(handler, test.methodName, args...)
204
+
205
+ require.Len(t, authorizer.Calls(), 1, "Authorizer must be called")
206
+ assert.Equal(t, errors.New("just a test fake"), out[len(out)-1].Interface(),
207
+ "execution must abort with Authorizer error")
208
+ assert.Equal(t, mocks.AuthZReq{Principal: principal, Verb: test.expectedVerb, Resources: test.expectedResources},
209
+ authorizer.Calls()[0], "correct parameters must have been used on Authorizer")
210
+ })
211
+ }
212
+ })
213
+ }
214
+
215
+ // inspired by https://stackoverflow.com/a/33008200
216
+ func callFuncByName(manager interface{}, funcName string, params ...interface{}) (out []reflect.Value, err error) {
217
+ managerValue := reflect.ValueOf(manager)
218
+ m := managerValue.MethodByName(funcName)
219
+ if !m.IsValid() {
220
+ return make([]reflect.Value, 0), fmt.Errorf("Method not found \"%s\"", funcName)
221
+ }
222
+ in := make([]reflect.Value, len(params))
223
+ for i, param := range params {
224
+ in[i] = reflect.ValueOf(param)
225
+ }
226
+ out = m.Call(in)
227
+ return
228
+ }
229
+
230
+ func allExportedMethods(subject interface{}) []string {
231
+ var methods []string
232
+ subjectType := reflect.TypeOf(subject)
233
+ for i := 0; i < subjectType.NumMethod(); i++ {
234
+ name := subjectType.Method(i).Name
235
+ if name[0] >= 'A' && name[0] <= 'Z' {
236
+ methods = append(methods, name)
237
+ }
238
+ }
239
+
240
+ return methods
241
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/class.go ADDED
@@ -0,0 +1,1009 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "encoding/json"
17
+ "fmt"
18
+ "os"
19
+ "reflect"
20
+ "strings"
21
+
22
+ "github.com/pkg/errors"
23
+ "github.com/prometheus/client_golang/prometheus"
24
+ "github.com/weaviate/weaviate/entities/modelsext"
25
+ schemaConfig "github.com/weaviate/weaviate/entities/schema/config"
26
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
27
+
28
+ "github.com/weaviate/weaviate/adapters/repos/db/inverted/stopwords"
29
+ cschema "github.com/weaviate/weaviate/cluster/schema"
30
+ "github.com/weaviate/weaviate/entities/backup"
31
+ "github.com/weaviate/weaviate/entities/classcache"
32
+ entcfg "github.com/weaviate/weaviate/entities/config"
33
+ "github.com/weaviate/weaviate/entities/models"
34
+ "github.com/weaviate/weaviate/entities/replication"
35
+ "github.com/weaviate/weaviate/entities/schema"
36
+ "github.com/weaviate/weaviate/entities/vectorindex"
37
+ "github.com/weaviate/weaviate/entities/versioned"
38
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
39
+ "github.com/weaviate/weaviate/usecases/config"
40
+ configRuntime "github.com/weaviate/weaviate/usecases/config/runtime"
41
+ "github.com/weaviate/weaviate/usecases/monitoring"
42
+ "github.com/weaviate/weaviate/usecases/replica"
43
+ "github.com/weaviate/weaviate/usecases/sharding"
44
+ shardingcfg "github.com/weaviate/weaviate/usecases/sharding/config"
45
+ )
46
+
47
+ func (h *Handler) GetClass(ctx context.Context, principal *models.Principal, name string) (*models.Class, error) {
48
+ if err := h.Authorizer.Authorize(ctx, principal, authorization.READ, authorization.CollectionsMetadata(name)...); err != nil {
49
+ return nil, err
50
+ }
51
+ name = schema.UppercaseClassName(name)
52
+
53
+ cl := h.schemaReader.ReadOnlyClass(name)
54
+ return cl, nil
55
+ }
56
+
57
+ func (h *Handler) GetConsistentClass(ctx context.Context, principal *models.Principal,
58
+ name string, consistency bool,
59
+ ) (*models.Class, uint64, error) {
60
+ if err := h.Authorizer.Authorize(ctx, principal, authorization.READ, authorization.CollectionsMetadata(name)...); err != nil {
61
+ return nil, 0, err
62
+ }
63
+
64
+ name = schema.UppercaseClassName(name)
65
+
66
+ if consistency {
67
+ vclasses, err := h.schemaManager.QueryReadOnlyClasses(name)
68
+ return vclasses[name].Class, vclasses[name].Version, err
69
+ }
70
+ class, err := h.schemaReader.ReadOnlyClassWithVersion(ctx, name, 0)
71
+ return class, 0, err
72
+ }
73
+
74
+ // GetCachedClass will return the class from the cache if it exists. Note that the context cache
75
+ // will likely be at the "request" or "operation" level and not be shared between requests.
76
+ // Uses the Handler's getClassMethod to determine how to get the class data.
77
+ func (h *Handler) GetCachedClass(ctxWithClassCache context.Context,
78
+ principal *models.Principal, names ...string,
79
+ ) (map[string]versioned.Class, error) {
80
+ if err := h.Authorizer.Authorize(ctxWithClassCache, principal, authorization.READ, authorization.CollectionsMetadata(names...)...); err != nil {
81
+ return nil, err
82
+ }
83
+
84
+ return classcache.ClassesFromContext(ctxWithClassCache, func(names ...string) (map[string]versioned.Class, error) {
85
+ return h.classGetter.getClasses(names)
86
+ }, names...)
87
+ }
88
+
89
+ // GetCachedClassNoAuth will return the class from the cache if it exists. Note that the context cache
90
+ // will likely be at the "request" or "operation" level and not be shared between requests.
91
+ // Uses the Handler's getClassMethod to determine how to get the class data.
92
+ func (h *Handler) GetCachedClassNoAuth(ctxWithClassCache context.Context, names ...string) (map[string]versioned.Class, error) {
93
+ return classcache.ClassesFromContext(ctxWithClassCache, func(names ...string) (map[string]versioned.Class, error) {
94
+ return h.classGetter.getClasses(names)
95
+ }, names...)
96
+ }
97
+
98
+ // AddClass to the schema
99
+ func (h *Handler) AddClass(ctx context.Context, principal *models.Principal,
100
+ cls *models.Class,
101
+ ) (*models.Class, uint64, error) {
102
+ cls.Class = schema.UppercaseClassName(cls.Class)
103
+ cls.Properties = schema.LowercaseAllPropertyNames(cls.Properties)
104
+
105
+ err := h.Authorizer.Authorize(ctx, principal, authorization.CREATE, authorization.CollectionsMetadata(cls.Class)...)
106
+ if err != nil {
107
+ return nil, 0, err
108
+ }
109
+
110
+ classGetterWithAuth := func(name string) (*models.Class, error) {
111
+ if err := h.Authorizer.Authorize(ctx, principal, authorization.READ, authorization.CollectionsMetadata(name)...); err != nil {
112
+ return nil, err
113
+ }
114
+ return h.schemaReader.ReadOnlyClass(name), nil
115
+ }
116
+
117
+ if err := h.setNewClassDefaults(cls, h.config.Replication); err != nil {
118
+ return nil, 0, err
119
+ }
120
+
121
+ if err := h.validateCanAddClass(ctx, cls, classGetterWithAuth, false); err != nil {
122
+ return nil, 0, err
123
+ }
124
+ // migrate only after validation in completed
125
+ h.migrateClassSettings(cls)
126
+ if err := h.parser.ParseClass(cls); err != nil {
127
+ return nil, 0, err
128
+ }
129
+
130
+ err = h.invertedConfigValidator(cls.InvertedIndexConfig)
131
+ if err != nil {
132
+ return nil, 0, err
133
+ }
134
+
135
+ existingCollectionsCount, err := h.schemaManager.QueryCollectionsCount()
136
+ if err != nil {
137
+ h.logger.WithField("error", err).Error("could not query the collections count")
138
+ }
139
+
140
+ limit := h.schemaConfig.MaximumAllowedCollectionsCount.Get()
141
+
142
+ if limit != config.DefaultMaximumAllowedCollectionsCount && existingCollectionsCount >= limit {
143
+ return nil, 0, fmt.Errorf(
144
+ "cannot create collection: maximum number of collections (%d) reached - "+
145
+ "please consider switching to multi-tenancy or increasing the collection count limit - "+
146
+ "see https://weaviate.io/collections-count-limit to learn about available options and best practices "+
147
+ "when working with multiple collections and tenants",
148
+ limit)
149
+ }
150
+
151
+ shardState, err := sharding.InitState(cls.Class,
152
+ cls.ShardingConfig.(shardingcfg.Config),
153
+ h.clusterState.LocalName(), h.schemaManager.StorageCandidates(), cls.ReplicationConfig.Factor,
154
+ schema.MultiTenancyEnabled(cls))
155
+ if err != nil {
156
+ return nil, 0, errors.Wrap(err, "init sharding state")
157
+ }
158
+
159
+ defaultQuantization := h.config.DefaultQuantization
160
+ h.enableQuantization(cls, defaultQuantization)
161
+
162
+ version, err := h.schemaManager.AddClass(ctx, cls, shardState)
163
+ if err != nil {
164
+ return nil, 0, err
165
+ }
166
+ return cls, version, err
167
+ }
168
+
169
+ func (h *Handler) enableQuantization(class *models.Class, defaultQuantization *configRuntime.DynamicValue[string]) {
170
+ compression := defaultQuantization.Get()
171
+ if !hasTargetVectors(class) || class.VectorIndexType != "" {
172
+ class.VectorIndexConfig = setDefaultQuantization(class.VectorIndexType, class.VectorIndexConfig.(schemaConfig.VectorIndexConfig), compression)
173
+ }
174
+
175
+ for k, vectorConfig := range class.VectorConfig {
176
+ vectorConfig.VectorIndexConfig = setDefaultQuantization(class.VectorIndexType, vectorConfig.VectorIndexConfig.(schemaConfig.VectorIndexConfig), compression)
177
+ class.VectorConfig[k] = vectorConfig
178
+ }
179
+ }
180
+
181
+ func setDefaultQuantization(vectorIndexType string, vectorIndexConfig schemaConfig.VectorIndexConfig, compression string) schemaConfig.VectorIndexConfig {
182
+ if len(vectorIndexType) == 0 {
183
+ vectorIndexType = vectorindex.DefaultVectorIndexType
184
+ }
185
+ if vectorIndexType == vectorindex.VectorIndexTypeHNSW && vectorIndexConfig.IndexType() == vectorindex.VectorIndexTypeHNSW {
186
+ hnswConfig := vectorIndexConfig.(hnsw.UserConfig)
187
+ pqEnabled := hnswConfig.PQ.Enabled
188
+ sqEnabled := hnswConfig.SQ.Enabled
189
+ rqEnabled := hnswConfig.RQ.Enabled
190
+ bqEnabled := hnswConfig.BQ.Enabled
191
+ skipDefaultQuantization := hnswConfig.SkipDefaultQuantization
192
+ hnswConfig.TrackDefaultQuantization = false
193
+ if pqEnabled || sqEnabled || rqEnabled || bqEnabled {
194
+ return hnswConfig
195
+ }
196
+ if skipDefaultQuantization {
197
+ return hnswConfig
198
+ }
199
+ switch compression {
200
+ case "pq":
201
+ hnswConfig.PQ.Enabled = true
202
+ case "sq":
203
+ hnswConfig.SQ.Enabled = true
204
+ case "rq-1":
205
+ hnswConfig.RQ.Enabled = true
206
+ hnswConfig.RQ.Bits = 1
207
+ hnswConfig.RQ.RescoreLimit = hnsw.DefaultBRQRescoreLimit
208
+ case "rq-8":
209
+ hnswConfig.RQ.Enabled = true
210
+ hnswConfig.RQ.Bits = 8
211
+ hnswConfig.RQ.RescoreLimit = hnsw.DefaultRQRescoreLimit
212
+ case "bq":
213
+ hnswConfig.BQ.Enabled = true
214
+ default:
215
+ return hnswConfig
216
+ }
217
+ hnswConfig.TrackDefaultQuantization = true
218
+ return hnswConfig
219
+ }
220
+ return vectorIndexConfig
221
+ }
222
+
223
+ func (h *Handler) RestoreClass(ctx context.Context, d *backup.ClassDescriptor, m map[string]string, overwriteAlias bool) error {
224
+ // get schema and sharding state
225
+ class := &models.Class{}
226
+ if err := json.Unmarshal(d.Schema, &class); err != nil {
227
+ return fmt.Errorf("unmarshal class schema: %w", err)
228
+ }
229
+ var shardingState sharding.State
230
+ if d.ShardingState != nil {
231
+ err := json.Unmarshal(d.ShardingState, &shardingState)
232
+ if err != nil {
233
+ return fmt.Errorf("unmarshal sharding state: %w", err)
234
+ }
235
+ }
236
+
237
+ aliases := make([]*models.Alias, 0)
238
+ if d.AliasesIncluded {
239
+ if err := json.Unmarshal(d.Aliases, &aliases); err != nil {
240
+ return fmt.Errorf("unmarshal aliases: %w", err)
241
+ }
242
+ }
243
+
244
+ metric, err := monitoring.GetMetrics().BackupRestoreClassDurations.GetMetricWithLabelValues(class.Class)
245
+ if err == nil {
246
+ timer := prometheus.NewTimer(metric)
247
+ defer timer.ObserveDuration()
248
+ }
249
+
250
+ class.Class = schema.UppercaseClassName(class.Class)
251
+ class.Properties = schema.LowercaseAllPropertyNames(class.Properties)
252
+
253
+ if err := h.setClassDefaults(class, h.config.Replication); err != nil {
254
+ return err
255
+ }
256
+
257
+ // no validation of reference for restore
258
+ classGetterWrapper := func(name string) (*models.Class, error) {
259
+ return h.schemaReader.ReadOnlyClass(name), nil
260
+ }
261
+
262
+ err = h.validateClassInvariants(ctx, class, classGetterWrapper, true)
263
+ if err != nil {
264
+ return err
265
+ }
266
+ // migrate only after validation in completed
267
+ h.migrateClassSettings(class)
268
+
269
+ if err := h.parser.ParseClass(class); err != nil {
270
+ return err
271
+ }
272
+
273
+ err = h.invertedConfigValidator(class.InvertedIndexConfig)
274
+ if err != nil {
275
+ return err
276
+ }
277
+
278
+ shardingState.MigrateFromOldFormat()
279
+ err = shardingState.MigrateShardingStateReplicationFactor()
280
+ if err != nil {
281
+ return fmt.Errorf("error while migrating replication factor: %w", err)
282
+ }
283
+ shardingState.ApplyNodeMapping(m)
284
+ _, err = h.schemaManager.RestoreClass(ctx, class, &shardingState)
285
+ if err != nil {
286
+ return fmt.Errorf("error when trying to restore class: %w", err)
287
+ }
288
+
289
+ for _, alias := range aliases {
290
+ var err error
291
+ _, err = h.schemaManager.CreateAlias(ctx, alias.Alias, class)
292
+ if errors.Is(err, cschema.ErrAliasExists) {
293
+ // Overwrite if user asks to during restore
294
+ if overwriteAlias {
295
+ _, err = h.schemaManager.DeleteAlias(ctx, alias.Alias)
296
+ if err != nil {
297
+ return fmt.Errorf("failed to restore alias for class: delete alias failed: %w", err)
298
+ }
299
+ // retry again
300
+ _, err = h.schemaManager.CreateAlias(ctx, alias.Alias, class)
301
+ if err != nil {
302
+ return fmt.Errorf("failed to restore alias for class: create alias failed: %w", err)
303
+ }
304
+ return nil
305
+ }
306
+ // Schema returned alias already exists error. So let user know
307
+ // that there is a "flag overwrite" if she want's to overwrite alias.
308
+ return fmt.Errorf("failed to restore alias for class: alias already exists. You can overwrite using `overwrite_alias` param when restoring")
309
+ }
310
+
311
+ if err != nil {
312
+ return fmt.Errorf("failed to restore alias for class: %w", err)
313
+ }
314
+ }
315
+
316
+ return nil
317
+ }
318
+
319
+ // DeleteClass from the schema
320
+ func (h *Handler) DeleteClass(ctx context.Context, principal *models.Principal, class string) error {
321
+ err := h.Authorizer.Authorize(ctx, principal, authorization.DELETE, authorization.CollectionsMetadata(class)...)
322
+ if err != nil {
323
+ return err
324
+ }
325
+
326
+ class = schema.UppercaseClassName(class)
327
+
328
+ if _, err = h.schemaManager.DeleteClass(ctx, class); err != nil {
329
+ return err
330
+ }
331
+
332
+ return nil
333
+ }
334
+
335
+ func (h *Handler) UpdateClass(ctx context.Context, principal *models.Principal,
336
+ className string, updated *models.Class,
337
+ ) error {
338
+ err := h.Authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.CollectionsMetadata(className)...)
339
+ if err != nil || updated == nil {
340
+ return err
341
+ }
342
+
343
+ return UpdateClassInternal(h, ctx, className, updated)
344
+ }
345
+
346
+ // bypass the auth check for internal class update requests
347
+ func UpdateClassInternal(h *Handler, ctx context.Context, className string, updated *models.Class,
348
+ ) error {
349
+ // make sure unset optionals on 'updated' don't lead to an error, as all
350
+ // optionals would have been set with defaults on the initial already
351
+ if err := h.setClassDefaults(updated, h.config.Replication); err != nil {
352
+ return err
353
+ }
354
+
355
+ if err := h.parser.ParseClass(updated); err != nil {
356
+ return err
357
+ }
358
+
359
+ // ideally, these calls would be encapsulated in ParseClass but ParseClass is
360
+ // used in many different areas of the codebase that may cause BC issues with the
361
+ // new validation logic. Issue ref: gh-5860
362
+ // As our testing becomes more comprehensive, we can move these calls into ParseClass
363
+ if err := h.parser.parseModuleConfig(updated); err != nil {
364
+ return fmt.Errorf("parse module config: %w", err)
365
+ }
366
+
367
+ if err := h.parser.parseVectorConfig(updated); err != nil {
368
+ return fmt.Errorf("parse vector config: %w", err)
369
+ }
370
+
371
+ if err := h.validateVectorSettings(updated); err != nil {
372
+ return err
373
+ }
374
+
375
+ if initial := h.schemaReader.ReadOnlyClass(className); initial != nil {
376
+ if err := validateImmutableFields(initial, updated); err != nil {
377
+ return err
378
+ }
379
+ }
380
+ // A nil sharding state means that the sharding state will not be updated.
381
+ _, err := h.schemaManager.UpdateClass(ctx, updated, nil)
382
+ return err
383
+ }
384
+
385
+ func (m *Handler) setNewClassDefaults(class *models.Class, globalCfg replication.GlobalConfig) error {
386
+ if class.ShardingConfig != nil && schema.MultiTenancyEnabled(class) {
387
+ return fmt.Errorf("cannot have both shardingConfig and multiTenancyConfig")
388
+ } else if class.MultiTenancyConfig == nil {
389
+ class.MultiTenancyConfig = &models.MultiTenancyConfig{}
390
+ } else if class.MultiTenancyConfig.Enabled {
391
+ class.ShardingConfig = shardingcfg.Config{DesiredCount: 0} // tenant shards will be created dynamically
392
+ }
393
+
394
+ if err := m.setClassDefaults(class, globalCfg); err != nil {
395
+ return err
396
+ }
397
+
398
+ if class.ReplicationConfig == nil {
399
+ class.ReplicationConfig = &models.ReplicationConfig{
400
+ Factor: int64(m.config.Replication.MinimumFactor),
401
+ DeletionStrategy: models.ReplicationConfigDeletionStrategyNoAutomatedResolution,
402
+ }
403
+ return nil
404
+ }
405
+
406
+ if class.ReplicationConfig.DeletionStrategy == "" {
407
+ class.ReplicationConfig.DeletionStrategy = models.ReplicationConfigDeletionStrategyNoAutomatedResolution
408
+ }
409
+ return nil
410
+ }
411
+
412
+ func (h *Handler) setClassDefaults(class *models.Class, globalCfg replication.GlobalConfig) error {
413
+ // set legacy vector index defaults only when:
414
+ // - no target vectors are configured
415
+ // - OR, there are target vectors configured AND there is a legacy vector configured
416
+ if !hasTargetVectors(class) || modelsext.ClassHasLegacyVectorIndex(class) {
417
+ if class.Vectorizer == "" {
418
+ class.Vectorizer = h.config.DefaultVectorizerModule
419
+ }
420
+
421
+ if class.VectorIndexType == "" {
422
+ class.VectorIndexType = vectorindex.DefaultVectorIndexType
423
+ }
424
+
425
+ if h.config.DefaultVectorDistanceMetric != "" {
426
+ if class.VectorIndexConfig == nil {
427
+ class.VectorIndexConfig = map[string]interface{}{"distance": h.config.DefaultVectorDistanceMetric}
428
+ } else if vIdxCfgMap, ok := class.VectorIndexConfig.(map[string]interface{}); ok && vIdxCfgMap["distance"] == nil {
429
+ class.VectorIndexConfig.(map[string]interface{})["distance"] = h.config.DefaultVectorDistanceMetric
430
+ }
431
+ }
432
+ }
433
+
434
+ setInvertedConfigDefaults(class)
435
+ for _, prop := range class.Properties {
436
+ setPropertyDefaults(prop)
437
+ }
438
+
439
+ if class.ReplicationConfig == nil {
440
+ class.ReplicationConfig = &models.ReplicationConfig{Factor: int64(globalCfg.MinimumFactor)}
441
+ }
442
+
443
+ if class.ReplicationConfig.Factor > 0 && class.ReplicationConfig.Factor < int64(globalCfg.MinimumFactor) {
444
+ return fmt.Errorf("invalid replication factor: setup requires a minimum replication factor of %d: got %d",
445
+ globalCfg.MinimumFactor, class.ReplicationConfig.Factor)
446
+ }
447
+
448
+ if class.ReplicationConfig.Factor < 1 {
449
+ class.ReplicationConfig.Factor = int64(globalCfg.MinimumFactor)
450
+ }
451
+
452
+ h.moduleConfig.SetClassDefaults(class)
453
+ return nil
454
+ }
455
+
456
+ func setPropertyDefaults(props ...*models.Property) {
457
+ setPropertyDefaultTokenization(props...)
458
+ setPropertyDefaultIndexing(props...)
459
+ for _, prop := range props {
460
+ setNestedPropertiesDefaults(prop.NestedProperties)
461
+ }
462
+ }
463
+
464
+ func setPropertyDefaultTokenization(props ...*models.Property) {
465
+ for _, prop := range props {
466
+ switch dataType, _ := schema.AsPrimitive(prop.DataType); dataType {
467
+ case schema.DataTypeString, schema.DataTypeStringArray:
468
+ // deprecated as of v1.19, default tokenization was word
469
+ // which will be migrated to text+whitespace
470
+ if prop.Tokenization == "" {
471
+ prop.Tokenization = models.PropertyTokenizationWord
472
+ }
473
+ case schema.DataTypeText, schema.DataTypeTextArray:
474
+ if prop.Tokenization == "" {
475
+ if os.Getenv("DEFAULT_TOKENIZATION") != "" {
476
+ prop.Tokenization = os.Getenv("DEFAULT_TOKENIZATION")
477
+ } else {
478
+ prop.Tokenization = models.PropertyTokenizationWord
479
+ }
480
+ }
481
+ default:
482
+ // tokenization not supported for other data types
483
+ }
484
+ }
485
+ }
486
+
487
+ func setPropertyDefaultIndexing(props ...*models.Property) {
488
+ for _, prop := range props {
489
+ // if IndexInverted is set but IndexFilterable and IndexSearchable are not
490
+ // migrate IndexInverted later.
491
+ if prop.IndexInverted != nil &&
492
+ prop.IndexFilterable == nil &&
493
+ prop.IndexSearchable == nil &&
494
+ prop.IndexRangeFilters == nil {
495
+ continue
496
+ }
497
+
498
+ vTrue := true
499
+ vFalse := false
500
+ if prop.IndexFilterable == nil {
501
+ prop.IndexFilterable = &vTrue
502
+ }
503
+ if prop.IndexSearchable == nil {
504
+ switch dataType, _ := schema.AsPrimitive(prop.DataType); dataType {
505
+ case schema.DataTypeString, schema.DataTypeStringArray:
506
+ // string/string[] are migrated to text/text[] later,
507
+ // at this point they are still valid data types, therefore should be handled here
508
+ prop.IndexSearchable = &vTrue
509
+ case schema.DataTypeText, schema.DataTypeTextArray:
510
+ prop.IndexSearchable = &vTrue
511
+ default:
512
+ prop.IndexSearchable = &vFalse
513
+ }
514
+ }
515
+ if prop.IndexRangeFilters == nil {
516
+ prop.IndexRangeFilters = &vFalse
517
+ }
518
+ }
519
+ }
520
+
521
+ func setNestedPropertiesDefaults(properties []*models.NestedProperty) {
522
+ for _, property := range properties {
523
+ primitiveDataType, isPrimitive := schema.AsPrimitive(property.DataType)
524
+ nestedDataType, isNested := schema.AsNested(property.DataType)
525
+
526
+ setNestedPropertyDefaultTokenization(property, primitiveDataType, nestedDataType, isPrimitive, isNested)
527
+ setNestedPropertyDefaultIndexing(property, primitiveDataType, nestedDataType, isPrimitive, isNested)
528
+
529
+ if isNested {
530
+ setNestedPropertiesDefaults(property.NestedProperties)
531
+ }
532
+ }
533
+ }
534
+
535
+ func setNestedPropertyDefaultTokenization(property *models.NestedProperty,
536
+ primitiveDataType, nestedDataType schema.DataType,
537
+ isPrimitive, isNested bool,
538
+ ) {
539
+ if property.Tokenization == "" && isPrimitive {
540
+ switch primitiveDataType {
541
+ case schema.DataTypeText, schema.DataTypeTextArray:
542
+ property.Tokenization = models.NestedPropertyTokenizationWord
543
+ default:
544
+ // do nothing
545
+ }
546
+ }
547
+ }
548
+
549
+ func setNestedPropertyDefaultIndexing(property *models.NestedProperty,
550
+ primitiveDataType, nestedDataType schema.DataType,
551
+ isPrimitive, isNested bool,
552
+ ) {
553
+ vTrue := true
554
+ vFalse := false
555
+
556
+ if property.IndexFilterable == nil {
557
+ property.IndexFilterable = &vTrue
558
+
559
+ if isPrimitive && primitiveDataType == schema.DataTypeBlob {
560
+ property.IndexFilterable = &vFalse
561
+ }
562
+ }
563
+
564
+ if property.IndexSearchable == nil {
565
+ property.IndexSearchable = &vFalse
566
+
567
+ if isPrimitive {
568
+ switch primitiveDataType {
569
+ case schema.DataTypeText, schema.DataTypeTextArray:
570
+ property.IndexSearchable = &vTrue
571
+ default:
572
+ // do nothing
573
+ }
574
+ }
575
+ }
576
+
577
+ if property.IndexRangeFilters == nil {
578
+ property.IndexRangeFilters = &vFalse
579
+ }
580
+ }
581
+
582
+ func (h *Handler) migrateClassSettings(class *models.Class) {
583
+ for _, prop := range class.Properties {
584
+ migratePropertySettings(prop)
585
+ }
586
+ }
587
+
588
+ func migratePropertySettings(props ...*models.Property) {
589
+ migratePropertyDataTypeAndTokenization(props...)
590
+ migratePropertyIndexInverted(props...)
591
+ }
592
+
593
+ // as of v1.19 DataTypeString and DataTypeStringArray are deprecated
594
+ // here both are changed to Text/TextArray
595
+ // and proper, backward compatible tokenization
596
+ func migratePropertyDataTypeAndTokenization(props ...*models.Property) {
597
+ for _, prop := range props {
598
+ switch dataType, _ := schema.AsPrimitive(prop.DataType); dataType {
599
+ case schema.DataTypeString:
600
+ prop.DataType = schema.DataTypeText.PropString()
601
+ case schema.DataTypeStringArray:
602
+ prop.DataType = schema.DataTypeTextArray.PropString()
603
+ default:
604
+ // other types need no migration and do not support tokenization
605
+ continue
606
+ }
607
+
608
+ switch prop.Tokenization {
609
+ case models.PropertyTokenizationWord:
610
+ prop.Tokenization = models.PropertyTokenizationWhitespace
611
+ case models.PropertyTokenizationField:
612
+ // stays field
613
+ }
614
+ }
615
+ }
616
+
617
+ // as of v1.19 IndexInverted is deprecated and replaced with
618
+ // IndexFilterable (set inverted index)
619
+ // and IndexSearchable (map inverted index with term frequencies;
620
+ // therefore applicable only to text/text[] data types)
621
+ func migratePropertyIndexInverted(props ...*models.Property) {
622
+ vFalse := false
623
+
624
+ for _, prop := range props {
625
+ // if none of new options is set, use inverted settings
626
+ if prop.IndexInverted != nil &&
627
+ prop.IndexFilterable == nil &&
628
+ prop.IndexSearchable == nil &&
629
+ prop.IndexRangeFilters == nil {
630
+ prop.IndexFilterable = prop.IndexInverted
631
+ switch dataType, _ := schema.AsPrimitive(prop.DataType); dataType {
632
+ // string/string[] are already migrated into text/text[], can be skipped here
633
+ case schema.DataTypeText, schema.DataTypeTextArray:
634
+ prop.IndexSearchable = prop.IndexInverted
635
+ default:
636
+ prop.IndexSearchable = &vFalse
637
+ }
638
+ prop.IndexRangeFilters = &vFalse
639
+ }
640
+ // new options have precedence so inverted can be reset
641
+ prop.IndexInverted = nil
642
+ }
643
+ }
644
+
645
+ func (h *Handler) validateProperty(
646
+ class *models.Class, existingPropertyNames map[string]bool,
647
+ relaxCrossRefValidation bool, classGetterWithAuth func(string) (*models.Class, error), props ...*models.Property,
648
+ ) error {
649
+ for _, property := range props {
650
+ if _, err := schema.ValidatePropertyName(property.Name); err != nil {
651
+ return err
652
+ }
653
+
654
+ if err := schema.ValidateReservedPropertyName(property.Name); err != nil {
655
+ return err
656
+ }
657
+
658
+ if existingPropertyNames[strings.ToLower(property.Name)] {
659
+ return fmt.Errorf("class %q: conflict for property %q: already in use or provided multiple times", class.Class, property.Name)
660
+ }
661
+
662
+ // Validate data type of property.
663
+ propertyDataType, err := schema.FindPropertyDataTypeWithRefsAndAuth(classGetterWithAuth, property.DataType,
664
+ relaxCrossRefValidation, schema.ClassName(class.Class))
665
+ if err != nil {
666
+ return fmt.Errorf("property '%s': invalid dataType: %v: %w", property.Name, property.DataType, err)
667
+ }
668
+
669
+ if propertyDataType.IsNested() {
670
+ if err := validateNestedProperties(property.NestedProperties, property.Name); err != nil {
671
+ return err
672
+ }
673
+ } else {
674
+ if len(property.NestedProperties) > 0 {
675
+ return fmt.Errorf("property '%s': nestedProperties not allowed for data types other than object/object[]",
676
+ property.Name)
677
+ }
678
+ }
679
+
680
+ if err := h.validatePropertyTokenization(property.Tokenization, propertyDataType); err != nil {
681
+ return err
682
+ }
683
+
684
+ if err := h.validatePropertyIndexing(property); err != nil {
685
+ return err
686
+ }
687
+
688
+ if err := h.validatePropModuleConfig(class, property); err != nil {
689
+ return err
690
+ }
691
+ }
692
+
693
+ return nil
694
+ }
695
+
696
+ func setInvertedConfigDefaults(class *models.Class) {
697
+ if class.InvertedIndexConfig == nil {
698
+ class.InvertedIndexConfig = &models.InvertedIndexConfig{
699
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
700
+ }
701
+ }
702
+
703
+ if class.InvertedIndexConfig.CleanupIntervalSeconds == 0 {
704
+ class.InvertedIndexConfig.CleanupIntervalSeconds = config.DefaultCleanupIntervalSeconds
705
+ }
706
+
707
+ if class.InvertedIndexConfig.Bm25 == nil {
708
+ class.InvertedIndexConfig.Bm25 = &models.BM25Config{
709
+ K1: config.DefaultBM25k1,
710
+ B: config.DefaultBM25b,
711
+ }
712
+ }
713
+
714
+ if class.InvertedIndexConfig.Stopwords == nil {
715
+ class.InvertedIndexConfig.Stopwords = &models.StopwordConfig{
716
+ Preset: stopwords.EnglishPreset,
717
+ }
718
+ }
719
+ }
720
+
721
+ func (h *Handler) validateCanAddClass(ctx context.Context, class *models.Class, classGetterWithAuth func(string) (*models.Class, error),
722
+ relaxCrossRefValidation bool,
723
+ ) error {
724
+ if modelsext.ClassHasLegacyVectorIndex(class) && len(class.VectorConfig) > 0 {
725
+ return fmt.Errorf("creating a class with both a class level vector index and named vectors is forbidden")
726
+ }
727
+
728
+ return h.validateClassInvariants(ctx, class, classGetterWithAuth, relaxCrossRefValidation)
729
+ }
730
+
731
+ func (h *Handler) validateClassInvariants(
732
+ ctx context.Context, class *models.Class, classGetterWithAuth func(string) (*models.Class, error),
733
+ relaxCrossRefValidation bool,
734
+ ) error {
735
+ if _, err := schema.ValidateClassName(class.Class); err != nil {
736
+ return err
737
+ }
738
+
739
+ existingPropertyNames := map[string]bool{}
740
+ for _, property := range class.Properties {
741
+ if err := h.validateProperty(class, existingPropertyNames, relaxCrossRefValidation, classGetterWithAuth, property); err != nil {
742
+ return err
743
+ }
744
+ existingPropertyNames[strings.ToLower(property.Name)] = true
745
+ }
746
+
747
+ if err := h.validateVectorSettings(class); err != nil {
748
+ return err
749
+ }
750
+
751
+ if err := h.moduleConfig.ValidateClass(ctx, class); err != nil {
752
+ return err
753
+ }
754
+
755
+ if err := validateMT(class); err != nil {
756
+ return err
757
+ }
758
+
759
+ if err := replica.ValidateConfig(class, h.config.Replication); err != nil {
760
+ return err
761
+ }
762
+
763
+ // all is fine!
764
+ return nil
765
+ }
766
+
767
+ func (h *Handler) validatePropertyTokenization(tokenization string, propertyDataType schema.PropertyDataType) error {
768
+ if propertyDataType.IsPrimitive() {
769
+ primitiveDataType := propertyDataType.AsPrimitive()
770
+
771
+ switch primitiveDataType {
772
+ case schema.DataTypeString, schema.DataTypeStringArray:
773
+ // deprecated as of v1.19, will be migrated to DataTypeText/DataTypeTextArray
774
+ switch tokenization {
775
+ case models.PropertyTokenizationField, models.PropertyTokenizationWord:
776
+ return nil
777
+ }
778
+ case schema.DataTypeText, schema.DataTypeTextArray:
779
+ switch tokenization {
780
+ case models.PropertyTokenizationField, models.PropertyTokenizationWord,
781
+ models.PropertyTokenizationWhitespace, models.PropertyTokenizationLowercase,
782
+ models.PropertyTokenizationTrigram:
783
+ return nil
784
+ case models.PropertyTokenizationGse:
785
+ if !entcfg.Enabled(os.Getenv("USE_GSE")) && !entcfg.Enabled(os.Getenv("ENABLE_TOKENIZER_GSE")) {
786
+ return fmt.Errorf("the GSE tokenizer is not enabled; set 'ENABLE_TOKENIZER_GSE' to 'true' to enable")
787
+ }
788
+ return nil
789
+ case models.PropertyTokenizationKagomeKr:
790
+ if !entcfg.Enabled(os.Getenv("ENABLE_TOKENIZER_KAGOME_KR")) {
791
+ return fmt.Errorf("the Korean tokenizer is not enabled; set 'ENABLE_TOKENIZER_KAGOME_KR' to 'true' to enable")
792
+ }
793
+ return nil
794
+ case models.PropertyTokenizationKagomeJa:
795
+ if !entcfg.Enabled(os.Getenv("ENABLE_TOKENIZER_KAGOME_JA")) {
796
+ return fmt.Errorf("the Japanese tokenizer is not enabled; set 'ENABLE_TOKENIZER_KAGOME_JA' to 'true' to enable")
797
+ }
798
+ return nil
799
+ }
800
+ default:
801
+ if tokenization == "" {
802
+ return nil
803
+ }
804
+ return fmt.Errorf("tokenization is not allowed for data type '%s'", primitiveDataType)
805
+ }
806
+ return fmt.Errorf("tokenization '%s' is not allowed for data type '%s'", tokenization, primitiveDataType)
807
+ }
808
+
809
+ if tokenization == "" {
810
+ return nil
811
+ }
812
+
813
+ if propertyDataType.IsNested() {
814
+ return fmt.Errorf("tokenization is not allowed for object/object[] data types")
815
+ }
816
+ return fmt.Errorf("tokenization is not allowed for reference data type")
817
+ }
818
+
819
+ func (h *Handler) validatePropertyIndexing(prop *models.Property) error {
820
+ if prop.IndexInverted != nil {
821
+ if prop.IndexFilterable != nil || prop.IndexSearchable != nil || prop.IndexRangeFilters != nil {
822
+ return fmt.Errorf("`indexInverted` is deprecated and can not be set together with `indexFilterable`, " + "`indexSearchable` or `indexRangeFilters`")
823
+ }
824
+ }
825
+
826
+ dataType, _ := schema.AsPrimitive(prop.DataType)
827
+ if prop.IndexSearchable != nil {
828
+ switch dataType {
829
+ case schema.DataTypeString, schema.DataTypeStringArray:
830
+ // string/string[] are migrated to text/text[] later,
831
+ // at this point they are still valid data types, therefore should be handled here.
832
+ // true or false allowed
833
+ case schema.DataTypeText, schema.DataTypeTextArray:
834
+ // true or false allowed
835
+ default:
836
+ if *prop.IndexSearchable {
837
+ return fmt.Errorf("`indexSearchable` is allowed only for text/text[] data types. " +
838
+ "For other data types set false or leave empty")
839
+ }
840
+ }
841
+ }
842
+ if prop.IndexRangeFilters != nil {
843
+ switch dataType {
844
+ case schema.DataTypeNumber, schema.DataTypeInt, schema.DataTypeDate:
845
+ // true or false allowed
846
+ case schema.DataTypeNumberArray, schema.DataTypeIntArray, schema.DataTypeDateArray:
847
+ // not supported (yet?)
848
+ fallthrough
849
+ default:
850
+ if *prop.IndexRangeFilters {
851
+ return fmt.Errorf("`indexRangeFilters` is allowed only for number/int/date data types. " +
852
+ "For other data types set false or leave empty")
853
+ }
854
+ }
855
+ }
856
+
857
+ return nil
858
+ }
859
+
860
+ func (h *Handler) validateVectorSettings(class *models.Class) error {
861
+ if modelsext.ClassHasLegacyVectorIndex(class) {
862
+ if err := h.validateVectorIndexType(class.VectorIndexType); err != nil {
863
+ return err
864
+ }
865
+
866
+ if err := h.validateVectorizer(class.Vectorizer); err != nil {
867
+ return err
868
+ }
869
+
870
+ if asMap, ok := class.VectorIndexConfig.(map[string]interface{}); ok && len(asMap) > 0 {
871
+ parsed, err := h.parser.parseGivenVectorIndexConfig(class.VectorIndexType, class.VectorIndexConfig, h.parser.modules.IsMultiVector(class.Vectorizer), h.config.DefaultQuantization)
872
+ if err != nil {
873
+ return fmt.Errorf("class.VectorIndexConfig can not parse: %w", err)
874
+ }
875
+ if parsed.IsMultiVector() {
876
+ return errors.New("class.VectorIndexConfig multi vector type index type is only configurable using named vectors")
877
+ }
878
+ }
879
+ }
880
+
881
+ for name, cfg := range class.VectorConfig {
882
+ // check only if vectorizer correctly configured (map with single key being vectorizer name)
883
+ // other cases are handled in module config validation
884
+ if vm, ok := cfg.Vectorizer.(map[string]interface{}); ok && len(vm) == 1 {
885
+ for vectorizer := range vm {
886
+ if err := h.validateVectorizer(vectorizer); err != nil {
887
+ return fmt.Errorf("target vector %q: %w", name, err)
888
+ }
889
+ }
890
+ }
891
+ if err := h.validateVectorIndexType(cfg.VectorIndexType); err != nil {
892
+ return fmt.Errorf("target vector %q: %w", name, err)
893
+ }
894
+ }
895
+ return nil
896
+ }
897
+
898
+ func (h *Handler) validateVectorizer(vectorizer string) error {
899
+ if vectorizer == config.VectorizerModuleNone {
900
+ return nil
901
+ }
902
+
903
+ if err := h.vectorizerValidator.ValidateVectorizer(vectorizer); err != nil {
904
+ return errors.Wrap(err, "vectorizer")
905
+ }
906
+
907
+ return nil
908
+ }
909
+
910
+ func (h *Handler) validateVectorIndexType(vectorIndexType string) error {
911
+ switch vectorIndexType {
912
+ case vectorindex.VectorIndexTypeHNSW, vectorindex.VectorIndexTypeFLAT:
913
+ return nil
914
+ case vectorindex.VectorIndexTypeDYNAMIC:
915
+ if !h.asyncIndexingEnabled {
916
+ return fmt.Errorf("the dynamic index can only be created under async indexing environment (ASYNC_INDEXING=true)")
917
+ }
918
+ return nil
919
+ default:
920
+ return errors.Errorf("unrecognized or unsupported vectorIndexType %q",
921
+ vectorIndexType)
922
+ }
923
+ }
924
+
925
+ func validateMT(class *models.Class) error {
926
+ enabled := schema.MultiTenancyEnabled(class)
927
+ if !enabled && schema.AutoTenantCreationEnabled(class) {
928
+ return fmt.Errorf("can't enable autoTenantCreation on a non-multi-tenant class")
929
+ }
930
+
931
+ if !enabled && schema.AutoTenantActivationEnabled(class) {
932
+ return fmt.Errorf("can't enable autoTenantActivation on a non-multi-tenant class")
933
+ }
934
+
935
+ return nil
936
+ }
937
+
938
+ // validateUpdatingMT validates toggling MT and returns whether mt is enabled
939
+ func validateUpdatingMT(current, update *models.Class) (enabled bool, err error) {
940
+ enabled = schema.MultiTenancyEnabled(current)
941
+ if schema.MultiTenancyEnabled(update) != enabled {
942
+ if enabled {
943
+ err = fmt.Errorf("disabling multi-tenancy for an existing class is not supported")
944
+ } else {
945
+ err = fmt.Errorf("enabling multi-tenancy for an existing class is not supported")
946
+ }
947
+ } else {
948
+ err = validateMT(update)
949
+ }
950
+
951
+ return
952
+ }
953
+
954
+ func validateImmutableFields(initial, updated *models.Class) error {
955
+ immutableFields := []immutableText{
956
+ {
957
+ name: "class name",
958
+ accessor: func(c *models.Class) string { return c.Class },
959
+ },
960
+ }
961
+
962
+ if err := validateImmutableTextFields(initial, updated, immutableFields...); err != nil {
963
+ return err
964
+ }
965
+
966
+ for k, v := range updated.VectorConfig {
967
+ if _, ok := initial.VectorConfig[k]; !ok {
968
+ continue
969
+ }
970
+
971
+ if !reflect.DeepEqual(initial.VectorConfig[k].Vectorizer, v.Vectorizer) {
972
+ return fmt.Errorf("vectorizer config of vector %q is immutable", k)
973
+ }
974
+ }
975
+
976
+ return nil
977
+ }
978
+
979
+ type immutableText struct {
980
+ accessor func(c *models.Class) string
981
+ name string
982
+ }
983
+
984
+ func validateImmutableTextFields(previous, next *models.Class,
985
+ immutables ...immutableText,
986
+ ) error {
987
+ for _, immutable := range immutables {
988
+ oldField := immutable.accessor(previous)
989
+ newField := immutable.accessor(next)
990
+ if oldField != newField {
991
+ return errors.Errorf("%s is immutable: attempted change from %q to %q",
992
+ immutable.name, oldField, newField)
993
+ }
994
+ }
995
+ return nil
996
+ }
997
+
998
+ func validateLegacyVectorIndexConfigImmutableFields(initial, updated *models.Class) error {
999
+ return validateImmutableTextFields(initial, updated, []immutableText{
1000
+ {
1001
+ name: "vectorizer",
1002
+ accessor: func(c *models.Class) string { return c.Vectorizer },
1003
+ },
1004
+ {
1005
+ name: "vector index type",
1006
+ accessor: func(c *models.Class) string { return c.VectorIndexType },
1007
+ },
1008
+ }...)
1009
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/class_test.go ADDED
@@ -0,0 +1,2338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "encoding/json"
17
+ "fmt"
18
+ "strings"
19
+ "testing"
20
+
21
+ "github.com/pkg/errors"
22
+ "github.com/stretchr/testify/assert"
23
+ "github.com/stretchr/testify/mock"
24
+ "github.com/stretchr/testify/require"
25
+ "github.com/weaviate/weaviate/entities/modelsext"
26
+ "github.com/weaviate/weaviate/entities/tokenizer"
27
+
28
+ "github.com/weaviate/weaviate/adapters/repos/db/inverted/stopwords"
29
+ "github.com/weaviate/weaviate/entities/backup"
30
+ "github.com/weaviate/weaviate/entities/models"
31
+ "github.com/weaviate/weaviate/entities/replication"
32
+ "github.com/weaviate/weaviate/entities/schema"
33
+ "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
34
+ "github.com/weaviate/weaviate/usecases/cluster/mocks"
35
+ "github.com/weaviate/weaviate/usecases/config"
36
+ "github.com/weaviate/weaviate/usecases/config/runtime"
37
+ "github.com/weaviate/weaviate/usecases/sharding"
38
+ shardingConfig "github.com/weaviate/weaviate/usecases/sharding/config"
39
+ )
40
+
41
+ func Test_AddClass(t *testing.T) {
42
+ t.Parallel()
43
+ ctx := context.Background()
44
+
45
+ t.Run("happy path", func(t *testing.T) {
46
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
47
+
48
+ class := &models.Class{
49
+ Class: "NewClass",
50
+ Properties: []*models.Property{
51
+ {DataType: []string{"text"}, Name: "textProp"},
52
+ {DataType: []string{"int"}, Name: "intProp"},
53
+ },
54
+ Vectorizer: "none",
55
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
56
+ }
57
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
58
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
59
+
60
+ _, _, err := handler.AddClass(ctx, nil, class)
61
+ assert.Nil(t, err)
62
+
63
+ fakeSchemaManager.AssertExpectations(t)
64
+ })
65
+
66
+ t.Run("happy path, named vectors", func(t *testing.T) {
67
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
68
+
69
+ class := &models.Class{
70
+ Class: "NewClass",
71
+ Properties: []*models.Property{
72
+ {DataType: []string{"text"}, Name: "textProp"},
73
+ },
74
+ VectorConfig: map[string]models.VectorConfig{
75
+ "vec1": {
76
+ VectorIndexType: hnswT,
77
+ Vectorizer: map[string]interface{}{
78
+ "text2vec-contextionary": map[string]interface{}{},
79
+ },
80
+ },
81
+ },
82
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
83
+ }
84
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
85
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
86
+
87
+ _, _, err := handler.AddClass(ctx, nil, class)
88
+ require.NoError(t, err)
89
+
90
+ fakeSchemaManager.AssertExpectations(t)
91
+ })
92
+
93
+ t.Run("mixed vector schema creation", func(t *testing.T) {
94
+ handler, _ := newTestHandler(t, &fakeDB{})
95
+
96
+ class := &models.Class{
97
+ Class: "NewClass",
98
+ Properties: []*models.Property{
99
+ {DataType: []string{"text"}, Name: "textProp"},
100
+ },
101
+ Vectorizer: "text2vec-contextionary",
102
+ VectorIndexType: hnswT,
103
+ VectorConfig: map[string]models.VectorConfig{
104
+ "vec1": {
105
+ VectorIndexType: hnswT,
106
+ Vectorizer: map[string]interface{}{
107
+ "text2vec-contextionary": map[string]interface{}{},
108
+ },
109
+ },
110
+ },
111
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
112
+ }
113
+
114
+ _, _, err := handler.AddClass(ctx, nil, class)
115
+ require.ErrorContains(t, err, "creating a class with both a class level vector index and named vectors is forbidden")
116
+ })
117
+
118
+ t.Run("with empty class name", func(t *testing.T) {
119
+ handler, _ := newTestHandler(t, &fakeDB{})
120
+ class := models.Class{ReplicationConfig: &models.ReplicationConfig{Factor: 1}}
121
+ _, _, err := handler.AddClass(ctx, nil, &class)
122
+ assert.EqualError(t, err, "'' is not a valid class name")
123
+ })
124
+
125
+ t.Run("with reserved class name", func(t *testing.T) {
126
+ handler, _ := newTestHandler(t, &fakeDB{})
127
+ class := models.Class{Class: config.DefaultRaftDir, ReplicationConfig: &models.ReplicationConfig{Factor: 1}}
128
+ _, _, err := handler.AddClass(ctx, nil, &class)
129
+ assert.EqualError(t, err, fmt.Sprintf("parse class name: class name `%s` is reserved", config.DefaultRaftDir))
130
+
131
+ class = models.Class{Class: "rAFT", ReplicationConfig: &models.ReplicationConfig{Factor: 1}}
132
+ _, _, err = handler.AddClass(ctx, nil, &class)
133
+ assert.EqualError(t, err, fmt.Sprintf("parse class name: class name `%s` is reserved", config.DefaultRaftDir))
134
+
135
+ class = models.Class{Class: "rAfT", ReplicationConfig: &models.ReplicationConfig{Factor: 1}}
136
+ _, _, err = handler.AddClass(ctx, nil, &class)
137
+ assert.EqualError(t, err, fmt.Sprintf("parse class name: class name `%s` is reserved", config.DefaultRaftDir))
138
+
139
+ class = models.Class{Class: "RaFT", ReplicationConfig: &models.ReplicationConfig{Factor: 1}}
140
+ _, _, err = handler.AddClass(ctx, nil, &class)
141
+ assert.EqualError(t, err, fmt.Sprintf("parse class name: class name `%s` is reserved", config.DefaultRaftDir))
142
+
143
+ class = models.Class{Class: "RAFT", ReplicationConfig: &models.ReplicationConfig{Factor: 1}}
144
+ _, _, err = handler.AddClass(ctx, nil, &class)
145
+ assert.EqualError(t, err, fmt.Sprintf("parse class name: class name `%s` is reserved", config.DefaultRaftDir))
146
+ })
147
+
148
+ t.Run("with default params", func(t *testing.T) {
149
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
150
+ class := models.Class{
151
+ Class: "NewClass",
152
+ Vectorizer: "none",
153
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
154
+ }
155
+
156
+ expectedBM25Config := &models.BM25Config{
157
+ K1: config.DefaultBM25k1,
158
+ B: config.DefaultBM25b,
159
+ }
160
+ expectedStopwordConfig := &models.StopwordConfig{
161
+ Preset: stopwords.EnglishPreset,
162
+ }
163
+ expectedClass := &class
164
+ expectedClass.InvertedIndexConfig = &models.InvertedIndexConfig{
165
+ Bm25: expectedBM25Config,
166
+ CleanupIntervalSeconds: 60,
167
+ Stopwords: expectedStopwordConfig,
168
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
169
+ }
170
+ fakeSchemaManager.On("AddClass", expectedClass, mock.Anything).Return(nil)
171
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
172
+ _, _, err := handler.AddClass(ctx, nil, &class)
173
+ require.Nil(t, err)
174
+ fakeSchemaManager.AssertExpectations(t)
175
+ })
176
+
177
+ t.Run("with customized params", func(t *testing.T) {
178
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
179
+ expectedBM25Config := &models.BM25Config{
180
+ K1: 1.88,
181
+ B: 0.44,
182
+ }
183
+ class := models.Class{
184
+ Class: "NewClass",
185
+ InvertedIndexConfig: &models.InvertedIndexConfig{
186
+ Bm25: expectedBM25Config,
187
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
188
+ },
189
+ Vectorizer: "none",
190
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
191
+ }
192
+
193
+ expectedStopwordConfig := &models.StopwordConfig{
194
+ Preset: "none",
195
+ Additions: []string{"monkey", "zebra", "octopus"},
196
+ Removals: []string{"are"},
197
+ }
198
+ expectedClass := &class
199
+ expectedClass.InvertedIndexConfig = &models.InvertedIndexConfig{
200
+ Bm25: expectedBM25Config,
201
+ CleanupIntervalSeconds: 60,
202
+ Stopwords: expectedStopwordConfig,
203
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
204
+ }
205
+ fakeSchemaManager.On("AddClass", expectedClass, mock.Anything).Return(nil)
206
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
207
+ _, _, err := handler.AddClass(ctx, nil, &class)
208
+ require.Nil(t, err)
209
+ fakeSchemaManager.AssertExpectations(t)
210
+ })
211
+
212
+ t.Run("with tokenizations", func(t *testing.T) {
213
+ type testCase struct {
214
+ propName string
215
+ dataType []string
216
+ tokenization string
217
+ expectedErrMsg string
218
+ callReadOnly bool
219
+ }
220
+
221
+ propName := func(dataType schema.DataType, tokenization string) string {
222
+ dtStr := strings.ReplaceAll(string(dataType), "[]", "Array")
223
+ tStr := "empty"
224
+ if tokenization != "" {
225
+ tStr = tokenization
226
+ }
227
+ return fmt.Sprintf("%s_%s", dtStr, tStr)
228
+ }
229
+
230
+ // These classes are necessary for tests using references
231
+ classes := map[string]models.Class{
232
+ "SomeClass": {Class: "SomeClass", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
233
+ "SomeOtherClass": {Class: "SomeOtherClass", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
234
+ "YetAnotherClass": {Class: "YetAnotherClass", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
235
+ }
236
+
237
+ runTestCases := func(t *testing.T, testCases []testCase) {
238
+ for i, tc := range testCases {
239
+ t.Run(tc.propName, func(t *testing.T) {
240
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
241
+
242
+ class := &models.Class{
243
+ Class: fmt.Sprintf("NewClass_%d", i),
244
+ Properties: []*models.Property{
245
+ {
246
+ Name: tc.propName,
247
+ DataType: tc.dataType,
248
+ Tokenization: tc.tokenization,
249
+ },
250
+ },
251
+ Vectorizer: "none",
252
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
253
+ }
254
+ classes[class.Class] = *class
255
+
256
+ if tc.callReadOnly {
257
+ call := fakeSchemaManager.On("ReadOnlyClass", mock.Anything, mock.Anything).Return(nil)
258
+ call.RunFn = func(a mock.Arguments) {
259
+ existedClass := classes[a.Get(0).(string)]
260
+ call.ReturnArguments = mock.Arguments{&existedClass}
261
+ }
262
+ }
263
+
264
+ // fakeSchemaManager.On("ReadOnlyClass", mock.Anything).Return(&models.Class{Class: classes[tc.dataType[0]].Class, Vectorizer: classes[tc.dataType[0]].Vectorizer})
265
+ if tc.expectedErrMsg == "" {
266
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
267
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
268
+ }
269
+
270
+ _, _, err := handler.AddClass(context.Background(), nil, class)
271
+ if tc.expectedErrMsg == "" {
272
+ require.Nil(t, err)
273
+ } else {
274
+ require.EqualError(t, err, tc.expectedErrMsg)
275
+ }
276
+ fakeSchemaManager.AssertExpectations(t)
277
+ })
278
+ }
279
+ }
280
+
281
+ t.Run("text/textArray and all tokenizations", func(t *testing.T) {
282
+ var testCases []testCase
283
+ for _, dataType := range []schema.DataType{
284
+ schema.DataTypeText, schema.DataTypeTextArray,
285
+ } {
286
+ for _, tokenization := range append(tokenizer.Tokenizations, "") {
287
+ testCases = append(testCases, testCase{
288
+ propName: propName(dataType, tokenization),
289
+ dataType: dataType.PropString(),
290
+ tokenization: tokenization,
291
+ expectedErrMsg: "",
292
+ })
293
+ }
294
+
295
+ tokenization := "non_existing"
296
+ testCases = append(testCases, testCase{
297
+ propName: propName(dataType, tokenization),
298
+ dataType: dataType.PropString(),
299
+ tokenization: tokenization,
300
+ expectedErrMsg: fmt.Sprintf("tokenization '%s' is not allowed for data type '%s'", tokenization, dataType),
301
+ })
302
+ }
303
+
304
+ runTestCases(t, testCases)
305
+ })
306
+
307
+ t.Run("non text/textArray and all tokenizations", func(t *testing.T) {
308
+ var testCases []testCase
309
+ for _, dataType := range schema.PrimitiveDataTypes {
310
+ switch dataType {
311
+ case schema.DataTypeText, schema.DataTypeTextArray:
312
+ continue
313
+ default:
314
+ tokenization := ""
315
+ testCases = append(testCases, testCase{
316
+ propName: propName(dataType, tokenization),
317
+ dataType: dataType.PropString(),
318
+ tokenization: tokenization,
319
+ expectedErrMsg: "",
320
+ })
321
+
322
+ for _, tokenization := range append(tokenizer.Tokenizations, "non_existing") {
323
+ testCases = append(testCases, testCase{
324
+ propName: propName(dataType, tokenization),
325
+ dataType: dataType.PropString(),
326
+ tokenization: tokenization,
327
+ expectedErrMsg: fmt.Sprintf("tokenization is not allowed for data type '%s'", dataType),
328
+ })
329
+ }
330
+ }
331
+ }
332
+
333
+ runTestCases(t, testCases)
334
+ })
335
+
336
+ t.Run("non text/textArray and all tokenizations", func(t *testing.T) {
337
+ var testCases []testCase
338
+ for i, dataType := range [][]string{
339
+ {"SomeClass"},
340
+ {"SomeOtherClass", "YetAnotherClass"},
341
+ } {
342
+ testCases = append(testCases, testCase{
343
+ propName: fmt.Sprintf("RefProp_%d_empty", i),
344
+ dataType: dataType,
345
+ tokenization: "",
346
+ expectedErrMsg: "",
347
+ callReadOnly: true,
348
+ })
349
+
350
+ for _, tokenization := range append(tokenizer.Tokenizations, "non_existing") {
351
+ testCases = append(testCases, testCase{
352
+ propName: fmt.Sprintf("RefProp_%d_%s", i, tokenization),
353
+ dataType: dataType,
354
+ tokenization: tokenization,
355
+ expectedErrMsg: "tokenization is not allowed for reference data type",
356
+ callReadOnly: true,
357
+ })
358
+ }
359
+ }
360
+
361
+ runTestCases(t, testCases)
362
+ })
363
+
364
+ t.Run("[deprecated string] string/stringArray and all tokenizations", func(t *testing.T) {
365
+ var testCases []testCase
366
+ for _, dataType := range []schema.DataType{
367
+ schema.DataTypeString, schema.DataTypeStringArray,
368
+ } {
369
+ for _, tokenization := range []string{
370
+ models.PropertyTokenizationWord, models.PropertyTokenizationField, "",
371
+ } {
372
+ testCases = append(testCases, testCase{
373
+ propName: propName(dataType, tokenization),
374
+ dataType: dataType.PropString(),
375
+ tokenization: tokenization,
376
+ expectedErrMsg: "",
377
+ })
378
+ }
379
+
380
+ for _, tokenization := range append(tokenizer.Tokenizations, "non_existing") {
381
+ switch tokenization {
382
+ case models.PropertyTokenizationWord, models.PropertyTokenizationField:
383
+ continue
384
+ default:
385
+ testCases = append(testCases, testCase{
386
+ propName: propName(dataType, tokenization),
387
+ dataType: dataType.PropString(),
388
+ tokenization: tokenization,
389
+ expectedErrMsg: fmt.Sprintf("tokenization '%s' is not allowed for data type '%s'", tokenization, dataType),
390
+ })
391
+ }
392
+ }
393
+ }
394
+
395
+ runTestCases(t, testCases)
396
+ })
397
+ })
398
+
399
+ t.Run("with invalid settings", func(t *testing.T) {
400
+ handler, _ := newTestHandler(t, &fakeDB{})
401
+
402
+ _, _, err := handler.AddClass(ctx, nil, &models.Class{
403
+ Class: "NewClass",
404
+ VectorIndexType: "invalid",
405
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
406
+ })
407
+ assert.EqualError(t, err, `unrecognized or unsupported vectorIndexType "invalid"`)
408
+
409
+ // VectorConfig is invalid VectorIndexType
410
+ _, _, err = handler.AddClass(ctx, nil, &models.Class{
411
+ Class: "NewClass",
412
+ VectorConfig: map[string]models.VectorConfig{
413
+ "custom": {
414
+ VectorIndexType: "invalid",
415
+ VectorIndexConfig: hnsw.UserConfig{},
416
+ Vectorizer: map[string]interface{}{"none": map[string]interface{}{}},
417
+ },
418
+ },
419
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
420
+ })
421
+ assert.EqualError(t, err, `target vector "custom": unrecognized or unsupported vectorIndexType "invalid"`)
422
+
423
+ // VectorConfig is invalid Vectorizer
424
+ _, _, err = handler.AddClass(ctx, nil, &models.Class{
425
+ Class: "NewClass",
426
+ VectorConfig: map[string]models.VectorConfig{
427
+ "custom": {
428
+ VectorIndexType: "flat",
429
+ VectorIndexConfig: hnsw.UserConfig{},
430
+ Vectorizer: map[string]interface{}{"invalid": nil},
431
+ },
432
+ },
433
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
434
+ })
435
+ assert.EqualError(t, err, `target vector "custom": vectorizer: invalid vectorizer "invalid"`)
436
+ })
437
+ }
438
+
439
+ func Test_AddClassWithLimits(t *testing.T) {
440
+ t.Parallel()
441
+ ctx := context.Background()
442
+
443
+ t.Run("with max collections limit", func(t *testing.T) {
444
+ tests := []struct {
445
+ name string
446
+ existingCount int
447
+ maxAllowed int
448
+ expectedError error
449
+ }{
450
+ {
451
+ name: "under the limit",
452
+ existingCount: 5,
453
+ maxAllowed: 10,
454
+ expectedError: nil,
455
+ },
456
+ {
457
+ name: "at the limit",
458
+ existingCount: 10,
459
+ maxAllowed: 10,
460
+ expectedError: fmt.Errorf("maximum number of collections (10) reached"),
461
+ },
462
+ {
463
+ name: "over the limit",
464
+ existingCount: 11,
465
+ maxAllowed: 10,
466
+ expectedError: fmt.Errorf("maximum number of collections (10) reached"),
467
+ },
468
+ {
469
+ name: "no limit set",
470
+ existingCount: 100,
471
+ maxAllowed: -1,
472
+ expectedError: nil,
473
+ },
474
+ }
475
+
476
+ for _, tt := range tests {
477
+ t.Run(tt.name, func(t *testing.T) {
478
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
479
+
480
+ // Mock the schema count
481
+ fakeSchemaManager.On("QueryCollectionsCount").Return(tt.existingCount, nil)
482
+
483
+ // Set the max collections limit in config
484
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(tt.maxAllowed)
485
+
486
+ class := &models.Class{
487
+ Class: "NewClass",
488
+ Vectorizer: "none",
489
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
490
+ }
491
+
492
+ if tt.expectedError == nil {
493
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
494
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
495
+ }
496
+
497
+ _, _, err := handler.AddClass(ctx, nil, class)
498
+ if tt.expectedError != nil {
499
+ require.NotNil(t, err)
500
+ assert.Contains(t, err.Error(), tt.expectedError.Error())
501
+ } else {
502
+ require.Nil(t, err)
503
+ }
504
+ fakeSchemaManager.AssertExpectations(t)
505
+ })
506
+ }
507
+ })
508
+
509
+ t.Run("adding dynamic index", func(t *testing.T) {
510
+ for _, tt := range []struct {
511
+ name string
512
+ asyncIndexingEnabled bool
513
+
514
+ expectError string
515
+ }{
516
+ {
517
+ name: "async indexing disabled",
518
+ asyncIndexingEnabled: false,
519
+
520
+ expectError: "the dynamic index can only be created under async indexing environment (ASYNC_INDEXING=true)",
521
+ },
522
+ {
523
+ name: "async indexing enabled",
524
+ asyncIndexingEnabled: true,
525
+ },
526
+ } {
527
+ t.Run(tt.name, func(t *testing.T) {
528
+ handler, schemaManager := newTestHandler(t, &fakeDB{})
529
+ handler.asyncIndexingEnabled = tt.asyncIndexingEnabled
530
+
531
+ if tt.expectError == "" {
532
+ schemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
533
+ schemaManager.On("QueryCollectionsCount").Return(0, nil)
534
+ defer schemaManager.AssertExpectations(t)
535
+ }
536
+
537
+ assertError := func(err error) {
538
+ if tt.expectError != "" {
539
+ require.ErrorContains(t, err, tt.expectError)
540
+ } else {
541
+ require.NoError(t, err)
542
+ }
543
+ }
544
+
545
+ _, _, err := handler.AddClass(ctx, nil, &models.Class{
546
+ Class: "NewClass",
547
+ VectorIndexType: "dynamic",
548
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
549
+ })
550
+ assertError(err)
551
+
552
+ _, _, err = handler.AddClass(ctx, nil, &models.Class{
553
+ Class: "NewClass",
554
+ VectorConfig: map[string]models.VectorConfig{
555
+ "vec1": {
556
+ VectorIndexType: "dynamic",
557
+ Vectorizer: map[string]any{"text2vec-contextionary": map[string]any{}},
558
+ },
559
+ },
560
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
561
+ })
562
+ assertError(err)
563
+ })
564
+ }
565
+ })
566
+ }
567
+
568
+ func Test_AddClass_DefaultsAndMigration(t *testing.T) {
569
+ t.Parallel()
570
+
571
+ t.Run("set defaults and migrate string|stringArray datatype and tokenization", func(t *testing.T) {
572
+ type testCase struct {
573
+ propName string
574
+ dataType schema.DataType
575
+ tokenization string
576
+
577
+ expectedDataType schema.DataType
578
+ expectedTokenization string
579
+ }
580
+
581
+ propName := func(dataType schema.DataType, tokenization string) string {
582
+ return strings.ReplaceAll(fmt.Sprintf("%s_%s", dataType, tokenization), "[]", "Array")
583
+ }
584
+
585
+ ctx := context.Background()
586
+ className := "MigrationClass"
587
+
588
+ var testCases []testCase
589
+ for _, dataType := range []schema.DataType{
590
+ schema.DataTypeText, schema.DataTypeTextArray,
591
+ } {
592
+ for _, tokenization := range tokenizer.Tokenizations {
593
+ testCases = append(testCases, testCase{
594
+ propName: propName(dataType, tokenization),
595
+ dataType: dataType,
596
+ tokenization: tokenization,
597
+ expectedDataType: dataType,
598
+ expectedTokenization: tokenization,
599
+ })
600
+ }
601
+ tokenization := ""
602
+ testCases = append(testCases, testCase{
603
+ propName: propName(dataType, tokenization),
604
+ dataType: dataType,
605
+ tokenization: tokenization,
606
+ expectedDataType: dataType,
607
+ expectedTokenization: models.PropertyTokenizationWord,
608
+ })
609
+ }
610
+ for _, dataType := range []schema.DataType{
611
+ schema.DataTypeString, schema.DataTypeStringArray,
612
+ } {
613
+ for _, tokenization := range []string{
614
+ models.PropertyTokenizationWord, models.PropertyTokenizationField, "",
615
+ } {
616
+ var expectedDataType schema.DataType
617
+ switch dataType {
618
+ case schema.DataTypeStringArray:
619
+ expectedDataType = schema.DataTypeTextArray
620
+ default:
621
+ expectedDataType = schema.DataTypeText
622
+ }
623
+
624
+ var expectedTokenization string
625
+ switch tokenization {
626
+ case models.PropertyTokenizationField:
627
+ expectedTokenization = models.PropertyTokenizationField
628
+ default:
629
+ expectedTokenization = models.PropertyTokenizationWhitespace
630
+ }
631
+
632
+ testCases = append(testCases, testCase{
633
+ propName: propName(dataType, tokenization),
634
+ dataType: dataType,
635
+ tokenization: tokenization,
636
+ expectedDataType: expectedDataType,
637
+ expectedTokenization: expectedTokenization,
638
+ })
639
+ }
640
+ }
641
+
642
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
643
+ var properties []*models.Property
644
+ for _, tc := range testCases {
645
+ properties = append(properties, &models.Property{
646
+ Name: "created_" + tc.propName,
647
+ DataType: tc.dataType.PropString(),
648
+ Tokenization: tc.tokenization,
649
+ })
650
+ }
651
+
652
+ class := models.Class{
653
+ Class: className,
654
+ Properties: properties,
655
+ Vectorizer: "none",
656
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
657
+ }
658
+
659
+ t.Run("create class with all properties", func(t *testing.T) {
660
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
661
+ fakeSchemaManager.On("ReadOnlyClass", mock.Anything, mock.Anything).Return(nil)
662
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
663
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(-1)
664
+ _, _, err := handler.AddClass(ctx, nil, &class)
665
+ require.Nil(t, err)
666
+ })
667
+
668
+ t.Run("add properties to existing class", func(t *testing.T) {
669
+ for _, tc := range testCases {
670
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
671
+ fakeSchemaManager.On("ReadOnlyClass", mock.Anything, mock.Anything).Return(&class)
672
+ fakeSchemaManager.On("AddProperty", mock.Anything, mock.Anything).Return(nil)
673
+ t.Run("added_"+tc.propName, func(t *testing.T) {
674
+ _, _, err := handler.AddClassProperty(ctx, nil, &class, class.Class, false, &models.Property{
675
+ Name: "added_" + tc.propName,
676
+ DataType: tc.dataType.PropString(),
677
+ Tokenization: tc.tokenization,
678
+ })
679
+
680
+ require.Nil(t, err)
681
+ })
682
+ }
683
+ })
684
+ })
685
+
686
+ t.Run("set defaults and migrate IndexInverted to IndexFilterable + IndexSearchable", func(t *testing.T) {
687
+ vFalse := false
688
+ vTrue := true
689
+ allBoolPtrs := []*bool{nil, &vFalse, &vTrue}
690
+
691
+ type testCase struct {
692
+ propName string
693
+ dataType schema.DataType
694
+ indexInverted *bool
695
+ indexFilterable *bool
696
+ indexSearchable *bool
697
+
698
+ expectedInverted *bool
699
+ expectedFilterable *bool
700
+ expectedSearchable *bool
701
+ }
702
+
703
+ boolPtrToStr := func(ptr *bool) string {
704
+ if ptr == nil {
705
+ return "nil"
706
+ }
707
+ return fmt.Sprintf("%v", *ptr)
708
+ }
709
+ propName := func(dt schema.DataType, inverted, filterable, searchable *bool) string {
710
+ return fmt.Sprintf("%s_inverted_%s_filterable_%s_searchable_%s",
711
+ dt.String(), boolPtrToStr(inverted), boolPtrToStr(filterable), boolPtrToStr(searchable))
712
+ }
713
+
714
+ ctx := context.Background()
715
+ className := "MigrationClass"
716
+
717
+ var testCases []testCase
718
+
719
+ for _, dataType := range []schema.DataType{schema.DataTypeText, schema.DataTypeInt} {
720
+ for _, inverted := range allBoolPtrs {
721
+ for _, filterable := range allBoolPtrs {
722
+ for _, searchable := range allBoolPtrs {
723
+ if inverted != nil {
724
+ if filterable != nil || searchable != nil {
725
+ // invalid combination, indexInverted can not be set
726
+ // together with indexFilterable or indexSearchable
727
+ continue
728
+ }
729
+ }
730
+
731
+ if searchable != nil && *searchable {
732
+ if dataType != schema.DataTypeText {
733
+ // invalid combination, indexSearchable can not be enabled
734
+ // for non text/text[] data type
735
+ continue
736
+ }
737
+ }
738
+
739
+ switch dataType {
740
+ case schema.DataTypeText:
741
+ if inverted != nil {
742
+ testCases = append(testCases, testCase{
743
+ propName: propName(dataType, inverted, filterable, searchable),
744
+ dataType: dataType,
745
+ indexInverted: inverted,
746
+ indexFilterable: filterable,
747
+ indexSearchable: searchable,
748
+ expectedInverted: nil,
749
+ expectedFilterable: inverted,
750
+ expectedSearchable: inverted,
751
+ })
752
+ } else {
753
+ expectedFilterable := filterable
754
+ if filterable == nil {
755
+ expectedFilterable = &vTrue
756
+ }
757
+ expectedSearchable := searchable
758
+ if searchable == nil {
759
+ expectedSearchable = &vTrue
760
+ }
761
+ testCases = append(testCases, testCase{
762
+ propName: propName(dataType, inverted, filterable, searchable),
763
+ dataType: dataType,
764
+ indexInverted: inverted,
765
+ indexFilterable: filterable,
766
+ indexSearchable: searchable,
767
+ expectedInverted: nil,
768
+ expectedFilterable: expectedFilterable,
769
+ expectedSearchable: expectedSearchable,
770
+ })
771
+ }
772
+ default:
773
+ if inverted != nil {
774
+ testCases = append(testCases, testCase{
775
+ propName: propName(dataType, inverted, filterable, searchable),
776
+ dataType: dataType,
777
+ indexInverted: inverted,
778
+ indexFilterable: filterable,
779
+ indexSearchable: searchable,
780
+ expectedInverted: nil,
781
+ expectedFilterable: inverted,
782
+ expectedSearchable: &vFalse,
783
+ })
784
+ } else {
785
+ expectedFilterable := filterable
786
+ if filterable == nil {
787
+ expectedFilterable = &vTrue
788
+ }
789
+ expectedSearchable := searchable
790
+ if searchable == nil {
791
+ expectedSearchable = &vFalse
792
+ }
793
+ testCases = append(testCases, testCase{
794
+ propName: propName(dataType, inverted, filterable, searchable),
795
+ dataType: dataType,
796
+ indexInverted: inverted,
797
+ indexFilterable: filterable,
798
+ indexSearchable: searchable,
799
+ expectedInverted: nil,
800
+ expectedFilterable: expectedFilterable,
801
+ expectedSearchable: expectedSearchable,
802
+ })
803
+ }
804
+ }
805
+ }
806
+ }
807
+ }
808
+ }
809
+
810
+ var properties []*models.Property
811
+ for _, tc := range testCases {
812
+ properties = append(properties, &models.Property{
813
+ Name: "created_" + tc.propName,
814
+ DataType: tc.dataType.PropString(),
815
+ IndexInverted: tc.indexInverted,
816
+ IndexFilterable: tc.indexFilterable,
817
+ IndexSearchable: tc.indexSearchable,
818
+ })
819
+ }
820
+
821
+ class := models.Class{
822
+ Class: className,
823
+ Properties: properties,
824
+ Vectorizer: "none",
825
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
826
+ }
827
+ t.Run("create class with all properties", func(t *testing.T) {
828
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
829
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
830
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
831
+ _, _, err := handler.AddClass(ctx, nil, &class)
832
+ require.Nil(t, err)
833
+ fakeSchemaManager.AssertExpectations(t)
834
+ })
835
+
836
+ t.Run("add properties to existing class", func(t *testing.T) {
837
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
838
+ for _, tc := range testCases {
839
+ t.Run("added_"+tc.propName, func(t *testing.T) {
840
+ prop := &models.Property{
841
+ Name: "added_" + tc.propName,
842
+ DataType: tc.dataType.PropString(),
843
+ IndexInverted: tc.indexInverted,
844
+ IndexFilterable: tc.indexFilterable,
845
+ IndexSearchable: tc.indexSearchable,
846
+ }
847
+ fakeSchemaManager.On("AddProperty", className, []*models.Property{prop}).Return(nil)
848
+ _, _, err := handler.AddClassProperty(ctx, nil, &class, class.Class, false, prop)
849
+
850
+ require.Nil(t, err)
851
+ })
852
+ }
853
+ fakeSchemaManager.AssertExpectations(t)
854
+ })
855
+ })
856
+ }
857
+
858
+ func Test_Defaults_NestedProperties(t *testing.T) {
859
+ t.Parallel()
860
+
861
+ for _, pdt := range schema.PrimitiveDataTypes {
862
+ t.Run(pdt.String(), func(t *testing.T) {
863
+ nestedProperties := []*models.NestedProperty{
864
+ {
865
+ Name: "nested_" + pdt.String(),
866
+ DataType: pdt.PropString(),
867
+ },
868
+ }
869
+
870
+ for _, ndt := range schema.NestedDataTypes {
871
+ t.Run(ndt.String(), func(t *testing.T) {
872
+ propPrimitives := &models.Property{
873
+ Name: "objectProp",
874
+ DataType: ndt.PropString(),
875
+ NestedProperties: nestedProperties,
876
+ }
877
+ propLvl2Primitives := &models.Property{
878
+ Name: "objectPropLvl2",
879
+ DataType: ndt.PropString(),
880
+ NestedProperties: []*models.NestedProperty{
881
+ {
882
+ Name: "nested_object",
883
+ DataType: ndt.PropString(),
884
+ NestedProperties: nestedProperties,
885
+ },
886
+ },
887
+ }
888
+
889
+ setPropertyDefaults(propPrimitives)
890
+ setPropertyDefaults(propLvl2Primitives)
891
+
892
+ t.Run("primitive data types", func(t *testing.T) {
893
+ for _, np := range []*models.NestedProperty{
894
+ propPrimitives.NestedProperties[0],
895
+ propLvl2Primitives.NestedProperties[0].NestedProperties[0],
896
+ } {
897
+ switch pdt {
898
+ case schema.DataTypeText, schema.DataTypeTextArray:
899
+ require.NotNil(t, np.IndexFilterable)
900
+ assert.True(t, *np.IndexFilterable)
901
+ require.NotNil(t, np.IndexSearchable)
902
+ assert.True(t, *np.IndexSearchable)
903
+ assert.Equal(t, models.PropertyTokenizationWord, np.Tokenization)
904
+ case schema.DataTypeBlob:
905
+ require.NotNil(t, np.IndexFilterable)
906
+ assert.False(t, *np.IndexFilterable)
907
+ require.NotNil(t, np.IndexSearchable)
908
+ assert.False(t, *np.IndexSearchable)
909
+ assert.Equal(t, "", np.Tokenization)
910
+ default:
911
+ require.NotNil(t, np.IndexFilterable)
912
+ assert.True(t, *np.IndexFilterable)
913
+ require.NotNil(t, np.IndexSearchable)
914
+ assert.False(t, *np.IndexSearchable)
915
+ assert.Equal(t, "", np.Tokenization)
916
+ }
917
+ }
918
+ })
919
+
920
+ t.Run("nested data types", func(t *testing.T) {
921
+ for _, indexFilterable := range []*bool{
922
+ propPrimitives.IndexFilterable,
923
+ propLvl2Primitives.IndexFilterable,
924
+ propLvl2Primitives.NestedProperties[0].IndexFilterable,
925
+ } {
926
+ require.NotNil(t, indexFilterable)
927
+ assert.True(t, *indexFilterable)
928
+ }
929
+ for _, indexSearchable := range []*bool{
930
+ propPrimitives.IndexSearchable,
931
+ propLvl2Primitives.IndexSearchable,
932
+ propLvl2Primitives.NestedProperties[0].IndexSearchable,
933
+ } {
934
+ require.NotNil(t, indexSearchable)
935
+ assert.False(t, *indexSearchable)
936
+ }
937
+ for _, tokenization := range []string{
938
+ propPrimitives.Tokenization,
939
+ propLvl2Primitives.Tokenization,
940
+ propLvl2Primitives.NestedProperties[0].Tokenization,
941
+ } {
942
+ assert.Equal(t, "", tokenization)
943
+ }
944
+ })
945
+ })
946
+ }
947
+ })
948
+ }
949
+ }
950
+
951
+ func Test_Validation_ClassNames(t *testing.T) {
952
+ t.Parallel()
953
+
954
+ type testCase struct {
955
+ input string
956
+ valid bool
957
+ storedAs string
958
+ name string
959
+ }
960
+
961
+ // all inputs represent class names (!)
962
+ tests := []testCase{
963
+ // valid names
964
+ {
965
+ name: "Single uppercase word",
966
+ input: "Car",
967
+ valid: true,
968
+ storedAs: "Car",
969
+ },
970
+ {
971
+ name: "Single lowercase word, stored as uppercase",
972
+ input: "car",
973
+ valid: true,
974
+ storedAs: "Car",
975
+ },
976
+ {
977
+ name: "empty class",
978
+ input: "",
979
+ valid: false,
980
+ },
981
+ }
982
+
983
+ t.Run("adding a class", func(t *testing.T) {
984
+ t.Run("different class names without keywords or properties", func(t *testing.T) {
985
+ for _, test := range tests {
986
+ t.Run(test.name+" as thing class", func(t *testing.T) {
987
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
988
+ class := &models.Class{
989
+ Vectorizer: "none",
990
+ Class: test.input,
991
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
992
+ }
993
+
994
+ if test.valid {
995
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
996
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
997
+ }
998
+ _, _, err := handler.AddClass(context.Background(), nil, class)
999
+ t.Log(err)
1000
+ assert.Equal(t, test.valid, err == nil)
1001
+ fakeSchemaManager.AssertExpectations(t)
1002
+ })
1003
+ }
1004
+ })
1005
+
1006
+ t.Run("different class names with valid keywords", func(t *testing.T) {
1007
+ for _, test := range tests {
1008
+ t.Run(test.name+" as thing class", func(t *testing.T) {
1009
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
1010
+ class := &models.Class{
1011
+ Vectorizer: "none",
1012
+ Class: test.input,
1013
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1014
+ }
1015
+
1016
+ if test.valid {
1017
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
1018
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
1019
+ }
1020
+ _, _, err := handler.AddClass(context.Background(), nil, class)
1021
+ t.Log(err)
1022
+ assert.Equal(t, test.valid, err == nil)
1023
+ fakeSchemaManager.AssertExpectations(t)
1024
+ })
1025
+ }
1026
+ })
1027
+ })
1028
+ }
1029
+
1030
+ func Test_Validation_PropertyNames(t *testing.T) {
1031
+ t.Parallel()
1032
+ type testCase struct {
1033
+ input string
1034
+ valid bool
1035
+ storedAs string
1036
+ name string
1037
+ }
1038
+
1039
+ // for all test cases keep in mind that the word "carrot" is not present in
1040
+ // the fake c11y, but every other word is
1041
+ //
1042
+ // all inputs represent property names (!)
1043
+ tests := []testCase{
1044
+ // valid names
1045
+ {
1046
+ name: "Single uppercase word, stored as lowercase",
1047
+ input: "Brand",
1048
+ valid: true,
1049
+ storedAs: "brand",
1050
+ },
1051
+ {
1052
+ name: "Single lowercase word",
1053
+ input: "brand",
1054
+ valid: true,
1055
+ storedAs: "brand",
1056
+ },
1057
+ {
1058
+ name: "Property with underscores",
1059
+ input: "property_name",
1060
+ valid: true,
1061
+ storedAs: "property_name",
1062
+ },
1063
+ {
1064
+ name: "Property with underscores and numbers",
1065
+ input: "property_name_2",
1066
+ valid: true,
1067
+ storedAs: "property_name_2",
1068
+ },
1069
+ {
1070
+ name: "Property starting with underscores",
1071
+ input: "_property_name",
1072
+ valid: true,
1073
+ storedAs: "_property_name",
1074
+ },
1075
+ {
1076
+ name: "empty prop name",
1077
+ input: "",
1078
+ valid: false,
1079
+ },
1080
+ {
1081
+ name: "reserved prop name: id",
1082
+ input: "id",
1083
+ valid: false,
1084
+ },
1085
+ {
1086
+ name: "reserved prop name: _id",
1087
+ input: "_id",
1088
+ valid: false,
1089
+ },
1090
+ {
1091
+ name: "reserved prop name: _additional",
1092
+ input: "_additional",
1093
+ valid: false,
1094
+ },
1095
+ }
1096
+
1097
+ ctx := context.Background()
1098
+
1099
+ t.Run("when adding a new class", func(t *testing.T) {
1100
+ t.Run("different property names without keywords for the prop", func(t *testing.T) {
1101
+ for _, test := range tests {
1102
+ t.Run(test.name+" as thing class", func(t *testing.T) {
1103
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
1104
+ class := &models.Class{
1105
+ Vectorizer: "none",
1106
+ Class: "ValidName",
1107
+ Properties: []*models.Property{{
1108
+ DataType: schema.DataTypeText.PropString(),
1109
+ Name: test.input,
1110
+ }},
1111
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1112
+ }
1113
+
1114
+ if test.valid {
1115
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
1116
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
1117
+ }
1118
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(-1)
1119
+ _, _, err := handler.AddClass(context.Background(), nil, class)
1120
+ assert.Equal(t, test.valid, err == nil)
1121
+ fakeSchemaManager.AssertExpectations(t)
1122
+ })
1123
+ }
1124
+ })
1125
+
1126
+ t.Run("different property names with valid keywords for the prop", func(t *testing.T) {
1127
+ for _, test := range tests {
1128
+ t.Run(test.name+" as thing class", func(t *testing.T) {
1129
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
1130
+ class := &models.Class{
1131
+ Vectorizer: "none",
1132
+ Class: "ValidName",
1133
+ Properties: []*models.Property{{
1134
+ DataType: schema.DataTypeText.PropString(),
1135
+ Name: test.input,
1136
+ }},
1137
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1138
+ }
1139
+
1140
+ if test.valid {
1141
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
1142
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
1143
+ }
1144
+ _, _, err := handler.AddClass(context.Background(), nil, class)
1145
+ t.Log(err)
1146
+ assert.Equal(t, test.valid, err == nil)
1147
+ fakeSchemaManager.AssertExpectations(t)
1148
+ })
1149
+ }
1150
+ })
1151
+ })
1152
+
1153
+ t.Run("when updating an existing class with a new property", func(t *testing.T) {
1154
+ t.Run("different property names without keywords for the prop", func(t *testing.T) {
1155
+ for _, test := range tests {
1156
+ t.Run(test.name+" as thing class", func(t *testing.T) {
1157
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
1158
+ class := &models.Class{
1159
+ Vectorizer: "none",
1160
+ Class: "ValidName",
1161
+ Properties: []*models.Property{
1162
+ {
1163
+ Name: "dummyPropSoWeDontRunIntoAllNoindexedError",
1164
+ DataType: schema.DataTypeText.PropString(),
1165
+ },
1166
+ },
1167
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1168
+ }
1169
+
1170
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
1171
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
1172
+ _, _, err := handler.AddClass(context.Background(), nil, class)
1173
+ require.Nil(t, err)
1174
+
1175
+ property := &models.Property{
1176
+ DataType: schema.DataTypeText.PropString(),
1177
+ Name: test.input,
1178
+ }
1179
+ if test.valid {
1180
+ fakeSchemaManager.On("AddProperty", class.Class, []*models.Property{property}).Return(nil)
1181
+ }
1182
+ _, _, err = handler.AddClassProperty(context.Background(), nil, class, class.Class, false, property)
1183
+ t.Log(err)
1184
+ require.Equal(t, test.valid, err == nil)
1185
+ fakeSchemaManager.AssertExpectations(t)
1186
+ })
1187
+ }
1188
+ })
1189
+
1190
+ t.Run("different property names with valid keywords for the prop", func(t *testing.T) {
1191
+ for _, test := range tests {
1192
+ t.Run(test.name+" as thing class", func(t *testing.T) {
1193
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
1194
+ class := &models.Class{
1195
+ Vectorizer: "none",
1196
+ Class: "ValidName",
1197
+ Properties: []*models.Property{{
1198
+ DataType: schema.DataTypeText.PropString(),
1199
+ Name: test.input,
1200
+ }},
1201
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1202
+ }
1203
+
1204
+ if test.valid {
1205
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
1206
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
1207
+ }
1208
+ _, _, err := handler.AddClass(ctx, nil, class)
1209
+ t.Log(err)
1210
+ assert.Equal(t, test.valid, err == nil)
1211
+ fakeSchemaManager.AssertExpectations(t)
1212
+ })
1213
+ }
1214
+ })
1215
+ })
1216
+ }
1217
+
1218
+ // As of now, most class settings are immutable, but we need to allow some
1219
+ // specific updates, such as the vector index config
1220
+ func Test_UpdateClass(t *testing.T) {
1221
+ t.Run("class not found", func(t *testing.T) {
1222
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
1223
+ fakeSchemaManager.On("ReadOnlyClass", "WrongClass", mock.Anything).Return(nil)
1224
+ fakeSchemaManager.On("UpdateClass", mock.Anything, mock.Anything).Return(ErrNotFound)
1225
+
1226
+ err := handler.UpdateClass(context.Background(), nil, "WrongClass", &models.Class{ReplicationConfig: &models.ReplicationConfig{Factor: 1}})
1227
+ require.ErrorIs(t, err, ErrNotFound)
1228
+ fakeSchemaManager.AssertExpectations(t)
1229
+ })
1230
+
1231
+ t.Run("fields validation", func(t *testing.T) {
1232
+ tests := []struct {
1233
+ name string
1234
+ initial *models.Class
1235
+ update *models.Class
1236
+ expectedError error
1237
+ }{
1238
+ {
1239
+ name: "ChangeName",
1240
+ initial: &models.Class{Class: "InitialName", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
1241
+ update: &models.Class{Class: "UpdatedName", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
1242
+ expectedError: fmt.Errorf(
1243
+ "class name is immutable: " +
1244
+ "attempted change from \"InitialName\" to \"UpdatedName\""),
1245
+ },
1246
+ {
1247
+ name: "ModifyVectorizer",
1248
+ initial: &models.Class{Class: "InitialName", Vectorizer: "model1", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
1249
+ update: &models.Class{Class: "InitialName", Vectorizer: "model2", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
1250
+ expectedError: fmt.Errorf(
1251
+ "vectorizer is immutable: " +
1252
+ "attempted change from \"model1\" to \"model2\""),
1253
+ },
1254
+ {
1255
+ name: "ModifyVectorIndexType",
1256
+ initial: &models.Class{Class: "InitialName", VectorIndexType: "hnsw", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
1257
+ update: &models.Class{Class: "InitialName", VectorIndexType: "flat", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
1258
+ expectedError: fmt.Errorf(
1259
+ "vector index type is immutable: " +
1260
+ "attempted change from \"hnsw\" to \"flat\""),
1261
+ },
1262
+ {
1263
+ name: "UnsupportedVectorIndex",
1264
+ initial: &models.Class{Class: "InitialName", VectorIndexType: "hnsw", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
1265
+ update: &models.Class{Class: "InitialName", VectorIndexType: "lsh", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
1266
+ expectedError: fmt.Errorf("unsupported vector"),
1267
+ },
1268
+ {
1269
+ name: "add property to an empty class",
1270
+ initial: &models.Class{Class: "InitialName", Vectorizer: "none", ReplicationConfig: &models.ReplicationConfig{Factor: 1}},
1271
+ update: &models.Class{
1272
+ Class: "InitialName",
1273
+ Vectorizer: "none",
1274
+ Properties: []*models.Property{
1275
+ {
1276
+ Name: "newProp",
1277
+ },
1278
+ },
1279
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1280
+ },
1281
+ expectedError: errPropertiesUpdatedInClassUpdate,
1282
+ },
1283
+ {
1284
+ name: "updating second property",
1285
+ initial: &models.Class{
1286
+ Class: "InitialName",
1287
+ Vectorizer: "none",
1288
+ Properties: []*models.Property{
1289
+ {
1290
+ Name: "prop1",
1291
+ DataType: schema.DataTypeText.PropString(),
1292
+ },
1293
+ {
1294
+ Name: "prop2",
1295
+ DataType: schema.DataTypeText.PropString(),
1296
+ },
1297
+ },
1298
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1299
+ },
1300
+ update: &models.Class{
1301
+ Class: "InitialName",
1302
+ Vectorizer: "none",
1303
+ Properties: []*models.Property{
1304
+ {
1305
+ Name: "prop1",
1306
+ DataType: schema.DataTypeText.PropString(),
1307
+ },
1308
+ {
1309
+ Name: "prop2",
1310
+ DataType: schema.DataTypeInt.PropString(),
1311
+ },
1312
+ },
1313
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1314
+ },
1315
+ expectedError: errPropertiesUpdatedInClassUpdate,
1316
+ },
1317
+ {
1318
+ name: "properties order should not matter",
1319
+ initial: &models.Class{
1320
+ Class: "InitialName",
1321
+ Vectorizer: "none",
1322
+ Properties: []*models.Property{
1323
+ {
1324
+ Name: "prop1",
1325
+ DataType: schema.DataTypeText.PropString(),
1326
+ },
1327
+ {
1328
+ Name: "prop2",
1329
+ DataType: schema.DataTypeInt.PropString(),
1330
+ },
1331
+ },
1332
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1333
+ },
1334
+ update: &models.Class{
1335
+ Class: "InitialName",
1336
+ Vectorizer: "none",
1337
+ Properties: []*models.Property{
1338
+ {
1339
+ Name: "prop2",
1340
+ DataType: schema.DataTypeInt.PropString(),
1341
+ },
1342
+ {
1343
+ Name: "prop1",
1344
+ DataType: schema.DataTypeText.PropString(),
1345
+ },
1346
+ },
1347
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1348
+ },
1349
+ expectedError: nil,
1350
+ },
1351
+ {
1352
+ name: "leaving properties unchanged",
1353
+ initial: &models.Class{
1354
+ Class: "InitialName",
1355
+ Vectorizer: "none",
1356
+ Properties: []*models.Property{
1357
+ {
1358
+ Name: "aProp",
1359
+ DataType: schema.DataTypeText.PropString(),
1360
+ },
1361
+ },
1362
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1363
+ },
1364
+ update: &models.Class{
1365
+ Class: "InitialName",
1366
+ Vectorizer: "none",
1367
+ Properties: []*models.Property{
1368
+ {
1369
+ Name: "aProp",
1370
+ DataType: schema.DataTypeText.PropString(),
1371
+ },
1372
+ },
1373
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1374
+ },
1375
+ expectedError: nil,
1376
+ },
1377
+ {
1378
+ name: "attempting to rename a property",
1379
+ initial: &models.Class{
1380
+ Class: "InitialName",
1381
+ Vectorizer: "none",
1382
+ Properties: []*models.Property{
1383
+ {
1384
+ Name: "aProp",
1385
+ DataType: schema.DataTypeText.PropString(),
1386
+ },
1387
+ },
1388
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1389
+ },
1390
+ update: &models.Class{
1391
+ Class: "InitialName",
1392
+ Vectorizer: "none",
1393
+ Properties: []*models.Property{
1394
+ {
1395
+ Name: "changedProp",
1396
+ DataType: schema.DataTypeText.PropString(),
1397
+ },
1398
+ },
1399
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1400
+ },
1401
+ expectedError: fmt.Errorf(
1402
+ "property fields other than description cannot be updated through updating the class. Use the add " +
1403
+ "property feature (e.g. \"POST /v1/schema/{className}/properties\") " +
1404
+ "to add additional properties"),
1405
+ },
1406
+ {
1407
+ name: "attempting to update the inverted index cleanup interval",
1408
+ initial: &models.Class{
1409
+ Class: "InitialName",
1410
+ Vectorizer: "none",
1411
+ InvertedIndexConfig: &models.InvertedIndexConfig{
1412
+ CleanupIntervalSeconds: 17,
1413
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
1414
+ },
1415
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1416
+ },
1417
+ update: &models.Class{
1418
+ Class: "InitialName",
1419
+ Vectorizer: "none",
1420
+ InvertedIndexConfig: &models.InvertedIndexConfig{
1421
+ CleanupIntervalSeconds: 18,
1422
+ Bm25: &models.BM25Config{
1423
+ K1: config.DefaultBM25k1,
1424
+ B: config.DefaultBM25b,
1425
+ },
1426
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
1427
+ },
1428
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1429
+ },
1430
+ },
1431
+ {
1432
+ name: "attempting to update the inverted index BM25 config",
1433
+ initial: &models.Class{
1434
+ Class: "InitialName",
1435
+ Vectorizer: "none",
1436
+ InvertedIndexConfig: &models.InvertedIndexConfig{
1437
+ CleanupIntervalSeconds: 18,
1438
+ Bm25: &models.BM25Config{
1439
+ K1: 1.012,
1440
+ B: 0.125,
1441
+ },
1442
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
1443
+ },
1444
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1445
+ },
1446
+ update: &models.Class{
1447
+ Class: "InitialName",
1448
+ Vectorizer: "none",
1449
+ InvertedIndexConfig: &models.InvertedIndexConfig{
1450
+ CleanupIntervalSeconds: 18,
1451
+ Bm25: &models.BM25Config{
1452
+ K1: 1.012,
1453
+ B: 0.125,
1454
+ },
1455
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
1456
+ },
1457
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1458
+ },
1459
+ },
1460
+ {
1461
+ name: "attempting to update the inverted index Stopwords config",
1462
+ initial: &models.Class{
1463
+ Class: "InitialName",
1464
+ Vectorizer: "none",
1465
+ InvertedIndexConfig: &models.InvertedIndexConfig{
1466
+ CleanupIntervalSeconds: 18,
1467
+ Stopwords: &models.StopwordConfig{
1468
+ Preset: "en",
1469
+ },
1470
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
1471
+ },
1472
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1473
+ },
1474
+ update: &models.Class{
1475
+ Class: "InitialName",
1476
+ Vectorizer: "none",
1477
+ InvertedIndexConfig: &models.InvertedIndexConfig{
1478
+ CleanupIntervalSeconds: 18,
1479
+ Stopwords: &models.StopwordConfig{
1480
+ Preset: "none",
1481
+ Additions: []string{"banana", "passionfruit", "kiwi"},
1482
+ Removals: []string{"a", "the"},
1483
+ },
1484
+ UsingBlockMaxWAND: config.DefaultUsingBlockMaxWAND,
1485
+ },
1486
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1487
+ },
1488
+ },
1489
+ {
1490
+ name: "attempting to update module config",
1491
+ initial: &models.Class{
1492
+ Class: "InitialName",
1493
+ Vectorizer: "none",
1494
+ ModuleConfig: map[string]interface{}{
1495
+ "my-module1": map[string]interface{}{
1496
+ "my-setting": "some-value",
1497
+ },
1498
+ },
1499
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1500
+ },
1501
+ update: &models.Class{
1502
+ Class: "InitialName",
1503
+ Vectorizer: "none",
1504
+ ModuleConfig: map[string]interface{}{
1505
+ "my-module1": map[string]interface{}{
1506
+ "my-setting": "updated-value",
1507
+ },
1508
+ },
1509
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1510
+ },
1511
+ expectedError: fmt.Errorf("can only update generative and reranker module configs"),
1512
+ },
1513
+ {
1514
+ name: "adding new module configuration",
1515
+ initial: &models.Class{
1516
+ Class: "InitialName",
1517
+ Vectorizer: "none",
1518
+ ModuleConfig: map[string]interface{}{
1519
+ "my-module1": map[string]interface{}{
1520
+ "my-setting": "some-value",
1521
+ },
1522
+ },
1523
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1524
+ },
1525
+ update: &models.Class{
1526
+ Class: "InitialName",
1527
+ Vectorizer: "none",
1528
+ ModuleConfig: map[string]interface{}{
1529
+ "my-module1": map[string]interface{}{
1530
+ "my-setting": "some-value",
1531
+ },
1532
+ "my-module2": map[string]interface{}{
1533
+ "my-setting": "some-value",
1534
+ },
1535
+ },
1536
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1537
+ },
1538
+ expectedError: nil,
1539
+ },
1540
+ {
1541
+ name: "adding new module configuration for a property",
1542
+ initial: &models.Class{
1543
+ Class: "InitialName",
1544
+ Vectorizer: "none",
1545
+ Properties: []*models.Property{
1546
+ {
1547
+ Name: "text",
1548
+ DataType: schema.DataTypeText.PropString(),
1549
+ ModuleConfig: map[string]interface{}{
1550
+ "my-module1": map[string]interface{}{
1551
+ "my-setting": "some-value",
1552
+ },
1553
+ },
1554
+ },
1555
+ },
1556
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1557
+ },
1558
+ update: &models.Class{
1559
+ Class: "InitialName",
1560
+ Vectorizer: "none",
1561
+ Properties: []*models.Property{
1562
+ {
1563
+ Name: "text",
1564
+ DataType: schema.DataTypeText.PropString(),
1565
+ ModuleConfig: map[string]interface{}{
1566
+ "my-module1": map[string]interface{}{
1567
+ "my-setting": "some-value",
1568
+ },
1569
+ "my-module2": map[string]interface{}{
1570
+ "my-setting": "some-value",
1571
+ },
1572
+ },
1573
+ },
1574
+ },
1575
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1576
+ },
1577
+ expectedError: nil,
1578
+ },
1579
+ {
1580
+ name: "updating existing module configuration for a property",
1581
+ initial: &models.Class{
1582
+ Class: "InitialName",
1583
+ Vectorizer: "none",
1584
+ Properties: []*models.Property{
1585
+ {
1586
+ Name: "text",
1587
+ DataType: schema.DataTypeText.PropString(),
1588
+ ModuleConfig: map[string]interface{}{
1589
+ "my-module1": map[string]interface{}{
1590
+ "my-setting": "some-value",
1591
+ },
1592
+ },
1593
+ },
1594
+ },
1595
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1596
+ },
1597
+ update: &models.Class{
1598
+ Class: "InitialName",
1599
+ Vectorizer: "none",
1600
+ Properties: []*models.Property{
1601
+ {
1602
+ Name: "text",
1603
+ DataType: schema.DataTypeText.PropString(),
1604
+ ModuleConfig: map[string]interface{}{
1605
+ "my-module1": map[string]interface{}{
1606
+ "my-setting": "new-value",
1607
+ },
1608
+ },
1609
+ },
1610
+ },
1611
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1612
+ },
1613
+ expectedError: errors.New(`module "my-module1" configuration cannot be updated`),
1614
+ },
1615
+ {
1616
+ name: "removing existing module configuration for a property",
1617
+ initial: &models.Class{
1618
+ Class: "InitialName",
1619
+ Vectorizer: "none",
1620
+ Properties: []*models.Property{
1621
+ {
1622
+ Name: "text",
1623
+ DataType: schema.DataTypeText.PropString(),
1624
+ ModuleConfig: map[string]interface{}{
1625
+ "my-module1": map[string]interface{}{
1626
+ "my-setting": "some-value",
1627
+ },
1628
+ },
1629
+ },
1630
+ },
1631
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1632
+ },
1633
+ update: &models.Class{
1634
+ Class: "InitialName",
1635
+ Vectorizer: "none",
1636
+ Properties: []*models.Property{
1637
+ {
1638
+ Name: "text",
1639
+ DataType: schema.DataTypeText.PropString(),
1640
+ ModuleConfig: map[string]interface{}{
1641
+ "my-module2": map[string]interface{}{
1642
+ "my-setting": "new-value",
1643
+ },
1644
+ },
1645
+ },
1646
+ },
1647
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1648
+ },
1649
+ expectedError: errors.New(`module "my-module1" configuration was removed`),
1650
+ },
1651
+ {
1652
+ name: "updating vector index config",
1653
+ initial: &models.Class{
1654
+ Class: "InitialName",
1655
+ Vectorizer: "none",
1656
+ VectorIndexConfig: map[string]interface{}{
1657
+ "some-setting": "old-value",
1658
+ },
1659
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1660
+ },
1661
+ update: &models.Class{
1662
+ Class: "InitialName",
1663
+ Vectorizer: "none",
1664
+ VectorIndexConfig: map[string]interface{}{
1665
+ "some-setting": "new-value",
1666
+ },
1667
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1668
+ },
1669
+ expectedError: nil,
1670
+ },
1671
+ {
1672
+ name: "try to turn MT on when it was previously off",
1673
+ initial: &models.Class{
1674
+ Class: "InitialName",
1675
+ Vectorizer: "none",
1676
+ MultiTenancyConfig: &models.MultiTenancyConfig{
1677
+ Enabled: false,
1678
+ },
1679
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1680
+ },
1681
+ update: &models.Class{
1682
+ Class: "InitialName",
1683
+ Vectorizer: "none",
1684
+ MultiTenancyConfig: &models.MultiTenancyConfig{
1685
+ Enabled: true,
1686
+ },
1687
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1688
+ },
1689
+ expectedError: fmt.Errorf("enabling multi-tenancy for an existing class is not supported"),
1690
+ },
1691
+ {
1692
+ name: "try to turn MT off when it was previously on",
1693
+ initial: &models.Class{
1694
+ Class: "InitialName",
1695
+ Vectorizer: "none",
1696
+ MultiTenancyConfig: &models.MultiTenancyConfig{
1697
+ Enabled: true,
1698
+ },
1699
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1700
+ },
1701
+ update: &models.Class{
1702
+ Class: "InitialName",
1703
+ Vectorizer: "none",
1704
+ MultiTenancyConfig: &models.MultiTenancyConfig{
1705
+ Enabled: false,
1706
+ },
1707
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1708
+ },
1709
+ expectedError: fmt.Errorf("disabling multi-tenancy for an existing class is not supported"),
1710
+ },
1711
+ {
1712
+ name: "change auto tenant creation after creating the class",
1713
+ initial: &models.Class{
1714
+ Class: "InitialName",
1715
+ Vectorizer: "none",
1716
+ MultiTenancyConfig: &models.MultiTenancyConfig{
1717
+ Enabled: true,
1718
+ },
1719
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1720
+ },
1721
+ update: &models.Class{
1722
+ Class: "InitialName",
1723
+ Vectorizer: "none",
1724
+ MultiTenancyConfig: &models.MultiTenancyConfig{
1725
+ Enabled: true,
1726
+ AutoTenantCreation: true,
1727
+ },
1728
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1729
+ },
1730
+ expectedError: nil,
1731
+ },
1732
+ {
1733
+ name: "change auto tenant activation after creating the class",
1734
+ initial: &models.Class{
1735
+ Class: "InitialName",
1736
+ Vectorizer: "none",
1737
+ MultiTenancyConfig: &models.MultiTenancyConfig{
1738
+ Enabled: true,
1739
+ },
1740
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1741
+ },
1742
+ update: &models.Class{
1743
+ Class: "InitialName",
1744
+ Vectorizer: "none",
1745
+ MultiTenancyConfig: &models.MultiTenancyConfig{
1746
+ Enabled: true,
1747
+ AutoTenantActivation: true,
1748
+ },
1749
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1750
+ },
1751
+ expectedError: nil,
1752
+ },
1753
+ {
1754
+ name: "adding named vector on a class with legacy index",
1755
+ initial: &models.Class{
1756
+ Class: "InitialName",
1757
+ Vectorizer: "text2vec-contextionary",
1758
+ VectorIndexType: hnswT,
1759
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1760
+ },
1761
+ update: &models.Class{
1762
+ Class: "InitialName",
1763
+ Vectorizer: "text2vec-contextionary",
1764
+ VectorIndexType: hnswT,
1765
+ VectorConfig: map[string]models.VectorConfig{
1766
+ "vec1": {
1767
+ VectorIndexType: hnswT,
1768
+ Vectorizer: map[string]interface{}{
1769
+ "text2vec-contextionary": map[string]interface{}{},
1770
+ },
1771
+ },
1772
+ },
1773
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1774
+ },
1775
+ expectedError: nil,
1776
+ },
1777
+ {
1778
+ name: "adding new vector to a class with named vectors",
1779
+ initial: &models.Class{
1780
+ Class: "InitialName",
1781
+ VectorConfig: map[string]models.VectorConfig{
1782
+ "initial": {
1783
+ VectorIndexType: hnswT,
1784
+ Vectorizer: map[string]interface{}{
1785
+ "text2vec-contextionary": map[string]interface{}{},
1786
+ },
1787
+ },
1788
+ },
1789
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1790
+ },
1791
+ update: &models.Class{
1792
+ Class: "InitialName",
1793
+ VectorConfig: map[string]models.VectorConfig{
1794
+ "initial": {
1795
+ VectorIndexType: hnswT,
1796
+ Vectorizer: map[string]interface{}{
1797
+ "text2vec-contextionary": map[string]interface{}{},
1798
+ },
1799
+ },
1800
+ "new": {
1801
+ VectorIndexType: hnswT,
1802
+ Vectorizer: map[string]interface{}{
1803
+ "text2vec-contextionary": map[string]interface{}{},
1804
+ },
1805
+ },
1806
+ },
1807
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1808
+ },
1809
+ },
1810
+ {
1811
+ name: "adding legacy vector to a class with named vectors",
1812
+ initial: &models.Class{
1813
+ Class: "InitialName",
1814
+ VectorConfig: map[string]models.VectorConfig{
1815
+ "initial": {
1816
+ VectorIndexType: hnswT,
1817
+ Vectorizer: map[string]interface{}{
1818
+ "text2vec-contextionary": map[string]interface{}{},
1819
+ },
1820
+ },
1821
+ },
1822
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1823
+ },
1824
+ update: &models.Class{
1825
+ Class: "InitialName",
1826
+ Vectorizer: "text2vec-contextionary",
1827
+ VectorIndexType: hnswT,
1828
+ VectorConfig: map[string]models.VectorConfig{
1829
+ "initial": {
1830
+ VectorIndexType: hnswT,
1831
+ Vectorizer: map[string]interface{}{
1832
+ "text2vec-contextionary": map[string]interface{}{},
1833
+ },
1834
+ },
1835
+ },
1836
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1837
+ },
1838
+ expectedError: fmt.Errorf("vectorizer is immutable"),
1839
+ },
1840
+ {
1841
+ name: "removing existing named vector",
1842
+ initial: &models.Class{
1843
+ Class: "InitialName",
1844
+ VectorConfig: map[string]models.VectorConfig{
1845
+ "first": {
1846
+ VectorIndexType: hnswT,
1847
+ Vectorizer: map[string]interface{}{
1848
+ "text2vec-contextionary": map[string]interface{}{},
1849
+ },
1850
+ },
1851
+ "second": {
1852
+ VectorIndexType: hnswT,
1853
+ Vectorizer: map[string]interface{}{
1854
+ "text2vec-contextionary": map[string]interface{}{},
1855
+ },
1856
+ },
1857
+ },
1858
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1859
+ },
1860
+ update: &models.Class{
1861
+ Class: "InitialName",
1862
+ VectorConfig: map[string]models.VectorConfig{
1863
+ "first": {
1864
+ VectorIndexType: hnswT,
1865
+ Vectorizer: map[string]interface{}{
1866
+ "text2vec-contextionary": map[string]interface{}{},
1867
+ },
1868
+ },
1869
+ },
1870
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1871
+ },
1872
+ expectedError: fmt.Errorf(`missing config for vector "second"`),
1873
+ },
1874
+ {
1875
+ name: "removing existing legacy vector",
1876
+ initial: &models.Class{
1877
+ Class: "InitialName",
1878
+ Vectorizer: "text2vec-contextionary",
1879
+ VectorIndexType: hnswT,
1880
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1881
+ },
1882
+ update: &models.Class{
1883
+ Class: "InitialName",
1884
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1885
+ },
1886
+ expectedError: fmt.Errorf("vectorizer is immutable"),
1887
+ },
1888
+ {
1889
+ name: "adding named vector with reserved named on a collection with legacy index",
1890
+ initial: &models.Class{
1891
+ Class: "InitialName",
1892
+ Vectorizer: "text2vec-contextionary",
1893
+ VectorIndexType: hnswT,
1894
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1895
+ },
1896
+ update: &models.Class{
1897
+ Class: "InitialName",
1898
+ Vectorizer: "text2vec-contextionary",
1899
+ VectorIndexType: hnswT,
1900
+ VectorConfig: map[string]models.VectorConfig{
1901
+ modelsext.DefaultNamedVectorName: {
1902
+ VectorIndexType: hnswT,
1903
+ Vectorizer: map[string]interface{}{
1904
+ "text2vec-contextionary": map[string]interface{}{},
1905
+ },
1906
+ },
1907
+ },
1908
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
1909
+ },
1910
+ expectedError: fmt.Errorf("vector named %s cannot be created when collection level vector index is configured", modelsext.DefaultNamedVectorName),
1911
+ },
1912
+ }
1913
+
1914
+ for _, test := range tests {
1915
+ t.Run(test.name, func(t *testing.T) {
1916
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
1917
+ ctx := context.Background()
1918
+
1919
+ store := NewFakeStore()
1920
+ store.parser = handler.parser
1921
+
1922
+ fakeSchemaManager.On("AddClass", test.initial, mock.Anything).Return(nil)
1923
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
1924
+ fakeSchemaManager.On("UpdateClass", mock.Anything, mock.Anything).Return(nil)
1925
+ fakeSchemaManager.On("ReadOnlyClass", test.initial.Class, mock.Anything).Return(test.initial)
1926
+ fakeSchemaManager.On("QueryShardingState", mock.Anything).Return(nil, nil)
1927
+ if len(test.initial.Properties) > 0 {
1928
+ fakeSchemaManager.On("ReadOnlyClass", test.initial.Class, mock.Anything).Return(test.initial)
1929
+ }
1930
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(-1)
1931
+ _, _, err := handler.AddClass(ctx, nil, test.initial)
1932
+ assert.Nil(t, err)
1933
+ store.AddClass(test.initial)
1934
+
1935
+ fakeSchemaManager.On("UpdateClass", mock.Anything, mock.Anything).Return(nil)
1936
+ err = handler.UpdateClass(ctx, nil, test.initial.Class, test.update)
1937
+ if err == nil {
1938
+ err = store.UpdateClass(test.update)
1939
+ }
1940
+
1941
+ if test.expectedError == nil {
1942
+ assert.NoError(t, err)
1943
+ } else {
1944
+ assert.ErrorContains(t, err, test.expectedError.Error())
1945
+ }
1946
+ })
1947
+ }
1948
+ })
1949
+ }
1950
+
1951
+ func TestRestoreClass_WithCircularRefs(t *testing.T) {
1952
+ // When restoring a class, there could be circular refs between the classes,
1953
+ // thus any validation that checks if linked classes exist would fail on the
1954
+ // first class to import. Since we have no control over the order of imports
1955
+ // when restoring, we need to relax this validation.
1956
+
1957
+ t.Parallel()
1958
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
1959
+
1960
+ classes := []*models.Class{
1961
+ {
1962
+ Class: "Class_A",
1963
+ Properties: []*models.Property{{
1964
+ Name: "to_Class_B",
1965
+ DataType: []string{"Class_B"},
1966
+ }, {
1967
+ Name: "to_Class_C",
1968
+ DataType: []string{"Class_C"},
1969
+ }},
1970
+ Vectorizer: "none",
1971
+ },
1972
+
1973
+ {
1974
+ Class: "Class_B",
1975
+ Properties: []*models.Property{{
1976
+ Name: "to_Class_A",
1977
+ DataType: []string{"Class_A"},
1978
+ }, {
1979
+ Name: "to_Class_C",
1980
+ DataType: []string{"Class_C"},
1981
+ }},
1982
+ Vectorizer: "none",
1983
+ },
1984
+
1985
+ {
1986
+ Class: "Class_C",
1987
+ Properties: []*models.Property{{
1988
+ Name: "to_Class_A",
1989
+ DataType: []string{"Class_A"},
1990
+ }, {
1991
+ Name: "to_Class_B",
1992
+ DataType: []string{"Class_B"},
1993
+ }},
1994
+ Vectorizer: "none",
1995
+ },
1996
+ }
1997
+
1998
+ for _, classRaw := range classes {
1999
+ schemaBytes, err := json.Marshal(classRaw)
2000
+ require.Nil(t, err)
2001
+
2002
+ // for this particular test the sharding state does not matter, so we can
2003
+ // initiate any new sharding state
2004
+ shardingConfig, err := shardingConfig.ParseConfig(nil, 1)
2005
+ require.Nil(t, err)
2006
+
2007
+ nodes := mocks.NewMockNodeSelector("node1", "node2")
2008
+ shardingState, err := sharding.InitState(classRaw.Class, shardingConfig, nodes.LocalName(), nodes.StorageCandidates(), 1, false)
2009
+ require.Nil(t, err)
2010
+
2011
+ shardingBytes, err := shardingState.JSON()
2012
+ require.Nil(t, err)
2013
+
2014
+ descriptor := backup.ClassDescriptor{Name: classRaw.Class, Schema: schemaBytes, ShardingState: shardingBytes}
2015
+ fakeSchemaManager.On("RestoreClass", mock.Anything, mock.Anything).Return(nil)
2016
+ err = handler.RestoreClass(context.Background(), &descriptor, map[string]string{}, false)
2017
+ assert.Nil(t, err, "class passes validation")
2018
+ fakeSchemaManager.AssertExpectations(t)
2019
+ }
2020
+ }
2021
+
2022
+ func TestRestoreClass_WithNodeMapping(t *testing.T) {
2023
+ classes := []*models.Class{{
2024
+ Class: "Class_A",
2025
+ Vectorizer: "none",
2026
+ }}
2027
+
2028
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
2029
+
2030
+ for _, classRaw := range classes {
2031
+ schemaBytes, err := json.Marshal(classRaw)
2032
+ require.Nil(t, err)
2033
+
2034
+ shardingConfig, err := shardingConfig.ParseConfig(nil, 2)
2035
+ require.Nil(t, err)
2036
+
2037
+ nodes := mocks.NewMockNodeSelector("node1", "node2")
2038
+ shardingState, err := sharding.InitState(classRaw.Class, shardingConfig, nodes.LocalName(), nodes.StorageCandidates(), 2, false)
2039
+ require.Nil(t, err)
2040
+
2041
+ shardingBytes, err := shardingState.JSON()
2042
+ require.Nil(t, err)
2043
+
2044
+ descriptor := backup.ClassDescriptor{Name: classRaw.Class, Schema: schemaBytes, ShardingState: shardingBytes}
2045
+ expectedShardingState := shardingState
2046
+ expectedShardingState.ApplyNodeMapping(map[string]string{"node1": "new-node1"})
2047
+ expectedShardingState.SetLocalName("")
2048
+ fakeSchemaManager.On("RestoreClass", mock.Anything, shardingState).Return(nil)
2049
+ err = handler.RestoreClass(context.Background(), &descriptor, map[string]string{"node1": "new-node1"}, false)
2050
+ assert.NoError(t, err)
2051
+ }
2052
+ }
2053
+
2054
+ func Test_DeleteClass(t *testing.T) {
2055
+ t.Parallel()
2056
+ ctx := context.Background()
2057
+
2058
+ tests := []struct {
2059
+ name string
2060
+ classToDelete string
2061
+ expErr bool
2062
+ expErrMsg string
2063
+ existing []*models.Class
2064
+ expected []*models.Class
2065
+ }{
2066
+ {
2067
+ name: "class exists",
2068
+ classToDelete: "C1",
2069
+ existing: []*models.Class{
2070
+ {Class: "C1", VectorIndexType: "hnsw"},
2071
+ {Class: "OtherClass", VectorIndexType: "hnsw"},
2072
+ },
2073
+ expected: []*models.Class{
2074
+ classWithDefaultsSet(t, "OtherClass"),
2075
+ },
2076
+ expErr: false,
2077
+ },
2078
+ {
2079
+ name: "class does not exist",
2080
+ classToDelete: "C1",
2081
+ existing: []*models.Class{
2082
+ {Class: "OtherClass", VectorIndexType: "hnsw"},
2083
+ },
2084
+ expected: []*models.Class{
2085
+ classWithDefaultsSet(t, "OtherClass"),
2086
+ },
2087
+ expErr: false,
2088
+ },
2089
+ {
2090
+ name: "class delete should auto transform to GQL convention",
2091
+ classToDelete: "c1", // all lower case form
2092
+ existing: []*models.Class{
2093
+ {Class: "C1", VectorIndexType: "hnsw"}, // GQL form
2094
+ {Class: "OtherClass", VectorIndexType: "hnsw"},
2095
+ },
2096
+ expected: []*models.Class{
2097
+ classWithDefaultsSet(t, "OtherClass"), // should still delete `C1` class name
2098
+ },
2099
+ expErr: false,
2100
+ },
2101
+ }
2102
+
2103
+ for _, test := range tests {
2104
+ t.Run(test.name, func(t *testing.T) {
2105
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
2106
+
2107
+ // NOTE: mocking schema manager's `DeleteClass` (not handler's)
2108
+ // underlying schemaManager should still work with canonical class name.
2109
+ canonical := schema.UppercaseClassName(test.classToDelete)
2110
+ fakeSchemaManager.On("DeleteClass", canonical).Return(nil)
2111
+
2112
+ // but layer above like handler's `DeleteClass` should work independent of case sensitivity.
2113
+ err := handler.DeleteClass(ctx, nil, test.classToDelete)
2114
+ if test.expErr {
2115
+ require.NotNil(t, err)
2116
+ assert.Contains(t, err.Error(), test.expErrMsg)
2117
+ } else {
2118
+ require.Nil(t, err)
2119
+ }
2120
+ fakeSchemaManager.AssertExpectations(t)
2121
+ })
2122
+ }
2123
+ }
2124
+
2125
+ func Test_GetConsistentClass(t *testing.T) {
2126
+ t.Parallel()
2127
+ ctx := context.Background()
2128
+
2129
+ tests := []struct {
2130
+ name string
2131
+ classToGet string
2132
+ expErr bool
2133
+ expErrMsg string
2134
+ existing []*models.Class
2135
+ expected *models.Class
2136
+ }{
2137
+ {
2138
+ name: "class exists",
2139
+ classToGet: "C1",
2140
+ existing: []*models.Class{
2141
+ {Class: "C1", VectorIndexType: "hnsw"},
2142
+ {Class: "OtherClass", VectorIndexType: "hnsw"},
2143
+ },
2144
+ expected: classWithDefaultsSet(t, "C1"),
2145
+ expErr: false,
2146
+ },
2147
+ {
2148
+ name: "class does not exist",
2149
+ classToGet: "C1",
2150
+ existing: []*models.Class{
2151
+ {Class: "OtherClass", VectorIndexType: "hnsw"},
2152
+ },
2153
+ expected: &models.Class{}, // empty
2154
+ expErr: false,
2155
+ },
2156
+ {
2157
+ name: "class get should auto transform to GQL convention",
2158
+ classToGet: "c1", // lowercase
2159
+ existing: []*models.Class{
2160
+ {Class: "C1", VectorIndexType: "hnsw"}, // original class is GQL form
2161
+ {Class: "OtherClass", VectorIndexType: "hnsw"},
2162
+ },
2163
+ expected: classWithDefaultsSet(t, "C1"),
2164
+ expErr: false,
2165
+ },
2166
+ }
2167
+
2168
+ for _, test := range tests {
2169
+ t.Run(test.name, func(t *testing.T) {
2170
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
2171
+
2172
+ // underlying schemaManager should still work with canonical class name.
2173
+ canonical := schema.UppercaseClassName(test.classToGet)
2174
+ fakeSchemaManager.On("ReadOnlyClassWithVersion", mock.Anything, canonical, mock.Anything).Return(test.expected, nil)
2175
+
2176
+ // but layer above like `GetConsistentClass` should work independent of case sensitivity.
2177
+ got, _, err := handler.GetConsistentClass(ctx, nil, test.classToGet, false)
2178
+ if test.expErr {
2179
+ require.NotNil(t, err)
2180
+ assert.Contains(t, err.Error(), test.expErrMsg)
2181
+ } else {
2182
+ require.Nil(t, err)
2183
+ assert.Equal(t, got, test.expected)
2184
+ }
2185
+ fakeSchemaManager.AssertExpectations(t)
2186
+ })
2187
+ }
2188
+ }
2189
+
2190
+ func classWithDefaultsSet(t *testing.T, name string) *models.Class {
2191
+ class := &models.Class{Class: name, VectorIndexType: "hnsw"}
2192
+
2193
+ sc, err := shardingConfig.ParseConfig(map[string]interface{}{}, 1)
2194
+ require.Nil(t, err)
2195
+
2196
+ class.ShardingConfig = sc
2197
+
2198
+ class.VectorIndexConfig = fakeVectorConfig{}
2199
+ class.ReplicationConfig = &models.ReplicationConfig{Factor: 1}
2200
+
2201
+ return class
2202
+ }
2203
+
2204
+ func Test_AddClass_MultiTenancy(t *testing.T) {
2205
+ ctx := context.Background()
2206
+
2207
+ t.Run("with MT enabled and no optional settings", func(t *testing.T) {
2208
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
2209
+ class := models.Class{
2210
+ MultiTenancyConfig: &models.MultiTenancyConfig{Enabled: true},
2211
+ Class: "NewClass",
2212
+ Vectorizer: "none",
2213
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
2214
+ }
2215
+
2216
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
2217
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
2218
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(-1)
2219
+ c, _, err := handler.AddClass(ctx, nil, &class)
2220
+ require.Nil(t, err)
2221
+ assert.False(t, schema.AutoTenantCreationEnabled(c))
2222
+ assert.False(t, schema.AutoTenantActivationEnabled(c))
2223
+ })
2224
+
2225
+ t.Run("with MT enabled and all optional settings", func(t *testing.T) {
2226
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
2227
+ class := models.Class{
2228
+ MultiTenancyConfig: &models.MultiTenancyConfig{
2229
+ Enabled: true,
2230
+ AutoTenantCreation: true,
2231
+ AutoTenantActivation: true,
2232
+ },
2233
+ Class: "NewClass",
2234
+ Vectorizer: "none",
2235
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
2236
+ }
2237
+
2238
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
2239
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
2240
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(-1)
2241
+ c, _, err := handler.AddClass(ctx, nil, &class)
2242
+ require.Nil(t, err)
2243
+ assert.True(t, schema.AutoTenantCreationEnabled(c))
2244
+ assert.True(t, schema.AutoTenantActivationEnabled(c))
2245
+ })
2246
+
2247
+ t.Run("with MT disabled, but auto tenant creation on", func(t *testing.T) {
2248
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
2249
+ class := models.Class{
2250
+ MultiTenancyConfig: &models.MultiTenancyConfig{Enabled: false, AutoTenantCreation: true},
2251
+ Class: "NewClass",
2252
+ Vectorizer: "none",
2253
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
2254
+ }
2255
+
2256
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
2257
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
2258
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(-1)
2259
+ _, _, err := handler.AddClass(ctx, nil, &class)
2260
+ require.NotNil(t, err)
2261
+ })
2262
+
2263
+ t.Run("with MT disabled, but auto tenant activation on", func(t *testing.T) {
2264
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
2265
+ class := models.Class{
2266
+ MultiTenancyConfig: &models.MultiTenancyConfig{Enabled: false, AutoTenantActivation: true},
2267
+ Class: "NewClass",
2268
+ Vectorizer: "none",
2269
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
2270
+ }
2271
+
2272
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
2273
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
2274
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(-1)
2275
+ _, _, err := handler.AddClass(ctx, nil, &class)
2276
+ require.NotNil(t, err)
2277
+ })
2278
+ }
2279
+
2280
+ func Test_SetClassDefaults(t *testing.T) {
2281
+ globalCfg := replication.GlobalConfig{MinimumFactor: 3}
2282
+ tests := []struct {
2283
+ name string
2284
+ class *models.Class
2285
+ expectedError string
2286
+ expectedFactor int64
2287
+ }{
2288
+ {
2289
+ name: "ReplicationConfig is nil",
2290
+ class: &models.Class{},
2291
+ expectedError: "",
2292
+ expectedFactor: 3,
2293
+ },
2294
+ {
2295
+ name: "ReplicationConfig factor less than MinimumFactor",
2296
+ class: &models.Class{
2297
+ ReplicationConfig: &models.ReplicationConfig{
2298
+ Factor: 2,
2299
+ },
2300
+ },
2301
+ expectedError: "invalid replication factor: setup requires a minimum replication factor of 3: got 2",
2302
+ expectedFactor: 2,
2303
+ },
2304
+ {
2305
+ name: "ReplicationConfig factor less than 1",
2306
+ class: &models.Class{
2307
+ ReplicationConfig: &models.ReplicationConfig{
2308
+ Factor: 0,
2309
+ },
2310
+ },
2311
+ expectedError: "",
2312
+ expectedFactor: 3,
2313
+ },
2314
+ {
2315
+ name: "ReplicationConfig factor greater than or equal to MinimumFactor",
2316
+ class: &models.Class{
2317
+ ReplicationConfig: &models.ReplicationConfig{
2318
+ Factor: 4,
2319
+ },
2320
+ },
2321
+ expectedError: "",
2322
+ expectedFactor: 4,
2323
+ },
2324
+ }
2325
+
2326
+ for _, tt := range tests {
2327
+ t.Run(tt.name, func(t *testing.T) {
2328
+ handler, _ := newTestHandler(t, &fakeDB{})
2329
+ err := handler.setClassDefaults(tt.class, globalCfg)
2330
+ if tt.expectedError != "" {
2331
+ assert.EqualError(t, err, tt.expectedError)
2332
+ } else {
2333
+ assert.NoError(t, err)
2334
+ }
2335
+ assert.Equal(t, tt.expectedFactor, tt.class.ReplicationConfig.Factor)
2336
+ })
2337
+ }
2338
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/executor.go ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "fmt"
18
+ "runtime"
19
+ "sync"
20
+
21
+ "github.com/sirupsen/logrus"
22
+ schemaConfig "github.com/weaviate/weaviate/entities/schema/config"
23
+ "golang.org/x/exp/slices"
24
+
25
+ "github.com/weaviate/weaviate/cluster/proto/api"
26
+ enterrors "github.com/weaviate/weaviate/entities/errors"
27
+ "github.com/weaviate/weaviate/entities/models"
28
+ "github.com/weaviate/weaviate/entities/schema"
29
+ )
30
+
31
+ var _NUMCPU = runtime.GOMAXPROCS(0)
32
+
33
+ type executor struct {
34
+ schemaReader SchemaReader
35
+ migrator Migrator
36
+
37
+ callbacksLock sync.RWMutex
38
+ callbacks []func(updatedSchema schema.SchemaWithAliases)
39
+
40
+ logger logrus.FieldLogger
41
+ restoreClassDir func(string) error
42
+ }
43
+
44
+ // NewManager creates a new manager
45
+ func NewExecutor(migrator Migrator, sr SchemaReader,
46
+ logger logrus.FieldLogger, classBackupDir func(string) error,
47
+ ) *executor {
48
+ return &executor{
49
+ migrator: migrator,
50
+ logger: logger,
51
+ schemaReader: sr,
52
+ restoreClassDir: classBackupDir,
53
+ }
54
+ }
55
+
56
+ func (e *executor) Open(ctx context.Context) error {
57
+ return e.migrator.WaitForStartup(ctx)
58
+ }
59
+
60
+ // ReloadLocalDB reloads the local database using the latest schema.
61
+ func (e *executor) ReloadLocalDB(ctx context.Context, all []api.UpdateClassRequest) error {
62
+ cs := make([]*models.Class, len(all))
63
+
64
+ g, ctx := enterrors.NewErrorGroupWithContextWrapper(e.logger, ctx)
65
+ g.SetLimit(_NUMCPU * 2)
66
+
67
+ var errList error
68
+ var errMutex sync.Mutex
69
+
70
+ for i, u := range all {
71
+ i, u := i, u
72
+
73
+ g.Go(func() error {
74
+ e.logger.WithField("index", u.Class.Class).Info("reload local index")
75
+ cs[i] = u.Class
76
+
77
+ if err := e.migrator.UpdateIndex(ctx, u.Class, u.State); err != nil {
78
+ e.logger.WithField("index", u.Class.Class).WithError(err).Error("failed to reload local index")
79
+ err := fmt.Errorf("failed to reload local index %q: %w", i, err)
80
+
81
+ errMutex.Lock()
82
+ errList = errors.Join(errList, err)
83
+ errMutex.Unlock()
84
+ }
85
+ return nil
86
+ })
87
+ }
88
+
89
+ if err := g.Wait(); err != nil {
90
+ return err
91
+ }
92
+ return errList
93
+ }
94
+
95
+ func (e *executor) Close(ctx context.Context) error {
96
+ return e.migrator.Shutdown(ctx)
97
+ }
98
+
99
+ func (e *executor) AddClass(pl api.AddClassRequest) error {
100
+ ctx := context.Background()
101
+ if err := e.migrator.AddClass(ctx, pl.Class); err != nil {
102
+ return fmt.Errorf("apply add class: %w", err)
103
+ }
104
+ return nil
105
+ }
106
+
107
+ func (e *executor) AddReplicaToShard(class string, shard string, targetNode string) error {
108
+ ctx := context.Background()
109
+ if replicas, err := e.schemaReader.ShardReplicas(class, shard); err != nil {
110
+ return fmt.Errorf("error reading replicas for collection %s shard %s: %w", class, shard, err)
111
+ } else if !slices.Contains(replicas, targetNode) {
112
+ return fmt.Errorf("replica %s does not exists for collection %s shard %s", targetNode, class, shard)
113
+ }
114
+ return e.migrator.LoadShard(ctx, class, shard)
115
+ }
116
+
117
+ func (e *executor) DeleteReplicaFromShard(class string, shard string, targetNode string) error {
118
+ ctx := context.Background()
119
+ if replicas, err := e.schemaReader.ShardReplicas(class, shard); err != nil {
120
+ return fmt.Errorf("error reading replicas for collection %s shard %s: %w", class, shard, err)
121
+ } else if slices.Contains(replicas, targetNode) {
122
+ return fmt.Errorf("replica %s exists for collection %s shard %s", targetNode, class, shard)
123
+ }
124
+ return e.migrator.DropShard(ctx, class, shard)
125
+ }
126
+
127
+ func (e *executor) LoadShard(class string, shard string) {
128
+ ctx := context.Background()
129
+ if err := e.migrator.LoadShard(ctx, class, shard); err != nil {
130
+ e.logger.WithFields(logrus.Fields{
131
+ "action": "load_shard",
132
+ "class": class,
133
+ "shard": shard,
134
+ }).WithError(err).Warn("migrator")
135
+ }
136
+ }
137
+
138
+ func (e *executor) ShutdownShard(class string, shard string) {
139
+ ctx := context.Background()
140
+ if err := e.migrator.ShutdownShard(ctx, class, shard); err != nil {
141
+ e.logger.WithFields(logrus.Fields{
142
+ "action": "shutdown_shard",
143
+ "class": class,
144
+ "shard": shard,
145
+ }).WithError(err).Warn("migrator")
146
+ }
147
+ }
148
+
149
+ func (e *executor) DropShard(class string, shard string) {
150
+ ctx := context.Background()
151
+ if err := e.migrator.DropShard(ctx, class, shard); err != nil {
152
+ e.logger.WithFields(logrus.Fields{
153
+ "action": "drop_shard",
154
+ "class": class,
155
+ "shard": shard,
156
+ }).WithError(err).Warn("migrator")
157
+ }
158
+ }
159
+
160
+ // RestoreClassDir restores classes on the filesystem directly from the temporary class backup stored on disk.
161
+ // This function is invoked by the Raft store when a restoration request is sent by the backup coordinator.
162
+ func (e *executor) RestoreClassDir(class string) error {
163
+ return e.restoreClassDir(class)
164
+ }
165
+
166
+ func (e *executor) UpdateClass(req api.UpdateClassRequest) error {
167
+ className := req.Class.Class
168
+ ctx := context.Background()
169
+
170
+ if cfg, ok := req.Class.VectorIndexConfig.(schemaConfig.VectorIndexConfig); ok {
171
+ if err := e.migrator.UpdateVectorIndexConfig(ctx, className, cfg); err != nil {
172
+ return fmt.Errorf("vector index config update: %w", err)
173
+ }
174
+ }
175
+
176
+ if cfgs := asVectorIndexConfigs(req.Class); cfgs != nil {
177
+ if err := e.migrator.UpdateVectorIndexConfigs(ctx, className, cfgs); err != nil {
178
+ return fmt.Errorf("vector index configs update: %w", err)
179
+ }
180
+ }
181
+
182
+ if err := e.migrator.UpdateInvertedIndexConfig(ctx, className,
183
+ req.Class.InvertedIndexConfig); err != nil {
184
+ return fmt.Errorf("inverted index config: %w", err)
185
+ }
186
+
187
+ if err := e.migrator.UpdateReplicationConfig(ctx, className, req.Class.ReplicationConfig); err != nil {
188
+ return fmt.Errorf("update replication config: %w", err)
189
+ }
190
+
191
+ return nil
192
+ }
193
+
194
+ func (e *executor) UpdateIndex(req api.UpdateClassRequest) error {
195
+ ctx := context.Background()
196
+ if err := e.migrator.UpdateIndex(ctx, req.Class, req.State); err != nil {
197
+ return err
198
+ }
199
+ return nil
200
+ }
201
+
202
+ func (e *executor) DeleteClass(cls string, hasFrozen bool) error {
203
+ ctx := context.Background()
204
+ if err := e.migrator.DropClass(ctx, cls, hasFrozen); err != nil {
205
+ e.logger.WithFields(logrus.Fields{
206
+ "action": "delete_class",
207
+ "class": cls,
208
+ }).WithError(err).Errorf("migrator")
209
+ }
210
+
211
+ e.logger.WithFields(logrus.Fields{
212
+ "action": "delete_class",
213
+ "class": cls,
214
+ }).Debug("deleting class")
215
+
216
+ return nil
217
+ }
218
+
219
+ func (e *executor) AddProperty(className string, req api.AddPropertyRequest) error {
220
+ ctx := context.Background()
221
+ if err := e.migrator.AddProperty(ctx, className, req.Properties...); err != nil {
222
+ return err
223
+ }
224
+
225
+ e.logger.WithFields(logrus.Fields{
226
+ "action": "add_property",
227
+ "class": className,
228
+ }).Debug("adding property")
229
+ return nil
230
+ }
231
+
232
+ func (e *executor) AddTenants(class string, req *api.AddTenantsRequest) error {
233
+ if len(req.Tenants) == 0 {
234
+ return nil
235
+ }
236
+ updates := make([]*CreateTenantPayload, len(req.Tenants))
237
+ for i, p := range req.Tenants {
238
+ updates[i] = &CreateTenantPayload{
239
+ Name: p.Name,
240
+ Status: p.Status,
241
+ }
242
+ }
243
+ cls := e.schemaReader.ReadOnlyClass(class)
244
+ if cls == nil {
245
+ return fmt.Errorf("class %q: %w", class, ErrNotFound)
246
+ }
247
+ ctx := context.Background()
248
+ if err := e.migrator.NewTenants(ctx, cls, updates); err != nil {
249
+ return fmt.Errorf("migrator.new_tenants: %w", err)
250
+ }
251
+ return nil
252
+ }
253
+
254
+ func (e *executor) UpdateTenants(class string, req *api.UpdateTenantsRequest) error {
255
+ ctx := context.Background()
256
+ cls := e.schemaReader.ReadOnlyClass(class)
257
+ if cls == nil {
258
+ return fmt.Errorf("class %q: %w", class, ErrNotFound)
259
+ }
260
+
261
+ updates := make([]*UpdateTenantPayload, 0, len(req.Tenants))
262
+ for _, tu := range req.Tenants {
263
+ updates = append(updates, &UpdateTenantPayload{
264
+ Name: tu.Name,
265
+ Status: tu.Status,
266
+ })
267
+ }
268
+
269
+ if err := e.migrator.UpdateTenants(ctx, cls, updates, req.ImplicitUpdateRequest); err != nil {
270
+ e.logger.WithFields(logrus.Fields{
271
+ "action": "update_tenants",
272
+ "class": class,
273
+ }).WithError(err).Error("error updating tenants")
274
+ return err
275
+ }
276
+ return nil
277
+ }
278
+
279
+ func (e *executor) UpdateTenantsProcess(class string, req *api.TenantProcessRequest) error {
280
+ ctx := context.Background()
281
+ cls := e.schemaReader.ReadOnlyClass(class)
282
+ if cls == nil {
283
+ return fmt.Errorf("class %q: %w", class, ErrNotFound)
284
+ }
285
+ // no error here because that means the process shouldn't be applied to db
286
+ if req.TenantsProcesses == nil {
287
+ return nil
288
+ }
289
+
290
+ updates := []*UpdateTenantPayload{}
291
+ for idx := range req.TenantsProcesses {
292
+ if req.TenantsProcesses[idx] == nil || req.TenantsProcesses[idx].Tenant == nil {
293
+ continue
294
+ }
295
+ updates = append(updates, &UpdateTenantPayload{
296
+ Name: req.TenantsProcesses[idx].Tenant.Name,
297
+ Status: req.TenantsProcesses[idx].Tenant.Status,
298
+ })
299
+ }
300
+
301
+ if err := e.migrator.UpdateTenants(ctx, cls, updates, false); err != nil {
302
+ e.logger.WithFields(logrus.Fields{
303
+ "action": "update_tenants_process",
304
+ "sub-action": "update_tenants",
305
+ "class": class,
306
+ }).WithError(err).Error("error updating tenants")
307
+ return err
308
+ }
309
+ return nil
310
+ }
311
+
312
+ func (e *executor) DeleteTenants(class string, tenants []*models.Tenant) error {
313
+ ctx := context.Background()
314
+ if err := e.migrator.DeleteTenants(ctx, class, tenants); err != nil {
315
+ e.logger.WithFields(logrus.Fields{
316
+ "action": "delete_tenants",
317
+ "class": class,
318
+ }).WithError(err).Error("error deleting tenants")
319
+ }
320
+
321
+ return nil
322
+ }
323
+
324
+ func (e *executor) UpdateShardStatus(req *api.UpdateShardStatusRequest) error {
325
+ ctx := context.Background()
326
+ return e.migrator.UpdateShardStatus(ctx, req.Class, req.Shard, req.Status, req.SchemaVersion)
327
+ }
328
+
329
+ func (e *executor) GetShardsStatus(class, tenant string) (models.ShardStatusList, error) {
330
+ ctx := context.Background()
331
+ shardsStatus, err := e.migrator.GetShardsStatus(ctx, class, tenant)
332
+ if err != nil {
333
+ return nil, err
334
+ }
335
+
336
+ resp := models.ShardStatusList{}
337
+
338
+ for name, status := range shardsStatus {
339
+ resp = append(resp, &models.ShardStatusGetResponse{
340
+ Name: name,
341
+ Status: status,
342
+ })
343
+ }
344
+
345
+ return resp, nil
346
+ }
347
+
348
+ func (e *executor) TriggerSchemaUpdateCallbacks() {
349
+ e.callbacksLock.RLock()
350
+ defer e.callbacksLock.RUnlock()
351
+
352
+ s := e.schemaReader.ReadOnlySchema()
353
+ body := schema.SchemaWithAliases{
354
+ Schema: schema.Schema{Objects: &s},
355
+ Aliases: e.schemaReader.Aliases(),
356
+ }
357
+ for _, cb := range e.callbacks {
358
+ cb(body)
359
+ }
360
+ }
361
+
362
+ // RegisterSchemaUpdateCallback allows other usecases to register a primitive
363
+ // type update callback. The callbacks will be called any time we persist a
364
+ // schema update
365
+ func (e *executor) RegisterSchemaUpdateCallback(callback func(updatedSchema schema.SchemaWithAliases)) {
366
+ e.callbacksLock.Lock()
367
+ defer e.callbacksLock.Unlock()
368
+
369
+ e.callbacks = append(e.callbacks, callback)
370
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/executor_test.go ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "errors"
17
+ "testing"
18
+
19
+ "github.com/sirupsen/logrus/hooks/test"
20
+ "github.com/stretchr/testify/assert"
21
+ "github.com/stretchr/testify/mock"
22
+
23
+ "github.com/weaviate/weaviate/cluster/proto/api"
24
+ "github.com/weaviate/weaviate/entities/models"
25
+ "github.com/weaviate/weaviate/entities/schema"
26
+ "github.com/weaviate/weaviate/entities/vectorindex/flat"
27
+ )
28
+
29
+ var (
30
+ Anything = mock.Anything
31
+ ErrAny = errors.New("any error")
32
+ )
33
+
34
+ func newMockExecutor(m *fakeMigrator, s *fakeSchemaManager) *executor {
35
+ logger, _ := test.NewNullLogger()
36
+ x := NewExecutor(m, s, logger, func(string) error { return nil })
37
+ x.RegisterSchemaUpdateCallback(func(updatedSchema schema.SchemaWithAliases) {})
38
+ return x
39
+ }
40
+
41
+ func TestExecutor(t *testing.T) {
42
+ ctx := context.Background()
43
+ store := &fakeSchemaManager{}
44
+ cls := &models.Class{
45
+ Class: "A",
46
+ VectorIndexConfig: flat.NewDefaultUserConfig(),
47
+ ReplicationConfig: &models.ReplicationConfig{
48
+ Factor: 1,
49
+ },
50
+ }
51
+ store.On("ReadOnlySchema").Return(models.Schema{})
52
+ store.On("ReadOnlyClass", "A", mock.Anything).Return(cls)
53
+
54
+ t.Run("OpenClose", func(t *testing.T) {
55
+ migrator := &fakeMigrator{}
56
+ migrator.On("WaitForStartup", ctx).Return(nil)
57
+ migrator.On("Shutdown", ctx).Return(nil)
58
+ x := newMockExecutor(migrator, store)
59
+ assert.Nil(t, x.Open(ctx))
60
+ assert.Nil(t, x.Close(ctx))
61
+ })
62
+
63
+ t.Run("AddClass", func(t *testing.T) {
64
+ migrator := &fakeMigrator{}
65
+ migrator.On("AddClass", Anything, Anything, Anything).Return(nil)
66
+ x := newMockExecutor(migrator, store)
67
+ assert.Nil(t, x.AddClass(api.AddClassRequest{}))
68
+ })
69
+ t.Run("AddClassWithError", func(t *testing.T) {
70
+ migrator := &fakeMigrator{}
71
+ migrator.On("AddClass", Anything, Anything, Anything).Return(ErrAny)
72
+ x := newMockExecutor(migrator, store)
73
+ assert.ErrorIs(t, x.AddClass(api.AddClassRequest{}), ErrAny)
74
+ })
75
+
76
+ t.Run("DropClass", func(t *testing.T) {
77
+ migrator := &fakeMigrator{}
78
+ migrator.On("DropClass", Anything, Anything).Return(nil)
79
+ x := newMockExecutor(migrator, store)
80
+ assert.Nil(t, x.DeleteClass("A", false))
81
+ })
82
+ t.Run("DropClassWithError", func(t *testing.T) {
83
+ migrator := &fakeMigrator{}
84
+ migrator.On("DropClass", Anything, Anything).Return(ErrAny)
85
+ x := newMockExecutor(migrator, store)
86
+ assert.Nil(t, x.DeleteClass("A", false))
87
+ })
88
+
89
+ t.Run("UpdateIndex", func(t *testing.T) {
90
+ migrator := &fakeMigrator{}
91
+ migrator.On("UpdateVectorIndexConfig", Anything, "A", Anything).Return(nil)
92
+ migrator.On("UpdateInvertedIndexConfig", Anything, "A", Anything).Return(nil)
93
+ migrator.On("UpdateReplicationConfig", context.Background(), "A", false).Return(nil)
94
+
95
+ x := newMockExecutor(migrator, store)
96
+ assert.Nil(t, x.UpdateClass(api.UpdateClassRequest{Class: cls}))
97
+ })
98
+
99
+ t.Run("UpdateVectorIndexConfig", func(t *testing.T) {
100
+ migrator := &fakeMigrator{}
101
+ migrator.On("UpdateVectorIndexConfig", Anything, "A", Anything).Return(ErrAny)
102
+ migrator.On("UpdateReplicationConfig", context.Background(), "A", false).Return(nil)
103
+
104
+ x := newMockExecutor(migrator, store)
105
+ assert.ErrorIs(t, x.UpdateClass(api.UpdateClassRequest{Class: cls}), ErrAny)
106
+ })
107
+ t.Run("UpdateInvertedIndexConfig", func(t *testing.T) {
108
+ migrator := &fakeMigrator{}
109
+ migrator.On("UpdateVectorIndexConfig", Anything, "A", Anything).Return(nil)
110
+ migrator.On("UpdateInvertedIndexConfig", Anything, "A", Anything).Return(ErrAny)
111
+ migrator.On("UpdateReplicationConfig", context.Background(), "A", false).Return(nil)
112
+
113
+ x := newMockExecutor(migrator, store)
114
+ assert.ErrorIs(t, x.UpdateClass(api.UpdateClassRequest{Class: cls}), ErrAny)
115
+ })
116
+
117
+ t.Run("AddProperty", func(t *testing.T) {
118
+ migrator := &fakeMigrator{}
119
+ req := api.AddPropertyRequest{Properties: []*models.Property{}}
120
+ migrator.On("AddProperty", Anything, "A", req.Properties).Return(nil)
121
+ x := newMockExecutor(migrator, store)
122
+ assert.Nil(t, x.AddProperty("A", req))
123
+ })
124
+
125
+ tenants := []*api.Tenant{{Name: "T1"}, {Name: "T2"}}
126
+
127
+ t.Run("DeleteTenants", func(t *testing.T) {
128
+ migrator := &fakeMigrator{}
129
+ tenants := []*models.Tenant{}
130
+ migrator.On("DeleteTenants", Anything, "A", tenants).Return(nil)
131
+ x := newMockExecutor(migrator, store)
132
+ assert.Nil(t, x.DeleteTenants("A", tenants))
133
+ })
134
+ t.Run("DeleteTenantsWithError", func(t *testing.T) {
135
+ migrator := &fakeMigrator{}
136
+ tenants := []*models.Tenant{}
137
+ migrator.On("DeleteTenants", Anything, "A", tenants).Return(ErrAny)
138
+ x := newMockExecutor(migrator, store)
139
+ assert.Nil(t, x.DeleteTenants("A", tenants))
140
+ })
141
+
142
+ t.Run("UpdateTenants", func(t *testing.T) {
143
+ migrator := &fakeMigrator{}
144
+ req := &api.UpdateTenantsRequest{Tenants: tenants}
145
+ migrator.On("UpdateTenants", Anything, cls, Anything).Return(nil)
146
+ x := newMockExecutor(migrator, store)
147
+ assert.Nil(t, x.UpdateTenants("A", req))
148
+ })
149
+
150
+ t.Run("UpdateTenantsClassNotFound", func(t *testing.T) {
151
+ store := &fakeSchemaManager{}
152
+ store.On("ReadOnlyClass", "A", mock.Anything).Return(nil)
153
+
154
+ req := &api.UpdateTenantsRequest{Tenants: tenants}
155
+ x := newMockExecutor(&fakeMigrator{}, store)
156
+ assert.ErrorIs(t, x.UpdateTenants("A", req), ErrNotFound)
157
+ })
158
+
159
+ t.Run("UpdateTenantsError", func(t *testing.T) {
160
+ migrator := &fakeMigrator{}
161
+ req := &api.UpdateTenantsRequest{Tenants: tenants}
162
+ migrator.On("UpdateTenants", Anything, cls, Anything).Return(ErrAny)
163
+ x := newMockExecutor(migrator, store)
164
+ assert.ErrorIs(t, x.UpdateTenants("A", req), ErrAny)
165
+ })
166
+
167
+ t.Run("AddTenants", func(t *testing.T) {
168
+ migrator := &fakeMigrator{}
169
+ req := &api.AddTenantsRequest{Tenants: tenants}
170
+ migrator.On("NewTenants", Anything, cls, Anything).Return(nil)
171
+ x := newMockExecutor(migrator, store)
172
+ assert.Nil(t, x.AddTenants("A", req))
173
+ })
174
+ t.Run("AddTenantsEmpty", func(t *testing.T) {
175
+ migrator := &fakeMigrator{}
176
+ req := &api.AddTenantsRequest{Tenants: nil}
177
+ x := newMockExecutor(migrator, store)
178
+ assert.Nil(t, x.AddTenants("A", req))
179
+ })
180
+ t.Run("AddTenantsError", func(t *testing.T) {
181
+ migrator := &fakeMigrator{}
182
+ req := &api.AddTenantsRequest{Tenants: tenants}
183
+ migrator.On("NewTenants", Anything, cls, Anything).Return(ErrAny)
184
+ x := newMockExecutor(migrator, store)
185
+ assert.ErrorIs(t, x.AddTenants("A", req), ErrAny)
186
+ })
187
+ t.Run("AddTenantsClassNotFound", func(t *testing.T) {
188
+ store := &fakeSchemaManager{}
189
+ store.On("ReadOnlyClass", "A", mock.Anything).Return(nil)
190
+ req := &api.AddTenantsRequest{Tenants: tenants}
191
+ x := newMockExecutor(&fakeMigrator{}, store)
192
+ assert.ErrorIs(t, x.AddTenants("A", req), ErrNotFound)
193
+ })
194
+
195
+ t.Run("GetShardsStatus", func(t *testing.T) {
196
+ migrator := &fakeMigrator{}
197
+ status := map[string]string{"A": "B"}
198
+ migrator.On("GetShardsStatus", Anything, "A", "").Return(status, nil)
199
+ x := newMockExecutor(migrator, store)
200
+ _, err := x.GetShardsStatus("A", "")
201
+ assert.Nil(t, err)
202
+ })
203
+ t.Run("GetShardsStatusError", func(t *testing.T) {
204
+ migrator := &fakeMigrator{}
205
+ status := map[string]string{"A": "B"}
206
+ migrator.On("GetShardsStatus", Anything, "A", "").Return(status, ErrAny)
207
+ x := newMockExecutor(migrator, store)
208
+ _, err := x.GetShardsStatus("A", "")
209
+ assert.ErrorIs(t, err, ErrAny)
210
+ })
211
+ t.Run("UpdateShardStatus", func(t *testing.T) {
212
+ migrator := &fakeMigrator{}
213
+ req := &api.UpdateShardStatusRequest{Class: "A", Shard: "S", Status: "ST", SchemaVersion: 123}
214
+ migrator.On("UpdateShardStatus", Anything, "A", "S", "ST", uint64(123)).Return(nil)
215
+ x := newMockExecutor(migrator, store)
216
+ assert.Nil(t, x.UpdateShardStatus(req))
217
+ })
218
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/fakes_test.go ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "encoding/json"
17
+ "fmt"
18
+
19
+ "github.com/stretchr/testify/mock"
20
+ command "github.com/weaviate/weaviate/cluster/proto/api"
21
+ clusterSchema "github.com/weaviate/weaviate/cluster/schema"
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/entities/versioned"
24
+ "github.com/weaviate/weaviate/usecases/fakes"
25
+ "github.com/weaviate/weaviate/usecases/sharding"
26
+ )
27
+
28
+ type fakeSchemaManager struct {
29
+ mock.Mock
30
+ countClassEqual bool
31
+ }
32
+
33
+ func (f *fakeSchemaManager) AddClass(_ context.Context, cls *models.Class, ss *sharding.State) (uint64, error) {
34
+ args := f.Called(cls, ss)
35
+ return 0, args.Error(0)
36
+ }
37
+
38
+ func (f *fakeSchemaManager) RestoreClass(_ context.Context, cls *models.Class, ss *sharding.State) (uint64, error) {
39
+ args := f.Called(cls, ss)
40
+ return 0, args.Error(0)
41
+ }
42
+
43
+ func (f *fakeSchemaManager) UpdateClass(_ context.Context, cls *models.Class, ss *sharding.State) (uint64, error) {
44
+ args := f.Called(cls, ss)
45
+ return 0, args.Error(0)
46
+ }
47
+
48
+ func (f *fakeSchemaManager) DeleteClass(_ context.Context, name string) (uint64, error) {
49
+ args := f.Called(name)
50
+ return 0, args.Error(0)
51
+ }
52
+
53
+ func (f *fakeSchemaManager) AddProperty(_ context.Context, class string, p ...*models.Property) (uint64, error) {
54
+ args := f.Called(class, p)
55
+ return 0, args.Error(0)
56
+ }
57
+
58
+ func (f *fakeSchemaManager) UpdateShardStatus(c_ context.Context, class, shard, status string) (uint64, error) {
59
+ args := f.Called(class, shard, status)
60
+ return 0, args.Error(0)
61
+ }
62
+
63
+ func (f *fakeSchemaManager) AddTenants(_ context.Context, class string, req *command.AddTenantsRequest) (uint64, error) {
64
+ args := f.Called(class, req)
65
+ return 0, args.Error(0)
66
+ }
67
+
68
+ func (f *fakeSchemaManager) UpdateTenants(_ context.Context, class string, req *command.UpdateTenantsRequest) (uint64, error) {
69
+ args := f.Called(class, req)
70
+ return 0, args.Error(0)
71
+ }
72
+
73
+ func (f *fakeSchemaManager) DeleteTenants(_ context.Context, class string, req *command.DeleteTenantsRequest) (uint64, error) {
74
+ args := f.Called(class, req)
75
+ return 0, args.Error(0)
76
+ }
77
+
78
+ func (f *fakeSchemaManager) ResolveAlias(alias string) string {
79
+ return ""
80
+ }
81
+
82
+ func (f *fakeSchemaManager) GetAliasesForClass(class string) []*models.Alias {
83
+ return nil
84
+ }
85
+
86
+ func (f *fakeSchemaManager) Join(ctx context.Context, nodeID, raftAddr string, voter bool) error {
87
+ args := f.Called(ctx, nodeID, raftAddr, voter)
88
+ return args.Error(0)
89
+ }
90
+
91
+ func (f *fakeSchemaManager) Remove(ctx context.Context, nodeID string) error {
92
+ args := f.Called(ctx, nodeID)
93
+ return args.Error(0)
94
+ }
95
+
96
+ func (f *fakeSchemaManager) Stats() map[string]any {
97
+ return map[string]any{}
98
+ }
99
+
100
+ func (f *fakeSchemaManager) StoreSchemaV1() error {
101
+ return nil
102
+ }
103
+
104
+ func (f *fakeSchemaManager) ClassEqual(name string) string {
105
+ if f.countClassEqual {
106
+ args := f.Called(name)
107
+ return args.String(0)
108
+ }
109
+ return ""
110
+ }
111
+
112
+ func (f *fakeSchemaManager) MultiTenancy(class string) models.MultiTenancyConfig {
113
+ args := f.Called(class)
114
+ return args.Get(0).(models.MultiTenancyConfig)
115
+ }
116
+
117
+ func (f *fakeSchemaManager) MultiTenancyWithVersion(ctx context.Context, class string, version uint64) (models.MultiTenancyConfig, error) {
118
+ args := f.Called(ctx, class, version)
119
+ return args.Get(0).(models.MultiTenancyConfig), args.Error(1)
120
+ }
121
+
122
+ func (f *fakeSchemaManager) ClassInfo(class string) (ci clusterSchema.ClassInfo) {
123
+ args := f.Called(class)
124
+ return args.Get(0).(clusterSchema.ClassInfo)
125
+ }
126
+
127
+ func (f *fakeSchemaManager) StorageCandidates() []string {
128
+ return []string{"node-1"}
129
+ }
130
+
131
+ func (f *fakeSchemaManager) ClassInfoWithVersion(ctx context.Context, class string, version uint64) (clusterSchema.ClassInfo, error) {
132
+ args := f.Called(ctx, class, version)
133
+ return args.Get(0).(clusterSchema.ClassInfo), args.Error(1)
134
+ }
135
+
136
+ func (f *fakeSchemaManager) QuerySchema() (models.Schema, error) {
137
+ args := f.Called()
138
+ return args.Get(0).(models.Schema), args.Error(1)
139
+ }
140
+
141
+ func (f *fakeSchemaManager) QueryCollectionsCount() (int, error) {
142
+ args := f.Called()
143
+ return args.Get(0).(int), args.Error(1)
144
+ }
145
+
146
+ func (f *fakeSchemaManager) QueryReadOnlyClasses(classes ...string) (map[string]versioned.Class, error) {
147
+ args := f.Called(classes)
148
+
149
+ models := args.Get(0)
150
+ if models == nil {
151
+ return nil, args.Error(1)
152
+ }
153
+
154
+ return models.(map[string]versioned.Class), nil
155
+ }
156
+
157
+ func (f *fakeSchemaManager) QueryClassVersions(classes ...string) (map[string]uint64, error) {
158
+ args := f.Called(classes)
159
+
160
+ models := args.Get(0)
161
+ if models == nil {
162
+ return nil, args.Error(1)
163
+ }
164
+
165
+ return models.(map[string]uint64), nil
166
+ }
167
+
168
+ func (f *fakeSchemaManager) QueryTenants(class string, tenants []string) ([]*models.Tenant, uint64, error) {
169
+ args := f.Called(class, tenants)
170
+ return args.Get(0).([]*models.Tenant), 0, args.Error(2)
171
+ }
172
+
173
+ func (f *fakeSchemaManager) QueryShardOwner(class, shard string) (string, uint64, error) {
174
+ args := f.Called(class, shard)
175
+ return args.Get(0).(string), 0, args.Error(0)
176
+ }
177
+
178
+ func (f *fakeSchemaManager) QueryTenantsShards(class string, tenants ...string) (map[string]string, uint64, error) {
179
+ args := f.Called(class, tenants)
180
+ res := map[string]string{}
181
+ for idx := range tenants {
182
+ res[args.String(idx+1)] = ""
183
+ }
184
+ return res, 0, nil
185
+ }
186
+
187
+ func (f *fakeSchemaManager) QueryShardingState(class string) (*sharding.State, uint64, error) {
188
+ args := f.Called(class)
189
+ return args.Get(0).(*sharding.State), 0, args.Error(0)
190
+ }
191
+
192
+ func (f *fakeSchemaManager) ReadOnlyClass(class string) *models.Class {
193
+ args := f.Called(class)
194
+ model := args.Get(0)
195
+ if model == nil {
196
+ return nil
197
+ }
198
+ return model.(*models.Class)
199
+ }
200
+
201
+ func (f *fakeSchemaManager) ReadOnlyVersionedClass(class string) versioned.Class {
202
+ args := f.Called(class)
203
+ model := args.Get(0)
204
+ return model.(versioned.Class)
205
+ }
206
+
207
+ func (f *fakeSchemaManager) ReadOnlyClassWithVersion(ctx context.Context, class string, version uint64) (*models.Class, error) {
208
+ args := f.Called(ctx, class, version)
209
+ model := args.Get(0)
210
+ if model == nil {
211
+ return nil, args.Error(1)
212
+ }
213
+ return model.(*models.Class), args.Error(1)
214
+ }
215
+
216
+ func (f *fakeSchemaManager) ReadOnlySchema() models.Schema {
217
+ args := f.Called()
218
+ return args.Get(0).(models.Schema)
219
+ }
220
+
221
+ func (f *fakeSchemaManager) Aliases() map[string]string {
222
+ return nil
223
+ }
224
+
225
+ func (f *fakeSchemaManager) ShardReplicas(class, shard string) ([]string, error) {
226
+ args := f.Called(class, shard)
227
+ return args.Get(0).([]string), args.Error(1)
228
+ }
229
+
230
+ func (f *fakeSchemaManager) ShardReplicasWithVersion(ctx context.Context, class, shard string, version uint64) ([]string, error) {
231
+ args := f.Called(ctx, class, shard, version)
232
+ return args.Get(0).([]string), args.Error(1)
233
+ }
234
+
235
+ func (f *fakeSchemaManager) ShardFromUUID(class string, uuid []byte) string {
236
+ args := f.Called(class, uuid)
237
+ return args.String(0)
238
+ }
239
+
240
+ func (f *fakeSchemaManager) ShardFromUUIDWithVersion(ctx context.Context, class string, uuid []byte, version uint64) (string, error) {
241
+ args := f.Called(ctx, class, uuid, version)
242
+ return args.String(0), args.Error(1)
243
+ }
244
+
245
+ func (f *fakeSchemaManager) ShardOwner(class, shard string) (string, error) {
246
+ args := f.Called(class, shard)
247
+ return args.String(0), args.Error(1)
248
+ }
249
+
250
+ func (f *fakeSchemaManager) ShardOwnerWithVersion(ctx context.Context, class, shard string, version uint64) (string, error) {
251
+ args := f.Called(ctx, class, shard, version)
252
+ return args.String(0), args.Error(1)
253
+ }
254
+
255
+ func (f *fakeSchemaManager) TenantsShardsWithVersion(ctx context.Context, version uint64, class string, tenants ...string) (tenantShards map[string]string, err error) {
256
+ args := f.Called(ctx, version, class, tenants)
257
+ return map[string]string{args.String(0): args.String(1)}, args.Error(2)
258
+ }
259
+
260
+ func (f *fakeSchemaManager) Read(class string, reader func(*models.Class, *sharding.State) error) error {
261
+ args := f.Called(class, reader)
262
+ return args.Error(0)
263
+ }
264
+
265
+ func (f *fakeSchemaManager) Shards(class string) ([]string, error) {
266
+ args := f.Called(class)
267
+ return args.Get(0).([]string), args.Error(1)
268
+ }
269
+
270
+ func (f *fakeSchemaManager) LocalShards(class string) ([]string, error) {
271
+ args := f.Called(class)
272
+ return args.Get(0).([]string), args.Error(1)
273
+ }
274
+
275
+ func (f *fakeSchemaManager) GetShardsStatus(class, tenant string) (models.ShardStatusList, error) {
276
+ args := f.Called(class, tenant)
277
+ return args.Get(0).(models.ShardStatusList), args.Error(1)
278
+ }
279
+
280
+ func (f *fakeSchemaManager) WaitForUpdate(ctx context.Context, schemaVersion uint64) error {
281
+ return nil
282
+ }
283
+
284
+ func (f *fakeSchemaManager) CreateAlias(ctx context.Context, alias string, class *models.Class) (uint64, error) {
285
+ args := f.Called(ctx, alias, class)
286
+ return 0, args.Error(0)
287
+ }
288
+
289
+ func (f *fakeSchemaManager) ReplaceAlias(ctx context.Context, alias *models.Alias, newClass *models.Class) (uint64, error) {
290
+ args := f.Called(ctx, alias, newClass)
291
+ return 0, args.Error(0)
292
+ }
293
+
294
+ func (f *fakeSchemaManager) DeleteAlias(ctx context.Context, alias string) (uint64, error) {
295
+ args := f.Called(ctx, alias)
296
+ return 0, args.Error(0)
297
+ }
298
+
299
+ func (f *fakeSchemaManager) GetAlias(ctx context.Context, alias string) (*models.Alias, error) {
300
+ args := f.Called(ctx, alias)
301
+ return args.Get(0).(*models.Alias), args.Error(1)
302
+ }
303
+
304
+ func (f *fakeSchemaManager) GetAliases(ctx context.Context, alias string, class *models.Class) ([]*models.Alias, error) {
305
+ args := f.Called(ctx, alias, class)
306
+ return args.Get(0).([]*models.Alias), args.Error(1)
307
+ }
308
+
309
+ type fakeStore struct {
310
+ collections map[string]*models.Class
311
+ parser Parser
312
+ }
313
+
314
+ func NewFakeStore() *fakeStore {
315
+ return &fakeStore{
316
+ collections: make(map[string]*models.Class),
317
+ parser: *NewParser(fakes.NewFakeClusterState(), dummyParseVectorConfig, &fakeValidator{}, fakeModulesProvider{}, nil),
318
+ }
319
+ }
320
+
321
+ func (f *fakeStore) AddClass(cls *models.Class) {
322
+ f.collections[cls.Class] = cls
323
+ }
324
+
325
+ func (f *fakeStore) UpdateClass(cls *models.Class) error {
326
+ bytes, err := json.Marshal(cls)
327
+ if err != nil {
328
+ return fmt.Errorf("marshal request: %w", err)
329
+ }
330
+
331
+ cls = f.collections[cls.Class]
332
+ if cls == nil {
333
+ return ErrNotFound
334
+ }
335
+
336
+ cls2 := &models.Class{}
337
+ if err := json.Unmarshal(bytes, cls2); err != nil {
338
+ return fmt.Errorf("unmarshal: %w", err)
339
+ }
340
+
341
+ u, err := f.parser.ParseClassUpdate(cls, cls2)
342
+ if err != nil {
343
+ return fmt.Errorf("parse class update: %w", err)
344
+ }
345
+
346
+ cls.VectorIndexConfig = u.VectorIndexConfig
347
+ cls.InvertedIndexConfig = u.InvertedIndexConfig
348
+ return nil
349
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/get_class.go ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "github.com/sirupsen/logrus"
16
+ "github.com/weaviate/weaviate/entities/versioned"
17
+ configRuntime "github.com/weaviate/weaviate/usecases/config/runtime"
18
+ )
19
+
20
+ type ClassGetter struct {
21
+ parser *Parser
22
+ schemaReader SchemaReader
23
+ schemaManager SchemaManager
24
+ logger logrus.FieldLogger
25
+
26
+ collectionRetrievalStrategy *configRuntime.FeatureFlag[string]
27
+ }
28
+
29
+ func NewClassGetter(
30
+ schemaParser *Parser,
31
+ schemaManager SchemaManager,
32
+ schemaReader SchemaReader,
33
+ collectionRetrievalStrategyFF *configRuntime.FeatureFlag[string],
34
+ logger logrus.FieldLogger,
35
+ ) *ClassGetter {
36
+ return &ClassGetter{
37
+ parser: schemaParser,
38
+ schemaReader: schemaReader,
39
+ schemaManager: schemaManager,
40
+ logger: logger,
41
+ collectionRetrievalStrategy: collectionRetrievalStrategyFF,
42
+ }
43
+ }
44
+
45
+ func (cg *ClassGetter) getClasses(names []string) (map[string]versioned.Class, error) {
46
+ switch configRuntime.CollectionRetrievalStrategy(cg.collectionRetrievalStrategy.Get()) {
47
+ case configRuntime.LeaderOnly:
48
+ return cg.getClassesLeaderOnly(names)
49
+ case configRuntime.LeaderOnMismatch:
50
+ return cg.getClassesLeaderOnMismatch(names)
51
+ case configRuntime.LocalOnly:
52
+ return cg.getClassesLocalOnly(names)
53
+
54
+ // This can happen if the feature flag gets configured with an invalid strategy
55
+ default:
56
+ return cg.getClassesLeaderOnly(names)
57
+ }
58
+ }
59
+
60
+ func (cg *ClassGetter) getClassesLeaderOnly(names []string) (map[string]versioned.Class, error) {
61
+ vclasses, err := cg.schemaManager.QueryReadOnlyClasses(names...)
62
+ if err != nil {
63
+ return nil, err
64
+ }
65
+
66
+ if len(vclasses) == 0 {
67
+ return nil, nil
68
+ }
69
+
70
+ for _, vclass := range vclasses {
71
+ if err := cg.parser.ParseClass(vclass.Class); err != nil {
72
+ // remove invalid classes
73
+ cg.logger.WithFields(logrus.Fields{
74
+ "class": vclass.Class.Class,
75
+ "error": err,
76
+ }).Warn("parsing class error")
77
+ delete(vclasses, vclass.Class.Class)
78
+ continue
79
+ }
80
+ }
81
+
82
+ return vclasses, nil
83
+ }
84
+
85
+ func (cg *ClassGetter) getClassesLocalOnly(names []string) (map[string]versioned.Class, error) {
86
+ vclasses := map[string]versioned.Class{}
87
+ for _, name := range names {
88
+ vc := cg.schemaReader.ReadOnlyVersionedClass(name)
89
+ if vc.Class == nil {
90
+ cg.logger.WithFields(logrus.Fields{
91
+ "class": name,
92
+ }).Debug("could not find class in local schema")
93
+ continue
94
+ }
95
+ vclasses[name] = vc
96
+ }
97
+
98
+ // Check if we have all the classes from the local schema
99
+ if len(vclasses) < len(names) {
100
+ missingClasses := []string{}
101
+ for _, name := range names {
102
+ if _, ok := vclasses[name]; !ok {
103
+ missingClasses = append(missingClasses, name)
104
+ }
105
+ }
106
+ cg.logger.WithFields(logrus.Fields{
107
+ "missing": missingClasses,
108
+ "suggestion": "This node received a data request for a class that is not present on the local schema on the node. If the class was just updated in the schema and you want to be able to query it immediately consider changing the " + configRuntime.CollectionRetrievalStrategyEnvVariable + " config to \"" + configRuntime.LeaderOnly + "\".",
109
+ }).Warn("not all classes found locally")
110
+ }
111
+ return vclasses, nil
112
+ }
113
+
114
+ func (cg *ClassGetter) getClassesLeaderOnMismatch(names []string) (map[string]versioned.Class, error) {
115
+ classVersions, err := cg.schemaManager.QueryClassVersions(names...)
116
+ if err != nil {
117
+ return nil, err
118
+ }
119
+ versionedClassesToReturn := map[string]versioned.Class{}
120
+ versionedClassesToQueryFromLeader := []string{}
121
+ for _, name := range names {
122
+ localVclass := cg.schemaReader.ReadOnlyVersionedClass(name)
123
+ // First check if we have the class locally, if not make sure we'll query from leader
124
+ if localVclass.Class == nil {
125
+ versionedClassesToQueryFromLeader = append(versionedClassesToQueryFromLeader, name)
126
+ continue
127
+ }
128
+
129
+ // We have the class locally, compare the version from leader (if any) and add to query to leader if we have to refresh the version
130
+ leaderClassVersion, ok := classVersions[name]
131
+ // < leaderClassVersion instead of != because there is some chance that the local version
132
+ // could be ahead of the version returned by the leader if the response from the leader was
133
+ // delayed and i don't think it would be helpful to query the leader again in that case as
134
+ // it would likely return a version that is at least as large as the local version.
135
+ if !ok || localVclass.Version < leaderClassVersion {
136
+ versionedClassesToQueryFromLeader = append(versionedClassesToQueryFromLeader, name)
137
+ continue
138
+ }
139
+
140
+ // We can use the local class version has not changed
141
+ versionedClassesToReturn[name] = localVclass
142
+ }
143
+ if len(versionedClassesToQueryFromLeader) == 0 {
144
+ return versionedClassesToReturn, nil
145
+ }
146
+
147
+ versionedClassesFromLeader, err := cg.schemaManager.QueryReadOnlyClasses(versionedClassesToQueryFromLeader...)
148
+ if err != nil || len(versionedClassesFromLeader) == 0 {
149
+ cg.logger.WithFields(logrus.Fields{
150
+ "classes": versionedClassesToQueryFromLeader,
151
+ "error": err,
152
+ "suggestion": "This node received a data request for a class that is not present on the local schema on the node. If the class was just updated in the schema and you want to be able to query it immediately consider changing the " + configRuntime.CollectionRetrievalStrategyEnvVariable + " config to \"" + configRuntime.LeaderOnly + "\".",
153
+ }).Warn("unable to query classes from leader")
154
+ // return as many classes as we could get (to match previous behavior of the caller)
155
+ return versionedClassesToReturn, err
156
+ }
157
+
158
+ // We only need to ParseClass the ones we receive from the leader due to the Class model containing `interface{}` that are broken on
159
+ // marshall/unmarshall with gRPC.
160
+ for _, vclass := range versionedClassesFromLeader {
161
+ if err := cg.parser.ParseClass(vclass.Class); err != nil {
162
+ // silently remove invalid classes to match previous behavior
163
+ cg.logger.WithFields(logrus.Fields{
164
+ "class": vclass.Class.Class,
165
+ "error": err,
166
+ }).Warn("parsing class error")
167
+ delete(versionedClassesFromLeader, vclass.Class.Class)
168
+ continue
169
+ }
170
+ versionedClassesToReturn[vclass.Class.Class] = vclass
171
+ }
172
+
173
+ return versionedClassesToReturn, nil
174
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/get_class_test.go ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "testing"
16
+
17
+ "github.com/sirupsen/logrus/hooks/test"
18
+ "github.com/stretchr/testify/require"
19
+ "github.com/weaviate/weaviate/entities/models"
20
+ "github.com/weaviate/weaviate/entities/versioned"
21
+ configRuntime "github.com/weaviate/weaviate/usecases/config/runtime"
22
+ shardingCfg "github.com/weaviate/weaviate/usecases/sharding/config"
23
+ )
24
+
25
+ func TestClassGetterFromSchema(t *testing.T) {
26
+ testCases := []struct {
27
+ name string
28
+ getFromSchema []string
29
+ strategy configRuntime.CollectionRetrievalStrategy
30
+ schemaExpect func(*fakeSchemaManager)
31
+ }{
32
+ {
33
+ name: "Read only from leader",
34
+ getFromSchema: []string{"class1", "class2", "class3"},
35
+ strategy: configRuntime.LeaderOnly,
36
+ schemaExpect: func(f *fakeSchemaManager) {
37
+ f.On("QueryReadOnlyClasses", []string{"class1", "class2", "class3"}).Return(map[string]versioned.Class{
38
+ "class1": {Version: 1, Class: &models.Class{Class: "class1", VectorIndexType: "hnsw", ShardingConfig: make(map[string]interface{})}},
39
+ "class2": {Version: 2, Class: &models.Class{Class: "class2", VectorIndexType: "hnsw", ShardingConfig: make(map[string]interface{})}},
40
+ "class3": {Version: 3, Class: &models.Class{Class: "class3", VectorIndexType: "hnsw", ShardingConfig: make(map[string]interface{})}},
41
+ }, nil)
42
+ },
43
+ },
44
+ {
45
+ name: "Read only from local",
46
+ getFromSchema: []string{"class1", "class2", "class3"},
47
+ strategy: configRuntime.LocalOnly,
48
+ schemaExpect: func(f *fakeSchemaManager) {
49
+ f.On("ReadOnlyVersionedClass", "class1").Return(versioned.Class{Version: 1, Class: &models.Class{Class: "class1", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
50
+ f.On("ReadOnlyVersionedClass", "class2").Return(versioned.Class{Version: 2, Class: &models.Class{Class: "class2", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
51
+ f.On("ReadOnlyVersionedClass", "class3").Return(versioned.Class{Version: 3, Class: &models.Class{Class: "class3", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
52
+ },
53
+ },
54
+ {
55
+ name: "Read all from leader if mismatch",
56
+ getFromSchema: []string{"class1", "class2", "class3"},
57
+ strategy: configRuntime.LeaderOnMismatch,
58
+ schemaExpect: func(f *fakeSchemaManager) {
59
+ // First we will query the versions from the leader
60
+ f.On("QueryClassVersions", []string{"class1", "class2", "class3"}).Return(map[string]uint64{
61
+ "class1": 4,
62
+ "class2": 5,
63
+ "class3": 6,
64
+ }, nil)
65
+ // Then we check the local version
66
+ f.On("ReadOnlyVersionedClass", "class1").Return(versioned.Class{Version: 1, Class: &models.Class{Class: "class1", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
67
+ f.On("ReadOnlyVersionedClass", "class2").Return(versioned.Class{Version: 2, Class: &models.Class{Class: "class2", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
68
+ f.On("ReadOnlyVersionedClass", "class3").Return(versioned.Class{Version: 3, Class: &models.Class{Class: "class3", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
69
+ // Then we fetch what we need to update
70
+ f.On("QueryReadOnlyClasses", []string{"class1", "class2", "class3"}).Return(map[string]versioned.Class{
71
+ "class1": {Version: 1, Class: &models.Class{Class: "class1", VectorIndexType: "hnsw"}},
72
+ "class2": {Version: 2, Class: &models.Class{Class: "class2", VectorIndexType: "hnsw"}},
73
+ "class3": {Version: 3, Class: &models.Class{Class: "class3", VectorIndexType: "hnsw"}},
74
+ }, nil)
75
+ },
76
+ },
77
+ {
78
+ name: "Read subset from leader if mismatch",
79
+ getFromSchema: []string{"class1", "class2", "class3"},
80
+ strategy: configRuntime.LeaderOnMismatch,
81
+ schemaExpect: func(f *fakeSchemaManager) {
82
+ // First we will query the versions from the leader
83
+ f.On("QueryClassVersions", []string{"class1", "class2", "class3"}).Return(map[string]uint64{
84
+ "class1": 1,
85
+ "class2": 2,
86
+ "class3": 6,
87
+ }, nil)
88
+ // Then we check the local version
89
+ f.On("ReadOnlyVersionedClass", "class1").Return(versioned.Class{Version: 1, Class: &models.Class{Class: "class1", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
90
+ f.On("ReadOnlyVersionedClass", "class2").Return(versioned.Class{Version: 2, Class: &models.Class{Class: "class2", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
91
+ f.On("ReadOnlyVersionedClass", "class3").Return(versioned.Class{Version: 3, Class: &models.Class{Class: "class3", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
92
+ // Then we fetch what we need to update
93
+ f.On("QueryReadOnlyClasses", []string{"class3"}).Return(map[string]versioned.Class{
94
+ "class3": {Version: 6, Class: &models.Class{Class: "class3", VectorIndexType: "hnsw"}},
95
+ }, nil)
96
+ },
97
+ },
98
+ {
99
+ name: "Read from leader local equal",
100
+ getFromSchema: []string{"class1", "class2", "class3"},
101
+ strategy: configRuntime.LeaderOnMismatch,
102
+ schemaExpect: func(f *fakeSchemaManager) {
103
+ // First we will query the versions from the leader
104
+ f.On("QueryClassVersions", []string{"class1", "class2", "class3"}).Return(map[string]uint64{
105
+ "class1": 1,
106
+ "class2": 2,
107
+ "class3": 3,
108
+ }, nil)
109
+ f.On("ReadOnlyVersionedClass", "class1").Return(versioned.Class{Version: 1, Class: &models.Class{Class: "class1", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
110
+ f.On("ReadOnlyVersionedClass", "class2").Return(versioned.Class{Version: 2, Class: &models.Class{Class: "class2", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
111
+ f.On("ReadOnlyVersionedClass", "class3").Return(versioned.Class{Version: 3, Class: &models.Class{Class: "class3", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
112
+ },
113
+ },
114
+ {
115
+ name: "Read from leader local ahead",
116
+ getFromSchema: []string{"class1", "class2", "class3"},
117
+ strategy: configRuntime.LeaderOnMismatch,
118
+ schemaExpect: func(f *fakeSchemaManager) {
119
+ // First we will query the versions from the leader
120
+ f.On("QueryClassVersions", []string{"class1", "class2", "class3"}).Return(map[string]uint64{
121
+ "class1": 1,
122
+ "class2": 2,
123
+ "class3": 3,
124
+ }, nil)
125
+ // Here we assume a delay between the leader returning the version and a change, so local > leader
126
+ f.On("ReadOnlyVersionedClass", "class1").Return(versioned.Class{Version: 4, Class: &models.Class{Class: "class1", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
127
+ f.On("ReadOnlyVersionedClass", "class2").Return(versioned.Class{Version: 5, Class: &models.Class{Class: "class2", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
128
+ f.On("ReadOnlyVersionedClass", "class3").Return(versioned.Class{Version: 6, Class: &models.Class{Class: "class3", VectorIndexType: "hnsw", ShardingConfig: shardingCfg.Config{}}})
129
+ },
130
+ },
131
+ }
132
+
133
+ for _, testCase := range testCases {
134
+ testCase := testCase
135
+ t.Run(testCase.name, func(t *testing.T) {
136
+ // Configure test setup
137
+ handler, fakeSchema := newTestHandler(t, &fakeDB{})
138
+ log, _ := test.NewNullLogger()
139
+ classGetter := NewClassGetter(
140
+ &handler.parser,
141
+ fakeSchema,
142
+ fakeSchema,
143
+ configRuntime.NewFeatureFlag(
144
+ "fake-key",
145
+ string(testCase.strategy),
146
+ nil,
147
+ "",
148
+ log,
149
+ ),
150
+ log,
151
+ )
152
+ require.NotNil(t, classGetter)
153
+
154
+ // Configure expectation
155
+ testCase.schemaExpect(fakeSchema)
156
+
157
+ // Get class and ensure we receive all classes as expected
158
+ classes, err := classGetter.getClasses(testCase.getFromSchema)
159
+ require.NoError(t, err)
160
+ require.Equal(t, len(testCase.getFromSchema), len(classes))
161
+ for _, c := range classes {
162
+ require.Contains(t, testCase.getFromSchema, c.Class.Class)
163
+ }
164
+
165
+ // Assert all the mock happened as expected
166
+ fakeSchema.AssertExpectations(t)
167
+ })
168
+ }
169
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/handler.go ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "os"
18
+ "strings"
19
+
20
+ "github.com/pkg/errors"
21
+ "github.com/sirupsen/logrus"
22
+ command "github.com/weaviate/weaviate/cluster/proto/api"
23
+ clusterSchema "github.com/weaviate/weaviate/cluster/schema"
24
+ entcfg "github.com/weaviate/weaviate/entities/config"
25
+ "github.com/weaviate/weaviate/entities/models"
26
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
27
+ "github.com/weaviate/weaviate/entities/schema"
28
+ schemaConfig "github.com/weaviate/weaviate/entities/schema/config"
29
+ "github.com/weaviate/weaviate/entities/versioned"
30
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
31
+ "github.com/weaviate/weaviate/usecases/auth/authorization/filter"
32
+ "github.com/weaviate/weaviate/usecases/config"
33
+ "github.com/weaviate/weaviate/usecases/sharding"
34
+ )
35
+
36
+ var (
37
+ ErrNotFound = errors.New("not found")
38
+ ErrUnexpectedMultiple = errors.New("unexpected multiple results")
39
+ )
40
+
41
+ // SchemaManager is responsible for consistent schema operations.
42
+ // It allows reading and writing the schema while directly talking to the leader, no matter which node it is.
43
+ // It also allows cluster related operations that can only be done on the leader (join/remove/stats/etc...)
44
+ // For details about each endpoint see [github.com/weaviate/weaviate/cluster.Raft].
45
+ // For local schema lookup where eventual consistency is acceptable, see [SchemaReader].
46
+ type SchemaManager interface {
47
+ // Schema writes operation.
48
+ AddClass(ctx context.Context, cls *models.Class, ss *sharding.State) (uint64, error)
49
+ RestoreClass(ctx context.Context, cls *models.Class, ss *sharding.State) (uint64, error)
50
+ UpdateClass(ctx context.Context, cls *models.Class, ss *sharding.State) (uint64, error)
51
+ DeleteClass(ctx context.Context, name string) (uint64, error)
52
+ AddProperty(ctx context.Context, class string, p ...*models.Property) (uint64, error)
53
+ UpdateShardStatus(ctx context.Context, class, shard, status string) (uint64, error)
54
+ AddTenants(ctx context.Context, class string, req *command.AddTenantsRequest) (uint64, error)
55
+ UpdateTenants(ctx context.Context, class string, req *command.UpdateTenantsRequest) (uint64, error)
56
+ DeleteTenants(ctx context.Context, class string, req *command.DeleteTenantsRequest) (uint64, error)
57
+
58
+ // Cluster related operations
59
+ Join(_ context.Context, nodeID, raftAddr string, voter bool) error
60
+ Remove(_ context.Context, nodeID string) error
61
+ Stats() map[string]any
62
+ StorageCandidates() []string
63
+ StoreSchemaV1() error
64
+
65
+ // Strongly consistent schema read. These endpoints will emit a query to the leader to ensure that the data is read
66
+ // from an up to date schema.
67
+ QueryReadOnlyClasses(names ...string) (map[string]versioned.Class, error)
68
+ QuerySchema() (models.Schema, error)
69
+ QueryTenants(class string, tenants []string) ([]*models.Tenant, uint64, error)
70
+ QueryCollectionsCount() (int, error)
71
+ QueryShardOwner(class, shard string) (string, uint64, error)
72
+ QueryTenantsShards(class string, tenants ...string) (map[string]string, uint64, error)
73
+ QueryShardingState(class string) (*sharding.State, uint64, error)
74
+ QueryClassVersions(names ...string) (map[string]uint64, error)
75
+
76
+ // Aliases
77
+ CreateAlias(ctx context.Context, alias string, class *models.Class) (uint64, error)
78
+ ReplaceAlias(ctx context.Context, alias *models.Alias, newClass *models.Class) (uint64, error)
79
+ DeleteAlias(ctx context.Context, alias string) (uint64, error)
80
+ GetAliases(ctx context.Context, alias string, class *models.Class) ([]*models.Alias, error)
81
+ GetAlias(ctx context.Context, alias string) (*models.Alias, error)
82
+ }
83
+
84
+ // SchemaReader allows reading the local schema with or without using a schema version.
85
+ type SchemaReader interface {
86
+ // WaitForUpdate ensures that the local schema has caught up to version.
87
+ WaitForUpdate(ctx context.Context, version uint64) error
88
+
89
+ // These schema reads function reads the metadata immediately present in the local schema and can be eventually
90
+ // consistent.
91
+ // For details about each endpoint see [github.com/weaviate/weaviate/cluster/schema.SchemaReader].
92
+ ClassEqual(name string) string
93
+ MultiTenancy(class string) models.MultiTenancyConfig
94
+ ClassInfo(class string) (ci clusterSchema.ClassInfo)
95
+ ReadOnlyClass(name string) *models.Class
96
+ ReadOnlyVersionedClass(name string) versioned.Class
97
+ ReadOnlySchema() models.Schema
98
+ Aliases() map[string]string
99
+ ShardReplicas(class, shard string) ([]string, error)
100
+ ShardFromUUID(class string, uuid []byte) string
101
+ ShardOwner(class, shard string) (string, error)
102
+ Read(class string, reader func(*models.Class, *sharding.State) error) error
103
+ Shards(class string) ([]string, error)
104
+ LocalShards(class string) ([]string, error)
105
+ GetShardsStatus(class, tenant string) (models.ShardStatusList, error)
106
+ ResolveAlias(alias string) string
107
+ GetAliasesForClass(class string) []*models.Alias
108
+
109
+ // These schema reads function (...WithVersion) return the metadata once the local schema has caught up to the
110
+ // version parameter. If version is 0 is behaves exactly the same as eventual consistent reads.
111
+ // For details about each endpoint see [github.com/weaviate/weaviate/cluster/schema.VersionedSchemaReader].
112
+ ClassInfoWithVersion(ctx context.Context, class string, version uint64) (clusterSchema.ClassInfo, error)
113
+ MultiTenancyWithVersion(ctx context.Context, class string, version uint64) (models.MultiTenancyConfig, error)
114
+ ReadOnlyClassWithVersion(ctx context.Context, class string, version uint64) (*models.Class, error)
115
+ ShardOwnerWithVersion(ctx context.Context, lass, shard string, version uint64) (string, error)
116
+ ShardFromUUIDWithVersion(ctx context.Context, class string, uuid []byte, version uint64) (string, error)
117
+ ShardReplicasWithVersion(ctx context.Context, class, shard string, version uint64) ([]string, error)
118
+ TenantsShardsWithVersion(ctx context.Context, version uint64, class string, tenants ...string) (map[string]string, error)
119
+ }
120
+
121
+ type validator interface {
122
+ ValidateVectorIndexConfigUpdate(old, updated schemaConfig.VectorIndexConfig) error
123
+ ValidateInvertedIndexConfigUpdate(old, updated *models.InvertedIndexConfig) error
124
+ ValidateVectorIndexConfigsUpdate(old, updated map[string]schemaConfig.VectorIndexConfig) error
125
+ }
126
+
127
+ // The handler manages API requests for manipulating class schemas.
128
+ // This separation of responsibilities helps decouple these tasks
129
+ // from the Manager class, which combines many unrelated functions.
130
+ // By delegating these clear responsibilities to the handler, it maintains
131
+ // a clean separation from the manager, enhancing code modularity and maintainability.
132
+ type Handler struct {
133
+ schemaManager SchemaManager
134
+ schemaReader SchemaReader
135
+
136
+ cloud modulecapabilities.OffloadCloud
137
+
138
+ validator validator
139
+
140
+ logger logrus.FieldLogger
141
+ Authorizer authorization.Authorizer
142
+ schemaConfig *config.SchemaHandlerConfig
143
+ config config.Config
144
+ vectorizerValidator VectorizerValidator
145
+ moduleConfig ModuleConfig
146
+ clusterState clusterState
147
+ configParser VectorConfigParser
148
+ invertedConfigValidator InvertedConfigValidator
149
+ parser Parser
150
+ classGetter *ClassGetter
151
+
152
+ asyncIndexingEnabled bool
153
+ }
154
+
155
+ // NewHandler creates a new handler
156
+ func NewHandler(
157
+ schemaReader SchemaReader,
158
+ schemaManager SchemaManager,
159
+ validator validator,
160
+ logger logrus.FieldLogger, authorizer authorization.Authorizer, schemaConfig *config.SchemaHandlerConfig,
161
+ config config.Config,
162
+ configParser VectorConfigParser, vectorizerValidator VectorizerValidator,
163
+ invertedConfigValidator InvertedConfigValidator,
164
+ moduleConfig ModuleConfig, clusterState clusterState,
165
+ cloud modulecapabilities.OffloadCloud,
166
+ parser Parser, classGetter *ClassGetter,
167
+ ) (Handler, error) {
168
+ handler := Handler{
169
+ config: config,
170
+ schemaConfig: schemaConfig,
171
+ schemaReader: schemaReader,
172
+ schemaManager: schemaManager,
173
+ parser: parser,
174
+ validator: validator,
175
+ logger: logger,
176
+ Authorizer: authorizer,
177
+ configParser: configParser,
178
+ vectorizerValidator: vectorizerValidator,
179
+ invertedConfigValidator: invertedConfigValidator,
180
+ moduleConfig: moduleConfig,
181
+ clusterState: clusterState,
182
+ cloud: cloud,
183
+ classGetter: classGetter,
184
+
185
+ asyncIndexingEnabled: entcfg.Enabled(os.Getenv("ASYNC_INDEXING")),
186
+ }
187
+ return handler, nil
188
+ }
189
+
190
+ // GetSchema retrieves a locally cached copy of the schema
191
+ func (h *Handler) GetConsistentSchema(ctx context.Context, principal *models.Principal, consistency bool) (schema.Schema, error) {
192
+ var fullSchema schema.Schema
193
+ if !consistency {
194
+ fullSchema = h.getSchema()
195
+ } else {
196
+ consistentSchema, err := h.schemaManager.QuerySchema()
197
+ if err != nil {
198
+ return schema.Schema{}, fmt.Errorf("could not read schema with strong consistency: %w", err)
199
+ }
200
+ fullSchema = schema.Schema{
201
+ Objects: &consistentSchema,
202
+ }
203
+ }
204
+
205
+ filteredClasses := filter.New[*models.Class](h.Authorizer, h.config.Authorization.Rbac).Filter(
206
+ ctx,
207
+ h.logger,
208
+ principal,
209
+ fullSchema.Objects.Classes,
210
+ authorization.READ,
211
+ func(class *models.Class) string {
212
+ return authorization.CollectionsMetadata(class.Class)[0]
213
+ },
214
+ )
215
+
216
+ return schema.Schema{
217
+ Objects: &models.Schema{
218
+ Classes: filteredClasses,
219
+ },
220
+ }, nil
221
+ }
222
+
223
+ // GetSchemaSkipAuth can never be used as a response to a user request as it
224
+ // could leak the schema to an unauthorized user, is intended to be used for
225
+ // non-user triggered processes, such as regular updates / maintenance / etc
226
+ func (h *Handler) GetSchemaSkipAuth() schema.Schema { return h.getSchema() }
227
+
228
+ func (h *Handler) getSchema() schema.Schema {
229
+ s := h.schemaReader.ReadOnlySchema()
230
+ return schema.Schema{
231
+ Objects: &s,
232
+ }
233
+ }
234
+
235
+ func (h *Handler) Nodes() []string {
236
+ return h.clusterState.AllNames()
237
+ }
238
+
239
+ func (h *Handler) NodeName() string {
240
+ return h.clusterState.LocalName()
241
+ }
242
+
243
+ func (h *Handler) UpdateShardStatus(ctx context.Context,
244
+ principal *models.Principal, class, shard, status string,
245
+ ) (uint64, error) {
246
+ err := h.Authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.ShardsMetadata(class, shard)...)
247
+ if err != nil {
248
+ return 0, err
249
+ }
250
+
251
+ return h.schemaManager.UpdateShardStatus(ctx, class, shard, status)
252
+ }
253
+
254
+ func (h *Handler) ShardsStatus(ctx context.Context,
255
+ principal *models.Principal, class, shard string,
256
+ ) (models.ShardStatusList, error) {
257
+ err := h.Authorizer.Authorize(ctx, principal, authorization.READ, authorization.ShardsMetadata(class, shard)...)
258
+ if err != nil {
259
+ return nil, err
260
+ }
261
+
262
+ return h.schemaReader.GetShardsStatus(class, shard)
263
+ }
264
+
265
+ // JoinNode adds the given node to the cluster.
266
+ // Node needs to reachable via memberlist/gossip.
267
+ // If nodePort is an empty string, nodePort will be the default raft port.
268
+ // If the node is not reachable using memberlist, an error is returned
269
+ // If joining the node fails, an error is returned.
270
+ func (h *Handler) JoinNode(ctx context.Context, node string, nodePort string, voter bool) error {
271
+ nodeAddr, ok := h.clusterState.NodeHostname(node)
272
+ if !ok {
273
+ return fmt.Errorf("could not resolve addr for node id %v", node)
274
+ }
275
+ nodeAddr = strings.Split(nodeAddr, ":")[0]
276
+
277
+ if nodePort == "" {
278
+ nodePort = fmt.Sprintf("%d", config.DefaultRaftPort)
279
+ }
280
+
281
+ if err := h.schemaManager.Join(ctx, node, nodeAddr+":"+nodePort, voter); err != nil {
282
+ return fmt.Errorf("node failed to join cluster: %w", err)
283
+ }
284
+ return nil
285
+ }
286
+
287
+ // RemoveNode removes the given node from the cluster.
288
+ func (h *Handler) RemoveNode(ctx context.Context, node string) error {
289
+ if err := h.schemaManager.Remove(ctx, node); err != nil {
290
+ return fmt.Errorf("node failed to leave cluster: %w", err)
291
+ }
292
+ return nil
293
+ }
294
+
295
+ // Statistics is used to return a map of various internal stats. This should only be used for informative purposes or debugging.
296
+ func (h *Handler) Statistics() map[string]any {
297
+ return h.schemaManager.Stats()
298
+ }
299
+
300
+ func (h *Handler) StoreSchemaV1() error {
301
+ return h.schemaManager.StoreSchemaV1()
302
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/handler_test.go ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "testing"
17
+
18
+ "github.com/stretchr/testify/assert"
19
+ "github.com/stretchr/testify/mock"
20
+ "github.com/stretchr/testify/require"
21
+
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/entities/schema"
24
+ "github.com/weaviate/weaviate/usecases/config"
25
+ "github.com/weaviate/weaviate/usecases/config/runtime"
26
+ )
27
+
28
+ var schemaTests = []struct {
29
+ name string
30
+ fn func(*testing.T, *Handler, *fakeSchemaManager)
31
+ }{
32
+ {name: "AddObjectClass", fn: testAddObjectClass},
33
+ {name: "AddObjectClassWithExplicitVectorizer", fn: testAddObjectClassExplicitVectorizer},
34
+ {name: "AddObjectClassWithImplicitVectorizer", fn: testAddObjectClassImplicitVectorizer},
35
+ {name: "AddObjectClassWithWrongVectorizer", fn: testAddObjectClassWrongVectorizer},
36
+ {name: "AddObjectClassWithWrongIndexType", fn: testAddObjectClassWrongIndexType},
37
+ {name: "RemoveObjectClass", fn: testRemoveObjectClass},
38
+ {name: "CantAddSameClassTwice", fn: testCantAddSameClassTwice},
39
+ {name: "CantAddSameClassTwiceDifferentKind", fn: testCantAddSameClassTwiceDifferentKinds},
40
+ {name: "AddPropertyDuringCreation", fn: testAddPropertyDuringCreation},
41
+ {name: "AddPropertyWithTargetVectorConfig", fn: testAddPropertyWithTargetVectorConfig},
42
+ {name: "AddInvalidPropertyDuringCreation", fn: testAddInvalidPropertyDuringCreation},
43
+ {name: "AddInvalidPropertyWithEmptyDataTypeDuringCreation", fn: testAddInvalidPropertyWithEmptyDataTypeDuringCreation},
44
+ {name: "DropProperty", fn: testDropProperty},
45
+ }
46
+
47
+ func testAddObjectClass(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
48
+ t.Parallel()
49
+
50
+ class := &models.Class{
51
+ Class: "Car",
52
+ Properties: []*models.Property{{
53
+ DataType: schema.DataTypeText.PropString(),
54
+ Tokenization: models.PropertyTokenizationWhitespace,
55
+ Name: "dummy",
56
+ }},
57
+ Vectorizer: "model1",
58
+ VectorIndexConfig: map[string]interface{}{},
59
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
60
+ }
61
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
62
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
63
+ _, _, err := handler.AddClass(context.Background(), nil, class)
64
+ assert.Nil(t, err)
65
+ }
66
+
67
+ func testAddObjectClassExplicitVectorizer(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
68
+ t.Parallel()
69
+
70
+ class := &models.Class{
71
+ Vectorizer: config.VectorizerModuleText2VecContextionary,
72
+ VectorIndexType: "hnsw",
73
+ Class: "Car",
74
+ Properties: []*models.Property{{
75
+ DataType: schema.DataTypeText.PropString(),
76
+ Tokenization: models.PropertyTokenizationWhitespace,
77
+ Name: "dummy",
78
+ }},
79
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
80
+ }
81
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
82
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
83
+ _, _, err := handler.AddClass(context.Background(), nil, class)
84
+ assert.Nil(t, err)
85
+ }
86
+
87
+ func testAddObjectClassImplicitVectorizer(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
88
+ t.Parallel()
89
+ handler.config.DefaultVectorizerModule = config.VectorizerModuleText2VecContextionary
90
+ class := &models.Class{
91
+ Class: "Car",
92
+ Properties: []*models.Property{{
93
+ DataType: schema.DataTypeText.PropString(),
94
+ Tokenization: models.PropertyTokenizationWhitespace,
95
+ Name: "dummy",
96
+ }},
97
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
98
+ }
99
+
100
+ fakeSchemaManager.On("AddClass", mock.Anything, mock.Anything).Return(nil)
101
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
102
+ _, _, err := handler.AddClass(context.Background(), nil, class)
103
+ assert.Nil(t, err)
104
+ }
105
+
106
+ func testAddObjectClassWrongVectorizer(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
107
+ t.Parallel()
108
+
109
+ class := &models.Class{
110
+ Class: "Car",
111
+ Vectorizer: "vectorizer-5000000",
112
+ Properties: []*models.Property{{
113
+ DataType: schema.DataTypeText.PropString(),
114
+ Tokenization: models.PropertyTokenizationWhitespace,
115
+ Name: "dummy",
116
+ }},
117
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
118
+ }
119
+
120
+ _, _, err := handler.AddClass(context.Background(), nil, class)
121
+ assert.Error(t, err)
122
+ }
123
+
124
+ func testAddObjectClassWrongIndexType(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
125
+ t.Parallel()
126
+
127
+ class := &models.Class{
128
+ Class: "Car",
129
+ VectorIndexType: "vector-index-2-million",
130
+ Properties: []*models.Property{{
131
+ DataType: schema.DataTypeText.PropString(),
132
+ Tokenization: models.PropertyTokenizationWhitespace,
133
+ Name: "dummy",
134
+ }},
135
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
136
+ }
137
+ _, _, err := handler.AddClass(context.Background(), nil, class)
138
+ require.NotNil(t, err)
139
+ assert.Equal(t, "unrecognized or unsupported vectorIndexType \"vector-index-2-million\"", err.Error())
140
+ }
141
+
142
+ func testRemoveObjectClass(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
143
+ t.Parallel()
144
+
145
+ class := &models.Class{
146
+ Class: "Car",
147
+ Vectorizer: "text2vec-contextionary",
148
+ ModuleConfig: map[string]interface{}{
149
+ "text2vec-contextionary": map[string]interface{}{
150
+ "vectorizeClassName": true,
151
+ },
152
+ },
153
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
154
+ }
155
+
156
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
157
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
158
+ _, _, err := handler.AddClass(context.Background(), nil, class)
159
+ require.Nil(t, err)
160
+
161
+ // Now delete the class
162
+ fakeSchemaManager.On("DeleteClass", "Car").Return(nil)
163
+ err = handler.DeleteClass(context.Background(), nil, "Car")
164
+ assert.Nil(t, err)
165
+ }
166
+
167
+ func testCantAddSameClassTwice(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
168
+ t.Parallel()
169
+
170
+ reset := fakeSchemaManager.On("ReadOnlySchema").Return(models.Schema{})
171
+
172
+ class := &models.Class{
173
+ Class: "Car",
174
+ Vectorizer: "text2vec-contextionary",
175
+ ModuleConfig: map[string]interface{}{
176
+ "text2vec-contextionary": map[string]interface{}{
177
+ "vectorizeClassName": true,
178
+ },
179
+ },
180
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
181
+ }
182
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
183
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
184
+ _, _, err := handler.AddClass(context.Background(), nil, class)
185
+ assert.Nil(t, err)
186
+
187
+ // Reset schema to simulate the class has been added
188
+ reset.Unset()
189
+ class = &models.Class{
190
+ Class: "Car",
191
+ Vectorizer: "text2vec-contextionary",
192
+ ModuleConfig: map[string]interface{}{
193
+ "text2vec-contextionary": map[string]interface{}{
194
+ "vectorizeClassName": true,
195
+ },
196
+ },
197
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
198
+ }
199
+ fakeSchemaManager.ExpectedCalls = fakeSchemaManager.ExpectedCalls[:0]
200
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
201
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(ErrNotFound)
202
+
203
+ // Add it again
204
+ _, _, err = handler.AddClass(context.Background(), nil, class)
205
+ assert.NotNil(t, err)
206
+ }
207
+
208
+ func testCantAddSameClassTwiceDifferentKinds(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
209
+ t.Parallel()
210
+ ctx := context.Background()
211
+ class := &models.Class{
212
+ Class: "Car",
213
+ Vectorizer: "text2vec-contextionary",
214
+ ModuleConfig: map[string]interface{}{
215
+ "text2vec-contextionary": map[string]interface{}{
216
+ "vectorizeClassName": true,
217
+ },
218
+ },
219
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
220
+ }
221
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
222
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
223
+ _, _, err := handler.AddClass(ctx, nil, class)
224
+ assert.Nil(t, err)
225
+
226
+ class.ModuleConfig = map[string]interface{}{
227
+ "my-module1": map[string]interface{}{
228
+ "my-setting": "some-value",
229
+ },
230
+ }
231
+
232
+ // Add it again, but with a different kind.
233
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
234
+ _, _, err = handler.AddClass(context.Background(), nil, class)
235
+ assert.NotNil(t, err)
236
+ }
237
+
238
+ func testAddPropertyDuringCreation(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
239
+ t.Parallel()
240
+
241
+ vFalse := false
242
+ vTrue := true
243
+
244
+ properties := []*models.Property{
245
+ {
246
+ Name: "color",
247
+ DataType: schema.DataTypeText.PropString(),
248
+ Tokenization: models.PropertyTokenizationWhitespace,
249
+ },
250
+ {
251
+ Name: "colorRaw1",
252
+ DataType: schema.DataTypeText.PropString(),
253
+ Tokenization: models.PropertyTokenizationWhitespace,
254
+ IndexFilterable: &vFalse,
255
+ IndexSearchable: &vFalse,
256
+ },
257
+ {
258
+ Name: "colorRaw2",
259
+ DataType: schema.DataTypeText.PropString(),
260
+ Tokenization: models.PropertyTokenizationWhitespace,
261
+ IndexFilterable: &vTrue,
262
+ IndexSearchable: &vFalse,
263
+ },
264
+ {
265
+ Name: "colorRaw3",
266
+ DataType: schema.DataTypeText.PropString(),
267
+ Tokenization: models.PropertyTokenizationWhitespace,
268
+ IndexFilterable: &vFalse,
269
+ IndexSearchable: &vTrue,
270
+ },
271
+ {
272
+ Name: "colorRaw4",
273
+ DataType: schema.DataTypeText.PropString(),
274
+ Tokenization: models.PropertyTokenizationWhitespace,
275
+ IndexFilterable: &vTrue,
276
+ IndexSearchable: &vTrue,
277
+ },
278
+ {
279
+ Name: "content",
280
+ DataType: schema.DataTypeText.PropString(),
281
+ Tokenization: models.PropertyTokenizationWhitespace,
282
+ },
283
+ {
284
+ Name: "allDefault",
285
+ DataType: schema.DataTypeText.PropString(),
286
+ Tokenization: models.PropertyTokenizationWhitespace,
287
+ },
288
+ }
289
+
290
+ class := &models.Class{
291
+ Class: "Car",
292
+ Properties: properties,
293
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
294
+ }
295
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
296
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
297
+ _, _, err := handler.AddClass(context.Background(), nil, class)
298
+ assert.Nil(t, err)
299
+ }
300
+
301
+ func testAddPropertyWithTargetVectorConfig(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
302
+ t.Parallel()
303
+
304
+ class := &models.Class{
305
+ Class: "Car",
306
+ Properties: []*models.Property{
307
+ {
308
+ Name: "color",
309
+ DataType: schema.DataTypeText.PropString(),
310
+ Tokenization: models.PropertyTokenizationWhitespace,
311
+ ModuleConfig: map[string]interface{}{
312
+ "text2vec-contextionary": map[string]interface{}{
313
+ "vectorizePropertyName": true,
314
+ },
315
+ },
316
+ },
317
+ },
318
+ VectorConfig: map[string]models.VectorConfig{
319
+ "vec1": {
320
+ Vectorizer: map[string]interface{}{"text2vec-contextionary": map[string]interface{}{}},
321
+ VectorIndexType: "flat",
322
+ },
323
+ },
324
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
325
+ }
326
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
327
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
328
+ _, _, err := handler.AddClass(context.Background(), nil, class)
329
+ require.NoError(t, err)
330
+ }
331
+
332
+ func testAddInvalidPropertyDuringCreation(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
333
+ t.Parallel()
334
+
335
+ properties := []*models.Property{
336
+ {Name: "color", DataType: []string{"blurp"}},
337
+ }
338
+
339
+ _, _, err := handler.AddClass(context.Background(), nil, &models.Class{
340
+ Class: "Car",
341
+ Properties: properties,
342
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
343
+ })
344
+ assert.NotNil(t, err)
345
+ }
346
+
347
+ func testAddInvalidPropertyWithEmptyDataTypeDuringCreation(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
348
+ t.Parallel()
349
+
350
+ properties := []*models.Property{
351
+ {Name: "color", DataType: []string{""}},
352
+ }
353
+
354
+ _, _, err := handler.AddClass(context.Background(), nil, &models.Class{
355
+ Class: "Car",
356
+ Properties: properties,
357
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
358
+ })
359
+ assert.NotNil(t, err)
360
+ }
361
+
362
+ func testDropProperty(t *testing.T, handler *Handler, fakeSchemaManager *fakeSchemaManager) {
363
+ // TODO: https://github.com/weaviate/weaviate/issues/973
364
+ // Remove skip
365
+
366
+ t.Skip()
367
+
368
+ t.Parallel()
369
+
370
+ fakeSchemaManager.On("ReadOnlySchema").Return(models.Schema{})
371
+
372
+ properties := []*models.Property{
373
+ {Name: "color", DataType: schema.DataTypeText.PropString(), Tokenization: models.PropertyTokenizationWhitespace},
374
+ }
375
+ class := &models.Class{
376
+ Class: "Car",
377
+ Properties: properties,
378
+ ReplicationConfig: &models.ReplicationConfig{Factor: 1},
379
+ }
380
+ fakeSchemaManager.On("QueryCollectionsCount").Return(0, nil)
381
+ fakeSchemaManager.On("AddClass", class, mock.Anything).Return(nil)
382
+ _, _, err := handler.AddClass(context.Background(), nil, class)
383
+ assert.Nil(t, err)
384
+
385
+ // Now drop the property
386
+ handler.DeleteClassProperty(context.Background(), nil, "Car", "color")
387
+ // TODO: add the mock necessary to verify that the property is deleted
388
+ }
389
+
390
+ // This grant parent test setups up the temporary directory needed for the tests.
391
+ func TestSchema(t *testing.T) {
392
+ t.Run("TestSchema", func(t *testing.T) {
393
+ for _, testCase := range schemaTests {
394
+ // Run each test independently with their own handler
395
+ t.Run(testCase.name, func(t *testing.T) {
396
+ handler, fakeSchemaManager := newTestHandler(t, &fakeDB{})
397
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(-1)
398
+ defer fakeSchemaManager.AssertExpectations(t)
399
+ testCase.fn(t, handler, fakeSchemaManager)
400
+ })
401
+ }
402
+ })
403
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/helpers_test.go ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "strings"
18
+ "testing"
19
+
20
+ "github.com/sirupsen/logrus/hooks/test"
21
+ "github.com/stretchr/testify/mock"
22
+ "github.com/stretchr/testify/require"
23
+
24
+ command "github.com/weaviate/weaviate/cluster/proto/api"
25
+ clusterSchema "github.com/weaviate/weaviate/cluster/schema"
26
+ "github.com/weaviate/weaviate/entities/models"
27
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
28
+ schemaConfig "github.com/weaviate/weaviate/entities/schema/config"
29
+ "github.com/weaviate/weaviate/entities/vectorindex/common"
30
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
31
+ "github.com/weaviate/weaviate/usecases/auth/authorization/mocks"
32
+ "github.com/weaviate/weaviate/usecases/config"
33
+ "github.com/weaviate/weaviate/usecases/config/runtime"
34
+ "github.com/weaviate/weaviate/usecases/fakes"
35
+ "github.com/weaviate/weaviate/usecases/sharding"
36
+ )
37
+
38
+ func newTestHandler(t *testing.T, db clusterSchema.Indexer) (*Handler, *fakeSchemaManager) {
39
+ schemaManager := &fakeSchemaManager{}
40
+ logger, _ := test.NewNullLogger()
41
+ vectorizerValidator := &fakeVectorizerValidator{
42
+ valid: []string{"text2vec-contextionary", "model1", "model2"},
43
+ }
44
+ cfg := config.Config{
45
+ DefaultVectorizerModule: config.VectorizerModuleNone,
46
+ DefaultVectorDistanceMetric: "cosine",
47
+ }
48
+ fakeClusterState := fakes.NewFakeClusterState()
49
+ fakeValidator := &fakeValidator{}
50
+ schemaParser := NewParser(fakeClusterState, dummyParseVectorConfig, fakeValidator, fakeModulesProvider{}, nil)
51
+ handler, err := NewHandler(
52
+ schemaManager, schemaManager, fakeValidator, logger, mocks.NewMockAuthorizer(),
53
+ &cfg.SchemaHandlerConfig, cfg, dummyParseVectorConfig, vectorizerValidator, dummyValidateInvertedConfig,
54
+ &fakeModuleConfig{}, fakeClusterState, nil, *schemaParser, nil)
55
+ require.NoError(t, err)
56
+ handler.schemaConfig.MaximumAllowedCollectionsCount = runtime.NewDynamicValue(-1)
57
+ return &handler, schemaManager
58
+ }
59
+
60
+ func newTestHandlerWithCustomAuthorizer(t *testing.T, db clusterSchema.Indexer, authorizer authorization.Authorizer) (*Handler, *fakeSchemaManager) {
61
+ cfg := config.Config{}
62
+ metaHandler := &fakeSchemaManager{}
63
+ logger, _ := test.NewNullLogger()
64
+ vectorizerValidator := &fakeVectorizerValidator{
65
+ valid: []string{
66
+ "model1", "model2",
67
+ },
68
+ }
69
+ fakeClusterState := fakes.NewFakeClusterState()
70
+ fakeValidator := &fakeValidator{}
71
+ schemaParser := NewParser(fakeClusterState, dummyParseVectorConfig, fakeValidator, nil, nil)
72
+ handler, err := NewHandler(
73
+ metaHandler, metaHandler, fakeValidator, logger, authorizer,
74
+ &cfg.SchemaHandlerConfig, cfg, dummyParseVectorConfig, vectorizerValidator, dummyValidateInvertedConfig,
75
+ &fakeModuleConfig{}, fakeClusterState, nil, *schemaParser, nil)
76
+ require.Nil(t, err)
77
+ return &handler, metaHandler
78
+ }
79
+
80
+ type fakeDB struct {
81
+ mock.Mock
82
+ }
83
+
84
+ func (f *fakeDB) Open(context.Context) error {
85
+ return nil
86
+ }
87
+
88
+ func (f *fakeDB) Close(context.Context) error {
89
+ return nil
90
+ }
91
+
92
+ func (f *fakeDB) AddClass(cmd command.AddClassRequest) error {
93
+ return nil
94
+ }
95
+
96
+ func (f *fakeDB) RestoreClassDir(class string) error {
97
+ return nil
98
+ }
99
+
100
+ func (f *fakeDB) AddReplicaToShard(class string, shard string, targetNode string) error {
101
+ return nil
102
+ }
103
+
104
+ func (f *fakeDB) DeleteReplicaFromShard(class string, shard string, targetNode string) error {
105
+ return nil
106
+ }
107
+
108
+ func (f *fakeDB) LoadShard(class string, shard string) {
109
+ }
110
+
111
+ func (f *fakeDB) DropShard(class string, shard string) {
112
+ }
113
+
114
+ func (f *fakeDB) ShutdownShard(class string, shard string) {
115
+ }
116
+
117
+ func (f *fakeDB) UpdateClass(cmd command.UpdateClassRequest) error {
118
+ return nil
119
+ }
120
+
121
+ func (f *fakeDB) UpdateIndex(cmd command.UpdateClassRequest) error {
122
+ return nil
123
+ }
124
+
125
+ func (f *fakeDB) ReloadLocalDB(ctx context.Context, all []command.UpdateClassRequest) error {
126
+ return nil
127
+ }
128
+
129
+ func (f *fakeDB) DeleteClass(class string, hasFrozen bool) error {
130
+ return nil
131
+ }
132
+
133
+ func (f *fakeDB) AddProperty(prop string, cmd command.AddPropertyRequest) error {
134
+ return nil
135
+ }
136
+
137
+ func (f *fakeDB) AddTenants(class string, cmd *command.AddTenantsRequest) error {
138
+ return nil
139
+ }
140
+
141
+ func (f *fakeDB) UpdateTenants(class string, cmd *command.UpdateTenantsRequest) error {
142
+ return nil
143
+ }
144
+
145
+ func (f *fakeDB) UpdateTenantsProcess(class string, req *command.TenantProcessRequest) error {
146
+ return nil
147
+ }
148
+
149
+ func (f *fakeDB) DeleteTenants(class string, tenants []*models.Tenant) error {
150
+ return nil
151
+ }
152
+
153
+ func (f *fakeDB) UpdateShardStatus(cmd *command.UpdateShardStatusRequest) error {
154
+ return nil
155
+ }
156
+
157
+ func (f *fakeDB) GetShardsStatus(class, tenant string) (models.ShardStatusList, error) {
158
+ args := f.Called(class, tenant)
159
+ return args.Get(0).(models.ShardStatusList), nil
160
+ }
161
+
162
+ func (f *fakeDB) TriggerSchemaUpdateCallbacks() {
163
+ f.Called()
164
+ }
165
+
166
+ type fakeValidator struct{}
167
+
168
+ func (f fakeValidator) ValidateVectorIndexConfigUpdate(
169
+ old, updated schemaConfig.VectorIndexConfig,
170
+ ) error {
171
+ return nil
172
+ }
173
+
174
+ func (f fakeValidator) ValidateInvertedIndexConfigUpdate(
175
+ old, updated *models.InvertedIndexConfig,
176
+ ) error {
177
+ return nil
178
+ }
179
+
180
+ func (fakeValidator) ValidateVectorIndexConfigsUpdate(old, updated map[string]schemaConfig.VectorIndexConfig,
181
+ ) error {
182
+ return nil
183
+ }
184
+
185
+ type fakeModuleConfig struct{}
186
+
187
+ func (f *fakeModuleConfig) SetClassDefaults(class *models.Class) {
188
+ defaultConfig := map[string]interface{}{
189
+ "my-module1": map[string]interface{}{
190
+ "my-setting": "default-value",
191
+ },
192
+ }
193
+
194
+ asMap, ok := class.ModuleConfig.(map[string]interface{})
195
+ if !ok {
196
+ class.ModuleConfig = defaultConfig
197
+ return
198
+ }
199
+
200
+ module, ok := asMap["my-module1"]
201
+ if !ok {
202
+ class.ModuleConfig = defaultConfig
203
+ return
204
+ }
205
+
206
+ asMap, ok = module.(map[string]interface{})
207
+ if !ok {
208
+ class.ModuleConfig = defaultConfig
209
+ return
210
+ }
211
+
212
+ if _, ok := asMap["my-setting"]; !ok {
213
+ asMap["my-setting"] = "default-value"
214
+ defaultConfig["my-module1"] = asMap
215
+ class.ModuleConfig = defaultConfig
216
+ }
217
+ }
218
+
219
+ func (f *fakeModuleConfig) SetSinglePropertyDefaults(class *models.Class,
220
+ prop ...*models.Property,
221
+ ) {
222
+ }
223
+
224
+ func (f *fakeModuleConfig) ValidateClass(ctx context.Context, class *models.Class) error {
225
+ return nil
226
+ }
227
+
228
+ func (f *fakeModuleConfig) GetByName(name string) modulecapabilities.Module {
229
+ return nil
230
+ }
231
+
232
+ func (f *fakeModuleConfig) IsGenerative(moduleName string) bool {
233
+ return strings.Contains(moduleName, "generative")
234
+ }
235
+
236
+ func (f *fakeModuleConfig) IsReranker(moduleName string) bool {
237
+ return strings.Contains(moduleName, "reranker")
238
+ }
239
+
240
+ func (f *fakeModuleConfig) IsMultiVector(moduleName string) bool {
241
+ return strings.Contains(moduleName, "colbert")
242
+ }
243
+
244
+ type fakeVectorizerValidator struct {
245
+ valid []string
246
+ }
247
+
248
+ func (f *fakeVectorizerValidator) ValidateVectorizer(moduleName string) error {
249
+ for _, valid := range f.valid {
250
+ if moduleName == valid {
251
+ return nil
252
+ }
253
+ }
254
+
255
+ return fmt.Errorf("invalid vectorizer %q", moduleName)
256
+ }
257
+
258
+ type fakeVectorConfig struct {
259
+ raw interface{}
260
+ }
261
+
262
+ func (f fakeVectorConfig) IndexType() string {
263
+ return "fake"
264
+ }
265
+
266
+ func (f fakeVectorConfig) DistanceName() string {
267
+ return common.DistanceCosine
268
+ }
269
+
270
+ func (f fakeVectorConfig) IsMultiVector() bool {
271
+ return false
272
+ }
273
+
274
+ func dummyParseVectorConfig(in interface{}, vectorIndexType string, isMultiVector bool) (schemaConfig.VectorIndexConfig, error) {
275
+ return fakeVectorConfig{raw: in}, nil
276
+ }
277
+
278
+ func dummyValidateInvertedConfig(in *models.InvertedIndexConfig) error {
279
+ return nil
280
+ }
281
+
282
+ type fakeMigrator struct {
283
+ mock.Mock
284
+ }
285
+
286
+ func (f *fakeMigrator) GetShardsQueueSize(ctx context.Context, className, tenant string) (map[string]int64, error) {
287
+ return nil, nil
288
+ }
289
+
290
+ func (f *fakeMigrator) AddClass(ctx context.Context, cls *models.Class) error {
291
+ args := f.Called(ctx, cls)
292
+ return args.Error(0)
293
+ }
294
+
295
+ func (f *fakeMigrator) DropClass(ctx context.Context, className string, hasFrozen bool) error {
296
+ args := f.Called(ctx, className)
297
+ return args.Error(0)
298
+ }
299
+
300
+ func (f *fakeMigrator) AddProperty(ctx context.Context, className string, prop ...*models.Property) error {
301
+ args := f.Called(ctx, className, prop)
302
+ return args.Error(0)
303
+ }
304
+
305
+ func (f *fakeMigrator) LoadShard(ctx context.Context, class string, shard string) error {
306
+ args := f.Called(ctx, class, shard)
307
+ return args.Error(0)
308
+ }
309
+
310
+ func (f *fakeMigrator) DropShard(ctx context.Context, class string, shard string) error {
311
+ args := f.Called(ctx, class, shard)
312
+ return args.Error(0)
313
+ }
314
+
315
+ func (f *fakeMigrator) ShutdownShard(ctx context.Context, class string, shard string) error {
316
+ args := f.Called(ctx, class, shard)
317
+ return args.Error(0)
318
+ }
319
+
320
+ func (f *fakeMigrator) UpdateProperty(ctx context.Context, className string, propName string, newName *string) error {
321
+ return nil
322
+ }
323
+
324
+ func (f *fakeMigrator) NewTenants(ctx context.Context, class *models.Class, creates []*CreateTenantPayload) error {
325
+ args := f.Called(ctx, class, creates)
326
+ return args.Error(0)
327
+ }
328
+
329
+ func (f *fakeMigrator) UpdateTenants(ctx context.Context, class *models.Class, updates []*UpdateTenantPayload, implicitUpdate bool) error {
330
+ args := f.Called(ctx, class, updates)
331
+ return args.Error(0)
332
+ }
333
+
334
+ func (f *fakeMigrator) DeleteTenants(ctx context.Context, class string, tenants []*models.Tenant) error {
335
+ args := f.Called(ctx, class, tenants)
336
+ return args.Error(0)
337
+ }
338
+
339
+ func (f *fakeMigrator) GetShardsStatus(ctx context.Context, className, tenant string) (map[string]string, error) {
340
+ args := f.Called(ctx, className, tenant)
341
+ return args.Get(0).(map[string]string), args.Error(1)
342
+ }
343
+
344
+ func (f *fakeMigrator) UpdateShardStatus(ctx context.Context, className, shardName, targetStatus string, schemaVersion uint64) error {
345
+ args := f.Called(ctx, className, shardName, targetStatus, schemaVersion)
346
+ return args.Error(0)
347
+ }
348
+
349
+ func (f *fakeMigrator) UpdateVectorIndexConfig(ctx context.Context, className string, updated schemaConfig.VectorIndexConfig) error {
350
+ args := f.Called(ctx, className, updated)
351
+ return args.Error(0)
352
+ }
353
+
354
+ func (*fakeMigrator) ValidateVectorIndexConfigsUpdate(old, updated map[string]schemaConfig.VectorIndexConfig,
355
+ ) error {
356
+ return nil
357
+ }
358
+
359
+ func (*fakeMigrator) UpdateVectorIndexConfigs(ctx context.Context, className string,
360
+ updated map[string]schemaConfig.VectorIndexConfig,
361
+ ) error {
362
+ return nil
363
+ }
364
+
365
+ func (*fakeMigrator) ValidateInvertedIndexConfigUpdate(old, updated *models.InvertedIndexConfig) error {
366
+ return nil
367
+ }
368
+
369
+ func (f *fakeMigrator) UpdateInvertedIndexConfig(ctx context.Context, className string, updated *models.InvertedIndexConfig) error {
370
+ args := f.Called(ctx, className, updated)
371
+ return args.Error(0)
372
+ }
373
+
374
+ func (f *fakeMigrator) UpdateReplicationConfig(ctx context.Context, className string, cfg *models.ReplicationConfig) error {
375
+ return nil
376
+ }
377
+
378
+ func (f *fakeMigrator) WaitForStartup(ctx context.Context) error {
379
+ args := f.Called(ctx)
380
+ return args.Error(0)
381
+ }
382
+
383
+ func (f *fakeMigrator) Shutdown(ctx context.Context) error {
384
+ args := f.Called(ctx)
385
+ return args.Error(0)
386
+ }
387
+
388
+ func (f *fakeMigrator) UpdateIndex(ctx context.Context, class *models.Class, shardingState *sharding.State) error {
389
+ args := f.Called(class, shardingState)
390
+ return args.Error(0)
391
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/manager.go ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "slices"
18
+ "strings"
19
+ "sync"
20
+
21
+ "github.com/sirupsen/logrus"
22
+ "github.com/weaviate/weaviate/cluster/proto/api"
23
+ "github.com/weaviate/weaviate/entities/models"
24
+ "github.com/weaviate/weaviate/entities/modulecapabilities"
25
+ "github.com/weaviate/weaviate/entities/schema"
26
+ schemaConfig "github.com/weaviate/weaviate/entities/schema/config"
27
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
28
+ "github.com/weaviate/weaviate/usecases/cluster"
29
+ "github.com/weaviate/weaviate/usecases/config"
30
+ configRuntime "github.com/weaviate/weaviate/usecases/config/runtime"
31
+ "github.com/weaviate/weaviate/usecases/sharding"
32
+ )
33
+
34
+ // Manager Manages schema changes at a use-case level, i.e. agnostic of
35
+ // underlying databases or storage providers
36
+ type Manager struct {
37
+ validator validator
38
+ repo SchemaStore
39
+ logger logrus.FieldLogger
40
+ Authorizer authorization.Authorizer
41
+ clusterState clusterState
42
+
43
+ sync.RWMutex
44
+ // The handler is responsible for well-defined tasks and should be decoupled from the manager.
45
+ // This enables API requests to be directed straight to the handler without the need to pass through the manager.
46
+ // For more context, refer to the handler's definition.
47
+ Handler
48
+
49
+ SchemaReader
50
+ }
51
+
52
+ type VectorConfigParser func(in interface{}, vectorIndexType string, isMultiVector bool) (schemaConfig.VectorIndexConfig, error)
53
+
54
+ type InvertedConfigValidator func(in *models.InvertedIndexConfig) error
55
+
56
+ type SchemaGetter interface {
57
+ GetSchemaSkipAuth() schema.Schema
58
+ ReadOnlyClass(string) *models.Class
59
+ ResolveAlias(string) string
60
+ GetAliasesForClass(class string) []*models.Alias
61
+ Nodes() []string
62
+ NodeName() string
63
+ ClusterHealthScore() int
64
+ ResolveParentNodes(string, string) (map[string]string, error)
65
+ Statistics() map[string]any
66
+
67
+ ShardOwner(class, shard string) (string, error)
68
+ TenantsShards(ctx context.Context, class string, tenants ...string) (map[string]string, error)
69
+ OptimisticTenantStatus(ctx context.Context, class string, tenants string) (map[string]string, error)
70
+ ShardFromUUID(class string, uuid []byte) string
71
+ ShardReplicas(class, shard string) ([]string, error)
72
+ }
73
+
74
+ type VectorizerValidator interface {
75
+ ValidateVectorizer(moduleName string) error
76
+ }
77
+
78
+ type ModuleConfig interface {
79
+ SetClassDefaults(class *models.Class)
80
+ SetSinglePropertyDefaults(class *models.Class, props ...*models.Property)
81
+ ValidateClass(ctx context.Context, class *models.Class) error
82
+ GetByName(name string) modulecapabilities.Module
83
+ IsGenerative(string) bool
84
+ IsReranker(string) bool
85
+ IsMultiVector(string) bool
86
+ }
87
+
88
+ // State is a cached copy of the schema that can also be saved into a remote
89
+ // storage, as specified by Repo
90
+ type State struct {
91
+ ObjectSchema *models.Schema `json:"object"`
92
+ ShardingState map[string]*sharding.State
93
+ }
94
+
95
+ // NewState returns a new state with room for nClasses classes
96
+ func NewState(nClasses int) State {
97
+ return State{
98
+ ObjectSchema: &models.Schema{
99
+ Classes: make([]*models.Class, 0, nClasses),
100
+ },
101
+ ShardingState: make(map[string]*sharding.State, nClasses),
102
+ }
103
+ }
104
+
105
+ func (s State) EqualEnough(other *State) bool {
106
+ // Same number of classes
107
+ eqClassLen := len(s.ObjectSchema.Classes) == len(other.ObjectSchema.Classes)
108
+ if !eqClassLen {
109
+ return false
110
+ }
111
+
112
+ // Same sharding state length
113
+ eqSSLen := len(s.ShardingState) == len(other.ShardingState)
114
+ if !eqSSLen {
115
+ return false
116
+ }
117
+
118
+ for cls, ss1ss := range s.ShardingState {
119
+ // Same sharding state keys
120
+ ss2ss, ok := other.ShardingState[cls]
121
+ if !ok {
122
+ return false
123
+ }
124
+
125
+ // Same number of physical shards
126
+ eqPhysLen := len(ss1ss.Physical) == len(ss2ss.Physical)
127
+ if !eqPhysLen {
128
+ return false
129
+ }
130
+
131
+ for shard, ss1phys := range ss1ss.Physical {
132
+ // Same physical shard contents and status
133
+ ss2phys, ok := ss2ss.Physical[shard]
134
+ if !ok {
135
+ return false
136
+ }
137
+ eqActivStat := ss1phys.ActivityStatus() == ss2phys.ActivityStatus()
138
+ if !eqActivStat {
139
+ return false
140
+ }
141
+ }
142
+ }
143
+
144
+ return true
145
+ }
146
+
147
+ // SchemaStore is responsible for persisting the schema
148
+ // by providing support for both partial and complete schema updates
149
+ // Deprecated: instead schema now is persistent via RAFT
150
+ // see : usecase/schema/handler.go & cluster/store/store.go
151
+ // Load and save are left to support backward compatibility
152
+ type SchemaStore interface {
153
+ // Save saves the complete schema to the persistent storage
154
+ Save(ctx context.Context, schema State) error
155
+
156
+ // Load loads the complete schema from the persistent storage
157
+ Load(context.Context) (State, error)
158
+ }
159
+
160
+ // KeyValuePair is used to serialize shards updates
161
+ type KeyValuePair struct {
162
+ Key string
163
+ Value []byte
164
+ }
165
+
166
+ // ClassPayload is used to serialize class updates
167
+ type ClassPayload struct {
168
+ Name string
169
+ Metadata []byte
170
+ ShardingState []byte
171
+ Shards []KeyValuePair
172
+ ReplaceShards bool
173
+ Error error
174
+ }
175
+
176
+ type clusterState interface {
177
+ cluster.NodeSelector
178
+ // Hostnames initializes a broadcast
179
+ Hostnames() []string
180
+
181
+ // AllNames initializes shard distribution across nodes
182
+ AllNames() []string
183
+ NodeCount() int
184
+
185
+ // ClusterHealthScore gets the whole cluster health, the lower number the better
186
+ ClusterHealthScore() int
187
+
188
+ SchemaSyncIgnored() bool
189
+ SkipSchemaRepair() bool
190
+ }
191
+
192
+ // NewManager creates a new manager
193
+ func NewManager(validator validator,
194
+ schemaManager SchemaManager,
195
+ schemaReader SchemaReader,
196
+ repo SchemaStore,
197
+ logger logrus.FieldLogger, authorizer authorization.Authorizer,
198
+ schemaConfig *config.SchemaHandlerConfig,
199
+ config config.Config,
200
+ configParser VectorConfigParser, vectorizerValidator VectorizerValidator,
201
+ invertedConfigValidator InvertedConfigValidator,
202
+ moduleConfig ModuleConfig, clusterState clusterState,
203
+ cloud modulecapabilities.OffloadCloud,
204
+ parser Parser,
205
+ collectionRetrievalStrategyFF *configRuntime.FeatureFlag[string],
206
+ ) (*Manager, error) {
207
+ handler, err := NewHandler(
208
+ schemaReader,
209
+ schemaManager,
210
+ validator,
211
+ logger, authorizer,
212
+ schemaConfig,
213
+ config, configParser, vectorizerValidator, invertedConfigValidator,
214
+ moduleConfig, clusterState, cloud, parser, NewClassGetter(&parser, schemaManager, schemaReader, collectionRetrievalStrategyFF, logger),
215
+ )
216
+ if err != nil {
217
+ return nil, fmt.Errorf("cannot init handler: %w", err)
218
+ }
219
+ m := &Manager{
220
+ validator: validator,
221
+ repo: repo,
222
+ logger: logger,
223
+ clusterState: clusterState,
224
+ Handler: handler,
225
+ SchemaReader: schemaReader,
226
+ Authorizer: authorizer,
227
+ }
228
+
229
+ return m, nil
230
+ }
231
+
232
+ // func (m *Manager) migrateSchemaIfNecessary(ctx context.Context, localSchema *State) error {
233
+ // // introduced when Weaviate started supporting multi-shards per class in v1.8
234
+ // if err := m.checkSingleShardMigration(ctx, localSchema); err != nil {
235
+ // return errors.Wrap(err, "migrating sharding state from previous version")
236
+ // }
237
+
238
+ // // introduced when Weaviate started supporting replication in v1.17
239
+ // if err := m.checkShardingStateForReplication(ctx, localSchema); err != nil {
240
+ // return errors.Wrap(err, "migrating sharding state from previous version (before replication)")
241
+ // }
242
+
243
+ // // if other migrations become necessary in the future, you can add them here.
244
+ // return nil
245
+ // }
246
+
247
+ // func (m *Manager) checkSingleShardMigration(ctx context.Context, localSchema *State) error {
248
+ // for _, c := range localSchema.ObjectSchema.Classes {
249
+ // if _, ok := localSchema.ShardingState[c.Class]; ok { // there is sharding state for this class. Nothing to do
250
+ // continue
251
+ // }
252
+
253
+ // m.logger.WithField("className", c.Class).WithField("action", "initialize_schema").
254
+ // Warningf("No sharding state found for class %q, initializing new state. "+
255
+ // "This is expected behavior if the schema was created with an older Weaviate "+
256
+ // "version, prior to supporting multi-shard indices.", c.Class)
257
+
258
+ // // there is no sharding state for this class, let's create the correct
259
+ // // config. This class must have been created prior to the sharding feature,
260
+ // // so we now that the shardCount==1 - we do not care about any of the other
261
+ // // parameters and simply use the defaults for those
262
+ // c.ShardingConfig = map[string]interface{}{
263
+ // "desiredCount": 1,
264
+ // }
265
+ // if err := m.praser.parseShardingConfig(c); err != nil {
266
+ // return err
267
+ // }
268
+
269
+ // if err := replica.ValidateConfig(c, m.config.Replication); err != nil {
270
+ // return fmt.Errorf("validate replication config: %w", err)
271
+ // }
272
+ // shardState, err := sharding.InitState(c.Class,
273
+ // c.ShardingConfig.(sharding.Config),
274
+ // m.clusterState, c.ReplicationConfig.Factor,
275
+ // schema.MultiTenancyEnabled(c))
276
+ // if err != nil {
277
+ // return errors.Wrap(err, "init sharding state")
278
+ // }
279
+
280
+ // if localSchema.ShardingState == nil {
281
+ // localSchema.ShardingState = map[string]*sharding.State{}
282
+ // }
283
+ // localSchema.ShardingState[c.Class] = shardState
284
+
285
+ // }
286
+
287
+ // return nil
288
+ // }
289
+
290
+ // func (m *Manager) checkShardingStateForReplication(ctx context.Context, localSchema *State) error {
291
+ // for _, classState := range localSchema.ShardingState {
292
+ // classState.MigrateFromOldFormat()
293
+ // }
294
+ // return nil
295
+ // }
296
+
297
+ // func newSchema() *State {
298
+ // return &State{
299
+ // ObjectSchema: &models.Schema{
300
+ // Classes: []*models.Class{},
301
+ // },
302
+ // ShardingState: map[string]*sharding.State{},
303
+ // }
304
+ // }
305
+
306
+ func (m *Manager) ClusterHealthScore() int {
307
+ return m.clusterState.ClusterHealthScore()
308
+ }
309
+
310
+ // ResolveParentNodes gets all replicas for a specific class shard and resolves their names
311
+ //
312
+ // it returns map[node_name] node_address where node_address = "" if can't resolve node_name
313
+ func (m *Manager) ResolveParentNodes(class, shardName string) (map[string]string, error) {
314
+ nodes, err := m.ShardReplicas(class, shardName)
315
+ if err != nil {
316
+ return nil, fmt.Errorf("get replicas from schema: %w", err)
317
+ }
318
+
319
+ if len(nodes) == 0 {
320
+ return nil, nil
321
+ }
322
+
323
+ name2Addr := make(map[string]string, len(nodes))
324
+ for _, node := range nodes {
325
+ if node != "" {
326
+ host, _ := m.clusterState.NodeHostname(node)
327
+ name2Addr[node] = host
328
+ }
329
+ }
330
+ return name2Addr, nil
331
+ }
332
+
333
+ func (m *Manager) TenantsShards(ctx context.Context, class string, tenants ...string) (map[string]string, error) {
334
+ slices.Sort(tenants)
335
+ tenants = slices.Compact(tenants)
336
+ status, _, err := m.schemaManager.QueryTenantsShards(class, tenants...)
337
+ if !m.AllowImplicitTenantActivation(class) || err != nil {
338
+ return status, err
339
+ }
340
+
341
+ return m.activateTenantIfInactive(ctx, class, status)
342
+ }
343
+
344
+ // OptimisticTenantStatus tries to query the local state first. It is
345
+ // optimistic that the state has already propagated correctly. If the state is
346
+ // unexpected, i.e. either the tenant is not found at all or the status is
347
+ // COLD, it will double-check with the leader.
348
+ //
349
+ // This way we accept false positives (for HOT tenants), but guarantee that there will never be
350
+ // false negatives (i.e. tenants labelled as COLD that the leader thinks should
351
+ // be HOT).
352
+ //
353
+ // This means:
354
+ //
355
+ // - If a tenant is HOT locally (true positive), we proceed normally
356
+ // - If a tenant is HOT locally, but should be COLD (false positive), we still
357
+ // proceed. This is a conscious decision to keep the happy path free from
358
+ // (expensive) leader lookups.
359
+ // - If a tenant is not found locally, we assume it was recently created, but
360
+ // the state hasn't propagated yet. To verify, we check with the leader.
361
+ // - If a tenant is found locally, but is marked as COLD, we assume it was
362
+ // recently turned HOT, but the state hasn't propagated yet. To verify, we
363
+ // check with the leader
364
+ //
365
+ // Overall, we keep the (very common) happy path, free from expensive
366
+ // leader-lookups and only fall back to the leader if the local result implies
367
+ // an unhappy path.
368
+ func (m *Manager) OptimisticTenantStatus(ctx context.Context, class string, tenant string) (map[string]string, error) {
369
+ var foundTenant bool
370
+ var status string
371
+ err := m.schemaReader.Read(class, func(_ *models.Class, ss *sharding.State) error {
372
+ t, ok := ss.Physical[tenant]
373
+ if !ok {
374
+ return nil
375
+ }
376
+
377
+ foundTenant = true
378
+ status = t.Status
379
+ return nil
380
+ })
381
+ if err != nil {
382
+ return nil, err
383
+ }
384
+
385
+ if !foundTenant || status != models.TenantActivityStatusHOT {
386
+ // either no state at all or state does not imply happy path -> delegate to
387
+ // leader
388
+ return m.TenantsShards(ctx, class, tenant)
389
+ }
390
+
391
+ return map[string]string{
392
+ tenant: status,
393
+ }, nil
394
+ }
395
+
396
+ func (m *Manager) activateTenantIfInactive(ctx context.Context, class string,
397
+ status map[string]string,
398
+ ) (map[string]string, error) {
399
+ req := &api.UpdateTenantsRequest{
400
+ Tenants: make([]*api.Tenant, 0, len(status)),
401
+ ClusterNodes: m.schemaManager.StorageCandidates(),
402
+ ImplicitUpdateRequest: true,
403
+ }
404
+ for tenant, s := range status {
405
+ if s != models.TenantActivityStatusHOT {
406
+ req.Tenants = append(req.Tenants,
407
+ &api.Tenant{Name: tenant, Status: models.TenantActivityStatusHOT})
408
+ }
409
+ }
410
+
411
+ if len(req.Tenants) == 0 {
412
+ // nothing to do, all tenants are already HOT
413
+ return status, nil
414
+ }
415
+
416
+ _, err := m.schemaManager.UpdateTenants(ctx, class, req)
417
+ if err != nil {
418
+ names := make([]string, len(req.Tenants))
419
+ for i, t := range req.Tenants {
420
+ names[i] = t.Name
421
+ }
422
+
423
+ return nil, fmt.Errorf("implicit activation of tenants %s: %w", strings.Join(names, ", "), err)
424
+ }
425
+
426
+ for _, t := range req.Tenants {
427
+ status[t.Name] = models.TenantActivityStatusHOT
428
+ }
429
+
430
+ return status, nil
431
+ }
432
+
433
+ func (m *Manager) AllowImplicitTenantActivation(class string) bool {
434
+ allow := false
435
+ m.schemaReader.Read(class, func(c *models.Class, _ *sharding.State) error {
436
+ allow = schema.AutoTenantActivationEnabled(c)
437
+ return nil
438
+ })
439
+
440
+ return allow
441
+ }
442
+
443
+ func (m *Manager) ShardOwner(class, shard string) (string, error) {
444
+ owner, _, err := m.schemaManager.QueryShardOwner(class, shard)
445
+ if err != nil {
446
+ return "", err
447
+ }
448
+ return owner, nil
449
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/migrator.go ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ // Package migrate provides a simple composer tool, which implements the
13
+ // Migrator interface and can take in any number of migrators which themselves
14
+ // have to implement the interface
15
+ package schema
16
+
17
+ import (
18
+ "context"
19
+
20
+ "github.com/weaviate/weaviate/entities/models"
21
+ schemaConfig "github.com/weaviate/weaviate/entities/schema/config"
22
+ "github.com/weaviate/weaviate/usecases/sharding"
23
+ )
24
+
25
+ type CreateTenantPayload struct {
26
+ Name string
27
+ Status string
28
+ }
29
+
30
+ type UpdateTenantPayload struct {
31
+ Name string
32
+ Status string
33
+ }
34
+
35
+ // Migrator represents both the input and output interface of the Composer
36
+ type Migrator interface {
37
+ AddClass(ctx context.Context, class *models.Class) error
38
+ DropClass(ctx context.Context, className string, hasFrozen bool) error
39
+ // UpdateClass(ctx context.Context, className string,newClassName *string) error
40
+ GetShardsQueueSize(ctx context.Context, className, tenant string) (map[string]int64, error)
41
+ LoadShard(ctx context.Context, class, shard string) error
42
+ DropShard(ctx context.Context, class, shard string) error
43
+ ShutdownShard(ctx context.Context, class, shard string) error
44
+
45
+ AddProperty(ctx context.Context, className string,
46
+ props ...*models.Property) error
47
+ UpdateProperty(ctx context.Context, className string,
48
+ propName string, newName *string) error
49
+ UpdateIndex(ctx context.Context, class *models.Class, shardingState *sharding.State) error
50
+
51
+ NewTenants(ctx context.Context, class *models.Class, creates []*CreateTenantPayload) error
52
+ UpdateTenants(ctx context.Context, class *models.Class, updates []*UpdateTenantPayload, implicitUpdate bool) error
53
+ DeleteTenants(ctx context.Context, class string, tenants []*models.Tenant) error
54
+
55
+ GetShardsStatus(ctx context.Context, className, tenant string) (map[string]string, error)
56
+ UpdateShardStatus(ctx context.Context, className, shardName, targetStatus string, schemaVersion uint64) error
57
+
58
+ UpdateVectorIndexConfig(ctx context.Context, className string, updated schemaConfig.VectorIndexConfig) error
59
+ ValidateVectorIndexConfigsUpdate(old, updated map[string]schemaConfig.VectorIndexConfig) error
60
+ UpdateVectorIndexConfigs(ctx context.Context, className string,
61
+ updated map[string]schemaConfig.VectorIndexConfig) error
62
+ ValidateInvertedIndexConfigUpdate(old, updated *models.InvertedIndexConfig) error
63
+ UpdateInvertedIndexConfig(ctx context.Context, className string,
64
+ updated *models.InvertedIndexConfig) error
65
+ UpdateReplicationConfig(ctx context.Context, className string,
66
+ updated *models.ReplicationConfig) error
67
+ WaitForStartup(context.Context) error
68
+ Shutdown(context.Context) error
69
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/mock_schema_getter.go ADDED
@@ -0,0 +1,777 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ // Code generated by mockery v2.53.2. DO NOT EDIT.
13
+
14
+ package schema
15
+
16
+ import (
17
+ context "context"
18
+
19
+ mock "github.com/stretchr/testify/mock"
20
+ entitiesschema "github.com/weaviate/weaviate/entities/schema"
21
+
22
+ models "github.com/weaviate/weaviate/entities/models"
23
+ )
24
+
25
+ // MockSchemaGetter is an autogenerated mock type for the SchemaGetter type
26
+ type MockSchemaGetter struct {
27
+ mock.Mock
28
+ }
29
+
30
+ type MockSchemaGetter_Expecter struct {
31
+ mock *mock.Mock
32
+ }
33
+
34
+ func (_m *MockSchemaGetter) EXPECT() *MockSchemaGetter_Expecter {
35
+ return &MockSchemaGetter_Expecter{mock: &_m.Mock}
36
+ }
37
+
38
+ // ClusterHealthScore provides a mock function with no fields
39
+ func (_m *MockSchemaGetter) ClusterHealthScore() int {
40
+ ret := _m.Called()
41
+
42
+ if len(ret) == 0 {
43
+ panic("no return value specified for ClusterHealthScore")
44
+ }
45
+
46
+ var r0 int
47
+ if rf, ok := ret.Get(0).(func() int); ok {
48
+ r0 = rf()
49
+ } else {
50
+ r0 = ret.Get(0).(int)
51
+ }
52
+
53
+ return r0
54
+ }
55
+
56
+ // MockSchemaGetter_ClusterHealthScore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClusterHealthScore'
57
+ type MockSchemaGetter_ClusterHealthScore_Call struct {
58
+ *mock.Call
59
+ }
60
+
61
+ // ClusterHealthScore is a helper method to define mock.On call
62
+ func (_e *MockSchemaGetter_Expecter) ClusterHealthScore() *MockSchemaGetter_ClusterHealthScore_Call {
63
+ return &MockSchemaGetter_ClusterHealthScore_Call{Call: _e.mock.On("ClusterHealthScore")}
64
+ }
65
+
66
+ func (_c *MockSchemaGetter_ClusterHealthScore_Call) Run(run func()) *MockSchemaGetter_ClusterHealthScore_Call {
67
+ _c.Call.Run(func(args mock.Arguments) {
68
+ run()
69
+ })
70
+ return _c
71
+ }
72
+
73
+ func (_c *MockSchemaGetter_ClusterHealthScore_Call) Return(_a0 int) *MockSchemaGetter_ClusterHealthScore_Call {
74
+ _c.Call.Return(_a0)
75
+ return _c
76
+ }
77
+
78
+ func (_c *MockSchemaGetter_ClusterHealthScore_Call) RunAndReturn(run func() int) *MockSchemaGetter_ClusterHealthScore_Call {
79
+ _c.Call.Return(run)
80
+ return _c
81
+ }
82
+
83
+ // GetAliasesForClass provides a mock function with given fields: class
84
+ func (_m *MockSchemaGetter) GetAliasesForClass(class string) []*models.Alias {
85
+ ret := _m.Called(class)
86
+
87
+ if len(ret) == 0 {
88
+ panic("no return value specified for GetAliasesForClass")
89
+ }
90
+
91
+ var r0 []*models.Alias
92
+ if rf, ok := ret.Get(0).(func(string) []*models.Alias); ok {
93
+ r0 = rf(class)
94
+ } else {
95
+ if ret.Get(0) != nil {
96
+ r0 = ret.Get(0).([]*models.Alias)
97
+ }
98
+ }
99
+
100
+ return r0
101
+ }
102
+
103
+ // MockSchemaGetter_GetAliasesForClass_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAliasesForClass'
104
+ type MockSchemaGetter_GetAliasesForClass_Call struct {
105
+ *mock.Call
106
+ }
107
+
108
+ // GetAliasesForClass is a helper method to define mock.On call
109
+ // - class string
110
+ func (_e *MockSchemaGetter_Expecter) GetAliasesForClass(class interface{}) *MockSchemaGetter_GetAliasesForClass_Call {
111
+ return &MockSchemaGetter_GetAliasesForClass_Call{Call: _e.mock.On("GetAliasesForClass", class)}
112
+ }
113
+
114
+ func (_c *MockSchemaGetter_GetAliasesForClass_Call) Run(run func(class string)) *MockSchemaGetter_GetAliasesForClass_Call {
115
+ _c.Call.Run(func(args mock.Arguments) {
116
+ run(args[0].(string))
117
+ })
118
+ return _c
119
+ }
120
+
121
+ func (_c *MockSchemaGetter_GetAliasesForClass_Call) Return(_a0 []*models.Alias) *MockSchemaGetter_GetAliasesForClass_Call {
122
+ _c.Call.Return(_a0)
123
+ return _c
124
+ }
125
+
126
+ func (_c *MockSchemaGetter_GetAliasesForClass_Call) RunAndReturn(run func(string) []*models.Alias) *MockSchemaGetter_GetAliasesForClass_Call {
127
+ _c.Call.Return(run)
128
+ return _c
129
+ }
130
+
131
+ // GetSchemaSkipAuth provides a mock function with no fields
132
+ func (_m *MockSchemaGetter) GetSchemaSkipAuth() entitiesschema.Schema {
133
+ ret := _m.Called()
134
+
135
+ if len(ret) == 0 {
136
+ panic("no return value specified for GetSchemaSkipAuth")
137
+ }
138
+
139
+ var r0 entitiesschema.Schema
140
+ if rf, ok := ret.Get(0).(func() entitiesschema.Schema); ok {
141
+ r0 = rf()
142
+ } else {
143
+ r0 = ret.Get(0).(entitiesschema.Schema)
144
+ }
145
+
146
+ return r0
147
+ }
148
+
149
+ // MockSchemaGetter_GetSchemaSkipAuth_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSchemaSkipAuth'
150
+ type MockSchemaGetter_GetSchemaSkipAuth_Call struct {
151
+ *mock.Call
152
+ }
153
+
154
+ // GetSchemaSkipAuth is a helper method to define mock.On call
155
+ func (_e *MockSchemaGetter_Expecter) GetSchemaSkipAuth() *MockSchemaGetter_GetSchemaSkipAuth_Call {
156
+ return &MockSchemaGetter_GetSchemaSkipAuth_Call{Call: _e.mock.On("GetSchemaSkipAuth")}
157
+ }
158
+
159
+ func (_c *MockSchemaGetter_GetSchemaSkipAuth_Call) Run(run func()) *MockSchemaGetter_GetSchemaSkipAuth_Call {
160
+ _c.Call.Run(func(args mock.Arguments) {
161
+ run()
162
+ })
163
+ return _c
164
+ }
165
+
166
+ func (_c *MockSchemaGetter_GetSchemaSkipAuth_Call) Return(_a0 entitiesschema.Schema) *MockSchemaGetter_GetSchemaSkipAuth_Call {
167
+ _c.Call.Return(_a0)
168
+ return _c
169
+ }
170
+
171
+ func (_c *MockSchemaGetter_GetSchemaSkipAuth_Call) RunAndReturn(run func() entitiesschema.Schema) *MockSchemaGetter_GetSchemaSkipAuth_Call {
172
+ _c.Call.Return(run)
173
+ return _c
174
+ }
175
+
176
+ // NodeName provides a mock function with no fields
177
+ func (_m *MockSchemaGetter) NodeName() string {
178
+ ret := _m.Called()
179
+
180
+ if len(ret) == 0 {
181
+ panic("no return value specified for NodeName")
182
+ }
183
+
184
+ var r0 string
185
+ if rf, ok := ret.Get(0).(func() string); ok {
186
+ r0 = rf()
187
+ } else {
188
+ r0 = ret.Get(0).(string)
189
+ }
190
+
191
+ return r0
192
+ }
193
+
194
+ // MockSchemaGetter_NodeName_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NodeName'
195
+ type MockSchemaGetter_NodeName_Call struct {
196
+ *mock.Call
197
+ }
198
+
199
+ // NodeName is a helper method to define mock.On call
200
+ func (_e *MockSchemaGetter_Expecter) NodeName() *MockSchemaGetter_NodeName_Call {
201
+ return &MockSchemaGetter_NodeName_Call{Call: _e.mock.On("NodeName")}
202
+ }
203
+
204
+ func (_c *MockSchemaGetter_NodeName_Call) Run(run func()) *MockSchemaGetter_NodeName_Call {
205
+ _c.Call.Run(func(args mock.Arguments) {
206
+ run()
207
+ })
208
+ return _c
209
+ }
210
+
211
+ func (_c *MockSchemaGetter_NodeName_Call) Return(_a0 string) *MockSchemaGetter_NodeName_Call {
212
+ _c.Call.Return(_a0)
213
+ return _c
214
+ }
215
+
216
+ func (_c *MockSchemaGetter_NodeName_Call) RunAndReturn(run func() string) *MockSchemaGetter_NodeName_Call {
217
+ _c.Call.Return(run)
218
+ return _c
219
+ }
220
+
221
+ // Nodes provides a mock function with no fields
222
+ func (_m *MockSchemaGetter) Nodes() []string {
223
+ ret := _m.Called()
224
+
225
+ if len(ret) == 0 {
226
+ panic("no return value specified for Nodes")
227
+ }
228
+
229
+ var r0 []string
230
+ if rf, ok := ret.Get(0).(func() []string); ok {
231
+ r0 = rf()
232
+ } else {
233
+ if ret.Get(0) != nil {
234
+ r0 = ret.Get(0).([]string)
235
+ }
236
+ }
237
+
238
+ return r0
239
+ }
240
+
241
+ // MockSchemaGetter_Nodes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Nodes'
242
+ type MockSchemaGetter_Nodes_Call struct {
243
+ *mock.Call
244
+ }
245
+
246
+ // Nodes is a helper method to define mock.On call
247
+ func (_e *MockSchemaGetter_Expecter) Nodes() *MockSchemaGetter_Nodes_Call {
248
+ return &MockSchemaGetter_Nodes_Call{Call: _e.mock.On("Nodes")}
249
+ }
250
+
251
+ func (_c *MockSchemaGetter_Nodes_Call) Run(run func()) *MockSchemaGetter_Nodes_Call {
252
+ _c.Call.Run(func(args mock.Arguments) {
253
+ run()
254
+ })
255
+ return _c
256
+ }
257
+
258
+ func (_c *MockSchemaGetter_Nodes_Call) Return(_a0 []string) *MockSchemaGetter_Nodes_Call {
259
+ _c.Call.Return(_a0)
260
+ return _c
261
+ }
262
+
263
+ func (_c *MockSchemaGetter_Nodes_Call) RunAndReturn(run func() []string) *MockSchemaGetter_Nodes_Call {
264
+ _c.Call.Return(run)
265
+ return _c
266
+ }
267
+
268
+ // OptimisticTenantStatus provides a mock function with given fields: ctx, class, tenants
269
+ func (_m *MockSchemaGetter) OptimisticTenantStatus(ctx context.Context, class string, tenants string) (map[string]string, error) {
270
+ ret := _m.Called(ctx, class, tenants)
271
+
272
+ if len(ret) == 0 {
273
+ panic("no return value specified for OptimisticTenantStatus")
274
+ }
275
+
276
+ var r0 map[string]string
277
+ var r1 error
278
+ if rf, ok := ret.Get(0).(func(context.Context, string, string) (map[string]string, error)); ok {
279
+ return rf(ctx, class, tenants)
280
+ }
281
+ if rf, ok := ret.Get(0).(func(context.Context, string, string) map[string]string); ok {
282
+ r0 = rf(ctx, class, tenants)
283
+ } else {
284
+ if ret.Get(0) != nil {
285
+ r0 = ret.Get(0).(map[string]string)
286
+ }
287
+ }
288
+
289
+ if rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok {
290
+ r1 = rf(ctx, class, tenants)
291
+ } else {
292
+ r1 = ret.Error(1)
293
+ }
294
+
295
+ return r0, r1
296
+ }
297
+
298
+ // MockSchemaGetter_OptimisticTenantStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OptimisticTenantStatus'
299
+ type MockSchemaGetter_OptimisticTenantStatus_Call struct {
300
+ *mock.Call
301
+ }
302
+
303
+ // OptimisticTenantStatus is a helper method to define mock.On call
304
+ // - ctx context.Context
305
+ // - class string
306
+ // - tenants string
307
+ func (_e *MockSchemaGetter_Expecter) OptimisticTenantStatus(ctx interface{}, class interface{}, tenants interface{}) *MockSchemaGetter_OptimisticTenantStatus_Call {
308
+ return &MockSchemaGetter_OptimisticTenantStatus_Call{Call: _e.mock.On("OptimisticTenantStatus", ctx, class, tenants)}
309
+ }
310
+
311
+ func (_c *MockSchemaGetter_OptimisticTenantStatus_Call) Run(run func(ctx context.Context, class string, tenants string)) *MockSchemaGetter_OptimisticTenantStatus_Call {
312
+ _c.Call.Run(func(args mock.Arguments) {
313
+ run(args[0].(context.Context), args[1].(string), args[2].(string))
314
+ })
315
+ return _c
316
+ }
317
+
318
+ func (_c *MockSchemaGetter_OptimisticTenantStatus_Call) Return(_a0 map[string]string, _a1 error) *MockSchemaGetter_OptimisticTenantStatus_Call {
319
+ _c.Call.Return(_a0, _a1)
320
+ return _c
321
+ }
322
+
323
+ func (_c *MockSchemaGetter_OptimisticTenantStatus_Call) RunAndReturn(run func(context.Context, string, string) (map[string]string, error)) *MockSchemaGetter_OptimisticTenantStatus_Call {
324
+ _c.Call.Return(run)
325
+ return _c
326
+ }
327
+
328
+ // ReadOnlyClass provides a mock function with given fields: _a0
329
+ func (_m *MockSchemaGetter) ReadOnlyClass(_a0 string) *models.Class {
330
+ ret := _m.Called(_a0)
331
+
332
+ if len(ret) == 0 {
333
+ panic("no return value specified for ReadOnlyClass")
334
+ }
335
+
336
+ var r0 *models.Class
337
+ if rf, ok := ret.Get(0).(func(string) *models.Class); ok {
338
+ r0 = rf(_a0)
339
+ } else {
340
+ if ret.Get(0) != nil {
341
+ r0 = ret.Get(0).(*models.Class)
342
+ }
343
+ }
344
+
345
+ return r0
346
+ }
347
+
348
+ // MockSchemaGetter_ReadOnlyClass_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadOnlyClass'
349
+ type MockSchemaGetter_ReadOnlyClass_Call struct {
350
+ *mock.Call
351
+ }
352
+
353
+ // ReadOnlyClass is a helper method to define mock.On call
354
+ // - _a0 string
355
+ func (_e *MockSchemaGetter_Expecter) ReadOnlyClass(_a0 interface{}) *MockSchemaGetter_ReadOnlyClass_Call {
356
+ return &MockSchemaGetter_ReadOnlyClass_Call{Call: _e.mock.On("ReadOnlyClass", _a0)}
357
+ }
358
+
359
+ func (_c *MockSchemaGetter_ReadOnlyClass_Call) Run(run func(_a0 string)) *MockSchemaGetter_ReadOnlyClass_Call {
360
+ _c.Call.Run(func(args mock.Arguments) {
361
+ run(args[0].(string))
362
+ })
363
+ return _c
364
+ }
365
+
366
+ func (_c *MockSchemaGetter_ReadOnlyClass_Call) Return(_a0 *models.Class) *MockSchemaGetter_ReadOnlyClass_Call {
367
+ _c.Call.Return(_a0)
368
+ return _c
369
+ }
370
+
371
+ func (_c *MockSchemaGetter_ReadOnlyClass_Call) RunAndReturn(run func(string) *models.Class) *MockSchemaGetter_ReadOnlyClass_Call {
372
+ _c.Call.Return(run)
373
+ return _c
374
+ }
375
+
376
+ // ResolveAlias provides a mock function with given fields: _a0
377
+ func (_m *MockSchemaGetter) ResolveAlias(_a0 string) string {
378
+ ret := _m.Called(_a0)
379
+
380
+ if len(ret) == 0 {
381
+ panic("no return value specified for ResolveAlias")
382
+ }
383
+
384
+ var r0 string
385
+ if rf, ok := ret.Get(0).(func(string) string); ok {
386
+ r0 = rf(_a0)
387
+ } else {
388
+ r0 = ret.Get(0).(string)
389
+ }
390
+
391
+ return r0
392
+ }
393
+
394
+ // MockSchemaGetter_ResolveAlias_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ResolveAlias'
395
+ type MockSchemaGetter_ResolveAlias_Call struct {
396
+ *mock.Call
397
+ }
398
+
399
+ // ResolveAlias is a helper method to define mock.On call
400
+ // - _a0 string
401
+ func (_e *MockSchemaGetter_Expecter) ResolveAlias(_a0 interface{}) *MockSchemaGetter_ResolveAlias_Call {
402
+ return &MockSchemaGetter_ResolveAlias_Call{Call: _e.mock.On("ResolveAlias", _a0)}
403
+ }
404
+
405
+ func (_c *MockSchemaGetter_ResolveAlias_Call) Run(run func(_a0 string)) *MockSchemaGetter_ResolveAlias_Call {
406
+ _c.Call.Run(func(args mock.Arguments) {
407
+ run(args[0].(string))
408
+ })
409
+ return _c
410
+ }
411
+
412
+ func (_c *MockSchemaGetter_ResolveAlias_Call) Return(_a0 string) *MockSchemaGetter_ResolveAlias_Call {
413
+ _c.Call.Return(_a0)
414
+ return _c
415
+ }
416
+
417
+ func (_c *MockSchemaGetter_ResolveAlias_Call) RunAndReturn(run func(string) string) *MockSchemaGetter_ResolveAlias_Call {
418
+ _c.Call.Return(run)
419
+ return _c
420
+ }
421
+
422
+ // ResolveParentNodes provides a mock function with given fields: _a0, _a1
423
+ func (_m *MockSchemaGetter) ResolveParentNodes(_a0 string, _a1 string) (map[string]string, error) {
424
+ ret := _m.Called(_a0, _a1)
425
+
426
+ if len(ret) == 0 {
427
+ panic("no return value specified for ResolveParentNodes")
428
+ }
429
+
430
+ var r0 map[string]string
431
+ var r1 error
432
+ if rf, ok := ret.Get(0).(func(string, string) (map[string]string, error)); ok {
433
+ return rf(_a0, _a1)
434
+ }
435
+ if rf, ok := ret.Get(0).(func(string, string) map[string]string); ok {
436
+ r0 = rf(_a0, _a1)
437
+ } else {
438
+ if ret.Get(0) != nil {
439
+ r0 = ret.Get(0).(map[string]string)
440
+ }
441
+ }
442
+
443
+ if rf, ok := ret.Get(1).(func(string, string) error); ok {
444
+ r1 = rf(_a0, _a1)
445
+ } else {
446
+ r1 = ret.Error(1)
447
+ }
448
+
449
+ return r0, r1
450
+ }
451
+
452
+ // MockSchemaGetter_ResolveParentNodes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ResolveParentNodes'
453
+ type MockSchemaGetter_ResolveParentNodes_Call struct {
454
+ *mock.Call
455
+ }
456
+
457
+ // ResolveParentNodes is a helper method to define mock.On call
458
+ // - _a0 string
459
+ // - _a1 string
460
+ func (_e *MockSchemaGetter_Expecter) ResolveParentNodes(_a0 interface{}, _a1 interface{}) *MockSchemaGetter_ResolveParentNodes_Call {
461
+ return &MockSchemaGetter_ResolveParentNodes_Call{Call: _e.mock.On("ResolveParentNodes", _a0, _a1)}
462
+ }
463
+
464
+ func (_c *MockSchemaGetter_ResolveParentNodes_Call) Run(run func(_a0 string, _a1 string)) *MockSchemaGetter_ResolveParentNodes_Call {
465
+ _c.Call.Run(func(args mock.Arguments) {
466
+ run(args[0].(string), args[1].(string))
467
+ })
468
+ return _c
469
+ }
470
+
471
+ func (_c *MockSchemaGetter_ResolveParentNodes_Call) Return(_a0 map[string]string, _a1 error) *MockSchemaGetter_ResolveParentNodes_Call {
472
+ _c.Call.Return(_a0, _a1)
473
+ return _c
474
+ }
475
+
476
+ func (_c *MockSchemaGetter_ResolveParentNodes_Call) RunAndReturn(run func(string, string) (map[string]string, error)) *MockSchemaGetter_ResolveParentNodes_Call {
477
+ _c.Call.Return(run)
478
+ return _c
479
+ }
480
+
481
+ // ShardFromUUID provides a mock function with given fields: class, uuid
482
+ func (_m *MockSchemaGetter) ShardFromUUID(class string, uuid []byte) string {
483
+ ret := _m.Called(class, uuid)
484
+
485
+ if len(ret) == 0 {
486
+ panic("no return value specified for ShardFromUUID")
487
+ }
488
+
489
+ var r0 string
490
+ if rf, ok := ret.Get(0).(func(string, []byte) string); ok {
491
+ r0 = rf(class, uuid)
492
+ } else {
493
+ r0 = ret.Get(0).(string)
494
+ }
495
+
496
+ return r0
497
+ }
498
+
499
+ // MockSchemaGetter_ShardFromUUID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShardFromUUID'
500
+ type MockSchemaGetter_ShardFromUUID_Call struct {
501
+ *mock.Call
502
+ }
503
+
504
+ // ShardFromUUID is a helper method to define mock.On call
505
+ // - class string
506
+ // - uuid []byte
507
+ func (_e *MockSchemaGetter_Expecter) ShardFromUUID(class interface{}, uuid interface{}) *MockSchemaGetter_ShardFromUUID_Call {
508
+ return &MockSchemaGetter_ShardFromUUID_Call{Call: _e.mock.On("ShardFromUUID", class, uuid)}
509
+ }
510
+
511
+ func (_c *MockSchemaGetter_ShardFromUUID_Call) Run(run func(class string, uuid []byte)) *MockSchemaGetter_ShardFromUUID_Call {
512
+ _c.Call.Run(func(args mock.Arguments) {
513
+ run(args[0].(string), args[1].([]byte))
514
+ })
515
+ return _c
516
+ }
517
+
518
+ func (_c *MockSchemaGetter_ShardFromUUID_Call) Return(_a0 string) *MockSchemaGetter_ShardFromUUID_Call {
519
+ _c.Call.Return(_a0)
520
+ return _c
521
+ }
522
+
523
+ func (_c *MockSchemaGetter_ShardFromUUID_Call) RunAndReturn(run func(string, []byte) string) *MockSchemaGetter_ShardFromUUID_Call {
524
+ _c.Call.Return(run)
525
+ return _c
526
+ }
527
+
528
+ // ShardOwner provides a mock function with given fields: class, shard
529
+ func (_m *MockSchemaGetter) ShardOwner(class string, shard string) (string, error) {
530
+ ret := _m.Called(class, shard)
531
+
532
+ if len(ret) == 0 {
533
+ panic("no return value specified for ShardOwner")
534
+ }
535
+
536
+ var r0 string
537
+ var r1 error
538
+ if rf, ok := ret.Get(0).(func(string, string) (string, error)); ok {
539
+ return rf(class, shard)
540
+ }
541
+ if rf, ok := ret.Get(0).(func(string, string) string); ok {
542
+ r0 = rf(class, shard)
543
+ } else {
544
+ r0 = ret.Get(0).(string)
545
+ }
546
+
547
+ if rf, ok := ret.Get(1).(func(string, string) error); ok {
548
+ r1 = rf(class, shard)
549
+ } else {
550
+ r1 = ret.Error(1)
551
+ }
552
+
553
+ return r0, r1
554
+ }
555
+
556
+ // MockSchemaGetter_ShardOwner_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShardOwner'
557
+ type MockSchemaGetter_ShardOwner_Call struct {
558
+ *mock.Call
559
+ }
560
+
561
+ // ShardOwner is a helper method to define mock.On call
562
+ // - class string
563
+ // - shard string
564
+ func (_e *MockSchemaGetter_Expecter) ShardOwner(class interface{}, shard interface{}) *MockSchemaGetter_ShardOwner_Call {
565
+ return &MockSchemaGetter_ShardOwner_Call{Call: _e.mock.On("ShardOwner", class, shard)}
566
+ }
567
+
568
+ func (_c *MockSchemaGetter_ShardOwner_Call) Run(run func(class string, shard string)) *MockSchemaGetter_ShardOwner_Call {
569
+ _c.Call.Run(func(args mock.Arguments) {
570
+ run(args[0].(string), args[1].(string))
571
+ })
572
+ return _c
573
+ }
574
+
575
+ func (_c *MockSchemaGetter_ShardOwner_Call) Return(_a0 string, _a1 error) *MockSchemaGetter_ShardOwner_Call {
576
+ _c.Call.Return(_a0, _a1)
577
+ return _c
578
+ }
579
+
580
+ func (_c *MockSchemaGetter_ShardOwner_Call) RunAndReturn(run func(string, string) (string, error)) *MockSchemaGetter_ShardOwner_Call {
581
+ _c.Call.Return(run)
582
+ return _c
583
+ }
584
+
585
+ // ShardReplicas provides a mock function with given fields: class, shard
586
+ func (_m *MockSchemaGetter) ShardReplicas(class string, shard string) ([]string, error) {
587
+ ret := _m.Called(class, shard)
588
+
589
+ if len(ret) == 0 {
590
+ panic("no return value specified for ShardReplicas")
591
+ }
592
+
593
+ var r0 []string
594
+ var r1 error
595
+ if rf, ok := ret.Get(0).(func(string, string) ([]string, error)); ok {
596
+ return rf(class, shard)
597
+ }
598
+ if rf, ok := ret.Get(0).(func(string, string) []string); ok {
599
+ r0 = rf(class, shard)
600
+ } else {
601
+ if ret.Get(0) != nil {
602
+ r0 = ret.Get(0).([]string)
603
+ }
604
+ }
605
+
606
+ if rf, ok := ret.Get(1).(func(string, string) error); ok {
607
+ r1 = rf(class, shard)
608
+ } else {
609
+ r1 = ret.Error(1)
610
+ }
611
+
612
+ return r0, r1
613
+ }
614
+
615
+ // MockSchemaGetter_ShardReplicas_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShardReplicas'
616
+ type MockSchemaGetter_ShardReplicas_Call struct {
617
+ *mock.Call
618
+ }
619
+
620
+ // ShardReplicas is a helper method to define mock.On call
621
+ // - class string
622
+ // - shard string
623
+ func (_e *MockSchemaGetter_Expecter) ShardReplicas(class interface{}, shard interface{}) *MockSchemaGetter_ShardReplicas_Call {
624
+ return &MockSchemaGetter_ShardReplicas_Call{Call: _e.mock.On("ShardReplicas", class, shard)}
625
+ }
626
+
627
+ func (_c *MockSchemaGetter_ShardReplicas_Call) Run(run func(class string, shard string)) *MockSchemaGetter_ShardReplicas_Call {
628
+ _c.Call.Run(func(args mock.Arguments) {
629
+ run(args[0].(string), args[1].(string))
630
+ })
631
+ return _c
632
+ }
633
+
634
+ func (_c *MockSchemaGetter_ShardReplicas_Call) Return(_a0 []string, _a1 error) *MockSchemaGetter_ShardReplicas_Call {
635
+ _c.Call.Return(_a0, _a1)
636
+ return _c
637
+ }
638
+
639
+ func (_c *MockSchemaGetter_ShardReplicas_Call) RunAndReturn(run func(string, string) ([]string, error)) *MockSchemaGetter_ShardReplicas_Call {
640
+ _c.Call.Return(run)
641
+ return _c
642
+ }
643
+
644
+ // Statistics provides a mock function with no fields
645
+ func (_m *MockSchemaGetter) Statistics() map[string]interface{} {
646
+ ret := _m.Called()
647
+
648
+ if len(ret) == 0 {
649
+ panic("no return value specified for Statistics")
650
+ }
651
+
652
+ var r0 map[string]interface{}
653
+ if rf, ok := ret.Get(0).(func() map[string]interface{}); ok {
654
+ r0 = rf()
655
+ } else {
656
+ if ret.Get(0) != nil {
657
+ r0 = ret.Get(0).(map[string]interface{})
658
+ }
659
+ }
660
+
661
+ return r0
662
+ }
663
+
664
+ // MockSchemaGetter_Statistics_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Statistics'
665
+ type MockSchemaGetter_Statistics_Call struct {
666
+ *mock.Call
667
+ }
668
+
669
+ // Statistics is a helper method to define mock.On call
670
+ func (_e *MockSchemaGetter_Expecter) Statistics() *MockSchemaGetter_Statistics_Call {
671
+ return &MockSchemaGetter_Statistics_Call{Call: _e.mock.On("Statistics")}
672
+ }
673
+
674
+ func (_c *MockSchemaGetter_Statistics_Call) Run(run func()) *MockSchemaGetter_Statistics_Call {
675
+ _c.Call.Run(func(args mock.Arguments) {
676
+ run()
677
+ })
678
+ return _c
679
+ }
680
+
681
+ func (_c *MockSchemaGetter_Statistics_Call) Return(_a0 map[string]interface{}) *MockSchemaGetter_Statistics_Call {
682
+ _c.Call.Return(_a0)
683
+ return _c
684
+ }
685
+
686
+ func (_c *MockSchemaGetter_Statistics_Call) RunAndReturn(run func() map[string]interface{}) *MockSchemaGetter_Statistics_Call {
687
+ _c.Call.Return(run)
688
+ return _c
689
+ }
690
+
691
+ // TenantsShards provides a mock function with given fields: ctx, class, tenants
692
+ func (_m *MockSchemaGetter) TenantsShards(ctx context.Context, class string, tenants ...string) (map[string]string, error) {
693
+ _va := make([]interface{}, len(tenants))
694
+ for _i := range tenants {
695
+ _va[_i] = tenants[_i]
696
+ }
697
+ var _ca []interface{}
698
+ _ca = append(_ca, ctx, class)
699
+ _ca = append(_ca, _va...)
700
+ ret := _m.Called(_ca...)
701
+
702
+ if len(ret) == 0 {
703
+ panic("no return value specified for TenantsShards")
704
+ }
705
+
706
+ var r0 map[string]string
707
+ var r1 error
708
+ if rf, ok := ret.Get(0).(func(context.Context, string, ...string) (map[string]string, error)); ok {
709
+ return rf(ctx, class, tenants...)
710
+ }
711
+ if rf, ok := ret.Get(0).(func(context.Context, string, ...string) map[string]string); ok {
712
+ r0 = rf(ctx, class, tenants...)
713
+ } else {
714
+ if ret.Get(0) != nil {
715
+ r0 = ret.Get(0).(map[string]string)
716
+ }
717
+ }
718
+
719
+ if rf, ok := ret.Get(1).(func(context.Context, string, ...string) error); ok {
720
+ r1 = rf(ctx, class, tenants...)
721
+ } else {
722
+ r1 = ret.Error(1)
723
+ }
724
+
725
+ return r0, r1
726
+ }
727
+
728
+ // MockSchemaGetter_TenantsShards_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TenantsShards'
729
+ type MockSchemaGetter_TenantsShards_Call struct {
730
+ *mock.Call
731
+ }
732
+
733
+ // TenantsShards is a helper method to define mock.On call
734
+ // - ctx context.Context
735
+ // - class string
736
+ // - tenants ...string
737
+ func (_e *MockSchemaGetter_Expecter) TenantsShards(ctx interface{}, class interface{}, tenants ...interface{}) *MockSchemaGetter_TenantsShards_Call {
738
+ return &MockSchemaGetter_TenantsShards_Call{Call: _e.mock.On("TenantsShards",
739
+ append([]interface{}{ctx, class}, tenants...)...)}
740
+ }
741
+
742
+ func (_c *MockSchemaGetter_TenantsShards_Call) Run(run func(ctx context.Context, class string, tenants ...string)) *MockSchemaGetter_TenantsShards_Call {
743
+ _c.Call.Run(func(args mock.Arguments) {
744
+ variadicArgs := make([]string, len(args)-2)
745
+ for i, a := range args[2:] {
746
+ if a != nil {
747
+ variadicArgs[i] = a.(string)
748
+ }
749
+ }
750
+ run(args[0].(context.Context), args[1].(string), variadicArgs...)
751
+ })
752
+ return _c
753
+ }
754
+
755
+ func (_c *MockSchemaGetter_TenantsShards_Call) Return(_a0 map[string]string, _a1 error) *MockSchemaGetter_TenantsShards_Call {
756
+ _c.Call.Return(_a0, _a1)
757
+ return _c
758
+ }
759
+
760
+ func (_c *MockSchemaGetter_TenantsShards_Call) RunAndReturn(run func(context.Context, string, ...string) (map[string]string, error)) *MockSchemaGetter_TenantsShards_Call {
761
+ _c.Call.Return(run)
762
+ return _c
763
+ }
764
+
765
+ // NewMockSchemaGetter creates a new instance of MockSchemaGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
766
+ // The first argument is typically a *testing.T value.
767
+ func NewMockSchemaGetter(t interface {
768
+ mock.TestingT
769
+ Cleanup(func())
770
+ }) *MockSchemaGetter {
771
+ mock := &MockSchemaGetter{}
772
+ mock.Mock.Test(t)
773
+
774
+ t.Cleanup(func() { mock.AssertExpectations(t) })
775
+
776
+ return mock
777
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/mock_schema_reader.go ADDED
@@ -0,0 +1,1335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ // Code generated by mockery v2.53.2. DO NOT EDIT.
13
+
14
+ package schema
15
+
16
+ import (
17
+ context "context"
18
+
19
+ clusterschema "github.com/weaviate/weaviate/cluster/schema"
20
+
21
+ mock "github.com/stretchr/testify/mock"
22
+
23
+ models "github.com/weaviate/weaviate/entities/models"
24
+
25
+ sharding "github.com/weaviate/weaviate/usecases/sharding"
26
+
27
+ versioned "github.com/weaviate/weaviate/entities/versioned"
28
+ )
29
+
30
+ // MockSchemaReader is an autogenerated mock type for the SchemaReader type
31
+ type MockSchemaReader struct {
32
+ mock.Mock
33
+ }
34
+
35
+ type MockSchemaReader_Expecter struct {
36
+ mock *mock.Mock
37
+ }
38
+
39
+ func (_m *MockSchemaReader) EXPECT() *MockSchemaReader_Expecter {
40
+ return &MockSchemaReader_Expecter{mock: &_m.Mock}
41
+ }
42
+
43
+ // Aliases provides a mock function with no fields
44
+ func (_m *MockSchemaReader) Aliases() map[string]string {
45
+ ret := _m.Called()
46
+
47
+ if len(ret) == 0 {
48
+ panic("no return value specified for Aliases")
49
+ }
50
+
51
+ var r0 map[string]string
52
+ if rf, ok := ret.Get(0).(func() map[string]string); ok {
53
+ r0 = rf()
54
+ } else {
55
+ if ret.Get(0) != nil {
56
+ r0 = ret.Get(0).(map[string]string)
57
+ }
58
+ }
59
+
60
+ return r0
61
+ }
62
+
63
+ // MockSchemaReader_Aliases_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Aliases'
64
+ type MockSchemaReader_Aliases_Call struct {
65
+ *mock.Call
66
+ }
67
+
68
+ // Aliases is a helper method to define mock.On call
69
+ func (_e *MockSchemaReader_Expecter) Aliases() *MockSchemaReader_Aliases_Call {
70
+ return &MockSchemaReader_Aliases_Call{Call: _e.mock.On("Aliases")}
71
+ }
72
+
73
+ func (_c *MockSchemaReader_Aliases_Call) Run(run func()) *MockSchemaReader_Aliases_Call {
74
+ _c.Call.Run(func(args mock.Arguments) {
75
+ run()
76
+ })
77
+ return _c
78
+ }
79
+
80
+ func (_c *MockSchemaReader_Aliases_Call) Return(_a0 map[string]string) *MockSchemaReader_Aliases_Call {
81
+ _c.Call.Return(_a0)
82
+ return _c
83
+ }
84
+
85
+ func (_c *MockSchemaReader_Aliases_Call) RunAndReturn(run func() map[string]string) *MockSchemaReader_Aliases_Call {
86
+ _c.Call.Return(run)
87
+ return _c
88
+ }
89
+
90
+ // ClassEqual provides a mock function with given fields: name
91
+ func (_m *MockSchemaReader) ClassEqual(name string) string {
92
+ ret := _m.Called(name)
93
+
94
+ if len(ret) == 0 {
95
+ panic("no return value specified for ClassEqual")
96
+ }
97
+
98
+ var r0 string
99
+ if rf, ok := ret.Get(0).(func(string) string); ok {
100
+ r0 = rf(name)
101
+ } else {
102
+ r0 = ret.Get(0).(string)
103
+ }
104
+
105
+ return r0
106
+ }
107
+
108
+ // MockSchemaReader_ClassEqual_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClassEqual'
109
+ type MockSchemaReader_ClassEqual_Call struct {
110
+ *mock.Call
111
+ }
112
+
113
+ // ClassEqual is a helper method to define mock.On call
114
+ // - name string
115
+ func (_e *MockSchemaReader_Expecter) ClassEqual(name interface{}) *MockSchemaReader_ClassEqual_Call {
116
+ return &MockSchemaReader_ClassEqual_Call{Call: _e.mock.On("ClassEqual", name)}
117
+ }
118
+
119
+ func (_c *MockSchemaReader_ClassEqual_Call) Run(run func(name string)) *MockSchemaReader_ClassEqual_Call {
120
+ _c.Call.Run(func(args mock.Arguments) {
121
+ run(args[0].(string))
122
+ })
123
+ return _c
124
+ }
125
+
126
+ func (_c *MockSchemaReader_ClassEqual_Call) Return(_a0 string) *MockSchemaReader_ClassEqual_Call {
127
+ _c.Call.Return(_a0)
128
+ return _c
129
+ }
130
+
131
+ func (_c *MockSchemaReader_ClassEqual_Call) RunAndReturn(run func(string) string) *MockSchemaReader_ClassEqual_Call {
132
+ _c.Call.Return(run)
133
+ return _c
134
+ }
135
+
136
+ // ClassInfo provides a mock function with given fields: class
137
+ func (_m *MockSchemaReader) ClassInfo(class string) clusterschema.ClassInfo {
138
+ ret := _m.Called(class)
139
+
140
+ if len(ret) == 0 {
141
+ panic("no return value specified for ClassInfo")
142
+ }
143
+
144
+ var r0 clusterschema.ClassInfo
145
+ if rf, ok := ret.Get(0).(func(string) clusterschema.ClassInfo); ok {
146
+ r0 = rf(class)
147
+ } else {
148
+ r0 = ret.Get(0).(clusterschema.ClassInfo)
149
+ }
150
+
151
+ return r0
152
+ }
153
+
154
+ // MockSchemaReader_ClassInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClassInfo'
155
+ type MockSchemaReader_ClassInfo_Call struct {
156
+ *mock.Call
157
+ }
158
+
159
+ // ClassInfo is a helper method to define mock.On call
160
+ // - class string
161
+ func (_e *MockSchemaReader_Expecter) ClassInfo(class interface{}) *MockSchemaReader_ClassInfo_Call {
162
+ return &MockSchemaReader_ClassInfo_Call{Call: _e.mock.On("ClassInfo", class)}
163
+ }
164
+
165
+ func (_c *MockSchemaReader_ClassInfo_Call) Run(run func(class string)) *MockSchemaReader_ClassInfo_Call {
166
+ _c.Call.Run(func(args mock.Arguments) {
167
+ run(args[0].(string))
168
+ })
169
+ return _c
170
+ }
171
+
172
+ func (_c *MockSchemaReader_ClassInfo_Call) Return(ci clusterschema.ClassInfo) *MockSchemaReader_ClassInfo_Call {
173
+ _c.Call.Return(ci)
174
+ return _c
175
+ }
176
+
177
+ func (_c *MockSchemaReader_ClassInfo_Call) RunAndReturn(run func(string) clusterschema.ClassInfo) *MockSchemaReader_ClassInfo_Call {
178
+ _c.Call.Return(run)
179
+ return _c
180
+ }
181
+
182
+ // ClassInfoWithVersion provides a mock function with given fields: ctx, class, version
183
+ func (_m *MockSchemaReader) ClassInfoWithVersion(ctx context.Context, class string, version uint64) (clusterschema.ClassInfo, error) {
184
+ ret := _m.Called(ctx, class, version)
185
+
186
+ if len(ret) == 0 {
187
+ panic("no return value specified for ClassInfoWithVersion")
188
+ }
189
+
190
+ var r0 clusterschema.ClassInfo
191
+ var r1 error
192
+ if rf, ok := ret.Get(0).(func(context.Context, string, uint64) (clusterschema.ClassInfo, error)); ok {
193
+ return rf(ctx, class, version)
194
+ }
195
+ if rf, ok := ret.Get(0).(func(context.Context, string, uint64) clusterschema.ClassInfo); ok {
196
+ r0 = rf(ctx, class, version)
197
+ } else {
198
+ r0 = ret.Get(0).(clusterschema.ClassInfo)
199
+ }
200
+
201
+ if rf, ok := ret.Get(1).(func(context.Context, string, uint64) error); ok {
202
+ r1 = rf(ctx, class, version)
203
+ } else {
204
+ r1 = ret.Error(1)
205
+ }
206
+
207
+ return r0, r1
208
+ }
209
+
210
+ // MockSchemaReader_ClassInfoWithVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClassInfoWithVersion'
211
+ type MockSchemaReader_ClassInfoWithVersion_Call struct {
212
+ *mock.Call
213
+ }
214
+
215
+ // ClassInfoWithVersion is a helper method to define mock.On call
216
+ // - ctx context.Context
217
+ // - class string
218
+ // - version uint64
219
+ func (_e *MockSchemaReader_Expecter) ClassInfoWithVersion(ctx interface{}, class interface{}, version interface{}) *MockSchemaReader_ClassInfoWithVersion_Call {
220
+ return &MockSchemaReader_ClassInfoWithVersion_Call{Call: _e.mock.On("ClassInfoWithVersion", ctx, class, version)}
221
+ }
222
+
223
+ func (_c *MockSchemaReader_ClassInfoWithVersion_Call) Run(run func(ctx context.Context, class string, version uint64)) *MockSchemaReader_ClassInfoWithVersion_Call {
224
+ _c.Call.Run(func(args mock.Arguments) {
225
+ run(args[0].(context.Context), args[1].(string), args[2].(uint64))
226
+ })
227
+ return _c
228
+ }
229
+
230
+ func (_c *MockSchemaReader_ClassInfoWithVersion_Call) Return(_a0 clusterschema.ClassInfo, _a1 error) *MockSchemaReader_ClassInfoWithVersion_Call {
231
+ _c.Call.Return(_a0, _a1)
232
+ return _c
233
+ }
234
+
235
+ func (_c *MockSchemaReader_ClassInfoWithVersion_Call) RunAndReturn(run func(context.Context, string, uint64) (clusterschema.ClassInfo, error)) *MockSchemaReader_ClassInfoWithVersion_Call {
236
+ _c.Call.Return(run)
237
+ return _c
238
+ }
239
+
240
+ // GetAliasesForClass provides a mock function with given fields: class
241
+ func (_m *MockSchemaReader) GetAliasesForClass(class string) []*models.Alias {
242
+ ret := _m.Called(class)
243
+
244
+ if len(ret) == 0 {
245
+ panic("no return value specified for GetAliasesForClass")
246
+ }
247
+
248
+ var r0 []*models.Alias
249
+ if rf, ok := ret.Get(0).(func(string) []*models.Alias); ok {
250
+ r0 = rf(class)
251
+ } else {
252
+ if ret.Get(0) != nil {
253
+ r0 = ret.Get(0).([]*models.Alias)
254
+ }
255
+ }
256
+
257
+ return r0
258
+ }
259
+
260
+ // MockSchemaReader_GetAliasesForClass_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAliasesForClass'
261
+ type MockSchemaReader_GetAliasesForClass_Call struct {
262
+ *mock.Call
263
+ }
264
+
265
+ // GetAliasesForClass is a helper method to define mock.On call
266
+ // - class string
267
+ func (_e *MockSchemaReader_Expecter) GetAliasesForClass(class interface{}) *MockSchemaReader_GetAliasesForClass_Call {
268
+ return &MockSchemaReader_GetAliasesForClass_Call{Call: _e.mock.On("GetAliasesForClass", class)}
269
+ }
270
+
271
+ func (_c *MockSchemaReader_GetAliasesForClass_Call) Run(run func(class string)) *MockSchemaReader_GetAliasesForClass_Call {
272
+ _c.Call.Run(func(args mock.Arguments) {
273
+ run(args[0].(string))
274
+ })
275
+ return _c
276
+ }
277
+
278
+ func (_c *MockSchemaReader_GetAliasesForClass_Call) Return(_a0 []*models.Alias) *MockSchemaReader_GetAliasesForClass_Call {
279
+ _c.Call.Return(_a0)
280
+ return _c
281
+ }
282
+
283
+ func (_c *MockSchemaReader_GetAliasesForClass_Call) RunAndReturn(run func(string) []*models.Alias) *MockSchemaReader_GetAliasesForClass_Call {
284
+ _c.Call.Return(run)
285
+ return _c
286
+ }
287
+
288
+ // GetShardsStatus provides a mock function with given fields: class, tenant
289
+ func (_m *MockSchemaReader) GetShardsStatus(class string, tenant string) (models.ShardStatusList, error) {
290
+ ret := _m.Called(class, tenant)
291
+
292
+ if len(ret) == 0 {
293
+ panic("no return value specified for GetShardsStatus")
294
+ }
295
+
296
+ var r0 models.ShardStatusList
297
+ var r1 error
298
+ if rf, ok := ret.Get(0).(func(string, string) (models.ShardStatusList, error)); ok {
299
+ return rf(class, tenant)
300
+ }
301
+ if rf, ok := ret.Get(0).(func(string, string) models.ShardStatusList); ok {
302
+ r0 = rf(class, tenant)
303
+ } else {
304
+ if ret.Get(0) != nil {
305
+ r0 = ret.Get(0).(models.ShardStatusList)
306
+ }
307
+ }
308
+
309
+ if rf, ok := ret.Get(1).(func(string, string) error); ok {
310
+ r1 = rf(class, tenant)
311
+ } else {
312
+ r1 = ret.Error(1)
313
+ }
314
+
315
+ return r0, r1
316
+ }
317
+
318
+ // MockSchemaReader_GetShardsStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetShardsStatus'
319
+ type MockSchemaReader_GetShardsStatus_Call struct {
320
+ *mock.Call
321
+ }
322
+
323
+ // GetShardsStatus is a helper method to define mock.On call
324
+ // - class string
325
+ // - tenant string
326
+ func (_e *MockSchemaReader_Expecter) GetShardsStatus(class interface{}, tenant interface{}) *MockSchemaReader_GetShardsStatus_Call {
327
+ return &MockSchemaReader_GetShardsStatus_Call{Call: _e.mock.On("GetShardsStatus", class, tenant)}
328
+ }
329
+
330
+ func (_c *MockSchemaReader_GetShardsStatus_Call) Run(run func(class string, tenant string)) *MockSchemaReader_GetShardsStatus_Call {
331
+ _c.Call.Run(func(args mock.Arguments) {
332
+ run(args[0].(string), args[1].(string))
333
+ })
334
+ return _c
335
+ }
336
+
337
+ func (_c *MockSchemaReader_GetShardsStatus_Call) Return(_a0 models.ShardStatusList, _a1 error) *MockSchemaReader_GetShardsStatus_Call {
338
+ _c.Call.Return(_a0, _a1)
339
+ return _c
340
+ }
341
+
342
+ func (_c *MockSchemaReader_GetShardsStatus_Call) RunAndReturn(run func(string, string) (models.ShardStatusList, error)) *MockSchemaReader_GetShardsStatus_Call {
343
+ _c.Call.Return(run)
344
+ return _c
345
+ }
346
+
347
+ // LocalShards provides a mock function with given fields: class
348
+ func (_m *MockSchemaReader) LocalShards(class string) ([]string, error) {
349
+ ret := _m.Called(class)
350
+
351
+ if len(ret) == 0 {
352
+ panic("no return value specified for LocalShards")
353
+ }
354
+
355
+ var r0 []string
356
+ var r1 error
357
+ if rf, ok := ret.Get(0).(func(string) ([]string, error)); ok {
358
+ return rf(class)
359
+ }
360
+ if rf, ok := ret.Get(0).(func(string) []string); ok {
361
+ r0 = rf(class)
362
+ } else {
363
+ if ret.Get(0) != nil {
364
+ r0 = ret.Get(0).([]string)
365
+ }
366
+ }
367
+
368
+ if rf, ok := ret.Get(1).(func(string) error); ok {
369
+ r1 = rf(class)
370
+ } else {
371
+ r1 = ret.Error(1)
372
+ }
373
+
374
+ return r0, r1
375
+ }
376
+
377
+ // MockSchemaReader_LocalShards_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LocalShards'
378
+ type MockSchemaReader_LocalShards_Call struct {
379
+ *mock.Call
380
+ }
381
+
382
+ // LocalShards is a helper method to define mock.On call
383
+ // - class string
384
+ func (_e *MockSchemaReader_Expecter) LocalShards(class interface{}) *MockSchemaReader_LocalShards_Call {
385
+ return &MockSchemaReader_LocalShards_Call{Call: _e.mock.On("LocalShards", class)}
386
+ }
387
+
388
+ func (_c *MockSchemaReader_LocalShards_Call) Run(run func(class string)) *MockSchemaReader_LocalShards_Call {
389
+ _c.Call.Run(func(args mock.Arguments) {
390
+ run(args[0].(string))
391
+ })
392
+ return _c
393
+ }
394
+
395
+ func (_c *MockSchemaReader_LocalShards_Call) Return(_a0 []string, _a1 error) *MockSchemaReader_LocalShards_Call {
396
+ _c.Call.Return(_a0, _a1)
397
+ return _c
398
+ }
399
+
400
+ func (_c *MockSchemaReader_LocalShards_Call) RunAndReturn(run func(string) ([]string, error)) *MockSchemaReader_LocalShards_Call {
401
+ _c.Call.Return(run)
402
+ return _c
403
+ }
404
+
405
+ // MultiTenancy provides a mock function with given fields: class
406
+ func (_m *MockSchemaReader) MultiTenancy(class string) models.MultiTenancyConfig {
407
+ ret := _m.Called(class)
408
+
409
+ if len(ret) == 0 {
410
+ panic("no return value specified for MultiTenancy")
411
+ }
412
+
413
+ var r0 models.MultiTenancyConfig
414
+ if rf, ok := ret.Get(0).(func(string) models.MultiTenancyConfig); ok {
415
+ r0 = rf(class)
416
+ } else {
417
+ r0 = ret.Get(0).(models.MultiTenancyConfig)
418
+ }
419
+
420
+ return r0
421
+ }
422
+
423
+ // MockSchemaReader_MultiTenancy_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MultiTenancy'
424
+ type MockSchemaReader_MultiTenancy_Call struct {
425
+ *mock.Call
426
+ }
427
+
428
+ // MultiTenancy is a helper method to define mock.On call
429
+ // - class string
430
+ func (_e *MockSchemaReader_Expecter) MultiTenancy(class interface{}) *MockSchemaReader_MultiTenancy_Call {
431
+ return &MockSchemaReader_MultiTenancy_Call{Call: _e.mock.On("MultiTenancy", class)}
432
+ }
433
+
434
+ func (_c *MockSchemaReader_MultiTenancy_Call) Run(run func(class string)) *MockSchemaReader_MultiTenancy_Call {
435
+ _c.Call.Run(func(args mock.Arguments) {
436
+ run(args[0].(string))
437
+ })
438
+ return _c
439
+ }
440
+
441
+ func (_c *MockSchemaReader_MultiTenancy_Call) Return(_a0 models.MultiTenancyConfig) *MockSchemaReader_MultiTenancy_Call {
442
+ _c.Call.Return(_a0)
443
+ return _c
444
+ }
445
+
446
+ func (_c *MockSchemaReader_MultiTenancy_Call) RunAndReturn(run func(string) models.MultiTenancyConfig) *MockSchemaReader_MultiTenancy_Call {
447
+ _c.Call.Return(run)
448
+ return _c
449
+ }
450
+
451
+ // MultiTenancyWithVersion provides a mock function with given fields: ctx, class, version
452
+ func (_m *MockSchemaReader) MultiTenancyWithVersion(ctx context.Context, class string, version uint64) (models.MultiTenancyConfig, error) {
453
+ ret := _m.Called(ctx, class, version)
454
+
455
+ if len(ret) == 0 {
456
+ panic("no return value specified for MultiTenancyWithVersion")
457
+ }
458
+
459
+ var r0 models.MultiTenancyConfig
460
+ var r1 error
461
+ if rf, ok := ret.Get(0).(func(context.Context, string, uint64) (models.MultiTenancyConfig, error)); ok {
462
+ return rf(ctx, class, version)
463
+ }
464
+ if rf, ok := ret.Get(0).(func(context.Context, string, uint64) models.MultiTenancyConfig); ok {
465
+ r0 = rf(ctx, class, version)
466
+ } else {
467
+ r0 = ret.Get(0).(models.MultiTenancyConfig)
468
+ }
469
+
470
+ if rf, ok := ret.Get(1).(func(context.Context, string, uint64) error); ok {
471
+ r1 = rf(ctx, class, version)
472
+ } else {
473
+ r1 = ret.Error(1)
474
+ }
475
+
476
+ return r0, r1
477
+ }
478
+
479
+ // MockSchemaReader_MultiTenancyWithVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MultiTenancyWithVersion'
480
+ type MockSchemaReader_MultiTenancyWithVersion_Call struct {
481
+ *mock.Call
482
+ }
483
+
484
+ // MultiTenancyWithVersion is a helper method to define mock.On call
485
+ // - ctx context.Context
486
+ // - class string
487
+ // - version uint64
488
+ func (_e *MockSchemaReader_Expecter) MultiTenancyWithVersion(ctx interface{}, class interface{}, version interface{}) *MockSchemaReader_MultiTenancyWithVersion_Call {
489
+ return &MockSchemaReader_MultiTenancyWithVersion_Call{Call: _e.mock.On("MultiTenancyWithVersion", ctx, class, version)}
490
+ }
491
+
492
+ func (_c *MockSchemaReader_MultiTenancyWithVersion_Call) Run(run func(ctx context.Context, class string, version uint64)) *MockSchemaReader_MultiTenancyWithVersion_Call {
493
+ _c.Call.Run(func(args mock.Arguments) {
494
+ run(args[0].(context.Context), args[1].(string), args[2].(uint64))
495
+ })
496
+ return _c
497
+ }
498
+
499
+ func (_c *MockSchemaReader_MultiTenancyWithVersion_Call) Return(_a0 models.MultiTenancyConfig, _a1 error) *MockSchemaReader_MultiTenancyWithVersion_Call {
500
+ _c.Call.Return(_a0, _a1)
501
+ return _c
502
+ }
503
+
504
+ func (_c *MockSchemaReader_MultiTenancyWithVersion_Call) RunAndReturn(run func(context.Context, string, uint64) (models.MultiTenancyConfig, error)) *MockSchemaReader_MultiTenancyWithVersion_Call {
505
+ _c.Call.Return(run)
506
+ return _c
507
+ }
508
+
509
+ // Read provides a mock function with given fields: class, reader
510
+ func (_m *MockSchemaReader) Read(class string, reader func(*models.Class, *sharding.State) error) error {
511
+ ret := _m.Called(class, reader)
512
+
513
+ if len(ret) == 0 {
514
+ panic("no return value specified for Read")
515
+ }
516
+
517
+ var r0 error
518
+ if rf, ok := ret.Get(0).(func(string, func(*models.Class, *sharding.State) error) error); ok {
519
+ r0 = rf(class, reader)
520
+ } else {
521
+ r0 = ret.Error(0)
522
+ }
523
+
524
+ return r0
525
+ }
526
+
527
+ // MockSchemaReader_Read_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Read'
528
+ type MockSchemaReader_Read_Call struct {
529
+ *mock.Call
530
+ }
531
+
532
+ // Read is a helper method to define mock.On call
533
+ // - class string
534
+ // - reader func(*models.Class , *sharding.State) error
535
+ func (_e *MockSchemaReader_Expecter) Read(class interface{}, reader interface{}) *MockSchemaReader_Read_Call {
536
+ return &MockSchemaReader_Read_Call{Call: _e.mock.On("Read", class, reader)}
537
+ }
538
+
539
+ func (_c *MockSchemaReader_Read_Call) Run(run func(class string, reader func(*models.Class, *sharding.State) error)) *MockSchemaReader_Read_Call {
540
+ _c.Call.Run(func(args mock.Arguments) {
541
+ run(args[0].(string), args[1].(func(*models.Class, *sharding.State) error))
542
+ })
543
+ return _c
544
+ }
545
+
546
+ func (_c *MockSchemaReader_Read_Call) Return(_a0 error) *MockSchemaReader_Read_Call {
547
+ _c.Call.Return(_a0)
548
+ return _c
549
+ }
550
+
551
+ func (_c *MockSchemaReader_Read_Call) RunAndReturn(run func(string, func(*models.Class, *sharding.State) error) error) *MockSchemaReader_Read_Call {
552
+ _c.Call.Return(run)
553
+ return _c
554
+ }
555
+
556
+ // ReadOnlyClass provides a mock function with given fields: name
557
+ func (_m *MockSchemaReader) ReadOnlyClass(name string) *models.Class {
558
+ ret := _m.Called(name)
559
+
560
+ if len(ret) == 0 {
561
+ panic("no return value specified for ReadOnlyClass")
562
+ }
563
+
564
+ var r0 *models.Class
565
+ if rf, ok := ret.Get(0).(func(string) *models.Class); ok {
566
+ r0 = rf(name)
567
+ } else {
568
+ if ret.Get(0) != nil {
569
+ r0 = ret.Get(0).(*models.Class)
570
+ }
571
+ }
572
+
573
+ return r0
574
+ }
575
+
576
+ // MockSchemaReader_ReadOnlyClass_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadOnlyClass'
577
+ type MockSchemaReader_ReadOnlyClass_Call struct {
578
+ *mock.Call
579
+ }
580
+
581
+ // ReadOnlyClass is a helper method to define mock.On call
582
+ // - name string
583
+ func (_e *MockSchemaReader_Expecter) ReadOnlyClass(name interface{}) *MockSchemaReader_ReadOnlyClass_Call {
584
+ return &MockSchemaReader_ReadOnlyClass_Call{Call: _e.mock.On("ReadOnlyClass", name)}
585
+ }
586
+
587
+ func (_c *MockSchemaReader_ReadOnlyClass_Call) Run(run func(name string)) *MockSchemaReader_ReadOnlyClass_Call {
588
+ _c.Call.Run(func(args mock.Arguments) {
589
+ run(args[0].(string))
590
+ })
591
+ return _c
592
+ }
593
+
594
+ func (_c *MockSchemaReader_ReadOnlyClass_Call) Return(_a0 *models.Class) *MockSchemaReader_ReadOnlyClass_Call {
595
+ _c.Call.Return(_a0)
596
+ return _c
597
+ }
598
+
599
+ func (_c *MockSchemaReader_ReadOnlyClass_Call) RunAndReturn(run func(string) *models.Class) *MockSchemaReader_ReadOnlyClass_Call {
600
+ _c.Call.Return(run)
601
+ return _c
602
+ }
603
+
604
+ // ReadOnlyClassWithVersion provides a mock function with given fields: ctx, class, version
605
+ func (_m *MockSchemaReader) ReadOnlyClassWithVersion(ctx context.Context, class string, version uint64) (*models.Class, error) {
606
+ ret := _m.Called(ctx, class, version)
607
+
608
+ if len(ret) == 0 {
609
+ panic("no return value specified for ReadOnlyClassWithVersion")
610
+ }
611
+
612
+ var r0 *models.Class
613
+ var r1 error
614
+ if rf, ok := ret.Get(0).(func(context.Context, string, uint64) (*models.Class, error)); ok {
615
+ return rf(ctx, class, version)
616
+ }
617
+ if rf, ok := ret.Get(0).(func(context.Context, string, uint64) *models.Class); ok {
618
+ r0 = rf(ctx, class, version)
619
+ } else {
620
+ if ret.Get(0) != nil {
621
+ r0 = ret.Get(0).(*models.Class)
622
+ }
623
+ }
624
+
625
+ if rf, ok := ret.Get(1).(func(context.Context, string, uint64) error); ok {
626
+ r1 = rf(ctx, class, version)
627
+ } else {
628
+ r1 = ret.Error(1)
629
+ }
630
+
631
+ return r0, r1
632
+ }
633
+
634
+ // MockSchemaReader_ReadOnlyClassWithVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadOnlyClassWithVersion'
635
+ type MockSchemaReader_ReadOnlyClassWithVersion_Call struct {
636
+ *mock.Call
637
+ }
638
+
639
+ // ReadOnlyClassWithVersion is a helper method to define mock.On call
640
+ // - ctx context.Context
641
+ // - class string
642
+ // - version uint64
643
+ func (_e *MockSchemaReader_Expecter) ReadOnlyClassWithVersion(ctx interface{}, class interface{}, version interface{}) *MockSchemaReader_ReadOnlyClassWithVersion_Call {
644
+ return &MockSchemaReader_ReadOnlyClassWithVersion_Call{Call: _e.mock.On("ReadOnlyClassWithVersion", ctx, class, version)}
645
+ }
646
+
647
+ func (_c *MockSchemaReader_ReadOnlyClassWithVersion_Call) Run(run func(ctx context.Context, class string, version uint64)) *MockSchemaReader_ReadOnlyClassWithVersion_Call {
648
+ _c.Call.Run(func(args mock.Arguments) {
649
+ run(args[0].(context.Context), args[1].(string), args[2].(uint64))
650
+ })
651
+ return _c
652
+ }
653
+
654
+ func (_c *MockSchemaReader_ReadOnlyClassWithVersion_Call) Return(_a0 *models.Class, _a1 error) *MockSchemaReader_ReadOnlyClassWithVersion_Call {
655
+ _c.Call.Return(_a0, _a1)
656
+ return _c
657
+ }
658
+
659
+ func (_c *MockSchemaReader_ReadOnlyClassWithVersion_Call) RunAndReturn(run func(context.Context, string, uint64) (*models.Class, error)) *MockSchemaReader_ReadOnlyClassWithVersion_Call {
660
+ _c.Call.Return(run)
661
+ return _c
662
+ }
663
+
664
+ // ReadOnlySchema provides a mock function with no fields
665
+ func (_m *MockSchemaReader) ReadOnlySchema() models.Schema {
666
+ ret := _m.Called()
667
+
668
+ if len(ret) == 0 {
669
+ panic("no return value specified for ReadOnlySchema")
670
+ }
671
+
672
+ var r0 models.Schema
673
+ if rf, ok := ret.Get(0).(func() models.Schema); ok {
674
+ r0 = rf()
675
+ } else {
676
+ r0 = ret.Get(0).(models.Schema)
677
+ }
678
+
679
+ return r0
680
+ }
681
+
682
+ // MockSchemaReader_ReadOnlySchema_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadOnlySchema'
683
+ type MockSchemaReader_ReadOnlySchema_Call struct {
684
+ *mock.Call
685
+ }
686
+
687
+ // ReadOnlySchema is a helper method to define mock.On call
688
+ func (_e *MockSchemaReader_Expecter) ReadOnlySchema() *MockSchemaReader_ReadOnlySchema_Call {
689
+ return &MockSchemaReader_ReadOnlySchema_Call{Call: _e.mock.On("ReadOnlySchema")}
690
+ }
691
+
692
+ func (_c *MockSchemaReader_ReadOnlySchema_Call) Run(run func()) *MockSchemaReader_ReadOnlySchema_Call {
693
+ _c.Call.Run(func(args mock.Arguments) {
694
+ run()
695
+ })
696
+ return _c
697
+ }
698
+
699
+ func (_c *MockSchemaReader_ReadOnlySchema_Call) Return(_a0 models.Schema) *MockSchemaReader_ReadOnlySchema_Call {
700
+ _c.Call.Return(_a0)
701
+ return _c
702
+ }
703
+
704
+ func (_c *MockSchemaReader_ReadOnlySchema_Call) RunAndReturn(run func() models.Schema) *MockSchemaReader_ReadOnlySchema_Call {
705
+ _c.Call.Return(run)
706
+ return _c
707
+ }
708
+
709
+ // ReadOnlyVersionedClass provides a mock function with given fields: name
710
+ func (_m *MockSchemaReader) ReadOnlyVersionedClass(name string) versioned.Class {
711
+ ret := _m.Called(name)
712
+
713
+ if len(ret) == 0 {
714
+ panic("no return value specified for ReadOnlyVersionedClass")
715
+ }
716
+
717
+ var r0 versioned.Class
718
+ if rf, ok := ret.Get(0).(func(string) versioned.Class); ok {
719
+ r0 = rf(name)
720
+ } else {
721
+ r0 = ret.Get(0).(versioned.Class)
722
+ }
723
+
724
+ return r0
725
+ }
726
+
727
+ // MockSchemaReader_ReadOnlyVersionedClass_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadOnlyVersionedClass'
728
+ type MockSchemaReader_ReadOnlyVersionedClass_Call struct {
729
+ *mock.Call
730
+ }
731
+
732
+ // ReadOnlyVersionedClass is a helper method to define mock.On call
733
+ // - name string
734
+ func (_e *MockSchemaReader_Expecter) ReadOnlyVersionedClass(name interface{}) *MockSchemaReader_ReadOnlyVersionedClass_Call {
735
+ return &MockSchemaReader_ReadOnlyVersionedClass_Call{Call: _e.mock.On("ReadOnlyVersionedClass", name)}
736
+ }
737
+
738
+ func (_c *MockSchemaReader_ReadOnlyVersionedClass_Call) Run(run func(name string)) *MockSchemaReader_ReadOnlyVersionedClass_Call {
739
+ _c.Call.Run(func(args mock.Arguments) {
740
+ run(args[0].(string))
741
+ })
742
+ return _c
743
+ }
744
+
745
+ func (_c *MockSchemaReader_ReadOnlyVersionedClass_Call) Return(_a0 versioned.Class) *MockSchemaReader_ReadOnlyVersionedClass_Call {
746
+ _c.Call.Return(_a0)
747
+ return _c
748
+ }
749
+
750
+ func (_c *MockSchemaReader_ReadOnlyVersionedClass_Call) RunAndReturn(run func(string) versioned.Class) *MockSchemaReader_ReadOnlyVersionedClass_Call {
751
+ _c.Call.Return(run)
752
+ return _c
753
+ }
754
+
755
+ // ResolveAlias provides a mock function with given fields: alias
756
+ func (_m *MockSchemaReader) ResolveAlias(alias string) string {
757
+ ret := _m.Called(alias)
758
+
759
+ if len(ret) == 0 {
760
+ panic("no return value specified for ResolveAlias")
761
+ }
762
+
763
+ var r0 string
764
+ if rf, ok := ret.Get(0).(func(string) string); ok {
765
+ r0 = rf(alias)
766
+ } else {
767
+ r0 = ret.Get(0).(string)
768
+ }
769
+
770
+ return r0
771
+ }
772
+
773
+ // MockSchemaReader_ResolveAlias_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ResolveAlias'
774
+ type MockSchemaReader_ResolveAlias_Call struct {
775
+ *mock.Call
776
+ }
777
+
778
+ // ResolveAlias is a helper method to define mock.On call
779
+ // - alias string
780
+ func (_e *MockSchemaReader_Expecter) ResolveAlias(alias interface{}) *MockSchemaReader_ResolveAlias_Call {
781
+ return &MockSchemaReader_ResolveAlias_Call{Call: _e.mock.On("ResolveAlias", alias)}
782
+ }
783
+
784
+ func (_c *MockSchemaReader_ResolveAlias_Call) Run(run func(alias string)) *MockSchemaReader_ResolveAlias_Call {
785
+ _c.Call.Run(func(args mock.Arguments) {
786
+ run(args[0].(string))
787
+ })
788
+ return _c
789
+ }
790
+
791
+ func (_c *MockSchemaReader_ResolveAlias_Call) Return(_a0 string) *MockSchemaReader_ResolveAlias_Call {
792
+ _c.Call.Return(_a0)
793
+ return _c
794
+ }
795
+
796
+ func (_c *MockSchemaReader_ResolveAlias_Call) RunAndReturn(run func(string) string) *MockSchemaReader_ResolveAlias_Call {
797
+ _c.Call.Return(run)
798
+ return _c
799
+ }
800
+
801
+ // ShardFromUUID provides a mock function with given fields: class, uuid
802
+ func (_m *MockSchemaReader) ShardFromUUID(class string, uuid []byte) string {
803
+ ret := _m.Called(class, uuid)
804
+
805
+ if len(ret) == 0 {
806
+ panic("no return value specified for ShardFromUUID")
807
+ }
808
+
809
+ var r0 string
810
+ if rf, ok := ret.Get(0).(func(string, []byte) string); ok {
811
+ r0 = rf(class, uuid)
812
+ } else {
813
+ r0 = ret.Get(0).(string)
814
+ }
815
+
816
+ return r0
817
+ }
818
+
819
+ // MockSchemaReader_ShardFromUUID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShardFromUUID'
820
+ type MockSchemaReader_ShardFromUUID_Call struct {
821
+ *mock.Call
822
+ }
823
+
824
+ // ShardFromUUID is a helper method to define mock.On call
825
+ // - class string
826
+ // - uuid []byte
827
+ func (_e *MockSchemaReader_Expecter) ShardFromUUID(class interface{}, uuid interface{}) *MockSchemaReader_ShardFromUUID_Call {
828
+ return &MockSchemaReader_ShardFromUUID_Call{Call: _e.mock.On("ShardFromUUID", class, uuid)}
829
+ }
830
+
831
+ func (_c *MockSchemaReader_ShardFromUUID_Call) Run(run func(class string, uuid []byte)) *MockSchemaReader_ShardFromUUID_Call {
832
+ _c.Call.Run(func(args mock.Arguments) {
833
+ run(args[0].(string), args[1].([]byte))
834
+ })
835
+ return _c
836
+ }
837
+
838
+ func (_c *MockSchemaReader_ShardFromUUID_Call) Return(_a0 string) *MockSchemaReader_ShardFromUUID_Call {
839
+ _c.Call.Return(_a0)
840
+ return _c
841
+ }
842
+
843
+ func (_c *MockSchemaReader_ShardFromUUID_Call) RunAndReturn(run func(string, []byte) string) *MockSchemaReader_ShardFromUUID_Call {
844
+ _c.Call.Return(run)
845
+ return _c
846
+ }
847
+
848
+ // ShardFromUUIDWithVersion provides a mock function with given fields: ctx, class, uuid, version
849
+ func (_m *MockSchemaReader) ShardFromUUIDWithVersion(ctx context.Context, class string, uuid []byte, version uint64) (string, error) {
850
+ ret := _m.Called(ctx, class, uuid, version)
851
+
852
+ if len(ret) == 0 {
853
+ panic("no return value specified for ShardFromUUIDWithVersion")
854
+ }
855
+
856
+ var r0 string
857
+ var r1 error
858
+ if rf, ok := ret.Get(0).(func(context.Context, string, []byte, uint64) (string, error)); ok {
859
+ return rf(ctx, class, uuid, version)
860
+ }
861
+ if rf, ok := ret.Get(0).(func(context.Context, string, []byte, uint64) string); ok {
862
+ r0 = rf(ctx, class, uuid, version)
863
+ } else {
864
+ r0 = ret.Get(0).(string)
865
+ }
866
+
867
+ if rf, ok := ret.Get(1).(func(context.Context, string, []byte, uint64) error); ok {
868
+ r1 = rf(ctx, class, uuid, version)
869
+ } else {
870
+ r1 = ret.Error(1)
871
+ }
872
+
873
+ return r0, r1
874
+ }
875
+
876
+ // MockSchemaReader_ShardFromUUIDWithVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShardFromUUIDWithVersion'
877
+ type MockSchemaReader_ShardFromUUIDWithVersion_Call struct {
878
+ *mock.Call
879
+ }
880
+
881
+ // ShardFromUUIDWithVersion is a helper method to define mock.On call
882
+ // - ctx context.Context
883
+ // - class string
884
+ // - uuid []byte
885
+ // - version uint64
886
+ func (_e *MockSchemaReader_Expecter) ShardFromUUIDWithVersion(ctx interface{}, class interface{}, uuid interface{}, version interface{}) *MockSchemaReader_ShardFromUUIDWithVersion_Call {
887
+ return &MockSchemaReader_ShardFromUUIDWithVersion_Call{Call: _e.mock.On("ShardFromUUIDWithVersion", ctx, class, uuid, version)}
888
+ }
889
+
890
+ func (_c *MockSchemaReader_ShardFromUUIDWithVersion_Call) Run(run func(ctx context.Context, class string, uuid []byte, version uint64)) *MockSchemaReader_ShardFromUUIDWithVersion_Call {
891
+ _c.Call.Run(func(args mock.Arguments) {
892
+ run(args[0].(context.Context), args[1].(string), args[2].([]byte), args[3].(uint64))
893
+ })
894
+ return _c
895
+ }
896
+
897
+ func (_c *MockSchemaReader_ShardFromUUIDWithVersion_Call) Return(_a0 string, _a1 error) *MockSchemaReader_ShardFromUUIDWithVersion_Call {
898
+ _c.Call.Return(_a0, _a1)
899
+ return _c
900
+ }
901
+
902
+ func (_c *MockSchemaReader_ShardFromUUIDWithVersion_Call) RunAndReturn(run func(context.Context, string, []byte, uint64) (string, error)) *MockSchemaReader_ShardFromUUIDWithVersion_Call {
903
+ _c.Call.Return(run)
904
+ return _c
905
+ }
906
+
907
+ // ShardOwner provides a mock function with given fields: class, shard
908
+ func (_m *MockSchemaReader) ShardOwner(class string, shard string) (string, error) {
909
+ ret := _m.Called(class, shard)
910
+
911
+ if len(ret) == 0 {
912
+ panic("no return value specified for ShardOwner")
913
+ }
914
+
915
+ var r0 string
916
+ var r1 error
917
+ if rf, ok := ret.Get(0).(func(string, string) (string, error)); ok {
918
+ return rf(class, shard)
919
+ }
920
+ if rf, ok := ret.Get(0).(func(string, string) string); ok {
921
+ r0 = rf(class, shard)
922
+ } else {
923
+ r0 = ret.Get(0).(string)
924
+ }
925
+
926
+ if rf, ok := ret.Get(1).(func(string, string) error); ok {
927
+ r1 = rf(class, shard)
928
+ } else {
929
+ r1 = ret.Error(1)
930
+ }
931
+
932
+ return r0, r1
933
+ }
934
+
935
+ // MockSchemaReader_ShardOwner_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShardOwner'
936
+ type MockSchemaReader_ShardOwner_Call struct {
937
+ *mock.Call
938
+ }
939
+
940
+ // ShardOwner is a helper method to define mock.On call
941
+ // - class string
942
+ // - shard string
943
+ func (_e *MockSchemaReader_Expecter) ShardOwner(class interface{}, shard interface{}) *MockSchemaReader_ShardOwner_Call {
944
+ return &MockSchemaReader_ShardOwner_Call{Call: _e.mock.On("ShardOwner", class, shard)}
945
+ }
946
+
947
+ func (_c *MockSchemaReader_ShardOwner_Call) Run(run func(class string, shard string)) *MockSchemaReader_ShardOwner_Call {
948
+ _c.Call.Run(func(args mock.Arguments) {
949
+ run(args[0].(string), args[1].(string))
950
+ })
951
+ return _c
952
+ }
953
+
954
+ func (_c *MockSchemaReader_ShardOwner_Call) Return(_a0 string, _a1 error) *MockSchemaReader_ShardOwner_Call {
955
+ _c.Call.Return(_a0, _a1)
956
+ return _c
957
+ }
958
+
959
+ func (_c *MockSchemaReader_ShardOwner_Call) RunAndReturn(run func(string, string) (string, error)) *MockSchemaReader_ShardOwner_Call {
960
+ _c.Call.Return(run)
961
+ return _c
962
+ }
963
+
964
+ // ShardOwnerWithVersion provides a mock function with given fields: ctx, lass, shard, version
965
+ func (_m *MockSchemaReader) ShardOwnerWithVersion(ctx context.Context, lass string, shard string, version uint64) (string, error) {
966
+ ret := _m.Called(ctx, lass, shard, version)
967
+
968
+ if len(ret) == 0 {
969
+ panic("no return value specified for ShardOwnerWithVersion")
970
+ }
971
+
972
+ var r0 string
973
+ var r1 error
974
+ if rf, ok := ret.Get(0).(func(context.Context, string, string, uint64) (string, error)); ok {
975
+ return rf(ctx, lass, shard, version)
976
+ }
977
+ if rf, ok := ret.Get(0).(func(context.Context, string, string, uint64) string); ok {
978
+ r0 = rf(ctx, lass, shard, version)
979
+ } else {
980
+ r0 = ret.Get(0).(string)
981
+ }
982
+
983
+ if rf, ok := ret.Get(1).(func(context.Context, string, string, uint64) error); ok {
984
+ r1 = rf(ctx, lass, shard, version)
985
+ } else {
986
+ r1 = ret.Error(1)
987
+ }
988
+
989
+ return r0, r1
990
+ }
991
+
992
+ // MockSchemaReader_ShardOwnerWithVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShardOwnerWithVersion'
993
+ type MockSchemaReader_ShardOwnerWithVersion_Call struct {
994
+ *mock.Call
995
+ }
996
+
997
+ // ShardOwnerWithVersion is a helper method to define mock.On call
998
+ // - ctx context.Context
999
+ // - lass string
1000
+ // - shard string
1001
+ // - version uint64
1002
+ func (_e *MockSchemaReader_Expecter) ShardOwnerWithVersion(ctx interface{}, lass interface{}, shard interface{}, version interface{}) *MockSchemaReader_ShardOwnerWithVersion_Call {
1003
+ return &MockSchemaReader_ShardOwnerWithVersion_Call{Call: _e.mock.On("ShardOwnerWithVersion", ctx, lass, shard, version)}
1004
+ }
1005
+
1006
+ func (_c *MockSchemaReader_ShardOwnerWithVersion_Call) Run(run func(ctx context.Context, lass string, shard string, version uint64)) *MockSchemaReader_ShardOwnerWithVersion_Call {
1007
+ _c.Call.Run(func(args mock.Arguments) {
1008
+ run(args[0].(context.Context), args[1].(string), args[2].(string), args[3].(uint64))
1009
+ })
1010
+ return _c
1011
+ }
1012
+
1013
+ func (_c *MockSchemaReader_ShardOwnerWithVersion_Call) Return(_a0 string, _a1 error) *MockSchemaReader_ShardOwnerWithVersion_Call {
1014
+ _c.Call.Return(_a0, _a1)
1015
+ return _c
1016
+ }
1017
+
1018
+ func (_c *MockSchemaReader_ShardOwnerWithVersion_Call) RunAndReturn(run func(context.Context, string, string, uint64) (string, error)) *MockSchemaReader_ShardOwnerWithVersion_Call {
1019
+ _c.Call.Return(run)
1020
+ return _c
1021
+ }
1022
+
1023
+ // ShardReplicas provides a mock function with given fields: class, shard
1024
+ func (_m *MockSchemaReader) ShardReplicas(class string, shard string) ([]string, error) {
1025
+ ret := _m.Called(class, shard)
1026
+
1027
+ if len(ret) == 0 {
1028
+ panic("no return value specified for ShardReplicas")
1029
+ }
1030
+
1031
+ var r0 []string
1032
+ var r1 error
1033
+ if rf, ok := ret.Get(0).(func(string, string) ([]string, error)); ok {
1034
+ return rf(class, shard)
1035
+ }
1036
+ if rf, ok := ret.Get(0).(func(string, string) []string); ok {
1037
+ r0 = rf(class, shard)
1038
+ } else {
1039
+ if ret.Get(0) != nil {
1040
+ r0 = ret.Get(0).([]string)
1041
+ }
1042
+ }
1043
+
1044
+ if rf, ok := ret.Get(1).(func(string, string) error); ok {
1045
+ r1 = rf(class, shard)
1046
+ } else {
1047
+ r1 = ret.Error(1)
1048
+ }
1049
+
1050
+ return r0, r1
1051
+ }
1052
+
1053
+ // MockSchemaReader_ShardReplicas_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShardReplicas'
1054
+ type MockSchemaReader_ShardReplicas_Call struct {
1055
+ *mock.Call
1056
+ }
1057
+
1058
+ // ShardReplicas is a helper method to define mock.On call
1059
+ // - class string
1060
+ // - shard string
1061
+ func (_e *MockSchemaReader_Expecter) ShardReplicas(class interface{}, shard interface{}) *MockSchemaReader_ShardReplicas_Call {
1062
+ return &MockSchemaReader_ShardReplicas_Call{Call: _e.mock.On("ShardReplicas", class, shard)}
1063
+ }
1064
+
1065
+ func (_c *MockSchemaReader_ShardReplicas_Call) Run(run func(class string, shard string)) *MockSchemaReader_ShardReplicas_Call {
1066
+ _c.Call.Run(func(args mock.Arguments) {
1067
+ run(args[0].(string), args[1].(string))
1068
+ })
1069
+ return _c
1070
+ }
1071
+
1072
+ func (_c *MockSchemaReader_ShardReplicas_Call) Return(_a0 []string, _a1 error) *MockSchemaReader_ShardReplicas_Call {
1073
+ _c.Call.Return(_a0, _a1)
1074
+ return _c
1075
+ }
1076
+
1077
+ func (_c *MockSchemaReader_ShardReplicas_Call) RunAndReturn(run func(string, string) ([]string, error)) *MockSchemaReader_ShardReplicas_Call {
1078
+ _c.Call.Return(run)
1079
+ return _c
1080
+ }
1081
+
1082
+ // ShardReplicasWithVersion provides a mock function with given fields: ctx, class, shard, version
1083
+ func (_m *MockSchemaReader) ShardReplicasWithVersion(ctx context.Context, class string, shard string, version uint64) ([]string, error) {
1084
+ ret := _m.Called(ctx, class, shard, version)
1085
+
1086
+ if len(ret) == 0 {
1087
+ panic("no return value specified for ShardReplicasWithVersion")
1088
+ }
1089
+
1090
+ var r0 []string
1091
+ var r1 error
1092
+ if rf, ok := ret.Get(0).(func(context.Context, string, string, uint64) ([]string, error)); ok {
1093
+ return rf(ctx, class, shard, version)
1094
+ }
1095
+ if rf, ok := ret.Get(0).(func(context.Context, string, string, uint64) []string); ok {
1096
+ r0 = rf(ctx, class, shard, version)
1097
+ } else {
1098
+ if ret.Get(0) != nil {
1099
+ r0 = ret.Get(0).([]string)
1100
+ }
1101
+ }
1102
+
1103
+ if rf, ok := ret.Get(1).(func(context.Context, string, string, uint64) error); ok {
1104
+ r1 = rf(ctx, class, shard, version)
1105
+ } else {
1106
+ r1 = ret.Error(1)
1107
+ }
1108
+
1109
+ return r0, r1
1110
+ }
1111
+
1112
+ // MockSchemaReader_ShardReplicasWithVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShardReplicasWithVersion'
1113
+ type MockSchemaReader_ShardReplicasWithVersion_Call struct {
1114
+ *mock.Call
1115
+ }
1116
+
1117
+ // ShardReplicasWithVersion is a helper method to define mock.On call
1118
+ // - ctx context.Context
1119
+ // - class string
1120
+ // - shard string
1121
+ // - version uint64
1122
+ func (_e *MockSchemaReader_Expecter) ShardReplicasWithVersion(ctx interface{}, class interface{}, shard interface{}, version interface{}) *MockSchemaReader_ShardReplicasWithVersion_Call {
1123
+ return &MockSchemaReader_ShardReplicasWithVersion_Call{Call: _e.mock.On("ShardReplicasWithVersion", ctx, class, shard, version)}
1124
+ }
1125
+
1126
+ func (_c *MockSchemaReader_ShardReplicasWithVersion_Call) Run(run func(ctx context.Context, class string, shard string, version uint64)) *MockSchemaReader_ShardReplicasWithVersion_Call {
1127
+ _c.Call.Run(func(args mock.Arguments) {
1128
+ run(args[0].(context.Context), args[1].(string), args[2].(string), args[3].(uint64))
1129
+ })
1130
+ return _c
1131
+ }
1132
+
1133
+ func (_c *MockSchemaReader_ShardReplicasWithVersion_Call) Return(_a0 []string, _a1 error) *MockSchemaReader_ShardReplicasWithVersion_Call {
1134
+ _c.Call.Return(_a0, _a1)
1135
+ return _c
1136
+ }
1137
+
1138
+ func (_c *MockSchemaReader_ShardReplicasWithVersion_Call) RunAndReturn(run func(context.Context, string, string, uint64) ([]string, error)) *MockSchemaReader_ShardReplicasWithVersion_Call {
1139
+ _c.Call.Return(run)
1140
+ return _c
1141
+ }
1142
+
1143
+ // Shards provides a mock function with given fields: class
1144
+ func (_m *MockSchemaReader) Shards(class string) ([]string, error) {
1145
+ ret := _m.Called(class)
1146
+
1147
+ if len(ret) == 0 {
1148
+ panic("no return value specified for Shards")
1149
+ }
1150
+
1151
+ var r0 []string
1152
+ var r1 error
1153
+ if rf, ok := ret.Get(0).(func(string) ([]string, error)); ok {
1154
+ return rf(class)
1155
+ }
1156
+ if rf, ok := ret.Get(0).(func(string) []string); ok {
1157
+ r0 = rf(class)
1158
+ } else {
1159
+ if ret.Get(0) != nil {
1160
+ r0 = ret.Get(0).([]string)
1161
+ }
1162
+ }
1163
+
1164
+ if rf, ok := ret.Get(1).(func(string) error); ok {
1165
+ r1 = rf(class)
1166
+ } else {
1167
+ r1 = ret.Error(1)
1168
+ }
1169
+
1170
+ return r0, r1
1171
+ }
1172
+
1173
+ // MockSchemaReader_Shards_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Shards'
1174
+ type MockSchemaReader_Shards_Call struct {
1175
+ *mock.Call
1176
+ }
1177
+
1178
+ // Shards is a helper method to define mock.On call
1179
+ // - class string
1180
+ func (_e *MockSchemaReader_Expecter) Shards(class interface{}) *MockSchemaReader_Shards_Call {
1181
+ return &MockSchemaReader_Shards_Call{Call: _e.mock.On("Shards", class)}
1182
+ }
1183
+
1184
+ func (_c *MockSchemaReader_Shards_Call) Run(run func(class string)) *MockSchemaReader_Shards_Call {
1185
+ _c.Call.Run(func(args mock.Arguments) {
1186
+ run(args[0].(string))
1187
+ })
1188
+ return _c
1189
+ }
1190
+
1191
+ func (_c *MockSchemaReader_Shards_Call) Return(_a0 []string, _a1 error) *MockSchemaReader_Shards_Call {
1192
+ _c.Call.Return(_a0, _a1)
1193
+ return _c
1194
+ }
1195
+
1196
+ func (_c *MockSchemaReader_Shards_Call) RunAndReturn(run func(string) ([]string, error)) *MockSchemaReader_Shards_Call {
1197
+ _c.Call.Return(run)
1198
+ return _c
1199
+ }
1200
+
1201
+ // TenantsShardsWithVersion provides a mock function with given fields: ctx, version, class, tenants
1202
+ func (_m *MockSchemaReader) TenantsShardsWithVersion(ctx context.Context, version uint64, class string, tenants ...string) (map[string]string, error) {
1203
+ _va := make([]interface{}, len(tenants))
1204
+ for _i := range tenants {
1205
+ _va[_i] = tenants[_i]
1206
+ }
1207
+ var _ca []interface{}
1208
+ _ca = append(_ca, ctx, version, class)
1209
+ _ca = append(_ca, _va...)
1210
+ ret := _m.Called(_ca...)
1211
+
1212
+ if len(ret) == 0 {
1213
+ panic("no return value specified for TenantsShardsWithVersion")
1214
+ }
1215
+
1216
+ var r0 map[string]string
1217
+ var r1 error
1218
+ if rf, ok := ret.Get(0).(func(context.Context, uint64, string, ...string) (map[string]string, error)); ok {
1219
+ return rf(ctx, version, class, tenants...)
1220
+ }
1221
+ if rf, ok := ret.Get(0).(func(context.Context, uint64, string, ...string) map[string]string); ok {
1222
+ r0 = rf(ctx, version, class, tenants...)
1223
+ } else {
1224
+ if ret.Get(0) != nil {
1225
+ r0 = ret.Get(0).(map[string]string)
1226
+ }
1227
+ }
1228
+
1229
+ if rf, ok := ret.Get(1).(func(context.Context, uint64, string, ...string) error); ok {
1230
+ r1 = rf(ctx, version, class, tenants...)
1231
+ } else {
1232
+ r1 = ret.Error(1)
1233
+ }
1234
+
1235
+ return r0, r1
1236
+ }
1237
+
1238
+ // MockSchemaReader_TenantsShardsWithVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TenantsShardsWithVersion'
1239
+ type MockSchemaReader_TenantsShardsWithVersion_Call struct {
1240
+ *mock.Call
1241
+ }
1242
+
1243
+ // TenantsShardsWithVersion is a helper method to define mock.On call
1244
+ // - ctx context.Context
1245
+ // - version uint64
1246
+ // - class string
1247
+ // - tenants ...string
1248
+ func (_e *MockSchemaReader_Expecter) TenantsShardsWithVersion(ctx interface{}, version interface{}, class interface{}, tenants ...interface{}) *MockSchemaReader_TenantsShardsWithVersion_Call {
1249
+ return &MockSchemaReader_TenantsShardsWithVersion_Call{Call: _e.mock.On("TenantsShardsWithVersion",
1250
+ append([]interface{}{ctx, version, class}, tenants...)...)}
1251
+ }
1252
+
1253
+ func (_c *MockSchemaReader_TenantsShardsWithVersion_Call) Run(run func(ctx context.Context, version uint64, class string, tenants ...string)) *MockSchemaReader_TenantsShardsWithVersion_Call {
1254
+ _c.Call.Run(func(args mock.Arguments) {
1255
+ variadicArgs := make([]string, len(args)-3)
1256
+ for i, a := range args[3:] {
1257
+ if a != nil {
1258
+ variadicArgs[i] = a.(string)
1259
+ }
1260
+ }
1261
+ run(args[0].(context.Context), args[1].(uint64), args[2].(string), variadicArgs...)
1262
+ })
1263
+ return _c
1264
+ }
1265
+
1266
+ func (_c *MockSchemaReader_TenantsShardsWithVersion_Call) Return(_a0 map[string]string, _a1 error) *MockSchemaReader_TenantsShardsWithVersion_Call {
1267
+ _c.Call.Return(_a0, _a1)
1268
+ return _c
1269
+ }
1270
+
1271
+ func (_c *MockSchemaReader_TenantsShardsWithVersion_Call) RunAndReturn(run func(context.Context, uint64, string, ...string) (map[string]string, error)) *MockSchemaReader_TenantsShardsWithVersion_Call {
1272
+ _c.Call.Return(run)
1273
+ return _c
1274
+ }
1275
+
1276
+ // WaitForUpdate provides a mock function with given fields: ctx, version
1277
+ func (_m *MockSchemaReader) WaitForUpdate(ctx context.Context, version uint64) error {
1278
+ ret := _m.Called(ctx, version)
1279
+
1280
+ if len(ret) == 0 {
1281
+ panic("no return value specified for WaitForUpdate")
1282
+ }
1283
+
1284
+ var r0 error
1285
+ if rf, ok := ret.Get(0).(func(context.Context, uint64) error); ok {
1286
+ r0 = rf(ctx, version)
1287
+ } else {
1288
+ r0 = ret.Error(0)
1289
+ }
1290
+
1291
+ return r0
1292
+ }
1293
+
1294
+ // MockSchemaReader_WaitForUpdate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WaitForUpdate'
1295
+ type MockSchemaReader_WaitForUpdate_Call struct {
1296
+ *mock.Call
1297
+ }
1298
+
1299
+ // WaitForUpdate is a helper method to define mock.On call
1300
+ // - ctx context.Context
1301
+ // - version uint64
1302
+ func (_e *MockSchemaReader_Expecter) WaitForUpdate(ctx interface{}, version interface{}) *MockSchemaReader_WaitForUpdate_Call {
1303
+ return &MockSchemaReader_WaitForUpdate_Call{Call: _e.mock.On("WaitForUpdate", ctx, version)}
1304
+ }
1305
+
1306
+ func (_c *MockSchemaReader_WaitForUpdate_Call) Run(run func(ctx context.Context, version uint64)) *MockSchemaReader_WaitForUpdate_Call {
1307
+ _c.Call.Run(func(args mock.Arguments) {
1308
+ run(args[0].(context.Context), args[1].(uint64))
1309
+ })
1310
+ return _c
1311
+ }
1312
+
1313
+ func (_c *MockSchemaReader_WaitForUpdate_Call) Return(_a0 error) *MockSchemaReader_WaitForUpdate_Call {
1314
+ _c.Call.Return(_a0)
1315
+ return _c
1316
+ }
1317
+
1318
+ func (_c *MockSchemaReader_WaitForUpdate_Call) RunAndReturn(run func(context.Context, uint64) error) *MockSchemaReader_WaitForUpdate_Call {
1319
+ _c.Call.Return(run)
1320
+ return _c
1321
+ }
1322
+
1323
+ // NewMockSchemaReader creates a new instance of MockSchemaReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
1324
+ // The first argument is typically a *testing.T value.
1325
+ func NewMockSchemaReader(t interface {
1326
+ mock.TestingT
1327
+ Cleanup(func())
1328
+ }) *MockSchemaReader {
1329
+ mock := &MockSchemaReader{}
1330
+ mock.Mock.Test(t)
1331
+
1332
+ t.Cleanup(func() { mock.AssertExpectations(t) })
1333
+
1334
+ return mock
1335
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/parser.go ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "encoding/json"
16
+ "fmt"
17
+ "reflect"
18
+ "sort"
19
+ "strings"
20
+
21
+ "github.com/pkg/errors"
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/entities/modelsext"
24
+ "github.com/weaviate/weaviate/entities/schema"
25
+ schemaConfig "github.com/weaviate/weaviate/entities/schema/config"
26
+ "github.com/weaviate/weaviate/entities/vectorindex"
27
+ "github.com/weaviate/weaviate/usecases/config"
28
+ configRuntime "github.com/weaviate/weaviate/usecases/config/runtime"
29
+ shardingConfig "github.com/weaviate/weaviate/usecases/sharding/config"
30
+ )
31
+
32
+ var errPropertiesUpdatedInClassUpdate = errors.Errorf(
33
+ "property fields other than description cannot be updated through updating the class. Use the add " +
34
+ "property feature (e.g. \"POST /v1/schema/{className}/properties\") " +
35
+ "to add additional properties")
36
+
37
+ type modulesProvider interface {
38
+ IsGenerative(string) bool
39
+ IsReranker(string) bool
40
+ IsMultiVector(string) bool
41
+ }
42
+
43
+ type Parser struct {
44
+ clusterState clusterState
45
+ configParser VectorConfigParser
46
+ validator validator
47
+ modules modulesProvider
48
+ defaultQuantization *configRuntime.DynamicValue[string]
49
+ }
50
+
51
+ func NewParser(cs clusterState, vCfg VectorConfigParser, v validator, modules modulesProvider, defaultQuantization *configRuntime.DynamicValue[string]) *Parser {
52
+ return &Parser{
53
+ clusterState: cs,
54
+ configParser: vCfg,
55
+ validator: v,
56
+ modules: modules,
57
+ defaultQuantization: defaultQuantization,
58
+ }
59
+ }
60
+
61
+ func (p *Parser) ParseClass(class *models.Class) error {
62
+ if class == nil {
63
+ return fmt.Errorf("class cannot be nil")
64
+ }
65
+
66
+ if strings.EqualFold(class.Class, config.DefaultRaftDir) {
67
+ return fmt.Errorf("parse class name: %w", fmt.Errorf("class name `raft` is reserved"))
68
+ }
69
+
70
+ if err := p.parseShardingConfig(class); err != nil {
71
+ return fmt.Errorf("parse sharding config: %w", err)
72
+ }
73
+
74
+ if err := p.parseVectorIndexConfig(class); err != nil {
75
+ return fmt.Errorf("parse vector index config: %w", err)
76
+ }
77
+
78
+ return nil
79
+ }
80
+
81
+ func (p *Parser) parseModuleConfig(class *models.Class) error {
82
+ if class.ModuleConfig == nil {
83
+ return nil
84
+ }
85
+
86
+ mapMC, ok := class.ModuleConfig.(map[string]any)
87
+ if !ok {
88
+ return fmt.Errorf("module config is not a map, got %v", class.ModuleConfig)
89
+ }
90
+
91
+ mc, err := p.moduleConfig(mapMC)
92
+ if err != nil {
93
+ return fmt.Errorf("module config: %w", err)
94
+ }
95
+ class.ModuleConfig = mc
96
+
97
+ return nil
98
+ }
99
+
100
+ func (p *Parser) parseVectorConfig(class *models.Class) error {
101
+ if class.VectorConfig == nil {
102
+ return nil
103
+ }
104
+
105
+ newVC := map[string]models.VectorConfig{}
106
+ for vector, config := range class.VectorConfig {
107
+ mapMC, ok := config.Vectorizer.(map[string]any)
108
+ if !ok {
109
+ return fmt.Errorf("vectorizer for %s is not a map, got %v", vector, config)
110
+ }
111
+
112
+ mc, err := p.moduleConfig(mapMC)
113
+ if err != nil {
114
+ return fmt.Errorf("vectorizer config: %w", err)
115
+ }
116
+
117
+ config.Vectorizer = mc
118
+ newVC[vector] = config
119
+ }
120
+ class.VectorConfig = newVC
121
+ return nil
122
+ }
123
+
124
+ func (p *Parser) moduleConfig(moduleConfig map[string]any) (map[string]any, error) {
125
+ parsedMC := map[string]any{}
126
+ for module, config := range moduleConfig {
127
+ if config == nil {
128
+ parsedMC[module] = nil // nil is allowed, do no further parsing
129
+ continue
130
+ }
131
+ mapC, ok := config.(map[string]any)
132
+ if !ok {
133
+ return nil, fmt.Errorf("module config for %s is not a map, got %v", module, config)
134
+ }
135
+ parsedC := map[string]any{}
136
+ // raft interprets all `json.Number` types as float64 when unmarshalling
137
+ // we parse them explicitly here so that UpdateClass can compare the new class
138
+ // with the old one read from the raft schema manager
139
+ for key, value := range mapC {
140
+ if number, ok := value.(json.Number); ok {
141
+ if integer, err := number.Int64(); err == nil {
142
+ parsedC[key] = float64(integer)
143
+ } else if float, err := number.Float64(); err == nil {
144
+ parsedC[key] = float
145
+ } else {
146
+ parsedC[key] = number.String()
147
+ }
148
+ continue
149
+ }
150
+ parsedC[key] = value
151
+ }
152
+ parsedMC[module] = parsedC
153
+ }
154
+ return parsedMC, nil
155
+ }
156
+
157
+ func (p *Parser) parseVectorIndexConfig(class *models.Class) error {
158
+ if !hasTargetVectors(class) || class.VectorIndexType != "" {
159
+ parsed, err := p.parseGivenVectorIndexConfig(class.VectorIndexType, class.VectorIndexConfig, p.modules.IsMultiVector(class.Vectorizer), p.defaultQuantization)
160
+ if err != nil {
161
+ return err
162
+ }
163
+ if parsed.IsMultiVector() {
164
+ return fmt.Errorf("class.VectorIndexConfig multi vector type index type is only configurable using named vectors")
165
+ }
166
+ class.VectorIndexConfig = parsed
167
+ }
168
+
169
+ if err := p.parseTargetVectorsIndexConfig(class); err != nil {
170
+ return err
171
+ }
172
+ return nil
173
+ }
174
+
175
+ func (p *Parser) parseShardingConfig(class *models.Class) (err error) {
176
+ // multiTenancyConfig and shardingConfig are mutually exclusive
177
+ cfg := shardingConfig.Config{} // cfg is empty in case of MT
178
+ if !schema.MultiTenancyEnabled(class) {
179
+ cfg, err = shardingConfig.ParseConfig(class.ShardingConfig, p.clusterState.NodeCount())
180
+ if err != nil {
181
+ return err
182
+ }
183
+
184
+ }
185
+ class.ShardingConfig = cfg
186
+ return nil
187
+ }
188
+
189
+ func (p *Parser) parseTargetVectorsIndexConfig(class *models.Class) error {
190
+ for targetVector, vectorConfig := range class.VectorConfig {
191
+ isMultiVector := false
192
+ vectorizerModuleName := ""
193
+ if vectorizer, ok := vectorConfig.Vectorizer.(map[string]interface{}); ok {
194
+ for name := range vectorizer {
195
+ isMultiVector = p.modules.IsMultiVector(name)
196
+ vectorizerModuleName = name
197
+ }
198
+ }
199
+ parsed, err := p.parseGivenVectorIndexConfig(vectorConfig.VectorIndexType, vectorConfig.VectorIndexConfig, isMultiVector, p.defaultQuantization)
200
+ if err != nil {
201
+ return fmt.Errorf("parse vector config for %s: %w", targetVector, err)
202
+ }
203
+ if parsed.IsMultiVector() && vectorizerModuleName != "none" && !isMultiVector {
204
+ return fmt.Errorf("parse vector config for %s: multi vector index configured but vectorizer: %q doesn't support multi vectors", targetVector, vectorizerModuleName)
205
+ }
206
+ vectorConfig.VectorIndexConfig = parsed
207
+ class.VectorConfig[targetVector] = vectorConfig
208
+ }
209
+ return nil
210
+ }
211
+
212
+ func (p *Parser) parseGivenVectorIndexConfig(vectorIndexType string,
213
+ vectorIndexConfig interface{}, isMultiVector bool, defaultQuantization *configRuntime.DynamicValue[string],
214
+ ) (schemaConfig.VectorIndexConfig, error) {
215
+ if vectorIndexType != vectorindex.VectorIndexTypeHNSW && vectorIndexType != vectorindex.VectorIndexTypeFLAT && vectorIndexType != vectorindex.VectorIndexTypeDYNAMIC {
216
+ return nil, errors.Errorf(
217
+ "parse vector index config: unsupported vector index type: %q",
218
+ vectorIndexType)
219
+ }
220
+
221
+ if vectorIndexType != vectorindex.VectorIndexTypeHNSW && isMultiVector {
222
+ return nil, errors.Errorf(
223
+ "parse vector index config: multi vector index is not supported for vector index type: %q, only supported type is hnsw",
224
+ vectorIndexType)
225
+ }
226
+
227
+ parsed, err := p.configParser(vectorIndexConfig, vectorIndexType, isMultiVector)
228
+ if err != nil {
229
+ return nil, errors.Wrap(err, "parse vector index config")
230
+ }
231
+ return parsed, nil
232
+ }
233
+
234
+ // ParseClassUpdate parses a class after unmarshaling by setting concrete types for the fields
235
+ func (p *Parser) ParseClassUpdate(class, update *models.Class) (*models.Class, error) {
236
+ if err := p.ParseClass(update); err != nil {
237
+ return nil, err
238
+ }
239
+ mtEnabled, err := validateUpdatingMT(class, update)
240
+ if err != nil {
241
+ return nil, err
242
+ }
243
+
244
+ if err := validateImmutableFields(class, update); err != nil {
245
+ return nil, err
246
+ }
247
+
248
+ if err := p.validateModuleConfigsParityAndImmutables(class, update); err != nil {
249
+ return nil, err
250
+ }
251
+
252
+ // run target vectors validation first, as it will reject classes
253
+ // where legacy vector was changed to target vectors and vice versa
254
+ if err = p.validateNamedVectorConfigsParityAndImmutables(class, update); err != nil {
255
+ return nil, err
256
+ }
257
+
258
+ if err = validateLegacyVectorIndexConfigImmutableFields(class, update); err != nil {
259
+ return nil, err
260
+ }
261
+
262
+ if class.VectorIndexConfig != nil || update.VectorIndexConfig != nil {
263
+ vIdxConfig, ok1 := class.VectorIndexConfig.(schemaConfig.VectorIndexConfig)
264
+ vIdxConfigU, ok2 := update.VectorIndexConfig.(schemaConfig.VectorIndexConfig)
265
+ if !ok1 || !ok2 {
266
+ return nil, fmt.Errorf("vector index config wrong type: current=%t new=%t", ok1, ok2)
267
+ }
268
+ if err := p.validator.ValidateVectorIndexConfigUpdate(vIdxConfig, vIdxConfigU); err != nil {
269
+ return nil, fmt.Errorf("validate vector index config: %w", err)
270
+ }
271
+ }
272
+
273
+ if hasTargetVectors(update) {
274
+ if err := p.validator.ValidateVectorIndexConfigsUpdate(
275
+ asVectorIndexConfigs(class), asVectorIndexConfigs(update)); err != nil {
276
+ return nil, err
277
+ }
278
+ }
279
+
280
+ if err := validateShardingConfig(class, update, mtEnabled); err != nil {
281
+ return nil, fmt.Errorf("validate sharding config: %w", err)
282
+ }
283
+
284
+ if err = p.validatePropertiesForUpdate(class.Properties, update.Properties); err != nil {
285
+ return nil, err
286
+ }
287
+
288
+ if err := p.validator.ValidateInvertedIndexConfigUpdate(
289
+ class.InvertedIndexConfig,
290
+ update.InvertedIndexConfig); err != nil {
291
+ return nil, fmt.Errorf("inverted index config: %w", err)
292
+ }
293
+
294
+ return update, nil
295
+ }
296
+
297
+ func (p *Parser) validatePropertiesForUpdate(existing []*models.Property, new []*models.Property) error {
298
+ if len(existing) != len(new) {
299
+ return errPropertiesUpdatedInClassUpdate
300
+ }
301
+
302
+ sort.Slice(existing, func(i, j int) bool {
303
+ return existing[i].Name < existing[j].Name
304
+ })
305
+
306
+ sort.Slice(new, func(i, j int) bool {
307
+ return new[i].Name < new[j].Name
308
+ })
309
+
310
+ for i, prop := range existing {
311
+ // make a copy of the properties to remove the description field
312
+ // so that we can compare the rest of the fields
313
+ if prop == nil {
314
+ continue
315
+ }
316
+ if new[i] == nil {
317
+ continue
318
+ }
319
+
320
+ if err := p.validatePropertyForUpdate(prop, new[i]); err != nil {
321
+ return errors.Wrapf(err, "property %q", prop.Name)
322
+ }
323
+ }
324
+
325
+ return nil
326
+ }
327
+
328
+ func propertyAsMap(in any) (map[string]any, error) {
329
+ out := make(map[string]any)
330
+
331
+ v := reflect.ValueOf(in)
332
+ if v.Kind() == reflect.Ptr {
333
+ v = v.Elem()
334
+ }
335
+
336
+ if v.Kind() != reflect.Struct { // Non-structural return error
337
+ return nil, fmt.Errorf("asMap only accepts struct or struct pointer; got %T", v)
338
+ }
339
+
340
+ t := v.Type()
341
+ // Traversing structure fields
342
+ // Specify the tagName value as the key in the map; the field value as the value in the map
343
+ for i := 0; i < v.NumField(); i++ {
344
+ tfi := t.Field(i)
345
+ if tagValue := tfi.Tag.Get("json"); tagValue != "" {
346
+ key := strings.Split(tagValue, ",")[0]
347
+ if key == "description" {
348
+ continue
349
+ }
350
+ if key == "nestedProperties" {
351
+ nps := v.Field(i).Interface().([]*models.NestedProperty)
352
+ out[key] = make([]map[string]any, 0, len(nps))
353
+ for _, np := range nps {
354
+ npm, err := propertyAsMap(np)
355
+ if err != nil {
356
+ return nil, err
357
+ }
358
+ out[key] = append(out[key].([]map[string]any), npm)
359
+ }
360
+ continue
361
+ }
362
+ out[key] = v.Field(i).Interface()
363
+ }
364
+ }
365
+ return out, nil
366
+ }
367
+
368
+ func (p *Parser) validatePropertyForUpdate(existing, new *models.Property) error {
369
+ e, err := propertyAsMap(existing)
370
+ if err != nil {
371
+ return errors.Wrap(err, "converting existing properties to a map")
372
+ }
373
+
374
+ n, err := propertyAsMap(new)
375
+ if err != nil {
376
+ return errors.Wrap(err, "converting new properties to a map")
377
+ }
378
+
379
+ var (
380
+ existingModuleConfig = cutModuleConfig(e)
381
+ newModuleConfig = cutModuleConfig(n)
382
+ )
383
+
384
+ for moduleName, existingCfg := range existingModuleConfig {
385
+ newCfg, ok := newModuleConfig[moduleName]
386
+ if !ok {
387
+ return errors.Errorf("module %q configuration was removed", moduleName)
388
+ }
389
+
390
+ if !reflect.DeepEqual(existingCfg, newCfg) {
391
+ return errors.Errorf("module %q configuration cannot be updated", moduleName)
392
+ }
393
+ }
394
+
395
+ if !reflect.DeepEqual(e, n) {
396
+ return errPropertiesUpdatedInClassUpdate
397
+ }
398
+
399
+ return nil
400
+ }
401
+
402
+ func cutModuleConfig(properties map[string]any) map[string]any {
403
+ cfg, _ := properties["moduleConfig"].(map[string]any)
404
+ delete(properties, "moduleConfig")
405
+ return cfg
406
+ }
407
+
408
+ func hasTargetVectors(class *models.Class) bool {
409
+ return len(class.VectorConfig) > 0
410
+ }
411
+
412
+ func (p *Parser) validateModuleConfigsParityAndImmutables(initial, updated *models.Class) error {
413
+ if updated.ModuleConfig == nil || reflect.DeepEqual(initial.ModuleConfig, updated.ModuleConfig) {
414
+ return nil
415
+ }
416
+
417
+ updatedModConf, ok := updated.ModuleConfig.(map[string]any)
418
+ if !ok {
419
+ return fmt.Errorf("module config for %s is not a map, got %v", updated.ModuleConfig, updated.ModuleConfig)
420
+ }
421
+
422
+ updatedModConf, err := p.moduleConfig(updatedModConf)
423
+ if err != nil {
424
+ return err
425
+ }
426
+
427
+ initialModConf, _ := initial.ModuleConfig.(map[string]any)
428
+
429
+ // this part:
430
+ // - allow adding new modules
431
+ // - only allows updating generative and rerankers
432
+ // - only one gen/rerank module can be present. Existing ones will be replaced, updating with more than one is not
433
+ // allowed
434
+ // - other modules will not be changed. They can be present in the update if they have EXACTLY the same settings
435
+ hasGenerativeUpdate := false
436
+ hasRerankerUpdate := false
437
+ for module := range updatedModConf {
438
+ if p.modules.IsGenerative(module) {
439
+ if hasGenerativeUpdate {
440
+ return fmt.Errorf("updated moduleconfig has multiple generative modules: %v", updatedModConf)
441
+ }
442
+ hasGenerativeUpdate = true
443
+ continue
444
+ }
445
+
446
+ if p.modules.IsReranker(module) {
447
+ if hasRerankerUpdate {
448
+ return fmt.Errorf("updated moduleconfig has multiple reranker modules: %v", updatedModConf)
449
+ }
450
+ hasRerankerUpdate = true
451
+ continue
452
+ }
453
+
454
+ if _, moduleExisted := initialModConf[module]; !moduleExisted {
455
+ continue
456
+ }
457
+
458
+ if reflect.DeepEqual(initialModConf[module], updatedModConf[module]) {
459
+ continue
460
+ }
461
+
462
+ return fmt.Errorf("can only update generative and reranker module configs. Got: %v", module)
463
+ }
464
+
465
+ if initial.ModuleConfig == nil {
466
+ initial.ModuleConfig = updatedModConf
467
+ return nil
468
+ }
469
+
470
+ if _, ok := initial.ModuleConfig.(map[string]any); !ok {
471
+ initial.ModuleConfig = updatedModConf
472
+ return nil
473
+ }
474
+ if hasGenerativeUpdate {
475
+ // clear out old generative module
476
+ for module := range initialModConf {
477
+ if p.modules.IsGenerative(module) {
478
+ delete(initialModConf, module)
479
+ }
480
+ }
481
+ }
482
+
483
+ if hasRerankerUpdate {
484
+ // clear out old reranker module
485
+ for module := range initialModConf {
486
+ if p.modules.IsReranker(module) {
487
+ delete(initialModConf, module)
488
+ }
489
+ }
490
+ }
491
+
492
+ for module := range updatedModConf {
493
+ initialModConf[module] = updatedModConf[module]
494
+ }
495
+ updated.ModuleConfig = initialModConf
496
+ return nil
497
+ }
498
+
499
+ func (p *Parser) validateNamedVectorConfigsParityAndImmutables(initial, updated *models.Class) error {
500
+ if modelsext.ClassHasLegacyVectorIndex(initial) {
501
+ for targetVector := range updated.VectorConfig {
502
+ if targetVector == modelsext.DefaultNamedVectorName {
503
+ return fmt.Errorf("vector named %s cannot be created when collection level vector index is configured", modelsext.DefaultNamedVectorName)
504
+ }
505
+ }
506
+ }
507
+
508
+ for vecName, initialCfg := range initial.VectorConfig {
509
+ updatedCfg, ok := updated.VectorConfig[vecName]
510
+ if !ok {
511
+ return fmt.Errorf("missing config for vector %q", vecName)
512
+ }
513
+
514
+ // immutable vector type
515
+ if initialCfg.VectorIndexType != updatedCfg.VectorIndexType {
516
+ return fmt.Errorf("vector index type of vector %q is immutable: attempted change from %q to %q",
517
+ vecName, initialCfg.VectorIndexType, updatedCfg.VectorIndexType)
518
+ }
519
+
520
+ // immutable vectorizer
521
+ if imap, ok := initialCfg.Vectorizer.(map[string]interface{}); ok && len(imap) == 1 {
522
+ umap, ok := updatedCfg.Vectorizer.(map[string]interface{})
523
+ if !ok || len(umap) != 1 {
524
+ return fmt.Errorf("invalid vectorizer config for vector %q", vecName)
525
+ }
526
+
527
+ ivectorizer := ""
528
+ for k := range imap {
529
+ ivectorizer = k
530
+ }
531
+ uvectorizer := ""
532
+ for k := range umap {
533
+ uvectorizer = k
534
+ }
535
+
536
+ if ivectorizer != uvectorizer {
537
+ return fmt.Errorf("vectorizer of vector %q is immutable: attempted change from %q to %q",
538
+ vecName, ivectorizer, uvectorizer)
539
+ }
540
+ }
541
+ }
542
+ return nil
543
+ }
544
+
545
+ func asVectorIndexConfigs(c *models.Class) map[string]schemaConfig.VectorIndexConfig {
546
+ if c.VectorConfig == nil {
547
+ return nil
548
+ }
549
+
550
+ cfgs := map[string]schemaConfig.VectorIndexConfig{}
551
+ for vecName := range c.VectorConfig {
552
+ cfgs[vecName] = c.VectorConfig[vecName].VectorIndexConfig.(schemaConfig.VectorIndexConfig)
553
+ }
554
+ return cfgs
555
+ }
556
+
557
+ func validateShardingConfig(current, update *models.Class, mtEnabled bool) error {
558
+ if mtEnabled {
559
+ return nil
560
+ }
561
+ first, ok := current.ShardingConfig.(shardingConfig.Config)
562
+ if !ok {
563
+ return fmt.Errorf("current config is not well-formed")
564
+ }
565
+ second, ok := update.ShardingConfig.(shardingConfig.Config)
566
+ if !ok {
567
+ return fmt.Errorf("updated config is not well-formed")
568
+ }
569
+ if first.DesiredCount != second.DesiredCount {
570
+ return fmt.Errorf("re-sharding not supported yet: shard count is immutable: "+
571
+ "attempted change from \"%d\" to \"%d\"", first.DesiredCount,
572
+ second.DesiredCount)
573
+ }
574
+
575
+ if first.VirtualPerPhysical != second.VirtualPerPhysical {
576
+ return fmt.Errorf("virtual shards per physical is immutable: "+
577
+ "attempted change from \"%d\" to \"%d\"", first.VirtualPerPhysical,
578
+ second.VirtualPerPhysical)
579
+ }
580
+ return nil
581
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/parser_test.go ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "strings"
16
+ "testing"
17
+
18
+ "github.com/stretchr/testify/require"
19
+ "github.com/weaviate/weaviate/entities/models"
20
+ "github.com/weaviate/weaviate/entities/vectorindex"
21
+ enthnsw "github.com/weaviate/weaviate/entities/vectorindex/hnsw"
22
+ "github.com/weaviate/weaviate/usecases/fakes"
23
+ "github.com/weaviate/weaviate/usecases/sharding/config"
24
+ )
25
+
26
+ const hnswT = vectorindex.VectorIndexTypeHNSW
27
+
28
+ func TestParser(t *testing.T) {
29
+ cs := fakes.NewFakeClusterState()
30
+ p := NewParser(cs, dummyParseVectorConfig, fakeValidator{}, fakeModulesProvider{}, nil)
31
+
32
+ sc := config.Config{DesiredCount: 1, VirtualPerPhysical: 128, ActualCount: 1, DesiredVirtualCount: 128, Key: "_id", Strategy: "hash", Function: "murmur3"}
33
+ vic := enthnsw.NewDefaultUserConfig()
34
+ emptyMap := map[string]interface{}{}
35
+ valueMap := map[string]interface{}{"something": emptyMap}
36
+
37
+ testCases := []struct {
38
+ name string
39
+ old *models.Class
40
+ update *models.Class
41
+ expected *models.Class
42
+ error bool
43
+ }{
44
+ {
45
+ name: "update description",
46
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: enthnsw.NewDefaultUserConfig(), ShardingConfig: sc},
47
+ update: &models.Class{Class: "Test", Description: "NEW", VectorIndexType: hnswT, VectorIndexConfig: enthnsw.NewDefaultUserConfig()},
48
+ expected: &models.Class{Class: "Test", Description: "NEW", VectorIndexType: hnswT, VectorIndexConfig: enthnsw.NewDefaultUserConfig(), ShardingConfig: sc},
49
+ error: false,
50
+ },
51
+ {
52
+ name: "update generative module - previously not configured",
53
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc},
54
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"generative-madeup": emptyMap}},
55
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"generative-madeup": emptyMap}},
56
+ error: false,
57
+ },
58
+ {
59
+ name: "update generative module - previously not configured, other modules present",
60
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"text2vec-random": emptyMap}},
61
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"generative-madeup": emptyMap}},
62
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"generative-madeup": emptyMap, "text2vec-random": emptyMap}},
63
+ error: false,
64
+ },
65
+ {
66
+ name: "update generative module - previously not configured, other generative module present",
67
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"generative-random": emptyMap}},
68
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"generative-madeup": emptyMap}},
69
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"generative-madeup": emptyMap}},
70
+ error: false,
71
+ },
72
+ {
73
+ name: "update reranker module - previously not configured",
74
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc},
75
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"reranker-madeup": emptyMap}},
76
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"reranker-madeup": emptyMap}},
77
+ error: false,
78
+ },
79
+ {
80
+ name: "update reranker module - previously not configured, other modules present",
81
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"text2vec-random": emptyMap}},
82
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"reranker-madeup": emptyMap}},
83
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"reranker-madeup": emptyMap, "text2vec-random": emptyMap}},
84
+ error: false,
85
+ },
86
+ {
87
+ name: "update reranker module - previously not configured, other generative module present",
88
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"reranker-random": emptyMap, "generative-random": emptyMap}},
89
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"reranker-madeup": emptyMap}},
90
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"reranker-madeup": emptyMap, "generative-random": emptyMap}},
91
+ error: false,
92
+ },
93
+ {
94
+ name: "update reranker and generative module - previously not configured, other text2vec module present",
95
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"reranker-random": emptyMap, "generative-random": emptyMap, "text2vec-random": emptyMap}},
96
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"reranker-madeup": emptyMap, "generative-madeup": emptyMap}},
97
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"reranker-madeup": emptyMap, "generative-madeup": emptyMap, "text2vec-random": emptyMap}},
98
+ error: false,
99
+ },
100
+ {
101
+ name: "update text2vec - previously not configured, add a new vector index",
102
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc},
103
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"text2vec-random": emptyMap}},
104
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"text2vec-random": emptyMap}},
105
+ error: false,
106
+ },
107
+ {
108
+ name: "update text2vec - previously differently configured => error",
109
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"text2vec-random": valueMap}},
110
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"text2vec-random": emptyMap}},
111
+ error: true,
112
+ },
113
+ {
114
+ name: "update text2vec - other modules present => error",
115
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"generative-random": valueMap}},
116
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"text2vec-random": emptyMap, "generative-random": valueMap}},
117
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"text2vec-random": emptyMap, "generative-random": valueMap}},
118
+ error: false,
119
+ },
120
+ {
121
+ name: "update with same text2vec config",
122
+ old: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"text2vec-random": valueMap}},
123
+ update: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ModuleConfig: map[string]interface{}{"text2vec-random": valueMap}},
124
+ expected: &models.Class{Class: "Test", VectorIndexType: hnswT, VectorIndexConfig: vic, ShardingConfig: sc, ModuleConfig: map[string]interface{}{"text2vec-random": valueMap}},
125
+ error: false,
126
+ },
127
+ }
128
+
129
+ for _, test := range testCases {
130
+ t.Run(test.name, func(t *testing.T) {
131
+ update, err := p.ParseClassUpdate(test.old, test.update)
132
+ if test.error {
133
+ require.Error(t, err)
134
+ } else {
135
+ require.NoError(t, err)
136
+ require.Equal(t, test.expected.Description, update.Description)
137
+ require.Equal(t, test.expected.ModuleConfig, update.ModuleConfig)
138
+ }
139
+ })
140
+ }
141
+ }
142
+
143
+ func Test_asMap(t *testing.T) {
144
+ t.Run("not nil", func(t *testing.T) {
145
+ m, err := propertyAsMap(&models.Property{
146
+ Name: "name",
147
+ Description: "description",
148
+ DataType: []string{"object"},
149
+ NestedProperties: []*models.NestedProperty{{
150
+ Name: "nested",
151
+ Description: "nested description",
152
+ DataType: []string{"text"},
153
+ }},
154
+ })
155
+ require.NotNil(t, m)
156
+ require.Nil(t, err)
157
+
158
+ _, ok := m["description"]
159
+ require.False(t, ok)
160
+
161
+ nps, ok := m["nestedProperties"].([]map[string]any)
162
+ require.True(t, ok)
163
+ require.Len(t, nps, 1)
164
+
165
+ _, ok = nps[0]["description"]
166
+ require.False(t, ok)
167
+ })
168
+ }
169
+
170
+ type fakeModulesProvider struct{}
171
+
172
+ func (m fakeModulesProvider) IsReranker(name string) bool {
173
+ return strings.Contains(name, "reranker")
174
+ }
175
+
176
+ func (m fakeModulesProvider) IsGenerative(name string) bool {
177
+ return strings.Contains(name, "generative")
178
+ }
179
+
180
+ func (m fakeModulesProvider) IsMultiVector(name string) bool {
181
+ return strings.Contains(name, "colbert")
182
+ }
platform/dbops/binaries/weaviate-src/usecases/schema/property.go ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package schema
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "strings"
18
+
19
+ clusterSchema "github.com/weaviate/weaviate/cluster/schema"
20
+ "github.com/weaviate/weaviate/entities/models"
21
+ "github.com/weaviate/weaviate/entities/schema"
22
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
23
+ )
24
+
25
+ // AddClassProperty it is upsert operation. it adds properties to a class and updates
26
+ // existing properties if the merge bool passed true.
27
+ func (h *Handler) AddClassProperty(ctx context.Context, principal *models.Principal,
28
+ class *models.Class, className string, merge bool, newProps ...*models.Property,
29
+ ) (*models.Class, uint64, error) {
30
+ if err := h.Authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.CollectionsMetadata(className)...); err != nil {
31
+ return nil, 0, err
32
+ }
33
+
34
+ if err := h.Authorizer.Authorize(ctx, principal, authorization.READ, authorization.CollectionsMetadata(className)...); err != nil {
35
+ return nil, 0, err
36
+ }
37
+ classGetterWithAuth := func(name string) (*models.Class, error) {
38
+ if err := h.Authorizer.Authorize(ctx, principal, authorization.READ, authorization.CollectionsMetadata(name)...); err != nil {
39
+ return nil, err
40
+ }
41
+ return h.schemaReader.ReadOnlyClass(name), nil
42
+ }
43
+
44
+ if class == nil {
45
+ return nil, 0, fmt.Errorf("class is nil: %w", ErrNotFound)
46
+ }
47
+
48
+ if len(newProps) == 0 {
49
+ return nil, 0, nil
50
+ }
51
+
52
+ // validate new props
53
+ for _, prop := range newProps {
54
+ if prop.Name == "" {
55
+ return nil, 0, fmt.Errorf("property must contain name")
56
+ }
57
+ prop.Name = schema.LowercaseFirstLetter(prop.Name)
58
+ if prop.DataType == nil {
59
+ return nil, 0, fmt.Errorf("property must contain dataType")
60
+ }
61
+ }
62
+
63
+ if err := h.setNewPropDefaults(class, newProps...); err != nil {
64
+ return nil, 0, err
65
+ }
66
+
67
+ existingNames := make(map[string]bool, len(class.Properties))
68
+ if !merge {
69
+ for _, prop := range class.Properties {
70
+ existingNames[strings.ToLower(prop.Name)] = true
71
+ }
72
+ }
73
+
74
+ if err := h.validateProperty(class, existingNames, false, classGetterWithAuth, newProps...); err != nil {
75
+ return nil, 0, err
76
+ }
77
+
78
+ // TODO-RAFT use UpdateProperty() for adding/merging property when index idempotence exists
79
+ // revisit when index idempotence exists and/or allowing merging properties on index.
80
+ props := schema.DedupProperties(class.Properties, newProps)
81
+ if len(props) == 0 {
82
+ return class, 0, nil
83
+ }
84
+
85
+ migratePropertySettings(props...)
86
+
87
+ class.Properties = clusterSchema.MergeProps(class.Properties, props)
88
+ version, err := h.schemaManager.AddProperty(ctx, class.Class, props...)
89
+ if err != nil {
90
+ return nil, 0, err
91
+ }
92
+ return class, version, err
93
+ }
94
+
95
+ // DeleteClassProperty from existing Schema
96
+ func (h *Handler) DeleteClassProperty(ctx context.Context, principal *models.Principal,
97
+ class string, property string,
98
+ ) error {
99
+ err := h.Authorizer.Authorize(ctx, principal, authorization.UPDATE, authorization.CollectionsMetadata(class)...)
100
+ if err != nil {
101
+ return err
102
+ }
103
+
104
+ return fmt.Errorf("deleting a property is currently not supported, see " +
105
+ "https://github.com/weaviate/weaviate/issues/973 for details")
106
+ // return h.deleteClassProperty(ctx, class, property, kind.Action)
107
+ }
108
+
109
+ func (h *Handler) setNewPropDefaults(class *models.Class, props ...*models.Property) error {
110
+ setPropertyDefaults(props...)
111
+ h.moduleConfig.SetSinglePropertyDefaults(class, props...)
112
+ return nil
113
+ }
114
+
115
+ func (h *Handler) validatePropModuleConfig(class *models.Class, props ...*models.Property) error {
116
+ configuredVectorizers := map[string]struct{}{}
117
+ if class.Vectorizer != "" {
118
+ configuredVectorizers[class.Vectorizer] = struct{}{}
119
+ }
120
+
121
+ for targetVector, cfg := range class.VectorConfig {
122
+ if vm, ok := cfg.Vectorizer.(map[string]interface{}); ok && len(vm) == 1 {
123
+ for vectorizer := range vm {
124
+ configuredVectorizers[vectorizer] = struct{}{}
125
+ }
126
+ } else if len(vm) > 1 {
127
+ return fmt.Errorf("vector index %q has multiple vectorizers", targetVector)
128
+ }
129
+ }
130
+
131
+ for _, prop := range props {
132
+ if prop.ModuleConfig == nil {
133
+ continue
134
+ }
135
+
136
+ modconfig, ok := prop.ModuleConfig.(map[string]interface{})
137
+ if !ok {
138
+ return fmt.Errorf("%v property config invalid", prop.Name)
139
+ }
140
+
141
+ for vectorizer, cfg := range modconfig {
142
+ if err := h.vectorizerValidator.ValidateVectorizer(vectorizer); err != nil {
143
+ continue
144
+ }
145
+
146
+ if _, ok := configuredVectorizers[vectorizer]; !ok {
147
+ return fmt.Errorf("vectorizer %q not configured for any of target vectors", vectorizer)
148
+ }
149
+
150
+ if _, ok := cfg.(map[string]interface{}); !ok {
151
+ return fmt.Errorf("vectorizer config for vectorizer %q not of type map[string]interface{}", vectorizer)
152
+ }
153
+ }
154
+ }
155
+
156
+ return nil
157
+ }