Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Web PubSub function bindings sdk. #20459

Merged
merged 18 commits into from
Apr 29, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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 @@ -84,6 +84,7 @@
<PackageReference Update="Azure.Security.KeyVault.Secrets" Version="4.0.2" />
<PackageReference Update="Azure.Security.KeyVault.Keys" Version="4.0.2" />
<PackageReference Update="Azure.Storage.Blobs" Version="12.8.0" />
<PackageReference Update="Azure.Messaging.WebPubSub" Version="1.0.0-alpha.20210402.1" />

<!-- Other approved packages -->
<PackageReference Update="Microsoft.Azure.Amqp" Version="2.4.13" />
Expand Down
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
120 changes: 120 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,120 @@
# 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 Event Grid extension with [NuGet][nuget]:
JialinXin marked this conversation as resolved.
Show resolved Hide resolved

```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://scaling-garbanzo-3fe86650.pages.github.io/references/functions-bindings#input-binding) to learn about using this extension for building `WebPubSubConnection` to create Websockets connection to service with input binding.
JialinXin marked this conversation as resolved.
Show resolved Hide resolved

### Using Web PubSub output binding

Please follow the [output binding tutorial](https://scaling-garbanzo-3fe86650.pages.github.io/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://scaling-garbanzo-3fe86650.pages.github.io/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<WebPubSubEvent> webpubsubEvent)
{
await webpubsubEvent.AddAsync(new WebPubSubEvent
{
Operation = Operation.SendToAll,
Message = new Message("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", EventType.User)]
ConnectionContext context,
WebPubSubMessage message,
MessageDataType dataType)
{
Console.WriteLine($"Request from: {context.userId}");
Console.WriteLine($"Request message: {message.Body.ToString()}");
Console.WriteLine($"Request message DataType: {dataType}");
return new MessageResponse
{
Message = new WebPubSubMessage("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,96 @@
using System;
using System.IO;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;

namespace WebPubSubTests
{
class Program
{
private const string DefaultLogin = "http://localhost:7071/api/login";
private static HttpClient _httpClient = new HttpClient();

static async Task Main(string[] args)
{
Console.WriteLine("== [Simple Chat] ==");

Console.WriteLine("[1] Enter login func url:");
var loginUrl = Console.ReadLine();
if (string.IsNullOrEmpty(loginUrl) || !Uri.TryCreate(loginUrl, UriKind.Absolute, out var url))
{
Console.WriteLine($"Invalid url, use default local func: {DefaultLogin}");
loginUrl = DefaultLogin;
}

Console.WriteLine("[2] Enter userId:");
var userId = Console.ReadLine();

var response = await _httpClient.GetAsync($"{loginUrl}?userid={userId}");
var result = await response.Content.ReadAsStringAsync();

var connection = JsonConvert.DeserializeObject<Connection>(result);

using var webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(connection.Url), default);
Console.WriteLine("Connected");

_ = ReceiveMessageAsync(webSocket);

await SendMessageAsync(webSocket);
}

private static async Task ReceiveMessageAsync(ClientWebSocket webSocket)
{
var ms = new MemoryStream();
Memory<byte> buffer = new byte[1024];
// receive loop
while (true)
{
var receiveResult = await webSocket.ReceiveAsync(buffer, default);
// Need to check again for NetCoreApp2.2 because a close can happen between a 0-byte read and the actual read
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
try
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, default);
}
catch
{
// It is possible that the remote is already closed
}
break;
}
await ms.WriteAsync(buffer.Slice(0, receiveResult.Count));
if (receiveResult.EndOfMessage)
{
Console.WriteLine($"[Received]: {Encoding.UTF8.GetString(ms.ToArray())}");
ms.SetLength(0);
}
}
}

private static async Task SendMessageAsync(ClientWebSocket webSocket)
{
while (true)
{
Console.WriteLine("[3] Input text to chat:");
var message = Console.ReadLine();
if (!string.IsNullOrEmpty(message))
{
var msgBuffer = Encoding.UTF8.GetBytes(message);
await webSocket.SendAsync(new ArraySegment<byte>(msgBuffer), WebSocketMessageType.Text, true, default);
}
}
}

private sealed class Connection
{
public string Url { get; set; }
public string AccessToken { get; set; }
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>

</Project>
Loading