-
Notifications
You must be signed in to change notification settings - Fork 119
Функция ТекущийПоток(): данные и событие завершения потока исполнения #1725
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
nixel2007
wants to merge
13
commits into
EvilBeaver:develop
Choose a base branch
from
nixel2007:claude/webserver-thread-id-1cpihb
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.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
6c2da66
Добавлена глобальная функция ИдентификаторПотокаИсполнения
claude 3b5d116
Обработчик исключений веб-сервера работает в процессе запроса
claude 3cb707c
Процесс запроса хранится в HttpContext.Features
claude d633efe
Процесс запроса выдаётся scoped-сервисом
claude e9cadbc
ТекущийПоток() вместо ИдентификаторПотокаИсполнения()
nixel2007 1e5c1d0
Событие завершения потока исполнения
nixel2007 e6df864
Завершение потока исполнения по замечаниям ревью
nixel2007 eb5a996
Изоляция освобождения данных потока и уборка за тестом
nixel2007 4ee6035
Процесс сам завершает свой поток исполнения
nixel2007 12861a5
Процесс освобождает свою область сервисов
nixel2007 e58c3d1
Переделка подхода к BslПроцессу, вариант с протекающим враппером.
EvilBeaver 7284463
Вынес контекст из папки Threads
EvilBeaver e29b496
Поправил тесты
EvilBeaver 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
133 changes: 133 additions & 0 deletions
133
src/OneScript.StandardLibrary/ExecutionThreadContext.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,133 @@ | ||
| /*---------------------------------------------------------- | ||
| 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.Linq; | ||
| using OneScript.Contexts; | ||
| using OneScript.Execution; | ||
| using OneScript.StandardLibrary.Collections; | ||
| using ScriptEngine; | ||
| using ScriptEngine.Machine; | ||
| using ScriptEngine.Machine.Contexts; | ||
|
|
||
| namespace OneScript.StandardLibrary | ||
| { | ||
| /// <summary> | ||
| /// Поток исполнения bsl-кода. | ||
| /// | ||
| /// Потоком исполнения является каждая независимая единица исполнения: основной скрипт, | ||
| /// каждое фоновое задание и каждый обрабатываемый запрос веб-сервера. Получить поток | ||
| /// исполнения текущего кода можно функцией ТекущийПоток(). | ||
| /// | ||
| /// Свойство Данные представляет собой хранилище, живущее ровно столько же, сколько живёт | ||
| /// сам поток исполнения. Оно предназначено для библиотек, которым нужно хранить состояние | ||
| /// в разрезе единицы исполнения (аналог thread-local хранилища). | ||
| /// | ||
| /// По завершении потока исполнения поднимается событие ПриЗавершении (оно же OnTermination), | ||
| /// на которое можно подписаться штатным способом: | ||
| /// | ||
| /// ДобавитьОбработчик ТекущийПоток().ПриЗавершении, ЭтотОбъект.ВернутьСоединениеВПул; | ||
| /// | ||
| /// Обработчик вызывается до очистки данных потока, поэтому ещё видит их содержимое. | ||
| /// Это позволяет владельцам ресурсов узнавать о конце единицы исполнения вместо того, | ||
| /// чтобы опрашивать список фоновых заданий. | ||
| /// </summary> | ||
| [ContextClass("ПотокИсполнения", "ExecutionThread")] | ||
| public sealed class ExecutionThreadContext : AutoContext<ExecutionThreadContext>, IDisposable | ||
| { | ||
| private readonly IBslProcess _process; | ||
|
|
||
| private bool _isDisposed; | ||
|
|
||
| private ExecutionThreadContext(IBslProcess process) | ||
| { | ||
| _process = process; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Идентификатор потока исполнения. Предназначен для диагностики и журналирования. | ||
| /// | ||
| /// Идентификаторы выдаются последовательно и в пределах запущенного движка не повторяются, | ||
| /// пока счётчик не исчерпает диапазон Int32. Для хранения состояния в разрезе потока | ||
| /// исполнения используйте свойство Данные, а не идентификатор в качестве ключа. | ||
| /// </summary> | ||
| /// <value>Число. Идентификатор потока исполнения.</value> | ||
| [ContextProperty("Идентификатор", "Id")] | ||
| public int Identifier => _process.VirtualThreadId; | ||
|
|
||
| /// <summary> | ||
| /// Хранилище данных потока исполнения, аналог набора thread-local переменных. | ||
| /// | ||
| /// Соответствие создаётся вместе с потоком исполнения и не разделяется с другими потоками. | ||
| /// В конце потока исполнения соответствие очищается, а его значения, поддерживающие | ||
| /// интерфейс IDisposable среды CLR, принудительно освобождаются. | ||
| /// </summary> | ||
| /// <value>Соответствие. Данные потока исполнения.</value> | ||
| [ContextProperty("Данные", "Data")] | ||
| public MapImpl Data { get; } = new MapImpl(); | ||
|
|
||
| /// <summary> | ||
| /// Возвращает поток исполнения указанного bsl-процесса, создавая его при первом обращении. | ||
| /// Для одного процесса всегда возвращается один и тот же экземпляр. | ||
| /// | ||
| /// Созданный поток остаётся на процессе и освобождается вместе с ним. | ||
| /// </summary> | ||
| internal static ExecutionThreadContext Of(IBslProcess process) | ||
| { | ||
| if (process.BslWrapper is ExecutionThreadContext wrapper) | ||
| return wrapper; | ||
|
|
||
| lock (process) | ||
| { | ||
| if (process.BslWrapper is ExecutionThreadContext created) | ||
| return created; | ||
|
|
||
| if (process.BslWrapper != null) | ||
| throw new InvalidOperationException($"BslWrapper for process is not {nameof(ExecutionThreadContext)}: {process.BslWrapper.GetType()}"); | ||
|
|
||
| var thread = new ExecutionThreadContext(process); | ||
| process.BslWrapper = thread; | ||
|
|
||
| return thread; | ||
| } | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| // Пока идёт завершение, поток ещё числится за процессом, и обработчик вправе | ||
| // добраться до него через ТекущийПоток(). Если он при этом освободит процесс, | ||
| // завершение не должно пойти по второму кругу. | ||
| if (_isDisposed) | ||
| return; | ||
|
|
||
| _isDisposed = true; | ||
|
|
||
| try | ||
| { | ||
| foreach (var item in Data.ToArray()) | ||
| { | ||
| if (item.Value is not IDisposable disposable) | ||
| continue; | ||
|
|
||
| try | ||
| { | ||
| disposable.Dispose(); | ||
| } | ||
| catch (Exception exception) | ||
| { | ||
| SystemLogger.Write( | ||
| $"WARNING! Error releasing execution thread data '{item.Key}': {exception.Message}"); | ||
| } | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| Data.Clear(); | ||
| } | ||
| } | ||
| } | ||
| } |
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| /*---------------------------------------------------------- | ||
| 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 FluentAssertions; | ||
| using ScriptEngine.Hosting; | ||
| using Xunit; | ||
|
|
||
| namespace OneScript.Core.Tests | ||
| { | ||
| /// <summary> | ||
| /// Регистрируется как scoped, поэтому живёт ровно столько же, сколько область сервисов процесса. | ||
| /// </summary> | ||
| public sealed class ScopedDisposableProbe : IDisposable | ||
| { | ||
| public bool IsDisposed { get; private set; } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| IsDisposed = true; | ||
| } | ||
| } | ||
|
|
||
| public class BslProcessTests | ||
| { | ||
| private static ScriptEngine.ScriptingEngine CreateEngineWithScopedProbe() | ||
| { | ||
| var builder = DefaultEngineBuilder.Create().SetDefaultOptions(); | ||
| builder.Services.RegisterScoped<ScopedDisposableProbe>(); | ||
|
|
||
| var engine = builder.Build(); | ||
| engine.Initialize(); | ||
|
|
||
| return engine; | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ProcessReleasesItsServiceScope() | ||
| { | ||
| var engine = CreateEngineWithScopedProbe(); | ||
|
|
||
| var process = engine.NewProcess(); | ||
| var scoped = process.Services.Resolve<ScopedDisposableProbe>(); | ||
|
|
||
| scoped.IsDisposed.Should().BeFalse("процесс ещё работает"); | ||
|
|
||
| engine.AttachedScriptsFactory.LoadFromString( | ||
| engine.GetCompilerService(), "f = 1", process); | ||
|
|
||
| scoped.IsDisposed.Should().BeTrue("процесс владеет своей областью сервисов"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ProcessDoesNotReleaseScopeOfAnotherProcess() | ||
| { | ||
| var engine = CreateEngineWithScopedProbe(); | ||
|
|
||
| var first = engine.NewProcess(); | ||
| var second = engine.NewProcess(); | ||
|
|
||
| var firstScoped = first.Services.Resolve<ScopedDisposableProbe>(); | ||
| var secondScoped = second.Services.Resolve<ScopedDisposableProbe>(); | ||
|
|
||
| firstScoped.Should().NotBeSameAs(secondScoped, "у каждого процесса своя область сервисов"); | ||
|
|
||
| secondScoped.IsDisposed.Should().BeFalse("освобождение одного процесса не трогает другой"); | ||
| } | ||
| } | ||
| } |
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.
Оба места нашли верно, проверил.
ConsoleContext.cs:274исправлен вeb5a9968— завершение потока добавлено вfinallyвокруг вызова обработчика Ctrl+C.С
ExceptionInfoFactory.cs:60так не выйдет: он живёт вScriptEngine, аExecutionThreadContext— вOneScript.StandardLibrary, и ссылка между ними односторонняя (StandardLibrary → ScriptEngine). Позвать завершение оттуда физически нечем.То есть остаётся ровно та развилка, которую вы и назвали: либо централизовать жизненный цикл на границе процесса, либо оставить это место незакрытым. Вижу два варианта централизации:
OneScript.Core, напримерIBslProcessLifetimeс методомFinished(IBslProcess), регистрируемый как enumerable.StandardLibraryрегистрирует реализацию, которая зовётRelease, а владельцы процессов в движке уведомляют слушателей. Абстракция маленькая, но владельцы всё равно должны её звать.IBslProcessосвобождаемым и завершать его владельцами черезusing. Честнее по смыслу и закрывает вообще все места разом, но это изменение публичного интерфейса, который реализуют ещёForbiddenBslProcessи тестовые заглушки.Сам выбирать не стал: это уже третье изменение формы API в этом PR, и решать, по-моему, автору движка. Пока оставил как есть и фиксирую здесь, чтобы не потерялось.
Замечу для полноты картины: утечки памяти в незакрытых местах нет — поток привязан к процессу через
ConditionalWeakTableи исчезает вместе с ним. Теряется только детерминированность:ПриЗавершениине наступает и значения сIDisposableне освобождаются сразу. Для разового преобразования в строку это вряд ли критично, но контракт действительно нарушается.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.
Закрыто. Из двух вариантов, которые я тут описывал, взяли второй — жизненный цикл централизован на процессе.
IBslProcessстал освобождаемым и сам завершает свой поток исполнения (4ee60355). Владельцы процессов перешли наusing, явных вызовов завершения не осталось нигде. Заодно исчезла статическая коллекция, которой процессы сопоставлялись потокам, — на неё отдельно указывал мэйнтейнер.Оба места, которые вы нашли, теперь закрыты:
ConsoleContext.cs:274— обработчик Ctrl+C исполняется в процессе подusing;ExceptionInfoFactory.cs:60— тоже подusing. Раньше сюда было не дотянуться: он живёт вScriptEngine, а завершение потока — вOneScript.StandardLibrary, и ссылка между ними односторонняя. После централизации ему достаточно освободить процесс, про поток исполнения знать не нужно.Попутно нашлась и закрыта соседняя утечка:
BslProcessсоздаёт себе область сервисов в конструкторе, но не освобождал её никогда — scoped-регистрации процесса жили до конца работы движка. Теперь освобождает, последним действием: завершение потока обращается к области за процессором событий (12861a55).Перед этой правкой разобрал
TinyIoC, потому что освобождение дочернего контейнера могло задеть родительские объекты: у синглтон-фабрикиGetFactoryForChildContainerвозвращаетthis. Оказалось безопасно — родительские фабрики идут транзитом черезGetParentObjectFactoryи в реестр дочернего контейнера не попадают, аDisposeобходит только его. Зафиксировано тестомProcessDoesNotReleaseScopeOfAnotherProcess.Оговорюсь честно: сегодня по этой ветке освобождать нечего — единственная scoped-регистрация в движке
StackMachineProvider, и он неIDisposable. Так что правка закрывает утечку на будущее, а тест работает на собственном зонде, а не на живой регистрации.