Skip to content

Commit

Permalink
make nested context kind inaccessible
Browse files Browse the repository at this point in the history
  • Loading branch information
cwaldren-ld committed Dec 4, 2024
1 parent 743a0e9 commit 11b739c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
11 changes: 7 additions & 4 deletions ldai/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func (c *Client) Config(

func getAllAttributes(context ldcontext.Context) map[string]interface{} {
if !context.Multiple() {
return addSingleKindContextAttributes(context)
return addContextAttributes(context, false)
}

attributes := map[string]interface{}{
Expand All @@ -125,19 +125,22 @@ func getAllAttributes(context ldcontext.Context) map[string]interface{} {
}

for _, ctx := range context.GetAllIndividualContexts(nil) {
attributes[string(ctx.Kind())] = addSingleKindContextAttributes(ctx)
attributes[string(ctx.Kind())] = addContextAttributes(ctx, true)
}

return attributes
}

func addSingleKindContextAttributes(context ldcontext.Context) map[string]interface{} {
func addContextAttributes(context ldcontext.Context, omitKind bool) map[string]interface{} {
attributes := map[string]interface{}{
"kind": context.Kind(),
"key": context.Key(),
"anonymous": context.Anonymous(),
}

if !omitKind {
attributes["kind"] = context.Kind()
}

for _, attr := range context.GetOptionalAttributeNames(nil) {
attributes[attr] = context.GetValue(attr).AsArbitraryValue()
}
Expand Down
23 changes: 21 additions & 2 deletions ldai/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,8 +375,27 @@ func TestInterpolation(t *testing.T) {

context := ldcontext.NewMulti(user, cat)

result, err := eval(t, "kind={{ ldctx.kind }}", context, nil)
result, err := eval(t, "kind=<{{ ldctx.kind }}>", context, nil)
require.NoError(t, err)
assert.Equal(t, "kind=multi", result)
assert.Equal(t, "kind=<multi>", result)
})

t.Run("interpolation with multi kind context does not have child kinds", func(t *testing.T) {

// The idea here is that in a multi-kind context, we can access ldctx.kind (== "multi"), but you can't
// access the kind field of the individual nested contexts since this doesn't match the actual data model.
// That is, you can't access ldctx.user.kind or ldctx.cat.kind, only ldctx.kind.

user := ldcontext.NewBuilder("123").
SetValue("cat_ownership", ldvalue.ObjectBuild().Set("count", ldvalue.Int(12)).Build()).Build()

cat := ldcontext.NewBuilder("456").Kind("cat").
SetValue("health", ldvalue.ObjectBuild().Set("hunger", ldvalue.String("off the charts")).Build()).Build()

context := ldcontext.NewMulti(user, cat)

result, err := eval(t, "user_kind=<{{ ldctx.user.kind}}>,cat_kind=<{{ ldctx.cat.kind }}>", context, nil)
require.NoError(t, err)
assert.Equal(t, "user_kind=<>,cat_kind=<>", result)
})
}

0 comments on commit 11b739c

Please sign in to comment.