@twin.org/tracing-processors 0.9.2-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -0
  3. package/dist/es/index.js +9 -0
  4. package/dist/es/index.js.map +1 -0
  5. package/dist/es/models/ITracingRestClientProcessorConfig.js +4 -0
  6. package/dist/es/models/ITracingRestClientProcessorConfig.js.map +1 -0
  7. package/dist/es/models/ITracingRestClientProcessorConstructorOptions.js +4 -0
  8. package/dist/es/models/ITracingRestClientProcessorConstructorOptions.js.map +1 -0
  9. package/dist/es/models/ITracingRouteProcessorConfig.js +4 -0
  10. package/dist/es/models/ITracingRouteProcessorConfig.js.map +1 -0
  11. package/dist/es/models/ITracingRouteProcessorConstructorOptions.js +2 -0
  12. package/dist/es/models/ITracingRouteProcessorConstructorOptions.js.map +1 -0
  13. package/dist/es/tracingRestClientProcessor.js +66 -0
  14. package/dist/es/tracingRestClientProcessor.js.map +1 -0
  15. package/dist/es/tracingRouteProcessor.js +144 -0
  16. package/dist/es/tracingRouteProcessor.js.map +1 -0
  17. package/dist/types/index.d.ts +6 -0
  18. package/dist/types/models/ITracingRestClientProcessorConfig.d.ts +9 -0
  19. package/dist/types/models/ITracingRestClientProcessorConstructorOptions.d.ts +15 -0
  20. package/dist/types/models/ITracingRouteProcessorConfig.d.ts +13 -0
  21. package/dist/types/models/ITracingRouteProcessorConstructorOptions.d.ts +18 -0
  22. package/dist/types/tracingRestClientProcessor.d.ts +29 -0
  23. package/dist/types/tracingRouteProcessor.d.ts +46 -0
  24. package/docs/changelog.md +17 -0
  25. package/docs/examples.md +88 -0
  26. package/docs/reference/classes/TracingRestClientProcessor.md +86 -0
  27. package/docs/reference/classes/TracingRouteProcessor.md +149 -0
  28. package/docs/reference/index.md +13 -0
  29. package/docs/reference/interfaces/ITracingRestClientProcessorConfig.md +11 -0
  30. package/docs/reference/interfaces/ITracingRestClientProcessorConstructorOptions.md +20 -0
  31. package/docs/reference/interfaces/ITracingRouteProcessorConfig.md +19 -0
  32. package/docs/reference/interfaces/ITracingRouteProcessorConstructorOptions.md +27 -0
  33. package/locales/.validate-ignore +3 -0
  34. package/locales/en.json +7 -0
  35. package/package.json +54 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 IOTA Stiftung.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # TWIN Tracing Processors
2
+
3
+ Traces the HTTP boundary, recording spans for inbound routes and outbound REST requests and carrying the trace between services.
4
+
5
+ ## Installation
6
+
7
+ ```shell
8
+ npm install @twin.org/tracing-processors
9
+ ```
10
+
11
+ ## Examples
12
+
13
+ Usage of the APIs is shown in the examples [docs/examples.md](docs/examples.md)
14
+
15
+ ## Reference
16
+
17
+ Detailed reference documentation for the API can be found in [docs/reference/index.md](docs/reference/index.md)
18
+
19
+ ## Changelog
20
+
21
+ The changes between each version can be found in [docs/changelog.md](docs/changelog.md)
@@ -0,0 +1,9 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export * from "./models/ITracingRestClientProcessorConfig.js";
4
+ export * from "./models/ITracingRestClientProcessorConstructorOptions.js";
5
+ export * from "./models/ITracingRouteProcessorConfig.js";
6
+ export * from "./models/ITracingRouteProcessorConstructorOptions.js";
7
+ export * from "./tracingRestClientProcessor.js";
8
+ export * from "./tracingRouteProcessor.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,+CAA+C,CAAC;AAC9D,cAAc,2DAA2D,CAAC;AAC1E,cAAc,0CAA0C,CAAC;AACzD,cAAc,sDAAsD,CAAC;AACrE,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./models/ITracingRestClientProcessorConfig.js\";\nexport * from \"./models/ITracingRestClientProcessorConstructorOptions.js\";\nexport * from \"./models/ITracingRouteProcessorConfig.js\";\nexport * from \"./models/ITracingRouteProcessorConstructorOptions.js\";\nexport * from \"./tracingRestClientProcessor.js\";\nexport * from \"./tracingRouteProcessor.js\";\n"]}
@@ -0,0 +1,4 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export {};
4
+ //# sourceMappingURL=ITracingRestClientProcessorConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ITracingRestClientProcessorConfig.js","sourceRoot":"","sources":["../../../src/models/ITracingRestClientProcessorConfig.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * Configuration for the tracing REST client processor.\n */\nexport interface ITracingRestClientProcessorConfig {\n\t/**\n\t * Route templates to skip tracing.\n\t */\n\texcludePaths?: string[];\n}\n"]}
@@ -0,0 +1,4 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export {};
4
+ //# sourceMappingURL=ITracingRestClientProcessorConstructorOptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ITracingRestClientProcessorConstructorOptions.js","sourceRoot":"","sources":["../../../src/models/ITracingRestClientProcessorConstructorOptions.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\nimport type { ITracingRestClientProcessorConfig } from \"./ITracingRestClientProcessorConfig.js\";\n\n/**\n * Options for the TracingRestClientProcessor constructor.\n */\nexport interface ITracingRestClientProcessorConstructorOptions {\n\t/**\n\t * The type for the tracing component, when absent no spans are created and no trace header is\n\t * sent.\n\t */\n\ttracingComponentType?: string;\n\n\t/**\n\t * Configuration for the processor.\n\t */\n\tconfig?: ITracingRestClientProcessorConfig;\n}\n"]}
@@ -0,0 +1,4 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export {};
4
+ //# sourceMappingURL=ITracingRouteProcessorConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ITracingRouteProcessorConfig.js","sourceRoot":"","sources":["../../../src/models/ITracingRouteProcessorConfig.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * Configuration for the tracing route processor.\n */\nexport interface ITracingRouteProcessorConfig {\n\t/**\n\t * Request URL path prefixes to skip tracing.\n\t */\n\texcludePaths?: string[];\n\n\t/**\n\t * Route operation IDs to skip tracing.\n\t */\n\texcludeOperationIds?: string[];\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ITracingRouteProcessorConstructorOptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ITracingRouteProcessorConstructorOptions.js","sourceRoot":"","sources":["../../../src/models/ITracingRouteProcessorConstructorOptions.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { ITracingRouteProcessorConfig } from \"./ITracingRouteProcessorConfig.js\";\n\n/**\n * Options for the TracingRouteProcessor constructor.\n */\nexport interface ITracingRouteProcessorConstructorOptions {\n\t/**\n\t * The type for the tracing component.\n\t */\n\ttracingComponentType?: string;\n\n\t/**\n\t * The type for the logging component.\n\t */\n\tloggingComponentType?: string;\n\n\t/**\n\t * The configuration for the tracing route processor.\n\t */\n\tconfig?: ITracingRouteProcessorConfig;\n}\n"]}
@@ -0,0 +1,66 @@
1
+ import { ComponentFactory, Is } from "@twin.org/core";
2
+ import { SpanKind, TraceparentHelper, TracingHelper } from "@twin.org/tracing-models";
3
+ import { HttpStatusCode } from "@twin.org/web";
4
+ /**
5
+ * Records a span for each outbound REST request and carries the trace via traceparent header.
6
+ */
7
+ export class TracingRestClientProcessor {
8
+ /**
9
+ * Runtime name for the class.
10
+ */
11
+ static CLASS_NAME = "TracingRestClientProcessor";
12
+ /**
13
+ * The component recording the spans.
14
+ * @internal
15
+ */
16
+ _tracing;
17
+ /**
18
+ * Route templates to skip tracing.
19
+ * @internal
20
+ */
21
+ _excludeRouteTemplates;
22
+ /**
23
+ * Create a new instance of TracingRestClientProcessor.
24
+ * @param options Options for the processor.
25
+ */
26
+ constructor(options) {
27
+ this._tracing = ComponentFactory.getIfExists(options?.tracingComponentType);
28
+ this._excludeRouteTemplates = options?.config?.excludePaths ?? [];
29
+ }
30
+ /**
31
+ * Returns the class name of the component.
32
+ * @returns The class name of the component.
33
+ */
34
+ className() {
35
+ return TracingRestClientProcessor.CLASS_NAME;
36
+ }
37
+ /**
38
+ * Wrap the request in a client span, sending the current span as the traceparent so the
39
+ * receiving service continues this trace.
40
+ * @param context The details of the request being made.
41
+ * @param next Performs the request.
42
+ * @returns The response.
43
+ */
44
+ async pre(context, next) {
45
+ if (Is.empty(this._tracing) || this._excludeRouteTemplates.includes(context.routeTemplate)) {
46
+ return next();
47
+ }
48
+ return TracingHelper.withSpan(this._tracing, `${context.restClientClassName}${context.route.startsWith("/") ? "" : "/"}${context.route}`, {
49
+ kind: SpanKind.Client,
50
+ attributes: { "http.method": context.method, "http.route": context.route }
51
+ }, async (span) => {
52
+ if (!Is.empty(span)) {
53
+ context.headers[TraceparentHelper.HEADER_NAME] = TraceparentHelper.format(span.context);
54
+ }
55
+ const response = await next();
56
+ if (!Is.empty(span)) {
57
+ span.attributes = {
58
+ ...span.attributes,
59
+ "http.status_code": response.status ?? HttpStatusCode.ok
60
+ };
61
+ }
62
+ return response;
63
+ });
64
+ }
65
+ }
66
+ //# sourceMappingURL=tracingRestClientProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracingRestClientProcessor.js","sourceRoot":"","sources":["../../src/tracingRestClientProcessor.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,EAAE,EAAE,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EACN,QAAQ,EACR,iBAAiB,EACjB,aAAa,EAEb,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAG/C;;GAEG;AACH,MAAM,OAAO,0BAA0B;IACtC;;OAEG;IACI,MAAM,CAAU,UAAU,gCAAgD;IAEjF;;;OAGG;IACc,QAAQ,CAAqB;IAE9C;;;OAGG;IACc,sBAAsB,CAAW;IAElD;;;OAGG;IACH,YAAY,OAAuD;QAClE,IAAI,CAAC,QAAQ,GAAG,gBAAgB,CAAC,WAAW,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC;QAC5E,IAAI,CAAC,sBAAsB,GAAG,OAAO,EAAE,MAAM,EAAE,YAAY,IAAI,EAAE,CAAC;IACnE,CAAC;IAED;;;OAGG;IACI,SAAS;QACf,OAAO,0BAA0B,CAAC,UAAU,CAAC;IAC9C,CAAC;IAED;;;;;;OAMG;IACI,KAAK,CAAC,GAAG,CACf,OAAoC,EACpC,IAA6B;QAE7B,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,sBAAsB,CAAC,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC;YAC5F,OAAO,IAAI,EAAE,CAAC;QACf,CAAC;QAED,OAAO,aAAa,CAAC,QAAQ,CAC5B,IAAI,CAAC,QAAQ,EACb,GAAG,OAAO,CAAC,mBAAmB,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,OAAO,CAAC,KAAK,EAAE,EAC3F;YACC,IAAI,EAAE,QAAQ,CAAC,MAAM;YACrB,UAAU,EAAE,EAAE,aAAa,EAAE,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,OAAO,CAAC,KAAK,EAAE;SAC1E,EACD,KAAK,EAAC,IAAI,EAAC,EAAE;YACZ,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrB,OAAO,CAAC,OAAO,CAAC,iBAAiB,CAAC,WAAW,CAAC,GAAG,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACzF,CAAC;YAED,MAAM,QAAQ,GAAG,MAAM,IAAI,EAAE,CAAC;YAE9B,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrB,IAAI,CAAC,UAAU,GAAG;oBACjB,GAAG,IAAI,CAAC,UAAU;oBAClB,kBAAkB,EAAE,QAAQ,CAAC,MAAM,IAAI,cAAc,CAAC,EAAE;iBACxD,CAAC;YACH,CAAC;YAED,OAAO,QAAQ,CAAC;QACjB,CAAC,CACD,CAAC;IACH,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IRestClientProcessor, IRestClientProcessorContext } from \"@twin.org/api-models\";\nimport { ComponentFactory, Is } from \"@twin.org/core\";\nimport { nameof } from \"@twin.org/nameof\";\nimport {\n\tSpanKind,\n\tTraceparentHelper,\n\tTracingHelper,\n\ttype ITracingComponent\n} from \"@twin.org/tracing-models\";\nimport { HttpStatusCode } from \"@twin.org/web\";\nimport type { ITracingRestClientProcessorConstructorOptions } from \"./models/ITracingRestClientProcessorConstructorOptions.js\";\n\n/**\n * Records a span for each outbound REST request and carries the trace via traceparent header.\n */\nexport class TracingRestClientProcessor implements IRestClientProcessor {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<TracingRestClientProcessor>();\n\n\t/**\n\t * The component recording the spans.\n\t * @internal\n\t */\n\tprivate readonly _tracing?: ITracingComponent;\n\n\t/**\n\t * Route templates to skip tracing.\n\t * @internal\n\t */\n\tprivate readonly _excludeRouteTemplates: string[];\n\n\t/**\n\t * Create a new instance of TracingRestClientProcessor.\n\t * @param options Options for the processor.\n\t */\n\tconstructor(options?: ITracingRestClientProcessorConstructorOptions) {\n\t\tthis._tracing = ComponentFactory.getIfExists(options?.tracingComponentType);\n\t\tthis._excludeRouteTemplates = options?.config?.excludePaths ?? [];\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn TracingRestClientProcessor.CLASS_NAME;\n\t}\n\n\t/**\n\t * Wrap the request in a client span, sending the current span as the traceparent so the\n\t * receiving service continues this trace.\n\t * @param context The details of the request being made.\n\t * @param next Performs the request.\n\t * @returns The response.\n\t */\n\tpublic async pre(\n\t\tcontext: IRestClientProcessorContext,\n\t\tnext: () => Promise<Response>\n\t): Promise<Response> {\n\t\tif (Is.empty(this._tracing) || this._excludeRouteTemplates.includes(context.routeTemplate)) {\n\t\t\treturn next();\n\t\t}\n\n\t\treturn TracingHelper.withSpan(\n\t\t\tthis._tracing,\n\t\t\t`${context.restClientClassName}${context.route.startsWith(\"/\") ? \"\" : \"/\"}${context.route}`,\n\t\t\t{\n\t\t\t\tkind: SpanKind.Client,\n\t\t\t\tattributes: { \"http.method\": context.method, \"http.route\": context.route }\n\t\t\t},\n\t\t\tasync span => {\n\t\t\t\tif (!Is.empty(span)) {\n\t\t\t\t\tcontext.headers[TraceparentHelper.HEADER_NAME] = TraceparentHelper.format(span.context);\n\t\t\t\t}\n\n\t\t\t\tconst response = await next();\n\n\t\t\t\tif (!Is.empty(span)) {\n\t\t\t\t\tspan.attributes = {\n\t\t\t\t\t\t...span.attributes,\n\t\t\t\t\t\t\"http.status_code\": response.status ?? HttpStatusCode.ok\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t}\n\t\t);\n\t}\n}\n"]}
@@ -0,0 +1,144 @@
1
+ import { BaseError, Coerce, ComponentFactory, Is } from "@twin.org/core";
2
+ import { SpanKind, SpanStatus, TraceparentHelper, TracingHelper } from "@twin.org/tracing-models";
3
+ import { HttpStatusCode } from "@twin.org/web";
4
+ /**
5
+ * Process the REST request and record it as a span.
6
+ */
7
+ export class TracingRouteProcessor {
8
+ /**
9
+ * Runtime name for the class.
10
+ */
11
+ static CLASS_NAME = "TracingRouteProcessor";
12
+ /**
13
+ * The key the span is stored under while it is handed between the processor phases.
14
+ * @internal
15
+ */
16
+ static _STATE_KEY = "tracingProcessorSpan";
17
+ /**
18
+ * The component for recording the spans.
19
+ * @internal
20
+ */
21
+ _tracing;
22
+ /**
23
+ * The component for logging failures.
24
+ * @internal
25
+ */
26
+ _logging;
27
+ /**
28
+ * Request URL path prefixes to skip tracing, defaults to ["/tracing"].
29
+ * @internal
30
+ */
31
+ _excludePaths;
32
+ /**
33
+ * Route operation IDs to skip tracing.
34
+ * @internal
35
+ */
36
+ _excludeOperationIds;
37
+ /**
38
+ * Create a new instance of TracingRouteProcessor.
39
+ * @param options Options for the processor.
40
+ */
41
+ constructor(options) {
42
+ this._tracing = ComponentFactory.getIfExists(options?.tracingComponentType);
43
+ this._logging = ComponentFactory.getIfExists(options?.loggingComponentType);
44
+ this._excludePaths = options?.config?.excludePaths ?? ["/tracing"];
45
+ this._excludeOperationIds = options?.config?.excludeOperationIds ?? [];
46
+ }
47
+ /**
48
+ * Returns the class name of the component.
49
+ * @returns The class name of the component.
50
+ */
51
+ className() {
52
+ return TracingRouteProcessor.CLASS_NAME;
53
+ }
54
+ /**
55
+ * Pre process the REST request for the specified route, opening the span for the request.
56
+ * @param request The incoming request.
57
+ * @param response The outgoing response.
58
+ * @param route The route to process.
59
+ * @param contextIds The context IDs of the request.
60
+ * @param processorState The state handed through the processors.
61
+ * @returns A promise that resolves when the span has been started.
62
+ */
63
+ async pre(request, response, route, contextIds, processorState) {
64
+ if (Is.empty(this._tracing)) {
65
+ return;
66
+ }
67
+ if (Is.stringValue(route?.path) && this._excludePaths.includes(route.path)) {
68
+ return;
69
+ }
70
+ if (Is.stringValue(route?.operationId) &&
71
+ this._excludeOperationIds.includes(route.operationId)) {
72
+ return;
73
+ }
74
+ const parentContext = TraceparentHelper.parse(Coerce.string(request.headers?.[TraceparentHelper.HEADER_NAME]));
75
+ const span = await this._tracing.startSpan(this.spanName(request, route), {
76
+ kind: SpanKind.Server,
77
+ parentContext,
78
+ attributes: this.requestAttributes(request, route)
79
+ });
80
+ processorState[TracingRouteProcessor._STATE_KEY] = span;
81
+ Object.assign(contextIds, TracingHelper.spanContextToContextIds(span.context));
82
+ }
83
+ /**
84
+ * Post process the REST request for the specified route, ending the span for the request.
85
+ * @param request The incoming request.
86
+ * @param response The outgoing response.
87
+ * @param route The route to process.
88
+ * @param contextIds The context IDs of the request.
89
+ * @param processorState The state handed through the processors.
90
+ * @returns A promise that resolves when the span has been ended.
91
+ */
92
+ async post(request, response, route, contextIds, processorState) {
93
+ const span = processorState[TracingRouteProcessor._STATE_KEY];
94
+ if (Is.empty(this._tracing) || !Is.object(span)) {
95
+ return;
96
+ }
97
+ delete processorState[TracingRouteProcessor._STATE_KEY];
98
+ try {
99
+ const statusCode = Is.number(response.statusCode) ? response.statusCode : HttpStatusCode.ok;
100
+ span.attributes = { ...span.attributes, "http.status_code": statusCode };
101
+ await this._tracing.endSpan(span, statusCode >= HttpStatusCode.badRequest ? SpanStatus.Error : SpanStatus.Ok);
102
+ }
103
+ catch (err) {
104
+ await this._logging?.log({
105
+ level: "error",
106
+ source: TracingRouteProcessor.CLASS_NAME,
107
+ ts: Date.now(),
108
+ message: "endSpanFailed",
109
+ error: BaseError.fromError(err)
110
+ });
111
+ }
112
+ }
113
+ /**
114
+ * Build the name for the span.
115
+ * @param request The incoming request.
116
+ * @param route The route to process.
117
+ * @returns The span name.
118
+ * @internal
119
+ */
120
+ spanName(request, route) {
121
+ const routeName = route?.operationId ?? route?.path;
122
+ return Is.stringValue(routeName)
123
+ ? routeName
124
+ : `${request.method ?? "UNKNOWN"} ${TracingRouteProcessor.CLASS_NAME}`;
125
+ }
126
+ /**
127
+ * Build the attributes describing the request.
128
+ * @param request The incoming request.
129
+ * @param route The route to process.
130
+ * @returns The attributes.
131
+ * @internal
132
+ */
133
+ requestAttributes(request, route) {
134
+ const attributes = {};
135
+ if (Is.stringValue(request.method)) {
136
+ attributes["http.method"] = request.method;
137
+ }
138
+ if (Is.stringValue(route?.path)) {
139
+ attributes["http.route"] = route.path;
140
+ }
141
+ return attributes;
142
+ }
143
+ }
144
+ //# sourceMappingURL=tracingRouteProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracingRouteProcessor.js","sourceRoot":"","sources":["../../src/tracingRouteProcessor.ts"],"names":[],"mappings":"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","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type {\n\tIBaseRoute,\n\tIBaseRouteProcessor,\n\tIHttpResponse,\n\tIHttpServerRequest\n} from \"@twin.org/api-models\";\nimport type { IContextIds } from \"@twin.org/context\";\nimport { BaseError, Coerce, ComponentFactory, Is } from \"@twin.org/core\";\nimport type { ILoggingComponent } from \"@twin.org/logging-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport {\n\tSpanKind,\n\tSpanStatus,\n\tTraceparentHelper,\n\tTracingHelper,\n\ttype ISpan,\n\ttype ITracingComponent\n} from \"@twin.org/tracing-models\";\nimport { HttpStatusCode } from \"@twin.org/web\";\nimport type { ITracingRouteProcessorConstructorOptions } from \"./models/ITracingRouteProcessorConstructorOptions.js\";\n\n/**\n * Process the REST request and record it as a span.\n */\nexport class TracingRouteProcessor implements IBaseRouteProcessor {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<TracingRouteProcessor>();\n\n\t/**\n\t * The key the span is stored under while it is handed between the processor phases.\n\t * @internal\n\t */\n\tprivate static readonly _STATE_KEY: string = \"tracingProcessorSpan\";\n\n\t/**\n\t * The component for recording the spans.\n\t * @internal\n\t */\n\tprivate readonly _tracing?: ITracingComponent;\n\n\t/**\n\t * The component for logging failures.\n\t * @internal\n\t */\n\tprivate readonly _logging?: ILoggingComponent;\n\n\t/**\n\t * Request URL path prefixes to skip tracing, defaults to [\"/tracing\"].\n\t * @internal\n\t */\n\tprivate readonly _excludePaths: string[];\n\n\t/**\n\t * Route operation IDs to skip tracing.\n\t * @internal\n\t */\n\tprivate readonly _excludeOperationIds: string[];\n\n\t/**\n\t * Create a new instance of TracingRouteProcessor.\n\t * @param options Options for the processor.\n\t */\n\tconstructor(options?: ITracingRouteProcessorConstructorOptions) {\n\t\tthis._tracing = ComponentFactory.getIfExists(options?.tracingComponentType);\n\t\tthis._logging = ComponentFactory.getIfExists(options?.loggingComponentType);\n\t\tthis._excludePaths = options?.config?.excludePaths ?? [\"/tracing\"];\n\t\tthis._excludeOperationIds = options?.config?.excludeOperationIds ?? [];\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn TracingRouteProcessor.CLASS_NAME;\n\t}\n\n\t/**\n\t * Pre process the REST request for the specified route, opening the span for the request.\n\t * @param request The incoming request.\n\t * @param response The outgoing response.\n\t * @param route The route to process.\n\t * @param contextIds The context IDs of the request.\n\t * @param processorState The state handed through the processors.\n\t * @returns A promise that resolves when the span has been started.\n\t */\n\tpublic async pre(\n\t\trequest: IHttpServerRequest,\n\t\tresponse: IHttpResponse,\n\t\troute: IBaseRoute | undefined,\n\t\tcontextIds: IContextIds,\n\t\tprocessorState: { [id: string]: unknown }\n\t): Promise<void> {\n\t\tif (Is.empty(this._tracing)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (Is.stringValue(route?.path) && this._excludePaths.includes(route.path)) {\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\tIs.stringValue(route?.operationId) &&\n\t\t\tthis._excludeOperationIds.includes(route.operationId)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst parentContext = TraceparentHelper.parse(\n\t\t\tCoerce.string(request.headers?.[TraceparentHelper.HEADER_NAME])\n\t\t);\n\n\t\tconst span = await this._tracing.startSpan(this.spanName(request, route), {\n\t\t\tkind: SpanKind.Server,\n\t\t\tparentContext,\n\t\t\tattributes: this.requestAttributes(request, route)\n\t\t});\n\n\t\tprocessorState[TracingRouteProcessor._STATE_KEY] = span;\n\n\t\tObject.assign(contextIds, TracingHelper.spanContextToContextIds(span.context));\n\t}\n\n\t/**\n\t * Post process the REST request for the specified route, ending the span for the request.\n\t * @param request The incoming request.\n\t * @param response The outgoing response.\n\t * @param route The route to process.\n\t * @param contextIds The context IDs of the request.\n\t * @param processorState The state handed through the processors.\n\t * @returns A promise that resolves when the span has been ended.\n\t */\n\tpublic async post(\n\t\trequest: IHttpServerRequest,\n\t\tresponse: IHttpResponse,\n\t\troute: IBaseRoute | undefined,\n\t\tcontextIds: IContextIds,\n\t\tprocessorState: { [id: string]: unknown }\n\t): Promise<void> {\n\t\tconst span = processorState[TracingRouteProcessor._STATE_KEY];\n\n\t\tif (Is.empty(this._tracing) || !Is.object<ISpan>(span)) {\n\t\t\treturn;\n\t\t}\n\n\t\tdelete processorState[TracingRouteProcessor._STATE_KEY];\n\n\t\ttry {\n\t\t\tconst statusCode = Is.number(response.statusCode) ? response.statusCode : HttpStatusCode.ok;\n\n\t\t\tspan.attributes = { ...span.attributes, \"http.status_code\": statusCode };\n\n\t\t\tawait this._tracing.endSpan(\n\t\t\t\tspan,\n\t\t\t\tstatusCode >= HttpStatusCode.badRequest ? SpanStatus.Error : SpanStatus.Ok\n\t\t\t);\n\t\t} catch (err) {\n\t\t\tawait this._logging?.log({\n\t\t\t\tlevel: \"error\",\n\t\t\t\tsource: TracingRouteProcessor.CLASS_NAME,\n\t\t\t\tts: Date.now(),\n\t\t\t\tmessage: \"endSpanFailed\",\n\t\t\t\terror: BaseError.fromError(err)\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Build the name for the span.\n\t * @param request The incoming request.\n\t * @param route The route to process.\n\t * @returns The span name.\n\t * @internal\n\t */\n\tprivate spanName(request: IHttpServerRequest, route: IBaseRoute | undefined): string {\n\t\tconst routeName = route?.operationId ?? route?.path;\n\n\t\treturn Is.stringValue(routeName)\n\t\t\t? routeName\n\t\t\t: `${request.method ?? \"UNKNOWN\"} ${TracingRouteProcessor.CLASS_NAME}`;\n\t}\n\n\t/**\n\t * Build the attributes describing the request.\n\t * @param request The incoming request.\n\t * @param route The route to process.\n\t * @returns The attributes.\n\t * @internal\n\t */\n\tprivate requestAttributes(\n\t\trequest: IHttpServerRequest,\n\t\troute: IBaseRoute | undefined\n\t): { [key: string]: unknown } {\n\t\tconst attributes: { [key: string]: unknown } = {};\n\n\t\tif (Is.stringValue(request.method)) {\n\t\t\tattributes[\"http.method\"] = request.method;\n\t\t}\n\t\tif (Is.stringValue(route?.path)) {\n\t\t\tattributes[\"http.route\"] = route.path;\n\t\t}\n\n\t\treturn attributes;\n\t}\n}\n"]}
@@ -0,0 +1,6 @@
1
+ export * from "./models/ITracingRestClientProcessorConfig.js";
2
+ export * from "./models/ITracingRestClientProcessorConstructorOptions.js";
3
+ export * from "./models/ITracingRouteProcessorConfig.js";
4
+ export * from "./models/ITracingRouteProcessorConstructorOptions.js";
5
+ export * from "./tracingRestClientProcessor.js";
6
+ export * from "./tracingRouteProcessor.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Configuration for the tracing REST client processor.
3
+ */
4
+ export interface ITracingRestClientProcessorConfig {
5
+ /**
6
+ * Route templates to skip tracing.
7
+ */
8
+ excludePaths?: string[];
9
+ }
@@ -0,0 +1,15 @@
1
+ import type { ITracingRestClientProcessorConfig } from "./ITracingRestClientProcessorConfig.js";
2
+ /**
3
+ * Options for the TracingRestClientProcessor constructor.
4
+ */
5
+ export interface ITracingRestClientProcessorConstructorOptions {
6
+ /**
7
+ * The type for the tracing component, when absent no spans are created and no trace header is
8
+ * sent.
9
+ */
10
+ tracingComponentType?: string;
11
+ /**
12
+ * Configuration for the processor.
13
+ */
14
+ config?: ITracingRestClientProcessorConfig;
15
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Configuration for the tracing route processor.
3
+ */
4
+ export interface ITracingRouteProcessorConfig {
5
+ /**
6
+ * Request URL path prefixes to skip tracing.
7
+ */
8
+ excludePaths?: string[];
9
+ /**
10
+ * Route operation IDs to skip tracing.
11
+ */
12
+ excludeOperationIds?: string[];
13
+ }
@@ -0,0 +1,18 @@
1
+ import type { ITracingRouteProcessorConfig } from "./ITracingRouteProcessorConfig.js";
2
+ /**
3
+ * Options for the TracingRouteProcessor constructor.
4
+ */
5
+ export interface ITracingRouteProcessorConstructorOptions {
6
+ /**
7
+ * The type for the tracing component.
8
+ */
9
+ tracingComponentType?: string;
10
+ /**
11
+ * The type for the logging component.
12
+ */
13
+ loggingComponentType?: string;
14
+ /**
15
+ * The configuration for the tracing route processor.
16
+ */
17
+ config?: ITracingRouteProcessorConfig;
18
+ }
@@ -0,0 +1,29 @@
1
+ import type { IRestClientProcessor, IRestClientProcessorContext } from "@twin.org/api-models";
2
+ import type { ITracingRestClientProcessorConstructorOptions } from "./models/ITracingRestClientProcessorConstructorOptions.js";
3
+ /**
4
+ * Records a span for each outbound REST request and carries the trace via traceparent header.
5
+ */
6
+ export declare class TracingRestClientProcessor implements IRestClientProcessor {
7
+ /**
8
+ * Runtime name for the class.
9
+ */
10
+ static readonly CLASS_NAME: string;
11
+ /**
12
+ * Create a new instance of TracingRestClientProcessor.
13
+ * @param options Options for the processor.
14
+ */
15
+ constructor(options?: ITracingRestClientProcessorConstructorOptions);
16
+ /**
17
+ * Returns the class name of the component.
18
+ * @returns The class name of the component.
19
+ */
20
+ className(): string;
21
+ /**
22
+ * Wrap the request in a client span, sending the current span as the traceparent so the
23
+ * receiving service continues this trace.
24
+ * @param context The details of the request being made.
25
+ * @param next Performs the request.
26
+ * @returns The response.
27
+ */
28
+ pre(context: IRestClientProcessorContext, next: () => Promise<Response>): Promise<Response>;
29
+ }
@@ -0,0 +1,46 @@
1
+ import type { IBaseRoute, IBaseRouteProcessor, IHttpResponse, IHttpServerRequest } from "@twin.org/api-models";
2
+ import type { IContextIds } from "@twin.org/context";
3
+ import type { ITracingRouteProcessorConstructorOptions } from "./models/ITracingRouteProcessorConstructorOptions.js";
4
+ /**
5
+ * Process the REST request and record it as a span.
6
+ */
7
+ export declare class TracingRouteProcessor implements IBaseRouteProcessor {
8
+ /**
9
+ * Runtime name for the class.
10
+ */
11
+ static readonly CLASS_NAME: string;
12
+ /**
13
+ * Create a new instance of TracingRouteProcessor.
14
+ * @param options Options for the processor.
15
+ */
16
+ constructor(options?: ITracingRouteProcessorConstructorOptions);
17
+ /**
18
+ * Returns the class name of the component.
19
+ * @returns The class name of the component.
20
+ */
21
+ className(): string;
22
+ /**
23
+ * Pre process the REST request for the specified route, opening the span for the request.
24
+ * @param request The incoming request.
25
+ * @param response The outgoing response.
26
+ * @param route The route to process.
27
+ * @param contextIds The context IDs of the request.
28
+ * @param processorState The state handed through the processors.
29
+ * @returns A promise that resolves when the span has been started.
30
+ */
31
+ pre(request: IHttpServerRequest, response: IHttpResponse, route: IBaseRoute | undefined, contextIds: IContextIds, processorState: {
32
+ [id: string]: unknown;
33
+ }): Promise<void>;
34
+ /**
35
+ * Post process the REST request for the specified route, ending the span for the request.
36
+ * @param request The incoming request.
37
+ * @param response The outgoing response.
38
+ * @param route The route to process.
39
+ * @param contextIds The context IDs of the request.
40
+ * @param processorState The state handed through the processors.
41
+ * @returns A promise that resolves when the span has been ended.
42
+ */
43
+ post(request: IHttpServerRequest, response: IHttpResponse, route: IBaseRoute | undefined, contextIds: IContextIds, processorState: {
44
+ [id: string]: unknown;
45
+ }): Promise<void>;
46
+ }
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## [0.9.2-next.3](https://github.com/iotaledger/twin-tracing/compare/tracing-processors-v0.9.2-next.2...tracing-processors-v0.9.2-next.3) (2026-08-17)
4
+
5
+
6
+ ### Features
7
+
8
+ * tracing processors ([#9](https://github.com/iotaledger/twin-tracing/issues/9)) ([e5f5d16](https://github.com/iotaledger/twin-tracing/commit/e5f5d1616992440d067830965372d32fc34a939d))
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @twin.org/tracing-models bumped from 0.9.2-next.2 to 0.9.2-next.3
16
+
17
+ ## Changelog
@@ -0,0 +1,88 @@
1
+ # Tracing Processors Examples
2
+
3
+ These two processors trace the HTTP boundary. Together they join the spans of separate services
4
+ into a single trace, via W3C `traceparent` header: the client processor sends the span it
5
+ opens, and the route processor on the receiving side continues from it.
6
+
7
+ ## Tracing inbound requests
8
+
9
+ `TracingRouteProcessor` records a span for each request the server handles. Register it and add it
10
+ to the route processor types of the server.
11
+
12
+ ```typescript
13
+ import { ComponentFactory } from '@twin.org/core';
14
+ import { TracingRouteProcessor } from '@twin.org/tracing-processors';
15
+
16
+ ComponentFactory.register(
17
+ 'tracing-route-processor',
18
+ () => new TracingRouteProcessor({ tracingComponentType: 'tracing' })
19
+ );
20
+ ```
21
+
22
+ The span is named from the route `operationId`, falling back to its path, and carries `http.method`,
23
+ `http.route` and `http.status_code` attributes. A status of 400 or above ends the span with an error
24
+ status.
25
+
26
+ Without a `tracingComponentType` which resolves, the processor does nothing, so it is safe to
27
+ register unconditionally.
28
+
29
+ ## Continuing a trace from the caller
30
+
31
+ When the request arrives with a `traceparent` header, the span becomes a child of the caller's span
32
+ and stays in the same trace. A missing or malformed header starts a new trace.
33
+
34
+ The span ids are written into the request `contextIds`, so anything the handler does through
35
+ `TracingHelper.withSpan` nests underneath the request span automatically.
36
+
37
+ ## Excluding paths
38
+
39
+ Requests to the tracing API itself are skipped by default, otherwise reading spans would create
40
+ spans. Supply `excludePaths` to change this.
41
+
42
+ ```typescript
43
+ new TracingRouteProcessor({
44
+ tracingComponentType: 'tracing',
45
+ config: { excludePaths: ['/tracing', '/health'] }
46
+ });
47
+ ```
48
+
49
+ ## Tracing outbound requests
50
+
51
+ `TracingRestClientProcessor` records a span for each request a REST client makes, and sends the
52
+ `traceparent` header so the service being called continues the same trace.
53
+
54
+ ```typescript
55
+ import { RestClientProcessorFactory } from '@twin.org/api-models';
56
+ import { TracingRestClientProcessor } from '@twin.org/tracing-processors';
57
+
58
+ RestClientProcessorFactory.register(
59
+ 'tracing-client-processor',
60
+ () => new TracingRestClientProcessor({ tracingComponentType: 'tracing' })
61
+ );
62
+ ```
63
+
64
+ Then name it in the configuration of any client which should be traced.
65
+
66
+ ```typescript
67
+ const client = new BlobStorageClient({
68
+ endpoint: 'https://example.com',
69
+ processorTypes: ['tracing-client-processor']
70
+ });
71
+ ```
72
+
73
+ ## Avoiding a loop when the tracing client is itself traced
74
+
75
+ A REST client which reports spans over HTTP must not be traced, or recording a span would make
76
+ another request, which would record another span. A client is only traced when it names a processor
77
+ type, so leaving `processorTypes` off the tracing client is all that is needed.
78
+
79
+ ## The two ends together
80
+
81
+ With both processors in place, a request arriving at service A and passed on to service B produces
82
+ one trace with a server span in A, a client span beneath it, and a server span in B beneath that.
83
+
84
+ ```text
85
+ GET /blob (A, server)
86
+ └── BlobStorageClient/blob (A, client)
87
+ └── blobStorageGet (B, server)
88
+ ```
@@ -0,0 +1,86 @@
1
+ # Class: TracingRestClientProcessor
2
+
3
+ Records a span for each outbound REST request and carries the trace via traceparent header.
4
+
5
+ ## Implements
6
+
7
+ - `IRestClientProcessor`
8
+
9
+ ## Constructors
10
+
11
+ ### Constructor
12
+
13
+ > **new TracingRestClientProcessor**(`options?`): `TracingRestClientProcessor`
14
+
15
+ Create a new instance of TracingRestClientProcessor.
16
+
17
+ #### Parameters
18
+
19
+ ##### options?
20
+
21
+ [`ITracingRestClientProcessorConstructorOptions`](../interfaces/ITracingRestClientProcessorConstructorOptions.md)
22
+
23
+ Options for the processor.
24
+
25
+ #### Returns
26
+
27
+ `TracingRestClientProcessor`
28
+
29
+ ## Properties
30
+
31
+ ### CLASS\_NAME {#class_name}
32
+
33
+ > `readonly` `static` **CLASS\_NAME**: `string`
34
+
35
+ Runtime name for the class.
36
+
37
+ ## Methods
38
+
39
+ ### className() {#classname}
40
+
41
+ > **className**(): `string`
42
+
43
+ Returns the class name of the component.
44
+
45
+ #### Returns
46
+
47
+ `string`
48
+
49
+ The class name of the component.
50
+
51
+ #### Implementation of
52
+
53
+ `IRestClientProcessor.className`
54
+
55
+ ***
56
+
57
+ ### pre() {#pre}
58
+
59
+ > **pre**(`context`, `next`): `Promise`\<`Response`\>
60
+
61
+ Wrap the request in a client span, sending the current span as the traceparent so the
62
+ receiving service continues this trace.
63
+
64
+ #### Parameters
65
+
66
+ ##### context
67
+
68
+ `IRestClientProcessorContext`
69
+
70
+ The details of the request being made.
71
+
72
+ ##### next
73
+
74
+ () => `Promise`\<`Response`\>
75
+
76
+ Performs the request.
77
+
78
+ #### Returns
79
+
80
+ `Promise`\<`Response`\>
81
+
82
+ The response.
83
+
84
+ #### Implementation of
85
+
86
+ `IRestClientProcessor.pre`
@@ -0,0 +1,149 @@
1
+ # Class: TracingRouteProcessor
2
+
3
+ Process the REST request and record it as a span.
4
+
5
+ ## Implements
6
+
7
+ - `IBaseRouteProcessor`
8
+
9
+ ## Constructors
10
+
11
+ ### Constructor
12
+
13
+ > **new TracingRouteProcessor**(`options?`): `TracingRouteProcessor`
14
+
15
+ Create a new instance of TracingRouteProcessor.
16
+
17
+ #### Parameters
18
+
19
+ ##### options?
20
+
21
+ [`ITracingRouteProcessorConstructorOptions`](../interfaces/ITracingRouteProcessorConstructorOptions.md)
22
+
23
+ Options for the processor.
24
+
25
+ #### Returns
26
+
27
+ `TracingRouteProcessor`
28
+
29
+ ## Properties
30
+
31
+ ### CLASS\_NAME {#class_name}
32
+
33
+ > `readonly` `static` **CLASS\_NAME**: `string`
34
+
35
+ Runtime name for the class.
36
+
37
+ ## Methods
38
+
39
+ ### className() {#classname}
40
+
41
+ > **className**(): `string`
42
+
43
+ Returns the class name of the component.
44
+
45
+ #### Returns
46
+
47
+ `string`
48
+
49
+ The class name of the component.
50
+
51
+ #### Implementation of
52
+
53
+ `IBaseRouteProcessor.className`
54
+
55
+ ***
56
+
57
+ ### pre() {#pre}
58
+
59
+ > **pre**(`request`, `response`, `route`, `contextIds`, `processorState`): `Promise`\<`void`\>
60
+
61
+ Pre process the REST request for the specified route, opening the span for the request.
62
+
63
+ #### Parameters
64
+
65
+ ##### request
66
+
67
+ `IHttpServerRequest`
68
+
69
+ The incoming request.
70
+
71
+ ##### response
72
+
73
+ `IHttpResponse`
74
+
75
+ The outgoing response.
76
+
77
+ ##### route
78
+
79
+ `IBaseRoute` \| `undefined`
80
+
81
+ The route to process.
82
+
83
+ ##### contextIds
84
+
85
+ `IContextIds`
86
+
87
+ The context IDs of the request.
88
+
89
+ ##### processorState
90
+
91
+ The state handed through the processors.
92
+
93
+ #### Returns
94
+
95
+ `Promise`\<`void`\>
96
+
97
+ A promise that resolves when the span has been started.
98
+
99
+ #### Implementation of
100
+
101
+ `IBaseRouteProcessor.pre`
102
+
103
+ ***
104
+
105
+ ### post() {#post}
106
+
107
+ > **post**(`request`, `response`, `route`, `contextIds`, `processorState`): `Promise`\<`void`\>
108
+
109
+ Post process the REST request for the specified route, ending the span for the request.
110
+
111
+ #### Parameters
112
+
113
+ ##### request
114
+
115
+ `IHttpServerRequest`
116
+
117
+ The incoming request.
118
+
119
+ ##### response
120
+
121
+ `IHttpResponse`
122
+
123
+ The outgoing response.
124
+
125
+ ##### route
126
+
127
+ `IBaseRoute` \| `undefined`
128
+
129
+ The route to process.
130
+
131
+ ##### contextIds
132
+
133
+ `IContextIds`
134
+
135
+ The context IDs of the request.
136
+
137
+ ##### processorState
138
+
139
+ The state handed through the processors.
140
+
141
+ #### Returns
142
+
143
+ `Promise`\<`void`\>
144
+
145
+ A promise that resolves when the span has been ended.
146
+
147
+ #### Implementation of
148
+
149
+ `IBaseRouteProcessor.post`
@@ -0,0 +1,13 @@
1
+ # @twin.org/tracing-processors
2
+
3
+ ## Classes
4
+
5
+ - [TracingRestClientProcessor](classes/TracingRestClientProcessor.md)
6
+ - [TracingRouteProcessor](classes/TracingRouteProcessor.md)
7
+
8
+ ## Interfaces
9
+
10
+ - [ITracingRestClientProcessorConfig](interfaces/ITracingRestClientProcessorConfig.md)
11
+ - [ITracingRestClientProcessorConstructorOptions](interfaces/ITracingRestClientProcessorConstructorOptions.md)
12
+ - [ITracingRouteProcessorConfig](interfaces/ITracingRouteProcessorConfig.md)
13
+ - [ITracingRouteProcessorConstructorOptions](interfaces/ITracingRouteProcessorConstructorOptions.md)
@@ -0,0 +1,11 @@
1
+ # Interface: ITracingRestClientProcessorConfig
2
+
3
+ Configuration for the tracing REST client processor.
4
+
5
+ ## Properties
6
+
7
+ ### excludePaths? {#excludepaths}
8
+
9
+ > `optional` **excludePaths?**: `string`[]
10
+
11
+ Route templates to skip tracing.
@@ -0,0 +1,20 @@
1
+ # Interface: ITracingRestClientProcessorConstructorOptions
2
+
3
+ Options for the TracingRestClientProcessor constructor.
4
+
5
+ ## Properties
6
+
7
+ ### tracingComponentType? {#tracingcomponenttype}
8
+
9
+ > `optional` **tracingComponentType?**: `string`
10
+
11
+ The type for the tracing component, when absent no spans are created and no trace header is
12
+ sent.
13
+
14
+ ***
15
+
16
+ ### config? {#config}
17
+
18
+ > `optional` **config?**: [`ITracingRestClientProcessorConfig`](ITracingRestClientProcessorConfig.md)
19
+
20
+ Configuration for the processor.
@@ -0,0 +1,19 @@
1
+ # Interface: ITracingRouteProcessorConfig
2
+
3
+ Configuration for the tracing route processor.
4
+
5
+ ## Properties
6
+
7
+ ### excludePaths? {#excludepaths}
8
+
9
+ > `optional` **excludePaths?**: `string`[]
10
+
11
+ Request URL path prefixes to skip tracing.
12
+
13
+ ***
14
+
15
+ ### excludeOperationIds? {#excludeoperationids}
16
+
17
+ > `optional` **excludeOperationIds?**: `string`[]
18
+
19
+ Route operation IDs to skip tracing.
@@ -0,0 +1,27 @@
1
+ # Interface: ITracingRouteProcessorConstructorOptions
2
+
3
+ Options for the TracingRouteProcessor constructor.
4
+
5
+ ## Properties
6
+
7
+ ### tracingComponentType? {#tracingcomponenttype}
8
+
9
+ > `optional` **tracingComponentType?**: `string`
10
+
11
+ The type for the tracing component.
12
+
13
+ ***
14
+
15
+ ### loggingComponentType? {#loggingcomponenttype}
16
+
17
+ > `optional` **loggingComponentType?**: `string`
18
+
19
+ The type for the logging component.
20
+
21
+ ***
22
+
23
+ ### config? {#config}
24
+
25
+ > `optional` **config?**: [`ITracingRouteProcessorConfig`](ITracingRouteProcessorConfig.md)
26
+
27
+ The configuration for the tracing route processor.
@@ -0,0 +1,3 @@
1
+ http.method
2
+ http.route
3
+ http.status_code
@@ -0,0 +1,7 @@
1
+ {
2
+ "error": {
3
+ "tracingRouteProcessor": {
4
+ "endSpanFailed": "The span for the request could not be ended"
5
+ }
6
+ }
7
+ }
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@twin.org/tracing-processors",
3
+ "version": "0.9.2-next.3",
4
+ "description": "Processors which record spans for inbound and outbound REST requests.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/iotaledger/twin-tracing.git",
8
+ "directory": "packages/tracing-processors"
9
+ },
10
+ "author": "martyn.janes@iota.org",
11
+ "license": "Apache-2.0",
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=20.0.0"
15
+ },
16
+ "dependencies": {
17
+ "@twin.org/api-models": "next",
18
+ "@twin.org/context": "next",
19
+ "@twin.org/core": "next",
20
+ "@twin.org/logging-models": "next",
21
+ "@twin.org/nameof": "next",
22
+ "@twin.org/tracing-models": "0.9.2-next.3",
23
+ "@twin.org/web": "next"
24
+ },
25
+ "main": "./dist/es/index.js",
26
+ "types": "./dist/types/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/types/index.d.ts",
30
+ "import": "./dist/es/index.js",
31
+ "default": "./dist/es/index.js"
32
+ },
33
+ "./locales/*.json": "./locales/*.json"
34
+ },
35
+ "files": [
36
+ "dist/es",
37
+ "dist/types",
38
+ "locales",
39
+ "docs"
40
+ ],
41
+ "keywords": [
42
+ "twin",
43
+ "iota",
44
+ "framework",
45
+ "tracing",
46
+ "spans",
47
+ "observability",
48
+ "processors"
49
+ ],
50
+ "bugs": {
51
+ "url": "git+https://github.com/iotaledger/twin-tracing/issues"
52
+ },
53
+ "homepage": "https://twindev.org"
54
+ }