aboutsummaryrefslogtreecommitdiffstats
path: root/library/go/yandex/tvm/roles_parser.go
blob: 0c74698efe85a54eaa44099a9fdd9899deea06e2 (plain) (blame)
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
package tvm

import (
	"encoding/json"
	"strconv"
	"time"

	"github.com/ydb-platform/ydb/library/go/core/xerrors"
)

type rawRoles struct {
	Revision string       `json:"revision"`
	BornDate int64        `json:"born_date"`
	Tvm      rawConsumers `json:"tvm"`
	User     rawConsumers `json:"user"`
}

type rawConsumers = map[string]rawConsumerRoles
type rawConsumerRoles = map[string][]Entity

func NewRoles(buf []byte) (*Roles, error) {
	return NewRolesWithOpts(buf)
}

func NewRolesWithOpts(buf []byte, opts ...RoleParserOption) (*Roles, error) {
	options := newRolesParserOptions(opts...)

	var raw rawRoles
	if err := json.Unmarshal(buf, &raw); err != nil {
		return nil, xerrors.Errorf("failed to parse roles: invalid json: %w", err)
	}

	tvmRoles := map[ClientID]*ConsumerRoles{}
	for key, value := range raw.Tvm {
		id, err := strconv.ParseUint(key, 10, 32)
		if err != nil {
			return nil, xerrors.Errorf("failed to parse roles: invalid tvmid '%s': %w", key, err)
		}
		tvmRoles[ClientID(id)] = buildConsumerRoles(value, options)
	}

	userRoles := map[UID]*ConsumerRoles{}
	for key, value := range raw.User {
		id, err := strconv.ParseUint(key, 10, 64)
		if err != nil {
			return nil, xerrors.Errorf("failed to parse roles: invalid UID '%s': %w", key, err)
		}
		userRoles[UID(id)] = buildConsumerRoles(value, options)
	}

	return &Roles{
		tvmRoles:  tvmRoles,
		userRoles: userRoles,
		raw:       buf,
		meta: Meta{
			Revision: raw.Revision,
			BornTime: time.Unix(raw.BornDate, 0),
			Applied:  time.Now(),
		},
	}, nil
}

func buildConsumerRoles(rawConsumerRoles rawConsumerRoles, opts *rolesParserOptions) *ConsumerRoles {
	roles := &ConsumerRoles{
		roles: make(EntitiesByRoles, len(rawConsumerRoles)),
	}

	for r, ents := range rawConsumerRoles {
		if opts.UseLightIndex {
			roles.roles[r] = buildLightEntities(ents)
		} else {
			roles.roles[r] = buildEntities(ents)
		}
	}

	return roles
}