-
Notifications
You must be signed in to change notification settings - Fork 0
/
synthetic_devices.go
203 lines (171 loc) · 6.09 KB
/
synthetic_devices.go
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Package synthetic contains the repository for synthetic devices.
package synthetic
import (
"context"
"fmt"
"slices"
"strings"
gmodel "github.com/DIMO-Network/identity-api/graph/model"
"github.com/DIMO-Network/identity-api/internal/helpers"
"github.com/DIMO-Network/identity-api/internal/repositories/base"
"github.com/DIMO-Network/identity-api/models"
"github.com/DIMO-Network/mnemonic"
"github.com/ethereum/go-ethereum/common"
"github.com/vektah/gqlparser/v2/gqlerror"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
)
// TokenPrefix is the prefix for a global token id for synthetic devices.
const TokenPrefix = "S"
var vehicleJoin = fmt.Sprintf("%s ON %s = %s", helpers.WithSchema(models.TableNames.Vehicles), models.VehicleTableColumns.ID, models.SyntheticDeviceTableColumns.VehicleID)
// Repository is the repository for synthetic devices.
type Repository struct {
*base.Repository
}
// ToAPI converts a synthetic device from the database to a GraphQL API model.
func ToAPI(sd *models.SyntheticDevice) (*gmodel.SyntheticDevice, error) {
globalID, err := base.EncodeGlobalTokenID(TokenPrefix, sd.ID)
if err != nil {
return nil, fmt.Errorf("failed to encode synthetic device primary key: %w", err)
}
nameList := mnemonic.FromInt32WithObfuscation(int32(sd.ID))
name := strings.Join(nameList, " ")
return &gmodel.SyntheticDevice{
ID: globalID,
Name: name,
TokenID: sd.ID,
IntegrationID: sd.IntegrationID,
Address: common.BytesToAddress(sd.DeviceAddress),
MintedAt: sd.MintedAt,
}, nil
}
// GetSyntheticDevice Device retrieves a synthetic device by either its address or tokenID from the database.
func (r *Repository) GetSyntheticDevice(ctx context.Context, by gmodel.SyntheticDeviceBy) (*gmodel.SyntheticDevice, error) {
if base.CountTrue(by.Address != nil, by.TokenID != nil) != 1 {
return nil, gqlerror.Errorf("Pass in exactly one of `address` or `id`.")
}
var mod qm.QueryMod
switch {
case by.Address != nil:
mod = models.SyntheticDeviceWhere.DeviceAddress.EQ(by.Address.Bytes())
case by.TokenID != nil:
mod = models.SyntheticDeviceWhere.ID.EQ(*by.TokenID)
}
synth, err := models.SyntheticDevices(mod).One(ctx, r.PDB.DBS().Reader)
if err != nil {
r.Log.Error().Err(err).Msg("failed to get query device")
return nil, base.InternalError
}
return ToAPI(synth)
}
// GetSyntheticDevices retrieves a list of synthetic devices from the database.
func (r *Repository) GetSyntheticDevices(ctx context.Context, first *int, last *int, after *string, before *string, filterBy *gmodel.SyntheticDevicesFilter) (*gmodel.SyntheticDeviceConnection, error) {
limit, err := helpers.ValidateFirstLast(first, last, base.MaxPageSize)
if err != nil {
return nil, fmt.Errorf("invalid first/last argument: %w", err)
}
var totalCount int64
queryMods := queryModsFromFilters(filterBy)
totalCount, err = models.SyntheticDevices(queryMods...).Count(ctx, r.PDB.DBS().Reader)
if err != nil {
r.Log.Err(err).Msg("failed to get synthetic device count")
return nil, base.InternalError
}
if after != nil {
afterID, err := helpers.CursorToID(*after)
if err != nil {
return nil, fmt.Errorf("invalid after cursor: %w", err)
}
queryMods = append(queryMods, models.SyntheticDeviceWhere.ID.LT(afterID))
}
if before != nil {
beforeID, err := helpers.CursorToID(*before)
if err != nil {
return nil, fmt.Errorf("invalid before cursor: %w", err)
}
queryMods = append(queryMods, models.SyntheticDeviceWhere.ID.GT(beforeID))
}
orderBy := "DESC"
if last != nil {
orderBy = "ASC"
}
queryMods = append(queryMods,
// Use limit + 1 here to check if there's another page.
qm.Limit(limit+1),
qm.OrderBy(models.SyntheticDeviceColumns.ID+" "+orderBy),
)
all, err := models.SyntheticDevices(queryMods...).All(ctx, r.PDB.DBS().Reader)
if err != nil {
r.Log.Err(err).Msg("failed to get synthetic devices")
return nil, base.InternalError
}
// We assume that cursors come from real elements.
hasNext := before != nil
hasPrevious := after != nil
if first != nil && len(all) == limit+1 {
hasNext = true
all = all[:limit]
} else if last != nil && len(all) == limit+1 {
hasPrevious = true
all = all[:limit]
}
// reverse the order if we're using last so tokenID is in descending order
if last != nil {
slices.Reverse(all)
}
return createSyntheticDevicesResponse(totalCount, all, hasNext, hasPrevious)
}
func queryModsFromFilters(filterBy *gmodel.SyntheticDevicesFilter) []qm.QueryMod {
if filterBy == nil {
return nil
}
var where []qm.QueryMod
if filterBy.IntegrationID != nil {
where = append(where, models.SyntheticDeviceWhere.IntegrationID.EQ(*filterBy.IntegrationID))
}
if filterBy.Owner != nil {
// join with the SyntheticDevice table to get the owner
vehicleJoin := qm.InnerJoin(vehicleJoin)
ownerWhere := models.VehicleWhere.OwnerAddress.EQ(filterBy.Owner.Bytes())
where = append(where, vehicleJoin, ownerWhere)
}
return where
}
func createSyntheticDevicesResponse(totalCount int64, syntheticDevices models.SyntheticDeviceSlice, hasNext bool, hasPrevious bool) (*gmodel.SyntheticDeviceConnection, error) {
var errList gqlerror.List
var endCur, startCur *string
if len(syntheticDevices) != 0 {
ec := helpers.IDToCursor(syntheticDevices[len(syntheticDevices)-1].ID)
endCur = &ec
sc := helpers.IDToCursor(syntheticDevices[0].ID)
startCur = &sc
}
edges := make([]*gmodel.SyntheticDeviceEdge, len(syntheticDevices))
nodes := make([]*gmodel.SyntheticDevice, len(syntheticDevices))
for i, synth := range syntheticDevices {
synthAPI, err := ToAPI(synth)
if err != nil {
errList = append(errList, gqlerror.Errorf("failed to convert synthetic device to API: %v", err))
continue
}
edges[i] = &gmodel.SyntheticDeviceEdge{
Node: synthAPI,
Cursor: helpers.IDToCursor(synth.ID),
}
nodes[i] = synthAPI
}
res := &gmodel.SyntheticDeviceConnection{
Edges: edges,
Nodes: nodes,
PageInfo: &gmodel.PageInfo{
EndCursor: endCur,
HasNextPage: hasNext,
HasPreviousPage: hasPrevious,
StartCursor: startCur,
},
TotalCount: int(totalCount),
}
if errList != nil {
return res, errList
}
return res, nil
}