@@ -9,13 +9,13 @@ import (
9
9
10
10
"github.com/coder/coder/v2/coderd/database"
11
11
"github.com/coder/coder/v2/coderd/rbac"
12
+ "github.com/coder/coder/v2/coderd/util/syncmap"
12
13
)
13
14
14
- type (
15
- customRoleCtxKey struct {}
16
- customRoleCache map [string ]rbac.Role
17
- )
15
+ type customRoleCtxKey struct {}
18
16
17
+ // CustomRoleMW adds a custom role cache on the ctx to prevent duplicate
18
+ // db fetches.
19
19
func CustomRoleMW (next http.Handler ) http.Handler {
20
20
return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
21
21
r = r .WithContext (CustomRoleCacheContext (r .Context ()))
@@ -27,33 +27,25 @@ func CustomRoleMW(next http.Handler) http.Handler {
27
27
// same request lifecycle. Optimizing this to span requests should be done
28
28
// in the future.
29
29
func CustomRoleCacheContext (ctx context.Context ) context.Context {
30
- return context .WithValue (ctx , customRoleCtxKey {}, customRoleCache {} )
30
+ return context .WithValue (ctx , customRoleCtxKey {}, syncmap . New [ string , rbac. Role ]() )
31
31
}
32
32
33
- func roleCache (ctx context.Context ) customRoleCache {
34
- c , ok := ctx .Value (customRoleCtxKey {}).(customRoleCache )
33
+ func roleCache (ctx context.Context ) * syncmap. Map [ string , rbac. Role ] {
34
+ c , ok := ctx .Value (customRoleCtxKey {}).(* syncmap. Map [ string , rbac. Role ] )
35
35
if ! ok {
36
- return customRoleCache {}
36
+ return syncmap . New [ string , rbac. Role ]()
37
37
}
38
38
return c
39
39
}
40
40
41
- func store (ctx context.Context , name string , role rbac.Role ) {
42
- roleCache (ctx )[name ] = role
43
- }
44
-
45
- func load (ctx context.Context , name string ) (rbac.Role , bool ) {
46
- r , ok := roleCache (ctx )[name ]
47
- return r , ok
48
- }
49
-
50
41
// Expand will expand built in roles, and fetch custom roles from the database.
51
42
func Expand (ctx context.Context , db database.Store , names []string ) (rbac.Roles , error ) {
52
43
if len (names ) == 0 {
53
44
// That was easy
54
45
return []rbac.Role {}, nil
55
46
}
56
47
48
+ cache := roleCache (ctx )
57
49
lookup := make ([]string , 0 )
58
50
roles := make ([]rbac.Role , 0 , len (names ))
59
51
@@ -66,7 +58,7 @@ func Expand(ctx context.Context, db database.Store, names []string) (rbac.Roles,
66
58
}
67
59
68
60
// Check custom role cache
69
- customRole , ok := load ( ctx , name )
61
+ customRole , ok := cache . Load ( name )
70
62
if ok {
71
63
roles = append (roles , customRole )
72
64
continue
@@ -92,7 +84,7 @@ func Expand(ctx context.Context, db database.Store, names []string) (rbac.Roles,
92
84
return nil , xerrors .Errorf ("convert db role %q: %w" , dbrole , err )
93
85
}
94
86
roles = append (roles , converted )
95
- store ( ctx , dbrole .Name , converted )
87
+ cache . Store ( dbrole .Name , converted )
96
88
}
97
89
}
98
90
0 commit comments