-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
resource_api_extension.go
520 lines (456 loc) · 14.3 KB
/
resource_api_extension.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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package commercetools
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"log"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/labd/commercetools-go-sdk/platform"
"github.com/labd/terraform-provider-commercetools/internal/utils"
)
func resourceAPIExtension() *schema.Resource {
return &schema.Resource{
Description: "Create a new API extension to extend the behaviour of an API with business logic. " +
"Note that API extensions affect the performance of the API it is extending. If it fails, the whole API " +
"call fails \n\n" +
"Also see the [API Extension API Documentation](https://docs.commercetools.com/api/projects/api-extensions)",
CreateContext: resourceAPIExtensionCreate,
ReadContext: resourceAPIExtensionRead,
UpdateContext: resourceAPIExtensionUpdate,
DeleteContext: resourceAPIExtensionDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
SchemaVersion: 1,
StateUpgraders: []schema.StateUpgrader{
{
Type: resourceAPIExtensionResourceV0().CoreConfigSchema().ImpliedType(),
Upgrade: migrateAPIExtensionStateV0toV1,
Version: 0,
},
},
Schema: map[string]*schema.Schema{
"key": {
Description: "User-specific unique identifier for the extension",
Type: schema.TypeString,
Optional: true,
},
"destination": {
Description: "[Destination](https://docs.commercetools.com/api/projects/api-extensions#destination) " +
"Details where the extension can be reached",
Type: schema.TypeList,
MaxItems: 1,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateDestinationType,
},
// HTTP specific fields
"url": {
Type: schema.TypeString,
Optional: true,
},
"azure_authentication": {
Type: schema.TypeString,
Optional: true,
},
"authorization_header": {
Type: schema.TypeString,
Optional: true,
},
// AWSLambda specific fields
"arn": {
Type: schema.TypeString,
Optional: true,
},
"access_key": {
Type: schema.TypeString,
Optional: true,
},
"access_secret": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
},
},
},
"trigger": {
Description: "Array of [Trigger](https://docs.commercetools.com/api/projects/api-extensions#trigger) " +
"Describes what triggers the extension",
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_type_id": {
Description: "Currently, cart, order, payment, and customer are supported",
Type: schema.TypeString,
Required: true,
},
"actions": {
Description: "Currently, Create and Update are supported",
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"condition": {
Description: "Valid predicate that controls the conditions under which the API Extension is called.",
Type: schema.TypeString,
Optional: true,
},
},
},
},
"timeout_in_ms": {
Description: "Extension timeout in milliseconds",
Type: schema.TypeInt,
Optional: true,
},
"version": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func validateDestinationType(val any, key string) (warns []string, errs []error) {
var v = strings.ToLower(val.(string))
switch v {
case
"googlecloudfunction",
"http",
"awslambda":
return
default:
errs = append(errs, fmt.Errorf("%q not a valid value for %q, valid options are: googlecloudfunction, http, awslambda", val, key))
}
return
}
func validateExtensionDestination(draft platform.ExtensionDraft) error {
switch t := draft.Destination.(type) {
case platform.AWSLambdaDestination:
if t.Arn == "" {
return fmt.Errorf("arn is required when using AWSLambda as destination")
}
}
return nil
}
func resourceAPIExtensionCreate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics {
client := getClient(m)
triggers := expandExtensionTriggers(d)
destination, err := expandExtensionDestination(d)
if err != nil {
// Workaround invalid state to be written, see
// https://github.com/hashicorp/terraform-plugin-sdk/issues/476
d.Partial(true)
return diag.FromErr(err)
}
draft := platform.ExtensionDraft{
Destination: destination,
Triggers: triggers,
}
timeoutInMs := d.Get("timeout_in_ms")
if timeoutInMs != 0 {
draft.TimeoutInMs = intRef(timeoutInMs)
}
key := stringRef(d.Get("key"))
if *key != "" {
draft.Key = key
}
if err := validateExtensionDestination(draft); err != nil {
return diag.FromErr(err)
}
var extension *platform.Extension
err = retry.RetryContext(ctx, 20*time.Second, func() *retry.RetryError {
var err error
extension, err = client.Extensions().Post(draft).Execute(ctx)
return utils.ProcessRemoteError(err)
})
if err != nil {
return diag.FromErr(err)
}
if extension == nil {
return diag.Errorf("Error creating extension")
}
d.SetId(extension.ID)
_ = d.Set("version", extension.Version)
return resourceAPIExtensionRead(ctx, d, m)
}
func resourceAPIExtensionRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics {
client := getClient(m)
extension, err := client.Extensions().WithId(d.Id()).Get().Execute(ctx)
if err != nil {
if utils.IsResourceNotFoundError(err) {
d.SetId("")
return nil
}
return diag.FromErr(err)
}
_ = d.Set("version", extension.Version)
_ = d.Set("key", extension.Key)
_ = d.Set("destination", flattenExtensionDestination(extension.Destination, d))
_ = d.Set("trigger", flattenExtensionTriggers(extension.Triggers))
_ = d.Set("timeout_in_ms", extension.TimeoutInMs)
return nil
}
func resourceAPIExtensionUpdate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics {
client := getClient(m)
input := platform.ExtensionUpdate{
Version: d.Get("version").(int),
Actions: []platform.ExtensionUpdateAction{},
}
if d.HasChange("key") {
newKey := d.Get("key").(string)
input.Actions = append(
input.Actions,
&platform.ExtensionSetKeyAction{Key: &newKey})
}
if d.HasChange("trigger") {
triggers := expandExtensionTriggers(d)
input.Actions = append(
input.Actions,
&platform.ExtensionChangeTriggersAction{Triggers: triggers})
}
if d.HasChange("destination") {
destination, err := expandExtensionDestination(d)
if err != nil {
// Workaround invalid state to be written, see
// https://github.com/hashicorp/terraform-plugin-sdk/issues/476
d.Partial(true)
return diag.FromErr(err)
}
input.Actions = append(
input.Actions,
&platform.ExtensionChangeDestinationAction{Destination: destination})
}
if d.HasChange("timeout_in_ms") {
newTimeout := d.Get("timeout_in_ms").(int)
input.Actions = append(
input.Actions,
&platform.ExtensionSetTimeoutInMsAction{TimeoutInMs: &newTimeout})
}
err := retry.RetryContext(ctx, 20*time.Second, func() *retry.RetryError {
_, err := client.Extensions().WithId(d.Id()).Post(input).Execute(ctx)
return utils.ProcessRemoteError(err)
})
if err != nil {
// Workaround invalid state to be written, see
// https://github.com/hashicorp/terraform-plugin-sdk/issues/476
d.Partial(true)
return diag.FromErr(err)
}
return resourceAPIExtensionRead(ctx, d, m)
}
func resourceAPIExtensionDelete(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics {
client := getClient(m)
version := d.Get("version").(int)
_, err := client.Extensions().WithId(d.Id()).Delete().Version(version).Execute(ctx)
if err != nil {
return diag.FromErr(err)
}
return nil
}
//
// Helper methods
//
func expandExtensionDestination(d *schema.ResourceData) (platform.Destination, error) {
input, err := elementFromList(d, "destination")
if err != nil {
return nil, err
}
switch strings.ToLower(input["type"].(string)) {
case "googlecloudfunction":
return platform.GoogleCloudFunctionDestination{
Url: input["url"].(string),
}, nil
case "http":
auth, err := expandExtensionDestinationAuthentication(input)
if err != nil {
return nil, err
}
return platform.HttpDestination{
Url: input["url"].(string),
Authentication: auth,
}, nil
case "awslambda":
return platform.AWSLambdaDestination{
Arn: input["arn"].(string),
AccessKey: input["access_key"].(string),
AccessSecret: input["access_secret"].(string),
}, nil
default:
return nil, fmt.Errorf("extension type %s not implemented", input["type"])
}
}
func expandExtensionDestinationAuthentication(destInput map[string]any) (platform.HttpDestinationAuthentication, error) {
authKeys := [2]string{"authorization_header", "azure_authentication"}
count := 0
for _, key := range authKeys {
if value, ok := destInput[key]; ok {
if value != "" {
count++
}
}
}
if count > 1 {
return nil, fmt.Errorf(
"in the destination only one of the auth values should be definied: %q", authKeys)
}
if val, ok := isNotEmpty(destInput, "authorization_header"); ok {
return platform.AuthorizationHeaderAuthentication{
HeaderValue: val.(string),
}, nil
}
if val, ok := isNotEmpty(destInput, "azure_authentication"); ok {
return platform.AzureFunctionsAuthentication{
Key: val.(string),
}, nil
}
return nil, nil
}
// flattenExtensionDestination flattens the destination returned by
// commercetools to write it in the state file.
func flattenExtensionDestination(dst platform.Destination, d *schema.ResourceData) []map[string]string {
// Special handling is required here since the destination contains a secret
// value which is returned as a masked value by the commercetools API. This means
// we need to extract the value from the current raw state file. However, when
// importing a resource we don't have the value, so we need to handle that
// scenario as well.
isExisting := true
rawState := d.GetRawState()
if !rawState.IsNull() {
isExisting = !rawState.AsValueMap()["version"].IsNull()
}
var current platform.Destination
if isExisting {
current, _ = expandExtensionDestination(d)
}
// A destination is either GoogleCloudFunction, HTTP or AWSLambda
switch d := dst.(type) {
case platform.GoogleCloudFunctionDestination:
return []map[string]string{{
"type": "GoogleCloudFunction",
"url": d.Url,
}}
// For the HTTP Destination there are two specific authentication types:
// AuthorizationHeader and AzureFunctions.
case platform.HttpDestination:
switch d.Authentication.(type) {
case platform.AuthorizationHeaderAuthentication:
// The headerValue value is masked when retrieved from commercetools,
// so use the value from the state file instead (if it exists)
secretValue := ""
if current != nil {
if c, ok := current.(platform.HttpDestination); ok {
if auth, ok := c.Authentication.(platform.AuthorizationHeaderAuthentication); ok {
secretValue = auth.HeaderValue
}
}
}
return []map[string]string{{
"type": "HTTP",
"url": d.Url,
"authorization_header": secretValue,
}}
case platform.AzureFunctionsAuthentication:
// The headerValue value is masked when retrieved from commercetools,
// so use the value from the state file instead (if it exists)
secretValue := ""
if current != nil {
if c, ok := current.(platform.HttpDestination); ok {
if auth, ok := c.Authentication.(platform.AzureFunctionsAuthentication); ok {
secretValue = auth.Key
}
}
}
return []map[string]string{{
"type": "HTTP",
"url": d.Url,
"azure_authentication": secretValue,
}}
default:
log.Println("Unexpected authentication type")
return []map[string]string{{
"type": "HTTP",
"url": d.Url,
}}
}
case platform.AWSLambdaDestination:
// The accessSecret value is masked when retrieved from commercetools,
// so use the value from the state file instead (if it exists)
secretValue := ""
if current != nil {
if c, ok := current.(platform.AWSLambdaDestination); ok {
secretValue = c.AccessSecret
}
}
return []map[string]string{{
"type": "awslambda",
"access_key": d.AccessKey,
"access_secret": secretValue,
"arn": d.Arn,
}}
default:
return []map[string]string{}
}
}
func flattenExtensionTriggers(triggers []platform.ExtensionTrigger) []map[string]any {
result := make([]map[string]any, 0, len(triggers))
for _, t := range triggers {
result = append(result, map[string]any{
"resource_type_id": t.ResourceTypeId,
"actions": t.Actions,
"condition": nilIfEmpty(t.Condition),
})
}
return result
}
func expandExtensionTriggers(d *schema.ResourceData) []platform.ExtensionTrigger {
input := d.Get("trigger").([]any)
var result []platform.ExtensionTrigger
for _, raw := range input {
i := raw.(map[string]any)
var typeId platform.ExtensionResourceTypeId
switch i["resource_type_id"].(string) {
case "cart":
typeId = platform.ExtensionResourceTypeIdCart
case "order":
typeId = platform.ExtensionResourceTypeIdOrder
case "payment":
typeId = platform.ExtensionResourceTypeIdPayment
case "customer":
typeId = platform.ExtensionResourceTypeIdCustomer
case "quote-request":
typeId = platform.ExtensionResourceTypeIdQuoteRequest
case "staged-quote":
typeId = platform.ExtensionResourceTypeIdStagedQuote
case "quote":
typeId = platform.ExtensionResourceTypeIdQuote
case "business-unit":
typeId = platform.ExtensionResourceTypeIdBusinessUnit
case "shopping-list":
typeId = platform.ExtensionResourceTypeIdShoppingList
}
rawActions := i["actions"].([]any)
actions := make([]platform.ExtensionAction, 0, len(rawActions))
for _, item := range rawActions {
actions = append(actions, platform.ExtensionAction(item.(string)))
}
var condition *string
if val, ok := i["condition"].(string); ok {
condition = nilIfEmpty(stringRef(val))
}
result = append(result, platform.ExtensionTrigger{
ResourceTypeId: typeId,
Actions: actions,
Condition: condition,
})
}
return result
}