Skip to content

Commit a9c2ac4

Browse files
committed
refactor: all lambdas
1 parent 68a6049 commit a9c2ac4

File tree

17 files changed

+706
-307
lines changed

17 files changed

+706
-307
lines changed

call-profile/main.go

Lines changed: 52 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,14 @@
11
package main
22

33
import (
4-
"context"
54
"fmt"
65
"identity-service/layer/utils"
7-
"log"
8-
"net/http"
96
"time"
107

11-
"cloud.google.com/go/firestore"
12-
138
"github.com/aws/aws-lambda-go/events"
14-
"github.com/aws/aws-lambda-go/lambda"
159
)
1610

17-
type deps struct {
18-
client *firestore.Client
19-
ctx context.Context
20-
}
21-
22-
func (d *deps) handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
11+
func handler(d *utils.Deps, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
2312
var userId, sessionId string = utils.GetDataFromBody([]byte(request.Body))
2413
if userId == "" {
2514
return events.APIGatewayProxyResponse{
@@ -28,52 +17,63 @@ func (d *deps) handler(request events.APIGatewayProxyRequest) (events.APIGateway
2817
}, nil
2918
}
3019

31-
dsnap, err := d.client.Collection("users").Doc(userId).Get(d.ctx)
32-
33-
var userUrl string
34-
var chaincode string
35-
var discordId string
20+
dsnap, err := d.Client.Collection("users").Doc(userId).Get(d.Ctx)
21+
if err != nil {
22+
return events.APIGatewayProxyResponse{
23+
Body: fmt.Sprintf("Error retrieving user: %v", err),
24+
StatusCode: 500,
25+
}, nil
26+
}
3627

37-
if str, ok := dsnap.Data()["discordId"].(string); ok {
38-
discordId = str
39-
} else {
40-
discordId = ""
28+
data := dsnap.Data()
29+
30+
var user utils.User
31+
err = dsnap.DataTo(&user)
32+
if err != nil {
33+
utils.LogProfileSkipped(d.Client, d.Ctx, userId, "UserData Type Error: "+fmt.Sprintln(err), sessionId)
34+
return events.APIGatewayProxyResponse{
35+
Body: "Profile Skipped No User Data",
36+
StatusCode: 200,
37+
}, nil
4138
}
4239

43-
if str, ok := dsnap.Data()["profileURL"].(string); ok {
44-
userUrl = str
45-
} else {
46-
utils.LogProfileSkipped(d.client, d.ctx, userId, "Profile URL not available", sessionId)
47-
utils.SetProfileStatusBlocked(d.client, d.ctx, userId, "Profile URL not available", sessionId, discordId)
40+
discordId := user.DiscordID
41+
42+
if user.ProfileURL == "" {
43+
utils.LogProfileSkipped(d.Client, d.Ctx, userId, "Profile URL not available", sessionId)
44+
utils.SetProfileStatusBlocked(d.Client, d.Ctx, userId, "Profile URL not available", sessionId, discordId)
4845
return events.APIGatewayProxyResponse{
4946
Body: "Profile Skipped No Profile URL",
5047
StatusCode: 200,
5148
}, nil
5249
}
5350

54-
if str, ok := dsnap.Data()["chaincode"].(string); ok {
55-
if str == "" {
56-
utils.LogProfileSkipped(d.client, d.ctx, userId, "Profile Service Blocked or Chaincode is empty", sessionId)
57-
utils.SetProfileStatusBlocked(d.client, d.ctx, userId, "Profile Service Blocked or Chaincode is empty", sessionId, discordId)
58-
return events.APIGatewayProxyResponse{
59-
Body: "Profile Skipped Profile Service Blocked",
60-
StatusCode: 200,
61-
}, nil
62-
}
63-
chaincode = str
64-
} else {
65-
utils.LogProfileSkipped(d.client, d.ctx, userId, "Chaincode Not Found", sessionId)
66-
utils.SetProfileStatusBlocked(d.client, d.ctx, userId, "Chaincode Not Found", sessionId, discordId)
51+
_, chaincodeExists := data["chaincode"]
52+
if !chaincodeExists {
53+
utils.LogProfileSkipped(d.Client, d.Ctx, userId, "Chaincode Not Found", sessionId)
54+
utils.SetProfileStatusBlocked(d.Client, d.Ctx, userId, "Chaincode Not Found", sessionId, discordId)
6755
return events.APIGatewayProxyResponse{
6856
Body: "Profile Skipped Chaincode Not Found",
6957
StatusCode: 200,
7058
}, nil
7159
}
7260

61+
if user.Chaincode == "" {
62+
utils.LogProfileSkipped(d.Client, d.Ctx, userId, "Profile Service Blocked or Chaincode is empty", sessionId)
63+
utils.SetProfileStatusBlocked(d.Client, d.Ctx, userId, "Profile Service Blocked or Chaincode is empty", sessionId, discordId)
64+
return events.APIGatewayProxyResponse{
65+
Body: "Profile Skipped Profile Service Blocked",
66+
StatusCode: 200,
67+
}, nil
68+
}
69+
70+
userUrl := user.ProfileURL
71+
chaincode := user.Chaincode
72+
7373
var userData utils.Diff
7474
err = dsnap.DataTo(&userData)
7575
if err != nil {
76-
utils.LogProfileSkipped(d.client, d.ctx, userId, "UserData Type Error: "+fmt.Sprintln(err), sessionId)
76+
utils.LogProfileSkipped(d.Client, d.Ctx, userId, "UserData Type Error: "+fmt.Sprintln(err), sessionId)
7777
return events.APIGatewayProxyResponse{
7878
Body: "Profile Skipped No User Data",
7979
StatusCode: 200,
@@ -83,33 +83,31 @@ func (d *deps) handler(request events.APIGatewayProxyRequest) (events.APIGateway
8383
if userUrl[len(userUrl)-1] != '/' {
8484
userUrl = userUrl + "/"
8585
}
86+
87+
_, serviceErr := utils.GetWithContext(d.Ctx, userUrl+"health", 5*time.Second)
8688
var isServiceRunning bool
87-
c := &http.Client{
88-
Timeout: 5 * time.Second,
89-
}
90-
_, serviceErr := c.Get(userUrl + "health")
9189
if serviceErr != nil {
9290
isServiceRunning = false
9391
} else {
9492
isServiceRunning = true
9593
}
9694

97-
utils.LogHealth(d.client, d.ctx, userId, isServiceRunning, sessionId)
95+
utils.LogHealth(d.Client, d.Ctx, userId, isServiceRunning, sessionId)
9896
if !isServiceRunning {
99-
utils.LogProfileSkipped(d.client, d.ctx, userId, "Profile Service Down", sessionId)
100-
utils.SetProfileStatusBlocked(d.client, d.ctx, userId, "Profile Service Down", sessionId, discordId)
97+
utils.LogProfileSkipped(d.Client, d.Ctx, userId, "Profile Service Down", sessionId)
98+
utils.SetProfileStatusBlocked(d.Client, d.Ctx, userId, "Profile Service Down", sessionId, discordId)
10199
return events.APIGatewayProxyResponse{
102100
Body: "Profile Skipped Service Down",
103101
StatusCode: 200,
104102
}, nil
105103
}
106104

107-
dataErr := utils.Getdata(d.client, d.ctx, userId, userUrl, chaincode, utils.DiffToRes(userData), sessionId, discordId)
108-
if dataErr != "" {
109-
return events.APIGatewayProxyResponse{
110-
Body: "Profile Skipped " + dataErr,
111-
StatusCode: 200,
112-
}, nil
105+
err = utils.Getdata(d.Client, d.Ctx, userId, userUrl, chaincode, utils.DiffToRes(userData), sessionId, discordId)
106+
if err != nil {
107+
if profileErr, ok := err.(*utils.ProfileError); ok {
108+
return utils.HandleProfileSkippedError(profileErr.Message), nil
109+
}
110+
return utils.HandleProfileSkippedError(err.Error()), nil
113111
}
114112

115113
return events.APIGatewayProxyResponse{
@@ -119,16 +117,5 @@ func (d *deps) handler(request events.APIGatewayProxyRequest) (events.APIGateway
119117
}
120118

121119
func main() {
122-
ctx := context.Background()
123-
client, err := utils.InitializeFirestoreClient(ctx)
124-
if err != nil {
125-
log.Fatalf("Failed to initialize Firestore client: %v", err)
126-
}
127-
128-
d := deps{
129-
client: client,
130-
ctx: ctx,
131-
}
132-
133-
lambda.Start(d.handler)
120+
utils.InitializeLambdaWithFirestore("call-profile", handler)
134121
}

call-profile/main_test.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -364,8 +364,8 @@ func TestHandlerIntegration(t *testing.T) {
364364
},
365365
userData: nil,
366366
mockServer: nil,
367-
expectedBody: "Profile Skipped No Profile URL",
368-
expectedStatus: 200,
367+
expectedBody: "Error retrieving user: rpc error: code = NotFound desc = \"projects/test-project/databases/(default)/documents/users/non-existent-user\" not found",
368+
expectedStatus: 500,
369369
expectedError: false,
370370
},
371371
{
@@ -435,7 +435,7 @@ func TestHandlerIntegration(t *testing.T) {
435435
w.Write([]byte("Service Unavailable"))
436436
}))
437437
},
438-
expectedBody: "Profile Skipped error in getting profile data",
438+
expectedBody: "Profile Skipped: error in getting profile data: status code 500",
439439
expectedStatus: 200,
440440
expectedError: false,
441441
},
@@ -590,7 +590,7 @@ func TestHandlerEdgeCases(t *testing.T) {
590590
"firstName": 123, // Invalid type
591591
"lastName": "Doe",
592592
},
593-
expectedBody: "Profile Skipped error in getting profile data",
593+
expectedBody: "Profile Skipped: error in getting profile data: status code 404",
594594
expectedStatus: 200,
595595
},
596596
{
@@ -604,7 +604,7 @@ func TestHandlerEdgeCases(t *testing.T) {
604604
"chaincode": "TESTCHAIN",
605605
"profileStatus": "PENDING",
606606
},
607-
expectedBody: "Profile Skipped error in getting profile data", // Will fail health check
607+
expectedBody: "Profile Skipped: error in getting profile data: status code 404", // Will fail health check
608608
expectedStatus: 200,
609609
},
610610
}
@@ -635,9 +635,9 @@ func newFirestoreMockClient(ctx context.Context) *firestore.Client {
635635

636636
func handlerWithClient(request events.APIGatewayProxyRequest, client *firestore.Client) (events.APIGatewayProxyResponse, error) {
637637
ctx := context.Background()
638-
d := deps{
639-
client: client,
640-
ctx: ctx,
638+
d := &utils.Deps{
639+
Client: client,
640+
Ctx: ctx,
641641
}
642-
return d.handler(request)
642+
return handler(d, request)
643643
}

call-profiles/main.go

Lines changed: 25 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,17 @@
11
package main
22

33
import (
4-
"context"
54
"fmt"
65
"identity-service/layer/utils"
7-
"log"
8-
"sync"
96
"time"
107

11-
"cloud.google.com/go/firestore"
12-
138
"github.com/aws/aws-lambda-go/events"
14-
"github.com/aws/aws-lambda-go/lambda"
159

1610
"google.golang.org/api/iterator"
1711
)
1812

19-
var wg sync.WaitGroup
20-
21-
type deps struct {
22-
client *firestore.Client
23-
ctx context.Context
24-
}
25-
2613
func callProfile(userId string, sessionId string) {
27-
defer wg.Done()
14+
logger := utils.GetLogger()
2815

2916
payload := utils.ProfileLambdaCallPayload{
3017
UserId: userId,
@@ -33,12 +20,16 @@ func callProfile(userId string, sessionId string) {
3320

3421
err := utils.InvokeProfileLambda(payload)
3522
if err != nil {
36-
log.Println("error calling profile lambda", err)
23+
logger.Error("Error calling profile lambda", err, map[string]interface{}{
24+
"function": "callProfile",
25+
"userId": userId,
26+
"sessionId": sessionId,
27+
})
3728
}
3829
}
3930

40-
func (d *deps) handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
41-
docRef, _, sessionIdErr := d.client.Collection("identitySessionIds").Add(d.ctx, map[string]interface{}{
31+
func handler(d *utils.Deps, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
32+
docRef, _, sessionIdErr := d.Client.Collection("identitySessionIds").Add(d.Ctx, map[string]interface{}{
4233
"Timestamp": time.Now(),
4334
})
4435

@@ -48,21 +39,32 @@ func (d *deps) handler(request events.APIGatewayProxyRequest) (events.APIGateway
4839

4940
totalProfilesCalled := 0
5041

51-
iter := d.client.Collection("users").Where("profileStatus", "==", "VERIFIED").Documents(d.ctx)
42+
workerPool := utils.NewWorkerPool(10, 100)
43+
defer workerPool.Close()
44+
45+
iter := d.Client.Collection("users").Where("profileStatus", "==", "VERIFIED").Documents(d.Ctx)
5246
for {
5347
doc, err := iter.Next()
5448
if err == iterator.Done {
5549
break
5650
}
5751
if err != nil {
58-
log.Fatalf("Failed to iterate: %v", err)
52+
return events.APIGatewayProxyResponse{
53+
Body: fmt.Sprintf("Failed to iterate users: %v", err),
54+
StatusCode: 500,
55+
}, nil
5956
}
57+
58+
userId := doc.Ref.ID
59+
sessionId := docRef.ID
60+
6061
totalProfilesCalled += 1
61-
wg.Add(1)
62-
go callProfile(doc.Ref.ID, docRef.ID)
62+
workerPool.Submit(func() {
63+
callProfile(userId, sessionId)
64+
})
6365
}
6466

65-
wg.Wait()
67+
workerPool.Wait()
6668

6769
return events.APIGatewayProxyResponse{
6870
Body: fmt.Sprintf("Total Profiles called in session is %d", totalProfilesCalled),
@@ -71,16 +73,5 @@ func (d *deps) handler(request events.APIGatewayProxyRequest) (events.APIGateway
7173
}
7274

7375
func main() {
74-
ctx := context.Background()
75-
client, err := utils.InitializeFirestoreClient(ctx)
76-
if err != nil {
77-
log.Fatalf("Failed to initialize Firestore client: %v", err)
78-
}
79-
80-
d := deps{
81-
client: client,
82-
ctx: ctx,
83-
}
84-
85-
lambda.Start(d.handler)
76+
utils.InitializeLambdaWithFirestore("call-profiles", handler)
8677
}

call-profiles/main_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -302,11 +302,11 @@ func newFirestoreMockClient(ctx context.Context) *firestore.Client {
302302

303303
func handlerWithClient(request events.APIGatewayProxyRequest, client *firestore.Client) (events.APIGatewayProxyResponse, error) {
304304
ctx := context.Background()
305-
d := deps{
306-
client: client,
307-
ctx: ctx,
305+
d := &utils.Deps{
306+
Client: client,
307+
Ctx: ctx,
308308
}
309-
return d.handler(request)
309+
return handler(d, request)
310310
}
311311

312312
func TestHandlerIntegration(t *testing.T) {

0 commit comments

Comments
 (0)