Skip to content

Commit 00af10f

Browse files
authored
[WebPubSub] Init the Microsoft.Azure.WebPubSub.AspNetCore lib. (Azure#24814)
https://apiview.dev/Assemblies/Review/57fc8bd7c6bd4479aeb2bcd2367d4717 # All SDK Contribution checklist: This checklist is used to make sure that common guidelines for a pull request are followed. - [ ] **Please open PR in `Draft` mode if it is:** - Work in progress or not intended to be merged. - Encountering multiple pipeline failures and working on fixes. - [ ] If an SDK is being regenerated based on a new swagger spec, a link to the pull request containing these swagger spec changes has been included above. - [ ] **I have read the [contribution guidelines](https://github.com/Azure/azure-sdk-for-net/blob/main/CONTRIBUTING.md).** - [ ] **The pull request does not introduce [breaking changes](https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/breaking-change-rules.md).** ### [General Guidelines and Best Practices](https://github.com/Azure/azure-sdk-for-net/blob/main/CONTRIBUTING.md#general-guidelines) - [ ] Title of the pull request is clear and informative. - [ ] There are a small number of commits, each of which have an informative message. This means that previously merged commits do not appear in the history of the PR. For more information on cleaning up the commits in your PR, [see this page](https://github.com/Azure/azure-powershell/blob/master/documentation/development-docs/cleaning-up-commits.md). ### [Testing Guidelines](https://github.com/Azure/azure-sdk-for-net/blob/main/CONTRIBUTING.md#testing-guidelines) - [ ] Pull request includes test coverage for the included changes. ### [SDK Generation Guidelines](https://github.com/Azure/azure-sdk-for-net/blob/main/CONTRIBUTING.md#sdk-generation-guidelines) - [ ] The generate.cmd file for the SDK has been updated with the version of AutoRest, as well as the commitid of your swagger spec or link to the swagger spec, used to generate the code. (Track 2 only) - [ ] The `*.csproj` and `AssemblyInfo.cs` files have been updated with the new version of the SDK. Please double check nuget.org current release version. ## Additional management plane SDK specific contribution checklist: Note: Only applies to `Microsoft.Azure.Management.[RP]` or `Azure.ResourceManager.[RP]` - [ ] Include updated [management metadata](https://github.com/Azure/azure-sdk-for-net/tree/main/eng/mgmt/mgmtmetadata). - [ ] Update AzureRP.props to add/remove version info to maintain up to date API versions. ### Management plane SDK Troubleshooting - If this is very first SDK for a services and you are adding new service folders directly under /SDK, please add `new service` label and/or contact assigned reviewer. - If the check fails at the `Verify Code Generation` step, please ensure: - Do not modify any code in generated folders. - Do not selectively include/remove generated files in the PR. - Do use `generate.ps1/cmd` to generate this PR instead of calling `autorest` directly. Please pay attention to the @microsoft.csharp version output after running `generate.ps1`. If it is lower than current released version (2.3.82), please run it again as it should pull down the latest version. **Note: We have recently updated the PSH module called by `generate.ps1` to emit additional data. This would help reduce/eliminate the Code Verification check error. Please run following command**: `dotnet msbuild eng/mgmt.proj /t:Util /p:UtilityName=InstallPsModules` ### Old outstanding PR cleanup Please note: If PRs (including draft) has been out for more than 60 days and there are no responses from our query or followups, they will be closed to maintain a concise list for our reviewers.
1 parent f190c45 commit 00af10f

24 files changed

+1962
-0
lines changed

eng/Packages.Data.props

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
<PackageReference Update="Microsoft.ServiceFabric.Services" Version="3.3.624" />
2727
<PackageReference Update="Microsoft.ServiceFabric" Version="6.4.624" />
2828
<PackageReference Update="Microsoft.Spatial" Version="7.5.3" />
29+
<PackageReference Update="Microsoft.AspNetCore.Http" Version="2.1.22" />
2930

3031
<PackageReference Update="Newtonsoft.Json" Version="10.0.3" />
3132

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Release History
2+
3+
## 1.0.0-beta.1 (Unreleased)
4+
5+
### Features Added
6+
7+
- Server side library to read and handle upstream requests using Azure Web PubSub service.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
2+
<!--
3+
Add any shared properties you want for the projects under this package directory that need to be set before the auto imported Directory.Build.props
4+
-->
5+
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory).., Directory.Build.props))\Directory.Build.props" />
6+
</Project>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.0.31410.414
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.WebPubSub.AspNetCore", "src\Microsoft.Azure.WebPubSub.AspNetCore.csproj", "{010E6C47-B3F4-4370-B947-2B4AC3982A1D}"
7+
EndProject
8+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.WebPubSub.Common", "..\Microsoft.Azure.WebPubSub.Common\src\Microsoft.Azure.WebPubSub.Common.csproj", "{D2F34C1D-DDC0-4E08-BF33-4BBC0152842C}"
9+
EndProject
10+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.WebPubSub.AspNetCore.Tests", "tests\Microsoft.Azure.WebPubSub.AspNetCore.Tests.csproj", "{7ECB787F-ED29-4750-AAE9-A4E7F66E61CB}"
11+
EndProject
12+
Global
13+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
14+
Debug|Any CPU = Debug|Any CPU
15+
Release|Any CPU = Release|Any CPU
16+
EndGlobalSection
17+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
18+
{010E6C47-B3F4-4370-B947-2B4AC3982A1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19+
{010E6C47-B3F4-4370-B947-2B4AC3982A1D}.Debug|Any CPU.Build.0 = Debug|Any CPU
20+
{010E6C47-B3F4-4370-B947-2B4AC3982A1D}.Release|Any CPU.ActiveCfg = Release|Any CPU
21+
{010E6C47-B3F4-4370-B947-2B4AC3982A1D}.Release|Any CPU.Build.0 = Release|Any CPU
22+
{D2F34C1D-DDC0-4E08-BF33-4BBC0152842C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23+
{D2F34C1D-DDC0-4E08-BF33-4BBC0152842C}.Debug|Any CPU.Build.0 = Debug|Any CPU
24+
{D2F34C1D-DDC0-4E08-BF33-4BBC0152842C}.Release|Any CPU.ActiveCfg = Release|Any CPU
25+
{D2F34C1D-DDC0-4E08-BF33-4BBC0152842C}.Release|Any CPU.Build.0 = Release|Any CPU
26+
{7ECB787F-ED29-4750-AAE9-A4E7F66E61CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27+
{7ECB787F-ED29-4750-AAE9-A4E7F66E61CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
28+
{7ECB787F-ED29-4750-AAE9-A4E7F66E61CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
29+
{7ECB787F-ED29-4750-AAE9-A4E7F66E61CB}.Release|Any CPU.Build.0 = Release|Any CPU
30+
EndGlobalSection
31+
GlobalSection(SolutionProperties) = preSolution
32+
HideSolutionNode = FALSE
33+
EndGlobalSection
34+
GlobalSection(ExtensibilityGlobals) = postSolution
35+
SolutionGuid = {95A1BED2-374A-43C9-A156-D918DDD2EC80}
36+
EndGlobalSection
37+
EndGlobal
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Azure Web PubSub service middleware client library for .NET
2+
3+
[Azure Web PubSub Service](https://aka.ms/awps/doc) is a service that enables you to build real-time messaging web applications using WebSockets and the publish-subscribe pattern. Any platform supporting WebSocket APIs can connect to the service easily, e.g. web pages, mobile applications, edge devices, etc. The service manages the WebSocket connections for you and allows up to 100K **concurrent** connections. It provides powerful APIs for you to manage these clients and deliver real-time messages.
4+
5+
Any scenario that requires real-time publish-subscribe messaging between server and clients or among clients, can use Azure Web PubSub service. Traditional real-time features that often require polling from server or submitting HTTP requests, can also use Azure Web PubSub service.
6+
7+
This library can be used to do the following actions. Details about the terms used here are described in [Key concepts](#key-concepts) section.
8+
9+
- Parse upstream request under CloudNative CloudEvents
10+
- Add validation options for upstream request
11+
- API to add user defined functionality to handle different upstream events
12+
13+
[Source code](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/webpubsub/Microsoft.Azure.WebPubSub.AspNetCore/src) |
14+
Package |
15+
[API reference documentation](https://aka.ms/awps/sdk/csharp) |
16+
[Product documentation](https://aka.ms/awps/doc) |
17+
Samples |
18+
19+
## Getting started
20+
21+
### Install the package
22+
23+
Install the client library from [NuGet](https://www.nuget.org/):
24+
25+
```PowerShell
26+
dotnet add package Microsoft.Azure.WebPubSub.AspNetCore --prerelease
27+
```
28+
29+
### Prerequisites
30+
31+
- An [Azure subscription][azure_sub].
32+
- An existing Azure Web PubSub service instance.
33+
34+
### Authenticate the client
35+
36+
In order to interact with the service, you'll need to create an instance of the WebPubSubServiceClient class. To make this possible, you'll need the connection string or a key, which you can access in the Azure portal.
37+
38+
### Create a `WebPubSubServiceClient`
39+
40+
```C# Snippet:WebPubSubAuthenticate
41+
var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));
42+
```
43+
44+
## Key concepts
45+
46+
For information about general Web PubSub concepts [Concepts in Azure Web PubSub](https://docs.microsoft.com/azure/azure-web-pubsub/key-concepts)
47+
48+
## Examples
49+
50+
### Add Web PubSub service with options
51+
52+
```C#
53+
public void ConfigureServices(IServiceCollection services)
54+
{
55+
services.AddWebPubSub(o =>
56+
{
57+
o.ValidationOptions.Add("<connection-string>");
58+
});
59+
}
60+
```
61+
62+
### Map `WebPubSubHub` to endpoint routing.
63+
64+
The path should match the value configured in the Azure Web PubSub service `EventHandler`. For example, if placeholder is using like `/api/{event}`, then the path set in code should be `/api/{event}` as well.
65+
66+
```C#
67+
public void Configure(IApplicationBuilder app)
68+
{
69+
app.UseEndpoints(endpoint =>
70+
{
71+
endpoint.MapWebPubSubHub<SampleHub>("/eventhander");
72+
});
73+
}
74+
```
75+
76+
### Handle Upstream event
77+
78+
```C#
79+
public override ValueTask<WebPubSubEventResponse> OnConnectAsync(ConnectEventRequest request, CancellationToken cancellationToken)
80+
{
81+
var response = new ConnectEventResponse
82+
{
83+
UserId = request.ConnectionContext.UserId
84+
};
85+
return new ValueTask<WebPubSubEventResponse>(response);
86+
}
87+
```
88+
89+
## Troubleshooting
90+
91+
### Setting up console logging
92+
You can also easily [enable console logging](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md#logging) if you want to dig deeper into the requests you're making against the service.
93+
94+
## Next steps
95+
96+
Please take a look at the
97+
[samples][samples_ref]
98+
directory for detailed examples on how to use this library.
99+
100+
## Contributing
101+
102+
This project welcomes contributions and suggestions.
103+
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.
104+
For details, visit <https://cla.microsoft.com.>
105+
106+
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment).
107+
Simply follow the instructions provided by the bot.
108+
You will only need to do this once across all repos using our CLA.
109+
110+
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
111+
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
112+
113+
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net%2Fsdk%2Ftemplate%2FAzure.Template%2FREADME.png)
114+
115+
[azure_sub]: https://azure.microsoft.com/free/dotnet/
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
namespace Microsoft.AspNetCore.Builder
2+
{
3+
public static partial class WebPubSubEndpointRouteBuilderExtensions
4+
{
5+
public static Microsoft.AspNetCore.Builder.IEndpointConventionBuilder MapWebPubSubHub<THub>(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints, string path) where THub : Microsoft.Azure.WebPubSub.AspNetCore.WebPubSubHub { throw null; }
6+
}
7+
}
8+
namespace Microsoft.Azure.WebPubSub.AspNetCore
9+
{
10+
public abstract partial class WebPubSubHub
11+
{
12+
protected WebPubSubHub() { }
13+
public abstract System.Threading.Tasks.ValueTask<Microsoft.Azure.WebPubSub.Common.WebPubSubEventResponse> OnConnectAsync(Microsoft.Azure.WebPubSub.Common.ConnectEventRequest request, System.Threading.CancellationToken cancellationToken);
14+
public virtual System.Threading.Tasks.Task OnConnectedAsync(Microsoft.Azure.WebPubSub.Common.ConnectedEventRequest request) { throw null; }
15+
public virtual System.Threading.Tasks.Task OnDisconnectedAsync(Microsoft.Azure.WebPubSub.Common.DisconnectedEventRequest request) { throw null; }
16+
public abstract System.Threading.Tasks.ValueTask<Microsoft.Azure.WebPubSub.Common.WebPubSubEventResponse> OnMessageReceivedAsync(Microsoft.Azure.WebPubSub.Common.UserEventRequest request, System.Threading.CancellationToken cancellationToken);
17+
}
18+
public partial class WebPubSubOptions
19+
{
20+
public WebPubSubOptions() { }
21+
public Microsoft.Azure.WebPubSub.AspNetCore.WebPubSubValidationOptions ValidationOptions { get { throw null; } set { } }
22+
}
23+
public static partial class WebPubSubRequestExtensions
24+
{
25+
public static System.Threading.Tasks.Task<Microsoft.Azure.WebPubSub.Common.WebPubSubEventRequest> ReadWebPubSubEventAsync(this Microsoft.AspNetCore.Http.HttpRequest request, Microsoft.Azure.WebPubSub.AspNetCore.WebPubSubValidationOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
26+
}
27+
public partial class WebPubSubValidationOptions
28+
{
29+
public WebPubSubValidationOptions(System.Collections.Generic.IEnumerable<string> connectionStrings) { }
30+
public WebPubSubValidationOptions(params string[] connectionStrings) { }
31+
public void Add(string connectionString) { }
32+
}
33+
}
34+
namespace Microsoft.Extensions.DependencyInjection
35+
{
36+
public static partial class WebPubSubDependencyInjectionExtensions
37+
{
38+
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddWebPubSub(this Microsoft.Extensions.DependencyInjection.IServiceCollection services) { throw null; }
39+
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddWebPubSub(this Microsoft.Extensions.DependencyInjection.IServiceCollection services, System.Action<Microsoft.Azure.WebPubSub.AspNetCore.WebPubSubOptions> configure) { throw null; }
40+
}
41+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
namespace Microsoft.Azure.WebPubSub.AspNetCore
2+
{
3+
public abstract partial class WebPubSubHub
4+
{
5+
protected WebPubSubHub() { }
6+
public abstract System.Threading.Tasks.ValueTask<Microsoft.Azure.WebPubSub.Common.WebPubSubEventResponse> OnConnectAsync(Microsoft.Azure.WebPubSub.Common.ConnectEventRequest request, System.Threading.CancellationToken cancellationToken);
7+
public virtual System.Threading.Tasks.Task OnConnectedAsync(Microsoft.Azure.WebPubSub.Common.ConnectedEventRequest request) { throw null; }
8+
public virtual System.Threading.Tasks.Task OnDisconnectedAsync(Microsoft.Azure.WebPubSub.Common.DisconnectedEventRequest request) { throw null; }
9+
public abstract System.Threading.Tasks.ValueTask<Microsoft.Azure.WebPubSub.Common.WebPubSubEventResponse> OnMessageReceivedAsync(Microsoft.Azure.WebPubSub.Common.UserEventRequest request, System.Threading.CancellationToken cancellationToken);
10+
}
11+
public partial class WebPubSubOptions
12+
{
13+
public WebPubSubOptions() { }
14+
public Microsoft.Azure.WebPubSub.AspNetCore.WebPubSubValidationOptions ValidationOptions { get { throw null; } set { } }
15+
}
16+
public static partial class WebPubSubRequestExtensions
17+
{
18+
public static System.Threading.Tasks.Task<Microsoft.Azure.WebPubSub.Common.WebPubSubEventRequest> ReadWebPubSubEventAsync(this Microsoft.AspNetCore.Http.HttpRequest request, Microsoft.Azure.WebPubSub.AspNetCore.WebPubSubValidationOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
19+
}
20+
public partial class WebPubSubValidationOptions
21+
{
22+
public WebPubSubValidationOptions(System.Collections.Generic.IEnumerable<string> connectionStrings) { }
23+
public WebPubSubValidationOptions(params string[] connectionStrings) { }
24+
public void Add(string connectionString) { }
25+
}
26+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
#if NETCOREAPP3_0_OR_GREATER
4+
using System;
5+
using Microsoft.Azure.WebPubSub.AspNetCore;
6+
using Microsoft.Extensions.DependencyInjection.Extensions;
7+
8+
namespace Microsoft.Extensions.DependencyInjection
9+
{
10+
/// <summary>
11+
/// Extension methods to add required services to use Azure Web PubSub service Hub methods.
12+
/// </summary>
13+
public static class WebPubSubDependencyInjectionExtensions
14+
{
15+
/// <summary>
16+
/// Adds the minimum essential Azure Web PubSub services to the <see cref="IServiceCollection"/>.
17+
/// </summary>
18+
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
19+
/// <param name="configure">A callback to configure the <see cref="WebPubSubOptions"/>.</param>
20+
/// <returns>The same instance of the <see cref="IServiceCollection"/>.</returns>
21+
public static IServiceCollection AddWebPubSub(this IServiceCollection services, Action<WebPubSubOptions> configure)
22+
{
23+
if (services == null)
24+
{
25+
throw new ArgumentNullException(nameof(services));
26+
}
27+
28+
if (configure == null)
29+
{
30+
throw new ArgumentNullException(nameof(configure));
31+
}
32+
33+
services.Configure(configure);
34+
35+
services.AddWebPubSub();
36+
37+
return services;
38+
}
39+
40+
/// <summary>
41+
/// Adds the minimum essential Azure Web PubSub services to the <see cref="IServiceCollection"/>.
42+
/// </summary>
43+
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
44+
/// <returns>The same instance of the <see cref="IServiceCollection"/>.</returns>
45+
public static IServiceCollection AddWebPubSub(this IServiceCollection services)
46+
{
47+
if (services == null)
48+
{
49+
throw new ArgumentNullException(nameof(services));
50+
}
51+
52+
return services.AddSingleton<ServiceRequestHandlerAdapter>()
53+
.AddSingleton<WebPubSubMarkerService>();
54+
}
55+
}
56+
}
57+
#endif
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#if NETCOREAPP3_0_OR_GREATER
2+
using System;
3+
using Microsoft.AspNetCore.Routing;
4+
using Microsoft.Azure.WebPubSub.AspNetCore;
5+
using Microsoft.Extensions.DependencyInjection;
6+
7+
namespace Microsoft.AspNetCore.Builder
8+
{
9+
/// <summary>
10+
/// Extensions for <see cref="IEndpointRouteBuilder"/>.
11+
/// </summary>
12+
public static class WebPubSubEndpointRouteBuilderExtensions
13+
{
14+
/// <summary>
15+
/// Maps the <see cref="WebPubSubHub"/> to the path <paramref name="path"/>.
16+
/// </summary>
17+
/// <typeparam name="THub">User implemented <see cref="WebPubSubHub"/>.</typeparam>
18+
/// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/>.</param>
19+
/// <param name="path">The path to map the <see cref="WebPubSubHub"/>.</param>
20+
/// <returns>The <see cref="IEndpointConventionBuilder"/>.</returns>
21+
public static IEndpointConventionBuilder MapWebPubSubHub<THub>(
22+
this IEndpointRouteBuilder endpoints,
23+
string path) where THub: WebPubSubHub
24+
{
25+
if (endpoints == null)
26+
{
27+
throw new ArgumentNullException(nameof(endpoints));
28+
}
29+
30+
var marker = endpoints.ServiceProvider.GetService<WebPubSubMarkerService>();
31+
32+
if (marker == null)
33+
{
34+
throw new InvalidOperationException(
35+
"Unable to find the required services. Please add all the required services by calling " +
36+
"'IServiceCollection.AddWebPubSub' inside the call to 'ConfigureServices(...)' in the application startup code.");
37+
}
38+
39+
var adaptor = endpoints.ServiceProvider.GetService<ServiceRequestHandlerAdapter>();
40+
adaptor.RegisterHub<THub>();
41+
42+
var app = endpoints.CreateApplicationBuilder();
43+
app.UseMiddleware<WebPubSubMiddleware>();
44+
45+
return endpoints.Map(path, app.Build());
46+
}
47+
}
48+
}
49+
#endif

0 commit comments

Comments
 (0)