[Event Grid] Initial Track 2 Client (#10059)

This change updates the Event Grid client to follow the new Azure SDK Design guidelines.  In addition, it exposes support for sending and processing events in the Cloud Events format, which the previous SDK did not support.
This commit is contained in:
Matt Ellis 2020-09-04 17:07:34 -07:00 коммит произвёл GitHub
Родитель 89c6f1bf2b
Коммит 1dc72f5ecd
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
61 изменённых файлов: 8234 добавлений и 1694 удалений

Просмотреть файл

@ -22,6 +22,7 @@ dependencies:
'@rush-temp/eslint-plugin-azure-sdk': 'file:projects/eslint-plugin-azure-sdk.tgz'
'@rush-temp/event-hubs': 'file:projects/event-hubs.tgz'
'@rush-temp/event-processor-host': 'file:projects/event-processor-host.tgz'
'@rush-temp/eventgrid': 'file:projects/eventgrid.tgz'
'@rush-temp/eventhubs-checkpointstore-blob': 'file:projects/eventhubs-checkpointstore-blob.tgz'
'@rush-temp/identity': 'file:projects/identity.tgz'
'@rush-temp/keyvault-admin': 'file:projects/keyvault-admin.tgz'
@ -9236,6 +9237,67 @@ packages:
integrity: sha512-QytC/CjcRtJZwlPxvYKLJ91gtaNaw860njdrpQZv0Ka1ZHwZzMkFaJPV15kGYqYrwZSz4IcBaRec90e8fccqOw==
tarball: 'file:projects/event-processor-host.tgz'
version: 0.0.0
'file:projects/eventgrid.tgz':
dependencies:
'@azure/core-tracing': 1.0.0-preview.9
'@microsoft/api-extractor': 7.7.11
'@opentelemetry/api': 0.10.2
'@rollup/plugin-commonjs': 11.0.2_rollup@1.32.1
'@rollup/plugin-json': 4.1.0_rollup@1.32.1
'@rollup/plugin-multi-entry': 3.0.1_rollup@1.32.1
'@rollup/plugin-node-resolve': 8.1.0_rollup@1.32.1
'@rollup/plugin-replace': 2.3.3_rollup@1.32.1
'@types/chai': 4.2.11
'@types/chai-as-promised': 7.1.3
'@types/mocha': 7.0.2
'@types/node': 8.10.61
'@types/sinon': 9.0.4
'@types/uuid': 8.0.0
'@typescript-eslint/eslint-plugin': 2.34.0_3787943315ebc5ea524d5c102dc9e452
'@typescript-eslint/parser': 2.34.0_eslint@6.8.0+typescript@3.9.6
chai: 4.2.0
chai-as-promised: 7.1.1_chai@4.2.0
cross-env: 7.0.2
dotenv: 8.2.0
eslint: 6.8.0
eslint-config-prettier: 6.11.0_eslint@6.8.0
eslint-plugin-no-null: 1.0.2_eslint@6.8.0
eslint-plugin-no-only-tests: 2.4.0
eslint-plugin-promise: 4.2.1
karma: 5.1.1
karma-chrome-launcher: 3.1.0
karma-coverage: 2.0.2
karma-edge-launcher: 0.4.2_karma@5.1.1
karma-env-preprocessor: 0.1.1
karma-firefox-launcher: 1.3.0
karma-ie-launcher: 1.0.0_karma@5.1.1
karma-json-preprocessor: 0.3.3_karma@5.1.1
karma-json-to-file-reporter: 1.0.1
karma-junit-reporter: 2.0.1_karma@5.1.1
karma-mocha: 2.0.1
karma-mocha-reporter: 2.2.5_karma@5.1.1
karma-remap-istanbul: 0.6.0_karma@5.1.1
mocha: 7.2.0
mocha-junit-reporter: 1.23.3_mocha@7.2.0
nyc: 14.1.1
prettier: 1.19.1
rimraf: 3.0.2
rollup: 1.32.1
rollup-plugin-shim: 1.0.0
rollup-plugin-sourcemaps: 0.4.2_rollup@1.32.1
rollup-plugin-terser: 5.3.0_rollup@1.32.1
rollup-plugin-visualizer: 4.0.4_rollup@1.32.1
sinon: 9.0.2
source-map-support: 0.5.19
ts-node: 8.10.2_typescript@3.9.6
tslib: 2.0.0
typescript: 3.9.6
dev: false
name: '@rush-temp/eventgrid'
resolution:
integrity: sha512-JneUDGxCKVc2OBMRQ2oIOHtmnt6clWBwZBmG3eJlAzk+PkSNVr87URfrJJy3nkU28+TUkK3xHnHyU/bmys6nXw==
tarball: 'file:projects/eventgrid.tgz'
version: 0.0.0
'file:projects/eventhubs-checkpointstore-blob.tgz':
dependencies:
'@azure/event-hubs': 5.2.2
@ -9366,6 +9428,7 @@ packages:
'file:projects/keyvault-admin.tgz':
dependencies:
'@azure/core-tracing': 1.0.0-preview.9
'@microsoft/api-extractor': 7.7.11
'@opentelemetry/api': 0.10.2
'@rollup/plugin-commonjs': 11.0.2_rollup@1.32.1
'@rollup/plugin-json': 4.1.0_rollup@1.32.1
@ -9395,7 +9458,7 @@ packages:
dev: false
name: '@rush-temp/keyvault-admin'
resolution:
integrity: sha512-zS+QZh+wHSnZhRTWpQcTgPlHzbm+Djb+pSL8tT6dTBo3cV1xFWHeYaenVT7gjQWgAJ41PREmPmSjBsLHnwSI7g==
integrity: sha512-eJjxCTqMLb7tC0iSwnDg/sXQpv/89fgdgtuMTfFMnx7nM+30n/L8qTwXhBQs87UucOKDQI3qSw8DD74fs7xGvg==
tarball: 'file:projects/keyvault-admin.tgz'
version: 0.0.0
'file:projects/keyvault-certificates.tgz':
@ -10512,6 +10575,7 @@ specifiers:
'@rush-temp/eslint-plugin-azure-sdk': 'file:./projects/eslint-plugin-azure-sdk.tgz'
'@rush-temp/event-hubs': 'file:./projects/event-hubs.tgz'
'@rush-temp/event-processor-host': 'file:./projects/event-processor-host.tgz'
'@rush-temp/eventgrid': 'file:./projects/eventgrid.tgz'
'@rush-temp/eventhubs-checkpointstore-blob': 'file:./projects/eventhubs-checkpointstore-blob.tgz'
'@rush-temp/identity': 'file:./projects/identity.tgz'
'@rush-temp/keyvault-admin': 'file:./projects/keyvault-admin.tgz'

Просмотреть файл

@ -60,6 +60,10 @@
"name": "cosmos",
"path": "sdk/cosmosdb/cosmos"
},
{
"name": "eventgrid",
"path": "sdk\\eventgrid\\eventgrid"
},
{
"name": "event-hubs",
"path": "sdk/eventhub/event-hubs"

Просмотреть файл

@ -422,6 +422,11 @@
"projectFolder": "common/tools/dev-tool",
"versionPolicyName": "utility"
},
{
"packageName": "@azure/eventgrid",
"projectFolder": "sdk/eventgrid/eventgrid",
"versionPolicyName": "client"
},
{
"packageName": "@azure/event-hubs",
"projectFolder": "sdk/eventhub/event-hubs",

30
sdk/eventgrid/ci.yml Normal file
Просмотреть файл

@ -0,0 +1,30 @@
# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file.
trigger:
branches:
include:
- master
- release/*
- hotfix/*
paths:
include:
- sdk/eventgrid/
pr:
branches:
include:
- master
- feature/*
- release/*
- hotfix/*
paths:
include:
- sdk/eventgrid/
extends:
template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml
parameters:
ServiceDirectory: eventgrid
Artifacts:
- name: azure-eventgrid
safeName: azureeventgrid

Просмотреть файл

@ -0,0 +1,4 @@
{
"plugins": ["@azure/azure-sdk"],
"extends": ["plugin:@azure/azure-sdk/azure-sdk-base"]
}

Просмотреть файл

@ -0,0 +1,14 @@
{
"include": [
"dist-esm/src/**/*.js"
],
"exclude": [
"**/*.d.ts",
"dist-esm/src/generated/*"
],
"exclude-after-remap": false,
"sourceMap": true,
"produce-source-map": true,
"instrument": true,
"all": true
}

76
sdk/eventgrid/eventgrid/.vscode/launch.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,76 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Javascript Samples",
"program": "${workspaceFolder}/samples/javascript/basic.js",
"preLaunchTask": "npm: build:js-samples"
},
{
"type": "node",
"request": "launch",
"name": "Debug Typescript Samples",
"program": "${workspaceFolder}/samples/typescript/basic.ts",
"preLaunchTask": "npm: build:ts-samples",
"outFiles": ["${workspaceFolder}/dist-esm/samples/typescript/*.js"]
},
{
"type": "node",
"request": "launch",
"name": "Current TS File",
"args": [
"${fileBasename}"
],
"runtimeArgs": [
"--nolazy",
"-r",
"ts-node/register"
],
"env": { "TS_NODE_COMPILER_OPTIONS": "{\"module\": \"commonjs\"}" },
"cwd": "${fileDirname}",
"sourceMaps": true,
"protocol": "inspector"
},
{
"type": "node",
"request": "launch",
"name": "Debug Mocha Test [Without Rollup]",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-r",
"ts-node/register",
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/test/*.spec.ts",
"${workspaceFolder}/test/node/*.spec.ts"
],
"env": { "TS_NODE_COMPILER_OPTIONS": "{\"module\": \"commonjs\"}" },
"envFile": "${workspaceFolder}/.env",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"protocol": "inspector"
},
{
"type": "node",
"request": "launch",
"name": "Debug Unit Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"tdd",
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/dist-test/index.node.js"
],
"internalConsoleOptions": "openOnSessionStart",
"preLaunchTask": "npm: build:test"
}
]
}

26
sdk/eventgrid/eventgrid/.vscode/settings.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,26 @@
{
"editor.detectIndentation": false,
"editor.formatOnSave": true,
"editor.insertSpaces": true,
"editor.tabSize": 2,
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,
"javascript.preferences.quoteStyle": "double",
"typescript.preferences.quoteStyle": "double",
"search.exclude": {
"test-results*.xml": true,
"**/temp/*": true,
"**/dist/*": true,
"**/*.map": true,
"**/dist-*/*": true,
"**/test-dist/*": true,
"**/node_modules": true,
"**/bower_components": true,
"**/*.code-search": true,
"**/types/*": true,
"**/coverage/*": true,
"**/*.d.ts": true,
"**/test-browser/*": true
},
"typescript.tsdk": "..\\..\\core\\core-http\\node_modules\\typescript\\lib"
}

Просмотреть файл

@ -0,0 +1,7 @@
# Release History
## 3.0.0-beta.1 (2020-09-08)
- This release is a preview of our efforts to create a client library that is user friendly and
idiomatic to the JavaScript ecosystem. The reasons for most of the changes in this update can be found in the
[Azure SDK Design Guidelines for TypeScript](https://azuresdkspecs.z5.web.core.windows.net/TypeScriptSpec.html).

Просмотреть файл

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2019 Microsoft
Copyright (c) 2020 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

Просмотреть файл

@ -1,119 +1,260 @@
## Azure EventGridClient SDK for JavaScript
# Azure Event Grid client library for JavaScript
This package contains an isomorphic SDK for EventGridClient.
[Azure Event Grid](https://azure.microsoft.com/en-us/services/event-grid/) is a cloud-based service that provides reliable event delivery at massive scale.
Use the client library to:
- Send events to Event Grid using either the Event Grid, Cloud Events 1.0 schemas, or a custom schema
- Decode and process events which were delivered to an Event Grid handler
- Generate Shared Access Signatures for Event Grid topics
[Source code](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/eventgrid/eventgrid/) |
[Package (NPM)](https://www.npmjs.com/package/@azure/eventgrid) |
[API reference documentation](https://aka.ms/azsdk-js-eventgrid-ref-docs) |
[Product documentation](https://docs.microsoft.com/en-us/azure/event-grid/) |
[Samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventgrid/eventgrid/samples)
## Getting started
### Currently supported environments
- Node.js version 6.x.x or higher
- Node.js version 8.x.x or higher
- Browser JavaScript
- Apple Safari: latest two versions
- Google Chrome: latest two versions
- Microsoft Edge: all supported versions
- Mozilla FireFox: latest two versions
### How to Install
### Prerequisites
- An [Azure subscription][azure_sub].
- An existing [Event Grid][event_grid] Topic or Domain. If you need to create the resource, you can use the [Azure Portal][azure_portal] or [Azure CLI][azure_cli].
If you use the Azure CLI, replace `<your-resource-group-name>` and `<your-resource-name>` with your own unique names:
#### Create an Event Grid Topic
```bash
az eventgrid topic create --location <location> --resource-group <your-resource-group-name> --name <your-resource-name>
```
#### Create an Event Grid Domain
```bash
az eventgrid domain create --location <location> --resource-group <your-resource-group-name> --name <your-resource-name>
```
### Install the `@azure/eventgrid` package
Install the Azure Event Grid client library for JavaScript with `npm`:
```bash
npm install @azure/eventgrid
```
### How to use
### Create and authenticate a `EventGridPublisherClient`
#### nodejs - Authentication, client creation and publishEvents as an example written in TypeScript.
To create a client object to access the Event Grid API, you will need the `endpoint` of your Event Grid topic and a `credential`. The Event Grid client can use either an Access Key or Shared Access Signature (SAS) created from an access key.
##### Install @azure/ms-rest-nodeauth
- Please install minimum version of `"@azure/ms-rest-nodeauth": "^3.0.0"`.
```bash
npm install @azure/ms-rest-nodeauth@"^3.0.0"
```
##### Sample code
```typescript
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";
import { EventGridClient, EventGridModels, EventGridMappers } from "@azure/eventgrid";
const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"];
msRestNodeAuth.interactiveLogin().then((creds) => {
const client = new EventGridClient(creds, subscriptionId);
const topicHostname = "testtopicHostname";
const events = [{
id: "testid",
topic: "testtopic",
subject: "testsubject",
data: {},
eventType: "testeventType",
eventTime: new Date().toISOString(),
dataVersion: "testdataVersion"
}];
client.publishEvents(topicHostname, events).then((result) => {
console.log("The result is:");
console.log(result);
});
}).catch((err) => {
console.error(err);
});
```
#### browser - Authentication, client creation and publishEvents as an example written in JavaScript.
##### Install @azure/ms-rest-browserauth
You can find the endpoint for your Event Grid topic either in the [Azure Portal][azure_portal] or by using the [Azure CLI][azure_cli] snippet below:
```bash
npm install @azure/ms-rest-browserauth
az eventgrid topic show --name <your-resource-name> --resource-group <your-resource-group-name> --query "endpoint"
```
##### Sample code
#### Using an Access Key
See https://github.com/Azure/ms-rest-browserauth to learn how to authenticate to Azure in the browser.
Use the [Azure Portal][azure_portal] to browse to your Event Grid resource and retrieve an Access Key, or use the [Azure CLI][azure_cli] snippet below:
- index.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>@azure/eventgrid sample</title>
<script src="node_modules/@azure/ms-rest-js/dist/msRest.browser.js"></script>
<script src="node_modules/@azure/ms-rest-azure-js/dist/msRestAzure.js"></script>
<script src="node_modules/@azure/ms-rest-browserauth/dist/msAuth.js"></script>
<script src="node_modules/@azure/eventgrid/dist/eventgrid.js"></script>
<script type="text/javascript">
const subscriptionId = "<Subscription_Id>";
const authManager = new msAuth.AuthManager({
clientId: "<client id for your Azure AD app>",
tenant: "<optional tenant for your organization>"
});
authManager.finalizeLogin().then((res) => {
if (!res.isLoggedIn) {
// may cause redirects
authManager.login();
```bash
az eventgrid topic key list --resource-group <your-resource-group-name> --name <your-event-grid-topic-name>
```
Once you have an API key and endpoint, you can use the `AzureKeyCredential` class to authenticate the client as follows:
```js
const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid");
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<Access Key>"));
```
#### Using a SAS Token
Like an access key, a SAS token allows access to sending events to an Event Grid topic. Unlike an access key, which can be used until it is regenerated, a SAS token has an experation time, at which point it is no longer valid. To use a SAS token for authentication, use the `EventGridSharedAccesSignatureCredential` as follows:
```js
const {
EventGridPublisherClient,
EventGridSharedAccessSignatureCredential
} = require("@azure/eventgrid");
const client = new EventGridPublisherClient(
"<endpoint>",
new EventGridSharedAccessSignatureCredential("<SAS Token>")
);
```
You can generate a SAS token by using the `generateSharedAccessSigniture` function.
```js
const { generateSharedAccessSignature, AzureKeyCredential } = require("@azure/eventgrid");
// Create a SAS Token which expires on 2020-01-01 at Midnight.
const token = generateSharedAccessSignature(
"<endpoint>",
new AzureKeyCredential("<API key>"),
new Date("2020-01-01T00:00:00")
);
```
## Key concepts
### EventGridPublisherClient
`EventGridPublisherClient` is used sending events to an Event Grid Topic or an Event Grid Domain.
### Event Schemas
Event Grid supports multiple schemas for encoding events. When a Custom Topic or Domain is created, you specify the schema that will be used when publishing events. While you may configure your topic to use a _custom schema_ it is more common to use the already defined _Event Grid schema_ or _CloudEvents 1.0 schema_. [CloudEvents](https://cloudevents.io/) is a Cloud Native Computing Foundation project which produces a specification for describing event data in a common way. Regardless of what schmea your topic or domain is configured to use, `EventGridPublisherClient` will be used to publish events to it. However, you must use the correct method for publishing:
| Schema | Publishing Method |
| ------------ | --------------------- |
| Event Grid | `publishEvents` |
| Cloud Events | `publishCloudEvents` |
| Custom | `publishCustomEvents` |
Using the wrong method will result in an error from the service and your events will not be published.
### EventGridConsumer
Events delivered to consumers by Event Grid are delivered as JSON. Depending on the type of consumer being delivered to, the Event Grid service may deliver one or more events as part of a single payload. While these events may be deserialized using normal JavaScript methods like `JSON.parse`, this library offers a helper type for deserializing events, called `EventGridConsumer`.
Compared with using `JSON.parse` directly, `EventGridConsumer` does some additional conversions while deserializng events:
1. `EventGridConsumer` validates that the required properties of an event are present and are the right types.
2. `EventGridConsumer` converts the event time property into a JavaScript `Date` object.
3. When using Cloud Events, binary data may be used for an event's data property (by using `Uint8Array`). When the event is sent through Event Grid, it is encoded in Base 64. `EventGridConsumer` will decode this data back into an instance of `Uint8Array`.
4. When deserilizing a _System Event_ (an event generated by another Azure service), `EventGridConsumer` will do additional conversions so that the `data` object matches the corresponding interface which describes its data. When using TypeScript, these interfaces ensure you have strong typing when access properties of the data object for a system event.
When creating an instance of `EventGridConsumer` you may supply custom deserializers that are used to further convert the `data` object.
## Examples
### Publish a Custom Event to an Event Grid Topic
```js
const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid");
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<API key>"));
await client.sendEvents([
{
eventType: "Azure.Sdk.SampleEvent",
subject: "Event Subject",
dataVersion: "1.0",
data: {
hello: "world"
}
const client = new Azure.Eventgrid.EventGridClient(res.creds, subscriptionId);
const topicHostname = "testtopicHostname";
const events = [{
id: "testid",
topic: "testtopic",
subject: "testsubject",
data: {},
eventType: "testeventType",
eventTime: new Date().toISOString(),
dataVersion: "testdataVersion"
}];
client.publishEvents(topicHostname, events).then((result) => {
console.log("The result is:");
console.log(result);
}).catch((err) => {
console.log("An error occurred:");
console.error(err);
});
});
</script>
</head>
<body></body>
</html>
}
]);
```
### Publish a Custom Event to a Topic in an Event Grid Domain
Publishing events to an Event Grid Domain is similar to publish to an Event Grid Topic, except that when using the Event Grid schema for events, you must include the `topic` property. When publishing events in the Cloud Events 1.0 schema, the required `source` property is used as the name of the topic in the domain to publish to:
```js
const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid");
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<API key>"));
await client.sendEvents([
{
topic: "my-sample-topic",
eventType: "Azure.Sdk.SampleEvent",
subject: "Event Subject",
dataVersion: "1.0",
data: {
hello: "world"
}
}
]);
```
### Deserializing an Event
`EventGridConsumer` can be used to deserialize events delivered by Event Grid. When deserializing an event, you need to know the schema used to deliver the event. In this example we have events being delivered to an Azure Service Bus Topic in the Cloud Events schema. Using the Service Bus SDK we can recieve these events from the Service Bus Topic and then deserialize them using `EventGridConsumer` and use `isSystemEvent` to detect what type of events they are.
```js
const { ServiceBusClient } = require("@azure/service-bus");
const { DefaultAzureCredential } = require("@azure/identity");
const { EventGridConsumer, isSystemEvent } = require("@azure/eventgrid");
const client = new ServiceBusClient("<service bus hostname>", new DefaultAzureCredential());
const receiver = client.createReceiver("<queue name>", "peekLock");
const consumer = new EventGridConsumer();
async function processMessage(message) {
// When delivering to a Service Bus Queue or Topic, EventGrid delivers a single event per message.
// so we just pluck the first one.
const event = (await consumer.decodeCloudEvents(message.body))[0];
if (isSystemEvent("Microsoft.ContainerRegistry.ImagePushed", event)) {
console.log(
`${event.time}: Container Registry Image Pushed event for image ${event.data.target.repository}:${event.data.target.tag}`
);
} else if (isSystemEvent("Microsoft.ContainerRegistry.ImageDeleted", event)) {
console.log(
`${event.time}: Container Registry Image Deleted event for repository ${event.data.target.repository}`
);
}
await message.complete();
}
console.log("starting receiver");
receiver.subscribe({
processError: async (err) => {
console.error(err);
},
processMessage
});
```
## Troubleshooting
### Enable logs
You can set the following environment variable to get the debug logging output when using this library.
- Getting debug logs from the Azure Event Grid client library
```bash
export AZURE_LOG_LEVEL=verbose
```
For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/core/logger).
## Next steps
Please take a look at the
[samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventgrid/eventgrid/samples)
directory for detailed examples on how to use this library.
## Contributing
If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/master/CONTRIBUTING.md) to learn more about how to build and test the code.
## Related projects
- [Microsoft Azure SDK for Javascript](https://github.com/Azure/azure-sdk-for-js)
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js/sdk/eventgrid/eventgrid/README.png)
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Feventgrid%2Feventgrid%2FREADME.png)
[azure_cli]: https://docs.microsoft.com/cli/azure
[azure_sub]: https://azure.microsoft.com/free/
[event_grid]: https://docs.microsoft.com/en-us/azure/event-grid
[azure_portal]: https://portal.azure.com

Просмотреть файл

@ -0,0 +1,31 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"mainEntryPointFilePath": "types/src/index.d.ts",
"docModel": {
"enabled": false
},
"apiReport": {
"enabled": true,
"reportFolder": "./review"
},
"dtsRollup": {
"enabled": true,
"untrimmedFilePath": "",
"publicTrimmedFilePath": "./types/eventgrid.d.ts"
},
"messages": {
"tsdocMessageReporting": {
"default": {
"logLevel": "none"
}
},
"extractorMessageReporting": {
"ae-missing-release-tag": {
"logLevel": "none"
},
"ae-unresolved-link": {
"logLevel": "none"
}
}
}
}

Просмотреть файл

@ -0,0 +1,148 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// https://github.com/karma-runner/karma-chrome-launcher
process.env.CHROME_BIN = require("puppeteer").executablePath();
require("dotenv").config();
const {
jsonRecordingFilterFunction,
isPlaybackMode,
isSoftRecordMode,
isRecordMode
} = require("@azure/test-utils-recorder");
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: "./",
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ["mocha"],
plugins: [
"karma-mocha",
"karma-mocha-reporter",
"karma-chrome-launcher",
"karma-edge-launcher",
"karma-firefox-launcher",
"karma-ie-launcher",
"karma-env-preprocessor",
"karma-coverage",
"karma-remap-istanbul",
"karma-junit-reporter",
"karma-json-to-file-reporter",
"karma-json-preprocessor"
],
// list of files / patterns to load in the browser
files: ["dist-test/index.browser.js"].concat(
isPlaybackMode() || isSoftRecordMode() ? ["recordings/browsers/**/*.json"] : []
),
// list of files / patterns to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"**/*.js": ["env"],
"recordings/browsers/**/*.json": ["json"]
// IMPORTANT: COMMENT following line if you want to debug in your browsers!!
// Preprocess source file to calculate code coverage, however this will make source file unreadable
// "test-browser/index.js": ["coverage"]
},
envPreprocessor: [
"TEST_MODE",
"EVENT_GRID_EVENT_GRID_SCHEMA_ENDPOINT",
"EVENT_GRID_EVENT_GRID_SCHEMA_API_KEY",
"EVENT_GRID_CUSTOM_SCHEMA_ENDPOINT",
"EVENT_GRID_CUSTOM_SCHEMA_API_KEY",
"EVENT_GRID_CLOUD_EVENT_SCHEMA_ENDPOINT",
"EVENT_GRID_CLOUD_EVENT_SCHEMA_API_KEY",
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ["mocha", "coverage", "karma-remap-istanbul", "junit", "json-to-file"],
coverageReporter: {
// specify a common output directory
dir: "coverage-browser/",
reporters: [{ type: "json", subdir: ".", file: "coverage.json" }]
},
remapIstanbulReporter: {
src: "coverage-browser/coverage.json",
reports: {
lcovonly: "coverage-browser/lcov.info",
html: "coverage-browser/html/report",
"text-summary": null,
cobertura: "./coverage-browser/cobertura-coverage.xml"
}
},
junitReporter: {
outputDir: "", // results will be saved as $outputDir/$browserName.xml
outputFile: "test-results.browser.xml", // if included, results will be saved as $outputDir/$browserName/$outputFile
suite: "", // suite will become the package name attribute in xml testsuite element
useBrowserName: false, // add browser name to report and classes names
nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element
classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element
properties: {} // key value pair of properties to add to the <properties> section of the report
},
jsonToFileReporter: {
filter: jsonRecordingFilterFunction,
outputPath: "."
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// --no-sandbox allows our tests to run in Linux without having to change the system.
// --disable-web-security allows us to authenticate from the browser without having to write tests using interactive auth, which would be far more complex.
browsers: ["ChromeHeadlessNoSandbox"],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: "ChromeHeadless",
flags: ["--no-sandbox", "--disable-web-security"]
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: 1,
browserNoActivityTimeout: 600000,
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 3,
browserConsoleLogOptions: {
terminal: !isRecordMode()
},
client: {
mocha: {
// change Karma's debug.html to the mocha web reporter
reporter: "html",
timeout: "600000"
}
}
});
};

Просмотреть файл

@ -1,13 +1,9 @@
{
"name": "@azure/eventgrid",
"sdk-type": "client",
"author": "Microsoft Corporation",
"description": "EventGridClient Library with typescript type definitions for node.js and browser.",
"version": "2.0.0",
"dependencies": {
"@azure/ms-rest-azure-js": "^2.0.1",
"@azure/ms-rest-js": "^2.0.4",
"tslib": "^1.10.0"
},
"description": "An isomorphic client library for the Azure Event Grid service.",
"version": "3.0.0-beta.1",
"keywords": [
"node",
"azure",
@ -16,16 +12,9 @@
"isomorphic"
],
"license": "MIT",
"main": "./dist/eventgrid.js",
"module": "./esm/eventGridClient.js",
"types": "./esm/eventGridClient.d.ts",
"devDependencies": {
"typescript": "^3.5.3",
"rollup": "^1.18.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-sourcemaps": "^0.4.2",
"uglify-js": "^3.6.0"
},
"main": "./dist/src/index.js",
"module": "./dist-esm/src/index.js",
"types": "./types/eventgrid.d.ts",
"homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventgrid/eventgrid",
"repository": {
"type": "git",
@ -35,24 +24,118 @@
"url": "https://github.com/Azure/azure-sdk-for-js/issues"
},
"files": [
"dist/**/*.js",
"dist/**/*.js.map",
"dist/**/*.d.ts",
"dist/**/*.d.ts.map",
"esm/**/*.js",
"esm/**/*.js.map",
"esm/**/*.d.ts",
"esm/**/*.d.ts.map",
"src/**/*.ts",
"dist/",
"dist-esm/src/",
"types/eventgrid.d.ts",
"README.md",
"rollup.config.js",
"tsconfig.json"
"LICENSE"
],
"//metadata": {
"constantPaths": [
{
"path": "src/generated/generatedClientContext.ts",
"prefix": "packageVersion"
},
{
"path": "src/constants.ts",
"prefix": "SDK_VERSION"
}
]
},
"browser": {
"./dist-esm/src/cryptoHelpers.js": "./dist-esm/src/cryptoHelpers.browser.js"
},
"scripts": {
"build": "tsc && rollup -c rollup.config.js && npm run minify",
"minify": "uglifyjs -c -m --comments --source-map \"content='./dist/eventgrid.js.map'\" -o ./dist/eventgrid.min.js ./dist/eventgrid.js",
"prepack": "npm install && npm run build"
"audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit",
"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": "node ../../../common/scripts/prep-samples.js && cd samples && tsc -p .",
"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 \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
"clean": "rimraf dist dist-browser dist-esm test-dist temp types *.tgz *.log",
"execute:js-samples": "node ../../../common/scripts/run-samples.js samples/javascript/",
"execute:ts-samples": "node ../../../common/scripts/run-samples.js samples/typescript/dist/samples/typescript/src/",
"execute:samples": "npm run build:samples && npm run execute:js-samples && npm run execute:ts-samples",
"extract-api": "tsc -p . && api-extractor run --local",
"format": "prettier --write --config ../../.prettierrc.json \"src/**/*.ts\" \"test/**/*.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",
"lint:fix": "eslint \"src/**/*.ts\" --fix --fix-type [problem,suggestion]",
"lint": "eslint src --ext .ts -f html -o textAnalytics-lintReport.html",
"pack": "npm pack 2>&1",
"prebuild": "npm run clean",
"test:browser": "npm run clean && npm run build:test && npm run unit-test:browser",
"test:node": "npm run clean && npm run build:test && npm run unit-test:node",
"test": "npm run clean && npm run build:test && npm run unit-test",
"unit-test:browser": "karma start --single-run",
"unit-test:node": "mocha --require source-map-support/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 1200000 --full-trace dist-test/index.node.js",
"unit-test": "npm run unit-test:node && npm run unit-test:browser"
},
"sideEffects": false,
"autoPublish": true
"autoPublish": false,
"dependencies": {
"@azure/core-auth": "^1.1.3",
"@azure/core-http": "^1.1.6",
"@azure/core-tracing": "1.0.0-preview.9",
"@azure/logger": "^1.0.0",
"@opentelemetry/api": "^0.10.2",
"tslib": "^2.0.0"
},
"devDependencies": {
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@azure/test-utils-recorder": "^1.0.0",
"@microsoft/api-extractor": "7.7.11",
"@rollup/plugin-commonjs": "11.0.2",
"@rollup/plugin-json": "^4.0.0",
"@rollup/plugin-multi-entry": "^3.0.0",
"@rollup/plugin-node-resolve": "^8.0.0",
"@rollup/plugin-replace": "^2.2.0",
"@types/chai": "^4.1.6",
"@types/chai-as-promised": "^7.1.0",
"@types/mocha": "^7.0.2",
"@types/node": "^8.0.0",
"@types/sinon": "^9.0.4",
"@types/uuid": "^8.0.0",
"@typescript-eslint/eslint-plugin": "^2.0.0",
"@typescript-eslint/parser": "^2.0.0",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"cross-env": "^7.0.2",
"dotenv": "^8.2.0",
"eslint": "^6.1.0",
"eslint-config-prettier": "^6.0.0",
"eslint-plugin-no-null": "^1.0.2",
"eslint-plugin-no-only-tests": "^2.3.0",
"eslint-plugin-promise": "^4.1.1",
"karma": "^5.1.0",
"karma-chrome-launcher": "^3.0.0",
"karma-coverage": "^2.0.0",
"karma-edge-launcher": "^0.4.2",
"karma-env-preprocessor": "^0.1.1",
"karma-firefox-launcher": "^1.1.0",
"karma-ie-launcher": "^1.0.0",
"karma-json-preprocessor": "^0.3.3",
"karma-json-to-file-reporter": "^1.0.1",
"karma-junit-reporter": "^2.0.1",
"karma-mocha": "^2.0.1",
"karma-mocha-reporter": "^2.2.5",
"karma-remap-istanbul": "^0.6.0",
"mocha": "^7.1.1",
"mocha-junit-reporter": "^1.18.0",
"nyc": "^14.0.0",
"prettier": "^1.16.4",
"rimraf": "^3.0.0",
"rollup": "^1.16.3",
"rollup-plugin-shim": "^1.0.0",
"rollup-plugin-sourcemaps": "^0.4.2",
"rollup-plugin-terser": "^5.1.1",
"rollup-plugin-visualizer": "^4.0.4",
"sinon": "^9.0.2",
"source-map-support": "^0.5.9",
"ts-node": "^8.3.0",
"typescript": "~3.9.3"
}
}

Просмотреть файл

@ -0,0 +1,32 @@
{
"recordings": [
{
"method": "POST",
"url": "https://endpoint/api/events",
"query": {
"api-version": "2018-01-01"
},
"requestBody": "[{\"id\":\"cloudSingleEventId159588374669809673\",\"source\":\"/earth/unitedstates/washington/kirkland/finnhill\",\"data\":{\"hello\":\"world\"},\"type\":\"Azure.Sdk.TestEvent1\",\"time\":\"2020-07-27T21:02:26.698Z\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\"}]",
"status": 200,
"response": "",
"responseHeaders": {
"api-supported-versions": "2018-01-01",
"content-length": "0",
"date": "Mon, 27 Jul 2020 21:02:26 GMT",
"server": "Microsoft-HTTPAPI/2.0",
"status": "200",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"x-ms-request-id": "46a799c7-f453-4894-9b7e-e6fd93259622"
}
}
],
"uniqueTestInfo": {
"uniqueName": {
"cloudSingleEventId": "cloudSingleEventId159588374669809673"
},
"newDate": {
"cloudSingleEventDate": "2020-07-27T21:02:26.698Z"
}
},
"hash": "7fe25ee020ac364dae32ce81a81c7c3f"
}

Просмотреть файл

@ -0,0 +1,34 @@
{
"recordings": [
{
"method": "POST",
"url": "https://endpoint/api/events",
"query": {
"api-version": "2018-01-01"
},
"requestBody": "[{\"id\":\"cloudMultiEventId1159588374680705635\",\"source\":\"/earth/unitedstates/washington/kirkland/finnhill\",\"data\":{\"hello\":\"world\"},\"type\":\"Azure.Sdk.TestEvent1\",\"time\":\"2020-07-27T21:02:26.807Z\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"Multiple 1\"},{\"id\":\"cloudMultiEventId2159588374680700679\",\"source\":\"/earth/unitedstates/washington/kirkland/finnhill\",\"data\":{\"hello\":\"world\"},\"type\":\"Azure.Sdk.TestEvent1\",\"time\":\"2020-07-27T21:02:26.807Z\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"Multiple 2\"}]",
"status": 200,
"response": "",
"responseHeaders": {
"api-supported-versions": "2018-01-01",
"content-length": "0",
"date": "Mon, 27 Jul 2020 21:02:26 GMT",
"server": "Microsoft-HTTPAPI/2.0",
"status": "200",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"x-ms-request-id": "5883a20b-ce78-4928-afb8-bde068f61fb5"
}
}
],
"uniqueTestInfo": {
"uniqueName": {
"cloudMultiEventId1": "cloudMultiEventId1159588374680705635",
"cloudMultiEventId2": "cloudMultiEventId2159588374680700679"
},
"newDate": {
"cloudMultiEventDate1": "2020-07-27T21:02:26.807Z",
"cloudMultiEventDate2": "2020-07-27T21:02:26.807Z"
}
},
"hash": "799392d36931d99dc2c24d3db67fcb0b"
}

Просмотреть файл

@ -0,0 +1,28 @@
{
"recordings": [
{
"method": "POST",
"url": "https://endpoint/api/events",
"query": {
"api-version": "2018-01-01"
},
"requestBody": "[{\"ver\":\"1.0\",\"typ\":\"Azure.Sdk.TestEvent1\",\"sub\":\"Single\",\"payload\":{\"hello\":\"world\"}}]",
"status": 200,
"response": "",
"responseHeaders": {
"api-supported-versions": "2018-01-01",
"content-length": "0",
"date": "Mon, 27 Jul 2020 21:02:26 GMT",
"server": "Microsoft-HTTPAPI/2.0",
"status": "200",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"x-ms-request-id": "e9595ef6-2387-4362-9573-9a2189e74b7d"
}
}
],
"uniqueTestInfo": {
"uniqueName": {},
"newDate": {}
},
"hash": "3aa867d763b256df1511358d9616f18f"
}

Просмотреть файл

@ -0,0 +1,28 @@
{
"recordings": [
{
"method": "POST",
"url": "https://endpoint/api/events",
"query": {
"api-version": "2018-01-01"
},
"requestBody": "[{\"ver\":\"1.0\",\"typ\":\"Azure.Sdk.TestEvent1\",\"sub\":\"Multiple 1\",\"payload\":{\"hello\":\"world\"}},{\"ver\":\"1.0\",\"typ\":\"Azure.Sdk.TestEvent1\",\"sub\":\"Multiple 2\",\"payload\":{\"hello\":\"world\"}}]",
"status": 200,
"response": "",
"responseHeaders": {
"api-supported-versions": "2018-01-01",
"content-length": "0",
"date": "Mon, 27 Jul 2020 21:02:26 GMT",
"server": "Microsoft-HTTPAPI/2.0",
"status": "200",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"x-ms-request-id": "a2b97d35-f1aa-4033-9886-e6907c7d6769"
}
}
],
"uniqueTestInfo": {
"uniqueName": {},
"newDate": {}
},
"hash": "1cfb052616732940934c2dfe9e0f6713"
}

Просмотреть файл

@ -0,0 +1,32 @@
{
"recordings": [
{
"method": "POST",
"url": "https://endpoint/api/events",
"query": {
"api-version": "2018-01-01"
},
"requestBody": "[{\"id\":\"singleEventId159588374414604202\",\"subject\":\"Single 1\",\"data\":{\"hello\":\"world\"},\"eventType\":\"Azure.Sdk.TestEvent1\",\"eventTime\":\"2020-07-27T21:02:24.145Z\",\"dataVersion\":\"1.0\"}]",
"status": 200,
"response": "",
"responseHeaders": {
"api-supported-versions": "2018-01-01",
"content-length": "0",
"date": "Mon, 27 Jul 2020 21:02:26 GMT",
"server": "Microsoft-HTTPAPI/2.0",
"status": "200",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"x-ms-request-id": "6b4ec1fb-b123-4406-ba01-4fd7c70f4ac0"
}
}
],
"uniqueTestInfo": {
"uniqueName": {
"singleEventId": "singleEventId159588374414604202"
},
"newDate": {
"singleEventDate": "2020-07-27T21:02:24.145Z"
}
},
"hash": "9b44e18369316233af4458904ca8ae09"
}

Просмотреть файл

@ -0,0 +1,34 @@
{
"recordings": [
{
"method": "POST",
"url": "https://endpoint/api/events",
"query": {
"api-version": "2018-01-01"
},
"requestBody": "[{\"id\":\"multiEventId1159588374666206734\",\"subject\":\"Multiple 1\",\"data\":{\"hello\":\"world\"},\"eventType\":\"Azure.Sdk.TestEvent1\",\"eventTime\":\"2020-07-27T21:02:26.662Z\",\"dataVersion\":\"1.0\"},{\"id\":\"multiEventId2159588374666206405\",\"subject\":\"Multiple 2\",\"data\":{\"hello\":\"world\"},\"eventType\":\"Azure.Sdk.TestEvent1\",\"eventTime\":\"2020-07-27T21:02:26.662Z\",\"dataVersion\":\"1.0\"}]",
"status": 200,
"response": "",
"responseHeaders": {
"api-supported-versions": "2018-01-01",
"content-length": "0",
"date": "Mon, 27 Jul 2020 21:02:26 GMT",
"server": "Microsoft-HTTPAPI/2.0",
"status": "200",
"strict-transport-security": "max-age=31536000; includeSubDomains",
"x-ms-request-id": "e8eb4406-e3e9-4f10-9f25-31ebd5c4e48b"
}
}
],
"uniqueTestInfo": {
"uniqueName": {
"multiEventId1": "multiEventId1159588374666206734",
"multiEventId2": "multiEventId2159588374666206405"
},
"newDate": {
"multiEventDate1": "2020-07-27T21:02:26.662Z",
"multiEventDate2": "2020-07-27T21:02:26.662Z"
}
},
"hash": "a1eefb69b1513dc523f50ee66055787d"
}

Просмотреть файл

@ -0,0 +1,23 @@
let nock = require('nock');
module.exports.hash = "b15b1edb6fd215ff27f66c70053afbb8";
module.exports.testInfo = {"uniqueName":{"cloudSingleEventId":"cloudSingleEventId159588373652209687"},"newDate":{"cloudSingleEventDate":"2020-07-27T21:02:16.522Z"}}
nock('https://endpoint', {"encodedQueryParams":true})
.post('/api/events', [{"id":"cloudSingleEventId159588373652209687","source":"/earth/unitedstates/washington/kirkland/finnhill","data":{"hello":"world"},"type":"Azure.Sdk.TestEvent1","time":"2020-07-27T21:02:16.522Z","specversion":"1.0","datacontenttype":"application/json"}])
.query(true)
.reply(200, "", [
'Content-Length',
'0',
'Server',
'Microsoft-HTTPAPI/2.0',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains',
'api-supported-versions',
'2018-01-01',
'x-ms-request-id',
'05f88f8f-bd50-41d7-b56c-394c1eeebe1f',
'Date',
'Mon, 27 Jul 2020 21:02:16 GMT'
]);

Просмотреть файл

@ -0,0 +1,23 @@
let nock = require('nock');
module.exports.hash = "cefc29910fbb6c53981faf8430a3521b";
module.exports.testInfo = {"uniqueName":{"cloudMultiEventId1":"cloudMultiEventId1159588373674007628","cloudMultiEventId2":"cloudMultiEventId2159588373674005416"},"newDate":{"cloudMultiEventDate1":"2020-07-27T21:02:16.740Z","cloudMultiEventDate2":"2020-07-27T21:02:16.740Z"}}
nock('https://endpoint', {"encodedQueryParams":true})
.post('/api/events', [{"id":"cloudMultiEventId1159588373674007628","source":"/earth/unitedstates/washington/kirkland/finnhill","data":{"hello":"world"},"type":"Azure.Sdk.TestEvent1","time":"2020-07-27T21:02:16.740Z","specversion":"1.0","datacontenttype":"application/json","subject":"Multiple 1"},{"id":"cloudMultiEventId2159588373674005416","source":"/earth/unitedstates/washington/kirkland/finnhill","data":{"hello":"world"},"type":"Azure.Sdk.TestEvent1","time":"2020-07-27T21:02:16.740Z","specversion":"1.0","datacontenttype":"application/json","subject":"Multiple 2"}])
.query(true)
.reply(200, "", [
'Content-Length',
'0',
'Server',
'Microsoft-HTTPAPI/2.0',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains',
'api-supported-versions',
'2018-01-01',
'x-ms-request-id',
'9ff2a9d4-8089-4ac2-9c2d-1d184abf00e5',
'Date',
'Mon, 27 Jul 2020 21:02:16 GMT'
]);

Просмотреть файл

@ -0,0 +1,23 @@
let nock = require('nock');
module.exports.hash = "3243d9d0032a64c42cdeaf331c65085e";
module.exports.testInfo = {"uniqueName":{},"newDate":{}}
nock('https://endpoint', {"encodedQueryParams":true})
.post('/api/events', [{"ver":"1.0","typ":"Azure.Sdk.TestEvent1","sub":"Single","payload":{"hello":"world"}}])
.query(true)
.reply(200, "", [
'Content-Length',
'0',
'Server',
'Microsoft-HTTPAPI/2.0',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains',
'api-supported-versions',
'2018-01-01',
'x-ms-request-id',
'fbdc8574-3c20-4bc9-af6b-0d5e454611f6',
'Date',
'Mon, 27 Jul 2020 21:02:16 GMT'
]);

Просмотреть файл

@ -0,0 +1,23 @@
let nock = require('nock');
module.exports.hash = "d76e8a9024ff01c8e6c19fad4188cddb";
module.exports.testInfo = {"uniqueName":{},"newDate":{}}
nock('https://endpoint', {"encodedQueryParams":true})
.post('/api/events', [{"ver":"1.0","typ":"Azure.Sdk.TestEvent1","sub":"Multiple 1","payload":{"hello":"world"}},{"ver":"1.0","typ":"Azure.Sdk.TestEvent1","sub":"Multiple 2","payload":{"hello":"world"}}])
.query(true)
.reply(200, "", [
'Content-Length',
'0',
'Server',
'Microsoft-HTTPAPI/2.0',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains',
'api-supported-versions',
'2018-01-01',
'x-ms-request-id',
'3461b247-63cd-4940-8cfd-61ada2073c7f',
'Date',
'Mon, 27 Jul 2020 21:02:17 GMT'
]);

Просмотреть файл

@ -0,0 +1,23 @@
let nock = require('nock');
module.exports.hash = "93ae44857b9e0329bc4ac9a07e444214";
module.exports.testInfo = {"uniqueName":{"singleEventId":"singleEventId159588373611301458"},"newDate":{"singleEventDate":"2020-07-27T21:02:16.113Z"}}
nock('https://endpoint', {"encodedQueryParams":true})
.post('/api/events', [{"id":"singleEventId159588373611301458","subject":"Single 1","data":{"hello":"world"},"eventType":"Azure.Sdk.TestEvent1","eventTime":"2020-07-27T21:02:16.113Z","dataVersion":"1.0"}])
.query(true)
.reply(200, "", [
'Content-Length',
'0',
'Server',
'Microsoft-HTTPAPI/2.0',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains',
'api-supported-versions',
'2018-01-01',
'x-ms-request-id',
'ef70f7ba-868c-4cee-8c9b-e27e2c01409b',
'Date',
'Mon, 27 Jul 2020 21:02:16 GMT'
]);

Просмотреть файл

@ -0,0 +1,23 @@
let nock = require('nock');
module.exports.hash = "b8c32c266a21a9129c07d237cc8e3d2b";
module.exports.testInfo = {"uniqueName":{"multiEventId1":"multiEventId1159588373643900701","multiEventId2":"multiEventId2159588373643900216"},"newDate":{"multiEventDate1":"2020-07-27T21:02:16.439Z","multiEventDate2":"2020-07-27T21:02:16.439Z"}}
nock('https://endpoint', {"encodedQueryParams":true})
.post('/api/events', [{"id":"multiEventId1159588373643900701","subject":"Multiple 1","data":{"hello":"world"},"eventType":"Azure.Sdk.TestEvent1","eventTime":"2020-07-27T21:02:16.439Z","dataVersion":"1.0"},{"id":"multiEventId2159588373643900216","subject":"Multiple 2","data":{"hello":"world"},"eventType":"Azure.Sdk.TestEvent1","eventTime":"2020-07-27T21:02:16.439Z","dataVersion":"1.0"}])
.query(true)
.reply(200, "", [
'Content-Length',
'0',
'Server',
'Microsoft-HTTPAPI/2.0',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains',
'api-supported-versions',
'2018-01-01',
'x-ms-request-id',
'2ea7f5e7-f8cf-4051-8b39-353aaa531c12',
'Date',
'Mon, 27 Jul 2020 21:02:16 GMT'
]);

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,134 @@
import path from "path";
import nodeResolve from "@rollup/plugin-node-resolve";
import multiEntry from "@rollup/plugin-multi-entry";
import cjs from "@rollup/plugin-commonjs";
import replace from "@rollup/plugin-replace";
import shim from "rollup-plugin-shim";
import { terser } from "rollup-plugin-terser";
import sourcemaps from "rollup-plugin-sourcemaps";
import viz from "rollup-plugin-visualizer";
const pkg = require("./package.json");
const depNames = Object.keys(pkg.dependencies);
const devDepNames = Object.keys(pkg.devDependencies);
const input = "dist-esm/src/index.js";
const production = process.env.NODE_ENV === "production";
export function nodeConfig(test = false) {
const externalNodeBuiltins = [];
const baseConfig = {
input: input,
external: depNames.concat(externalNodeBuiltins),
output: { file: "dist/src/index.js", format: "cjs", sourcemap: true },
preserveSymlinks: false,
plugins: [
sourcemaps(),
replace({
delimiters: ["", ""],
values: {
// replace dynamic checks with if (true) since this is for node only.
// Allows rollup's dead code elimination to be more aggressive.
"if (isNode)": "if (true)"
}
}),
nodeResolve({ preferBuiltins: true }),
cjs()
]
};
if (test) {
// Entry points - test files under the `test` folder(common for both browser and node), node specific test files
baseConfig.input = ["dist-esm/test/*.spec.js", "dist-esm/test/node/*.spec.js"];
baseConfig.plugins.unshift(multiEntry({ exports: false }));
// different output file
baseConfig.output.file = "dist-test/index.node.js";
// mark devdeps as external
baseConfig.external.push(...devDepNames);
// Disable tree-shaking of test code. In rollup-plugin-node-resolve@5.0.0, rollup started respecting
// the "sideEffects" field in package.json. Since our package.json sets "sideEffects=false", this also
// applies to test code, which causes all tests to be removed by tree-shaking.
baseConfig.treeshake = false;
} else if (production) {
baseConfig.plugins.push(terser());
}
return baseConfig;
}
export function browserConfig(test = false, production = false) {
const baseConfig = {
input: input,
output: {
file: "dist-browser/azure-eventgrid.js",
format: "umd",
name: "Azure.MessagingEventGrid",
sourcemap: true,
globals: { "@azure/core-http": "Azure.Core.HTTP" }
},
preserveSymlinks: false,
external: ["fs-extra"],
plugins: [
sourcemaps(),
replace({
delimiters: ["", ""],
values: {
// replace dynamic checks with if (false) since this is for
// browser only. Rollup's dead code elimination will remove
// any code guarded by if (isNode) { ... }
"if (isNode)": "if (false)"
}
}),
shim({
constants: `export default {}`,
fs: `export default {}`,
os: `export default {}`,
dotenv: `export function config() { }`,
path: `export default {}`
}),
nodeResolve({
mainFields: ["module", "browser"],
preferBuiltins: false
}),
cjs({
namedExports: {
chai: ["assert", "expect", "use"],
events: ["EventEmitter"],
"@opentelemetry/api": ["CanonicalCode", "SpanKind", "TraceFlags"]
}
}),
viz({ filename: "dist-browser/browser-stats.html", sourcemap: false })
]
};
if (test) {
// Entry points - test files under the `test` folder(common for both browser and node), browser specific test files
baseConfig.input = ["dist-esm/test/*.spec.js", "dist-esm/test/browser/*.spec.js"];
baseConfig.plugins.unshift(multiEntry({ exports: false }));
baseConfig.output.file = "dist-test/index.browser.js";
baseConfig.onwarn = (warning) => {
if (
warning.code === "CIRCULAR_DEPENDENCY" &&
warning.importer.indexOf(path.normalize("node_modules/chai/lib") === 0)
) {
// Chai contains circular references, but they are not fatal and can be ignored.
return;
}
console.error(`(!) ${warning.message}`);
};
// Disable tree-shaking of test code. In rollup-plugin-node-resolve@5.0.0, rollup started respecting
// the "sideEffects" field in package.json. Since our package.json sets "sideEffects=false", this also
// applies to test code, which causes all tests to be removed by tree-shaking.
baseConfig.treeshake = false;
} else if (production) {
baseConfig.output.file = "dist-browser/azure-eventgrid.min.js";
baseConfig.plugins.push(terser());
}
return baseConfig;
}

Просмотреть файл

@ -1,37 +1,14 @@
import rollup from "rollup";
import nodeResolve from "rollup-plugin-node-resolve";
import sourcemaps from "rollup-plugin-sourcemaps";
import * as base from "./rollup.base.config";
/**
* @type {rollup.RollupFileOptions}
*/
const config = {
input: "./esm/eventGridClient.js",
external: [
"@azure/ms-rest-js",
"@azure/ms-rest-azure-js"
],
output: {
file: "./dist/eventgrid.js",
format: "umd",
name: "Azure.Eventgrid",
sourcemap: true,
globals: {
"@azure/ms-rest-js": "msRest",
"@azure/ms-rest-azure-js": "msRestAzure"
},
banner: `/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/`
},
plugins: [
nodeResolve({ mainFields: ['module', 'main'] }),
sourcemaps()
]
};
const inputs = [];
export default config;
if (!process.env.ONLY_BROWSER) {
inputs.push(base.nodeConfig());
}
if (!process.env.ONLY_NODE) {
inputs.push(base.browserConfig());
inputs.push(base.browserConfig(false, true));
}
export default inputs;

Просмотреть файл

@ -0,0 +1,3 @@
import * as base from "./rollup.base.config";
export default [base.nodeConfig(true), base.browserConfig(true)];

Просмотреть файл

@ -0,0 +1,18 @@
# An Event Grid Topic configured to use the Event Grid Schema
EVENT_GRID_EVENT_GRID_SCHEMA_ENDPOINT="https://<event grid topic name>.<event grid topic region>.eventgrid.azure.net/api/events"
EVENT_GRID_EVENT_GRID_SCHEMA_API_KEY="<event grid api key>"
# An Event Grid Topic configured to use the Cloud Event 1.0 Schema.
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

Просмотреть файл

@ -0,0 +1,5 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export const SDK_VERSION: string = "3.0.0-preview.1";
export const DEFAULT_API_VERSION = "2018-01-01";

Просмотреть файл

@ -0,0 +1,190 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { Serializer } from "@azure/core-http";
import { CloudEvent as WireCloudEvent } from "./generated/models";
import {
CustomEventDataDeserializer,
CloudEvent,
EventGridEvent,
cloudEventReservedPropertyNames
} from "./models";
import {
EventGridEvent as EventGridEventMapper,
CloudEvent as CloudEventMapper
} from "./generated/models/mappers";
import { parseAndWrap, validateEventGridEvent, validateCloudEventEvent } from "./util";
import { systemDeserializers } from "./systemEventDecoders";
const serializer = new Serializer();
/**
* Options for the Event Grid Consumer
*/
export interface EventGridConsumerOptions {
/**
* Custom deserializers to use when decoding a specific event's data, based on the type
* field of the event.
*/
customDeserializers: Record<string, CustomEventDataDeserializer>;
}
/**
* EventGridConsumer is used to aid in processing events delivered by EventGrid. It can deserialize a JSON encoded payload
* of either a single event or batch of events as well as be used to convert the result of `JSON.parse` into an
* `EventGridEvent` or `CloudEvent` like object.
*
* Unlike normal JSON deseralization, EventGridConsumer does some additional conversions:
*
* - The consumer parses the event time property into a `Date` object, for ease of use.
* - When deserializing an event in the CloudEvent schema, if the event contains binary data, it is base64 decoded
* and returned as an instance of the `Uint8Array` type.
* - The `data` payload from system events is converted to match the interfaces this library defines.
*
* When constructing an `EventGridConsumer`, a map of event types to custom deserializers may be provided. When
* deserializing, if a custom deserializer has been registered for a given event type, it will be called with the
* data object. The object this deserializer returns will replace the existing data object.
*/
export class EventGridConsumer {
readonly customDeserializers: Record<string, CustomEventDataDeserializer>;
constructor(options?: EventGridConsumerOptions) {
this.customDeserializers = options?.customDeserializers ?? {};
}
/**
* Deserializes events encoded in the Event Grid schema.
*
* @param encodedEvents the JSON encoded representation of either a single event or an array of
* events, encoded in the Event Grid Schema.
*/
public async deserializeEventGridEvents(
encodedEvents: string
): Promise<EventGridEvent<unknown>[]>;
/**
* Deserializes events encoded in the Event Grid schema.
*
* @param encodedEvents an object representing a single event, encoded in the Event Grid schema.
*/
public async deserializeEventGridEvents(
encodedEvents: object
): Promise<EventGridEvent<unknown>[]>;
public async deserializeEventGridEvents(
encodedEvents: string | object
): Promise<EventGridEvent<unknown>[]> {
const decodedArray = parseAndWrap(encodedEvents);
const events: EventGridEvent<unknown>[] = [];
for (const o of decodedArray) {
validateEventGridEvent(o);
const deserialized: EventGridEvent<any> = serializer.deserialize(EventGridEventMapper, o, "");
if (systemDeserializers[deserialized.eventType]) {
deserialized.data = await systemDeserializers[deserialized.eventType](deserialized.data);
} else if (this.customDeserializers[deserialized.eventType]) {
deserialized.data = await this.customDeserializers[deserialized.eventType](
deserialized.data
);
}
events.push(deserialized as EventGridEvent<unknown>);
}
return events;
}
/**
* Deserializes events encoded in the Cloud Events 1.0 schema.
*
* @param encodedEvents the JSON encoded representation of either a single event or an array of
* events, encoded in the Cloud Events 1.0 Schema.
*/
public async deserializeCloudEvents(encodedEvents: string): Promise<CloudEvent<unknown>[]>;
/**
* Deserializes events encoded in the Cloud Events 1.0 schema.
*
* @param encodedEvents an object representing a single event, encoded in the Cloud Events 1.0 schema.
*/
public async deserializeCloudEvents(encodedEvents: object): Promise<CloudEvent<unknown>[]>;
public async deserializeCloudEvents(
encodedEvents: string | object
): Promise<CloudEvent<unknown>[]> {
const decodedArray = parseAndWrap(encodedEvents);
const events: CloudEvent<unknown>[] = [];
for (const o of decodedArray) {
validateCloudEventEvent(o);
// Check that the required fields are present and of the correct type and the optional fields are missing
// or of the correct type.
const deserialized: WireCloudEvent = serializer.deserialize(CloudEventMapper, o, "");
const modelEvent: Record<string, any> = {
specversion: deserialized.specversion,
id: deserialized.id,
source: deserialized.source,
type: deserialized.type
};
if (deserialized.datacontenttype !== undefined) {
modelEvent.datacontenttype = deserialized.datacontenttype;
}
if (deserialized.dataschema !== undefined) {
modelEvent.dataschema = deserialized.dataschema;
}
if (deserialized.subject !== undefined) {
modelEvent.subject = deserialized.subject;
}
if (deserialized.time !== undefined) {
modelEvent.time = deserialized.time;
}
if (deserialized.data !== undefined) {
modelEvent.data = deserialized.data;
}
// If the data the event represents binary, it is encoded as base64 text in a different property on the event and we need to transform it.
if (deserialized.dataBase64 !== undefined) {
if (deserialized.data !== undefined) {
throw new TypeError("event contains both a data and data_base64 field");
}
if (!(deserialized.dataBase64 instanceof Uint8Array)) {
throw new TypeError("event data_base64 property is invalid");
}
modelEvent.data = deserialized.dataBase64;
}
// If a decoder is registered, apply it to the data.
if (systemDeserializers[modelEvent.type]) {
modelEvent.data = await systemDeserializers[modelEvent.type](modelEvent.data);
} else if (this.customDeserializers[modelEvent.type]) {
modelEvent.data = await this.customDeserializers[modelEvent.type](modelEvent.data);
}
// Build the "extensionsAttributes" property bag by removing all known top level properties.
const extensionAttributes = { ...deserialized };
for (const propName of cloudEventReservedPropertyNames) {
delete extensionAttributes[propName];
}
delete extensionAttributes.dataBase64;
// If any properties remain, copy them to the model.
if (Object.keys(extensionAttributes).length > 0) {
modelEvent.extensionAttributes = extensionAttributes;
}
events.push(modelEvent as CloudEvent<unknown>);
}
return events;
}
}

Просмотреть файл

@ -0,0 +1,31 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/// <reference lib="dom"/>
/**
* @internal
* @ignore
*/
export async function sha256Hmac(secret: string, stringToSign: string): Promise<string> {
const key = await self.crypto.subtle.importKey(
"raw",
Uint8Array.from(atob(secret), (c) => c.charCodeAt(0)),
{
name: "HMAC",
hash: "SHA-256"
},
false,
["sign"]
);
const sigArray = await self.crypto.subtle.sign(
"HMAC",
key,
new TextEncoder().encode(stringToSign)
);
// The conversions here are a bit odd but necessary (see "Unicode strings" in the link below)
// https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa
return btoa(String.fromCharCode(...new Uint8Array(sigArray)));
}

Просмотреть файл

@ -0,0 +1,16 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { createHmac } from "crypto";
/**
* @internal
* @ignore
*/
export async function sha256Hmac(secret: string, stringToSign: string): Promise<string> {
const decodedSecret = Buffer.from(secret, "base64");
return createHmac("sha256", decodedSecret)
.update(stringToSign)
.digest("base64");
}

Просмотреть файл

@ -0,0 +1,70 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { KeyCredential } from "@azure/core-auth";
import {
RequestPolicyFactory,
RequestPolicy,
BaseRequestPolicy,
WebResourceLike,
HttpOperationResponse,
RequestPolicyOptionsLike
} from "@azure/core-http";
import { SignatureCredential } from "./sharedAccessSignitureCredential";
import { isKeyCredentialLike } from "./util";
/**
* The name of the header to include when a Shared Key is used for authentication.
*/
const API_KEY_HEADER_NAME = "aeg-sas-key";
/**
* The name of the header to include when Shared Access Signature is used for authentication.
*/
const SAS_TOKEN_HEADER_NAME = "aeg-sas-token";
/**
* Create an HTTP pipeline policy to authenticate a request
* using an `AzureKeyCredential` for Event Grid
*/
export function createEventGridCredentialPolicy(
credential: KeyCredential | SignatureCredential
): RequestPolicyFactory {
return {
create: (nextPolicy: RequestPolicy, options: RequestPolicyOptionsLike) => {
return new EventGridAzureKeyCredentialPolicy(nextPolicy, options, credential);
}
};
}
/**
* A concrete implementation of an AzureKeyCredential policy
* using the appropriate header for Event Grid
*/
class EventGridAzureKeyCredentialPolicy extends BaseRequestPolicy {
private credential: KeyCredential | SignatureCredential;
constructor(
nextPolicy: RequestPolicy,
options: RequestPolicyOptionsLike,
credential: KeyCredential | SignatureCredential
) {
super(nextPolicy, options);
this.credential = credential;
}
public async sendRequest(webResource: WebResourceLike): Promise<HttpOperationResponse> {
if (!webResource) {
throw new Error("webResource cannot be null or undefined");
}
if (isKeyCredentialLike(this.credential)) {
webResource.headers.set(API_KEY_HEADER_NAME, this.credential.key);
} else {
webResource.headers.set(SAS_TOKEN_HEADER_NAME, this.credential.signature());
}
return this._nextPolicy.sendRequest(webResource);
}
}

Просмотреть файл

@ -1,106 +1,241 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { KeyCredential } from "@azure/core-auth";
import {
PipelineOptions,
createPipelineFromOptions,
OperationOptions,
generateUuid,
HttpResponse
} from "@azure/core-http";
import { createEventGridCredentialPolicy } from "./eventGridAuthenticationPolicy";
import { SignatureCredential } from "./sharedAccessSignitureCredential";
import { SDK_VERSION } from "./constants";
import {
SendCloudEventInput,
SendEventGridEventInput,
cloudEventReservedPropertyNames
} from "./models";
import { GeneratedClient } from "./generated/generatedClient";
import {
CloudEvent as CloudEventWireModel,
EventGridEvent as EventGridEventWireModel
} from "./generated/models";
/**
* Options for the Event Grid Client.
*/
export type EventGridPublisherClientOptions = PipelineOptions;
/**
* Options for the send events operation.
*/
export type SendEventsOptions = OperationOptions;
/**
* Options for the send cloud events operation.
*/
export type SendCloudEventsOptions = OperationOptions;
/**
* Options for the send custom schema events operation.
*/
export type SendCustomSchemaEventsOptions = OperationOptions;
/**
* The response when sending events to the Event Grid service.
*/
export interface SendEventsResponse {
_response: HttpResponse;
}
/**
* Client class for publishing events to the Event Grid Service.
*/
export class EventGridPublisherClient {
/**
* The URL to the Event Grid endpoint.
*/
public readonly endpointUrl: string;
/**
* The version of the Even Grid service.
*/
public readonly apiVersion: string;
/**
* The AutoRest generated client for the EventGrid dataplane.
*/
private readonly client: GeneratedClient;
/**
* Creates an instance of EventGridPublisherClient.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
* Example usage:
* ```ts
* import { EventGridPublisherClient, AzureKeyCredential } from "@azure/eventgrid";
*
* const client = new EventGridPublisherClient(
* "<service endpoint>",
* new AzureKeyCredential("<api key>")
* );
* ```
*
* @param endpointUrl The URL to the EventGrid endpoint, e.g. https://eg-topic.westus2-1.eventgrid.azure.net/api/events
* @param credential Used to authenticate requests to the service.
* @param options Used to configure the Event Grid Client
*/
constructor(
endpointUrl: string,
credential: KeyCredential | SignatureCredential,
options: EventGridPublisherClientOptions = {}
) {
this.endpointUrl = endpointUrl;
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "./models";
import * as Mappers from "./models/mappers";
import * as Parameters from "./models/parameters";
import { EventGridClientContext } from "./eventGridClientContext";
const libInfo = `azsdk-js-eventgrid/${SDK_VERSION}`;
const pipelineOptions = { ...options };
if (!pipelineOptions.userAgentOptions) {
pipelineOptions.userAgentOptions = {};
}
class EventGridClient extends EventGridClientContext {
/**
* Initializes a new instance of the EventGridClient class.
* @param credentials Credentials needed for the client to connect to Azure.
* @param [options] The parameter options
*/
constructor(credentials: msRest.ServiceClientCredentials, options?: msRestAzure.AzureServiceClientOptions) {
super(credentials, options);
if (pipelineOptions.userAgentOptions.userAgentPrefix) {
pipelineOptions.userAgentOptions.userAgentPrefix = `${pipelineOptions.userAgentOptions.userAgentPrefix} ${libInfo}`;
} else {
pipelineOptions.userAgentOptions.userAgentPrefix = libInfo;
}
const authPolicy = createEventGridCredentialPolicy(credential);
const pipeline = createPipelineFromOptions(options, authPolicy);
this.client = new GeneratedClient(pipeline);
this.apiVersion = this.client.apiVersion;
}
/**
* Publishes a batch of events to an Azure Event Grid topic.
* @param topicHostname The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net
* @param events An array of events to be published to Event Grid.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
* Publishes events in the Event Grid scheama. The topic must be configured to expect events in the Event Grid schema.
*
* @param message One or more events to publish
*/
publishEvents(topicHostname: string, events: Models.EventGridEvent[], options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param topicHostname The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net
* @param events An array of events to be published to Event Grid.
* @param callback The callback
*/
publishEvents(topicHostname: string, events: Models.EventGridEvent[], callback: msRest.ServiceCallback<void>): void;
/**
* @param topicHostname The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net
* @param events An array of events to be published to Event Grid.
* @param options The optional parameters
* @param callback The callback
*/
publishEvents(topicHostname: string, events: Models.EventGridEvent[], options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
publishEvents(topicHostname: string, events: Models.EventGridEvent[], options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.sendOperationRequest(
{
topicHostname,
events,
sendEvents(
events: SendEventGridEventInput<any>[],
options?: SendEventsOptions
): Promise<SendEventsResponse> {
return this.client
.publishEvents(
this.endpointUrl,
(events || []).map(convertEventGridEventToModelType),
options
},
publishEventsOperationSpec,
callback);
)
.then((r) => {
return {
_response: r._response
};
});
}
/**
* Publishes events in the Cloud Events 1.0 schema. The topic must be configured to expect events in the Cloud Events 1.0 schema.
*
* @param message One or more events to publish
*/
sendCloudEvents(
events: SendCloudEventInput<any>[],
options?: SendCloudEventsOptions
): Promise<SendEventsResponse> {
return this.client
.publishCloudEventEvents(
this.endpointUrl,
(events || []).map(convertCloudEventToModelType),
options
)
.then((r) => {
return {
_response: r._response
};
});
}
/**
* Publishes events written using a custom schema. The topic must be configured to expect events in a custom schema.
*
* @param message One or more events to publish
*/
sendCustomSchemaEvents(
events: Record<string, any>[],
options?: SendCustomSchemaEventsOptions
): Promise<SendEventsResponse> {
return this.client
.publishCustomEventEvents(this.endpointUrl, events || [], options)
.then((r) => {
return {
_response: r._response
};
});
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const publishEventsOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "api/events",
urlParameters: [
Parameters.topicHostname
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "events",
mapper: {
required: true,
serializedName: "events",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "EventGridEvent"
/**
* @internal
*/
export function convertEventGridEventToModelType(
event: SendEventGridEventInput<any>
): EventGridEventWireModel {
return {
eventType: event.eventType,
eventTime: event.eventTime ?? new Date(),
id: event.id ?? generateUuid(),
subject: event.subject,
topic: event.topic,
data: event.data,
dataVersion: event.dataVersion
};
}
/**
* @internal
*/
export function convertCloudEventToModelType(event: SendCloudEventInput<any>): CloudEventWireModel {
if (event.extensionAttributes) {
for (const propName in event.extensionAttributes) {
// Per the cloud events spec: "CloudEvents attribute names MUST consist of lower-case letters ('a' to 'z') or digits ('0' to '9') from the ASCII character set"
// they also can not match an existing defined property name.
if (
!/^[a-z0-9]*$/.test(propName) ||
cloudEventReservedPropertyNames.indexOf(propName) !== -1
) {
throw new Error(`invalid extension attribute name: ${propName}`);
}
}
}
}
},
responses: {
200: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
const converted: CloudEventWireModel = {
specversion: "1.0",
type: event.type,
source: event.source,
id: event.id ?? generateUuid(),
time: event.time ?? new Date(),
subject: event.subject,
dataschema: event.dataschema,
...(event.extensionAttributes ?? [])
};
export {
EventGridClient,
EventGridClientContext,
Models as EventGridModels,
Mappers as EventGridMappers
};
if (event.data instanceof Uint8Array) {
if (!event.datacontenttype) {
throw new Error(
"a data content type must be provided when sending an event with binary data"
);
}
converted.datacontenttype = event.datacontenttype;
converted.dataBase64 = event.data;
} else {
converted.datacontenttype = event.datacontenttype ?? "application/json";
converted.data = event.data;
}
return converted;
}

Просмотреть файл

@ -1,55 +0,0 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
const packageName = "@azure/eventgrid";
const packageVersion = "2.0.0";
export class EventGridClientContext extends msRestAzure.AzureServiceClient {
credentials: msRest.ServiceClientCredentials;
apiVersion?: string;
/**
* Initializes a new instance of the EventGridClient class.
* @param credentials Credentials needed for the client to connect to Azure.
* @param [options] The parameter options
*/
constructor(credentials: msRest.ServiceClientCredentials, options?: msRestAzure.AzureServiceClientOptions) {
if (credentials == undefined) {
throw new Error('\'credentials\' cannot be null.');
}
if (!options) {
options = {};
}
if(!options.userAgent) {
const defaultUserAgent = msRestAzure.getDefaultUserAgentValue();
options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`;
}
super(credentials, options);
this.apiVersion = '2018-01-01';
this.acceptLanguage = 'en-US';
this.longRunningOperationRetryTimeout = 30;
this.baseUri = "https://{topicHostname}";
this.requestContentType = "application/json; charset=utf-8";
this.credentials = credentials;
if(options.acceptLanguage !== null && options.acceptLanguage !== undefined) {
this.acceptLanguage = options.acceptLanguage;
}
if(options.longRunningOperationRetryTimeout !== null && options.longRunningOperationRetryTimeout !== undefined) {
this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout;
}
}
}

Просмотреть файл

@ -0,0 +1,39 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { KeyCredential } from "@azure/core-auth";
import { DEFAULT_API_VERSION } from "./constants";
import { sha256Hmac } from "./cryptoHelpers";
import { dateToServiceTimeString } from "./util";
export interface GenerateSharedAccessSignatureOptions {
/**
* The API Version to include in the signature. If not provided, the default
* API version will be used.
*/
apiVersion?: string;
}
/**
* Generate a shared access signature, which allows a client to send events to an Event Grid Topic or Domain for a limited period of time. This
* function may only be called when the EventGridPublisherClient was constructed with a KeyCredential instance.
*
* @param endpointUrl The endpoint for the topic or domain you wish to generate a shared access signature for.
* @param credential The credential to use when generating the shared access signatrue.
* @param expiresOn The time at which the shared access signature is no longer valid.
* @param options Options to control how the signature is generated.
*/
export async function generateSharedAccessSignature(
endpointUrl: string,
credential: KeyCredential,
expiresOnUtc: Date,
options?: GenerateSharedAccessSignatureOptions
): Promise<string> {
const expiresOnString = dateToServiceTimeString(expiresOnUtc);
const unsignedSas = `r=${encodeURIComponent(
`${endpointUrl}?apiVersion=${options?.apiVersion || DEFAULT_API_VERSION}`
)}&e=${encodeURIComponent(expiresOnString)}`;
return sha256Hmac(credential.key, unsignedSas).then(
(digest) => `${unsignedSas}&s=${encodeURIComponent(digest)}`
);
}

Просмотреть файл

@ -0,0 +1,134 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreHttp from "@azure/core-http";
import * as Parameters from "./models/parameters";
import * as Models from "./models";
import * as Mappers from "./models/mappers";
import { GeneratedClientContext } from "./generatedClientContext";
import {
GeneratedClientOptionalParams,
EventGridEvent,
CloudEvent
} from "./models";
class GeneratedClient extends GeneratedClientContext {
/**
* Initializes a new instance of the GeneratedClient class.
* @param options The parameter options
*/
constructor(options?: GeneratedClientOptionalParams) {
super(options);
}
/**
* Publishes a batch of events to an Azure Event Grid topic.
* @param topicHostname The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net
* @param events An array of events to be published to Event Grid.
* @param options The options parameters.
*/
publishEvents(
topicHostname: string,
events: EventGridEvent[],
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase(
options || {}
);
return this.sendOperationRequest(
{ topicHostname, events, options: operationOptions },
publishEventsOperationSpec
) as Promise<coreHttp.RestResponse>;
}
/**
* Publishes a batch of events to an Azure Event Grid topic.
* @param topicHostname The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net
* @param events An array of events to be published to Event Grid.
* @param options The options parameters.
*/
publishCloudEventEvents(
topicHostname: string,
events: CloudEvent[],
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase(
options || {}
);
return this.sendOperationRequest(
{ topicHostname, events, options: operationOptions },
publishCloudEventEventsOperationSpec
) as Promise<coreHttp.RestResponse>;
}
/**
* Publishes a batch of events to an Azure Event Grid topic.
* @param topicHostname The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net
* @param events An array of events to be published to Event Grid.
* @param options The options parameters.
*/
publishCustomEventEvents(
topicHostname: string,
events: any[],
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase(
options || {}
);
return this.sendOperationRequest(
{ topicHostname, events, options: operationOptions },
publishCustomEventEventsOperationSpec
) as Promise<coreHttp.RestResponse>;
}
}
// Operation Specifications
const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false);
const publishEventsOperationSpec: coreHttp.OperationSpec = {
path: "/api/events",
httpMethod: "POST",
responses: { 200: {}, default: {} },
requestBody: Parameters.events,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.topicHostname],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const publishCloudEventEventsOperationSpec: coreHttp.OperationSpec = {
path: "/api/events",
httpMethod: "POST",
responses: { 200: {}, default: {} },
requestBody: Parameters.events1,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.topicHostname],
headerParameters: [Parameters.contentType1],
mediaType: "json",
serializer
};
const publishCustomEventEventsOperationSpec: coreHttp.OperationSpec = {
path: "/api/events",
httpMethod: "POST",
responses: { 200: {}, default: {} },
requestBody: Parameters.events2,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.topicHostname],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
// Operation Specifications
export {
GeneratedClient,
GeneratedClientContext,
Models as GeneratedModels,
Mappers as GeneratedMappers
};

Просмотреть файл

@ -0,0 +1,42 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreHttp from "@azure/core-http";
import { GeneratedClientOptionalParams } from "./models";
const packageName = "@azure/eventgrid";
const packageVersion = "1.0.0";
export class GeneratedClientContext extends coreHttp.ServiceClient {
apiVersion: string;
/**
* Initializes a new instance of the GeneratedClientContext class.
* @param options The parameter options
*/
constructor(options?: GeneratedClientOptionalParams) {
// Initializing default values for options
if (!options) {
options = {};
}
if (!options.userAgent) {
const defaultUserAgent = coreHttp.getDefaultUserAgentValue();
options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`;
}
super(undefined, options);
this.requestContentType = "application/json; charset=utf-8";
this.baseUri = options.endpoint || "https://{topicHostname}";
// Assigning values to Constant parameters
this.apiVersion = options.apiVersion || "2018-01-01";
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,97 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import {
OperationParameter,
OperationURLParameter,
OperationQueryParameter
} from "@azure/core-http";
export const contentType: OperationParameter = {
parameterPath: ["options", "contentType"],
mapper: {
defaultValue: "application/json",
isConstant: true,
serializedName: "Content-Type",
type: {
name: "String"
}
}
};
export const events: OperationParameter = {
parameterPath: "events",
mapper: {
serializedName: "events",
required: true,
type: {
name: "Sequence",
element: { type: { name: "Composite", className: "EventGridEvent" } }
}
}
};
export const topicHostname: OperationURLParameter = {
parameterPath: "topicHostname",
mapper: {
serializedName: "topicHostname",
required: true,
type: {
name: "String"
}
},
skipEncoding: true
};
export const apiVersion: OperationQueryParameter = {
parameterPath: "apiVersion",
mapper: {
defaultValue: "2018-01-01",
isConstant: true,
serializedName: "api-version",
type: {
name: "String"
}
}
};
export const contentType1: OperationParameter = {
parameterPath: ["options", "contentType"],
mapper: {
defaultValue: "application/cloudevents-batch+json; charset=utf-8",
isConstant: true,
serializedName: "Content-Type",
type: {
name: "String"
}
}
};
export const events1: OperationParameter = {
parameterPath: "events",
mapper: {
serializedName: "events",
required: true,
type: {
name: "Sequence",
element: { type: { name: "Composite", className: "CloudEvent" } }
}
}
};
export const events2: OperationParameter = {
parameterPath: "events",
mapper: {
serializedName: "events",
required: true,
type: {
name: "Sequence",
element: { type: { name: "any" } }
}
}
};

Просмотреть файл

@ -0,0 +1,147 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export { AzureKeyCredential } from "@azure/core-auth";
export {
CloudEvent,
CustomEventDataDeserializer,
EventGridEvent,
SendCloudEventInput,
SendEventGridEventInput
} from "./models";
export {
EventGridPublisherClient,
EventGridPublisherClientOptions,
SendEventsOptions,
SendCloudEventsOptions,
SendCustomSchemaEventsOptions
} from "./eventGridClient";
export {
SignatureCredential,
EventGridSharedAccessSignatureCredential
} from "./sharedAccessSignitureCredential";
export { EventGridConsumer, EventGridConsumerOptions } from "./consumer";
export {
generateSharedAccessSignature,
GenerateSharedAccessSignatureOptions
} from "./generateSharedAccessSignature";
export { isSystemEvent, KnownSystemEventTypes, SystemEventNameToEventData } from "./predicates";
export {
AppConfigurationKeyValueDeletedEventData,
AppConfigurationKeyValueModifiedEventData,
AppEventTypeDetail,
AppServicePlanEventTypeDetail,
ContainerRegistryArtifactEventTarget,
ContainerRegistryEventData,
ContainerRegistryImagePushedEventData,
ContainerRegistryImageDeletedEventData,
ContainerRegistryChartDeletedEventData,
ContainerRegistryChartPushedEventData,
DeviceConnectionStateEventInfo,
DeviceTwinInfo,
DeviceTwinInfoProperties,
DeviceTwinInfoX509Thumbprint,
IotHubDeviceCreatedEventData,
IotHubDeviceDeletedEventData,
IotHubDeviceConnectedEventData,
IotHubDeviceDisconnectedEventData,
IotHubDeviceTelemetryEventData,
SubscriptionValidationEventData,
SubscriptionDeletedEventData,
EventHubCaptureFileCreatedEventData,
MachineLearningServicesDatasetDriftDetectedEventData,
MachineLearningServicesModelDeployedEventData,
MachineLearningServicesModelRegisteredEventData,
MachineLearningServicesRunCompletedEventData,
MachineLearningServicesRunStatusChangedEventData,
MapsGeofenceEventProperties,
MapsGeofenceEnteredEventData,
MapsGeofenceExitedEventData,
MapsGeofenceResultEventData,
MediaJobStateChangeEventData,
MediaJobOutputStateChangeEventData,
MediaJobScheduledEventData,
MediaJobProcessingEventData,
MediaJobCancelingEventData,
MediaJobFinishedEventData,
MediaJobCanceledEventData,
MediaJobError,
MediaJobErrorCategory,
MediaJobErrorDetail,
MediaJobErrorCode,
MediaJobRetry,
MediaJobErroredEventData,
MediaJobOutputCanceledEventData,
MediaJobOutputCancelingEventData,
MediaJobOutputErroredEventData,
MediaJobOutputFinishedEventData,
MediaJobOutputProcessingEventData,
MediaJobOutputScheduledEventData,
MediaJobOutputProgressEventData,
MediaJobOutputUnion,
MediaJobState,
MediaLiveEventEncoderConnectedEventData,
MediaLiveEventConnectionRejectedEventData,
MediaLiveEventEncoderDisconnectedEventData,
MediaLiveEventIncomingStreamReceivedEventData,
MediaLiveEventIncomingStreamsOutOfSyncEventData,
MediaLiveEventIncomingVideoStreamsOutOfSyncEventData,
MediaLiveEventIncomingDataChunkDroppedEventData,
MediaLiveEventIngestHeartbeatEventData,
MediaLiveEventTrackDiscontinuityDetectedEventData,
ResourceWriteSuccessEventData,
ResourceWriteFailureEventData,
ResourceWriteCancelEventData,
ResourceDeleteSuccessEventData,
ResourceDeleteFailureEventData,
ResourceDeleteCancelEventData,
ResourceActionSuccessEventData,
ResourceActionFailureEventData,
ResourceActionCancelEventData,
ServiceBusActiveMessagesAvailableWithNoListenersEventData,
ServiceBusDeadletterMessagesAvailableWithNoListenersEventData,
StorageBlobCreatedEventData,
StorageBlobDeletedEventData,
StorageBlobRenamedEventData,
StorageDirectoryCreatedEventData,
StorageDirectoryDeletedEventData,
StorageDirectoryRenamedEventData,
StorageLifecyclePolicyCompletedEventData,
WebAppUpdatedEventData,
WebBackupOperationStartedEventData,
WebBackupOperationCompletedEventData,
WebBackupOperationFailedEventData,
WebRestoreOperationStartedEventData,
WebRestoreOperationCompletedEventData,
WebRestoreOperationFailedEventData,
WebSlotSwapStartedEventData,
WebSlotSwapCompletedEventData,
WebSlotSwapFailedEventData,
WebSlotSwapWithPreviewStartedEventData,
WebSlotSwapWithPreviewCancelledEventData,
WebAppServicePlanUpdatedEventData,
WebAppServicePlanUpdatedEventDataSku,
AppAction,
StampKind,
AsyncStatus,
ContainerRegistryArtifactEventData,
ContainerRegistryEventActor,
ContainerRegistryEventRequest,
ContainerRegistryEventSource,
ContainerRegistryEventTarget,
DeviceConnectionStateEventProperties,
DeviceLifeCycleEventProperties,
DeviceTelemetryEventProperties,
MapsGeofenceGeometry,
MediaJobOutput,
MediaJobOutputAsset,
DeviceTwinProperties,
DeviceTwinMetadata
} from "./generated/models";

Просмотреть файл

@ -0,0 +1,9 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { createClientLogger } from "@azure/logger";
/**
* The @azure/logger configuration for this package.
*/
export const logger = createClientLogger("eventgrid");

Просмотреть файл

@ -0,0 +1,176 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* The shape of the input for EventGridProducerClient#sendEvents
*/
export interface SendEventGridEventInput<T> {
/**
* The type of the event.
*/
eventType: string;
/**
* The time the event was generated. If not provided, the current time will be used.
*/
eventTime?: Date;
/**
* An unique identifier for the event. If an ID is not provided, a random UUID will be generated
* and used.
*/
id?: string;
/**
* The resource path of the event source.
*/
topic?: string;
/**
* A resource path relative to the topic path.
*/
subject: string;
/**
* The schema version of the data object.
*/
dataVersion: string;
/**
* Event data specific to the event type.
*/
data: T;
}
/**
* An event in the in the Event Grid Schema.
*/
export interface EventGridEvent<T> {
/**
* The type of the event.
*/
eventType: string;
/**
* The time the event was generated.
*/
eventTime: Date;
/**
* An unique identifier for the event.
*/
id: string;
/**
* The resource path of the event source.
*/
topic?: string;
/**
* A resource path relative to the topic path.
*/
subject: string;
/**
* The schema version of the data object.
*/
dataVersion: string;
/**
* Event data specific to the event type.
*/
data: T;
}
/**
* * The shape of the input for EventGridProducerClient#sendCloudEvents
*/
export interface SendCloudEventInput<T> {
/**
* Type of event related to the originating occurrence.
*/
type: string;
/**
* Identifies the context in which an event happened. The combination of id and source must be unique for each distinct event.
*/
source: string;
/**
* An identifier for the event. The combination of id and source must be unique for each distinct event. If an ID is not provided,
* a random UUID will be generated and used.
*/
id?: string;
/**
* The time the event was generated. If not provided, the current time will be used.
*/
time?: Date;
/**
* Identifies the schema that data adheres to.
*/
dataschema?: string;
/**
* Content type of data value.
*/
datacontenttype?: string;
/**
* Event data specific to the event type.
*/
data?: T;
/**
* This describes the subject of the event in the context of the event producer (identified by source).
*/
subject?: string;
/**
* Additional context attributes for the event. The Cloud Event specification refers to these as "extension attributes".
*/
extensionAttributes?: Record<string, unknown>;
}
/**
* An event in the Cloud Event 1.0 schema.
*/
export interface CloudEvent<T> {
/**
* Type of event related to the originating occurrence.
*/
type: string;
/**
* Identifies the context in which an event happened. The combination of id and source must be unique for each distinct event.
*/
source: string;
/**
* An identifier for the event. The combination of id and source must be unique for each distinct event.
*/
id: string;
/**
* The time the event was generated.
*/
time?: Date;
/**
* Identifies the schema that data adheres to.
*/
dataschema?: string;
/**
* Content type of data value.
*/
datacontenttype?: string;
/**
* Event data specific to the event type.
*/
data?: T;
/**
* This describes the subject of the event in the context of the event producer (identified by source).
*/
subject?: string;
/**
* Additional context attributes for the event. The Cloud Event specification refers to these as "extension attributes".
*/
extensionAttributes?: Record<string, unknown>;
}
/**
* Property names defined by the CloudEvents 1.0 specification, these may not be reused as the names of extension properties.
*/
export const cloudEventReservedPropertyNames = [
"specversion",
"id",
"source",
"type",
"datacontenttype",
"dataschema",
"subject",
"time",
"data"
];
/**
* A function which provides custom logic to be used when decoding events.
*/
export type CustomEventDataDeserializer = (o: any) => Promise<any>;

Просмотреть файл

@ -1,44 +0,0 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
import * as msRest from "@azure/ms-rest-js";
export const acceptLanguage: msRest.OperationParameter = {
parameterPath: "acceptLanguage",
mapper: {
serializedName: "accept-language",
defaultValue: 'en-US',
type: {
name: "String"
}
}
};
export const apiVersion: msRest.OperationQueryParameter = {
parameterPath: "apiVersion",
mapper: {
required: true,
serializedName: "api-version",
type: {
name: "String"
}
}
};
export const topicHostname: msRest.OperationURLParameter = {
parameterPath: "topicHostname",
mapper: {
required: true,
serializedName: "topicHostname",
defaultValue: '',
type: {
name: "String"
}
},
skipEncoding: true
};

Просмотреть файл

@ -0,0 +1,379 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
AppConfigurationKeyValueDeletedEventData,
AppConfigurationKeyValueModifiedEventData,
ContainerRegistryImagePushedEventData,
ContainerRegistryImageDeletedEventData,
ContainerRegistryChartDeletedEventData,
ContainerRegistryChartPushedEventData,
IotHubDeviceCreatedEventData,
IotHubDeviceDeletedEventData,
IotHubDeviceConnectedEventData,
IotHubDeviceDisconnectedEventData,
IotHubDeviceTelemetryEventData,
SubscriptionValidationEventData,
SubscriptionDeletedEventData,
EventHubCaptureFileCreatedEventData,
MachineLearningServicesDatasetDriftDetectedEventData,
MachineLearningServicesModelDeployedEventData,
MachineLearningServicesModelRegisteredEventData,
MachineLearningServicesRunCompletedEventData,
MachineLearningServicesRunStatusChangedEventData,
MapsGeofenceEnteredEventData,
MapsGeofenceExitedEventData,
MapsGeofenceResultEventData,
MediaJobStateChangeEventData,
MediaJobOutputStateChangeEventData,
MediaJobScheduledEventData,
MediaJobProcessingEventData,
MediaJobCancelingEventData,
MediaJobFinishedEventData,
MediaJobCanceledEventData,
MediaJobErroredEventData,
MediaJobOutputCanceledEventData,
MediaJobOutputCancelingEventData,
MediaJobOutputErroredEventData,
MediaJobOutputFinishedEventData,
MediaJobOutputProcessingEventData,
MediaJobOutputScheduledEventData,
MediaJobOutputProgressEventData,
MediaLiveEventEncoderConnectedEventData,
MediaLiveEventConnectionRejectedEventData,
MediaLiveEventEncoderDisconnectedEventData,
MediaLiveEventIncomingStreamReceivedEventData,
MediaLiveEventIncomingStreamsOutOfSyncEventData,
MediaLiveEventIncomingVideoStreamsOutOfSyncEventData,
MediaLiveEventIncomingDataChunkDroppedEventData,
MediaLiveEventIngestHeartbeatEventData,
MediaLiveEventTrackDiscontinuityDetectedEventData,
ResourceWriteSuccessEventData,
ResourceWriteFailureEventData,
ResourceWriteCancelEventData,
ResourceDeleteSuccessEventData,
ResourceDeleteFailureEventData,
ResourceDeleteCancelEventData,
ResourceActionSuccessEventData,
ResourceActionFailureEventData,
ResourceActionCancelEventData,
ServiceBusActiveMessagesAvailableWithNoListenersEventData,
ServiceBusDeadletterMessagesAvailableWithNoListenersEventData,
StorageBlobCreatedEventData,
StorageBlobDeletedEventData,
StorageBlobRenamedEventData,
StorageDirectoryCreatedEventData,
StorageDirectoryDeletedEventData,
StorageDirectoryRenamedEventData,
WebAppUpdatedEventData,
WebBackupOperationStartedEventData,
WebBackupOperationCompletedEventData,
WebBackupOperationFailedEventData,
WebRestoreOperationStartedEventData,
WebRestoreOperationCompletedEventData,
WebRestoreOperationFailedEventData,
WebSlotSwapStartedEventData,
WebSlotSwapCompletedEventData,
WebSlotSwapFailedEventData,
WebSlotSwapWithPreviewStartedEventData,
WebSlotSwapWithPreviewCancelledEventData,
WebAppServicePlanUpdatedEventData,
StorageLifecyclePolicyCompletedEventData
} from "./generated/models";
import { CloudEvent, EventGridEvent } from "./models";
/**
* The Event Types for all System Events. These may be used with `isSystemEvent` to determine if an
* event is a system event of a given type.
*/
export type KnownSystemEventTypes =
| "Microsoft.AppConfiguration.KeyValueDeleted"
| "Microsoft.AppConfiguration.KeyValueModified"
| "Microsoft.ContainerRegistry.ImagePushed"
| "Microsoft.ContainerRegistry.ImageDeleted"
| "Microsoft.ContainerRegistry.ChartDeleted"
| "Microsoft.ContainerRegistry.ChartPushed"
| "Microsoft.Devices.DeviceCreated"
| "Microsoft.Devices.DeviceDeleted"
| "Microsoft.Devices.DeviceConnected"
| "Microsoft.Devices.DeviceDisconnected"
| "Microsoft.Devices.DeviceTelemetry"
| "Microsoft.EventGrid.SubscriptionValidationEvent"
| "Microsoft.EventGrid.SubscriptionDeletedEvent"
| "Microsoft.EventHub.CaptureFileCreated"
| "Microsoft.MachineLearningServices.DatasetDriftDetected"
| "Microsoft.MachineLearningServices.ModelDeployed"
| "Microsoft.MachineLearningServices.ModelRegistered"
| "Microsoft.MachineLearningServices.RunCompleted"
| "Microsoft.MachineLearningServices.RunStatusChanged"
| "Microsoft.Maps.GeofenceEntered"
| "Microsoft.Maps.GeofenceExited"
| "Microsoft.Maps.GeofenceResult"
| "Microsoft.Media.JobStateChange"
| "Microsoft.Media.JobOutputStateChange"
| "Microsoft.Media.JobScheduled"
| "Microsoft.Media.JobProcessing"
| "Microsoft.Media.JobCanceling"
| "Microsoft.Media.JobFinished"
| "Microsoft.Media.JobCanceled"
| "Microsoft.Media.JobErrored"
| "Microsoft.Media.JobOutputCanceled"
| "Microsoft.Media.JobOutputCanceling"
| "Microsoft.Media.JobOutputErrored"
| "Microsoft.Media.JobOutputFinished"
| "Microsoft.Media.JobOutputProcessing"
| "Microsoft.Media.JobOutputScheduled"
| "Microsoft.Media.JobOutputProgress"
| "Microsoft.Media.LiveEventEncoderConnected"
| "Microsoft.Media.LiveEventConnectionRejected"
| "Microsoft.Media.LiveEventEncoderDisconnected"
| "Microsoft.Media.LiveEventIncomingStreamReceived"
| "Microsoft.Media.LiveEventIncomingStreamsOutOfSync"
| "Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync"
| "Microsoft.Media.LiveEventIncomingDataChunkDropped"
| "Microsoft.Media.LiveEventIngestHeartbeat"
| "Microsoft.Media.LiveEventTrackDiscontinuityDetected"
| "Microsoft.Resources.ResourceWriteSuccess"
| "Microsoft.Resources.ResourceWriteFailure"
| "Microsoft.Resources.ResourceWriteCancel"
| "Microsoft.Resources.ResourceDeleteSuccess"
| "Microsoft.Resources.ResourceDeleteFailure"
| "Microsoft.Resources.ResourceDeleteCancel"
| "Microsoft.Resources.ResourceActionSuccess"
| "Microsoft.Resources.ResourceActionFailure"
| "Microsoft.Resources.ResourceActionCancel"
| "Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners"
| "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener"
| "Microsoft.Storage.BlobCreated"
| "Microsoft.Storage.BlobDeleted"
| "Microsoft.Storage.BlobRenamed"
| "Microsoft.Storage.DirectoryCreated"
| "Microsoft.Storage.DirectoryDeleted"
| "Microsoft.Storage.DirectoryRenamed"
| "Microsoft.Storage.LifecyclePolicyCompleted"
| "Microsoft.Web.AppUpdated"
| "Microsoft.Web.BackupOperationStarted"
| "Microsoft.Web.BackupOperationCompleted"
| "Microsoft.Web.BackupOperationFailed"
| "Microsoft.Web.RestoreOperationStarted"
| "Microsoft.Web.RestoreOperationCompleted"
| "Microsoft.Web.RestoreOperationFailed"
| "Microsoft.Web.SlotSwapStarted"
| "Microsoft.Web.SlotSwapCompleted"
| "Microsoft.Web.SlotSwapFailed"
| "Microsoft.Web.SlotSwapWithPreviewStarted"
| "Microsoft.Web.SlotSwapWithPreviewCancelled"
| "Microsoft.Web.AppServicePlanUpdated";
/**
* A mapping of event type names to event data type interfaces.
*
* @ignore
*/
export interface SystemEventNameToEventData {
/** An interface for the event data of a "Microsoft.AppConfiguration.KeyValueDeleted" event. */
"Microsoft.AppConfiguration.KeyValueDeleted": AppConfigurationKeyValueDeletedEventData;
/** An interface for the event data of a "Microsoft.AppConfiguration.KeyValueModified" event. */
"Microsoft.AppConfiguration.KeyValueModified": AppConfigurationKeyValueModifiedEventData;
/** An interface for the event data of a "Microsoft.ContainerRegistry.ImagePushed" event. */
"Microsoft.ContainerRegistry.ImagePushed": ContainerRegistryImagePushedEventData;
/** An interface for the event data of a "Microsoft.ContainerRegistry.ImageDeleted" event. */
"Microsoft.ContainerRegistry.ImageDeleted": ContainerRegistryImageDeletedEventData;
/** An interface for the event data of a "Microsoft.ContainerRegistry.ChartDeleted" event. */
"Microsoft.ContainerRegistry.ChartDeleted": ContainerRegistryChartDeletedEventData;
/** An interface for the event data of a "Microsoft.ContainerRegistry.ChartPushed" event. */
"Microsoft.ContainerRegistry.ChartPushed": ContainerRegistryChartPushedEventData;
/** An interface for the event data of a "Microsoft.Devices.DeviceCreated" event. */
"Microsoft.Devices.DeviceCreated": IotHubDeviceCreatedEventData;
/** An interface for the event data of a "Microsoft.Devices.DeviceDeleted" event. */
"Microsoft.Devices.DeviceDeleted": IotHubDeviceDeletedEventData;
/** An interface for the event data of a "Microsoft.Devices.DeviceConnected" event. */
"Microsoft.Devices.DeviceConnected": IotHubDeviceConnectedEventData;
/** An interface for the event data of a "Microsoft.Devices.DeviceDisconnected" event. */
"Microsoft.Devices.DeviceDisconnected": IotHubDeviceDisconnectedEventData;
/** An interface for the event data of a "Microsoft.Devices.DeviceTelemetry" event. */
"Microsoft.Devices.DeviceTelemetry": IotHubDeviceTelemetryEventData;
/** An interface for the event data of a "Microsoft.EventGrid.SubscriptionValidationEvent" event. */
"Microsoft.EventGrid.SubscriptionValidationEvent": SubscriptionValidationEventData;
/** An interface for the event data of a "Microsoft.EventGrid.SubscriptionDeletedEvent" event. */
"Microsoft.EventGrid.SubscriptionDeletedEvent": SubscriptionDeletedEventData;
/** An interface for the event data of a "Microsoft.EventHub.CaptureFileCreated" event. */
"Microsoft.EventHub.CaptureFileCreated": EventHubCaptureFileCreatedEventData;
/** An interface for the event data of a "Microsoft.MachineLearningServices.DatasetDriftDetected" event. */
"Microsoft.MachineLearningServices.DatasetDriftDetected": MachineLearningServicesDatasetDriftDetectedEventData;
/** An interface for the event data of a "Microsoft.MachineLearningServices.ModelDeployed" event. */
"Microsoft.MachineLearningServices.ModelDeployed": MachineLearningServicesModelDeployedEventData;
/** An interface for the event data of a "Microsoft.MachineLearningServices.ModelRegistered" event. */
"Microsoft.MachineLearningServices.ModelRegistered": MachineLearningServicesModelRegisteredEventData;
/** An interface for the event data of a "Microsoft.MachineLearningServices.RunCompleted" event. */
"Microsoft.MachineLearningServices.RunCompleted": MachineLearningServicesRunCompletedEventData;
/** An interface for the event data of a "Microsoft.MachineLearningServices.RunStatusChanged" event. */
"Microsoft.MachineLearningServices.RunStatusChanged": MachineLearningServicesRunStatusChangedEventData;
/** An interface for the event data of a "Microsoft.Maps.GeofenceEntered" event. */
"Microsoft.Maps.GeofenceEntered": MapsGeofenceEnteredEventData;
/** An interface for the event data of a "Microsoft.Maps.GeofenceExited" event. */
"Microsoft.Maps.GeofenceExited": MapsGeofenceExitedEventData;
/** An interface for the event data of a "Microsoft.Maps.GeofenceResult" event. */
"Microsoft.Maps.GeofenceResult": MapsGeofenceResultEventData;
/** An interface for the event data of a "Microsoft.Media.JobStateChange" event. */
"Microsoft.Media.JobStateChange": MediaJobStateChangeEventData;
/** An interface for the event data of a "Microsoft.Media.JobOutputStateChange" event. */
"Microsoft.Media.JobOutputStateChange": MediaJobOutputStateChangeEventData;
/** An interface for the event data of a "Microsoft.Media.JobScheduled" event. */
"Microsoft.Media.JobScheduled": MediaJobScheduledEventData;
/** An interface for the event data of a "Microsoft.Media.JobProcessing" event. */
"Microsoft.Media.JobProcessing": MediaJobProcessingEventData;
/** An interface for the event data of a "Microsoft.Media.JobCanceling" event. */
"Microsoft.Media.JobCanceling": MediaJobCancelingEventData;
/** An interface for the event data of a "Microsoft.Media.JobFinished" event. */
"Microsoft.Media.JobFinished": MediaJobFinishedEventData;
/** An interface for the event data of a "Microsoft.Media.JobCanceled" event. */
"Microsoft.Media.JobCanceled": MediaJobCanceledEventData;
/** An interface for the event data of a "Microsoft.Media.JobErrored" event. */
"Microsoft.Media.JobErrored": MediaJobErroredEventData;
/** An interface for the event data of a "Microsoft.Media.JobOutputCanceled" event. */
"Microsoft.Media.JobOutputCanceled": MediaJobOutputCanceledEventData;
/** An interface for the event data of a "Microsoft.Media.JobOutputCanceling" event. */
"Microsoft.Media.JobOutputCanceling": MediaJobOutputCancelingEventData;
/** An interface for the event data of a "Microsoft.Media.JobOutputErrored" event. */
"Microsoft.Media.JobOutputErrored": MediaJobOutputErroredEventData;
/** An interface for the event data of a "Microsoft.Media.JobOutputFinished" event. */
"Microsoft.Media.JobOutputFinished": MediaJobOutputFinishedEventData;
/** An interface for the event data of a "Microsoft.Media.JobOutputProcessing" event. */
"Microsoft.Media.JobOutputProcessing": MediaJobOutputProcessingEventData;
/** An interface for the event data of a "Microsoft.Media.JobOutputScheduled" event. */
"Microsoft.Media.JobOutputScheduled": MediaJobOutputScheduledEventData;
/** An interface for the event data of a "Microsoft.Media.JobOutputProgress" event. */
"Microsoft.Media.JobOutputProgress": MediaJobOutputProgressEventData;
/** An interface for the event data of a "Microsoft.Media.LiveEventEncoderConnected" event. */
"Microsoft.Media.LiveEventEncoderConnected": MediaLiveEventEncoderConnectedEventData;
/** An interface for the event data of a "Microsoft.Media.LiveEventConnectionRejected" event. */
"Microsoft.Media.LiveEventConnectionRejected": MediaLiveEventConnectionRejectedEventData;
/** An interface for the event data of a "Microsoft.Media.LiveEventEncoderDisconnected" event. */
"Microsoft.Media.LiveEventEncoderDisconnected": MediaLiveEventEncoderDisconnectedEventData;
/** An interface for the event data of a "Microsoft.Media.LiveEventIncomingStreamReceived" event. */
"Microsoft.Media.LiveEventIncomingStreamReceived": MediaLiveEventIncomingStreamReceivedEventData;
/** An interface for the event data of a "Microsoft.Media.LiveEventIncomingStreamsOutOfSync" event. */
"Microsoft.Media.LiveEventIncomingStreamsOutOfSync": MediaLiveEventIncomingStreamsOutOfSyncEventData;
/** An interface for the event data of a "Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync" event. */
"Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync": MediaLiveEventIncomingVideoStreamsOutOfSyncEventData;
/** An interface for the event data of a "Microsoft.Media.LiveEventIncomingDataChunkDropped" event. */
"Microsoft.Media.LiveEventIncomingDataChunkDropped": MediaLiveEventIncomingDataChunkDroppedEventData;
/** An interface for the event data of a "Microsoft.Media.LiveEventIngestHeartbeat" event. */
"Microsoft.Media.LiveEventIngestHeartbeat": MediaLiveEventIngestHeartbeatEventData;
/** An interface for the event data of a "Microsoft.Media.LiveEventTrackDiscontinuityDetected" event. */
"Microsoft.Media.LiveEventTrackDiscontinuityDetected": MediaLiveEventTrackDiscontinuityDetectedEventData;
/** An interface for the event data of a "Microsoft.Resources.ResourceWriteSuccess" event. */
"Microsoft.Resources.ResourceWriteSuccess": ResourceWriteSuccessEventData;
/** An interface for the event data of a "Microsoft.Resources.ResourceWriteFailure" event. */
"Microsoft.Resources.ResourceWriteFailure": ResourceWriteFailureEventData;
/** An interface for the event data of a "Microsoft.Resources.ResourceWriteCancel" event. */
"Microsoft.Resources.ResourceWriteCancel": ResourceWriteCancelEventData;
/** An interface for the event data of a "Microsoft.Resources.ResourceDeleteSuccess" event. */
"Microsoft.Resources.ResourceDeleteSuccess": ResourceDeleteSuccessEventData;
/** An interface for the event data of a "Microsoft.Resources.ResourceDeleteFailure" event. */
"Microsoft.Resources.ResourceDeleteFailure": ResourceDeleteFailureEventData;
/** An interface for the event data of a "Microsoft.Resources.ResourceDeleteCancel" event. */
"Microsoft.Resources.ResourceDeleteCancel": ResourceDeleteCancelEventData;
/** An interface for the event data of a "Microsoft.Resources.ResourceActionSuccess" event. */
"Microsoft.Resources.ResourceActionSuccess": ResourceActionSuccessEventData;
/** An interface for the event data of a "Microsoft.Resources.ResourceActionFailure" event. */
"Microsoft.Resources.ResourceActionFailure": ResourceActionFailureEventData;
/** An interface for the event data of a "Microsoft.Resources.ResourceActionCancel" event. */
"Microsoft.Resources.ResourceActionCancel": ResourceActionCancelEventData;
/** An interface for the event data of a "Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners" event. */
"Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners": ServiceBusActiveMessagesAvailableWithNoListenersEventData;
/** An interface for the event data of a "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener" event. */
"Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener": ServiceBusDeadletterMessagesAvailableWithNoListenersEventData;
/** An interface for the event data of a "Microsoft.Storage.BlobCreated" event. */
"Microsoft.Storage.BlobCreated": StorageBlobCreatedEventData;
/** An interface for the event data of a "Microsoft.Storage.BlobDeleted" event. */
"Microsoft.Storage.BlobDeleted": StorageBlobDeletedEventData;
/** An interface for the event data of a "Microsoft.Storage.BlobRenamed" event. */
"Microsoft.Storage.BlobRenamed": StorageBlobRenamedEventData;
/** An interface for the event data of a "Microsoft.Storage.DirectoryCreated" event. */
"Microsoft.Storage.DirectoryCreated": StorageDirectoryCreatedEventData;
/** An interface for the event data of a "Microsoft.Storage.DirectoryDeleted" event. */
"Microsoft.Storage.DirectoryDeleted": StorageDirectoryDeletedEventData;
/** An interface for the event data of a "Microsoft.Storage.DirectoryRenamed" event. */
"Microsoft.Storage.DirectoryRenamed": StorageDirectoryRenamedEventData;
/** An interface for the event data of a "Microsoft.Storage.LifecyclePolicyCompleted" event. */
"Microsoft.Storage.LifecyclePolicyCompleted": StorageLifecyclePolicyCompletedEventData;
/** An interface for the event data of a "Microsoft.Web.AppUpdated" event. */
"Microsoft.Web.AppUpdated": WebAppUpdatedEventData;
/** An interface for the event data of a "Microsoft.Web.BackupOperationStarted" event. */
"Microsoft.Web.BackupOperationStarted": WebBackupOperationStartedEventData;
/** An interface for the event data of a "Microsoft.Web.BackupOperationCompleted" event. */
"Microsoft.Web.BackupOperationCompleted": WebBackupOperationCompletedEventData;
/** An interface for the event data of a "Microsoft.Web.BackupOperationFailed" event. */
"Microsoft.Web.BackupOperationFailed": WebBackupOperationFailedEventData;
/** An interface for the event data of a "Microsoft.Web.RestoreOperationStarted" event. */
"Microsoft.Web.RestoreOperationStarted": WebRestoreOperationStartedEventData;
/** An interface for the event data of a "Microsoft.Web.RestoreOperationCompleted" event. */
"Microsoft.Web.RestoreOperationCompleted": WebRestoreOperationCompletedEventData;
/** An interface for the event data of a "Microsoft.Web.RestoreOperationFailed" event. */
"Microsoft.Web.RestoreOperationFailed": WebRestoreOperationFailedEventData;
/** An interface for the event data of a "Microsoft.Web.SlotSwapStarted" event. */
"Microsoft.Web.SlotSwapStarted": WebSlotSwapStartedEventData;
/** An interface for the event data of a "Microsoft.Web.SlotSwapCompleted" event. */
"Microsoft.Web.SlotSwapCompleted": WebSlotSwapCompletedEventData;
/** An interface for the event data of a "Microsoft.Web.SlotSwapFailed" event. */
"Microsoft.Web.SlotSwapFailed": WebSlotSwapFailedEventData;
/** An interface for the event data of a "Microsoft.Web.SlotSwapWithPreviewStarted" event. */
"Microsoft.Web.SlotSwapWithPreviewStarted": WebSlotSwapWithPreviewStartedEventData;
/** An interface for the event data of a "Microsoft.Web.SlotSwapWithPreviewCancelled" event. */
"Microsoft.Web.SlotSwapWithPreviewCancelled": WebSlotSwapWithPreviewCancelledEventData;
/** An interface for the event data of a "Microsoft.Web.AppServicePlanUpdated" event. */
"Microsoft.Web.AppServicePlanUpdated": WebAppServicePlanUpdatedEventData;
}
/**
* isCloudEventLike returns "true" when the event is a CloudEvent
*
* @param o Either an EventGrid our CloudEvent event.
*/
function isCloudEventLike(
o: EventGridEvent<unknown> | CloudEvent<unknown>
): o is CloudEvent<unknown> {
return (o as any).source !== undefined;
}
/**
* iSystemEvent returns "true" when a given event is a system event of a given type. When using
* TypeScript, this function acts as a custom type guard and allows the TypeScript compiler to
* identify the underlying data
*
* @param eventType The type of system event to check for, e.g., "Microsoft.AppConfiguration.KeyValueDeleted"
* @param event The event to test.
*/
export function isSystemEvent<T extends KnownSystemEventTypes>(
eventType: T,
event: EventGridEvent<unknown>
): event is EventGridEvent<SystemEventNameToEventData[T]>;
/**
* iSystemEvent returns "true" when a given event is a system event of a given type. When using
* TypeScript, this function acts as a custom type guard and allows the TypeScript compiler to
* identify the underlying data
*
* @param eventType The type of system event to check for, e.g., "Microsoft.AppConfiguration.KeyValueDeleted"
* @param event The event to test.
*/
export function isSystemEvent<T extends KnownSystemEventTypes>(
eventType: T,
event: CloudEvent<unknown>
): event is CloudEvent<SystemEventNameToEventData[T]>;
export function isSystemEvent<T extends KnownSystemEventTypes>(
eventType: T,
event: EventGridEvent<unknown> | CloudEvent<unknown>
): event is
| EventGridEvent<SystemEventNameToEventData[T]>
| CloudEvent<SystemEventNameToEventData[T]> {
if (isCloudEventLike(event)) {
return event.type === eventType;
} else {
return event.eventType === eventType;
}
}

Просмотреть файл

@ -0,0 +1,55 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* Represents a credential defined by a shared signature.
*/
export interface SignatureCredential {
/**
* The signature to be used in authentication.
*/
signature(): string;
}
/**
* A credential type which allows using a "shared access signature" to authenticate with EventGrid
* when sending events.
*
* A shared access signiture may be generated by using `EventGridPublisherClient#generateSharedAccessSignature`
*/
export class EventGridSharedAccessSignatureCredential implements SignatureCredential {
private _signature: string;
/**
* The value of the signature to be used in authentication
*/
public signature(): string {
return this._signature;
}
/**
* Create an instance of an EventGridSharedAccessSignatureCredential for use
* with a service client.
*
* @param {string} signature the signature to use in authentication
*/
constructor(signature: string) {
if (!signature) {
throw new Error("signature must be a non-empty string");
}
this._signature = signature;
}
/**
* Change the value of the signature.
*
* Updates will take effect upon the next request after
* updating the signature value.
*
* @param {string} newSignature the new signature value to be used
*/
public update(newSignature: string): void {
this._signature = newSignature;
}
}

Просмотреть файл

@ -0,0 +1,463 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { Mapper, Serializer } from "@azure/core-http";
import { CustomEventDataDeserializer } from "./models";
import {
AppConfigurationKeyValueDeletedEventData,
AppConfigurationKeyValueModifiedEventData,
AppEventTypeDetail,
AppServicePlanEventTypeDetail,
ContainerRegistryArtifactEventData,
ContainerRegistryArtifactEventTarget,
ContainerRegistryChartDeletedEventData,
ContainerRegistryChartPushedEventData,
ContainerRegistryEventActor,
ContainerRegistryEventData,
ContainerRegistryEventRequest,
ContainerRegistryEventSource,
ContainerRegistryEventTarget,
ContainerRegistryImageDeletedEventData,
ContainerRegistryImagePushedEventData,
DeviceConnectionStateEventInfo,
DeviceConnectionStateEventProperties,
DeviceLifeCycleEventProperties,
DeviceTelemetryEventProperties,
DeviceTwinInfo,
DeviceTwinInfoProperties,
DeviceTwinInfoX509Thumbprint,
DeviceTwinMetadata,
DeviceTwinProperties,
EventHubCaptureFileCreatedEventData,
IotHubDeviceConnectedEventData,
IotHubDeviceCreatedEventData,
IotHubDeviceDeletedEventData,
IotHubDeviceDisconnectedEventData,
IotHubDeviceTelemetryEventData,
KeyVaultCertificateExpiredEventData,
KeyVaultCertificateNearExpiryEventData,
KeyVaultCertificateNewVersionCreatedEventData,
KeyVaultKeyExpiredEventData,
KeyVaultKeyNearExpiryEventData,
KeyVaultKeyNewVersionCreatedEventData,
KeyVaultSecretExpiredEventData,
KeyVaultSecretNearExpiryEventData,
KeyVaultSecretNewVersionCreatedEventData,
MachineLearningServicesDatasetDriftDetectedEventData,
MachineLearningServicesModelDeployedEventData,
MachineLearningServicesModelRegisteredEventData,
MachineLearningServicesRunCompletedEventData,
MachineLearningServicesRunStatusChangedEventData,
MapsGeofenceEnteredEventData,
MapsGeofenceEventProperties,
MapsGeofenceExitedEventData,
MapsGeofenceGeometry,
MapsGeofenceResultEventData,
MediaJobCanceledEventData,
MediaJobCancelingEventData,
MediaJobError,
MediaJobErrorDetail,
MediaJobErroredEventData,
MediaJobFinishedEventData,
MediaJobOutput,
MediaJobOutputAsset,
MediaJobOutputCanceledEventData,
MediaJobOutputCancelingEventData,
MediaJobOutputErroredEventData,
MediaJobOutputFinishedEventData,
MediaJobOutputProcessingEventData,
MediaJobOutputProgressEventData,
MediaJobOutputScheduledEventData,
MediaJobOutputStateChangeEventData,
MediaJobProcessingEventData,
MediaJobScheduledEventData,
MediaJobStateChangeEventData,
MediaLiveEventConnectionRejectedEventData,
MediaLiveEventEncoderConnectedEventData,
MediaLiveEventEncoderDisconnectedEventData,
MediaLiveEventIncomingDataChunkDroppedEventData,
MediaLiveEventIncomingStreamReceivedEventData,
MediaLiveEventIncomingStreamsOutOfSyncEventData,
MediaLiveEventIncomingVideoStreamsOutOfSyncEventData,
MediaLiveEventIngestHeartbeatEventData,
MediaLiveEventTrackDiscontinuityDetectedEventData,
RedisExportRDBCompletedEventData,
RedisImportRDBCompletedEventData,
RedisPatchingCompletedEventData,
RedisScalingCompletedEventData,
ResourceActionCancelEventData,
ResourceActionFailureEventData,
ResourceActionSuccessEventData,
ResourceDeleteCancelEventData,
ResourceDeleteFailureEventData,
ResourceDeleteSuccessEventData,
ResourceWriteCancelEventData,
ResourceWriteFailureEventData,
ResourceWriteSuccessEventData,
ServiceBusActiveMessagesAvailableWithNoListenersEventData,
ServiceBusDeadletterMessagesAvailableWithNoListenersEventData,
SignalRServiceClientConnectionConnectedEventData,
SignalRServiceClientConnectionDisconnectedEventData,
StorageBlobCreatedEventData,
StorageBlobDeletedEventData,
StorageBlobRenamedEventData,
StorageDirectoryCreatedEventData,
StorageDirectoryDeletedEventData,
StorageDirectoryRenamedEventData,
StorageLifecyclePolicyActionSummaryDetail,
StorageLifecyclePolicyCompletedEventData,
SubscriptionDeletedEventData,
SubscriptionValidationEventData,
SubscriptionValidationResponse,
WebAppServicePlanUpdatedEventData,
WebAppServicePlanUpdatedEventDataSku,
WebAppUpdatedEventData,
WebBackupOperationCompletedEventData,
WebBackupOperationFailedEventData,
WebBackupOperationStartedEventData,
WebRestoreOperationCompletedEventData,
WebRestoreOperationFailedEventData,
WebRestoreOperationStartedEventData,
WebSlotSwapCompletedEventData,
WebSlotSwapFailedEventData,
WebSlotSwapStartedEventData,
WebSlotSwapWithPreviewCancelledEventData,
WebSlotSwapWithPreviewStartedEventData
} from "./generated/models/mappers";
const serializer = new Serializer({
AppConfigurationKeyValueDeletedEventData: AppConfigurationKeyValueDeletedEventData,
AppConfigurationKeyValueModifiedEventData: AppConfigurationKeyValueModifiedEventData,
AppEventTypeDetail: AppEventTypeDetail,
AppServicePlanEventTypeDetail: AppServicePlanEventTypeDetail,
ContainerRegistryArtifactEventData: ContainerRegistryArtifactEventData,
ContainerRegistryArtifactEventTarget: ContainerRegistryArtifactEventTarget,
ContainerRegistryChartDeletedEventData: ContainerRegistryChartDeletedEventData,
ContainerRegistryChartPushedEventData: ContainerRegistryChartPushedEventData,
ContainerRegistryEventActor: ContainerRegistryEventActor,
ContainerRegistryEventData: ContainerRegistryEventData,
ContainerRegistryEventRequest: ContainerRegistryEventRequest,
ContainerRegistryEventSource: ContainerRegistryEventSource,
ContainerRegistryEventTarget: ContainerRegistryEventTarget,
ContainerRegistryImageDeletedEventData: ContainerRegistryImageDeletedEventData,
ContainerRegistryImagePushedEventData: ContainerRegistryImagePushedEventData,
DeviceConnectionStateEventInfo: DeviceConnectionStateEventInfo,
DeviceConnectionStateEventProperties: DeviceConnectionStateEventProperties,
DeviceLifeCycleEventProperties: DeviceLifeCycleEventProperties,
DeviceTelemetryEventProperties: DeviceTelemetryEventProperties,
DeviceTwinInfo: DeviceTwinInfo,
DeviceTwinInfoProperties: DeviceTwinInfoProperties,
DeviceTwinInfoX509Thumbprint: DeviceTwinInfoX509Thumbprint,
DeviceTwinMetadata: DeviceTwinMetadata,
DeviceTwinProperties: DeviceTwinProperties,
EventHubCaptureFileCreatedEventData: EventHubCaptureFileCreatedEventData,
IotHubDeviceConnectedEventData: IotHubDeviceConnectedEventData,
IotHubDeviceCreatedEventData: IotHubDeviceCreatedEventData,
IotHubDeviceDeletedEventData: IotHubDeviceDeletedEventData,
IotHubDeviceDisconnectedEventData: IotHubDeviceDisconnectedEventData,
IotHubDeviceTelemetryEventData: IotHubDeviceTelemetryEventData,
KeyVaultCertificateExpiredEventData: KeyVaultCertificateExpiredEventData,
KeyVaultCertificateNearExpiryEventData: KeyVaultCertificateNearExpiryEventData,
KeyVaultCertificateNewVersionCreatedEventData: KeyVaultCertificateNewVersionCreatedEventData,
KeyVaultKeyExpiredEventData: KeyVaultKeyExpiredEventData,
KeyVaultKeyNearExpiryEventData: KeyVaultKeyNearExpiryEventData,
KeyVaultKeyNewVersionCreatedEventData: KeyVaultKeyNewVersionCreatedEventData,
KeyVaultSecretExpiredEventData: KeyVaultSecretExpiredEventData,
KeyVaultSecretNearExpiryEventData: KeyVaultSecretNearExpiryEventData,
KeyVaultSecretNewVersionCreatedEventData: KeyVaultSecretNewVersionCreatedEventData,
MachineLearningServicesDatasetDriftDetectedEventData: MachineLearningServicesDatasetDriftDetectedEventData,
MachineLearningServicesModelDeployedEventData: MachineLearningServicesModelDeployedEventData,
MachineLearningServicesModelRegisteredEventData: MachineLearningServicesModelRegisteredEventData,
MachineLearningServicesRunCompletedEventData: MachineLearningServicesRunCompletedEventData,
MachineLearningServicesRunStatusChangedEventData: MachineLearningServicesRunStatusChangedEventData,
MapsGeofenceEnteredEventData: MapsGeofenceEnteredEventData,
MapsGeofenceEventProperties: MapsGeofenceEventProperties,
MapsGeofenceExitedEventData: MapsGeofenceExitedEventData,
MapsGeofenceGeometry: MapsGeofenceGeometry,
MapsGeofenceResultEventData: MapsGeofenceResultEventData,
MediaJobCanceledEventData: MediaJobCanceledEventData,
MediaJobCancelingEventData: MediaJobCancelingEventData,
MediaJobError: MediaJobError,
MediaJobErrorDetail: MediaJobErrorDetail,
MediaJobErroredEventData: MediaJobErroredEventData,
MediaJobFinishedEventData: MediaJobFinishedEventData,
MediaJobOutput: MediaJobOutput,
MediaJobOutputAsset: MediaJobOutputAsset,
MediaJobOutputCanceledEventData: MediaJobOutputCanceledEventData,
MediaJobOutputCancelingEventData: MediaJobOutputCancelingEventData,
MediaJobOutputErroredEventData: MediaJobOutputErroredEventData,
MediaJobOutputFinishedEventData: MediaJobOutputFinishedEventData,
MediaJobOutputProcessingEventData: MediaJobOutputProcessingEventData,
MediaJobOutputProgressEventData: MediaJobOutputProgressEventData,
MediaJobOutputScheduledEventData: MediaJobOutputScheduledEventData,
MediaJobOutputStateChangeEventData: MediaJobOutputStateChangeEventData,
MediaJobProcessingEventData: MediaJobProcessingEventData,
MediaJobScheduledEventData: MediaJobScheduledEventData,
MediaJobStateChangeEventData: MediaJobStateChangeEventData,
MediaLiveEventConnectionRejectedEventData: MediaLiveEventConnectionRejectedEventData,
MediaLiveEventEncoderConnectedEventData: MediaLiveEventEncoderConnectedEventData,
MediaLiveEventEncoderDisconnectedEventData: MediaLiveEventEncoderDisconnectedEventData,
MediaLiveEventIncomingDataChunkDroppedEventData: MediaLiveEventIncomingDataChunkDroppedEventData,
MediaLiveEventIncomingStreamReceivedEventData: MediaLiveEventIncomingStreamReceivedEventData,
MediaLiveEventIncomingStreamsOutOfSyncEventData: MediaLiveEventIncomingStreamsOutOfSyncEventData,
MediaLiveEventIncomingVideoStreamsOutOfSyncEventData: MediaLiveEventIncomingVideoStreamsOutOfSyncEventData,
MediaLiveEventIngestHeartbeatEventData: MediaLiveEventIngestHeartbeatEventData,
MediaLiveEventTrackDiscontinuityDetectedEventData: MediaLiveEventTrackDiscontinuityDetectedEventData,
RedisExportRDBCompletedEventData: RedisExportRDBCompletedEventData,
RedisImportRDBCompletedEventData: RedisImportRDBCompletedEventData,
RedisPatchingCompletedEventData: RedisPatchingCompletedEventData,
RedisScalingCompletedEventData: RedisScalingCompletedEventData,
ResourceActionCancelEventData: ResourceActionCancelEventData,
ResourceActionFailureEventData: ResourceActionFailureEventData,
ResourceActionSuccessEventData: ResourceActionSuccessEventData,
ResourceDeleteCancelEventData: ResourceDeleteCancelEventData,
ResourceDeleteFailureEventData: ResourceDeleteFailureEventData,
ResourceDeleteSuccessEventData: ResourceDeleteSuccessEventData,
ResourceWriteCancelEventData: ResourceWriteCancelEventData,
ResourceWriteFailureEventData: ResourceWriteFailureEventData,
ResourceWriteSuccessEventData: ResourceWriteSuccessEventData,
ServiceBusActiveMessagesAvailableWithNoListenersEventData: ServiceBusActiveMessagesAvailableWithNoListenersEventData,
ServiceBusDeadletterMessagesAvailableWithNoListenersEventData: ServiceBusDeadletterMessagesAvailableWithNoListenersEventData,
SignalRServiceClientConnectionConnectedEventData: SignalRServiceClientConnectionConnectedEventData,
SignalRServiceClientConnectionDisconnectedEventData: SignalRServiceClientConnectionDisconnectedEventData,
StorageBlobCreatedEventData: StorageBlobCreatedEventData,
StorageBlobDeletedEventData: StorageBlobDeletedEventData,
StorageBlobRenamedEventData: StorageBlobRenamedEventData,
StorageDirectoryCreatedEventData: StorageDirectoryCreatedEventData,
StorageDirectoryDeletedEventData: StorageDirectoryDeletedEventData,
StorageDirectoryRenamedEventData: StorageDirectoryRenamedEventData,
StorageLifecyclePolicyActionSummaryDetail: StorageLifecyclePolicyActionSummaryDetail,
StorageLifecyclePolicyCompletedEventData: StorageLifecyclePolicyCompletedEventData,
SubscriptionDeletedEventData: SubscriptionDeletedEventData,
SubscriptionValidationEventData: SubscriptionValidationEventData,
SubscriptionValidationResponse: SubscriptionValidationResponse,
WebAppServicePlanUpdatedEventData: WebAppServicePlanUpdatedEventData,
WebAppServicePlanUpdatedEventDataSku: WebAppServicePlanUpdatedEventDataSku,
WebAppUpdatedEventData: WebAppUpdatedEventData,
WebBackupOperationCompletedEventData: WebBackupOperationCompletedEventData,
WebBackupOperationFailedEventData: WebBackupOperationFailedEventData,
WebBackupOperationStartedEventData: WebBackupOperationStartedEventData,
WebRestoreOperationCompletedEventData: WebRestoreOperationCompletedEventData,
WebRestoreOperationFailedEventData: WebRestoreOperationFailedEventData,
WebRestoreOperationStartedEventData: WebRestoreOperationStartedEventData,
WebSlotSwapCompletedEventData: WebSlotSwapCompletedEventData,
WebSlotSwapFailedEventData: WebSlotSwapFailedEventData,
WebSlotSwapStartedEventData: WebSlotSwapStartedEventData,
WebSlotSwapWithPreviewCancelledEventData: WebSlotSwapWithPreviewCancelledEventData,
WebSlotSwapWithPreviewStartedEventData: WebSlotSwapWithPreviewStartedEventData
});
function makeDeserializerFromMapper(
mapper: Mapper,
initialDeserializers?: CustomEventDataDeserializer[]
): CustomEventDataDeserializer {
return async function(o: any): Promise<any> {
if (initialDeserializers) {
for (const deserializer of initialDeserializers) {
o = await deserializer(o);
}
}
return serializer.deserialize(mapper, o, "");
};
}
// Some system events are published in a format that does not match the schema they publish. In these cases, the "event data"
// field is actually a string with the event data encoded as JSON. For the few system events we know of that are incorrect we
// use this deserializer to convert from the string to an object. This function is written such that it is a no-op when a non
// string value is provided (i.e. when the system events are corrected to publish the data as an actual object, we will not break).
async function jsonParseDeserializer(o: any): Promise<any> {
if (typeof o === "string") {
return JSON.parse(o);
}
return o;
}
export const systemDeserializers: Record<string, CustomEventDataDeserializer> = {
"Microsoft.AppConfiguration.KeyValueDeleted": makeDeserializerFromMapper(
AppConfigurationKeyValueDeletedEventData
),
"Microsoft.AppConfiguration.KeyValueModified": makeDeserializerFromMapper(
AppConfigurationKeyValueModifiedEventData
),
"Microsoft.ContainerRegistry.ChartDeleted": makeDeserializerFromMapper(
ContainerRegistryEventData,
[jsonParseDeserializer]
),
"Microsoft.ContainerRegistry.ChartPushed": makeDeserializerFromMapper(
ContainerRegistryEventData,
[jsonParseDeserializer]
),
"Microsoft.ContainerRegistry.ImageDeleted": makeDeserializerFromMapper(
ContainerRegistryEventData,
[jsonParseDeserializer]
),
"Microsoft.ContainerRegistry.ImagePushed": makeDeserializerFromMapper(
ContainerRegistryEventData,
[jsonParseDeserializer]
),
"Microsoft.Devices.DeviceCreated": makeDeserializerFromMapper(IotHubDeviceCreatedEventData),
"Microsoft.Devices.DeviceDeleted": makeDeserializerFromMapper(IotHubDeviceDeletedEventData),
"Microsoft.Devices.DeviceConnected": makeDeserializerFromMapper(IotHubDeviceConnectedEventData),
"Microsoft.Devices.DeviceDisconnected": makeDeserializerFromMapper(
IotHubDeviceDisconnectedEventData
),
"Microsoft.Devices.DeviceTelemetry": makeDeserializerFromMapper(IotHubDeviceTelemetryEventData),
"Microsoft.EventGrid.SubscriptionValidationEvent": makeDeserializerFromMapper(
SubscriptionValidationEventData
),
"Microsoft.EventGrid.SubscriptionDeletedEvent": makeDeserializerFromMapper(
SubscriptionDeletedEventData
),
"Microsoft.EventHub.CaptureFileCreated": makeDeserializerFromMapper(
EventHubCaptureFileCreatedEventData
),
"Microsoft.MachineLearningServices.DatasetDriftDetected": makeDeserializerFromMapper(
MachineLearningServicesDatasetDriftDetectedEventData
),
"Microsoft.MachineLearningServices.ModelDeployed": makeDeserializerFromMapper(
MachineLearningServicesModelDeployedEventData
),
"Microsoft.MachineLearningServices.ModelRegistered": makeDeserializerFromMapper(
MachineLearningServicesModelRegisteredEventData
),
"Microsoft.MachineLearningServices.RunCompleted": makeDeserializerFromMapper(
MachineLearningServicesRunCompletedEventData
),
"Microsoft.MachineLearningServices.RunStatusChanged": makeDeserializerFromMapper(
MachineLearningServicesRunStatusChangedEventData
),
"Microsoft.Maps.GeofenceEntered": makeDeserializerFromMapper(MapsGeofenceEnteredEventData),
"Microsoft.Maps.GeofenceExited": makeDeserializerFromMapper(MapsGeofenceExitedEventData),
"Microsoft.Maps.GeofenceResult": makeDeserializerFromMapper(MapsGeofenceResultEventData),
"Microsoft.Media.JobStateChange": makeDeserializerFromMapper(MediaJobStateChangeEventData),
"Microsoft.Media.JobOutputStateChange": makeDeserializerFromMapper(
MediaJobOutputStateChangeEventData
),
"Microsoft.Media.JobScheduled": makeDeserializerFromMapper(MediaJobScheduledEventData),
"Microsoft.Media.JobProcessing": makeDeserializerFromMapper(MediaJobProcessingEventData),
"Microsoft.Media.JobCanceling": makeDeserializerFromMapper(MediaJobCancelingEventData),
"Microsoft.Media.JobFinished": makeDeserializerFromMapper(MediaJobFinishedEventData),
"Microsoft.Media.JobCanceled": makeDeserializerFromMapper(MediaJobCanceledEventData),
"Microsoft.Media.JobErrored": makeDeserializerFromMapper(MediaJobErroredEventData),
"Microsoft.Media.JobOutputCanceled": makeDeserializerFromMapper(MediaJobOutputCanceledEventData),
"Microsoft.Media.JobOutputCanceling": makeDeserializerFromMapper(
MediaJobOutputCancelingEventData
),
"Microsoft.Media.JobOutputErrored": makeDeserializerFromMapper(MediaJobOutputErroredEventData),
"Microsoft.Media.JobOutputFinished": makeDeserializerFromMapper(MediaJobOutputFinishedEventData),
"Microsoft.Media.JobOutputProcessing": makeDeserializerFromMapper(
MediaJobOutputProcessingEventData
),
"Microsoft.Media.JobOutputScheduled": makeDeserializerFromMapper(
MediaJobOutputScheduledEventData
),
"Microsoft.Media.JobOutputProgress": makeDeserializerFromMapper(MediaJobOutputProgressEventData),
"Microsoft.Media.LiveEventEncoderConnected": makeDeserializerFromMapper(
MediaLiveEventEncoderConnectedEventData
),
"Microsoft.Media.LiveEventConnectionRejected": makeDeserializerFromMapper(
MediaLiveEventConnectionRejectedEventData
),
"Microsoft.Media.LiveEventEncoderDisconnected": makeDeserializerFromMapper(
MediaLiveEventEncoderDisconnectedEventData
),
"Microsoft.Media.LiveEventIncomingStreamReceived": makeDeserializerFromMapper(
MediaLiveEventIncomingStreamReceivedEventData
),
"Microsoft.Media.LiveEventIncomingStreamsOutOfSync": makeDeserializerFromMapper(
MediaLiveEventIncomingStreamsOutOfSyncEventData
),
"Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync": makeDeserializerFromMapper(
MediaLiveEventIncomingVideoStreamsOutOfSyncEventData
),
"Microsoft.Media.LiveEventIncomingDataChunkDropped": makeDeserializerFromMapper(
MediaLiveEventIncomingDataChunkDroppedEventData
),
"Microsoft.Media.LiveEventIngestHeartbeat": makeDeserializerFromMapper(
MediaLiveEventIngestHeartbeatEventData
),
"Microsoft.Media.LiveEventTrackDiscontinuityDetected": makeDeserializerFromMapper(
MediaLiveEventTrackDiscontinuityDetectedEventData
),
"Microsoft.Resources.ResourceWriteSuccess": makeDeserializerFromMapper(
ResourceWriteSuccessEventData
),
"Microsoft.Resources.ResourceWriteFailure": makeDeserializerFromMapper(
ResourceWriteFailureEventData
),
"Microsoft.Resources.ResourceWriteCancel": makeDeserializerFromMapper(
ResourceWriteCancelEventData
),
"Microsoft.Resources.ResourceDeleteSuccess": makeDeserializerFromMapper(
ResourceDeleteSuccessEventData
),
"Microsoft.Resources.ResourceDeleteFailure": makeDeserializerFromMapper(
ResourceDeleteFailureEventData
),
"Microsoft.Resources.ResourceDeleteCancel": makeDeserializerFromMapper(
ResourceDeleteCancelEventData
),
"Microsoft.Resources.ResourceActionSuccess": makeDeserializerFromMapper(
ResourceActionSuccessEventData
),
"Microsoft.Resources.ResourceActionFailure": makeDeserializerFromMapper(
ResourceActionFailureEventData
),
"Microsoft.Resources.ResourceActionCancel": makeDeserializerFromMapper(
ResourceActionCancelEventData
),
"Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners": makeDeserializerFromMapper(
ServiceBusActiveMessagesAvailableWithNoListenersEventData
),
"Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener": makeDeserializerFromMapper(
ServiceBusDeadletterMessagesAvailableWithNoListenersEventData
),
"Microsoft.Storage.BlobCreated": makeDeserializerFromMapper(StorageBlobCreatedEventData),
"Microsoft.Storage.BlobDeleted": makeDeserializerFromMapper(StorageBlobDeletedEventData),
"Microsoft.Storage.BlobRenamed": makeDeserializerFromMapper(StorageBlobRenamedEventData),
"Microsoft.Storage.DirectoryCreated": makeDeserializerFromMapper(
StorageDirectoryCreatedEventData
),
"Microsoft.Storage.DirectoryDeleted": makeDeserializerFromMapper(
StorageDirectoryDeletedEventData
),
"Microsoft.Storage.DirectoryRenamed": makeDeserializerFromMapper(
StorageDirectoryRenamedEventData
),
"Microsoft.Storage.LifecyclePolicyCompleted": makeDeserializerFromMapper(
StorageLifecyclePolicyCompletedEventData
),
"Microsoft.Web.AppUpdated": makeDeserializerFromMapper(WebAppUpdatedEventData),
"Microsoft.Web.BackupOperationStarted": makeDeserializerFromMapper(
WebBackupOperationStartedEventData
),
"Microsoft.Web.BackupOperationCompleted": makeDeserializerFromMapper(
WebBackupOperationCompletedEventData
),
"Microsoft.Web.BackupOperationFailed": makeDeserializerFromMapper(
WebBackupOperationFailedEventData
),
"Microsoft.Web.RestoreOperationStarted": makeDeserializerFromMapper(
WebRestoreOperationStartedEventData
),
"Microsoft.Web.RestoreOperationCompleted": makeDeserializerFromMapper(
WebRestoreOperationCompletedEventData
),
"Microsoft.Web.RestoreOperationFailed": makeDeserializerFromMapper(
WebRestoreOperationFailedEventData
),
"Microsoft.Web.SlotSwapStarted": makeDeserializerFromMapper(WebSlotSwapStartedEventData),
"Microsoft.Web.SlotSwapCompleted": makeDeserializerFromMapper(WebSlotSwapCompletedEventData),
"Microsoft.Web.SlotSwapFailed": makeDeserializerFromMapper(WebSlotSwapFailedEventData),
"Microsoft.Web.SlotSwapWithPreviewStarted": makeDeserializerFromMapper(
WebSlotSwapWithPreviewStartedEventData
),
"Microsoft.Web.SlotSwapWithPreviewCancelled": makeDeserializerFromMapper(
WebSlotSwapWithPreviewCancelledEventData
),
"Microsoft.Web.AppServicePlanUpdated": makeDeserializerFromMapper(
WebAppServicePlanUpdatedEventData
)
};

Просмотреть файл

@ -0,0 +1,136 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { KeyCredential } from "@azure/core-auth";
/**
* Stringifies a Date object in the format expected by the Event Grid service, for use in a Shared Access Signiture.
*
* The service expects this time string to be in the same format as what is returned by the .NET DateTime.ToString
* method, using the "en-US" culture.
*
* This corresponds to the .NET format string: "M/d/yyyy h:mm:ss tt". For example, the date "June 5th, 2020, 12:09:03 PM"
* is represented as the string "6/5/2020 12:09:03 PM"
*
* The service expects a UTC time, so this method returns a string based on the UTC time of the provided Date.
*
* @param d The Date object to convert to a string.
*/
export function dateToServiceTimeString(d: Date): string {
const month = d.getUTCMonth() + 1; // getUTCMonth returns 0-11 not 1-12.
const day = d.getUTCDate();
const year = d.getUTCFullYear();
const hour = d.getUTCHours() === 0 ? 12 : d.getUTCHours() % 12; // getUTCHours returns 0-23, and we want this in 12 hour format.
const minute = d
.getUTCMinutes()
.toString()
.padStart(2, "0");
const second = d
.getUTCSeconds()
.toString()
.padStart(2, "0");
const am = d.getUTCHours() >= 13 ? "PM" : "AM";
return `${month}/${day}/${year} ${hour}:${minute}:${second} ${am}`;
}
/**
* Returns `true` if the credential object is like the KeyCredential interface (i.e. it has a
* key property).
*
* @param credential the object to test
*/
export function isKeyCredentialLike(o: any): o is KeyCredential {
return o.key !== undefined;
}
export function parseAndWrap(jsonStringOrObject: string | object): any[] {
if (typeof jsonStringOrObject === "string") {
const o = JSON.parse(jsonStringOrObject);
if (Array.isArray(o)) {
return o;
} else {
return [o];
}
}
if (Array.isArray(jsonStringOrObject)) {
return jsonStringOrObject;
} else {
return [jsonStringOrObject];
}
}
const EVENT_GRID_SCHEMA_METADATA_VERSION = "1";
export function validateEventGridEvent(o: any): void {
if (typeof o !== "object") {
throw new TypeError("event is not an object");
}
validateRequiredStringProperties(o, [
"eventType",
"eventTime",
"id",
"subject",
"topic",
"dataVersion",
"metadataVersion"
]);
validateRequiredAnyProperties(o, ["data"]);
if (o.metadataVersion !== EVENT_GRID_SCHEMA_METADATA_VERSION) {
throw new TypeError("event is not in the Event Grid schema");
}
}
const CLOUD_EVENT_1_0_SPEC_VERSION = "1.0";
export function validateCloudEventEvent(o: any): void {
validateRequiredStringProperties(o, ["type", "source", "id", "specversion"]);
validateOptionalStringProperties(o, ["time", "dataschema", "datacontenttype", "subject"]);
if (typeof o !== "object") {
throw new TypeError("event is not an object");
}
if (o.specversion !== CLOUD_EVENT_1_0_SPEC_VERSION) {
throw new Error("event is not in the Cloud Event 1.0 schema");
}
}
function validateRequiredStringProperties(o: any, propertyNames: string[]): void {
for (const propertyName of propertyNames) {
if (typeof o[propertyName] === "undefined") {
throw new Error(`event is missing required property '${propertyName}'`);
}
if (typeof o[propertyName] !== "string") {
throw new TypeError(
`event property '${propertyName} should be a 'string', but is '${typeof o[propertyName]}'`
);
}
}
}
function validateRequiredAnyProperties(o: any, propertyNames: string[]): void {
for (const propertyName of propertyNames) {
if (typeof o[propertyName] === "undefined") {
throw new Error(`event is missing required property '${propertyName}'`);
}
}
}
function validateOptionalStringProperties(o: any, propertyNames: string[]): void {
for (const propertyName of propertyNames) {
if (typeof o[propertyName] !== "undefined" && typeof o[propertyName] !== "string") {
throw new TypeError(
`event property '${propertyName}' should be a 'string' but it is a '${typeof o[
propertyName
]}'`
);
}
}
}

Просмотреть файл

@ -0,0 +1,52 @@
# Azure Text Analytics TypeScript Protocol Layer
> see https://aka.ms/autorest
## Configuration
```yaml
package-name: "@azure/eventgrid"
title: GeneratedClient
description: EventGrid Client
generate-metadata: false
add-credentials: false
license-header: MICROSOFT_MIT_NO_VERSION
output-folder: ../
source-code-folder-path: ./src/generated
input-file:
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.Storage/stable/2018-01-01/Storage.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.EventHub/stable/2018-01-01/EventHub.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.Resources/stable/2018-01-01/Resources.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.EventGrid/stable/2018-01-01/EventGrid.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.Devices/stable/2018-01-01/IotHub.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.ContainerRegistry/stable/2018-01-01/ContainerRegistry.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.ServiceBus/stable/2018-01-01/ServiceBus.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.Media/stable/2018-01-01/MediaServices.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.Maps/stable/2018-01-01/Maps.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.AppConfiguration/stable/2018-01-01/AppConfiguration.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.SignalRService/stable/2018-01-01/SignalRService.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.KeyVault/stable/2018-01-01/KeyVault.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.MachineLearningServices/stable/2018-01-01/MachineLearningServices.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.Cache/stable/2018-01-01/RedisCache.json
- https://raw.githubusercontent.com/ellismg/azure-rest-api-specs/dev-eventgrid-Microsoft.EventGrid-2018-01-01/specification/eventgrid/data-plane/Microsoft.Web/stable/2018-01-01/Web.json
use-extension:
"@autorest/typescript": "6.0.0-dev.20200618.1"
```
## Customizations
### Use the "EventData" suffix on the Azure Resource Manager Event types, instead of just "Data"
```yaml
directive:
- from: swagger-document
where: $.definitions
transform: >
["Write", "Delete", "Action"].forEach(action => {
["Success", "Failure", "Cancel"].forEach(status => {
if ($[`Resource${action}${status}Data`]) {
$[`Resource${action}${status}Data`]["x-ms-client-name"] = `Resource${action}${status}EventData`;
}
});
});
```

Просмотреть файл

@ -0,0 +1,192 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { assert, use as chaiUse } from "chai";
import chaiPromises from "chai-as-promised";
import { EventGridConsumer } from "../src";
import * as testData from "./utils/testData";
chaiUse(chaiPromises);
describe("EventGridConsumer", function() {
const consumer = new EventGridConsumer();
describe("#deserializeEventGridEvents", function() {
it("deserializes a single event", async () => {
const events = await consumer.deserializeEventGridEvents(
testData.customTestEvent1.eventGridSchema.encodedEvent
);
assert.lengthOf(events, 1);
assert.deepStrictEqual(events[0], testData.customTestEvent1.eventGridSchema.expected);
});
it("deserialized a batch with a single event ", async () => {
const events = await consumer.deserializeEventGridEvents(
wrapEncodedEventsInArray([testData.customTestEvent1.eventGridSchema])
);
assert.lengthOf(events, 1);
assert.deepStrictEqual(events[0], testData.customTestEvent1.eventGridSchema.expected);
});
it("deserializes an batch of multiple events", async () => {
const events = await consumer.deserializeEventGridEvents(
wrapEncodedEventsInArray([
testData.customTestEvent1.eventGridSchema,
testData.customTestEvent2.eventGridSchema
])
);
assert.lengthOf(events, 2);
assert.deepStrictEqual(events[0], testData.customTestEvent1.eventGridSchema.expected);
assert.deepStrictEqual(events[1], testData.customTestEvent2.eventGridSchema.expected);
});
it("deserializes system events correctly", async () => {
const events = await consumer.deserializeEventGridEvents(
testData.containerRegistryPushedEvent.eventGridSchema.encodedEvent
);
assert.lengthOf(events, 1);
assert.deepStrictEqual(
events[0],
testData.containerRegistryPushedEvent.eventGridSchema.expected
);
});
it("fails when a required property is missing", () => {
const o = { ...testData.customTestEvent1.eventGridSchema.expected };
for (const property of [
"eventType",
"eventTime",
"id",
"metadataVersion",
"data",
"dataVersion"
]) {
delete o[property];
assert.isRejected(
consumer.deserializeEventGridEvents(JSON.stringify(o)),
/missing required property/
);
}
});
it("fails when metadata version is wrong", () => {
const o = { ...testData.customTestEvent1.eventGridSchema.expected };
o.metadataVersion = "2";
assert.isRejected(
consumer.deserializeEventGridEvents(JSON.stringify(o)),
/event is not in the Event Grid schema/
);
});
});
describe("#deserializeCloudEvents", function() {
it("deserializes a single event", async () => {
const events = await consumer.deserializeCloudEvents(
testData.customTestEvent1.cloudEventSchema.encodedEvent
);
assert.lengthOf(events, 1);
assert.deepStrictEqual(events[0], testData.customTestEvent1.cloudEventSchema.expected);
});
it("deserialized a batch with a single event ", async () => {
const events = await consumer.deserializeCloudEvents(
wrapEncodedEventsInArray([testData.customTestEvent1.cloudEventSchema])
);
assert.lengthOf(events, 1);
assert.deepStrictEqual(events[0], testData.customTestEvent1.cloudEventSchema.expected);
});
it("deserializes an batch of multiple events", async () => {
const events = await consumer.deserializeCloudEvents(
wrapEncodedEventsInArray([
testData.customTestEvent1.cloudEventSchema,
testData.customTestEvent2.cloudEventSchema
])
);
assert.lengthOf(events, 2);
assert.deepStrictEqual(events[0], testData.customTestEvent1.cloudEventSchema.expected);
assert.deepStrictEqual(events[1], testData.customTestEvent2.cloudEventSchema.expected);
});
it("deserializes system events correctly", async () => {
const events = await consumer.deserializeCloudEvents(
testData.containerRegistryPushedEvent.cloudEventSchema.encodedEvent
);
assert.lengthOf(events, 1);
assert.deepStrictEqual(
events[0],
testData.containerRegistryPushedEvent.cloudEventSchema.expected
);
});
it("fails when a required property is missing", () => {
const o = { ...testData.customTestEvent1.cloudEventSchema.expected };
for (const property of ["type", "source", "id", "specversion"]) {
delete o[property];
assert.isRejected(
consumer.deserializeCloudEvents(JSON.stringify(o)),
/missing required property/
);
}
});
it("fails when spec version is wrong", () => {
const o = { ...testData.customTestEvent1.cloudEventSchema.expected };
o.specversion = "2.0";
assert.isRejected(
consumer.deserializeCloudEvents(JSON.stringify(o)),
/event is not in the Cloud Event 1.0 schema/
);
});
it("decodes byte arrays for cloud events as expected", async () => {
const events = await consumer.deserializeCloudEvents({
type: "Azure.Sdk.TestEvent",
id: "a-unique-id",
source: "/azure/sdk/test",
specversion: "1.0",
data_base64: "AAECAwQFBgcICQ==" /* Base 64 encoding of: 0x01 0x02 ... 0x09 */
});
assert.strictEqual(events.length, 1);
const data = events[0].data;
assert.instanceOf(data, Uint8Array);
assert.strictEqual((data as Uint8Array).length, 10);
for (let i = 0; i < 10; i++) {
assert.strictEqual((data as Uint8Array)[i], i);
}
assert.isUndefined((data as any)["data_base64"]);
});
});
});
/**
* wrapEncodedEventsInArray takes the encoded events for a set of test cases and returns a string
* which is the JSON encoding of an array containing all the encoded events.
*/
function wrapEncodedEventsInArray(testCases: testData.TestCase[]): string {
const foo = [];
for (const testCase of testCases) {
foo.push(JSON.parse(testCase.encodedEvent));
}
return JSON.stringify(foo);
}

Просмотреть файл

@ -0,0 +1,355 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/* eslint-disable no-invalid-this */
import { assert } from "chai";
import { Recorder } from "@azure/test-utils-recorder";
import { createRecordedClient, testEnv } from "./utils/recordedClient";
import { AzureKeyCredential, EventGridPublisherClient } from "../src/index";
import {
convertEventGridEventToModelType,
convertCloudEventToModelType
} from "../src/eventGridClient";
describe("EventGridPublisherClient", function() {
let recorder: Recorder;
let client: EventGridPublisherClient;
this.timeout(10000);
describe("#sendEvents", function() {
beforeEach(function() {
({ client, recorder } = createRecordedClient(
this,
testEnv.EVENT_GRID_EVENT_GRID_SCHEMA_ENDPOINT,
new AzureKeyCredential(testEnv.EVENT_GRID_EVENT_GRID_SCHEMA_API_KEY)
));
});
afterEach(function() {
recorder.stop();
});
it("sends a single event", async () => {
const res = await client.sendEvents([
{
eventTime: recorder.newDate("singleEventDate"),
id: recorder.getUniqueName("singleEventId"),
eventType: "Azure.Sdk.TestEvent1",
subject: "Single 1",
dataVersion: "1.0",
data: {
hello: "world"
}
}
]);
assert.equal(res._response.status, 200);
});
it("sends multiple events", async () => {
const res = await client.sendEvents([
{
eventTime: recorder.newDate("multiEventDate1"),
id: recorder.getUniqueName("multiEventId1"),
eventType: "Azure.Sdk.TestEvent1",
subject: "Multiple 1",
dataVersion: "1.0",
data: {
hello: "world"
}
},
{
eventTime: recorder.newDate("multiEventDate2"),
id: recorder.getUniqueName("multiEventId2"),
eventType: "Azure.Sdk.TestEvent1",
subject: "Multiple 2",
dataVersion: "1.0",
data: {
hello: "world"
}
}
]);
assert.equal(res._response.status, 200);
});
});
describe("#sendCloudEventSchemaEvents", function() {
beforeEach(function() {
({ client, recorder } = createRecordedClient(
this,
testEnv.EVENT_GRID_CLOUD_EVENT_SCHEMA_ENDPOINT,
new AzureKeyCredential(testEnv.EVENT_GRID_CLOUD_EVENT_SCHEMA_API_KEY)
));
});
afterEach(function() {
recorder.stop();
});
it("sends a single event", async () => {
const res = await client.sendCloudEvents([
{
type: "Azure.Sdk.TestEvent1",
id: recorder.getUniqueName("cloudSingleEventId"),
time: recorder.newDate("cloudSingleEventDate"),
source: "/earth/unitedstates/washington/kirkland/finnhill",
data: {
hello: "world"
}
}
]);
assert.equal(res._response.status, 200);
});
it("sends multiple events", async () => {
const res = await client.sendCloudEvents([
{
type: "Azure.Sdk.TestEvent1",
id: recorder.getUniqueName("cloudMultiEventId1"),
time: recorder.newDate("cloudMultiEventDate1"),
source: "/earth/unitedstates/washington/kirkland/finnhill",
subject: "Multiple 1",
data: {
hello: "world"
}
},
{
type: "Azure.Sdk.TestEvent1",
id: recorder.getUniqueName("cloudMultiEventId2"),
time: recorder.newDate("cloudMultiEventDate2"),
source: "/earth/unitedstates/washington/kirkland/finnhill",
subject: "Multiple 2",
data: {
hello: "world"
}
}
]);
assert.equal(res._response.status, 200);
});
});
describe("#sendCustomSchemaEvents", function() {
beforeEach(function() {
({ client, recorder } = createRecordedClient(
this,
testEnv.EVENT_GRID_CUSTOM_SCHEMA_ENDPOINT,
new AzureKeyCredential(testEnv.EVENT_GRID_CUSTOM_SCHEMA_API_KEY)
));
});
afterEach(function() {
recorder.stop();
});
it("sends a single event", async () => {
const res = await client.sendCustomSchemaEvents([
{
ver: "1.0",
typ: "Azure.Sdk.TestEvent1",
sub: "Single",
payload: {
hello: "world"
}
}
]);
assert.equal(res._response.status, 200);
});
it("sends multiple events", async () => {
const res = await client.sendCustomSchemaEvents([
{
ver: "1.0",
typ: "Azure.Sdk.TestEvent1",
sub: "Multiple 1",
payload: {
hello: "world"
}
},
{
ver: "1.0",
typ: "Azure.Sdk.TestEvent1",
sub: "Multiple 2",
payload: {
hello: "world"
}
}
]);
assert.equal(res._response.status, 200);
});
});
});
describe("convertEventGridEventToModelType", function() {
it("sets a default ID if one is not provided", () => {
const convertedEvent = convertEventGridEventToModelType({
dataVersion: "1.0",
eventType: "Azure.Sdk.TestEvent",
subject: "Test Event",
data: { hello: "world " }
});
assert.isDefined(convertedEvent.id);
});
it("sets a default event time if one is not provided", () => {
const convertedEvent = convertEventGridEventToModelType({
dataVersion: "1.0",
eventType: "Azure.Sdk.TestEvent",
subject: "Test Event",
data: { hello: "world " }
});
assert.isDefined(convertedEvent.eventTime);
});
it("does not change set values", () => {
const time = new Date();
const id = "272871ba-2496-4750-9a90-bedd1ea10191";
const convertedEvent = convertEventGridEventToModelType({
id: id,
eventTime: time,
dataVersion: "1.0",
eventType: "Azure.Sdk.TestEvent",
subject: "Test Event",
data: { hello: "world " }
});
assert.strictEqual(convertedEvent.id, id);
assert.strictEqual(convertedEvent.eventTime, time);
});
});
describe("convertCloudEventToModelType", function() {
it("sets a default ID if one is not provided", () => {
const convertedEvent = convertCloudEventToModelType({
source: "/azure/sdk/tests",
type: "Azure.Sdk.TestEvent"
});
assert.isDefined(convertedEvent.id);
});
it("sets a default event time if one is not provided", () => {
const convertedEvent = convertCloudEventToModelType({
source: "/azure/sdk/tests",
type: "Azure.Sdk.TestEvent"
});
assert.isDefined(convertedEvent.time);
});
it("does not change set values", () => {
const time = new Date();
const id = "272871ba-2496-4750-9a90-bedd1ea10191";
const convertedEvent = convertCloudEventToModelType({
id: id,
time: time,
source: "/azure/sdk/tests",
type: "Azure.Sdk.TestEvent"
});
assert.strictEqual(convertedEvent.id, id);
assert.strictEqual(convertedEvent.time, time);
});
it("promotes extension attributes", () => {
const traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
const tracestate =
"rojo=00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01,congo=lZWRzIHRoNhcm5hbCBwbGVhc3VyZS4";
const convertedEvent = convertCloudEventToModelType({
source: "/azure/sdk/tests",
type: "Azure.Sdk.TestEvent",
extensionAttributes: {
traceparent,
tracestate
}
});
// When converted to a model type to send over the wire, the extension attributes are promoted to be
// properties on the envelope itself.
assert.equal(convertedEvent["traceparent"], traceparent);
assert.equal(convertedEvent["tracestate"], tracestate);
});
it("base64 encodes binary data", () => {
const binaryData = new Uint8Array(10);
for (let i = 0; i < binaryData.length; i++) {
binaryData[i] = i;
}
const convertedEvent = convertCloudEventToModelType({
source: "/azure/sdk/tests",
type: "Azure.Sdk.TestEvent",
data: binaryData,
datacontenttype: "application/binary"
});
assert.isUndefined(convertedEvent.data);
assert.strictEqual(convertedEvent.dataBase64, binaryData);
});
it("fails if data content type is missing for binary data", () => {
const binaryData = new Uint8Array(10);
for (let i = 0; i < binaryData.length; i++) {
binaryData[i] = i;
}
assert.throws(() => {
convertCloudEventToModelType({
source: "/azure/sdk/tests",
type: "Azure.Sdk.TestEvent",
data: binaryData
});
}, /data content type/);
});
it("fails if extenion attributes are invalid", () => {
const binaryData = new Uint8Array(10);
for (let i = 0; i < binaryData.length; i++) {
binaryData[i] = i;
}
assert.throws(() => {
convertCloudEventToModelType({
source: "/azure/sdk/tests",
type: "Azure.Sdk.TestEvent",
extensionAttributes: {
source: "this-is-not-allowed"
}
});
}, /invalid extension attribute name: source/);
assert.throws(() => {
convertCloudEventToModelType({
source: "/azure/sdk/tests",
type: "Azure.Sdk.TestEvent",
extensionAttributes: {
MiXedCasE: "this-is-not-allowed"
}
});
}, /invalid extension attribute name: MiXedCasE/);
assert.throws(() => {
convertCloudEventToModelType({
source: "/azure/sdk/tests",
type: "Azure.Sdk.TestEvent",
extensionAttributes: {
data_base64: "this-is-not-allowed"
}
});
}, /invalid extension attribute name: data_base64/);
});
});

Просмотреть файл

@ -0,0 +1,25 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { assert } from "chai";
import { AzureKeyCredential, generateSharedAccessSignature } from "../src/index";
describe("generateSharedAccessSignature", function() {
it("generates the correct signiture", async () => {
// This is not a real key, it's the base64 encoding of "this is not a real EventGrid key", which happens to be the same
// number of bytes as an actual EventGrid Access Key.
const key = "dGhpcyBpcyBub3QgYSByZWFsIEV2ZW50R3JpZCBrZXk=";
const topicUrl = "https://eg-topic.westus-2.eventgrid.azure.net/api/events";
const sig = await generateSharedAccessSignature(
topicUrl,
new AzureKeyCredential(key),
new Date(Date.UTC(2020, 0, 1, 0, 0, 0))
);
assert.equal(
sig,
"r=https%3A%2F%2Feg-topic.westus-2.eventgrid.azure.net%2Fapi%2Fevents%3FapiVersion%3D2018-01-01&e=1%2F1%2F2020%2012%3A00%3A00%20AM&s=ZzvNAYRyvJwDrOJKYxbNAPNCoSqgOJVLFi4IMXOrW2Q%3D"
);
});
});

Просмотреть файл

@ -0,0 +1,21 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { assert } from "chai";
import { dateToServiceTimeString } from "../src/util";
describe("util", function() {
describe("dateToServiceTimeString", () => {
it("converts dates correctly", () => {
const simpleMorningDate = new Date(Date.UTC(2020, 0, 2, 3, 4, 5));
assert.equal(dateToServiceTimeString(simpleMorningDate), "1/2/2020 3:04:05 AM");
const simpleAfternoonDate = new Date(Date.UTC(2020, 0, 2, 13, 10, 21));
assert.equal(dateToServiceTimeString(simpleAfternoonDate), "1/2/2020 1:10:21 PM");
const slightlyAfterMidnight = new Date(Date.UTC(2020, 0, 2, 0, 10, 21));
assert.equal(dateToServiceTimeString(slightlyAfterMidnight), "1/2/2020 12:10:21 AM");
});
});
});

Просмотреть файл

@ -0,0 +1,67 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { Context } from "mocha";
import * as dotenv from "dotenv";
import { env, Recorder, record, RecorderEnvironmentSetup } from "@azure/test-utils-recorder";
import { isNode } from "@azure/core-http";
import { EventGridPublisherClient } from "../../src/index";
import { KeyCredential } from "@azure/core-auth";
if (isNode) {
dotenv.config();
}
export interface RecordedClient {
client: EventGridPublisherClient;
recorder: Recorder;
}
const replaceableVariables: { [k: string]: string } = {
EVENT_GRID_EVENT_GRID_SCHEMA_API_KEY: "api_key",
EVENT_GRID_EVENT_GRID_SCHEMA_ENDPOINT: "https://endpoint/api/events",
EVENT_GRID_CLOUD_EVENT_SCHEMA_API_KEY: "api_key",
EVENT_GRID_CLOUD_EVENT_SCHEMA_ENDPOINT: "https://endpoint/api/events",
EVENT_GRID_CUSTOM_SCHEMA_API_KEY: "api_key",
EVENT_GRID_CUSTOM_SCHEMA_ENDPOINT: "https://endpoint/api/events"
};
export const testEnv = new Proxy(replaceableVariables, {
get: (target, key: string) => {
return env[key] || target[key];
}
});
export const environmentSetup: RecorderEnvironmentSetup = {
replaceableVariables,
customizationsOnRecordings: [
(recording: string): string =>
recording.replace(/"aeg-sas-key"\s?:\s?"[^"]*"/g, `"aeg-sas-key":"aeg-sas-key"`),
(recording: string): string =>
recording.replace(/"aeg-sas-token"\s?:\s?"[^"]*"/g, `"aeg-sas-token":"aeg-sas-token"`),
// If we put EVENT_GRID_EVENT_GRID_SCHEMA_ENDPOINT (or similar) in replaceableVariables above,
// it will not capture the endpoint string used with nock, which will be expanded to
// https://<endpoint>:443/ and therefore will not match, so we have to do
// this instead.
(recording: string): string => {
const replaced = recording.replace("endpoint:443", "endpoint");
return replaced;
}
],
queryParametersToSkip: []
};
export function createRecordedClient(
context: Context,
endpoint: string,
credential: KeyCredential
): RecordedClient {
const recorder = record(context, environmentSetup);
return {
client: new EventGridPublisherClient(endpoint, credential),
recorder
};
}

Просмотреть файл

@ -0,0 +1,172 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export class TestCase {
public expected: any;
public encodedEvent: string;
constructor(expected: any, encodedEvent?: string) {
this.expected = expected;
this.encodedEvent = encodedEvent ?? JSON.stringify(expected);
}
}
export interface TestEventInfo {
/**
* A test case of an event in the Event Grid Schema
*/
eventGridSchema: TestCase;
/**
* A test case of an event in the Cloud Event Schema.
*/
cloudEventSchema: TestCase;
}
export const customTestEvent1: TestEventInfo = {
eventGridSchema: new TestCase({
id: "5bc888aa-c2f4-11ea-b3de-0242ac130004",
subject: "",
data: {
hello: "world"
},
eventType: "Azure.Sdk.TestEvent1",
dataVersion: "1.0",
metadataVersion: "1",
eventTime: new Date("2020-07-10T21:27:12.925Z"),
topic:
"/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/matell-rg/providers/Microsoft.EventGrid/topics/matell-eg-topic"
}),
cloudEventSchema: new TestCase({
id: "5bc888aa-c2f4-11ea-b3de-0242ac130004",
source:
"/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/matell-rg/providers/Microsoft.EventGrid/topics/matell-eg-topic",
specversion: "1.0",
type: "Azure.Sdk.TestEvent1",
subject: "",
time: new Date("2020-07-10T21:27:12.925Z"),
data: {
hello: "world"
}
})
};
export const customTestEvent2: TestEventInfo = {
eventGridSchema: new TestCase({
id: "ddf773ae-c2f4-11ea-b3de-0242ac130004",
subject: "",
data: {
goodbye: "everyone"
},
eventType: "Azure.Sdk.TestEvent2",
dataVersion: "1.0",
metadataVersion: "1",
eventTime: new Date("2020-07-10T21:27:12.925Z"),
topic:
"/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/matell-rg/providers/Microsoft.EventGrid/topics/matell-eg-topic"
}),
cloudEventSchema: new TestCase({
id: "ddf773ae-c2f4-11ea-b3de-0242ac130004",
source:
"/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/matell-rg/providers/Microsoft.EventGrid/topics/matell-eg-topic",
specversion: "1.0",
type: "Azure.Sdk.TestEvent2",
subject: "",
time: new Date("2020-07-10T21:27:12.925Z"),
data: {
goodbye: "everyone"
}
})
};
// As of 2020-07-10, the Container Registry service is delivering the `data` object as string instead of a JSON object. This disagrees with
// the documented shape of the event. Our parsers have a special case to deal with this, for these events.
export const containerRegistryPushedEvent: TestEventInfo = {
eventGridSchema: new TestCase(
{
id: "b734f818-f923-472b-aec8-50995013fd7c",
topic:
"/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/matell-rg/providers/Microsoft.ContainerRegistry/registries/matellcr",
subject: "ubuntu:18.04",
eventType: "Microsoft.ContainerRegistry.ImagePushed",
data: {
id: "b734f818-f923-472b-aec8-50995013fd7c",
timestamp: new Date("2020-07-09T00:29:38.143428094Z"),
action: "push",
target: {
mediaType: "application/vnd.docker.distribution.manifest.v2+json",
size: 1152,
digest: "sha256:3013b0d761d4bad6ff16dd2805887a2f2c3fc140d6206086698b5c3e44e0f7fe",
length: 1152,
repository: "ubuntu",
tag: "18.04"
},
request: {
id: "6d472f8e-8366-408a-a248-fb76348c91a0",
host: "matellcr.azurecr.io",
method: "PUT",
useragent:
"docker/19.03.8 go/go1.12.17 git-commit/afacb8b kernel/4.19.104-microsoft-standard os/linux arch/amd64 UpstreamClient(Docker-Client/19.03.8 \\(windows\\))"
}
},
dataVersion: "1.0",
metadataVersion: "1",
eventTime: new Date("2020-07-09T00:29:38.3640826Z")
},
JSON.stringify({
id: "b734f818-f923-472b-aec8-50995013fd7c",
topic:
"/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/matell-rg/providers/Microsoft.ContainerRegistry/registries/matellcr",
subject: "ubuntu:18.04",
eventType: "Microsoft.ContainerRegistry.ImagePushed",
data:
'{"id":"b734f818-f923-472b-aec8-50995013fd7c","timestamp":"2020-07-09T00:29:38.143428094Z","action":"push","target":{"mediaType":"application/vnd.docker.distribution.manifest.v2+json","size":1152,"digest":"sha256:3013b0d761d4bad6ff16dd2805887a2f2c3fc140d6206086698b5c3e44e0f7fe","length":1152,"repository":"ubuntu","tag":"18.04"},"request":{"id":"6d472f8e-8366-408a-a248-fb76348c91a0","host":"matellcr.azurecr.io","method":"PUT","useragent":"docker/19.03.8 go/go1.12.17 git-commit/afacb8b kernel/4.19.104-microsoft-standard os/linux arch/amd64 UpstreamClient(Docker-Client/19.03.8 \\\\(windows\\\\))"}}',
dataVersion: "1.0",
metadataVersion: "1",
eventTime: "2020-07-09T00:29:38.3640826Z"
})
),
cloudEventSchema: new TestCase(
{
id: "2092c215-d22b-4116-8e56-42dfa856d711",
source:
"/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/matell-rg/providers/Microsoft.ContainerRegistry/registries/matellcr",
specversion: "1.0",
type: "Microsoft.ContainerRegistry.ImagePushed",
dataschema: "#1.0",
subject: "alpine:latest",
time: new Date("2020-07-10T20:30:31.3653996Z"),
data: {
id: "2092c215-d22b-4116-8e56-42dfa856d711",
timestamp: new Date("2020-07-10T20:30:30.956083501Z"),
action: "push",
target: {
mediaType: "application/vnd.docker.distribution.manifest.v2+json",
size: 528,
digest: "sha256:a15790640a6690aa1730c38cf0a440e2aa44aaca9b0e8931a9f2b0d7cc90fd65",
length: 528,
repository: "alpine",
tag: "latest"
},
request: {
id: "1dd0b459-1fc7-43aa-a1a1-c820e996699f",
host: "matellcr.azurecr.io",
method: "PUT",
useragent:
"docker/19.03.8 go/go1.12.17 git-commit/afacb8b kernel/4.19.104-microsoft-standard os/linux arch/amd64 UpstreamClient(Docker-Client/19.03.8 \\(linux\\))"
}
}
},
JSON.stringify({
id: "2092c215-d22b-4116-8e56-42dfa856d711",
source:
"/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/matell-rg/providers/Microsoft.ContainerRegistry/registries/matellcr",
specversion: "1.0",
type: "Microsoft.ContainerRegistry.ImagePushed",
dataschema: "#1.0",
subject: "alpine:latest",
time: "2020-07-10T20:30:31.3653996Z",
data:
'{"id":"2092c215-d22b-4116-8e56-42dfa856d711","timestamp":"2020-07-10T20:30:30.956083501Z","action":"push","target":{"mediaType":"application/vnd.docker.distribution.manifest.v2+json","size":528,"digest":"sha256:a15790640a6690aa1730c38cf0a440e2aa44aaca9b0e8931a9f2b0d7cc90fd65","length":528,"repository":"alpine","tag":"latest"},"request":{"id":"1dd0b459-1fc7-43aa-a1a1-c820e996699f","host":"matellcr.azurecr.io","method":"PUT","useragent":"docker/19.03.8 go/go1.12.17 git-commit/afacb8b kernel/4.19.104-microsoft-standard os/linux arch/amd64 UpstreamClient(Docker-Client/19.03.8 \\\\(linux\\\\))"}}'
})
)
};

Просмотреть файл

@ -0,0 +1,19 @@
trigger: none
resources:
repositories:
- repository: azure-sdk-build-tools
type: git
name: internal/azure-sdk-build-tools
- repository: azure-sdk-tools
type: github
name: Azure/azure-sdk-tools
endpoint: azure
jobs:
- template: ../../../eng/pipelines/templates/jobs/archetype-sdk-integration.yml
parameters:
PackageName: "@azure/eventgrid"
ResourceServiceDirectory: eventgrid
EnvVars:
AZURE_CLIENT_ID: $(aad-azure-sdk-test-client-id)
AZURE_TENANT_ID: $(aad-azure-sdk-test-tenant-id)
AZURE_CLIENT_SECRET: $(aad-azure-sdk-test-client-secret)

Просмотреть файл

@ -1,19 +1,17 @@
{
"extends": "../../../tsconfig.package",
"compilerOptions": {
"module": "es6",
"moduleResolution": "node",
"strict": true,
"target": "es5",
"sourceMap": true,
"declarationMap": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"lib": ["es6", "dom"],
"declaration": true,
"outDir": "./esm",
"importHelpers": true
"outDir": "./dist-esm",
"declarationDir": "./types"
},
"include": ["./src/**/*.ts"],
"exclude": ["node_modules"]
"exclude": [
"node_modules",
"types",
"temp",
"browser",
"dist",
"dist-samples",
"dist-esm",
"./samples/**/*.ts"
]
}