From 9b5a0d7ea56aa8c317c1d17ed27900ea3da40546 Mon Sep 17 00:00:00 2001 From: masiton Date: Sat, 5 Jul 2025 04:38:31 +0200 Subject: [PATCH] SubscriptionClient carried over. --- .gitea/workflows/publish-nuget.yml | 38 ++ .gitignore | 400 ++++++++++++++++++ Directory.Packages.props | 6 + LICENSE | 7 + NuGet.config | 16 + README.md | 7 + ...engerApi.SubscriptionClient.Example.csproj | 14 + .../Program.cs | 48 +++ code/MessengerApi.SubscriptionClient.sln | 49 +++ .../MessengerApi.SubscriptionClient.csproj | 27 ++ .../Model/Subscription.cs | 52 +++ .../SubscriptionClient.cs | 61 +++ .../SubscriptionPollingEngine.cs | 129 ++++++ 13 files changed, 854 insertions(+) create mode 100644 .gitea/workflows/publish-nuget.yml create mode 100644 .gitignore create mode 100644 Directory.Packages.props create mode 100644 LICENSE create mode 100644 NuGet.config create mode 100644 README.md create mode 100644 code/MessengerApi.SubscriptionClient.Example/MessengerApi.SubscriptionClient.Example.csproj create mode 100644 code/MessengerApi.SubscriptionClient.Example/Program.cs create mode 100644 code/MessengerApi.SubscriptionClient.sln create mode 100644 code/MessengerApi.SubscriptionClient/MessengerApi.SubscriptionClient.csproj create mode 100644 code/MessengerApi.SubscriptionClient/Model/Subscription.cs create mode 100644 code/MessengerApi.SubscriptionClient/SubscriptionClient.cs create mode 100644 code/MessengerApi.SubscriptionClient/SubscriptionPollingEngine.cs diff --git a/.gitea/workflows/publish-nuget.yml b/.gitea/workflows/publish-nuget.yml new file mode 100644 index 0000000..42306b8 --- /dev/null +++ b/.gitea/workflows/publish-nuget.yml @@ -0,0 +1,38 @@ +name: Pack and Push NuGet Package + +on: + push: + branches: + - main + +jobs: + publish: + container: + image: mcr.microsoft.com/dotnet/sdk:9.0 + + steps: + - name: Install Node.js and dependencies + run: | + apt-get update + apt-get install -y curl gnupg + curl -fsSL https://deb.nodesource.com/setup_18.x | bash - + apt-get install -y nodejs git + + - name: Checkout + uses: actions/checkout@v3 + + - name: Restore dependencies + run: dotnet restore ./code/MessengerApi.SubscriptionClient/MessengerApi.SubscriptionClient.csproj + + - name: Build project + run: dotnet build ./code/MessengerApi.SubscriptionClient/MessengerApi.SubscriptionClient.csproj -c Release + + - name: Pack NuGet Package + run: | + dotnet pack ./code/MessengerApi.SubscriptionClient/MessengerApi.SubscriptionClient.csproj -c Release -o out + + - name: Push to Gitea NuGet Registry + run: | + dotnet nuget push out/*.nupkg \ + --api-key "${{ secrets.NUGET_PUBLISH_TOKEN }}" \ + --source "https://gitea.masita.net/api/packages/${{ secrets.NUGET_PUBLISH_USERNAME }}/nuget/index.json" \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ca1c7a3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,400 @@ +# ---> VisualStudio +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..98640e7 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8fac48c --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright 2024 Ondřej Mašita + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/NuGet.config b/NuGet.config new file mode 100644 index 0000000..6ba577e --- /dev/null +++ b/NuGet.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..b2becdc --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# messengerapi.Client + +[!["send me a tip"](https://img.shields.io/badge/give%20me%20a%20-tip-FFD200)](https://paypal.me/emsicz) [!["see my github"](https://img.shields.io/badge/see%20my%20-github-1F2328)](https://github.com/masiton?tab=repositories) + +Allows subscription-based consumption of MessengerApi. Simply subscribe to pattern in PayloadType property of the message and SubscriptionClient will let you know when a message arrives. + +![example](./assets/example.jpeg) \ No newline at end of file diff --git a/code/MessengerApi.SubscriptionClient.Example/MessengerApi.SubscriptionClient.Example.csproj b/code/MessengerApi.SubscriptionClient.Example/MessengerApi.SubscriptionClient.Example.csproj new file mode 100644 index 0000000..a608868 --- /dev/null +++ b/code/MessengerApi.SubscriptionClient.Example/MessengerApi.SubscriptionClient.Example.csproj @@ -0,0 +1,14 @@ + + + + Exe + net9.0 + enable + enable + + + + + + + diff --git a/code/MessengerApi.SubscriptionClient.Example/Program.cs b/code/MessengerApi.SubscriptionClient.Example/Program.cs new file mode 100644 index 0000000..7b59720 --- /dev/null +++ b/code/MessengerApi.SubscriptionClient.Example/Program.cs @@ -0,0 +1,48 @@ +using MessengerApi.Model; +using MessengerApi.Model.Messages; +using portaloggy; + +namespace MessengerApi.Example +{ + internal class Program + { + static void Main(string[] args) + { + var logger = new ConsoleLogger(); + var httpClient = new HttpClient(); + + var client1 = new Client( + new Credentials( + "aab8f7e9-ad13-4bf8-bb2e-0cd93d81adc0", + "http://localhost:5259"), + httpClient, + logger); + + var client2 = new SubscriptionClient( + new Credentials( + "8f73f683-7cb3-40df-998e-6e604aef0e53", + "http://localhost:5259"), + httpClient, + logger); + + var user1 = Guid.Parse("f696442b-e8dc-4074-b34f-94bcece8e74b"); + var user2 = Guid.Parse("15d97720-f5b7-47aa-9c1a-71f98b0b9248"); + + var client2Subscription = client2.Subscribe("TEST"); + + client2Subscription.OnMessage += (s, m) => + { + logger.Info($"Received subscribed message - {m.Payload}"); + }; + + var messageId = client1.SendMessage(new OutboxMessage + { + ToUserId = user2, + PayloadType = "TEST", + Payload = "Testing payload." + }); + + Task.Delay(2000).Wait(); + } + } +} diff --git a/code/MessengerApi.SubscriptionClient.sln b/code/MessengerApi.SubscriptionClient.sln new file mode 100644 index 0000000..7bbba59 --- /dev/null +++ b/code/MessengerApi.SubscriptionClient.sln @@ -0,0 +1,49 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.11.35312.102 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8EC462FD-D22E-90A8-E5CE-7E832BA40C5D}" + ProjectSection(SolutionItems) = preProject + ..\Directory.Packages.props = ..\Directory.Packages.props + ..\NuGet.config = ..\NuGet.config + ..\README.md = ..\README.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}" + ProjectSection(SolutionItems) = preProject + ..\.gitea\workflows\publish-nuget.yml = ..\.gitea\workflows\publish-nuget.yml + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".gitea", ".gitea", "{C3305381-7A52-4E26-9527-1697692DDD5A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MessengerApi.SubscriptionClient", "MessengerApi.SubscriptionClient\MessengerApi.SubscriptionClient.csproj", "{38F678EF-B8DB-5BF5-CFE7-69BA61F502EF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MessengerApi.SubscriptionClient.Example", "MessengerApi.SubscriptionClient.Example\MessengerApi.SubscriptionClient.Example.csproj", "{0DA95596-3ECF-4AC1-B9F0-E51AF344F64C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {38F678EF-B8DB-5BF5-CFE7-69BA61F502EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {38F678EF-B8DB-5BF5-CFE7-69BA61F502EF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {38F678EF-B8DB-5BF5-CFE7-69BA61F502EF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {38F678EF-B8DB-5BF5-CFE7-69BA61F502EF}.Release|Any CPU.Build.0 = Release|Any CPU + {0DA95596-3ECF-4AC1-B9F0-E51AF344F64C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0DA95596-3ECF-4AC1-B9F0-E51AF344F64C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0DA95596-3ECF-4AC1-B9F0-E51AF344F64C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0DA95596-3ECF-4AC1-B9F0-E51AF344F64C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} = {C3305381-7A52-4E26-9527-1697692DDD5A} + {C3305381-7A52-4E26-9527-1697692DDD5A} = {8EC462FD-D22E-90A8-E5CE-7E832BA40C5D} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {61948E36-4C2B-4BC9-80B6-9E155CE9F7DE} + EndGlobalSection +EndGlobal diff --git a/code/MessengerApi.SubscriptionClient/MessengerApi.SubscriptionClient.csproj b/code/MessengerApi.SubscriptionClient/MessengerApi.SubscriptionClient.csproj new file mode 100644 index 0000000..abca5f6 --- /dev/null +++ b/code/MessengerApi.SubscriptionClient/MessengerApi.SubscriptionClient.csproj @@ -0,0 +1,27 @@ + + + + net9.0 + enable + disable + True + $(AssemblyName) + $([System.DateTime]::UtcNow.ToString("yyyy.MM.dd.HHmm")) + $([System.DateTime]::UtcNow.ToString("yyyy.MM.dd.HHmm")) + ..\out\ + true + $(AssemblyName) + https://gitea.masita.net/mc/messengerapi.SubscriptionClient + https://gitea.masita.net/mc/messengerapi.SubscriptionClient + logging;log;logger + mit-0 + Allows subscription-based consumption of MessengerApi. Simply subscribe to pattern in PayloadType property of the message and SubscriptionClient will let you know when a message arrives. + mc @ 2024 + mc + + + + + + + \ No newline at end of file diff --git a/code/MessengerApi.SubscriptionClient/Model/Subscription.cs b/code/MessengerApi.SubscriptionClient/Model/Subscription.cs new file mode 100644 index 0000000..c8fd03a --- /dev/null +++ b/code/MessengerApi.SubscriptionClient/Model/Subscription.cs @@ -0,0 +1,52 @@ +using MessengerApi.Model.Messages; + +namespace MessengerApi.Model +{ + /// + /// See if you need to subscribe. It will give you one of these upon subscribing. + /// Also see for what happens where you actually receive message for this sub. + /// + public class Subscription : IDisposable + { + public string MessageTypeMask { get; private set; } + + public event EventHandler OnMessage; + + internal SubscriptionClient client; + + private bool isDisposed; + + internal Subscription(string messageTypeMask, SubscriptionClient client) + { + MessageTypeMask = messageTypeMask; + this.client = client; + } + + internal void Message(InboxMessage message) + { + OnMessage?.Invoke(this, message); + } + + public void Dispose() + { + if (isDisposed) + { + return; + } + + AssertNotDisposedOrThrow(); + client.Unsubscribe(this); + Dispose(); + + isDisposed = true; + } + + private void AssertNotDisposedOrThrow() + { + if (isDisposed) + { + throw new ObjectDisposedException(MessageTypeMask); + } + } + } +} \ No newline at end of file diff --git a/code/MessengerApi.SubscriptionClient/SubscriptionClient.cs b/code/MessengerApi.SubscriptionClient/SubscriptionClient.cs new file mode 100644 index 0000000..b55e649 --- /dev/null +++ b/code/MessengerApi.SubscriptionClient/SubscriptionClient.cs @@ -0,0 +1,61 @@ +using MessengerApi.Model; +using portaloggy; + +namespace MessengerApi +{ + /// + /// This exists so you can mock it. + /// + public interface ISubscriptionClient : IDisposable + { + /// + /// Subscribes to given message type mask. Thread-safe. + /// + /// Expected format of mask: "MY-MESSAGE-TYPE". No wildcards or placeholders, we only compare MessageType.StartsWith using this value. + Subscription Subscribe(string payloadTypeMask); + + /// + /// Unsubscribes from given subscriptions. Thread-safe. + /// + void Unsubscribe(Subscription subscription); + } + + /// + /// This is where you begin. Instantiate one of these and start subscribing with . + /// + public class SubscriptionClient : Client, ISubscriptionClient + { + private readonly SubscriptionPollingEngine _engine; + + private bool _isDisposed; + + public SubscriptionClient(Credentials credentials, HttpClient client = null, ILogger logger = null) : base(credentials, client, logger) + { + this._engine = new SubscriptionPollingEngine(this._logger, this); + } + + public void Dispose() + { + if (this._isDisposed) + { + return; + } + + this._engine.Dispose(); + this._isDisposed = true; + } + + public Subscription Subscribe(string messageTypeMask) + { + var sub = new Subscription(messageTypeMask, this); + this._engine.AddSubscription(sub); + + return sub; + } + + public void Unsubscribe(Subscription subscription) + { + this._engine.RemoveSubscription(subscription); + } + } +} \ No newline at end of file diff --git a/code/MessengerApi.SubscriptionClient/SubscriptionPollingEngine.cs b/code/MessengerApi.SubscriptionClient/SubscriptionPollingEngine.cs new file mode 100644 index 0000000..751dc42 --- /dev/null +++ b/code/MessengerApi.SubscriptionClient/SubscriptionPollingEngine.cs @@ -0,0 +1,129 @@ +using portaloggy; +using MessengerApi.Model.Messages; +using MessengerApi.Model; + +namespace MessengerApi +{ + internal class SubscriptionPollingEngine : IDisposable + { + private readonly ILogger logger; + private readonly IClient client; + private readonly List subscriptions = new List(); + private readonly object subscriptionsLocker = new object(); + + private Task executionTask; + private CancellationTokenSource executionCts; + private bool isDisposed; + + internal SubscriptionPollingEngine( + ILogger logger, + IClient client) + { + this.logger = logger; + this.client = client; + } + + public Task AddSubscription(Subscription subscription) + { + this.AssertNotDisposedOrThrow(); + + lock (subscriptionsLocker) + { + subscriptions.Add(subscription); + } + + this.logger.Log($"Subscription added for message {subscription.MessageTypeMask}."); + + if(this.executionTask == null && this.executionCts == null) + { + this.BeginPolling(); + } + + return Task.CompletedTask; + } + + public void Dispose() + { + if (this.isDisposed) + { + return; + } + + this.executionCts.Cancel(); + this.executionCts.Dispose(); + + this.isDisposed = true; + } + + internal void BeginPolling() + { + this.executionCts = new CancellationTokenSource(); + this.executionTask = this.PollEndlessly(this.executionCts.Token); + + this.logger.Log("Polling endlessly now."); + } + + internal void RemoveSubscription(Subscription subscription) + { + lock (subscriptionsLocker) + { + this.subscriptions.Remove(subscription); + } + } + + private async Task PollEndlessly(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + var messages = Enumerable.Empty(); + + try + { + messages = this.client.GetMessages(); + this.logger.Info($"Received {messages.Count()} messages."); + } + catch (Exception ex) + { + this.logger.Error("Can't obtain messages.", ex); + } + + foreach (var message in messages) + { + try + { + var sub = (Subscription)null; + + lock (this.subscriptionsLocker) + { + sub = this.subscriptions.FirstOrDefault(x => message.PayloadType.StartsWith(x.MessageTypeMask)); + } + + if (sub == null) + { + this.logger.Log($"This message has no subscription and will be ignored: {message.PayloadType}."); + continue; + } + + sub.Message(message); + } + catch (Exception ex) + { + this.logger.Error("Can't process received message.", ex); + } + } + + await Task.Delay(1000); + } + + this.logger.Info("Polling ended."); + } + + private void AssertNotDisposedOrThrow() + { + if (this.isDisposed) + { + throw new ObjectDisposedException(null); + } + } + } +} \ No newline at end of file