File: ops.go

package info (click to toggle)
golang-github-mendersoftware-go-lib-micro 0.0~git20211108.4e20429%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, experimental, forky, sid, trixie
  • size: 656 kB
  • sloc: makefile: 5
file content (147 lines) | stat: -rw-r--r-- 3,900 bytes parent folder | download
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
// Copyright 2020 Northern.tech AS
//
//    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 doc

import (
	"fmt"
	"reflect"
	"sort"

	"go.mongodb.org/mongo-driver/bson"
)

const (
	// PermutationThreshold limits the complexity of Unwound maps to the
	// given array length.
	PermutationThreshold = 1024
)

var (
	// ErrPermutations is returned if the map contains arrays with a combined
	// number of permutations than the threshold.
	ErrPermutations = fmt.Errorf(
		"object complexity (array permutations) exceeded threshold")
)

// item is an internally used struct to organize the output in UnwindMap
type item struct {
	Key   string
	Value reflect.Value
}

// UnwindMap takes a string map and perform mongodb $unwind aggregation operation
// on all array entries.
// Don't return a map - but a sorted list of tuples; mongo indices are sensitive
// to order.
// Example:
//   {"foo": ["1", "2"], "bar": "3"} becomes
//   [ {{"foo", "1", "bar", "3"}}, {{"foo": "2", "bar": "3"}} ]
func UnwindMap(
	in interface{},
) ([]bson.D, error) {
	// returned bloated map
	var unwoundMap []bson.D
	// permutations and cumulative sum of permutations
	var permutations int64 = 1

	inVal := reflect.ValueOf(in)
	if inVal.Kind() != reflect.Map {
		return nil, fmt.Errorf(
			"invalid argument type: %s != map[string]interface{}",
			inVal.Kind().String())
	}
	mapLen := inVal.Len()
	orderedMap := make([]item, mapLen)

	// Compute number of permutations and initialize ordered map.
	var i int
	keys := inVal.MapKeys()
	for _, key := range keys {
		var keyStr string
		var ok bool
		value := inVal.MapIndex(key)
		if key.Kind() == reflect.Interface {
			key = key.Elem()
		}
		if value.Kind() == reflect.Interface {
			value = value.Elem()
		}
		if keyStr, ok = key.Interface().(string); !ok {
			return nil, fmt.Errorf("invalid argument type: "+
				"%s != map[string]interface{}", inVal.Kind())
		}

		switch value.Kind() {
		case reflect.Slice, reflect.Array:
			orderedMap[i] = item{
				Key: keyStr,
			}
			prevPermutations := permutations
			permutations = permutations * int64(value.Len())

			// Check with constraint or overflow
			if permutations > PermutationThreshold ||
				permutations < prevPermutations {
				return nil, ErrPermutations
			}

		case reflect.String:
			orderedMap[i] = item{
				Key: keyStr,
			}
		default:
			return nil, fmt.Errorf(
				"cannot unwind entry %s of type: %s",
				key, value.Kind().String())
		}
		orderedMap[i].Value = value
		i++
	}

	sort.Slice(orderedMap, func(i, j int) bool {
		return orderedMap[i].Key < orderedMap[j].Key
	})

	// Allocate returned map array
	unwoundMap = make([]bson.D, permutations)

	// Fill in the map entries
	for k := int64(0); k < permutations; k++ {
		var tmpPerm int64 = 1
		unwoundMap[k] = make(bson.D, mapLen)
		for i, item := range orderedMap {
			unwoundMap[k][i].Key = item.Key
			itemKind := item.Value.Kind()
			if itemKind == reflect.Slice ||
				itemKind == reflect.Array {

				// Compute index
				// - think of it as counting using array
				//   length as base
				itemLen := item.Value.Len()
				idx := (k / tmpPerm) % int64(itemLen)

				unwoundMap[k][i].Value = item.Value.
					Index(int(idx)).Interface()

				// Update cumulative permutations
				tmpPerm *= int64(itemLen)
			} else {
				unwoundMap[k][i].Value = item.Value.Interface()
			}
		}
	}
	return unwoundMap, nil
}