Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions eng/Packages.Data.props
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
<PackageReference Update="Azure.Messaging.EventHubs" Version="5.4.0" />
<PackageReference Update="Azure.Messaging.EventGrid" Version="4.0.0" />
<PackageReference Update="Azure.Messaging.ServiceBus" Version="7.2.0-beta.2" Condition="'$(HasReleaseVersion)' == 'false'"/>
<PackageReference Update="Azure.Messaging.WebPubSub" Version="1.0.0-beta.1" />
<PackageReference Update="Azure.Identity" Version="1.2.1" />
<PackageReference Update="Azure.Security.KeyVault.Secrets" Version="4.0.2" />
<PackageReference Update="Azure.Security.KeyVault.Keys" Version="4.0.2" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Release History

## 1.0.0-beta.1 (2021-04-26)

- The initial beta release of Microsoft.Azure.WebJobs.Extensions.WebPubSub 1.0.0
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IsClientLibrary>true</IsClientLibrary>
</PropertyGroup>

<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory)..\, Directory.Build.props))\Directory.Build.props" />
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30803.129
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.WebJobs.Extensions.WebPubSub", "src\Microsoft.Azure.WebJobs.Extensions.WebPubSub.csproj", "{6CF5F6B5-F8D6-4D92-9AE5-F766B1C83EED}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.WebJobs.Extensions.WebPubSub.Tests", "tests\Microsoft.Azure.WebJobs.Extensions.WebPubSub.Tests.csproj", "{89759B66-5CF1-4A86-9D07-D3DA48300AE9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6CF5F6B5-F8D6-4D92-9AE5-F766B1C83EED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6CF5F6B5-F8D6-4D92-9AE5-F766B1C83EED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6CF5F6B5-F8D6-4D92-9AE5-F766B1C83EED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6CF5F6B5-F8D6-4D92-9AE5-F766B1C83EED}.Release|Any CPU.Build.0 = Release|Any CPU
{89759B66-5CF1-4A86-9D07-D3DA48300AE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{89759B66-5CF1-4A86-9D07-D3DA48300AE9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{89759B66-5CF1-4A86-9D07-D3DA48300AE9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{89759B66-5CF1-4A86-9D07-D3DA48300AE9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AFE7981B-5322-4E4D-BACC-3380116A52F5}
EndGlobalSection
EndGlobal
119 changes: 119 additions & 0 deletions sdk/webpubsub/Microsoft.Azure.WebJobs.Extensions.WebPubSub/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Azure WebJobs Web PubSub client library for .NET

This extension provides functionality for receiving Web PubSub webhook calls in Azure Functions, allowing you to easily write functions that respond to any event published to Web PubSub.

## Getting started

### Install the package

Install the Web PubSub extension with [NuGet][nuget]:

```Powershell
dotnet add package Microsoft.Azure.WebJobs.Extensions.WebPubSub
```

### Prerequisites

You must have an [Azure subscription](https://azure.microsoft.com/free/) and an Azure resource group with a Web PubSub resource. Follow this [step-by-step tutorial](https://review.docs.microsoft.com/azure/azure-web-pubsub/howto-develop-create-instance?branch=release-azure-web-pubsub) to create an Azure Web PubSub instance.

## Key concepts

### Using Web PubSub input binding

Please follow the [input binding tutorial](https://azure.github.io/azure-webpubsub/references/functions-bindings#input-binding) to learn about using this extension for building `WebPubSubConnection` to create Websockets connection to service with input binding.

### Using Web PubSub output binding

Please follow the [output binding tutorial](https://azure.github.io/azure-webpubsub/references/functions-bindings#output-binding) to learn about using this extension for publishing Web PubSub messages.

### Using Web PubSub trigger

Please follow the [trigger binding tutorial](https://azure.github.io/azure-webpubsub/references/functions-bindings#trigger-binding) to learn about triggering an Azure Function when an event is sent from service upstream.

## Examples

### Functions that uses Web PubSub input binding

```C# Snippet:WebPubSubInputBindingFunction
[FunctionName("WebPubSubInputBindingFunction")]
public static WebPubSubConnection Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req,
[WebPubSubConnection(Hub = "simplechat", UserId = "{query.userid}")] WebPubSubConnection connection)
{
Console.WriteLine("login");
return connection;
}
```

### Functions that uses Web PubSub output binding

```c# Snippet:WebPubSubOutputBindingFunction
[FunctionName("WebPubSubOutputBindingFunction")]
public static async Task RunAsync(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req,
[WebPubSub(Hub = "simplechat")] IAsyncCollector<WebPubSubOperation> operation)
{
await operation.AddAsync(new SendToAll
{
Message = BinaryData.FromString("Hello Web PubSub"),
DataType = MessageDataType.Text
});
}
```

### Functions that uses Web PubSub trigger

```C# Snippet:WebPubSubTriggerFunction
[FunctionName("WebPubSubTriggerFunction")]
public static async Task<MessageResponse> RunAsync(
[WebPubSubTrigger("message", WebPubSubEventType.User)]
ConnectionContext context,
string message,
MessageDataType dataType)
{
Console.WriteLine($"Request from: {context.userId}");
Console.WriteLine($"Request message: {message}");
Console.WriteLine($"Request message DataType: {dataType}");
return new MessageResponse
{
Message = BinaryData.FromString("ack"),
};
}
```

## Troubleshooting

Please refer to [Monitor Azure Functions](https://docs.microsoft.com/azure/azure-functions/functions-monitoring) for troubleshooting guidance.

## Next steps

Read the [introduction to Azure Function](https://docs.microsoft.com/azure/azure-functions/functions-overview) or [creating an Azure Function guide](https://docs.microsoft.com/azure/azure-functions/functions-create-first-azure-function).

## Contributing

See our [CONTRIBUTING.md][contrib] for details on building,
testing, and contributing to this library.

This project welcomes contributions and suggestions. Most contributions require
you to agree to a Contributor License Agreement (CLA) declaring that you have
the right to, and actually do, grant us the rights to use your contribution. For
details, visit [cla.microsoft.com][cla].

This project has adopted the [Microsoft Open Source Code of Conduct][coc].
For more information see the [Code of Conduct FAQ][coc_faq]
or contact [[email protected]][coc_contact] with any
additional questions or comments.

![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net%2Fsdk%2Fsearch%2FMicrosoft.Azure.WebJobs.Extensions.WebPubSub%2FREADME.png)

<!-- LINKS -->
[source]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/search/Microsoft.Azure.WebJobs.Extensions.WebPubSub/src
[package]: https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.WebPubSub/
[docs]: https://docs.microsoft.com/dotnet/api/Microsoft.Azure.WebJobs.Extensions.WebPubSub
[nuget]: https://www.nuget.org/

[contrib]: https://github.com/Azure/azure-sdk-for-net/tree/master/CONTRIBUTING.md
[cla]: https://cla.microsoft.com
[coc]: https://opensource.microsoft.com/codeofconduct/
[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
[coc_contact]: mailto:[email protected]
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;

using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Microsoft.Azure.WebJobs.Extensions.WebPubSub
{
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class ConnectionContext
{
/// <summary>
/// The type of the message.
/// </summary>
public WebPubSubEventType EventType { get; internal set; }

/// <summary>
/// The event name of the message.
/// </summary>
public string EventName { get; internal set; }

/// <summary>
/// The hub which the message belongs to.
/// </summary>
public string Hub { get; internal set; }

/// <summary>
/// The connection-id of the client which send the message.
/// </summary>
public string ConnectionId { get; internal set; }

/// <summary>
/// The user identity of the client which send the message.
/// </summary>
public string UserId { get; internal set; }

/// <summary>
/// The signature for validation
/// </summary>
public string Signature { get; internal set; }

/// <summary>
/// The headers of request.
/// </summary>
public Dictionary<string, StringValues> Headers { get; internal set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Runtime.Serialization;

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Microsoft.Azure.WebJobs.Extensions.WebPubSub
{
[JsonConverter(typeof(StringEnumConverter))]
public enum MessageDataType
{
[EnumMember(Value = "binary")]
Binary,
[EnumMember(Value = "json")]
Json,
[EnumMember(Value = "text")]
Text
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Microsoft.Azure.WebJobs.Extensions.WebPubSub
{
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class AddConnectionToGroup : WebPubSubOperation
{
public string ConnectionId { get; set; }

public string Group { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Microsoft.Azure.WebJobs.Extensions.WebPubSub
{
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class AddUserToGroup : WebPubSubOperation
{
public string UserId { get; set; }

public string Group { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using Newtonsoft.Json.Linq;

namespace Microsoft.Azure.WebJobs.Extensions.WebPubSub
{
internal static class BinaryDataExtensions
{
public static object Convert(this BinaryData message, Type targetType)
{
if (targetType == typeof(JObject))
{
return JObject.FromObject(message.ToArray());
}

if (targetType == typeof(Stream))
{
return message.ToStream();
}

if (targetType == typeof(byte[]))
{
return message.ToArray();
}

if (targetType == typeof(string))
{
return message.ToString();
}

if (targetType == typeof(BinaryData))
{
return message;
}

return null;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Microsoft.Azure.WebJobs.Extensions.WebPubSub
{
internal class BinaryDataJsonConverter : JsonConverter<BinaryData>
{
public override BinaryData ReadJson(JsonReader reader, Type objectType, BinaryData existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.String)
{
return BinaryData.FromString(serializer.Deserialize<string>(reader));
}

var value = JToken.Load(reader);

if (TryLoadBinary(value, out var bytes))
{
return BinaryData.FromBytes(bytes);
}
// string JObject
return BinaryData.FromString(value.ToString());
}

public override void WriteJson(JsonWriter writer, BinaryData value, JsonSerializer serializer)
{
serializer.Serialize(writer, value.ToString());
}

private static bool TryLoadBinary(JToken input, out byte[] output)
{
var converted = new List<byte>();
if (input["type"] != null && input["type"].ToString().Equals("Buffer", StringComparison.OrdinalIgnoreCase))
{
var data = input["data"];
if (data is JArray bytes)
{
foreach (var item in bytes)
{
converted.Add(byte.Parse(item.ToString(), CultureInfo.InvariantCulture));
}
output = converted.ToArray();
return true;
}
}
output = null;
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Microsoft.Azure.WebJobs.Extensions.WebPubSub
{
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class CloseClientConnection : WebPubSubOperation
{
public string ConnectionId { get; set; }

public string Reason { get; set; }
}
}
Loading