Repository navigation
Веб-сервер: прием WebSocket и повторный Запустить #1778
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
Open
sfaqer
wants to merge
1
commit into
EvilBeaver:develop
Choose a base branch
from
sfaqer:bugfix/web-server-thread-safety
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+246
−35
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
189 changes: 189 additions & 0 deletions
189
src/Tests/OneScript.Core.Tests/WebServerConcurrencyTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| /*---------------------------------------------------------- | ||
| This Source Code Form is subject to the terms of the | ||
| Mozilla Public License, v.2.0. If a copy of the MPL | ||
| was not distributed with this file, You can obtain one | ||
| at http://mozilla.org/MPL/2.0/. | ||
| ----------------------------------------------------------*/ | ||
|
|
||
| using System; | ||
| using System.Net; | ||
| using System.Net.Sockets; | ||
| using System.Net.WebSockets; | ||
| using System.Text; | ||
| using System.Threading; | ||
| using FluentAssertions; | ||
| using OneScript.StandardLibrary; | ||
| using OneScript.Web.Server; | ||
| using ScriptEngine.HostedScript; | ||
| using ScriptEngine.HostedScript.Extensions; | ||
| using ScriptEngine.Hosting; | ||
| using ScriptEngine.Machine; | ||
| using Xunit; | ||
|
|
||
| namespace OneScript.Core.Tests | ||
| { | ||
| public class WebServerConcurrencyTests | ||
| { | ||
| private const string WebSocketScript = | ||
| "Перем мСервер Экспорт;\n" + | ||
| "\n" + | ||
| "Функция Прочитать(Сокет) Экспорт\n" + | ||
| " Возврат Сокет.ПолучитьСтроку();\n" + | ||
| "КонецФункции\n" + | ||
| "\n" + | ||
| "Функция ОбработчикЗапроса(Контекст, СледующийОбработчик) Экспорт\n" + | ||
| " Сокет = Контекст.ВебСокеты.ПодключитьВебСокет();\n" + | ||
| " Параметры = Новый Массив;\n" + | ||
| " Параметры.Добавить(Сокет);\n" + | ||
| " Задания = Новый Массив;\n" + | ||
| " // Два задания ждут сообщения из одного сокета одновременно\n" + | ||
| " Задания.Добавить(ФоновыеЗадания.Выполнить(ЭтотОбъект, \"Прочитать\", Параметры, Истина));\n" + | ||
| " Задания.Добавить(ФоновыеЗадания.Выполнить(ЭтотОбъект, \"Прочитать\", Параметры, Истина));\n" + | ||
| " ФоновыеЗадания.ОжидатьВсе(Задания);\n" + | ||
| " Ответы = Новый Массив;\n" + | ||
| " Для Каждого Задание Из Задания Цикл\n" + | ||
| " Если Задание.ИнформацияОбОшибке = Неопределено Тогда\n" + | ||
| " Ответы.Добавить(Задание.Результат);\n" + | ||
| " Иначе\n" + | ||
| " Ответы.Добавить(\"ошибка: \" + Задание.ИнформацияОбОшибке.Описание);\n" + | ||
| " КонецЕсли;\n" + | ||
| " КонецЦикла;\n" + | ||
| " Сокет.ОтправитьСтроку(СтрСоединить(Ответы, \"|\"));\n" + | ||
| "КонецФункции\n" + | ||
| "\n" + | ||
| "Процедура ЗапуститьСервер() Экспорт\n" + | ||
| " мСервер.Запустить();\n" + | ||
| "КонецПроцедуры\n" + | ||
| "\n" + | ||
| "мСервер = Новый ВебСервер(Порт);\n" + | ||
| "мСервер.ИспользоватьВебСокеты();\n" + | ||
| "мСервер.ДобавитьОбработчикЗапросов(ЭтотОбъект, \"ОбработчикЗапроса\");\n" + | ||
| "Задание = ФоновыеЗадания.Выполнить(ЭтотОбъект, \"ЗапуститьСервер\");\n"; | ||
|
|
||
| private const string SecondRunScript = | ||
| "Перем мСервер;\n" + | ||
| "Перем ОшибкаПовторногоЗапуска Экспорт;\n" + | ||
| "Перем Остановлен Экспорт;\n" + | ||
| "\n" + | ||
| "Функция ОбработчикЗапроса(Контекст, СледующийОбработчик) Экспорт\n" + | ||
| " Контекст.Ответ.КодСостояния = 200;\n" + | ||
| "КонецФункции\n" + | ||
| "\n" + | ||
| "Процедура ЗапуститьСервер() Экспорт\n" + | ||
| " мСервер.Запустить();\n" + | ||
| "КонецПроцедуры\n" + | ||
| "\n" + | ||
| "мСервер = Новый ВебСервер(0);\n" + | ||
| "мСервер.ДобавитьОбработчикЗапросов(ЭтотОбъект, \"ОбработчикЗапроса\");\n" + | ||
| "Задания = Новый Массив;\n" + | ||
| "Задания.Добавить(ФоновыеЗадания.Выполнить(ЭтотОбъект, \"ЗапуститьСервер\"));\n" + | ||
| "Для Номер = 1 По 200 Цикл\n" + | ||
| " Если мСервер.Порт <> 0 Тогда\n" + | ||
| " Прервать;\n" + | ||
| " КонецЕсли;\n" + | ||
| " Приостановить(50);\n" + | ||
| "КонецЦикла;\n" + | ||
| "Попытка\n" + | ||
| " мСервер.Запустить();\n" + | ||
| " ОшибкаПовторногоЗапуска = \"\";\n" + | ||
| "Исключение\n" + | ||
| " ОшибкаПовторногоЗапуска = ИнформацияОбОшибке().Описание;\n" + | ||
| "КонецПопытки;\n" + | ||
| "мСервер.Остановить();\n" + | ||
| "Остановлен = ФоновыеЗадания.ОжидатьВсе(Задания, 10000);\n"; | ||
|
|
||
| [Fact] | ||
| public void WebSocketMessagesAreReceivedWholeFromManyTasks() | ||
| { | ||
| var engine = CreateEngine(); | ||
| var port = FreePort(); | ||
| var context = new ExternalContextData | ||
| { | ||
| { "Порт", ValueFactory.Create(port) } | ||
| }; | ||
| var instance = engine.Engine.AttachedScriptsFactory.LoadFromString( | ||
| engine.GetCompilerService(), WebSocketScript, engine.Engine.NewProcess(), context); | ||
| var server = (WebServer)instance.GetPropValue(instance.GetPropertyNumber("мСервер")); | ||
| try | ||
| { | ||
| using var client = Connect(new Uri($"ws://127.0.0.1:{port}/")); | ||
| Send(client, "раз"); | ||
| Send(client, "два"); | ||
|
|
||
| var answers = Receive(client).Split('|'); | ||
|
|
||
| answers.Should().BeEquivalentTo("раз", "два"); | ||
| } | ||
| finally | ||
| { | ||
| server.Stop(); | ||
| } | ||
| } | ||
|
|
||
| [Fact] | ||
| public void SecondRunOfSameServerIsRejected() | ||
| { | ||
| var engine = CreateEngine(); | ||
| var instance = engine.Engine.AttachedScriptsFactory.LoadFromString( | ||
| engine.GetCompilerService(), SecondRunScript, engine.Engine.NewProcess()); | ||
|
|
||
| instance.GetPropValue(instance.GetPropertyNumber("ОшибкаПовторногоЗапуска")).ToString() | ||
| .Should().Contain("уже запущен"); | ||
| instance.GetPropValue(instance.GetPropertyNumber("Остановлен")).AsBoolean() | ||
| .Should().BeTrue("Остановить должен остановить первый запуск"); | ||
| } | ||
|
|
||
| private static ClientWebSocket Connect(Uri uri) | ||
| { | ||
| for (var attempt = 0; ; attempt++) | ||
| { | ||
| var client = new ClientWebSocket(); | ||
| try | ||
| { | ||
| client.ConnectAsync(uri, CancellationToken.None).Wait(); | ||
| return client; | ||
| } | ||
| catch (AggregateException) when (attempt < 100) | ||
| { | ||
| // Сервер еще запускается в фоновом задании | ||
| client.Dispose(); | ||
| Thread.Sleep(100); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static void Send(ClientWebSocket client, string text) | ||
| { | ||
| client.SendAsync(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text, true, CancellationToken.None).Wait(); | ||
| } | ||
|
|
||
| private static string Receive(ClientWebSocket client) | ||
| { | ||
| var buffer = new byte[4096]; | ||
| using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); | ||
| var result = client.ReceiveAsync(buffer, cancellation.Token).Result; | ||
| return Encoding.UTF8.GetString(buffer, 0, result.Count); | ||
| } | ||
|
|
||
| private static HostedScriptEngine CreateEngine() | ||
| { | ||
| var builder = DefaultEngineBuilder.Create() | ||
| .SetDefaultOptions() | ||
| .UseImports() | ||
| .UseDefaultHosting() | ||
| .SetupEnvironment(e => e.AddStandardLibrary().AddWebServer()); | ||
| var engine = new HostedScriptEngine(builder.Build()); | ||
| engine.Initialize(); | ||
| return engine; | ||
| } | ||
|
|
||
| private static int FreePort() | ||
| { | ||
| var listener = new TcpListener(IPAddress.Loopback, 0); | ||
| listener.Start(); | ||
| var port = ((IPEndPoint)listener.LocalEndpoint).Port; | ||
| listener.Stop(); | ||
| return port; | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А не проще было бы
volatile boolполе объявить, чем вот эту конструкцию использовать?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
volatileдает только видимость, а тут надо проверить и выставить одним действием: дваЗапуститьиз разных потоков оба прочитали быЛожьи оба запустили бы сервер. Могу переписать наlockс обычнымbool, если так понятнее.