-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathimport.go
More file actions
382 lines (314 loc) · 11.6 KB
/
Copy pathimport.go
File metadata and controls
382 lines (314 loc) · 11.6 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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package tuple
import (
"context"
"errors"
"fmt"
"math"
"strings"
"sync"
"time"
openfga "github.com/openfga/go-sdk"
"github.com/openfga/go-sdk/client"
"github.com/rung/go-safecast"
"github.com/openfga/cli/internal/requests"
"github.com/openfga/cli/internal/utils"
)
const (
// MaxTuplesPerWrite Limit the tuples in a single batch.
MaxTuplesPerWrite = 1
// MaxParallelRequests Limit the parallel writes to the API.
MaxParallelRequests = 10
// DefaultMinRPS Default minimum requests per second.
DefaultMinRPS = 1
// DefaultMaxTuplesPerWriteWithRPS is the tuples per write when --max-rps is set but --max-tuples-per-write is omitted.
DefaultMaxTuplesPerWriteWithRPS = 40
// RPSToParallelRequestsDivisor defines how max-rps translates to max parallel requests.
RPSToParallelRequestsDivisor = 5
// RPSToRampupPeriodMultiplier defines how max-rps translates to ramp-up period.
RPSToRampupPeriodMultiplier = 2
)
type failedWriteResponse struct {
TupleKey client.ClientTupleKey `json:"tuple_key"`
Reason string `json:"reason"`
}
type ImportResponse struct {
Successful []client.ClientTupleKey `json:"successful"`
Failed []failedWriteResponse `json:"failed"`
}
func validateImportParams(minRPS, maxRPS, rampUpPeriodInSec, maxTuplesPerWrite, maxParallelRequests int,
body client.ClientWriteRequest,
) error {
if maxRPS != 0 && minRPS > maxRPS {
if minRPS <= 0 || maxRPS <= 0 || rampUpPeriodInSec < 0 {
return errors.New("ramp-up parameters must be a positive integer") //nolint:err113
}
return errors.New("minRPS must be less than or equal to maxRPS") //nolint:err113
}
if maxTuplesPerWrite < 1 {
return errors.New("maxTuplesPerWrite must be at least 1") //nolint:err113
}
if maxParallelRequests < 1 {
return errors.New("maxParallelRequests must be at least 1") //nolint:err113
}
requestsLen := len(body.Writes) + len(body.Deletes)
if requestsLen > math.MaxInt32 {
return fmt.Errorf( //nolint:err113
"too many requests in ramp up: %d. max supported is %d", requestsLen, math.MaxInt32,
)
}
return nil
}
// ImportTuplesWithoutRampUp receives a client.ClientWriteRequest and imports the tuples to the store.
// It can be used to import either writes or deletes.
// It returns a pointer to an ImportResponse and an error.
// It does not allow ramping up the requests.
// The ImportResponse contains the tuples that were successfully imported and the tuples that failed to be imported.
// Deletes and writes are put together in the same ImportResponse.
func ImportTuplesWithoutRampUp(ctx context.Context, fgaClient client.SdkClient,
maxTuplesPerWrite, maxParallelRequests int,
body client.ClientWriteRequest,
) (*ImportResponse, error) {
return ImportTuples(ctx, fgaClient, 0, 0, 0, maxTuplesPerWrite, maxParallelRequests, body)
}
// ImportTuples receives a client.ClientWriteRequest and imports the tuples to the store. It can be used to import
// either writes or deletes.
// It returns a pointer to an ImportResponse and an error.
// The ImportResponse contains the tuples that were successfully imported and the tuples that failed to be imported.
// Deletes and writes are put together in the same ImportResponse.
func ImportTuples(ctx context.Context, fgaClient client.SdkClient,
minRPS, maxRPS, rampUpPeriodInSec, maxTuplesPerWrite, maxParallelRequests int,
body client.ClientWriteRequest,
) (*ImportResponse, error) {
if err := validateImportParams(
minRPS, maxRPS, rampUpPeriodInSec, maxTuplesPerWrite, maxParallelRequests, body,
); err != nil {
return nil, fmt.Errorf("failed to validate import parameters due to %w", err)
}
maxTuplesPerWrite32, err := safecast.Int32(maxTuplesPerWrite)
if err != nil {
return nil, fmt.Errorf("failed to parse maxTuplesPerWrite due to %w", err)
}
maxParallelRequests32, err := safecast.Int32(maxParallelRequests)
if err != nil {
return nil, fmt.Errorf("failed to parse maxParallelRequests due to %w", err)
}
options := client.ClientWriteOptions{
Transaction: &client.TransactionOptions{
Disable: true,
MaxPerChunk: maxTuplesPerWrite32,
MaxParallelRequests: maxParallelRequests32,
},
}
// If RPS values are 0, then fallback to the previous way of importing
if minRPS == 0 || maxRPS == 0 {
return importTuplesWithoutRampUp(ctx, fgaClient, body, options)
}
return importTuplesWithRampUp(ctx, fgaClient,
minRPS, maxRPS, rampUpPeriodInSec, maxTuplesPerWrite, maxParallelRequests,
body, options)
}
func importTuplesWithoutRampUp(
ctx context.Context, fgaClient client.SdkClient, body client.ClientWriteRequest, options client.ClientWriteOptions,
) (*ImportResponse, error) {
response, err := fgaClient.Write(ctx).Body(body).Options(options).Execute()
if err != nil {
return nil, fmt.Errorf("failed to import tuples due to %w", err)
}
successful, failed := processWritesAndDeletes(ctx, response)
result := ImportResponse{
Successful: successful,
Failed: failed,
}
return &result, nil
}
// importTuplesWithRampUp imports tuples to the store with rate limiting.
// It receives a context, an FGA client, rate limiting parameters, and a write request body.
// It returns a pointer to an ImportResponse and an error.
//
// Parameters:
// - ctx: context.Context - The context for the request.
// - fgaClient: client.SdkClient - The FGA client to use for the request.
// - minRPS: int - The minimum requests per second.
// - maxRPS: int - The maximum requests per second.
// - rampUpPeriodInSec: int - The ramp-up period in seconds.
// - maxTuplesPerWrite: int - The maximum number of tuples per write request.
// - maxParallelRequests: int - The maximum number of parallel requests.
// - body: client.ClientWriteRequest - The write request body containing tuples to write or delete.
// - options: client.ClientWriteOptions - The options for the write request.
//
// Returns:
// - *ImportResponse: A pointer to the ImportResponse containing successful and failed tuples.
// - error: An error if the import fails.
func importTuplesWithRampUp(ctx context.Context, fgaClient client.SdkClient,
minRPS, maxRPS, rampUpPeriodInSec, maxTuplesPerWrite, maxParallelRequests int,
body client.ClientWriteRequest, options client.ClientWriteOptions,
) (*ImportResponse, error) {
result := ImportResponse{}
writes := body.Writes
deletes := body.Deletes
numRequests := (len(writes) + len(deletes) + maxTuplesPerWrite - 1) / maxTuplesPerWrite
isDebug := utils.GetDebugContextValue(ctx)
if isDebug {
fmt.Printf(
"Importing tuples: writing %d tuples and deleting %d tuples over %v requests\n",
len(writes),
len(deletes),
numRequests,
)
}
reqs := make([]func() error, numRequests)
var mutex sync.Mutex
for requestIndex := range numRequests {
writeChunk, deleteChunk := getImportChunk(requestIndex, maxTuplesPerWrite, writes, deletes)
if len(writeChunk)+len(deleteChunk) == 0 {
fmt.Printf("Failed to import tuples due to empty write chunk index %v\n", requestIndex)
reqs[requestIndex] = func() error { return nil }
break
}
reqs[requestIndex] = func() error {
request := fgaClient.Write(ctx).Body(client.ClientWriteRequest{
Writes: writeChunk,
Deletes: deleteChunk,
}).Options(options)
response, err := request.Execute()
if err != nil {
if isDebug {
fmt.Printf("Failed to import tuples due to error %v\n", err)
}
return err //nolint:wrapcheck
}
successfulWrites, failedWrites := processWrites(ctx, response.Writes)
successfulDeletes, failedDeletes := processDeletes(ctx, response.Deletes)
mutex.Lock()
result.Successful = append(result.Successful, successfulWrites...)
result.Successful = append(result.Successful, successfulDeletes...)
result.Failed = append(result.Failed, failedWrites...)
result.Failed = append(result.Failed, failedDeletes...)
mutex.Unlock()
return nil
}
}
if err := requests.RampUpAPIRequests(
ctx, minRPS, maxRPS, rampUpPeriodInSec, time.Second, maxParallelRequests, reqs,
); err != nil {
return nil, fmt.Errorf("failed to import tuples due to %w", err)
}
return &result, nil
}
// getImportChunk returns a chunk of tuples to write.
// It receives an index, the maximum number of tuples per write, and the writes and deletes to import,
// and based on that returns the chunk of tuples to write/delete.
// It does that by filling the buckets with the writes first and then when out of writes, fills the rest with deletes.
func getImportChunk(
index, maxTuplesPerWrite int,
writes []client.ClientTupleKey, deletes []client.ClientTupleKeyWithoutCondition) (
[]client.ClientTupleKey, []client.ClientTupleKeyWithoutCondition,
) {
start := index * maxTuplesPerWrite
end := start + maxTuplesPerWrite
writeChunk := []client.ClientTupleKey{}
deleteChunk := []client.ClientTupleKeyWithoutCondition{}
if start < len(writes) {
if end > len(writes) {
end = len(writes)
}
writeChunk = writes[start:end]
}
if len(deletes) == 0 || len(writeChunk) == maxTuplesPerWrite {
return writeChunk, deleteChunk
}
indexOffset := index - len(writes)/maxTuplesPerWrite
extraWrites := len(writes) % maxTuplesPerWrite
start = indexOffset * maxTuplesPerWrite
end = start + maxTuplesPerWrite - extraWrites
if start < len(deletes) {
if end > len(deletes) {
end = len(deletes)
}
deleteChunk = deletes[start:end]
}
return writeChunk, deleteChunk
}
func extractErrMsg(err error) string {
errorMsg := err.Error()
startIndex := strings.Index(errorMsg, "error message:")
if startIndex == -1 {
return errorMsg
}
errorMsg = errorMsg[startIndex:]
errorMsg = strings.TrimSpace(errorMsg)
return errorMsg
}
func processWritesAndDeletes(
ctx context.Context,
response *client.ClientWriteResponse,
) ([]client.ClientTupleKey, []failedWriteResponse) {
successfulWrites, failedWrites := processWrites(ctx, response.Writes)
successfulDeletes, failedDeletes := processDeletes(ctx, response.Deletes)
return append(successfulWrites, successfulDeletes...), append(failedWrites, failedDeletes...)
}
func processWrites(
ctx context.Context,
writes []client.ClientWriteRequestWriteResponse,
) ([]client.ClientTupleKey, []failedWriteResponse) {
var (
successfulWrites []client.ClientTupleKey
failedWrites []failedWriteResponse
)
successLogger := getSuccessLogger(ctx)
failureLogger := getFailureLogger(ctx)
for _, write := range writes {
if write.Status == client.SUCCESS {
successfulWrites = append(successfulWrites, write.TupleKey)
if successLogger != nil {
successLogger.LogSuccess(write.TupleKey)
}
} else {
reason := extractErrMsg(write.Error)
failed := failedWriteResponse{
TupleKey: write.TupleKey,
Reason: reason,
}
failedWrites = append(failedWrites, failed)
if failureLogger != nil {
failureLogger.LogFailure(write.TupleKey)
}
}
}
return successfulWrites, failedWrites
}
func processDeletes(
ctx context.Context,
deletes []client.ClientWriteRequestDeleteResponse,
) ([]client.ClientTupleKey, []failedWriteResponse) {
var (
successfulDeletes []client.ClientTupleKey
failedDeletes []failedWriteResponse
)
successLogger := getSuccessLogger(ctx)
failureLogger := getFailureLogger(ctx)
for _, del := range deletes {
deletedTupleKey := openfga.TupleKey{
Object: del.TupleKey.Object,
Relation: del.TupleKey.Relation,
User: del.TupleKey.User,
}
if del.Status == client.SUCCESS {
successfulDeletes = append(successfulDeletes, deletedTupleKey)
if successLogger != nil {
successLogger.LogSuccess(deletedTupleKey)
}
} else {
reason := extractErrMsg(del.Error)
failed := failedWriteResponse{
TupleKey: deletedTupleKey,
Reason: reason,
}
failedDeletes = append(failedDeletes, failed)
if failureLogger != nil {
failureLogger.LogFailure(deletedTupleKey)
}
}
}
return successfulDeletes, failedDeletes
}