| 1 |
// Copyright (C) MongoDB, Inc. 2023-present. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 |
// not use this file except in compliance with the License. You may obtain |
| 5 |
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 |
|
| 7 |
package main |
| 8 |
|
| 9 |
import ( |
| 10 |
"context" |
| 11 |
"encoding/json" |
| 12 |
"fmt" |
| 13 |
"net/http" |
| 14 |
"os" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/aws/aws-lambda-go/events" |
| 18 |
"github.com/aws/aws-lambda-go/lambda" |
| 19 |
"go.mongodb.org/mongo-driver/event" |
| 20 |
"go.mongodb.org/mongo-driver/mongo" |
| 21 |
"go.mongodb.org/mongo-driver/mongo/options" |
| 22 |
) |
| 23 |
|
| 24 |
const timeout = 60 * time.Second |
| 25 |
|
| 26 |
// eventListener supports command, heartbeat, and pool event handlers to record |
| 27 |
// event durations, as well as the number of heartbeats, commands, and open |
| 28 |
// connections. |
| 29 |
type eventListener struct { |
| 30 |
commandCount int |
| 31 |
commandDuration int64 |
| 32 |
heartbeatAwaitedCount int |
| 33 |
heartbeatCount int |
| 34 |
heartbeatDuration int64 |
| 35 |
openConnections int |
| 36 |
} |
| 37 |
|
| 38 |
// commandMonitor initializes an event.CommandMonitor that will count the number |
| 39 |
// of successful or failed command events and record a running duration of these |
| 40 |
// events. |
| 41 |
func (listener *eventListener) commandMonitor() *event.CommandMonitor { |
| 42 |
succeeded := func(_ context.Context, e *event.CommandSucceededEvent) { |
| 43 |
listener.commandCount++ |
| 44 |
listener.commandDuration += e.DurationNanos |
| 45 |
} |
| 46 |
|
| 47 |
failed := func(_ context.Context, e *event.CommandFailedEvent) { |
| 48 |
listener.commandCount++ |
| 49 |
listener.commandDuration += e.DurationNanos |
| 50 |
} |
| 51 |
|
| 52 |
return &event.CommandMonitor{ |
| 53 |
Succeeded: succeeded, |
| 54 |
Failed: failed, |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
// serverMonitor initializes an event.ServerMonitor that will count the number |
| 59 |
// of successful or failed heartbeat events and record a running duration of |
| 60 |
// these events. |
| 61 |
func (listener *eventListener) serverMonitor() *event.ServerMonitor { |
| 62 |
succeeded := func(e *event.ServerHeartbeatSucceededEvent) { |
| 63 |
listener.heartbeatCount++ |
| 64 |
listener.heartbeatDuration += e.DurationNanos |
| 65 |
|
| 66 |
if e.Awaited { |
| 67 |
listener.heartbeatAwaitedCount++ |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
failed := func(e *event.ServerHeartbeatFailedEvent) { |
| 72 |
listener.heartbeatCount++ |
| 73 |
listener.heartbeatDuration += e.DurationNanos |
| 74 |
|
| 75 |
if e.Awaited { |
| 76 |
listener.heartbeatAwaitedCount++ |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
return &event.ServerMonitor{ |
| 81 |
ServerHeartbeatSucceeded: succeeded, |
| 82 |
ServerHeartbeatFailed: failed, |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
// poolMonitor initialize an event.PoolMonitor that will increment each time a |
| 87 |
// new connection is created and decrement each time a connection is closed. |
| 88 |
func (listener *eventListener) poolMonitor() *event.PoolMonitor { |
| 89 |
poolEvent := func(e *event.PoolEvent) { |
| 90 |
switch e.Type { |
| 91 |
case event.ConnectionCreated: |
| 92 |
listener.openConnections++ |
| 93 |
case event.ConnectionClosed: |
| 94 |
listener.openConnections-- |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
return &event.PoolMonitor{Event: poolEvent} |
| 99 |
} |
| 100 |
|
| 101 |
// response is the data we return in the body of the API Gateway response. |
| 102 |
type response struct { |
| 103 |
AvgCommandDuration float64 `json:"averageCommandDuration"` |
| 104 |
AvgHeartbeatDuration float64 `json:"averageHeartbeatDuration"` |
| 105 |
OpenConnections int `json:"openConnections"` |
| 106 |
HeartbeatCount int `json:"heartbeatCount"` |
| 107 |
} |
| 108 |
|
| 109 |
// gateway500 is a convenience function for constructing a gateway response with |
| 110 |
// a 500 status code, indicating an internal server error. |
| 111 |
func gateway500() events.APIGatewayProxyResponse { |
| 112 |
return events.APIGatewayProxyResponse{ |
| 113 |
StatusCode: http.StatusInternalServerError, |
| 114 |
Body: http.StatusText(http.StatusInternalServerError), |
| 115 |
} |
| 116 |
|
| 117 |
} |
| 118 |
|
| 119 |
// handler is the AWS Lambda handler, executing at runtime. |
| 120 |
func handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { |
| 121 |
ctx, cancel := context.WithTimeout(ctx, timeout) |
| 122 |
defer cancel() |
| 123 |
|
| 124 |
listener := new(eventListener) |
| 125 |
|
| 126 |
clientOptions := options.Client().ApplyURI(os.Getenv("MONGODB_URI")). |
| 127 |
SetMonitor(listener.commandMonitor()). |
| 128 |
SetServerMonitor(listener.serverMonitor()). |
| 129 |
SetPoolMonitor(listener.poolMonitor()) |
| 130 |
|
| 131 |
// Create a MongoClient that points to MONGODB_URI and listens to the |
| 132 |
// ComandMonitor, ServerMonitor, and PoolMonitor events. |
| 133 |
client, err := mongo.NewClient(clientOptions) |
| 134 |
if err != nil { |
| 135 |
return gateway500(), fmt.Errorf("failed to create client: %w", err) |
| 136 |
} |
| 137 |
|
| 138 |
// Attempt to connect to the client with a timeout. |
| 139 |
if err = client.Connect(ctx); err != nil { |
| 140 |
return gateway500(), fmt.Errorf("failed to connect: %w", err) |
| 141 |
} |
| 142 |
|
| 143 |
defer client.Disconnect(ctx) |
| 144 |
|
| 145 |
collection := client.Database("faas").Collection("lambda") |
| 146 |
|
| 147 |
// Create a document to insert for the automated test. |
| 148 |
doc := map[string]string{"hello": "world"} |
| 149 |
|
| 150 |
// Insert the document. |
| 151 |
_, err = collection.InsertOne(ctx, doc) |
| 152 |
if err != nil { |
| 153 |
return gateway500(), fmt.Errorf("failed to insert: %w", err) |
| 154 |
} |
| 155 |
|
| 156 |
// Delete the document. |
| 157 |
_, err = collection.DeleteOne(ctx, doc) |
| 158 |
if err != nil { |
| 159 |
return gateway500(), fmt.Errorf("failed to delete: %w", err) |
| 160 |
} |
| 161 |
|
| 162 |
// Driver must switch to polling monitoring when running within a FaaS |
| 163 |
// environment. |
| 164 |
if listener.heartbeatAwaitedCount > 0 { |
| 165 |
return gateway500(), fmt.Errorf("FaaS environment failed to switch to polling") |
| 166 |
} |
| 167 |
|
| 168 |
var avgCmdDur float64 |
| 169 |
if count := listener.commandCount; count != 0 { |
| 170 |
avgCmdDur = float64(listener.commandDuration) / float64(count) |
| 171 |
} |
| 172 |
|
| 173 |
var avgHBDur float64 |
| 174 |
if count := listener.heartbeatCount; count != 0 { |
| 175 |
avgHBDur = float64(listener.heartbeatDuration) / float64(count) |
| 176 |
} |
| 177 |
|
| 178 |
rsp := &response{ |
| 179 |
AvgCommandDuration: avgCmdDur, |
| 180 |
AvgHeartbeatDuration: avgHBDur, |
| 181 |
OpenConnections: listener.openConnections, |
| 182 |
HeartbeatCount: listener.heartbeatCount, |
| 183 |
} |
| 184 |
|
| 185 |
body, err := json.Marshal(rsp) |
| 186 |
if err != nil { |
| 187 |
return gateway500(), fmt.Errorf("failed to marshal: %w", err) |
| 188 |
} |
| 189 |
|
| 190 |
return events.APIGatewayProxyResponse{ |
| 191 |
Body: string(body), |
| 192 |
StatusCode: http.StatusOK, |
| 193 |
}, nil |
| 194 |
} |
| 195 |
|
| 196 |
func main() { |
| 197 |
ctx := context.Background() |
| 198 |
|
| 199 |
lambda.StartWithOptions(handler, lambda.WithContext(ctx)) |
| 200 |
} |