Skip to content

Commit

Permalink
feat: add GetNamespace utils method for context [multi-tenancy PR 1] (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
binbin-li authored Apr 3, 2024
1 parent e58f337 commit 4b07a26
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
8 changes: 7 additions & 1 deletion httpserver/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,19 @@ func (server *Server) mutate(ctx context.Context, w http.ResponseWriter, r *http
returnItem.Error = err.Error()
return
}
parsedReference, err := pkgUtils.ParseSubjectReference(image)
requestKey, err := pkgUtils.ParseRequestKey(image)
if err != nil {
returnItem.Error = err.Error()
return
}
parsedReference, err := pkgUtils.ParseSubjectReference(requestKey.Subject)
if err != nil {
err = errors.ErrorCodeReferenceInvalid.WithError(err).WithDetail(fmt.Sprintf("failed to parse image reference %s", image))
logger.GetLogger(ctx, server.LogOption).Error(err)
returnItem.Error = err.Error()
return
}
ctx = ctxUtils.SetContextWithNamespace(ctx, requestKey.Namespace)

if parsedReference.Digest == "" {
var selectedStore referrerstore.ReferrerStore
Expand Down
9 changes: 9 additions & 0 deletions internal/context/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ func SetContextWithNamespace(ctx context.Context, namespace string) context.Cont
return context.WithValue(ctx, contextKeyNamespace, namespace)
}

// GetNamespace returns the embedded namespace from the context.
func GetNamespace(ctx context.Context) string {
namespace := ctx.Value(contextKeyNamespace)
if namespace == nil {
return ""
}
return namespace.(string)
}

// CreateCacheKey creates a new cache key prefixed with embedded namespace.
func CreateCacheKey(ctx context.Context, key string) string {
namespace := ctx.Value(contextKeyNamespace)
Expand Down
37 changes: 37 additions & 0 deletions internal/context/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,40 @@ func TestCreateCacheKey(t *testing.T) {
})
}
}

func TestGetNamespace(t *testing.T) {
testCases := []struct {
name string
namespaceSet bool
namespace string
}{
{
name: "no namespace",
namespaceSet: false,
},
{
name: "empty namespace",
namespaceSet: true,
namespace: "",
},
{
name: "with namespace",
namespaceSet: true,
namespace: testNamespace,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
if tc.namespaceSet {
ctx = SetContextWithNamespace(ctx, tc.namespace)
}

namespace := GetNamespace(ctx)
if namespace != tc.namespace {
t.Fatalf("expected namespace %s, got %s", tc.namespace, namespace)
}
})
}
}

0 comments on commit 4b07a26

Please sign in to comment.