-
Notifications
You must be signed in to change notification settings - Fork 69
/
adapter.go
263 lines (206 loc) · 7.31 KB
/
adapter.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
/*
Copyright 2022 TriggerMesh Inc.
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 awscognitoidentitysource
import (
"context"
"fmt"
"go.uber.org/zap"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cognitoidentity"
"github.com/aws/aws-sdk-go/service/cognitoidentity/cognitoidentityiface"
"github.com/aws/aws-sdk-go/service/cognitosync"
"github.com/aws/aws-sdk-go/service/cognitosync/cognitosynciface"
pkgadapter "knative.dev/eventing/pkg/adapter/v2"
"knative.dev/pkg/logging"
"github.com/triggermesh/triggermesh/pkg/apis/sources"
"github.com/triggermesh/triggermesh/pkg/apis/sources/v1alpha1"
"github.com/triggermesh/triggermesh/pkg/sources/adapter/common"
)
// envConfig is a set parameters sourced from the environment for the source's
// adapter.
type envConfig struct {
pkgadapter.EnvConfig
ARN string `envconfig:"ARN" required:"true"`
// Assume this IAM Role when access keys provided.
AssumeIamRole string `envconfig:"AWS_ASSUME_ROLE_ARN"`
// The environment variables below aren't read from the envConfig struct
// by the AWS SDK, but rather directly using os.Getenv().
// They are nevertheless listed here for documentation purposes.
_ string `envconfig:"AWS_ACCESS_KEY_ID"`
_ string `envconfig:"AWS_SECRET_ACCESS_KEY"`
}
// adapter implements the source's adapter.
type adapter struct {
logger *zap.SugaredLogger
mt *pkgadapter.MetricTag
cgnIdentityClient cognitoidentityiface.CognitoIdentityAPI
cgnSyncClient cognitosynciface.CognitoSyncAPI
ceClient cloudevents.Client
arn arn.ARN
identityPoolID string
}
// NewEnvConfig satisfies pkgadapter.EnvConfigConstructor.
func NewEnvConfig() pkgadapter.EnvConfigAccessor {
return &envConfig{}
}
// NewAdapter satisfies pkgadapter.AdapterConstructor.
func NewAdapter(ctx context.Context, envAcc pkgadapter.EnvConfigAccessor, ceClient cloudevents.Client) pkgadapter.Adapter {
logger := logging.FromContext(ctx)
mt := &pkgadapter.MetricTag{
ResourceGroup: sources.AWSCognitoIdentitySourceResource.String(),
Namespace: envAcc.GetNamespace(),
Name: envAcc.GetName(),
}
env := envAcc.(*envConfig)
arn := common.MustParseARN(env.ARN)
sess := session.Must(session.NewSession(aws.NewConfig().
WithRegion(arn.Region).
WithMaxRetries(5),
))
config := &aws.Config{}
if env.AssumeIamRole != "" {
config.Credentials = stscreds.NewCredentials(sess, env.AssumeIamRole)
}
return &adapter{
logger: logger,
mt: mt,
cgnIdentityClient: cognitoidentity.New(sess, config),
cgnSyncClient: cognitosync.New(sess, config),
ceClient: ceClient,
arn: arn,
identityPoolID: common.MustParseCognitoIdentityResource(arn.Resource),
}
}
// Start implements adapter.Adapter.
func (a *adapter) Start(ctx context.Context) error {
a.logger.Infof("Listening to AWS Cognito stream for Identity: %s", a.identityPoolID)
ctx = pkgadapter.ContextWithMetricTag(ctx, a.mt)
backoff := common.NewBackoff()
err := backoff.Run(ctx.Done(), func(ctx context.Context) (bool, error) {
resetBackoff := false
identities, err := a.getIdentities()
if err != nil {
a.logger.Errorw("Unable to get identities", zap.Error(err))
}
datasets, err := a.getDatasets(identities)
if err != nil {
a.logger.Errorw("Unable to get datasets", zap.Error(err))
}
for _, dataset := range datasets {
resetBackoff = true
records, err := a.getRecords(dataset)
if err != nil {
a.logger.Errorw("Unable to get records", zap.Error(err))
continue
}
err = a.sendCognitoEvent(ctx, dataset, records)
if err != nil {
a.logger.Errorw("Failed to send the event", zap.Error(err))
}
}
return resetBackoff, nil
})
return err
}
func (a *adapter) getIdentities() ([]*cognitoidentity.IdentityDescription, error) {
identities := []*cognitoidentity.IdentityDescription{}
listIdentitiesInput := cognitoidentity.ListIdentitiesInput{
MaxResults: aws.Int64(1),
IdentityPoolId: &a.identityPoolID,
}
for {
listIdentitiesOutput, err := a.cgnIdentityClient.ListIdentities(&listIdentitiesInput)
if err != nil {
return identities, err
}
identities = append(identities, listIdentitiesOutput.Identities...)
listIdentitiesInput.NextToken = listIdentitiesOutput.NextToken
if listIdentitiesOutput.NextToken == nil {
break
}
}
return identities, nil
}
func (a *adapter) getDatasets(identities []*cognitoidentity.IdentityDescription) ([]*cognitosync.Dataset, error) {
datasets := []*cognitosync.Dataset{}
for _, identity := range identities {
listDatasetsInput := cognitosync.ListDatasetsInput{
IdentityPoolId: &a.identityPoolID,
IdentityId: identity.IdentityId,
}
for {
listDatasetsOutput, err := a.cgnSyncClient.ListDatasets(&listDatasetsInput)
if err != nil {
return datasets, err
}
datasets = append(datasets, listDatasetsOutput.Datasets...)
listDatasetsInput.NextToken = listDatasetsOutput.NextToken
if listDatasetsOutput.NextToken == nil {
break
}
}
}
return datasets, nil
}
func (a *adapter) getRecords(dataset *cognitosync.Dataset) ([]*cognitosync.Record, error) {
records := []*cognitosync.Record{}
input := cognitosync.ListRecordsInput{
DatasetName: dataset.DatasetName,
IdentityId: dataset.IdentityId,
IdentityPoolId: &a.identityPoolID,
}
for {
recordsOutput, err := a.cgnSyncClient.ListRecords(&input)
if err != nil {
return records, err
}
records = append(records, recordsOutput.Records...)
input.NextToken = recordsOutput.NextToken
if recordsOutput.NextToken == nil {
break
}
}
return records, nil
}
func (a *adapter) sendCognitoEvent(ctx context.Context, dataset *cognitosync.Dataset, records []*cognitosync.Record) error {
a.logger.Debugf("Processing Dataset: %s", *dataset.DatasetName)
data := &CognitoIdentitySyncEvent{
CreationDate: dataset.CreationDate,
DataStorage: dataset.DataStorage,
DatasetName: dataset.DatasetName,
IdentityID: dataset.IdentityId,
LastModifiedBy: dataset.LastModifiedBy,
LastModifiedDate: dataset.LastModifiedDate,
NumRecords: dataset.NumRecords,
EventType: aws.String("SyncTrigger"),
Region: &a.arn.Region,
IdentityPoolID: &a.identityPoolID,
DatasetRecords: records,
}
event := cloudevents.NewEvent(cloudevents.VersionV1)
event.SetType(v1alpha1.AWSEventType(a.arn.Service, v1alpha1.AWSCognitoIdentityGenericEventType))
event.SetSubject(*dataset.DatasetName)
event.SetSource(a.arn.String())
event.SetID(*dataset.IdentityId)
if err := event.SetData(cloudevents.ApplicationJSON, data); err != nil {
return fmt.Errorf("failed to set event data: %w", err)
}
if result := a.ceClient.Send(ctx, event); !cloudevents.IsACK(result) {
return result
}
return nil
}