|
| 1 | +package testscenario |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/amp-labs/connectors" |
| 10 | + "github.com/amp-labs/connectors/common" |
| 11 | + "github.com/amp-labs/connectors/internal/components" |
| 12 | + "github.com/amp-labs/connectors/internal/datautils" |
| 13 | + "github.com/amp-labs/connectors/test/utils" |
| 14 | +) |
| 15 | + |
| 16 | +type ConnectorWebhookSubscriber interface { |
| 17 | + components.SubscriptionCreator |
| 18 | + components.WebhookMessageVerifier |
| 19 | + connectors.ReadConnector |
| 20 | + connectors.WriteConnector |
| 21 | + connectors.DeleteConnector |
| 22 | +} |
| 23 | + |
| 24 | +type SubscribeParamBuilder func(webhookURL string) *common.SubscribeParams |
| 25 | + |
| 26 | +type SubscribeReceiveEventsSuite struct { |
| 27 | + SubscribeParamBuilder SubscribeParamBuilder |
| 28 | + // ExpectedWebhookCalls is the number of events to wait before quiting the script. |
| 29 | + // |
| 30 | + // Number of Operations may be greater than the number of expected events. |
| 31 | + // Some operations can be utilized for cleaning records. |
| 32 | + // Ex: You are testing only update. The operations would still need create, delete, not just update. |
| 33 | + // |
| 34 | + // Webhook may be called more if there are already some subscriptions that would intervene. |
| 35 | + // There is no way to protect against these side effects. |
| 36 | + ExpectedWebhookCalls int |
| 37 | + Operations []ConnectorOperation |
| 38 | + // WebhookRouter allows a list of alternative request handling by the webhook handler. |
| 39 | + // When conditions are met for the Route that handler is executed. |
| 40 | + // If there are no custom routes or none match then default webhook handling will take place. |
| 41 | + // This includes printing events until reaching the number of ExpectedWebhookCalls or |
| 42 | + // script cancellation. |
| 43 | + WebhookRouter WebhookRouter |
| 44 | + VerificationParams *common.VerificationParams |
| 45 | +} |
| 46 | + |
| 47 | +type ConnectorMethod string |
| 48 | + |
| 49 | +const ( |
| 50 | + ConnectorMethodCreate ConnectorMethod = "create" |
| 51 | + ConnectorMethodUpdate ConnectorMethod = "update" |
| 52 | + ConnectorMethodDelete ConnectorMethod = "delete" |
| 53 | +) |
| 54 | + |
| 55 | +type ConnectorOperation struct { |
| 56 | + // ObjectName object to create, update or to remove. |
| 57 | + ObjectName string |
| 58 | + // Method invokes Write() or Delete(). |
| 59 | + Method ConnectorMethod |
| 60 | + // Payload relevant for ConnectorMethodCreate and ConnectorMethodUpdate. |
| 61 | + Payload any |
| 62 | + // SearchProcedure relevant for ConnectorMethodUpdate and ConnectorMethodDelete. |
| 63 | + SearchProcedure SearchProcedure |
| 64 | +} |
| 65 | + |
| 66 | +type SearchProcedure struct { |
| 67 | + ReadFields datautils.StringSet |
| 68 | + RecordIdentifierKey string |
| 69 | + WaitBeforeSearch time.Duration |
| 70 | + SearchBy Property |
| 71 | +} |
| 72 | + |
| 73 | +// ValidateSubscribeReceiveEvents is a comprehensive test scenario utilizing subscription connector operations. |
| 74 | +// |
| 75 | +// Flow: |
| 76 | +// 1. Starts local server |
| 77 | +// 2. Asks user for public URL (ngrok) |
| 78 | +// 3. Creates subscription |
| 79 | +// 4. Optionally triggers events (Write) |
| 80 | +// 5. Waits for webhook(s) |
| 81 | +// 6. Exits cleanly |
| 82 | +func ValidateSubscribeReceiveEvents( |
| 83 | + ctx context.Context, |
| 84 | + conn ConnectorWebhookSubscriber, |
| 85 | + suite SubscribeReceiveEventsSuite, |
| 86 | +) { |
| 87 | + fmt.Println("> TEST Subscribe/Write/Recieve") |
| 88 | + |
| 89 | + fmt.Println("============== Starting Webhook Handler ==================") |
| 90 | + messageChannel := make(chan webhookMessageResult) |
| 91 | + webhookURL, shutdown := startWebhookHandler(ctx, conn, |
| 92 | + suite.WebhookRouter, suite.VerificationParams, messageChannel, |
| 93 | + ) |
| 94 | + defer shutdown() |
| 95 | + |
| 96 | + fmt.Printf("Local webhook server started at: \"%s\"\n", webhookURL) |
| 97 | + publicURL, ok := getPublicWebhookURL(ctx) |
| 98 | + if !ok { |
| 99 | + return |
| 100 | + } |
| 101 | + |
| 102 | + fmt.Println("============== Invoking connector.Subscribe() ==================") |
| 103 | + params := *suite.SubscribeParamBuilder(publicURL) |
| 104 | + subscriptionResult, err := conn.Subscribe(ctx, params) |
| 105 | + if printError(err) { |
| 106 | + return |
| 107 | + } |
| 108 | + |
| 109 | + switch subscriptionResult.Status { |
| 110 | + case common.SubscriptionStatusPending: |
| 111 | + fmt.Printf("Connector returned status (%v). Script is not designed to handle this.\n", |
| 112 | + common.SubscriptionStatusPending) |
| 113 | + return |
| 114 | + case common.SubscriptionStatusFailed: |
| 115 | + utils.DumpJSON(subscriptionResult.Result, os.Stdout) |
| 116 | + fmt.Println("Subscription failed ❌") |
| 117 | + return |
| 118 | + case common.SubscriptionStatusSuccess: |
| 119 | + utils.DumpJSON(subscriptionResult.Result, os.Stdout) |
| 120 | + utils.DumpJSON(subscriptionResult.ObjectEvents, os.Stdout) |
| 121 | + // continue script execution. |
| 122 | + case common.SubscriptionStatusFailedToRollback: |
| 123 | + fmt.Println("Subscription encountered failures and then failed to rollback ❌") |
| 124 | + utils.DumpJSON(subscriptionResult.Result, os.Stdout) |
| 125 | + utils.DumpJSON(subscriptionResult.ObjectEvents, os.Stdout) |
| 126 | + return |
| 127 | + default: |
| 128 | + fmt.Printf("Unknown subscription status (%v)\n", subscriptionResult.Status) |
| 129 | + return |
| 130 | + } |
| 131 | + |
| 132 | + fmt.Println("============== Invoking connector.Write/Delete() ==================") |
| 133 | + for _, trigger := range suite.Operations { |
| 134 | + switch trigger.Method { |
| 135 | + case ConnectorMethodCreate: |
| 136 | + fmt.Printf("Creating object %v:\n", trigger.ObjectName) |
| 137 | + createResult, err := createObject[any](ctx, conn, trigger.ObjectName, &trigger.Payload) |
| 138 | + if printError(err) { |
| 139 | + return |
| 140 | + } |
| 141 | + utils.DumpJSON(createResult, os.Stdout) |
| 142 | + case ConnectorMethodUpdate: |
| 143 | + objectID, ok := searchForRecord(ctx, conn, trigger.ObjectName, trigger.SearchProcedure) |
| 144 | + if !ok { |
| 145 | + return |
| 146 | + } |
| 147 | + |
| 148 | + fmt.Printf("Updating object %v:\n", trigger.ObjectName) |
| 149 | + updateResult, err := updateObject[any](ctx, conn, trigger.ObjectName, objectID, &trigger.Payload) |
| 150 | + if printError(err) { |
| 151 | + return |
| 152 | + } |
| 153 | + utils.DumpJSON(updateResult, os.Stdout) |
| 154 | + case ConnectorMethodDelete: |
| 155 | + objectID, ok := searchForRecord(ctx, conn, trigger.ObjectName, trigger.SearchProcedure) |
| 156 | + if !ok { |
| 157 | + return |
| 158 | + } |
| 159 | + |
| 160 | + fmt.Printf("Deleting object %v:\n", trigger.ObjectName) |
| 161 | + err = removeObject(ctx, conn, trigger.ObjectName, objectID) |
| 162 | + if printError(err) { |
| 163 | + return |
| 164 | + } |
| 165 | + fmt.Println("... object deleted.") |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + // Waiting for the events to arrive. Then report on them and exit. |
| 170 | + // This can be stopped prematurely via context cancellation. |
| 171 | + receivedNumEvents := 0 |
| 172 | + fmt.Printf("============== Waiting for %d webhook messages ==================\n", suite.ExpectedWebhookCalls) |
| 173 | + |
| 174 | + for receivedNumEvents < suite.ExpectedWebhookCalls { |
| 175 | + select { |
| 176 | + case message := <-messageChannel: |
| 177 | + receivedNumEvents++ |
| 178 | + fmt.Printf("[%d/%d] Received webhook message:\n", receivedNumEvents, suite.ExpectedWebhookCalls) |
| 179 | + if message.Error == "" { |
| 180 | + utils.DumpJSON(message.Body, os.Stdout) |
| 181 | + } else { |
| 182 | + utils.DumpJSON(message.Error, os.Stdout) |
| 183 | + } |
| 184 | + |
| 185 | + case <-ctx.Done(): |
| 186 | + fmt.Println("Context cancelled, stopping...") |
| 187 | + return |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + fmt.Println("============== Done ==================") |
| 192 | +} |
| 193 | + |
| 194 | +func searchForRecord( |
| 195 | + ctx context.Context, conn ConnectorWebhookSubscriber, objectName string, procedure SearchProcedure, |
| 196 | +) (string, bool) { |
| 197 | + if procedure.WaitBeforeSearch != 0 { |
| 198 | + fmt.Println("... waiting") |
| 199 | + time.Sleep(procedure.WaitBeforeSearch) |
| 200 | + } |
| 201 | + |
| 202 | + fmt.Printf("Search object %v by %v\n", objectName, procedure.SearchBy.String()) |
| 203 | + res, err := readObjects(ctx, conn, objectName, procedure.ReadFields, procedure.SearchBy.Since) |
| 204 | + if printError(err) { |
| 205 | + return "", false |
| 206 | + } |
| 207 | + |
| 208 | + search := procedure.SearchBy |
| 209 | + object, err := searchObjectRecord(res, search.Key, search.Value) |
| 210 | + if printError(err) { |
| 211 | + return "", false |
| 212 | + } |
| 213 | + |
| 214 | + objectID := object.getRecordIdentifierValue(procedure.RecordIdentifierKey) |
| 215 | + |
| 216 | + return objectID, true |
| 217 | +} |
0 commit comments