-
Notifications
You must be signed in to change notification settings - Fork 0
update MDC, otel, WFlow #74
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
Merged
Merged
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
7c47e1a
init plan
karle0wne d1aecc9
guarantee MDC cleanup plus span termination when traces are absent (…
karle0wne 2e51698
bump test log level
karle0wne bd20b0b
Update dependency org.apache.commons:commons-lang3 to v3.18.0 [SECURI…
renovate[bot] 082bf01
Replace dependency org.slf4j:slf4j-log4j12 with org.slf4j:slf4j-reloa…
renovate[bot] d45b0af
Update all non-major maven dependencies (#51)
renovate[bot] 666a55e
add missing pom sonatype elements
karle0wne 59320bc
Refine THProviderErrorMapper error mapping and MDC tests (#78)
karle0wne 67163fe
refactor: unify trace metadata and rpc handling and add MDC propagati…
karle0wne 7f3320e
fixes
karle0wne 2afcb88
codacy
karle0wne f52ccdf
codacy
karle0wne 17ef0c0
codacy
karle0wne dcc7bf9
codacy
karle0wne 5e1c2af
codacy
karle0wne fff7bd1
add otel attributes (#81)
karle0wne 94dbac4
second put mdc after filling metadata (#82)
karle0wne 65040de
add MdcRefreshInterceptor (#83)
karle0wne 7c83f79
bump
karle0wne 9db2874
bump
karle0wne 80ed896
bump
karle0wne 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 was deleted.
Oops, something went wrong.
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 |
|---|---|---|
| @@ -1,18 +1,141 @@ | ||
| # dev.vality.woody | ||
| # Woody | ||
| [](https://central.sonatype.com/artifact/dev.vality.woody/woody) | ||
|
|
||
| Java реализация [Библиотеки RPC вызовов для общения между микросервисами](http://52.29.202.218/design/ms/platform/rpc-lib/). | ||
| Java реализация [Библиотеки RPC вызовов][rpc-lib] для общения между | ||
| микросервисами. | ||
|
|
||
| ## Описание | ||
|
|
||
| 1. [woody-api](woody-api/woody-api.md) | ||
| 1. [woody-thrift](woody-thrift/woody-thrift.md) | ||
|
|
||
| ## Архитектура | ||
|
|
||
| - **woody-api** – базовая библиотека трассировки: управляет `TraceContext`, | ||
| генерирует `trace_id/span_id`, переносит контекст между потоками (`WFlow`, | ||
| `WCallable/WRunnable/WExecutorService`), содержит цепочку прокси и | ||
| перехватчиков для событий, дедлайнов и маппинга ошибок. | ||
| - **woody-thrift** – интеграция с Thrift over HTTP: билдеры | ||
| клиентов/сервисов (`THClientBuilder`, `THServiceBuilder`) добавляют | ||
| transport/message интерсепторы, логирование, поддержку `traceparent` и | ||
| расширения метаданных. | ||
| - **libthrift** – локальный модуль с патчами Apache Thrift (HTTP-клиент 5, | ||
| сервлеты и TLS), используется как зависимость для `woody-thrift`. | ||
|
|
||
| ## Ключевые возможности | ||
|
|
||
| - Сквозная трассировка вызовов через `TraceData`, автоматическое измерение | ||
| длительности и интеграция со SLF4J MDC и OpenTelemetry. | ||
| - Расширенный MDC: автоматически публикует идентификаторы Woody/OTel, дедлайны, | ||
| RPC-метаданные и может отключаться через `-Dwoody.mdc.extended=false`. | ||
| - Потокобезопасная обработка фоновых задач с сохранением контекста | ||
| (`WFlow.create`, `createServiceFork`). | ||
| - Расширяемая система перехватчиков и `MetadataExtensionKit` для | ||
| обогащения метаданных и настройки transport/message уровней. | ||
| - HTTP Thrift клиенты и сервисы с пуллингом, логированием, маппингом ошибок и | ||
| готовыми EventListener’ами. | ||
| - Обновлённый маппинг ошибок и транспорта (`THProviderErrorMapper`), покрытый | ||
| изолированными тестами и сценариями с сетевыми исключениями. | ||
|
|
||
| ## Для ознакомления | ||
|
|
||
| [Thrift](https://thrift.apache.org/) | ||
| [Dapper](http://research.google.com/pubs/pub36356.html) | ||
|
|
||
| ## Выпуск новой версии | ||
| Версии _woody-pom_ и всех его модулей должны совпадать, для этого перед началом работы над новой версией библиотеки нужно увеличить версию _woody-pom_ и в корневой директории проекта выполнить команду: | ||
|
|
||
| Версии _woody-pom_ и всех его модулей должны совпадать, для этого перед | ||
| началом работы над новой версией библиотеки нужно увеличить версию | ||
| _woody-pom_ и в корневой директории проекта выполнить команду: | ||
| `mvn versions:update-child-modules -DgenerateBackupPoms=false` | ||
| Параметр `generateBackupPoms` можно опустить, если нужны резервные копии изменяемых файлов. | ||
| Параметр `generateBackupPoms` можно опустить, если нужны резервные копии | ||
| изменяемых файлов. | ||
|
|
||
| ## Общая структура | ||
|
|
||
| - Maven-монорепо (`pom.xml`) с тремя артефактами: базовая библиотека | ||
| `woody-api`, интеграция `woody-thrift`, а также пропатченный `libthrift` | ||
| (форк Apache Thrift, переиспользующий HttpClient5 и подключающийся как | ||
| модуль). | ||
| - Основной стек: Java 11, SLF4J, Apache Commons Pool 2, OpenTelemetry | ||
| (API/SDK/OTLP), Jakarta Servlet 5, Jetty и EasyMock в тестах. | ||
|
|
||
| ## Woody API | ||
|
|
||
| - `TraceContext`/`TraceData` управляют client/service span’ами в | ||
| `ThreadLocal`, автоматически создают `trace_id/span_id`, фиксируют | ||
| длительность, синхронизируют SLF4J MDC и завершают OTEL-спаны. | ||
| - `WFlow` и `flow.concurrent` оборачивают `Runnable`/`Callable`/ | ||
| `ExecutorService`, сохраняя контекст при выполнении в других потоках, | ||
| поддерживают форки с новыми root- и service-span’ами. | ||
| - Система перехватчиков (`proxy`, `interceptor`, `event`): | ||
| - `ProxyFactory` строит динамические прокси вокруг клиентов и | ||
| обработчиков, направляя вызовы через `MethodCallTracer`. | ||
| - `AbstractClientBuilder`/`AbstractServiceBuilder` подключают | ||
| `ContextTracer`, контроль дедлайнов, маппинг ошибок и event-трейсеры. | ||
| - События (`ClientEvent`, `ServiceEvent`) обрабатываются композиционными | ||
| слушателями; `TransportEventInterceptor` и `ProviderEventInterceptor` | ||
| публикуют события до и после вызовов. | ||
| - Расширяемость через `interceptor.ext` и `MetadataExtensionKit`: | ||
| расширения получают `TraceData` и транспортный контекст для обогащения | ||
| метаданных. | ||
| - Ошибки классифицируются `WErrorType`/`WErrorDefinition`; | ||
| `ErrorMapProcessor` и `ErrorMappingInterceptor` мэппят транспортные и | ||
| бизнес-ошибки; `DeadlineTracer` обеспечивает контроль таймаутов. | ||
|
|
||
| ## Woody Thrift | ||
|
|
||
| - Thrift over HTTP поверх Woody. | ||
| - Клиенты (`THClientBuilder`, `THSpawnClientBuilder`, | ||
| `THPooledClientBuilder`) создают `TServiceClient`, добавляют | ||
| транспортные и message перехватчики (метаданные, traceparent, события), | ||
| управляют ресурсами HttpClient5. | ||
| - Сервисы (`THServiceBuilder`) собирают `TServlet` с обёртками над | ||
| `TProcessor`, прокидывая `TraceContext.forService`, подключая | ||
| транспортные перехватчики и error-mapping (`THErrorMapProcessor`); | ||
| логирование (`THSEventLogListener`, `THCEventLogListener`) включено по | ||
| умолчанию. | ||
| - Транспорт и сообщения расширяются через bundles | ||
| (`MetadataExtensionBundle` и др.), создавая `THCExtensionContext`/ | ||
| `THSExtensionContext` для клиента и сервиса. | ||
| - Поддержка W3C traceparent (`TraceParentUtils`), заполнение | ||
| дедлайнов/ошибок в метаданные, HTTP-логгеры. | ||
| - Дополнительные пакеты: `error` (конвертация исключений и | ||
| HTTP-статусов), `event` (логирование), `transport` (конфигурация HTTP | ||
| servlet’ов и клиентов). | ||
|
|
||
| ## Libthrift | ||
|
|
||
| - Локальный модуль с модифицированными классами Apache Thrift | ||
| (HTTP-транспорт, сервлеты, TLS и т.д.) под HttpClient5 и расширения Woody; | ||
| подключается к `woody-thrift` как зависимость той же версии. | ||
|
|
||
| ## Тесты и утилиты | ||
|
|
||
| - `woody-api/src/test` покрывает генераторы идентификаторов, трассировку и | ||
| прокси. | ||
| - `woody-thrift/src/test` (Jetty quickstart + EasyMock) проверяет | ||
| HTTP-интеграцию, обработку исключений и метаданные, включая | ||
| интеграционные сценарии `TraceLifecycleIntegrationTest` для проверки | ||
| сквозной OpenTelemetry-трассировки, восстановления контекста, ошибок и | ||
| работы с неполными заголовками. | ||
| - Профиль `gen_thrift_classes` включает `thrift-maven-plugin` для генерации | ||
| Thrift IDL. | ||
| - Интеграционные тесты `MetadataMdcPropagationTest` и | ||
| `TraceLifecycleIntegrationTest` контролируют перенос MDC-метаданных, | ||
| OpenTelemetry-трассировку и восстановление контекста при ошибках. | ||
|
|
||
| ## Дополнительные материалы | ||
|
|
||
| - [Контекст Woody Java](context.md) — сводный обзор модулей, | ||
| инструментов и ключевых понятий. | ||
|
|
||
| ## Итог | ||
|
|
||
| Реализация обеспечивает сквозную трассировку, управление временем жизни | ||
| span’ов и доступ к событиям через единую API-обвязку; `woody-thrift` поверх | ||
| неё инкапсулирует создание HTTP-клиентов и сервисов Thrift с `traceparent`, | ||
| логированием и расширяемыми метаданными, опираясь на локально | ||
| модифицированный `libthrift`. | ||
|
|
||
| [rpc-lib]: http://52.29.202.218/design/ms/platform/rpc-lib/ |
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,125 @@ | ||
| # Woody Java – Reference Context | ||
|
|
||
| ## Project Overview | ||
|
|
||
| - Maven multi-module library delivering RPC tracing infrastructure for | ||
| microservices. | ||
| - Java 11 baseline; core dependencies include SLF4J, Apache Commons Pool 2, | ||
| OpenTelemetry (API/SDK/OTLP exporter), Jakarta Servlet 5, HttpClient5, Jetty | ||
| (tests), EasyMock. | ||
| - Modules share version `woody` (root POM); `dependencyManagement` keeps `woody- | ||
| api` version-aligned. | ||
|
|
||
| ## Module Breakdown | ||
|
|
||
| ### woody-api | ||
|
|
||
| - Thread-local tracing via `TraceContext`/`TraceData` managing client/service | ||
| spans, auto ID generation, duration tracking, SLF4J MDC sync, OTEL span | ||
| lifecycle. | ||
| - `MDCUtils` публикует trace/span идентификаторы Woody и OpenTelemetry, | ||
| дедлайны и RPC-метаданные (отключаемо через системное свойство | ||
| `woody.mdc.extended`). | ||
| - Concurrency helpers (`WFlow`, `WCallable`, `WRunnable`, `WExecutorService`) | ||
| clone/propagate trace context across threads, including service/client forks. | ||
| - Proxy/interceptor pipeline: | ||
| - `ProxyFactory` wraps interfaces with dynamic proxies and | ||
| `MethodCallTracer`. | ||
| - `AbstractClientBuilder`/`AbstractServiceBuilder` assemble tracing, | ||
| deadline | ||
| enforcement (`DeadlineTracer`), error | ||
| mapping, and event dispatch. | ||
| - Event system (`ClientEvent`, `ServiceEvent`, composite listeners) plus | ||
| transport/provider interceptors for | ||
| lifecycle hooks. | ||
| - Error framework (`WErrorType`, `WErrorDefinition`, `ErrorMapProcessor`, | ||
| `ErrorMappingInterceptor`) translating transport/business outcomes. | ||
| - Metadata extensibility via `interceptor.ext`, `ExtensionBundle`, | ||
| `MetadataExtensionKit`. | ||
|
|
||
| ### woody-thrift | ||
|
|
||
| - Thrift-over-HTTP implementation layered on woody-api. | ||
| - Client builders (`THClientBuilder`, `THSpawnClientBuilder`, | ||
| `THPooledClientBuilder`) construct `TServiceClient`, inject message/transport | ||
| interceptors, traceparent propagation, metadata extensions, logging | ||
| (`THCEventLogListener`); support custom or pooled HttpClient5. | ||
| - Service builder (`THServiceBuilder`) wraps `TProcessor` into `TServlet`, | ||
| applies transport interceptors, `THErrorMapProcessor`, logging | ||
| (`THSEventLogListener`), and ensures `TraceContext.forService`. | ||
| - Extension bundles produce `THCExtensionContext`/`THSExtensionContext`; | ||
| `TraceParentUtils` handles W3C traceparent parsing/serialization. | ||
| - Supplemental packages: `error` (exception ↔ response mapping), `event` (HTTP | ||
| logging), `transport` (servlet/client wiring). | ||
| - Обновлённый `THProviderErrorMapper` синхронизирует статус, источники ошибок, | ||
| метаданные и обеспечивает трассировку при транспортных исключениях. | ||
|
|
||
| ### libthrift | ||
|
|
||
| - Local fork of Apache Thrift with HttpClient5 transport adjustments, | ||
| servlet/TLS tweaks, and hooks compatible with woody interceptors. | ||
| - Packaged as module dependency for `woody-thrift` (same version). | ||
|
|
||
| ## Build & Tooling | ||
|
|
||
| - Root `pom.xml` наследуется от `dev.vality:library-parent-pom:3.1.0` и | ||
| управляет версией через `${revision}`. | ||
| - `woody-thrift` offers `gen_thrift_classes` profile running `thrift-maven- | ||
| plugin` (`thrift` executable required). | ||
| - Target Java version 11; uses Checkstyle suppressions and Renovate config. | ||
|
|
||
| ## Testing | ||
|
|
||
| - `woody-api/src/test`: ID generators, tracing logic, proxy behavior. | ||
| - `woody-thrift/src/test`: Jetty quickstart servers + EasyMock cover HTTP | ||
| integration, metadata propagation, error mapping, а также свежие | ||
| интеграционные сценарии `TraceLifecycleIntegrationTest`, проверяющие | ||
| сквозную OpenTelemetry-трассировку (новый/восстановленный контекст, | ||
| обработку ошибок, отсутствие обязательных метаданных). | ||
| - Дополнительно `THProviderErrorMapperTest` и `MetadataMdcPropagationTest` | ||
| контролируют обработку ошибок и перенос MDC/OTel данных. | ||
|
|
||
| ## Key Concepts for Agents | ||
|
|
||
| - Always maintain root/service/client span consistency; `TraceContext` | ||
| orchestrates init/destroy hooks and ensures MDC/Otel sync. | ||
| - Cross-thread execution must wrap tasks with | ||
| `WFlow.create`/`createServiceFork`. | ||
| - Interceptors are composable; metadata extensions rely on extension bundles | ||
| (client/service contexts differ). | ||
| - `libthrift` should be treated as authoritative transport layer—do not upgrade | ||
| Apache Thrift without reconciling local changes. | ||
|
|
||
| ## Ready-to-Use Snippets | ||
|
|
||
| - Create forked service task: `WFlow.createServiceFork(runnable)` or callables | ||
| with custom ID generators. | ||
| - Client build pattern: | ||
|
|
||
| ```java | ||
| ThriftServiceSrv.Iface client = new THClientBuilder() | ||
| .withAddress(URI.create("https://example")) | ||
| .withHttpClient(HttpClientBuilder.create().build()) | ||
| .withEventListener(listener) | ||
| .build(ThriftServiceSrv.Iface.class); | ||
| ``` | ||
|
|
||
| - Service servlet: | ||
|
|
||
| ```java | ||
| Servlet servlet = new THServiceBuilder() | ||
| .withEventListener(listener) | ||
| .build(ThriftServiceSrv.Iface.class, handlerImpl); | ||
| ``` | ||
|
|
||
| ## Operational Notes | ||
|
|
||
| - Logging depends on composite listeners; disable via `withLogEnabled(false)`. | ||
| - Deadlines propagate through spans; ensure upstream services respect | ||
| `DeadlineTracer`. | ||
| - Error mapping distinguishes transport errors vs business | ||
| (`WErrorType.BUSINESS_ERROR` leaves transport metadata intact). | ||
| - For new metadata, implement `MetadataExtensionKit` and include via builder | ||
| `withMetaExtensions`. | ||
| - Для фоновых задач используйте `WFlow.createServiceFork(...)` — он создаёт | ||
| новый service-span и корректно инициализирует OpenTelemetry контекст. |
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
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.
Uh oh!
There was an error while loading. Please reload this page.