|
| 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 | + "fmt" |
| 12 | + "net/http" |
| 13 | + "os" |
| 14 | + "time" |
| 15 | + |
| 16 | + "github.com/aws/aws-lambda-go/events" |
| 17 | + "github.com/aws/aws-lambda-go/lambda" |
| 18 | + "go.mongodb.org/mongo-driver/bson" |
| 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 = 10 * 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 | +// conections. |
| 29 | +type eventListener struct { |
| 30 | + commandCount int |
| 31 | + commandDuration int64 |
| 32 | + heartbeatCount int |
| 33 | + heartbeatDuration int64 |
| 34 | + openConnections int |
| 35 | +} |
| 36 | + |
| 37 | +// commandMonitor initializes an event.CommandMonitor that will count the number |
| 38 | +// of successful or failed command events and record a running duration of these |
| 39 | +// events. |
| 40 | +func (listener *eventListener) commandMonitor() *event.CommandMonitor { |
| 41 | + succeeded := func(_ context.Context, e *event.CommandSucceededEvent) { |
| 42 | + listener.commandCount++ |
| 43 | + listener.commandDuration += e.DurationNanos |
| 44 | + } |
| 45 | + |
| 46 | + failed := func(_ context.Context, e *event.CommandFailedEvent) { |
| 47 | + listener.commandCount++ |
| 48 | + listener.commandDuration += e.DurationNanos |
| 49 | + } |
| 50 | + |
| 51 | + return &event.CommandMonitor{ |
| 52 | + Succeeded: succeeded, |
| 53 | + Failed: failed, |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +// severMonitor initializes an event.ServerMonitor that will count the number |
| 58 | +// of successful or failed heartbeat events and record a running duration of |
| 59 | +// these events. |
| 60 | +func (listener *eventListener) serverMonitor() *event.ServerMonitor { |
| 61 | + succeeded := func(e *event.ServerHeartbeatSucceededEvent) { |
| 62 | + listener.heartbeatCount++ |
| 63 | + listener.heartbeatDuration += e.DurationNanos |
| 64 | + } |
| 65 | + |
| 66 | + failed := func(e *event.ServerHeartbeatFailedEvent) { |
| 67 | + listener.heartbeatCount++ |
| 68 | + listener.heartbeatDuration += e.DurationNanos |
| 69 | + } |
| 70 | + |
| 71 | + return &event.ServerMonitor{ |
| 72 | + ServerHeartbeatSucceeded: succeeded, |
| 73 | + ServerHeartbeatFailed: failed, |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +// poolMonitor initialize an event.PoolMonitor that will increment each time a |
| 78 | +// new conneciton is created and decrement each time a connection is closed. |
| 79 | +func (listener *eventListener) poolMonitor() *event.PoolMonitor { |
| 80 | + poolEvent := func(e *event.PoolEvent) { |
| 81 | + switch e.Type { |
| 82 | + case event.ConnectionCreated: |
| 83 | + listener.openConnections++ |
| 84 | + case event.ConnectionClosed: |
| 85 | + listener.openConnections-- |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + return &event.PoolMonitor{Event: poolEvent} |
| 90 | +} |
| 91 | + |
| 92 | +// response is the data we return in the body of the API Gateway response. |
| 93 | +type response struct { |
| 94 | + AvgCommandDuration float64 `json:"averageCommandDuration"` |
| 95 | + AvgHeartbeatDuration float64 `json:"averageHeartbeatDuration"` |
| 96 | + OpenConnections int `json:"openConnections"` |
| 97 | + HeartbeatCount int `json:"heartbeatCount"` |
| 98 | +} |
| 99 | + |
| 100 | +// gateway500 is a convenience function for constructing a gateway response with |
| 101 | +// a 500 status code, indicating an internal server error. |
| 102 | +func gateway500() events.APIGatewayProxyResponse { |
| 103 | + return events.APIGatewayProxyResponse{ |
| 104 | + StatusCode: http.StatusInternalServerError, |
| 105 | + Body: http.StatusText(http.StatusInternalServerError), |
| 106 | + } |
| 107 | + |
| 108 | +} |
| 109 | + |
| 110 | +// handler is the AWS Lambda handler, executing at runtime. |
| 111 | +func handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { |
| 112 | + ctx, cancel := context.WithTimeout(ctx, timeout) |
| 113 | + defer cancel() |
| 114 | + |
| 115 | + listener := new(eventListener) |
| 116 | + |
| 117 | + clientOptions := options.Client().ApplyURI(os.Getenv("MONGODB_URI")). |
| 118 | + SetMonitor(listener.commandMonitor()). |
| 119 | + SetServerMonitor(listener.serverMonitor()). |
| 120 | + SetPoolMonitor(listener.poolMonitor()) |
| 121 | + |
| 122 | + // Create a MongoClient that points to MONGODB_URI and listens to the |
| 123 | + // ComandMonitor, ServerMonitor, and PoolMonitor events. |
| 124 | + client, err := mongo.NewClient(clientOptions) |
| 125 | + if err != nil { |
| 126 | + return gateway500(), fmt.Errorf("failed to create client: %w", err) |
| 127 | + } |
| 128 | + |
| 129 | + // Attempt to connect to the client with a timeout. |
| 130 | + if err = client.Connect(ctx); err != nil { |
| 131 | + return gateway500(), fmt.Errorf("failed to connect: %w", err) |
| 132 | + } |
| 133 | + |
| 134 | + defer client.Disconnect(ctx) |
| 135 | + |
| 136 | + collection := client.Database("test").Collection("coll0") |
| 137 | + |
| 138 | + // Insert the document. |
| 139 | + view := collection.SearchIndexes() |
| 140 | + name := "test-search-index" |
| 141 | + index, err := view.CreateOne(ctx, mongo.SearchIndexModel{ |
| 142 | + Definition: bson.D{{"mapping", bson.D{{"dynamic", true}}}}, |
| 143 | + Name: &name, |
| 144 | + }) |
| 145 | + if err != nil { |
| 146 | + return gateway500(), fmt.Errorf("failed to insert: %w", err) |
| 147 | + } |
| 148 | + |
| 149 | + // Delete the document. |
| 150 | + cursor, err := view.List(ctx, &index, nil) |
| 151 | + if err != nil { |
| 152 | + return gateway500(), fmt.Errorf("failed to delete: %w", err) |
| 153 | + } |
| 154 | + |
| 155 | + defer cursor.Close(ctx) |
| 156 | + |
| 157 | + return events.APIGatewayProxyResponse{ |
| 158 | + Body: cursor.Current.String(), |
| 159 | + StatusCode: http.StatusOK, |
| 160 | + }, nil |
| 161 | +} |
| 162 | + |
| 163 | +func main() { |
| 164 | + ctx := context.Background() |
| 165 | + |
| 166 | + lambda.StartWithOptions(handler, lambda.WithContext(ctx)) |
| 167 | +} |
0 commit comments