diff --git a/pkg/utils/converter.go b/pkg/utils/converter.go index a87e6b44..9490724e 100644 --- a/pkg/utils/converter.go +++ b/pkg/utils/converter.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "fmt" - "reflect" "strings" "github.com/sdcio/logger" @@ -96,24 +95,16 @@ func (c *Converter) ExpandUpdate(ctx context.Context, upd *sdcpb.Update) ([]*sdc } return nil, nil } - var v any - var err error - var jsonDecoder *json.Decoder - switch upd.GetValue().Value.(type) { - case *sdcpb.TypedValue_JsonIetfVal: - jsonDecoder = json.NewDecoder(bytes.NewReader(upd.GetValue().GetJsonIetfVal())) - case *sdcpb.TypedValue_JsonVal: - jsonDecoder = json.NewDecoder(bytes.NewReader(upd.GetValue().GetJsonVal())) - default: - return []*sdcpb.Update{upd}, nil - } - // don't decode into float64 but keep as a string - // this solves issues created by reading long integers - jsonDecoder.UseNumber() - err = jsonDecoder.Decode(&v) + v, isJSON, err := decodeJSONValue(upd.GetValue()) if err != nil { return nil, err } + if !isJSON { + return []*sdcpb.Update{upd}, nil + } + if v == nil { + return nil, nil + } // log.Debugf("update has jsonVal: %T, %v\n", v, v) rs, err := c.ExpandContainerValue(ctx, upd.GetPath(), v, rsp) if err != nil { @@ -123,29 +114,17 @@ func (c *Converter) ExpandUpdate(ctx context.Context, upd *sdcpb.Update) ([]*sdc return upds, nil case *sdcpb.SchemaElem_Field: - var v interface{} - var err error - - var jsonValue []byte if upd.GetValue() == nil { log.Error(nil, "value is nil", "path", upd.Path.ToXPath(false)) return nil, nil } - switch upd.GetValue().Value.(type) { - case *sdcpb.TypedValue_JsonVal: - jsonValue = upd.GetValue().GetJsonVal() - case *sdcpb.TypedValue_JsonIetfVal: - jsonValue = upd.GetValue().GetJsonIetfVal() + v, isJSON, err := decodeJSONValue(upd.GetValue()) + if err != nil { + return nil, err } - - // process value - if jsonValue != nil { - decoder := json.NewDecoder(bytes.NewReader(jsonValue)) - // Keep numbers as json.Number to avoid precision loss for large integers. - decoder.UseNumber() - err = decoder.Decode(&v) - if err != nil { - return nil, err + if isJSON { + if v == nil { + return nil, nil } upd.Value, err = sdcpb.ConvertJsonValueToTv(v, rsp.Field.GetType()) if err != nil { @@ -169,6 +148,13 @@ func (c *Converter) ExpandUpdate(ctx context.Context, upd *sdcpb.Update) ([]*sdc upds = append(upds, upd) return upds, nil case *sdcpb.SchemaElem_Leaflist: + v, isJSON, err := decodeJSONValue(upd.GetValue()) + if err != nil { + return nil, err + } + if isJSON && v == nil { + return nil, nil + } upds = append(upds, upd) return upds, nil } @@ -222,6 +208,8 @@ func (c *Converter) ExpandContainerValue(ctx context.Context, p *sdcpb.Path, jv log := logger.FromContext(ctx) // log.Debugf("expanding jsonVal %T | %v | %v", jv, jv, p) switch jv := jv.(type) { + case nil: + return nil, nil case string: v := strings.Trim(jv, "\"") return []*sdcpb.Update{ @@ -240,53 +228,16 @@ func (c *Converter) ExpandContainerValue(ctx context.Context, p *sdcpb.Path, jv if numElems := len(p.GetElem()); numElems > 0 { keysInPath = p.GetElem()[numElems-1].GetKey() } - // make sure all keys exist either in the JSON value or - // in the path but NOT in both and build keySet keySet := map[string]string{} for _, k := range cs.Container.GetKeys() { - if v, ok := jv[k.Name]; ok { - if _, ok := keysInPath[k.Name]; ok { - return nil, fmt.Errorf("key %q is present in both the path and JSON value", k.Name) - } - // in case of json_ietf we need to cut the module prefix - if k.Type.Type == "identityref" { - found := false - var val string - _, val, found = strings.Cut(fmt.Sprintf("%v", v), ":") - if found { - v = val - } - } - keySet[k.Name] = fmt.Sprintf("%v", v) - continue - } - if v, ok := keysInPath[k.Name]; ok { - // identityref key values arriving via the gNMI path (rather - // than nested in the JSON-IETF value) can also carry a - // module prefix (e.g. "srl_nokia-common:ipv4-unicast"). - // Strip it the same way the JSON-value branch above does, - // so a list entry keyed by an identityref resolves to the - // same tree node regardless of whether the key arrived via - // the path or the JSON body — otherwise sync-derived and - // intent-derived entries for the same key silently diverge - // into two sibling nodes. - if k.Type.Type == "identityref" { - if _, val, found := strings.Cut(v, ":"); found { - v = val - } - } - keySet[k.Name] = v - continue + val, err := resolveListKey(k, jv, keysInPath, cs.Container.GetName()) + if err != nil { + return nil, err } - return nil, fmt.Errorf("missing key %s in element %s", k.Name, cs.Container.GetName()) - } - // Write the (possibly module-prefix-stripped) keySet back onto the - // path's last element unconditionally — regardless of whether any - // individual key came from the JSON value or was already present in - // the path — so identityref stripping above always takes effect and - // every key ends up normalized in one place. All "present in both"/ - // "missing" validation already happened while building keySet above. - if len(cs.Container.GetKeys()) > 0 { + keySet[k.Name] = val + } + // Normalized keys overwrite the last path element so stripped prefixes apply uniformly. + if len(cs.Container.GetKeys()) > 0 && len(p.GetElem()) > 0 { p.GetElem()[len(p.GetElem())-1].Key = keySet } for k, v := range jv { @@ -298,6 +249,9 @@ func (c *Converter) ExpandContainerValue(ctx context.Context, p *sdcpb.Path, jv if !ok { return nil, fmt.Errorf("unknown object %q under container %q", k, cs.Container.Name) } + if v == nil { + continue + } switch item := item.(type) { case *sdcpb.LeafSchema: // field // log.Debugf("handling field %s", item.Name) @@ -353,6 +307,9 @@ func (c *Converter) ExpandContainerValue(ctx context.Context, p *sdcpb.Path, jv switch x := v.(type) { case []any: for _, e := range x { + if e == nil { + continue + } tvYangType, err := sdcpb.SchemaElemToTV(se, fmt.Sprintf("%v", e), 0) if err != nil { return nil, err @@ -360,7 +317,7 @@ func (c *Converter) ExpandContainerValue(ctx context.Context, p *sdcpb.Path, jv list = append(list, tvYangType) } default: - return nil, fmt.Errorf("leaflist %s expects array as input, but %v of type %v was given", np.String(), x, reflect.TypeOf(x).Name()) + return nil, fmt.Errorf("leaflist %s expects array as input, but %v of type %T was given", np.String(), x, x) } upd := &sdcpb.Update{ @@ -386,24 +343,20 @@ func (c *Converter) ExpandContainerValue(ctx context.Context, p *sdcpb.Path, jv } switch rsp := rsp.GetSchema().Schema.(type) { case *sdcpb.SchemaElem_Container: - var rs []*sdcpb.Update - // code for presence containers - m, ok := v.(map[string]any) - if ok && len(m) == 0 && rsp.Container.IsPresence { - rs = []*sdcpb.Update{ - { + rs, err := c.ExpandContainerValue(ctx, np, v, rsp) + if err != nil { + return nil, err + } + if len(rs) == 0 && rsp.Container.IsPresence { + if _, ok := v.(map[string]any); ok { + rs = []*sdcpb.Update{{ Path: np, Value: &sdcpb.TypedValue{ Value: &sdcpb.TypedValue_EmptyVal{}, }, }} - } else { - rs, err = c.ExpandContainerValue(ctx, np, v, rsp) - if err != nil { - return nil, err } } - upds = append(upds, rs...) default: // should not happen @@ -426,11 +379,118 @@ func (c *Converter) ExpandContainerValue(ctx context.Context, p *sdcpb.Path, jv } return upds, nil default: - log.Error(nil, "unexpected json type cast", "type", reflect.TypeOf(jv).String()) + log.Error(nil, "unexpected json type cast", "type", fmt.Sprintf("%T", jv)) return nil, nil } } +// decodeJSONValue decodes JSON or JSON_IETF TypedValues with UseNumber enabled. +// It reports isJSON=false for non-JSON variants, and returns (nil, true, nil) +// when the JSON payload is empty, whitespace-only, or literal null. +func decodeJSONValue(tv *sdcpb.TypedValue) (any, bool, error) { + var raw []byte + switch tv.GetValue().(type) { + case *sdcpb.TypedValue_JsonVal: + raw = tv.GetJsonVal() + case *sdcpb.TypedValue_JsonIetfVal: + raw = tv.GetJsonIetfVal() + default: + return nil, false, nil + } + if len(bytes.TrimSpace(raw)) == 0 { + return nil, true, nil + } + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + var v any + if err := dec.Decode(&v); err != nil { + return nil, true, err + } + return v, true, nil +} + +// resolveListKey resolves the canonical value of list key k across jv (bare and +// module-qualified names, ignoring JSON null) and keysInPath. It strips module +// prefixes on identityref keys and errors when k is missing or values disagree. +func resolveListKey(k *sdcpb.LeafSchema, jv map[string]any, keysInPath map[string]string, containerName string) (string, error) { + idRefType := resolveIdentityRefType(k.GetType()) + var resolved string + var explicitMod string + haveValue := false + + merge := func(raw string) error { + norm := raw + if idRefType != nil { + if mod, local, hasMod := strings.Cut(raw, ":"); hasMod { + if !validIdentityQualifier(idRefType, mod, local) { + return fmt.Errorf("invalid qualifier %q for identityref key %q", mod, k.Name) + } + if explicitMod != "" && explicitMod != mod && !sameIdentityDifferentForm(idRefType, explicitMod, mod, local) { + return fmt.Errorf("conflicting qualifiers for key %q (%q vs %q)", k.Name, explicitMod, mod) + } + explicitMod = mod + norm = local + } + } + if haveValue && norm != resolved { + return fmt.Errorf("conflicting values for key %q (%q vs %q)", k.Name, resolved, norm) + } + resolved = norm + haveValue = true + return nil + } + + if v, ok := jv[k.Name]; ok && v != nil { + if err := merge(fmt.Sprintf("%v", v)); err != nil { + return "", err + } + } + if k.ModuleName != "" { + if v, ok := jv[k.ModuleName+":"+k.Name]; ok && v != nil { + if err := merge(fmt.Sprintf("%v", v)); err != nil { + return "", err + } + } + } + if v, ok := keysInPath[k.Name]; ok { + if err := merge(v); err != nil { + return "", err + } + } + if !haveValue { + return "", fmt.Errorf("missing key %s in element %s", k.Name, containerName) + } + return resolved, nil +} + +func resolveIdentityRefType(slt *sdcpb.SchemaLeafType) *sdcpb.SchemaLeafType { + for slt != nil { + if slt.GetType() == "identityref" { + return slt + } + slt = slt.GetLeafrefTargetType() + } + return nil +} + +// validIdentityQualifier reports whether qualifier names the module or prefix +// defining identity local. Identities absent from both prefix maps accept any +// qualifier, since the schema cannot contradict it. +func validIdentityQualifier(slt *sdcpb.SchemaLeafType, qualifier, local string) bool { + mod := slt.GetModulePrefixMap()[local] + pfx := slt.GetIdentityPrefixesMap()[local] + if mod == "" && pfx == "" { + return true + } + return qualifier == mod || qualifier == pfx +} + +func sameIdentityDifferentForm(slt *sdcpb.SchemaLeafType, q1, q2, local string) bool { + mod := slt.GetModulePrefixMap()[local] + pfx := slt.GetIdentityPrefixesMap()[local] + return mod != "" && pfx != "" && ((q1 == mod && q2 == pfx) || (q1 == pfx && q2 == mod)) +} + func getItem(ctx context.Context, s string, cs *sdcpb.SchemaElem_Container, scb SchemaClientBound) (any, bool) { f, ok := getField(s, cs) if ok { diff --git a/pkg/utils/converter_test.go b/pkg/utils/converter_test.go index 90bac7bb..3352f3cc 100644 --- a/pkg/utils/converter_test.go +++ b/pkg/utils/converter_test.go @@ -20,6 +20,24 @@ func (t *testSchemaClientBound) GetSchemaElements(context.Context, *sdcpb.Path, return nil, nil } +func newMapSchemaConverter(schemaMap map[string]*sdcpb.GetSchemaResponse) *Converter { + return NewConverter(&testSchemaClientBound{ + getSchemaPathFn: func(_ context.Context, path *sdcpb.Path) (*sdcpb.GetSchemaResponse, error) { + key := "" + for i, pe := range path.GetElem() { + if i > 0 { + key += "/" + } + key += pe.GetName() + } + if rsp, ok := schemaMap[key]; ok { + return rsp, nil + } + return &sdcpb.GetSchemaResponse{Schema: &sdcpb.SchemaElem{}}, nil + }, + }) +} + func TestExpandUpdateFieldJSONStringNormalizesQuotes(t *testing.T) { converter := NewConverter(&testSchemaClientBound{ getSchemaPathFn: func(context.Context, *sdcpb.Path) (*sdcpb.GetSchemaResponse, error) { @@ -305,3 +323,684 @@ func TestExpandUpdateFieldJSONUint64PreservesPrecision(t *testing.T) { t.Fatalf("expected max uint64 %d, got %d", ^uint64(0), got) } } + +func TestExpandUpdateContainerJSONNullReturnsEmpty(t *testing.T) { + converter := NewConverter(&testSchemaClientBound{ + getSchemaPathFn: func(context.Context, *sdcpb.Path) (*sdcpb.GetSchemaResponse, error) { + return &sdcpb.GetSchemaResponse{ + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{ + Name: "LbRtdIf-list", + Keys: []*sdcpb.LeafSchema{{Name: "id", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}}, + Fields: []*sdcpb.LeafSchema{{Name: "descr", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}}, + }, + }, + }, + }, nil + }, + }) + + for _, tc := range []struct { + name string + val *sdcpb.TypedValue + }{ + { + name: "json_val", + val: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonVal{JsonVal: []byte("null")}}, + }, + { + name: "json_ietf_val", + val: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: []byte("null")}}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + updates, err := converter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + {Name: "LbRtdIf-list", Key: map[string]string{"id": "lo99"}}, + }}, + Value: tc.val, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error: %v", err) + } + if len(updates) != 0 { + t.Fatalf("expected 0 updates, got %d: %v", len(updates), updates) + } + }) + } +} + +func TestExpandUpdateFieldAndNestedMembersJSONNullSkipped(t *testing.T) { + t.Run("field_leaf_types", func(t *testing.T) { + for _, leafType := range []string{"string", "uint32", "boolean", "decimal64", "enumeration", "empty"} { + t.Run(leafType, func(t *testing.T) { + converter := NewConverter(&testSchemaClientBound{ + getSchemaPathFn: func(context.Context, *sdcpb.Path) (*sdcpb.GetSchemaResponse, error) { + return &sdcpb.GetSchemaResponse{ + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{ + Name: "leaf", + Type: &sdcpb.SchemaLeafType{Type: leafType, TypeName: leafType}, + }, + }, + }, + }, nil + }, + }) + + for _, tv := range []*sdcpb.TypedValue{ + {Value: &sdcpb.TypedValue_JsonVal{JsonVal: []byte("null")}}, + {Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: []byte("null")}}, + } { + updates, err := converter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "root"}, {Name: "leaf"}}}, + Value: tv, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error for %s: %v", leafType, err) + } + if len(updates) != 0 { + t.Fatalf("expected 0 updates for null %s, got %d: %v", leafType, len(updates), updates) + } + } + }) + } + }) + + t.Run("field_empty_array_null_preserved", func(t *testing.T) { + converter := NewConverter(&testSchemaClientBound{ + getSchemaPathFn: func(context.Context, *sdcpb.Path) (*sdcpb.GetSchemaResponse, error) { + return &sdcpb.GetSchemaResponse{ + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{ + Name: "empty-leaf", + Type: &sdcpb.SchemaLeafType{Type: "empty", TypeName: "empty"}, + }, + }, + }, + }, nil + }, + }) + + updates, err := converter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "root"}, {Name: "empty-leaf"}}}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: []byte("[null]")}}, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error: %v", err) + } + if len(updates) != 1 || updates[0].GetValue().GetEmptyVal() == nil { + t.Fatalf("expected 1 EmptyVal update for [null], got %v", updates) + } + }) + + t.Run("nested_null_members_in_container", func(t *testing.T) { + schemaMap := map[string]*sdcpb.GetSchemaResponse{ + "iface": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{ + Name: "iface", + Fields: []*sdcpb.LeafSchema{ + {Name: "admin-state", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + {Name: "descr", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + {Name: "flag", Type: &sdcpb.SchemaLeafType{Type: "empty", TypeName: "empty"}}, + }, + Leaflists: []*sdcpb.LeafListSchema{ + {Name: "tags", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + Children: []string{"sub", "present-sub"}, + }, + }, + }, + }, + "iface/admin-state": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{Name: "admin-state", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, + "iface/descr": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{Name: "descr", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, + "iface/flag": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{Name: "flag", Type: &sdcpb.SchemaLeafType{Type: "empty", TypeName: "empty"}}, + }, + }, + }, + "iface/tags": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Leaflist{ + Leaflist: &sdcpb.LeafListSchema{Name: "tags", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, + "iface/sub": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{ + Name: "sub", + IsPresence: true, + Fields: []*sdcpb.LeafSchema{ + {Name: "descr", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, + }, + }, + "iface/sub/descr": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{Name: "descr", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, + "iface/present-sub": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{ + Name: "present-sub", + IsPresence: true, + Fields: []*sdcpb.LeafSchema{ + {Name: "descr", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, + }, + }, + "iface/present-sub/descr": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{Name: "descr", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, + } + + converter := newMapSchemaConverter(schemaMap) + + updates, err := converter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "iface"}}}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonVal{ + JsonVal: []byte(`{"admin-state":"up","descr":null,"flag":null,"tags":null,"sub":null,"present-sub":{"descr":null}}`), + }, + }, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error: %v", err) + } + if len(updates) != 2 { + t.Fatalf("expected 2 updates (admin-state and present-sub EmptyVal), got %d: %v", len(updates), updates) + } + gotByLeaf := map[string]*sdcpb.TypedValue{} + for _, u := range updates { + elems := u.GetPath().GetElem() + gotByLeaf[elems[len(elems)-1].GetName()] = u.GetValue() + } + if gotByLeaf["admin-state"].GetStringVal() != "up" { + t.Fatalf("expected admin-state %q, got %v", "up", gotByLeaf["admin-state"]) + } + if _, ok := gotByLeaf["present-sub"].GetValue().(*sdcpb.TypedValue_EmptyVal); !ok { + t.Fatalf("expected EmptyVal for presence container with null child leaf, got %v", gotByLeaf["present-sub"]) + } + }) + + t.Run("null_leaflist_elements_skipped", func(t *testing.T) { + tagsSchema := &sdcpb.LeafListSchema{Name: "tags", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}} + converter := newMapSchemaConverter(map[string]*sdcpb.GetSchemaResponse{ + "iface": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{Name: "iface", Leaflists: []*sdcpb.LeafListSchema{tagsSchema}}, + }, + }, + }, + "iface/tags": { + Schema: &sdcpb.SchemaElem{Schema: &sdcpb.SchemaElem_Leaflist{Leaflist: tagsSchema}}, + }, + }) + + updates, err := converter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "iface"}}}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonVal{JsonVal: []byte(`{"tags":["a",null,"b"]}`)}}, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error: %v", err) + } + if len(updates) != 1 { + t.Fatalf("expected 1 leaf-list update, got %d: %v", len(updates), updates) + } + var got []string + for _, e := range updates[0].GetValue().GetLeaflistVal().GetElement() { + got = append(got, e.GetStringVal()) + } + if len(got) != 2 || got[0] != "a" || got[1] != "b" { + t.Fatalf("expected leaf-list [a b], got %v", got) + } + }) +} + +func TestExpandUpdateLeaflistNullOrEmptyJSONReturnsEmpty(t *testing.T) { + converter := NewConverter(&testSchemaClientBound{ + getSchemaPathFn: func(context.Context, *sdcpb.Path) (*sdcpb.GetSchemaResponse, error) { + return &sdcpb.GetSchemaResponse{ + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Leaflist{ + Leaflist: &sdcpb.LeafListSchema{Name: "tags", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, nil + }, + }) + + for _, pl := range []struct { + name string + raw []byte + }{ + {name: "nil_bytes", raw: nil}, + {name: "empty_bytes", raw: []byte{}}, + {name: "whitespace_only", raw: []byte(" \t\r\n ")}, + {name: "null", raw: []byte("null")}, + } { + for _, enc := range []struct { + name string + tv *sdcpb.TypedValue + }{ + {name: "json_val", tv: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonVal{JsonVal: pl.raw}}}, + {name: "json_ietf_val", tv: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: pl.raw}}}, + } { + t.Run(pl.name+"/"+enc.name, func(t *testing.T) { + updates, err := converter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "iface"}, {Name: "tags"}}}, + Value: enc.tv, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error: %v", err) + } + if len(updates) != 0 { + t.Fatalf("expected 0 updates, got %d: %v", len(updates), updates) + } + }) + } + } +} + +func TestExpandUpdateEmptyOrWhitespaceJSONReturnsEmpty(t *testing.T) { + containerSchema := &sdcpb.GetSchemaResponse{ + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{ + Name: "ntpq-items", + Fields: []*sdcpb.LeafSchema{{Name: "adminSt", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}}, + }, + }, + }, + } + fieldSchema := &sdcpb.GetSchemaResponse{ + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{ + Name: "adminSt", + Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}, + }, + }, + }, + } + + converter := NewConverter(&testSchemaClientBound{ + getSchemaPathFn: func(_ context.Context, path *sdcpb.Path) (*sdcpb.GetSchemaResponse, error) { + elems := path.GetElem() + if len(elems) == 2 { + return fieldSchema, nil + } + return containerSchema, nil + }, + }) + + payloads := []struct { + name string + raw []byte + }{ + {name: "nil_bytes", raw: nil}, + {name: "empty_bytes", raw: []byte{}}, + {name: "whitespace_only", raw: []byte(" \t\r\n ")}, + } + + paths := []struct { + name string + path *sdcpb.Path + }{ + {name: "container", path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "ntpq-items"}}}}, + {name: "field", path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "ntpq-items"}, {Name: "adminSt"}}}}, + } + + for _, p := range paths { + for _, pl := range payloads { + for _, enc := range []struct { + name string + tv *sdcpb.TypedValue + }{ + {name: "json_val", tv: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonVal{JsonVal: pl.raw}}}, + {name: "json_ietf_val", tv: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: pl.raw}}}, + } { + t.Run(p.name+"/"+pl.name+"/"+enc.name, func(t *testing.T) { + updates, err := converter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: p.path, + Value: enc.tv, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error: %v", err) + } + if len(updates) != 0 { + t.Fatalf("expected 0 updates, got %d: %v", len(updates), updates) + } + }) + } + } + } +} + +func TestExpandContainerValueDuplicateKeyInPathAndJSON(t *testing.T) { + lbSchemaMap := map[string]*sdcpb.GetSchemaResponse{ + "LbRtdIf-list": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{ + Name: "LbRtdIf-list", + ModuleName: "Cisco-NX-OS-device", + Keys: []*sdcpb.LeafSchema{ + {Name: "id", ModuleName: "Cisco-NX-OS-device", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + Fields: []*sdcpb.LeafSchema{ + {Name: "adminSt", ModuleName: "Cisco-NX-OS-device", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, + }, + }, + "LbRtdIf-list/id": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{ + Name: "id", + Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}, + }, + }, + }, + }, + "LbRtdIf-list/adminSt": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{ + Name: "adminSt", + Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}, + }, + }, + }, + }, + } + + lbConverter := newMapSchemaConverter(lbSchemaMap) + + t.Run("matching_key_in_single_element_array", func(t *testing.T) { + updates, err := lbConverter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + {Name: "LbRtdIf-list", Key: map[string]string{"id": "lo99"}}, + }}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonVal{ + JsonVal: []byte(`[{"id":"lo99","adminSt":"up"}]`), + }, + }, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error: %v", err) + } + if len(updates) != 2 { + t.Fatalf("expected 2 updates (id and adminSt), got %d: %v", len(updates), updates) + } + got := map[string]string{} + for _, u := range updates { + elems := u.GetPath().GetElem() + if elems[0].GetKey()["id"] != "lo99" { + t.Fatalf("expected key id=lo99 on path, got %v", elems[0].GetKey()) + } + got[elems[len(elems)-1].GetName()] = u.GetValue().GetStringVal() + } + if got["id"] != "lo99" || got["adminSt"] != "up" { + t.Fatalf("unexpected leaf values: %v", got) + } + }) + + t.Run("matching_key_in_object", func(t *testing.T) { + updates, err := lbConverter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + {Name: "LbRtdIf-list", Key: map[string]string{"id": "lo99"}}, + }}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonVal{ + JsonVal: []byte(`{"id":"lo99","adminSt":"up"}`), + }, + }, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error: %v", err) + } + if len(updates) != 2 { + t.Fatalf("expected 2 updates, got %d: %v", len(updates), updates) + } + }) + + t.Run("conflicting_key_in_path_and_json_errors", func(t *testing.T) { + _, err := lbConverter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + {Name: "LbRtdIf-list", Key: map[string]string{"id": "lo99"}}, + }}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonVal{ + JsonVal: []byte(`[{"id":"lo100","adminSt":"up"}]`), + }, + }, + }) + if err == nil { + t.Fatal("expected error for conflicting key between path and JSON value, got nil") + } + }) + + t.Run("matching_identityref_key_with_module_prefixes", func(t *testing.T) { + idRefType := &sdcpb.SchemaLeafType{ + Type: "identityref", + TypeName: "afi-safi-type", + IdentityPrefixesMap: map[string]string{"ipv4-unicast": "srl_nokia-common", "ipv6-unicast": "srl_nokia-common"}, + ModulePrefixMap: map[string]string{"ipv4-unicast": "srl_nokia-common", "ipv6-unicast": "srl_nokia-common"}, + } + afiSchemaMap := map[string]*sdcpb.GetSchemaResponse{ + "afi-safi": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{ + Name: "afi-safi", + ModuleName: "srl_nokia-bgp", + Keys: []*sdcpb.LeafSchema{ + { + Name: "afi-safi-name", + ModuleName: "srl_nokia-bgp", + Type: &sdcpb.SchemaLeafType{Type: "leafref", LeafrefTargetType: idRefType}, + }, + }, + Fields: []*sdcpb.LeafSchema{ + {Name: "admin-state", ModuleName: "srl_nokia-bgp", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}, + }, + }, + }, + }, + }, + "afi-safi/afi-safi-name": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{ + Name: "afi-safi-name", + Type: &sdcpb.SchemaLeafType{Type: "leafref", LeafrefTargetType: idRefType}, + }, + }, + }, + }, + "afi-safi/admin-state": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{ + Name: "admin-state", + Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}, + }, + }, + }, + }, + } + + afiConverter := newMapSchemaConverter(afiSchemaMap) + + updates, err := afiConverter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + {Name: "afi-safi", Key: map[string]string{"afi-safi-name": "srl_nokia-common:ipv4-unicast"}}, + }}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonIetfVal{ + JsonIetfVal: []byte(`{"srl_nokia-bgp:afi-safi-name":"ipv4-unicast","admin-state":"enable"}`), + }, + }, + }) + if err != nil { + t.Fatalf("ExpandUpdate returned error: %v", err) + } + if len(updates) != 2 { + t.Fatalf("expected 2 updates, got %d: %v", len(updates), updates) + } + for _, u := range updates { + if gotKey := u.GetPath().GetElem()[0].GetKey()["afi-safi-name"]; gotKey != "ipv4-unicast" { + t.Fatalf("expected normalized key ipv4-unicast, got %q", gotKey) + } + } + + _, err = afiConverter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + {Name: "afi-safi", Key: map[string]string{"afi-safi-name": "srl_nokia-common:ipv4-unicast"}}, + }}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonIetfVal{ + JsonIetfVal: []byte(`{"afi-safi-name":"srl_nokia-common:ipv6-unicast","admin-state":"enable"}`), + }, + }, + }) + if err == nil { + t.Fatal("expected error for conflicting identityref key between path and JSON value, got nil") + } + + _, err = afiConverter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + {Name: "afi-safi", Key: map[string]string{"afi-safi-name": "srl_nokia-common:ipv4-unicast"}}, + }}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonIetfVal{ + JsonIetfVal: []byte(`{"afi-safi-name":"other-mod:ipv4-unicast","admin-state":"enable"}`), + }, + }, + }) + if err == nil { + t.Fatal("expected error for conflicting explicit module prefixes on identityref key, got nil") + } + + updates, err = afiConverter.ExpandUpdate(context.Background(), &sdcpb.Update{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + {Name: "afi-safi", Key: map[string]string{"afi-safi-name": "other-mod:l2vpn-evpn"}}, + }}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: []byte(`{"admin-state":"enable"}`)}, + }, + }) + if err != nil { + t.Fatalf("expected qualifier of identity absent from prefix maps to be stripped, got error: %v", err) + } + for _, u := range updates { + if gotKey := u.GetPath().GetElem()[0].GetKey()["afi-safi-name"]; gotKey != "l2vpn-evpn" { + t.Fatalf("expected normalized key l2vpn-evpn, got %q", gotKey) + } + } + }) +} + +func TestExpandUpdatesBatchPreservesSiblingsAroundNullAndEmpty(t *testing.T) { + converter := newMapSchemaConverter(map[string]*sdcpb.GetSchemaResponse{ + "empty-cont": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{Name: "empty-cont"}, + }, + }, + }, + "missing-entry": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{ + Name: "missing-entry", + Keys: []*sdcpb.LeafSchema{{Name: "id", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}}, + }, + }, + }, + }, + "live-cont": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Container{ + Container: &sdcpb.ContainerSchema{ + Name: "live-cont", + Fields: []*sdcpb.LeafSchema{{Name: "hostname", Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}}}, + }, + }, + }, + }, + "live-cont/hostname": { + Schema: &sdcpb.SchemaElem{ + Schema: &sdcpb.SchemaElem_Field{ + Field: &sdcpb.LeafSchema{ + Name: "hostname", + Type: &sdcpb.SchemaLeafType{Type: "string", TypeName: "string"}, + }, + }, + }, + }, + }) + + updates, err := converter.ExpandUpdates(context.Background(), []*sdcpb.Update{ + { + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "empty-cont"}}}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonVal{JsonVal: []byte("")}}, + }, + { + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "missing-entry", Key: map[string]string{"id": "lo99"}}}}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonVal{JsonVal: []byte("null")}}, + }, + { + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{{Name: "live-cont"}}}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonVal{JsonVal: []byte(`{"hostname":"n9k-leaf1"}`)}}, + }, + }) + if err != nil { + t.Fatalf("ExpandUpdates returned error: %v", err) + } + if len(updates) != 1 { + t.Fatalf("expected 1 update from live-cont, got %d: %v", len(updates), updates) + } + if got := updates[0].GetValue().GetStringVal(); got != "n9k-leaf1" { + t.Fatalf("expected hostname %q, got %q", "n9k-leaf1", got) + } +}