-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpresence.go
More file actions
160 lines (139 loc) · 4.56 KB
/
presence.go
File metadata and controls
160 lines (139 loc) · 4.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package validation
import (
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
)
// PresenceMap tracks which fields are present in the request body.
// Keys are normalized dot paths (e.g., "items.2.price"), values are always true.
//
// PresenceMap is used for partial update validation (PATCH requests),
// where only present fields should be validated, while absent fields
// should be ignored even if they have "required" constraints.
//
// Use [ComputePresence] to create a PresenceMap from raw JSON,
// and [WithPresence] to pass it to validation.
type PresenceMap map[string]bool
// Has returns true if the exact path is present.
func (pm PresenceMap) Has(path string) bool {
return pm != nil && pm[path]
}
// HasPrefix returns true if any path with the given prefix is present.
// HasPrefix is useful for checking if a nested object or array element is present.
func (pm PresenceMap) HasPrefix(prefix string) bool {
if pm == nil {
return false
}
prefixDot := prefix + "."
for path := range pm {
if path == prefix || strings.HasPrefix(path, prefixDot) {
return true
}
}
return false
}
// LeafPaths returns paths that aren't prefixes of others.
// LeafPaths is useful for partial validation where only leaf fields that were actually provided
// should be validated, not their parent objects.
//
// Example:
// - If presence contains "address" and "address.city", only "address.city" is a leaf.
// - If presence contains "items.0" and "items.0.name", only "items.0.name" is a leaf.
func (pm PresenceMap) LeafPaths() []string {
if pm == nil {
return nil
}
paths := make([]string, 0, len(pm))
for p := range pm {
paths = append(paths, p)
}
// Sort to process in order
sort.Strings(paths)
// Use single-pass algorithm: if next path has current as prefix, current is not a leaf
isLeaf := make([]bool, 0, len(paths))
for range paths {
isLeaf = append(isLeaf, true)
}
for i := range len(paths) - 1 {
// If next path has current as prefix, current is not a leaf
if strings.HasPrefix(paths[i+1], paths[i]+".") {
isLeaf[i] = false
}
}
leaves := make([]string, 0, len(paths))
for i, leaf := range isLeaf {
if leaf {
leaves = append(leaves, paths[i])
}
}
return leaves
}
// ComputePresence analyzes raw JSON and returns a [PresenceMap] of present field paths.
// It enables partial validation where only provided fields are validated.
//
// It returns an empty map (not nil) if rawJSON is empty.
// It has a maximum recursion depth of 100 to prevent stack overflow
// from deeply nested JSON structures.
//
// Example:
//
// rawJSON := []byte(`{"user": {"name": "Alice", "age": 0}}`)
// presence, err := ComputePresence(rawJSON)
// // Returns: {"user": true, "user.name": true, "user.age": true}
//
// Errors:
// - Returns error if rawJSON is not valid JSON
func ComputePresence(rawJSON []byte) (PresenceMap, error) {
if len(rawJSON) == 0 {
return make(PresenceMap), nil
}
var data map[string]any
if err := json.Unmarshal(rawJSON, &data); err != nil {
return nil, fmt.Errorf("failed to parse JSON for presence tracking: %w", err)
}
pm := make(PresenceMap)
markPresence(data, "", pm, 0)
return pm, nil
}
// markPresence recursively marks fields as present in the [PresenceMap].
// The depth parameter tracks recursion depth to prevent stack overflow (max: maxRecursionDepth).
func markPresence(m map[string]any, prefix string, pm PresenceMap, depth int) {
if depth > maxRecursionDepth {
return // Prevent stack overflow from deeply nested structures
}
for k, v := range m {
//nolint:copyloopvar // path is modified conditionally
path := k
if prefix != "" {
path = prefix + "." + k
}
pm[path] = true
if nested, ok := v.(map[string]any); ok {
markPresence(nested, path, pm, depth+1)
}
if arr, arrOk := v.([]any); arrOk {
for i, item := range arr {
itemPath := path + "." + strconv.Itoa(i)
pm[itemPath] = true
if nestedMap, nestedMapOk := item.(map[string]any); nestedMapOk {
markPresence(nestedMap, itemPath, pm, depth+1)
}
}
}
}
}