Skip to content

Commit

Permalink
[EventGrid] Move to Samples v2 Framework (Azure#14532)
Browse files Browse the repository at this point in the history
This change moves our samples to be generated via `devtool`, as part
of the samples quality effort. Much of the diff here is just moving
code around to confirm to the new patterns, as outlined in the
migration guide, but one interesting outcome is that since the samples
are now part of the ts compliation for the package itself, and our
samples use service bus (which itself uses AsyncIterators) we have to
add a `lib` in our `tsconfig.json`.

We do not add any polyfill or anything like that to our `package.json`
because our implementation does not use these features.

After talking about this with will, I did manually patch the
*generated* tsconfig.json for our samples to say we target ES2018
(since the samples will need this), and he will add support for that
for the tool going forward.

In addition, we add some more resources to our `test-resources.json`
so that these samples can run in CI and be validated.

Fixes Azure#14471
Fixes Azure#14573
  • Loading branch information
ellismg authored Mar 29, 2021
1 parent cd0edbc commit fc7fc96
Show file tree
Hide file tree
Showing 29 changed files with 581 additions and 281 deletions.
20 changes: 16 additions & 4 deletions sdk/eventgrid/eventgrid/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@
"README.md",
"LICENSE"
],
"//sampleConfiguration": {
"productName": "Azure Event Grid",
"productSlugs": [
"azure",
"azure-event-grid"
],
"requiredResources": {
"Azure Event Grid Custom Topic, configured to use the Event Grid Schema": "https://docs.microsoft.com/azure/event-grid/scripts/event-grid-cli-create-custom-topic",
"Azure Event Grid Custom Topic, configured to use the Cloud Event 1.0 Schema": "https://docs.microsoft.com/azure/event-grid/scripts/event-grid-cli-create-custom-topic",
"Azure Service Bus Queue": "https://docs.microsoft.com/azure/service-bus-messaging/service-bus-quickstart-portal"
}
},
"//metadata": {
"constantPaths": [
{
Expand All @@ -51,14 +63,14 @@
"build:autorest": "autorest ./swagger/README.md --typescript --v3",
"build:browser": "tsc -p . && cross-env ONLY_BROWSER=true rollup -c 2>&1",
"build:node": "tsc -p . && cross-env ONLY_NODE=true rollup -c 2>&1",
"build:samples": "dev-tool samples prep && cd dist-samples && tsc -p .",
"build:samples": "echo Obsolete",
"build:test": "tsc -p . && rollup -c rollup.test.config.js 2>&1",
"build": "tsc -p . && rollup -c 2>&1 && api-extractor run --local",
"check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
"check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
"clean": "rimraf dist dist-browser dist-esm test-dist temp types *.tgz *.log",
"execute:samples": "npm run build:samples && dev-tool samples run samples/javascript samples/typescript/dist/samples/typescript/src/",
"execute:samples": "dev-tool samples run samples-dev",
"extract-api": "tsc -p . && api-extractor run --local",
"format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
"format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
"integration-test:browser": "karma start --single-run",
"integration-test:node": "nyc mocha -r esm --require source-map-support/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 5000000 --full-trace \"dist-esm/test/**/*.spec.js\"",
"integration-test": "npm run integration-test:node && npm run integration-test:browser",
Expand Down
13 changes: 3 additions & 10 deletions sdk/eventgrid/eventgrid/sample.env
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,6 @@ EVENT_GRID_EVENT_GRID_SCHEMA_API_KEY="<event grid api key>"
EVENT_GRID_CLOUD_EVENT_SCHEMA_ENDPOINT="https://<event grid topic name>.<event grid topic region>.eventgrid.azure.net/api/events"
EVENT_GRID_CLOUD_EVENT_SCHEMA_API_KEY="<event grid api key>"

# An Event Grid Topic configured to use a custom schema, the topic should be configured with the following mappings:
# typ -> eventType
# sub -> subject
# ver -> dataVersion
EVENT_GRID_CUSTOM_SCHEMA_ENDPOINT="https://<event grid topic name>.<event grid topic region>.eventgrid.azure.net/api/events"
EVENT_GRID_CUSTOM_SCHEMA_API_KEY="<event grid api key>"

# Our tests assume that TEST_MODE is "playback" by default. You can
# change it to "record" to generate new recordings, or "live" to bypass the recorder entirely.
# TEST_MODE=playback
# A Service Bus Namespace and Queue, used for the sample which shows how to consume events from Service Bus.
SERVICE_BUS_CONNECTION_STRING="Endpoint=sb://<namespace-name>.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<key from the portal>"
SERVICE_BUS_QUEUE_NAME="<queue name>"
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

/**
* @summary Consume events delivered by Event Grid to a Service Bus Queue
* @azsdk-weight 3
*/

import { EventGridDeserializer, isSystemEvent } from "@azure/eventgrid";
import { ServiceBusClient, ServiceBusReceivedMessage } from "@azure/service-bus";
import * as dotenv from "dotenv";

// Load the .env file if it exists
dotenv.config();

// Create a Event Grid Consumer which will decode the payload of service bus message into an array of EventGridEvent objects.
const consumer = new EventGridDeserializer();

// The connection string for Service Bus namespace that Event Grid will deliver messages to.
// You can find the connection string in the Azure portal.
// Navigate to Settings > Shared access policies > RootManageSharedAccessKey in your Service Bus Namespace's menu blade to see
// the connection string.
const serviceBusClientConnectionString = process.env["SERVICE_BUS_CONNECTION_STRING"] || "";

// The name of the queue within the Service Bus namespace that Event Grid will deliver messages to. You should ensure that
// events sent to this queue are sent using the Event Grid schema.
const serviceBusQueueName = process.env["SERVICE_BUS_QUEUE_NAME"] || "";

// Create a receiver to read messages from the Service Bus Queue.
const receiver = new ServiceBusClient(serviceBusClientConnectionString).createReceiver(
serviceBusQueueName
);

// The handler function which will be run on each message we remove from the Service Bus Queue.
async function processMessage(message: ServiceBusReceivedMessage): Promise<void> {
// Convert the message into an array of Event Grid Events.
const events = await consumer.deserializeEventGridEvents(message.body);

// Process each message, printing the type and ID. In addition, if the event is a system event generated by Azure when
// a blob is created, print the URL from the event.
for (const event of events) {
console.log(`Processing event of type ${event.eventType} with id: ${event.id}`);
if (isSystemEvent("Microsoft.Storage.BlobCreated", event)) {
console.log(`A blob was created with URL: ${event.data.url}`);
}
}
}

async function main() {
// Start processing events.
const closer = receiver.subscribe({
processMessage,
processError: async (err) => {
console.error("Error while processing events:", err);
}
});

// Run for 10 seconds, allowing events to be processed.
await new Promise((resolve) => {
setTimeout(resolve, 1000 * 10);
});

// Stop processing events and exit.
await closer.close();
await receiver.close();
process.exit();
}

main().catch((err) => {
console.error("The sample encountered an error:", err);
});
45 changes: 45 additions & 0 deletions sdk/eventgrid/eventgrid/samples-dev/sendCloudEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

/**
* @summary Send events to Event Grid using the Cloud Events 1.0 Schema.
* @azsdk-weight 1
*/

import { EventGridPublisherClient, AzureKeyCredential } from "@azure/eventgrid";
import * as dotenv from "dotenv";

// Load the .env file if it exists
dotenv.config();

// The URL of the endpoint of the Event Grid topic.
const endpoint = process.env["EVENT_GRID_CLOUD_EVENT_SCHEMA_ENDPOINT"] || "";

// You can find the access keys in the Azure portal.
// Navigate to Settings > Access keys in your Event Grid topic's menu blade to see both access keys (you may use either).
const accessKey = process.env["EVENT_GRID_CLOUD_EVENT_SCHEMA_API_KEY"] || "";

export async function main(): Promise<void> {
// Create the client used to publish events to the Event Grid Service
const client = new EventGridPublisherClient(
endpoint,
"CloudEvent",
new AzureKeyCredential(accessKey)
);

// Send an event to the Event Grid Service, using the Cloud Event schema.
// A random ID will be generated for this event, since one is not provided.
await client.send([
{
type: "azure.sdk.eventgrid.samples.cloudevent",
source: "/azure/sdk/eventgrid/samples/sendEventSample",
data: {
message: "this is a sample event"
}
}
]);
}

main().catch((err) => {
console.error("The sample encountered an error:", err);
});
46 changes: 46 additions & 0 deletions sdk/eventgrid/eventgrid/samples-dev/sendEventGridEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

/**
* @summary Send events to Event Grid using the Event Grid Schema.
* @azsdk-weight 2
*/

import { EventGridPublisherClient, AzureKeyCredential } from "@azure/eventgrid";
import * as dotenv from "dotenv";

// Load the .env file if it exists
dotenv.config();

// The URL of the endpoint of the Event Grid topic.
const endpoint = process.env["EVENT_GRID_EVENT_GRID_SCHEMA_ENDPOINT"] || "";

// You can find the access keys in the Azure portal.
// Navigate to Settings > Access keys in your Event Grid topic's menu blade to see both access keys (you may use either).
const accessKey = process.env["EVENT_GRID_EVENT_GRID_SCHEMA_API_KEY"] || "";

export async function main(): Promise<void> {
// Create the client used to publish events to the Event Grid Service
const client = new EventGridPublisherClient(
endpoint,
"EventGrid",
new AzureKeyCredential(accessKey)
);

// Send an event to the Event Grid Service, using the Event Grid schema.
// A random ID will be generated for this event, since one is not provided.
await client.send([
{
eventType: "Azure.SDK.Samples.CustomEvent",
subject: "azure/sdk/eventgrid/samples/sendEventSample",
dataVersion: "1.0",
data: {
message: "this is a sample event"
}
}
]);
}

main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Empty file.
54 changes: 0 additions & 54 deletions sdk/eventgrid/eventgrid/samples/javascript/README.md

This file was deleted.

34 changes: 0 additions & 34 deletions sdk/eventgrid/eventgrid/samples/javascript/package.json

This file was deleted.

6 changes: 0 additions & 6 deletions sdk/eventgrid/eventgrid/samples/javascript/sample.env

This file was deleted.

10 changes: 0 additions & 10 deletions sdk/eventgrid/eventgrid/samples/tsconfig.json

This file was deleted.

67 changes: 0 additions & 67 deletions sdk/eventgrid/eventgrid/samples/typescript/README.md

This file was deleted.

Loading

0 comments on commit fc7fc96

Please sign in to comment.